SPB Git

Repository Public

AssistantSheet.swift 16.7 KB 358 lines swift

1// SP Notes iOS2// File: Features/AI/AssistantSheet.swift3// Description: The assistant sheet of a note. "Actions" transforms the selection (or the whole note) and shows the streamed result;4//              nothing is written to the note until the user picks "Remplacer la sélection" or "Insérer en dessous".5//              "Questions" is a conversation about the notes, with tappable sources.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesCore10import SwiftUI11import UIKit1213/// What the sheet works on, captured when it opens.14struct AssistantContext {15    var noteId: String16    var noteTitle: String17    /// The selection, or the whole note when nothing is selected.18    var sourceText: String19    var hasSelection: Bool20    /// False while the note has never been synchronised (page modes of the chat need the server copy).21    var pageIsOnServer: Bool22}2324struct AssistantSheet: View {25    enum Tab: String, CaseIterable, Identifiable {26        case actions, questions27        var id: String { rawValue }28        var title: String { self == .actions ? String(localized: "Actions") : String(localized: "Questions") }29    }3031    let context: AssistantContext32    /// `(markdown, replacingSelection)`: called only when the user chooses to put the result in the note.33    var onInsert: (String, Bool) -> Void34    var onOpenNote: (String, String?) -> Void3536    @State private var actions: AssistantActionModel37    @State private var chat: AssistantChatModel38    @State private var tab: Tab = .actions39    @Environment(\.dismiss) private var dismiss4041    init(context: AssistantContext, provider: any AssistantProvider, availability: @escaping AssistantAvailability,42         onInsert: @escaping (String, Bool) -> Void, onOpenNote: @escaping (String, String?) -> Void) {43        self.context = context44        self.onInsert = onInsert45        self.onOpenNote = onOpenNote46        _actions = State(initialValue: AssistantActionModel(sourceText: context.sourceText, hasSelection: context.hasSelection, provider: provider, availability: availability))47        _chat = State(initialValue: AssistantChatModel(pageId: context.noteId, pageIsOnServer: context.pageIsOnServer, provider: provider, availability: availability))48    }4950    var body: some View {51        NavigationStack {52            VStack(spacing: 0) {53                Picker("Mode de l’assistant", selection: $tab) {54                    ForEach(Tab.allCases) { Text($0.title).tag($0) }55                }56                .pickerStyle(.segmented)57                .padding(.horizontal, 16)58                .padding(.vertical, 8)59                .accessibilityIdentifier("assistant-tabs")60                switch tab {61                case .actions:62                    AssistantActionsView(model: actions, context: context) { markdown, replacing in63                        onInsert(markdown, replacing)64                        dismiss()65                    }66                case .questions:67                    AssistantChatView(model: chat, noteTitle: context.noteTitle) { id, blockId in68                        dismiss()69                        onOpenNote(id, blockId)70                    }71                }72            }73            .intelligentPanel() // Intelligent Panels: slide + blur in (cross-fade under Reduce Motion)74            .background(Color.spBackground)75            .navigationTitle("Assistant")76            .navigationBarTitleDisplayMode(.inline)77            .toolbar {78                ToolbarItem(placement: .cancellationAction) {79                    Button("Fermer") { dismiss() }.accessibilityIdentifier("assistant-close")80                }81            }82        }83        .accessibilityIdentifier("assistant-sheet")84        .onDisappear { actions.reset(); chat.stop() }85    }86}8788// MARK: - Actions8990struct AssistantActionsView: View {91    let model: AssistantActionModel92    let context: AssistantContext93    var onInsert: (String, Bool) -> Void9495    @State private var instruction = ""96    @State private var copied = false97    @FocusState private var instructionFocused: Bool9899    private let columns = [GridItem(.adaptive(minimum: 150), spacing: 10)]100101    var body: some View {102        if model.phase == .idle { picker } else { result }103    }104105    private var scopeLine: String {106        let words = context.sourceText.split(whereSeparator: \.isWhitespace).count107        return context.hasSelection108            ? String(localized: "Sur la sélection · \(DocumentFacts.words(words))")109            : String(localized: "Sur toute la note · \(DocumentFacts.words(words))")110    }111112    // The list of actions.113    private var picker: some View {114        ScrollView {115            VStack(alignment: .leading, spacing: 18) {116                Label(scopeLine, systemImage: context.hasSelection ? "text.cursor" : "doc.text")117                    .font(.subheadline)118                    .foregroundStyle(Color.spTextSecondary)119                    .accessibilityIdentifier("assistant-scope")120                VStack(alignment: .leading, spacing: 8) {121                    Text("Instruction libre").font(.footnote.weight(.semibold)).foregroundStyle(Color.spTextSecondary)122                    HStack(alignment: .center, spacing: 8) {123                        TextField("Demande ce que tu veux sur ce texte", text: $instruction, axis: .vertical)124                            .lineLimit(1...4)125                            .focused($instructionFocused)126                            .submitLabel(.send)127                            .accessibilityIdentifier("assistant-instruction")128                        Button { runCustom() } label: {129                            Image(systemName: "arrow.up.circle.fill").font(.title2)130                        }131                        .disabled(instruction.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)132                        .accessibilityLabel("Envoyer l’instruction")133                        .accessibilityIdentifier("assistant-instruction-send")134                        .frame(minWidth: 44, minHeight: 44)135                    }136                    .padding(.leading, 14).padding(.trailing, 4).padding(.vertical, 4)137                    .background(Color.spSurface, in: RoundedRectangle(cornerRadius: 12, style: .continuous))138                    .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(Color.spBorder))139                }140                ForEach(AssistantCatalog.groups) { group in141                    VStack(alignment: .leading, spacing: 8) {142                        Text(group.title).font(.footnote.weight(.semibold)).foregroundStyle(Color.spTextSecondary)143                            .accessibilityAddTraits(.isHeader)144                        LazyVGrid(columns: columns, alignment: .leading, spacing: 10) {145                            ForEach(group.actions) { action in146                                if action.kind == .translate { translateMenu(action) } else {147                                    Button { model.run(.init(action: action.kind)) } label: { tile(action) }148                                        .buttonStyle(.plain)149                                        .accessibilityIdentifier("assistant-action-\(action.kind.rawValue)")150                                }151                            }152                        }153                    }154                }155                Text("Le texte est envoyé au serveur SP Notes, qui choisit le modèle. Rien n’est écrit dans ta note sans ton accord.")156                    .font(.footnote)157                    .foregroundStyle(Color.spMuted)158            }159            .padding(16)160            .frame(maxWidth: 720, alignment: .leading)161            .frame(maxWidth: .infinity)162        }163        .scrollDismissesKeyboard(.interactively)164    }165166    private func tile(_ action: AssistantAction) -> some View {167        HStack(spacing: 10) {168            Image(systemName: action.symbol).font(.body.weight(.medium)).foregroundStyle(Color.accentColor).frame(width: 26)169                .accessibilityHidden(true)170            Text(action.title).font(.subheadline.weight(.medium)).foregroundStyle(Color.spText).multilineTextAlignment(.leading)171            Spacer(minLength: 0)172        }173        .padding(.horizontal, 12)174        .frame(maxWidth: .infinity, minHeight: 48, alignment: .leading)175        .background(Color.spSurface, in: RoundedRectangle(cornerRadius: 12, style: .continuous))176        .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(Color.spBorder))177        .contentShape(RoundedRectangle(cornerRadius: 12, style: .continuous))178    }179180    private func translateMenu(_ action: AssistantAction) -> some View {181        Menu {182            ForEach(AssistantCatalog.languages) { language in183                Button(language.name) { model.run(.init(action: .translate, language: language.code)) }184            }185        } label: { tile(action) }186        .accessibilityIdentifier("assistant-action-translate")187    }188189    private func runCustom() {190        let text = instruction.trimmingCharacters(in: .whitespacesAndNewlines)191        guard !text.isEmpty else { return }192        instructionFocused = false193        model.run(.init(action: .custom, instruction: text))194    }195196    // The streamed result and what to do with it.197    private var result: some View {198        VStack(spacing: 0) {199            header200            Divider().overlay(Color.spBorder)201            Group {202                switch model.phase {203                case .awaitingConfirmation(let message): confirmation(message)204                case .failed(let failure): failureView(failure)205                default: answer206                }207            }208            .frame(maxWidth: .infinity, maxHeight: .infinity)209        }210        .safeAreaInset(edge: .bottom, spacing: 0) { footer }211    }212213    private var header: some View {214        HStack(alignment: .firstTextBaseline, spacing: 10) {215            Button { model.reset() } label: { Label("Actions", systemImage: "chevron.left").labelStyle(.iconOnly) }216                .frame(minWidth: 44, minHeight: 44)217                .accessibilityLabel("Revenir aux actions")218                .accessibilityIdentifier("assistant-back")219            VStack(alignment: .leading, spacing: 2) {220                Text(model.invocation.map { AssistantCatalog.title(for: $0.action) } ?? "").font(.headline).foregroundStyle(Color.spText)221                Text(model.modelLine ?? scopeLine).font(.caption).foregroundStyle(Color.spTextSecondary)222                    .accessibilityIdentifier("assistant-model-line")223            }224            Spacer(minLength: 0)225            if model.isStreaming { ProgressView().accessibilityLabel("Réponse en cours") }226        }227        .padding(.horizontal, 8)228        .padding(.vertical, 4)229    }230231    @ViewBuilder private var answer: some View {232        if model.renderedText.isEmpty {233            VStack(spacing: 10) {234                if model.isStreaming {235                    ProgressView()236                    Text("En attente de la réponse…").font(.subheadline).foregroundStyle(Color.spTextSecondary)237                } else {238                    Text("Aucune réponse reçue.").font(.subheadline).foregroundStyle(Color.spTextSecondary)239                }240            }241        } else {242            NativeDocumentView(markdown: model.renderedText, followsEnd: model.isStreaming, identifier: "assistant-result")243                .frame(maxWidth: 720)244        }245    }246247    private func confirmation(_ message: String) -> some View {248        VStack(spacing: 14) {249            Image(systemName: "dollarsign.circle").font(.system(size: 40, weight: .light)).foregroundStyle(Color.spWarning).accessibilityHidden(true)250            Text("Demande coûteuse").font(.title3.weight(.semibold)).foregroundStyle(Color.spText)251            Text(message).font(.subheadline).foregroundStyle(Color.spTextSecondary).multilineTextAlignment(.center)252            Text("Rien n’a encore été envoyé au fournisseur.").font(.footnote).foregroundStyle(Color.spMuted)253            Button("Continuer") { model.confirmExpensive() }254                .buttonStyle(.borderedProminent)255                .accessibilityIdentifier("assistant-confirm-expensive")256            Button("Annuler") { model.reset() }257        }258        .padding(28)259        .frame(maxWidth: 440)260    }261262    private func failureView(_ failure: AssistantFailure) -> some View {263        ScrollView {264            VStack(spacing: 12) {265                Image(systemName: failure.symbol).font(.system(size: 40, weight: .light)).foregroundStyle(Color.spMuted).accessibilityHidden(true)266                Text(failure.title).font(.title3.weight(.semibold)).foregroundStyle(Color.spText).multilineTextAlignment(.center)267                Text(failure.message).font(.subheadline).foregroundStyle(Color.spTextSecondary).multilineTextAlignment(.center)268                if let detail = failure.detail, !detail.isEmpty {269                    Text(detail).font(.footnote).foregroundStyle(Color.spMuted).multilineTextAlignment(.center).textSelection(.enabled)270                }271                if failure.retryable {272                    Button("Réessayer") { model.regenerate() }273                        .buttonStyle(.borderedProminent)274                        .padding(.top, 6)275                        .accessibilityIdentifier("assistant-retry")276                }277                if model.hasResult {278                    Text("Le début de la réponse a été reçu ; tu peux le copier.").font(.footnote).foregroundStyle(Color.spMuted)279                    Button("Copier ce qui a été reçu") { UIPasteboard.general.string = model.text }280                }281            }282            .padding(28)283            .frame(maxWidth: 440)284            .frame(maxWidth: .infinity)285        }286        .accessibilityIdentifier("assistant-failure")287    }288289    @ViewBuilder private var footer: some View {290        switch model.phase {291        case .streaming:292            Button(role: .cancel) { model.stop() } label: {293                Label("Arrêter", systemImage: "stop.fill").frame(maxWidth: .infinity, minHeight: 30)294            }295            .buttonStyle(.bordered)296            .padding(16)297            .frame(maxWidth: 720)298            .frame(maxWidth: .infinity)299            .background(.bar)300            .accessibilityIdentifier("assistant-stop")301        case .finished(let stopped) where model.hasResult:302            VStack(spacing: 10) {303                if stopped {304                    Text("Réponse interrompue : le texte est incomplet.").font(.footnote).foregroundStyle(Color.spTextSecondary)305                }306                if context.hasSelection {307                    Button { onInsert(model.text, true) } label: { Text("Remplacer la sélection") }308                        .buttonStyle(PrimaryButtonStyle())309                        .accessibilityIdentifier("assistant-replace")310                    secondaryRow(insertIsPrimary: false)311                } else {312                    Button { onInsert(model.text, false) } label: { Text("Insérer en dessous") }313                        .buttonStyle(PrimaryButtonStyle())314                        .accessibilityIdentifier("assistant-insert-below")315                    secondaryRow(insertIsPrimary: true)316                }317            }318            .padding(16)319            .frame(maxWidth: 720)320            .frame(maxWidth: .infinity)321            .background(.bar)322        case .finished:323            Button { model.regenerate() } label: { Label("Régénérer", systemImage: "arrow.clockwise").frame(maxWidth: .infinity, minHeight: 30) }324                .buttonStyle(.bordered)325                .padding(16)326                .frame(maxWidth: 720)327                .frame(maxWidth: .infinity)328                .background(.bar)329        default:330            EmptyView()331        }332    }333334    private func secondaryRow(insertIsPrimary: Bool) -> some View {335        let buttons = Group {336            if !insertIsPrimary {337                Button { onInsert(model.text, false) } label: { Label("Insérer en dessous", systemImage: "text.insert").frame(maxWidth: .infinity, minHeight: 30) }338                    .accessibilityIdentifier("assistant-insert-below")339            }340            Button {341                UIPasteboard.general.string = model.text342                copied = true343                Haptics.success()344            } label: { Label(copied ? "Copié" : "Copier", systemImage: copied ? "checkmark" : "doc.on.doc").frame(maxWidth: .infinity, minHeight: 30) }345                .accessibilityIdentifier("assistant-copy")346            Button { copied = false; model.regenerate() } label: { Label("Régénérer", systemImage: "arrow.clockwise").frame(maxWidth: .infinity, minHeight: 30) }347                .accessibilityIdentifier("assistant-regenerate")348        }349        .buttonStyle(.bordered)350        .labelStyle(.titleAndIcon)351        .lineLimit(1)352        return ViewThatFits(in: .horizontal) {353            HStack(spacing: 8) { buttons }354            VStack(spacing: 8) { buttons }355        }356    }357}358
Files main
Menu

Theme