diff --git a/Docs/PHASES.md b/Docs/PHASES.md index 02daa17..3c47356 100644 --- a/Docs/PHASES.md +++ b/Docs/PHASES.md @@ -26,7 +26,7 @@ - [x] Verify the ZIP checksum, then extract it and verify the app signature and arm64-only executable. - [ ] Run a smoke test against a real remote Ollama endpoint with a preinstalled model. - [x] Run discovery, source inventory, and read-only search against the Pegasus MCP server over SSH stdio. -- [ ] Verify a real remote Streamable HTTP MCP endpoint when one is configured. +- [x] Verify discovery, inventory, and search against the live Pegasus Streamable HTTP endpoint at `https://kb.absdev.net/mcp`. Search and inventory passed before the indexed files were removed. A subsequent check needs a restored or rebuilt index. - [x] Sign with Developer ID Application and verify the extracted app has hardened runtime. - [ ] Notarize and staple with a configured notary profile. @@ -42,7 +42,7 @@ - [x] Import text chats from the installed Msty Studio database schema, scan a chosen folder for AI Studio backups, and relocate a workspace. Msty attachments and non-chat resources are outside the importer. - [x] Add editable appearance shortcuts, chat rendering options, and a side-by-side conversation comparison. -- [ ] Add independent composers and concurrent generation in split chats. +- [x] Add independent composers and concurrent generation across two conversations. Both panes use the current model configuration. - [x] Extend Prompt Library with notes, tags, and version history. Add rendered web clip capture in an isolated WebKit session. Interactive sign-in has not been verified. - [x] Document the ACP adapter, diff review, tool history, and compatible proxy configuration design. - [ ] Implement and validate ACP adapters, diff review, and tool history. Verify a selected separate local proxy. diff --git a/Docs/TRAINING.md b/Docs/TRAINING.md new file mode 100644 index 0000000..ce5d232 --- /dev/null +++ b/Docs/TRAINING.md @@ -0,0 +1,109 @@ +# Fine-tune a model for use in AI Studio + +AI Studio can download and run MLX checkpoints from Hugging Face and register +local MLX model folders. Training is currently an external MLX LM workflow. +The app does not yet provide a Clone or Train button. + +## 1. Choose the base model + +On an Apple Silicon Mac, choose a small, supported MLX text-generation model. +In **Settings → Model Library → MLX**, download it and choose **Reveal** to +find its folder. The downloaded files are a snapshot from a specific Hugging +Face repository revision. Record the repository, revision, model card license +and runtime format. A Hugging Face repository can contain MLX weights, PyTorch +weights or GGUF files. Pick a working MLX checkpoint for this workflow. + +A derived model does not need a second copy of the base weights during LoRA +training. Keep the base folder intact and create a separate project folder for +your dataset, adapter and experimental outputs. If you get the checkpoint +outside the app, use the Hugging Face Hub CLI or its snapshot downloader with +an explicit revision. For a gated repository, request access and authenticate +using the Hub CLI before downloading. AI Studio's built-in catalog currently +downloads public MLX Community checkpoints. + +## 2. Prepare your local dataset + +Create a dataset folder with `train.jsonl`, `valid.jsonl`, and `test.jsonl`. +Each line is one JSON object. For a chat model, use examples of the questions +and answers you want the model to learn. Use one example per line. + +```json +{"messages":[{"role":"user","content":"Review this change for missing validation."},{"role":"assistant","content":"Validate the input at the boundary and add a test for invalid data."}]} +``` + +Keep related examples together in a single split so near duplicates cannot +inflate your test results. Remove credentials and private data you do not +want reproduced. Start with a small, hand-reviewed dataset. To answer from +changing internal standards or documents, keep using the Pegasus knowledge +base. Use fine-tuning for response style, task behavior and conventions that +you can demonstrate with examples. + +Hugging Face can also host datasets. MLX LM supports a Hub dataset as an +input, alongside local JSONL. For an internal dataset, start with local files +and explicitly review access and retention before uploading anything. + +## 3. Train and evaluate an adapter + +In a dedicated project folder, create a Python environment and install MLX LM. +Record the installed version with the experiment so you can reproduce it. + +```sh +python3 -m venv .venv +source .venv/bin/activate +python -m pip install mlx-lm +python -m pip show mlx-lm +``` + +Set `BASE` to the model folder from Reveal. The relative paths below are +inside the training project folder. + +```sh +BASE="/absolute/path/to/downloaded-mlx-model" +mlx_lm.lora --model "$BASE" --train --data ./dataset \ + --adapter-path ./adapter --iters 100 --batch-size 1 +mlx_lm.lora --model "$BASE" --test --data ./dataset \ + --adapter-path ./adapter +mlx_lm.generate --model "$BASE" --adapter-path ./adapter \ + --prompt "Review this change for missing validation." +``` + +Compare base and adapter answers on the same held-out examples. Check +grounding, task accuracy, style, and regressions outside the target task. +Use a small first run to check memory and verify the checkpoint supports +LoRA. Adjust sequence length, batch size and iteration count based on the +measured run. Keep each adapter tied to the exact base weights it was trained +against. + +## 4. Load the trained derivative + +Fuse into a **new folder** and keep the original checkpoint available. + +```sh +mlx_lm.fuse --model "$BASE" --adapter-path ./adapter --save-path ./trained-model +``` + +In **Settings → Model Library → MLX**, use **Register Model Folder…**, select +`trained-model`, and use **Load Model**. Verify a short reply before using the +derivative for real work. An Ollama tag is a packaged inference artifact. +For an Ollama deployment, train from a supported base checkpoint first, then +check whether the target Ollama model architecture supports the adapter or +whether a separate compatible export is needed. + +Hugging Face publishing is optional. When sharing, check the original license +and organizational data rules. Document the base revision, dataset rights, +training configuration, evaluation and limitations in the model card. A Hub +repository can store the adapter or fused checkpoint separately from the base. +Keep it private unless you intend to publish it. + +## Proposed AI Studio integration + +A **Create Training Variant** action should create a new local record tied to +the pinned base revision. A dataset picker should validate JSONL and preview +the splits. A training screen should show settings, progress, loss, cancellation +and checkpoints. Once a run completes, present a side-by-side evaluation and +a **Register Trained Model** action. Start with the MLX LM worker in a dedicated +environment and record the runtime version and exact inputs. Set no automatic +upload destination. + +Sources: [MLX LM LoRA guide](https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/LORA.md) · +[Hugging Face Hub download guide](https://huggingface.co/docs/huggingface_hub/guides/download) diff --git a/Sources/AIStudioApp.swift b/Sources/AIStudioApp.swift index 4e0eb61..e1410e2 100644 --- a/Sources/AIStudioApp.swift +++ b/Sources/AIStudioApp.swift @@ -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 ") { diff --git a/Sources/ModelDownload.swift b/Sources/ModelDownload.swift index a8c9adc..65eeee0 100644 --- a/Sources/ModelDownload.swift +++ b/Sources/ModelDownload.swift @@ -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? - @State private var active: CatalogModel? + @State private var downloads: [String: Task] = [:] + @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 { diff --git a/Sources/StudioModel.swift b/Sources/StudioModel.swift index f32d1fe..b6309b4 100644 --- a/Sources/StudioModel.swift +++ b/Sources/StudioModel.swift @@ -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 : "") } diff --git a/Tests/StudioTests.swift b/Tests/StudioTests.swift index a6d4b08..3de82a5 100644 --- a/Tests/StudioTests.swift +++ b/Tests/StudioTests.swift @@ -1018,6 +1018,40 @@ final class ConnectedChatTests: XCTestCase { XCTAssertEqual(studio.knowledgeSources, ["knowledge.md"]) } + @MainActor + func testTwoChatSessionsGenerateConcurrentlyAndPersistSeparately() async throws { + guard let address = ProcessInfo.processInfo.environment["AISTUDIO_TEST_WEB_URL"], + let base = URL(string: address)?.deletingLastPathComponent() else { + throw XCTSkip("Run Scripts/test.sh to configure the fixture.") + } + let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) + defer { try? FileManager.default.removeItem(at: folder) } + let database = folder.appending(path: "studio.sqlite") + let left = StudioModel() + let right = StudioModel() + left.open(databaseURL: database) + right.open(databaseURL: database) + left.newChat() + right.newChat() + let first = try XCTUnwrap(left.selected) + let second = try XCTUnwrap(right.selected) + for studio in [left, right] { + studio.prompt = "Read \(base.appending(path: "article").absoluteString)" + studio.send(endpoint: base.appending(path: "chat-web").absoluteString, model: "fixture", mlxPath: "", + thinking: .off, failover: false, mlxOnly: false, compatible: false, recall: false, + useDocuments: false, instructions: "", settings: GenerationSettings()) + } + XCTAssertTrue(left.running && right.running) + let deadline = ContinuousClock.now + .seconds(8) + while (left.running || right.running) && ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(10)) + } + let store = try Store(url: database) + XCTAssertNotEqual(first, second) + XCTAssertEqual(try store.messages(in: first).last?.content, "Page received.") + XCTAssertEqual(try store.messages(in: second).last?.content, "Page received.") + } + @MainActor func testChatRetrievesPageWithoutToolboxConnection() async throws { guard let address = ProcessInfo.processInfo.environment["AISTUDIO_TEST_WEB_URL"],