From 1d5edbc292513040c1f71e11d0e3dee6799560a7 Mon Sep 17 00:00:00 2001 From: Mark Gregory Date: Tue, 17 Nov 2026 09:20:58 +0000 Subject: [PATCH] Browse MLX and Ollama catalogs in a unified model library --- README.md | 4 +- Sources/AIStudioApp.swift | 4 +- Sources/MCP.swift | 50 ++++++------- Sources/ModelDownload.swift | 142 +++++++++++++++++++++++++++++++++++- Sources/StudioModel.swift | 4 +- Tests/StudioTests.swift | 12 +++ 6 files changed, 181 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 58b7841..a72fab8 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Native SwiftUI chat for Apple silicon Macs running macOS 14 or later. Open `AISt - **Ollama:** In **Settings → Models**, refresh the installed list and select a tag. The default server is `http://127.0.0.1:11434`. Use the same pane to pull, inspect, and delete models. Enter a remote HTTP or HTTPS base URL to use another server. The optional bearer token stays in memory and requires HTTPS for remote servers. - **OpenAI-compatible:** In **Settings → Models**, choose the compatible backend, enter the API base URL (for example `http://127.0.0.1:1234/v1` for LM Studio), then refresh models and select the exact model ID. Remote URLs require HTTPS. An optional bearer token stays in memory and is cleared when the endpoint changes. The server manages model loading. Chat Completions streams the reply and any separately reported reasoning. -- **MLX:** In **Settings → MLX Library**, search Hugging Face for public MLX Community checkpoints or browse the recommended models. Download a checkpoint and choose **Load Model** to load it for on-device inference. **Settings → Models** also accepts a local model folder with configuration, tokenizer files, and safetensors weights. **Prefer Ollama** can fall back to the configured MLX folder when Ollama fails before emitting output. +- **MLX:** In **Settings → Model Library**, browse or search Hugging Face for public MLX Community text-generation checkpoints. Switch to **Ollama** for models installed on your server and the public Ollama catalog. Download a checkpoint and choose **Load Model** to load it for on-device inference. **Settings → Models** also accepts a local model folder with configuration, tokenizer files, and safetensors weights. **Prefer Ollama** can fall back to the configured MLX folder when Ollama fails before emitting output. - **Thinking:** The composer sends Boolean or named effort settings to Ollama. Supported MLX templates expose Default, Off, and On. Reported reasoning appears in an expandable section. If an Ollama request is interrupted after emitting text, reasoning, or a tool call, the router keeps that backend. **Stop** cancels generation and retains any partial output. ## 2. Chat with documents @@ -82,7 +82,7 @@ Return sends and Shift–Return inserts a newline. **Settings → Appearance** controls workspace mode, theme, accent, typography, spell checking and automatic correction. **Settings → Workspace Data** exports the SQLite workspace and restores an AI Studio backup after confirmation. Backup -reminders appear in that panel. **Settings → MLX Library** downloads catalog +reminders appear in that panel. **Settings → Model Library** downloads catalog models, registers existing local MLX folders, and scans a selected library folder for compatible checkpoints. Settings → Models lists Ollama models as rows with direct selection controls. diff --git a/Sources/AIStudioApp.swift b/Sources/AIStudioApp.swift index 0749f03..3277a1f 100644 --- a/Sources/AIStudioApp.swift +++ b/Sources/AIStudioApp.swift @@ -1614,7 +1614,7 @@ struct StudioSettingsView: View { @ObservedObject var studio: StudioModel @State private var page: String? = "Models" private let pages = [ - ("Models", "cpu"), ("MLX Library", "square.stack"), ("Generation", "slider.horizontal.3"), + ("Models", "cpu"), ("Model Library", "square.stack"), ("Generation", "slider.horizontal.3"), ("Toolbox", "wrench.and.screwdriver"), ("Local Tools", "terminal"), ("Runtime", "waveform.path"), ("Appearance", "paintpalette"), ("Workspace Data", "externaldrive") ] @@ -1628,7 +1628,7 @@ struct StudioSettingsView: View { .frame(minWidth: 160, idealWidth: 180, maxWidth: 210) Group { switch page { - case "MLX Library": ModelCatalogView(studio: studio) + case "Model Library": ModelCatalogView(studio: studio) case "Generation": GenerationSettingsView() case "Toolbox": MCPSettings(studio: studio) case "Local Tools": LocalToolsView(studio: studio) diff --git a/Sources/MCP.swift b/Sources/MCP.swift index 8df5381..970b60b 100644 --- a/Sources/MCP.swift +++ b/Sources/MCP.swift @@ -250,7 +250,7 @@ struct MCPSettings: View { } } Section("Custom MCP Servers") { - VStack(alignment: .leading, spacing: 6) { + Menu("Manage Servers", systemImage: "ellipsis.circle") { Button("Import mcp.json…") { importingConfig = true } Button("Use LM Studio Config") { loadConfig(FileManager.default.homeDirectoryForCurrentUser.appending(path: ".lmstudio/mcp.json")) @@ -261,27 +261,25 @@ struct MCPSettings: View { } }.buttonStyle(.bordered) ForEach(profiles.keys.sorted(), id: \.self) { name in - if let profile = profiles[name] { - let id = MCPConnectionID.profile(name) - let state = studio.mcpConnections[id] - VStack(alignment: .leading, spacing: 5) { - Toggle(name, isOn: Binding( - get: { studio.enabledMCPProfiles(path: configPath).contains(name) }, - set: { enabled in - if enabled { selected = id } - studio.setMCPProfile(name, enabled: enabled, path: configPath) - } - )) - if let state { - Text(state.progress ?? state.output) - .font(.caption) - .foregroundStyle(state.failed ? Color.red : Color.secondary) - .textSelection(.enabled) - if state.failed { - Button("Retry") { studio.restoreToolsets() } - } else if state.toolset != nil { - Button("Tools") { selected = id } - } + let id = MCPConnectionID.profile(name) + let state = studio.mcpConnections[id] + VStack(alignment: .leading, spacing: 5) { + Toggle(name, isOn: Binding( + get: { studio.enabledMCPProfiles(path: configPath).contains(name) }, + set: { enabled in + if enabled { selected = id } + studio.setMCPProfile(name, enabled: enabled, path: configPath) + } + )) + if let state { + Text(state.progress ?? state.output) + .font(.caption) + .foregroundStyle(state.failed ? Color.red : Color.secondary) + .textSelection(.enabled) + if state.failed { + Button("Retry") { studio.restoreToolsets() } + } else if state.toolset != nil { + Button("Tools") { selected = id } } } } @@ -331,12 +329,14 @@ struct MCPSettings: View { .font(.system(.caption, design: .monospaced)).textSelection(.enabled) } } - TextEditor(text: $arguments).font(.system(.body, design: .monospaced)) - .frame(height: 85).accessibilityLabel("JSON arguments") + DisclosureGroup("Arguments") { + TextEditor(text: $arguments).font(.system(.body, design: .monospaced)) + .frame(height: 85).accessibilityLabel("JSON arguments") + } Button("Review Tool Call…") { confirm = true } .disabled(tool.isEmpty || state.progress != nil) } - if !state.output.isEmpty { + if !state.output.isEmpty && (state.completedTool != nil || state.failed) { ScrollView { Text(state.output).font(.system(.caption, design: .monospaced)).textSelection(.enabled) .frame(maxWidth: .infinity, alignment: .leading) diff --git a/Sources/ModelDownload.swift b/Sources/ModelDownload.swift index f09c8e5..bd9f502 100644 --- a/Sources/ModelDownload.swift +++ b/Sources/ModelDownload.swift @@ -33,8 +33,11 @@ struct CatalogModel: Identifiable, Hashable, Sendable, Codable { url.path = "/api/models" url.queryItems = [ .init(name: "author", value: "mlx-community"), + .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.") } @@ -142,6 +145,15 @@ struct ModelCatalogView: View { @State private var searchStatus = "" @State private var progress: Double? @State private var loadingPath: String? + @State private var backend = "MLX" + @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 = "" + private var installedModels: [CatalogModel] { (try? JSONDecoder().decode([CatalogModel].self, from: managed)) ?? [] @@ -149,8 +161,25 @@ struct ModelCatalogView: View { var body: some View { + VStack(spacing: 0) { + Picker("Model runtime", selection: $backend) { + Text("MLX").tag("MLX") + Text("Ollama").tag("Ollama") + } + .pickerStyle(.segmented) + .frame(width: 260) + .padding() + if backend == "Ollama" { + ollamaLibrary + } else { + mlxLibrary + } + } + } + + private var mlxLibrary: some View { Form { - Section("Model Library") { + Section("Local MLX Models") { HStack { Button("Register Model Folder…") { scanRequested = false; pickingLibrary = true } Button("Scan Folder for Models…") { scanRequested = true; pickingLibrary = true } @@ -185,8 +214,9 @@ struct ModelCatalogView: View { } Section("Hugging Face") { HStack { - TextField("Search MLX models", text: $query).onSubmit(search) - Button("Search", action: search).disabled(searching || query.trimmingCharacters(in: .whitespaces).isEmpty) + TextField("Search MLX models", text: $query, prompt: Text("e.g. Qwen, Gemma")) + .labelsHidden().textFieldStyle(.roundedBorder).onSubmit(search) + Button(query.isEmpty ? "Browse" : "Search", action: search).disabled(searching) if searching { ProgressView().controlSize(.small) } } if !searchStatus.isEmpty { Text(searchStatus).foregroundStyle(.secondary) } @@ -207,6 +237,7 @@ struct ModelCatalogView: View { } } .formStyle(.grouped) + .onAppear { if matches.isEmpty && searchStatus.isEmpty { search() } } .fileImporter(isPresented: $pickingLibrary, allowedContentTypes: [.folder]) { result in do { let url = try result.get() @@ -236,6 +267,85 @@ struct ModelCatalogView: View { } message: { model in Text(model.title) } } + private var ollamaLibrary: some View { + Form { + Section("Installed on Ollama") { + 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(studio.models) { model in + HStack { + Label(model.name, systemImage: "cube") + Spacer() + if let size = model.size { + Text(ByteCountFormatter.string(fromByteCount: size, countStyle: .file)) + .font(.caption).foregroundStyle(.secondary) + } + let active = ollamaModel == model.name && !mlxOnly && !compatibleEnabled + Button(active ? "Active" : "Use Model") { + ollamaModel = model.name + compatibleEnabled = false + mlxOnly = false + } + .disabled(active || studio.running) + } + } + } + if !studio.modelStatus.isEmpty { Text(studio.modelStatus).foregroundStyle(.secondary) } + if studio.managing { + ProgressView().controlSize(.small) + Button("Cancel") { studio.cancelManagement() } + } + } + Section("Ollama Catalog") { + 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) + if ollamaSearching { ProgressView().controlSize(.small) } + } + if !ollamaCatalogStatus.isEmpty { Text(ollamaCatalogStatus).foregroundStyle(.secondary) } + ForEach(ollamaCatalog, id: \.self) { name in + HStack { + Text(name).font(.headline) + Spacer() + 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" }) { + Text("Installed").foregroundStyle(.secondary) + } else { + Button("Pull Latest") { studio.pull(name, endpoint: ollamaEndpoint) } + .disabled(studio.managing) + } + } + } + } + } + .formStyle(.grouped) + .onAppear { + studio.refresh(endpoint: ollamaEndpoint) + if ollamaCatalog.isEmpty && ollamaCatalogStatus.isEmpty { searchOllama() } + } + } + + private func searchOllama() { + guard !ollamaSearching 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) @@ -274,7 +384,7 @@ struct ModelCatalogView: View { private func search() { let term = query.trimmingCharacters(in: .whitespacesAndNewlines) - guard !term.isEmpty, !searching else { return } + guard !searching else { return } searching = true searchStatus = "" Task { @@ -368,3 +478,27 @@ enum MLXLibrary { ((try? MLXRuntimeLimits.weightBytes(in: url)) ?? 0) > 0 } } + +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() + 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 + } + } +} diff --git a/Sources/StudioModel.swift b/Sources/StudioModel.swift index 42cca69..08bc19a 100644 --- a/Sources/StudioModel.swift +++ b/Sources/StudioModel.swift @@ -428,9 +428,9 @@ final class StudioModel: ObservableObject { func refresh(endpoint: String) { guard !managing else { return } manage(endpoint: endpoint) { ollama in - if self.modelListEndpoint != endpoint { self.models = [] } - self.modelListEndpoint = endpoint + self.modelListEndpoint = "" self.models = try await ollama.models().sorted { $0.name < $1.name } + self.modelListEndpoint = endpoint return "\(self.models.count) installed" } } diff --git a/Tests/StudioTests.swift b/Tests/StudioTests.swift index d3eadb6..4d2d925 100644 --- a/Tests/StudioTests.swift +++ b/Tests/StudioTests.swift @@ -220,6 +220,18 @@ final class ExpandedStudioTests: XCTestCase { XCTAssertNoThrow(try HTTPMCPClient.arguments(Data(#"{"q":"example"}"#.utf8))) } + func testLiveModelCatalogsBrowseAndSearch() async throws { + guard ProcessInfo.processInfo.environment["AISTUDIO_TEST_LIVE_CATALOGS"] == "1" else { + throw XCTSkip("Enable live catalog checks explicitly.") + } + let mlx = try await CatalogModel.search("") + let ollama = try await OllamaCatalog.search("") + let qwen = try await OllamaCatalog.search("qwen") + XCTAssertFalse(mlx.isEmpty) + XCTAssertFalse(ollama.isEmpty) + XCTAssertTrue(qwen.contains { $0.hasPrefix("qwen") }) + } + func testHuggingFaceCatalogRejectsNonModelFilesAndAdapters() throws { let data = Data(""" [{"id":"mlx-community/Test-4bit","sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",