Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Workspace/ExplorerModel.swift3// Description: State of the Model Explorer (query, results over the whole catalogue, maker facet, compare tray, category rules) and the wording / formatting shared by its views.4import SwiftUI5import SPChatCore67/// State of one Explorer screen. Results are recomputed only when the query or the catalogue changes, never per frame.8@Observable final class ExplorerModel {9 static let maxCompare = 41011 var query = ModelQuery() { didSet { if query != oldValue { recompute() } } }12 private(set) var results: [AIModel] = []13 /// Makers of the rows the current « tous les types » switch lets through, most models first.14 private(set) var makers: [MakerFacet] = []15 /// Number of rows before search and filters (the denominator of the result count).16 private(set) var universeCount = 017 /// Compare tray: 2–4 model ids, in the order they were picked.18 private(set) var compare: [String] = []19 /// The rule behind each category, as written by the server (`GET /api/providers → categoryRules`).20 var categoryRules: [String: String] = [:]21 @ObservationIgnored private var index = ModelSearchIndex([])2223 struct MakerFacet: Identifiable, Equatable { let slug: String; let name: String; let logo: String?; let count: Int; var id: String { slug } }2425 func setIndex(_ index: ModelSearchIndex) { self.index = index; recompute() }2627 private func recompute() {28 var all = ModelQuery(); all.includeNonChat = query.includeNonChat29 let universe = index.search(all)30 universeCount = universe.count31 makers = universe.makers.map { MakerFacet(slug: $0.slug, name: $0.name, logo: $0.logo, count: $0.count) }32 var r = index.search(query)33 // a router publishes a negative price (« variable »): it has no price to compare, so it never passes a price34 // ceiling and always sorts after the priced models35 if query.maxInputPrice != nil { r.removeAll(where: \.hasVariablePrice) }36 if query.sort == .priceAscending || query.sort == .priceDescending { r = r.filter { !$0.hasVariablePrice } + r.filter(\.hasVariablePrice) }37 results = r38 }3940 // MARK: Filters4142 func toggle(maker slug: String) { query.makers.formSymmetricDifference([slug]) }43 func toggle(route: String) { query.routes.formSymmetricDifference([route]) }44 func toggle(capability: String) { query.capabilities.formSymmetricDifference([capability]) }45 func toggle(category: String) { query.categories.formSymmetricDifference([category]) }46 func clearFilters() { query.clearFilters() }47 /// Search text and filters back to nothing (sort and « tous les types » are kept).48 func clearAll() { var q = query; q.clearFilters(); q.text = ""; query = q }4950 // MARK: Compare tray5152 func isCompared(_ id: String) -> Bool { compare.contains(id) }53 var compareIsFull: Bool { compare.count >= Self.maxCompare }54 var canCompare: Bool { compare.count >= 2 }55 /// Adds or removes a model; returns false when the tray is full (4 models).56 @discardableResult func toggleCompare(_ id: String) -> Bool {57 if let i = compare.firstIndex(of: id) { compare.remove(at: i); return true }58 guard !compareIsFull else { return false }59 compare.append(id); return true60 }61 func clearCompare() { compare = [] }62 /// Drops ids that left the catalogue (after a registry refresh).63 func pruneCompare(known: (String) -> Bool) { let kept = compare.filter(known); if kept != compare { compare = kept } }64}6566extension AIModel {67 /// Only a verified, available chat model may become the default (rule of the server).68 var canBeDefault: Bool { isSelectableForChat && isVerified && isDirect }69}7071/// Wording and formatting shared by the Explorer views. Labels only: every value shown comes from the server.72enum ExplorerText {73 static let kinds: [String: String] = ["chat": "Chat", "chat-pro": "Chat pro", "search": "Recherche web", "image": "Image", "tts": "Synthèse vocale", "stt": "Transcription", "embedding": "Embedding", "moderation": "Modération",74 "realtime": "Temps réel", "video": "Vidéo", "legacy-completion": "Complétion (ancien)", "deep-research": "Recherche approfondie", "audio-chat": "Audio"]75 static func kind(_ k: String) -> String { kinds[k] ?? k }7677 static let testOrder = ["basic", "reasoning", "math", "code", "french", "english", "json", "tools", "vision", "longctx", "streaming"]78 static let tests: [String: String] = ["basic": "Base", "reasoning": "Raisonnement", "math": "Maths", "code": "Code", "french": "Français", "english": "Anglais", "json": "JSON", "tools": "Outils", "vision": "Vision",79 "longctx": "Long contexte", "streaming": "Streaming", "image": "Image", "tts": "TTS", "stt": "STT", "embedding": "Embedding", "moderation": "Modération", "audio-chat": "Audio"]8081 static func status(_ m: AIModel) -> (label: String, color: Color, icon: String) {82 switch m.status {83 case "verified": ("Vérifié par le banc", DS.C.ok, "checkmark.seal")84 case "catalog": (m.isLocal ? "MacLustr AI (local) · non testé par le banc" : "Catalogue OpenRouter · non testé par le banc", DS.C.muted, m.isLocal ? "desktopcomputer" : "books.vertical")85 case "unavailable": ("Indisponible", DS.C.danger, "nosign")86 case "unsupported": ("Non pris en charge", DS.C.warn, "questionmark.circle")87 case "untested": ("Non testé", DS.C.muted, "questionmark.circle")88 default: (m.status, DS.C.muted, "questionmark.circle")89 }90 }9192 /// « 3 $ », « 0 $ », « variable » (negative price published for routers) or « — » when no price is published.93 static func price(_ v: Double?) -> String {94 guard let v else { return "—" }95 if v < 0 { return "variable" }96 return v == 0 ? "0 $" : "\(Format.price(v)) $"97 }98 /// Unit prices of the catalogue are published per unit (a token, an image, a search): tiny values keep their digits.99 static func unitPrice(_ v: Double) -> String {100 if v < 0 { return "variable" }101 if v == 0 { return "0 $" }102 if v >= 0.01 { return "\(Format.price(v)) $" }103 let f = NumberFormatter(); f.locale = Locale(identifier: "fr_CA"); f.numberStyle = .decimal; f.maximumSignificantDigits = 3; f.usesSignificantDigits = true104 return "\(f.string(from: NSNumber(value: v)) ?? String(v)) $"105 }106 static func number(_ v: Double, digits: Int = 1) -> String {107 let f = NumberFormatter(); f.locale = Locale(identifier: "fr_CA"); f.numberStyle = .decimal; f.minimumFractionDigits = 0; f.maximumFractionDigits = v == v.rounded() ? 0 : digits108 return f.string(from: NSNumber(value: v)) ?? String(v)109 }110 static func integer(_ v: Int) -> String { number(Double(v), digits: 0) }111 static func date(_ d: Date) -> String { d.formatted(.dateTime.day().month(.abbreviated).year().locale(Locale(identifier: "fr_CA"))) }112 static func dateTime(_ d: Date) -> String { d.formatted(.dateTime.day().month(.abbreviated).year().hour().minute().locale(Locale(identifier: "fr_CA"))) }113114 /// Label of a key of `pricing` (USD per million tokens unless the key says otherwise); unknown keys are shown as sent.115 static func pricingLabel(_ key: String) -> String {116 switch key {117 case "input": "Entrée"; case "output": "Sortie"; case "cachedInput": "Entrée en cache (lecture)"; case "cacheWrite5m": "Écriture du cache (5 min)"; case "cacheWrite1h": "Écriture du cache (1 h)"118 case "imageInput": "Image en entrée"; case "imageOutput": "Image en sortie"; case "imageCachedInput": "Image en cache"; case "audioInput": "Audio en entrée"; case "audioOutput": "Audio en sortie"119 case "perMinute": "Par minute"; case "perMillionCharacters": "Par million de caractères"120 default: key121 }122 }123 /// Order of the keys of `pricing`: the usual ones first, anything else alphabetically after.124 static func pricingKeys(_ pricing: [String: JSONValue]) -> [String] {125 let order = ["input", "output", "cachedInput", "cacheWrite5m", "cacheWrite1h", "imageInput", "imageOutput", "imageCachedInput", "audioInput", "audioOutput", "perMinute", "perMillionCharacters"]126 let numeric = pricing.filter { $0.value.doubleValue != nil }.keys127 return order.filter { numeric.contains($0) } + numeric.filter { !order.contains($0) }.sorted()128 }129 static func pricingSuffix(_ key: String) -> String { switch key { case "perMinute": "/ min"; case "perMillionCharacters": "/ M car."; default: "/ M" } }130131 static func modality(_ m: String) -> String {132 switch m { case "text": "texte"; case "image": "image"; case "audio": "audio"; case "video": "vidéo"; case "file": "fichier"; default: m }133 }134 static func effort(_ e: String) -> String { Effort(rawValue: e)?.label.lowercased() ?? e }135 /// `artificial_analysis` → « Artificial Analysis » (name of a third-party benchmark source, as sent).136 static func sourceLabel(_ source: String) -> String { source.split(separator: "_").map { $0.prefix(1).uppercased() + $0.dropFirst() }.joined(separator: " ") }137 static func route(_ r: String) -> String { Provider.routeLabel(r) }138139 static let priceCeilings: [Double] = [0.5, 1, 3, 5, 15]140 static let contextFloors: [Int] = [32_000, 128_000, 200_000, 400_000, 1_000_000]141}142143extension WindowModel {144 /// « Démarrer une conversation avec ce modèle »: a new, unsaved conversation of this window whose next turn uses the145 /// model (manual routing, no preset). Nothing is sent and the owner's defaults are not rewritten.146 @discardableResult func startConversation(withModel id: String, env: AppEnvironment) -> Bool {147 guard let m = env.catalog.model(id), m.isSelectableForChat else { return false }148 newConversation()149 let chat = env.chat(conversationId: nil, draftKey: draftKey)150 chat.settings.presetId = nil; chat.settings.routingMode = .manual; chat.settings.modelId = m.id151 return true152 }153}154