SPB Git

Repository Public

IntelligencePanel.swift 16.8 KB 318 lines swift

1import SwiftUI23/// Network side of SP Intelligence. Requests use an ephemeral session: no cookies, no cache, no shared credentials.4@MainActor5enum AIService {6    static let session: URLSession = {7        let configuration = URLSessionConfiguration.ephemeral8        configuration.httpCookieAcceptPolicy = .never9        configuration.httpShouldSetCookies = false10        configuration.urlCache = nil11        configuration.timeoutIntervalForResource = 60012        return URLSession(configuration: configuration)13    }()1415    static func isReachable(_ provider: AIProviderConfig, secrets: SecretStore) async -> Bool {16        guard let request = AIWire.probeRequest(config: provider, apiKey: secrets.secret(for: provider.id)),17              let (_, response) = try? await session.data(for: request), let http = response as? HTTPURLResponse else { return false }18        return (200..<500).contains(http.statusCode) && http.statusCode != 40419    }2021    /// The provider a request would go to: a running local endpoint when "prefer local" is on, else the active one.22    static func resolveProvider(settings: AppSettings, secrets: SecretStore) async -> AIProviderConfig? {23        let usable = settings.aiProviders.filter { $0.validationError == nil }24        if settings.aiPreferLocal {25            for provider in usable where provider.isLocal {26                if await isReachable(provider, secrets: secrets) { return provider }27            }28        }29        if let active = usable.first(where: { $0.id == settings.aiActiveProviderID }) { return active }30        return usable.first { !$0.isLocal } ?? usable.first31    }3233    static func send(_ prepared: AIPreparedRequest, to provider: AIProviderConfig, secrets: SecretStore) async throws -> String {34        let request = try AIWire.request(config: provider, apiKey: secrets.secret(for: provider.id), system: prepared.system,35                                         messages: [AIMessage(role: .user, content: prepared.userMessage)])36        do {37            let (data, response) = try await session.data(for: request)38            return try AIWire.text(from: data, status: (response as? HTTPURLResponse)?.statusCode ?? 0, kind: provider.kind)39        } catch let error as AIError {40            throw error41        } catch {42            throw AIError.unreachable(error.localizedDescription)43        }44    }45}4647struct PendingAIRequest: Identifiable {48    let id = UUID()49    let action: AIAction50    let provider: AIProviderConfig51    let prepared: AIPreparedRequest52    let page: PageContext53}5455struct IntelligencePanel: View {56    let tab: BrowserTab57    let state: BrowserWindowState58    let environment: AppEnvironment59    @State private var pending: PendingAIRequest?60    @State private var isPreparing = false61    @State private var sendingTo: AIProviderConfig?62    @State private var answer: String?63    @State private var answerMeta = ""64    @State private var errorText: String?65    @State private var question = ""66    @State private var language = Locale.current.language.languageCode?.identifier == "fr" ? "English" : "French"67    @State private var historyRevision = 068    @State private var task: Task<Void, Never>?6970    private static let languages = ["French", "English", "Spanish", "German", "Italian", "Portuguese", "Japanese", "Chinese"]71    private var replyLanguage: String { Locale.current.language.languageCode?.identifier == "fr" ? "French" : "English" }7273    var body: some View {74        let settings = environment.settings75        VStack(spacing: 0) {76            if settings.aiProviders.filter({ $0.validationError == nil }).isEmpty {77                StateView(symbol: "sparkles", title: L("No model configured"),78                          message: L("SP Intelligence uses your own model: a local endpoint on this Mac or an API key you provide. Nothing is configured yet."),79                          actionTitle: L("Open Settings")) { state.perform(.openSettings) }80            } else {81                ScrollView {82                    VStack(alignment: .leading, spacing: 12) {83                        actions84                        if let provider = sendingTo { sendingIndicator(provider) }85                        if let errorText {86                            Label(errorText, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.orange)87                                .fixedSize(horizontal: false, vertical: true).padding(10).cardSurface(radius: Theme.radiusM)88                        }89                        if let answer { answerCard(answer) }90                        history91                    }92                    .padding(14)93                }94                Divider().overlay(Theme.hairline)95                HStack(spacing: 6) {96                    TextField(L("Ask about this page…"), text: $question).textFieldStyle(.plain).onSubmit(ask)97                        .accessibilityLabel(L("Question about this page"))98                    IconButton(symbol: "arrow.up.circle.fill", label: L("Ask"), tint: Theme.accent, size: 26, action: ask)99                        .disabled(question.trimmingCharacters(in: .whitespaces).isEmpty || busy)100                }101                .padding(10)102            }103        }104        .sheet(item: $pending) { request in105            ConsentSheet(request: request, cancel: { pending = nil }, send: { pending = nil; send(request) })106        }107        .onDisappear { task?.cancel() }108    }109110    private var busy: Bool { isPreparing || sendingTo != nil || tab.url == nil }111112    private var actions: some View {113        VStack(alignment: .leading, spacing: 8) {114            LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 8) {115                actionButton(.summarize, "text.alignleft")116                actionButton(.explain, "lightbulb")117                actionButton(.extractTables, "tablecells")118                actionButton(.organize, "list.bullet.rectangle")119            }120            HStack {121                Button { prepare(.translate(language)) } label: { Label(AIAction.translate("").title, systemImage: "translate").frame(maxWidth: .infinity) }122                    .disabled(busy)123                Picker(L("Target language"), selection: $language) { ForEach(Self.languages, id: \.self) { Text($0) } }.labelsHidden().fixedSize()124            }125            Text(L("Nothing is sent until you confirm. You will see exactly what leaves the browser, and where it goes."))126                .font(.caption).foregroundStyle(.tertiary).fixedSize(horizontal: false, vertical: true)127        }128    }129130    private func actionButton(_ action: AIAction, _ symbol: String) -> some View {131        Button { prepare(action) } label: { Label(action.title, systemImage: symbol).frame(maxWidth: .infinity) }132            .controlSize(.large).disabled(busy)133    }134135    private func sendingIndicator(_ provider: AIProviderConfig) -> some View {136        HStack(spacing: 10) {137            ProgressView().controlSize(.small)138            VStack(alignment: .leading, spacing: 1) {139                Text(L("Using this page's content")).font(.callout.weight(.semibold))140                Text(provider.isLocal ? L("Processing on this Mac with %@", provider.name) : L("Sent to %@ (%@)", provider.name, provider.endpointURL?.host ?? ""))141                    .font(.caption).foregroundStyle(.secondary)142            }143            Spacer()144            Button(L("Stop")) { task?.cancel(); sendingTo = nil }.controlSize(.small)145        }146        .padding(10)147        .background(RoundedRectangle(cornerRadius: Theme.radiusM).fill((provider.isLocal ? Color.green : Theme.accent).opacity(0.12)))148        .accessibilityElement(children: .combine)149    }150151    private func answerCard(_ text: String) -> some View {152        VStack(alignment: .leading, spacing: 8) {153            HStack {154                Text(answerMeta).font(.caption).foregroundStyle(.secondary)155                Spacer()156                Button(L("Copy")) { NSPasteboard.general.clearContents(); NSPasteboard.general.setString(text, forType: .string) }.controlSize(.small)157            }158            MarkdownText(text: text)159            Text(L("Generated by a model: it can be wrong. Check important facts against the page.")).font(.caption2).foregroundStyle(.tertiary)160        }161        .padding(12).cardSurface(radius: Theme.radiusM)162    }163164    @ViewBuilder private var history: some View {165        let _ = historyRevision166        let entries = environment.aiHistory.entries167        if !entries.isEmpty {168            HStack {169                SectionLabel(text: L("History on this Mac"))170                Button(L("Erase")) { environment.aiHistory.clear(); historyRevision += 1 }.controlSize(.small)171            }172            .padding(.top, 6)173            ForEach(entries.prefix(15)) { entry in174                DisclosureGroup {175                    MarkdownText(text: entry.answer).padding(.top, 4)176                } label: {177                    VStack(alignment: .leading, spacing: 1) {178                        Text(entry.question.isEmpty ? entry.action : entry.question).font(.system(size: 12, weight: .medium)).lineLimit(1)179                        Text("\(entry.pageHost) · \(entry.date.relativeShort) · \(entry.providerName)").font(.system(size: 10)).foregroundStyle(.secondary).lineLimit(1)180                    }181                }182                .contextMenu { Button(L("Delete"), role: .destructive) { environment.aiHistory.delete(id: entry.id); historyRevision += 1 } }183            }184        }185    }186187    private func ask() {188        let text = question.trimmingCharacters(in: .whitespacesAndNewlines)189        guard !text.isEmpty, !busy else { return }190        prepare(.ask(text))191    }192193    /// Step 1: read the page and build the request locally. Nothing is transmitted here.194    private func prepare(_ action: AIAction) {195        errorText = nil196        isPreparing = true197        Task {198            defer { isPreparing = false }199            guard let provider = await AIService.resolveProvider(settings: environment.settings, secrets: environment.secrets) else {200                errorText = L("No usable provider. Check the endpoint address and model in Settings › Intelligence.")201                return202            }203            let text = await tab.pageText()204            guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {205                errorText = L("This page has no readable text.")206                return207            }208            let page = PageContext(title: tab.displayTitle, url: tab.url?.absoluteString ?? "", text: text)209            let prepared = AIPrompt.prepare(action: action, page: page, maxCharacters: environment.settings.aiMaxPageCharacters, replyLanguage: replyLanguage)210            pending = PendingAIRequest(action: action, provider: provider, prepared: prepared, page: page)211        }212    }213214    /// Step 2: only after the user confirmed the preview.215    private func send(_ request: PendingAIRequest) {216        sendingTo = request.provider217        answer = nil218        errorText = nil219        task = Task {220            defer { sendingTo = nil }221            do {222                let text = try await AIService.send(request.prepared, to: request.provider, secrets: environment.secrets)223                guard !Task.isCancelled else { return }224                answer = text225                answerMeta = request.action.title + " · " + request.provider.name + (request.provider.isLocal ? " · " + L("on this Mac") : "")226                if case .ask = request.action { question = "" }227                if environment.settings.aiKeepHistory, !state.isPrivate {228                    var asked = ""229                    if case .ask(let q) = request.action { asked = q }230                    environment.aiHistory.append(AIConversationEntry(pageTitle: request.page.title, pageHost: URL(string: request.page.url)?.host ?? "",231                                                                     action: request.action.title, question: asked, answer: text,232                                                                     providerName: request.provider.name, wasLocal: request.provider.isLocal))233                    historyRevision += 1234                }235            } catch {236                if !Task.isCancelled { errorText = (error as? AIError)?.errorDescription ?? error.localizedDescription }237            }238        }239    }240}241242/// Shows exactly what will be transmitted and to whom, before anything is sent.243struct ConsentSheet: View {244    let request: PendingAIRequest245    let cancel: () -> Void246    let send: () -> Void247248    var body: some View {249        let provider = request.provider250        VStack(alignment: .leading, spacing: 12) {251            Label(L("Send this page's content?"), systemImage: provider.isLocal ? "desktopcomputer" : "paperplane").font(.title3.weight(.semibold))252            Grid(alignment: .leading, horizontalSpacing: 12, verticalSpacing: 4) {253                GridRow { Text(L("Task")).foregroundStyle(.secondary); Text(request.action.title) }254                GridRow { Text(L("Destination")).foregroundStyle(.secondary); Text("\(provider.name) — \(provider.endpointURL?.host ?? "")") }255                GridRow { Text(L("Model")).foregroundStyle(.secondary); Text(provider.model) }256                GridRow { Text(L("Size")).foregroundStyle(.secondary); Text(L("%d characters of page text", request.prepared.includedText.count)) }257            }258            .font(.callout)259            Label(provider.isLocal ? L("This endpoint runs on this Mac: the content does not leave your computer.")260                                   : L("This is a remote service. The text below will leave your computer and be handled under that provider's terms."),261                  systemImage: provider.isLocal ? "lock.shield" : "exclamationmark.triangle")262                .font(.callout).foregroundStyle(provider.isLocal ? Color.green : .orange).fixedSize(horizontal: false, vertical: true)263            if request.prepared.wasTruncated {264                Label(L("The page is longer than the limit: only the first %d of %d characters are included. The model will be told.", request.prepared.includedText.count, request.prepared.originalLength),265                      systemImage: "scissors").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)266            }267            Text(L("Content that will be sent")).font(.caption).foregroundStyle(.secondary)268            ScrollView {269                Text(request.prepared.userMessage).font(.system(size: 11, design: .monospaced)).textSelection(.enabled)270                    .frame(maxWidth: .infinity, alignment: .leading).padding(8)271            }272            .frame(height: 220).background(RoundedRectangle(cornerRadius: Theme.radiusS).fill(Theme.field))273            .overlay(RoundedRectangle(cornerRadius: Theme.radiusS).strokeBorder(Theme.hairline))274            .accessibilityLabel(L("Content that will be sent"))275            Text(L("Check that it contains nothing private (messages, account details). Cookies and passwords are never included."))276                .font(.caption).foregroundStyle(.tertiary).fixedSize(horizontal: false, vertical: true)277            HStack {278                Spacer()279                Button(L("Cancel"), action: cancel).keyboardShortcut(.cancelAction)280                Button(provider.isLocal ? L("Process Locally") : L("Send"), action: send).keyboardShortcut(.defaultAction)281            }282        }283        .padding(20).frame(width: 560)284    }285}286287/// Renders model output as Markdown, block by block, without ever interpreting HTML.288struct MarkdownText: View {289    let text: String290291    var body: some View {292        VStack(alignment: .leading, spacing: 7) {293            ForEach(Array(text.components(separatedBy: "\n").enumerated()), id: \.offset) { _, rawLine in294                let line = rawLine.trimmingCharacters(in: .whitespaces)295                if line.isEmpty {296                    EmptyView()297                } else if line.hasPrefix("#") {298                    Text(inline(String(line.drop { $0 == "#" }).trimmingCharacters(in: .whitespaces))).font(.headline).padding(.top, 3)299                } else if line.hasPrefix("- ") || line.hasPrefix("* ") {300                    HStack(alignment: .firstTextBaseline, spacing: 6) { Text("•").foregroundStyle(.secondary); Text(inline(String(line.dropFirst(2)))) }301                } else if line.hasPrefix("|") {302                    Text(line).font(.system(size: 11, design: .monospaced))303                } else {304                    Text(inline(line))305                }306            }307        }308        .font(.callout).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)309    }310311    private func inline(_ source: String) -> AttributedString {312        var attributed = (try? AttributedString(markdown: source, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))) ?? AttributedString(source)313        // Links in model output are shown but never made clickable: the model's text is not a trusted source of destinations.314        for run in attributed.runs where run.link != nil { attributed[run.range].link = nil }315        return attributed316    }317}318
Files main
Menu

Theme