Repository Public
1// SP Notes iOS2// File: Features/AI/AssistantChatView.swift3// Description: The "Questions" tab of the assistant: a conversation about the owner's notes (answers grounded in the notes, with4// their sources), about the open note (summary, actions) or general. Kept for the life of the sheet only.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SPNotesCore9import SwiftUI10import UIKit1112struct AssistantChatView: View {13 @Bindable var model: AssistantChatModel14 let noteTitle: String15 /// Opens a note, at a block when the source has one.16 var onOpenNote: (String, String?) -> Void1718 @State private var draft = ""19 @FocusState private var composerFocused: Bool2021 private var scope: AssistantChatScope { AssistantChatScope.scope(for: model.mode) }2223 var body: some View {24 VStack(spacing: 0) {25 scopeBar26 Divider().overlay(Color.spBorder)27 ScrollViewReader { proxy in28 ScrollView {29 LazyVStack(alignment: .leading, spacing: 14) {30 if model.messages.isEmpty { introduction }31 ForEach(model.messages) { message in32 AssistantMessageRow(message: message, onOpenNote: onOpenNote, onRetry: { model.retry() }, onConfirm: { model.confirmExpensive() })33 .id(message.id)34 }35 Color.clear.frame(height: 1).id("end")36 }37 .padding(16)38 .frame(maxWidth: 720, alignment: .leading)39 .frame(maxWidth: .infinity)40 }41 .scrollDismissesKeyboard(.interactively)42 .onChange(of: model.messages.last?.text) { _, _ in proxy.scrollTo("end", anchor: .bottom) }43 .onChange(of: model.messages.count) { _, _ in withAnimation { proxy.scrollTo("end", anchor: .bottom) } }44 }45 }46 .safeAreaInset(edge: .bottom, spacing: 0) { composer }47 }4849 private var scopeBar: some View {50 HStack(spacing: 8) {51 Menu {52 Picker("Portée", selection: $model.mode) {53 ForEach(AssistantChatScope.all) { scope in Label(scope.title, systemImage: scope.symbol).tag(scope.mode) }54 }55 } label: {56 HStack(spacing: 6) {57 Image(systemName: scope.symbol)58 Text(scope.title).font(.subheadline.weight(.medium))59 Image(systemName: "chevron.up.chevron.down").font(.caption2)60 }61 .padding(.horizontal, 12)62 .frame(minHeight: 36)63 .background(Color.spSurface2, in: Capsule())64 }65 .accessibilityLabel("Portée des questions : \(scope.title)")66 .accessibilityIdentifier("assistant-chat-scope")67 Spacer(minLength: 0)68 }69 .padding(.horizontal, 16)70 .padding(.vertical, 8)71 }7273 private var introduction: some View {74 VStack(alignment: .leading, spacing: 8) {75 Text(introTitle).font(.headline).foregroundStyle(Color.spText)76 Text(introText).font(.subheadline).foregroundStyle(Color.spTextSecondary)77 if scope.needsPage && !model.pageIsOnServer {78 Label("Cette note n’est pas encore sur le serveur : ce mode sera disponible après la synchronisation.", systemImage: "icloud.slash")79 .font(.footnote)80 .foregroundStyle(Color.spWarning)81 }82 }83 .padding(14)84 .frame(maxWidth: .infinity, alignment: .leading)85 .background(Color.spSurface, in: RoundedRectangle(cornerRadius: 14, style: .continuous))86 .accessibilityIdentifier("assistant-chat-intro")87 }8889 private var introTitle: String {90 switch model.mode {91 case .notes: String(localized: "Interroge tes notes")92 case .summarise: String(localized: "Résumé de « \(AppModel.displayTitle(noteTitle)) »")93 case .actions: String(localized: "Actions de « \(AppModel.displayTitle(noteTitle)) »")94 default: String(localized: "Question générale")95 }96 }9798 private var introText: String {99 switch model.mode {100 case .notes: String(localized: "Les réponses s’appuient sur tes notes synchronisées et citent leurs sources. Touche une source pour ouvrir la note.")101 case .summarise: String(localized: "Le serveur résume la dernière version synchronisée de cette note. Précise ce que tu veux retenir.")102 case .actions: String(localized: "Le serveur relève les actions à faire dans la dernière version synchronisée de cette note.")103 default: String(localized: "Réponse du modèle sans consulter tes notes.")104 }105 }106107 private var composer: some View {108 HStack(alignment: .bottom, spacing: 8) {109 TextField(placeholder, text: $draft, axis: .vertical)110 .lineLimit(1...5)111 .focused($composerFocused)112 .padding(.horizontal, 14)113 .padding(.vertical, 10)114 .background(Color.spSurface, in: RoundedRectangle(cornerRadius: 18, style: .continuous))115 .overlay(RoundedRectangle(cornerRadius: 18, style: .continuous).strokeBorder(Color.spBorder))116 .accessibilityIdentifier("assistant-chat-field")117 if model.isStreaming {118 Button { model.stop() } label: { Image(systemName: "stop.circle.fill").font(.title) }119 .frame(minWidth: 44, minHeight: 44)120 .accessibilityLabel("Arrêter la réponse")121 .accessibilityIdentifier("assistant-chat-stop")122 } else {123 Button { send() } label: { Image(systemName: "arrow.up.circle.fill").font(.title) }124 .frame(minWidth: 44, minHeight: 44)125 .disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)126 .accessibilityLabel("Envoyer la question")127 .accessibilityIdentifier("assistant-chat-send")128 }129 }130 .padding(.horizontal, 12)131 .padding(.vertical, 8)132 .frame(maxWidth: 720)133 .frame(maxWidth: .infinity)134 .background(.bar)135 }136137 private var placeholder: String {138 switch model.mode {139 case .notes: String(localized: "Pose une question sur tes notes")140 case .summarise: String(localized: "Que veux-tu retenir de cette note ?")141 case .actions: String(localized: "Quelles actions chercher ?")142 default: String(localized: "Pose une question")143 }144 }145146 private func send() {147 let text = draft148 draft = ""149 model.send(text)150 }151}152153private struct AssistantMessageRow: View {154 let message: AssistantChatMessage155 /// Opens a note, at a block when the source has one.156 var onOpenNote: (String, String?) -> Void157 var onRetry: () -> Void158 var onConfirm: () -> Void159160 var body: some View {161 switch message.role {162 case .user:163 HStack {164 Spacer(minLength: 40)165 Text(message.text)166 .font(.body)167 .foregroundStyle(Color.spText)168 .textSelection(.enabled)169 .padding(.horizontal, 14)170 .padding(.vertical, 10)171 .background(Color.accentColor.opacity(0.16), in: RoundedRectangle(cornerRadius: 16, style: .continuous))172 }173 .accessibilityElement(children: .combine)174 .accessibilityLabel("Toi : \(message.text)")175 case .assistant:176 VStack(alignment: .leading, spacing: 8) {177 content178 if !message.sources.isEmpty { sources }179 if let line = message.modelLine, message.state != .streaming {180 Text(line).font(.caption2).foregroundStyle(Color.spMuted)181 }182 }183 .frame(maxWidth: .infinity, alignment: .leading)184 }185 }186187 @ViewBuilder private var content: some View {188 switch message.state {189 case .streaming:190 if message.text.isEmpty {191 HStack(spacing: 8) { ProgressView(); Text("Recherche et rédaction…").font(.subheadline).foregroundStyle(Color.spTextSecondary) }192 } else {193 // While the answer arrives it is shown as plain text; it is typeset once complete.194 Text(message.text).font(.body).foregroundStyle(Color.spText).frame(maxWidth: .infinity, alignment: .leading)195 }196 case .done, .stopped:197 if message.text.isEmpty {198 Text("Aucune réponse reçue.").font(.subheadline).foregroundStyle(Color.spTextSecondary)199 } else {200 NativeDocumentView(markdown: message.text, scrolls: false, identifier: "assistant-chat-answer")201 }202 if message.state == .stopped {203 Text("Réponse interrompue.").font(.footnote).foregroundStyle(Color.spTextSecondary)204 Button("Relancer", action: onRetry).font(.footnote)205 }206 case .awaitingConfirmation(let text):207 VStack(alignment: .leading, spacing: 8) {208 Label("Demande coûteuse", systemImage: "dollarsign.circle").font(.subheadline.weight(.semibold)).foregroundStyle(Color.spWarning)209 Text(text).font(.subheadline).foregroundStyle(Color.spTextSecondary)210 Button("Continuer", action: onConfirm).buttonStyle(.borderedProminent).accessibilityIdentifier("assistant-chat-confirm")211 }212 case .failed(let failure):213 VStack(alignment: .leading, spacing: 6) {214 Label(failure.title, systemImage: failure.symbol).font(.subheadline.weight(.semibold)).foregroundStyle(Color.spDanger)215 Text(failure.message).font(.subheadline).foregroundStyle(Color.spTextSecondary)216 if let detail = failure.detail, !detail.isEmpty { Text(detail).font(.footnote).foregroundStyle(Color.spMuted) }217 if failure.retryable { Button("Réessayer", action: onRetry).buttonStyle(.bordered).accessibilityIdentifier("assistant-chat-retry") }218 }219 .accessibilityIdentifier("assistant-chat-failure")220 }221 }222223 private var sources: some View {224 VStack(alignment: .leading, spacing: 6) {225 Text("Sources").font(.caption.weight(.semibold)).foregroundStyle(Color.spTextSecondary)226 ForEach(AssistantSource.uniqueAnchors(message.sources)) { source in227 Button {228 if let id = source.pageId { onOpenNote(id, source.blockId) }229 } label: {230 HStack(spacing: 8) {231 if let n = source.n { Text("\(n)").font(.caption.monospacedDigit().weight(.semibold)).foregroundStyle(Color.accentColor).frame(minWidth: 18) }232 VStack(alignment: .leading, spacing: 1) {233 Text(AppModel.displayTitle(source.title ?? "")).font(.subheadline.weight(.medium)).foregroundStyle(Color.spText).lineLimit(1)234 if let heading = source.heading, !heading.isEmpty { Text(heading).font(.caption).foregroundStyle(Color.spTextSecondary).lineLimit(1) }235 }236 Spacer(minLength: 0)237 Image(systemName: "chevron.right").font(.caption).foregroundStyle(Color.spMuted).accessibilityHidden(true)238 }239 .padding(.horizontal, 12)240 .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading)241 .background(Color.spSurface, in: RoundedRectangle(cornerRadius: 10, style: .continuous))242 .contentShape(RoundedRectangle(cornerRadius: 10, style: .continuous))243 }244 .buttonStyle(.plain)245 .accessibilityHint(source.blockId == nil ? "Ouvre la note" : "Ouvre la note au passage cité")246 .accessibilityIdentifier("assistant-source")247 }248 }249 .accessibilityIdentifier("assistant-chat-sources")250 }251}252