Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Compose/WritingAssistant.swift3// Description: The writing assistant of the composer (optional intelligence, feature « write ») — improve, fix grammar, shorten, expand,4// change tone, translate, propose subject lines. It acts on the selection, or on everything the person wrote above the signature; the5// quoted original and the signature are never sent to the model. Nothing is applied before the person has read the proposal: preview,6// then accept or cancel. Hidden entirely when the feature is off; every surface names the provider that processes the text.7import SPMailCore8import SwiftUI910/// What the model proposed for one request of one composer.11@MainActor @Observable12final class WritingAssistant {13 var isPresented = false14 var action = AIWriteAction.improve15 /// `professional`, `concise`, `detailed`, `friendly`, `formal` — for the « tone » action.16 var tone: String?17 /// `fr`, `en`, `es`, `de`, `it`, `pt` — for the « translate » action.18 var targetLanguage: String?19 /// The text that was sent (the selection, or the authored text) and where it sits in the editor.20 var source = ""21 var range = NSRange(location: 0, length: 0)22 var onSelection = false23 /// The range holds something a plain-text proposal cannot carry (an inline image): accepting inserts under it instead of replacing it.24 var keepsOriginal = false25 var isWorking = false26 var proposal: String?27 var subjects: [String] = []28 /// Who processed the text (« MacLustr local · model », « Anthropic · model »): known once the server answered.29 var provider = ""30 var error: String?31 @ObservationIgnored var task: Task<Void, Never>?3233 func reset() {34 task?.cancel(); task = nil35 isWorking = false; proposal = nil; subjects = []; provider = ""; error = nil; source = ""; keepsOriginal = false36 }37}3839extension AIWriteAction {40 var title: String {41 switch self {42 case .improve: L("Améliorer")43 case .grammar: L("Corriger l’orthographe et la grammaire")44 case .shorten: L("Raccourcir")45 case .expand: L("Développer")46 case .tone: L("Changer le ton")47 case .translate: L("Traduire")48 case .subject: L("Proposer des objets")49 }50 }51 var icon: String {52 switch self {53 case .improve: "wand.and.stars"; case .grammar: "textformat.abc.dottedunderline"; case .shorten: "arrow.down.right.and.arrow.up.left"; case .expand: "arrow.up.left.and.arrow.down.right"54 case .tone: "theatermasks"; case .translate: "character.bubble"; case .subject: "text.cursor"55 }56 }57}5859enum WritingTone: String, CaseIterable, Identifiable {60 case professional, concise, detailed, friendly, formal61 var id: String { rawValue }62 var title: String {63 switch self { case .professional: L("Professionnel"); case .concise: L("Concis"); case .detailed: L("Détaillé"); case .friendly: L("Amical"); case .formal: L("Formel") }64 }65}6667enum WritingLanguage: String, CaseIterable, Identifiable {68 case fr, en, es, de, it, pt69 var id: String { rawValue }70 /// Each language under its own name, as language pickers do.71 var title: String { switch self { case .fr: "Français"; case .en: "English"; case .es: "Español"; case .de: "Deutsch"; case .it: "Italiano"; case .pt: "Português" } }72}7374extension ComposeModel {75 /// The assistant exists only while the owner enabled the « write » feature of the intelligence layer (off by default).76 var assistantAvailable: Bool { app?.next.aiEnabled(.write) == true }77 /// Who will process the text, said before anything is asked.78 var assistantProviderNotice: String { app?.next.ai.isExternal == true ? L("Traité par Anthropic") : L("Traité par MacLustr local") }7980 /// What the person wrote: from the top of the text to the signature block (the block and the quoted original are not part of it).81 var authoredRange: NSRange {82 let end = RichSignature.range(in: editor.document).map { max(0, $0.location - 2) } ?? editor.storage.length83 return NSRange(location: 0, length: min(end, editor.storage.length))84 }85 private func plain(_ range: NSRange) -> String {86 (editor.storage.string as NSString).substring(with: range).replacingOccurrences(of: RichText.attachmentCharacter, with: "")87 }88 var authoredPlainText: String { plain(authoredRange) }8990 /// Asks the model for a rewrite of the selection (when there is one, signature excluded) or of the authored text, or for subject lines91 /// of the authored text. The editor is not touched: the answer is shown for review.92 func assist(_ action: AIWriteAction, tone: WritingTone? = nil, language: WritingLanguage? = nil) async {93 guard let app, assistantAvailable, !isLocked else { return }94 let a = assistant95 a.reset()96 a.action = action; a.tone = tone?.rawValue; a.targetLanguage = language?.rawValue97 let authored = authoredRange98 let selected = NSIntersectionRange(editor.selection, authored)99 let useSelection = action != .subject && selected.length > 0 && !plain(selected).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty100 a.range = useSelection ? selected : authored101 a.onSelection = useSelection102 a.source = plain(a.range)103 a.keepsOriginal = (editor.storage.string as NSString).substring(with: a.range).contains(RichText.attachmentCharacter)104 a.isPresented = true105 let text = a.source.trimmingCharacters(in: .whitespacesAndNewlines)106 guard !text.isEmpty else { a.error = L("Écrivez d’abord quelques mots : l’assistant travaille sur votre texte."); return }107 guard text.count <= 20_000 else { a.error = L("Ce texte est trop long pour l’assistant. Sélectionnez-en une partie."); return }108 guard app.isOnline else { a.error = L("L’intelligence passe par le serveur : indisponible hors ligne."); return }109 a.isWorking = true110 let request = AIWriteRequest(action: action, text: text, tone: action == .tone ? (tone ?? .professional).rawValue : nil, targetLanguage: action == .translate ? (language ?? .en).rawValue : nil)111 let work = Task { [weak self] in112 defer { a.isWorking = false }113 do {114 let result = try await app.next.api.write(request)115 guard !Task.isCancelled, self != nil else { return }116 a.provider = app.next.providerLabel(provider: result.provider, model: result.model)117 if action == .subject { a.subjects = result.subjects; if result.subjects.isEmpty { a.error = L("Le modèle n’a pas produit de réponse exploitable. Réessayez.") } }118 else if let t = result.text?.trimmingCharacters(in: .whitespacesAndNewlines), !t.isEmpty { a.proposal = t }119 else { a.error = L("Le modèle n’a pas produit de réponse exploitable. Réessayez.") }120 } catch {121 guard !Task.isCancelled else { return }122 a.error = app.next.describe(error) ?? ""123 if (error as? NextError) == .aiDisabled { await app.next.reloadAI() }124 }125 }126 a.task = work127 await work.value128 }129130 /// True while the text the proposal was made for is still where it was (the person may have typed meanwhile).131 var assistantSourceUnchanged: Bool {132 let a = assistant133 return NSMaxRange(a.range) <= editor.storage.length && plain(a.range) == a.source134 }135136 /// Applies the proposal as ONE undoable edit: over the text it was made for, or under it when that text holds an inline image.137 /// Returns false (and says why) when the text changed since the request.138 @discardableResult139 func acceptAssist() -> Bool {140 let a = assistant141 guard let proposal = a.proposal, !isLocked else { return false }142 guard assistantSourceUnchanged else { a.error = L("Le texte a changé depuis la demande. Relancez l’assistant."); a.proposal = nil; return false }143 if a.keepsOriginal {144 editor.edit(NSRange(location: NSMaxRange(a.range), length: 0), with: RichText.attributed(fromPlain: "\n" + proposal), actionName: L("Aide à la rédaction"))145 } else {146 editor.edit(a.range, with: RichText.attributed(fromPlain: proposal), select: NSRange(location: a.range.location + (proposal as NSString).length, length: 0), actionName: L("Aide à la rédaction"))147 }148 a.isPresented = false149 a.reset()150 return true151 }152153 func acceptSubject(_ subject: String) {154 setSubject(subject)155 assistant.isPresented = false156 assistant.reset()157 }158159 func cancelAssist() {160 assistant.isPresented = false161 assistant.reset()162 }163}164165// MARK: - menu166167/// The assistant's entry in the formatting bar and in the composer's « Plus » menu. Renders nothing while the feature is off.168struct WritingAssistantMenu: View {169 let model: ComposeModel170 var side: CGFloat = 28171 var accessory = false172173 var body: some View {174 if model.assistantAvailable {175 Menu {176 WritingAssistantItems(model: model)177 } label: {178 Image(systemName: "sparkles").font(.system(size: accessory ? 17 : 13)).frame(width: side, height: side).foregroundStyle(SPColor.info).contentShape(Rectangle())179 }180 .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize()181 .disabled(model.isLocked)182 .help("Aide à la rédaction")183 .accessibilityLabel(Text("Aide à la rédaction"))184 }185 }186}187188struct WritingAssistantItems: View {189 let model: ComposeModel190191 var body: some View {192 let online = model.app?.isOnline != false193 Section {194 ForEach([AIWriteAction.improve, .grammar, .shorten, .expand], id: \.self) { action in195 Button { Task { await model.assist(action) } } label: { Label(action.title, systemImage: action.icon) }196 }197 Menu {198 ForEach(WritingTone.allCases) { tone in Button(tone.title) { Task { await model.assist(.tone, tone: tone) } } }199 } label: { Label(AIWriteAction.tone.title, systemImage: AIWriteAction.tone.icon) }200 Menu {201 ForEach(WritingLanguage.allCases) { language in Button(language.title) { Task { await model.assist(.translate, language: language) } } }202 } label: { Label(AIWriteAction.translate.title, systemImage: AIWriteAction.translate.icon) }203 Divider()204 Button { Task { await model.assist(.subject) } } label: { Label(AIWriteAction.subject.title, systemImage: AIWriteAction.subject.icon) }205 } header: {206 // who will process the text, before anything is asked207 Text(online ? model.assistantProviderNotice : L("L’intelligence passe par le serveur : indisponible hors ligne."))208 }209 .disabled(!online)210 }211}212213// MARK: - preview214215/// The proposal next to what it would replace, with the provider's name: accept, ask again or cancel. Nothing changes in the message216/// until « accept ».217struct WritingAssistantSheet: View {218 let model: ComposeModel219 private var a: WritingAssistant { model.assistant }220221 var body: some View {222 NavigationStack {223 ScrollView {224 VStack(alignment: .leading, spacing: SPSpacing.xl) {225 AIPanel(title: a.action.title, provider: a.provider.isEmpty ? model.assistantProviderNotice : a.provider) {226 if a.isWorking { BodySkeleton() }227 if let e = a.error {228 Label(e, systemImage: "info.circle").font(SPFont.callout).foregroundStyle(SPColor.text2).fixedSize(horizontal: false, vertical: true)229 }230 if let p = a.proposal {231 Text(p).font(SPFont.body).foregroundStyle(SPColor.text).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)232 .accessibilityLabel(Text("Proposition : \(p)"))233 }234 ForEach(Array(a.subjects.enumerated()), id: \.offset) { _, s in235 Button { model.acceptSubject(s) } label: {236 HStack(spacing: SPSpacing.m) {237 Text(s).font(SPFont.callout).foregroundStyle(SPColor.text).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true)238 Spacer(minLength: SPSpacing.m)239 Image(systemName: "arrow.up.left").imageScale(.small).foregroundStyle(SPColor.text3)240 }241 .padding(SPSpacing.l).frame(maxWidth: .infinity, alignment: .leading)242 .background(SPColor.surface, in: RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous))243 .contentShape(Rectangle())244 }245 .buttonStyle(.plain)246 .accessibilityHint(Text("Utiliser comme objet du message"))247 }248 Text(a.action == .subject ? L("Choisir un objet remplace celui du message. Rien d’autre n’est modifié.")249 : L("Proposition générée automatiquement : relisez-la. Rien n’est modifié dans le message avant que vous l’acceptiez."))250 .font(SPFont.caption).foregroundStyle(SPColor.text3).padding(.top, SPSpacing.xs)251 }252 if !a.source.isEmpty, a.action != .subject {253 VStack(alignment: .leading, spacing: SPSpacing.s) {254 Text(a.onSelection ? L("Texte sélectionné") : L("Votre texte")).font(SPFont.caption).foregroundStyle(SPColor.text3).textCase(.uppercase).accessibilityAddTraits(.isHeader)255 Text(a.source.trimmingCharacters(in: .whitespacesAndNewlines)).font(SPFont.callout).foregroundStyle(SPColor.text2).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)256 }257 .padding(.horizontal, SPSpacing.m)258 }259 }260 .padding(SPSpacing.xl)261 .frame(maxWidth: .infinity, alignment: .leading)262 }263 .background(SPColor.bg)264 .navigationTitle("Aide à la rédaction")265 #if os(iOS)266 .navigationBarTitleDisplayMode(.inline)267 #endif268 .toolbar {269 ToolbarItem(placement: .cancellationAction) { Button("Annuler", role: .cancel) { model.cancelAssist() } }270 if a.action != .subject {271 ToolbarItem(placement: .confirmationAction) {272 Button(a.keepsOriginal ? L("Insérer sous le texte") : a.onSelection ? L("Remplacer la sélection") : L("Remplacer mon texte")) { model.acceptAssist() }273 .disabled(a.proposal == nil || a.isWorking)274 }275 }276 ToolbarItem(placement: .automatic) {277 Button { Task { await model.assist(a.action, tone: a.tone.flatMap(WritingTone.init(rawValue:)), language: a.targetLanguage.flatMap(WritingLanguage.init(rawValue:))) } } label: { Label("Proposer de nouveau", systemImage: "arrow.clockwise") }278 .disabled(a.isWorking)279 }280 }281 }282 #if os(macOS)283 .frame(minWidth: 520, idealWidth: 580, minHeight: 380, idealHeight: 460)284 #endif285 .presentationDetents([.medium, .large])286 }287}288