Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Next/NextServices.swift3// Description: The SP Mail Next service layer owned by AppModel — one NextAPI + NextStore per session, capabilities-gated (an older server4// leaves every Next entry hidden), refreshed on launch / foreground / after a sync, wiped on sign-out. Holds the observable mirrors the5// interface reads (labels, saved searches, snoozes, reminders, AI settings, dashboard, inbox insights, triage) and the calls that change them.6import SPMailCore7import SwiftUI89@MainActor @Observable10final class NextServices {11 @ObservationIgnored weak var app: AppModel?12 @ObservationIgnored private(set) var store: NextStore?13 @ObservationIgnored private var observer: Task<Void, Never>?14 @ObservationIgnored private var lastRefresh = Date.distantPast15 @ObservationIgnored private var triageInFlight: Set<String> = []16 /// The scene that asked for a snooze through `AppModel.hooks.snooze` (the hook itself carries no window).17 @ObservationIgnored weak var requestingScene: MailScene?1819 /// What the server announces. `.none` (an older server, or not yet known) hides every Next entry.20 private(set) var capabilities = NextCapabilities.none21 private(set) var labels: [MailLabel] = []22 private(set) var savedSearches: [SavedSearch] = []23 private(set) var ai = AISettings()24 private(set) var favorites: [Contact] = []25 private(set) var snoozes: [Snooze] = []26 private(set) var reminders: [Reminder] = []27 private(set) var dashboard: Dashboard?28 /// Model-free inbox insights per mailbox id.29 private(set) var insights: [String: InboxInsights] = [:]30 /// AI triage per `mailbox/email` — only filled while the triage feature is enabled.31 private(set) var triage: [String: TriageResult] = [:]32 /// Widget layout of the Command Center (synchronised preference `dashboard`).33 var dashboardLayout = DashboardLayout()3435 var api: NextAPI { NextAPI(app?.api ?? APIClient(baseURL: AppConfig.baseURL, userAgent: AppConfig.userAgent)) }36 var isAvailable: Bool { !capabilities.features.isEmpty }37 func has(_ feature: NextFeature) -> Bool { capabilities.has(feature) }38 var isOnline: Bool { app?.isOnline ?? false }3940 // MARK: lifecycle4142 /// Session start: the capabilities (cached copy offline), the sealed store, the cached collections at once, then a refresh.43 func start() async {44 guard let app, let mail = app.store else { return }45 do { capabilities = try await api.capabilitiesOrNone(); try? await mail.setValue("next.capabilities", Array(capabilities.features)) } catch {46 // offline at launch: what this server announced last time47 let cached = (try? await mail.value("next.capabilities", as: [String].self)) ?? []48 capabilities = NextCapabilities(version: "", features: Set(cached))49 }50 guard isAvailable else { return }51 if store == nil { store = try? NextStore(directory: AppConfig.cacheDirectory.appendingPathComponent("next", isDirectory: true), secrets: AppConfig.secrets(), api: api) }52 app.hooks.snooze = { [weak self] ids, account in53 guard let self else { return }54 (self.requestingScene ?? self.app?.main)?.next.snoozeRequest = SnoozeRequest(account: account, emailIds: ids, mode: .snooze)55 }56 dashboardLayout = DashboardLayout(json: app.me?.user.prefs?["dashboard"] ?? .null)57 await mirror(Set(NextStore.Collection.allCases))58 observer?.cancel()59 if let store {60 observer = Task { [weak self] in61 for await changed in await store.changes() { await self?.mirror(changed) }62 }63 }64 Task { await refresh(force: true) }65 }6667 /// Sign-out or revoked session: nothing of the previous user stays in memory or on disk.68 func wipe() async {69 observer?.cancel(); observer = nil70 await store?.wipe()71 store = nil72 capabilities = .none73 labels = []; savedSearches = []; ai = AISettings(); favorites = []; snoozes = []; reminders = []; dashboard = nil; insights = [:]; triage = [:]74 dashboardLayout = DashboardLayout()75 lastRefresh = .distantPast76 app?.hooks.snooze = nil77 }7879 private var collections: Set<NextStore.Collection> {80 var c: Set<NextStore.Collection> = []81 if has(.labels) { c.insert(.labels) }82 if has(.savedSearches) { c.insert(.savedSearches) }83 if has(.contacts) { c.formUnion([.favoriteContacts, .suggestions]) }84 if has(.ai) { c.insert(.aiSettings) }85 if has(.dashboard) { c.insert(.dashboard) }86 // what the composer reads from this same store (ComposeCenter)87 if has(.signatures) { c.insert(.signatures) }88 if has(.snippets) { c.insert(.snippets) }89 if has(.undoSend) { c.insert(.composePrefs) }90 return c91 }9293 private func mirror(_ changed: Set<NextStore.Collection>) async {94 guard let store else { return }95 if changed.contains(.labels) { let v = await store.labels(); if v != labels { labels = v } }96 if changed.contains(.savedSearches) { let v = await store.savedSearches().sorted { ($0.pinned ? 0 : 1, $0.position, $0.name.lowercased()) < ($1.pinned ? 0 : 1, $1.position, $1.name.lowercased()) }; if v != savedSearches { savedSearches = v } }97 if changed.contains(.aiSettings), let v = await store.aiSettings(), v != ai { ai = v }98 if changed.contains(.favoriteContacts) { let v = await store.favoriteContacts(); if v != favorites { favorites = v } }99 if changed.contains(.dashboard), let v = await store.dashboard(), v != dashboard { dashboard = v }100 if !changed.isDisjoint(with: [.signatures, .snippets, .composePrefs]) { await app?.compose.storeChanged() }101 }102103 /// Replays queued changes, re-reads the synchronised collections and the server-side lists. Throttled unless `force`.104 func refresh(force: Bool = false) async {105 guard isAvailable, let store, let app, app.phase == .ready || app.phase == .locked else { return }106 if !force, Date().timeIntervalSince(lastRefresh) < 20 { return }107 lastRefresh = Date()108 let report = try? await store.refresh(collections)109 if report?.unauthorized == true { await app.sessionRevoked(); return }110 await mirror(Set(NextStore.Collection.allCases))111 guard report?.offline != true else { return }112 await reloadSnoozes()113 await reloadReminders()114 }115116 func reloadSnoozes() async {117 guard has(.snooze), let list = try? await api.snoozes(status: .active) else { return }118 let sorted = list.sorted { ($0.until ?? .distantFuture) < ($1.until ?? .distantFuture) }119 if sorted != snoozes { snoozes = sorted }120 }121 func reloadReminders() async {122 guard has(.reminders), let list = try? await api.reminders() else { return }123 let open = list.filter(\.isOpen).sorted { ($0.dueAt ?? .distantFuture) < ($1.dueAt ?? .distantFuture) }124 if open != reminders { reminders = open }125 }126127 // MARK: errors128129 /// A sentence for a refusal of the Next API; nil for a cancellation.130 func describe(_ error: Error) -> String? {131 if error is CancellationError { return nil }132 if let n = error as? NextError {133 switch n {134 case .aiDisabled: return L("L’intelligence est désactivée pour cette fonction.")135 case .consentRequired: return L("Le fournisseur externe exige votre consentement explicite.")136 case .confirmationRequired: return L("Une confirmation est requise.")137 case .notFound: return L("Cet élément n’existe plus sur le serveur.")138 case .rateLimited(let after): return after.map { L("Trop de demandes. Réessayez dans \(Int($0.rounded(.up))) s.") } ?? L("Trop de demandes. Réessayez dans un instant.")139 case .badResponse: return L("Le serveur a renvoyé une réponse inattendue.")140 }141 }142 if let e = error as? APIError {143 switch e.code {144 case "name_taken": return L("Ce nom est déjà utilisé.")145 case "invalid_query": return L("Cette recherche n’est pas valide.")146 case "ai_unreachable", "ai_timeout", "ai_error", "ai_not_configured", "provider_unavailable": return L("Le service d’intelligence est indisponible pour le moment.")147 case "ai_rate_limited": return L("Trop de demandes. Réessayez dans un instant.")148 case "ai_invalid_output": return L("Le modèle n’a pas produit de réponse exploitable. Réessayez.")149 default: break150 }151 }152 return app?.describe(error)153 }154 private func fail(_ error: Error) { if let m = describe(error) { app?.toast = Toast(message: m, kind: .error) } }155 private func flushSoon() { Task { [store] in _ = await store?.flush(force: true); await self.mirror([.labels, .savedSearches, .favoriteContacts, .aiSettings]) } }156157 // MARK: labels158159 func label(id: String) -> MailLabel? { labels.first { $0.id == id } }160 func labels(for keywords: [String]) -> [MailLabel] { MailLabel.labels(for: keywords, in: labels) }161162 /// Creates a label. Online the server answers at once (the keyword is needed to apply it); offline the creation is queued and the163 /// label can be applied once it exists on the server.164 @discardableResult165 func createLabel(name: String, color: String) async -> MailLabel? {166 let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)167 guard !trimmed.isEmpty, let store else { return nil }168 do {169 let created = try await api.createLabel(name: trimmed, color: color)170 _ = try? await store.refresh([.labels])171 await mirror([.labels])172 return created173 } catch let e where NextError.isOffline(e) {174 let queued = await store.createLabel(name: trimmed, color: color)175 await mirror([.labels])176 return queued177 } catch { fail(error); return nil }178 }179 func updateLabel(_ label: MailLabel, name: String? = nil, color: String? = nil) async {180 guard let store else { return }181 await store.updateLabel(id: label.id, name: name, color: color)182 await mirror([.labels])183 let report = await store.flush(force: true)184 if let dropped = report.dropped.first { app?.toast = Toast(message: dropped.code == "name_taken" ? L("Ce nom est déjà utilisé.") : L("Le serveur a refusé cette modification."), kind: .error) }185 await mirror([.labels])186 }187 /// Deleting a label does not touch messages: the orphan keyword is ignored everywhere.188 func deleteLabel(_ label: MailLabel) async {189 guard let store else { return }190 await store.deleteLabel(id: label.id)191 await mirror([.labels])192 _ = await store.flush(force: true)193 }194195 // MARK: saved searches196197 func savedSearch(id: String) -> SavedSearch? { savedSearches.first { $0.id == id } }198 @discardableResult199 func saveSearch(name: String, query: String, scope: MailboxScope) async -> SavedSearch? {200 guard let store else { return nil }201 do {202 let created = try await api.createSavedSearch(SavedSearchContent(name: name, query: query, scope: scope))203 _ = try? await store.refresh([.savedSearches])204 await mirror([.savedSearches])205 return created206 } catch let e where NextError.isOffline(e) {207 let queued = await store.createSavedSearch(SavedSearchContent(name: name, query: query, scope: scope))208 await mirror([.savedSearches])209 return queued210 } catch { fail(error); return nil }211 }212 func updateSavedSearch(_ search: SavedSearch, _ content: SavedSearchContent) async {213 guard let store else { return }214 await store.updateSavedSearch(id: search.id, content)215 await mirror([.savedSearches])216 flushSoon()217 }218 func deleteSavedSearch(_ search: SavedSearch) async {219 guard let store else { return }220 await store.deleteSavedSearch(id: search.id)221 await mirror([.savedSearches])222 flushSoon()223 }224225 // MARK: snooze and reminders (server-side: never queued silently)226227 /// Snoozes messages of one mailbox until `until`. Returns false (with a toast) when the server refused or could not be reached.228 @discardableResult229 func snooze(account: String, emailIds: [String], until: Date) async -> Bool {230 guard let app, !emailIds.isEmpty else { return false }231 do {232 _ = try await api.snooze(mailboxId: account, emailIds: emailIds, until: until)233 // the server moved the messages to « Snoozed »: the cache follows through a normal sync234 try? await app.engines[account]?.syncNow()235 await reloadSnoozes()236 await app.reloadMailboxes()237 app.toast = Toast(message: L("En veille jusqu’au \(until.formatted(date: .abbreviated, time: .shortened))"), kind: .success)238 return true239 } catch { fail(error); return false }240 }241 @discardableResult242 func wake(_ snooze: Snooze) async -> Bool {243 do {244 _ = try await api.cancelSnooze(id: snooze.id)245 snoozes.removeAll { $0.id == snooze.id }246 try? await app?.engines[snooze.mailboxId]?.syncNow()247 await app?.reloadMailboxes()248 return true249 } catch { fail(error); await reloadSnoozes(); return false }250 }251 @discardableResult252 func reschedule(_ snooze: Snooze, until: Date) async -> Bool {253 do { _ = try await api.updateSnooze(id: snooze.id, until: until); await reloadSnoozes(); return true } catch { fail(error); return false }254 }255 @discardableResult256 func remind(account: String, emailId: String, dueAt: Date, onlyIfNoReply: Bool, note: String?) async -> Reminder? {257 do {258 let r = try await api.createReminder(mailboxId: account, emailId: emailId, dueAt: dueAt, onlyIfNoReply: onlyIfNoReply, note: note)259 await reloadReminders()260 app?.toast = Toast(message: L("Rappel le \(dueAt.formatted(date: .abbreviated, time: .shortened))"), kind: .success)261 return r262 } catch { fail(error); return nil }263 }264 func completeReminder(_ reminder: Reminder) async {265 do { _ = try await api.updateReminder(id: reminder.id, done: true); reminders.removeAll { $0.id == reminder.id }; try? await app?.engines[reminder.mailboxId]?.syncNow() } catch { fail(error) }266 }267 func cancelReminder(_ reminder: Reminder) async {268 do { _ = try await api.cancelReminder(id: reminder.id); reminders.removeAll { $0.id == reminder.id } } catch { fail(error) }269 }270 func rescheduleReminder(_ reminder: Reminder, dueAt: Date) async {271 do { _ = try await api.updateReminder(id: reminder.id, dueAt: dueAt); await reloadReminders() } catch { fail(error) }272 }273274 // MARK: contacts275276 func setFavorite(_ contact: Contact, _ on: Bool) async {277 guard let store else { return }278 await store.setFavorite(contact, on)279 await mirror([.favoriteContacts])280 flushSoon()281 }282283 // MARK: dashboard284285 func loadDashboard(fresh: Bool = false) async -> String? {286 guard has(.dashboard) else { return nil }287 do { dashboard = try await api.dashboard(fresh: fresh); return nil } catch {288 if NextError.isOffline(error) { return dashboard == nil ? L("Le centre de commande n’est visible qu’en ligne.") : L("Hors ligne — dernières données connues") }289 return describe(error)290 }291 }292 /// Writes the widget layout under the `dashboard` key only (`PATCH /api/prefs` merges: the other preferences are untouched).293 func saveDashboardLayout() async {294 guard let app else { return }295 do { _ = try await app.api.patchPrefs(["dashboard": dashboardLayout.json]) } catch { if !NextError.isOffline(error) { fail(error) } }296 }297298 // MARK: intelligence299300 func aiEnabled(_ feature: AIFeature) -> Bool { has(.ai) && ai.isEnabled(feature) }301 /// What an AI surface is labelled with: who processed the content.302 func providerLabel(provider: String, model: String) -> String {303 let who = provider == "anthropic" ? "Anthropic" : provider == "local" ? L("MacLustr local") : provider304 return model.isEmpty ? who : "\(who) · \(model)"305 }306 /// Changes the AI settings on the server and re-reads them. Throws `NextError.consentRequired` when the external provider needs the307 /// explicit consent (the caller shows the consent dialog and calls again with `consentExternal`).308 func setAI(_ update: AISettingsUpdate) async throws {309 let fresh = try await api.setAISettings(update)310 ai = fresh311 _ = try? await store?.refresh([.aiSettings])312 if !ai.isEnabled(.triage) { triage = [:] }313 }314 func reloadAI() async {315 guard has(.ai), let fresh = try? await api.aiSettings() else { return }316 ai = fresh317 }318319 /// Inbox insights computed without a model (newsletters, needs reply, unanswered sent).320 func loadInsights(account: String) async {321 guard isAvailable, let fresh = try? await api.inboxInsights(mailboxId: account) else { return }322 if insights[account] != fresh { insights[account] = fresh }323 }324325 static func triageKey(_ account: String, _ emailId: String) -> String { "\(account)/\(emailId)" }326 func triage(account: String, emailId: String) -> TriageResult? { triage[Self.triageKey(account, emailId)] }327 /// Asks the model to classify the given inbox messages (≤ 25 per call), once each. Quiet on failure: the badges are optional.328 func loadTriage(account: String, emailIds: [String]) async {329 guard aiEnabled(.triage) else { return }330 let wanted = emailIds.filter { triage[Self.triageKey(account, $0)] == nil && !triageInFlight.contains(Self.triageKey(account, $0)) }.prefix(25)331 guard !wanted.isEmpty else { return }332 let keys = wanted.map { Self.triageKey(account, $0) }333 triageInFlight.formUnion(keys)334 defer { triageInFlight.subtract(keys) }335 guard let results = try? await api.triage(mailboxId: account, emailIds: Array(wanted)) else { return }336 for r in results { triage[Self.triageKey(account, r.emailId)] = r }337 }338}339340// MARK: - dashboard layout (synchronised preference `dashboard`)341342enum DashboardWidget: String, CaseIterable, Identifiable, Sendable {343 case inbox, attention, scheduled, pendingReplies, recentAttachments, contacts, storage, deliveryIssues, sync344 var id: String { rawValue }345 var title: String {346 switch self {347 case .inbox: L("Boîtes de réception"); case .attention: L("À traiter"); case .scheduled: L("Envois programmés"); case .pendingReplies: L("Réponses en attente")348 case .recentAttachments: L("Pièces jointes récentes"); case .contacts: L("Contacts importants"); case .storage: L("Stockage"); case .deliveryIssues: L("Problèmes de livraison")349 case .sync: L("État de la synchronisation")350 }351 }352 var icon: String {353 switch self {354 case .inbox: "tray"; case .attention: "exclamationmark.circle"; case .scheduled: "clock.badge"; case .pendingReplies: "arrowshape.turn.up.left"355 case .recentAttachments: "paperclip"; case .contacts: "person.2"; case .storage: "internaldrive"; case .deliveryIssues: "exclamationmark.triangle"; case .sync: "arrow.triangle.2.circlepath"356 }357 }358}359360/// Order and visibility of the Command Center widgets. Stored as `{ "order": [...], "hidden": [...] }`; keys this build does not know361/// (another client's widgets, future fields) are carried through unchanged.362struct DashboardLayout: Equatable, Sendable {363 var order: [DashboardWidget] = DashboardWidget.allCases364 var hidden: Set<DashboardWidget> = []365 private var unknownOrder: [String] = []366 private var unknownHidden: [String] = []367 private var extra: [String: JSONValue] = [:]368369 init() {}370 init(json: JSONValue) {371 guard let object = json.objectValue else { return }372 let raw = json["order"].stringArray373 var seen = Set<DashboardWidget>()374 let known = raw.compactMap(DashboardWidget.init(rawValue:)).filter { seen.insert($0).inserted }375 // a widget added by a newer build goes at the end376 order = known + DashboardWidget.allCases.filter { !seen.contains($0) }377 unknownOrder = raw.filter { DashboardWidget(rawValue: $0) == nil }378 let hid = json["hidden"].stringArray379 hidden = Set(hid.compactMap(DashboardWidget.init(rawValue:)))380 unknownHidden = hid.filter { DashboardWidget(rawValue: $0) == nil }381 extra = object.filter { $0.key != "order" && $0.key != "hidden" }382 }383 var json: JSONValue {384 var o = extra385 o["order"] = JSONValue(order.map(\.rawValue) + unknownOrder)386 o["hidden"] = JSONValue(hidden.map(\.rawValue).sorted() + unknownHidden)387 return .object(o)388 }389 var visible: [DashboardWidget] { order.filter { !hidden.contains($0) } }390 /// Default order and visibility of the widgets this build knows; what it does not know is left alone.391 mutating func resetKnown() { order = DashboardWidget.allCases; hidden = [] }392}393394// MARK: - requests presented by a window395396/// A snooze or a reminder asked for some messages of one mailbox; presented as a popover (macOS, iPad) or a sheet with detents (iPhone).397struct SnoozeRequest: Identifiable, Equatable {398 enum Mode: Equatable { case snooze, remind, rescheduleSnooze(Snooze), rescheduleReminder(Reminder) }399 let id = UUID()400 var account: String401 var emailIds: [String]402 var mode: Mode403}404405/// The label editor: a new label (optionally applied to messages once created) or an existing one.406struct LabelEditRequest: Identifiable {407 let id = UUID()408 var label: MailLabel?409 /// Applied after creation.410 var apply: (@MainActor (MailLabel) -> Void)?411}412