Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/AI/AssistantPanel.swift3// Description: Assistant panel: the server's AI actions on the selection or the note (streamed), questions about the note or the workspace, and explicit application of a proposal — nothing is ever written to the note without a click.4import SwiftUI5import SPNotesDocument6import SPNotesEditor7import SPNotesAPI8import SPNotesSync9import SPNotesDesign1011@Observable final class AssistantModel {12 enum Phase: Equatable { case idle, running, done, failed(String), needsConfirmation(String) }13 private(set) var phase: Phase = .idle14 private(set) var output = ""15 private(set) var modelName: String?16 private(set) var costUsd: Double?17 private(set) var sentDescription = ""18 /// Sources of a grounded answer: each opens its page at the cited block.19 private(set) var citations: [AssistantCitation] = []20 @ObservationIgnored var citationsOf: ((AIEvent) -> [AssistantCitation])?21 /// Range of the selection the proposal was computed from (nil = whole note).22 private(set) var sourceRange: NSRange?23 @ObservationIgnored private var task: Task<Void, Never>?24 @ObservationIgnored private var last: (() -> Void)?2526 func stop() { task?.cancel(); task = nil; if phase == .running { phase = output.isEmpty ? .idle : .done } }27 func reset() { stop(); phase = .idle; output = ""; modelName = nil; costUsd = nil; citations = [] }2829 /// Model chosen by the owner for the next requests (nil = the server routes automatically).30 @ObservationIgnored var chosenModel: String?3132 func run(action: AIActionKind, instruction: String? = nil, language: String? = nil, session: NoteSession, api: NotesAPI, confirm: Bool = false) {33 let v = session.editor.textView; let sel = v.selectedRange()34 let text = v.selectedMarkdown()35 guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { phase = .failed("La note est vide : il n'y a rien à envoyer."); return }36 sourceRange = sel.length > 0 ? sel : nil37 sentDescription = sel.length > 0 ? "Envoyé au serveur : la sélection (\(text.count) caractères)." : "Envoyé au serveur : le texte de cette note (\(text.count) caractères)."38 last = { [weak self] in self?.run(action: action, instruction: instruction, language: language, session: session, api: api, confirm: true) }39 let chosen = chosenModel40 start { try await api.aiAction(AIActionRequest(action: action, text: String(text.prefix(120_000)), instruction: instruction, model: chosen, language: language, confirmExpensive: confirm ? true : nil)) }41 }4243 func ask(_ question: String, mode: AIChatMode, session: NoteSession, api: NotesAPI, confirm: Bool = false) {44 sourceRange = nil45 sentDescription = mode == .notes ? "Envoyé au serveur : ta question ; il cherche dans tes notes synchronisées." : mode == .general ? "Envoyé au serveur : ta question seulement." : "Envoyé au serveur : ta question et cette note (sa version synchronisée)."46 let pageId = mode == .general || mode == .notes ? nil : session.id47 last = { [weak self] in self?.ask(question, mode: mode, session: session, api: api, confirm: true) }48 let chosen = chosenModel49 start { try await api.aiChat(AIChatRequest(message: question, clientId: NotesAPI.newIdempotencyKey(), mode: mode, pageId: pageId, model: chosen, confirmExpensive: confirm ? true : nil)) }50 }51 func confirmExpensive() { last?() }5253 private func start(_ open: @escaping @Sendable () async throws -> AsyncThrowingStream<AIEvent, Error>) {54 task?.cancel(); output = ""; modelName = nil; costUsd = nil; citations = []; phase = .running55 task = Task { [weak self] in56 do {57 for try await event in try await open() {58 guard let self, !Task.isCancelled else { return }59 let cited = self.citationsOf?(event) ?? []; if !cited.isEmpty { self.citations = cited }60 switch event {61 case .meta(let m): self.modelName = m.model62 case .text(let t): self.output += t63 case .done(let d): self.costUsd = d.costUsd; if let c = d.content, !c.isEmpty { self.output = c }; self.phase = .done64 case .error(let e): self.phase = .failed(Self.describe(code: e.code, message: e.message))65 case .needsConfirmation(let c): self.phase = .needsConfirmation(c.reason ?? "Cette demande est coûteuse.")66 case .other: break67 }68 }69 if let self, self.phase == .running { self.phase = self.output.isEmpty ? .failed("Le serveur n'a rien renvoyé.") : .done }70 } catch let e as APIError {71 guard let self, !Task.isCancelled else { return }72 if case .confirmExpensive(_, let message) = e { self.phase = .needsConfirmation(message) }73 else if e.isOffline { self.phase = .failed("Hors ligne : l'assistant a besoin du serveur. L'éditeur et tes notes restent disponibles.") }74 else if e.isUnauthenticated { self.phase = .failed("Connecte-toi pour utiliser l'assistant.") }75 else { self.phase = .failed(Self.describe(code: e.code, message: e.message)) }76 } catch { if let self, !Task.isCancelled { self.phase = .failed("La demande n'a pas abouti.") } }77 }78 }79 static func describe(code: String?, message: String) -> String {80 switch code {81 case "not_configured": "L'IA n'est pas configurée sur le serveur (aucune clé de fournisseur)."82 case "no_model": "Aucun modèle n'est disponible pour cette demande."83 case "refused": "Le modèle a refusé cette demande."84 case "page_required": "Cette note doit d'abord être synchronisée."85 case "rate_limited": "Trop de demandes. Réessaie dans un instant."86 default: message87 }88 }89}9091struct AssistantPanel: View {92 @Environment(AppEnvironment.self) private var env93 @Environment(WindowModel.self) private var window94 let session: NoteSession95 @State private var model = AssistantModel()96 @State private var question = ""97 @State private var scope: AIChatMode = .summarise98 @State private var custom = ""99100 private static let actions: [(AIActionKind, String, String)] = [(.summarize, "Résumer", "text.redaction"), (.rewrite, "Reformuler", "arrow.triangle.2.circlepath"), (.fix, "Corriger", "checkmark.seal"), (.shorten, "Raccourcir", "arrow.down.right.and.arrow.up.left"), (.expand, "Développer", "arrow.up.left.and.arrow.down.right"), (.simplify, "Simplifier", "wand.and.stars"), (.explain, "Expliquer", "questionmark.bubble"), (.outline, "Faire un plan", "list.bullet.indent"), (.actionItems, "Points d'action", "checklist"), (.toTasks, "En liste de tâches", "checklist.unchecked"), (.toList, "En liste", "list.bullet"), (.table, "En tableau", "tablecells"), (.continue, "Continuer", "text.append")]101 private static let languages = [("fr", "Français"), ("en", "Anglais"), ("es", "Espagnol"), ("de", "Allemand"), ("it", "Italien"), ("pt", "Portugais")]102 private var hasSelection: Bool { session.editor.selection.hasSelection }103 private var available: Bool { env.account.isSignedIn && env.connectivity.reachable }104105 var body: some View {106 VStack(alignment: .leading, spacing: 0) {107 PanelHeader(title: "Assistant", symbol: "sparkles", subtitle: hasSelection ? "Sur la sélection" : "Sur la note", tone: NVColor.ai) { AssistantModelButton() }.padding(NVSpace.lg)108 Divider().overlay(NVColor.line)109 ScrollView {110 VStack(alignment: .leading, spacing: NVSpace.lg) {111 if !available { Label(env.account.isSignedIn ? "Hors ligne : l'assistant a besoin du serveur." : "Connecte-toi pour utiliser l'assistant. Tes notes restent disponibles sans lui.", systemImage: "wifi.slash").font(.callout).foregroundStyle(.secondary) }112 FlowLayout(spacing: 6) {113 ForEach(Self.actions, id: \.0) { a in Button { model.run(action: a.0, session: session, api: env.api) } label: { Label(a.1, systemImage: a.2) }.accessibilityIdentifier("ai-" + a.0.rawValue) }114 Menu { ForEach(Self.languages, id: \.0) { l in Button(l.1) { model.run(action: .translate, language: l.0, session: session, api: env.api) } } } label: { Label("Traduire", systemImage: "character.bubble") }.fixedSize()115 }.controlSize(.small).disabled(!available || model.phase == .running)116 HStack { TextField("Consigne libre (ex. : ton plus formel)", text: $custom).textFieldStyle(.roundedBorder).onSubmit(runCustom); Button("Appliquer", action: runCustom).disabled(custom.trimmingCharacters(in: .whitespaces).isEmpty) }.controlSize(.small).disabled(!available || model.phase == .running)117 Divider()118 VStack(alignment: .leading, spacing: 6) {119 Picker("Portée", selection: $scope) { Text("Cette note").tag(AIChatMode.summarise); Text("Toutes mes notes").tag(AIChatMode.notes); Text("Général").tag(AIChatMode.general) }.pickerStyle(.segmented).labelsHidden()120 HStack(alignment: .bottom) {121 TextField(scope == .notes ? "Question sur mes notes…" : scope == .general ? "Question générale…" : "Question sur cette note…", text: $question, axis: .vertical).lineLimit(1...4).textFieldStyle(.roundedBorder).onSubmit(ask).accessibilityIdentifier("ai-question")122 Button { ask() } label: { Image(systemName: "arrow.up.circle.fill").font(.title2) }.buttonStyle(.plain).foregroundStyle(NVColor.ai).disabled(question.trimmingCharacters(in: .whitespaces).isEmpty).help("Envoyer")123 }124 if scope == .notes { Text("La réponse ne s'appuie que sur tes notes synchronisées, avec citations ; le serveur le dit quand elles ne suffisent pas.").font(.caption2).foregroundStyle(.secondary) }125 }.controlSize(.small).disabled(!available || model.phase == .running)126 result127 }.padding(NVSpace.lg)128 }129 }130 .onAppear { let repo = env.repositories.assistant; model.citationsOf = { repo.citations(of: $0) }; model.chosenModel = window.assistantModel }131 .onChange(of: window.assistantModel) { _, m in model.chosenModel = m }132 .accessibilityIdentifier("assistant-panel")133 }134135 @ViewBuilder private var result: some View {136 switch model.phase {137 case .idle: EmptyView()138 case .failed(let m): Label(m, systemImage: "exclamationmark.triangle").nvFont(.ui).foregroundStyle(NVColor.warningText)139 case .needsConfirmation(let m):140 VStack(alignment: .leading, spacing: 6) { Label(m, systemImage: "dollarsign.circle").font(.callout); HStack { Button("Annuler") { model.reset() }; Button("Continuer quand même") { model.confirmExpensive() }.buttonStyle(.borderedProminent) }.controlSize(.small) }141 case .running, .done:142 VStack(alignment: .leading, spacing: 8) {143 HStack { NVAIBadge(model: model.modelName, style: .full); Spacer(); if model.phase == .running { ProgressView().controlSize(.small); Button("Arrêter") { model.stop() }.controlSize(.small) } }144 Text(model.output.isEmpty ? "…" : model.output).textSelection(.enabled).font(.callout).frame(maxWidth: .infinity, alignment: .leading)145 .padding(NVSpace.md).background(NVColor.aiSoft, in: NVRadius.shape(NVRadius.md)).accessibilityIdentifier("ai-output")146 if !model.citations.isEmpty {147 // the sources of the answer: a click opens the note at the cited block148 VStack(alignment: .leading, spacing: NVSpace.xs) {149 GroupLabel("Sources")150 FlowLayout(spacing: NVSpace.xs) {151 ForEach(model.citations) { c in152 NVCitationChip(index: c.n, label: c.title.map { Format.title($0) } ?? c.heading ?? "Source") { if let page = c.pageId { window.open(Route(pageId: page, blockId: c.blockId)) } }153 .help(c.quote ?? c.heading ?? "Ouvrir la source").disabled(c.pageId == nil)154 }155 }156 }.accessibilityIdentifier("ai-citations")157 }158 Text(model.sentDescription + (model.modelName.map { " Modèle : \($0)." } ?? "") + (model.costUsd.map { String(format: " Coût : %.4f $.", $0) } ?? "")).font(.caption2).foregroundStyle(.secondary)159 if model.phase == .done, !model.output.isEmpty {160 FlowLayout(spacing: 6) {161 if model.sourceRange != nil, session.isEditable { Button("Remplacer la sélection") { apply(replace: true) }.buttonStyle(.borderedProminent) }162 if session.isEditable { Button(model.sourceRange != nil ? "Insérer après" : "Insérer dans la note") { apply(replace: false) } }163 Button("Copier") { NSPasteboard.general.clearContents(); NSPasteboard.general.setString(model.output, forType: .string) }164 Button("Nouvelle note") { Task { if let id = await env.library.newNote(title: "Proposition de l'assistant", content: NoteDocument(markdown: model.output)) { env.open(noteId: id) } } }165 Button("Ignorer") { model.reset() }166 }.controlSize(.small)167 }168 }169 }170 }171 private func runCustom() { let c = custom.trimmingCharacters(in: .whitespaces); guard !c.isEmpty else { return }; model.run(action: .custom, instruction: c, session: session, api: env.api) }172 private func ask() { let q = question.trimmingCharacters(in: .whitespacesAndNewlines); guard !q.isEmpty else { return }; model.ask(q, mode: scope, session: session, api: env.api); question = "" }173 /// The proposal becomes one undoable edit of the note.174 private func apply(replace: Bool) {175 let v = session.editor.textView176 if replace, let r = model.sourceRange, NSMaxRange(r) <= v.storage.length { v.insertMarkdown(model.output, replacing: r, actionName: "Proposition de l'assistant") }177 else { if let r = model.sourceRange { v.setSelectedRange(NSRange(location: min(NSMaxRange(r), max(0, v.storage.length - 1)), length: 0)) }; v.insertMarkdown(model.output, actionName: "Proposition de l'assistant") }178 model.reset(); session.editor.focus()179 }180}181