SPB Git

Repository Public

AskScreen.swift 24.3 KB 400 lines swift

1// SP Drive iOS2// File: Features/Next/AskScreen.swift3// Description: SP Drive AI — ask a document, a folder or the whole Drive. The server retrieves passages from the user's own indexed4//              files and only those go to the model; the answer streams in and cites its passages by number, each opening its file.5//              The picker tells who made a model apart from the route that serves it. Every state where there is no answer is said6//              plainly: not configured, external not allowed, nothing retrieved (no model was called), file not indexed.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import SPDriveNext11import SwiftUI1213/// One question and what came back for it.14struct AskExchange: Identifiable {15    let id = UUID()16    var question: String17    var answer = ""18    var sources: [AISource] = []19    var unindexed: [AIUnindexed] = []20    var done: AIDone?21    var failure: String?22    var streaming = true23}2425struct AskScope: Hashable {26    enum Kind: Hashable { case all, folder(String), file(String) }27    var kind: Kind28    var name: String29    var api: AIScope { switch kind { case .all: .all; case .folder(let id): .folder(id); case .file(let id): .files([id]) } }30}3132struct AskScreen: View {33    @Environment(AppModel.self) private var model34    @Environment(\.dismiss) private var dismiss35    let scope: AskScope36    /// Presented as a sheet (from a document): shows a close button.37    var modal = false38    @State private var question = ""39    @State private var exchanges: [AskExchange] = []40    @State private var task: Task<Void, Never>?41    @State private var picking = false42    @AppStorage("ai.provider") private var providerID = ""43    @AppStorage("ai.model") private var modelID = ""44    @FocusState private var typing: Bool4546    private var providers: AIProviders? { model.next.providers }47    private var choice: (provider: AIProvider, model: AIModel)? {48        guard let providers else { return nil }49        let usable = providers.providers.filter { $0.usable ?? ($0.configured && $0.local) }50        let p = usable.first { $0.id == providerID } ?? usable.first { $0.id == providers.default?.provider } ?? usable.first51        guard let p else { return nil }52        let m = p.models.first { $0.id == modelID } ?? p.models.first { $0.id == providers.default?.model } ?? p.models.first53        return m.map { (p, $0) }54    }55    private var busy: Bool { exchanges.last?.streaming == true }5657    var body: some View {58        Group {59            if let providers {60                if !providers.enabled || choice == nil { unavailable(providers) } else { conversation }61            } else if model.network.online {62                ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)63            } else {64                EmptyState(symbol: "wifi.slash", title: String(localized: "Hors ligne"), message: String(localized: "SP Drive AI interroge le serveur : il faut une connexion."))65            }66        }67        .navigationTitle(scope.kind == .all ? String(localized: "Demander à mon Drive") : String(localized: "Interroger"))68        .navigationBarTitleDisplayMode(.inline)69        .toolbar {70            if modal { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { task?.cancel(); dismiss() } } }71            if let choice {72                ToolbarItem(placement: .topBarTrailing) {73                    Button { picking = true } label: { Label(choice.model.label, systemImage: "cpu") }74                        .accessibilityIdentifier("ask.model")75                        .accessibilityLabel(Text("Modèle : \(choice.model.label)"))76                }77            }78        }79        .sheet(isPresented: $picking) { ModelPicker(providerID: $providerID, modelID: $modelID) }80        .task { await model.next.refreshProviders() }81        .onDisappear { task?.cancel() }82    }8384    private func unavailable(_ p: AIProviders) -> some View {85        let external = p.providers.contains { !$0.local && $0.configured }86        return EmptyState(symbol: "sparkles", title: String(localized: "SP Drive AI n’est pas disponible"),87                          message: external && p.external?.account == false88                            ? String(localized: "Seuls des fournisseurs externes sont configurés sur ce serveur, et tu ne les as pas autorisés. Tu peux les autoriser dans Paramètres → SP Drive AI : des extraits de tes documents quitteraient alors MacLustr.")89                            : String(localized: "Aucun modèle n’est utilisable sur ce serveur pour l’instant. Rien n’a été envoyé."))90            .accessibilityIdentifier("ask.unavailable")91    }9293    private var conversation: some View {94        ScrollViewReader { proxy in95            ScrollView {96                VStack(alignment: .leading, spacing: SPDTheme.Space.lg) {97                    scopeHeader98                    ForEach(exchanges) { exchange in ExchangeView(exchange: exchange, open: open).id(exchange.id) }99                    Color.clear.frame(height: 1).id("end")100                }101                .padding(SPDTheme.Space.lg)102            }103            .onChange(of: exchanges.last?.answer) { _, _ in proxy.scrollTo("end", anchor: .bottom) }104            .onChange(of: exchanges.count) { _, _ in proxy.scrollTo("end", anchor: .bottom) }105        }106        .safeAreaInset(edge: .bottom) { composer }107        .background(SPDTheme.Palette.surface)108    }109110    private var scopeHeader: some View {111        VStack(alignment: .leading, spacing: 6) {112            Label(scope.kind == .all ? String(localized: "Tout mon Drive") : scope.name, systemImage: scope.kind == .all ? "externaldrive" : { if case .folder = scope.kind { return "folder" }; return "doc.text" }())113                .font(SPDTheme.Typo.headline)114            Text("La réponse s’appuie uniquement sur des passages retrouvés dans tes propres fichiers indexés. Elle cite ses passages par numéro ; vérifie-les : un modèle peut se tromper.")115                .font(SPDTheme.Typo.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)116            if let choice {117                Label(choice.provider.local ? String(localized: "Modèle local sur MacLustr : rien ne quitte le cluster.") : String(localized: "Fournisseur externe (\(choice.provider.label)) : les passages retrouvés lui sont envoyés."),118                      systemImage: choice.provider.local ? "lock.shield" : "arrow.up.right.circle")119                    .font(SPDTheme.Typo.caption).foregroundStyle(choice.provider.local ? AnyShapeStyle(.secondary) : AnyShapeStyle(SPDTheme.Palette.warning))120                    .accessibilityIdentifier("ask.route")121            }122        }123        .padding(SPDTheme.Space.md).frame(maxWidth: .infinity, alignment: .leading).spdCard()124    }125126    private var composer: some View {127        HStack(alignment: .bottom, spacing: SPDTheme.Space.sm) {128            TextField("Pose ta question…", text: $question, axis: .vertical)129                .lineLimit(1...5).focused($typing)130                .padding(.horizontal, 14).padding(.vertical, 10)131                .background(SPDTheme.Palette.surfaceRaised, in: RoundedRectangle(cornerRadius: SPDTheme.Radius.xl, style: .continuous))132                .onSubmit { ask() }133                .accessibilityIdentifier("ask.field")134            if busy {135                Button { task?.cancel() } label: { Image(systemName: "stop.circle.fill").font(.system(size: 34)) }.accessibilityLabel(Text("Arrêter la réponse")).accessibilityIdentifier("ask.stop")136            } else {137                Button { ask() } label: { Image(systemName: "arrow.up.circle.fill").font(.system(size: 34)) }138                    .disabled(question.trimmingCharacters(in: .whitespacesAndNewlines).count < 2)139                    .accessibilityLabel(Text("Envoyer la question")).accessibilityIdentifier("ask.send")140            }141        }142        .padding(.horizontal, SPDTheme.Space.md).padding(.vertical, SPDTheme.Space.sm)143        .background(.bar)144    }145146    private func open(_ source: AISource) {147        Task {148            if model.store.item(source.fileId) == nil { await model.engine.sync() }149            guard model.store.item(source.fileId) != nil else { model.toast = Toast(text: String(localized: "Ce fichier n’est plus sur ton Drive."), style: .error); return }150            if modal { dismiss() }151            model.pendingRoute = .file(source.fileId)152        }153    }154155    private func ask() {156        let q = question.trimmingCharacters(in: .whitespacesAndNewlines)157        guard q.count >= 2, !busy, let choice else { return }158        question = ""159        Haptics.tap()160        // earlier turns give the model the thread of the conversation161        let history = exchanges.filter { $0.failure == nil && !$0.answer.isEmpty }.suffix(4).flatMap { [AITurn(role: "user", content: $0.question), AITurn(role: "assistant", content: $0.answer)] }162        exchanges.append(AskExchange(question: q))163        let index = exchanges.count - 1164        let request = AIAskRequest(scope: scope.api, question: q, provider: choice.provider.id, model: choice.model.id, history: history.isEmpty ? nil : Array(history))165        let client = model.next.client166        task = Task {167            do {168                for try await event in client.aiAsk(request) {169                    switch event {170                    case .notice(let unindexed): exchanges[index].unindexed = unindexed171                    case .sources(let s): exchanges[index].sources = s172                    case .delta(let t): exchanges[index].answer += t173                    case .done(let d): exchanges[index].done = d174                    case .error(let code, let message): exchanges[index].failure = Self.modelFailure(code, message)175                    }176                }177            } catch {178                if Task.isCancelled || (error as? NextError) == .cancelled { exchanges[index].failure = String(localized: "Réponse arrêtée.") }179                else { exchanges[index].failure = NextCenter.describe(error) }180            }181            exchanges[index].streaming = false182            if exchanges[index].failure == nil { Haptics.success() }183        }184    }185186    static func modelFailure(_ code: String, _ message: String) -> String {187        switch code {188        case "provider_auth": String(localized: "Le fournisseur a refusé la clé du serveur.")189        case "provider_unreachable", "provider_unavailable": String(localized: "Le modèle ne répond pas pour l’instant.")190        case "provider_rate_limited": String(localized: "Le fournisseur limite les requêtes : réessaie dans un instant.")191        case "provider_refused": String(localized: "Le modèle a refusé de répondre à cette question.")192        case "model_unknown": String(localized: "Ce modèle n’existe plus chez ce fournisseur : choisis-en un autre.")193        default: message.isEmpty ? String(localized: "La réponse a été interrompue.") : String(localized: "La réponse a été interrompue (\(message)).")194        }195    }196}197198private struct ExchangeView: View {199    let exchange: AskExchange200    let open: (AISource) -> Void201202    var body: some View {203        VStack(alignment: .leading, spacing: SPDTheme.Space.md) {204            Text(exchange.question).font(SPDTheme.Typo.body.weight(.semibold))205                .padding(.horizontal, 14).padding(.vertical, 10)206                .background(SPDTheme.Palette.brand.opacity(0.14), in: RoundedRectangle(cornerRadius: SPDTheme.Radius.xl, style: .continuous))207                .frame(maxWidth: .infinity, alignment: .trailing)208                .accessibilityLabel(Text("Question : \(exchange.question)"))209            if !exchange.unindexed.isEmpty {210                Label(exchange.unindexed.count == 1 ? String(localized: "« \(exchange.unindexed[0].name) » n’est pas indexé (\(Self.status(exchange.unindexed[0].status))) : son contenu n’a pas pu être consulté.")211                                                    : String(localized: "\(exchange.unindexed.count) fichiers ne sont pas indexés : leur contenu n’a pas pu être consulté."), systemImage: "doc.questionmark")212                    .font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.Palette.warning).fixedSize(horizontal: false, vertical: true)213                    .accessibilityIdentifier("ask.unindexed")214            }215            if exchange.done?.empty == true {216                Label("Aucun passage de tes documents ne correspond à cette question. Aucun modèle n’a été appelé.", systemImage: "text.magnifyingglass")217                    .font(SPDTheme.Typo.body).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)218                    .padding(SPDTheme.Space.md).frame(maxWidth: .infinity, alignment: .leading).spdCard()219                    .accessibilityIdentifier("ask.empty")220            } else if !exchange.answer.isEmpty || exchange.streaming {221                VStack(alignment: .leading, spacing: SPDTheme.Space.sm) {222                    if exchange.answer.isEmpty { ProgressView().accessibilityLabel(Text("Réponse en cours")) }223                    else { Text(exchange.answer).font(SPDTheme.Typo.body).textSelection(.enabled).fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("ask.answer") }224                    if let d = exchange.done, let m = d.model { Text("Réponse générée par \(m)").font(SPDTheme.Typo.eyebrow).foregroundStyle(.tertiary) }225                }226                .padding(SPDTheme.Space.md).frame(maxWidth: .infinity, alignment: .leading).spdCard()227            }228            if let failure = exchange.failure {229                Label(failure, systemImage: "exclamationmark.triangle").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.Palette.critical).fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("ask.failure")230            }231            if !exchange.sources.isEmpty, exchange.done?.empty != true {232                VStack(alignment: .leading, spacing: SPDTheme.Space.sm) {233                    Text("Passages cités").font(SPDTheme.Typo.caption.weight(.semibold)).foregroundStyle(.secondary)234                    ForEach(exchange.sources) { source in235                        Button { open(source) } label: {236                            HStack(alignment: .top, spacing: SPDTheme.Space.sm) {237                                Text("\(source.n)").font(.caption.weight(.bold).monospacedDigit()).foregroundStyle(.white).frame(minWidth: 22, minHeight: 22).background(SPDTheme.Palette.brand, in: Circle())238                                VStack(alignment: .leading, spacing: 2) {239                                    Text(source.page.map { String(localized: "\(source.name) · page \($0)") } ?? source.name).font(SPDTheme.Typo.callout.weight(.medium)).lineLimit(2).multilineTextAlignment(.leading)240                                    Text(source.text).font(SPDTheme.Typo.caption).foregroundStyle(.secondary).lineLimit(3).multilineTextAlignment(.leading)241                                }242                                Spacer(minLength: 0)243                                Image(systemName: "chevron.right").font(.caption).foregroundStyle(.tertiary)244                            }245                            .padding(SPDTheme.Space.sm + 2).contentShape(Rectangle())246                        }247                        .buttonStyle(.plain).spdCard(radius: SPDTheme.Radius.md).hoverEffect(.highlight)248                        .accessibilityLabel(Text("Passage \(source.n), \(source.name)"))249                        .accessibilityHint(Text("Ouvre le fichier"))250                        .accessibilityIdentifier("ask.source.\(source.n)")251                    }252                }253            }254        }255    }256257    static func status(_ s: String) -> String {258        switch s { case "pending": String(localized: "indexation en cours"); case "empty": String(localized: "aucun texte"); case "unsupported": String(localized: "type non pris en charge"); case "failed": String(localized: "échec de l’indexation"); default: s }259    }260}261262/// Choice of the model. Two different things are named: who made the model, and the route (provider) that serves it.263struct ModelPicker: View {264    @Environment(AppModel.self) private var model265    @Environment(\.dismiss) private var dismiss266    @Binding var providerID: String267    @Binding var modelID: String268269    var body: some View {270        NavigationStack {271            List {272                if let providers = model.next.providers {273                    ForEach(providers.providers) { p in274                        let usable = p.usable ?? (p.configured && p.local)275                        Section {276                            if p.models.isEmpty { Text("Aucun modèle annoncé").foregroundStyle(.secondary) }277                            ForEach(p.models) { m in278                                Button {279                                    providerID = p.id; modelID = m.id; Haptics.selection(); dismiss()280                                } label: {281                                    HStack {282                                        VStack(alignment: .leading, spacing: 2) {283                                            Text(m.label).foregroundStyle(usable ? .primary : .secondary)284                                            Text(m.creator.map { String(localized: "Créé par \($0)") } ?? String(localized: "Créateur non précisé")).font(.caption).foregroundStyle(.secondary)285                                        }286                                        Spacer()287                                        if providerID == p.id, modelID == m.id { Image(systemName: "checkmark").foregroundStyle(SPDTheme.Palette.brand).accessibilityLabel(Text("Sélectionné")) }288                                    }289                                }290                                .disabled(!usable)291                                .accessibilityIdentifier("model.\(p.id).\(m.id)")292                            }293                        } header: {294                            Text("Servi par : \(p.label)")295                        } footer: {296                            Text(p.local ? String(localized: "Route locale : le modèle tourne sur le cluster MacLustr.")297                                 : !p.configured ? String(localized: "Route externe, non configurée sur ce serveur.")298                                 : usable ? String(localized: "Route externe, autorisée : les passages retrouvés sont envoyés à ce fournisseur.")299                                 : String(localized: "Route externe, non autorisée (réglage du serveur, ou ton consentement dans Paramètres)."))300                        }301                    }302                }303            }304            .navigationTitle("Modèle")305            .navigationBarTitleDisplayMode(.inline)306            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() } } }307        }308        .presentationDetents([.medium, .large])309    }310}311312/// Settings → SP Drive AI: what is configured, and the consent for external providers.313struct AISettingsSection: View {314    @Environment(AppModel.self) private var model315    @State private var saving = false316317    var body: some View {318        if model.next.has(.ai) {319            Section {320                if let p = model.next.providers {321                    LabeledContent("Modèles utilisables") { Text("\(p.providers.filter { $0.usable ?? ($0.configured && $0.local) }.reduce(0) { $0 + $1.models.count })").monospacedDigit() }322                    Toggle(isOn: Binding(get: { p.external?.account ?? false }, set: { on in323                        saving = true324                        Task { await model.performNext { try await model.next.client.setExternalAI(on) }; await model.next.refreshProviders(); saving = false }325                    })) { Label("Autoriser les fournisseurs d’IA externes", systemImage: "arrow.up.right.circle") }326                    .disabled(saving)327                    .accessibilityIdentifier("settings.aiExternal")328                } else { ProgressView() }329            } header: {330                Text("SP Drive AI")331            } footer: {332                let server = model.next.providers?.external?.server ?? false333                Text(server ? String(localized: "Avec un fournisseur externe, les passages retrouvés dans tes documents pour répondre à une question lui sont envoyés. Le modèle local de MacLustr n’envoie rien hors du cluster et n’a pas besoin de ce réglage.")334                            : String(localized: "Ce serveur n’accepte aucun fournisseur externe : ce réglage est sans effet tant que l’administrateur ne les active pas. Le modèle local de MacLustr n’en a pas besoin."))335            }336            .task { await model.next.refreshProviders() }337        }338    }339}340341/// Organisation suggestions for a few files: proposals only. The server applies nothing; each proposal is applied here, one by one,342/// when the user asks for it, through the ordinary operations (rename, tags, move).343struct SuggestionsSheet: View {344    @Environment(AppModel.self) private var model345    @Environment(\.dismiss) private var dismiss346    let items: [DriveItem]347    @State private var state: Loadable<AISuggestions> = .loading348    @State private var applied: Set<String> = []349350    var body: some View {351        NavigationStack {352            LoadingView(state: state, retry: load) { result in353                List {354                    if result.suggestions.isEmpty { Text("Aucune proposition pour ces fichiers.").foregroundStyle(.secondary) }355                    ForEach(result.suggestions) { s in356                        let item = model.store.item(s.fileId)357                        Section {358                            if let name = s.name, name != item?.name { proposal("name-\(s.fileId)", String(localized: "Renommer en « \(name) »"), "pencil") { try await model.engine.rename(s.fileId, to: name) } }359                            if let tags = s.tags, !tags.isEmpty {360                                proposal("tags-\(s.fileId)", String(localized: "Étiqueter : \(tags.joined(separator: ", "))"), "tag") {361                                    var all = try await model.next.client.tags()362                                    var ids = Set(try await model.next.client.tagIDs(of: s.fileId))363                                    for t in tags {364                                        if let known = all.first(where: { $0.name.caseInsensitiveCompare(t) == .orderedSame }) { ids.insert(known.id) }365                                        else { let made = try await model.next.client.createTag(name: t, color: "slate"); all.append(made); ids.insert(made.id) }366                                    }367                                    try await model.next.client.setTags(of: s.fileId, to: Array(ids))368                                }369                            }370                            if let folder = s.folder, folder.id != item?.parentID { proposal("move-\(s.fileId)", String(localized: "Déplacer vers « \(folder.path) »"), "folder") { try await model.engine.move([s.fileId], to: folder.id) } }371                            if let reason = s.reason { Text(reason).font(.caption).foregroundStyle(.secondary) }372                        } header: { Text(item?.name ?? s.fileId) }373                    }374                    Section { } footer: {375                        Text("Propositions générées par \(result.model ?? "un modèle") à partir du texte indexé de ces fichiers. Rien n’est appliqué tant que tu ne touches pas « Appliquer » ; vérifie chaque proposition.")376                    }377                }378            }379            .navigationTitle("Suggestions de rangement")380            .navigationBarTitleDisplayMode(.inline)381            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() } } }382            .task { await load() }383        }384    }385386    private func proposal(_ id: String, _ text: String, _ symbol: String, apply: @escaping () async throws -> Void) -> some View {387        HStack {388            Label(text, systemImage: symbol).fixedSize(horizontal: false, vertical: true)389            Spacer(minLength: 8)390            if applied.contains(id) { Label("Appliqué", systemImage: "checkmark.circle.fill").labelStyle(.iconOnly).foregroundStyle(SPDTheme.Palette.positive) }391            else { Button("Appliquer") { Task { await model.performNext { try await apply(); applied.insert(id); Haptics.success() } } }.buttonStyle(.bordered).accessibilityIdentifier("suggest.apply.\(id.prefix(4))") }392        }393    }394395    private func load() async {396        do { state = .loaded(try await model.next.client.aiSuggest(fileIDs: items.filter { !$0.isFolder && !$0.isLocalOnly }.prefix(20).map(\.id))) }397        catch { state = .failed(NextCenter.describe(error)) }398    }399}400
Files main
Menu

Theme