Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/Assistant/AskScreen.swift3// Description: « Demander à mes notes »: the conversation (questions, streamed answers under the AI badge with their4// model, citation chips that open the cited block, the evidence verdict), the composer with scope and model,5// and the stored conversations (a side column on regular, a sheet on compact).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesAPI10import SPNotesDesign11import SPNotesSync12import SwiftUI1314public struct AskScreen: View {15 @State private var model: AskModel16 @State private var showsHistory = false17 @State private var showsModels = false18 @Environment(\.accessibilityReduceMotion) private var reduceMotion1920 public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, context: AskContext = AskContext(), scope: AskScope? = nil) {21 _model = State(initialValue: AskModel(repositories: repositories, router: router, context: context, scope: scope))22 }2324 public init(model: AskModel) { _model = State(initialValue: model) }2526 public var body: some View {27 FeatureScaffold(title: L("Demander à mes notes"), subtitle: L("Des réponses appuyées sur vos notes, avec leurs sources."),28 actions: {29 FeatureIconButton("square.and.pencil", label: L("Nouvelle conversation")) { model.newConversation() }30 FeatureCompactOnly { FeatureIconButton("clock.arrow.circlepath", label: L("Conversations précédentes")) { showsHistory = true } }31 }) { sizeClass in32 HStack(spacing: 0) {33 if !sizeClass.isCompact {34 AskHistoryList(model: model)35 .frame(width: 280)36 .background(NVColor.bgSidebar)37 Divider().overlay(NVColor.line)38 }39 VStack(spacing: 0) {40 AskConversationView(model: model, compact: sizeClass.isCompact)41 AskComposer(model: model, compact: sizeClass.isCompact, showsModels: $showsModels)42 }43 }44 }45 .task { if model.phase == .idle { await model.load() } }46 .sheet(isPresented: $showsHistory) {47 AskHistoryList(model: model, onOpen: { showsHistory = false })48 .featureSheetChrome(title: L("Conversations"), close: { showsHistory = false })49 }50 .sheet(isPresented: $showsModels) {51 ModelPickerView(model: ModelPickerModel(repositories: model.repositories, selectedId: model.selectedModel?.id, onSelect: { choice in52 model.selectModel(choice)53 showsModels = false54 }))55 .featureSheetChrome(title: nil, close: { showsModels = false })56 }57 }58}5960/// Shows its content only in the compact layout.61struct FeatureCompactOnly<Content: View>: View {62 @Environment(\.featureSizeClass) private var sizeClass63 @ViewBuilder var content: () -> Content64 var body: some View { if sizeClass.isCompact { content() } }65}6667extension View {68 /// A sheet's minimum chrome: a close button (and a sensible size on macOS).69 func featureSheetChrome(title: String?, close: @escaping () -> Void) -> some View {70 VStack(spacing: 0) {71 HStack {72 if let title { Text(title).nvFont(.h3).foregroundStyle(NVColor.fg) }73 Spacer()74 FeatureButton(L("Fermer"), action: close)75 }76 .padding(NVSpace.md)77 self78 }79 .background(NVColor.bg)80 #if os(macOS)81 .frame(minWidth: 520, idealWidth: 640, minHeight: 520, idealHeight: 680)82 #endif83 }84}8586/// The turns of the conversation, or the invitation to ask.87public struct AskConversationView: View {88 let model: AskModel89 let compact: Bool9091 public init(model: AskModel, compact: Bool) {92 self.model = model93 self.compact = compact94 }9596 public var body: some View {97 ScrollViewReader { proxy in98 ScrollView {99 VStack(alignment: .leading, spacing: NVSpace.xl) {100 if model.turns.isEmpty {101 NVEmptyState(systemImage: "text.bubble", title: L("Posez une question à vos notes"),102 message: L("La réponse cite les passages qui l'appuient. Sans passage à l'appui, aucun modèle n'est appelé."))103 .frame(maxWidth: .infinity)104 .padding(.top, NVSpace.xxxl)105 }106 ForEach(Array(model.turns.enumerated()), id: \.element.id) { index, turn in107 AskTurnView(model: model, turn: turn, compact: compact)108 .nvBlockReveal(index: index)109 .id(turn.id)110 }111 }112 .frame(maxWidth: NVSpace.readingMeasure + 80, alignment: .leading)113 .padding(.horizontal, compact ? NVSpace.lg : NVSpace.xl)114 .padding(.vertical, NVSpace.lg)115 .frame(maxWidth: .infinity)116 }117 .onChange(of: model.turns.last?.answer.count) { _, _ in118 if let last = model.turns.last { proxy.scrollTo(last.id, anchor: .bottom) }119 }120 }121 }122}123124/// One question and its answer.125public struct AskTurnView: View {126 let model: AskModel127 let turn: AskTurn128 let compact: Bool129130 public init(model: AskModel, turn: AskTurn, compact: Bool) {131 self.model = model132 self.turn = turn133 self.compact = compact134 }135136 public var body: some View {137 VStack(alignment: .leading, spacing: NVSpace.md) {138 question139 answer140 }141 }142143 private var question: some View {144 HStack(alignment: .top, spacing: NVSpace.sm) {145 Spacer(minLength: compact ? NVSpace.xl : NVSpace.huge)146 VStack(alignment: .trailing, spacing: NVSpace.xs) {147 Text(turn.question)148 .nvFont(.body)149 .foregroundStyle(NVColor.fg)150 .textSelection(.enabled)151 .padding(.horizontal, NVSpace.md)152 .padding(.vertical, NVSpace.sm)153 .background(NVColor.accentSoft, in: NVRadius.shape(NVRadius.lg))154 if turn.isLive, turn.scope != .all {155 Label(turn.scope.title, systemImage: turn.scope.symbol).nvFont(.micro).foregroundStyle(NVColor.fgMuted)156 }157 }158 }159 .accessibilityElement(children: .combine)160 .accessibilityLabel(LF("Votre question : %@", turn.question))161 }162163 @ViewBuilder164 private var answer: some View {165 switch turn.evidence {166 case .some(.none):167 verdict(symbol: "magnifyingglass", title: L("Aucune note à l'appui"),168 message: L("Rien dans cette portée ne permet de répondre. Aucun modèle n'a été appelé et rien n'a été dépensé."))169 case .some(.insufficient):170 FeatureAICard(model: turn.model) {171 Label(L("Réponse retenue"), systemImage: "hand.raised").nvFont(.uiStrong).foregroundStyle(NVColor.fg)172 Text(L("Le modèle a répondu sans citer aucun des passages retrouvés. Le serveur n'affiche pas cette réponse : elle n'est pas appuyée sur vos notes."))173 .nvFont(.body).foregroundStyle(NVColor.fg).fixedSize(horizontal: false, vertical: true)174 footer175 }176 default:177 FeatureAICard(model: turn.model) {178 if turn.answer.isEmpty, turn.state == .streaming {179 HStack(spacing: NVSpace.sm) {180 NVProgressDots(tone: .ai)181 Text(turn.citations.isEmpty ? L("Recherche dans vos notes…") : L("Rédaction de la réponse…")).nvFont(.ui).foregroundStyle(NVColor.fgMuted)182 }183 } else if !turn.answer.isEmpty {184 Text(AskModel.rendered(turn.answer))185 .nvFont(.reading)186 .foregroundStyle(NVColor.fg)187 .textSelection(.enabled)188 .fixedSize(horizontal: false, vertical: true)189 }190 stateNote191 sources192 footer193 }194 }195 }196197 private func verdict(symbol: String, title: String, message: String) -> some View {198 VStack(alignment: .leading, spacing: NVSpace.sm) {199 Label(title, systemImage: symbol).nvFont(.uiStrong).foregroundStyle(NVColor.fg)200 Text(message).nvFont(.body).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true)201 }202 .padding(NVSpace.lg)203 .frame(maxWidth: .infinity, alignment: .leading)204 .nvCard()205 }206207 @ViewBuilder208 private var stateNote: some View {209 switch turn.state {210 case .stopped:211 Label(L("Réponse interrompue : le texte ci-dessus est incomplet."), systemImage: "stop.circle").nvFont(.ui).foregroundStyle(NVColor.warningText)212 case .failed(let failure, let retryable):213 VStack(alignment: .leading, spacing: NVSpace.sm) {214 Label(failure.message, systemImage: "exclamationmark.triangle").nvFont(.ui).foregroundStyle(NVColor.dangerText).fixedSize(horizontal: false, vertical: true)215 if retryable, turn.isLive { FeatureButton(L("Réessayer"), systemImage: "arrow.clockwise") { Task { await model.retry(turnId: turn.id) } } }216 }217 default:218 EmptyView()219 }220 }221222 @ViewBuilder223 private var sources: some View {224 if !turn.citations.isEmpty {225 VStack(alignment: .leading, spacing: NVSpace.xs) {226 Text(turn.state == .streaming ? L("Passages retrouvés") : L("Sources citées")).nvFont(.micro).foregroundStyle(NVColor.fgMuted)227 AskFlow(spacing: NVSpace.sm) {228 ForEach(turn.citations) { citation in229 NVCitationChip(index: citation.n, label: citation.label, action: citation.pageId == nil ? nil : { model.open(citation) })230 }231 }232 }233 }234 }235236 @ViewBuilder237 private var footer: some View {238 let notes = [turn.removedCitations > 0 ? LF("%lld renvoi(s) sans source retiré(s) par le serveur", turn.removedCitations) : nil,239 turn.replayed ? L("Réponse déjà enregistrée, rejouée sans nouvel appel") : nil,240 turn.state == .done ? AskModel.cost(turn.costUsd) : nil].compactMap { $0 }241 if !notes.isEmpty {242 Text(notes.joined(separator: " · ")).nvFont(.micro).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true)243 }244 }245}246247/// Wrapping row of chips.248struct AskFlow: Layout {249 var spacing: CGFloat250251 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {252 arrange(width: proposal.width ?? .infinity, subviews: subviews).size253 }254255 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {256 let result = arrange(width: bounds.width, subviews: subviews)257 for (index, origin) in result.origins.enumerated() {258 subviews[index].place(at: CGPoint(x: bounds.minX + origin.x, y: bounds.minY + origin.y), proposal: ProposedViewSize(width: min(bounds.width, result.sizes[index].width), height: nil))259 }260 }261262 private func arrange(width: CGFloat, subviews: Subviews) -> (size: CGSize, origins: [CGPoint], sizes: [CGSize]) {263 var origins: [CGPoint] = [], sizes: [CGSize] = []264 var x: CGFloat = 0, y: CGFloat = 0, rowHeight: CGFloat = 0, widest: CGFloat = 0265 for subview in subviews {266 var size = subview.sizeThatFits(.unspecified)267 if size.width > width { size = subview.sizeThatFits(ProposedViewSize(width: width, height: nil)) }268 if x > 0, x + size.width > width { x = 0; y += rowHeight + spacing; rowHeight = 0 }269 origins.append(CGPoint(x: x, y: y)); sizes.append(size)270 x += size.width + spacing271 rowHeight = max(rowHeight, size.height)272 widest = max(widest, x - spacing)273 }274 return (CGSize(width: width.isFinite ? min(width, max(widest, 0)) : widest, height: y + rowHeight), origins, sizes)275 }276}277278/// The question field with the scope, the model and the send / stop button.279public struct AskComposer: View {280 @Bindable var model: AskModel281 let compact: Bool282 @Binding var showsModels: Bool283284 public init(model: AskModel, compact: Bool, showsModels: Binding<Bool>) {285 self.model = model286 self.compact = compact287 _showsModels = showsModels288 }289290 public var body: some View {291 VStack(alignment: .leading, spacing: NVSpace.sm) {292 if let failure = model.actionFailure { FeatureStatusBanner(failure: failure, freshness: nil) }293 if let confirmation = model.confirmation { confirmationCard(confirmation) }294 ScrollView(.horizontal, showsIndicators: false) {295 HStack(spacing: NVSpace.sm) {296 ForEach(model.availableScopes) { scope in297 NVChip(chipTitle(scope), systemImage: scope.symbol, tone: .accent, isSelected: model.scope == scope) { model.setScope(scope) }298 .accessibilityLabel(LF("Portée : %@", chipTitle(scope)))299 .accessibilityAddTraits(model.scope == scope ? .isSelected : [])300 }301 }302 }303 HStack(alignment: .bottom, spacing: NVSpace.sm) {304 TextField(L("Votre question"), text: $model.draft, axis: .vertical)305 .textFieldStyle(.plain)306 .nvFont(.body)307 .lineLimit(1...6)308 .padding(.horizontal, NVSpace.md)309 .padding(.vertical, NVSpace.sm)310 .frame(minHeight: compact ? 44 : 36)311 .background(NVColor.bgElevated, in: NVRadius.shape(NVRadius.md))312 .overlay(NVRadius.shape(NVRadius.md).strokeBorder(NVColor.lineStrong, lineWidth: 1))313 .onSubmit { Task { await model.send() } }314 .accessibilityLabel(L("Votre question"))315 if model.isStreaming {316 sendButton("stop.fill", label: L("Arrêter la réponse"), enabled: true) { model.stop() }317 } else {318 sendButton("arrow.up", label: L("Envoyer la question"), enabled: model.canSend) { Task { await model.send() } }319 }320 }321 HStack(spacing: NVSpace.sm) {322 Button { showsModels = true } label: {323 HStack(spacing: NVSpace.xs) {324 if let selected = model.selectedModel {325 ModelLogoView(creator: ModelPickerModel.creatorId(selected), logoPath: selected.logo, monogram: selected.monogram, size: 18)326 } else {327 Image(systemName: "wand.and.stars").foregroundStyle(NVColor.accent).accessibilityHidden(true)328 }329 Text(LF("Modèle : %@", model.modelTitle)).nvFont(.ui).foregroundStyle(NVColor.fgMuted)330 Image(systemName: "chevron.up.chevron.down").font(.system(size: 9, weight: .semibold)).foregroundStyle(NVColor.fgMuted).accessibilityHidden(true)331 }332 .frame(minHeight: compact ? 44 : 28)333 .contentShape(Rectangle())334 }335 .buttonStyle(.plain)336 Spacer(minLength: 0)337 Text(L("Chaque envoi peut appeler un modèle payant.")).nvFont(.micro).foregroundStyle(NVColor.fgMuted).lineLimit(2).multilineTextAlignment(.trailing)338 }339 }340 .padding(.horizontal, compact ? NVSpace.lg : NVSpace.xl)341 .padding(.vertical, NVSpace.md)342 .background(NVColor.bgElevated.opacity(0.6))343 .overlay(alignment: .top) { Rectangle().fill(NVColor.line).frame(height: 1) }344 }345346 private func chipTitle(_ scope: AskScope) -> String {347 if let detail = model.scopeDetail(scope), !detail.isEmpty { return scope.title + " · " + detail }348 return scope.title349 }350351 private func sendButton(_ symbol: String, label: String, enabled: Bool, action: @escaping () -> Void) -> some View {352 Button(action: action) {353 Image(systemName: symbol)354 .font(.system(size: 15, weight: .semibold))355 .foregroundStyle(enabled ? NVColor.accentFg : NVColor.fgMuted)356 .frame(width: compact ? 44 : 36, height: compact ? 44 : 36)357 .background(enabled ? NVColor.accent : NVColor.bgHover, in: Circle())358 }359 .buttonStyle(.plain)360 .disabled(!enabled)361 .accessibilityLabel(label)362 }363364 private func confirmationCard(_ confirmation: AskConfirmation) -> some View {365 VStack(alignment: .leading, spacing: NVSpace.sm) {366 Label(L("Demande coûteuse : rien n'a encore été envoyé à un modèle."), systemImage: "exclamationmark.circle").nvFont(.uiStrong).foregroundStyle(NVColor.fg)367 if let reason = confirmation.reason, !reason.isEmpty { Text(reason).nvFont(.ui).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true) }368 if let cost = confirmation.estimatedCostUsd {369 Text(LF("Coût estimé : %@ $", ModelPickerModel.number(cost))).nvFont(.ui).foregroundStyle(NVColor.fgMuted)370 }371 HStack(spacing: NVSpace.sm) {372 FeatureButton(L("Envoyer quand même"), kind: .primary) { Task { await model.confirmExpensive() } }373 FeatureButton(L("Annuler")) { model.cancelConfirmation() }374 }375 }376 .padding(NVSpace.md)377 .frame(maxWidth: .infinity, alignment: .leading)378 .background(NVColor.warning.opacity(0.12), in: NVRadius.shape(NVRadius.md))379 .overlay(NVRadius.shape(NVRadius.md).strokeBorder(NVColor.warning.opacity(0.5), lineWidth: 1))380 }381}382383/// The stored conversations.384public struct AskHistoryList: View {385 let model: AskModel386 var onOpen: (() -> Void)?387 @Environment(\.featureNow) private var fixedNow388 @State private var renaming: AIConversation?389 @State private var newTitle = ""390391 public init(model: AskModel, onOpen: (() -> Void)? = nil) {392 self.model = model393 self.onOpen = onOpen394 }395396 public var body: some View {397 VStack(alignment: .leading, spacing: 0) {398 NVSectionHeader(L("Conversations"))399 .padding(.horizontal, NVSpace.md).padding(.top, NVSpace.md)400 if let deleted = model.lastDeleted {401 HStack(spacing: NVSpace.sm) {402 Text(LF("« %@ » supprimée", AskModel.title(deleted))).nvFont(.ui).foregroundStyle(NVColor.fgMuted).lineLimit(1)403 Spacer(minLength: 0)404 Button(L("Annuler")) { Task { await model.undoDelete() } }.buttonStyle(.plain).nvFont(.uiStrong).foregroundStyle(NVColor.accent)405 }406 .padding(NVSpace.md)407 }408 content409 }410 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)411 }412413 @ViewBuilder414 private var content: some View {415 if model.historyUnsupported {416 note(L("Ce serveur ne conserve pas les conversations."))417 } else if let failure = model.phase.failure, model.conversations.isEmpty {418 note(failure.isOffline ? L("Hors ligne : les conversations enregistrées sont sur le serveur.") : failure.message)419 } else if model.conversations.isEmpty {420 note(model.phase.isLoading || model.phase == .idle ? L("Chargement…") : L("Aucune conversation enregistrée."))421 } else {422 ScrollView {423 VStack(alignment: .leading, spacing: NVSpace.xxs) {424 ForEach(model.conversations) { conversation in row(conversation) }425 }426 .padding(NVSpace.sm)427 }428 }429 }430431 private func note(_ text: String) -> some View {432 Text(text).nvFont(.ui).foregroundStyle(NVColor.fgMuted).padding(NVSpace.md).fixedSize(horizontal: false, vertical: true)433 }434435 @ViewBuilder436 private func row(_ conversation: AIConversation) -> some View {437 let isCurrent = model.conversationId == conversation.id438 if renaming?.id == conversation.id {439 HStack(spacing: NVSpace.sm) {440 TextField(L("Titre de la conversation"), text: $newTitle)441 .textFieldStyle(.plain).nvFont(.ui)442 .onSubmit { commitRename(conversation) }443 FeatureIconButton("checkmark", label: L("Enregistrer le titre"), tone: .accent) { commitRename(conversation) }444 }445 .padding(NVSpace.sm)446 .background(NVColor.bgElevated, in: NVRadius.shape(NVRadius.sm))447 } else {448 Button {449 Task { await model.open(conversation: conversation); onOpen?() }450 } label: {451 VStack(alignment: .leading, spacing: NVSpace.xxs) {452 HStack(spacing: NVSpace.xs) {453 if conversation.pinned == true { Image(systemName: "pin.fill").font(.system(size: 9)).foregroundStyle(NVColor.accent).accessibilityLabel(L("Épinglée")) }454 Text(AskModel.title(conversation)).nvFont(isCurrent ? .uiStrong : .ui).foregroundStyle(isCurrent ? NVColor.accent : NVColor.fg).lineLimit(2)455 }456 if let date = conversation.updatedAt {457 Text(FeatureFormat.relative(date, now: fixedNow ?? Date())).nvFont(.micro).foregroundStyle(NVColor.fgMuted)458 }459 }460 .padding(.horizontal, NVSpace.sm)461 .padding(.vertical, NVSpace.sm)462 .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading)463 .background(isCurrent ? NVColor.accentSoft.opacity(0.6) : Color.clear, in: NVRadius.shape(NVRadius.sm))464 .contentShape(Rectangle())465 }466 .buttonStyle(.plain)467 .contextMenu {468 Button(L("Renommer")) { newTitle = AskModel.title(conversation); renaming = conversation }469 Button(L("Supprimer"), role: .destructive) { Task { await model.delete(conversation: conversation) } }470 }471 .accessibilityAction(named: L("Renommer")) { newTitle = AskModel.title(conversation); renaming = conversation }472 .accessibilityAction(named: L("Supprimer")) { Task { await model.delete(conversation: conversation) } }473 }474 }475476 private func commitRename(_ conversation: AIConversation) {477 let title = newTitle478 renaming = nil479 Task { await model.rename(conversation: conversation, title: title) }480 }481}482