SPB Git

Repository Public

IntelligenceViews.swift 20.4 KB 309 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Next/IntelligenceViews.swift3// Description: The optional intelligence layer, OFF by default — the reader panel (« Résumer », « Suggestions de réponse ») and the4// Settings › Intelligence pane (provider, explicit consent for the external one, per-feature switches, language, semantic index).5// Every surface is hidden unless its feature is enabled and is labelled with the provider that processed the content. Nothing is ever6// sent by a model: a suggested reply only opens the composer with the text inserted, for review.7import SPMailCore8import SwiftUI910// MARK: - reply prefill (through the composer's public entry point)1112extension MailScene {13    /// Opens the composer on a reply to `email` with `text` placed above the signature and the quoted original — for review; nothing is sent.14    /// Built on `AppModel.openReply(to:body:all:in:)`: the composer inserts the text itself (one undoable edit, rich-text model untouched).15    @discardableResult16    func composeReply(to email: EmailSummary, inserting text: String, subject: String? = nil) async -> String? {17        guard let composer = await app.openReply(to: email, body: text.trimmingCharacters(in: .whitespacesAndNewlines) + "\n", in: self) else { return nil }18        if let subject = subject?.trimmingCharacters(in: .whitespaces), !subject.isEmpty { composer.setSubject(subject) }19        return composer.id20    }21}2223// MARK: - reader panel2425/// What the model answered for the conversation being read. Kept per window; dropped when another conversation opens.26@MainActor @Observable27final class ReaderAIState {28    var threadId: String?29    var summary: AIThreadSummary?30    var summaryError: String?31    var isSummarizing = false32    var replies: ReplySuggestions?33    var repliesError: String?34    var isSuggesting = false35    var tone = ReplyTone.professional36    /// `fr` / `en`.37    var language = Locale.current.language.languageCode?.identifier == "en" ? "en" : "fr"38    var showReplies = false3940    func reset(for thread: String?) {41        guard thread != threadId else { return }42        threadId = thread; summary = nil; summaryError = nil; isSummarizing = false; replies = nil; repliesError = nil; isSuggesting = false; showReplies = false43    }44}4546extension ReplyTone {47    var title: String { switch self { case .concise: L("Concis"); case .professional: L("Professionnel"); case .detailed: L("Détaillé") } }48}4950extension MailScene {51    /// Summarises the conversation being read with the provider the owner chose.52    func summarize() async {53        let ai = next.ai54        guard let account = activeAccount, let thread = reader.conversation.first?.threadId, !ai.isSummarizing else { return }55        ai.reset(for: thread)56        ai.isSummarizing = true; ai.summaryError = nil57        defer { ai.isSummarizing = false }58        do {59            let s = try await app.next.api.summarize(mailboxId: account, threadId: thread)60            if ai.threadId == thread { ai.summary = s }61        } catch { if ai.threadId == thread { ai.summaryError = app.next.describe(error); if (error as? NextError) == .aiDisabled { await app.next.reloadAI() } } }62    }6364    /// Asks for three replies to the message being read, in the chosen tone and language.65    func suggestReplies() async {66        let ai = next.ai67        guard let account = activeAccount, let email = replyTarget(), !ai.isSuggesting else { return }68        ai.reset(for: reader.conversation.first?.threadId)69        let thread = ai.threadId70        ai.showReplies = true; ai.isSuggesting = true; ai.repliesError = nil71        defer { ai.isSuggesting = false }72        do {73            let r = try await app.next.api.suggestReplies(mailboxId: account, emailId: email.id, tone: ai.tone, language: ai.language)74            if ai.threadId == thread { ai.replies = r }75        } catch { if ai.threadId == thread { ai.replies = nil; ai.repliesError = app.next.describe(error); if (error as? NextError) == .aiDisabled { await app.next.reloadAI() } } }76    }77}7879struct ReaderIntelligence: View {80    let scene: MailScene81    private var next: NextServices { scene.app.next }82    private var ai: ReaderAIState { scene.next.ai }8384    var body: some View {85        let canSummarize = next.aiEnabled(.summary), canReply = next.aiEnabled(.reply) && scene.replyTarget() != nil86        if canSummarize || canReply {87            let thread = scene.reader.conversation.first?.threadId88            VStack(alignment: .leading, spacing: SPSpacing.m) {89                WrapLayout(spacing: SPSpacing.m) {90                    if canSummarize {91                        Button { Task { await scene.summarize() } } label: { Label(ai.summary != nil && ai.threadId == thread ? L("Résumer de nouveau") : L("Résumer"), systemImage: "sparkles").lineLimit(1).fixedSize() }92                            .disabled(ai.isSummarizing || !next.isOnline)93                    }94                    if canReply {95                        Button { Task { await scene.suggestReplies() } } label: { Label("Suggestions de réponse", systemImage: "text.bubble").lineLimit(1).fixedSize() }.disabled(ai.isSuggesting || !next.isOnline)96                    }97                    if ai.isSummarizing || ai.isSuggesting { ProgressView().controlSize(.small) }98                    // who will process the content, before anything is asked99                    Text(next.ai.isExternal ? L("Traité par Anthropic") : L("Traité par MacLustr local")).font(SPFont.caption).foregroundStyle(SPColor.text3).lineLimit(1).fixedSize()100                }101                .buttonStyle(.bordered).controlSize(.small).tint(SPColor.info)102                if !next.isOnline { Text("L’intelligence passe par le serveur : indisponible hors ligne.").font(SPFont.caption).foregroundStyle(SPColor.text3) }103                if ai.threadId == thread {104                    if let e = ai.summaryError { quiet(e) { Task { await scene.summarize() } } }105                    if let s = ai.summary { summary(s) }106                    if ai.showReplies { replies }107                }108            }109            .padding(.horizontal, SPSpacing.m)110            .onChange(of: thread) { _, t in ai.reset(for: t) }111        }112    }113114    private func quiet(_ message: String, retry: @escaping () -> Void) -> some View {115        HStack(spacing: SPSpacing.m) {116            Label(message, systemImage: "info.circle").font(SPFont.callout).foregroundStyle(SPColor.text2).fixedSize(horizontal: false, vertical: true)117            Spacer(minLength: 0)118            Button("Réessayer", action: retry).buttonStyle(.borderless).font(SPFont.callout)119        }120        .padding(SPSpacing.m).background(SPColor.surface2, in: RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous))121    }122123    private func heading(_ text: String) -> some View { Text(text).font(SPFont.caption).foregroundStyle(SPColor.info).textCase(.uppercase).padding(.top, SPSpacing.xs).accessibilityAddTraits(.isHeader) }124    private func bullet(_ text: String) -> some View {125        HStack(alignment: .firstTextBaseline, spacing: SPSpacing.m) { Text("•").foregroundStyle(SPColor.info); Text(text).foregroundStyle(SPColor.text).fixedSize(horizontal: false, vertical: true) }.font(SPFont.callout)126    }127128    private func summary(_ s: AIThreadSummary) -> some View {129        AIPanel(title: L("Résumé"), provider: next.providerLabel(provider: s.provider, model: s.model)) {130            Text(s.summary).font(SPFont.body).foregroundStyle(SPColor.text).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)131            if !s.decisions.isEmpty { heading(L("Décisions")); ForEach(Array(s.decisions.enumerated()), id: \.offset) { _, d in bullet(d) } }132            if !s.actionItems.isEmpty {133                heading(L("À faire"))134                ForEach(Array(s.actionItems.enumerated()), id: \.offset) { _, item in135                    HStack(alignment: .firstTextBaseline, spacing: SPSpacing.m) {136                        Image(systemName: "circle").imageScale(.small).foregroundStyle(SPColor.info)137                        VStack(alignment: .leading, spacing: 0) {138                            Text(item.text).font(SPFont.callout).foregroundStyle(SPColor.text).fixedSize(horizontal: false, vertical: true)139                            let meta = [item.owner, item.due].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")140                            if !meta.isEmpty { Text(meta).font(SPFont.caption).foregroundStyle(SPColor.text3) }141                        }142                        Spacer(minLength: SPSpacing.m)143                        if next.has(.reminders), let account = scene.activeAccount, let email = scene.replyTarget() {144                            // an action item becomes a reminder on this message, the item as its note — the date is the owner's choice145                            Button { scene.next.reminderNote = item.text; scene.next.snoozeRequest = SnoozeRequest(account: account, emailIds: [email.id], mode: .remind) } label: { Label("Créer un rappel", systemImage: "bell.badge").labelStyle(.iconOnly).frame(minWidth: 28, minHeight: 28) }146                                .buttonStyle(.borderless).help("Créer un rappel pour cette action").accessibilityLabel(Text("Créer un rappel : \(item.text)"))147                        }148                    }149                }150            }151            if !s.deadlines.isEmpty { heading(L("Échéances")); ForEach(Array(s.deadlines.enumerated()), id: \.offset) { _, d in bullet([d.text, d.date].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " — ")) } }152            if !s.timeline.isEmpty {153                heading(L("Chronologie"))154                ForEach(Array(s.timeline.enumerated()), id: \.offset) { _, e in155                    bullet([e.date?.formatted(date: .abbreviated, time: .omitted) ?? e.at, e.who.isEmpty ? nil : e.who, e.what].compactMap { $0 }.joined(separator: " · "))156                }157            }158            Text("Résumé généré automatiquement : vérifiez les points importants dans les messages.").font(SPFont.caption).foregroundStyle(SPColor.text3).padding(.top, SPSpacing.xs)159        }160    }161162    @ViewBuilder private var replies: some View {163        @Bindable var ai = scene.next.ai164        AIPanel(title: L("Suggestions de réponse"), provider: ai.replies.map { next.providerLabel(provider: $0.provider, model: $0.model) } ?? (next.ai.isExternal ? "Anthropic" : L("MacLustr local"))) {165            HStack(spacing: SPSpacing.m) {166                Picker("Ton", selection: $ai.tone) { ForEach(ReplyTone.allCases, id: \.self) { Text($0.title).tag($0) } }.pickerStyle(.segmented).labelsHidden().accessibilityLabel(Text("Ton"))167                Picker("Langue", selection: $ai.language) { Text("FR").tag("fr"); Text("EN").tag("en") }.pickerStyle(.segmented).labelsHidden().fixedSize().accessibilityLabel(Text("Langue de la réponse"))168            }169            .onChange(of: ai.tone) { _, _ in Task { await scene.suggestReplies() } }170            .onChange(of: ai.language) { _, _ in Task { await scene.suggestReplies() } }171            if let e = ai.repliesError { quiet(e) { Task { await scene.suggestReplies() } } }172            if ai.isSuggesting, ai.replies == nil { BodySkeleton() }173            ForEach(ai.replies?.suggestions ?? []) { suggestion in174                VStack(alignment: .leading, spacing: SPSpacing.m) {175                    Text(suggestion.text).font(SPFont.callout).foregroundStyle(SPColor.text).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)176                    Button { if let email = scene.replyTarget() { Task { await scene.composeReply(to: email, inserting: suggestion.text, subject: suggestion.subject) } } } label: { Label("Ouvrir dans la réponse", systemImage: "square.and.pencil") }177                        .buttonStyle(.bordered).controlSize(.small)178                        .help("Ouvre le rédacteur avec ce texte : rien n’est envoyé sans vous")179                }180                .padding(SPSpacing.l).frame(maxWidth: .infinity, alignment: .leading)181                .background(SPColor.surface, in: RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous))182            }183            Text("Choisir une suggestion ouvre le rédacteur avec le texte : vous relisez, modifiez et envoyez vous-même.").font(SPFont.caption).foregroundStyle(SPColor.text3)184        }185    }186}187188// MARK: - Settings › Intelligence189190struct IntelligenceSettings: View {191    @Bindable var model: AppModel192    @State private var index: SemanticIndexStatus?193    @State private var usage: AIUsageReport?194    @State private var error: String?195    @State private var askConsent = false196    @State private var working = false197    @State private var loaded = false198199    private var next: NextServices { model.next }200    private var ai: AISettings { next.ai }201202    var body: some View {203        Form {204            if !next.has(.ai) {205                Section { Text(next.isAvailable ? L("Ce serveur ne propose pas la couche d’intelligence.") : L("Indisponible : ce serveur ne propose pas les fonctions SP Mail Next, ou l’app n’a pas encore pu le joindre.")).foregroundStyle(.secondary) }206            } else {207                Section {208                    Picker("Fournisseur", selection: Binding(get: { ai.provider == .unknown ? .off : ai.provider }, set: { choose($0) })) {209                        Text("Désactivée").tag(AIProvider.off)210                        Text(ai.localAvailable ? L("MacLustr local") : L("MacLustr local (non configuré sur ce serveur)")).tag(AIProvider.local)211                        Text(ai.anthropicAvailable ? "Anthropic" : L("Anthropic (non configuré sur ce serveur)")).tag(AIProvider.anthropic)212                    }213                    .disabled(working || !model.isOnline)214                    switch ai.provider {215                    case .off, .unknown: Text("L’intelligence est désactivée : aucun contenu n’est transmis à un modèle, et aucune de ses fonctions n’apparaît dans l’app.").font(.footnote).foregroundStyle(.secondary)216                    case .local: Text("MacLustr local : le contenu traité reste sur l’infrastructure du propriétaire de ce serveur.").font(.footnote).foregroundStyle(.secondary)217                    case .anthropic:218                        Label("Anthropic : le contenu des messages traités quitte l’infrastructure du propriétaire et est envoyé à Anthropic.", systemImage: "exclamationmark.shield").font(.footnote).foregroundStyle(SPColor.warn)219                        if let at = ai.consentExternalAt { Text("Consentement enregistré le \(at.formatted(date: .abbreviated, time: .shortened)).").font(.footnote).foregroundStyle(.secondary) }220                    }221                } header: { Text("Fournisseur") } footer: { Text("Un modèle ne fait que proposer : il n’envoie, ne déplace et ne supprime jamais rien.") }222223                if ai.provider != .off, ai.provider != .unknown {224                    Section("Fonctions") {225                        feature(.summary, L("Résumé de conversation"), L("« Résumer » dans la lecture : résumé, décisions, actions, échéances."))226                        feature(.reply, L("Suggestions de réponse"), L("Trois réponses proposées, insérées dans le rédacteur pour relecture."))227                        feature(.write, L("Aide à la rédaction"), L("Améliorer, corriger, raccourcir ou traduire un brouillon."))228                        feature(.triage, L("Tri intelligent"), L("Catégories discrètes dans la boîte de réception et filtre « Important »."))229                        feature(.semantic, L("Recherche par le sens"), ai.semanticAvailable ? L("Recherche hybride ; l’index est calculé sur le serveur, sans tiers.") : L("Indisponible : ce serveur ne peut pas calculer l’index."), disabled: !ai.semanticAvailable)230                    }231                    Section("Langue des réponses") {232                        Picker("Langue", selection: Binding(get: { ai.language == .unknown ? .auto : ai.language }, set: { l in apply(AISettingsUpdate(language: l)) })) {233                            Text("Automatique").tag(AILanguage.auto); Text("Français").tag(AILanguage.fr); Text("English").tag(AILanguage.en)234                        }235                        .disabled(working)236                    }237                    if ai.isEnabled(.semantic) {238                        Section {239                            if let index {240                                LabeledContent("Messages indexés", value: index.total.map { "\(index.indexed) / \($0)" } ?? "\(index.indexed)")241                                if index.pending > 0 { LabeledContent("En attente", value: "\(index.pending)") }242                                if let m = index.model, !m.isEmpty { LabeledContent("Modèle", value: m) }243                                if index.running { Label("Indexation en cours", systemImage: "arrow.triangle.2.circlepath").foregroundStyle(.secondary) }244                                if let e = index.lastError, !e.isEmpty { Text(e).font(.footnote).foregroundStyle(SPColor.danger) }245                            } else { Text("État de l’index indisponible").foregroundStyle(.secondary) }246                            Button("Reconstruire l’index") { rebuild() }.disabled(working || !model.isOnline)247                        } header: { Text("Index sémantique") } footer: { Text("L’index est supprimé quand la recherche par le sens est désactivée.") }248                    }249                    if let usage {250                        Section("Utilisation") {251                            LabeledContent("Demandes sur 24 h", value: usage.perDay.map { "\(usage.used24h) / \($0)" } ?? "\(usage.used24h)")252                            if let m = usage.perMinute { LabeledContent("Limite par minute", value: "\(m)") }253                        }254                    }255                }256                if !model.isOnline { Section { Label("Hors ligne : ces réglages se modifient en ligne.", systemImage: "wifi.slash").foregroundStyle(.secondary) } }257                if let error { Section { Text(error).foregroundStyle(SPColor.danger) } }258            }259        }260        .formStyle(.grouped)261        .task { await load() }262        .alert("Envoyer du contenu à Anthropic ?", isPresented: $askConsent) {263            Button("J’accepte : utiliser Anthropic") { apply(AISettingsUpdate(provider: .anthropic, consentExternal: true)) }264            Button("Annuler", role: .cancel) {}265        } message: {266            Text("Avec ce fournisseur, le contenu des messages que vous faites traiter (résumé, suggestions, tri, rédaction) quitte l’infrastructure du propriétaire de ce serveur et est envoyé à Anthropic. Rien n’est transmis tant que vous n’utilisez pas une fonction d’intelligence. Vous pouvez revenir à « Désactivée » ou à « MacLustr local » à tout moment.")267        }268    }269270    private func feature(_ f: AIFeature, _ title: String, _ detail: String, disabled: Bool = false) -> some View {271        Toggle(isOn: Binding(get: { ai.features[f.rawValue] == true }, set: { on in apply(AISettingsUpdate(feature: f, enabled: on)) })) {272            VStack(alignment: .leading, spacing: 1) { Text(title); Text(detail).font(.footnote).foregroundStyle(.secondary) }273        }274        .disabled(disabled || working || !model.isOnline)275    }276277    private func choose(_ provider: AIProvider) {278        guard provider != ai.provider else { return }279        // the external provider always goes through the explicit consent dialog, unless a consent is already on record280        if provider == .anthropic, !ai.hasExternalConsent { askConsent = true; return }281        apply(AISettingsUpdate(provider: provider))282    }283284    private func apply(_ update: AISettingsUpdate) {285        working = true; error = nil286        Task {287            defer { working = false }288            do { try await next.setAI(update); await loadIndex() } catch NextError.consentRequired { askConsent = true } catch { self.error = next.describe(error) }289        }290    }291292    private func rebuild() {293        working = true; error = nil294        Task {295            defer { working = false }296            do { let n = try await next.api.rebuildSemanticIndex(); model.toast = Toast(message: L("\(n) messages mis en file pour l’index"), kind: .info); await loadIndex() } catch { self.error = next.describe(error) }297        }298    }299300    private func load() async {301        guard next.has(.ai) else { return }302        await next.reloadAI()303        await loadIndex()304        usage = try? await next.api.aiUsage(days: 1)305        loaded = true306    }307    private func loadIndex() async { index = ai.isEnabled(.semantic) ? try? await next.api.semanticIndexStatus() : nil }308}309
Files main
Menu

Theme