Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/Assistant/AskModel.swift3// Description: View model of « Demander à mes notes »: one streamed, grounded answer per question (meta → text deltas →4// done), its scope (everything / this page / this project / the selection), citations that carry the block5// to open, the server's evidence verdict (ok / none / insufficient — never rewritten), the expensive-request6// confirmation, stop, and the stored conversations (list, open, continue, rename, delete with undo).7// Nothing is ever sent without `send()`.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation12import Observation13import SPNotesAPI14import SPNotesSync1516/// What the host knows about where the user is (all optional): it decides which scopes can be offered.17public struct AskContext: Sendable, Equatable {18 public var pageId: String?19 public var pageTitle: String?20 /// The root page of the project; when nil with a `pageId`, the server takes the root ancestor of the page.21 public var projectId: String?22 public var projectTitle: String?23 /// The text selected in the editor (scope « sélection »).24 public var selection: String?25 public var selectionBlockId: String?2627 public init(pageId: String? = nil, pageTitle: String? = nil, projectId: String? = nil, projectTitle: String? = nil, selection: String? = nil, selectionBlockId: String? = nil) {28 self.pageId = pageId29 self.pageTitle = pageTitle30 self.projectId = projectId31 self.projectTitle = projectTitle32 self.selection = selection33 self.selectionBlockId = selectionBlockId34 }35}3637/// Where the evidence may come from (`AIChatScope`).38public enum AskScope: String, Sendable, CaseIterable, Identifiable {39 case all, page, project, selection40 public var id: String { rawValue }4142 public var title: String {43 switch self {44 case .all: return L("Toutes mes notes")45 case .page: return L("Cette page")46 case .project: return L("Ce projet")47 case .selection: return L("La sélection")48 }49 }5051 public var symbol: String {52 switch self {53 case .all: return "tray.full"54 case .page: return "doc.text"55 case .project: return "folder"56 case .selection: return "text.cursor"57 }58 }59}6061/// A source of an answer, as shown in a chip.62public struct AskCitation: Sendable, Equatable, Identifiable {63 /// The marker `[n]` of the answer; nil for a stored message (the history does not keep the numbers).64 public var n: Int?65 public var pageId: String?66 public var blockId: String?67 public var title: String68 public var heading: String?69 public var quote: String?70 public var position: Int71 public var id: Int { position }7273 /// « Titre › Section ».74 public var label: String {75 if let heading, !heading.isEmpty { return title + " › " + heading }76 return title77 }78}7980/// The server's verdict on the evidence of an answer (`evidence` of `meta` / `done`).81public enum AskEvidence: Sendable, Equatable {82 /// Supported by cited passages.83 case ok84 /// No supporting note: **no model was called**, nothing was spent.85 case none86 /// A model answered without citing any retrieved passage: the answer is withheld by the server.87 case insufficient88 /// A value this build does not know (shown as is).89 case other(String)9091 public init?(_ raw: String?) {92 guard let raw, !raw.isEmpty else { return nil }93 switch raw {94 case "ok": self = .ok95 case "none": self = .none96 case "insufficient": self = .insufficient97 default: self = .other(raw)98 }99 }100}101102/// One question and its answer.103public struct AskTurn: Sendable, Equatable, Identifiable {104 public enum State: Sendable, Equatable {105 case streaming106 case done107 /// Stopped by the user: the partial text is kept and marked.108 case stopped109 /// Failed in the stream (`error` event) or before it.110 case failed(FeatureFailure, retryable: Bool)111 }112113 public var id: String114 public var question: String115 public var scope: AskScope116 /// Markdown; grows with the deltas, replaced by the server's final text (citations checked) at `done`.117 public var answer: String118 public var state: State119 /// The model that answers (nil when none was called).120 public var model: String?121 public var provider: String?122 /// The sources actually cited (`done`), else the retrieved ones while streaming (`meta`).123 public var citations: [AskCitation]124 public var evidence: AskEvidence?125 public var costUsd: Double?126 /// Markers the model wrote that matched no source: the server removed them.127 public var removedCitations: Int128 /// The answer comes from the server's store (same `clientId` sent again), no new model call.129 public var replayed: Bool130 /// False for a turn rebuilt from the history.131 public var isLive: Bool132133 /// Whether a model produced the text shown (drives the AI badge).134 public var isModelOutput: Bool { evidence != AskEvidence.none && (model != nil || !answer.isEmpty) }135}136137/// A pending "this request is expensive" confirmation: nothing was sent to a provider yet.138public struct AskConfirmation: Sendable, Equatable {139 public var question: String140 public var reason: String?141 public var estimatedCostUsd: Double?142 public var model: String?143}144145@Observable @MainActor146public final class AskModel {147 // MARK: state148 public var draft = ""149 public private(set) var scope: AskScope150 public private(set) var turns: [AskTurn] = []151 public private(set) var isStreaming = false152 /// Failure of a send before any stream (offline, not configured…): the draft is kept.153 public var actionFailure: FeatureFailure?154 public private(set) var confirmation: AskConfirmation?155 /// nil = Auto.156 public private(set) var selectedModel: AIModelInfo?157 public private(set) var conversationId: String?158159 public private(set) var conversations: [AIConversation] = []160 /// Phase of the history list (the composer works without it).161 public private(set) var phase: LoadPhase = .idle162 public private(set) var historyUnsupported = false163 /// The conversation just deleted (offer « Annuler »).164 public private(set) var lastDeleted: AIConversation?165166 public let context: AskContext167 public let repositories: NotesRepositories168 private let repository: AssistantRepository169 private weak var router: (any FeatureRouter)?170 private var streamTask: Task<Void, Never>?171172 public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, context: AskContext = AskContext(), scope: AskScope? = nil,173 now: @escaping @Sendable () -> Date = { Date() }) {174 self.repositories = repositories175 repository = repositories.assistant176 self.router = router177 self.context = context178 let wanted = scope ?? .all179 self.scope = Self.isAvailable(wanted, in: context) ? wanted : .all180 }181182 // MARK: scope183184 public nonisolated static func isAvailable(_ scope: AskScope, in context: AskContext) -> Bool {185 switch scope {186 case .all: return true187 case .page: return context.pageId != nil188 case .project: return context.projectId != nil || context.pageId != nil189 case .selection: return !(context.selection ?? "").trimmingCharacters(in: .whitespacesAndNewlines).isEmpty190 }191 }192193 public var availableScopes: [AskScope] { AskScope.allCases.filter { Self.isAvailable($0, in: context) } }194195 public func setScope(_ scope: AskScope) {196 guard Self.isAvailable(scope, in: context) else { return }197 self.scope = scope198 }199200 /// « Cette page · Offre de la banque ».201 public func scopeDetail(_ scope: AskScope) -> String? {202 switch scope {203 case .all: return nil204 case .page: return context.pageTitle205 case .project: return context.projectTitle206 case .selection:207 guard let selection = context.selection else { return nil }208 return LF("%lld caractères", selection.count)209 }210 }211212 public func selectModel(_ model: AIModelInfo?) {213 if let model, !model.isSelectable { return }214 selectedModel = model215 }216217 public var modelTitle: String { selectedModel.map(ModelPickerModel.name) ?? L("Auto") }218 public var canSend: Bool { !isStreaming && !draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }219220 // MARK: asking221222 /// Sends the draft (the only way a question leaves the device). Returns when the answer is complete, stopped or failed.223 public func send() async {224 let question = draft.trimmingCharacters(in: .whitespacesAndNewlines)225 guard !question.isEmpty, !isStreaming else { return }226 await run(question, confirmExpensive: nil)227 }228229 /// Accepts the announced expensive request and sends it.230 public func confirmExpensive() async {231 guard let pending = confirmation, !isStreaming else { return }232 confirmation = nil233 await run(pending.question, confirmExpensive: true)234 }235236 public func cancelConfirmation() { confirmation = nil }237238 /// Asks the same question again after a retryable failure.239 public func retry(turnId: String) async {240 guard !isStreaming, let index = turns.firstIndex(where: { $0.id == turnId }), case .failed = turns[index].state else { return }241 let question = turns[index].question242 turns.remove(at: index)243 await run(question, confirmExpensive: nil)244 }245246 /// Stops the current request: before the answer starts nothing is kept (the draft stays); once it streams, what was247 /// received stays, marked as interrupted.248 public func stop() {249 streamTask?.cancel()250 }251252 private func run(_ question: String, confirmExpensive: Bool?) async {253 isStreaming = true254 actionFailure = nil255 let task = Task { await self.ask(question, confirmExpensive: confirmExpensive) }256 streamTask = task257 await task.value258 streamTask = nil259 isStreaming = false260 }261262 private func ask(_ question: String, confirmExpensive: Bool?) async {263 let scope = scope264 let clientId = NotesAPI.newID()265 let stream: AsyncThrowingStream<AIEvent, Error>266 do {267 stream = try await repository.ask(question, scope: scope.rawValue, pageId: context.pageId, projectId: scope == .project ? context.projectId : nil,268 selection: scope == .selection ? context.selection : nil, selectionBlockId: scope == .selection ? context.selectionBlockId : nil,269 conversationId: conversationId, model: selectedModel?.id, confirmExpensive: confirmExpensive, clientId: clientId)270 } catch {271 if Task.isCancelled { return } // stopped before the answer started: the draft is untouched272 if case .server(let api) = RepositoryError.from(error), api.code == APIError.Code.confirmExpensive {273 confirmation = Self.confirmation(question: question, reason: api.message, plan: api.plan)274 } else {275 actionFailure = FeatureFailure(error) // the draft is untouched276 }277 return278 }279 if draft.trimmingCharacters(in: .whitespacesAndNewlines) == question { draft = "" }280 turns.append(AskTurn(id: clientId, question: question, scope: scope, answer: "", state: .streaming, model: nil, provider: nil, citations: [], evidence: nil,281 costUsd: nil, removedCitations: 0, replayed: false, isLive: true))282 do {283 for try await event in stream {284 if Task.isCancelled { break }285 apply(event, to: clientId, question: question)286 }287 finish(clientId, cancelled: Task.isCancelled, error: nil)288 } catch {289 finish(clientId, cancelled: Task.isCancelled || error is CancellationError, error: error)290 }291 }292293 private func apply(_ event: AIEvent, to id: String, question: String) {294 guard let index = turns.firstIndex(where: { $0.id == id }) else { return }295 switch event {296 case .meta(let meta):297 turns[index].model = meta.model298 turns[index].provider = meta.provider299 if let conversation = meta.conversationId { conversationId = conversation }300 turns[index].citations = Self.citations(repository.citations(of: event))301 turns[index].evidence = AskEvidence(meta.evidence)302 turns[index].replayed = meta.replayed ?? false303 case .text(let delta):304 turns[index].answer += delta305 case .done(let done):306 if let content = done.content { turns[index].answer = content }307 turns[index].citations = Self.citations(repository.citations(of: event))308 turns[index].evidence = AskEvidence(done.evidence) ?? turns[index].evidence309 turns[index].costUsd = done.costUsd310 turns[index].removedCitations = done.invalidCitations?.count ?? 0311 turns[index].replayed = done.replayed ?? turns[index].replayed312 turns[index].state = .done313 case .error(let error):314 turns[index].state = .failed(Self.failure(error), retryable: error.retryable)315 case .needsConfirmation(let pending):316 // Nothing was sent to a provider: the turn is withdrawn and the question comes back with the request to confirm.317 turns.remove(at: index)318 confirmation = Self.confirmation(question: question, reason: pending.reason, plan: pending.plan)319 if draft.isEmpty { draft = question }320 case .other:321 break322 }323 }324325 private func finish(_ id: String, cancelled: Bool, error: Error?) {326 guard let index = turns.firstIndex(where: { $0.id == id }), turns[index].state == .streaming else { return }327 if cancelled {328 turns[index].state = .stopped329 } else if let error {330 turns[index].state = .failed(FeatureFailure(error), retryable: true)331 } else {332 // The server closed without `done`: what arrived is shown as interrupted, never as a complete answer.333 turns[index].state = turns[index].answer.isEmpty ? .failed(FeatureFailure(kind: .server, message: L("La réponse s'est interrompue avant la fin.")), retryable: true) : .stopped334 }335 }336337 nonisolated static func citations(_ sources: [AssistantCitation]) -> [AskCitation] {338 sources.enumerated().map { index, source in339 AskCitation(n: source.n, pageId: source.pageId, blockId: source.blockId, title: source.title ?? L("Sans titre"), heading: source.heading, quote: source.quote, position: index)340 }341 }342343 nonisolated static func confirmation(question: String, reason: String?, plan: RawJSON?) -> AskConfirmation {344 let decoded = try? plan?.decode(AIPlan.self)345 return AskConfirmation(question: question, reason: reason ?? decoded?.reason, estimatedCostUsd: decoded?.estCostUsd, model: decoded?.model)346 }347348 /// The stream's error codes in the user's words (the server's message otherwise).349 nonisolated static func failure(_ error: AIStreamError) -> FeatureFailure {350 let message: String351 switch error.code {352 case "not_configured": message = L("L'assistant n'est pas configuré sur le serveur (aucune clé de fournisseur).")353 case "no_model": message = L("Aucun modèle disponible pour répondre.")354 case "page_required": message = L("Cette portée a besoin d'une page ouverte.")355 case "selection_required": message = L("Cette portée a besoin d'un texte sélectionné.")356 case "bad_scope": message = L("Cette portée n'est pas acceptée par le serveur.")357 case "refused": message = L("Le modèle a refusé de répondre.")358 case "provider_error": message = L("Le fournisseur du modèle a échoué. Réessayez.")359 default: message = error.message360 }361 return FeatureFailure(kind: .server, message: message, code: error.code)362 }363364 public func open(_ citation: AskCitation) {365 guard let pageId = citation.pageId else { return }366 router?.openPage(id: pageId, blockId: citation.blockId)367 }368369 // MARK: conversations370371 /// Starts an empty conversation (the stored ones stay in the history).372 public func newConversation() {373 guard !isStreaming else { return }374 conversationId = nil375 turns = []376 confirmation = nil377 actionFailure = nil378 }379380 /// The stored conversations, most recent first. Offline or unsupported never blocks asking.381 public func load() async {382 phase = .loading383 do {384 let api = repositories.context.api385 let list = try await repositories.context.online { try await api.aiConversations() }386 conversations = list.filter { $0.deletedAt == nil }.sorted { ($0.updatedAt ?? .distantPast) > ($1.updatedAt ?? .distantPast) }387 historyUnsupported = false388 phase = .loaded389 } catch {390 let failure = FeatureFailure(error)391 historyUnsupported = failure.kind == .unsupported392 phase = failure.kind == .unsupported ? .loaded : .failed(failure)393 }394 }395396 /// Opens a stored conversation: its messages become the turns, and the next question continues it.397 public func open(conversation: AIConversation) async {398 guard !isStreaming else { return }399 actionFailure = nil400 do {401 let api = repositories.context.api402 let detail = try await repositories.context.online { try await api.aiConversation(id: conversation.id) }403 turns = Self.turns(from: detail.messages)404 conversationId = detail.conversation.id405 confirmation = nil406 } catch {407 actionFailure = FeatureFailure(error)408 }409 }410411 private struct StoredMeta: Decodable { var evidence: String? }412413 /// user / assistant messages paired into turns (an assistant message without question keeps an empty one).414 nonisolated static func turns(from messages: [AIMessage]) -> [AskTurn] {415 var out: [AskTurn] = []416 var question: AIMessage?417 func turn(_ question: AIMessage?, _ answer: AIMessage?) -> AskTurn {418 let sources = (answer?.sources ?? []).enumerated().map { index, source in419 AskCitation(n: source.n, pageId: source.pageId, blockId: source.blockId, title: source.title ?? L("Sans titre"), heading: nil, quote: source.excerpt, position: index)420 }421 let meta = try? answer?.meta?.decode(StoredMeta.self)422 return AskTurn(id: answer?.id ?? question?.id ?? NotesAPI.newID(), question: question?.content ?? "", scope: .all, answer: answer?.content ?? "",423 state: answer == nil ? .stopped : .done, model: answer?.model, provider: answer?.provider, citations: sources,424 evidence: AskEvidence(meta?.evidence), costUsd: answer?.costUsd, removedCitations: 0, replayed: false, isLive: false)425 }426 for message in messages {427 if message.role == "user" {428 if let pending = question { out.append(turn(pending, nil)) }429 question = message430 } else if message.role == "assistant" {431 out.append(turn(question, message))432 question = nil433 }434 }435 if let pending = question { out.append(turn(pending, nil)) }436 return out437 }438439 public func rename(conversation: AIConversation, title: String) async {440 let title = title.trimmingCharacters(in: .whitespacesAndNewlines)441 guard !title.isEmpty else { return }442 await mutate {443 let api = self.repositories.context.api444 _ = try await self.repositories.context.online { try await api.updateAIConversation(id: conversation.id, AIConversationChanges(title: title)) }445 if let index = self.conversations.firstIndex(where: { $0.id == conversation.id }) { self.conversations[index].title = title }446 }447 }448449 public func delete(conversation: AIConversation) async {450 await mutate {451 let api = self.repositories.context.api452 _ = try await self.repositories.context.online { try await api.deleteAIConversation(id: conversation.id) }453 self.conversations.removeAll { $0.id == conversation.id }454 self.lastDeleted = conversation455 if self.conversationId == conversation.id { self.conversationId = nil; self.turns = [] }456 }457 }458459 public func undoDelete() async {460 guard let conversation = lastDeleted else { return }461 await mutate {462 let api = self.repositories.context.api463 _ = try await self.repositories.context.online { try await api.restoreAIConversation(id: conversation.id) }464 self.lastDeleted = nil465 await self.load()466 }467 }468469 private func mutate(_ work: @MainActor () async throws -> Void) async {470 actionFailure = nil471 do { try await work() } catch { actionFailure = FeatureFailure(error) }472 }473474 // MARK: presentation (pure)475476 public nonisolated static func title(_ conversation: AIConversation) -> String {477 let title = (conversation.title ?? "").trimmingCharacters(in: .whitespacesAndNewlines)478 return title.isEmpty ? L("Conversation sans titre") : title479 }480481 /// `0,0001 $` — the cost the server reports for an answer; nil when it reports none.482 public nonisolated static func cost(_ value: Double?) -> String? {483 guard let value else { return nil }484 if value == 0 { return L("0 $ (aucun appel de modèle)") }485 return LF("%@ $", ModelPickerModel.number(value, decimals: value < 0.01 ? 4 : 2))486 }487488 /// The answer as attributed Markdown (inline styles; `[n]` markers stay as text next to the chips).489 public nonisolated static func rendered(_ markdown: String) -> AttributedString {490 let options = AttributedString.MarkdownParsingOptions(interpretedSyntax: .inlineOnlyPreservingWhitespace, failurePolicy: .returnPartiallyParsedIfPossible)491 return (try? AttributedString(markdown: markdown, options: options)) ?? AttributedString(markdown)492 }493}494