SPB Git

Repository Public

ModelSheet.swift 19.1 KB 331 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Features/ModelSelection/ModelSheet.swift4//  Description: The model sheet, built for touch: Favorites Dock, routing modes and profiles, recents, verified direct5//               models, and instant search over the whole OpenRouter catalogue (lazy list, swipe actions).6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import SwiftUI1213struct ModelSheet: View {14    enum Purpose {15        /// Choose the model of the next messages (changes the device preference).16        case select17        /// Pick one model for something else (regenerate with, judge, lens, project default): nothing else changes.18        case pick(title: String, current: String?, onPick: (AIModel) -> Void)19    }20    let purpose: Purpose2122    @Environment(AppEnvironment.self) private var env23    @Environment(\.dismiss) private var dismiss24    @Environment(\.accessibilityReduceMotion) private var reduceMotion25    @State private var query = ""26    @State private var lists = Lists()27    @State private var notice: String?2829    struct Lists: Equatable { var recents: [AIModel] = []; var direct: [AIModel] = []; var local: [AIModel] = []; var openRouter: [AIModel] = []; var key = "" }3031    private var isSelecting: Bool { if case .select = purpose { return true } else { return false } }32    private var title: String { if case .pick(let t, _, _) = purpose { return t } else { return String(localized: "Modèle") } }33    private var selectedId: String? {34        switch purpose {35        case .select: env.preferences.routingMode == .manual && env.preferences.presetId == nil ? env.catalog.effectiveModelId(preferred: env.preferences.modelId) : nil36        case .pick(_, let current, _): current37        }38    }3940    var body: some View {41        NavigationStack {42            List {43                if isSelecting && query.isEmpty {44                    dockSection45                    modeSection46                }47                if !lists.recents.isEmpty {48                    Section { ForEach(lists.recents) { row($0) } } header: { header(String(localized: "Récents"), nil) }49                }50                if !lists.direct.isEmpty {51                    Section { ForEach(lists.direct) { row($0) } } header: { header(String(localized: "Vérifiés · route directe"), lists.direct.count) }52                }53                if !lists.local.isEmpty {54                    Section { ForEach(lists.local) { row($0) } } header: { header(String(localized: "Local (MacLustr)"), lists.local.count) } footer: {55                        Text("Inférence sur le service MacLustr AI du propriétaire : aucun coût par jeton. Non testé par le banc.").font(.caption2).foregroundStyle(Color.muted)56                    }57                }58                if !lists.openRouter.isEmpty {59                    Section { ForEach(lists.openRouter) { row($0) } } header: { header(String(localized: "OpenRouter · catalogue"), lists.openRouter.count) } footer: {60                        Text("Catalogue OpenRouter · non testé par le banc. Prix publiés par le catalogue, en USD par million de jetons (entrée / sortie).").font(.caption2).foregroundStyle(Color.muted)61                    }62                } else if query.isEmpty && !env.catalog.openRouterConfigured && !env.catalog.selectable.isEmpty {63                    Section { Label("Ajoute une clé OpenRouter dans Réglages → Fournisseurs pour ouvrir le catalogue.", systemImage: "key").font(.footnote).foregroundStyle(Color.muted) }64                }65                if lists.direct.isEmpty && lists.local.isEmpty && lists.openRouter.isEmpty && lists.recents.isEmpty {66                    if env.catalog.selectable.isEmpty {67                        ContentUnavailableView { Label("Aucun modèle", systemImage: "cpu") } description: { Text(env.catalog.error ?? String(localized: "Le catalogue n’a pas encore été chargé.")) } actions: { Button("Recharger") { Task { await env.catalog.refresh() } } }68                            .listRowSeparator(.hidden)69                    } else { ContentUnavailableView.search(text: query).listRowSeparator(.hidden) }70                }71            }72            .listStyle(.plain)73            .scrollContentBackground(.hidden)74            .background(Color.appBackground)75            .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: Text("Rechercher parmi \(env.catalog.selectable.count) modèles"))76            .autocorrectionDisabled().textInputAutocapitalization(.never)77            .navigationTitle(title)78            .navigationBarTitleDisplayMode(.inline)79            .toolbar {80                ToolbarItem(placement: .topBarLeading) {81                    NavigationLink { ExplorerView(embedded: true) } label: { Label("Explorer", systemImage: "square.grid.2x2") }82                        .accessibilityIdentifier("models.explore")83                }84                ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() }.accessibilityIdentifier("models.done") }85            }86            .refreshable { await env.catalog.refreshModels() }87            .onChange(of: query, initial: true) { rebuild() }88            .onChange(of: env.catalog.revision) { rebuild() }89            .navigationDestination(for: AIModel.self) { ModelDetailView(model: $0) }90            .overlay(alignment: .bottom) {91                if let notice { Text(notice).font(.footnote).foregroundStyle(Color.textPrimary).padding(.horizontal, 14).padding(.vertical, 10).floatSurface(cornerRadius: 14).padding(.bottom, 12).transition(.opacity.combined(with: .offset(y: 8))) }92            }93            .animation(Motion.snappy(reduceMotion), value: notice)94        }95    }9697    /// Derived lists are computed when the query or the catalogue changes — never per row while scrolling.98    private func rebuild() {99        let key = "\(query)|\(env.catalog.revision)"100        guard key != lists.key else { return }101        var q = ModelQuery(); q.text = query102        let all = q.apply(to: env.catalog.selectable)103        var next = Lists(key: key)104        next.direct = all.filter { !$0.isOpenRouter && !$0.isLocal }105        next.local = all.filter(\.isLocal)106        next.openRouter = all.filter(\.isOpenRouter)107        if query.isEmpty { next.recents = Array(env.catalog.recents.prefix(4)) }108        lists = next109    }110111    private func header(_ title: String, _ count: Int?) -> some View {112        HStack(spacing: 6) {113            Text(title).font(.spMicro).tracking(0.3).textCase(.uppercase)114            if let count { Text("\(count)").font(.spMicro).monospacedDigit().foregroundStyle(Color.muted) }115        }116        .foregroundStyle(Color.textSecondary)117    }118119    // MARK: Favorites Dock120121    private var dockSection: some View {122        let dock = env.catalog.dockModels123        return Section {124            if dock.isEmpty {125                Label("Balaye un modèle vers la gauche pour l’épingler ici (8 au plus, synchronisé avec le web et le Mac).", systemImage: "pin").font(.footnote).foregroundStyle(Color.muted)126                    .listRowBackground(Color.clear)127            } else {128                ScrollView(.horizontal, showsIndicators: false) {129                    HStack(spacing: 10) {130                        ForEach(dock) { m in131                            let on = selectedId == m.id132                            Button { choose(m) } label: {133                                VStack(spacing: 6) {134                                    ModelMark(m, size: 26, color: true)135                                        .frame(width: 54, height: 54)136                                        .background(on ? Color.accentSoft : Color.surface, in: .rect(cornerRadius: 16, style: .continuous))137                                        .overlay(RoundedRectangle(cornerRadius: 16, style: .continuous).strokeBorder(on ? Color.accentColor : Color.hairline, lineWidth: on ? 1.5 : 0.75))138                                    Text(m.shortName).font(.caption2.weight(.medium)).foregroundStyle(on ? Color.accentColor : Color.textSecondary).lineLimit(1).frame(width: 66)139                                }140                            }141                            .buttonStyle(PressScale(scale: 0.92))142                            .contextMenu {143                                Button(role: .destructive) { Task { await env.catalog.toggleDock(m.id) } } label: { Label("Retirer du dock", systemImage: "pin.slash") }144                                NavigationLink(value: m) { Label("Fiche du modèle", systemImage: "info.circle") }145                            }146                            .accessibilityLabel(m.nameWithRoute)147                            .accessibilityAddTraits(on ? .isSelected : [])148                            .accessibilityIdentifier("dock.\(m.id)")149                        }150                    }151                    .padding(.horizontal, 16).padding(.vertical, 4)152                }153                .listRowInsets(EdgeInsets())154                .listRowBackground(Color.clear)155            }156        } header: { header(String(localized: "Dock des favoris"), nil) }157        .listRowSeparator(.hidden)158    }159160    // MARK: routing modes and profiles161162    private var modeSection: some View {163        @Bindable var prefs = env.preferences164        return Section {165            ScrollView(.horizontal, showsIndicators: false) {166                HStack(spacing: 8) {167                    ForEach(RoutingMode.allCases) { m in168                        let on = prefs.routingMode == m && prefs.presetId == nil169                        Button { env.haptics.selection(); withAnimation(Motion.snappy(reduceMotion)) { prefs.routingMode = m; prefs.presetId = nil } } label: { ChipLabel(text: Self.label(m), systemImage: m == .manual ? nil : "sparkles", selected: on) }170                            .buttonStyle(PressScale()).accessibilityAddTraits(on ? .isSelected : [])171                    }172                    if !env.catalog.presets.isEmpty { Divider().frame(height: 20) }173                    ForEach(env.catalog.presets) { p in174                        let on = prefs.presetId == p.id175                        Button { env.haptics.selection(); withAnimation(Motion.snappy(reduceMotion)) { prefs.presetId = on ? nil : p.id } } label: { ChipLabel(text: p.name, systemImage: "dial.medium", selected: on) }176                            .buttonStyle(PressScale()).accessibilityAddTraits(on ? .isSelected : []).accessibilityHint(p.description ?? "")177                    }178                }179                .padding(.horizontal, 16).padding(.vertical, 2)180            }181            .listRowInsets(EdgeInsets())182            .listRowBackground(Color.clear)183            if let d = env.catalog.preset(prefs.presetId)?.description ?? Self.description(prefs.routingMode) {184                Text(d).font(.footnote).foregroundStyle(Color.muted).listRowBackground(Color.clear)185            }186        } header: { header(String(localized: "Routage et profils"), nil) }187        .listRowSeparator(.hidden)188    }189190    // MARK: rows191192    private func choose(_ m: AIModel) {193        env.haptics.selection()194        switch purpose {195        case .select: withAnimation(Motion.smooth(reduceMotion)) { env.select(model: m.id) }196        case .pick(_, _, let onPick): onPick(m)197        }198        dismiss()199    }200201    private func row(_ m: AIModel) -> some View {202        let selected = selectedId == m.id203        return HStack(spacing: 4) {204            Button { choose(m) } label: { ModelRowLabel(model: m, selected: selected, isDefault: m.id == env.catalog.defaultModelId, inDock: env.catalog.isInDock(m.id)) }205                .buttonStyle(.plain)206                .accessibilityAddTraits(selected ? .isSelected : [])207                .accessibilityIdentifier("model.\(m.id)")208            NavigationLink(value: m) { EmptyView() }.frame(width: 18).opacity(0.6)209                .accessibilityLabel(String(localized: "Fiche de \(m.displayName)"))210        }211        .listRowBackground(selected ? Color.accentSoft : Color.clear)212        .swipeActions(edge: .leading, allowsFullSwipe: true) {213            Button { env.haptics.soften(); Task { await env.catalog.toggleFavorite(m) } } label: { Label(m.favorite ? "Retirer" : "Favori", systemImage: m.favorite ? "star.slash" : "star.fill") }.tint(.orange)214        }215        .swipeActions(edge: .trailing, allowsFullSwipe: false) {216            Button {217                env.haptics.soften()218                if !env.catalog.isInDock(m.id) && env.catalog.dock.count >= ModelCatalog.dockLimit { flash(String(localized: "Le dock contient déjà 8 modèles.")) }219                else { Task { await env.catalog.toggleDock(m.id) } }220            } label: { Label(env.catalog.isInDock(m.id) ? "Retirer du dock" : "Dock", systemImage: env.catalog.isInDock(m.id) ? "pin.slash" : "pin.fill") }.tint(.accentColor)221            if !m.isOpenRouter && !m.isLocal { Button { Task { await env.catalog.makeDefault(m) } } label: { Label("Par défaut", systemImage: "checkmark.seal") }.tint(.gray) }222        }223    }224225    private func flash(_ text: String) {226        notice = text227        Task { try? await Task.sleep(for: .seconds(2.2)); if notice == text { notice = nil } }228    }229230    static func label(_ m: RoutingMode) -> String {231        switch m {232        case .manual: String(localized: "Manuel"); case .auto: String(localized: "Automatique"); case .fast: String(localized: "Rapide")233        case .quality: String(localized: "Qualité"); case .economy: String(localized: "Économie")234        }235    }236    static func description(_ m: RoutingMode) -> String? {237        switch m {238        case .manual: nil239        case .auto: String(localized: "Le serveur choisit un modèle vérifié selon la demande.")240        case .fast: String(localized: "Le modèle vérifié le plus vif.")241        case .quality: String(localized: "Le modèle vérifié le mieux noté.")242        case .economy: String(localized: "Le modèle le moins cher ayant réussi toute la batterie de tests.")243        }244    }245    static func label(_ e: Effort) -> String {246        switch e { case .low: String(localized: "Faible"); case .medium: String(localized: "Moyen"); case .high: String(localized: "Élevé"); case .xhigh: String(localized: "Très élevé"); case .max: String(localized: "Maximal") }247    }248}249250/// One model row: colour mark, exact name, route badge, then capability glyphs · context · price · catalogue label.251struct ModelRowLabel: View {252    let model: AIModel253    var selected = false254    var isDefault = false255    var inDock = false256257    var body: some View {258        HStack(spacing: 12) {259            ModelMark(model, size: 26, color: true)260            VStack(alignment: .leading, spacing: 3) {261                HStack(spacing: 6) {262                    Text(model.displayName).font(.body.weight(selected ? .semibold : .regular)).foregroundStyle(Color.textPrimary).lineLimit(1)263                    RouteBadge(route: model.route)264                    if model.favorite { Image(systemName: "star.fill").font(.system(size: 9)).foregroundStyle(Color.orange).accessibilityLabel(String(localized: "favori")) }265                    if inDock { Image(systemName: "pin.fill").font(.system(size: 9)).foregroundStyle(Color.accentColor).accessibilityLabel(String(localized: "dans le dock")) }266                }267                HStack(spacing: 8) {268                    CapabilityGlyphs(model: model)269                    if let c = model.contextLabel { Text(c).accessibilityLabel(String(localized: "contexte \(c) jetons")) }270                    if let p = model.priceLabel { Text(p).accessibilityLabel(String(localized: "prix \(p) par million de jetons")) }271                    if isDefault { Text("défaut") }272                    if model.isCatalogOnly { Text(model.isLocal ? "local · non testé" : "catalogue · non testé").lineLimit(1) }273                }274                .font(.caption.monospacedDigit()).foregroundStyle(Color.muted).lineLimit(1)275            }276            Spacer(minLength: 0)277            if selected { Image(systemName: "checkmark").font(.subheadline.weight(.bold)).foregroundStyle(Color.accentColor) }278        }279        .frame(minHeight: 46)280        .contentShape(.rect)281        .accessibilityElement(children: .combine)282    }283}284285/// Effort and advanced options of the next messages (per-turn `settings`).286struct TurnOptionsSheet: View {287    @Environment(AppEnvironment.self) private var env288    @Environment(\.dismiss) private var dismiss289290    var body: some View {291        @Bindable var prefs = env.preferences292        let model = prefs.routingMode == .manual ? env.catalog.model(env.catalog.effectiveModelId(preferred: prefs.modelId)) : nil293        let efforts = model?.effortLevels.flatMap { $0.isEmpty ? nil : $0 }294        NavigationStack {295            Form {296                Section {297                    Picker("Effort de raisonnement", selection: $prefs.effort) {298                        Text("Par défaut").tag(Effort?.none)299                        ForEach(Effort.allCases.filter { efforts?.contains($0.rawValue) ?? true }) { e in Text(ModelSheet.label(e)).tag(Effort?.some(e)) }300                    }301                    .pickerStyle(.inline).labelsHidden()302                } header: { Text("Effort de raisonnement") } footer: {303                    if let model, efforts != nil { Text("Niveaux listés pour \(model.displayName).") }304                    else if model?.reasoning == false { Text("Ce modèle n’expose pas de raisonnement réglable : l’effort sera signalé comme ignoré.") }305                }306                Section {307                    Toggle("Température personnalisée", isOn: Binding(get: { prefs.temperature != nil }, set: { prefs.temperature = $0 ? 0.7 : nil }))308                    if let t = prefs.temperature {309                        VStack(alignment: .leading) {310                            Text(String(format: "%.1f", t)).font(.subheadline.monospacedDigit()).foregroundStyle(Color.textSecondary)311                            Slider(value: Binding(get: { prefs.temperature ?? 0.7 }, set: { prefs.temperature = ($0 * 10).rounded() / 10 }), in: 0...2, step: 0.1).accessibilityLabel(String(localized: "Température"))312                        }313                    }314                    Picker("Longueur maximale", selection: $prefs.maxOutputTokens) {315                        Text("Par défaut").tag(Int?.none)316                        ForEach([1000, 4000, 8000, 16_000, 32_000], id: \.self) { n in Text("\(Format.tokens(n)) jetons").tag(Int?.some(n)) }317                    }318                } header: { Text("Avancé") } footer: { Text("Un paramètre que le modèle n’accepte pas n’est pas envoyé : la réponse l’indique comme « ignoré », avec la raison.") }319                Section {320                    Toggle("Proposer un modèle pendant la saisie", isOn: $prefs.suggestModel)321                } footer: { Text("Le routeur du serveur suggère un modèle vérifié pour le brouillon en cours. Rien n’est envoyé et le modèle ne change jamais sans toi.") }322                if prefs.effort != nil || prefs.temperature != nil || prefs.maxOutputTokens != nil {323                    Section { Button("Tout remettre par défaut") { prefs.effort = nil; prefs.temperature = nil; prefs.maxOutputTokens = nil } }324                }325            }326            .navigationTitle("Options de réponse").navigationBarTitleDisplayMode(.inline)327            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() } } }328        }329    }330}331
Files main
Menu

Theme