Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Workspace/ArenaColumnView.swift3// Description: Arena pieces: the side-by-side column strip, one streaming column with its metrics strip and actions, and the searchable model picker over the whole catalogue.4import SwiftUI5import AppKit6import SPChatCore78// MARK: - Column strip910/// 2–4 columns visible depending on the width; more scroll horizontally. Each column scrolls its own answer.11struct ArenaColumns: View {12 let model: ArenaViewModel13 let onContinue: (String) -> Void14 /// (model id, conversation id or nil for a new conversation)15 let onAdopt: (String, String?) -> Void16 @Environment(AppEnvironment.self) private var env17 static let spacing: CGFloat = DS.S.l1819 static func visibleCount(width: CGFloat, columns: Int) -> Int {20 let fit = width >= 1500 ? 4 : (width >= 1000 ? 3 : (width >= 620 ? 2 : 1))21 return max(1, min(columns, fit))22 }2324 var body: some View {25 GeometryReader { geo in26 let visible = Self.visibleCount(width: geo.size.width, columns: model.columns.count)27 let width = max(280, (geo.size.width - Self.spacing * CGFloat(visible - 1)) / CGFloat(visible))28 ScrollView(.horizontal) {29 HStack(alignment: .top, spacing: Self.spacing) {30 ForEach(model.columns) { column in31 ArenaColumnView(column: column, running: model.running, canAct: model.canAct, isPreferred: model.preferred == column.modelId,32 judgeLabel: model.judge?.label(for: column.modelId), adopting: model.adopting == column.modelId, onPrefer: { model.prefer(column.modelId, env: env) },33 onContinue: { onContinue(column.modelId) }, onAdopt: { onAdopt(column.modelId, $0) })34 .frame(width: width, height: geo.size.height)35 }36 }37 }38 .scrollIndicators(model.columns.count > visible ? .automatic : .hidden)39 }40 .frame(minHeight: 260)41 }42}4344// MARK: - Column4546struct ArenaColumnView: View {47 let column: ArenaColumn48 let running: Bool49 let canAct: Bool50 let isPreferred: Bool51 let judgeLabel: String?52 let adopting: Bool53 let onPrefer: () -> Void54 let onContinue: () -> Void55 let onAdopt: (String?) -> Void56 @Environment(AppEnvironment.self) private var env57 @State private var showReasoning = false5859 private var streaming: Bool { running && !column.done }6061 /// Catalogue identity; for a model that left the catalogue, what the server said about it in the run.62 private var identity: ModelIdentity {63 var i = env.catalog.identity(for: column.modelId)64 guard !i.isKnown else { return i }65 if let n = column.displayName, !n.isEmpty { i.name = n }66 if let l = column.logo { i.logo = l }67 if let r = column.route { i.route = r }68 return i69 }7071 var body: some View {72 VStack(alignment: .leading, spacing: 0) {73 header.padding(.horizontal, DS.S.xl).padding(.top, DS.S.l).padding(.bottom, DS.S.m)74 ZStack { Rectangle().fill(DS.C.border).frame(height: 1); LumenLine(active: streaming, cornerInset: 0) }.frame(height: 6)75 ScrollView {76 VStack(alignment: .leading, spacing: DS.S.l) {77 if !column.reasoning.isEmpty { reasoning }78 if !column.text.isEmpty {79 MarkdownView(text: column.text).textSelection(.enabled)80 } else if streaming {81 Text(column.reasoning.isEmpty ? "En attente du premier jeton…" : "Le modèle réfléchit…").font(DS.F.uiRegular).foregroundStyle(DS.C.muted)82 } else if column.error == nil {83 Text("Aucune réponse.").font(DS.F.uiRegular).foregroundStyle(DS.C.muted)84 }85 if let error = column.error {86 Label(error, systemImage: "exclamationmark.triangle").font(DS.F.uiRegular).foregroundStyle(DS.C.danger).textSelection(.enabled)87 .padding(DS.S.l).frame(maxWidth: .infinity, alignment: .leading)88 .background(DS.C.danger.opacity(0.08), in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))89 }90 }91 .padding(.horizontal, DS.S.xl).padding(.vertical, DS.S.l).frame(maxWidth: .infinity, alignment: .topLeading)92 }93 Rectangle().fill(DS.C.border).frame(height: 1)94 metrics.padding(.horizontal, DS.S.xl).padding(.vertical, DS.S.l)95 if column.done, !column.text.isEmpty {96 Rectangle().fill(DS.C.border).frame(height: 1)97 actions.padding(.horizontal, DS.S.l).padding(.vertical, DS.S.m)98 }99 }100 .background(DS.C.surface, in: RoundedRectangle(cornerRadius: DS.R.card, style: .continuous))101 .overlay(RoundedRectangle(cornerRadius: DS.R.card, style: .continuous).strokeBorder(isPreferred ? DS.C.accent : DS.C.border, lineWidth: isPreferred ? 1.5 : 1))102 .clipShape(RoundedRectangle(cornerRadius: DS.R.card, style: .continuous))103 .motion(DS.Motion.snappy, value: isPreferred)104 }105106 private var header: some View {107 VStack(alignment: .leading, spacing: 3) {108 HStack(spacing: DS.S.s) {109 ModelChip(identity: identity, markSize: 18, font: DS.F.ui, breathing: streaming)110 Spacer(minLength: DS.S.xs)111 if let judgeLabel { StatusPill(text: judgeLabel, color: DS.C.text2).help("Lettre attribuée à cette réponse par le modèle juge").accessibilityLabel("Réponse \(judgeLabel) pour le juge") }112 if isPreferred { StatusPill(text: "Préférée", color: DS.C.accent, systemImage: "trophy.fill") }113 if column.error != nil { StatusPill(text: "Erreur", color: DS.C.danger, systemImage: "xmark.octagon") }114 }115 Text(subtitle).font(.system(size: 10.5, weight: .medium)).foregroundStyle(DS.C.muted).lineLimit(1)116 }117 }118119 /// Who served the request when the route reports it, else what is going on.120 private var subtitle: String {121 if let s = column.servedBy, !s.isEmpty { return "Servi par \(s)" }122 if streaming { return column.text.isEmpty ? "Envoi…" : "Réponse en cours" }123 if identity.isLocal { return "Inférence locale MacLustr AI" }124 if identity.isCatalogOnly { return "Catalogue OpenRouter · non testé par le banc" }125 return identity.isOpenRouter ? "Via OpenRouter" : "API directe · \(identity.creatorName)"126 }127128 private var reasoning: some View {129 DisclosureGroup(isExpanded: $showReasoning) {130 Text(column.reasoning).font(DS.F.caption).foregroundStyle(DS.C.text2).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading).padding(.top, DS.S.xs)131 } label: {132 Label(streaming && column.text.isEmpty ? "Raisonnement en cours" : "Raisonnement (résumé)", systemImage: "brain").font(DS.F.caption).foregroundStyle(DS.C.muted)133 }134 }135136 // MARK: Metrics strip137138 /// Before the answer is complete: the server's pre-run estimate (input side only), labelled as such. After:139 /// the measured figures, the cost « facturé » when the provider reported the billed amount, else « estimé ».140 private var isLocalRoute: Bool { column.route == "local" || column.modelId.hasPrefix("local:") }141142 private var metrics: some View {143 VStack(alignment: .leading, spacing: DS.S.s) {144 HStack(alignment: .top, spacing: DS.S.m) {145 if column.done {146 SourcedFigure(label: "1er jeton", value: Format.duration(ms: column.ttftMs), source: " ")147 SourcedFigure(label: "Durée", value: Format.duration(ms: column.latencyMs), source: " ")148 SourcedFigure(label: "Jetons", value: "\(Format.tokens(column.inputTokens)) → \(Format.tokens(column.outputTokens))", source: column.reasoningTokens.flatMap { $0 > 0 ? "réflexion \(Format.tokens($0))" : nil } ?? " ")149 .help("Jetons en entrée → en sortie, rapportés par le fournisseur" + (column.reasoningTokens.flatMap { $0 > 0 ? " ; dont \(Format.tokens($0)) jetons de raisonnement" : nil } ?? ""))150 // the local route bills nothing: « 0 $ · local », never « estimé »151 SourcedFigure(label: "Coût", value: isLocalRoute ? "0 $" : Format.usd(column.costUsd), source: isLocalRoute ? "local" : column.costUsd == nil ? " " : (column.isBilledCost ? "facturé" : "estimé"))152 .help(isLocalRoute ? "Inférence locale MacLustr AI : aucune facturation à la requête" : column.isBilledCost ? "Montant facturé, rapporté par le fournisseur pour cette requête" : "Estimation : jetons mesurés × prix catalogue")153 } else {154 SourcedFigure(label: "1er jeton", value: "—", source: " ")155 SourcedFigure(label: "Durée", value: "—", source: " ")156 SourcedFigure(label: "Jetons", value: column.estimate?.inputTokens.map { "≈ \(Format.tokens($0)) → …" } ?? "—", source: column.estimate?.inputTokens == nil ? " " : "estimé")157 SourcedFigure(label: "Coût", value: column.estimate?.inputCostUsd.map { "≈ \(Format.usd($0))" } ?? "—", source: column.estimate?.inputCostUsd == nil ? " " : "estimé · entrée")158 }159 }160 if !column.done, let basis = column.estimate?.basis, !basis.isEmpty {161 Text(basis).font(.system(size: 10)).foregroundStyle(DS.C.muted).lineLimit(2).fixedSize(horizontal: false, vertical: true)162 }163 }164 .accessibilityElement(children: .contain)165 }166167 // MARK: Actions168169 private var actions: some View {170 HStack(spacing: DS.S.s) {171 if column.error == nil {172 Button { onPrefer() } label: { Label(isPreferred ? "Préférée" : "Préférer", systemImage: isPreferred ? "trophy.fill" : "trophy") }173 .disabled(!canAct || isPreferred).help("Marquer cette réponse comme la préférée de la comparaison")174 Menu {175 Button("Dans une nouvelle conversation") { onAdopt(nil) }176 let recent = env.conversations.items.prefix(8)177 if !recent.isEmpty {178 Section("Dans une conversation existante") {179 ForEach(Array(recent)) { c in Button(c.title.isEmpty ? "Sans titre" : c.title) { onAdopt(c.id) } }180 }181 }182 Divider()183 Button("Nouvelle conversation vide avec ce modèle (invite copiée)") { onContinue() }184 } label: { Label(adopting ? "Adoption…" : "Adopter", systemImage: "arrow.turn.down.right") }185 .fixedSize().disabled(!canAct || adopting)186 .help("Reprend cette réponse dans une conversation, avec ses mesures. Aucun modèle n'est rappelé.")187 }188 Spacer(minLength: 0)189 IconButton(systemImage: "doc.on.doc", label: "Copier la réponse") {190 NSPasteboard.general.clearContents(); NSPasteboard.general.setString(column.text, forType: .string); env.toasts.show("Réponse copiée")191 }192 }193 .controlSize(.small)194 }195}196197// MARK: - Model picker198199/// Searchable popover over the whole catalogue (direct + OpenRouter): favourites and recents first, lazy rows.200struct ArenaModelPicker: View {201 let model: ArenaViewModel202 @Environment(AppEnvironment.self) private var env203 @State private var text = ""204 @State private var route = ""205 @FocusState private var focused: Bool206207 private var isFull: Bool { model.selected.count >= ArenaViewModel.maxModels }208209 private var results: [AIModel] {210 var q = ModelQuery(); q.text = text211 if !route.isEmpty { q.routes = [route] }212 return env.catalog.index.search(q)213 }214215 var body: some View {216 let all = results217 let searching = !text.trimmingCharacters(in: .whitespaces).isEmpty218 let favorites = searching ? [] : all.filter(\.favorite)219 let recents = searching ? [] : env.catalog.recents.filter { m in (route.isEmpty || m.route == route) && !m.favorite }220 let pinned = Set((favorites + recents).map(\.id))221 let rest = searching ? all : all.filter { !pinned.contains($0.id) }222 VStack(alignment: .leading, spacing: DS.S.m) {223 HStack(spacing: DS.S.m) {224 Image(systemName: "magnifyingglass").foregroundStyle(DS.C.muted)225 TextField("Rechercher dans \(env.catalog.index.count) modèles", text: $text).textFieldStyle(.plain).focused($focused)226 .onSubmit { if let first = all.first { model.toggle(first.id) } }227 .accessibilityIdentifier("arena-model-search")228 Text("\(model.selected.count) / \(ArenaViewModel.maxModels)").font(DS.F.caption.monospacedDigit()).foregroundStyle(isFull ? DS.C.accent : DS.C.muted)229 }230 .padding(.horizontal, DS.S.l).frame(height: 34).surface(radius: DS.R.control, fill: DS.C.bg)231 if env.catalog.hasOpenRouter || !env.catalog.localModels.isEmpty {232 HStack(spacing: DS.S.s) {233 ForEach([("", "Toutes les routes"), ("direct", "Direct")] + (env.catalog.localModels.isEmpty ? [] : [("local", "Local")]) + (env.catalog.hasOpenRouter ? [("openrouter", "OpenRouter")] : []), id: \.0) { value, label in234 Button(label) { route = value }.buttonStyle(ChipStyle(selected: route == value))235 }236 }237 }238 ScrollView {239 LazyVStack(alignment: .leading, spacing: 1) {240 if !favorites.isEmpty { SectionCaption(text: "Favoris").padding(.top, DS.S.xs).padding(.horizontal, DS.S.m); ForEach(favorites) { row($0) } }241 if !recents.isEmpty { SectionCaption(text: "Récents").padding(.top, DS.S.m).padding(.horizontal, DS.S.m); ForEach(recents) { row($0) } }242 if !rest.isEmpty {243 if !searching { SectionCaption(text: "Tout le catalogue").padding(.top, DS.S.m).padding(.horizontal, DS.S.m) }244 ForEach(rest) { row($0) }245 }246 if all.isEmpty { Text(env.catalog.loaded ? "Aucun modèle ne correspond." : "Chargement du catalogue…").font(DS.F.uiRegular).foregroundStyle(DS.C.muted).padding(DS.S.l) }247 }248 }249 .frame(height: 380)250 if isFull { Text("Six modèles au plus par comparaison : retires-en un pour en ajouter un autre.").font(DS.F.caption).foregroundStyle(DS.C.muted) }251 }252 .padding(DS.S.l).frame(width: 460)253 .onAppear { focused = true }254 }255256 private func row(_ m: AIModel) -> some View {257 let selected = model.selected.contains(m.id)258 return Button { model.toggle(m.id) } label: {259 HStack(spacing: DS.S.m) {260 ModelMark(m, size: 18)261 VStack(alignment: .leading, spacing: 1) {262 HStack(spacing: DS.S.s) {263 Text(m.displayName).font(DS.F.ui).foregroundStyle(DS.C.text).lineLimit(1)264 RouteBadge(route: m.route)265 }266 HStack(spacing: DS.S.s) {267 Text([m.creatorName, m.factsLine].filter { !$0.isEmpty }.joined(separator: " · ")).font(.system(size: 10.5)).foregroundStyle(DS.C.muted).lineLimit(1)268 if m.isCatalogOnly { CatalogNotice() }269 }270 }271 Spacer(minLength: DS.S.s)272 Image(systemName: selected ? "checkmark.circle.fill" : "plus.circle").font(.system(size: 14)).foregroundStyle(selected ? DS.C.accent : DS.C.muted.opacity(isFull ? 0.35 : 1))273 }274 .padding(.horizontal, DS.S.m).padding(.vertical, 5).frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle())275 .background(selected ? DS.C.accentSoft : .clear, in: RoundedRectangle(cornerRadius: DS.R.chip, style: .continuous))276 }277 .buttonStyle(.plain).disabled(!selected && isFull)278 .accessibilityLabel("\(ModelIdentity(m).accessibilityText)\(selected ? ", sélectionné" : "")").accessibilityIdentifier("arena-model-row")279 }280}281