SPB Git

Repository Public

ModelPickerView.swift 6.5 KB 110 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Models/ModelPickerView.swift3// Description: Compact searchable model picker (popover on macOS, sheet on iPhone): on-device, Apple Intelligence and remote models with fit and measured speed.4import SwiftUI5import LocalChatCore67/// Lists the models the user can chat with and reports the choice. `allowAuto` adds the "Auto (router)" entry (reported as nil).8public struct ModelPickerView: View {9    @Environment(AppModel.self) private var app10    let selectedID: String?; let allowAuto: Bool; let onSelect: (ModelDescriptor?) -> Void11    @State private var query = ""12    @FocusState private var focused: Bool1314    public init(selectedID: String?, allowAuto: Bool = true, onSelect: @escaping (ModelDescriptor?) -> Void) {15        self.selectedID = selectedID; self.allowAuto = allowAuto; self.onSelect = onSelect16    }1718    private func matches(_ m: ModelDescriptor) -> Bool {19        let q = query.trimmingCharacters(in: .whitespaces).lowercased()20        return q.isEmpty || m.name.lowercased().contains(q) || (m.repoID?.lowercased().contains(q) ?? false) || (m.quantization?.lowercased().contains(q) ?? false)21    }22    private var local: [ModelDescriptor] { app.chatModels.filter { ($0.backend == .mlx || $0.backend == .gguf) && matches($0) } }23    private var system: [ModelDescriptor] { app.chatModels.filter { $0.backend == .appleFoundation && matches($0) } }24    private var remoteGroups: [(name: String, models: [ModelDescriptor])] {25        Dictionary(grouping: app.chatModels.filter { $0.backend == .remote && matches($0) }) { app.nodeName(for: $0) ?? "Remote node" }26            .map { (name: $0.key, models: $0.value.sorted { $0.name < $1.name }) }.sorted { $0.name < $1.name }27    }2829    public var body: some View {30        VStack(spacing: 0) {31            HStack(spacing: 8) {32                Image(systemName: "magnifyingglass").foregroundStyle(DS.C.muted)33                TextField("Search models", text: $query).textFieldStyle(.plain).font(DS.F.body).focused($focused).autocorrectionDisabled()34                if !query.isEmpty { IconButton("xmark.circle.fill", label: "Clear search", tint: DS.C.muted) { query = "" } }35            }36            .padding(.horizontal, 12).padding(.vertical, 10)37            Rectangle().fill(DS.C.border).frame(height: 1)38            ScrollView {39                LazyVStack(alignment: .leading, spacing: 2) {40                    if allowAuto && query.isEmpty {41                        Button { onSelect(nil) } label: {42                            HStack(spacing: 10) {43                                Image(systemName: "arrow.triangle.branch").foregroundStyle(DS.G.accent).frame(width: 18)44                                VStack(alignment: .leading, spacing: 1) {45                                    Text("Auto").font(DS.F.body.weight(.medium)).foregroundStyle(DS.C.text)46                                    Text("Let the router choose per message").font(DS.F.caption).foregroundStyle(DS.C.muted)47                                }48                                Spacer()49                            }50                            .padding(.horizontal, 10).padding(.vertical, 7).contentShape(Rectangle())51                        }.buttonStyle(.plain)52                    }53                    group("On this device", local)54                    group("Apple Intelligence", system)55                    ForEach(remoteGroups, id: \.name) { g in group("Remote · \(g.name)", g.models) }56                    if local.isEmpty && system.isEmpty && remoteGroups.isEmpty {57                        Text(app.chatModels.isEmpty ? "No model yet. Download one in Models." : "No model matches “\(query)”.")58                            .font(DS.F.callout).foregroundStyle(DS.C.muted).frame(maxWidth: .infinity).padding(.vertical, DS.S.xl)59                    }60                }61                .padding(6)62            }63        }64        .background(DS.C.surface)65        #if os(macOS)66        .frame(minWidth: 380, idealWidth: 420, minHeight: 220, idealHeight: 440, maxHeight: 560)67        .onAppear { focused = true }68        #else69        .frame(minWidth: 300, idealWidth: 420, minHeight: 300)70        .presentationDetents([.medium, .large]).presentationDragIndicator(.visible)71        #endif72    }7374    @ViewBuilder private func group(_ title: String, _ models: [ModelDescriptor]) -> some View {75        if !models.isEmpty {76            Text(title.uppercased()).font(DS.F.micro).kerning(0.4).foregroundStyle(DS.C.muted).padding(.horizontal, 10).padding(.top, 10).padding(.bottom, 2)77            ForEach(models) { row($0) }78        }79    }8081    private func row(_ m: ModelDescriptor) -> some View {82        let verdict = app.compatibility(m)83        let usable = verdict.canAttemptLoad84        let selected = m.id == selectedID85        return Button { onSelect(m) } label: {86            HStack(spacing: 10) {87                Circle().fill(app.snapshot.isLoaded(m.id) ? DS.C.ok : .clear).overlay(Circle().strokeBorder(app.snapshot.isLoaded(m.id) ? .clear : DS.C.borderStrong, lineWidth: 1))88                    .frame(width: 8, height: 8).accessibilityLabel(app.snapshot.isLoaded(m.id) ? "Loaded" : "Not loaded")89                VStack(alignment: .leading, spacing: 2) {90                    Text(m.name).font(DS.F.body.weight(selected ? .semibold : .regular)).foregroundStyle(DS.C.text).lineLimit(1).truncationMode(.middle)91                    HStack(spacing: 6) {92                        Text(([m.parameterLabel, m.quantization] + [app.measuredSpeed[m.id].map { MetricFormat.rate($0) + " t/s" }]).compactMap { $0 }.joined(separator: " · "))93                            .font(DS.F.mono(10.5)).foregroundStyle(DS.C.text2)94                        if !usable, let reason = verdict.reasons.first { Text(reason).font(DS.F.micro).foregroundStyle(DS.C.danger).lineLimit(1) }95                    }96                }97                Spacer(minLength: 4)98                BackendBadge(m.backend)99                if verdict.fit != .comfortable { FitBadge(verdict) }100                if selected { Image(systemName: "checkmark").font(.system(size: 11, weight: .bold)).foregroundStyle(DS.C.accent) }101            }102            .padding(.horizontal, 10).padding(.vertical, 7)103            .background(selected ? DS.C.accent.opacity(0.1) : .clear, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))104            .contentShape(Rectangle()).opacity(usable ? 1 : 0.45)105        }106        .buttonStyle(.plain).disabled(!usable)107        .help(usable ? m.id : verdict.reasons.joined(separator: "\n"))108    }109}110
Files main
Menu

Theme