import SwiftUI import AppKit import Charts import UniformTypeIdentifiers @main struct AIStudioApp: App { @StateObject private var studio = StudioModel() var body: some Scene { Window("AI Studio", id: "studio") { Group { if studio.launching { StudioWelcome(loading: true) } else { ChatView(studio: studio) } } .frame(minWidth: 740, minHeight: 500) .task { await Task.yield() studio.open() } } .defaultSize(width: 1000, height: 700) Settings { TabView { BackendSettings(studio: studio) .tabItem { Label("Models", systemImage: "cpu") } ModelCatalogView(studio: studio) .tabItem { Label("MLX Catalog", systemImage: "arrow.down.circle") } GenerationSettingsView() .tabItem { Label("Generation", systemImage: "slider.horizontal.3") } LocalToolsView(studio: studio) .tabItem { Label("Local Tools", systemImage: "terminal") } RuntimeSettingsView(studio: studio) .tabItem { Label("Runtime", systemImage: "waveform.path") } MCPSettings(studio: studio) .tabItem { Label("MCP Tools", systemImage: "wrench.and.screwdriver") } } .frame(width: 630, height: 600) } } } struct ChatView: View { @ObservedObject var studio: StudioModel @AppStorage("endpoint") private var endpoint = "http://127.0.0.1:11434" @AppStorage("ollamaModel") private var model = "" @AppStorage("mlxPath") private var mlxPath = "" @AppStorage("thinking") private var thinking = Thinking.automatic @AppStorage("failover") private var failover = true @AppStorage("mlxOnly") private var mlxOnly = false @AppStorage("compatibleEnabled") private var compatibleEnabled = false @AppStorage("compatibleEndpoint") private var compatibleEndpoint = "http://127.0.0.1:1234/v1" @AppStorage("compatibleModel") private var compatibleModel = "" @AppStorage("recall") private var recall = true @AppStorage("globalPromptMode") private var promptMode = PromptMode.standard @AppStorage("globalCustomPrompt") private var customPrompt = "" @AppStorage(GenerationSettings.key) private var generationSettings = Data() @State private var showingPromptBuilder = false @State private var showingPerformance = false @State private var confirmDelete = false @State private var search = "" @State private var renaming = false @State private var newTitle = "" private var backendName: String { compatibleEnabled ? "Compatible API" : "Ollama" } private var activeEndpoint: String { compatibleEnabled ? compatibleEndpoint : endpoint } private var activeModel: String { compatibleEnabled ? compatibleModel : model } private var visibleChats: [Conversation] { search.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? studio.conversations : studio.searchConversations(search) } @State private var showingLibrary = false @State private var useDocuments = false var body: some View { NavigationSplitView { List(visibleChats, selection: $studio.selected) { chat in Label(chat.title, systemImage: "bubble.left").tag(chat.id) } .searchable(text: $search, placement: .sidebar, prompt: "Search Chats") .disabled(studio.running) .navigationSplitViewColumnWidth(min: 180, ideal: 235) .toolbar { Button("New Chat", systemImage: "square.and.pencil") { search = "" studio.newChat() } .disabled(studio.running) Button("Rename Chat", systemImage: "pencil") { newTitle = studio.conversations.first(where: { $0.id == studio.selected })?.title ?? "" renaming = true } .disabled(studio.running || studio.selected == nil) Button("Delete Chat", systemImage: "trash") { confirmDelete = true } .disabled(studio.running || studio.selected == nil) } } detail: { VStack(spacing: 0) { if studio.messages.isEmpty && studio.partial == nil { StudioWelcome(loading: false) } else { transcript } Divider() composer } .navigationTitle("AI Studio") .toolbar { Button("Documents", systemImage: "doc.on.doc") { showingLibrary = true } .disabled(studio.selected == nil) Button("Prompt Builder", systemImage: "wand.and.stars") { showingPromptBuilder = true } Button("Performance", systemImage: "chart.xyaxis.line") { showingPerformance = true } SettingsLink { Label("Settings", systemImage: "gear") } } } .sheet(isPresented: $showingLibrary) { DocumentLibraryView(studio: studio) } .sheet(isPresented: $showingPerformance) { PerformanceDashboard(studio: studio) } .sheet(isPresented: $showingPromptBuilder) { PromptBuilder(customPrompt: $customPrompt) { instructions, global in if global { customPrompt = instructions promptMode = .custom } else { studio.prompt = instructions } } } .onChange(of: studio.selected) { _, _ in useDocuments = false } .alert("Rename Chat", isPresented: $renaming) { TextField("Title", text: $newTitle) Button("Rename") { studio.renameSelectedChat(newTitle) } Button("Cancel", role: .cancel) {} } .confirmationDialog("Delete this conversation?", isPresented: $confirmDelete, titleVisibility: .visible) { Button("Delete Conversation", role: .destructive) { studio.deleteChat() } } message: { Text("This permanently removes the conversation and its recalled messages.") } } private var transcript: some View { ScrollViewReader { proxy in ScrollView { LazyVStack(alignment: .leading, spacing: 18) { ForEach(studio.messages) { MessageView(message: $0) } if let partial = studio.partial { MessageView(message: partial, streaming: true) } Color.clear.frame(height: 1).id("end") } .frame(maxWidth: 800) .padding(24) .frame(maxWidth: .infinity) } .onChange(of: studio.messages.count, initial: true) { _, _ in proxy.scrollTo("end", anchor: .bottom) } .onChange(of: studio.partial) { _, _ in proxy.scrollTo("end", anchor: .bottom) } } } private var composer: some View { VStack(alignment: .leading, spacing: 8) { HStack { Label(mlxOnly ? "MLX on this Mac" : "\(backendName) · \(activeModel.isEmpty ? "Choose a model" : activeModel)", systemImage: mlxOnly ? "cpu" : "server.rack") .font(.caption) if !mlxOnly { Text(activeEndpoint).font(.caption).foregroundStyle(.secondary).lineLimit(1) } Spacer() if (!mlxOnly && !compatibleEnabled) || (mlxOnly && MLXThinking.supports(mlxPath)) { let modes: [Thinking] = mlxOnly ? [.automatic, .off, .on] : Thinking.allCases Picker("Thinking", selection: Binding( get: { modes.contains(thinking) ? thinking : .automatic }, set: { thinking = $0 } )) { ForEach(modes) { Text($0.rawValue.capitalized).tag($0) } } .fixedSize() .disabled(studio.running) } } if !studio.documents.isEmpty { Toggle(mlxOnly ? "Include matching document excerpts" : "Send matching document excerpts to \(backendName)", isOn: $useDocuments) .font(.caption) .disabled(studio.running) } if let attachment = studio.toolAttachment { HStack { Label("Attach \(attachment.name) result to next message", systemImage: "paperclip") if !mlxOnly { Text("Sent to \(backendName)").foregroundStyle(.secondary) } Spacer() Button("Remove", systemImage: "xmark.circle") { studio.removeToolAttachment() } } .font(.caption) } TextEditor(text: $studio.prompt) .font(.body) .frame(height: 62) .padding(5) .background(.background, in: RoundedRectangle(cornerRadius: 8)) .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(.quaternary)) .accessibilityLabel("Message") HStack { Text(studio.status).font(.caption).foregroundStyle(.secondary).textSelection(.enabled) Spacer() if studio.running { Button("Stop", systemImage: "stop.fill") { studio.stop() } } else { Button("Send", systemImage: "arrow.up") { studio.send(endpoint: activeEndpoint, model: activeModel, mlxPath: mlxPath, thinking: thinking, failover: failover, mlxOnly: mlxOnly, compatible: compatibleEnabled, recall: recall, useDocuments: useDocuments, instructions: promptMode.instructions(custom: customPrompt), settings: GenerationSettings.read(generationSettings)) } .buttonStyle(.borderedProminent) .keyboardShortcut(.return, modifiers: .command) .disabled(studio.prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) } } } .padding(16) } } struct MessageView: View { let message: Message var streaming = false var body: some View { VStack(alignment: .leading, spacing: 8) { HStack { Label(message.role == .user ? "You" : "Assistant", systemImage: message.role == .user ? "person.crop.circle" : "sparkle") .font(.headline) if !message.backend.isEmpty { Text(message.backend).font(.caption).foregroundStyle(.secondary) } Spacer() if !streaming, !message.content.isEmpty { Button("Copy Message", systemImage: "doc.on.doc") { copyChatText(message.content) } .labelStyle(.iconOnly) .buttonStyle(.borderless) .help("Copy message") } } if !message.thinking.isEmpty { DisclosureGroup("Thinking") { Text(message.thinking).foregroundStyle(.secondary).textSelection(.enabled) .frame(maxWidth: .infinity, alignment: .leading) } } if !message.content.isEmpty { if message.role == .assistant && !streaming { ChatMarkdown(text: message.content) } else { Text(message.content).textSelection(.enabled) } } if message.content.isEmpty && message.thinking.isEmpty { ProgressView().controlSize(.small) } } .frame(maxWidth: .infinity, alignment: .leading) .padding(14) .background(message.role == .user ? Color.accentColor.opacity(0.08) : Color.secondary.opacity(0.06), in: RoundedRectangle(cornerRadius: 12)) } } struct BackendSettings: View { @ObservedObject var studio: StudioModel @AppStorage("endpoint") private var endpoint = "http://127.0.0.1:11434" @AppStorage("ollamaModel") private var model = "" @AppStorage("mlxPath") private var mlxPath = "" @AppStorage("failover") private var failover = true @AppStorage("mlxOnly") private var mlxOnly = false @AppStorage("compatibleEnabled") private var compatibleEnabled = false @AppStorage("compatibleEndpoint") private var compatibleEndpoint = "http://127.0.0.1:1234/v1" @AppStorage("compatibleModel") private var compatibleModel = "" @AppStorage("recall") private var recall = true @State private var tag = "" @State private var pickingFolder = false @State private var confirmRemoval = false @State private var folderError = "" @State private var modelsEndpoint = "" var body: some View { Form { Section("Inference") { Picker("Backend", selection: Binding( get: { mlxOnly ? "mlx" : (compatibleEnabled ? "compatible" : "ollama") }, set: { mode in mlxOnly = mode == "mlx" compatibleEnabled = mode == "compatible" } )) { Text("Prefer Ollama").tag("ollama") Text("OpenAI-compatible").tag("compatible") Text("MLX only").tag("mlx") } Toggle("Fall back to MLX before output begins", isOn: $failover) .disabled(mlxOnly) Toggle("Recall older matching messages in this conversation", isOn: $recall) } Section("Ollama") { TextField("Server URL", text: $endpoint) .disabled(studio.managing) SecureField("Ollama bearer token (session only)", text: Binding( get: { studio.ollamaToken }, set: { studio.setOllamaToken($0, endpoint: endpoint) } )) .disabled(studio.managing) .onChange(of: endpoint) { _, newEndpoint in studio.setOllamaToken("", endpoint: newEndpoint) } TextField("Chat model", text: $model, prompt: Text("model:tag")) HStack { Button("Refresh Installed Models") { modelsEndpoint = endpoint studio.refresh(endpoint: endpoint) } .disabled(studio.managing) if studio.managing { Button("Cancel") { studio.cancelManagement() } } } if modelsEndpoint == endpoint, !studio.models.isEmpty { Menu("Installed Models") { ForEach(studio.models) { entry in Button(entry.name) { model = entry.name } } } } HStack { Button("Inspect Model") { studio.inspect(model, endpoint: endpoint) } Button("Delete Model…", role: .destructive) { confirmRemoval = true } } .disabled(studio.managing || model.isEmpty) HStack { TextField("Download model", text: $tag, prompt: Text("model:tag")) Button("Pull") { modelsEndpoint = endpoint studio.pull(tag, endpoint: endpoint) } .disabled(studio.managing || tag.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) } Text(studio.modelStatus).foregroundStyle(.secondary).textSelection(.enabled) } CompatibleEndpointSettings(studio: studio, endpoint: $compatibleEndpoint, model: $compatibleModel) Section("MLX") { LabeledContent("Model folder", value: mlxPath.isEmpty ? "None selected" : mlxPath) HStack { Button("Choose Folder…") { pickingFolder = true } Button("Unload Model") { studio.unloadMLX() } Button("Clear") { mlxPath = ""; studio.unloadMLX() }.disabled(mlxPath.isEmpty) } .disabled(studio.running) if !folderError.isEmpty { Text(folderError).foregroundStyle(.red) } } } .formStyle(.grouped) .frame(width: 590, height: 550) .fileImporter(isPresented: $pickingFolder, allowedContentTypes: [.folder]) { result in do { let url = try result.get() guard FileManager.default.fileExists(atPath: url.appending(path: "config.json").path) else { throw StudioError("This folder does not contain an MLX config.json.") } mlxPath = url.path folderError = "" studio.unloadMLX() } catch { folderError = error.localizedDescription } } .confirmationDialog("Delete \(model) from this Ollama server?", isPresented: $confirmRemoval, titleVisibility: .visible) { Button("Delete Model", role: .destructive) { studio.remove(model, endpoint: endpoint) } } } } struct StudioWelcome: View { let loading: Bool var body: some View { VStack(spacing: 12) { Image(nsImage: NSApp.applicationIconImage) .resizable() .interpolation(.high) .frame(width: 116, height: 116) .accessibilityHidden(true) Text("AI Studio") .font(.system(size: 34, weight: .semibold, design: .rounded)) if loading { ProgressView("Opening workspace…") .controlSize(.small) } else { Text("Choose a model in Settings or start with a message below.") .foregroundStyle(.secondary) .multilineTextAlignment(.center) SettingsLink { Label("Model Settings", systemImage: "slider.horizontal.3") } .buttonStyle(.bordered) .padding(.top, 4) } } .padding(32) .frame(maxWidth: .infinity, maxHeight: .infinity) .background { LinearGradient(colors: [.accentColor.opacity(0.12), .clear], startPoint: .top, endPoint: .bottom) } } } struct DocumentLibraryView: View { @Environment(\.dismiss) private var dismiss @ObservedObject var studio: StudioModel @State private var importing = false @State private var fileError = "" @State private var removing: LibraryDocument? var body: some View { VStack(alignment: .leading, spacing: 14) { Text("Conversation Documents").font(.title2.bold()) Text("Import PDF, text, Markdown, or CSV. Enable excerpts in the composer to use matching passages.") .foregroundStyle(.secondary) List(studio.documents) { document in HStack { Label(document.title, systemImage: "doc.text") Spacer() Button("Remove…", systemImage: "trash") { removing = document } .labelStyle(.iconOnly) .disabled(studio.running || studio.importingDocument) } } .overlay { if studio.documents.isEmpty { Text("No documents imported").foregroundStyle(.secondary) } } if !fileError.isEmpty || !studio.libraryStatus.isEmpty { Text(fileError.isEmpty ? studio.libraryStatus : fileError).foregroundStyle(.red) } HStack { Button("Import Document…", systemImage: "plus") { importing = true } .disabled(studio.running || studio.importingDocument) if studio.importingDocument { ProgressView().controlSize(.small) } Spacer() Button("Done") { dismiss() }.keyboardShortcut(.defaultAction) } } .padding(22) .frame(width: 470, height: 360) .fileImporter(isPresented: $importing, allowedContentTypes: [ .pdf, .plainText, .commaSeparatedText, UTType(filenameExtension: "md") ?? .plainText ]) { result in do { let url = try result.get() fileError = "" Task { await studio.importDocument(url) } } catch { fileError = error.localizedDescription } } .confirmationDialog("Remove this document?", isPresented: Binding( get: { removing != nil }, set: { if !$0 { removing = nil } } ), titleVisibility: .visible, presenting: removing) { document in Button("Remove", role: .destructive) { studio.deleteDocument(document) } } message: { document in Text(document.title) } } } private func copyChatText(_ text: String) { NSPasteboard.general.clearContents() NSPasteboard.general.setString(text, forType: .string) } struct ChatMarkdown: View { let text: String struct Block: Equatable { let content: String let language: String? } static func blocks(_ markdown: String) -> [Block] { var blocks: [Block] = [] var lines: [String] = [] var language: String? var opener = "" for line in markdown.components(separatedBy: .newlines) { let trimmed = line.trimmingCharacters(in: .whitespaces) if language != nil && trimmed == "```" { blocks.append(Block(content: lines.joined(separator: "\n"), language: language)) lines = [] language = nil } else if language == nil && trimmed.hasPrefix("```") { if !lines.isEmpty { blocks.append(Block(content: lines.joined(separator: "\n"), language: nil)) } lines = [] opener = line language = String(trimmed.dropFirst(3)).trimmingCharacters(in: .whitespaces) } else { lines.append(line) } } if language != nil { lines.insert(opener, at: 0) } if !lines.isEmpty { blocks.append(Block(content: lines.joined(separator: "\n"), language: nil)) } return blocks.filter { $0.language != nil || !$0.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } } var body: some View { let blocks = Self.blocks(text) VStack(alignment: .leading, spacing: 10) { ForEach(blocks.indices, id: \.self) { index in let block = blocks[index] if let language = block.language { VStack(alignment: .leading, spacing: 8) { HStack { Text(language.isEmpty ? "Code" : String(language.prefix(60))) .font(.caption).foregroundStyle(.secondary) Spacer() Button("Copy Code", systemImage: "doc.on.doc") { copyChatText(block.content) } .buttonStyle(.borderless) } ScrollView(.horizontal) { Text(block.content).font(.system(.body, design: .monospaced)).textSelection(.enabled) } } .padding(10) .background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 8)) } else { let parsed = try? AttributedString(markdown: block.content, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace)) Text(parsed ?? AttributedString(block.content)).textSelection(.enabled) } } } } } struct PromptBuilder: View { @Environment(\.dismiss) private var dismiss @Binding var customPrompt: String let apply: (String, Bool) -> Void @State private var draft = PromptDraft() @State private var edited = "" @State private var editingDirectly = false private var output: String { editingDirectly ? edited.trimmingCharacters(in: .whitespacesAndNewlines) : draft.rendered } var body: some View { VStack(alignment: .leading, spacing: 12) { Text("Prompt Builder").font(.title2.bold()) HSplitView { Form { TextField("Role", text: $draft.role, prompt: Text("Who should the model act as?")) TextField("Task", text: $draft.task, prompt: Text("What should it do?"), axis: .vertical) TextField("Context", text: $draft.context, axis: .vertical) TextField("Audience", text: $draft.audience) TextField("Requirements and constraints", text: $draft.constraints, axis: .vertical) TextField("Output format", text: $draft.format, axis: .vertical) TextField("Examples", text: $draft.examples, axis: .vertical) TextField("Success criteria", text: $draft.success, axis: .vertical) } .formStyle(.grouped) .disabled(editingDirectly) .frame(minWidth: 310) VStack(alignment: .leading) { HStack { Text("Preview").font(.headline) Spacer() Toggle("Edit directly", isOn: Binding( get: { editingDirectly }, set: { enabled in if enabled { edited = draft.rendered } editingDirectly = enabled } )) } if editingDirectly { TextEditor(text: $edited).accessibilityLabel("Prompt text") } else { ScrollView { Text(output.isEmpty ? "Fill in any field to build your prompt." : output) .textSelection(.enabled) .frame(maxWidth: .infinity, alignment: .leading) } } } .padding(12) .frame(minWidth: 285, maxHeight: .infinity, alignment: .top) } HStack { Button("Load Global Custom Prompt") { editingDirectly = true edited = customPrompt } .disabled(customPrompt.isEmpty) Spacer() Button("Copy") { copyChatText(output) }.disabled(output.isEmpty) Button("Use in Composer") { submit(global: false) }.disabled(output.isEmpty) Button("Set as Global Prompt") { submit(global: true) }.disabled(output.isEmpty) Button("Close") { dismiss() }.keyboardShortcut(.cancelAction) } } .padding(20) .frame(minWidth: 780, minHeight: 520) } private func submit(global: Bool) { apply(output, global) dismiss() } } struct PerformanceDashboard: View { @Environment(\.dismiss) private var dismiss @ObservedObject var studio: StudioModel var body: some View { VStack(alignment: .leading, spacing: 14) { HStack { Text("Inference Performance").font(.title2.bold()) Spacer() Button("Done") { dismiss() }.keyboardShortcut(.defaultAction) } Text("Up to 50 generations from this session. First output includes model loading and any fallback.") .foregroundStyle(.secondary) if studio.measurements.isEmpty { ContentUnavailableView("No measurements yet", systemImage: "chart.xyaxis.line", description: Text("Send a chat message to collect timing and throughput.")) } else { Chart { ForEach(Array(studio.measurements.reversed().enumerated()), id: \.element.id) { index, run in BarMark(x: .value("Run", index + 1), y: .value("Seconds", run.seconds)) .foregroundStyle(by: .value("Backend", run.backend)) } } .chartXAxisLabel("Generation") .chartYAxisLabel("Total seconds") .frame(height: 160) Table(studio.measurements) { TableColumn("Backend", value: \.backend) TableColumn("First output") { Text(seconds($0.firstOutput)) } TableColumn("Total") { Text(seconds($0.seconds)) } TableColumn("Tokens/s") { Text($0.provider?.tokensPerSecond.map { $0.formatted(.number.precision(.fractionLength(1))) } ?? "—") } TableColumn("Tokens") { Text($0.provider?.tokens.formatted() ?? "—") } TableColumn("Characters") { Text($0.characters.formatted()) } TableColumn("Outcome", value: \.outcome) } } } .padding(20) .frame(minWidth: 800, minHeight: 475) } private func seconds(_ value: Double?) -> String { value.map { $0.formatted(.number.precision(.fractionLength(2))) + " s" } ?? "—" } } struct GenerationSettingsView: View { @AppStorage("globalPromptMode") private var promptMode = PromptMode.standard @AppStorage("globalCustomPrompt") private var prompt = "" @AppStorage("thinking") private var thinking = Thinking.automatic @AppStorage(GenerationSettings.key) private var stored = Data() @State private var draft = GenerationSettings() @State private var status = "" var body: some View { VStack(spacing: 0) { Form { Section("System Prompt") { Picker("Global preset", selection: $promptMode) { ForEach(PromptMode.allCases) { Text($0.rawValue).tag($0) } } if promptMode == .custom { TextEditor(text: $prompt) .font(.body).frame(minHeight: 88).accessibilityLabel("Global system instructions") } else if promptMode != .standard { Text(promptMode.instructions(custom: prompt)).foregroundStyle(.secondary).textSelection(.enabled) } Text("Applied automatically to new replies across chats. System instructions stay out of the transcript.") .foregroundStyle(.secondary) } Section("Shared Generation") { Picker("Thinking", selection: $thinking) { ForEach(Thinking.allCases) { Text($0.rawValue.capitalized).tag($0) } } field("Temperature", $draft.temperature) field("Maximum output tokens", $draft.maxTokens) field("Top P", $draft.topP) field("Repeat penalty", $draft.repeatPenalty) field("Repeat window", $draft.repeatLastN) TextField("Stop sequences (one per line)", text: $draft.stop, axis: .vertical) } Section("Ollama") { field("Context length", $draft.context) field("Top K", $draft.topK) field("Min P", $draft.minP) field("Seed", $draft.seed) field("Keep alive (e.g. 5m or 0)", $draft.keepAlive) } Section("Ollama and OpenAI-compatible") { field("Frequency penalty", $draft.frequencyPenalty) field("Presence penalty", $draft.presencePenalty) Toggle("JSON output", isOn: $draft.json) } Section("MLX") { field("Rolling KV cache tokens", $draft.mlxCache) field("Prefill step size", $draft.mlxPrefill) Text("MLX uses Default, Off, or On for supported thinking templates. Its default output cap is 1,024 tokens.") .foregroundStyle(.secondary) } } .formStyle(.grouped) Divider() HStack { Text(status.isEmpty ? "Blank fields use backend defaults." : status) .foregroundStyle(.secondary).font(.caption).textSelection(.enabled) Spacer() Button("Reset Overrides") { draft = GenerationSettings() save() } Button("Apply Parameters", action: save).buttonStyle(.borderedProminent) } .padding(12) } .onAppear { draft = GenerationSettings.read(stored) } } private func field(_ title: String, _ value: Binding) -> some View { TextField(title, text: value, prompt: Text("Default")) } private func save() { do { _ = try draft.parameters(mlxOnly: false) stored = try JSONEncoder().encode(draft) status = "Parameters saved for future replies." } catch { status = error.localizedDescription } } } enum DockerCommand { static func arguments(_ line: String) throws -> [String] { var arguments: [String] = [] var word = "" var quote: Character? var escaped = false var started = false for character in line { if escaped { word.append(character) escaped = false } else if character == "\\" && quote != "'" { escaped = true started = true } else if let activeQuote = quote { if character == activeQuote { quote = nil } else { word.append(character) } } else if character == "'" || character == "\"" { quote = character started = true } else if character.isWhitespace { if started { arguments.append(word); word = ""; started = false } } else { word.append(character) started = true } } guard quote == nil, !escaped else { throw StudioError("Close the quoted argument or remove the trailing backslash.") } if started { arguments.append(word) } if arguments.first == "docker" { arguments.removeFirst() } guard let first = arguments.first, !first.isEmpty else { throw StudioError("Enter a Docker command.") } return arguments } static var executable: URL? { let paths = ["/usr/local/bin/docker", "/opt/homebrew/bin/docker", FileManager.default.homeDirectoryForCurrentUser.appending(path: ".docker/bin/docker").path, "/Applications/Docker.app/Contents/Resources/bin/docker"] return paths.first(where: FileManager.default.isExecutableFile(atPath:)).map { URL(fileURLWithPath: $0) } } } struct LocalToolsView: View { @ObservedObject var studio: StudioModel @State private var line = "docker ps" @State private var pending: [String]? @State private var output = "" @State private var process: Process? @State private var file: URL? @State private var preview = "" @State private var fileStatus = "" @State private var picking = false @State private var status = "" @State private var confirm = false var body: some View { Form { Section("Docker") { TextField("Command", text: $line, prompt: Text("docker ps --all")) .font(.system(.body, design: .monospaced)) .disabled(process != nil) Text("Commands run through the local Docker CLI. Interactive input is unavailable.") .foregroundStyle(.secondary) HStack { Button("Review Command…") { do { pending = try DockerCommand.arguments(line) confirm = true status = "" } catch { status = error.localizedDescription } } .disabled(process != nil) if let process { Button("Stop") { if process.isRunning { process.terminate() } } } } if !status.isEmpty { Text(status).foregroundStyle(.secondary) } if !output.isEmpty { ScrollView { Text(output).font(.system(.caption, design: .monospaced)).textSelection(.enabled) .frame(maxWidth: .infinity, alignment: .leading) } .frame(height: 140) HStack { Button("Copy Output") { copyChatText(output) } Button("Attach to Active Chat") { studio.attachToolResult(name: "Docker", output: output) } .disabled(studio.selected == nil || studio.running) } } } Section("Finder") { Button("Choose File or Folder…") { picking = true } if let file { Text(file.path).textSelection(.enabled) HStack { Button("Open") { NSWorkspace.shared.open(file) } Button("Reveal in Finder") { NSWorkspace.shared.activateFileViewerSelecting([file]) } Button("Copy Path") { copyChatText(file.path) } } Button("Preview Text") { do { preview = try LocalFilePreview.read(file) fileStatus = preview.isEmpty ? "This file is empty." : "" } catch { preview = ""; fileStatus = error.localizedDescription } } if !fileStatus.isEmpty { Text(fileStatus).foregroundStyle(.secondary) } if !preview.isEmpty { ScrollView { Text(preview).font(.system(.caption, design: .monospaced)).textSelection(.enabled) .frame(maxWidth: .infinity, alignment: .leading) } .frame(height: 120) Button("Attach Preview to Active Chat") { studio.attachToolResult(name: file.lastPathComponent, output: preview) } .disabled(studio.selected == nil || studio.running) } } } } .formStyle(.grouped) .fileImporter(isPresented: $picking, allowedContentTypes: [.item, .folder]) { result in preview = "" fileStatus = "" do { file = try result.get() } catch { fileStatus = error.localizedDescription } } .confirmationDialog("Run Docker command?", isPresented: $confirm, titleVisibility: .visible) { Button("Run Command") { if let pending { run(pending) } } } message: { Text(line) } } private func run(_ args: [String]) { guard process == nil else { return } guard let executable = DockerCommand.executable else { status = "Docker CLI was not found in the standard install locations." return } let child = Process() let pipe = Pipe() child.executableURL = executable child.arguments = args child.standardInput = FileHandle.nullDevice child.standardOutput = pipe child.standardError = pipe do { try child.run() process = child output = "" status = "Running…" } catch { status = error.localizedDescription return } Task { let result = await Task.detached { let reader = pipe.fileHandleForReading var captured = Data() var truncated = false while let bytes = try? reader.read(upToCount: 8192), !bytes.isEmpty { let remaining = max(0, 131_072 - captured.count) captured.append(bytes.prefix(remaining)) truncated = truncated || bytes.count > remaining } child.waitUntilExit() return (String(decoding: captured, as: UTF8.self), child.terminationStatus, truncated) }.value output = result.0 + (result.2 ? "\n[Output truncated]" : "") status = "Exited with status \(result.1)." process = nil } } } struct CompatibleEndpointSettings: View { @ObservedObject var studio: StudioModel @Binding var endpoint: String @Binding var model: String @State private var models: [String] = [] @State private var connecting = false @State private var status = "" var body: some View { Section("OpenAI-compatible endpoint") { TextField("Base URL", text: $endpoint, prompt: Text("http://127.0.0.1:1234/v1")) .disabled(connecting) SecureField("Bearer token (session only)", text: Binding( get: { studio.compatibleToken }, set: { studio.setCompatibleToken($0, endpoint: endpoint) } )) .disabled(connecting) TextField("Model ID", text: $model) HStack { Button("Refresh Models") { Task { await refresh() } } .disabled(connecting) if connecting { ProgressView().controlSize(.small) } if !models.isEmpty { Menu("Available Models") { ForEach(models, id: \.self) { name in Button(name) { model = name } } } } } if !status.isEmpty { Text(status).foregroundStyle(.secondary).textSelection(.enabled) } Text("Use the API base path, such as /v1 for LM Studio. Model downloads and loading are managed by the server.") .foregroundStyle(.secondary) } .onChange(of: endpoint) { _, value in studio.setCompatibleToken("", endpoint: value) models = [] status = "" } } private func refresh() async { guard !connecting else { return } connecting = true models = [] status = "" defer { connecting = false } do { models = try await studio.compatibleClient(endpoint: endpoint).models() status = models.isEmpty ? "The server returned no models." : "\(models.count) model(s) available." } catch { status = error.localizedDescription } } } enum LocalFilePreview { static func read(_ url: URL, limit: Int = 8_000) throws -> String { let scoped = url.startAccessingSecurityScopedResource() defer { if scoped { url.stopAccessingSecurityScopedResource() } } let file = url.resolvingSymlinksInPath() guard try file.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw StudioError("Select a regular UTF-8 text file to preview.") } let handle = try FileHandle(forReadingFrom: file) defer { try? handle.close() } let bytes = try handle.read(upToCount: limit + 1) ?? Data() let truncated = bytes.count > limit var prefix = Data(bytes.prefix(limit)) guard !prefix.contains(0) else { throw StudioError("This file does not contain UTF-8 text.") } for trim in 0...(truncated ? 3 : 0) { if trim > 0 && !prefix.isEmpty { prefix.removeLast() } if let text = String(data: prefix, encoding: .utf8) { return truncated ? text + "\n[Preview truncated]" : text } } throw StudioError("This file does not contain UTF-8 text.") } } struct RuntimeSettingsView: View { @ObservedObject var studio: StudioModel @AppStorage(MLXRuntimeLimits.idleKey) private var idleMinutes = MLXRuntimeLimits.defaultIdleMinutes @AppStorage(MLXRuntimeLimits.weightKey) private var weightGiB = 0 @State private var loaded: String? var body: some View { Form { Section("MLX Model Residency") { LabeledContent("Cached model", value: loaded ?? "None") LabeledContent("State", value: studio.running ? "Generation in progress" : "Idle") Button("Unload Cached Model") { studio.unloadMLX() } .disabled(studio.running || loaded == nil) Stepper(value: $idleMinutes, in: 0...120) { LabeledContent("Unload after idle", value: idleMinutes == 0 ? "Never" : "\(idleMinutes) min") } Text("The idle timer starts after MLX finishes a generation. Changing the timeout restarts the timer.") .foregroundStyle(.secondary) } Section("Loading Limit") { LabeledContent("Physical memory", value: ByteCountFormatter.string( fromByteCount: Int64(ProcessInfo.processInfo.physicalMemory), countStyle: .memory)) Stepper(value: $weightGiB, in: 0...512) { LabeledContent("Maximum model weights", value: weightGiB == 0 ? "Off" : "\(weightGiB) GiB") } Text("The limit checks safetensors on disk before a new MLX load. Runtime memory also depends on the model and cache.") .foregroundStyle(.secondary) } } .formStyle(.grouped) .onChange(of: idleMinutes) { _, _ in studio.reloadRuntimeSettings() } .onChange(of: weightGiB) { _, _ in studio.reloadRuntimeSettings() } .task { while !Task.isCancelled { loaded = await studio.mlxModelName() do { try await Task.sleep(for: .milliseconds(500)) } catch { return } } } } }