new features

This commit is contained in:
Mark Gregory
2026-11-17 15:35:04 +00:00
parent 71972cd843
commit d1a1b454f6
18 changed files with 2598 additions and 112 deletions
+427 -33
View File
@@ -74,6 +74,7 @@ struct CatalogModel: Identifiable, Hashable, Sendable, Codable {
}
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, directoryHint: .isDirectory)
@@ -123,6 +124,194 @@ struct CatalogModel: Identifiable, Hashable, Sendable, Codable {
}
}
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 rfilename: String
let size: Int64?
let lfs: LFS?
}
let siblings: [File]
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)
}
}
private struct ModelPreview: Identifiable {
let id = UUID()
let title: String
let fields: [(String, String?)]
var source: URL?
var load: (() async throws -> [(String, String?)])?
}
private 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 } }
}
}
}
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
func isMLX(_ path: String) -> Bool {
mlxOnly && !mlxPath.isEmpty &&
URL(fileURLWithPath: mlxPath).resolvingSymlinksInPath().standardizedFileURL.path ==
URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL.path
}
func isOllama(_ name: String) -> Bool {
guard !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("mlxPath") private var mlxPath = ""
@@ -151,7 +340,12 @@ struct ModelCatalogView: View {
@State private var loadingPath: String?
@AppStorage("favoriteModelKeys") private var favoriteData = Data()
@State private var backend = "MLX"
@State private var libraryBackend: String?
private var backend: Binding<String> {
Binding(get: { libraryBackend ?? (selection.mlxOnly ? "MLX" : "Ollama") },
set: { libraryBackend = $0 })
}
@AppStorage("endpoint") private var ollamaEndpoint = "http://127.0.0.1:11434"
@AppStorage("ollamaModel") private var ollamaModel = ""
@AppStorage("compatibleEnabled") private var compatibleEnabled = false
@@ -161,6 +355,113 @@ struct ModelCatalogView: View {
@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?.lastPathComponent ?? "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)
], 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
)
}
return ModelLibrarySelection(mlxOnly: mlxOnly, compatible: compatibleEnabled,
mlxPath: mlxPath, ollamaModel: ollamaModel)
}
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) }
@@ -195,19 +496,34 @@ struct ModelCatalogView: View {
var body: some View {
VStack(spacing: 0) {
Picker("Model runtime", selection: $backend) {
Picker("Model runtime", selection: backend) {
Text("MLX").tag("MLX")
Text("Ollama").tag("Ollama")
}
.pickerStyle(.segmented)
.frame(width: 260)
.padding()
if backend == "Ollama" {
if backend.wrappedValue == "Ollama" {
ollamaLibrary
} else {
mlxLibrary
}
}
.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 var mlxLibrary: some View {
@@ -216,30 +532,52 @@ struct ModelCatalogView: View {
HStack {
Button("Register Model Folder…") { scanRequested = false; pickingLibrary = true }
Button("Scan Folder for Models…") { scanRequested = true; pickingLibrary = true }
Button("MLX Tools…") { workshop = ModelWorkshop(base: nil) }
if scanningLibrary { ProgressView().controlSize(.small) }
}
.disabled(studio.running || scanningLibrary)
if library.isEmpty && readyModels.isEmpty {
if library.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) { "mlx:" + $0.id }) { model in modelRow(model) }
let paths = library.filter { path in !readyModels.contains { $0.localFolder.path == path } }
let selectedPath = selection.mlxOnly && !selection.mlxPath.isEmpty ? [selection.mlxPath] : []
let paths = Array(Set(library + selectedPath)).sorted().filter { path in
!readyModels.contains { $0.localFolder.standardizedFileURL.path == URL(fileURLWithPath: path).standardizedFileURL.path }
}
ForEach(favoriteFirst(paths) { "folder:" + $0 }, id: \.self) { path in
HStack {
Text(URL(fileURLWithPath: path).lastPathComponent).help(path)
let title = URL(fileURLWithPath: path).lastPathComponent
VStack(alignment: .leading, spacing: 4) {
Text(title).help(path)
popularityBadge(title)
}
favoriteButton("folder:" + path)
Spacer()
Button(mlxPath == path && mlxOnly ? "Active" : "Load Model") { load(path) }
.disabled(studio.running || loadingPath != nil || !MLXLibrary.isModel(at: URL(fileURLWithPath: path)) ||
(mlxPath == path && mlxOnly))
Button("Reveal") {
NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
Text(ModelLibrarySize.mlx(path))
.font(.caption).foregroundStyle(.secondary)
.help("Size of local model weights")
if selection.isMLX(path) { activeBadge("MLX") }
Button("Preview") {
preview = mlxPreview(model: nil, folder: URL(fileURLWithPath: path))
}
Button("Load Model") { load(path) }
.disabled(studio.running || loadingPath != nil || selection.isMLX(path) ||
!MLXLibrary.isModel(at: URL(fileURLWithPath: 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) {
Button("Unregister") {
registered = (try? JSONEncoder().encode(library.filter { $0 != path })) ?? Data()
}.disabled(studio.running)
}
Button("Unregister") {
registered = (try? JSONEncoder().encode(library.filter { $0 != path })) ?? Data()
}.disabled(studio.running)
}
.listRowBackground(selection.isMLX(path) ? Color.accentColor.opacity(0.12) : nil)
}
if !libraryStatus.isEmpty { Text(libraryStatus).foregroundStyle(.secondary) }
}
@@ -307,19 +645,31 @@ struct ModelCatalogView: View {
if studio.models.isEmpty { Text("No models installed on this server.").foregroundStyle(.secondary) }
ForEach(favoriteFirst(studio.models) { "ollama:" + $0.name }) { model in
HStack {
Label(model.name, systemImage: "cube")
VStack(alignment: .leading, spacing: 4) {
Label(model.name, systemImage: "cube")
popularityBadge(model.name)
}
favoriteButton("ollama:" + model.name)
Spacer()
if let size = model.size {
Text(ByteCountFormatter.string(fromByteCount: size, countStyle: .file))
.font(.caption).foregroundStyle(.secondary)
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)
}
let active = ollamaModel == model.name && !mlxOnly && !compatibleEnabled
Button(active ? "Active" : "Use Model") {
.fixedSize()
Button("Use Model") {
studio.selectOllamaModel(model.name)
}
.disabled(active || studio.running)
.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) }
@@ -339,14 +689,26 @@ struct ModelCatalogView: View {
ForEach(favoriteFirst(ollamaCatalog) { "ollama:" + $0 + ":latest" }, id: \.self) { name in
VStack(alignment: .leading, spacing: 6) {
HStack {
Text(name).font(.headline)
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 studio.modelListEndpoint == ollamaEndpoint,
studio.models.contains(where: { $0.name == name || $0.name == name + ":latest" }) {
if installed != nil {
Text("Installed").foregroundStyle(.secondary)
} else if let task = downloads["ollama:" + name] {
Button("Cancel Download") { task.cancel() }
@@ -356,14 +718,29 @@ struct ModelCatalogView: View {
}
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 {
studio.refresh(endpoint: ollamaEndpoint)
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:") } }
@@ -425,28 +802,29 @@ struct ModelCatalogView: View {
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 = mlxPath == saved.localFolder.path && mlxOnly
let diskBytes = installed ? try? MLXRuntimeLimits.weightBytes(in: saved.localFolder) : nil
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 {
if let diskBytes {
Text(ByteCountFormatter.string(fromByteCount: Int64(clamping: diskBytes), countStyle: .file) + " weights")
} else if !model.size.isEmpty {
Text(model.size)
}
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")
if let count = model.downloads { Label(count.formatted(), systemImage: "arrow.down") }
if let count = model.likes { Label(count.formatted(), systemImage: "heart") }
if isActive { Label("Active", systemImage: "checkmark.circle.fill") }
if isActive { activeBadge("MLX") }
}.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 {
Button("Load Model") { load(saved.localFolder.path) }
.disabled(studio.running || loadingPath != nil || isActive)
Button("Clone & Train…") { workshop = ModelWorkshop(base: saved.localFolder) }
.disabled(studio.running || loadingPath != nil)
Button("Reveal") { NSWorkspace.shared.activateFileViewerSelecting([saved.localFolder]) }
} else {
@@ -464,6 +842,22 @@ struct ModelCatalogView: View {
downloadProgress("mlx:" + model.id)
}
.padding(.vertical, 4)
.listRowBackground(isActive ? Color.accentColor.opacity(0.12) : nil)
.task(id: installed) {
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() {