import Foundation import SwiftUI import UniformTypeIdentifiers import AppKit struct CatalogModel: Identifiable, Hashable, Sendable { let id: String let title: String let size: String let repository: String let revision: String let files: [String] 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"]) ] var source: URL { URL(string: "https://huggingface.co/" + repository)! } var localFolder: URL { URL.applicationSupportDirectory.appending(path: "AIStudio/Models", directoryHint: .isDirectory) .appending(path: id, directoryHint: .isDirectory) } func installed(at folder: URL) -> Bool { files.allSatisfy { let file = folder.appending(path: $0) return ((try? file.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) > 0 } } func install( to destination: URL, progress: @Sendable (String) 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 staging = URL.temporaryDirectory.appending(path: "AIStudio-model-\(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))…") 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 { throw StudioError("Could not download \(file).") } 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.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) try manager.moveItem(at: staging, to: destination) } } struct ModelCatalogView: View { @ObservedObject var studio: StudioModel @AppStorage("mlxPath") private var mlxPath = "" @AppStorage("mlxOnly") private var mlxOnly = false @State private var operation: Task? @State private var active: CatalogModel? @AppStorage("mlxRegisteredPaths") private var registered = Data() @State private var pickingLibrary = false @State private var libraryStatus = "" private var library: [String] { (try? JSONDecoder().decode([String].self, from: registered)) ?? [] } @State private var removing: CatalogModel? @State private var status = "" var body: some View { Form { Section("Model Library") { Button("Register Model Folder…") { pickingLibrary = true } .disabled(studio.running) ForEach(library, id: \.self) { path in HStack { Text(URL(fileURLWithPath: path).lastPathComponent).help(path) Spacer() Button(mlxPath == path && mlxOnly ? "Selected" : "Use Model") { mlxPath = path mlxOnly = true studio.unloadMLX() } .disabled(studio.running || !MLXLibrary.isModel(at: URL(fileURLWithPath: path)) || (mlxPath == path && mlxOnly)) Button("Reveal") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)]) } Button("Unregister") { registered = (try? JSONEncoder().encode(library.filter { $0 != path })) ?? Data() }.disabled(studio.running) } } if !libraryStatus.isEmpty { Text(libraryStatus).foregroundStyle(.secondary) } } Section("Download for on-device inference") { ForEach(CatalogModel.all) { model in let installed = model.installed(at: model.localFolder) VStack(alignment: .leading, spacing: 6) { HStack { Text(model.title).font(.headline) Spacer() Text(model.size).font(.caption).foregroundStyle(.secondary) } HStack { Link("Model Card", destination: model.source) Spacer() if installed { Button(mlxPath == model.localFolder.path && mlxOnly ? "Selected" : "Use Model") { mlxPath = model.localFolder.path mlxOnly = true studio.unloadMLX() } .disabled(studio.running || (mlxPath == model.localFolder.path && mlxOnly)) } else { Button("Download") { download(model) }.disabled(active != nil) } if FileManager.default.fileExists(atPath: model.localFolder.path) { Button("Remove…", role: .destructive) { removing = model } .disabled(studio.running || active != nil) } } } .padding(.vertical, 4) } } if !status.isEmpty { Section { Text(status).textSelection(.enabled).foregroundStyle(.secondary) if active != nil { Button("Cancel Download") { operation?.cancel() } } } } } .formStyle(.grouped) .fileImporter(isPresented: $pickingLibrary, allowedContentTypes: [.folder]) { result in do { let url = try result.get().resolvingSymlinksInPath() guard MLXLibrary.isModel(at: url) else { throw StudioError("Choose an MLX folder with config.json and safetensors weights.") } if !library.contains(url.path) { registered = try JSONEncoder().encode(library + [url.path]) } libraryStatus = "Registered \(url.lastPathComponent)." } 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 func download(_ model: CatalogModel) { guard active == nil else { return } active = model operation = Task { defer { active = nil; operation = nil } do { try await model.install(to: model.localFolder) { message in await MainActor.run { status = message } } status = "Downloaded \(model.title)." } catch { status = Task.isCancelled ? "Download cancelled." : error.localizedDescription } } } private func remove(_ model: CatalogModel) { guard !studio.running, active == nil else { return } do { try FileManager.default.removeItem(at: model.localFolder) if mlxPath == model.localFolder.path { mlxPath = "" studio.unloadMLX() } status = "Removed \(model.title)." } catch { status = error.localizedDescription } } } enum MLXLibrary { static func isModel(at url: URL) -> Bool { FileManager.default.fileExists(atPath: url.appending(path: "config.json").path) && ((try? MLXRuntimeLimits.weightBytes(in: url)) ?? 0) > 0 } }