Add custom MCP profiles and reusable workspace libraries

This commit is contained in:
Mark Gregory
2026-11-16 14:50:20 +00:00
parent bc2ae8ec02
commit 32c4b9f91c
12 changed files with 1398 additions and 76 deletions
+603 -28
View File
@@ -6,6 +6,10 @@ import UniformTypeIdentifiers
@main
struct AIStudioApp: App {
@StateObject private var studio = StudioModel()
@AppStorage("studioTheme") private var theme = StudioTheme.system
@AppStorage("studioAccent") private var accent = StudioAccent.storm
@AppStorage("studioChatSize") private var chatSize = 14
@AppStorage("studioMode") private var mode = StudioMode.normal
var body: some Scene {
Window("AI Studio", id: "studio") {
@@ -17,29 +21,33 @@ struct AIStudioApp: App {
}
}
.frame(minWidth: 740, minHeight: 500)
.preferredColorScheme(theme.colorScheme)
.tint(accent.color)
.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") }
.commands {
CommandMenu("Appearance") {
Button("Increase Chat Font Size") { chatSize = min(28, chatSize + 1) }.keyboardShortcut("=")
Button("Decrease Chat Font Size") { chatSize = max(10, chatSize - 1) }.keyboardShortcut("-")
Button("Reset Chat Font Size") { chatSize = 14 }.keyboardShortcut("0")
Button("Cycle Theme") { theme = nextValue(theme) }.keyboardShortcut("3")
Button("Cycle Workspace Mode") { mode = nextValue(mode) }.keyboardShortcut("9")
}
.frame(width: 630, height: 600)
}
Settings {
StudioSettingsView(studio: studio)
.preferredColorScheme(theme.colorScheme)
.tint(accent.color)
}
}
private func nextValue<Value: CaseIterable & Equatable>(_ current: Value) -> Value {
let all = Array(Value.allCases)
return all[((all.firstIndex(of: current) ?? 0) + 1) % all.count]
}
}
@@ -60,6 +68,14 @@ struct ChatView: View {
@AppStorage(GenerationSettings.key) private var generationSettings = Data()
@State private var showingPromptBuilder = false
@State private var showingPerformance = false
@State private var showingWorkspace = false
@State private var showingToolbox = false
@AppStorage("composerSpellCheck") private var spellCheck = true
@AppStorage("composerAutoCorrect") private var autoCorrect = false
@AppStorage("studioChatSize") private var chatSize = 14
@AppStorage("studioChatFont") private var chatFont = StudioFont.system
@AppStorage("studioMode") private var mode = StudioMode.normal
@State private var columns: NavigationSplitViewVisibility = .all
@State private var confirmDelete = false
@State private var search = ""
@State private var renaming = false
@@ -77,7 +93,7 @@ struct ChatView: View {
@State private var useDocuments = false
var body: some View {
NavigationSplitView {
NavigationSplitView(columnVisibility: $columns) {
List(visibleChats, selection: $studio.selected) { chat in
Label(chat.title, systemImage: "bubble.left").tag(chat.id)
}
@@ -113,12 +129,19 @@ struct ChatView: View {
Button("Documents", systemImage: "doc.on.doc") { showingLibrary = true }
.disabled(studio.selected == nil)
Button("Prompt Builder", systemImage: "wand.and.stars") { showingPromptBuilder = true }
Button("Workspace", systemImage: "square.stack.3d.up") { showingWorkspace = true }
Button("Performance", systemImage: "chart.xyaxis.line") { showingPerformance = true }
SettingsLink { Label("Settings", systemImage: "gear") }
}
}
.toolbar(mode == .zen ? .hidden : .visible, for: .windowToolbar)
.onChange(of: mode, initial: true) { _, value in columns = value == .normal ? .all : .detailOnly }
.sheet(isPresented: $showingLibrary) { DocumentLibraryView(studio: studio) }
.sheet(isPresented: $showingPerformance) { PerformanceDashboard(studio: studio) }
.sheet(isPresented: $showingWorkspace) { WorkspaceResourcesView(studio: studio) }
.sheet(isPresented: $showingToolbox) {
ToolboxSheet(studio: studio).frame(width: 650, height: 620)
}
.sheet(isPresented: $showingPromptBuilder) {
PromptBuilder(customPrompt: $customPrompt) { instructions, global in
if global {
@@ -129,7 +152,15 @@ struct ChatView: View {
}
}
}
.onChange(of: studio.selected) { _, _ in useDocuments = false }
.onChange(of: studio.selected) { old, _ in
useDocuments = false
if old != nil {
studio.activeStack = nil
studio.activeSkill = nil
studio.activeContext = nil
studio.activeWebClip = nil
}
}
.alert("Rename Chat", isPresented: $renaming) {
TextField("Title", text: $newTitle)
Button("Rename") { studio.renameSelectedChat(newTitle) }
@@ -154,6 +185,7 @@ struct ChatView: View {
.padding(24)
.frame(maxWidth: .infinity)
}
.font(chatFont.font(size: chatSize))
.onChange(of: studio.messages.count, initial: true) { _, _ in proxy.scrollTo("end", anchor: .bottom) }
.onChange(of: studio.partial) { _, _ in proxy.scrollTo("end", anchor: .bottom) }
}
@@ -196,25 +228,38 @@ struct ChatView: View {
}
.font(.caption)
}
TextEditor(text: $studio.prompt)
.font(.body)
HStack(spacing: 10) {
Button {
showingToolbox = true
} label: {
Label(studio.activeToolset == nil ? "Toolbox" : "1 Active Toolset",
systemImage: "wrench.and.screwdriver")
}
.buttonStyle(.bordered)
if let toolset = studio.activeToolset {
Text("\(toolset.name) · \(toolset.tools.count) tools").lineLimit(1).foregroundStyle(.secondary)
}
if studio.activeStack != nil || studio.activeSkill != nil ||
studio.activeContext != nil || studio.activeWebClip != nil {
Button("Active Resources", systemImage: "square.stack") { showingWorkspace = true }
.buttonStyle(.borderless)
}
Spacer()
}
.font(.caption)
ChatComposerInput(text: $studio.prompt, canSend: !studio.running, spellCheck: spellCheck,
autoCorrect: autoCorrect, font: chatFont.appKit(size: chatSize), send: sendMessage)
.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))
}
Button("Send", systemImage: "arrow.up", action: sendMessage)
.buttonStyle(.borderedProminent)
.keyboardShortcut(.return, modifiers: .command)
.disabled(studio.prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
@@ -223,6 +268,13 @@ struct ChatView: View {
}
.padding(16)
}
private func sendMessage() {
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))
}
}
struct MessageView: View {
@@ -472,6 +524,8 @@ private func copyChatText(_ text: String) {
struct ChatMarkdown: View {
let text: String
@AppStorage("studioCodeTheme") private var codeTheme = StudioTheme.system
@Environment(\.colorScheme) private var currentScheme
struct Block: Equatable {
let content: String
@@ -527,6 +581,7 @@ struct ChatMarkdown: View {
}
.padding(10)
.background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 8))
.environment(\.colorScheme, codeTheme.colorScheme ?? currentScheme)
} else {
let parsed = try? AttributedString(markdown: block.content,
options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))
@@ -625,8 +680,11 @@ struct PerformanceDashboard: View {
Spacer()
Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)
}
Text("Up to 50 generations from this session. First output includes model loading and any fallback.")
Text("Last 50 generations. First output includes model loading and any fallback.")
.foregroundStyle(.secondary)
if studio.running {
Label("Generation in progress…", systemImage: "ellipsis").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."))
@@ -646,7 +704,9 @@ struct PerformanceDashboard: View {
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("Characters/s") { run in
Text(run.charactersPerSecond.map { $0.formatted(.number.precision(.fractionLength(1))) } ?? "—")
}
TableColumn("Outcome", value: \.outcome)
}
}
@@ -1035,3 +1095,518 @@ struct RuntimeSettingsView: View {
}
}
}
struct ChatComposerInput: NSViewRepresentable {
@Binding var text: String
var canSend: Bool
var spellCheck: Bool
var autoCorrect: Bool
var font: NSFont
var send: () -> Void
func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeNSView(context: Context) -> NSScrollView {
let scroll = NSTextView.scrollableTextView()
guard let editor = scroll.documentView as? NSTextView else { return scroll }
editor.isRichText = false
editor.font = font
editor.delegate = context.coordinator
editor.drawsBackground = false
scroll.drawsBackground = false
editor.setAccessibilityLabel("Message")
return scroll
}
func updateNSView(_ scroll: NSScrollView, context: Context) {
context.coordinator.parent = self
if let editor = scroll.documentView as? NSTextView {
editor.font = font
editor.isContinuousSpellCheckingEnabled = spellCheck
editor.isAutomaticSpellingCorrectionEnabled = autoCorrect
if editor.string != text {
editor.string = text
editor.setSelectedRange(NSRange(location: text.utf16.count, length: 0))
}
}
}
static func sendsReturn(modifiers: NSEvent.ModifierFlags, marked: Bool) -> Bool {
!marked && modifiers.intersection([.shift, .command, .option, .control]).isEmpty
}
final class Coordinator: NSObject, NSTextViewDelegate {
var parent: ChatComposerInput
init(_ parent: ChatComposerInput) { self.parent = parent }
func textDidChange(_ notification: Notification) {
guard let editor = notification.object as? NSTextView else { return }
parent.text = editor.string
}
func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
guard commandSelector == #selector(NSResponder.insertNewline(_:)),
let event = NSApp.currentEvent,
event.type == .keyDown,
ChatComposerInput.sendsReturn(modifiers: event.modifierFlags, marked: textView.hasMarkedText()) else {
return false
}
if parent.canSend { parent.send() }
return true
}
}
}
struct ToolboxSheet: View {
@Environment(\.dismiss) private var dismiss
@ObservedObject var studio: StudioModel
var body: some View {
VStack(spacing: 0) {
HStack {
Label("Toolbox", systemImage: "wrench.and.screwdriver").font(.headline)
Spacer()
Button("Done") { dismiss() }
}
.padding()
MCPSettings(studio: studio)
}
}
}
struct WorkspaceResourcesView: View {
@Environment(\.dismiss) private var dismiss
@ObservedObject var studio: StudioModel
var body: some View {
VStack(spacing: 0) {
HStack {
Text("Workspace").font(.title2.bold())
Spacer()
Button("Done") { dismiss() }
}
.padding()
TabView {
KnowledgeStacksView(studio: studio).tabItem { Label("Stacks", systemImage: "square.stack.3d.up") }
WorkspaceSnippetsView(studio: studio, kind: .skill).tabItem { Label("Skills", systemImage: "bolt") }
WorkspaceSnippetsView(studio: studio, kind: .context).tabItem { Label("Contexts", systemImage: "doc.text") }
WorkspaceSnippetsView(studio: studio, kind: .prompt).tabItem { Label("Prompts", systemImage: "text.bubble") }
WorkspaceSnippetsView(studio: studio, kind: .webClip).tabItem { Label("Web Clips", systemImage: "link") }
}
if !studio.workspaceStatus.isEmpty {
Text(studio.workspaceStatus).foregroundStyle(.red).textSelection(.enabled).padding(8)
}
}
.frame(width: 720, height: 560)
}
}
struct KnowledgeStacksView: View {
@ObservedObject var studio: StudioModel
@State private var selected: UUID?
@State private var name = ""
@State private var documents: [LibraryDocument] = []
@State private var importing = false
@State private var busy = false
@State private var removing = false
var body: some View {
Form {
Section("Knowledge Stacks") {
HStack {
TextField("New stack name", text: $name)
Button("Create") {
selected = studio.createStack(name.trimmingCharacters(in: .whitespacesAndNewlines))
name = ""
}.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || busy)
}
Picker("Manage stack", selection: $selected) {
Text("Select a stack").tag(UUID?.none)
ForEach(studio.knowledgeStacks) { Text($0.title).tag(Optional($0.id)) }
}
Picker("Use in this chat", selection: $studio.activeStack) {
Text("None").tag(UUID?.none)
ForEach(studio.knowledgeStacks) { Text($0.title).tag(Optional($0.id)) }
}
Text("Matching passages from the active stack are included in inference requests.")
.foregroundStyle(.secondary)
}
if let selected {
Section("Indexed Documents") {
ForEach(documents) { document in
HStack {
Text(document.title)
Spacer()
Button("Remove", role: .destructive) {
studio.deleteStackDocument(document, in: selected)
refresh()
}.disabled(busy)
}
}
HStack {
Button("Import Document…") { importing = true }.disabled(busy)
if busy { ProgressView().controlSize(.small) }
Spacer()
Button("Delete Stack…", role: .destructive) { removing = true }.disabled(busy)
}
}
}
}
.formStyle(.grouped)
.onAppear { selected = studio.activeStack; refresh() }
.onChange(of: selected) { _, _ in refresh() }
.fileImporter(isPresented: $importing, allowedContentTypes: [
.pdf, .plainText, .commaSeparatedText, UTType(filenameExtension: "md") ?? .plainText
]) { result in
guard let url = try? result.get(), let selected else { return }
busy = true
Task {
await studio.importStackDocument(url, in: selected)
refresh()
busy = false
}
}
.confirmationDialog("Delete this stack and its index?", isPresented: $removing) {
Button("Delete Stack", role: .destructive) {
if let selected { studio.deleteStack(selected) }
selected = nil
}
}
}
private func refresh() { documents = selected.map(studio.stackDocuments) ?? [] }
}
struct WorkspaceSnippetsView: View {
@ObservedObject var studio: StudioModel
let kind: WorkspaceSnippet.Kind
@State private var search = ""
@State private var id: UUID?
@State private var title = ""
@State private var content = ""
@State private var address = ""
@State private var importing = false
@State private var capturing = false
@State private var deleting = false
@State private var error = ""
private var items: [WorkspaceSnippet] {
studio.snippets.filter {
$0.kind == kind && (search.isEmpty || $0.title.localizedCaseInsensitiveContains(search))
}
}
var body: some View {
HSplitView {
VStack(spacing: 8) {
TextField("Search \(kind.rawValue)s", text: $search)
List(items, selection: $id) { item in Text(item.title).tag(item.id) }
Button("New \(kind.rawValue)") { clear() }
}
.padding(12)
.frame(minWidth: 180, idealWidth: 220)
VStack(alignment: .leading, spacing: 10) {
TextField("Title", text: $title)
if kind == .webClip {
HStack {
TextField("Source URL", text: $address)
Button("Capture Text") {
capturing = true
let source = address
Task {
defer { capturing = false }
do {
content = try await WebClipCapture.text(from: source)
if title.isEmpty { title = URL(string: source)?.host ?? "Web Clip" }
error = ""
} catch { self.error = error.localizedDescription }
}
}.disabled(capturing || address.isEmpty)
}
}
TextEditor(text: $content).accessibilityLabel("\(kind.rawValue) text")
.border(.quaternary)
if !error.isEmpty { Text(error).foregroundStyle(.red).textSelection(.enabled) }
HStack {
if kind != .webClip { Button("Import Text…") { importing = true } }
if id != nil { Button("Delete…", role: .destructive) { deleting = true } }
Spacer()
if id != nil {
Button(kind == .prompt ? "Use in Composer" : isActive ? "Remove from Chat" : "Use in Chat") {
apply()
}.disabled(studio.running)
}
Button("Save", action: save).buttonStyle(.borderedProminent)
.disabled(title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||
content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || capturing)
}
}
.padding(15)
.frame(minWidth: 400)
}
.onChange(of: id) { _, value in
if let item = studio.snippets.first(where: { $0.id == value }) {
title = item.title
if kind == .webClip {
let parts = item.content.components(separatedBy: "\n\n")
address = String((parts.first ?? "").dropFirst("Source: ".count))
content = parts.dropFirst().joined(separator: "\n\n")
} else {
content = item.content
}
}
}
.fileImporter(isPresented: $importing, allowedContentTypes: [
.plainText, UTType(filenameExtension: "md") ?? .plainText
]) { result in
do {
let file = try result.get()
content = try LocalFilePreview.read(file, limit: 12000)
if title.isEmpty { title = file.deletingPathExtension().lastPathComponent }
error = ""
} catch { self.error = error.localizedDescription }
}
.confirmationDialog("Delete saved \(kind.rawValue.lowercased())?", isPresented: $deleting) {
Button("Delete", role: .destructive) {
if let id { studio.removeSnippet(id) }
clear()
}
}
}
private var isActive: Bool {
guard let id else { return false }
return switch kind {
case .skill: studio.activeSkill == id
case .context: studio.activeContext == id
case .webClip: studio.activeWebClip == id
case .prompt: false
}
}
private func apply() {
guard let item = studio.snippets.first(where: { $0.id == id }) else { return }
switch kind {
case .skill: studio.activeSkill = isActive ? nil : item.id
case .context: studio.activeContext = isActive ? nil : item.id
case .webClip: studio.activeWebClip = isActive ? nil : item.id
case .prompt: studio.prompt = item.content
}
}
private func save() {
if kind == .webClip {
do { _ = try WebClipCapture.url(address) }
catch { self.error = error.localizedDescription; return }
}
let key = id ?? UUID()
let stored = kind == .webClip ? "Source: \(address)\n\n\(content)" : content
studio.saveSnippet(id: key, kind: kind, title: title.trimmingCharacters(in: .whitespacesAndNewlines), content: stored)
id = key
error = ""
}
private func clear() { id = nil; title = ""; content = ""; address = ""; error = "" }
}
enum StudioTheme: String, CaseIterable, Identifiable {
case system = "System", light = "Light", dark = "Dark"
var id: Self { self }
var colorScheme: ColorScheme? {
switch self { case .system: nil; case .light: .light; case .dark: .dark }
}
}
enum StudioAccent: String, CaseIterable, Identifiable {
case storm = "Storm", moss = "Moss", ocean = "Ocean", dusk = "Dusk", ember = "Ember"
var id: Self { self }
var color: Color {
switch self { case .storm: .blue; case .moss: .green; case .ocean: .teal; case .dusk: .purple; case .ember: .orange }
}
}
enum StudioMode: String, CaseIterable, Identifiable {
case normal = "Normal", focus = "Focus", zen = "Zen"
var id: Self { self }
}
enum StudioFont: String, CaseIterable, Identifiable {
case system = "System", serif = "Serif", mono = "Monospaced"
var id: Self { self }
func font(size: Int) -> Font {
.system(size: CGFloat(size), design: self == .serif ? .serif : self == .mono ? .monospaced : .default)
}
func appKit(size: Int) -> NSFont {
switch self {
case .system: .systemFont(ofSize: CGFloat(size))
case .serif: NSFont(name: "Georgia", size: CGFloat(size)) ?? .systemFont(ofSize: CGFloat(size))
case .mono: .monospacedSystemFont(ofSize: CGFloat(size), weight: .regular)
}
}
}
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"),
("Toolbox", "wrench.and.screwdriver"), ("Local Tools", "terminal"), ("Runtime", "waveform.path"),
("Appearance", "paintpalette"), ("Workspace Data", "externaldrive")
]
var body: some View {
HSplitView {
List(selection: $page) {
ForEach(pages, id: \.0) { name, icon in Label(name, systemImage: icon).tag(name) }
}
.listStyle(.sidebar)
.frame(minWidth: 160, idealWidth: 180, maxWidth: 210)
Group {
switch page {
case "MLX Library": ModelCatalogView(studio: studio)
case "Generation": GenerationSettingsView()
case "Toolbox": MCPSettings(studio: studio)
case "Local Tools": LocalToolsView(studio: studio)
case "Runtime": RuntimeSettingsView(studio: studio)
case "Appearance": StudioAppearanceView()
case "Workspace Data": WorkspaceDataView(studio: studio)
default: BackendSettings(studio: studio)
}
}
.frame(minWidth: 570, maxWidth: .infinity, maxHeight: .infinity)
}
.frame(width: 780, height: 610)
}
}
struct StudioAppearanceView: View {
@AppStorage("studioTheme") private var theme = StudioTheme.system
@AppStorage("studioAccent") private var accent = StudioAccent.storm
@AppStorage("studioMode") private var mode = StudioMode.normal
@AppStorage("studioChatFont") private var font = StudioFont.system
@AppStorage("studioChatSize") private var size = 14
@AppStorage("studioCodeTheme") private var codeTheme = StudioTheme.system
@AppStorage("composerSpellCheck") private var spell = true
@AppStorage("composerAutoCorrect") private var correct = false
@State private var query = ""
var body: some View {
Form {
Section("Appearance") {
Picker("Color preference", selection: $theme) {
ForEach(StudioTheme.allCases) { Text($0.rawValue).tag($0) }
}
Picker("Workspace mode", selection: $mode) {
ForEach(StudioMode.allCases) { Text($0.rawValue).tag($0) }
}.pickerStyle(.segmented)
Picker("Accent", selection: $accent) {
ForEach(StudioAccent.allCases) { entry in
Label(entry.rawValue, systemImage: "circle.fill").foregroundStyle(entry.color).tag(entry)
}
}
Picker("Chat font", selection: $font) {
ForEach(StudioFont.allCases) { Text($0.rawValue).tag($0) }
}
Stepper(value: $size, in: 10...28) { LabeledContent("Chat font size", value: "\(size) pt") }
Picker("Code block appearance", selection: $codeTheme) {
ForEach(StudioTheme.allCases) { Text($0.rawValue).tag($0) }
}
}
Section("Composer") {
Toggle("Check spelling as you type", isOn: $spell)
Toggle("Correct spelling automatically", isOn: $correct)
}
Section("Keyboard Shortcuts") {
TextField("Find a shortcut", text: $query)
ForEach(shortcuts.filter { query.isEmpty || $0.0.localizedCaseInsensitiveContains(query) }, id: \.0) {
LabeledContent($0.0, value: $0.1)
}
}
}
.formStyle(.grouped)
}
private var shortcuts: [(String, String)] {
[("Send chat message", "Return"), ("Insert newline", "⇧ Return"), ("Open Settings", "⌘ ,"),
("Increase chat font", "⌘ ="), ("Decrease chat font", "⌘ −"), ("Reset chat font", "⌘ 0"),
("Cycle theme", "⌘ 3"), ("Cycle workspace mode", "⌘ 9")]
}
}
struct WorkspaceDataView: View {
@ObservedObject var studio: StudioModel
@AppStorage("workspaceBackupTime") private var lastBackup = 0.0
@AppStorage("workspaceBackupReminderDays") private var reminderDays = 0
@State private var restoring = false
@State private var pending: URL?
@State private var confirm = false
@State private var status = ""
var body: some View {
Form {
Section("Backup") {
LabeledContent("Last export", value: lastBackup > 0
? Date(timeIntervalSince1970: lastBackup).formatted(date: .abbreviated, time: .shortened)
: "None")
Button("Export Workspace…", action: export)
Stepper(value: $reminderDays, in: 0...30) {
LabeledContent("Remind every", value: reminderDays > 0 ? "\(reminderDays) day(s)" : "Off")
}
if reminderDays > 0 && (lastBackup == 0 || Date.now.timeIntervalSince1970 - lastBackup >= Double(reminderDays) * 86_400) {
Label("Workspace backup is due", systemImage: "exclamationmark.circle").foregroundStyle(.orange)
}
Text("Exports include chats, document indexes, stacks and saved resources.")
.foregroundStyle(.secondary)
}
Section("Storage") {
Text(StudioModel.workspaceDirectory.path).textSelection(.enabled)
Button("Reveal Workspace in Finder") { NSWorkspace.shared.activateFileViewerSelecting([StudioModel.workspaceDirectory]) }
}
Section("Restore") {
Button("Choose Backup…") { restoring = true }
.disabled(studio.running || studio.importingDocument)
if !status.isEmpty { Text(status).textSelection(.enabled).foregroundStyle(.secondary) }
}
}
.formStyle(.grouped)
.fileImporter(isPresented: $restoring, allowedContentTypes: [.data]) { result in
do { pending = try result.get(); confirm = true }
catch { status = error.localizedDescription }
}
.confirmationDialog("Replace the current workspace with this backup?", isPresented: $confirm) {
Button("Restore Workspace", role: .destructive) { restore() }
} message: {
Text("The current chats and saved resources will be replaced. Export a backup first if you need to keep them.")
}
}
private func export() {
let panel = NSSavePanel()
panel.nameFieldStringValue = "AIStudio-Workspace-\(Date.now.formatted(.iso8601.year().month().day())).sqlite"
panel.canCreateDirectories = true
panel.begin { response in
guard response == .OK, let url = panel.url else { return }
do {
try studio.exportWorkspace(to: url)
lastBackup = Date.now.timeIntervalSince1970
status = "Exported \(url.lastPathComponent)."
} catch { status = error.localizedDescription }
}
}
private func restore() {
guard let url = pending else { return }
let scoped = url.startAccessingSecurityScopedResource()
defer {
if scoped { url.stopAccessingSecurityScopedResource() }
pending = nil
}
do {
try studio.restoreWorkspace(from: url)
status = "Restored \(url.lastPathComponent)."
} catch { status = error.localizedDescription }
}
}
+10 -3
View File
@@ -143,7 +143,7 @@ enum Router {
}
}
struct ProviderMetrics: Equatable, Sendable {
struct ProviderMetrics: Codable, Equatable, Sendable {
let tokens: Int
let seconds: Double
@@ -154,14 +154,21 @@ struct ProviderMetrics: Equatable, Sendable {
}
}
struct GenerationMeasurement: Identifiable {
let id = UUID()
struct GenerationMeasurement: Codable, Identifiable {
var id = UUID()
static let key = "generationMeasurements"
let backend: String
let firstOutput: Double?
let seconds: Double
let characters: Int
let provider: ProviderMetrics?
let outcome: String
var charactersPerSecond: Double? {
guard let firstOutput, seconds > firstOutput, characters > 0 else { return nil }
let rate = Double(characters) / (seconds - firstOutput)
return rate.isFinite ? rate : nil
}
}
enum PromptMode: String, CaseIterable, Identifiable {
+53
View File
@@ -99,3 +99,56 @@ struct DocumentVector {
return Self(language: "\(language.rawValue):\(model.revision)", values: values.map { Float($0 / magnitude) })
}
}
enum WebClipCapture {
static func url(_ address: String) throws -> URL {
let input = address.trimmingCharacters(in: .whitespacesAndNewlines)
guard let parts = URLComponents(string: input), let scheme = parts.scheme?.lowercased(),
["http", "https"].contains(scheme), let host = parts.host, !host.isEmpty,
parts.user == nil, parts.password == nil, let url = parts.url else {
throw StudioError("Enter an HTTP or HTTPS page URL.")
}
return url
}
static func text(from address: String) async throws -> String {
let session = URLSession(configuration: .ephemeral)
defer { session.invalidateAndCancel() }
var request = URLRequest(url: try url(address), timeoutInterval: 20)
request.setValue("text/html, text/plain", forHTTPHeaderField: "Accept")
let (bytes, response) = try await session.bytes(for: request)
guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode),
let type = response.mimeType, ["text/html", "text/plain", "application/xhtml+xml"].contains(type) else {
throw StudioError("The server did not return a supported text page.")
}
var data = Data()
for try await byte in bytes {
try Task.checkCancellation()
guard data.count < 1_048_576 else { throw StudioError("The page exceeds the 1 MB capture limit.") }
data.append(byte)
}
guard let raw = String(data: data, encoding: .utf8) else { throw StudioError("The page is not UTF-8.") }
let content = type == "text/plain" ? raw : plainText(raw)
guard !content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw StudioError("The page contains no readable text.")
}
return String(content.prefix(12_000))
}
static func plainText(_ html: String) -> String {
html.replacingOccurrences(of: "(?is)<(script|style|head|noscript)\\b[^>]*>.*?</\\1\\s*>", with: " ",
options: .regularExpression)
.replacingOccurrences(of: "(?s)<!--.*?-->", with: " ", options: .regularExpression)
.replacingOccurrences(of: "(?i)</(?:p|div|li|section|article|h[1-6])\\s*>|<br\\s*/?>", with: "\n",
options: .regularExpression)
.replacingOccurrences(of: "<[^>]+>", with: " ", options: .regularExpression)
.replacingOccurrences(of: "&nbsp;", with: " ")
.replacingOccurrences(of: "&lt;", with: "<")
.replacingOccurrences(of: "&gt;", with: ">")
.replacingOccurrences(of: "&quot;", with: "\"")
.replacingOccurrences(of: "&amp;", with: "&")
.components(separatedBy: .newlines)
.map { $0.split(whereSeparator: \.isWhitespace).joined(separator: " ") }
.filter { !$0.isEmpty }.joined(separator: "\n")
}
}
+233 -35
View File
@@ -1,6 +1,8 @@
import Foundation
import Darwin
import SwiftUI
import AppKit
import UniformTypeIdentifiers
actor HTTPMCPClient: MCPToolClient {
private struct Connection {
@@ -19,12 +21,13 @@ actor HTTPMCPClient: MCPToolClient {
private let endpoint: URL
private let token: String
private let headers: [String: String]
private let session: URLSession
private var connection: Connection?
private static let modern = "2026-07-28"
private let versions = ["2025-11-25", "2025-06-18", "2025-03-26"]
init(endpoint: String, token: String = "") throws {
init(endpoint: String, token: String = "", headers: [String: String] = [:]) throws {
guard let parsed = URLComponents(string: endpoint.trimmingCharacters(in: .whitespacesAndNewlines)),
let host = parsed.host?.lowercased(), !host.isEmpty,
parsed.user == nil, parsed.password == nil, parsed.fragment == nil, let url = parsed.url else {
@@ -37,6 +40,13 @@ actor HTTPMCPClient: MCPToolClient {
guard !token.contains(where: \.isNewline) else { throw StudioError("The bearer token must be a single line.") }
self.endpoint = url
self.token = token
self.headers = headers
let protected = Set(["host", "content-length", "transfer-encoding", "connection", "content-type",
"accept", "mcp-protocol-version", "mcp-session-id", "mcp-method", "mcp-name"])
guard headers.allSatisfy({ name, value in
guard !name.isEmpty, !protected.contains(name.lowercased()), !value.contains(where: \.isNewline) else { return false }
return name.utf8.allSatisfy { (33...126).contains($0) && $0 != 58 }
}) else { throw StudioError("A custom MCP HTTP header has an invalid or reserved name or value.") }
let config = URLSessionConfiguration.ephemeral
config.timeoutIntervalForRequest = 30
config.timeoutIntervalForResource = 120
@@ -151,6 +161,7 @@ actor HTTPMCPClient: MCPToolClient {
request.setValue(params["name"] as? String, forHTTPHeaderField: "Mcp-Name")
}
}
for (name, value) in headers { request.setValue(value, forHTTPHeaderField: name) }
if !token.isEmpty { request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") }
let (bytes, response) = try await session.bytes(for: request)
guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
@@ -213,9 +224,18 @@ struct MCPSettings: View {
@AppStorage("mcpTransport") private var transport = "http"
@AppStorage("mcpExecutable") private var executable = ""
@AppStorage("mcpArguments") private var launchArguments = ""
@State private var client: (any MCPToolClient)?
private var client: (any MCPToolClient)? { studio.activeToolset?.client }
@State private var confirmLaunch = false
@State private var tools: [MCPTool] = []
@AppStorage("mcpConfigPath") private var configPath = ""
@AppStorage("mcpSelectedProfile") private var selectedProfile = ""
@State private var profiles: [String: MCPServerConfiguration] = [:]
@State private var importingConfig = false
@State private var configStatus = ""
private var profile: MCPServerConfiguration? { profiles[selectedProfile] }
private var local: Bool { profile.map { $0.command != nil } ?? (transport == "stdio") }
private var target: String { profile?.target ?? (local ? executable : endpoint) }
private var tools: [MCPTool] { studio.activeToolset?.tools ?? [] }
@State private var name = ""
@State private var arguments = "{}"
@State private var result = ""
@@ -226,24 +246,49 @@ struct MCPSettings: View {
var body: some View {
Form {
Section("MCP server") {
Picker("Transport", selection: $transport) {
Text("Streamable HTTP").tag("http")
Text("Local stdio").tag("stdio")
Section("Custom MCP Servers") {
HStack {
Button("Import mcp.json…") { importingConfig = true }
Button("Use LM Studio Config") {
let url = FileManager.default.homeDirectoryForCurrentUser.appending(path: ".lmstudio/mcp.json")
loadConfig(url)
}
if !configPath.isEmpty {
Button("Reload") { loadConfig(URL(fileURLWithPath: configPath)) }
Button("Edit File") { NSWorkspace.shared.open(URL(fileURLWithPath: configPath)) }
}
}
if transport == "stdio" {
TextField("Executable path", text: $executable, prompt: Text("/absolute/path/to/server"))
TextField("Arguments (one per line)", text: $launchArguments, axis: .vertical)
if !profiles.isEmpty {
Picker("Server", selection: $selectedProfile) {
Text("Manual connection").tag("")
ForEach(profiles.keys.sorted(), id: \.self) { name in Text(name).tag(name) }
}
}
if !configStatus.isEmpty { Text(configStatus).foregroundStyle(.secondary).textSelection(.enabled) }
}
Section("MCP server") {
if let profile {
LabeledContent("Transport", value: local ? "Local stdio" : "Streamable HTTP")
LabeledContent("Target", value: profile.target)
} else {
TextField("Endpoint", text: $endpoint, prompt: Text("https://server.example/mcp"))
SecureField("Bearer token (optional)", text: $token)
Picker("Transport", selection: $transport) {
Text("Streamable HTTP").tag("http")
Text("Local stdio").tag("stdio")
}
if transport == "stdio" {
TextField("Executable path", text: $executable, prompt: Text("/absolute/path/to/server"))
TextField("Arguments (one per line)", text: $launchArguments, axis: .vertical)
} else {
TextField("Endpoint", text: $endpoint, prompt: Text("https://server.example/mcp"))
SecureField("Bearer token (optional)", text: $token)
}
}
HStack {
Button(transport == "stdio" ? "Start Server and Discover…" : "Discover Tools") {
if transport == "stdio" { confirmLaunch = true }
Button(local ? "Start Server and Discover…" : "Discover Tools") {
if local { confirmLaunch = true }
else { discover() }
}
.disabled(busy || (transport == "stdio" ? executable.isEmpty : endpoint.isEmpty))
.disabled(busy || target.isEmpty)
if client != nil {
Button("Disconnect") { resetConnection() }.disabled(busy)
}
@@ -286,22 +331,48 @@ struct MCPSettings: View {
}
}
.formStyle(.grouped)
.fileImporter(isPresented: $importingConfig, allowedContentTypes: [.json]) { result in
do { loadConfig(try result.get()) }
catch { configStatus = error.localizedDescription }
}
.onAppear {
if !configPath.isEmpty { loadConfig(URL(fileURLWithPath: configPath), disconnect: false) }
if !tools.contains(where: { $0.name == name }) { name = tools.first?.name ?? "" }
}
.onChange(of: selectedProfile) { _, _ in resetConnection() }
.onChange(of: endpoint) { _, _ in resetConnection() }
.onChange(of: token) { _, _ in resetConnection() }
.onChange(of: name) { _, _ in arguments = "{}" }
.onChange(of: transport) { _, _ in resetConnection() }
.onChange(of: executable) { _, _ in resetConnection() }
.onChange(of: launchArguments) { _, _ in resetConnection() }
.onDisappear { resetConnection() }
.onDisappear { operation?.cancel() }
.confirmationDialog("Start local MCP server?", isPresented: $confirmLaunch, titleVisibility: .visible) {
Button("Start and Discover", action: discover)
} message: {
Text("Launch \(executable) with the listed arguments using your macOS account.")
Text("Launch \(target) with its configured arguments using your macOS account.")
}
.confirmationDialog("Run \(name)?", isPresented: $confirm, titleVisibility: .visible) {
Button("Run Tool", action: invoke)
} message: {
Text("Send these arguments to \(transport == "stdio" ? executable : endpoint):\n\(arguments.prefix(800))")
Text("Send these arguments to \(target):\n\(arguments.prefix(800))")
}
}
private func loadConfig(_ url: URL, disconnect: Bool = true) {
let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
do {
let file = try MCPServerConfiguration.File.read(url)
if disconnect { resetConnection() }
profiles = file.mcpServers
configPath = url.path
if profiles[selectedProfile] == nil && (disconnect || !selectedProfile.isEmpty) {
selectedProfile = profiles.keys.sorted().first ?? ""
}
configStatus = "\(profiles.count) custom server(s) loaded from \(url.lastPathComponent)."
} catch {
configStatus = "Could not read \(url.lastPathComponent): \(error.localizedDescription)"
}
}
@@ -309,7 +380,9 @@ struct MCPSettings: View {
run {
resetConnection(cancel: false)
let server: any MCPToolClient
if transport == "stdio" {
if let profile {
server = try profile.makeClient()
} else if local {
let args = launchArguments.split(whereSeparator: \.isNewline).map(String.init)
server = try StdioMCPClient(path: executable, arguments: args)
} else {
@@ -317,8 +390,8 @@ struct MCPSettings: View {
}
let discovered = try await server.listTools()
try Task.checkCancellation()
client = server
tools = discovered
studio.activeToolset = ActiveToolset(name: profile == nil ? target : selectedProfile,
client: server, tools: discovered)
name = discovered.first?.name ?? ""
result = discovered.isEmpty ? "This server has no exposed tools." : "\(discovered.count) tools discovered."
}
@@ -338,8 +411,7 @@ struct MCPSettings: View {
private func resetConnection(cancel: Bool = true) {
if cancel { operation?.cancel() }
client = nil
tools = []
studio.activeToolset = nil
name = ""
invokedTool = nil
result = ""
@@ -361,18 +433,19 @@ struct MCPSettings: View {
actor StdioMCPClient: MCPToolClient {
private let executable: URL
private let arguments: [String]
private let environment: [String: String]
private let workingDirectory: URL?
private var transport: StdioTransport?
private var ready = false
private var busy = false
private static let versions = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]
init(path: String, arguments: [String]) throws {
let expanded = (path.trimmingCharacters(in: .whitespacesAndNewlines) as NSString).expandingTildeInPath
guard expanded.hasPrefix("/"), FileManager.default.isExecutableFile(atPath: expanded) else {
throw StudioError("Choose the absolute path to a local MCP server executable.")
}
executable = URL(fileURLWithPath: expanded)
init(path: String, arguments: [String], environment: [String: String] = [:], cwd: String? = nil) throws {
let launch = try MCPServerConfiguration.resolveCommand(path, environment: environment, cwd: cwd)
executable = launch.executable
self.arguments = arguments
self.environment = launch.environment
workingDirectory = launch.workingDirectory
}
func disconnect() {
@@ -385,7 +458,7 @@ actor StdioMCPClient: MCPToolClient {
busy = true
defer { busy = false }
if !ready {
transport = try StdioTransport(executable: executable, arguments: arguments)
transport = try StdioTransport(executable: executable, arguments: arguments, environment: environment, cwd: workingDirectory)
do {
let info = try await exchange("initialize", params: [
"protocolVersion": Self.versions[0], "capabilities": [:],
@@ -466,19 +539,31 @@ private final class StdioTransport: @unchecked Sendable {
private let child = Process()
private let input: FileHandle
private let output: FileHandle
private let errorOutput: FileHandle
private let diagnostics = MCPDiagnostics()
private var buffered = Data()
private let limit = 2_000_000
init(executable: URL, arguments: [String]) throws {
init(executable: URL, arguments: [String], environment: [String: String], cwd: URL?) throws {
let source = Pipe()
let sink = Pipe()
let errors = Pipe()
errorOutput = errors.fileHandleForReading
input = source.fileHandleForWriting
output = sink.fileHandleForReading
child.executableURL = executable
child.arguments = arguments
child.environment = environment
child.currentDirectoryURL = cwd
child.standardInput = source
child.standardOutput = sink
child.standardError = FileHandle.nullDevice
child.standardError = errors
let diagnostics = diagnostics
errorOutput.readabilityHandler = { handle in
let data = handle.availableData
if data.isEmpty { handle.readabilityHandler = nil }
else { diagnostics.append(data) }
}
guard fcntl(input.fileDescriptor, F_SETNOSIGPIPE, 1) != -1,
fcntl(input.fileDescriptor, F_SETFL, O_NONBLOCK) != -1 else {
throw StudioError("Could not configure the local MCP input pipe.")
@@ -490,6 +575,7 @@ private final class StdioTransport: @unchecked Sendable {
if child.isRunning { child.terminate() }
try? input.close()
try? output.close()
errorOutput.readabilityHandler = nil
}
func exchange(_ payload: Data, id: String?) throws -> Data {
@@ -524,7 +610,7 @@ private final class StdioTransport: @unchecked Sendable {
Darwin.read(output.fileDescriptor, $0.baseAddress, $0.count)
}
if count < 0 && errno == EINTR { continue }
guard count > 0 else { throw StudioError("The local MCP server closed its output.") }
guard count > 0 else { throw diagnostics.error("The local MCP server closed its output.") }
buffered.append(contentsOf: bytes.prefix(count))
guard buffered.count <= limit else { throw StudioError("The local MCP response is too large.") }
}
@@ -538,7 +624,7 @@ private final class StdioTransport: @unchecked Sendable {
try wait(input.fileDescriptor, event: Int16(POLLOUT), until: deadline)
let count = Darwin.write(input.fileDescriptor, start.advanced(by: sent), bytes.count - sent)
if count < 0 && (errno == EINTR || errno == EAGAIN) { continue }
guard count > 0 else { throw StudioError("The local MCP server closed its input.") }
guard count > 0 else { throw diagnostics.error("The local MCP server closed its input.") }
sent += count
}
}
@@ -552,6 +638,118 @@ private final class StdioTransport: @unchecked Sendable {
if result > 0 { return }
if result < 0 && errno != EINTR { throw StudioError("An MCP pipe error occurred.") }
}
throw StudioError("The local MCP server timed out.")
throw diagnostics.error("The local MCP server timed out.")
}
}
struct MCPServerConfiguration: Decodable {
let command: String?
let args: [String]?
let env: [String: String]?
let cwd: String?
let url: String?
let headers: [String: String]?
struct File: Decodable {
let mcpServers: [String: MCPServerConfiguration]
static func read(_ url: URL) throws -> Self {
let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0
guard size <= 1_048_576 else { throw StudioError("Choose an MCP configuration under 1 MB.") }
return try JSONDecoder().decode(Self.self, from: Data(contentsOf: url))
}
}
var target: String { command ?? url ?? "Unconfigured server" }
func makeClient() throws -> any MCPToolClient {
switch (command, url) {
case (let command?, nil):
let arguments = args ?? []
let launcher = Self.projectPython(command, arguments: arguments, environment: env ?? [:]) ?? command
if let script = arguments.first(where: { $0.hasPrefix("/") && $0.hasSuffix(".py") }),
["python", "python3"].contains(URL(fileURLWithPath: command).lastPathComponent),
!FileManager.default.fileExists(atPath: script) {
throw StudioError("The configured Python script does not exist: \(script)")
}
return try StdioMCPClient(path: launcher, arguments: arguments, environment: env ?? [:], cwd: cwd)
case (nil, let url?):
return try HTTPMCPClient(endpoint: url, headers: headers ?? [:])
default:
throw StudioError("An MCP server must specify either command or url.")
}
}
static func projectPython(_ command: String, arguments: [String], environment: [String: String]) -> String? {
guard ["python", "python3"].contains(command), environment["PATH"] == nil,
let script = arguments.first(where: { $0.hasPrefix("/") && $0.hasSuffix(".py") }) else { return nil }
let folder = URL(fileURLWithPath: script).deletingLastPathComponent()
return [folder, folder.deletingLastPathComponent()]
.map { $0.appending(path: ".venv/bin/" + command).path }
.first(where: FileManager.default.isExecutableFile(atPath:))
}
static func resolveCommand(_ command: String, environment: [String: String], cwd: String?) throws
-> (executable: URL, environment: [String: String], workingDirectory: URL?) {
let command = (command.trimmingCharacters(in: .whitespacesAndNewlines) as NSString).expandingTildeInPath
guard !command.isEmpty else { throw StudioError("Enter an MCP executable or command name.") }
let manager = FileManager.default
let home = manager.homeDirectoryForCurrentUser.path
var childEnvironment = ProcessInfo.processInfo.environment.merging(environment) { _, new in new }
let common = ["/opt/homebrew/bin", "/usr/local/bin", "/Applications/ServBay/bin",
home + "/.local/bin", home + "/.cargo/bin", "/usr/bin", "/bin"]
let directories = (childEnvironment["PATH"] ?? "").split(separator: ":").map(String.init) + common
childEnvironment["PATH"] = directories.joined(separator: ":")
let folder: URL?
if let cwd {
let path = (cwd as NSString).expandingTildeInPath
var isDirectory: ObjCBool = false
guard path.hasPrefix("/"), manager.fileExists(atPath: path, isDirectory: &isDirectory), isDirectory.boolValue else {
throw StudioError("The configured MCP working directory does not exist.")
}
folder = URL(fileURLWithPath: path, isDirectory: true)
} else {
folder = nil
}
let candidates: [String]
if command.hasPrefix("/") {
candidates = [command]
} else if command.contains("/") {
candidates = folder.map { [$0.appending(path: command).path] } ?? []
} else {
let names = command == "python" ? ["python", "python3"] : [command]
candidates = names.flatMap { name in
directories.filter { $0.hasPrefix("/") }.map { URL(fileURLWithPath: $0).appending(path: name).path }
}
}
guard let path = candidates.first(where: manager.isExecutableFile(atPath:)) else {
throw StudioError("Could not find the MCP executable ‘\(command)’. Check PATH or use an absolute path.")
}
return (URL(fileURLWithPath: path), childEnvironment, folder)
}
}
private final class MCPDiagnostics: @unchecked Sendable {
private let lock = NSLock()
private var tail = Data()
func append(_ bytes: Data) {
lock.lock()
defer { lock.unlock() }
tail.append(bytes)
if tail.count > 4096 { tail = Data(tail.suffix(4096)) }
}
func error(_ message: String) -> StudioError {
lock.lock()
defer { lock.unlock() }
let context = String(decoding: tail, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
return StudioError(context.isEmpty ? message : message + "\n" + context)
}
}
struct ActiveToolset {
let name: String
let client: any MCPToolClient
let tools: [MCPTool]
}
+50
View File
@@ -1,5 +1,7 @@
import Foundation
import SwiftUI
import UniformTypeIdentifiers
import AppKit
struct CatalogModel: Identifiable, Hashable, Sendable {
let id: String
@@ -78,11 +80,40 @@ struct ModelCatalogView: View {
@AppStorage("mlxOnly") private var mlxOnly = false
@State private var operation: Task<Void, Never>?
@State private var active: CatalogModel?
@AppStorage("mlxRegisteredPaths") private var registered = Data()
@State private var pickingLibrary = false
@State private var libraryStatus = ""
private var library: [String] { (try? JSONDecoder().decode([String].self, from: registered)) ?? [] }
@State private var removing: CatalogModel?
@State private var status = ""
var body: some View {
Form {
Section("Model Library") {
Button("Register Model Folder…") { pickingLibrary = true }
.disabled(studio.running)
ForEach(library, id: \.self) { path in
HStack {
Text(URL(fileURLWithPath: path).lastPathComponent).help(path)
Spacer()
Button(mlxPath == path && mlxOnly ? "Selected" : "Use Model") {
mlxPath = path
mlxOnly = true
studio.unloadMLX()
}
.disabled(studio.running || !MLXLibrary.isModel(at: URL(fileURLWithPath: path)) ||
(mlxPath == path && mlxOnly))
Button("Reveal") {
NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
}
Button("Unregister") {
registered = (try? JSONEncoder().encode(library.filter { $0 != path })) ?? Data()
}.disabled(studio.running)
}
}
if !libraryStatus.isEmpty { Text(libraryStatus).foregroundStyle(.secondary) }
}
Section("Download for on-device inference") {
ForEach(CatalogModel.all) { model in
let installed = model.installed(at: model.localFolder)
@@ -122,6 +153,18 @@ struct ModelCatalogView: View {
}
}
.formStyle(.grouped)
.fileImporter(isPresented: $pickingLibrary, allowedContentTypes: [.folder]) { result in
do {
let url = try result.get().resolvingSymlinksInPath()
guard MLXLibrary.isModel(at: url) else {
throw StudioError("Choose an MLX folder with config.json and safetensors weights.")
}
if !library.contains(url.path) {
registered = try JSONEncoder().encode(library + [url.path])
}
libraryStatus = "Registered \(url.lastPathComponent)."
} catch { libraryStatus = error.localizedDescription }
}
.confirmationDialog("Remove downloaded model?", isPresented: Binding(
get: { removing != nil }, set: { if !$0 { removing = nil } }
), titleVisibility: .visible, presenting: removing) { model in
@@ -157,3 +200,10 @@ struct ModelCatalogView: View {
} catch { status = error.localizedDescription }
}
}
enum MLXLibrary {
static func isModel(at url: URL) -> Bool {
FileManager.default.fileExists(atPath: url.appending(path: "config.json").path) &&
((try? MLXRuntimeLimits.weightBytes(in: url)) ?? 0) > 0
}
}
+5
View File
@@ -285,8 +285,10 @@ struct CompatibleEndpoint: InferenceProvider {
let delta: Piece?
let finish_reason: String?
}
struct Usage: Decodable { let completion_tokens: Int? }
let error: Failure?
let choices: [Choice]?
let usage: Usage?
}
func models() async throws -> [String] {
@@ -317,6 +319,9 @@ struct CompatibleEndpoint: InferenceProvider {
if payload.isEmpty { continue }
let frame = try JSONDecoder().decode(Frame.self, from: Data(payload.utf8))
if let error = frame.error { throw StudioError(error.message) }
if let tokens = frame.usage?.completion_tokens, tokens >= 0 {
continuation.yield(.metrics(ProviderMetrics(tokens: tokens, seconds: 0)))
}
guard let choice = frame.choices?.first else { continue }
if choice.finish_reason == "tool_calls" || !(choice.delta?.tool_calls ?? []).isEmpty {
continuation.yield(.committed)
+101 -3
View File
@@ -6,6 +6,22 @@ struct Conversation: Identifiable {
let title: String
}
struct WorkspaceSnippet: Identifiable {
enum Kind: String, CaseIterable, Identifiable {
case skill = "Skill"
case context = "Context"
case prompt = "Prompt"
case webClip = "Web Clip"
var id: Self { self }
}
let id: UUID
let kind: Kind
let title: String
let content: String
}
final class Store {
private let db: OpaquePointer
private let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
@@ -24,6 +40,12 @@ final class Store {
CREATE TABLE IF NOT EXISTS chats(
id TEXT PRIMARY KEY, title TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS knowledge_stacks(
id TEXT PRIMARY KEY REFERENCES chats(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS workspace_snippets(
id TEXT PRIMARY KEY, kind TEXT NOT NULL, title TEXT NOT NULL, content TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS messages(
id TEXT PRIMARY KEY, chat TEXT NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
role TEXT NOT NULL, content TEXT NOT NULL, thinking TEXT NOT NULL, backend TEXT NOT NULL
@@ -50,7 +72,7 @@ final class Store {
deinit { sqlite3_close(db) }
func conversations() throws -> [Conversation] {
try query("SELECT id,title FROM chats ORDER BY rowid DESC") {
try query("SELECT id,title FROM chats WHERE id NOT IN (SELECT id FROM knowledge_stacks) ORDER BY rowid DESC") {
Conversation(id: try uuid($0, 0), title: string($0, 1))
}
}
@@ -60,8 +82,10 @@ final class Store {
guard !term.isEmpty else { return try conversations() }
return try query("""
SELECT c.id, c.title FROM chats c
WHERE instr(lower(c.title), lower(?)) > 0 OR EXISTS (
SELECT 1 FROM messages m WHERE m.chat=c.id AND instr(lower(m.content), lower(?)) > 0
WHERE c.id NOT IN (SELECT id FROM knowledge_stacks) AND (
instr(lower(c.title), lower(?)) > 0 OR EXISTS (
SELECT 1 FROM messages m WHERE m.chat=c.id AND instr(lower(m.content), lower(?)) > 0
)
)
ORDER BY c.rowid DESC
""", [term, term]) {
@@ -69,6 +93,45 @@ final class Store {
}
}
func knowledgeStacks() throws -> [Conversation] {
try query("SELECT c.id,c.title FROM chats c JOIN knowledge_stacks s ON s.id=c.id ORDER BY c.rowid DESC") {
Conversation(id: try uuid($0, 0), title: string($0, 1))
}
}
func createKnowledgeStack(title: String) throws -> Conversation {
try execute("BEGIN IMMEDIATE")
do {
let entry = try create(title: title)
try mutate("INSERT INTO knowledge_stacks(id) VALUES(?)", [entry.id.uuidString])
try execute("COMMIT")
return entry
} catch {
try? execute("ROLLBACK")
throw error
}
}
func snippets() throws -> [WorkspaceSnippet] {
try query("SELECT id,kind,title,content FROM workspace_snippets ORDER BY rowid DESC") {
guard let kind = WorkspaceSnippet.Kind(rawValue: string($0, 1)) else {
throw StudioError("Invalid workspace resource.")
}
return WorkspaceSnippet(id: try uuid($0, 0), kind: kind, title: string($0, 2), content: string($0, 3))
}
}
func saveSnippet(id: UUID, kind: WorkspaceSnippet.Kind, title: String, content: String) throws {
try mutate("""
INSERT INTO workspace_snippets(id,kind,title,content) VALUES(?,?,?,?)
ON CONFLICT(id) DO UPDATE SET kind=excluded.kind, title=excluded.title, content=excluded.content
""", [id.uuidString, kind.rawValue, title, content])
}
func deleteSnippet(_ id: UUID) throws {
try mutate("DELETE FROM workspace_snippets WHERE id=?", [id.uuidString])
}
func rename(_ id: UUID, title: String) throws {
try mutate("UPDATE chats SET title=? WHERE id=?", [title, id.uuidString])
}
@@ -180,6 +243,41 @@ final class Store {
return excerpts
}
func exportWorkspace(to url: URL) throws {
guard !FileManager.default.fileExists(atPath: url.path) else {
throw StudioError("Choose a new filename for the workspace backup.")
}
try mutate("VACUUM INTO ?", [url.path])
}
func restoreWorkspace(from url: URL) throws {
var input: OpaquePointer?
let opened = sqlite3_open_v2(url.path, &input, SQLITE_OPEN_READONLY, nil)
guard opened == SQLITE_OK, let input else {
if let input { sqlite3_close(input) }
throw StudioError("The workspace backup could not be opened.")
}
defer { sqlite3_close(input) }
let check = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name IN ('chats','messages','documents','workspace_snippets','knowledge_stacks')"
var prepared: OpaquePointer?
guard sqlite3_prepare_v2(input, check, -1, &prepared, nil) == SQLITE_OK, let prepared else {
throw StudioError("The selected file is not an AI Studio workspace backup.")
}
let valid = sqlite3_step(prepared) == SQLITE_ROW && sqlite3_column_int(prepared, 0) == 5
sqlite3_finalize(prepared)
guard valid else { throw StudioError("The selected file is not an AI Studio workspace backup.") }
var checkHandle: OpaquePointer?
guard sqlite3_prepare_v2(input, "PRAGMA quick_check", -1, &checkHandle, nil) == SQLITE_OK,
let integrity = checkHandle else { throw StudioError("Could not verify backup integrity.") }
let healthy = sqlite3_step(integrity) == SQLITE_ROW && string(integrity, 0) == "ok"
sqlite3_finalize(integrity)
guard healthy else { throw StudioError("The selected backup did not pass SQLite integrity checks.") }
guard let backup = sqlite3_backup_init(db, "main", input, "main") else { throw failure }
let step = sqlite3_backup_step(backup, -1)
let finish = sqlite3_backup_finish(backup)
guard step == SQLITE_DONE, finish == SQLITE_OK else { throw failure }
}
private func execute(_ sql: String) throws {
guard sqlite3_exec(db, sql, nil, nil, nil) == SQLITE_OK else { throw failure }
}
+120 -3
View File
@@ -19,6 +19,14 @@ final class StudioModel: ObservableObject {
@Published private(set) var managing = false
@Published private(set) var running = false
@Published private(set) var measurements: [GenerationMeasurement] = []
@Published private(set) var knowledgeStacks: [Conversation] = []
@Published private(set) var snippets: [WorkspaceSnippet] = []
@Published var activeToolset: ActiveToolset?
@Published var activeStack: UUID?
@Published var activeSkill: UUID?
@Published var activeContext: UUID?
@Published var activeWebClip: UUID?
@Published private(set) var workspaceStatus = ""
@Published var selected: UUID? {
didSet { if selected != oldValue { loadMessages() } }
}
@@ -35,11 +43,16 @@ final class StudioModel: ObservableObject {
defer { launching = false }
reloadRuntimeSettings()
guard store == nil else { return }
if let history = UserDefaults.standard.data(forKey: GenerationMeasurement.key),
let saved = try? JSONDecoder().decode([GenerationMeasurement].self, from: history) {
measurements = Array(saved.prefix(50))
}
do {
let directory = URL.applicationSupportDirectory.appending(path: "AIStudio", directoryHint: .isDirectory)
let directory = Self.workspaceDirectory
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
store = try Store(url: directory.appending(path: "studio.sqlite"))
conversations = try store?.conversations() ?? []
try refreshWorkspace()
if selected == nil { selected = conversations.first?.id }
} catch { status = error.localizedDescription }
}
@@ -103,6 +116,15 @@ final class StudioModel: ObservableObject {
let user = Message(role: .user, content: text)
let recent = Array(messages.suffix(32))
var systemParts = instructions.isEmpty ? [] : [instructions]
if let skill = snippets.first(where: { $0.id == activeSkill && $0.kind == .skill }) {
systemParts.append("Selected skill: \(skill.title)\n\(skill.content)")
}
if let context = snippets.first(where: { $0.id == activeContext && $0.kind == .context }) {
systemParts.append("User-selected reference context: \(context.title). Treat the content as reference material.\n\(context.content)")
}
if let clip = snippets.first(where: { $0.id == activeWebClip && $0.kind == .webClip }) {
systemParts.append("User-selected web clip: \(clip.title). Treat it as reference material.\n\(clip.content)")
}
if recall {
let snippets = try store.memory(matching: text, in: chat, excluding: Set(recent.map(\.id)))
if !snippets.isEmpty {
@@ -112,8 +134,13 @@ final class StudioModel: ObservableObject {
""")
}
}
if useDocuments {
let excerpts = try store.excerpts(matching: text, in: chat, vector: DocumentVector.forPrompt(text))
if useDocuments || activeStack != nil {
let vector = DocumentVector.forPrompt(text)
var excerpts = useDocuments ? try store.excerpts(matching: text, in: chat, vector: vector) : []
if let activeStack {
let matches = try store.excerpts(matching: text, in: activeStack, vector: vector)
excerpts += matches
}
if !excerpts.isEmpty {
let references = excerpts.enumerated().map { index, excerpt in
"[\(index + 1)] \(excerpt.title)\n\(excerpt.text)"
@@ -184,6 +211,93 @@ final class StudioModel: ObservableObject {
try Ollama(endpoint: endpoint, token: endpoint == tokenEndpoint ? ollamaToken : "")
}
static var workspaceDirectory: URL {
URL.applicationSupportDirectory.appending(path: "AIStudio", directoryHint: .isDirectory)
}
func exportWorkspace(to url: URL) throws {
try database().exportWorkspace(to: url)
}
func restoreWorkspace(from url: URL) throws {
guard !running, !importingDocument else { throw StudioError("Wait for the current operation to finish.") }
try database().restoreWorkspace(from: url)
conversations = try database().conversations()
try refreshWorkspace()
selected = nil
selected = conversations.first?.id
activeStack = nil
activeSkill = nil
activeContext = nil
activeWebClip = nil
}
func refreshWorkspace() throws {
let store = try database()
knowledgeStacks = try store.knowledgeStacks()
snippets = try store.snippets()
}
func createStack(_ title: String) -> UUID? {
do {
let stack = try database().createKnowledgeStack(title: String(title.prefix(100)))
try refreshWorkspace()
workspaceStatus = ""
return stack.id
} catch { workspaceStatus = error.localizedDescription; return nil }
}
func stackDocuments(_ id: UUID) -> [LibraryDocument] {
(try? store?.documents(in: id)) ?? []
}
func deleteStack(_ id: UUID) {
do {
try database().delete(id)
if activeStack == id { activeStack = nil }
try refreshWorkspace()
workspaceStatus = ""
} catch { workspaceStatus = error.localizedDescription }
}
func deleteStackDocument(_ document: LibraryDocument, in id: UUID) {
do {
try database().deleteDocument(document.id, in: id)
workspaceStatus = ""
} catch { workspaceStatus = error.localizedDescription }
}
func importStackDocument(_ url: URL, in id: UUID) async {
do {
let (chunks, vectors) = try await Task.detached(priority: .userInitiated) {
let chunks = try LibraryImport.chunks(at: url)
return (chunks, DocumentVector.forChunks(chunks))
}.value
try Task.checkCancellation()
try database().addDocument(title: url.lastPathComponent, chunks: chunks, vectors: vectors, in: id)
workspaceStatus = ""
} catch { workspaceStatus = error.localizedDescription }
}
func saveSnippet(id: UUID, kind: WorkspaceSnippet.Kind, title: String, content: String) {
do {
try database().saveSnippet(id: id, kind: kind, title: String(title.prefix(100)), content: String(content.prefix(12000)))
try refreshWorkspace()
workspaceStatus = ""
} catch { workspaceStatus = error.localizedDescription }
}
func removeSnippet(_ id: UUID) {
do {
try database().deleteSnippet(id)
if activeSkill == id { activeSkill = nil }
if activeContext == id { activeContext = nil }
if activeWebClip == id { activeWebClip = nil }
try refreshWorkspace()
workspaceStatus = ""
} catch { workspaceStatus = error.localizedDescription }
}
func importDocument(_ url: URL) async {
guard !importingDocument, let chat = selected else { return }
importingDocument = true
@@ -318,6 +432,9 @@ final class StudioModel: ObservableObject {
provider: provider, outcome: Task.isCancelled ? "Stopped" : (status.isEmpty ? "Complete" : "Failed")
), at: 0)
if measurements.count > 50 { measurements.removeLast() }
if let history = try? JSONEncoder().encode(measurements) {
UserDefaults.standard.set(history, forKey: GenerationMeasurement.key)
}
if var reply = partial, !reply.content.isEmpty || !reply.thinking.isEmpty {
if !status.isEmpty { reply.backend += " · Interrupted" }
do {