Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Workspace/ExplorerDetail.swift3// Description: Live Model Intelligence sheet of the Explorer: catalogue facts, published prices, accepted parameters, figures measured on this account, live endpoints, third-party benchmarks, twins and the local benchmark — each block with its source.4import SwiftUI5import SPChatCore67struct ModelDetailView: View {8 @Bindable var window: WindowModel9 var explorer: ExplorerModel?10 let close: () -> Void11 @Environment(AppEnvironment.self) private var env12 /// Models visited in this sheet (a twin opens on top of the model it was reached from).13 @State private var history: [String]14 @State private var detail: ModelDetail?15 @State private var loadError: String?16 @State private var loading = false1718 init(modelId: String, window: WindowModel, explorer: ExplorerModel? = nil, preloaded: ModelDetail? = nil, close: @escaping () -> Void) {19 self.window = window; self.explorer = explorer; self.close = close20 _history = State(initialValue: [modelId]); _detail = State(initialValue: preloaded)21 }2223 private var currentId: String { history.last ?? "" }24 /// Full row of the detail payload once loaded, else the catalogue row (instant, also offline).25 private var facts: AIModel? { if let d = detail, d.model.id == currentId { return d.model }; return env.catalog.model(currentId) }26 /// Favourite / hidden flags follow the shared catalogue so that a toggle shows at once.27 private var live: AIModel? { env.catalog.model(currentId) ?? facts }28 private var loaded: ModelDetail? { detail?.model.id == currentId ? detail : nil }2930 var body: some View {31 VStack(spacing: 0) {32 topBar33 Rectangle().fill(DS.C.border).frame(height: 1)34 if let m = facts {35 ScrollView {36 VStack(alignment: .leading, spacing: 22) {37 hero(m)38 if let reason = m.unavailableReason, !reason.isEmpty { Banner(kind: m.status == "unavailable" ? .error : .info, text: reason) }39 if let error = loadError { Banner(kind: .warning, text: "Les données en direct n'ont pas pu être chargées : \(error)", actionTitle: "Réessayer") { Task { await load() } } }40 if let d = m.description, !d.isEmpty { description(d, m) }41 factsBlock(m)42 pricesBlock(m)43 if let p = loaded?.params { paramsBlock(p) }44 if let x = loaded?.measured { measuredBlock(x) }45 if let e = loaded?.endpoints, !e.list.isEmpty { endpointsBlock(e) }46 if let b = loaded?.thirdPartyBenchmarks, !b.isEmpty { thirdPartyBlock(b) }47 if let t = loaded?.twins, !t.isEmpty { twinsBlock(t) }48 if let b = m.benchmark { localBenchmarkBlock(b, m) }49 if loading, loaded == nil {50 HStack(spacing: 8) { ProgressView().controlSize(.small); Text("Chargement des données en direct…").font(DS.F.caption).foregroundStyle(DS.C.muted) }51 }52 }53 .padding(.horizontal, 28).padding(.vertical, 22).frame(maxWidth: .infinity, alignment: .leading)54 }55 } else if loading {56 ProgressView("Chargement du modèle…").frame(maxWidth: .infinity, maxHeight: .infinity)57 } else {58 EmptyStateView(systemImage: "questionmark.circle", title: "Modèle introuvable", message: loadError ?? "« \(currentId) » ne figure plus au catalogue.").frame(maxWidth: .infinity, maxHeight: .infinity)59 }60 }61 .frame(minWidth: 760, idealWidth: 800, minHeight: 520, idealHeight: 740)62 .background(DS.C.bg)63 .task(id: currentId) { await load() }64 }6566 // MARK: Chrome6768 private var topBar: some View {69 HStack(spacing: 8) {70 if history.count > 1 {71 Button { history.removeLast() } label: { Label(env.catalog.identity(for: history[history.count - 2], short: true).name, systemImage: "chevron.left") }72 .buttonStyle(.plain).font(DS.F.ui).foregroundStyle(DS.C.accent).accessibilityLabel("Revenir au modèle précédent")73 }74 Text("Fiche du modèle").font(DS.F.micro).tracking(0.5).textCase(.uppercase).foregroundStyle(DS.C.muted)75 Spacer()76 Button("Fermer", action: close).keyboardShortcut(.cancelAction).controlSize(.small)77 }78 .padding(.horizontal, 20).frame(height: 44).background(DS.C.bgElev)79 }8081 private func hero(_ m: AIModel) -> some View {82 let status = ExplorerText.status(m)83 let flags = live ?? m84 return VStack(alignment: .leading, spacing: 16) {85 HStack(alignment: .top, spacing: 16) {86 ModelMark(m, size: 40, colored: true)87 VStack(alignment: .leading, spacing: 5) {88 HStack(alignment: .firstTextBaseline, spacing: 8) {89 Text(m.displayName).font(DS.F.title).tracking(-0.3).foregroundStyle(DS.C.text).lineLimit(2).textSelection(.enabled)90 RouteBadge(route: m.route)91 if env.catalog.models.defaultModel == m.id { Tag(text: "défaut", color: DS.C.accent) }92 if flags.hidden { Tag(text: "masqué") }93 }94 HStack(spacing: 6) {95 Text(m.creatorName).font(DS.F.ui).foregroundStyle(DS.C.text2)96 Text("·").foregroundStyle(DS.C.muted)97 Label(status.label, systemImage: status.icon).font(DS.F.caption).foregroundStyle(status.color)98 }99 Text(m.id).font(DS.F.mono(11.5)).foregroundStyle(DS.C.muted).textSelection(.enabled).lineLimit(1)100 }101 Spacer(minLength: 0)102 }103 HStack(spacing: 8) {104 if m.isSelectableForChat {105 Button { if window.startConversation(withModel: m.id, env: env) { close() } } label: { Label("Démarrer une conversation", systemImage: "plus.bubble") }106 .buttonStyle(.borderedProminent).tint(DS.C.accent).accessibilityIdentifier("detail-start")107 }108 Button { toggleFavorite(flags) } label: { Label(flags.favorite ? "Favori" : "Mettre en favori", systemImage: flags.favorite ? "star.fill" : "star") }109 if m.isSelectableForChat {110 let inDock = env.catalog.models.dock.contains(m.id)111 Button { toggleDock(m) } label: { Label(inDock ? "Dans le dock" : "Ajouter au dock", systemImage: "dock.rectangle") }112 .disabled(!inDock && env.catalog.models.dock.count >= 8).help(inDock ? "Retirer du dock" : "Le dock contient jusqu'à 8 modèles, partagés entre les apps")113 }114 if let explorer {115 let compared = explorer.isCompared(m.id)116 Button { if !explorer.toggleCompare(m.id) { env.toasts.show("La comparaison est limitée à \(ExplorerModel.maxCompare) modèles.", isError: true) } } label: {117 Label(compared ? "Dans la comparaison" : "Comparer", systemImage: compared ? "checkmark.rectangle.stack.fill" : "rectangle.stack.badge.plus")118 }119 .disabled(!compared && explorer.compareIsFull)120 }121 Spacer(minLength: 0)122 Menu {123 if m.canBeDefault { Button("Définir par défaut") { makeDefault(m) }.disabled(env.catalog.models.defaultModel == m.id) }124 Button(flags.hidden ? "Réafficher dans le sélecteur" : "Masquer du sélecteur") { toggleHidden(flags) }125 Divider()126 Button("Copier l'identifiant") { NSPasteboard.general.clearContents(); NSPasteboard.general.setString(m.id, forType: .string) }127 } label: { Image(systemName: "ellipsis.circle") }128 .menuStyle(.borderlessButton).fixedSize().accessibilityLabel("Autres actions")129 }130 .controlSize(.regular)131 }132 }133134 // MARK: Blocks135136 private func description(_ text: String, _ m: AIModel) -> some View {137 DetailSection(title: "Description", source: m.isLocal ? "MacLustr AI (local)" : m.catalog?.source == "openrouter" || m.isOpenRouter ? "Catalogue OpenRouter" : nil) {138 Text(text).font(.system(size: 13)).foregroundStyle(DS.C.text2).lineSpacing(3).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)139 }140 }141142 private func factsBlock(_ m: AIModel) -> some View {143 var rows: [Fact] = [Fact("Fabricant", m.creatorName), Fact("Route", ExplorerText.route(m.route)), Fact("Exécuté par", Provider.label(m.provider)), Fact("Type", ExplorerText.kind(m.kind))]144 if let c = m.contextWindow { rows.append(Fact("Fenêtre de contexte", "\(ExplorerText.integer(c)) jetons")) }145 if let o = m.maxOutputTokens { rows.append(Fact("Sortie maximale", "\(ExplorerText.integer(o)) jetons")) }146 if let d = m.lastVerifiedAt { rows.append(Fact("Dernière vérification", ExplorerText.dateTime(d))) }147 if let d = m.lastUsedAt { rows.append(Fact("Dernière utilisation", ExplorerText.dateTime(d))) }148 if let c = m.catalog {149 if !c.slug.isEmpty { rows.append(Fact("Identifiant catalogue", c.slug, mono: true)) }150 if !c.inputModalities.isEmpty { rows.append(Fact("Entrées", c.inputModalities.map(ExplorerText.modality).joined(separator: ", "))) }151 if !c.outputModalities.isEmpty { rows.append(Fact("Sorties", c.outputModalities.map(ExplorerText.modality).joined(separator: ", "))) }152 if let t = c.tokenizer { rows.append(Fact("Tokeniseur", t)) }153 if let h = c.huggingFaceId, !h.isEmpty { rows.append(Fact("Hugging Face", h, mono: true)) }154 if let q = c.quantization, !q.isEmpty { rows.append(Fact("Quantification", q)) }155 if let l = c.license, !l.isEmpty { rows.append(Fact("Licence", l)) }156 if let r = c.revision, !r.isEmpty { rows.append(Fact("Révision", r, mono: true)) }157 if let s = c.servedBy, !s.isEmpty { rows.append(Fact("Servi par", s)) }158 if let mod = c.moderated { rows.append(Fact("Modération du fournisseur", mod ? "oui" : "non")) }159 if let d = m.publishedAt { rows.append(Fact("Publié le", ExplorerText.date(d))) }160 if let e = c.expirationDate, !e.isEmpty { rows.append(Fact("Expiration", e)) }161 if let a = c.aliasOf, !a.isEmpty { rows.append(Fact("Alias de", a, mono: true)) }162 if let r = c.reasoning {163 if let efforts = r.efforts, !efforts.isEmpty { rows.append(Fact("Efforts de raisonnement", efforts.map(ExplorerText.effort).joined(separator: ", "))) }164 if let d = r.defaultEffort { rows.append(Fact("Effort par défaut", ExplorerText.effort(d))) }165 if let mandatory = r.mandatory { rows.append(Fact("Raisonnement obligatoire", mandatory ? "oui" : "non")) }166 }167 if !c.rankedIn.isEmpty { rows.append(Fact("Classements d'usage OpenRouter", c.rankedIn.joined(separator: ", "))) }168 } else if let levels = m.effortLevels, !levels.isEmpty {169 rows.append(Fact("Efforts de raisonnement", levels.map(ExplorerText.effort).joined(separator: ", ")))170 }171 let capabilities = ModelFacet.capabilities.filter { m.has($0) } + ["audioOutput", "streaming"].filter { m.has($0) }172 return DetailSection(title: "Faits", source: m.isLocal ? "MacLustr AI (service local)" : m.catalog != nil ? "Catalogue OpenRouter" : "Registre de SP Chat") {173 VStack(alignment: .leading, spacing: 14) {174 FactGrid(rows: rows)175 if !capabilities.isEmpty {176 ChipLine(title: "Capacités") {177 ForEach(capabilities, id: \.self) { c in Label(ModelFacet.capabilityLabel(c), systemImage: ModelFacet.capabilitySymbol(c)).modifier(QuietChip()) }178 }179 }180 if !m.categories.isEmpty {181 ChipLine(title: "Catégories") {182 ForEach(m.categories, id: \.self) { c in183 Label(ModelFacet.label(c), systemImage: ModelFacet.symbol(c)).modifier(QuietChip()).help(explorer?.categoryRules[c] ?? rules[c] ?? ModelFacet.label(c))184 }185 }186 }187 if let p = m.catalog?.supportedParameters, !p.isEmpty {188 ChipLine(title: "Paramètres pris en charge") { ForEach(p, id: \.self) { Text($0).font(DS.F.mono(10.5)).modifier(QuietChip()) } }189 }190 }191 }192 }193194 private func pricesBlock(_ m: AIModel) -> some View {195 let pricing = m.pricing ?? [:]196 let keys = ExplorerText.pricingKeys(pricing)197 let tiers = pricing["tiers"]?.arrayValue ?? []198 let units = (m.catalog?.prices ?? [:]).sorted { $0.key < $1.key }199 return Group {200 if !keys.isEmpty || !tiers.isEmpty || !units.isEmpty || m.pricingNotes != nil {201 DetailSection(title: "Prix publiés", source: m.isOpenRouter ? "Catalogue OpenRouter · USD par million de jetons" : "Liste de prix vérifiée · USD par million de jetons") {202 VStack(alignment: .leading, spacing: 12) {203 if !keys.isEmpty {204 FigureGrid {205 ForEach(keys, id: \.self) { k in206 SourcedFigure(label: ExplorerText.pricingLabel(k), value: pricing[k]?.doubleValue.map { v in v < 0 ? "variable" : "\(ExplorerText.price(v)) \(ExplorerText.pricingSuffix(k))" } ?? "—")207 }208 }209 }210 if let unit = pricing["unit"]?.stringValue { Text("Unité : \(unit)").font(DS.F.caption).foregroundStyle(DS.C.text2) }211 ForEach(Array(tiers.enumerated()), id: \.offset) { _, tier in Text(tierText(tier)).font(.system(size: 12).monospacedDigit()).foregroundStyle(DS.C.text2) }212 if !units.isEmpty {213 VStack(alignment: .leading, spacing: 6) {214 Text("Prix unitaires du catalogue (USD par unité, tels que publiés)").font(DS.F.caption).foregroundStyle(DS.C.muted)215 FactGrid(rows: units.map { Fact($0.key, ExplorerText.unitPrice($0.value), monoLabel: true) })216 }217 }218 if let notes = m.pricingNotes, !notes.isEmpty { Text(notes).font(DS.F.caption).foregroundStyle(DS.C.muted).textSelection(.enabled) }219 }220 }221 }222 }223 }224225 private func tierText(_ tier: JSONValue) -> String {226 var parts: [String] = []227 if let min = tier["minPromptTokens"]?.doubleValue { parts.append("Prompt d'au moins \(Format.tokens(Int(min))) jetons :") }228 if let i = tier["input"]?.doubleValue { parts.append("entrée \(ExplorerText.price(i)) / M") }229 if let o = tier["output"]?.doubleValue { parts.append("sortie \(ExplorerText.price(o)) / M") }230 for (k, v) in (tier.objectValue ?? [:]).sorted(by: { $0.key < $1.key }) where !["minPromptTokens", "input", "output"].contains(k) {231 if let d = v.doubleValue { parts.append("\(ExplorerText.pricingLabel(k).lowercased()) \(ExplorerText.price(d))") }232 }233 return parts.joined(separator: " ")234 }235236 private func paramsBlock(_ p: ModelDetail.Params) -> some View {237 var rows: [Fact] = []238 if !p.effort.isEmpty { rows.append(Fact("Efforts acceptés", p.effort.map(ExplorerText.effort).joined(separator: ", "))) }239 if !p.effortAlias.isEmpty { rows.append(Fact("Équivalences d'effort", p.effortAlias.sorted { $0.key < $1.key }.map { "\(ExplorerText.effort($0.key)) → \(ExplorerText.effort($0.value))" }.joined(separator: ", "))) }240 if let t = p.temperature { rows.append(Fact("Température réglable", t ? "oui" : "non")) }241 if let r = p.reasoningSummary { rows.append(Fact("Résumé du raisonnement", r ? "oui" : "non")) }242 return Group {243 if !rows.isEmpty || !p.notes.isEmpty {244 DetailSection(title: "Paramètres acceptés", source: "Serveur SP Chat") {245 VStack(alignment: .leading, spacing: 8) {246 FactGrid(rows: rows)247 ForEach(p.notes.sorted { $0.key < $1.key }, id: \.key) { _, note in Text(note).font(DS.F.caption).foregroundStyle(DS.C.muted).fixedSize(horizontal: false, vertical: true) }248 }249 }250 }251 }252 }253254 private func measuredBlock(_ x: ModelDetail.Measured) -> some View {255 DetailSection(title: "Mesuré sur ce compte", source: x.source.isEmpty ? nil : x.source) {256 if x.requests == 0 {257 Text("Aucune requête enregistrée avec ce modèle.").font(DS.F.caption).foregroundStyle(DS.C.muted)258 } else {259 FigureGrid {260 SourcedFigure(label: "Requêtes", value: ExplorerText.integer(x.requests))261 SourcedFigure(label: "Erreurs", value: ExplorerText.integer(x.errors))262 if let v = x.p50LatencyMs { SourcedFigure(label: "Durée médiane (p50)", value: Format.duration(ms: Int(v.rounded()))) }263 if let v = x.p50TtftMs { SourcedFigure(label: "Premier jeton (p50)", value: Format.duration(ms: Int(v.rounded()))) }264 if let v = x.tokensPerSec { SourcedFigure(label: "Débit", value: "\(ExplorerText.number(v, digits: 0)) jetons/s") }265 if let v = x.costUsd { SourcedFigure(label: "Coût cumulé", value: Format.usd(v)) }266 if let v = x.inputTokens { SourcedFigure(label: "Jetons en entrée", value: Format.tokens(v)) }267 if let v = x.outputTokens { SourcedFigure(label: "Jetons en sortie", value: Format.tokens(v)) }268 if let v = x.firstUsed { SourcedFigure(label: "Première utilisation", value: ExplorerText.date(v)) }269 if let v = x.lastUsed { SourcedFigure(label: "Dernière utilisation", value: ExplorerText.date(v)) }270 }271 }272 }273 }274275 private func endpointsBlock(_ e: ModelDetail.Endpoints) -> some View {276 DetailSection(title: "Points de terminaison en direct", source: e.source.isEmpty ? nil : e.source) {277 Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 0) {278 GridRow {279 Text("Fournisseur"); Text("Contexte").gridColumnAlignment(.trailing); Text("Sortie max").gridColumnAlignment(.trailing)280 Text("Entrée / M").gridColumnAlignment(.trailing); Text("Sortie / M").gridColumnAlignment(.trailing); Text("Dispo. 30 min").gridColumnAlignment(.trailing); Text("Outils").gridColumnAlignment(.center)281 }282 .font(DS.F.micro).textCase(.uppercase).foregroundStyle(DS.C.muted).padding(.bottom, 6)283 ForEach(Array(e.list.enumerated()), id: \.offset) { _, p in284 Rectangle().fill(DS.C.border.opacity(0.7)).frame(height: 1).gridCellColumns(7)285 GridRow {286 VStack(alignment: .leading, spacing: 1) {287 Text(p.provider).font(.system(size: 12, weight: .medium)).foregroundStyle(DS.C.text).lineLimit(1)288 if let tag = p.tag { Text(tag + (quantization(p).map { " · \($0)" } ?? "")).font(DS.F.mono(10)).foregroundStyle(DS.C.muted).lineLimit(1) }289 }290 Text(p.contextLength.map { Format.tokens($0) } ?? "—")291 Text(p.maxCompletionTokens.map { Format.tokens($0) } ?? "—")292 Text(ExplorerText.price(p.inputPerM))293 Text(ExplorerText.price(p.outputPerM))294 Text(p.uptimeLast30m.map { "\(ExplorerText.number($0)) %" } ?? "—")295 Group {296 if let t = p.supportsTools { Image(systemName: t ? "checkmark" : "minus").foregroundStyle(t ? DS.C.ok : DS.C.muted).accessibilityLabel(t ? "Outils pris en charge" : "Outils non pris en charge") } else { Text("—") }297 }298 }299 .font(.system(size: 12).monospacedDigit()).foregroundStyle(DS.C.text2).padding(.vertical, 6)300 }301 }302 }303 }304 private func quantization(_ p: ModelDetail.Endpoint) -> String? { guard let q = p.quantization, !q.isEmpty, q != "unknown" else { return nil }; return q }305306 private func thirdPartyBlock(_ sources: [ModelDetail.BenchmarkSource]) -> some View {307 DetailSection(title: "Bancs d'essai tiers", source: "Transmis par le catalogue OpenRouter, non vérifiés par SP Chat") {308 VStack(alignment: .leading, spacing: 14) {309 ForEach(sources) { s in310 VStack(alignment: .leading, spacing: 8) {311 Text("Source : \(s.sourceLabel)").font(DS.F.caption).foregroundStyle(DS.C.text2)312 FigureGrid { ForEach(s.figures, id: \.name) { f in SourcedFigure(label: ModelDetail.BenchmarkSource.figureLabel(f.name), value: ExplorerText.number(f.value)) } }313 }314 }315 }316 }317 }318319 private func twinsBlock(_ twins: [ModelDetail.Twin]) -> some View {320 DetailSection(title: "Même modèle par une autre route", source: "Registre de SP Chat") {321 VStack(spacing: 0) {322 ForEach(twins) { t in323 Button { history.append(t.id) } label: {324 HStack(spacing: 10) {325 ModelMark(env.catalog.identity(for: t.id), size: 18)326 Text(t.displayName).font(DS.F.ui).foregroundStyle(DS.C.text).lineLimit(1)327 RouteBadge(route: t.route)328 if t.route == "direct" { Tag(text: "direct") }329 if t.status == "catalog" { CatalogNotice() }330 Spacer(minLength: 8)331 if let i = t.inputPrice, let o = t.outputPrice { Text("\(ExplorerText.price(i)) / \(ExplorerText.price(o)) par M").font(.system(size: 12).monospacedDigit()).foregroundStyle(DS.C.text2) }332 Image(systemName: "chevron.right").font(.system(size: 10, weight: .semibold)).foregroundStyle(DS.C.muted)333 }334 .frame(height: 36).contentShape(Rectangle())335 }336 .buttonStyle(.plain).accessibilityLabel("Ouvrir la fiche de \(t.displayName), route \(ExplorerText.route(t.route))")337 }338 }339 }340 }341342 private func localBenchmarkBlock(_ b: AIModel.Benchmark, _ m: AIModel) -> some View {343 let keys = ExplorerText.testOrder.filter { b.perTest[$0] != nil } + b.perTest.keys.filter { !ExplorerText.testOrder.contains($0) }.sorted()344 return DetailSection(title: "Banc d'essai local", source: "Banc d'essai de SP Chat" + (m.lastVerifiedAt.map { " · \(ExplorerText.date($0))" } ?? "") + " · une passe par test, résultats indicatifs") {345 VStack(alignment: .leading, spacing: 12) {346 FigureGrid {347 SourcedFigure(label: "Tests réussis", value: "\(b.passed) / \(b.tests)")348 if let q = b.qualityScore { SourcedFigure(label: "Score de qualité", value: "\(Int(q.rounded())) %") }349 if let l = b.p50LatencyMs { SourcedFigure(label: "Durée médiane (p50)", value: Format.duration(ms: Int(l.rounded()))) }350 if let t = b.p50TtftMs { SourcedFigure(label: "Premier jeton (p50)", value: Format.duration(ms: Int(t.rounded()))) }351 if let c = b.totalCostUsd { SourcedFigure(label: "Coût du banc", value: Format.usd(c)) }352 }353 if !keys.isEmpty { ChipLine(title: "Résultat par test") { ForEach(keys, id: \.self) { testChip($0, b.perTest[$0]) } } }354 }355 }356 }357358 private func testChip(_ key: String, _ value: String?) -> some View {359 let (icon, color, word): (String, Color, String) = switch value {360 case "pass": ("checkmark.circle.fill", DS.C.ok, "réussi")361 case "fail": ("xmark.circle.fill", DS.C.danger, "échoué")362 case "error": ("exclamationmark.triangle.fill", DS.C.warn, "erreur")363 default: ("minus.circle", DS.C.muted, value ?? "non exécuté")364 }365 let name = ExplorerText.tests[key] ?? key366 return HStack(spacing: 4) { Image(systemName: icon).foregroundStyle(color); Text(name) }367 .modifier(QuietChip()).help("\(name) : \(word)").accessibilityElement(children: .ignore).accessibilityLabel("\(name) : \(word)")368 }369370 // MARK: Data371372 @State private var rules: [String: String] = [:]373374 private func load() async {375 let id = currentId376 if detail?.model.id == id { return }377 loading = true; loadError = nil378 defer { if currentId == id { loading = false } }379 do {380 let d = try await env.api.modelDetail(id)381 if currentId == id { detail = d }382 } catch {383 if Task.isCancelled { return }384 if let e = error as? APIError, e.kind == .cancelled { return }385 if currentId == id { loadError = (error as? LocalizedError)?.errorDescription ?? String(describing: error) }386 }387 if explorer == nil, rules.isEmpty, let overview = try? await env.api.providers() { rules = overview.categoryRules }388 }389390 private func toggleFavorite(_ m: AIModel) {391 Task { do { try await env.catalog.setFavorite(m.id, !m.favorite) } catch { env.toasts.error(error) } }392 }393 private func toggleHidden(_ m: AIModel) {394 Task { do { try await env.catalog.setHidden(m.id, !m.hidden) } catch { env.toasts.error(error) } }395 }396 private func toggleDock(_ m: AIModel) {397 Task { do { try await env.catalog.toggleDock(m.id) } catch { env.toasts.error(error) } }398 }399 private func makeDefault(_ m: AIModel) {400 Task { do { try await env.catalog.setDefault(m.id); env.toasts.show("\(m.displayName) est le modèle par défaut") } catch { env.toasts.error(error) } }401 }402}403404// MARK: - Building blocks shared by the detail sheet and the compare table405406/// A block of the fiche: caption on the left, the source of its figures on the right, hairline above.407struct DetailSection<Content: View>: View {408 let title: String409 var source: String?410 @ViewBuilder let content: () -> Content411 var body: some View {412 VStack(alignment: .leading, spacing: 12) {413 Rectangle().fill(DS.C.border).frame(height: 1)414 HStack(alignment: .firstTextBaseline, spacing: 12) {415 Text(title.uppercased()).font(DS.F.micro).tracking(0.5).foregroundStyle(DS.C.text2)416 Spacer(minLength: 8)417 if let source { Text("Source : \(source)").font(.system(size: 10.5)).foregroundStyle(DS.C.muted).lineLimit(2).multilineTextAlignment(.trailing).textSelection(.enabled) }418 }419 content()420 }421 .frame(maxWidth: .infinity, alignment: .leading)422 }423}424425struct Fact: Identifiable, Equatable {426 let label: String; let value: String; var mono = false; var monoLabel = false427 var id: String { label }428 init(_ label: String, _ value: String, mono: Bool = false, monoLabel: Bool = false) { self.label = label; self.value = value; self.mono = mono; self.monoLabel = monoLabel }429}430431/// Label / value pairs on two columns (one in narrow panes), hairline-free, selectable values.432struct FactGrid: View {433 let rows: [Fact]434 var columns = 2435 var body: some View {436 LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 28, alignment: .topLeading), count: max(columns, 1)), alignment: .leading, spacing: 7) {437 ForEach(rows) { r in438 HStack(alignment: .firstTextBaseline, spacing: 10) {439 Text(r.label).font(r.monoLabel ? DS.F.mono(11) : .system(size: 12)).foregroundStyle(DS.C.muted).frame(width: 150, alignment: .leading).lineLimit(2)440 Text(r.value).font(r.mono ? DS.F.mono(11.5) : .system(size: 12, weight: .medium).monospacedDigit()).foregroundStyle(DS.C.text).textSelection(.enabled)441 .lineLimit(3).fixedSize(horizontal: false, vertical: true).frame(maxWidth: .infinity, alignment: .leading)442 }443 .accessibilityElement(children: .combine)444 }445 }446 }447}448449/// Figures on four columns.450struct FigureGrid<Content: View>: View {451 @ViewBuilder let content: () -> Content452 var body: some View {453 LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 16, alignment: .topLeading), count: 4), alignment: .leading, spacing: 14) { content() }454 }455}456457/// A caption followed by chips that wrap.458struct ChipLine<Content: View>: View {459 let title: String460 @ViewBuilder let content: () -> Content461 var body: some View {462 VStack(alignment: .leading, spacing: 6) {463 Text(title).font(.system(size: 12)).foregroundStyle(DS.C.muted)464 WrapLayout(spacing: 5) { content() }465 }466 }467}468469struct QuietChip: ViewModifier {470 func body(content: Content) -> some View {471 content.font(DS.F.caption).foregroundStyle(DS.C.text2).lineLimit(1).labelStyle(.titleAndIcon)472 .padding(.horizontal, 8).padding(.vertical, 3.5)473 .background(DS.C.surface2, in: Capsule()).overlay(Capsule().strokeBorder(DS.C.border, lineWidth: 1))474 }475}476477/// Left-aligned wrapping layout for chips.478struct WrapLayout: Layout {479 var spacing: CGFloat = 6480 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {481 let rows = arrange(width: proposal.width ?? .infinity, subviews: subviews)482 return CGSize(width: proposal.width ?? rows.width, height: rows.height)483 }484 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {485 let rows = arrange(width: bounds.width, subviews: subviews)486 for (i, p) in rows.points.enumerated() { subviews[i].place(at: CGPoint(x: bounds.minX + p.x, y: bounds.minY + p.y), proposal: .unspecified) }487 }488 private func arrange(width: CGFloat, subviews: Subviews) -> (points: [CGPoint], width: CGFloat, height: CGFloat) {489 var points: [CGPoint] = []; var x: CGFloat = 0, y: CGFloat = 0, rowHeight: CGFloat = 0, maxX: CGFloat = 0490 for s in subviews {491 let size = s.sizeThatFits(.unspecified)492 if x > 0, x + size.width > width { x = 0; y += rowHeight + spacing; rowHeight = 0 }493 points.append(CGPoint(x: x, y: y)); x += size.width + spacing; rowHeight = max(rowHeight, size.height); maxX = max(maxX, x - spacing)494 }495 return (points, maxX, y + rowHeight)496 }497}498