Run model downloads and split conversations independently

This commit is contained in:
Mark Gregory
2026-11-17 11:48:11 +00:00
parent 0b8a07b10f
commit 1f373d0ece
6 changed files with 267 additions and 55 deletions
+46 -7
View File
@@ -74,6 +74,7 @@ struct ChatView: View {
@State private var showingPerformance = false
@State private var showingComparison = false
@State private var comparisonChat: UUID?
@StateObject private var splitStudio = StudioModel()
@State private var showingWorkspace = false
@State private var showingToolbox = false
@AppStorage("chatDebugOutput") private var showDebugOutput = false
@@ -126,24 +127,24 @@ struct ChatView: View {
}
}
.searchable(text: $search, placement: .sidebar, prompt: "Search Chats")
.disabled(studio.running)
.disabled(studio.running || splitStudio.running)
.navigationSplitViewColumnWidth(min: 180, ideal: 235)
.toolbar {
Button("New Chat", systemImage: "square.and.pencil") {
search = ""
studio.newChat()
}
.disabled(studio.running)
.disabled(studio.running || splitStudio.running)
Button("Rename Chat", systemImage: "pencil") {
newTitle = studio.conversations.first(where: { $0.id == studio.selected })?.title ?? ""
renaming = true
}
.disabled(studio.running || studio.selected == nil)
.disabled(studio.running || splitStudio.running || studio.selected == nil)
Button("Delete Chat", systemImage: "trash") {
chatToDelete = studio.conversations.first { $0.id == studio.selected }
confirmDelete = chatToDelete != nil
}
.disabled(studio.running || studio.selected == nil)
.disabled(studio.running || splitStudio.running || studio.selected == nil)
}
} detail: {
VStack(spacing: 0) {
@@ -167,9 +168,13 @@ struct ChatView: View {
Button("Workspace", systemImage: "square.stack.3d.up") { showingWorkspace = true }
Button("Compare Chats", systemImage: "rectangle.split.2x1") {
showingComparison.toggle()
if showingComparison { comparisonChat = studio.conversations.first { $0.id != studio.selected }?.id }
if showingComparison {
splitStudio.open()
comparisonChat = studio.conversations.first { $0.id != studio.selected }?.id
splitStudio.selected = comparisonChat
}
}
.disabled(studio.conversations.count < 2 && !showingComparison)
.disabled(splitStudio.running || (studio.conversations.count < 2 && !showingComparison))
Button("Performance", systemImage: "chart.xyaxis.line") { showingPerformance = true }
}
}
@@ -270,15 +275,40 @@ struct ChatView: View {
}
}
.padding(10)
.disabled(splitStudio.running)
.onChange(of: comparisonChat) { _, value in
splitStudio.selected = value
splitStudio.prompt = ""
}
Divider()
if let comparisonChat, comparisonChat != studio.selected,
studio.conversations.contains(where: { $0.id == comparisonChat }) {
ScrollView {
LazyVStack(alignment: .leading, spacing: 12) {
ForEach(studio.conversationMessages(comparisonChat)) { MessageView(message: $0) }
ForEach(splitStudio.messages) { MessageView(message: $0) }
if let partial = splitStudio.partial { MessageView(message: partial, streaming: true) }
}.padding(12)
}
.font(chatFont.font(size: chatSize))
Divider()
VStack(alignment: .leading, spacing: 6) {
let feedback = [splitStudio.knowledgeStatus, splitStudio.webStatus, splitStudio.status]
.filter { !$0.isEmpty }.joined(separator: " · ")
if !feedback.isEmpty { Text(feedback).font(.caption).foregroundStyle(.secondary) }
ChatComposerInput(text: $splitStudio.prompt, canSend: !splitStudio.running, spellCheck: spellCheck,
autoCorrect: autoCorrect, font: chatFont.appKit(size: chatSize), send: sendSplitMessage)
.frame(height: 54)
HStack {
Spacer()
if splitStudio.running {
Button("Stop", systemImage: "stop.fill") { splitStudio.stop() }
} else {
Button("Send", systemImage: "arrow.up", action: sendSplitMessage)
.disabled(splitStudio.prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
}
}
}
.padding(10)
} else {
ContentUnavailableView("Choose a conversation", systemImage: "rectangle.split.2x1")
}
@@ -442,6 +472,15 @@ struct ChatView: View {
}
}
private func sendSplitMessage() {
guard splitStudio.selected != nil, splitStudio.selected != studio.selected else { return }
splitStudio.copyInferenceCredentials(from: studio)
splitStudio.send(endpoint: activeEndpoint, model: activeModel, mlxPath: mlxPath, thinking: thinking,
failover: failover, mlxOnly: mlxOnly, compatible: compatibleEnabled, recall: recall, useDocuments: false,
instructions: promptMode.instructions(custom: customPrompt),
settings: GenerationSettings.read(generationSettings))
}
private func sendMessage() {
let draft = studio.prompt
if draft.lowercased().hasPrefix("/write ") {
+70 -45
View File
@@ -127,8 +127,13 @@ 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 downloads: [String: Task<Void, Never>] = [:]
@State private var downloadStates: [String: DownloadState] = [:]
private struct DownloadState {
let message: String
let fraction: Double?
}
@AppStorage("mlxRegisteredPaths") private var registered = Data()
@State private var pickingLibrary = false
@State private var scanningLibrary = false
@@ -143,10 +148,8 @@ struct ModelCatalogView: View {
@State private var matches: [CatalogModel] = []
@State private var searching = false
@State private var searchStatus = ""
@State private var progress: Double?
@State private var loadingPath: String?
@AppStorage("favoriteModelKeys") private var favoriteData = Data()
@State private var pullingModel: String?
@State private var backend = "MLX"
@AppStorage("endpoint") private var ollamaEndpoint = "http://127.0.0.1:11434"
@@ -244,7 +247,7 @@ struct ModelCatalogView: View {
HStack {
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 || active != nil)
Button(query.isEmpty ? "Browse" : "Search", action: search).disabled(searching || hasMLXDownloads)
if searching { ProgressView().controlSize(.small) }
}
if !searchStatus.isEmpty { Text(searchStatus).foregroundStyle(.secondary) }
@@ -256,7 +259,7 @@ struct ModelCatalogView: View {
Section("Recommended Models") {
ForEach(favoriteFirst(CatalogModel.all.filter { !$0.installed(at: $0.localFolder) }) { "mlx:" + $0.id }) { model in modelRow(model) }
}
if !status.isEmpty && active == nil {
if !status.isEmpty && !hasMLXDownloads {
Section {
Text(status).textSelection(.enabled).foregroundStyle(.secondary)
if loadingPath != nil { ProgressView().controlSize(.small) }
@@ -329,7 +332,7 @@ struct ModelCatalogView: View {
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 || pullingModel != nil)
Button(ollamaQuery.isEmpty ? "Browse" : "Search", action: searchOllama).disabled(ollamaSearching || hasOllamaDownloads)
if ollamaSearching { ProgressView().controlSize(.small) }
}
if !ollamaCatalogStatus.isEmpty { Text(ollamaCatalogStatus).foregroundStyle(.secondary) }
@@ -345,40 +348,68 @@ struct ModelCatalogView: View {
if studio.modelListEndpoint == ollamaEndpoint,
studio.models.contains(where: { $0.name == name || $0.name == name + ":latest" }) {
Text("Installed").foregroundStyle(.secondary)
} else if let task = downloads["ollama:" + name] {
Button("Cancel Download") { task.cancel() }
} else {
Button("Pull Latest") {
pullingModel = name
studio.pull(name, endpoint: ollamaEndpoint)
}
.disabled(studio.managing)
Button("Pull Latest") { pull(name) }
}
}
if studio.managing && pullingModel == name {
ProgressView(value: ollamaPullFraction).progressViewStyle(.linear)
.accessibilityLabel("Download progress")
Text(studio.modelStatus).font(.caption).foregroundStyle(.secondary)
}
downloadProgress("ollama:" + name)
}
}
}
}
.formStyle(.grouped)
.onChange(of: studio.managing) { _, busy in if !busy { pullingModel = nil } }
.onAppear {
studio.refresh(endpoint: ollamaEndpoint)
if ollamaCatalog.isEmpty && ollamaCatalogStatus.isEmpty { searchOllama() }
}
}
private var ollamaPullFraction: Double? {
guard studio.modelStatus.hasSuffix("%"),
let value = studio.modelStatus.split(separator: " ").last,
let percent = Double(value.dropLast()) else { return nil }
return percent / 100
private var hasMLXDownloads: Bool { downloads.keys.contains { $0.hasPrefix("mlx:") } }
private var hasOllamaDownloads: Bool { downloads.keys.contains { $0.hasPrefix("ollama:") } }
@ViewBuilder private func downloadProgress(_ key: String) -> some View {
if let state = downloadStates[key] {
if downloads[key] != nil {
ProgressView(value: state.fraction).progressViewStyle(.linear)
.accessibilityLabel("Download progress")
}
Text(state.message).font(.caption).foregroundStyle(.secondary)
}
}
private func pull(_ name: String) {
let key = "ollama:" + name
guard downloads[key] == nil else { return }
let endpoint = ollamaEndpoint
downloadStates[key] = DownloadState(message: "Preparing download…", fraction: nil)
downloads[key] = Task {
defer {
downloads[key] = nil
if !hasOllamaDownloads && endpoint == ollamaEndpoint {
Task {
while studio.managing { try await Task.sleep(for: .milliseconds(100)) }
if endpoint == ollamaEndpoint { studio.refresh(endpoint: endpoint) }
}
}
}
do {
let client = try studio.ollamaClient(endpoint: endpoint)
for try await message in client.pull(name) {
let percent = message.hasSuffix("%") ? message.split(separator: " ").last.flatMap { Double($0.dropLast()) } : nil
downloadStates[key] = DownloadState(message: message, fraction: percent.map { $0 / 100 })
}
try Task.checkCancellation()
downloadStates[key] = DownloadState(message: "Downloaded.", fraction: nil)
} catch {
downloadStates[key] = DownloadState(message: Task.isCancelled ? "Download cancelled." : error.localizedDescription, fraction: nil)
}
}
}
private func searchOllama() {
guard !ollamaSearching, pullingModel == nil else { return }
guard !ollamaSearching, !hasOllamaDownloads else { return }
let term = ollamaQuery.trimmingCharacters(in: .whitespacesAndNewlines)
ollamaSearching = true
ollamaCatalogStatus = ""
@@ -419,30 +450,25 @@ struct ModelCatalogView: View {
.disabled(studio.running || loadingPath != nil)
Button("Reveal") { NSWorkspace.shared.activateFileViewerSelecting([saved.localFolder]) }
} else {
if active?.id == model.id {
Button("Cancel Download") { operation?.cancel() }
if let task = downloads["mlx:" + model.id] {
Button("Cancel Download") { task.cancel() }
} else {
Button("Download") { download(model) }.disabled(active != nil)
Button("Download") { download(model) }
}
}
if FileManager.default.fileExists(atPath: saved.localFolder.path) {
Button("Remove…", role: .destructive) { removing = saved }
.disabled(studio.running || active != nil || loadingPath != nil)
.disabled(studio.running || downloads["mlx:" + model.id] != nil || loadingPath != nil)
}
}
if active?.id == model.id, let progress {
ProgressView(value: progress)
.progressViewStyle(.linear)
.accessibilityLabel("Download progress")
Text(status).font(.caption).foregroundStyle(.secondary)
}
downloadProgress("mlx:" + model.id)
}
.padding(.vertical, 4)
}
private func search() {
let term = query.trimmingCharacters(in: .whitespacesAndNewlines)
guard !searching, active == nil else { return }
guard !searching, !hasMLXDownloads else { return }
searching = true
searchStatus = ""
Task {
@@ -470,28 +496,27 @@ struct ModelCatalogView: View {
}
private func download(_ model: CatalogModel) {
guard active == nil else { return }
active = model
progress = 0
status = "Preparing download…"
operation = Task {
defer { active = nil; operation = nil; progress = nil }
let key = "mlx:" + model.id
guard downloads[key] == nil else { return }
downloadStates[key] = DownloadState(message: "Preparing download…", fraction: 0)
downloads[key] = Task {
defer { downloads[key] = nil }
do {
try await model.install(to: model.localFolder) { message, fraction in
await MainActor.run { status = message; progress = fraction }
await MainActor.run { downloadStates[key] = DownloadState(message: message, fraction: fraction) }
}
if !CatalogModel.all.contains(where: { $0.id == model.id }) {
managed = try JSONEncoder().encode(installedModels.filter { $0.id != model.id && !CatalogModel.all.contains($0) } + [model])
}
status = "Downloaded \(model.title)."
downloadStates[key] = DownloadState(message: "Downloaded.", fraction: nil)
} catch {
status = Task.isCancelled ? "Download cancelled." : error.localizedDescription
downloadStates[key] = DownloadState(message: Task.isCancelled ? "Download cancelled." : error.localizedDescription, fraction: nil)
}
}
}
private func remove(_ model: CatalogModel) {
guard !studio.running, active == nil else { return }
guard !studio.running, downloads["mlx:" + model.id] == nil else { return }
do {
try FileManager.default.removeItem(at: model.localFolder)
if mlxPath == model.localFolder.path {
+6 -1
View File
@@ -348,6 +348,11 @@ final class StudioModel: ObservableObject {
func removeToolAttachment() { toolAttachment = nil }
func copyInferenceCredentials(from source: StudioModel) {
setOllamaToken(source.ollamaToken, endpoint: source.tokenEndpoint)
setCompatibleToken(source.compatibleToken, endpoint: source.compatibleTokenEndpoint)
}
func setOllamaToken(_ token: String, endpoint: String) {
tokenEndpoint = endpoint
ollamaToken = token
@@ -362,7 +367,7 @@ final class StudioModel: ObservableObject {
try CompatibleEndpoint(endpoint: endpoint, token: endpoint == compatibleTokenEndpoint ? compatibleToken : "")
}
private func ollamaClient(endpoint: String) throws -> Ollama {
func ollamaClient(endpoint: String) throws -> Ollama {
try Ollama(endpoint: endpoint, token: endpoint == tokenEndpoint ? ollamaToken : "")
}