Build AI Studio 1.1 for macOS #1

Open
admin wants to merge 38 commits from admin/ai-studio-v1.1 AGit into main
6 changed files with 181 additions and 35 deletions
Showing only changes of commit 1d5edbc292 - Show all commits
+2 -2
View File
@@ -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. - **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. - **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. - **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 ## 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 controls workspace mode, theme, accent, typography, spell checking and
automatic correction. **Settings → Workspace Data** exports the SQLite automatic correction. **Settings → Workspace Data** exports the SQLite
workspace and restores an AI Studio backup after confirmation. Backup 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 models, registers existing local MLX folders, and scans a selected library
folder for compatible checkpoints. Settings → Models lists Ollama models folder for compatible checkpoints. Settings → Models lists Ollama models
as rows with direct selection controls. as rows with direct selection controls.
+2 -2
View File
@@ -1614,7 +1614,7 @@ struct StudioSettingsView: View {
@ObservedObject var studio: StudioModel @ObservedObject var studio: StudioModel
@State private var page: String? = "Models" @State private var page: String? = "Models"
private let pages = [ 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"), ("Toolbox", "wrench.and.screwdriver"), ("Local Tools", "terminal"), ("Runtime", "waveform.path"),
("Appearance", "paintpalette"), ("Workspace Data", "externaldrive") ("Appearance", "paintpalette"), ("Workspace Data", "externaldrive")
] ]
@@ -1628,7 +1628,7 @@ struct StudioSettingsView: View {
.frame(minWidth: 160, idealWidth: 180, maxWidth: 210) .frame(minWidth: 160, idealWidth: 180, maxWidth: 210)
Group { Group {
switch page { switch page {
case "MLX Library": ModelCatalogView(studio: studio) case "Model Library": ModelCatalogView(studio: studio)
case "Generation": GenerationSettingsView() case "Generation": GenerationSettingsView()
case "Toolbox": MCPSettings(studio: studio) case "Toolbox": MCPSettings(studio: studio)
case "Local Tools": LocalToolsView(studio: studio) case "Local Tools": LocalToolsView(studio: studio)
+4 -4
View File
@@ -250,7 +250,7 @@ struct MCPSettings: View {
} }
} }
Section("Custom MCP Servers") { Section("Custom MCP Servers") {
VStack(alignment: .leading, spacing: 6) { Menu("Manage Servers", systemImage: "ellipsis.circle") {
Button("Import mcp.json…") { importingConfig = true } Button("Import mcp.json…") { importingConfig = true }
Button("Use LM Studio Config") { Button("Use LM Studio Config") {
loadConfig(FileManager.default.homeDirectoryForCurrentUser.appending(path: ".lmstudio/mcp.json")) loadConfig(FileManager.default.homeDirectoryForCurrentUser.appending(path: ".lmstudio/mcp.json"))
@@ -261,7 +261,6 @@ struct MCPSettings: View {
} }
}.buttonStyle(.bordered) }.buttonStyle(.bordered)
ForEach(profiles.keys.sorted(), id: \.self) { name in ForEach(profiles.keys.sorted(), id: \.self) { name in
if let profile = profiles[name] {
let id = MCPConnectionID.profile(name) let id = MCPConnectionID.profile(name)
let state = studio.mcpConnections[id] let state = studio.mcpConnections[id]
VStack(alignment: .leading, spacing: 5) { VStack(alignment: .leading, spacing: 5) {
@@ -285,7 +284,6 @@ struct MCPSettings: View {
} }
} }
} }
}
if !configStatus.isEmpty { Text(configStatus).foregroundStyle(.secondary).textSelection(.enabled) } if !configStatus.isEmpty { Text(configStatus).foregroundStyle(.secondary).textSelection(.enabled) }
} }
Section("Manual Connection") { Section("Manual Connection") {
@@ -331,12 +329,14 @@ struct MCPSettings: View {
.font(.system(.caption, design: .monospaced)).textSelection(.enabled) .font(.system(.caption, design: .monospaced)).textSelection(.enabled)
} }
} }
DisclosureGroup("Arguments") {
TextEditor(text: $arguments).font(.system(.body, design: .monospaced)) TextEditor(text: $arguments).font(.system(.body, design: .monospaced))
.frame(height: 85).accessibilityLabel("JSON arguments") .frame(height: 85).accessibilityLabel("JSON arguments")
}
Button("Review Tool Call…") { confirm = true } Button("Review Tool Call…") { confirm = true }
.disabled(tool.isEmpty || state.progress != nil) .disabled(tool.isEmpty || state.progress != nil)
} }
if !state.output.isEmpty { if !state.output.isEmpty && (state.completedTool != nil || state.failed) {
ScrollView { ScrollView {
Text(state.output).font(.system(.caption, design: .monospaced)).textSelection(.enabled) Text(state.output).font(.system(.caption, design: .monospaced)).textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
+138 -4
View File
@@ -33,8 +33,11 @@ struct CatalogModel: Identifiable, Hashable, Sendable, Codable {
url.path = "/api/models" url.path = "/api/models"
url.queryItems = [ url.queryItems = [
.init(name: "author", value: "mlx-community"), .init(name: "author", value: "mlx-community"),
.init(name: "pipeline_tag", value: "text-generation"),
.init(name: "search", value: query), .init(name: "search", value: query),
.init(name: "limit", value: "25"), .init(name: "limit", value: "25"),
.init(name: "sort", value: "downloads"),
.init(name: "direction", value: "-1"),
.init(name: "full", value: "true") .init(name: "full", value: "true")
] ]
guard let endpoint = url.url else { throw StudioError("Could not prepare the model search.") } 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 searchStatus = ""
@State private var progress: Double? @State private var progress: Double?
@State private var loadingPath: String? @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] { private var installedModels: [CatalogModel] {
(try? JSONDecoder().decode([CatalogModel].self, from: managed)) ?? [] (try? JSONDecoder().decode([CatalogModel].self, from: managed)) ?? []
@@ -149,8 +161,25 @@ struct ModelCatalogView: View {
var body: some 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 { Form {
Section("Model Library") { Section("Local MLX Models") {
HStack { HStack {
Button("Register Model Folder…") { scanRequested = false; pickingLibrary = true } Button("Register Model Folder…") { scanRequested = false; pickingLibrary = true }
Button("Scan Folder for Models…") { scanRequested = true; pickingLibrary = true } Button("Scan Folder for Models…") { scanRequested = true; pickingLibrary = true }
@@ -185,8 +214,9 @@ struct ModelCatalogView: View {
} }
Section("Hugging Face") { Section("Hugging Face") {
HStack { HStack {
TextField("Search MLX models", text: $query).onSubmit(search) TextField("Search MLX models", text: $query, prompt: Text("e.g. Qwen, Gemma"))
Button("Search", action: search).disabled(searching || query.trimmingCharacters(in: .whitespaces).isEmpty) .labelsHidden().textFieldStyle(.roundedBorder).onSubmit(search)
Button(query.isEmpty ? "Browse" : "Search", action: search).disabled(searching)
if searching { ProgressView().controlSize(.small) } if searching { ProgressView().controlSize(.small) }
} }
if !searchStatus.isEmpty { Text(searchStatus).foregroundStyle(.secondary) } if !searchStatus.isEmpty { Text(searchStatus).foregroundStyle(.secondary) }
@@ -207,6 +237,7 @@ struct ModelCatalogView: View {
} }
} }
.formStyle(.grouped) .formStyle(.grouped)
.onAppear { if matches.isEmpty && searchStatus.isEmpty { search() } }
.fileImporter(isPresented: $pickingLibrary, allowedContentTypes: [.folder]) { result in .fileImporter(isPresented: $pickingLibrary, allowedContentTypes: [.folder]) { result in
do { do {
let url = try result.get() let url = try result.get()
@@ -236,6 +267,85 @@ struct ModelCatalogView: View {
} message: { model in Text(model.title) } } 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 { private func modelRow(_ model: CatalogModel) -> some View {
let saved = installedModels.first { $0.id == model.id } ?? model let saved = installedModels.first { $0.id == model.id } ?? model
let installed = saved.installed(at: saved.localFolder) let installed = saved.installed(at: saved.localFolder)
@@ -274,7 +384,7 @@ struct ModelCatalogView: View {
private func search() { private func search() {
let term = query.trimmingCharacters(in: .whitespacesAndNewlines) let term = query.trimmingCharacters(in: .whitespacesAndNewlines)
guard !term.isEmpty, !searching else { return } guard !searching else { return }
searching = true searching = true
searchStatus = "" searchStatus = ""
Task { Task {
@@ -368,3 +478,27 @@ enum MLXLibrary {
((try? MLXRuntimeLimits.weightBytes(in: url)) ?? 0) > 0 ((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<String>()
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
}
}
}
+2 -2
View File
@@ -428,9 +428,9 @@ final class StudioModel: ObservableObject {
func refresh(endpoint: String) { func refresh(endpoint: String) {
guard !managing else { return } guard !managing else { return }
manage(endpoint: endpoint) { ollama in manage(endpoint: endpoint) { ollama in
if self.modelListEndpoint != endpoint { self.models = [] } self.modelListEndpoint = ""
self.modelListEndpoint = endpoint
self.models = try await ollama.models().sorted { $0.name < $1.name } self.models = try await ollama.models().sorted { $0.name < $1.name }
self.modelListEndpoint = endpoint
return "\(self.models.count) installed" return "\(self.models.count) installed"
} }
} }
+12
View File
@@ -220,6 +220,18 @@ final class ExpandedStudioTests: XCTestCase {
XCTAssertNoThrow(try HTTPMCPClient.arguments(Data(#"{"q":"example"}"#.utf8))) 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 { func testHuggingFaceCatalogRejectsNonModelFilesAndAdapters() throws {
let data = Data(""" let data = Data("""
[{"id":"mlx-community/Test-4bit","sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", [{"id":"mlx-community/Test-4bit","sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",