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/Lab/LabSupport.swift10// Module : Lab11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2113// Last Modified : 2026-11-2114//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 AstraPersistence92#if canImport(UIKit)93import UIKit94#endif9596/// Number formatting shared by Arena and Lab. Every function returns nil for a value that was not measured, so the97/// views show an em dash instead of a made-up figure.98enum LabFormat {99 static func seconds(_ t: TimeInterval?) -> String? { t.map { $0 < 10 ? String(format: "%.2f", $0) : String(format: "%.1f", $0) } }100 static func rate(_ r: Double?) -> String? { r.map { String(format: "%.1f", $0) } }101 static func count(_ n: Int?) -> String? { n.map { $0.formatted(.number) } }102 static func compact(_ n: Int) -> String { n.formatted(.number.notation(.compactName)) }103 static func bytes(_ b: Int64?) -> String? { b.map { ByteCountFormatter.string(fromByteCount: $0, countStyle: .memory) } }104 static func fileBytes(_ b: Int64) -> String { ByteCountFormatter.string(fromByteCount: b, countStyle: .file) }105 static func dateTime(_ d: Date) -> String { d.formatted(date: .abbreviated, time: .shortened) }106107 static func basis(_ basis: CostEstimate.Basis) -> String {108 switch basis {109 case .reportedByProvider: "Reported by the provider"110 case .estimatedFromUsage: "Estimated from reported tokens and dated prices"111 case .estimatedFromText: "Estimated from the text length"112 case .onDevice: "On device, no charge"113 case .unavailable: "Unavailable"114 }115 }116}117118/// The scrolling page every Lab section uses: page margins, the star backdrop and an inline title.119struct LabPage<Content: View>: View {120 let title: String121 @ViewBuilder var content: () -> Content122 var body: some View {123 ScrollView {124 VStack(alignment: .leading, spacing: AstraSpace.xl) { content() }125 .padding(.horizontal, AstraSpace.page).padding(.vertical, AstraSpace.lg)126 .frame(maxWidth: .infinity, alignment: .leading)127 }128 .scrollDismissesKeyboard(.interactively)129 .background(Starfield(density: 0.4))130 .navigationTitle(title).navigationBarTitleDisplayMode(.inline)131 }132}133134/// A label with its value and, when given, where the value comes from. Stacks vertically when the two do not fit on one line.135struct FactRow: View {136 let label: String137 let value: String?138 var source: String?139 var mono = false140141 var body: some View {142 VStack(alignment: .leading, spacing: AstraSpace.xxs) {143 ViewThatFits(in: .horizontal) {144 HStack(alignment: .firstTextBaseline, spacing: AstraSpace.md) { labelText; Spacer(minLength: AstraSpace.sm); valueText.multilineTextAlignment(.trailing) }145 VStack(alignment: .leading, spacing: AstraSpace.xxs) { labelText; valueText }146 }147 if let source { Text(source).font(AstraFont.micro).foregroundStyle(AstraColor.textTertiary) }148 }149 .frame(maxWidth: .infinity, alignment: .leading)150 .padding(.vertical, AstraSpace.xs)151 .accessibilityElement(children: .ignore)152 .accessibilityLabel(label)153 .accessibilityValue((value ?? "not available") + (source.map { ", source: \($0)" } ?? ""))154 }155156 private var labelText: some View { Text(label).font(AstraFont.subheadline).foregroundStyle(AstraColor.textSecondary) }157 private var valueText: some View {158 Text(value ?? "—").font(mono ? AstraFont.monoSmall : AstraFont.subheadline.weight(.medium))159 .foregroundStyle(value == nil ? AstraColor.textTertiary : AstraColor.textPrimary).textSelection(.enabled)160 }161}162163/// A full-width row inside a card that navigates or acts, with a 44-point target.164struct LabActionRow: View {165 let title: String166 var detail: String?167 let symbol: String168 var tint: Color = AstraColor.violet169 var showsChevron = true170171 var body: some View {172 HStack(spacing: AstraSpace.md) {173 Image(systemName: symbol).font(.body.weight(.semibold)).foregroundStyle(tint).frame(width: 28).accessibilityHidden(true)174 VStack(alignment: .leading, spacing: AstraSpace.xxs) {175 Text(title).font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary)176 if let detail { Text(detail).font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true) }177 }178 Spacer(minLength: AstraSpace.sm)179 if showsChevron { Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(AstraColor.textTertiary).accessibilityHidden(true) }180 }181 .frame(minHeight: AstraSpace.hit)182 .contentShape(Rectangle())183 }184}185186/// A centred spinner with a caption, for the first load of a section.187struct LabLoading: View {188 var text = "Loading…"189 var body: some View {190 HStack(spacing: AstraSpace.md) {191 ProgressView()192 Text(text).font(AstraFont.subheadline).foregroundStyle(AstraColor.textSecondary)193 }194 .frame(maxWidth: .infinity, minHeight: 120)195 .accessibilityElement(children: .combine)196 }197}198199/// A hairline between rows of a card.200struct LabDivider: View {201 var body: some View { Rectangle().fill(AstraColor.stroke).frame(height: 1).accessibilityHidden(true) }202}203204/// The chosen model as a tappable row, or an invitation to choose one.205struct ModelChoiceRow: View {206 @Environment(AppModel.self) private var app207 let ref: ModelRef?208 var placeholder = "Choose a model"209 let action: () -> Void210211 var body: some View {212 Button(action: action) {213 HStack(spacing: AstraSpace.md) {214 if let ref, let info = app.library.info(for: ref) {215 ModelRow(model: info, compact: true)216 } else if let ref {217 ProviderLogo(ref: ref, size: 30)218 Text(ref.modelID).font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary).lineLimit(1)219 Spacer(minLength: 0)220 } else {221 Image(systemName: "plus.circle.fill").font(.title3).foregroundStyle(AstraColor.violet).accessibilityHidden(true)222 Text(placeholder).font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary)223 Spacer(minLength: 0)224 }225 Image(systemName: "chevron.up.chevron.down").font(.caption.weight(.semibold)).foregroundStyle(AstraColor.textTertiary).accessibilityHidden(true)226 }227 .frame(minHeight: AstraSpace.hit).contentShape(Rectangle())228 }229 .buttonStyle(.plain)230 .accessibilityHint("Opens the model picker")231 }232}233234/// Editing of the generation parameters shared by Arena, the prompt studio, presets and the default settings.235/// A switched-off control means "provider default" and stores nil.236struct ParameterEditor: View {237 @Binding var parameters: GenerationParameters238 /// When false the output limit is always set (Arena needs it for its cost bound).239 var outputLimitOptional = true240 var maxOutputCeiling = 8_192241242 private var temperatureOn: Binding<Bool> {243 Binding(get: { parameters.temperature != nil }, set: { parameters.temperature = $0 ? (parameters.temperature ?? 0.7) : nil })244 }245 private var temperature: Binding<Double> { Binding(get: { parameters.temperature ?? 0.7 }, set: { parameters.temperature = $0 }) }246 private var limitOn: Binding<Bool> {247 Binding(get: { parameters.maxOutputTokens != nil }, set: { parameters.maxOutputTokens = $0 ? (parameters.maxOutputTokens ?? 1_024) : nil })248 }249 private var limit: Binding<Double> {250 Binding(get: { Double(parameters.maxOutputTokens ?? 1_024) }, set: { parameters.maxOutputTokens = Int($0) })251 }252 private var reasoning: Binding<ReasoningEffort> {253 Binding(get: { parameters.reasoning ?? .off }, set: { parameters.reasoning = $0 == .off ? nil : $0 })254 }255256 var body: some View {257 VStack(alignment: .leading, spacing: AstraSpace.md) {258 if outputLimitOptional {259 Toggle("Limit answer length", isOn: limitOn).font(AstraFont.subheadline).tint(AstraColor.accentFill).frame(minHeight: AstraSpace.hit)260 }261 if parameters.maxOutputTokens != nil || !outputLimitOptional {262 sliderRow("Maximum output", value: "\(Int(limit.wrappedValue)) tokens") {263 Slider(value: limit, in: 64...Double(max(128, maxOutputCeiling)), step: 64)264 .accessibilityLabel("Maximum output tokens").accessibilityValue("\(Int(limit.wrappedValue)) tokens")265 }266 }267 Toggle("Set temperature", isOn: temperatureOn).font(AstraFont.subheadline).tint(AstraColor.accentFill).frame(minHeight: AstraSpace.hit)268 if parameters.temperature != nil {269 sliderRow("Temperature", value: String(format: "%.2f", temperature.wrappedValue)) {270 Slider(value: temperature, in: 0...2, step: 0.05)271 .accessibilityLabel("Temperature").accessibilityValue(String(format: "%.2f", temperature.wrappedValue))272 }273 }274 HStack {275 Text("Reasoning effort").font(AstraFont.subheadline).foregroundStyle(AstraColor.textPrimary)276 Spacer(minLength: AstraSpace.sm)277 Picker("Reasoning effort", selection: reasoning) { ForEach(ReasoningEffort.allCases) { Text($0.title).tag($0) } }278 .pickerStyle(.menu).tint(AstraColor.violet)279 }280 .frame(minHeight: AstraSpace.hit)281 }282 }283284 private func sliderRow<S: View>(_ label: String, value: String, @ViewBuilder slider: () -> S) -> some View {285 VStack(alignment: .leading, spacing: AstraSpace.xs) {286 HStack {287 Text(label).font(AstraFont.subheadline).foregroundStyle(AstraColor.textSecondary)288 Spacer(minLength: AstraSpace.sm)289 Text(value).font(AstraFont.metricSmall).foregroundStyle(AstraColor.textPrimary)290 }291 slider().tint(AstraColor.accentFill).frame(minHeight: AstraSpace.hit)292 }293 }294}295296/// A multi-line text field on a sunken surface, with a placeholder.297struct LabTextArea: View {298 let label: String299 @Binding var text: String300 var placeholder = ""301 var minHeight: CGFloat = 96302 var mono = false303304 var body: some View {305 ZStack(alignment: .topLeading) {306 if text.isEmpty {307 Text(placeholder).font(mono ? AstraFont.monoSmall : AstraFont.callout).foregroundStyle(AstraColor.textTertiary)308 .padding(.horizontal, AstraSpace.md + 1).padding(.vertical, AstraSpace.md).allowsHitTesting(false).accessibilityHidden(true)309 }310 TextEditor(text: $text)311 .font(mono ? AstraFont.monoSmall : AstraFont.callout).foregroundStyle(AstraColor.textPrimary)312 .scrollContentBackground(.hidden)313 .padding(.horizontal, AstraSpace.sm).padding(.vertical, AstraSpace.xs)314 .frame(minHeight: minHeight)315 .accessibilityLabel(label)316 }317 .background(AstraColor.surfaceSunken, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))318 .overlay(RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous).strokeBorder(AstraColor.stroke, lineWidth: 1))319 }320}321322extension View {323 /// A "Done" button above the keyboard, so multi-line fields can always be dismissed.324 func keyboardDoneButton() -> some View {325 toolbar {326 ToolbarItemGroup(placement: .keyboard) {327 Spacer()328 Button("Done") { LabKeyboard.dismiss() }.font(AstraFont.bodyEmphasis)329 }330 }331 }332}333334@MainActor enum LabKeyboard {335 static func dismiss() {336 #if canImport(UIKit)337 UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)338 #endif339 }340}341342extension AppModel {343 /// Writes text to a temporary file and returns it for the share sheet, or shows the failure as a toast.344 func exportedFile(_ text: String, name: String, ext: String) -> ExportedFile? {345 do { return try ExportedFile.write(text, name: name, ext: ext) }346 catch { show(AstraError.wrap(error).message, .error); return nil }347 }348}349