Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/Work/Inbox/InboxModel.swift3// Description: View model of the inbox: the captures waiting for triage (last list offline), capture, triage with undo,4// and the Smart Inbox — AI suggestions read from the server's cache by default, asked to a model only on an5// explicit action, presented as a checklist where nothing is ticked for the user and nothing is applied6// before they confirm.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import Observation12import SPNotesAPI13import SPNotesSync1415@Observable @MainActor16public final class InboxModel {17 /// Where the AI suggestions of the selected capture stand.18 public enum SuggestionState: Equatable, Sendable {19 /// Not asked yet for this capture.20 case unknown21 /// Reading the server's cache (free).22 case checking23 /// Nothing was ever generated: offer the explicit, paid request.24 case notGenerated25 /// A model is working (explicit request).26 case generating27 case ready(InboxSuggestions)28 /// The server has no Smart Inbox.29 case unavailable30 case failed(FeatureFailure)31 }3233 /// What the user ticked (and possibly edited) in the checklist. Everything starts unticked.34 public struct Choice: Equatable, Sendable {35 public var useTitle = false36 public var title = ""37 public var tags: Set<String> = []38 public var useDestination = false39 public var relations: Set<String> = []40 public var useSummary = false41 public var summary = ""4243 public init() {}4445 public var isEmpty: Bool { !useTitle && tags.isEmpty && !useDestination && relations.isEmpty && !useSummary }46 public var count: Int { (useTitle ? 1 : 0) + tags.count + (useDestination ? 1 : 0) + relations.count + (useSummary ? 1 : 0) }47 }4849 public struct Undoable: Equatable, Sendable {50 public var actionId: String51 public var message: String52 }5354 public enum CaptureMode: String, Sendable, CaseIterable, Identifiable {55 case note, tasks, link56 public var id: String { rawValue }57 }5859 // MARK: state6061 public private(set) var items: [InboxItem] = []62 public private(set) var phase: LoadPhase = .idle63 public private(set) var freshness: Freshness?64 public var actionFailure: FeatureFailure?65 public var selectedId: String?66 public private(set) var suggestionState: SuggestionState = .unknown67 public var choice = Choice()68 public private(set) var lastAction: Undoable?69 public private(set) var databases: [DatabaseInfo] = []70 public private(set) var isWorking = false71 public var captureText = ""72 public var captureMode: CaptureMode = .note7374 private let repo: InboxRepository75 private let repositories: NotesRepositories76 private weak var router: (any FeatureRouter)?77 private let now: @Sendable () -> Date7879 public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, now: @escaping @Sendable () -> Date = { Date() }) {80 self.repositories = repositories81 repo = repositories.inbox82 self.router = router83 self.now = now84 }8586 public var selectedItem: InboxItem? { items.first { $0.id == selectedId } }87 /// True when the list on screen is the device's copy because the server cannot be reached: actions are disabled.88 public var isOffline: Bool { phase.failure?.isOffline == true || freshness?.fromCache == true }89 public var canCapture: Bool { !isOffline && !isWorking && !captureText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }9091 // MARK: loading9293 public func load() async {94 if items.isEmpty { phase = .loading }95 do {96 let cached = try await repo.items()97 items = cached.value98 freshness = Freshness(cached)99 phase = cached.source == .cache ? .failed(FeatureFailure(RepositoryError.offline)) : .loaded100 if let selectedId, !items.contains(where: { $0.id == selectedId }) { self.selectedId = nil; suggestionState = .unknown }101 } catch {102 phase = .failed(FeatureFailure(error))103 }104 databases = (try? await repositories.databases.list()) ?? []105 }106107 // MARK: capture and triage (online)108109 @discardableResult110 public func capture() async -> Bool {111 let text = captureText.trimmingCharacters(in: .whitespacesAndNewlines)112 guard !text.isEmpty else { return false }113 let draft: CaptureDraft114 switch captureMode {115 case .note: draft = CaptureDraft(kind: CaptureKindName.note, text: text)116 case .tasks: draft = CaptureDraft(kind: CaptureKindName.tasks, text: text)117 case .link:118 let parts = text.split(separator: " ", maxSplits: 1).map(String.init)119 draft = CaptureDraft(kind: CaptureKindName.link, text: parts.count > 1 ? parts[1] : nil, url: parts.first)120 }121 let done = await perform { [self] in _ = try await repo.capture(draft) }122 if done { captureText = "" }123 return done124 }125126 @discardableResult127 public func triage(_ id: String, _ action: InboxAction) async -> Bool {128 await perform { [self] in129 let result = try await repo.triage(id: id, action)130 lastAction = Undoable(actionId: result.actionId, message: Self.message(for: action, result: result))131 if selectedId == id { selectedId = nil; suggestionState = .unknown }132 }133 }134135 @discardableResult136 public func undo() async -> Bool {137 guard let action = lastAction else { return false }138 return await perform { [self] in139 _ = try await repo.undo(actionId: action.actionId)140 lastAction = nil141 }142 }143144 public func dismissUndo() { lastAction = nil }145146 public func open(_ item: InboxItem) { router?.openPage(id: item.id, blockId: nil) }147148 public nonisolated static func message(for action: InboxAction, result: TriageResult) -> String {149 switch action {150 case .keep: return L("Capture classée.")151 case .task:152 let count = result.createdObjects.taskIds?.count ?? 1153 return count > 1 ? LF("%lld tâches créées.", count) : L("Tâche créée.")154 case .database: return L("Ajoutée à la base de données.")155 case .reference: return L("Ajoutée aux références.")156 case .archive: return L("Capture archivée.")157 case .trash: return L("Capture mise à la corbeille.")158 }159 }160161 // MARK: Smart Inbox162163 /// Selects a capture and reads its suggestions from the server's cache (never a model call).164 public func select(_ id: String?) async {165 selectedId = id166 choice = Choice()167 suggestionState = .unknown168 guard let id else { return }169 suggestionState = .checking170 let state = await fetchSuggestions(id: id, cachedOnly: true)171 if selectedId == id { apply(state) }172 }173174 /// The explicit request: one (cheap, paid) model call. Only ever called from the user's button.175 public func askSuggestions() async {176 guard let id = selectedId else { return }177 suggestionState = .generating178 let state = await fetchSuggestions(id: id, cachedOnly: false)179 if selectedId == id { apply(state) }180 }181182 private func apply(_ state: SuggestionState) {183 suggestionState = state184 choice = Choice()185 if case .ready(let suggestions) = state {186 // Editable values are prefilled, but nothing is ticked.187 choice.title = suggestions.suggestions?.title?.value ?? ""188 choice.summary = suggestions.suggestions?.summary ?? ""189 }190 }191192 private func fetchSuggestions(id: String, cachedOnly: Bool) async -> SuggestionState {193 do {194 return .ready(try await repo.suggestions(id: id, cachedOnly: cachedOnly))195 } catch {196 let failure = FeatureFailure(error)197 switch failure.kind {198 case .unsupported: return .unavailable199 case .notFound where cachedOnly: return .notGenerated200 case .server where failure.code == "not_generated": return .notGenerated201 default: return cachedOnly && failure.isOffline ? .failed(failure) : .failed(failure)202 }203 }204 }205206 /// Whether the suggestion set has anything to offer.207 public nonisolated static func hasContent(_ suggestions: InboxSuggestions) -> Bool {208 guard let set = suggestions.suggestions else { return false }209 return set.title != nil || !(set.tags ?? []).isEmpty || set.destination != nil || !(set.relations ?? []).isEmpty || !(set.summary ?? "").isEmpty210 }211212 /// The selection sent to the server: only what is ticked, with the user's edits.213 public func selection() -> InboxSuggestionSelection {214 guard case .ready(let suggestions) = suggestionState, let set = suggestions.suggestions else { return InboxSuggestionSelection() }215 var out = InboxSuggestionSelection()216 let title = choice.title.trimmingCharacters(in: .whitespacesAndNewlines)217 if choice.useTitle, !title.isEmpty { out.title = title }218 let tags = (set.tags ?? []).map(\.name).filter { choice.tags.contains($0) }219 if !tags.isEmpty { out.tags = tags }220 if choice.useDestination, let destination = set.destination {221 out.destination = .init(section: destination.section, parentId: destination.parentId.map { .value($0) })222 }223 let relations = (set.relations ?? []).filter { choice.relations.contains($0.pageId) }224 if !relations.isEmpty { out.relations = relations.map { .init(pageId: $0.pageId, reason: $0.reason) } }225 let summary = choice.summary.trimmingCharacters(in: .whitespacesAndNewlines)226 if choice.useSummary, !summary.isEmpty { out.summary = summary }227 return out228 }229230 /// Applies what the user ticked. Never called without their confirmation.231 @discardableResult232 public func applySuggestions() async -> Bool {233 guard let id = selectedId else { return false }234 let selection = selection()235 guard !selection.isEmpty else {236 actionFailure = FeatureFailure(kind: .other, message: L("Cochez au moins une suggestion à appliquer."))237 return false238 }239 return await perform { [self] in240 let result = try await repo.apply(id: id, selection)241 let count = result.applied?.count ?? choice.count242 lastAction = Undoable(actionId: result.actionId, message: count > 1 ? LF("%lld suggestions appliquées.", count) : L("Suggestion appliquée."))243 choice = Choice()244 if result.filed == true { selectedId = nil; suggestionState = .unknown }245 }246 }247248 @discardableResult249 private func perform(_ work: @escaping () async throws -> Void) async -> Bool {250 isWorking = true251 defer { isWorking = false }252 do {253 try await work()254 actionFailure = nil255 await load()256 return true257 } catch {258 actionFailure = FeatureFailure(error)259 return false260 }261 }262263 // MARK: labels264265 public nonisolated static func kindSymbol(_ kind: String?) -> String {266 switch kind {267 case CaptureKindName.tasks: return "checklist"268 case CaptureKindName.link: return "link"269 case CaptureKindName.photo, CaptureKindName.screenshot: return "photo"270 case CaptureKindName.file, CaptureKindName.document: return "doc"271 case CaptureKindName.audio: return "waveform"272 case CaptureKindName.selection: return "text.quote"273 default: return "note.text"274 }275 }276277 public nonisolated static func kindLabel(_ kind: String?) -> String {278 switch kind {279 case CaptureKindName.tasks: return L("Tâches")280 case CaptureKindName.link: return L("Lien")281 case CaptureKindName.photo: return L("Photo")282 case CaptureKindName.screenshot: return L("Capture d'écran")283 case CaptureKindName.file, CaptureKindName.document: return L("Fichier")284 case CaptureKindName.audio: return L("Audio")285 case CaptureKindName.selection: return L("Sélection")286 default: return L("Note")287 }288 }289290 public nonisolated static func sectionLabel(_ section: String?) -> String {291 switch section {292 case "documents": return L("Documents")293 case "projects": return L("Projets")294 case "research": return L("Recherche")295 case "databases": return L("Bases de données")296 default: return L("Notes")297 }298 }299}300