SPB Git

Repository Public MIT

ArenaScreen.swift 34.2 KB 657 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraUI/Sources/Arena/ArenaScreen.swift10// Module           : Arena11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2214//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import SwiftUI89import AstraCore90import AstraDesign91import AstraPersistence9293enum ArenaRoute: Hashable { case live, history, session(String) }9495/// Everything the person chose for the next comparison.96struct ArenaDraft: Equatable {97    var competitors: [ModelRef] = []98    var prompt = ""99    var system = ""100    var parameters = GenerationParameters(maxOutputTokens: 1_024)101    var blind = false102    var templateID: String?103    var templateName: String?104105    static let maxCompetitors = 4106    var trimmedPrompt: String { prompt.trimmingCharacters(in: .whitespacesAndNewlines) }107}108109/// Astra Arena: one prompt, two to four models, side by side. Measurements only; the only verdict is the person's own pick.110struct ArenaScreen: View {111    @Environment(AppModel.self) private var app112    @State private var path: [ArenaRoute] = []113    @State private var live: ArenaController?114    @State private var draft = ArenaDraft()115    @State private var restored = false116117    var body: some View {118        NavigationStack(path: $path) {119            ArenaSetupView(draft: $draft, live: live, onRun: { await run() }, onOpenLive: { path.append(.live) })120                .navigationTitle("Arena")121                .toolbar {122                    ToolbarItem(placement: .topBarTrailing) {123                        Button { path.append(.history) } label: { Label("History", systemImage: "clock.arrow.circlepath") }124                            .accessibilityIdentifier("arena-history")125                    }126                }127                .navigationDestination(for: ArenaRoute.self) { route in128                    switch route {129                    case .live:130                        if let live { ArenaSessionView(controller: live, onReuse: reuse) }131                    case .history:132                        ArenaHistoryView(onOpen: { path.append(.session($0)) })133                    case .session(let id):134                        ArenaStoredSessionView(sessionID: id, onReuse: reuse)135                    }136                }137        }138        .task { await restore() }139    }140141    private func restore() async {142        guard !restored else { return }143        restored = true144        let ids: [String] = (try? await app.store.setting("arena.lastCompetitors", default: [String]())) ?? []145        if draft.competitors.isEmpty {146            draft.competitors = ids.compactMap { ModelRef(id: $0) }.filter { app.library.info(for: $0) != nil && app.library.availability(of: $0) == nil }147        }148        #if DEBUG149        if app.options.screen == "arena-history" { path = [.history] }150        // Screenshot and test hook: -ORIXArenaModels "<ref>,<ref>" -ORIXArenaPrompt "<text>" [-ORIXArenaBlind YES] starts a real comparison.151        let defaults = UserDefaults.standard152        if let list = defaults.string(forKey: "ORIXArenaModels"), let prompt = defaults.string(forKey: "ORIXArenaPrompt") {153            draft.competitors = list.split(separator: ",").compactMap { ModelRef(id: String($0)) }154            draft.prompt = prompt; draft.blind = defaults.bool(forKey: "ORIXArenaBlind")155            await run()156        }157        #endif158    }159160    private func run() async {161        let controller = ArenaController(store: app.store, library: app.library, orchestrator: app.orchestrator)162        live?.stopAll()163        let ok = await controller.start(prompt: draft.trimmedPrompt, system: draft.system, parameters: draft.parameters, blind: draft.blind,164                                        templateID: draft.templateID, competitors: draft.competitors)165        guard ok else { app.show(controller.failure?.message ?? "The comparison could not be started.", .error); return }166        try? await app.store.setSetting("arena.lastCompetitors", draft.competitors.map(\.id))167        live = controller168        AstraHaptics.send()169        path.append(.live)170    }171172    /// Copies a past session into the setup form.173    private func reuse(_ session: ArenaSessionRecord, _ models: [ModelRef]) {174        draft.prompt = session.prompt; draft.system = session.system; draft.blind = session.blind175        draft.parameters = session.parameters176        if draft.parameters.maxOutputTokens == nil { draft.parameters.maxOutputTokens = 1_024 }177        draft.templateID = session.templateID; draft.templateName = nil178        draft.competitors = models.filter { app.library.availability(of: $0) == nil }179        path = []180    }181}182183// MARK: - Setup184185struct ArenaSetupView: View {186    @Environment(AppModel.self) private var app187    @Binding var draft: ArenaDraft188    let live: ArenaController?189    let onRun: () async -> Void190    let onOpenLive: () -> Void191192    @State private var showPicker = false193    @State private var showTemplates = false194    @State private var showSystem = false195    @State private var localNotice = false196    @State private var budgetOn = false197    @State private var budgetText = ""198    @State private var budgetLoaded = false199    @State private var confirmRun = false200    @State private var isStarting = false201202    private var preflight: ArenaPreflight {203        ArenaPreflight.make(prompt: draft.trimmedPrompt, system: draft.system, parameters: draft.parameters, competitors: draft.competitors, library: app.library)204    }205    private var budget: Double? {206        guard budgetOn, let value = Double(budgetText.replacingOccurrences(of: ",", with: ".")), value > 0 else { return nil }207        return value208    }209    private var blocker: String? {210        if !app.library.hasAnyUsableModel { return "Add a model in the Models tab first." }211        if draft.competitors.count < 2 { return "Choose at least two models." }212        if draft.trimmedPrompt.isEmpty { return "Write the prompt to send." }213        return nil214    }215216    var body: some View {217        let preflight = self.preflight218        ScrollView {219            VStack(alignment: .leading, spacing: AstraSpace.xl) {220                if let live, live.session != nil { liveCard(live) }221                competitorsSection(preflight)222                promptSection223                parametersSection224                costSection(preflight)225                runSection(preflight)226            }227            .padding(.horizontal, AstraSpace.page).padding(.vertical, AstraSpace.lg)228        }229        .scrollDismissesKeyboard(.interactively)230        .background(Starfield(density: 0.5))231        .keyboardDoneButton()232        .sheet(isPresented: $showPicker) {233            ModelPickerSheet(selected: nil, title: "Add a competitor") { add($0) }234        }235        .sheet(isPresented: $showTemplates) {236            ArenaTemplateSheet { template, rendered in237                draft.prompt = rendered.user; draft.system = rendered.system238                draft.templateID = template.id; draft.templateName = template.name239                var p = template.parameters240                if p.maxOutputTokens == nil { p.maxOutputTokens = draft.parameters.maxOutputTokens ?? 1_024 }241                draft.parameters = p242                if !rendered.system.isEmpty { showSystem = true }243            }244        }245        .confirmationDialog(confirmTitle(preflight), isPresented: $confirmRun, titleVisibility: .visible) {246            Button("Run anyway") { start() }247            Button("Cancel", role: .cancel) {}248        } message: { Text(confirmMessage(preflight)) }249        .task { await loadBudget() }250        .onChange(of: budgetOn) { _, _ in saveBudget() }251        .onChange(of: budgetText) { _, _ in saveBudget() }252    }253254    // MARK: Sections255256    private func liveCard(_ live: ArenaController) -> some View {257        Button(action: onOpenLive) {258            AstraCard(tint: AstraColor.accentSoft) {259                HStack(spacing: AstraSpace.md) {260                    if live.isRunning { OrbitActivity(size: 26) }261                    else { Image(systemName: "rectangle.split.2x1.fill").font(.title3).foregroundStyle(AstraColor.violet).accessibilityHidden(true) }262                    VStack(alignment: .leading, spacing: AstraSpace.xxs) {263                        Text(live.isRunning ? "Comparison in progress" : "Latest comparison").font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary)264                        Text(live.session?.title.isEmpty == false ? (live.session?.title ?? "") : "Open the answers")265                            .font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).lineLimit(1)266                    }267                    Spacer(minLength: AstraSpace.sm)268                    Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(AstraColor.textTertiary).accessibilityHidden(true)269                }270                .frame(minHeight: AstraSpace.hit)271            }272        }273        .buttonStyle(.plain)274        .accessibilityIdentifier("arena-open-live")275        .accessibilityHint("Opens the answers")276    }277278    private func competitorsSection(_ preflight: ArenaPreflight) -> some View {279        VStack(alignment: .leading, spacing: AstraSpace.md) {280            SectionTitle("Competitors", detail: "\(draft.competitors.count) of \(ArenaDraft.maxCompetitors)")281            if !app.library.hasAnyUsableModel {282                AstraCard {283                    EmptyStateView(symbol: "square.stack.3d.up.slash", title: "No model yet", message: "Download an on-device model or add a provider key, then come back to compare them.") {284                        Button("Open Models") { app.tab = .models }.buttonStyle(AstraPrimaryButtonStyle()).accessibilityIdentifier("arena-open-models")285                    }286                    .frame(maxWidth: .infinity)287                }288            } else {289                AstraCard(padding: 0) {290                    VStack(spacing: 0) {291                        ForEach(preflight.rows) { row in292                            competitorRow(row)293                            LabDivider()294                        }295                        Button { LabKeyboard.dismiss(); showPicker = true } label: {296                            HStack(spacing: AstraSpace.md) {297                                Image(systemName: "plus.circle.fill").font(.title3).foregroundStyle(AstraColor.violet).accessibilityHidden(true)298                                Text(draft.competitors.isEmpty ? "Add a model" : "Add another model").font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary)299                                Spacer(minLength: 0)300                            }301                            .padding(.horizontal, AstraSpace.lg).frame(minHeight: 52).contentShape(Rectangle())302                        }303                        .buttonStyle(.plain)304                        .disabled(draft.competitors.count >= ArenaDraft.maxCompetitors)305                        .opacity(draft.competitors.count >= ArenaDraft.maxCompetitors ? 0.4 : 1)306                        .accessibilityIdentifier("arena-add-model")307                    }308                }309                if localNotice {310                    NoticeCard(.info, title: "One on-device MLX model per run",311                               message: "An iPhone keeps a single MLX model in memory. Two would have to be loaded and unloaded in turn, which would distort every timing. Compare the on-device model with cloud models, or run it against another on-device model in a second comparison.",312                               actionTitle: "Got it") { localNotice = false }313                }314                Text("Every model receives the same prompt, the same instructions and the same parameters. A parameter a model cannot accept is dropped for that model only, and listed under its name.")315                    .font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary)316            }317        }318    }319320    private func competitorRow(_ row: ArenaPreflight.Row) -> some View {321        VStack(alignment: .leading, spacing: AstraSpace.xs) {322            HStack(spacing: AstraSpace.sm) {323                if let info = row.info { ModelRow(model: info, compact: true) }324                else {325                    ProviderLogo(ref: row.ref, size: 30)326                    Text(row.ref.modelID).font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary).lineLimit(1)327                    Spacer(minLength: 0)328                }329                IconButton("minus.circle", label: "Remove \(row.info?.displayName ?? row.ref.modelID)", tint: AstraColor.textTertiary) {330                    draft.competitors.removeAll { $0 == row.ref }331                }332            }333            if let unavailable = row.unavailable {334                Label(unavailable.message, systemImage: "exclamationmark.triangle.fill").font(AstraFont.caption).foregroundStyle(AstraColor.danger)335                    .fixedSize(horizontal: false, vertical: true)336            }337            if !row.fits {338                Label("The prompt is estimated at \(row.inputTokens) tokens and may not fit this model's window.", systemImage: "exclamationmark.triangle.fill")339                    .font(AstraFont.caption).foregroundStyle(AstraColor.warning).fixedSize(horizontal: false, vertical: true)340            }341            if !row.notes.isEmpty {342                VStack(alignment: .leading, spacing: AstraSpace.xxs) {343                    Text("Incompatible with this model").font(AstraFont.micro).foregroundStyle(AstraColor.warning)344                    ForEach(row.notes, id: \.self) { note in345                        Text("• " + note).font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true)346                    }347                }348                .padding(.bottom, AstraSpace.xs)349                .accessibilityElement(children: .combine)350            }351        }352        .padding(.leading, AstraSpace.lg).padding(.trailing, AstraSpace.xs).padding(.vertical, AstraSpace.xs)353    }354355    private var promptSection: some View {356        VStack(alignment: .leading, spacing: AstraSpace.md) {357            SectionTitle("Prompt", detail: draft.trimmedPrompt.isEmpty ? nil : "≈ \(TokenEstimator.estimate(draft.trimmedPrompt)) tokens")358            AstraCard {359                VStack(alignment: .leading, spacing: AstraSpace.md) {360                    if let name = draft.templateName {361                        HStack(spacing: AstraSpace.sm) {362                            AstraBadge("From template: \(name)", symbol: "doc.text", tone: .accent)363                            Spacer(minLength: 0)364                        }365                    }366                    LabTextArea(label: "Prompt", text: $draft.prompt, placeholder: "What should every model answer?", minHeight: 120)367                        .accessibilityIdentifier("arena-prompt")368                    if showSystem || !draft.system.isEmpty {369                        Text("System instructions").font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textSecondary)370                        LabTextArea(label: "System instructions", text: $draft.system, placeholder: "Optional. Sent to every model before the prompt.", minHeight: 72)371                            .accessibilityIdentifier("arena-system")372                    }373                    FlowLayout(spacing: AstraSpace.sm) {374                        if !showSystem && draft.system.isEmpty {375                            Button { showSystem = true } label: { Label("System prompt", systemImage: "text.badge.plus") }376                                .buttonStyle(AstraSecondaryButtonStyle(compact: true)).accessibilityIdentifier("arena-add-system")377                        }378                        Button { LabKeyboard.dismiss(); showTemplates = true } label: { Label("Load a template", systemImage: "doc.text") }379                            .buttonStyle(AstraSecondaryButtonStyle(compact: true)).accessibilityIdentifier("arena-load-template")380                        if !draft.prompt.isEmpty || !draft.system.isEmpty {381                            Button { draft.prompt = ""; draft.system = ""; draft.templateID = nil; draft.templateName = nil; showSystem = false } label: { Label("Clear", systemImage: "xmark") }382                                .buttonStyle(AstraSecondaryButtonStyle(compact: true)).accessibilityIdentifier("arena-clear-prompt")383                        }384                    }385                }386            }387        }388    }389390    private var parametersSection: some View {391        VStack(alignment: .leading, spacing: AstraSpace.md) {392            SectionTitle("Shared parameters")393            AstraCard {394                VStack(alignment: .leading, spacing: AstraSpace.md) {395                    ParameterEditor(parameters: $draft.parameters, outputLimitOptional: false)396                    LabDivider()397                    Toggle(isOn: $draft.blind) {398                        VStack(alignment: .leading, spacing: AstraSpace.xxs) {399                            Text("Blind mode").font(AstraFont.subheadline).foregroundStyle(AstraColor.textPrimary)400                            Text("Answers are shown as Model A, B, C… in shuffled order, without logos, until you pick the one you prefer or tap Reveal.")401                                .font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true)402                        }403                    }404                    .tint(AstraColor.accentFill)405                    .accessibilityIdentifier("arena-blind")406                }407            }408        }409    }410411    private func costSection(_ preflight: ArenaPreflight) -> some View {412        VStack(alignment: .leading, spacing: AstraSpace.md) {413            SectionTitle("Cost guard", detail: "Estimate")414            AstraCard {415                VStack(alignment: .leading, spacing: AstraSpace.md) {416                    if preflight.rows.isEmpty {417                        Text("Add models to see what a run could cost at most.").font(AstraFont.subheadline).foregroundStyle(AstraColor.textSecondary)418                    } else {419                        ForEach(preflight.rows) { row in420                            HStack(alignment: .firstTextBaseline, spacing: AstraSpace.sm) {421                                Text(row.info?.displayName ?? row.ref.modelID).font(AstraFont.subheadline).foregroundStyle(AstraColor.textPrimary).lineLimit(1)422                                Spacer(minLength: AstraSpace.sm)423                                Text(costLine(row)).font(AstraFont.metricSmall)424                                    .foregroundStyle(row.estimate.basis == .unavailable ? AstraColor.warning : AstraColor.textPrimary)425                            }426                            .accessibilityElement(children: .combine)427                        }428                        LabDivider()429                        HStack(alignment: .firstTextBaseline) {430                            Text("Estimated upper bound").font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary)431                            Spacer(minLength: AstraSpace.sm)432                            Text(totalLine(preflight)).font(AstraFont.metric).foregroundStyle(AstraColor.textPrimary).minimumScaleFactor(0.7).lineLimit(1)433                        }434                        .accessibilityElement(children: .combine)435                        .accessibilityIdentifier("arena-cost-total")436                        if preflight.unknownCount > 0 {437                            Label("\(preflight.unknownCount) model\(preflight.unknownCount == 1 ? " has" : "s have") no known price, so the real total can be higher than this figure.", systemImage: "questionmark.circle")438                                .font(AstraFont.caption).foregroundStyle(AstraColor.warning).fixedSize(horizontal: false, vertical: true)439                        }440                        Text("Upper bound = about \(preflight.rows.first?.inputTokens ?? 0) prompt tokens (estimated from the text) plus each model's full output limit, at the published prices. Real cost is usually lower and is shown after the run from the tokens the provider reports.")441                            .font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary).fixedSize(horizontal: false, vertical: true)442                    }443                    LabDivider()444                    Toggle("Per-run budget", isOn: $budgetOn).font(AstraFont.subheadline).tint(AstraColor.accentFill).frame(minHeight: AstraSpace.hit)445                        .accessibilityIdentifier("arena-budget-toggle")446                    if budgetOn {447                        HStack(spacing: AstraSpace.sm) {448                            Text("Ask before spending more than").font(AstraFont.subheadline).foregroundStyle(AstraColor.textSecondary)449                            Spacer(minLength: AstraSpace.sm)450                            Text("$").font(AstraFont.metricSmall).foregroundStyle(AstraColor.textSecondary).accessibilityHidden(true)451                            TextField("0.10", text: $budgetText)452                                .keyboardType(.decimalPad).multilineTextAlignment(.trailing).font(AstraFont.metricSmall)453                                .frame(width: 84).frame(minHeight: AstraSpace.hit)454                                .padding(.horizontal, AstraSpace.sm)455                                .background(AstraColor.surfaceSunken, in: RoundedRectangle(cornerRadius: AstraRadius.sm, style: .continuous))456                                .accessibilityLabel("Budget per run in US dollars")457                                .accessibilityIdentifier("arena-budget-field")458                        }459                        if budget == nil {460                            Text("Enter an amount greater than zero.").font(AstraFont.caption).foregroundStyle(AstraColor.warning)461                        } else if let budget, !preflight.rows.isEmpty {462                            let over = preflight.knownUpperBoundUSD > budget463                            Label(over ? "The estimate is above your budget: you will be asked to confirm." : "The estimate is within your budget.",464                                  systemImage: over ? "exclamationmark.triangle.fill" : "checkmark.circle.fill")465                                .font(AstraFont.caption).foregroundStyle(over ? AstraColor.warning : AstraColor.success)466                        }467                    }468                }469            }470        }471    }472473    private func runSection(_ preflight: ArenaPreflight) -> some View {474        VStack(alignment: .leading, spacing: AstraSpace.sm) {475            Button {476                LabKeyboard.dismiss()477                if needsConfirmation(preflight) { confirmRun = true } else { start() }478            } label: {479                HStack(spacing: AstraSpace.sm) {480                    if isStarting { ProgressView().tint(AstraColor.onAccent) }481                    else { Image(systemName: "play.fill").accessibilityHidden(true) }482                    Text(isStarting ? "Starting…" : "Run comparison")483                }484            }485            .buttonStyle(AstraPrimaryButtonStyle())486            .disabled(blocker != nil || isStarting)487            .accessibilityIdentifier("arena-run")488            if let blocker {489                Text(blocker).font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).frame(maxWidth: .infinity, alignment: .center)490            }491        }492    }493494    // MARK: Behaviour495496    private func add(_ ref: ModelRef) {497        if draft.competitors.contains(ref) { app.show("That model is already in the comparison.", .info); return }498        if draft.competitors.count >= ArenaDraft.maxCompetitors { return }499        if ref.provider == .mlx, draft.competitors.contains(where: { $0.provider == .mlx }) {500            localNotice = true501            AstraHaptics.warning()502            return503        }504        draft.competitors.append(ref)505    }506507    private func start() {508        guard !isStarting else { return }509        isStarting = true510        Task { await onRun(); isStarting = false }511    }512513    private func costLine(_ row: ArenaPreflight.Row) -> String {514        switch row.estimate.basis {515        case .onDevice: "On device"516        case .unavailable: "Price unknown"517        default: row.estimate.amountUSD.map { "≤ " + CostEstimate.format($0) } ?? "Price unknown"518        }519    }520521    private func totalLine(_ preflight: ArenaPreflight) -> String {522        if preflight.pricedCount == 0 { return preflight.unknownCount > 0 ? "Unknown" : "$0" }523        return "≈ " + CostEstimate.format(preflight.knownUpperBoundUSD) + (preflight.unknownCount > 0 ? " +" : "")524    }525526    private func needsConfirmation(_ preflight: ArenaPreflight) -> Bool {527        guard let budget else { return false }528        return preflight.knownUpperBoundUSD > budget || preflight.unknownCount > 0529    }530531    private func confirmTitle(_ preflight: ArenaPreflight) -> String {532        guard let budget else { return "Run this comparison?" }533        return preflight.knownUpperBoundUSD > budget ? "This run could exceed your budget" : "Part of the cost is unknown"534    }535536    private func confirmMessage(_ preflight: ArenaPreflight) -> String {537        guard let budget else { return "" }538        var text = "Estimated upper bound: \(CostEstimate.format(preflight.knownUpperBoundUSD)). Your budget per run: \(CostEstimate.format(budget))."539        if preflight.unknownCount > 0 { text += " \(preflight.unknownCount) model\(preflight.unknownCount == 1 ? " has" : "s have") no known price and cannot be checked against the budget." }540        return text541    }542543    private func loadBudget() async {544        guard !budgetLoaded else { return }545        if let stored: Double = try? await app.store.setting("arena.runBudgetUSD"), stored > 0 {546            budgetText = String(format: "%g", stored); budgetOn = true547        }548        budgetLoaded = true549    }550551    private func saveBudget() {552        guard budgetLoaded else { return }553        let value = budget554        let store = app.store555        Task { try? await store.setSetting("arena.runBudgetUSD", value) }556    }557}558559// MARK: - Template loader560561/// Picks a saved prompt template and fills its `{{variables}}` before it becomes the Arena prompt.562struct ArenaTemplateSheet: View {563    struct Rendered { var system: String; var user: String }564    @Environment(AppModel.self) private var app565    @Environment(\.dismiss) private var dismiss566    let onUse: (PromptTemplateRecord, Rendered) -> Void567568    @State private var templates: [PromptTemplateRecord]?569    @State private var error: String?570    @State private var chosen: PromptTemplateRecord?571    @State private var values: [String: String] = [:]572573    var body: some View {574        NavigationStack {575            Group {576                if let chosen { fill(chosen) }577                else if let templates {578                    if templates.isEmpty {579                        EmptyStateView(symbol: "doc.text", title: "No template yet", message: "Create prompt templates with variables in Lab, under Prompt studio. They can then be loaded here.") {580                            Button("Open Lab") { dismiss(); app.tab = .lab }.buttonStyle(AstraPrimaryButtonStyle())581                        }582                        .frame(maxWidth: .infinity, maxHeight: .infinity)583                    } else {584                        List(templates) { template in585                            Button { choose(template) } label: {586                                VStack(alignment: .leading, spacing: AstraSpace.xs) {587                                    Text(template.name.isEmpty ? "Untitled template" : template.name).font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary)588                                    Text(template.userTemplate).font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary).lineLimit(2)589                                    if !template.variables.isEmpty {590                                        Text(template.variables.map { "{{\($0)}}" }.joined(separator: "  ")).font(AstraFont.micro).foregroundStyle(AstraColor.violet).lineLimit(1)591                                    }592                                }593                                .frame(maxWidth: .infinity, minHeight: AstraSpace.hit, alignment: .leading).contentShape(Rectangle())594                            }595                            .buttonStyle(.plain)596                            .listRowBackground(AstraColor.surface)597                        }598                        .listStyle(.insetGrouped).scrollContentBackground(.hidden)599                    }600                } else if let error {601                    EmptyStateView(symbol: "exclamationmark.triangle", title: "Templates could not be read", message: error) {602                        Button("Try again") { Task { await load() } }.buttonStyle(AstraSecondaryButtonStyle())603                    }604                } else { LabLoading() }605            }606            .background(AstraColor.background)607            .navigationTitle(chosen == nil ? "Load a template" : "Fill the variables").navigationBarTitleDisplayMode(.inline)608            .toolbar {609                ToolbarItem(placement: .cancellationAction) {610                    if chosen != nil { Button("Back") { chosen = nil } } else { Button("Close") { dismiss() } }611                }612            }613            .task { await load() }614        }615        .presentationDetents([.large])616    }617618    private func fill(_ template: PromptTemplateRecord) -> some View {619        let system = PromptRenderer.render(template.system, values: values)620        let user = PromptRenderer.render(template.userTemplate, values: values)621        let missing = Array(Set(system.missing + user.missing)).sorted()622        return ScrollView {623            VStack(alignment: .leading, spacing: AstraSpace.lg) {624                ForEach(template.variables, id: \.self) { name in625                    VStack(alignment: .leading, spacing: AstraSpace.xs) {626                        Text(name).font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textSecondary)627                        LabTextArea(label: "Value of \(name)", text: Binding(get: { values[name] ?? "" }, set: { values[name] = $0.isEmpty ? nil : $0 }),628                                    placeholder: "Value", minHeight: 52)629                    }630                }631                SectionTitle("Preview")632                AstraCard {633                    Text(user.text).font(AstraFont.callout).foregroundStyle(AstraColor.textPrimary).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)634                }635                if !missing.isEmpty {636                    NoticeCard(.warning, title: "Unfilled variables", message: "Left as written in the prompt: " + missing.map { "{{\($0)}}" }.joined(separator: ", "))637                }638                Button("Use this prompt") { onUse(template, Rendered(system: system.text, user: user.text)); dismiss() }639                    .buttonStyle(AstraPrimaryButtonStyle()).accessibilityIdentifier("arena-template-use")640            }641            .padding(AstraSpace.page)642        }643        .scrollDismissesKeyboard(.interactively)644    }645646    private func choose(_ template: PromptTemplateRecord) {647        if template.variables.isEmpty {648            onUse(template, Rendered(system: template.system, user: template.userTemplate)); dismiss()649        } else { values = [:]; chosen = template }650    }651652    private func load() async {653        error = nil654        do { templates = try await app.store.templates() } catch { self.error = AstraError.wrap(error).message }655    }656}657
Files main
Menu

Theme