Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Features/Explorer/ModelDetailView.swift4// Description: Live Model Intelligence (`/api/models/detail`): facts, prices, local bench, figures measured on this5// account, live endpoints, third-party benchmarks under their source name, twins — and the side-by-side6// comparison of 2 to 4 models. Nothing is invented: a block without data is not shown.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10//1112import SwiftUI1314struct ModelDetailView: View {15 let model: AIModel16 @Environment(AppEnvironment.self) private var env17 @Environment(\.accessibilityReduceMotion) private var reduceMotion18 @State private var detail: ModelDetail?19 @State private var error: String?20 @State private var rules: [String: String] = [:]21 @State private var copied = false2223 /// The freshest copy: the detail answer, else the catalogue row (favourite / dock flags stay live).24 private var m: AIModel { env.catalog.model(model.id) ?? detail?.model ?? model }2526 var body: some View {27 ScrollView {28 VStack(alignment: .leading, spacing: 18) {29 hero30 actions31 facts32 prices33 if m.qualityScore != nil || m.p50LatencyMs != nil { bench }34 if let d = detail {35 if let x = d.measured { measured(x) }36 if !d.endpoints.isEmpty { endpoints(d) }37 ForEach(d.benchmarks) { thirdParty($0) }38 if !d.twins.isEmpty { twins(d) }39 if !d.efforts.isEmpty || !d.notes.isEmpty || d.acceptsTemperature != nil { params(d) }40 } else if let error {41 Banner(kind: .warning, text: error)42 } else {43 HStack(spacing: 8) { ProgressView(); Text("Mesures et points de terminaison en direct…").font(.footnote).foregroundStyle(Color.muted) }44 }45 }46 .padding(16)47 .frame(maxWidth: 720).frame(maxWidth: .infinity)48 }49 .background(Color.appBackground)50 .navigationTitle(m.displayName).navigationBarTitleDisplayMode(.inline)51 .task(id: model.id) {52 do { detail = try await env.api.modelDetail(model.id); error = nil } catch let e { error = (e as? APIError)?.message ?? String(localized: "Fiche indisponible.") }53 if rules.isEmpty, let r = try? await env.api.providers() { rules = r.categoryRules }54 }55 .accessibilityElement(children: .contain)56 .accessibilityIdentifier("model.detail")57 }5859 // MARK: hero6061 private var hero: some View {62 VStack(alignment: .leading, spacing: 10) {63 HStack(alignment: .center, spacing: 14) {64 ModelMark(m, size: 40, color: true)65 .frame(width: 68, height: 68).cardSurface(cornerRadius: 18)66 VStack(alignment: .leading, spacing: 4) {67 Text(m.displayName).font(.spDisplay).tracking(-0.4).foregroundStyle(Color.textPrimary).lineLimit(2).minimumScaleFactor(0.7)68 HStack(spacing: 6) { Text(m.creatorName).font(.subheadline).foregroundStyle(Color.textSecondary); RouteBadge(route: m.route) }69 }70 }71 Button { UIPasteboard.general.string = m.id; env.haptics.soften(); copied = true; Task { try? await Task.sleep(for: .seconds(1.5)); copied = false } } label: {72 HStack(spacing: 6) { Text(m.id).font(.system(.caption, design: .monospaced)).lineLimit(1).truncationMode(.middle); Image(systemName: copied ? "checkmark" : "doc.on.doc").font(.caption2).contentTransition(.symbolEffect(.replace)) }73 .foregroundStyle(Color.muted).frame(minHeight: 30).contentShape(.rect)74 }75 .buttonStyle(.plain).accessibilityLabel(String(localized: "Copier l’identifiant \(m.id)"))76 Label(m.isVerified ? String(localized: "Vérifié par le banc d’essai local") : m.isCatalogOnly ? (m.isLocal ? String(localized: "Modèle local MacLustr · non testé par le banc") : String(localized: "Catalogue OpenRouter · non testé par le banc")) : m.status, systemImage: m.isVerified ? "checkmark.seal.fill" : "books.vertical")77 .font(.spCaption).foregroundStyle(m.isVerified ? Color.success : Color.textSecondary)78 .padding(.horizontal, 10).padding(.vertical, 6).background(m.isVerified ? Color.success.opacity(0.12) : Color.surface2, in: .capsule)79 if let d = m.description, !d.isEmpty { Text(d).font(.subheadline).foregroundStyle(Color.textSecondary).fixedSize(horizontal: false, vertical: true) }80 }81 }8283 private var actions: some View {84 let selected = env.preferences.routingMode == .manual && env.catalog.effectiveModelId(preferred: env.preferences.modelId) == m.id85 return ScrollView(.horizontal, showsIndicators: false) {86 HStack(spacing: 8) {87 if m.isSelectableForChat {88 Button { env.haptics.selection(); withAnimation(Motion.smooth(reduceMotion)) { env.select(model: m.id) } } label: {89 Label(selected ? String(localized: "Modèle actuel") : String(localized: "Utiliser"), systemImage: selected ? "checkmark" : "bubble.left.and.text.bubble.right")90 .font(.subheadline.weight(.semibold)).foregroundStyle(selected ? Color.accentColor : .white).padding(.horizontal, 14).frame(minHeight: 40)91 .background(selected ? Color.accentSoft : Color.accentColor, in: .capsule)92 }93 .buttonStyle(PressScale()).accessibilityIdentifier("model.use")94 }95 Button { env.haptics.soften(); Task { await env.catalog.toggleFavorite(m) } } label: { ChipLabel(text: m.favorite ? String(localized: "Favori") : String(localized: "Ajouter aux favoris"), systemImage: m.favorite ? "star.fill" : "star", selected: m.favorite).frame(minHeight: 40) }96 .buttonStyle(PressScale())97 Button { env.haptics.soften(); Task { await env.catalog.toggleDock(m.id) } } label: { ChipLabel(text: env.catalog.isInDock(m.id) ? String(localized: "Dans le dock") : String(localized: "Dock"), systemImage: env.catalog.isInDock(m.id) ? "pin.fill" : "pin", selected: env.catalog.isInDock(m.id)).frame(minHeight: 40) }98 .buttonStyle(PressScale())99 .disabled(!env.catalog.isInDock(m.id) && env.catalog.dock.count >= ModelCatalog.dockLimit)100 }101 }102 }103104 // MARK: blocks105106 private func block<Content: View>(_ title: String, source: String?, @ViewBuilder content: () -> Content) -> some View {107 VStack(alignment: .leading, spacing: 12) {108 Text(title).font(.spHeading).foregroundStyle(Color.textPrimary)109 content()110 if let source, !source.isEmpty { SourceNote(text: source) }111 }112 .padding(14).frame(maxWidth: .infinity, alignment: .leading)113 .cardSurface()114 }115116 private func grid(_ cells: [(String, String, String?)]) -> some View {117 LazyVGrid(columns: [GridItem(.adaptive(minimum: 104), spacing: 12, alignment: .topLeading)], alignment: .leading, spacing: 14) {118 ForEach(Array(cells.enumerated()), id: \.offset) { _, c in FactCell(title: c.0, value: c.1, note: c.2) }119 }120 }121122 private var facts: some View {123 var cells: [(String, String, String?)] = []124 if let c = m.contextWindow { cells.append((String(localized: "Contexte"), Format.tokens(c), String(localized: "jetons"))) }125 if let o = m.maxOutputTokens { cells.append((String(localized: "Sortie max."), Format.tokens(o), String(localized: "jetons"))) }126 if let cat = m.catalog {127 if !cat.inputModalities.isEmpty { cells.append((String(localized: "Entrées"), cat.inputModalities.joined(separator: ", "), nil)) }128 if !cat.outputModalities.isEmpty { cells.append((String(localized: "Sorties"), cat.outputModalities.joined(separator: ", "), nil)) }129 if let t = cat.tokenizer { cells.append((String(localized: "Tokeniseur"), t, nil)) }130 if let d = cat.createdDate { cells.append((String(localized: "Publié"), d.formatted(.dateTime.day().month(.abbreviated).year()), nil)) }131 if let hf = cat.huggingFaceId, !hf.isEmpty { cells.append((String(localized: "Poids ouverts"), hf, "Hugging Face")) }132 if let mod = cat.moderated { cells.append((String(localized: "Modération"), mod ? String(localized: "oui") : String(localized: "non"), nil)) }133 if let e = cat.expirationDate { cells.append((String(localized: "Retrait prévu"), e, nil)) }134 if let a = cat.aliasOf { cells.append((String(localized: "Alias de"), a, nil)) }135 if let q = cat.quantization { cells.append((String(localized: "Quantification"), q, nil)) }136 if let l = cat.license { cells.append((String(localized: "Licence"), l, nil)) }137 if let r = cat.revision { cells.append((String(localized: "Révision"), r, nil)) }138 if let s = cat.servedBy { cells.append((String(localized: "Servi par"), s, nil)) }139 if let r = cat.reasoning, let e = r.efforts, !e.isEmpty { cells.append((String(localized: "Raisonnement"), e.joined(separator: " · "), r.mandatory == true ? String(localized: "obligatoire") : nil)) }140 }141 return block(String(localized: "Faits"), source: m.isOpenRouter ? String(localized: "Catalogue OpenRouter") : m.isLocal ? String(localized: "Service local MacLustr AI (liste publiée par le service)") : String(localized: "Registre du serveur (listes des fournisseurs, banc local)")) {142 if !cells.isEmpty { grid(cells) }143 let caps = ModelCapability.allCases.filter { $0.holds(for: m) }144 if !caps.isEmpty {145 FlowChips(items: caps.map { ($0.label, $0.symbol) })146 }147 if !m.categories.isEmpty {148 VStack(alignment: .leading, spacing: 6) {149 ForEach(ModelQuery.categoryOrder.filter(m.categories.contains) + m.categories.filter { !ModelQuery.categoryOrder.contains($0) }, id: \.self) { c in150 HStack(alignment: .firstTextBaseline, spacing: 8) {151 Text(ModelQuery.categoryLabel(c)).font(.spCaption).foregroundStyle(Color.accentColor).padding(.horizontal, 8).padding(.vertical, 3).background(Color.accentSoft, in: .capsule).fixedSize()152 if let r = rules[c] { Text(r).font(.caption2).foregroundStyle(Color.muted) }153 }154 }155 }156 }157 }158 }159160 @ViewBuilder private var prices: some View {161 if m.priceInput != nil || m.priceOutput != nil {162 block(String(localized: "Prix"), source: m.priceNotes ?? (m.isOpenRouter ? String(localized: "Prix publié par le catalogue OpenRouter") : m.isLocal ? String(localized: "Inférence locale : aucun coût par jeton") : String(localized: "Prix de liste vérifié (USD par million de jetons)"))) {163 grid([164 m.priceInput.map { (String(localized: "Entrée"), "\(Format.price($0)) $", String(localized: "par M de jetons")) },165 m.priceOutput.map { (String(localized: "Sortie"), "\(Format.price($0)) $", String(localized: "par M de jetons")) },166 m.priceCachedInput.map { (String(localized: "Entrée en cache"), "\(Format.price($0)) $", String(localized: "par M de jetons")) },167 ].compactMap { $0 })168 }169 }170 }171172 private var bench: some View {173 block(String(localized: "Banc d’essai local"), source: String(localized: "Banc d’essai de SP Chat, exécuté sur le serveur")) {174 grid([175 m.qualityScore.map { (String(localized: "Qualité"), String(format: "%.0f / 100", $0), nil) },176 m.p50LatencyMs.map { (String(localized: "Durée médiane"), Format.duration(ms: $0), nil) },177 m.p50TtftMs.map { (String(localized: "1ᵉʳ jeton médian"), Format.duration(ms: $0), nil) },178 ].compactMap { $0 })179 }180 }181182 private func measured(_ x: ModelDetail.Measured) -> some View {183 block(String(localized: "Mesuré sur ce compte"), source: x.source) {184 grid([185 (String(localized: "Demandes"), x.requests.formatted(), x.errors > 0 ? String(localized: "\(x.errors) erreur(s)") : nil) as (String, String, String?)?,186 x.p50LatencyMs.map { (String(localized: "Durée médiane"), Format.duration(ms: $0), nil) },187 x.p50TtftMs.map { (String(localized: "1ᵉʳ jeton médian"), Format.duration(ms: $0), nil) },188 x.tokensPerSec.map { (String(localized: "Débit"), String(format: "%.0f", $0), String(localized: "jetons / s")) },189 x.costUsd.map { (String(localized: "Coût cumulé"), Format.usd($0), nil) },190 x.lastUsed.map { (String(localized: "Dernier usage"), Format.relative($0), nil) },191 ].compactMap { $0 })192 }193 }194195 private func endpoints(_ d: ModelDetail) -> some View {196 block(String(localized: "Points de terminaison en direct"), source: d.endpointsSource) {197 VStack(spacing: 0) {198 ForEach(Array(d.endpoints.enumerated()), id: \.element.id) { i, e in199 if i > 0 { Divider() }200 VStack(alignment: .leading, spacing: 4) {201 HStack {202 Text(e.provider).font(.subheadline.weight(.medium)).foregroundStyle(Color.textPrimary).lineLimit(1)203 Text(e.id).font(.caption2.monospaced()).foregroundStyle(Color.muted).lineLimit(1)204 Spacer(minLength: 4)205 if let u = e.uptimeLast30m { Text(String(format: "%.0f %%", u)).font(.caption.monospacedDigit().weight(.medium)).foregroundStyle(u >= 99 ? Color.success : u >= 90 ? Color.warning : Color.danger).accessibilityLabel(String(localized: "disponibilité 30 minutes : \(Int(u)) %")) }206 }207 HStack(spacing: 8) {208 if let i = e.inputPerM, let o = e.outputPerM { Text("\(Format.price(i)) / \(Format.price(o)) $") }209 if let c = e.contextLength { Text(Format.tokens(c)) }210 if let q = e.quantization, q != "unknown" { Text(q) }211 if e.supportsTools == true { Image(systemName: "wrench.and.screwdriver").accessibilityLabel(String(localized: "outils")) }212 }213 .font(.caption.monospacedDigit()).foregroundStyle(Color.muted)214 }215 .padding(.vertical, 8)216 .accessibilityElement(children: .combine)217 }218 }219 Text("Disponibilité sur les 30 dernières minutes ; prix en USD par million de jetons (entrée / sortie).").font(.caption2).foregroundStyle(Color.muted)220 }221 }222223 private func thirdParty(_ set: ModelDetail.BenchmarkSet) -> some View {224 block(String(localized: "Bancs d’essai tiers"), source: String(localized: "Source : \(set.source), transmis par le catalogue OpenRouter — non vérifié par SP Chat")) {225 grid(set.figures.map { (Self.humanize($0.name), String(format: $0.value.rounded() == $0.value ? "%.0f" : "%.1f", $0.value), nil) })226 }227 }228229 private func twins(_ d: ModelDetail) -> some View {230 block(String(localized: "Le même modèle par une autre route"), source: String(localized: "Registre du serveur : les deux routes restent distinctes, jamais fusionnées")) {231 ForEach(d.twins) { t in232 if let tm = env.catalog.model(t.id) {233 NavigationLink(value: tm) { twinRow(t) }.buttonStyle(.plain)234 } else { twinRow(t) }235 }236 }237 }238 private func twinRow(_ t: ModelDetail.Twin) -> some View {239 HStack(spacing: 8) {240 ModelMark(logo: m.logo, name: m.creatorName, size: 18)241 Text(t.displayName).font(.subheadline.weight(.medium)).foregroundStyle(Color.textPrimary).lineLimit(1)242 RouteBadge(route: t.route)243 if t.route == "direct" { Text("direct").font(.caption2).foregroundStyle(Color.muted) }244 Spacer(minLength: 4)245 if let i = t.priceInput, let o = t.priceOutput { Text("\(Format.price(i)) / \(Format.price(o)) $").font(.caption.monospacedDigit()).foregroundStyle(Color.muted) }246 Image(systemName: "chevron.right").font(.caption2.weight(.bold)).foregroundStyle(Color.muted)247 }248 .frame(minHeight: 40).contentShape(.rect)249 }250251 private func params(_ d: ModelDetail) -> some View {252 block(String(localized: "Paramètres acceptés"), source: String(localized: "Règles du serveur pour ce modèle")) {253 if !d.efforts.isEmpty { LabeledContent(String(localized: "Efforts"), value: d.efforts.joined(separator: " · ")).font(.subheadline) }254 if let t = d.acceptsTemperature { LabeledContent(String(localized: "Température"), value: t ? String(localized: "acceptée") : String(localized: "fixée par le fournisseur")).font(.subheadline) }255 ForEach(d.notes.keys.sorted(), id: \.self) { k in Text(d.notes[k] ?? "").font(.caption).foregroundStyle(Color.muted) }256 }257 }258259 static func humanize(_ key: String) -> String { key.replacingOccurrences(of: "_", with: " ").replacingOccurrences(of: " index", with: "").capitalized }260}261262/// Wrapping row of small labelled glyph chips.263struct FlowChips: View {264 let items: [(String, String)]265 var body: some View {266 ViewThatFits(in: .horizontal) {267 HStack(spacing: 6) { chips }268 VStack(alignment: .leading, spacing: 6) { HStack(spacing: 6) { chips(0..<min(3, items.count)) }; if items.count > 3 { HStack(spacing: 6) { chips(3..<items.count) } } }269 }270 }271 @ViewBuilder private var chips: some View { chips(0..<items.count) }272 private func chips(_ r: Range<Int>) -> some View {273 ForEach(Array(r), id: \.self) { i in274 Label(items[i].0, systemImage: items[i].1).font(.spCaption).foregroundStyle(Color.textSecondary).padding(.horizontal, 9).padding(.vertical, 5).background(Color.surface2, in: .capsule).fixedSize()275 }276 }277}278279/// 2 to 4 models side by side, attribute by attribute. Figures: catalogue or local bench — the footer says which.280struct ModelCompareView: View {281 let models: [AIModel]282 @Environment(AppEnvironment.self) private var env283 @Environment(\.dismiss) private var dismiss284285 private struct Line: Identifiable { var id: String; var title: String; var values: [String]; var best: Int? }286287 private var lines: [Line] {288 func line(_ title: String, _ value: (AIModel) -> String?, best: ((AIModel) -> Double?)? = nil, lowerIsBetter: Bool = true) -> Line? {289 let values = models.map { value($0) ?? "—" }290 guard values.contains(where: { $0 != "—" }) else { return nil }291 var bestIndex: Int?292 if let best {293 let scored = models.enumerated().compactMap { i, m in best(m).map { (i, $0) } }294 if scored.count >= 2, Set(scored.map(\.1)).count > 1 { bestIndex = (lowerIsBetter ? scored.min { $0.1 < $1.1 } : scored.max { $0.1 < $1.1 })?.0 }295 }296 return Line(id: title, title: title, values: values, best: bestIndex)297 }298 return [299 line(String(localized: "Route")) { AIModel.routeLabel($0.route) },300 line(String(localized: "État")) { $0.isVerified ? String(localized: "vérifié") : $0.isCatalogOnly ? String(localized: "catalogue") : $0.status },301 line(String(localized: "Contexte"), { $0.contextLabel }, best: { $0.contextWindow.map(Double.init) }, lowerIsBetter: false),302 line(String(localized: "Sortie max."), { $0.maxOutputTokens.map { Format.tokens($0) } }, best: { $0.maxOutputTokens.map(Double.init) }, lowerIsBetter: false),303 line(String(localized: "Prix entrée"), { $0.priceInput.map { "\(Format.price($0)) $" } }, best: { $0.priceInput }),304 line(String(localized: "Prix sortie"), { $0.priceOutput.map { "\(Format.price($0)) $" } }, best: { $0.priceOutput }),305 line(String(localized: "Cache"), { $0.priceCachedInput.map { "\(Format.price($0)) $" } }, best: { $0.priceCachedInput }),306 line(String(localized: "Qualité (banc)"), { $0.qualityScore.map { String(format: "%.0f", $0) } }, best: { $0.qualityScore }, lowerIsBetter: false),307 line(String(localized: "1ᵉʳ jeton (banc)"), { $0.p50TtftMs.map { Format.duration(ms: $0) } }, best: { $0.p50TtftMs.map(Double.init) }),308 line(String(localized: "Durée (banc)"), { $0.p50LatencyMs.map { Format.duration(ms: $0) } }, best: { $0.p50LatencyMs.map(Double.init) }),309 line(String(localized: "Vision")) { $0.vision ? "✓" : "—" }, line(String(localized: "Raisonnement")) { $0.reasoning ? "✓" : "—" },310 line(String(localized: "Outils")) { $0.tools ? "✓" : "—" }, line(String(localized: "Audio")) { $0.audioInput ? "✓" : "—" },311 line(String(localized: "Images")) { $0.imageGeneration ? "✓" : "—" }, line(String(localized: "JSON structuré")) { $0.structuredOutput ? "✓" : "—" },312 line(String(localized: "Poids ouverts")) { $0.isOpenWeight ? "✓" : "—" },313 line(String(localized: "Publié")) { $0.catalog?.createdDate?.formatted(.dateTime.month(.abbreviated).year()) },314 ].compactMap { $0 }315 }316317 var body: some View {318 NavigationStack {319 ScrollView {320 Grid(alignment: .leading, horizontalSpacing: 8, verticalSpacing: 0) {321 GridRow(alignment: .bottom) {322 Color.clear.frame(width: 84, height: 1)323 ForEach(models) { m in324 VStack(spacing: 6) {325 ModelMark(m, size: 26, color: true)326 Text(m.displayName).font(.caption.weight(.semibold)).foregroundStyle(Color.textPrimary).multilineTextAlignment(.center).lineLimit(3).minimumScaleFactor(0.8)327 RouteBadge(route: m.route)328 }329 .frame(maxWidth: .infinity)330 .accessibilityElement(children: .combine)331 }332 }333 .padding(.bottom, 12)334 ForEach(lines) { l in335 Divider().gridCellColumns(models.count + 1)336 GridRow(alignment: .firstTextBaseline) {337 Text(l.title).font(.caption).foregroundStyle(Color.muted).frame(width: 84, alignment: .leading)338 ForEach(Array(l.values.enumerated()), id: \.offset) { i, v in339 Text(v).font(.footnote.monospacedDigit().weight(l.best == i ? .semibold : .regular))340 .foregroundStyle(l.best == i ? Color.accentColor : Color.textPrimary)341 .frame(maxWidth: .infinity).multilineTextAlignment(.center).lineLimit(2).minimumScaleFactor(0.75)342 }343 }344 .padding(.vertical, 10)345 .accessibilityElement(children: .combine)346 }347 }348 .padding(16)349 VStack(alignment: .leading, spacing: 6) {350 SourceNote(text: String(localized: "Prix : liste vérifiée (route directe) ou catalogue OpenRouter, en USD par million de jetons. « Banc » = banc d’essai local ; un modèle du catalogue non testé n’a pas ces mesures."))351 Text("La valeur en iris est la plus favorable de la ligne.").font(.caption2).foregroundStyle(Color.muted)352 }353 .padding(.horizontal, 16).padding(.bottom, 24)354 }355 .background(Color.appBackground)356 .navigationTitle("Comparaison").navigationBarTitleDisplayMode(.inline)357 .toolbar {358 ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() } }359 ToolbarItem(placement: .primaryAction) {360 Button { env.router.arenaSeed = ArenaSeed(); env.router.arenaModelIds = models.map(\.id); dismiss(); Task { try? await Task.sleep(for: .milliseconds(450)); env.router.sheet = .arena } } label: { Label("Arène", systemImage: "square.split.2x1") }361 .accessibilityLabel(String(localized: "Lancer ces modèles dans l’Arène"))362 }363 }364 }365 }366}367