new features

This commit is contained in:
Mark Gregory
2026-11-19 09:18:49 +00:00
parent a07ddf4d6d
commit 0720c8a18b
13 changed files with 918 additions and 211 deletions
+223 -55
View File
@@ -211,6 +211,45 @@ struct HubModelMetadata: Decodable {
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
@@ -248,7 +287,7 @@ struct OllamaRegistryManifest: Decodable {
}
}
private struct ModelPreview: Identifiable {
struct ModelPreview: Identifiable {
let id = UUID()
let title: String
let fields: [(String, String?)]
@@ -256,7 +295,7 @@ private struct ModelPreview: Identifiable {
var load: (() async throws -> [(String, String?)])?
}
private struct ModelPreviewSheet: View {
struct ModelPreviewSheet: View {
let preview: ModelPreview
@Environment(\.dismiss) private var dismiss
@State private var details: [(String, String?)] = []
@@ -300,6 +339,54 @@ private struct ModelPreviewSheet: View {
}
}
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 }
@@ -413,6 +500,14 @@ struct ModelCatalogView: View {
@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"
@@ -555,29 +650,25 @@ struct ModelCatalogView: View {
}
private func favoriteButton(_ key: String) -> some View {
let saved = favorites.contains(key)
let label = saved ? "Remove from Favorites" : "Add to Favorites"
return Button(label, systemImage: saved ? "star.fill" : "star") {
var updated = favorites
if saved { updated.remove(key) } else { updated.insert(key) }
if let data = try? JSONEncoder().encode(updated) { favoriteData = data }
}
.labelStyle(.iconOnly)
.buttonStyle(.borderless)
.help(label)
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)
.frame(width: 260)
.labelsHidden()
.accessibilityLabel("Model library")
.frame(maxWidth: 430)
.padding()
if libraryBackend == "Ollama" {
ollamaLibrary
} else if libraryBackend == "LM Studio" {
lmStudioLibrary
} else {
localLibrary
}
@@ -621,12 +712,93 @@ struct ModelCatalogView: View {
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 }
@@ -665,7 +837,7 @@ struct ModelCatalogView: View {
private var localLibrary: some View {
Form {
Section {
ModelLibrarySection("Import & Filter", key: "libraryImportExpanded") {
TextField("Filter installed models", text: $localQuery, prompt: Text("Name, architecture, or format"))
.textFieldStyle(.roundedBorder)
.accessibilityLabel("Filter installed models")
@@ -688,7 +860,7 @@ struct ModelCatalogView: View {
studio.selectGGUFModel($0)
}
Section("Installed MLX Models") {
ModelLibrarySection("Installed MLX Models", key: "libraryMLXExpanded") {
HStack {
Button("Import MLX Models…") { pickingLibrary = true }
Button("Refresh Local Models") { cacheScan += 1 }
@@ -745,7 +917,7 @@ struct ModelCatalogView: View {
}
CoreMLModels(selection: defaultCoreMLPath, disabled: studio.running) { studio.selectCoreMLModel($0) }
HubGGUFDownloads()
Section("Hugging Face · MLX") {
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)
@@ -758,7 +930,7 @@ struct ModelCatalogView: View {
modelRow(model)
}
}
Section("Recommended Models") {
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 {
@@ -816,7 +988,7 @@ struct ModelCatalogView: View {
private var ollamaLibrary: some View {
Form {
Section("Installed on Ollama") {
ModelLibrarySection("Installed on Ollama", key: "libraryOllamaExpanded") {
LabeledContent("Server", value: ollamaEndpoint)
Button("Refresh Installed Models") { studio.refresh(endpoint: ollamaEndpoint) }
.disabled(studio.managing)
@@ -860,7 +1032,7 @@ struct ModelCatalogView: View {
Button("Cancel") { studio.cancelManagement() }
}
}
Section("Ollama Catalog") {
ModelLibrarySection("Ollama Catalog", key: "catalogOllamaExpanded") {
HStack {
TextField("Search Ollama models", text: $ollamaQuery, prompt: Text("e.g. Qwen, Llama"))
.labelsHidden().textFieldStyle(.roundedBorder).onSubmit(searchOllama)
@@ -986,47 +1158,43 @@ struct ModelCatalogView: View {
let installed = saved.installed(at: saved.localFolder)
let isActive = installed && selection.isMLX(saved.localFolder.path)
let metadataKey = model.metadataKey
return VStack(alignment: .leading, spacing: 6) {
HStack {
Text(model.title).font(.headline)
favoriteButton("mlx:" + model.id)
popularityBadge(model.repository)
}
HStack {
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) }
}.font(.caption).foregroundStyle(.secondary)
HStack {
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]) }
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 {
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)
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)
}
.padding(.vertical, 4)
.listRowBackground(isActive ? Color.accentColor.opacity(0.12) : nil)
.task(id: installed ? nil : metadataKey) {
guard !installed, catalogBytes[metadataKey] == nil else { return }