Files
ai_studio/Sources/ModelDownload.swift
T
Mark Gregory 2238df4631 Build AI Studio for macOS
Add branded startup, Ollama and MLX inference, persistent chat and document retrieval, confirmed MCP tools, and reproducible build and test scripts.
2026-11-16 13:14:00 +00:00

160 lines
7.1 KiB
Swift

import Foundation
import SwiftUI
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<Void, Never>?
@State private var active: CatalogModel?
@State private var removing: CatalogModel?
@State private var status = ""
var body: some View {
Form {
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)
.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 }
}
}