SPB Git

Repository Public

CompareScreen.swift 32.5 KB 600 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Workspace/CompareScreen.swift3// Description: Arena: the same prompt streamed to 2–6 models of any route in side-by-side columns, preferred answer, judge, adoption, export, history; plus the detached-run stream follower shared with deep research.4import SwiftUI5import AppKit6import UniformTypeIdentifiers7import SPChatCore89// MARK: - Detached run follower (shared by comparison and deep research)1011enum RunStreamEnd {12    /// The server sent its terminal `end` event.13    case ended14    /// The run is no longer in the server's memory: the saved row holds the result.15    case gone16    /// The connection dropped and could not be re-established; the run may still be going on the server.17    case lost18    /// The consuming task was cancelled (stop, or the screen went away).19    case cancelled20}2122/// Reads the SSE stream of a detached server run (`run` event first, `end` last) and re-attaches with23/// `GET /api/chat/stream?run=<id>&after=<last index>` when the connection drops before `end`.24final class RunFollower {25    private let api: APIClient26    private(set) var runId: String?27    private(set) var last = -12829    init(api: APIClient) { self.api = api }3031    /// Throws only when the first opening fails (validation, budget, 409…). `handle` receives every event except `run` and `end`.32    func follow(maxReattach: Int = 6, open: () async throws -> APIClient.StreamOpening,33                onReconnecting: (Bool) -> Void = { _ in }, handle: (String, JSONValue) -> Void) async throws -> RunStreamEnd {34        guard case .events(_, let first) = try await open() else { throw APIError(.decoding, message: "Réponse inattendue du serveur.") }35        var bytes: AsyncThrowingStream<Data, Error>? = first36        var tries = 037        while true {38            if let current = bytes {39                let before = last40                if await consume(current, handle: handle) { return .ended }41                if last > before { tries = 0 }42                bytes = nil43            }44            if Task.isCancelled { return .cancelled }45            guard let runId else { return .lost }46            tries += 147            if tries > maxReattach { return .lost }48            onReconnecting(true)49            try? await Task.sleep(for: .seconds(min(1 << min(tries - 1, 4), 15)))50            if Task.isCancelled { return .cancelled }51            do {52                guard case .events(_, let next) = try await api.openStream(.get, "/api/chat/stream", query: ["run": runId, "after": String(last)]) else { return .gone }53                bytes = next54                onReconnecting(false)55            } catch let e as APIError {56                if e.status == 410 || e.status == 404 { return .gone }57                if e.kind == .cancelled { return .cancelled }58                if e.kind == .locked { throw e }59            } catch { return .lost }60        }61    }6263    /// True when `end` was read; false when the body closed or failed before it.64    private func consume(_ bytes: AsyncThrowingStream<Data, Error>, handle: (String, JSONValue) -> Void) async -> Bool {65        var parser = SSEParser()66        do {67            for try await chunk in bytes {68                for ev in parser.feed(chunk) {69                    if let i = ev.index { last = i }70                    if ev.event == "end" { return true }71                    let data = JSONValue.parse(Data(ev.data.utf8)) ?? .null72                    if ev.event == "run" { if let id = data["runId"]?.stringValue, !id.isEmpty { runId = id }; continue }73                    handle(ev.event, data)74                }75            }76        } catch { /* dropped connection: the caller re-attaches */ }77        return false78    }79}8081/// A budget refusal (HTTP 402) gets its own wording so that it cannot be mistaken for a network problem.82func workspaceErrorText(_ error: Error) -> String {83    guard let e = error as? APIError else { return (error as? LocalizedError)?.errorDescription ?? String(describing: error) }84    if e.status == 402 || e.code == "budget" { return "Budget atteint — \(e.message)" }85    return e.message86}8788// MARK: - Model8990@Observable final class ArenaViewModel {91    static let minModels = 2, maxModels = 69293    var selected: [String] = []94    var prompt = ""95    var effort: Effort?96    var judgeModel = ""9798    private(set) var columns: [ArenaColumn] = []99    private(set) var running = false100    private(set) var stopping = false101    private(set) var reconnecting = false102    private(set) var comparisonId: String?103    private(set) var preferred: String?104    /// The columns show a past comparison loaded from the history.105    private(set) var fromHistory = false106    private(set) var judge: ArenaJudge?107    private(set) var judging = false108    private(set) var loadingComparison = false109    /// Model whose answer is being adopted into a conversation.110    private(set) var adopting: String?111    private(set) var exporting = false112    var errorText: String?113    /// The stream ended without `end`: the result must be reloaded from the server.114    private(set) var connectionLost = false115116    private(set) var history: [ArenaHistoryItem] = []117    private(set) var historyLoading = false118    private(set) var historyError: String?119    private(set) var historyLoaded = false120121    @ObservationIgnored private var task: Task<Void, Never>?122    @ObservationIgnored private var follower: RunFollower?123    /// Events are folded here as they arrive; text deltas are published to `columns` ~30 times per second.124    @ObservationIgnored private var accumulator = ArenaAccumulator()125    @ObservationIgnored private var dirty = false126    @ObservationIgnored private var defaultsApplied = false127128    var canRun: Bool { !running && (Self.minModels...Self.maxModels).contains(selected.count) && !prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }129    var comparableAnswers: Int { columns.filter(\.hasAnswer).count }130    /// The comparison is stored on the server: it can be preferred, judged, adopted, exported.131    var canAct: Bool { comparisonId != nil && !running }132133    func applyDefaults(models: [AIModel]) {134        guard !models.isEmpty else { return }135        let ok = Set(models.map(\.id))136        selected.removeAll { !ok.contains($0) }137        if !ok.contains(judgeModel) { judgeModel = models.first { $0.provider == "anthropic" && $0.kind == "chat" && !$0.isOpenRouter }?.id ?? models[0].id }138        guard !defaultsApplied else { return }139        defaultsApplied = true140        if selected.isEmpty { selected = models.filter(\.favorite).prefix(3).map(\.id) }141    }142143    /// Models handed over by the palette or the Explorer compare tray replace the selection (unknown ids are skipped).144    func preselect(_ ids: [String], catalog: CatalogStore) {145        guard !running else { return }146        var seen = Set<String>()147        let usable = ids.filter { id in seen.insert(id).inserted && (catalog.model(id).map { $0.isSelectableForChat } ?? false) }148        guard !usable.isEmpty else { return }149        selected = Array(usable.prefix(Self.maxModels)); defaultsApplied = true150    }151152    func toggle(_ id: String) {153        guard !running else { return }154        if let i = selected.firstIndex(of: id) { selected.remove(at: i) } else if selected.count < Self.maxModels { selected.append(id) }155    }156157    // MARK: Run158159    func start(env: AppEnvironment) {160        guard canRun else { return }161        let ids = selected, text = prompt, effort = effort?.rawValue162        accumulator = ArenaAccumulator(modelIds: ids) { env.catalog.model($0)?.provider }163        columns = accumulator.columns; dirty = false164        running = true; stopping = false; reconnecting = false; connectionLost = false; errorText = nil165        comparisonId = nil; preferred = nil; judge = nil; fromHistory = false166        let follower = RunFollower(api: env.api); self.follower = follower167168        task = Task {169            let flusher = Task { while !Task.isCancelled { try? await Task.sleep(for: .milliseconds(33)); self.flush() } }170            var end = RunStreamEnd.lost171            do {172                end = try await follower.follow(maxReattach: 4, open: { try await env.api.openArena(prompt: text, modelIds: ids, effort: effort) },173                                                onReconnecting: { self.reconnecting = $0 }, handle: { self.handle(ArenaEvent(event: $0, data: $1)) })174            } catch {175                end = .cancelled176                if (error as? APIError)?.kind != .cancelled { errorText = workspaceErrorText(error); accumulator = ArenaAccumulator() }177            }178            flusher.cancel()179            reconnecting = false180            var reloaded = false181            switch end {182            case .ended, .cancelled: break183            case .gone: if let id = comparisonId { reloaded = await load(id, env: env, keepSetup: true) } else { connectionLost = true }184            case .lost: connectionLost = true185            }186            if !reloaded { accumulator.close(); columns = accumulator.columns }187            running = false; stopping = false188            self.follower = nil; task = nil189            await loadHistory(env.api)190        }191    }192193    private func handle(_ event: ArenaEvent) {194        guard accumulator.apply(event) else { return }195        switch event {196        case .text, .reasoning: dirty = true197        default:198            columns = accumulator.columns; dirty = false199            comparisonId = accumulator.comparisonId ?? comparisonId200            if case .failure(let message) = event { errorText = message }201        }202    }203204    private func flush() {205        guard dirty else { return }206        dirty = false; columns = accumulator.columns207    }208209    /// Stop = cancel the run on the server (the provider calls are aborted); the stream then closes by itself.210    func stop(env: AppEnvironment) {211        guard running, !stopping else { return }212        stopping = true213        let runId = follower?.runId214        let current = task215        Task {216            if let runId { try? await env.api.cancelGeneration(runId: runId, messageId: nil) }217            else { current?.cancel(); return }218            try? await Task.sleep(for: .seconds(2))219            current?.cancel() // the server did not close the stream in time: stop listening anyway220        }221    }222223    /// The screen went away: only the UI subscription stops, the server run continues and is saved in the history.224    func detach() { task?.cancel() }225226    // MARK: After the run227228    func prefer(_ modelId: String, env: AppEnvironment) {229        guard let id = comparisonId else { return }230        let previous = preferred; preferred = modelId231        Task {232            do {233                try await env.api.preferArenaAnswer(comparisonId: id, modelId: modelId)234                env.toasts.show("\(env.catalog.displayName(forModel: modelId)) marqué comme réponse préférée")235                await loadHistory(env.api)236            } catch { preferred = previous; env.toasts.error(error) }237        }238    }239240    func runJudge(env: AppEnvironment) {241        guard let id = comparisonId, !judgeModel.isEmpty, !judging else { return }242        judging = true243        Task {244            do {245                if let parsed = try await env.api.judgeArena(comparisonId: id, judgeModel: judgeModel) { judge = parsed } else { errorText = "Le juge n'a rien renvoyé." }246            } catch { errorText = "Évaluation impossible : \(workspaceErrorText(error))" }247            judging = false248        }249    }250251    /// Brings the answer of `modelId` into a conversation (`conversationId == nil` → a new one) and returns its id.252    /// No model is called again: the server copies the stored answer with its measured figures.253    func adopt(_ modelId: String, into conversationId: String?, env: AppEnvironment) async -> String? {254        guard let id = comparisonId, adopting == nil else { return nil }255        adopting = modelId; defer { adopting = nil }256        do {257            var target = conversationId258            if target == nil {259                let title = String(prompt.trimmingCharacters(in: .whitespacesAndNewlines).prefix(60))260                let conv = try await env.api.createConversation(title: title.isEmpty ? "Réponse de l'Arena" : title, modelId: modelId)261                env.conversations.upsert(conv); target = conv.id262            }263            guard let target else { return nil }264            try await env.api.adoptArenaAnswer(conversationId: target, comparisonId: id, modelId: modelId)265            preferred = modelId // the server marks the adopted answer as the preferred one266            env.toasts.show("Réponse de \(env.catalog.displayName(forModel: modelId)) adoptée dans la conversation")267            await env.conversations.refreshQuietly()268            return target269        } catch { env.toasts.show("Adoption impossible : \(workspaceErrorText(error))", isError: true); return nil }270    }271272    /// The export document written by the server (`GET /api/compare/export`).273    func exportFile(_ format: ArenaExportFormat, api: APIClient) async throws -> DownloadedFile {274        guard let id = comparisonId else { throw APIError(.decoding, message: "Aucune comparaison enregistrée à exporter.") }275        exporting = true; defer { exporting = false }276        return try await api.exportArena(comparisonId: id, format: format)277    }278279    func loadHistory(_ api: APIClient) async {280        historyLoading = true; historyError = nil281        do { history = try await api.arenaHistory(); historyLoaded = true }282        catch { if (error as? APIError)?.kind != .cancelled { historyError = workspaceErrorText(error) } }283        historyLoading = false284    }285286    /// Re-displays a saved comparison. `keepSetup` leaves the prompt and the selection untouched (reload after a lost stream).287    @discardableResult func load(_ id: String, env: AppEnvironment, keepSetup: Bool = false) async -> Bool {288        guard !running || keepSetup else { return false }289        loadingComparison = true; defer { loadingComparison = false }290        do {291            guard let c = try await env.api.arenaComparison(id) else {292                errorText = keepSetup ? "La comparaison n'est pas encore enregistrée sur le serveur. Réessaie dans un instant." : "Comparaison introuvable."293                return false294            }295            show(c, keepSetup: keepSetup, known: Set(env.catalog.selectableModels.map(\.id)))296            return true297        } catch { errorText = workspaceErrorText(error); return false }298    }299300    /// Displays a stored comparison. `known` = ids that can be selected again (nil keeps every id).301    func show(_ c: ArenaComparison, keepSetup: Bool = false, known: Set<String>? = nil) {302        columns = c.columns; comparisonId = c.id; preferred = c.preferredModel; judge = c.judge303        connectionLost = false; errorText = nil304        guard !keepSetup else { return }305        fromHistory = true; prompt = c.prompt306        selected = Array(c.modelIds.filter { known?.contains($0) ?? true }.prefix(Self.maxModels))307    }308309    func reloadAfterLoss(env: AppEnvironment) {310        Task {311            if let id = comparisonId { await load(id, env: env, keepSetup: true) }312            else { errorText = "La comparaison n'avait pas encore d'identifiant : ouvre l'historique pour retrouver son résultat une fois terminée."; connectionLost = false }313            await loadHistory(env.api)314        }315    }316317    func clearResults() { guard !running else { return }; columns = []; comparisonId = nil; preferred = nil; judge = nil; fromHistory = false; connectionLost = false; errorText = nil }318}319320// MARK: - Screen321322struct CompareScreen: View {323    @Bindable var window: WindowModel324    @Environment(AppEnvironment.self) private var env325    @State private var model: ArenaViewModel326    @State private var showHistory = false327    @State private var showPicker = false328    @State private var showVerdict = true329330    /// `model` lets a caller (tests, previews) show a prepared state; the screen owns a fresh one otherwise.331    init(window: WindowModel, model: ArenaViewModel = ArenaViewModel()) { self.window = window; _model = State(initialValue: model) }332333    private var models: [AIModel] { env.catalog.selectableModels }334335    var body: some View {336        VStack(alignment: .leading, spacing: DS.S.l) {337            header338            setup339            if let text = model.errorText { Banner(kind: .error, text: text, onDismiss: { model.errorText = nil }) }340            if model.connectionLost {341                Banner(kind: .warning, text: "Connexion perdue avant la fin. La comparaison continue sur le serveur ; son résultat sera enregistré dans l'historique.",342                       actionTitle: "Recharger le résultat", action: { model.reloadAfterLoss(env: env) })343            }344            if model.reconnecting { Banner(kind: .info, text: "Connexion interrompue : reconnexion au flux en cours…") }345            if model.columns.isEmpty {346                EmptyStateView(systemImage: "rectangle.split.3x1", title: model.loadingComparison ? "Chargement de la comparaison…" : "Aucune comparaison affichée",347                               message: model.loadingComparison ? nil : (models.count < 2 ? "Il faut au moins deux modèles disponibles pour comparer." : "Choisis de deux à six modèles, écris une invite et lance la comparaison."))348                    .frame(maxWidth: .infinity, maxHeight: .infinity)349            } else {350                ArenaColumns(model: model, onContinue: continueWith, onAdopt: adopt)351                if !model.running { judgeCard }352            }353        }354        .padding(DS.S.xxl)355        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)356        .background(DS.C.bg)357        .environment(\.transcriptFontSize, 13)358        .task {359            if !env.catalog.loaded { await env.catalog.load() }360            model.applyDefaults(models: models)361            consumePreselection()362            if !model.historyLoaded { await model.loadHistory(env.api) }363        }364        .onChange(of: models.map(\.id)) { model.applyDefaults(models: models) }365        .onChange(of: window.arenaModelIds) { consumePreselection() }366        .onChange(of: window.arenaComparisonId, initial: true) { _, id in if let id { window.arenaComparisonId = nil; Task { await model.load(id, env: env) } } }367        .onDisappear { model.detach() }368        .sheet(isPresented: $showHistory) { ArenaHistorySheet(model: model, isPresented: $showHistory) }369    }370371    /// `window.arenaModelIds` is a hand-over: consumed once, then cleared.372    private func consumePreselection() {373        guard !window.arenaModelIds.isEmpty else { return }374        model.preselect(window.arenaModelIds, catalog: env.catalog)375        window.arenaModelIds = []376    }377378    private var header: some View {379        HStack(alignment: .firstTextBaseline, spacing: DS.S.l) {380            VStack(alignment: .leading, spacing: 2) {381                Text("Arena").font(DS.F.title).foregroundStyle(DS.C.text)382                Text("La même invite, envoyée en même temps à 2 à 6 modèles de n'importe quelle route. Réponses, délais, jetons et coûts côte à côte.")383                    .font(DS.F.uiRegular).foregroundStyle(DS.C.text2).lineLimit(2)384            }385            Spacer(minLength: DS.S.l)386            Menu {387                Button("Markdown (.md)") { export(.markdown) }388                Button("JSON (.json)") { export(.json) }389            } label: { Label("Exporter", systemImage: "square.and.arrow.up") }390                .fixedSize().disabled(!model.canAct || model.exporting)391                .help("Document écrit par le serveur : invite, réponses et mesures").accessibilityIdentifier("arena-export")392            Button { showHistory = true; Task { await model.loadHistory(env.api) } } label: {393                Label(model.history.isEmpty ? "Historique" : "Historique (\(model.history.count))", systemImage: "clock.arrow.circlepath")394            }395            .accessibilityIdentifier("arena-history")396        }397    }398399    private var setup: some View {400        @Bindable var model = model401        return VStack(alignment: .leading, spacing: DS.S.l) {402            CompareFlow(spacing: 6) {403                ForEach(model.selected, id: \.self) { id in404                    HStack(spacing: 2) {405                        ModelChip(identity: env.catalog.identity(for: id), markSize: 15, font: DS.F.caption)406                        IconButton(systemImage: "xmark", label: "Retirer \(env.catalog.displayName(forModel: id))") { model.toggle(id) }407                            .font(.system(size: 9, weight: .bold)).foregroundStyle(DS.C.muted).disabled(model.running)408                    }409                    .padding(.leading, 9).padding(.trailing, 2).frame(height: 28)410                    .background(DS.C.surface2, in: Capsule()).overlay(Capsule().strokeBorder(DS.C.border, lineWidth: 1))411                }412                Button { showPicker = true } label: { Label(model.selected.isEmpty ? "Choisir des modèles" : "Ajouter", systemImage: "plus") }413                    .buttonStyle(ChipStyle(selected: showPicker)).frame(height: 28)414                    .disabled(model.running).accessibilityIdentifier("arena-add-model")415                    .popover(isPresented: $showPicker, arrowEdge: .bottom) { ArenaModelPicker(model: model) }416                Text("\(model.selected.count) / \(ArenaViewModel.maxModels)").font(DS.F.caption.monospacedDigit()).foregroundStyle(DS.C.muted).frame(height: 28)417            }418            ZStack(alignment: .topLeading) {419                TextEditor(text: $model.prompt)420                    .font(.body).scrollContentBackground(.hidden).frame(minHeight: model.columns.isEmpty ? 96 : 44, maxHeight: model.columns.isEmpty ? 220 : 88).fixedSize(horizontal: false, vertical: true)421                    .accessibilityLabel("Invite à comparer").accessibilityIdentifier("compare-prompt")422                if model.prompt.isEmpty { Text("Écris l'invite envoyée à tous les modèles…").foregroundStyle(DS.C.muted).padding(.leading, 5).allowsHitTesting(false) }423            }424            .padding(DS.S.s).background(DS.C.bg, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))425            .overlay(RoundedRectangle(cornerRadius: DS.R.control, style: .continuous).strokeBorder(DS.C.border, lineWidth: 1))426            HStack(spacing: DS.S.l) {427                Picker("Effort de raisonnement", selection: $model.effort) {428                    Text("Par défaut").tag(Effort?.none)429                    ForEach(Effort.allCases, id: \.self) { Text($0.label).tag(Effort?.some($0)) }430                }431                .fixedSize().disabled(model.running).controlSize(.small)432                .help("Appliqué aux modèles qui acceptent un niveau d'effort.")433                if model.fromHistory { Label("Comparaison passée, affichée depuis l'historique", systemImage: "clock.arrow.circlepath").font(DS.F.caption).foregroundStyle(DS.C.muted).lineLimit(1) }434                Spacer()435                if model.selected.count < ArenaViewModel.minModels { Text("Choisis au moins deux modèles.").font(DS.F.caption).foregroundStyle(DS.C.muted) }436                if !model.columns.isEmpty && !model.running { Button("Effacer") { model.clearResults() }.help("Retire les résultats affichés (la comparaison reste dans l'historique)") }437                if model.running {438                    Button(role: .cancel) { model.stop(env: env) } label: { Label(model.stopping ? "Arrêt…" : "Arrêter", systemImage: "stop.fill") }439                        .disabled(model.stopping).accessibilityIdentifier("compare-stop")440                } else {441                    Button { model.start(env: env) } label: { Label("Comparer", systemImage: "play.fill") }442                        .buttonStyle(.borderedProminent).tint(DS.C.accent).keyboardShortcut(.return, modifiers: .command).disabled(!model.canRun)443                        .accessibilityIdentifier("compare-start")444                }445            }446        }447        .card()448        .overlay(alignment: .top) { LumenLine(active: model.running, cornerInset: DS.R.card).offset(y: -2.5) }449    }450451    private var judgeCard: some View {452        VStack(alignment: .leading, spacing: DS.S.m) {453            HStack(spacing: DS.S.l) {454                Label("Juge", systemImage: "scalemass").font(DS.F.ui).foregroundStyle(DS.C.text)455                Menu {456                    ForEach(env.catalog.menuModels) { m in Button { model.judgeModel = m.id } label: { Text(m.displayName + (m.isOpenRouter ? " — OpenRouter" : "")) } }457                } label: { ModelChip(identity: env.catalog.identity(for: model.judgeModel.isEmpty ? nil : model.judgeModel), markSize: 14, font: DS.F.caption) }458                    .menuStyle(.borderlessButton).fixedSize().disabled(model.judging).accessibilityLabel("Modèle juge")459                Button(model.judge == nil ? "Évaluer les réponses" : "Réévaluer") { model.runJudge(env: env) }460                    .controlSize(.small).disabled(model.judging || !model.canAct || model.comparableAnswers < 2 || model.judgeModel.isEmpty).accessibilityIdentifier("arena-judge")461                if model.judging { Text("Évaluation en cours…").font(DS.F.caption).foregroundStyle(DS.C.muted) }462                Spacer(minLength: DS.S.m)463                Text(judgeHint).font(DS.F.caption).foregroundStyle(DS.C.muted).lineLimit(2).multilineTextAlignment(.trailing)464            }465            if let judge = model.judge {466                Divider()467                HStack(spacing: DS.S.l) {468                    ModelChip(identity: env.catalog.identity(for: judge.judgeModel), markSize: 14, font: DS.F.caption)469                    Text("\(Format.usd(judge.costUsd)) · estimé").font(DS.F.caption.monospacedDigit()).foregroundStyle(DS.C.muted).help("Coût de l'évaluation : jetons × prix catalogue")470                    Text(judge.mapping.map { "\($0.label) = \(env.catalog.displayName(forModel: $0.modelId))" }.joined(separator: " · ")).font(DS.F.caption).foregroundStyle(DS.C.text2).lineLimit(1).truncationMode(.middle)471                    Spacer(minLength: 0)472                    Button(showVerdict ? "Replier l'avis" : "Lire l'avis") { showVerdict.toggle() }.buttonStyle(.link).font(DS.F.caption)473                }474                if showVerdict { ScrollView { MarkdownView(text: judge.text).textSelection(.enabled).padding(.trailing, DS.S.m) }.frame(maxHeight: 132) }475                Label(judge.disclaimer, systemImage: "exclamationmark.triangle").font(DS.F.caption).foregroundStyle(DS.C.muted)476            }477        }478        .frame(maxWidth: .infinity, alignment: .leading).card(padding: DS.S.l)479        .overlay(alignment: .top) { LumenLine(active: model.judging, cornerInset: DS.R.card).offset(y: -2.5) }480    }481482    private var judgeHint: String {483        if model.comparisonId == nil { return "Disponible une fois la comparaison enregistrée." }484        if model.comparableAnswers < 2 { return "Il faut au moins deux réponses sans erreur." }485        return "Lecture anonyme (A, B, C…) par un modèle : une opinion, facturée comme une requête."486    }487488    // MARK: Actions489490    private func export(_ format: ArenaExportFormat) {491        Task {492            do {493                let file = try await model.exportFile(format, api: env.api)494                let ext = format == .json ? "json" : "md"495                SavePanel.save(file.data, name: file.filename ?? "arene.\(ext)", type: format == .json ? .json : (UTType(filenameExtension: "md") ?? .plainText), env: env)496            } catch { env.toasts.show("Export impossible : \(workspaceErrorText(error))", isError: true) }497        }498    }499500    private func adopt(_ modelId: String, _ conversationId: String?) {501        Task { if let id = await model.adopt(modelId, into: conversationId, env: env) { window.open(id) } }502    }503504    /// Opens a new conversation set to that model; the prompt is put on the clipboard and never sent automatically.505    private func continueWith(_ modelId: String) {506        let prompt = model.prompt507        Task {508            do {509                let title = String(prompt.trimmingCharacters(in: .whitespacesAndNewlines).prefix(60))510                let conv = try await env.api.createConversation(title: title.isEmpty ? "Suite de comparaison" : title, modelId: modelId)511                env.conversations.upsert(conv)512                NSPasteboard.general.clearContents(); NSPasteboard.general.setString(prompt, forType: .string)513                env.toasts.show("Conversation créée — l'invite est dans le presse-papiers")514                window.open(conv.id)515            } catch { env.toasts.error(error) }516        }517    }518}519520// MARK: - History521522private struct ArenaHistorySheet: View {523    let model: ArenaViewModel524    @Binding var isPresented: Bool525    @Environment(AppEnvironment.self) private var env526527    var body: some View {528        VStack(alignment: .leading, spacing: 0) {529            HStack {530                Label("Comparaisons passées", systemImage: "clock.arrow.circlepath").font(DS.F.heading)531                Spacer()532                IconButton(systemImage: "arrow.clockwise", label: "Actualiser l'historique") { Task { await model.loadHistory(env.api) } }.disabled(model.historyLoading)533                Button("Fermer") { isPresented = false }.keyboardShortcut(.cancelAction)534            }535            .padding(14)536            Divider()537            if let error = model.historyError {538                Banner(kind: .error, text: error, actionTitle: "Réessayer", action: { Task { await model.loadHistory(env.api) } }).padding(12)539            }540            if model.history.isEmpty {541                if model.historyLoading { Text("Chargement…").font(DS.F.uiRegular).foregroundStyle(DS.C.muted).frame(maxWidth: .infinity, maxHeight: .infinity) }542                else if model.historyError == nil { EmptyStateView(systemImage: "clock", title: "Aucune comparaison enregistrée").frame(maxWidth: .infinity, maxHeight: .infinity) }543                else { Spacer() }544            } else {545                List(model.history) { item in546                    Button {547                        isPresented = false548                        Task { await model.load(item.id, env: env) }549                    } label: {550                        VStack(alignment: .leading, spacing: 5) {551                            Text(item.prompt).font(DS.F.uiRegular).lineLimit(2).frame(maxWidth: .infinity, alignment: .leading)552                            HStack(spacing: 8) {553                                HStack(spacing: 3) { ForEach(item.modelIds.prefix(6), id: \.self) { ModelMark(env.catalog.identity(for: $0), size: 14).help(env.catalog.identity(for: $0).name) } }554                                if let d = item.createdAt { Text(Format.relative(d)) }555                                if let c = item.cost { Text(Format.usd(c)).monospacedDigit() }556                                if let p = item.preferredModel { Label(env.catalog.displayName(forModel: p), systemImage: "trophy.fill").foregroundStyle(DS.C.accent).lineLimit(1) }557                            }558                            .font(DS.F.caption).foregroundStyle(DS.C.muted)559                        }560                        .padding(.vertical, 2).contentShape(Rectangle())561                    }562                    .buttonStyle(.plain).disabled(model.running)563                    .accessibilityLabel("\(item.prompt), \(item.modelIds.map { env.catalog.identity(for: $0).name }.joined(separator: ", "))")564                    .listRowBackground(item.id == model.comparisonId ? DS.C.accentSoft : Color.clear)565                }566                .listStyle(.inset)567                if model.running { Text("Une comparaison est en cours : attends sa fin pour en ouvrir une autre.").font(DS.F.caption).foregroundStyle(DS.C.muted).padding(10) }568            }569        }570        .frame(width: 520, height: 540)571    }572}573574// MARK: - Flow layout (model chips)575576struct CompareFlow: Layout {577    var spacing: CGFloat = 6578579    nonisolated func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {580        let width = proposal.width ?? .infinity581        var x: CGFloat = 0, y: CGFloat = 0, row: CGFloat = 0, maxX: CGFloat = 0582        for s in subviews {583            let size = s.sizeThatFits(.unspecified)584            if x > 0, x + size.width > width { x = 0; y += row + spacing; row = 0 }585            x += size.width + spacing; row = max(row, size.height); maxX = max(maxX, x - spacing)586        }587        return CGSize(width: maxX, height: y + row)588    }589590    nonisolated func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {591        var x = bounds.minX, y = bounds.minY, row: CGFloat = 0592        for s in subviews {593            let size = s.sizeThatFits(.unspecified)594            if x > bounds.minX, x + size.width > bounds.maxX { x = bounds.minX; y += row + spacing; row = 0 }595            s.place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(size))596            x += size.width + spacing; row = max(row, size.height)597        }598    }599}600
Files main
Menu

Theme