1444 lines
69 KiB
Swift
1444 lines
69 KiB
Swift
import Foundation
|
||
import SwiftUI
|
||
import UniformTypeIdentifiers
|
||
import AppKit
|
||
|
||
struct CatalogModel: Identifiable, Hashable, Sendable, Codable {
|
||
let id: String
|
||
let title: String
|
||
let size: String
|
||
let repository: String
|
||
let revision: String
|
||
let files: [String]
|
||
var downloads: Int? = nil
|
||
var likes: Int? = nil
|
||
|
||
static let all: [Self] = [
|
||
.init(id: "smollm2-135m", title: "SmolLM2 135M Instruct", size: "270 MB",
|
||
repository: "HuggingFaceTB/SmolLM2-135M-Instruct",
|
||
revision: "12fd25f77366fa6b3b4b768ec3050bf629380bac",
|
||
files: ["config.json", "model.safetensors", "tokenizer.json", "tokenizer_config.json",
|
||
"generation_config.json", "special_tokens_map.json"]),
|
||
.init(id: "qwen3-0.6b-4bit", title: "Qwen3 0.6B 4-bit", size: "350 MB",
|
||
repository: "mlx-community/Qwen3-0.6B-4bit",
|
||
revision: "73e3e38d981303bc594367cd910ea6eb48349da8",
|
||
files: ["config.json", "model.safetensors", "model.safetensors.index.json", "tokenizer.json",
|
||
"tokenizer_config.json", "special_tokens_map.json", "added_tokens.json"])
|
||
]
|
||
|
||
static func search(_ query: String) async throws -> [Self] {
|
||
var url = URLComponents()
|
||
url.scheme = "https"
|
||
url.host = "huggingface.co"
|
||
url.path = "/api/models"
|
||
url.queryItems = [
|
||
.init(name: "filter", value: "mlx"),
|
||
.init(name: "pipeline_tag", value: "text-generation"),
|
||
.init(name: "search", value: query),
|
||
.init(name: "limit", value: "25"),
|
||
.init(name: "sort", value: "downloads"),
|
||
.init(name: "direction", value: "-1"),
|
||
.init(name: "full", value: "true")
|
||
]
|
||
guard let endpoint = url.url else { throw StudioError("Could not prepare the model search.") }
|
||
let response = try await WebFetch.load(endpoint, types: ["application/json"])
|
||
return try decodeSearch(response.data)
|
||
}
|
||
|
||
enum HubGating: Decodable {
|
||
case open, restricted
|
||
|
||
init(from decoder: Decoder) throws {
|
||
let value = try decoder.singleValueContainer()
|
||
self = (try? value.decode(Bool.self)) == false ? .open : .restricted
|
||
}
|
||
}
|
||
|
||
private struct HubEntry: Decodable {
|
||
struct File: Decodable { let rfilename: String }
|
||
let id: String
|
||
let sha: String?
|
||
let siblings: [File]?
|
||
let downloads: Int?
|
||
let likes: Int?
|
||
let library_name: String?
|
||
let tags: [String]?
|
||
let privateModel: Bool?
|
||
let gated: HubGating?
|
||
|
||
enum CodingKeys: String, CodingKey {
|
||
case id, sha, siblings, downloads, likes, library_name, tags, gated
|
||
case privateModel = "private"
|
||
}
|
||
|
||
func catalogModel() -> CatalogModel? {
|
||
guard let (owner, name) = CatalogModel.repositoryParts(id),
|
||
let revision = sha, revision.count == 40,
|
||
revision.allSatisfy({ $0.isASCII && $0.isHexDigit }),
|
||
privateModel != true, gated != .restricted else { return nil }
|
||
let declaresMLX = library_name == "mlx" || tags?.contains("mlx") == true
|
||
guard declaresMLX || (owner == "mlx-community" && library_name == nil) else { return nil }
|
||
let files = Set((siblings ?? []).map(\.rfilename).filter { file in
|
||
CatalogModel.safeComponent(file) &&
|
||
[".safetensors", ".json", ".txt", ".model", ".jinja", ".tiktoken"].contains { file.hasSuffix($0) }
|
||
})
|
||
guard files.contains("config.json"), files.contains(where: { $0.hasSuffix(".safetensors") }),
|
||
!files.contains("adapter_config.json"), !files.contains("adapter_model.safetensors") else { return nil }
|
||
// Keep the existing installation key for mlx-community models.
|
||
let key = owner == "mlx-community" ? "hf-" + name : "hf--" + owner + "/" + name
|
||
return CatalogModel(id: key, title: name, size: "", repository: id, revision: revision,
|
||
files: files.sorted(), downloads: downloads, likes: likes)
|
||
}
|
||
}
|
||
|
||
static func safeComponent(_ value: String) -> Bool {
|
||
let safe = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.")
|
||
return !value.isEmpty && !value.hasPrefix(".") && value.unicodeScalars.allSatisfy(safe.contains)
|
||
}
|
||
|
||
static func repositoryParts(_ id: String) -> (String, String)? {
|
||
let parts = id.split(separator: "/", omittingEmptySubsequences: false).map(String.init)
|
||
guard parts.count == 2, parts.allSatisfy(safeComponent) else { return nil }
|
||
return (parts[0], parts[1])
|
||
}
|
||
|
||
static func decodeSearch(_ data: Data) throws -> [Self] {
|
||
try JSONDecoder().decode([HubEntry].self, from: data).compactMap { $0.catalogModel() }
|
||
}
|
||
|
||
static func resolve(_ repository: String) async throws -> Self {
|
||
guard repositoryParts(repository) != nil else {
|
||
throw StudioError("Enter a Hugging Face model ID in owner/model format.")
|
||
}
|
||
let endpoint = URL(string: "https://huggingface.co/api/models/")!.appending(path: repository)
|
||
let response = try await WebFetch.load(endpoint, types: ["application/json"])
|
||
return try decodeRepository(response.data, requested: repository)
|
||
}
|
||
|
||
static func decodeRepository(_ data: Data, requested: String) throws -> Self {
|
||
let entry = try JSONDecoder().decode(HubEntry.self, from: data)
|
||
guard entry.id.caseInsensitiveCompare(requested) == .orderedSame,
|
||
let model = entry.catalogModel() else {
|
||
throw StudioError("The repository does not expose a public MLX checkpoint with safetensors weights.")
|
||
}
|
||
return model
|
||
}
|
||
|
||
var source: URL { URL(string: "https://huggingface.co/" + repository)! }
|
||
var metadataKey: String { "mlx:" + repository + "@" + revision }
|
||
var localFolder: URL {
|
||
URL.applicationSupportDirectory.appending(path: "AIStudio/Models", directoryHint: .isDirectory)
|
||
.appending(path: id.contains("/") ? "Custom/" + repository : id, directoryHint: .isDirectory)
|
||
}
|
||
|
||
func installed(at folder: URL) -> Bool {
|
||
!files.isEmpty && files.allSatisfy { MLXLibrary.hasFile($0, in: folder) } && MLXLibrary.isModel(at: folder)
|
||
}
|
||
|
||
func install(
|
||
to destination: URL,
|
||
progress: @Sendable (String, Double) async -> Void
|
||
) async throws {
|
||
if installed(at: destination) { return }
|
||
let manager = FileManager.default
|
||
if manager.fileExists(atPath: destination.path) {
|
||
throw StudioError("Remove the incomplete managed model before reinstalling.")
|
||
}
|
||
let parent = destination.deletingLastPathComponent()
|
||
try manager.createDirectory(at: parent, withIntermediateDirectories: true)
|
||
let staging = parent.appending(path: ".download-\(UUID())", directoryHint: .isDirectory)
|
||
try manager.createDirectory(at: staging, withIntermediateDirectories: false)
|
||
defer { try? manager.removeItem(at: staging) }
|
||
|
||
let config = URLSessionConfiguration.ephemeral
|
||
config.timeoutIntervalForRequest = 60
|
||
config.timeoutIntervalForResource = 3600
|
||
let session = URLSession(configuration: config)
|
||
defer { session.finishTasksAndInvalidate() }
|
||
for (offset, file) in files.enumerated() {
|
||
try Task.checkCancellation()
|
||
await progress("Downloading \(file) (\(offset + 1) of \(files.count))…", Double(offset) / Double(files.count))
|
||
let url = source.appending(path: "resolve/\(revision)/\(file)")
|
||
let (download, response) = try await session.download(from: url)
|
||
defer { try? manager.removeItem(at: download) }
|
||
guard let http = response as? HTTPURLResponse, http.statusCode == 200,
|
||
http.url?.scheme == "https" else {
|
||
let code = (response as? HTTPURLResponse).map { " (HTTP \($0.statusCode))" } ?? ""
|
||
throw StudioError("Could not download \(file)\(code).")
|
||
}
|
||
try manager.moveItem(at: download, to: staging.appending(path: file))
|
||
}
|
||
try Task.checkCancellation()
|
||
guard installed(at: staging) else { throw StudioError("The download was incomplete.") }
|
||
try manager.moveItem(at: staging, to: destination)
|
||
await progress("Download complete.", 1)
|
||
}
|
||
}
|
||
|
||
struct MLXModelConfiguration: Decodable {
|
||
struct Quantization: Decodable { let bits: Int? }
|
||
let modelType: String?
|
||
let architectures: [String]?
|
||
let maxPositionEmbeddings: Int?
|
||
let quantization: Quantization?
|
||
let quantizationConfig: Quantization?
|
||
let textConfig: TextConfiguration?
|
||
|
||
struct TextConfiguration: Decodable {
|
||
let maxPositionEmbeddings: Int?
|
||
}
|
||
|
||
static func decode(_ data: Data) throws -> Self {
|
||
let decoder = JSONDecoder()
|
||
decoder.keyDecodingStrategy = .convertFromSnakeCase
|
||
return try decoder.decode(Self.self, from: data)
|
||
}
|
||
|
||
var fields: [(String, String?)] {
|
||
[("Architecture", architectures?.first ?? modelType),
|
||
("Quantization", (quantization?.bits ?? quantizationConfig?.bits).map { "\($0)-bit" }),
|
||
("Context length", (maxPositionEmbeddings ?? textConfig?.maxPositionEmbeddings).map { $0.formatted() })]
|
||
}
|
||
}
|
||
|
||
struct HubModelMetadata: Decodable {
|
||
struct File: Decodable {
|
||
struct LFS: Decodable { let size: Int64; let sha256: String? }
|
||
let rfilename: String
|
||
let size: Int64?
|
||
let lfs: LFS?
|
||
}
|
||
|
||
let siblings: [File]
|
||
|
||
enum Format { case gguf, coreML }
|
||
|
||
func variantSizes(format: Format) -> CatalogVariantSizes {
|
||
var groups: [String: [Int64?]] = [:]
|
||
for file in siblings {
|
||
let name = file.rfilename
|
||
let lower = name.lowercased()
|
||
let bytes = file.lfs?.size ?? file.size
|
||
switch format {
|
||
case .gguf:
|
||
guard lower.hasSuffix(".gguf"), !lower.contains("mmproj"), !lower.contains("adapter") else { continue }
|
||
let key = name.replacingOccurrences(of: #"-[0-9]{5}-of-[0-9]{5}\.gguf$"#,
|
||
with: ".gguf", options: .regularExpression)
|
||
groups[key, default: []].append(bytes)
|
||
case .coreML:
|
||
if let range = lower.range(of: ".mlpackage/") {
|
||
let key = String(name[..<range.upperBound])
|
||
groups[key, default: []].append(bytes)
|
||
} else if lower.hasSuffix(".mlmodel") {
|
||
groups[name] = [bytes]
|
||
}
|
||
}
|
||
}
|
||
return CatalogVariantSizes(known: groups.values.compactMap { ModelLibrarySize.total($0) },
|
||
totalVariants: groups.count)
|
||
}
|
||
|
||
static func load(repository: String) async throws -> Self {
|
||
guard CatalogModel.repositoryParts(repository) != nil else { throw StudioError("Invalid model repository.") }
|
||
var parts = URLComponents()
|
||
parts.scheme = "https"
|
||
parts.host = "huggingface.co"
|
||
parts.path = "/api/models/" + repository
|
||
parts.queryItems = [.init(name: "blobs", value: "true")]
|
||
guard let url = parts.url else { throw StudioError("Invalid metadata URL.") }
|
||
let response = try await WebFetch.load(url, types: ["application/json"])
|
||
return try JSONDecoder().decode(Self.self, from: response.data)
|
||
}
|
||
|
||
func weightBytes(files: [String]) -> Int64? {
|
||
let weights = Set(files.filter { $0.hasSuffix(".safetensors") })
|
||
return ModelLibrarySize.total(weights.sorted().map { name in
|
||
let file = siblings.first { $0.rfilename == name }
|
||
return file?.lfs?.size ?? file?.size
|
||
})
|
||
}
|
||
|
||
static func load(_ model: CatalogModel) async throws -> Self {
|
||
var url = URLComponents()
|
||
url.scheme = "https"
|
||
url.host = "huggingface.co"
|
||
url.path = "/api/models/\(model.repository)/revision/\(model.revision)"
|
||
url.queryItems = [.init(name: "blobs", value: "true")]
|
||
guard let endpoint = url.url else { throw StudioError("Invalid model metadata URL.") }
|
||
let result = try await WebFetch.load(endpoint, types: ["application/json"])
|
||
return try JSONDecoder().decode(Self.self, from: result.data)
|
||
}
|
||
}
|
||
|
||
struct OllamaRegistryManifest: Decodable {
|
||
struct Blob: Decodable { let size: Int64 }
|
||
let config: Blob
|
||
let layers: [Blob]
|
||
|
||
var bytes: Int64? {
|
||
ModelLibrarySize.total(([config] + layers).map { $0.size })
|
||
}
|
||
|
||
static func latest(_ name: String) async throws -> Self {
|
||
let url = URL(string: "https://registry.ollama.ai")!
|
||
.appending(path: "v2/library").appending(path: name).appending(path: "manifests/latest")
|
||
let result = try await WebFetch.load(url, types: ["application/vnd.docker.distribution.manifest.v2+json", "application/json"])
|
||
return try JSONDecoder().decode(Self.self, from: result.data)
|
||
}
|
||
}
|
||
|
||
struct ModelPreview: Identifiable {
|
||
let id = UUID()
|
||
let title: String
|
||
let fields: [(String, String?)]
|
||
var source: URL?
|
||
var load: (() async throws -> [(String, String?)])?
|
||
}
|
||
|
||
struct ModelPreviewSheet: View {
|
||
let preview: ModelPreview
|
||
@Environment(\.dismiss) private var dismiss
|
||
@State private var details: [(String, String?)] = []
|
||
@State private var fetching = false
|
||
@State private var error = ""
|
||
|
||
var body: some View {
|
||
VStack(alignment: .leading, spacing: 12) {
|
||
Text(preview.title).font(.title2.weight(.semibold)).textSelection(.enabled)
|
||
ScrollView {
|
||
Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 10) {
|
||
let fields = preview.fields + details
|
||
ForEach(fields.indices, id: \.self) { index in
|
||
if let value = fields[index].1, !value.isEmpty {
|
||
GridRow {
|
||
Text(fields[index].0).foregroundStyle(.secondary)
|
||
Text(value).textSelection(.enabled)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
.frame(maxWidth: .infinity, alignment: .leading)
|
||
}
|
||
if fetching { ProgressView("Loading model information…").controlSize(.small) }
|
||
if !error.isEmpty { Text(error).font(.caption).foregroundStyle(.secondary) }
|
||
HStack {
|
||
if let source = preview.source { Link("Model Card", destination: source) }
|
||
Spacer()
|
||
Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)
|
||
}
|
||
}
|
||
.padding(20)
|
||
.frame(width: 540, height: 330)
|
||
.task {
|
||
guard let load = preview.load else { return }
|
||
fetching = true
|
||
defer { fetching = false }
|
||
do { details = try await load() }
|
||
catch { if !Task.isCancelled { self.error = error.localizedDescription } }
|
||
}
|
||
}
|
||
}
|
||
|
||
struct CatalogVariantSizes {
|
||
let known: [Int64]
|
||
let totalVariants: Int
|
||
|
||
var label: String {
|
||
guard let minimum = known.min(), let maximum = known.max() else { return "Size unknown" }
|
||
let range = minimum == maximum ? ModelLibrarySize.label(minimum) :
|
||
ModelLibrarySize.label(minimum) + " – " + ModelLibrarySize.label(maximum)
|
||
return range + (known.count < totalVariants ? " · some sizes unknown" : "")
|
||
}
|
||
|
||
func someExceed(budget: Int64?) -> Bool {
|
||
guard let budget else { return false }
|
||
return known.contains { $0 > budget }
|
||
}
|
||
|
||
func allExceed(budget: Int64?) -> Bool {
|
||
totalVariants > 0 && known.count == totalVariants &&
|
||
known.allSatisfy { ModelMemoryBudget.exceeds(bytes: $0, budget: budget) }
|
||
}
|
||
}
|
||
|
||
struct ModelLibrarySection<Content: View>: View {
|
||
let title: String
|
||
@AppStorage private var expanded: Bool
|
||
@ViewBuilder let content: () -> Content
|
||
|
||
init(_ title: String, key: String, @ViewBuilder content: @escaping () -> Content) {
|
||
self.title = title
|
||
self._expanded = AppStorage(wrappedValue: true, key)
|
||
self.content = content
|
||
}
|
||
|
||
var body: some View {
|
||
Section {
|
||
DisclosureGroup(isExpanded: $expanded) {
|
||
VStack(alignment: .leading, spacing: 12) {
|
||
content()
|
||
}
|
||
.frame(maxWidth: .infinity, alignment: .leading)
|
||
.padding(.top, 8)
|
||
} label: {
|
||
Text(title).font(.headline)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
enum ModelLibrarySize {
|
||
static func total(_ sizes: [Int64?]) -> Int64? {
|
||
guard !sizes.isEmpty else { return nil }
|
||
var bytes: Int64 = 0
|
||
for size in sizes {
|
||
guard let size, size > 0 else { return nil }
|
||
let (total, overflow) = bytes.addingReportingOverflow(size)
|
||
guard !overflow else { return nil }
|
||
bytes = total
|
||
}
|
||
return bytes
|
||
}
|
||
|
||
static func label(_ bytes: Int64?) -> String {
|
||
guard let bytes, bytes > 0 else { return "Size unknown" }
|
||
return ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file)
|
||
}
|
||
|
||
static func mlx(_ path: String) -> String {
|
||
let bytes = try? MLXRuntimeLimits.weightBytes(in: URL(fileURLWithPath: path))
|
||
return label(bytes.map { Int64(clamping: $0) })
|
||
}
|
||
}
|
||
|
||
enum ModelPopularity {
|
||
// Families represented among the highest-pull general-purpose models in
|
||
// https://ollama.com/library. The badge applies across backends.
|
||
private static let families = ["Qwen", "Llama", "Gemma", "DeepSeek", "Mistral"]
|
||
|
||
static func family(for identifier: String) -> String? {
|
||
guard let leaf = identifier.split(separator: "/").last else { return nil }
|
||
let name = leaf.split(separator: ":").first?.lowercased() ?? ""
|
||
return families.first { family in
|
||
let prefix = family.lowercased()
|
||
guard name.hasPrefix(prefix) else { return false }
|
||
guard let next = name.dropFirst(prefix.count).first else { return true }
|
||
return next.isASCII && (next.isNumber || "-_. ".contains(next))
|
||
}
|
||
}
|
||
}
|
||
|
||
struct ModelLibrarySelection {
|
||
let mlxOnly: Bool
|
||
let compatible: Bool
|
||
let mlxPath: String
|
||
let ollamaModel: String
|
||
let ggufPath: String
|
||
|
||
init(mlxOnly: Bool, compatible: Bool, mlxPath: String, ollamaModel: String, ggufPath: String = "") {
|
||
self.mlxOnly = mlxOnly
|
||
self.compatible = compatible
|
||
self.mlxPath = mlxPath
|
||
self.ollamaModel = ollamaModel
|
||
self.ggufPath = ggufPath
|
||
}
|
||
|
||
func isGGUF(_ path: String) -> Bool {
|
||
!ggufPath.isEmpty && canonicalPath(ggufPath) == canonicalPath(path)
|
||
}
|
||
|
||
private func canonicalPath(_ path: String) -> String {
|
||
URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL.path
|
||
}
|
||
|
||
func isMLX(_ path: String) -> Bool {
|
||
ggufPath.isEmpty && mlxOnly && !mlxPath.isEmpty && canonicalPath(mlxPath) == canonicalPath(path)
|
||
}
|
||
|
||
func isOllama(_ name: String) -> Bool {
|
||
guard ggufPath.isEmpty, !mlxOnly, !compatible, !ollamaModel.isEmpty else { return false }
|
||
func tag(_ value: String) -> String {
|
||
let value = value.trimmingCharacters(in: .whitespacesAndNewlines)
|
||
return value.split(separator: "/").last?.contains(":") == true ? value : value + ":latest"
|
||
}
|
||
return tag(ollamaModel) == tag(name)
|
||
}
|
||
}
|
||
|
||
struct ModelCatalogView: View {
|
||
@ObservedObject var studio: StudioModel
|
||
@AppStorage("defaultCoreMLPath") private var defaultCoreMLPath = ""
|
||
@AppStorage("defaultGGUFPath") private var defaultGGUFPath = ""
|
||
@AppStorage("mlxPath") private var mlxPath = ""
|
||
@AppStorage("mlxOnly") private var mlxOnly = false
|
||
@State private var downloads: [String: Task<Void, Never>] = [:]
|
||
@State private var downloadStates: [String: DownloadState] = [:]
|
||
|
||
private struct DownloadState {
|
||
let message: String
|
||
let fraction: Double?
|
||
}
|
||
@AppStorage("mlxRegisteredPaths") private var registered = Data()
|
||
@AppStorage(GGUFModelMetadata.libraryKey) private var ggufLibrary = Data()
|
||
@State private var dropTargeted = false
|
||
@State private var pickingLibrary = false
|
||
@State private var scanningLibrary = false
|
||
@State private var libraryStatus = ""
|
||
|
||
@State private var loadedPath: String?
|
||
@State private var cacheScan = 0
|
||
|
||
private var library: [String] { (try? JSONDecoder().decode([String].self, from: registered)) ?? [] }
|
||
@State private var removing: CatalogModel?
|
||
@State private var status = ""
|
||
@AppStorage("managedMLXModels") private var managed = Data()
|
||
@State private var query = ""
|
||
@State private var matches: [CatalogModel] = []
|
||
@State private var searching = false
|
||
@State private var searchStatus = ""
|
||
@State private var loadingPath: String?
|
||
@AppStorage("favoriteModelKeys") private var favoriteData = Data()
|
||
|
||
@State private var libraryBackend = "Local"
|
||
@AppStorage("lmStudioLibraryEndpoint") private var lmStudioEndpoint = "http://127.0.0.1:1234/v1"
|
||
@AppStorage("compatibleEndpoint") private var compatibleEndpoint = "http://127.0.0.1:1234/v1"
|
||
@AppStorage("compatibleModel") private var compatibleModel = ""
|
||
@State private var lmStudioLocalModels: [LocalModelImport] = []
|
||
@State private var lmStudioServerModels: [String] = []
|
||
@State private var lmStudioResultsEndpoint = ""
|
||
@State private var lmStudioConnecting = false
|
||
@State private var lmStudioServerStatus = ""
|
||
@State private var localQuery = ""
|
||
|
||
@AppStorage("endpoint") private var ollamaEndpoint = "http://127.0.0.1:11434"
|
||
@AppStorage("ollamaModel") private var ollamaModel = ""
|
||
@AppStorage("compatibleEnabled") private var compatibleEnabled = false
|
||
@State private var ollamaQuery = ""
|
||
@State private var ollamaCatalog: [String] = []
|
||
@State private var ollamaSearching = false
|
||
@State private var ollamaCatalogStatus = ""
|
||
|
||
|
||
@State private var preview: ModelPreview?
|
||
@State private var workshop: ModelWorkshop?
|
||
@State private var cloneSource: Ollama.Model?
|
||
@State private var cloneName = ""
|
||
|
||
private var validCloneName: String? {
|
||
let name = cloneName.trimmingCharacters(in: .whitespacesAndNewlines)
|
||
let pattern = #"^[A-Za-z0-9][A-Za-z0-9._-]*(/[A-Za-z0-9][A-Za-z0-9._-]*)?(:[A-Za-z0-9][A-Za-z0-9._-]*)?$"#
|
||
return name.range(of: pattern, options: .regularExpression) == nil ? nil : name
|
||
}
|
||
@State private var catalogBytes: [String: Int64] = [:]
|
||
|
||
private func mlxPreview(model: CatalogModel?, folder: URL?) -> ModelPreview {
|
||
let title = model?.title ?? folder.map(MLXLibrary.displayName(for:)) ?? "MLX model"
|
||
let cached = model.flatMap { catalogBytes[$0.metadataKey] }
|
||
let size = folder.map { ModelLibrarySize.mlx($0.path) } ?? cached.map { ModelLibrarySize.label($0) }
|
||
return ModelPreview(title: title, fields: [
|
||
("Backend", "MLX"), ("Weights", size), ("Repository", model?.repository),
|
||
("Revision", model?.revision), ("Local folder", folder?.path),
|
||
("Compatibility", folder.map {
|
||
MLXLibrary.isModel(at: $0) ? "Checkpoint files present · runtime checked on load" : "Missing or invalid checkpoint files"
|
||
} ?? "MLX checkpoint · runtime checked on load")
|
||
], source: model?.source, load: {
|
||
if let folder {
|
||
let data = try Data(contentsOf: folder.appending(path: "config.json"))
|
||
return try MLXModelConfiguration.decode(data).fields
|
||
}
|
||
guard let model else { return [] }
|
||
let url = model.source.appending(path: "raw").appending(path: model.revision).appending(path: "config.json")
|
||
let result = try await WebFetch.load(url, types: ["application/json", "text/plain", "application/octet-stream"])
|
||
var fields = try MLXModelConfiguration.decode(result.data).fields
|
||
if cached == nil {
|
||
let metadata = try? await HubModelMetadata.load(model)
|
||
fields.insert(("Weights", ModelLibrarySize.label(metadata?.weightBytes(files: model.files))), at: 0)
|
||
}
|
||
return fields
|
||
})
|
||
}
|
||
|
||
private func ollamaPreview(_ model: Ollama.Model) -> ModelPreview {
|
||
let endpoint = ollamaEndpoint
|
||
return ModelPreview(title: model.name, fields: [
|
||
("Backend", "Ollama"), ("Server", endpoint), ("Installed size", ModelLibrarySize.label(model.size)),
|
||
("Family", model.details?.family), ("Format", model.details?.format),
|
||
("Parameters", model.details?.parameters), ("Quantization", model.details?.quantization)
|
||
], load: {
|
||
let details = try await studio.ollamaClient(endpoint: endpoint).details(for: model.name)
|
||
return [("Architecture", details.architecture),
|
||
("Family", model.details?.family == nil ? details.details?.family : nil),
|
||
("Format", model.details?.format == nil ? details.details?.format : nil),
|
||
("Parameters", model.details?.parameters == nil ? details.details?.parameters : nil),
|
||
("Quantization", model.details?.quantization == nil ? details.details?.quantization : nil),
|
||
("Context length", details.contextLength.map { $0.formatted() }),
|
||
("Capabilities", details.capabilities?.joined(separator: ", "))]
|
||
})
|
||
}
|
||
|
||
private func ollamaCatalogPreview(_ name: String) -> ModelPreview {
|
||
let source = URL(string: "https://ollama.com/library/" + name)
|
||
let bytes = catalogBytes["ollama:" + name]
|
||
return ModelPreview(title: name, fields: [
|
||
("Backend", "Ollama"), ("Tag", "latest"), ("Source", "Ollama Registry"),
|
||
("Download size", bytes.map { ModelLibrarySize.label($0) })
|
||
], source: source, load: bytes == nil ? {
|
||
let manifest = try await OllamaRegistryManifest.latest(name)
|
||
return [("Download size", ModelLibrarySize.label(manifest.bytes))]
|
||
} : nil)
|
||
}
|
||
|
||
private var selection: ModelLibrarySelection {
|
||
if let run = studio.inferenceSelection, !studio.inferenceBackend.isEmpty {
|
||
return ModelLibrarySelection(
|
||
mlxOnly: studio.inferenceBackend.hasPrefix("MLX · "),
|
||
compatible: !studio.inferenceBackend.hasPrefix("Ollama · ") || run.endpoint != ollamaEndpoint,
|
||
mlxPath: run.path, ollamaModel: run.tag,
|
||
ggufPath: studio.inferenceBackend.hasPrefix("GGUF · ") ? run.tag : ""
|
||
)
|
||
}
|
||
return ModelLibrarySelection(mlxOnly: mlxOnly && defaultCoreMLPath.isEmpty, compatible: compatibleEnabled || !defaultCoreMLPath.isEmpty,
|
||
mlxPath: mlxPath, ollamaModel: ollamaModel, ggufPath: defaultGGUFPath)
|
||
}
|
||
|
||
private func activeBadge(_ runtime: String) -> some View {
|
||
Label("\(studio.inferenceBackend.isEmpty ? "Active" : "In use") · \(runtime)", systemImage: "checkmark.circle.fill")
|
||
.font(.caption.weight(.semibold))
|
||
.foregroundStyle(Color.accentColor)
|
||
.padding(.horizontal, 7)
|
||
.padding(.vertical, 3)
|
||
.background(Color.accentColor.opacity(0.10), in: Capsule())
|
||
.fixedSize()
|
||
}
|
||
|
||
@ViewBuilder
|
||
private func popularityBadge(_ identifier: String) -> some View {
|
||
if let family = ModelPopularity.family(for: identifier) {
|
||
Label {
|
||
Text("Popular family")
|
||
} icon: {
|
||
Image(systemName: "chart.bar.fill").foregroundStyle(.indigo)
|
||
}
|
||
.font(.caption2.weight(.semibold))
|
||
.foregroundStyle(.primary)
|
||
.padding(.horizontal, 7)
|
||
.padding(.vertical, 3)
|
||
.background(Color.indigo.opacity(0.12), in: Capsule())
|
||
.fixedSize()
|
||
.accessibilityLabel("Popular model family: " + family)
|
||
.help(family + " has widely pulled models in the Ollama Library.")
|
||
}
|
||
}
|
||
|
||
private var installedModels: [CatalogModel] {
|
||
let saved = (try? JSONDecoder().decode([CatalogModel].self, from: managed)) ?? []
|
||
return saved + CatalogModel.all.filter { $0.installed(at: $0.localFolder) }
|
||
}
|
||
|
||
|
||
private var readyModels: [CatalogModel] {
|
||
installedModels.filter { $0.installed(at: $0.localFolder) }
|
||
}
|
||
|
||
private var favorites: Set<String> {
|
||
(try? JSONDecoder().decode(Set<String>.self, from: favoriteData)) ?? []
|
||
}
|
||
|
||
private func favoriteFirst<T>(_ rows: [T], key: (T) -> String) -> [T] {
|
||
let saved = favorites
|
||
return rows.filter { saved.contains(key($0)) } + rows.filter { !saved.contains(key($0)) }
|
||
}
|
||
|
||
private func favoriteButton(_ key: String) -> some View {
|
||
HubCatalogFavorite(key: key)
|
||
}
|
||
|
||
var body: some View {
|
||
VStack(spacing: 0) {
|
||
Picker("Model library", selection: $libraryBackend) {
|
||
Text("On This Mac").tag("Local")
|
||
Text("LM Studio").tag("LM Studio")
|
||
Text("Ollama").tag("Ollama")
|
||
}
|
||
.pickerStyle(.segmented)
|
||
.labelsHidden()
|
||
.accessibilityLabel("Model library")
|
||
.frame(maxWidth: 430)
|
||
.padding()
|
||
if libraryBackend == "Ollama" {
|
||
ollamaLibrary
|
||
} else if libraryBackend == "LM Studio" {
|
||
lmStudioLibrary
|
||
} else {
|
||
localLibrary
|
||
}
|
||
}
|
||
.sheet(item: $preview) { ModelPreviewSheet(preview: $0) }
|
||
.sheet(item: $workshop) { ModelWorkshopView(workshop: $0, register: registerWorkshopModel) }
|
||
.alert("Clone Ollama Model", isPresented: Binding(
|
||
get: { cloneSource != nil }, set: { if !$0 { cloneSource = nil } }
|
||
), presenting: cloneSource) { model in
|
||
TextField("New model name", text: $cloneName)
|
||
Button("Clone") {
|
||
guard let name = validCloneName else { return }
|
||
studio.copyOllamaModel(model.name, to: name, endpoint: ollamaEndpoint)
|
||
}
|
||
.disabled(validCloneName == nil)
|
||
Button("Cancel", role: .cancel) {}
|
||
} message: { model in
|
||
Text("Copy \(model.name) under a new name on \(ollamaEndpoint).")
|
||
}
|
||
}
|
||
|
||
private func matchesLocal(_ name: String) -> Bool {
|
||
let query = localQuery.trimmingCharacters(in: .whitespacesAndNewlines)
|
||
return query.isEmpty || [name, "MLX"].contains { $0.localizedStandardContains(query) }
|
||
}
|
||
|
||
private func registerLocalModels(_ models: [LocalModelImport]) throws {
|
||
let gguf = models.compactMap { if case .gguf(let model) = $0 { return model }; return nil }
|
||
let mlx = models.compactMap { if case .mlx(let path) = $0 { return path }; return nil }
|
||
if !gguf.isEmpty { ggufLibrary = try GGUFModelMetadata.register(gguf, in: ggufLibrary) }
|
||
if !mlx.isEmpty { registered = try JSONEncoder().encode(Array(Set(library + mlx)).sorted()) }
|
||
}
|
||
|
||
private func importLMStudioLibrary() {
|
||
scanningLibrary = true
|
||
libraryStatus = ""
|
||
Task {
|
||
defer { scanningLibrary = false }
|
||
do {
|
||
let models = try await Task.detached(priority: .userInitiated) {
|
||
try LocalModelImport.discover(in: LocalModelImport.lmStudioFolder)
|
||
}.value
|
||
try registerLocalModels(models)
|
||
lmStudioLocalModels = models
|
||
libraryStatus = models.isEmpty ? "No supported models found in the LM Studio library." :
|
||
"Found \(models.count) models in the LM Studio library."
|
||
} catch { libraryStatus = error.localizedDescription }
|
||
}
|
||
}
|
||
|
||
private var lmStudioLibrary: some View {
|
||
Form {
|
||
ModelLibrarySection("Files on This Mac", key: "libraryLMStudioFilesExpanded") {
|
||
LabeledContent("Folder", value: LocalModelImport.lmStudioFolder.path(percentEncoded: false))
|
||
HStack {
|
||
Button("Scan & Import", systemImage: "folder.badge.plus", action: importLMStudioLibrary)
|
||
.disabled(scanningLibrary || studio.running)
|
||
if scanningLibrary { ProgressView().controlSize(.small) }
|
||
}
|
||
if !libraryStatus.isEmpty { Text(libraryStatus).font(.caption).foregroundStyle(.secondary) }
|
||
ForEach(lmStudioLocalModels, id: \.path) { model in
|
||
HStack {
|
||
VStack(alignment: .leading, spacing: 3) {
|
||
Text(URL(fileURLWithPath: model.path).deletingPathExtension().lastPathComponent)
|
||
Text(model.format).font(.caption).foregroundStyle(.secondary)
|
||
switch model {
|
||
case .gguf:
|
||
let size = try? URL(fileURLWithPath: model.path).resourceValues(forKeys: [.fileSizeKey]).fileSize
|
||
ModelMemoryWarning(bytes: size.map(Int64.init))
|
||
case .mlx:
|
||
let size = try? MLXRuntimeLimits.weightBytes(in: URL(fileURLWithPath: model.path))
|
||
ModelMemoryWarning(bytes: size.flatMap { Int64(exactly: $0) }, mlx: true)
|
||
}
|
||
}
|
||
Spacer()
|
||
Button("Use Locally") {
|
||
switch model {
|
||
case .gguf(let entry): studio.selectGGUFModel(entry.path)
|
||
case .mlx(let path): studio.selectMLXModel(path)
|
||
}
|
||
}.disabled(studio.running || studio.benchmarkRunning)
|
||
}
|
||
}
|
||
}
|
||
ModelLibrarySection("LM Studio Server", key: "libraryLMStudioServerExpanded") {
|
||
TextField("API endpoint", text: $lmStudioEndpoint).onSubmit(refreshLMStudioServer)
|
||
HStack {
|
||
Button("List Server Models", systemImage: "arrow.clockwise", action: refreshLMStudioServer)
|
||
.disabled(lmStudioConnecting || lmStudioEndpoint.isEmpty)
|
||
if lmStudioConnecting { ProgressView().controlSize(.small) }
|
||
}
|
||
if !lmStudioServerStatus.isEmpty { Text(lmStudioServerStatus).font(.caption).foregroundStyle(.secondary) }
|
||
if lmStudioResultsEndpoint == lmStudioEndpoint {
|
||
ForEach(lmStudioServerModels, id: \.self) { model in
|
||
HStack {
|
||
Text(model)
|
||
Spacer()
|
||
let active = compatibleEnabled && defaultCoreMLPath.isEmpty && defaultGGUFPath.isEmpty &&
|
||
!mlxOnly && compatibleModel == model && compatibleEndpoint == lmStudioEndpoint
|
||
Button(active ? "Selected" : "Use Server Model") {
|
||
studio.selectCompatibleModel(model, endpoint: lmStudioEndpoint)
|
||
}.disabled(active || studio.running || studio.benchmarkRunning)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}.formStyle(.grouped)
|
||
}
|
||
|
||
private func refreshLMStudioServer() {
|
||
guard !lmStudioConnecting else { return }
|
||
let endpoint = lmStudioEndpoint.trimmingCharacters(in: .whitespacesAndNewlines)
|
||
lmStudioEndpoint = endpoint
|
||
lmStudioConnecting = true
|
||
lmStudioServerStatus = ""
|
||
lmStudioResultsEndpoint = ""
|
||
Task {
|
||
defer { lmStudioConnecting = false }
|
||
do {
|
||
let models = try await studio.compatibleClient(endpoint: endpoint).models()
|
||
guard lmStudioEndpoint == endpoint else { return }
|
||
lmStudioServerModels = models
|
||
lmStudioResultsEndpoint = endpoint
|
||
if models.isEmpty { lmStudioServerStatus = "The server reported no models." }
|
||
} catch {
|
||
if lmStudioEndpoint == endpoint { lmStudioServerStatus = error.localizedDescription }
|
||
}
|
||
}
|
||
}
|
||
|
||
private func acceptModelDrop(_ providers: [NSItemProvider]) -> Bool {
|
||
let files = providers.filter { $0.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) }
|
||
guard !files.isEmpty, !scanningLibrary, !studio.running else { return false }
|
||
scanningLibrary = true
|
||
Task {
|
||
defer { scanningLibrary = false }
|
||
var models: [LocalModelImport] = []
|
||
var messages: [String] = []
|
||
for provider in files {
|
||
do {
|
||
let url: URL = try await withCheckedThrowingContinuation { continuation in
|
||
_ = provider.loadDataRepresentation(forTypeIdentifier: UTType.fileURL.identifier) { data, error in
|
||
if let error { continuation.resume(throwing: error) }
|
||
else if let data, let url = URL(dataRepresentation: data, relativeTo: nil), url.isFileURL {
|
||
continuation.resume(returning: url)
|
||
} else {
|
||
continuation.resume(throwing: StudioError("Finder did not provide a local file URL."))
|
||
}
|
||
}
|
||
}
|
||
let model = try await Task.detached(priority: .userInitiated) { try LocalModelImport.inspect(url) }.value
|
||
models.append(model)
|
||
} catch {
|
||
messages.append(error.localizedDescription)
|
||
}
|
||
}
|
||
do {
|
||
try registerLocalModels(models)
|
||
let count = models.count
|
||
if count > 0 { messages.insert("Registered \(count) model(s).", at: 0) }
|
||
} catch { messages.append(error.localizedDescription) }
|
||
libraryStatus = messages.joined(separator: " ")
|
||
}
|
||
return true
|
||
}
|
||
|
||
private var localLibrary: some View {
|
||
Form {
|
||
ModelLibrarySection("Import & Filter", key: "libraryImportExpanded") {
|
||
TextField("Filter installed models", text: $localQuery, prompt: Text("Name, architecture, or format"))
|
||
.textFieldStyle(.roundedBorder)
|
||
.accessibilityLabel("Filter installed models")
|
||
Label(dropTargeted ? "Release to import" : "Drop GGUF files or MLX folders here",
|
||
systemImage: "square.and.arrow.down")
|
||
.font(.callout)
|
||
.foregroundStyle(dropTargeted ? Color.accentColor : Color.secondary)
|
||
.frame(maxWidth: .infinity, alignment: .leading)
|
||
.padding(10)
|
||
.background(dropTargeted ? Color.accentColor.opacity(0.12) : Color.secondary.opacity(0.07),
|
||
in: RoundedRectangle(cornerRadius: 8))
|
||
.onDrop(of: [.fileURL], isTargeted: $dropTargeted, perform: acceptModelDrop)
|
||
Button("Import LM Studio Library", systemImage: "folder.badge.plus", action: importLMStudioLibrary)
|
||
.disabled(scanningLibrary || studio.running)
|
||
if scanningLibrary { ProgressView("Checking model files…").controlSize(.small) }
|
||
if !libraryStatus.isEmpty { Text(libraryStatus).foregroundStyle(.secondary) }
|
||
}
|
||
GGUFModels(selection: selection.ggufPath, inUse: studio.inferenceBackend.hasPrefix("GGUF · "),
|
||
filter: localQuery, selectionDisabled: studio.running) {
|
||
studio.selectGGUFModel($0)
|
||
}
|
||
|
||
ModelLibrarySection("Installed MLX Models", key: "libraryMLXExpanded") {
|
||
HStack {
|
||
Button("Import MLX Models…") { pickingLibrary = true }
|
||
Button("Refresh Local Models") { cacheScan += 1 }
|
||
Button("MLX Tools…") { workshop = ModelWorkshop(base: nil) }
|
||
if scanningLibrary { ProgressView().controlSize(.small) }
|
||
}
|
||
.disabled(studio.running || scanningLibrary)
|
||
if library.isEmpty && studio.discoveredMLXPaths.isEmpty && readyModels.isEmpty && (!selection.mlxOnly || selection.mlxPath.isEmpty) {
|
||
Text("Register an existing MLX folder, scan a model library, or download a catalog model below.")
|
||
.foregroundStyle(.secondary)
|
||
}
|
||
ForEach(favoriteFirst(readyModels.filter { matchesLocal($0.id) }) { "mlx:" + $0.id }) { model in modelRow(model) }
|
||
let selectedPath = selection.mlxOnly && !selection.mlxPath.isEmpty ? [selection.mlxPath] : []
|
||
let managedPaths = Set(readyModels.map { $0.localFolder.resolvingSymlinksInPath().path })
|
||
let paths = Set((library + studio.discoveredMLXPaths + selectedPath).map {
|
||
URL(fileURLWithPath: $0).resolvingSymlinksInPath().path
|
||
}).subtracting(managedPaths).sorted()
|
||
ForEach(favoriteFirst(paths.filter { matchesLocal(MLXLibrary.displayName(for: URL(fileURLWithPath: $0))) }) { "folder:" + $0 }, id: \.self) { path in
|
||
HStack {
|
||
let title = MLXLibrary.displayName(for: URL(fileURLWithPath: path))
|
||
VStack(alignment: .leading, spacing: 4) {
|
||
Text(title).help(path)
|
||
Text("MLX · Safetensors").font(.caption).foregroundStyle(.secondary)
|
||
ModelMemoryWarning(bytes: (try? MLXRuntimeLimits.weightBytes(in: URL(fileURLWithPath: path))).flatMap { Int64(exactly: $0) }, mlx: true)
|
||
popularityBadge(title)
|
||
}
|
||
favoriteButton("folder:" + path)
|
||
Spacer()
|
||
Text(ModelLibrarySize.mlx(path))
|
||
.font(.caption).foregroundStyle(.secondary)
|
||
.help("Size of local model weights")
|
||
mlxStatus(path)
|
||
Button("Preview") {
|
||
preview = mlxPreview(model: nil, folder: URL(fileURLWithPath: path))
|
||
}
|
||
mlxLoadButton(path)
|
||
Menu("Tools") {
|
||
Button("Clone & Train…") { workshop = ModelWorkshop(base: URL(fileURLWithPath: path)) }
|
||
Button("Reveal") {
|
||
NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
|
||
}
|
||
}
|
||
.fixedSize()
|
||
if library.contains(path) {
|
||
if library.contains(path) {
|
||
Button("Unregister") {
|
||
registered = (try? JSONEncoder().encode(library.filter { $0 != path })) ?? Data()
|
||
}.disabled(studio.running)
|
||
}
|
||
}
|
||
}
|
||
.listRowBackground(selection.isMLX(path) ? Color.accentColor.opacity(0.12) : nil)
|
||
}
|
||
}
|
||
CoreMLModels(selection: defaultCoreMLPath, disabled: studio.running) { studio.selectCoreMLModel($0) }
|
||
HubGGUFDownloads()
|
||
ModelLibrarySection("Hugging Face · MLX", key: "catalogMLXExpanded") {
|
||
HStack {
|
||
TextField("Search MLX models", text: $query, prompt: Text("Qwen, Gemma, or owner/model"))
|
||
.labelsHidden().textFieldStyle(.roundedBorder).onSubmit(search)
|
||
Button(query.isEmpty ? "Browse" : (query.contains("/") ? "Find Model ID" : "Search"), action: search).disabled(searching || hasMLXDownloads)
|
||
if searching { ProgressView().controlSize(.small) }
|
||
}
|
||
if !searchStatus.isEmpty { Text(searchStatus).foregroundStyle(.secondary) }
|
||
let available = matches.filter { model in !readyModels.contains { $0.id == model.id } }
|
||
ForEach(favoriteFirst(available) { "mlx:" + $0.id }) { model in
|
||
modelRow(model)
|
||
}
|
||
}
|
||
ModelLibrarySection("Recommended Models", key: "libraryRecommendedExpanded") {
|
||
ForEach(favoriteFirst(CatalogModel.all.filter { !$0.installed(at: $0.localFolder) }) { "mlx:" + $0.id }) { model in modelRow(model) }
|
||
}
|
||
if !status.isEmpty && !hasMLXDownloads {
|
||
Section {
|
||
Text(status).textSelection(.enabled).foregroundStyle(.secondary)
|
||
if loadingPath != nil { ProgressView().controlSize(.small) }
|
||
}
|
||
}
|
||
}
|
||
.formStyle(.grouped)
|
||
.task(id: cacheScan) {
|
||
do {
|
||
try await studio.refreshLocalMLXModels()
|
||
} catch is CancellationError {
|
||
return
|
||
} catch {
|
||
libraryStatus = "Could not scan local models. \(error.localizedDescription)"
|
||
}
|
||
}
|
||
.task {
|
||
while !Task.isCancelled {
|
||
await refreshLoadedPath()
|
||
do { try await Task.sleep(for: .seconds(2)) }
|
||
catch { return }
|
||
}
|
||
}
|
||
.fileImporter(isPresented: $pickingLibrary, allowedContentTypes: [.folder]) { result in
|
||
do {
|
||
let url = try result.get()
|
||
scanningLibrary = true
|
||
libraryStatus = ""
|
||
Task {
|
||
defer { scanningLibrary = false }
|
||
do {
|
||
let found = try await Task.detached(priority: .userInitiated) {
|
||
let scoped = url.startAccessingSecurityScopedResource()
|
||
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
|
||
return try MLXLibrary.discover(in: url.resolvingSymlinksInPath())
|
||
}.value
|
||
guard !found.isEmpty else {
|
||
throw StudioError("No complete MLX checkpoints found in \(url.lastPathComponent).")
|
||
}
|
||
try registerLocalModels(found.map { .mlx($0.path) })
|
||
libraryStatus = "Registered \(found.count) MLX model(s)."
|
||
} catch { libraryStatus = error.localizedDescription }
|
||
}
|
||
} catch { libraryStatus = error.localizedDescription }
|
||
}
|
||
.confirmationDialog("Remove downloaded model?", isPresented: Binding(
|
||
get: { removing != nil }, set: { if !$0 { removing = nil } }
|
||
), titleVisibility: .visible, presenting: removing) { model in
|
||
Button("Remove Model", role: .destructive) { remove(model) }
|
||
} message: { model in Text(model.title) }
|
||
}
|
||
|
||
private var ollamaLibrary: some View {
|
||
Form {
|
||
ModelLibrarySection("Installed on Ollama", key: "libraryOllamaExpanded") {
|
||
LabeledContent("Server", value: ollamaEndpoint)
|
||
Button("Refresh Installed Models") { studio.refresh(endpoint: ollamaEndpoint) }
|
||
.disabled(studio.managing)
|
||
if studio.modelListEndpoint == ollamaEndpoint {
|
||
if studio.models.isEmpty { Text("No models installed on this server.").foregroundStyle(.secondary) }
|
||
ForEach(favoriteFirst(studio.models) { "ollama:" + $0.name }) { model in
|
||
HStack {
|
||
VStack(alignment: .leading, spacing: 4) {
|
||
Label(model.name, systemImage: "cube")
|
||
if let format = model.details?.format {
|
||
Text(format.uppercased()).font(.caption).foregroundStyle(.secondary)
|
||
}
|
||
popularityBadge(model.name)
|
||
}
|
||
favoriteButton("ollama:" + model.name)
|
||
Spacer()
|
||
Text(ModelLibrarySize.label(model.size)).font(.caption).foregroundStyle(.secondary)
|
||
if selection.isOllama(model.name) { activeBadge("Ollama") }
|
||
Button("Preview") { preview = ollamaPreview(model) }
|
||
Menu("Tools") {
|
||
Button("Clone…") {
|
||
cloneName = (model.name.split(separator: ":").first.map(String.init) ?? model.name) + "-clone"
|
||
cloneSource = model
|
||
}
|
||
.disabled(studio.managing)
|
||
Button("Convert to MLX…") { workshop = ModelWorkshop(base: nil, modelName: model.name) }
|
||
.disabled(studio.running)
|
||
}
|
||
.fixedSize()
|
||
Button("Use Model") {
|
||
studio.selectOllamaModel(model.name)
|
||
}
|
||
.disabled(selection.isOllama(model.name) || studio.running)
|
||
}
|
||
.listRowBackground(selection.isOllama(model.name) ? Color.accentColor.opacity(0.12) : nil)
|
||
}
|
||
}
|
||
if !studio.modelStatus.isEmpty { Text(studio.modelStatus).foregroundStyle(.secondary) }
|
||
if studio.managing {
|
||
ProgressView().controlSize(.small)
|
||
Button("Cancel") { studio.cancelManagement() }
|
||
}
|
||
}
|
||
ModelLibrarySection("Ollama Catalog", key: "catalogOllamaExpanded") {
|
||
HStack {
|
||
TextField("Search Ollama models", text: $ollamaQuery, prompt: Text("e.g. Qwen, Llama"))
|
||
.labelsHidden().textFieldStyle(.roundedBorder).onSubmit(searchOllama)
|
||
Button(ollamaQuery.isEmpty ? "Browse" : "Search", action: searchOllama).disabled(ollamaSearching || hasOllamaDownloads)
|
||
if ollamaSearching { ProgressView().controlSize(.small) }
|
||
}
|
||
if !ollamaCatalogStatus.isEmpty { Text(ollamaCatalogStatus).foregroundStyle(.secondary) }
|
||
ForEach(favoriteFirst(ollamaCatalog) { "ollama:" + $0 + ":latest" }, id: \.self) { name in
|
||
VStack(alignment: .leading, spacing: 6) {
|
||
HStack {
|
||
VStack(alignment: .leading, spacing: 4) {
|
||
Text(name).font(.headline)
|
||
popularityBadge(name)
|
||
}
|
||
favoriteButton("ollama:" + name + ":latest")
|
||
Spacer()
|
||
let installed = studio.modelListEndpoint == ollamaEndpoint ?
|
||
studio.models.first { $0.name == name || $0.name == name + ":latest" } : nil
|
||
let installedBytes = installed?.size.flatMap { $0 > 0 ? $0 : nil }
|
||
let bytes = installedBytes ?? catalogBytes["ollama:" + name]
|
||
Text(ModelLibrarySize.label(bytes)).font(.caption).foregroundStyle(.secondary)
|
||
.help(installedBytes == nil ? "Registry download size for the latest tag" : "Installed size reported by the server")
|
||
Button("Preview") {
|
||
preview = installed.map(ollamaPreview) ?? ollamaCatalogPreview(name)
|
||
}
|
||
if let installed, selection.isOllama(installed.name) { activeBadge("Ollama") }
|
||
if let card = URL(string: "https://ollama.com/library/" + name) {
|
||
Link("Tags", destination: card)
|
||
}
|
||
if installed != nil {
|
||
Text("Installed").foregroundStyle(.secondary)
|
||
} else if let task = downloads["ollama:" + name] {
|
||
Button("Cancel Download") { task.cancel() }
|
||
} else {
|
||
Button("Pull Latest") { pull(name) }
|
||
}
|
||
}
|
||
downloadProgress("ollama:" + name)
|
||
}
|
||
.task {
|
||
let key = "ollama:" + name
|
||
guard catalogBytes[key] == nil else { return }
|
||
if let manifest = try? await OllamaRegistryManifest.latest(name), !Task.isCancelled {
|
||
catalogBytes[key] = manifest.bytes
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
.formStyle(.grouped)
|
||
.onAppear {
|
||
if ollamaCatalog.isEmpty && ollamaCatalogStatus.isEmpty { searchOllama() }
|
||
}
|
||
.task(id: ollamaEndpoint) {
|
||
let endpoint = ollamaEndpoint
|
||
while studio.managing {
|
||
do { try await Task.sleep(for: .milliseconds(100)) }
|
||
catch { return }
|
||
}
|
||
guard !Task.isCancelled else { return }
|
||
studio.refresh(endpoint: endpoint)
|
||
}
|
||
}
|
||
|
||
private var hasMLXDownloads: Bool { downloads.keys.contains { $0.hasPrefix("mlx:") } }
|
||
private var hasOllamaDownloads: Bool { downloads.keys.contains { $0.hasPrefix("ollama:") } }
|
||
|
||
@ViewBuilder private func downloadProgress(_ key: String) -> some View {
|
||
if let state = downloadStates[key] {
|
||
if downloads[key] != nil {
|
||
ProgressView(value: state.fraction).progressViewStyle(.linear)
|
||
.accessibilityLabel("Download progress")
|
||
}
|
||
Text(state.message).font(.caption).foregroundStyle(.secondary)
|
||
}
|
||
}
|
||
|
||
private func pull(_ name: String) {
|
||
let key = "ollama:" + name
|
||
guard downloads[key] == nil else { return }
|
||
let endpoint = ollamaEndpoint
|
||
downloadStates[key] = DownloadState(message: "Preparing download…", fraction: nil)
|
||
downloads[key] = Task {
|
||
defer {
|
||
downloads[key] = nil
|
||
if !hasOllamaDownloads && endpoint == ollamaEndpoint {
|
||
Task {
|
||
while studio.managing { try await Task.sleep(for: .milliseconds(100)) }
|
||
if endpoint == ollamaEndpoint { studio.refresh(endpoint: endpoint) }
|
||
}
|
||
}
|
||
}
|
||
do {
|
||
let client = try studio.ollamaClient(endpoint: endpoint)
|
||
for try await message in client.pull(name) {
|
||
let percent = message.hasSuffix("%") ? message.split(separator: " ").last.flatMap { Double($0.dropLast()) } : nil
|
||
downloadStates[key] = DownloadState(message: message, fraction: percent.map { $0 / 100 })
|
||
}
|
||
try Task.checkCancellation()
|
||
downloadStates[key] = DownloadState(message: "Downloaded.", fraction: nil)
|
||
} catch {
|
||
downloadStates[key] = DownloadState(message: Task.isCancelled ? "Download cancelled." : error.localizedDescription, fraction: nil)
|
||
}
|
||
}
|
||
}
|
||
|
||
private func searchOllama() {
|
||
guard !ollamaSearching, !hasOllamaDownloads else { return }
|
||
let term = ollamaQuery.trimmingCharacters(in: .whitespacesAndNewlines)
|
||
ollamaSearching = true
|
||
ollamaCatalogStatus = ""
|
||
Task {
|
||
defer { ollamaSearching = false }
|
||
do {
|
||
ollamaCatalog = try await OllamaCatalog.search(term)
|
||
if ollamaCatalog.isEmpty { ollamaCatalogStatus = "No models found." }
|
||
} catch { ollamaCatalogStatus = error.localizedDescription }
|
||
}
|
||
}
|
||
|
||
private func modelRow(_ model: CatalogModel) -> some View {
|
||
let saved = installedModels.first { $0.id == model.id } ?? model
|
||
let installed = saved.installed(at: saved.localFolder)
|
||
let isActive = installed && selection.isMLX(saved.localFolder.path)
|
||
let metadataKey = model.metadataKey
|
||
return HubCatalogRow {
|
||
Text(model.title).font(.headline)
|
||
favoriteButton("mlx:" + model.id)
|
||
popularityBadge(model.repository)
|
||
} metadata: {
|
||
Text("MLX · Safetensors")
|
||
Text(installed ? ModelLibrarySize.mlx(saved.localFolder.path) : ModelLibrarySize.label(catalogBytes[metadataKey]))
|
||
.help(installed ? "Size of local model weights" : "Weight files at the listed Hugging Face revision")
|
||
ModelMemoryWarning(bytes: installed
|
||
? (try? MLXRuntimeLimits.weightBytes(in: saved.localFolder)).flatMap { Int64(exactly: $0) }
|
||
: catalogBytes[metadataKey], mlx: true)
|
||
if let count = model.downloads { Label(count.formatted(), systemImage: "arrow.down") }
|
||
if let count = model.likes { Label(count.formatted(), systemImage: "heart") }
|
||
if installed { mlxStatus(saved.localFolder.path) }
|
||
} actions: {
|
||
Button("Preview") { preview = mlxPreview(model: model, folder: installed ? saved.localFolder : nil) }
|
||
Link("Model Card", destination: model.source)
|
||
Spacer()
|
||
if installed {
|
||
mlxLoadButton(saved.localFolder.path)
|
||
Button("Clone & Train…") { workshop = ModelWorkshop(base: saved.localFolder) }
|
||
.disabled(studio.running || loadingPath != nil)
|
||
Button("Reveal") { NSWorkspace.shared.activateFileViewerSelecting([saved.localFolder]) }
|
||
} else {
|
||
if let task = downloads["mlx:" + model.id] {
|
||
Button("Cancel Download") { task.cancel() }
|
||
} else {
|
||
Button("Download") { download(model) }
|
||
}
|
||
}
|
||
if FileManager.default.fileExists(atPath: saved.localFolder.path) {
|
||
Button("Remove…", role: .destructive) { removing = saved }
|
||
.disabled(studio.running || downloads["mlx:" + model.id] != nil || loadingPath != nil)
|
||
}
|
||
} footer: {
|
||
downloadProgress("mlx:" + model.id)
|
||
}
|
||
.listRowBackground(isActive ? Color.accentColor.opacity(0.12) : nil)
|
||
.task(id: installed ? nil : metadataKey) {
|
||
guard !installed, catalogBytes[metadataKey] == nil else { return }
|
||
if let metadata = try? await HubModelMetadata.load(model), !Task.isCancelled {
|
||
catalogBytes[metadataKey] = metadata.weightBytes(files: model.files)
|
||
}
|
||
}
|
||
}
|
||
|
||
private func registerWorkshopModel(_ url: URL) {
|
||
let path = url.resolvingSymlinksInPath().path
|
||
if let data = try? JSONEncoder().encode(Array(Set(library + [path])).sorted()) {
|
||
registered = data
|
||
libraryBackend = "MLX"
|
||
libraryStatus = "Registered \(url.lastPathComponent)."
|
||
}
|
||
}
|
||
|
||
private func search() {
|
||
let term = query.trimmingCharacters(in: .whitespacesAndNewlines)
|
||
guard !searching, !hasMLXDownloads else { return }
|
||
searching = true
|
||
searchStatus = ""
|
||
matches = []
|
||
Task {
|
||
defer { searching = false }
|
||
do {
|
||
if term.contains("/") {
|
||
matches = [try await CatalogModel.resolve(term)]
|
||
} else {
|
||
matches = try await CatalogModel.search(term)
|
||
}
|
||
if matches.isEmpty { searchStatus = "No MLX checkpoints matched." }
|
||
} catch { searchStatus = error.localizedDescription }
|
||
}
|
||
}
|
||
|
||
private func refreshLoadedPath() async {
|
||
loadedPath = await studio.mlxLoadedPath().map {
|
||
URL(fileURLWithPath: $0).resolvingSymlinksInPath().path
|
||
}
|
||
}
|
||
|
||
private func isLoaded(_ path: String) -> Bool {
|
||
loadedPath == URL(fileURLWithPath: path).resolvingSymlinksInPath().path
|
||
}
|
||
|
||
@ViewBuilder
|
||
private func mlxStatus(_ path: String) -> some View {
|
||
if selection.isMLX(path) {
|
||
Label("Selected", systemImage: "checkmark.circle.fill")
|
||
.font(.caption.weight(.semibold)).foregroundStyle(Color.accentColor)
|
||
}
|
||
if isLoaded(path) {
|
||
let inUse = studio.running && studio.inferenceBackend.hasPrefix("MLX")
|
||
Label(inUse ? "In use" : "Loaded", systemImage: "memorychip")
|
||
.font(.caption).foregroundStyle(.secondary)
|
||
}
|
||
}
|
||
|
||
@ViewBuilder
|
||
private func mlxLoadButton(_ path: String) -> some View {
|
||
if isLoaded(path) {
|
||
Button("Unload") {
|
||
Task {
|
||
await studio.unloadMLXModel()
|
||
await refreshLoadedPath()
|
||
}
|
||
}
|
||
.disabled(studio.running || loadingPath != nil)
|
||
if !selection.isMLX(path) {
|
||
Button("Use Model") { studio.selectMLXModel(path) }.disabled(studio.running)
|
||
}
|
||
} else {
|
||
Button("Load Model") { load(path) }
|
||
.disabled(studio.running || loadingPath != nil || !MLXLibrary.isModel(at: URL(fileURLWithPath: path)))
|
||
}
|
||
}
|
||
|
||
private func load(_ path: String) {
|
||
guard loadingPath == nil, !studio.running else { return }
|
||
loadingPath = path
|
||
let name = MLXLibrary.displayName(for: URL(fileURLWithPath: path))
|
||
status = "Loading \(name)…"
|
||
Task {
|
||
do {
|
||
try await studio.loadMLX(path)
|
||
studio.selectMLXModel(path)
|
||
status = "Loaded \(name)."
|
||
} catch { status = "Could not load \(name). \(error.localizedDescription)" }
|
||
await refreshLoadedPath()
|
||
loadingPath = nil
|
||
}
|
||
}
|
||
|
||
private func download(_ model: CatalogModel) {
|
||
let key = "mlx:" + model.id
|
||
guard downloads[key] == nil else { return }
|
||
downloadStates[key] = DownloadState(message: "Preparing download…", fraction: 0)
|
||
downloads[key] = Task {
|
||
defer { downloads[key] = nil }
|
||
do {
|
||
try await model.install(to: model.localFolder) { message, fraction in
|
||
await MainActor.run { downloadStates[key] = DownloadState(message: message, fraction: fraction) }
|
||
}
|
||
if !CatalogModel.all.contains(where: { $0.id == model.id }) {
|
||
managed = try JSONEncoder().encode(installedModels.filter { $0.id != model.id && !CatalogModel.all.contains($0) } + [model])
|
||
}
|
||
downloadStates[key] = DownloadState(message: "Downloaded.", fraction: nil)
|
||
} catch {
|
||
downloadStates[key] = DownloadState(message: Task.isCancelled ? "Download cancelled." : error.localizedDescription, fraction: nil)
|
||
}
|
||
}
|
||
}
|
||
|
||
private func remove(_ model: CatalogModel) {
|
||
guard !studio.running, downloads["mlx:" + model.id] == nil else { return }
|
||
do {
|
||
try FileManager.default.removeItem(at: model.localFolder)
|
||
if isLoaded(model.localFolder.path) { studio.unloadMLX() }
|
||
if URL(fileURLWithPath: mlxPath).resolvingSymlinksInPath().path == model.localFolder.resolvingSymlinksInPath().path {
|
||
mlxPath = ""
|
||
}
|
||
studio.forgetDiscoveredMLXModel(model.localFolder.resolvingSymlinksInPath().path)
|
||
managed = try JSONEncoder().encode(installedModels.filter { $0.id != model.id && !CatalogModel.all.contains($0) })
|
||
status = "Removed \(model.title)."
|
||
} catch { status = error.localizedDescription }
|
||
}
|
||
}
|
||
|
||
enum MLXLibrary {
|
||
static func discover(in root: URL) throws -> [URL] {
|
||
let scoped = root.startAccessingSecurityScopedResource()
|
||
defer { if scoped { root.stopAccessingSecurityScopedResource() } }
|
||
let manager = FileManager.default
|
||
var queue: [(URL, Int)] = [(root.resolvingSymlinksInPath(), 0)]
|
||
var found: [URL] = []
|
||
var offset = 0
|
||
while offset < queue.count && offset < 2000 && found.count < 100 {
|
||
try Task.checkCancellation()
|
||
let (folder, depth) = queue[offset]
|
||
offset += 1
|
||
if isModel(at: folder) { found.append(folder); continue }
|
||
guard depth < 4 else { continue }
|
||
let children: [URL]
|
||
do {
|
||
children = try manager.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
|
||
options: [.skipsHiddenFiles, .skipsPackageDescendants])
|
||
.sorted { $0.lastPathComponent < $1.lastPathComponent }
|
||
} catch {
|
||
if depth == 0 { throw error }
|
||
continue
|
||
}
|
||
for child in children where queue.count < 2000 {
|
||
if folder.lastPathComponent.hasPrefix("models--"), child.lastPathComponent != "snapshots" { continue }
|
||
if let values = try? child.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]),
|
||
values.isDirectory == true, values.isSymbolicLink != true {
|
||
queue.append((child, depth + 1))
|
||
}
|
||
}
|
||
}
|
||
return found.sorted { $0.path < $1.path }
|
||
}
|
||
|
||
static func discoverLocalModels() throws -> [URL] {
|
||
let environment = ProcessInfo.processInfo.environment
|
||
let home = URL.homeDirectory
|
||
let defaultCache = home.appending(path: ".cache/huggingface/hub")
|
||
var roots = [
|
||
URL.applicationSupportDirectory.appending(path: "AIStudio/Models"),
|
||
URL.documentsDirectory.appending(path: "huggingface/models"),
|
||
defaultCache, LocalModelImport.lmStudioFolder
|
||
]
|
||
if let cache = environment["HF_HUB_CACHE"] ?? environment["HUGGINGFACE_HUB_CACHE"], !cache.isEmpty {
|
||
roots.append(URL(fileURLWithPath: cache))
|
||
}
|
||
if let hfHome = environment["HF_HOME"], !hfHome.isEmpty {
|
||
roots.append(URL(fileURLWithPath: hfHome).appending(path: "hub"))
|
||
}
|
||
if let cache = environment["XDG_CACHE_HOME"], !cache.isEmpty {
|
||
roots.append(URL(fileURLWithPath: cache).appending(path: "huggingface/hub"))
|
||
}
|
||
var found: Set<URL> = []
|
||
for root in Set(roots.map { $0.resolvingSymlinksInPath() }) where FileManager.default.fileExists(atPath: root.path) {
|
||
found.formUnion(try discover(in: root))
|
||
}
|
||
return found.sorted { $0.path < $1.path }
|
||
}
|
||
|
||
static func displayName(for folder: URL) -> String {
|
||
let snapshots = folder.deletingLastPathComponent()
|
||
let repository = snapshots.deletingLastPathComponent().lastPathComponent
|
||
guard snapshots.lastPathComponent == "snapshots", repository.hasPrefix("models--") else {
|
||
return folder.lastPathComponent
|
||
}
|
||
let name = repository.dropFirst("models--".count).replacingOccurrences(of: "--", with: "/")
|
||
return "\(name) · \(folder.lastPathComponent.prefix(8))"
|
||
}
|
||
|
||
static func hasFile(_ name: String, in folder: URL) -> Bool {
|
||
let file = folder.appending(path: name).resolvingSymlinksInPath()
|
||
guard let values = try? file.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]) else { return false }
|
||
return values.isRegularFile == true && (values.fileSize ?? 0) > 0
|
||
}
|
||
|
||
static func isModel(at url: URL) -> Bool {
|
||
let config = url.appending(path: "config.json")
|
||
guard hasFile("config.json", in: url),
|
||
let data = try? Data(contentsOf: config),
|
||
(try? MLXModelConfiguration.decode(data)) != nil,
|
||
((try? MLXRuntimeLimits.weightBytes(in: url)) ?? 0) > 0 else { return false }
|
||
let index = url.appending(path: "model.safetensors.index.json")
|
||
guard FileManager.default.fileExists(atPath: index.path) else { return true }
|
||
struct Index: Decodable { let weight_map: [String: String] }
|
||
guard let data = try? Data(contentsOf: index),
|
||
let map = try? JSONDecoder().decode(Index.self, from: data).weight_map,
|
||
!map.isEmpty else { return false }
|
||
return Set(map.values).allSatisfy {
|
||
CatalogModel.safeComponent($0) && $0.hasSuffix(".safetensors") && hasFile($0, in: url)
|
||
}
|
||
}
|
||
}
|
||
|
||
enum OllamaCatalog {
|
||
static func search(_ term: String) async throws -> [String] {
|
||
var parts = URLComponents()
|
||
parts.scheme = "https"
|
||
parts.host = "ollama.com"
|
||
parts.path = "/search"
|
||
parts.queryItems = [.init(name: "q", value: term)]
|
||
guard let url = parts.url else { throw StudioError("Could not prepare the Ollama catalog request.") }
|
||
let result = try await WebFetch.load(url, types: ["text/html"])
|
||
return modelNames(in: String(decoding: result.data, as: UTF8.self))
|
||
}
|
||
|
||
static func modelNames(in html: String) -> [String] {
|
||
let pattern = #"href\s*=\s*["']/library/([A-Za-z0-9._-]+)["']"#
|
||
guard let regex = try? NSRegularExpression(pattern: pattern) else { return [] }
|
||
var seen = Set<String>()
|
||
return regex.matches(in: html, range: NSRange(html.startIndex..., in: html)).compactMap { match in
|
||
guard let range = Range(match.range(at: 1), in: html) else { return nil }
|
||
let name = String(html[range])
|
||
return name != "." && name != ".." && seen.insert(name).inserted ? name : nil
|
||
}
|
||
}
|
||
}
|