Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/Assistant/ModelPicker.swift3// Description: The model picker: the server's catalogue grouped by creator (who made the model) with the API route (who4// serves it) shown as a separate badge, capabilities, context window, prices and availability. « Auto »5// lets the server route. A model the server marks unavailable is listed with its reason and cannot be chosen.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import Observation11import SPNotesAPI12import SPNotesDesign13import SPNotesSync14import SwiftUI1516/// The models of one creator.17public struct ModelPickerGroup: Identifiable, Equatable, Sendable {18 public var id: String19 public var name: String20 public var logoPath: String?21 public var monogram: String?22 public var models: [AIModelInfo]23}2425@Observable @MainActor26public final class ModelPickerModel {27 public private(set) var catalog: AIModelCatalog?28 public private(set) var phase: LoadPhase = .idle29 public private(set) var freshness: Freshness?30 /// nil = « Auto » (the server chooses).31 public private(set) var selectedId: String?32 public var searchText = ""33 /// Also list the models that cannot be used now (greyed, with the reason).34 public var showsUnavailable = true35 public var actionFailure: FeatureFailure?3637 private let repository: AssistantRepository38 private let onSelect: (@MainActor (AIModelInfo?) -> Void)?3940 public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, selectedId: String? = nil,41 now: @escaping @Sendable () -> Date = { Date() }, onSelect: (@MainActor (AIModelInfo?) -> Void)? = nil) {42 repository = repositories.assistant43 self.selectedId = selectedId44 self.onSelect = onSelect45 }4647 /// The cached catalogue when it is recent (a day), else the server; offline the last copy with its date.48 public func load(forceRefresh: Bool = false) async {49 phase = .loading50 do {51 let cached = try await repository.models(AIModelQuery(includeUnavailable: true), policy: forceRefresh ? .networkFirst : .cacheFirst(maxAge: Staleness.models))52 catalog = cached.value53 freshness = Freshness(cached)54 phase = .loaded55 } catch {56 phase = .failed(FeatureFailure(error))57 }58 }5960 public var selected: AIModelInfo? { catalog?.models.first { $0.id == selectedId } }6162 /// Chooses a model (nil = Auto). Refused for a model the server marks unavailable.63 @discardableResult64 public func select(_ model: AIModelInfo?) -> Bool {65 if let model, !model.isSelectable {66 actionFailure = FeatureFailure(kind: .other, message: Self.unavailableReason(model) ?? L("Ce modèle n'est pas disponible."))67 return false68 }69 actionFailure = nil70 selectedId = model?.id71 onSelect?(model)72 return true73 }7475 /// Creators in the server's order (then the others alphabetically), each with its models: available first, then by name.76 public var groups: [ModelPickerGroup] {77 guard let catalog else { return [] }78 let needle = searchText.trimmingCharacters(in: .whitespaces).lowercased()79 let models = catalog.models.filter { model in80 (showsUnavailable || model.isSelectable) && (needle.isEmpty || Self.haystack(model).contains(needle))81 }82 var buckets: [String: [AIModelInfo]] = [:]83 for model in models { buckets[Self.creatorId(model), default: []].append(model) }84 let declared = (catalog.creators ?? []).map(\.id)85 let order = declared.filter { buckets[$0] != nil } + buckets.keys.filter { !declared.contains($0) }.sorted()86 return order.map { id in87 let creator = catalog.creators?.first { $0.id == id }88 let list = (buckets[id] ?? []).sorted { a, b in89 if a.isSelectable != b.isSelectable { return a.isSelectable }90 return Self.name(a).localizedCaseInsensitiveCompare(Self.name(b)) == .orderedAscending91 }92 let first = list.first93 return ModelPickerGroup(id: id, name: creator?.name ?? first?.creatorName ?? Self.fallbackCreatorName(id), logoPath: creator?.logo ?? first?.logo,94 monogram: creator?.monogram ?? first?.monogram, models: list)95 }96 }9798 public var isEmpty: Bool { groups.isEmpty }99100 // MARK: presentation (pure)101102 /// A 2.x server has no `creator`: the provider is the only thing known.103 public nonisolated static func creatorId(_ model: AIModelInfo) -> String { model.creator ?? model.provider ?? "unknown" }104 public nonisolated static func name(_ model: AIModelInfo) -> String { model.displayName ?? model.id }105 nonisolated static func fallbackCreatorName(_ id: String) -> String { id == "unknown" ? L("Créateur inconnu") : id.prefix(1).uppercased() + id.dropFirst() }106107 nonisolated static func haystack(_ model: AIModelInfo) -> String {108 [model.id, model.displayName, model.creator, model.creatorName, model.route, model.routeLabel, model.provider].compactMap { $0 }.joined(separator: " ").lowercased()109 }110111 /// « via OpenRouter »: who serves the model. nil when unknown (2.x server).112 public nonisolated static func routeLabel(_ model: AIModelInfo) -> String? {113 guard let label = model.routeLabel ?? model.route ?? model.provider else { return nil }114 return LF("via %@", label)115 }116117 /// True when the model is served by somebody else than its creator (an aggregator or the cluster).118 public nonisolated static func isIndirectRoute(_ model: AIModelInfo) -> Bool {119 guard let route = model.route, let creator = model.creator else { return false }120 return route != creator121 }122123 /// A number in the locale of the strings, with at most `decimals` decimals and no trailing zeros.124 public nonisolated static func number(_ value: Double, decimals: Int = 2) -> String {125 let formatter = NumberFormatter()126 formatter.locale = FeatureStrings.locale127 formatter.numberStyle = .decimal128 formatter.usesGroupingSeparator = false129 formatter.minimumFractionDigits = 0130 formatter.maximumFractionDigits = decimals131 return formatter.string(from: NSNumber(value: value)) ?? String(value)132 }133134 /// `1 M`, `1,5 M`, `200 k`, `8192`.135 public nonisolated static func tokens(_ count: Int?) -> String? {136 guard let count, count > 0 else { return nil }137 if count >= 1_000_000 { return number(Double(count) / 1_000_000, decimals: 1) + " M" }138 if count >= 10_000 { return number((Double(count) / 1000).rounded(), decimals: 0) + " k" }139 return String(count)140 }141142 public nonisolated static func contextLabel(_ model: AIModelInfo) -> String? {143 tokens(model.context ?? model.contextWindow).map { LF("Contexte %@", $0) }144 }145146 nonisolated static func price(_ value: Double) -> String { number(value, decimals: value < 0.1 ? 3 : 2) }147148 /// « 3 $ entrée · 15 $ sortie / M jetons » from the catalogue's prices (USD per million tokens); nil when unknown.149 public nonisolated static func priceLabel(_ model: AIModelInfo) -> String? {150 let input = model.priceIn ?? model.inputPrice, output = model.priceOut ?? model.outputPrice151 guard input != nil || output != nil else { return nil }152 if let input, let output {153 if input == 0, output == 0 { return L("Gratuit") }154 return LF("%@ $ entrée · %@ $ sortie / M jetons", price(input), price(output))155 }156 if let input { return LF("%@ $ entrée / M jetons", price(input)) }157 return LF("%@ $ sortie / M jetons", price(output ?? 0))158 }159160 /// The capabilities the catalogue declares or measured, as (symbol, label).161 public nonisolated static func capabilities(_ model: AIModelInfo) -> [(symbol: String, label: String)] {162 guard let caps = model.normalizedCapabilities else { return [] }163 var out: [(String, String)] = []164 if caps.vision == true { out.append(("eye", L("Vision"))) }165 if caps.tools == true { out.append(("wrench.and.screwdriver", L("Outils"))) }166 if caps.reasoning == true { out.append(("brain", L("Raisonnement"))) }167 if caps.structuredOutput == true || caps.jsonMode == true { out.append(("curlybraces", L("Sortie structurée"))) }168 return out169 }170171 /// True when the capabilities were measured by the server's probes (else declared by the provider).172 public nonisolated static func capabilitiesMeasured(_ model: AIModelInfo) -> Bool? {173 model.normalizedCapabilities?.source.map { $0 == "measured" }174 }175176 /// Why a model cannot be chosen (nil when it can).177 public nonisolated static func unavailableReason(_ model: AIModelInfo) -> String? {178 guard !model.isSelectable else { return nil }179 switch model.unavailableReason {180 case AIUnavailableReason.noKey: return L("Indisponible : aucune clé configurée sur le serveur pour cette route.")181 case AIUnavailableReason.providerDisabled: return L("Indisponible : cette route est désactivée sur le serveur.")182 case AIUnavailableReason.notListed: return L("Indisponible : le fournisseur ne propose plus ce modèle.")183 case AIUnavailableReason.disabled: return L("Indisponible : modèle désactivé sur le serveur.")184 default: return L("Indisponible pour le moment.")185 }186 }187188 /// A model that was never benchmarked is never chosen by « Auto ».189 public nonisolated static func manualOnlyNote(_ model: AIModelInfo) -> String? {190 model.autoRoutable == false ? L("Choix manuel seulement : non mesuré, jamais retenu par Auto.") : nil191 }192193 public nonisolated static func accessibilityLabel(_ model: AIModelInfo, creator: String) -> String {194 ([name(model), creator, routeLabel(model), contextLabel(model), priceLabel(model)].compactMap { $0 } + capabilities(model).map(\.label)195 + [unavailableReason(model)].compactMap { $0 }).joined(separator: ", ")196 }197}198199/// The picker. Host it in a sheet (compact) or a popover / inspector (regular); `onSelect` of the model receives the choice.200public struct ModelPickerView: View {201 @State private var model: ModelPickerModel202 private let showsHeader: Bool203204 public init(repositories: NotesRepositories, selectedId: String? = nil, showsHeader: Bool = true, onSelect: @escaping @MainActor (AIModelInfo?) -> Void) {205 _model = State(initialValue: ModelPickerModel(repositories: repositories, selectedId: selectedId, onSelect: onSelect))206 self.showsHeader = showsHeader207 }208209 public init(model: ModelPickerModel, showsHeader: Bool = true) {210 _model = State(initialValue: model)211 self.showsHeader = showsHeader212 }213214 public var body: some View {215 FeatureScaffold(title: L("Modèle"), subtitle: L("Le créateur du modèle, et la route d'API qui le sert."), phase: model.phase, freshness: model.freshness,216 showsHeader: showsHeader, retry: { Task { await model.load(forceRefresh: true) } },217 actions: { FeatureIconButton("arrow.clockwise", label: L("Actualiser le catalogue")) { Task { await model.load(forceRefresh: true) } } }) { sizeClass in218 FeaturePhaseView(phase: model.phase, hasData: model.catalog != nil, retry: { Task { await model.load(forceRefresh: true) } }) {219 EmptyView()220 } content: {221 ScrollView {222 VStack(alignment: .leading, spacing: NVSpace.lg) {223 controls(sizeClass)224 if let failure = model.actionFailure { FeatureStatusBanner(failure: failure, freshness: nil) }225 autoRow226 if model.isEmpty {227 NVEmptyState(systemImage: "cpu", title: L("Aucun modèle"), message: L("Aucun modèle ne correspond à cette recherche."))228 .frame(maxWidth: .infinity).padding(.vertical, NVSpace.xl)229 }230 if sizeClass.isCompact {231 ForEach(model.groups) { group in groupView(group, compact: true) }232 } else {233 LazyVGrid(columns: [GridItem(.flexible(), spacing: NVSpace.lg, alignment: .top), GridItem(.flexible(), spacing: NVSpace.lg, alignment: .top)], alignment: .leading, spacing: NVSpace.lg) {234 ForEach(model.groups) { group in groupView(group, compact: false) }235 }236 }237 Text(L("Logos : collection simple-icons (CC0) ; les marques appartiennent à leurs propriétaires."))238 .nvFont(.micro).foregroundStyle(NVColor.fgMuted)239 }240 .padding(.horizontal, sizeClass.isCompact ? NVSpace.lg : NVSpace.xl)241 .padding(.bottom, NVSpace.xl)242 }243 }244 }245 .task { if model.phase == .idle { await model.load() } }246 }247248 private func controls(_ sizeClass: FeatureSizeClass) -> some View {249 HStack(spacing: NVSpace.sm) {250 HStack(spacing: NVSpace.sm) {251 Image(systemName: "magnifyingglass").foregroundStyle(NVColor.fgMuted).accessibilityHidden(true)252 TextField(L("Chercher un modèle"), text: $model.searchText)253 .textFieldStyle(.plain)254 .nvFont(.body)255 }256 .padding(.horizontal, NVSpace.md)257 .frame(minHeight: sizeClass.isCompact ? 44 : 36)258 .background(NVColor.bgElevated, in: NVRadius.shape(NVRadius.md))259 .overlay(NVRadius.shape(NVRadius.md).strokeBorder(NVColor.line, lineWidth: 1))260 NVChip(L("Indisponibles"), systemImage: model.showsUnavailable ? "eye" : "eye.slash", tone: .accent, isSelected: model.showsUnavailable) {261 model.showsUnavailable.toggle()262 }263 .fixedSize()264 .accessibilityLabel(model.showsUnavailable ? L("Masquer les modèles indisponibles") : L("Afficher les modèles indisponibles"))265 }266 }267268 private var autoRow: some View {269 Button { model.select(nil) } label: {270 HStack(spacing: NVSpace.md) {271 Image(systemName: "wand.and.stars")272 .font(.system(size: 15, weight: .medium))273 .foregroundStyle(NVColor.accent)274 .frame(width: 32, height: 32)275 .background(NVColor.accentSoft, in: NVRadius.shape(NVRadius.sm))276 .accessibilityHidden(true)277 VStack(alignment: .leading, spacing: NVSpace.xxs) {278 Text(L("Auto")).nvFont(.uiStrong).foregroundStyle(NVColor.fg)279 Text(L("Le serveur choisit le modèle mesuré le plus adapté à la demande.")).nvFont(.ui).foregroundStyle(NVColor.fgMuted)280 .fixedSize(horizontal: false, vertical: true)281 }282 Spacer(minLength: NVSpace.sm)283 selectionMark(model.selectedId == nil)284 }285 .padding(NVSpace.md)286 .frame(maxWidth: .infinity, alignment: .leading)287 .background(model.selectedId == nil ? NVColor.accentSoft.opacity(0.5) : NVColor.bgElevated, in: NVRadius.shape(NVRadius.lg))288 .overlay(NVRadius.shape(NVRadius.lg).strokeBorder(model.selectedId == nil ? NVColor.accent : NVColor.line, lineWidth: 1))289 .contentShape(Rectangle())290 }291 .buttonStyle(.plain)292 .accessibilityAddTraits(model.selectedId == nil ? .isSelected : [])293 }294295 private func selectionMark(_ on: Bool) -> some View {296 Image(systemName: on ? "checkmark.circle.fill" : "circle")297 .font(.system(size: 18))298 .foregroundStyle(on ? NVColor.accent : NVColor.lineStrong)299 .accessibilityHidden(true)300 }301302 private func groupView(_ group: ModelPickerGroup, compact: Bool) -> some View {303 VStack(alignment: .leading, spacing: 0) {304 HStack(spacing: NVSpace.sm) {305 ModelLogoView(creator: group.id, logoPath: group.logoPath, monogram: group.monogram, size: 28)306 Text(group.name).nvFont(.h3).foregroundStyle(NVColor.fg)307 Spacer(minLength: 0)308 Text(String(group.models.count)).nvFont(.micro).foregroundStyle(NVColor.fgMuted)309 .accessibilityLabel(LF("%lld modèles", group.models.count))310 }311 .padding(NVSpace.md)312 .accessibilityElement(children: .combine)313 .accessibilityAddTraits(.isHeader)314 ForEach(group.models) { item in315 Divider().overlay(NVColor.line)316 row(item, group: group, compact: compact)317 }318 }319 .nvCard()320 }321322 private func row(_ item: AIModelInfo, group: ModelPickerGroup, compact: Bool) -> some View {323 let selectable = item.isSelectable324 let isSelected = model.selectedId == item.id325 return Button { model.select(item) } label: {326 HStack(alignment: .top, spacing: NVSpace.md) {327 VStack(alignment: .leading, spacing: NVSpace.xs) {328 HStack(alignment: .firstTextBaseline, spacing: NVSpace.sm) {329 Text(ModelPickerModel.name(item)).nvFont(.uiStrong).foregroundStyle(selectable ? NVColor.fg : NVColor.fgMuted)330 if let route = ModelPickerModel.routeLabel(item) { routeBadge(item, label: route) }331 }332 let facts = [ModelPickerModel.contextLabel(item), ModelPickerModel.priceLabel(item)].compactMap { $0 }333 if compact {334 ForEach(facts, id: \.self) { fact in Text(fact).nvFont(.ui).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true) }335 } else if !facts.isEmpty {336 Text(facts.joined(separator: " · ")).nvFont(.ui).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true)337 }338 let caps = ModelPickerModel.capabilities(item)339 if !caps.isEmpty {340 AskFlow(spacing: NVSpace.md) {341 ForEach(caps, id: \.label) { cap in342 Label(cap.label, systemImage: cap.symbol).nvFont(.micro).foregroundStyle(NVColor.fgMuted).labelStyle(.titleAndIcon).fixedSize()343 }344 }345 }346 if let reason = ModelPickerModel.unavailableReason(item) {347 Label(reason, systemImage: "slash.circle").nvFont(.micro).foregroundStyle(NVColor.warningText).fixedSize(horizontal: false, vertical: true)348 } else if let note = ModelPickerModel.manualOnlyNote(item) {349 Text(note).nvFont(.micro).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true)350 }351 }352 Spacer(minLength: NVSpace.sm)353 if selectable { selectionMark(isSelected) }354 }355 .padding(.horizontal, NVSpace.md)356 .padding(.vertical, NVSpace.sm)357 .frame(maxWidth: .infinity, minHeight: compact ? 44 : nil, alignment: .leading)358 .background(isSelected ? NVColor.accentSoft.opacity(0.5) : Color.clear)359 .contentShape(Rectangle())360 }361 .buttonStyle(.plain)362 .allowsHitTesting(selectable) // not `.disabled`: its dimming would make the reason unreadable363 .accessibilityElement(children: .ignore)364 .accessibilityLabel(ModelPickerModel.accessibilityLabel(item, creator: group.name))365 .accessibilityAddTraits(isSelected ? .isSelected : [])366 .accessibilityHint(selectable ? "" : L("Ne peut pas être choisi"))367 }368369 /// The API route: a different shape from the creator's tile, with the route's own small mark.370 private func routeBadge(_ item: AIModelInfo, label: String) -> some View {371 let indirect = ModelPickerModel.isIndirectRoute(item)372 return HStack(spacing: NVSpace.xs) {373 if item.route != nil { ModelLogoView(route: item.route, logoPath: item.routeLogo, size: 14) }374 Text(label).nvFont(.micro)375 }376 .foregroundStyle(indirect ? NVColor.accent : NVColor.fgMuted)377 .padding(.horizontal, NVSpace.sm)378 .padding(.vertical, NVSpace.xxs)379 .background(indirect ? NVColor.accentSoft : NVColor.bgSunken, in: Capsule())380 }381}382