SPB Git

Repository Public MIT

ModelPickerSheet.swift 9.8 KB 215 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraUI/Sources/Models/ModelPickerSheet.swift10// Module           : Models11// 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 AstraDesign9192/// One model in a list: logo on the left, name, verified facts, capability badges.93struct ModelRow: View {94    let model: ModelInfo95    var subtitle: String?96    var isSelected = false97    var isFavorite = false98    var compact = false99100    var body: some View {101        HStack(alignment: .center, spacing: 12) {102            ProviderLogo(model: model, size: compact ? 30 : 38)103            VStack(alignment: .leading, spacing: 4) {104                HStack(spacing: 6) {105                    Text(model.displayName).font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary).lineLimit(1)106                    if isFavorite { Image(systemName: "star.fill").font(.caption2).foregroundStyle(AstraColor.warning).accessibilityLabel("Favourite") }107                }108                if let line = subtitle ?? factsLine { Text(line).font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary).lineLimit(1) }109                if !compact, !badges.isEmpty {110                    HStack(spacing: 4) { ForEach(badges, id: \.self) { AstraBadge($0.label, symbol: $0.symbol) } }111                }112            }113            Spacer(minLength: 4)114            if isSelected { Image(systemName: "checkmark.circle.fill").foregroundStyle(AstraColor.violet).font(.title3).accessibilityHidden(true) }115        }116        .padding(.vertical, 6)117        .contentShape(Rectangle())118        .accessibilityElement(children: .combine)119        .accessibilityAddTraits(isSelected ? .isSelected : [])120    }121122    /// Only facts that have a source: context length and price are omitted when unknown, never guessed.123    private var factsLine: String? {124        var parts: [String] = []125        if model.ref.provider.isLocal { parts.append("On device") }126        if let c = model.contextLabel { parts.append("\(c) context") }127        if let p = model.priceLabel { parts.append(p) }128        if parts.isEmpty { return model.ref.modelID == model.displayName ? nil : model.ref.modelID }129        return parts.joined(separator: " · ")130    }131132    private var badges: [Capability] {133        [Capability.vision, .tools, .reasoning, .structuredOutput].filter { model.capabilities.contains($0) && model.source != .unknown }134    }135}136137/// Picks one model among everything that can be used right now, grouped by where it runs.138struct ModelPickerSheet: View {139    @Environment(AppModel.self) private var app140    @Environment(\.dismiss) private var dismiss141    let selected: ModelRef?142    var title = "Choose a model"143    let onPick: (ModelRef) -> Void144    @State private var query = ""145146    private func matches(_ m: ModelInfo) -> Bool {147        let q = query.trimmingCharacters(in: .whitespaces).lowercased()148        return q.isEmpty || m.displayName.lowercased().contains(q) || m.ref.modelID.lowercased().contains(q) || (m.vendor?.lowercased().contains(q) ?? false)149    }150151    var body: some View {152        NavigationStack {153            List {154                if !app.library.hasAnyUsableModel {155                    EmptyStateView(symbol: "square.stack.3d.up.slash", title: "No model yet",156                                   message: "Download an on-device model or add a provider key in Models.") {157                        Button("Open Models") { dismiss(); app.tab = .models }.buttonStyle(AstraPrimaryButtonStyle())158                    }159                    .frame(maxWidth: .infinity).listRowBackground(Color.clear)160                }161                if query.isEmpty {162                    let quick = uniqued(app.library.favoriteModels + app.library.recentModels)163                    if !quick.isEmpty { section("Favourites and recent", quick, footer: nil) }164                }165                let local = app.library.localModels.filter(matches)166                if !local.isEmpty { section("On this iPhone", local, footer: "Private: prompts and answers stay on the device.") }167                ForEach(ProviderKind.cloudKeyed) { kind in168                    let state = app.library.providers[kind]169                    let models = (state?.hasKey == true ? (state?.models ?? []) : []).filter(matches)170                    if !models.isEmpty {171                        section(kind.displayName, Array(models.prefix(query.isEmpty ? 40 : 200)),172                                footer: models.count > 40 && query.isEmpty ? "\(models.count) models. Search to see them all." : nil)173                    }174                }175                ForEach(app.library.endpoints) { endpoint in176                    let models = (app.library.endpointModels[endpoint.id] ?? []).filter(matches)177                    if !models.isEmpty { section(endpoint.name, models, footer: "Custom endpoint") }178                }179            }180            .listStyle(.insetGrouped)181            .scrollContentBackground(.hidden)182            .background(AstraColor.background)183            .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: "Search models")184            .navigationTitle(title).navigationBarTitleDisplayMode(.inline)185            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }186        }187        .presentationDetents([.large])188    }189190    private func uniqued(_ models: [ModelInfo]) -> [ModelInfo] {191        var seen = Set<String>()192        return models.filter { seen.insert($0.id).inserted }193    }194195    private func section(_ title: String, _ models: [ModelInfo], footer: String?) -> some View {196        Section {197            ForEach(models) { model in198                Button {199                    AstraHaptics.selection(); onPick(model.ref); dismiss()200                } label: {201                    ModelRow(model: model, isSelected: model.ref == selected, isFavorite: app.library.isFavorite(model.ref), compact: true)202                }203                .buttonStyle(.plain)204                .swipeActions(edge: .trailing) {205                    Button { app.library.toggleFavorite(model.ref) } label: {206                        Label(app.library.isFavorite(model.ref) ? "Unfavourite" : "Favourite", systemImage: app.library.isFavorite(model.ref) ? "star.slash" : "star")207                    }208                    .tint(AstraColor.warning)209                }210                .listRowBackground(AstraColor.surface)211            }212        } header: { Text(title) } footer: { if let footer { Text(footer) } }213    }214}215
Files main
Menu

Theme