SPB Git

Repository Public

ArenaView.swift 32.9 KB 572 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Features/Arena/ArenaView.swift4//  Description: Arena — the same prompt sent to 2–6 models of any route. iPhone: swipeable pages with a summary strip5//               and a page indicator; iPad: columns side by side. Live streams, measured figures (first token,6//               duration, tokens, cost « estimé » / « facturé »), prefer, judge, adopt and export.7//8//  Author: Simon-Pierre Boucher9//  Contact: contact@spboucher.ai10//1112import SwiftUI13import UIKit1415struct ArenaView: View {16    @Environment(AppEnvironment.self) private var env17    @Environment(\.dismiss) private var dismiss18    @Environment(\.accessibilityReduceMotion) private var reduceMotion1920    @State private var session: ArenaSession?21    @State private var page: String?22    @State private var sheet: Sheet?23    @State private var shareURL: URL?24    @FocusState private var promptFocused: Bool2526    enum Sheet: String, Identifiable { case addModel, judgeModel, judgement; var id: String { rawValue } }2728    var body: some View {29        NavigationStack {30            Group {31                if let session {32                    content(session)33                } else { Color.appBackground }34            }35            .background(Color.appBackground)36            .navigationTitle("Arène").navigationBarTitleDisplayMode(.inline)37            .toolbar { toolbar }38        }39        // iPad: the largest sheet, so the columns sit side by side40        .presentationSizing(.page)41        .task { prepare() }42        .onDisappear { session?.close() }43        .sheet(item: $sheet) { s in sheetView(s) }44        .sheet(item: Binding(get: { shareURL.map(IdentifiedURL.init) }, set: { shareURL = $0?.url })) { u in ActivityView(items: [u.url]) }45        .interactiveDismissDisabled(session?.isRunning == true)46    }4748    /// Builds the session once from what the caller handed over (prompt, conversation, preselected models), then49    /// clears the hand-over so the next Arena starts clean.50    private func prepare() {51        guard session == nil else { return }52        let s = ArenaSession(api: env.api, model: { [catalog = env.catalog] id in catalog.model(id).flatMap { $0.isSelectableForChat ? $0 : nil } })53        let seed = env.router.arenaSeed54        s.prompt = seed?.prompt ?? ""; s.conversationId = seed?.conversationId; s.projectId = seed?.projectId55        var ids = env.router.arenaModelIds56        if ids.count < ArenaSession.minModels {57            // the owner's own line-up: dock, then favourites, then the current model and the recents58            let current = env.catalog.effectiveModelId(preferred: env.preferences.modelId)59            ids += env.catalog.dockModels.map(\.id) + env.catalog.favorites.map(\.id)60            if Set(ids).count < ArenaSession.minModels { ids += [current].compactMap { $0 } + env.catalog.recents.map(\.id) + [env.catalog.defaultModelId].compactMap { $0 } }61            ids = Array(ids.prefix(max(env.router.arenaModelIds.count, 3)))62        }63        s.setModels(ids)64        env.router.arenaSeed = nil; env.router.arenaModelIds = []65        session = s66        #if DEBUG67        // UI tests / Scripts/sim.sh screenshots: SPCHAT_UI_ARENA_AUTOSTART=1 launches the comparison of a deep-linked prompt68        if ProcessInfo.processInfo.environment["SPCHAT_UI_TESTS"] != nil, ProcessInfo.processInfo.environment["SPCHAT_UI_ARENA_AUTOSTART"] != nil, s.canStart { start(s) }69        #endif70    }7172    // MARK: layout7374    private func content(_ s: ArenaSession) -> some View {75        VStack(spacing: 0) {76            if let state = s.state {77                results(s, state)78            } else {79                intro(s)80            }81        }82        .frame(maxWidth: .infinity, maxHeight: .infinity)83        .safeAreaInset(edge: .bottom, spacing: 0) {84            VStack(spacing: 6) {85                if let e = s.error { Banner(kind: .error, text: e) { s.error = nil }.padding(.horizontal, 12).frame(maxWidth: 760) }86                composer(s)87            }88        }89        .animation(Motion.smooth(reduceMotion), value: s.state == nil)90        .animation(Motion.snappy(reduceMotion), value: s.error)91    }9293    private func intro(_ s: ArenaSession) -> some View {94        ScrollView {95            VStack(spacing: 14) {96                Image(systemName: "square.split.2x1").font(.system(size: 30, weight: .medium)).foregroundStyle(Color.accentColor)97                    .frame(width: 64, height: 64).background(Color.accentSoft, in: .rect(cornerRadius: 18, style: .continuous)).padding(.top, 36)98                Text("Un prompt, plusieurs modèles").font(.spDisplay).tracking(-0.4).foregroundStyle(Color.textPrimary).multilineTextAlignment(.center)99                Text("Envoie la même demande à 2 à 6 modèles, toutes routes confondues, et compare les réponses, le premier jeton, la durée et le coût réel.")100                    .font(.subheadline).foregroundStyle(Color.textSecondary).multilineTextAlignment(.center).frame(maxWidth: 420)101                VStack(spacing: 0) {102                    ForEach(Array(s.models.enumerated()), id: \.element.id) { i, m in103                        if i > 0 { Divider().padding(.leading, 50) }104                        HStack(spacing: 4) {105                            ModelRowLabel(model: m)106                            Button { env.haptics.soften(); withAnimation(Motion.snappy(reduceMotion)) { s.remove(m.id) } } label: {107                                Image(systemName: "minus.circle.fill").font(.body).foregroundStyle(Color.muted).frame(width: 44, height: 44).contentShape(.rect)108                            }109                            .buttonStyle(.plain).accessibilityLabel(String(localized: "Retirer \(m.displayName)"))110                        }111                        .padding(.leading, 12)112                    }113                    if s.canAddModel {114                        if !s.models.isEmpty { Divider().padding(.leading, 50) }115                        Button { sheet = .addModel } label: {116                            HStack(spacing: 12) {117                                Image(systemName: "plus").font(.subheadline.weight(.semibold)).foregroundStyle(Color.accentColor).frame(width: 26, height: 26)118                                Text("Ajouter un modèle").font(.body).foregroundStyle(Color.accentColor)119                                Spacer(minLength: 0)120                                Text("\(s.models.count) / \(ArenaSession.maxModels)").font(.caption.monospacedDigit()).foregroundStyle(Color.muted)121                            }122                            .padding(.horizontal, 12).frame(minHeight: 50).contentShape(.rect)123                        }124                        .buttonStyle(.plain).accessibilityIdentifier("arena.addModel")125                    }126                }127                .cardSurface()128                .frame(maxWidth: 520).padding(.top, 6)129                if s.models.count < ArenaSession.minModels {130                    Text("Choisis au moins deux modèles.").font(.footnote).foregroundStyle(Color.muted)131                }132            }133            .padding(.horizontal, 16).padding(.bottom, 24)134            .frame(maxWidth: .infinity)135        }136        .scrollDismissesKeyboard(.interactively)137    }138139    @ViewBuilder private func results(_ s: ArenaSession, _ state: ArenaState) -> some View {140        VStack(spacing: 10) {141            HStack(alignment: .firstTextBaseline, spacing: 8) {142                Text(state.prompt).font(.footnote).foregroundStyle(Color.textSecondary).lineLimit(2).frame(maxWidth: .infinity, alignment: .leading)143                if let total = state.totalCostUsd, !state.isRunning {144                    Text("\(Format.usd(total)) \(state.allCostsExact ? String(localized: "facturé") : String(localized: "estimé"))").font(.caption2.monospacedDigit()).foregroundStyle(Color.muted).fixedSize()145                        .accessibilityLabel(String(localized: "Coût total : \(Format.usd(total))"))146                }147            }148            .padding(.horizontal, 16).padding(.top, 8)149            // side by side when there is room for at least two readable columns (iPad), pages otherwise (iPhone, Slide Over)150            GeometryReader { geo in151                if geo.size.width >= 640 { columns(s, state, width: geo.size.width) } else { pager(s, state) }152            }153        }154    }155156    // MARK: iPhone — summary strip, pages, page indicator157158    private func pager(_ s: ArenaSession, _ state: ArenaState) -> some View {159        let current = page ?? state.columns.first?.id160        return VStack(spacing: 8) {161            ScrollView(.horizontal, showsIndicators: false) {162                HStack(spacing: 8) {163                    ForEach(state.columns) { c in164                        Button { env.haptics.selection(); withAnimation(Motion.smooth(reduceMotion)) { page = c.id } } label: { ArenaSummaryCell(column: c, running: state.isRunning, selected: c.id == current, preferred: state.preferred == c.id, fastest: state.fastestFirstToken == c.id && !state.isRunning) }165                            .buttonStyle(PressScale(scale: 0.96))166                            .containerRelativeFrame(.horizontal, count: min(state.columns.count, 3), spacing: 8)167                    }168                }169                .scrollTargetLayout()170            }171            .contentMargins(.horizontal, 16, for: .scrollContent)172            .scrollTargetBehavior(.viewAligned)173            ScrollView(.horizontal, showsIndicators: false) {174                LazyHStack(spacing: 0) {175                    ForEach(state.columns) { c in176                        ScrollView {177                            ArenaColumnView(column: c, session: s, state: state).padding(.horizontal, 16).padding(.top, 4).padding(.bottom, 28)178                        }179                        .containerRelativeFrame(.horizontal)180                        .id(c.id)181                    }182                }183                .scrollTargetLayout()184            }185            .scrollTargetBehavior(.paging)186            .scrollPosition(id: $page)187            .onChange(of: page) { env.haptics.selection() }188            if state.columns.count > 1 {189                HStack(spacing: 7) {190                    ForEach(state.columns) { c in191                        Capsule().fill(c.id == current ? Color.accentColor : Color.muted.opacity(0.4)).frame(width: c.id == current ? 16 : 6, height: 6)192                    }193                }194                .animation(Motion.snappy(reduceMotion), value: current)195                .padding(.bottom, 2)196                .accessibilityElement()197                .accessibilityLabel(String(localized: "Page \((state.columns.firstIndex { $0.id == current } ?? 0) + 1) sur \(state.columns.count)"))198                .accessibilityIdentifier("arena.pageIndicator")199            }200        }201    }202203    // MARK: iPad — columns side by side (4 visible, horizontal scroll beyond)204205    private func columns(_ s: ArenaSession, _ state: ArenaState, width total: CGFloat) -> some View {206        let spacing: CGFloat = 12207        let visible = CGFloat(min(state.columns.count, 4, max(2, Int((total - 32 + spacing) / (290 + spacing)))))208        let width = (total - 32 - spacing * (visible - 1)) / visible209        return ScrollView(.horizontal, showsIndicators: CGFloat(state.columns.count) > visible) {210            HStack(alignment: .top, spacing: spacing) {211                ForEach(state.columns) { c in212                    ScrollView {213                        ArenaColumnView(column: c, session: s, state: state).padding(14)214                    }215                    .frame(width: width)216                    .frame(maxHeight: .infinity)217                    .cardSurface(cornerRadius: Radius.float)218                }219            }220            .padding(.horizontal, 16).padding(.bottom, 8)221        }222    }223224    // MARK: composer — line-up, prompt, effort, start / stop225226    private func composer(_ s: ArenaSession) -> some View {227        @Bindable var s = s228        return VStack(alignment: .leading, spacing: 6) {229            if s.state != nil {230                // the line-up stays editable between two runs231                ScrollView(.horizontal, showsIndicators: false) {232                    HStack(spacing: 6) {233                        ForEach(s.models) { m in234                            HStack(spacing: 4) {235                                ModelChip(logo: m.logo, creatorName: m.creatorName, name: m.shortName, route: m.route, markSize: 14, font: .spCaption)236                                if !s.isRunning {237                                    Button { withAnimation(Motion.snappy(reduceMotion)) { s.remove(m.id) } } label: { Image(systemName: "xmark").font(.system(size: 9, weight: .bold)).foregroundStyle(Color.muted).frame(width: 22, height: 30).contentShape(.rect) }238                                        .buttonStyle(.plain).accessibilityLabel(String(localized: "Retirer \(m.displayName)"))239                                }240                            }241                            .padding(.leading, 9).padding(.trailing, s.isRunning ? 9 : 2).frame(minHeight: 30)242                            .background(Color.textPrimary.opacity(0.07), in: .capsule)243                        }244                    }245                }246                .transition(.opacity.combined(with: .offset(y: 6)))247            }248            TextField("Prompt à comparer", text: $s.prompt, axis: .vertical)249                .lineLimit(1...6).font(.body).focused($promptFocused)250                .padding(.horizontal, 6).padding(.vertical, 6).frame(minHeight: 36)251                .contentShape(.rect).onTapGesture { promptFocused = true }252                .disabled(s.isRunning)253                .accessibilityIdentifier("arena.prompt")254            HStack(spacing: 2) {255                Button { sheet = .addModel } label: { controlIcon("plus") }256                    .buttonStyle(PressScale()).disabled(!s.canAddModel).opacity(s.canAddModel ? 1 : 0.4)257                    .accessibilityLabel(String(localized: "Ajouter un modèle"))258                Menu {259                    Picker("Effort de raisonnement", selection: $s.effort) {260                        Text("Par défaut").tag(Effort?.none)261                        ForEach(Effort.allCases) { e in Text(ModelSheet.label(e)).tag(Effort?.some(e)) }262                    }263                } label: {264                    HStack(spacing: 4) {265                        Image(systemName: "brain").font(.system(size: 14, weight: .medium))266                        if let e = s.effort { Text(ModelSheet.label(e)).font(.spCaption) }267                    }268                    .foregroundStyle(s.effort == nil ? Color.textSecondary : Color.accentColor)269                    .padding(.horizontal, s.effort == nil ? 0 : 10).frame(minWidth: 34, minHeight: 34)270                    .background(s.effort == nil ? Color.clear : Color.accentSoft, in: .capsule)271                    .frame(minWidth: 38, minHeight: 44).contentShape(.rect)272                }273                .disabled(s.isRunning)274                .accessibilityLabel(String(localized: "Effort de raisonnement"))275                Spacer(minLength: 4)276                Text(s.models.count < ArenaSession.minModels ? String(localized: "2 modèles au moins") : String(localized: "\(s.models.count) modèles"))277                    .font(.spCaption).foregroundStyle(s.models.count < ArenaSession.minModels ? Color.warning : Color.muted).monospacedDigit().contentTransition(.numericText())278                    .padding(.trailing, 6)279                if s.isRunning {280                    Button { env.haptics.tap(); s.stop() } label: {281                        Image(systemName: "stop.fill").font(.system(size: 13, weight: .bold)).foregroundStyle(Color.appBackground)282                            .frame(width: 34, height: 34).background(Color.textPrimary, in: .circle).frame(width: 38, height: 44).contentShape(.rect)283                    }284                    .buttonStyle(PressScale()).transition(.scale(scale: 0.7).combined(with: .opacity))285                    .accessibilityLabel(String(localized: "Arrêter la comparaison")).accessibilityIdentifier("arena.stop")286                } else {287                    Button { start(s) } label: {288                        Image(systemName: "arrow.up").font(.system(size: 15, weight: .bold)).foregroundStyle(Color.white)289                            .frame(width: 34, height: 34).background(s.canStart ? Color.accentColor : Color.muted.opacity(0.5), in: .circle).frame(width: 38, height: 44).contentShape(.rect)290                    }291                    .buttonStyle(PressScale()).disabled(!s.canStart)292                    .keyboardShortcut(.return, modifiers: .command)293                    .transition(.scale(scale: 0.7).combined(with: .opacity))294                    .accessibilityLabel(String(localized: "Lancer la comparaison")).accessibilityIdentifier("arena.start")295                }296            }297        }298        .padding(.horizontal, 10).padding(.top, 10).padding(.bottom, 8)299        .floatSurface(cornerRadius: Radius.float)300        .overlay(alignment: .top) { LumenLine(active: s.isRunning).animation(Motion.fade, value: s.isRunning) }301        .animation(Motion.smooth(reduceMotion), value: s.modelIds)302        .animation(Motion.snappy(reduceMotion), value: s.isRunning)303        .animation(Motion.snappy(reduceMotion), value: s.prompt.count)304        .padding(.horizontal, 12).padding(.bottom, 8).padding(.top, 4)305        .frame(maxWidth: 760).frame(maxWidth: .infinity)306    }307308    private func controlIcon(_ symbol: String) -> some View {309        Image(systemName: symbol).font(.system(size: 15, weight: .medium)).foregroundStyle(Color.textSecondary)310            .frame(width: 34, height: 34).frame(width: 38, height: 44).contentShape(.rect)311    }312313    private func start(_ s: ArenaSession) {314        guard s.canStart else { return }315        env.haptics.tap()316        promptFocused = false317        page = s.models.first?.id318        s.start()319    }320321    // MARK: toolbar and sheets322323    @ToolbarContentBuilder private var toolbar: some ToolbarContent {324        ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() }.accessibilityIdentifier("arena.close") }325        if let s = session, s.state != nil {326            ToolbarItemGroup(placement: .primaryAction) {327                if s.isJudging || s.isExporting { ProgressView() }328                Menu {329                    Section {330                        Button { Task { if let u = await s.export(format: "md") { shareURL = u } } } label: { Label("Exporter en Markdown", systemImage: "square.and.arrow.up") }331                        Button { Task { if let u = await s.export(format: "json") { shareURL = u } } } label: { Label("Exporter en JSON", systemImage: "curlybraces") }332                    }333                    .disabled(!s.isStored)334                    Section {335                        if s.state?.judgement != nil { Button { sheet = .judgement } label: { Label("Voir l’avis du juge", systemImage: "text.badge.checkmark") } }336                        Button { sheet = .judgeModel } label: { Label(s.state?.judgement == nil ? "Demander l’avis d’un modèle juge…" : "Demander un autre avis…", systemImage: "scalemass") }337                    }338                    .disabled(!s.isStored)339                    Section {340                        Button { env.haptics.tap(); page = s.models.first?.id; s.rerun() } label: { Label("Relancer le même prompt", systemImage: "arrow.clockwise") }341                            .disabled(s.models.count < ArenaSession.minModels)342                        Button { withAnimation(Motion.smooth(reduceMotion)) { s.reset() }; promptFocused = true } label: { Label("Nouvelle comparaison", systemImage: "plus.square.on.square") }343                    }344                } label: { Image(systemName: "ellipsis.circle") }345                .disabled(s.isRunning || s.isJudging || s.isExporting)346                .accessibilityLabel(String(localized: "Exporter, juger, recommencer"))347                .accessibilityIdentifier("arena.export")348            }349        }350    }351352    @ViewBuilder private func sheetView(_ which: Sheet) -> some View {353        if let s = session {354            switch which {355            case .addModel:356                ModelSheet(purpose: .pick(title: String(localized: "Ajouter à l’Arène"), current: nil) { m in357                    if s.modelIds.contains(m.id) { s.error = String(localized: "\(m.displayName) est déjà dans la comparaison.") } else { withAnimation(Motion.snappy(reduceMotion)) { s.add(m.id) } }358                }).presentationDetents([.large])359            case .judgeModel:360                ModelSheet(purpose: .pick(title: String(localized: "Modèle juge"), current: s.state?.judgement?.judgeModel) { m in361                    Task { await s.judge(with: m.id); if s.state?.judgement != nil { env.haptics.success(); sheet = .judgement } }362                }).presentationDetents([.large])363            case .judgement:364                if let j = s.state?.judgement { ArenaJudgementSheet(judgement: j, columns: s.state?.columns ?? []).presentationDetents([.medium, .large]) }365            }366        }367    }368}369370/// One cell of the compact summary strip: maker mark, first token, cost. Tapping it jumps to the model's page.371struct ArenaSummaryCell: View {372    let column: ArenaColumn373    let running: Bool374    let selected: Bool375    let preferred: Bool376    let fastest: Bool377378    var body: some View {379        VStack(alignment: .leading, spacing: 5) {380            HStack(spacing: 5) {381                ModelMark(logo: column.logo, name: column.displayName, size: 15, breathing: running && !column.isDone)382                Text(column.displayName).font(.caption2.weight(.semibold)).foregroundStyle(Color.textPrimary).lineLimit(1)383                Spacer(minLength: 0)384                if preferred { Image(systemName: "star.fill").font(.system(size: 9)).foregroundStyle(Color.orange) }385            }386            HStack(spacing: 6) {387                if column.error != nil {388                    Label("erreur", systemImage: "exclamationmark.triangle.fill").labelStyle(.titleAndIcon).foregroundStyle(Color.danger)389                } else if let t = column.ttftMs {390                    Text(Format.duration(ms: t)).foregroundStyle(fastest ? Color.accentColor : Color.textSecondary)391                    if let c = column.costUsd { Text(Format.usd(c)).foregroundStyle(Color.muted) }392                } else if !column.isDone {393                    Text(column.text.isEmpty ? String(localized: "en attente") : String(localized: "écrit…")).foregroundStyle(Color.muted)394                } else { Text("—").foregroundStyle(Color.muted) }395            }396            .font(.caption2.monospacedDigit()).lineLimit(1)397        }398        .padding(.horizontal, 10).padding(.vertical, 8)399        .frame(maxWidth: .infinity, minHeight: 48, alignment: .leading)400        .background(selected ? Color.accentSoft : Color.surface, in: .rect(cornerRadius: Radius.control + 2, style: .continuous))401        .overlay(RoundedRectangle(cornerRadius: Radius.control + 2, style: .continuous).strokeBorder(selected ? Color.accentColor.opacity(0.6) : Color.hairline, lineWidth: selected ? 1 : 0.75))402        .accessibilityElement(children: .ignore)403        .accessibilityLabel(summaryLabel)404        .accessibilityAddTraits(selected ? [.isButton, .isSelected] : .isButton)405        .accessibilityIdentifier("arena.summary")406    }407408    private var summaryLabel: String {409        if column.error != nil { return String(localized: "\(column.displayName) : erreur") }410        if let t = column.ttftMs { return String(localized: "\(column.displayName) : premier jeton en \(Format.duration(ms: t))") + (column.costUsd.map { ", " + Format.usd($0) } ?? "") }411        return String(localized: "\(column.displayName) : en cours")412    }413}414415/// One model of the comparison: identity, live answer, then its measured figures and actions.416struct ArenaColumnView: View {417    let column: ArenaColumn418    let session: ArenaSession419    let state: ArenaState420    @Environment(AppEnvironment.self) private var env421    @Environment(\.accessibilityReduceMotion) private var reduceMotion422    @State private var copied = false423424    private var streaming: Bool { state.isRunning && !column.isDone }425    private var isPreferred: Bool { state.preferred == column.id }426427    var body: some View {428        VStack(alignment: .leading, spacing: 12) {429            HStack(spacing: 6) {430                ModelChip(logo: column.logo, creatorName: AIModel.providerLabel(column.creator ?? column.provider), name: column.displayName, route: column.route, markSize: 18, font: .system(.subheadline, weight: .semibold), breathing: streaming)431                Spacer(minLength: 0)432                if isPreferred { Label("préférée", systemImage: "star.fill").font(.spMicro).foregroundStyle(Color.orange).labelStyle(.titleAndIcon) }433            }434            if let served = column.servedBy { Text(served).font(.caption2).foregroundStyle(Color.muted) }435            if env.preferences.showReasoning, !column.reasoning.isEmpty { ReasoningDisclosure(text: column.reasoning, streaming: streaming && column.text.isEmpty) }436437            if !column.text.isEmpty {438                MarkdownView(text: column.text).foregroundStyle(Color.textPrimary).textSelection(.enabled)439            } else if streaming {440                PresenceDots()441            }442            if let e = column.error { Banner(kind: column.text.isEmpty ? .error : .warning, text: e) }443444            metrics445            if column.isDone && !state.isRunning { actions }446        }447        .frame(maxWidth: .infinity, alignment: .leading)448        .accessibilityElement(children: .contain)449        .accessibilityIdentifier("arena.column")450    }451452    /// First token · duration · tokens · cost. Before the answer ends the only cost known is the server's input453    /// estimate; afterwards the cost is the billed amount (« facturé ») or tokens × list price (« estimé »).454    private var metrics: some View {455        let cost: (String, String?) = {456            if column.route == "local" { return (Format.usd(0), String(localized: "local")) }457            if let c = column.costUsd { return (Format.usd(c), column.exactCost ? String(localized: "facturé") : String(localized: "estimé")) }458            if let e = column.estimatedInputCostUsd { return ("≈ " + Format.usd(e), String(localized: "estimé · entrée seule")) }459            return ("—", nil)460        }()461        return VStack(alignment: .leading, spacing: 8) {462            LazyVGrid(columns: [GridItem(.flexible(), alignment: .topLeading), GridItem(.flexible(), alignment: .topLeading)], alignment: .leading, spacing: 12) {463                FactCell(title: String(localized: "Premier jeton"), value: Format.duration(ms: column.ttftMs), note: state.fastestFirstToken == column.id && !state.isRunning && state.columns.count > 1 ? String(localized: "le plus rapide") : nil)464                FactCell(title: String(localized: "Durée"), value: Format.duration(ms: column.latencyMs))465                FactCell(title: String(localized: "Jetons"), value: column.inputTokens != nil || column.outputTokens != nil ? "\(Format.tokens(column.inputTokens)) → \(Format.tokens(column.outputTokens))" : "—", note: String(localized: "entrée → sortie"))466                FactCell(title: String(localized: "Coût"), value: cost.0, note: cost.1)467            }468            if column.costUsd == nil, let basis = column.estimateBasis { SourceNote(text: basis) }469        }470        .padding(12)471        .background(Color.surface2.opacity(0.6), in: .rect(cornerRadius: Radius.card, style: .continuous))472        .animation(Motion.snappy(reduceMotion), value: column.isDone)473    }474475    private var actions: some View {476        ViewThatFits(in: .horizontal) {477            HStack(spacing: 8) { actionButtons }478            VStack(alignment: .leading, spacing: 8) { actionButtons }479        }480    }481482    @ViewBuilder private var actionButtons: some View {483        if column.error == nil || !column.text.isEmpty {484            Button {485                guard !isPreferred else { return }486                env.haptics.success()487                Task { await session.prefer(column.id) }488            } label: { ChipLabel(text: isPreferred ? String(localized: "Préférée") : String(localized: "Préférer"), systemImage: isPreferred ? "star.fill" : "star", selected: isPreferred).frame(minHeight: 44) }489                .buttonStyle(PressScale()).disabled(!session.isStored)490                .accessibilityIdentifier("arena.prefer")491        }492        if !column.text.isEmpty {493            Button {494                UIPasteboard.general.string = column.text; env.haptics.soften()495                withAnimation(Motion.snappy(reduceMotion)) { copied = true }496                Task { try? await Task.sleep(for: .seconds(1.6)); withAnimation(Motion.fade) { copied = false } }497            } label: { ChipLabel(text: copied ? String(localized: "Copié") : String(localized: "Copier"), systemImage: copied ? "checkmark" : "square.on.square").frame(minHeight: 44) }498                .buttonStyle(PressScale())499        }500        if session.conversationId != nil, column.error == nil, !column.text.isEmpty {501            let adopted = session.adoptedModel == column.id502            Button {503                Task {504                    if await session.adopt(column.id), let id = session.conversationId {505                        env.haptics.success()506                        await env.session(for: id).load(attach: false)507                        await env.conversations.refresh()508                    }509                }510            } label: {511                HStack(spacing: 6) {512                    if session.adoptingModel == column.id { ProgressView().controlSize(.small) }513                    ChipLabel(text: adopted ? String(localized: "Reprise dans la conversation") : String(localized: "Reprendre dans la conversation"), systemImage: adopted ? "checkmark" : "arrow.turn.down.left", selected: adopted)514                }515                .frame(minHeight: 44)516            }517            .buttonStyle(PressScale()).disabled(!session.isStored || session.adoptingModel != nil || adopted)518            .accessibilityHint(String(localized: "Ajoute cette réponse comme nouvelle version de la dernière réponse ; aucun modèle n’est rappelé"))519            .accessibilityIdentifier("arena.adopt")520        }521    }522}523524/// The judge's opinion — a model-generated evaluation, presented with the server's own disclaimer.525struct ArenaJudgementSheet: View {526    let judgement: ArenaJudgement527    let columns: [ArenaColumn]528    @Environment(AppEnvironment.self) private var env529    @Environment(\.dismiss) private var dismiss530531    var body: some View {532        NavigationStack {533            ScrollView {534                VStack(alignment: .leading, spacing: 14) {535                    if let d = judgement.disclaimer, !d.isEmpty { Banner(kind: .info, text: d, systemImage: "scalemass") }536                    HStack(spacing: 6) {537                        Text("Juge").font(.spMicro).foregroundStyle(Color.muted).textCase(.uppercase)538                        ModelChip(model: env.catalog.model(judgement.judgeModel), fallback: judgement.judgeModel, markSize: 15, font: .spCaption)539                        Spacer(minLength: 0)540                        if let c = judgement.costUsd { Text("\(Format.usd(c)) \(String(localized: "estimé"))").font(.caption2.monospacedDigit()).foregroundStyle(Color.muted) }541                    }542                    if !judgement.mapping.isEmpty {543                        // the judge saw anonymous answers: this is which letter was which model544                        VStack(alignment: .leading, spacing: 8) {545                            ForEach(judgement.mapping.keys.sorted(), id: \.self) { letter in546                                let id = judgement.mapping[letter] ?? ""547                                let col = columns.first { $0.id == id }548                                HStack(spacing: 8) {549                                    Text(letter).font(.system(.caption, design: .rounded, weight: .bold)).foregroundStyle(Color.accentColor).frame(width: 22, height: 22).background(Color.accentSoft, in: .rect(cornerRadius: 6, style: .continuous))550                                    ModelChip(logo: col?.logo, creatorName: AIModel.providerLabel(col?.creator ?? col?.provider), name: col?.displayName ?? id, route: col?.route, markSize: 15, font: .spCaption)551                                }552                                .accessibilityElement(children: .combine)553                                .accessibilityLabel(String(localized: "Réponse \(letter) : \(col?.displayName ?? id)"))554                            }555                        }556                        .padding(12).frame(maxWidth: .infinity, alignment: .leading).cardSurface()557                    }558                    MarkdownView(text: judgement.text).foregroundStyle(Color.textPrimary).textSelection(.enabled)559                }560                .padding(16).frame(maxWidth: 720).frame(maxWidth: .infinity)561            }562            .background(Color.appBackground)563            .navigationTitle("Avis du juge").navigationBarTitleDisplayMode(.inline)564            .toolbar {565                ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() } }566                ToolbarItem(placement: .topBarLeading) { ShareLink(item: judgement.text) { Image(systemName: "square.and.arrow.up") }.accessibilityLabel(String(localized: "Partager l’avis")) }567            }568        }569        .accessibilityIdentifier("arena.judge")570    }571}572
Files main
Menu

Theme