Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraUI/Sources/Arena/ArenaSessionView.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 AstraPersistence9293extension ArenaLane {94 /// Status as text, symbol and tone: never colour alone.95 var statusText: String {96 switch entry.status {97 case .pending: return "Waiting"98 case .streaming:99 if isLoadingModel && entry.timeToFirstToken == nil { return "Loading model" }100 return entry.timeToFirstToken == nil ? "Waiting for first token" : "Streaming"101 case .complete: return entry.stopReason == .maxTokens ? "Reached output limit" : "Done"102 case .stopped: return "Stopped"103 case .failed: return "Failed"104 }105 }106 var statusSymbol: String {107 switch entry.status {108 case .pending: "hourglass"109 case .streaming: "dot.radiowaves.left.and.right"110 case .complete: "checkmark.circle.fill"111 case .stopped: "stop.circle.fill"112 case .failed: "xmark.octagon.fill"113 }114 }115 var statusTone: AstraBadge.Tone {116 switch entry.status {117 case .pending: .neutral118 case .streaming: .cyan119 case .complete: entry.stopReason == .maxTokens ? .warning : .success120 case .stopped: .warning121 case .failed: .danger122 }123 }124 var statusColor: Color {125 switch statusTone {126 case .neutral: AstraColor.textTertiary127 case .cyan: AstraColor.cyan128 case .success: AstraColor.success129 case .warning: AstraColor.warning130 case .danger: AstraColor.danger131 case .accent: AstraColor.violet132 }133 }134}135136/// The logo of a competitor, or a neutral letter tile while a blind session hides it.137struct ArenaLaneTile: View {138 let lane: ArenaLane139 let hidden: Bool140 var vendor: String?141 var size: CGFloat = 30142 var body: some View {143 if hidden {144 ProviderMark(initials: String(lane.entry.blindLabel.suffix(1)), tint: AstraColor.violet, size: size)145 } else {146 ProviderLogo(ref: lane.entry.model, vendor: vendor, size: size)147 }148 }149}150151/// A running or finished comparison: an overview strip, swipeable competitor cards and a stacked comparison.152struct ArenaSessionView: View {153 enum Mode: String, CaseIterable, Identifiable {154 case cards, compare155 var id: String { rawValue }156 var title: String { self == .cards ? "Cards" : "Compare" }157 }158159 @Environment(AppModel.self) private var app160 @Environment(\.accessibilityReduceMotion) private var reduceMotion161 @Environment(\.dynamicTypeSize) private var typeSize162 let controller: ArenaController163 let onReuse: (ArenaSessionRecord, [ModelRef]) -> Void164165 @State private var mode: Mode = .cards166 @State private var page: String?167 @State private var exported: ExportedFile?168 @State private var isExporting = false169 @State private var renaming = false170 @State private var newTitle = ""171 @State private var expanded: Set<String> = []172 @ScaledMetric(relativeTo: .body) private var fontSize: CGFloat = 16173174 private var hidden: Bool { controller.isBlindHidden }175 private var currentPage: String? { page ?? controller.lanes.first?.id }176 /// The lane that completed in the shortest measured time; a fact about speed, never a judgement of the answer.177 private var firstToFinish: String? {178 controller.lanes.filter { $0.entry.status == .complete && $0.entry.totalTime != nil }179 .min { ($0.entry.totalTime ?? .infinity) < ($1.entry.totalTime ?? .infinity) }?.id180 }181182 var body: some View {183 VStack(spacing: 0) {184 if let failure = controller.failure {185 NoticeCard(.error, title: failure.title, message: failure.message).padding(.horizontal, AstraSpace.page).padding(.top, AstraSpace.sm)186 }187 ArenaOverviewStrip(controller: controller, selected: mode == .cards ? currentPage : nil, firstToFinish: firstToFinish) { id in188 mode = .cards189 withAnimation(AstraMotion.resolve(AstraMotion.standard, reduceMotion: reduceMotion)) { page = id }190 }191 Picker("Layout", selection: $mode) { ForEach(Mode.allCases) { Text($0.title).tag($0) } }192 .pickerStyle(.segmented)193 .padding(.horizontal, AstraSpace.page).padding(.bottom, AstraSpace.sm)194 .accessibilityIdentifier("arena-view-mode")195 switch mode {196 case .cards: pager197 case .compare: compare198 }199 }200 .environment(\.transcriptFontSize, fontSize)201 .background(Starfield(density: 0.4))202 .safeAreaInset(edge: .bottom, spacing: 0) { bottomBar }203 .navigationTitle(title).navigationBarTitleDisplayMode(.inline)204 .toolbar(.hidden, for: .tabBar) // a comparison is a focused task: the cards get the full height and their actions are never covered205 .toolbar { ToolbarItem(placement: .topBarTrailing) { menu } }206 .sheet(item: $exported) { file in ShareSheet(items: [file.url]) }207 .alert("Rename comparison", isPresented: $renaming) {208 TextField("Title", text: $newTitle)209 Button("Save") { Task { await controller.rename(newTitle) } }210 Button("Cancel", role: .cancel) {}211 }212 }213214 private var title: String {215 guard let session = controller.session else { return "Comparison" }216 return session.title.isEmpty ? "Comparison" : session.title217 }218219 // MARK: Cards220221 /// One card per competitor, paged horizontally. A page-style TabView sizes each page to exactly the space between the222 /// bars above and below, so a card's header and its actions are always fully visible.223 private var pager: some View {224 TabView(selection: Binding(get: { currentPage ?? "" }, set: { page = $0 })) {225 ForEach(controller.lanes) { lane in226 laneCard(lane)227 .padding(.horizontal, AstraSpace.page).padding(.bottom, AstraSpace.sm)228 .tag(lane.id)229 }230 }231 .tabViewStyle(.page(indexDisplayMode: .never))232 .accessibilityIdentifier("arena-pager")233 }234235 private func laneCard(_ lane: ArenaLane) -> some View {236 let top = VStack(alignment: .leading, spacing: AstraSpace.md) {237 ArenaLaneHeader(lane: lane, label: controller.label(for: lane), hidden: hidden, vendor: controller.info(for: lane)?.vendor,238 isFirstToFinish: firstToFinish == lane.id)239 ArenaLaneMetrics(lane: lane, hidden: hidden)240 }241 .padding(AstraSpace.lg)242 let answer = ArenaLaneBody(lane: lane, hidden: hidden, showDetails: true, onRetry: { controller.retry(lane.id) }, onOpenModels: { app.tab = .models })243 .padding(AstraSpace.lg)244 return VStack(alignment: .leading, spacing: 0) {245 if typeSize.isAccessibilitySize {246 // At accessibility sizes the header and figures scroll with the answer, so the text is never squeezed out.247 ScrollView { VStack(alignment: .leading, spacing: 0) { top; LabDivider(); answer } }248 } else {249 top250 LabDivider()251 ScrollView { answer }252 }253 LabDivider()254 actions(lane).padding(.horizontal, AstraSpace.lg).padding(.vertical, AstraSpace.sm)255 }256 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)257 .background(AstraColor.surface, in: RoundedRectangle(cornerRadius: AstraRadius.lg, style: .continuous))258 .overlay(RoundedRectangle(cornerRadius: AstraRadius.lg, style: .continuous)259 .strokeBorder(lane.entry.isWinner ? AstraColor.violet : AstraColor.stroke, lineWidth: lane.entry.isWinner ? 2 : 1))260 }261262 private func actions(_ lane: ArenaLane) -> some View {263 let name = controller.label(for: lane)264 return FlowLayout(spacing: AstraSpace.sm) {265 if lane.isActive {266 Button { controller.stop(lane.id); AstraHaptics.tap() } label: { Label("Stop", systemImage: "stop.fill") }267 .buttonStyle(AstraSecondaryButtonStyle(compact: true))268 .accessibilityLabel("Stop \(name)").accessibilityIdentifier("arena-stop-\(lane.entry.revealOrder)")269 } else {270 Button { controller.retry(lane.id); AstraHaptics.tap() } label: { Label("Retry", systemImage: "arrow.clockwise") }271 .buttonStyle(AstraSecondaryButtonStyle(compact: true))272 .accessibilityLabel("Retry \(name)").accessibilityHint("Sends the same prompt to this model again and replaces its answer")273 .accessibilityIdentifier("arena-retry-\(lane.entry.revealOrder)")274 }275 Button { Pasteboard.copy(lane.displayText); AstraHaptics.tap(); app.show("Copied", .success) } label: { Label("Copy", systemImage: "doc.on.doc") }276 .buttonStyle(AstraSecondaryButtonStyle(compact: true))277 .disabled(lane.displayText.isEmpty)278 .accessibilityLabel("Copy the answer of \(name)")279 Button {280 AstraHaptics.selection()281 Task { await controller.pickWinner(lane.entry.isWinner ? nil : lane.id) }282 } label: {283 Label(lane.entry.isWinner ? "Your pick" : "I prefer this", systemImage: lane.entry.isWinner ? "heart.fill" : "heart")284 .foregroundStyle(lane.entry.isWinner ? AstraColor.violet : AstraColor.textPrimary)285 }286 .buttonStyle(AstraSecondaryButtonStyle(compact: true))287 .disabled(lane.isActive || lane.entry.text.isEmpty)288 .accessibilityLabel(lane.entry.isWinner ? "\(name) is your pick" : "Mark \(name) as the answer you prefer")289 .accessibilityHint(lane.entry.isWinner ? "Clears your preference" : (hidden ? "Records your preference and reveals the models" : "Records your own preference"))290 .accessibilityAddTraits(lane.entry.isWinner ? .isSelected : [])291 .accessibilityIdentifier("arena-pick-\(lane.entry.revealOrder)")292 }293 .frame(maxWidth: .infinity, alignment: .leading)294 }295296 // MARK: Compare297298 private var compare: some View {299 ScrollView {300 VStack(alignment: .leading, spacing: AstraSpace.lg) {301 if let session = controller.session { ArenaPromptCard(session: session) }302 ArenaMetricsTable(controller: controller, firstToFinish: firstToFinish)303 Text("Arena measures time, tokens and cost. It never scores or ranks the quality of an answer: the heart marks the one you prefer, nothing more.")304 .font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary).fixedSize(horizontal: false, vertical: true)305 ForEach(controller.lanes) { lane in306 let isLong = lane.displayText.count > 700307 let open = expanded.contains(lane.id) || !isLong308 AstraCard(tint: nil) {309 VStack(alignment: .leading, spacing: AstraSpace.md) {310 ArenaLaneHeader(lane: lane, label: controller.label(for: lane), hidden: hidden, vendor: controller.info(for: lane)?.vendor,311 isFirstToFinish: firstToFinish == lane.id)312 ArenaLaneBody(lane: lane, hidden: hidden, showDetails: false, onRetry: { controller.retry(lane.id) }, onOpenModels: { app.tab = .models })313 .frame(maxHeight: open ? nil : 240, alignment: .top).clipped()314 if isLong {315 Button(open ? "Show less" : "Show the full answer") {316 if open { expanded.remove(lane.id) } else { expanded.insert(lane.id) }317 }318 .font(AstraFont.footnote.weight(.semibold)).foregroundStyle(AstraColor.violet)319 .frame(minHeight: AstraSpace.hit, alignment: .leading)320 }321 actions(lane)322 }323 }324 .overlay(RoundedRectangle(cornerRadius: AstraRadius.lg, style: .continuous).strokeBorder(AstraColor.violet, lineWidth: 2).opacity(lane.entry.isWinner ? 1 : 0))325 }326 }327 .padding(.horizontal, AstraSpace.page).padding(.bottom, AstraSpace.lg)328 }329 .accessibilityIdentifier("arena-compare")330 }331332 // MARK: Bars and menus333334 @ViewBuilder private var bottomBar: some View {335 let running = controller.lanes.filter(\.isActive).count336 if running > 0 || hidden {337 HStack(spacing: AstraSpace.md) {338 if running > 0 {339 VStack(alignment: .leading, spacing: AstraSpace.xxs) {340 Text("\(running) of \(controller.lanes.count) still answering").font(AstraFont.subheadline.weight(.semibold)).foregroundStyle(AstraColor.textPrimary)341 Text("Each model can be stopped on its own card.").font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary)342 }343 Spacer(minLength: AstraSpace.sm)344 Button { controller.stopAll(); AstraHaptics.tap() } label: { Label("Stop all", systemImage: "stop.fill") }345 .buttonStyle(AstraSecondaryButtonStyle(compact: true)).accessibilityIdentifier("arena-stop-all")346 } else {347 VStack(alignment: .leading, spacing: AstraSpace.xxs) {348 Text("Blind comparison").font(AstraFont.subheadline.weight(.semibold)).foregroundStyle(AstraColor.textPrimary)349 Text("Pick the answer you prefer, or reveal the models.").font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary)350 }351 Spacer(minLength: AstraSpace.sm)352 Button { controller.reveal(); AstraHaptics.selection() } label: { Label("Reveal", systemImage: "eye") }353 .buttonStyle(AstraSecondaryButtonStyle(compact: true)).accessibilityIdentifier("arena-reveal")354 }355 }356 .padding(.horizontal, AstraSpace.page).padding(.vertical, AstraSpace.sm)357 .background(AstraColor.surface)358 .overlay(alignment: .top) { LabDivider() }359 }360 }361362 private var menu: some View {363 Menu {364 Section("Export") {365 Button { export(.markdown) } label: { Label("Markdown", systemImage: "doc.plaintext") }366 Button { export(.csv) } label: { Label("CSV", systemImage: "tablecells") }367 Button { export(.json) } label: { Label("JSON", systemImage: "curlybraces") }368 }369 Button { newTitle = controller.session?.title ?? ""; renaming = true } label: { Label("Rename", systemImage: "pencil") }370 if hidden {371 Button { controller.reveal() } label: { Label("Reveal the models", systemImage: "eye") }372 } else if let session = controller.session, !controller.isRunning {373 Button { onReuse(session, controller.lanes.sorted { $0.entry.ordinal < $1.entry.ordinal }.map(\.entry.model)) } label: {374 Label("Reuse this setup", systemImage: "arrow.uturn.backward")375 }376 }377 } label: {378 if isExporting { ProgressView() } else { Label("More", systemImage: "ellipsis.circle") }379 }380 .accessibilityIdentifier("arena-menu")381 }382383 private func export(_ format: ExportFormat) {384 guard !isExporting else { return }385 isExporting = true386 Task {387 defer { isExporting = false }388 do {389 let text = try await controller.export(format)390 exported = app.exportedFile(text, name: title == "Comparison" ? "arena-comparison" : title, ext: format.fileExtension)391 } catch { app.show(AstraError.wrap(error).message, .error) }392 }393 }394}395396// MARK: - Overview strip397398/// One chip per competitor: who is still streaming, who is done, who finished first. Tapping a chip shows its card.399struct ArenaOverviewStrip: View {400 let controller: ArenaController401 let selected: String?402 let firstToFinish: String?403 let onSelect: (String) -> Void404405 var body: some View {406 ScrollView(.horizontal) {407 HStack(spacing: AstraSpace.sm) {408 ForEach(controller.lanes) { lane in chip(lane) }409 }410 .padding(.horizontal, AstraSpace.page).padding(.vertical, AstraSpace.sm)411 }412 .scrollIndicators(.hidden)413 }414415 private func chip(_ lane: ArenaLane) -> some View {416 let name = controller.label(for: lane)417 let isSelected = selected == lane.id418 let first = firstToFinish == lane.id419 return Button { onSelect(lane.id) } label: {420 HStack(spacing: AstraSpace.sm) {421 ArenaLaneTile(lane: lane, hidden: controller.isBlindHidden, vendor: controller.info(for: lane)?.vendor, size: 28)422 VStack(alignment: .leading, spacing: AstraSpace.xxs) {423 HStack(spacing: AstraSpace.xs) {424 Text(name).font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textPrimary).lineLimit(1)425 if lane.entry.isWinner { Image(systemName: "heart.fill").font(.caption2).foregroundStyle(AstraColor.violet) }426 }427 HStack(spacing: AstraSpace.xs) {428 if lane.isActive { OrbitActivity(size: 12) } else { Image(systemName: lane.statusSymbol).font(.caption2).foregroundStyle(lane.statusColor) }429 Text(summary(lane, first: first)).font(AstraFont.micro).foregroundStyle(AstraColor.textSecondary).lineLimit(1)430 }431 }432 }433 .padding(.horizontal, AstraSpace.md).frame(minHeight: 52)434 .frame(maxWidth: 220, alignment: .leading)435 .background(isSelected ? AstraColor.accentSoft : AstraColor.surface, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))436 .overlay(RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous).strokeBorder(isSelected ? AstraColor.violet : AstraColor.stroke, lineWidth: 1))437 .contentShape(Rectangle())438 }439 .buttonStyle(.plain)440 .accessibilityElement(children: .ignore)441 .accessibilityLabel(name)442 .accessibilityValue(summary(lane, first: first) + (lane.entry.isWinner ? ", your pick" : ""))443 .accessibilityHint("Shows this answer")444 .accessibilityAddTraits(isSelected ? .isSelected : [])445 .accessibilityIdentifier("arena-chip-\(lane.entry.revealOrder)")446 }447448 private func summary(_ lane: ArenaLane, first: Bool) -> String {449 if lane.entry.status == .complete, let total = LabFormat.seconds(lane.entry.totalTime) {450 return (first && controller.lanes.count > 1 ? "First to finish · " : "Done · ") + total + " s"451 }452 return lane.statusText453 }454}455456// MARK: - Lane pieces457458struct ArenaLaneHeader: View {459 let lane: ArenaLane460 let label: String461 let hidden: Bool462 var vendor: String?463 let isFirstToFinish: Bool464465 var body: some View {466 HStack(alignment: .center, spacing: AstraSpace.md) {467 ArenaLaneTile(lane: lane, hidden: hidden, vendor: vendor, size: 34)468 VStack(alignment: .leading, spacing: AstraSpace.xs) {469 Text(label).font(AstraFont.headline).foregroundStyle(AstraColor.textPrimary).lineLimit(2)470 FlowLayout(spacing: AstraSpace.xs) {471 AstraBadge(lane.statusText, symbol: lane.statusSymbol, tone: lane.statusTone)472 if isFirstToFinish { AstraBadge("First to finish", symbol: "flag.checkered", tone: .neutral) }473 if lane.entry.isWinner { AstraBadge("Your pick", symbol: "heart.fill", tone: .accent) }474 if !hidden, lane.entry.model.provider.isLocal { AstraBadge("On device", symbol: "iphone", tone: .neutral) }475 }476 }477 Spacer(minLength: 0)478 }479 .accessibilityElement(children: .combine)480 .accessibilityAddTraits(.isHeader)481 }482}483484/// The four headline measurements. Total time counts up from the wall clock while the answer is still arriving.485struct ArenaLaneMetrics: View {486 let lane: ArenaLane487 /// While a blind session is hidden the cost is masked: "On device" or a price would give the model away.488 var hidden = false489490 var body: some View {491 if lane.isActive, let started = lane.startedAt {492 TimelineView(.periodic(from: .now, by: 0.5)) { context in493 tiles(total: LabFormat.seconds(max(0, context.date.timeIntervalSince(started))))494 }495 } else {496 tiles(total: LabFormat.seconds(lane.entry.totalTime))497 }498 }499500 private func tiles(total: String?) -> some View {501 let first = MetricTile("First token", value: LabFormat.seconds(lane.entry.timeToFirstToken), unit: "s", symbol: "bolt")502 let whole = MetricTile(lane.isActive ? "Elapsed" : "Total", value: total, unit: "s", symbol: "clock")503 let speed = MetricTile("Speed", value: LabFormat.rate(lane.entry.tokensPerSecond), unit: "tok/s", symbol: "speedometer")504 let cost = MetricTile("Cost", value: hidden ? "Hidden" : lane.entry.cost?.label, symbol: "dollarsign.circle")505 return ViewThatFits(in: .horizontal) {506 HStack(alignment: .top, spacing: AstraSpace.md) { first; whole; speed; cost }507 Grid(alignment: .leading, horizontalSpacing: AstraSpace.md, verticalSpacing: AstraSpace.md) {508 GridRow { first; whole }509 GridRow { speed; cost }510 }511 }512 }513}514515/// The answer itself, with the waiting state, the error card, the dropped parameters and the detailed figures.516struct ArenaLaneBody: View {517 let lane: ArenaLane518 let hidden: Bool519 let showDetails: Bool520 let onRetry: () -> Void521 let onOpenModels: () -> Void522523 var body: some View {524 VStack(alignment: .leading, spacing: AstraSpace.md) {525 if !lane.notes.isEmpty { notes }526 let text = lane.displayText527 if !text.isEmpty {528 MarkdownView(text: text).foregroundStyle(AstraColor.textPrimary).textSelection(.enabled)529 } else if lane.isActive {530 HStack(spacing: AstraSpace.sm) {531 OrbitActivity(size: 22)532 Text(lane.isLoadingModel ? "Loading the model into memory…" : "Waiting for the first token…").font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary)533 }534 } else if lane.entry.status == .complete || lane.entry.status == .stopped {535 Text(lane.entry.status == .stopped ? "Stopped before any text arrived." : "The model returned no text.")536 .font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary)537 }538 if let error = lane.entry.error, !lane.isActive { errorCard(error) }539 if lane.entry.stopReason == .maxTokens, !lane.isActive {540 NoticeCard(.warning, title: "Cut at the output limit", message: "The answer reached the shared output limit before it was complete.")541 }542 if showDetails, !lane.isActive, lane.entry.status != .pending { details }543 }544 .frame(maxWidth: .infinity, alignment: .leading)545 }546547 private var notes: some View {548 VStack(alignment: .leading, spacing: AstraSpace.xs) {549 Label(lane.notes.contains { $0.contains("not accepted") || $0.contains("lowered") || $0.contains("left out") || $0.contains("does not support") || $0.contains("no reasoning") } ? "Parameters adjusted for this model" : "About the parameters", systemImage: "slider.horizontal.below.square.and.square.filled").font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.warning)550 ForEach(lane.notes, id: \.self) { Text("• " + $0).font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true) }551 }552 .padding(AstraSpace.md).frame(maxWidth: .infinity, alignment: .leading)553 .background(AstraColor.warningSoft, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))554 .accessibilityElement(children: .combine)555 }556557 @ViewBuilder private func errorCard(_ error: AstraError) -> some View {558 if hidden {559 NoticeCard(.error, title: "This model failed", message: "The reason is hidden with the model's identity. Reveal the models to read it, or try again.", actionTitle: "Try again", action: onRetry)560 } else {561 let needsKey: Bool = { if case .missingCredential = error { return true }; if case .unauthorized = error { return true }; return false }()562 NoticeCard(.error, title: error.title, message: error.message, actionTitle: needsKey ? "Open Models" : "Try again", action: needsKey ? onOpenModels : onRetry)563 }564 }565566 private var details: some View {567 let e = lane.entry568 return VStack(alignment: .leading, spacing: 0) {569 Text("Measured").font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textSecondary).padding(.bottom, AstraSpace.xs)570 FactRow(label: "Input tokens", value: LabFormat.count(e.usage?.inputTokens))571 FactRow(label: "Output tokens", value: LabFormat.count(e.usage?.outputTokens))572 if let cached = e.usage?.cachedInputTokens { FactRow(label: "Cached input tokens", value: LabFormat.count(cached)) }573 if let reasoning = e.usage?.reasoningTokens { FactRow(label: "Reasoning tokens", value: LabFormat.count(reasoning)) }574 FactRow(label: "Stop reason", value: e.stopReason?.label)575 if hidden {576 FactRow(label: "Cost and model identity", value: "Hidden until reveal")577 } else {578 FactRow(label: "Cost basis", value: e.cost.map { LabFormat.basis($0.basis) }, source: e.cost?.pricingAsOf.map { "Prices as of \($0)" })579 FactRow(label: "Model reported by the provider", value: e.reportedModel, mono: true)580 FactRow(label: "Served by", value: e.servedBy)581 FactRow(label: "Requested model", value: e.model.modelID, mono: true)582 }583 }584 .padding(AstraSpace.md)585 .background(AstraColor.surfaceSunken, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))586 }587}588589// MARK: - Compare pieces590591struct ArenaPromptCard: View {592 let session: ArenaSessionRecord593 @State private var open = false594595 var body: some View {596 AstraCard {597 VStack(alignment: .leading, spacing: AstraSpace.sm) {598 Button { open.toggle() } label: {599 HStack {600 Text("Prompt").font(AstraFont.headline).foregroundStyle(AstraColor.textPrimary)601 Spacer(minLength: AstraSpace.sm)602 Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(AstraColor.textTertiary).rotationEffect(.degrees(open ? 90 : 0))603 }604 .frame(minHeight: AstraSpace.hit).contentShape(Rectangle())605 }606 .buttonStyle(.plain)607 .accessibilityValue(open ? "expanded" : "collapsed")608 Text(session.prompt).font(AstraFont.callout).foregroundStyle(AstraColor.textPrimary).lineLimit(open ? nil : 3).textSelection(.enabled)609 if open, !session.system.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {610 Text("System instructions").font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textSecondary)611 Text(session.system).font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).textSelection(.enabled)612 }613 FlowLayout(spacing: AstraSpace.xs) {614 if let max = session.parameters.maxOutputTokens { AstraBadge("Max \(max) tokens", symbol: "text.append") }615 if let t = session.parameters.temperature { AstraBadge(String(format: "Temperature %.2f", t), symbol: "thermometer.medium") }616 if let r = session.parameters.reasoning { AstraBadge("Reasoning \(r.title.lowercased())", symbol: "brain") }617 if session.blind { AstraBadge("Blind", symbol: "eye.slash", tone: .accent) }618 AstraBadge(LabFormat.dateTime(session.createdAt), symbol: "calendar")619 }620 }621 }622 }623}624625/// Measured figures side by side: one column per competitor, one row per metric. Scrolls sideways when it cannot fit.626struct ArenaMetricsTable: View {627 let controller: ArenaController628 let firstToFinish: String?629630 private struct Metric: Identifiable {631 let id: String632 let label: String633 let value: (ArenaLane) -> String?634 }635 private var metrics: [Metric] {636 let hidden = controller.isBlindHidden637 return [Metric(id: "ttft", label: "First token (s)") { LabFormat.seconds($0.entry.timeToFirstToken) },638 Metric(id: "total", label: "Total (s)") { LabFormat.seconds($0.entry.totalTime) },639 Metric(id: "speed", label: "Tokens/s") { LabFormat.rate($0.entry.tokensPerSecond) },640 Metric(id: "in", label: "Input tokens") { LabFormat.count($0.entry.usage?.inputTokens) },641 Metric(id: "out", label: "Output tokens") { LabFormat.count($0.entry.usage?.outputTokens) },642 Metric(id: "cost", label: "Cost") { lane in hidden ? "Hidden" : lane.entry.cost?.label }]643 }644645 var body: some View {646 AstraCard {647 VStack(alignment: .leading, spacing: AstraSpace.md) {648 SectionTitle("Measured", detail: "Not a ranking")649 ViewThatFits(in: .horizontal) {650 grid651 ScrollView(.horizontal) { grid }.scrollIndicators(.visible)652 }653 }654 }655 }656657 private var grid: some View {658 Grid(alignment: .leading, horizontalSpacing: AstraSpace.md, verticalSpacing: AstraSpace.sm) {659 GridRow {660 Text("").accessibilityHidden(true)661 ForEach(controller.lanes) { lane in662 VStack(spacing: AstraSpace.xxs) {663 ArenaLaneTile(lane: lane, hidden: controller.isBlindHidden, vendor: controller.info(for: lane)?.vendor, size: 26)664 Text(short(controller.label(for: lane))).font(AstraFont.micro).foregroundStyle(AstraColor.textSecondary).lineLimit(1)665 }666 .frame(minWidth: 56)667 .gridColumnAlignment(.trailing)668 .accessibilityElement(children: .ignore).accessibilityLabel(controller.label(for: lane)).accessibilityAddTraits(.isHeader)669 }670 }671 ForEach(metrics) { metric in672 GridRow {673 Text(metric.label).font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary).fixedSize()674 ForEach(controller.lanes) { lane in675 let value = metric.value(lane)676 Text(value ?? "—").font(AstraFont.metricSmall).foregroundStyle(value == nil ? AstraColor.textTertiary : AstraColor.textPrimary)677 .lineLimit(1).fixedSize()678 .accessibilityLabel("\(controller.label(for: lane)), \(metric.label)")679 .accessibilityValue(value ?? "not available")680 }681 }682 }683 }684 }685686 private func short(_ name: String) -> String { name.count > 12 ? String(name.prefix(11)) + "…" : name }687}688