SPB Git

Repository Public

DiscoverView.swift 15.9 KB 292 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Models/DiscoverView.swift3// Description: Hugging Face discovery: debounced search with format / task / sort filters, pagination, starter picks with live metadata, gated-repo token.4import SwiftUI5import Observation6import LocalChatCore7import LocalChatModelHub89@MainActor @Observable10final class DiscoverModel {11    var text = ""12    var format: HubFormat? = .mlx13    var task: String?14    var sort: HubSort = .downloads15    var results: [HubModel] = []16    var next: URL?17    var isSearching = false18    var isLoadingMore = false19    var error: String?20    var starters: [(entry: StarterEntry, candidate: ModelCandidate)] = []21    var startersLoading = false22    var startersFailed = false23    @ObservationIgnored private var generation = 02425    static let tasks: [(tag: String?, title: String)] = [(nil, "Any task"), ("text-generation", "Text generation"), ("image-text-to-text", "Vision"),26                                                         ("sentence-similarity", "Embeddings"), ("feature-extraction", "Feature extraction")]27    var key: String { "\(text)|\(format?.rawValue ?? "any")|\(task ?? "any")|\(sort.rawValue)" }28    var showsStarters: Bool { text.trimmingCharacters(in: .whitespaces).isEmpty && task == nil && format == .mlx && sort == .downloads }2930    func search(api: HuggingFaceAPI) async {31        generation += 1; let mine = generation32        isSearching = true; error = nil33        defer { if mine == generation { isSearching = false } }34        do {35            let page = try await api.search(HubSearchQuery(text: text.trimmingCharacters(in: .whitespaces), format: format, pipelineTag: task, sort: sort, limit: 30))36            guard mine == generation else { return }37            results = page.models; next = page.next38        } catch is CancellationError {39        } catch {40            guard mine == generation, (error as? URLError)?.code != .cancelled else { return }41            self.error = hubErrorText(error); results = []; next = nil42        }43    }4445    func loadMore(api: HuggingFaceAPI) async {46        guard let url = next, !isLoadingMore else { return }47        isLoadingMore = true; defer { isLoadingMore = false }48        let mine = generation49        do {50            let page = try await api.page(at: url)51            guard mine == generation else { return }52            let known = Set(results.map(\.id))53            results += page.models.filter { !known.contains($0.id) }; next = page.next54        } catch { self.error = hubErrorText(error) }55    }5657    func loadStarters(api: HuggingFaceAPI, resolver: ModelMetadataResolver) async {58        guard starters.isEmpty, !startersLoading else { return }59        startersLoading = true; startersFailed = false60        starters = await StarterCatalog.resolve(api: api, resolver: resolver)61        startersFailed = starters.isEmpty62        startersLoading = false63    }64}6566struct DiscoverView: View {67    @Environment(AppModel.self) private var app68    let showDownloads: () -> Void69    @State private var model = DiscoverModel()70    @State private var selectedRepo: String?71    @State private var showToken = false72    @FocusState private var searchFocused: Bool7374    var body: some View {75        @Bindable var model = model76        ScrollView {77            LazyVStack(alignment: .leading, spacing: DS.S.md) {78                searchBar79                filters80                if let error = model.error {81                    InlineNotice(.error, error)82                    Button("Try again") { Task { await model.search(api: app.hub) } }.buttonStyle(.lcSecondaryCompact)83                }84                if model.showsStarters { starters }85                SectionHeader(model.text.isEmpty ? "On Hugging Face" : "Results", subtitle: resultSubtitle, symbol: "magnifyingglass")86                if model.isSearching && model.results.isEmpty {87                    HStack { Spacer(); ThinkingDots(); Spacer() }.padding(.vertical, DS.S.xl)88                } else if model.results.isEmpty && model.error == nil {89                    EmptyStateView(symbol: "sparkle.magnifyingglass", title: "Nothing found", message: "No repository matches these filters. Try another name, or switch between MLX and GGUF.").frame(minHeight: 220)90                } else {91                    ForEach(model.results) { repo in92                        Button { selectedRepo = repo.id } label: { HubRow(repo: repo, installed: installedCount(repo.id)) }.buttonStyle(.plain)93                    }94                    if model.next != nil {95                        HStack { Spacer()96                            Button { Task { await model.loadMore(api: app.hub) } } label: { if model.isLoadingMore { ProgressView().controlSize(.small) } else { Text("Load more") } }97                                .buttonStyle(.lcSecondaryCompact).disabled(model.isLoadingMore)98                            Spacer() }99                    }100                }101            }102            .padding(DS.S.lg)103        }104        .task(id: model.key) {105            try? await Task.sleep(for: .milliseconds(model.text.isEmpty ? 10 : 350))   // debounce typing106            guard !Task.isCancelled else { return }107            await model.search(api: app.hub)108        }109        .task { await model.loadStarters(api: app.hub, resolver: app.hubResolver) }110        .sheet(item: Binding(get: { selectedRepo.map(RepoRef.init) }, set: { selectedRepo = $0?.id })) { ref in111            ModelDetailView(repoID: ref.id, showDownloads: { selectedRepo = nil; showDownloads() })112        }113        .sheet(isPresented: $showToken) { HubTokenSheet() }114    }115116    private struct RepoRef: Identifiable { let id: String }117118    private var resultSubtitle: String? {119        guard !model.results.isEmpty else { return nil }120        return "\(model.results.count)\(model.next != nil ? "+" : "") repositories · metadata fetched live"121    }122123    private func installedCount(_ repo: String) -> Int { app.installedModels.filter { $0.repoID == repo }.count }124125    private var searchBar: some View {126        @Bindable var model = model127        return HStack(spacing: 8) {128            HStack(spacing: 8) {129                Image(systemName: "magnifyingglass").foregroundStyle(DS.C.muted)130                TextField("Search models on Hugging Face", text: $model.text).textFieldStyle(.plain).font(DS.F.body).focused($searchFocused)131                    .autocorrectionDisabled()132                    #if os(iOS)133                    .textInputAutocapitalization(.never)134                    #endif135                if model.isSearching { ProgressView().controlSize(.small) }136                if !model.text.isEmpty { IconButton("xmark.circle.fill", label: "Clear search", tint: DS.C.muted) { model.text = "" } }137            }138            .padding(.horizontal, 12).padding(.vertical, 8)139            .background(DS.C.surface, in: RoundedRectangle(cornerRadius: DS.R.card, style: .continuous))140            .overlay(RoundedRectangle(cornerRadius: DS.R.card, style: .continuous).strokeBorder(searchFocused ? DS.C.accent.opacity(0.6) : DS.C.border, lineWidth: 1))141            Button { showToken = true } label: { Image(systemName: app.hasHubToken ? "key.fill" : "key").frame(width: 20, height: 20) }142                .buttonStyle(.lcSecondaryCompact).help("Hugging Face token (gated models)").accessibilityLabel("Hugging Face token")143        }144        .background { Button("") { searchFocused = true }.keyboardShortcut("f", modifiers: .command).opacity(0).accessibilityHidden(true) }145    }146147    private var filters: some View {148        @Bindable var model = model149        return ScrollView(.horizontal, showsIndicators: false) {150            HStack(spacing: 8) {151                // Local Chat proposes MLX models only (Apple's framework for Apple silicon)152                Pill("MLX", symbol: "cpu", tone: .accent)153                Picker("Task", selection: $model.task) { ForEach(DiscoverModel.tasks, id: \.title) { Text($0.title).tag($0.tag) } }.fixedSize().labelsHidden()154                Picker("Sort", selection: $model.sort) { ForEach(HubSort.allCases, id: \.self) { Text($0.title).tag($0) } }.fixedSize().labelsHidden()155                if model.format == .gguf, let reason = app.backendIssues[.gguf] { Pill("GGUF cannot run here", symbol: "exclamationmark.triangle.fill", tone: .warn).help(reason) }156                if model.format == .mlx, let reason = app.backendIssues[.mlx] { Pill("MLX cannot run here", symbol: "exclamationmark.triangle.fill", tone: .warn).help(reason) }157            }158        }159    }160161    @ViewBuilder private var starters: some View {162        SectionHeader("Starter picks", subtitle: "Well-known open models, with sizes and fit checked live for this device.", symbol: "wand.and.stars")163        if model.startersLoading {164            HStack(spacing: 8) { ProgressView().controlSize(.small); Text("Fetching live metadata…").font(DS.F.caption).foregroundStyle(DS.C.muted) }165        } else if model.startersFailed {166            InlineNotice(.warning, "Starter picks could not be fetched (offline or rate-limited). Search still works when the connection is back.")167        } else {168            ForEach(TaskCategory.allCases) { task in169                let items = model.starters.filter { $0.entry.task == task }170                if !items.isEmpty {171                    Label(task.title, systemImage: task.symbol).font(DS.F.callout.weight(.semibold)).foregroundStyle(DS.C.text2).padding(.top, 2)172                    LazyVGrid(columns: [GridItem(.adaptive(minimum: 300), spacing: DS.S.md)], alignment: .leading, spacing: DS.S.md) {173                        ForEach(items, id: \.entry.id) { item in174                            StarterCard(entry: item.entry, candidate: item.candidate, open: { selectedRepo = item.entry.repoID }, showDownloads: showDownloads)175                        }176                    }177                }178            }179        }180    }181}182183private struct HubRow: View {184    let repo: HubModel; let installed: Int185    var body: some View {186        HStack(alignment: .center, spacing: 12) {187            VStack(alignment: .leading, spacing: 4) {188                HStack(spacing: 6) {189                    Text(repo.name).font(DS.F.headline).foregroundStyle(DS.C.text).lineLimit(1).truncationMode(.middle)190                    if repo.isGated { Pill("Gated", symbol: "lock.fill", tone: .warn) }191                    if installed > 0 { Pill("Installed", symbol: "checkmark", tone: .ok) }192                }193                Text(repo.organization).font(DS.F.caption).foregroundStyle(DS.C.muted)194                HStack(spacing: 10) {195                    if let d = repo.downloads { Label(ModelFacts.compact(d), systemImage: "arrow.down.circle") }196                    if let l = repo.likes { Label(ModelFacts.compact(l), systemImage: "heart") }197                    if let u = ModelFacts.relative(repo.lastModified) { Label(u, systemImage: "clock") }198                    if let t = repo.pipelineTag { Text(t) }199                    if let lic = repo.license { Text(lic) }200                }201                .font(DS.F.micro).foregroundStyle(DS.C.text2).labelStyle(.titleAndIcon).lineLimit(1)202            }203            Spacer(minLength: 4)204            Image(systemName: "chevron.right").font(.system(size: 11, weight: .semibold)).foregroundStyle(DS.C.muted)205        }206        .card(padding: DS.S.md).contentShape(Rectangle())207        .accessibilityElement(children: .combine).accessibilityHint("Shows files and compatibility")208    }209}210211private struct StarterCard: View {212    @Environment(AppModel.self) private var app213    let entry: StarterEntry; let candidate: ModelCandidate; let open: () -> Void; let showDownloads: () -> Void214    @State private var error: String?215    var body: some View {216        let verdict = app.compatibility(candidate.descriptor)217        VStack(alignment: .leading, spacing: 8) {218            Button(action: open) {219                VStack(alignment: .leading, spacing: 4) {220                    Text(candidate.descriptor.name).font(DS.F.headline).foregroundStyle(DS.C.text).lineLimit(1).truncationMode(.middle)221                    Text(entry.reason).font(DS.F.caption).foregroundStyle(DS.C.text2).lineLimit(2).fixedSize(horizontal: false, vertical: true)222                }223                .frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle())224            }.buttonStyle(.plain)225            FactsLine(facts: ModelFacts.line(candidate.descriptor))226            HStack(spacing: 6) {227                FitBadge(verdict)228                if candidate.unsupportedReason != nil { Pill("Architecture unsupported", symbol: "nosign", tone: .danger) }229                Spacer(minLength: 0)230                CandidateAction(candidate: candidate, verdict: verdict, showDownloads: showDownloads, onError: { error = $0 })231            }232            if let error { Text(error).font(DS.F.micro).foregroundStyle(DS.C.danger) }233        }234        .card(padding: DS.S.md)235    }236}237238/// Download / progress / installed state of one hub candidate.239struct CandidateAction: View {240    @Environment(AppModel.self) private var app241    let candidate: ModelCandidate; let verdict: CompatibilityVerdict; let showDownloads: () -> Void; let onError: (String?) -> Void242    var body: some View {243        if app.installedModels.contains(where: { $0.id == candidate.id }) {244            Pill("Installed", symbol: "checkmark.circle.fill", tone: .ok)245        } else if let state = app.isDownloading(candidate.id) {246            Button(action: showDownloads) {247                HStack(spacing: 6) { ProgressBar(state.fraction).frame(width: 54); Text("\(Int(state.fraction * 100)) %").font(DS.F.mono(11)) }248            }.buttonStyle(.lcSecondaryCompact).accessibilityLabel("Downloading, show downloads")249        } else {250            let blocked = candidate.unsupportedReason != nil || verdict.fit == .unsupported251            Button { Task { onError(await app.startDownload(candidate)) } } label: {252                Label(candidate.downloadBytes > 0 ? ByteFormat.string(candidate.downloadBytes) : "Download", systemImage: "arrow.down.circle.fill")253            }254            .buttonStyle(.lcPrimaryCompact).disabled(blocked)255            .help(blocked ? (candidate.unsupportedReason ?? verdict.reasons.joined(separator: "\n")) : verdict.fit == .tooLarge ? "Too large for this device; you can still download it for another use." : "Download")256        }257    }258}259260struct HubTokenSheet: View {261    @Environment(AppModel.self) private var app262    @Environment(\.dismiss) private var dismiss263    @State private var token = ""264    @State private var hint: String?265    @State private var error: String?266    var body: some View {267        VStack(alignment: .leading, spacing: DS.S.md) {268            SectionHeader("Hugging Face token", subtitle: "Only needed for gated or private repositories.", symbol: "key.fill")269            InlineNotice(.privacy, "The token is stored in the Keychain of this device and sent only to huggingface.co.")270            if let hint { Text("Saved token: \(hint)").font(DS.F.mono(12)).foregroundStyle(DS.C.text2) }271            SecureField("hf_…", text: $token).textFieldStyle(.roundedBorder)272            if let error { InlineNotice(.error, error) }273            HStack {274                if hint != nil { Button("Remove") { _ = try? app.keychain.delete("huggingface.token"); hint = nil; dismiss() }.buttonStyle(.lcDestructive) }275                Spacer()276                Button("Cancel") { dismiss() }.buttonStyle(.lcSecondaryCompact)277                Button("Save") {278                    do { try app.keychain.set(token.trimmingCharacters(in: .whitespacesAndNewlines), for: "huggingface.token"); dismiss() }279                    catch { self.error = error.localizedDescription }280                }.buttonStyle(.lcPrimaryCompact).disabled(token.trimmingCharacters(in: .whitespacesAndNewlines).count < 8)281            }282        }283        .padding(DS.S.xl).frame(minWidth: 320, idealWidth: 440)284        .onAppear {285            if let t = (try? app.keychain.string(for: "huggingface.token")) ?? nil, !t.isEmpty { hint = String(t.prefix(5)) + "…" + String(t.suffix(2)) }286        }287        #if os(iOS)288        .presentationDetents([.medium])289        #endif290    }291}292
Files main
Menu

Theme