Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Sources/SPGlassAI/AI/GlassModelPicker.swift8// Module : SPGlassAI9// Repository : https://git.spboucher.ai/sp-glasskit10// Project Website : https://glass.spboucher.ai11// Created : 2026-12-0212// Last Modified : 2026-12-0313//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import SwiftUI42import SPGlassCore43import SPGlassTokens44import SPGlassThemes4546/// What a model can do. Shown as words in the picker; the symbols are for hosts that draw their own rows.47public struct GlassModelCapabilities: OptionSet, Hashable, Sendable {48 public let rawValue: Int4950 public init(rawValue: Int) {51 self.rawValue = rawValue52 }5354 public static let text = GlassModelCapabilities(rawValue: 1 << 0)55 public static let vision = GlassModelCapabilities(rawValue: 1 << 1)56 public static let tools = GlassModelCapabilities(rawValue: 1 << 2)57 public static let reasoning = GlassModelCapabilities(rawValue: 1 << 3)58 public static let audio = GlassModelCapabilities(rawValue: 1 << 4)59 public static let code = GlassModelCapabilities(rawValue: 1 << 5)6061 /// One capability with its symbol and localised name.62 public struct Descriptor: Hashable, Sendable {63 public let capability: GlassModelCapabilities64 public let symbolName: String65 public let labelKey: GlassL10n.Key6667 public var label: String { GlassL10n.string(labelKey) }68 }6970 /// Every known capability, in display order.71 public static let allDescriptors: [Descriptor] = [72 Descriptor(capability: .text, symbolName: "text.alignleft", labelKey: .capabilityText),73 Descriptor(capability: .vision, symbolName: "eye", labelKey: .capabilityVision),74 Descriptor(capability: .tools, symbolName: "wrench.and.screwdriver", labelKey: .capabilityTools),75 Descriptor(capability: .reasoning, symbolName: "lightbulb", labelKey: .capabilityReasoning),76 Descriptor(capability: .audio, symbolName: "waveform", labelKey: .capabilityAudio),77 Descriptor(capability: .code, symbolName: "chevron.left.forwardslash.chevron.right", labelKey: .capabilityCode),78 ]7980 /// The capabilities of this set, in display order.81 public var descriptors: [Descriptor] {82 Self.allDescriptors.filter { contains($0.capability) }83 }84}8586/// Where a model runs, or why it cannot be used.87public enum GlassModelAvailability: Hashable, Sendable {88 /// Runs on the device.89 case local90 /// Runs on a server.91 case remote92 /// Cannot be selected. `reason` is shown to the user ("Not downloaded", "Requires a newer device").93 case unavailable(reason: String)9495 public var labelKey: GlassL10n.Key {96 switch self {97 case .local: .modelLocal98 case .remote: .modelRemote99 case .unavailable: .modelUnavailable100 }101 }102103 public var symbolName: String {104 switch self {105 case .local: "internaldrive"106 case .remote: "cloud"107 case .unavailable: "exclamationmark.triangle"108 }109 }110111 public var isSelectable: Bool {112 if case .unavailable = self { false } else { true }113 }114}115116/// A model as the host describes it to a ``GlassModelPicker``.117public struct GlassModelInfo: Identifiable, Hashable, Sendable {118 public let id: String119 public let name: String120 /// Who provides the model; models are grouped by this label.121 public let provider: String122 public let capabilities: GlassModelCapabilities123 public let availability: GlassModelAvailability124125 public init(id: String, name: String, provider: String, capabilities: GlassModelCapabilities = [.text], availability: GlassModelAvailability) {126 self.id = id127 self.name = name128 self.provider = provider129 self.capabilities = capabilities130 self.availability = availability131 }132}133134/// The models of one provider.135public struct GlassModelGroup: Identifiable, Equatable, Sendable {136 public let provider: String137 public let models: [GlassModelInfo]138 public var id: String { provider }139}140141/// Grouping, sorting and wording of ``GlassModelPicker``.142public enum GlassModelCatalog {143 /// Groups models by provider.144 ///145 /// Providers are ordered alphabetically (localised, numeric-aware). Inside a provider, selectable models146 /// come before unavailable ones, then by name. A repeated identifier keeps its first occurrence only.147 public static func grouped(_ models: [GlassModelInfo]) -> [GlassModelGroup] {148 var seen = Set<String>()149 let unique = models.filter { seen.insert($0.id).inserted }150 return Dictionary(grouping: unique, by: \.provider)151 .map { provider, models in152 GlassModelGroup(provider: provider, models: models.sorted(by: precedes))153 }154 .sorted { ascending($0.provider, $1.provider) }155 }156157 private static func precedes(_ lhs: GlassModelInfo, _ rhs: GlassModelInfo) -> Bool {158 if lhs.availability.isSelectable != rhs.availability.isSelectable {159 return lhs.availability.isSelectable160 }161 if lhs.name != rhs.name { return ascending(lhs.name, rhs.name) }162 return lhs.id < rhs.id163 }164165 private static func ascending(_ lhs: String, _ rhs: String) -> Bool {166 let order = lhs.localizedStandardCompare(rhs)167 return order == .orderedSame ? lhs < rhs : order == .orderedAscending168 }169170 /// The model with `id`, or `nil`.171 public static func model(withID id: String?, in models: [GlassModelInfo]) -> GlassModelInfo? {172 guard let id else { return nil }173 return models.first { $0.id == id }174 }175176 /// The selection after the user picks `model`: unavailable models leave the selection unchanged.177 public static func selection(afterPicking model: GlassModelInfo, current: String?) -> String? {178 model.availability.isSelectable ? model.id : current179 }180181 /// The second line of a row: where the model runs and what it can do, or why it is unavailable.182 public static func subtitle(for model: GlassModelInfo) -> String {183 let availability = GlassL10n.string(model.availability.labelKey)184 if case .unavailable(let reason) = model.availability {185 let trimmed = reason.trimmingCharacters(in: .whitespacesAndNewlines)186 return trimmed.isEmpty ? availability : "\(availability) · \(trimmed)"187 }188 let capabilities = model.capabilities.descriptors.map(\.label)189 return capabilities.isEmpty ? availability : "\(availability) · \(capabilities.formatted(.list(type: .and, width: .narrow)))"190 }191}192193/// The form of a ``GlassModelPicker``.194public enum GlassModelPickerStyle: String, CaseIterable, Sendable {195 /// A compact button that opens the system menu. For a toolbar or a prompt bar.196 case menu197 /// The models as rows on an opaque surface, grouped by provider. For a settings screen or a sheet.198 case list199}200201/// A control to choose a model from a list supplied by the host.202///203/// ```swift204/// GlassModelPicker(models: models, selection: $selectedModelID) // a menu205/// GlassModelPicker(models: models, selection: $selectedModelID, style: .list) // rows206/// ```207///208/// Models are grouped by provider. The menu is drawn by the system; each of its rows gives the name, where the209/// model runs and its capabilities in words. The list draws one row per model: the name, a marker saying where210/// it runs (symbol and word), a chip per capability and a checkmark on the selected one. Unavailable models are211/// listed, disabled, with their reason. The picker loads nothing and contacts no provider: the list and its212/// states come from the host.213public struct GlassModelPicker: View {214 @GlassThemed private var theme215 private let title: Text216 private let models: [GlassModelInfo]217 private let style: GlassModelPickerStyle218 @Binding private var selection: GlassModelInfo.ID?219220 /// - Parameters:221 /// - title: accessibility label of the control, and its visible title when no model is selected. "Model" by default.222 /// - models: the models, in any order.223 /// - selection: identifier of the selected model; `nil` when none is.224 /// - style: ``GlassModelPickerStyle/menu`` (default) or ``GlassModelPickerStyle/list``.225 public init(_ title: LocalizedStringKey? = nil, models: [GlassModelInfo], selection: Binding<GlassModelInfo.ID?>, style: GlassModelPickerStyle = .menu) {226 self.title = title.map { Text($0) } ?? Text(GlassL10n.string(.model))227 self.models = models228 self.style = style229 _selection = selection230 }231232 public var body: some View {233 switch style {234 case .menu: menu235 case .list: list236 }237 }238239 // MARK: Menu240241 private var menu: some View {242 let selected = GlassModelCatalog.model(withID: selection, in: models)243 return Menu {244 ForEach(GlassModelCatalog.grouped(models)) { group in245 Section(group.provider) {246 ForEach(group.models) { model in247 Toggle(isOn: isSelected(model)) {248 Text(verbatim: model.name)249 Text(verbatim: GlassModelCatalog.subtitle(for: model))250 }251 .disabled(!model.availability.isSelectable)252 }253 }254 }255 } label: {256 HStack(spacing: theme.spacing.xs) {257 Image(systemName: selected?.availability.symbolName ?? "cpu")258 .font(.system(size: 12, weight: .semibold))259 .foregroundStyle(theme.color(.primary))260 Group {261 if let selected {262 Text(verbatim: selected.name)263 } else {264 title265 }266 }267 .font(theme.font(.callout).weight(.medium))268 .foregroundStyle(theme.color(models.isEmpty ? .textSecondary : .textPrimary))269 .lineLimit(1)270 Image(systemName: "chevron.up.chevron.down")271 .font(.system(size: 10, weight: .bold))272 .foregroundStyle(theme.color(.textSecondary))273 }274 .padding(.horizontal, theme.spacing.sm)275 .frame(minHeight: 34)276 .background(theme.color(.textSecondary).opacity(0.14), in: Capsule())277 .contentShape(Capsule())278 }279 .buttonStyle(.plain)280 .disabled(models.isEmpty)281 .accessibilityLabel(title)282 .accessibilityValue(Text(verbatim: selected.map { "\($0.name), \(GlassModelCatalog.subtitle(for: $0))" } ?? ""))283 }284285 private func isSelected(_ model: GlassModelInfo) -> Binding<Bool> {286 Binding(287 get: { selection == model.id },288 set: { isOn in289 if isOn { selection = GlassModelCatalog.selection(afterPicking: model, current: selection) }290 }291 )292 }293294 // MARK: List295296 @ViewBuilder297 private var list: some View {298 let groups = GlassModelCatalog.grouped(models)299 if groups.isEmpty {300 Label(GlassL10n.string(.noData), systemImage: "cpu")301 .font(theme.font(.callout))302 .foregroundStyle(theme.color(.textSecondary))303 .frame(maxWidth: .infinity)304 .padding(theme.spacing.lg)305 .glassOpaqueSurface(in: theme.shape(\.large))306 .accessibilityLabel(title)307 .accessibilityValue(Text(GlassL10n.string(.noData)))308 } else {309 VStack(alignment: .leading, spacing: theme.spacing.md) {310 ForEach(groups) { group in311 VStack(alignment: .leading, spacing: theme.spacing.xs) {312 Text(verbatim: group.provider.uppercased())313 .font(theme.font(.caption).weight(.semibold))314 .tracking(0.6)315 .foregroundStyle(theme.color(.textSecondary))316 .padding(.horizontal, theme.spacing.sm)317 .accessibilityAddTraits(.isHeader)318 VStack(spacing: 0) {319 ForEach(group.models) { model in320 row(model)321 if model.id != group.models.last?.id {322 Rectangle()323 .fill(theme.color(.separator))324 .frame(height: 0.5)325 .padding(.leading, theme.spacing.md)326 }327 }328 }329 .glassOpaqueSurface(in: theme.shape(\.large))330 }331 }332 }333 .accessibilityElement(children: .contain)334 .accessibilityLabel(title)335 }336 }337338 private func row(_ model: GlassModelInfo) -> some View {339 let isChosen = selection == model.id340 let isSelectable = model.availability.isSelectable341 return Button {342 selection = GlassModelCatalog.selection(afterPicking: model, current: selection)343 } label: {344 HStack(alignment: .center, spacing: theme.spacing.sm) {345 VStack(alignment: .leading, spacing: theme.spacing.xs) {346 HStack(spacing: theme.spacing.xs) {347 Text(verbatim: model.name)348 .font(theme.font(.body).weight(.semibold))349 .foregroundStyle(theme.color(isSelectable ? .textPrimary : .textSecondary))350 availabilityMarker(model.availability)351 }352 if case .unavailable(let reason) = model.availability, !reason.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {353 Text(verbatim: reason)354 .font(theme.font(.caption))355 .foregroundStyle(theme.color(.textSecondary))356 }357 GlassModelChipFlow(spacing: 6) {358 ForEach(model.capabilities.descriptors, id: \.self) { capability in359 HStack(spacing: 4) {360 Image(systemName: capability.symbolName)361 .font(.system(size: 10, weight: .semibold))362 Text(capability.label)363 .font(theme.font(.caption).weight(.medium))364 }365 .foregroundStyle(theme.color(.textSecondary))366 .padding(.horizontal, 8)367 .padding(.vertical, 4)368 .background(theme.color(.textSecondary).opacity(0.12), in: Capsule())369 }370 }371 .opacity(isSelectable ? 1 : 0.6)372 }373 Spacer(minLength: 0)374 Image(systemName: isChosen ? "checkmark.circle.fill" : "circle")375 .font(.system(size: 22, weight: .regular))376 .foregroundStyle(isChosen ? theme.color(.primary) : theme.color(.separator))377 .opacity(isSelectable ? 1 : 0)378 .accessibilityHidden(true)379 }380 .padding(.horizontal, theme.spacing.md)381 .padding(.vertical, theme.spacing.sm)382 .frame(maxWidth: .infinity, alignment: .leading)383 .contentShape(Rectangle())384 }385 .buttonStyle(.plain)386 .disabled(!isSelectable)387 .accessibilityElement(children: .ignore)388 .accessibilityLabel(Text(verbatim: model.name))389 .accessibilityValue(Text(verbatim: GlassModelCatalog.subtitle(for: model)))390 .accessibilityAddTraits(isChosen ? .isSelected : [])391 }392393 /// Where the model runs: a symbol and a word, never colour alone.394 private func availabilityMarker(_ availability: GlassModelAvailability) -> some View {395 let color = theme.color(availability.isSelectable ? .primary : .warning)396 return HStack(spacing: 4) {397 Image(systemName: availability.symbolName)398 .font(.system(size: 10, weight: .bold))399 Text(GlassL10n.string(availability.labelKey))400 .font(theme.font(.caption).weight(.semibold))401 }402 .foregroundStyle(availability.isSelectable ? color : theme.color(.textSecondary))403 .padding(.horizontal, 7)404 .padding(.vertical, 3)405 .overlay(Capsule().strokeBorder((availability.isSelectable ? color : theme.color(.textSecondary)).opacity(0.45), lineWidth: 1))406 }407}408409/// Places chips on as many lines as the width requires.410struct GlassModelChipFlow: Layout {411 let spacing: CGFloat412413 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {414 arrange(width: proposal.width ?? .infinity, subviews: subviews).size415 }416417 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {418 let arrangement = arrange(width: bounds.width, subviews: subviews)419 for (index, origin) in arrangement.origins.enumerated() {420 subviews[index].place(at: CGPoint(x: bounds.minX + origin.x, y: bounds.minY + origin.y), anchor: .topLeading, proposal: .unspecified)421 }422 }423424 private func arrange(width: CGFloat, subviews: Subviews) -> (origins: [CGPoint], size: CGSize) {425 var origins: [CGPoint] = []426 var x: CGFloat = 0427 var y: CGFloat = 0428 var lineHeight: CGFloat = 0429 var widest: CGFloat = 0430 for subview in subviews {431 let size = subview.sizeThatFits(.unspecified)432 if x > 0, x + size.width > width {433 x = 0434 y += lineHeight + spacing435 lineHeight = 0436 }437 origins.append(CGPoint(x: x, y: y))438 x += size.width + spacing439 lineHeight = max(lineHeight, size.height)440 widest = max(widest, x - spacing)441 }442 return (origins, CGSize(width: widest, height: y + lineHeight))443 }444}445