Files
ai_studio/Sources/AIStudioApp.swift
T
2026-11-18 08:48:24 +00:00

3519 lines
156 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import SwiftUI
import AppKit
import Charts
import UniformTypeIdentifiers
import WebKit
import JavaScriptCore
@main
enum StudioEntryPoint {
@MainActor static func main() {
let arguments = CommandLine.arguments
if arguments.count == 3, arguments[1] == "--javascript-sandbox" {
exit(JavaScriptSandbox.evaluate(arguments[2]))
}
AIStudioApp.main()
}
}
struct AIStudioApp: App {
@StateObject private var studio = StudioModel()
@AppStorage("studioCustomThemes") private var customThemesData = Data()
@AppStorage("studioCustomThemeID") private var customThemeID = ""
@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
@AppStorage("studioShortcutKeys") private var shortcutData = Data()
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)
.preferredColorScheme(theme.colorScheme)
.tint(StudioCustomTheme.selected(customThemeID, in: customThemesData)?.accentColor ?? accent.color)
.task {
await Task.yield()
studio.open()
}
}
.defaultSize(width: 1000, height: 700)
.commands {
CommandMenu("Appearance") {
Button("Increase Chat Font Size") { chatSize = min(28, chatSize + 1) }.keyboardShortcut(StudioShortcut.increase.shortcut(in: shortcutData))
Button("Decrease Chat Font Size") { chatSize = max(10, chatSize - 1) }.keyboardShortcut(StudioShortcut.decrease.shortcut(in: shortcutData))
Button("Reset Chat Font Size") { chatSize = 14 }.keyboardShortcut(StudioShortcut.reset.shortcut(in: shortcutData))
Button("Cycle Theme") { theme = nextValue(theme) }.keyboardShortcut(StudioShortcut.theme.shortcut(in: shortcutData))
Button("Cycle Workspace Mode") { mode = nextValue(mode) }.keyboardShortcut(StudioShortcut.workspaceMode.shortcut(in: shortcutData))
}
}
Settings {
StudioSettingsView(studio: studio)
.preferredColorScheme(theme.colorScheme)
.tint(StudioCustomTheme.selected(customThemeID, in: customThemesData)?.accentColor ?? 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]
}
}
struct ChatView: View {
@ObservedObject var studio: StudioModel
@AppStorage("endpoint") private var endpoint = "http://127.0.0.1:11434"
@AppStorage("ollamaModel") private var model = ""
@AppStorage("agentWorkflowEnabled") private var agentWorkflowEnabled = false
@AppStorage("agentMCPEnabled") private var agentMCPEnabled = false
@AppStorage("agentPlannerEnabled") private var agentPlannerEnabled = true
@AppStorage("agentSpecialistEnabled") private var agentSpecialistEnabled = true
@AppStorage(AgentProfile.storageKey) private var agentProfiles = Data()
@AppStorage(AgentProfile.overridesKey) private var builtInAgents = Data()
private var selectedAgents: [AgentRole] {
guard agentWorkflowEnabled else { return [] }
let custom = AgentProfile.read(agentProfiles).filter(\.enabled).prefix(AgentProfile.limit).map(AgentRole.custom)
let builtIns: [AgentRole] = (agentPlannerEnabled ? [.planner] : []) + (agentSpecialistEnabled ? [.specialist] : [])
return builtIns.map { $0.applyingOverrides(builtInAgents) } + custom +
[AgentRole.reviewer.applyingOverrides(builtInAgents)]
}
@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("chatRAGEnabled") private var ragEnabled = true
@AppStorage("lmStudioPluginEndpoint") private var pluginEndpoint = ""
@AppStorage("lmStudioPluginIDs") private var pluginIDs = ""
@AppStorage("lmStudioPluginsEnabled") private var pluginsEnabled = false
@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 showingComparison = false
@State private var comparisonChat: UUID?
@StateObject private var splitStudio = StudioModel()
@State private var showingWorkspace = false
@State private var showingToolbox = false
@AppStorage("chatDebugOutput") private var showDebugOutput = false
@AppStorage("composerSpellCheck") private var spellCheck = true
@AppStorage("composerAutoCorrect") private var autoCorrect = false
@AppStorage("studioChatSize") private var chatSize = 14
@AppStorage("studioCustomThemes") private var customThemesData = Data()
@AppStorage("studioCustomThemeID") private var customThemeID = ""
@AppStorage("studioPalette") private var palette = StudioPalette.system
@Environment(\.colorScheme) private var colorScheme
@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 chatToDelete: Conversation?
@State private var toolboxSection = ToolboxSheet.Section.servers
@State private var search = ""
@State private var renaming = false
@State private var newTitle = ""
@AppStorage(ChatModelChoice.settingsKey) private var chatModelData = Data()
@AppStorage("mlxRegisteredPaths") private var registeredMLX = Data()
@AppStorage("managedMLXModels") private var managedMLX = Data()
private var defaultChatModel: ChatModelChoice {
if mlxOnly { return ChatModelChoice(backend: .mlx, model: mlxPath) }
if compatibleEnabled { return ChatModelChoice(backend: .compatible, model: compatibleModel) }
return ChatModelChoice(backend: .ollama, model: model)
}
private var chatChoices: [UUID: ChatModelChoice] { ChatModelChoice.read(chatModelData) }
private var chatModel: ChatModelChoice { modelForChat(studio.selected) }
private var backendName: String { chatModel.backend.rawValue }
private func modelForChat(_ id: UUID?) -> ChatModelChoice {
id.flatMap { chatChoices[$0] } ?? defaultChatModel
}
private func setChatModel(_ choice: ChatModelChoice?, for id: UUID?) {
var target = id
if target == nil && choice != nil {
studio.newChat()
target = studio.selected
}
guard let target else { return }
var choices = chatChoices
choices[target] = choice
if let data = try? JSONEncoder().encode(choices) { chatModelData = data }
}
private var mlxChoices: [String] {
let registered = (try? JSONDecoder().decode([String].self, from: registeredMLX)) ?? []
let managed = (try? JSONDecoder().decode([CatalogModel].self, from: managedMLX)) ?? []
let paths = (managed + CatalogModel.all).map { $0.localFolder.path } + registered + [mlxPath]
let installed = paths.filter { !$0.isEmpty && MLXLibrary.isModel(at: URL(fileURLWithPath: $0)) }
return Array(Set(installed)).sorted { $0.localizedStandardCompare($1) == .orderedAscending }
}
private func modelPicker(for id: UUID?, running: Bool) -> some View {
ChatModelPicker(studio: studio, choice: modelForChat(id), defaultChoice: defaultChatModel,
hasOverride: id.flatMap { chatChoices[$0] } != nil,
endpoint: endpoint, ollamaDefault: model, mlxPaths: { mlxChoices },
compatibleEndpoint: compatibleEndpoint, compatibleDefault: compatibleModel,
select: { setChatModel($0, for: id) })
.disabled(running)
}
private var visibleChats: [Conversation] {
search.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
? studio.conversations : studio.searchConversations(search)
}
@State private var showingLibrary = false
@AppStorage("documentExcerptOptOuts") private var documentExcerptOptOuts = Data()
private var documentOptOuts: Set<UUID> {
(try? JSONDecoder().decode(Set<UUID>.self, from: documentExcerptOptOuts)) ?? []
}
private func includesDocuments(_ target: StudioModel) -> Bool {
guard let id = target.selected else { return false }
return !target.documents.isEmpty && !documentOptOuts.contains(id)
}
private var documentExcerptsEnabled: Binding<Bool> {
Binding(get: { includesDocuments(studio) }, set: { enabled in
guard let id = studio.selected else { return }
var next = documentOptOuts
if enabled { next.remove(id) } else { next.insert(id) }
if let data = try? JSONEncoder().encode(next) { documentExcerptOptOuts = data }
})
}
@State private var pendingWrite: ChatFileRequest.Write?
@State private var writeDestination: URL?
@State private var confirmFileWrite = false
@State private var replacingFile = false
@AppStorage("chatFileAccessFolder") private var chatFileScope = ""
@AppStorage("chatFileWriteEnabled") private var chatFileWriteEnabled = false
@State private var filePreview: ChatFilePreview?
@State private var preparingFilePreview = false
@State private var fileError = ""
var body: some View {
NavigationSplitView(columnVisibility: $columns) {
List(visibleChats, selection: $studio.selected) { chat in
Label(chat.title, systemImage: "bubble.left").tag(chat.id)
.contextMenu {
Button("Delete Chat", systemImage: "trash", role: .destructive) {
chatToDelete = chat
confirmDelete = true
}
}
}
.searchable(text: $search, placement: .sidebar, prompt: "Search Chats")
.disabled(studio.running || splitStudio.running)
.navigationSplitViewColumnWidth(min: 180, ideal: 235)
.toolbar {
Button("New Chat", systemImage: "square.and.pencil") {
search = ""
studio.newChat()
}
.disabled(studio.running || splitStudio.running)
Button("Rename Chat", systemImage: "pencil") {
newTitle = studio.conversations.first(where: { $0.id == studio.selected })?.title ?? ""
renaming = true
}
.disabled(studio.running || splitStudio.running || studio.selected == nil)
Button("Delete Chat", systemImage: "trash") {
chatToDelete = studio.conversations.first { $0.id == studio.selected }
confirmDelete = chatToDelete != nil
}
.disabled(studio.running || splitStudio.running || studio.selected == nil)
}
} detail: {
VStack(spacing: 0) {
if showingComparison {
HSplitView {
currentTranscript.frame(minWidth: 280)
comparisonTranscript.frame(minWidth: 260)
}
} else {
currentTranscript
}
Divider()
composer
}
.background(StudioCustomTheme.selected(customThemeID, in: customThemesData)?.surface(dark: colorScheme == .dark) ?? palette.surface(dark: colorScheme == .dark))
.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("Workspace", systemImage: "square.stack.3d.up") { showingWorkspace = true }
Button("Compare Chats", systemImage: "rectangle.split.2x1") {
showingComparison.toggle()
if showingComparison {
splitStudio.open()
comparisonChat = studio.conversations.first { $0.id != studio.selected }?.id
splitStudio.selected = comparisonChat
}
}
.disabled(splitStudio.running || (studio.conversations.count < 2 && !showingComparison))
Button("Performance", systemImage: "chart.xyaxis.line") { showingPerformance = true }
}
}
.toolbar(mode == .zen ? .hidden : .visible, for: .windowToolbar)
.onChange(of: mode, initial: true) { _, value in columns = value == .normal ? .all : .detailOnly }
.sheet(item: Binding(
get: { studio.agentToolApproval },
set: { approval in
if approval == nil, let current = studio.agentToolApproval {
studio.resolveAgentTool(current.id, approved: false)
}
}
)) { approval in
AgentToolApprovalView(approval: approval) { studio.resolveAgentTool(approval.id, approved: $0) }
}
.sheet(isPresented: $showingLibrary) { DocumentLibraryView(studio: studio) }
.sheet(isPresented: $showingPerformance) { PerformanceDashboard(studio: studio) }
.sheet(isPresented: $showingWorkspace) { WorkspaceResourcesView(studio: studio) }
.sheet(item: $filePreview) { preview in
VStack(alignment: .leading, spacing: 12) {
Text(preview.name).font(.headline)
ScrollView {
if let data = preview.imagePNG, let image = NSImage(data: data) {
Image(nsImage: image).resizable().scaledToFit()
.frame(maxWidth: 520, maxHeight: 260)
.accessibilityLabel("Attachment preview")
}
if preview.imagePNG == nil || chatModel.backend == .mlx {
Text(preview.text.isEmpty && preview.imagePNG != nil
? "No readable text detected. Choose a vision-capable model to analyze this image."
: preview.text)
.textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)
}
}
HStack {
Spacer()
Button("Cancel") { filePreview = nil }.keyboardShortcut(.cancelAction)
Button("Attach to Next Message") {
studio.attachToolResult(name: preview.name, output: preview.text,
isDocument: true, isPDF: preview.isPDF, imagePNG: preview.imagePNG)
filePreview = nil
}.keyboardShortcut(.defaultAction)
}
}.padding().frame(width: 560, height: 360)
}
.sheet(isPresented: $showingToolbox) {
ToolboxSheet(studio: studio, section: $toolboxSection).frame(width: 880, height: 620)
}
.sheet(isPresented: $showingPromptBuilder) {
PromptBuilder(customPrompt: $customPrompt) { instructions, global in
if global {
customPrompt = instructions
promptMode = .custom
} else {
studio.prompt = instructions
}
}
}
.onChange(of: studio.modelSelectionRevision) {
let defaults = UserDefaults.standard
mlxPath = defaults.string(forKey: "mlxPath") ?? ""
model = defaults.string(forKey: "ollamaModel") ?? ""
mlxOnly = defaults.bool(forKey: "mlxOnly")
compatibleEnabled = defaults.bool(forKey: "compatibleEnabled")
}
.onChange(of: studio.selected) { old, _ in
if old != nil {
studio.activeStack = nil
studio.activeRemoteStack = .automatic
studio.activeSkill = nil
studio.activePrompt = nil
studio.activeContext = nil
studio.activeWebClip = nil
}
}
.alert("Rename Chat", isPresented: $renaming) {
TextField("Title", text: $newTitle)
Button("Rename") { studio.renameSelectedChat(newTitle) }
Button("Cancel", role: .cancel) {}
}
.alert("Save File?", isPresented: $confirmFileWrite, presenting: writeDestination) { destination in
Button(replacingFile ? "Replace File" : "Save File") {
guard let pendingWrite, chatFileWriteEnabled else { return }
do {
let current = try ChatFileRequest.destination(pendingWrite.path, inside: chatFileScope)
guard current == destination else { throw StudioError("The destination changed. Review the command again.") }
_ = try ChatFileRequest.write(pendingWrite, inside: chatFileScope, replace: replacingFile)
fileError = "Saved \(destination.path)"
studio.prompt = ""
} catch { fileError = error.localizedDescription }
self.pendingWrite = nil
}
Button("Cancel", role: .cancel) { pendingWrite = nil }
} message: { destination in
Text(destination.path)
}
.alert("Delete Chat?", isPresented: $confirmDelete, presenting: chatToDelete) { chat in
Button("Delete", role: .destructive) {
studio.deleteChat(chat.id)
if !studio.conversations.contains(where: { $0.id == chat.id }) { setChatModel(nil, for: chat.id) }
}
Button("Cancel", role: .cancel) {}
} message: { chat in
Text("“\(chat.title)” and its messages will be permanently deleted.")
}
}
@ViewBuilder private var currentTranscript: some View {
if studio.messages.isEmpty && studio.partial == nil {
StudioWelcome(loading: false)
} else {
transcript
}
}
private var comparisonTranscript: some View {
VStack(spacing: 0) {
Picker("Compare with", selection: $comparisonChat) {
Text("Choose a conversation").tag(Optional<UUID>.none)
ForEach(studio.conversations.filter { $0.id != studio.selected }) { chat in
Text(chat.title).tag(Optional(chat.id))
}
}
.padding(10)
.disabled(splitStudio.running)
.onChange(of: comparisonChat) { _, value in
if splitStudio.selected != value { splitStudio.activeRemoteStack = .automatic }
splitStudio.selected = value
splitStudio.prompt = ""
}
Divider()
if let comparisonChat, comparisonChat != studio.selected,
studio.conversations.contains(where: { $0.id == comparisonChat }) {
ScrollView {
LazyVStack(alignment: .leading, spacing: 12) {
ForEach(splitStudio.messages) { MessageView(message: $0) }
if let partial = splitStudio.partial { MessageView(message: partial, streaming: true) }
if showDebugOutput { ChatDebugOutput(studio: splitStudio) }
}.padding(12)
}
.font(chatFont.font(size: chatSize))
Divider()
VStack(alignment: .leading, spacing: 6) {
let feedback = [showDebugOutput ? "" : splitStudio.webStatus, splitStudio.status]
.filter { !$0.isEmpty }.joined(separator: " · ")
if !feedback.isEmpty { Text(feedback).font(.caption).foregroundStyle(.secondary) }
ChatComposerInput(text: $splitStudio.prompt, canSend: !splitStudio.running, spellCheck: spellCheck,
autoCorrect: autoCorrect, font: chatFont.appKit(size: chatSize), send: sendSplitMessage)
.frame(height: 54)
HStack {
resourceMenu(for: splitStudio)
modelPicker(for: splitStudio.selected, running: splitStudio.running)
if let role = splitStudio.agentStage {
Label(role.name, systemImage: "person.2").font(.caption)
}
Spacer()
if splitStudio.running {
Button("Stop", systemImage: "stop.fill") { splitStudio.stop() }
} else {
Button("Send", systemImage: "arrow.up", action: sendSplitMessage)
.disabled(splitStudio.prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
}
}
}
.padding(10)
} else {
ContentUnavailableView("Choose a conversation", systemImage: "rectangle.split.2x1")
}
}
.onChange(of: studio.selected) {
if comparisonChat == studio.selected {
comparisonChat = studio.conversations.first { $0.id != studio.selected }?.id
}
}
}
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) }
if showDebugOutput { ChatDebugOutput(studio: studio) }
Color.clear.frame(height: 1).id("end")
}
.frame(maxWidth: 800)
.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) }
.onChange(of: showDebugOutput) { _, enabled in
if enabled { proxy.scrollTo("end", anchor: .bottom) }
}
}
}
private var composer: some View {
VStack(alignment: .leading, spacing: 8) {
if ragEnabled && !studio.documents.isEmpty {
Toggle(chatModel.backend == .mlx ? "Include matching document excerpts" :
"Send matching document excerpts to \(backendName)", isOn: documentExcerptsEnabled)
.font(.caption)
.disabled(studio.running)
}
if let attachment = studio.toolAttachment {
HStack {
Label("\(attachment.name) attached to next message", systemImage: "paperclip")
if attachment.imagePNG != nil && chatModel.backend == .mlx {
Text("Extracted text only").foregroundStyle(.secondary)
}
if chatModel.backend != .mlx { Text("Sent to \(backendName)").foregroundStyle(.secondary) }
Spacer()
Button("Remove", systemImage: "xmark.circle") { studio.removeToolAttachment() }
}
.font(.caption)
}
let activity = [preparingFilePreview ? "Preparing attachment preview…" : fileError,
showDebugOutput ? "" : studio.webStatus, studio.status].filter { !$0.isEmpty }
if !activity.isEmpty {
Text(activity.joined(separator: " · "))
.font(.caption).foregroundStyle(.secondary).lineLimit(2).textSelection(.enabled)
}
if let link = studio.webSearchLink {
Link("Open in Browser", destination: link).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))
HStack {
Menu {
Toggle("Show Debug Output", isOn: $showDebugOutput)
} label: {
Label("Chat Diagnostics", systemImage: "ladybug")
}
.labelStyle(.iconOnly)
.fixedSize()
Button("Attach Files", systemImage: "paperclip", action: pickLocalFile)
.labelStyle(.iconOnly).buttonStyle(.bordered)
.help("Attach an image, PDF, text file, or folder listing")
.disabled(studio.running || preparingFilePreview)
Button("Web Search", systemImage: "magnifyingglass") {
toolboxSection = .search
showingToolbox = true
}
.labelStyle(.iconOnly).buttonStyle(.bordered).help("Web Search")
Button("Retrieve Page", systemImage: "link") {
toolboxSection = .retrieve
showingToolbox = true
}
.labelStyle(.iconOnly).buttonStyle(.bordered).help("Retrieve Page")
Button {
toolboxSection = .servers
showingToolbox = true
} label: {
let count = studio.activeToolsets.count
Label(count == 0 ? "Tools" : "Tools \(count)", systemImage: "wrench.and.screwdriver")
}
.buttonStyle(.bordered)
.help(studio.activeToolsets.map { $0.toolset.name }.joined(separator: ", "))
resourceMenu(for: studio)
Toggle("RAG", isOn: $ragEnabled)
.toggleStyle(.button)
.help("Retrieve matching documents and knowledge stack content")
Spacer()
}
HStack(spacing: 10) {
modelPicker(for: studio.selected, running: studio.running)
Spacer()
if chatModel.backend == .ollama || (chatModel.backend == .mlx && MLXThinking.supports(chatModel.model)) {
let modes: [Thinking] = chatModel.backend == .mlx ? [.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)
}
Toggle("Agents", isOn: $agentWorkflowEnabled)
.toggleStyle(.checkbox)
.fixedSize()
.disabled(studio.running)
if let role = studio.agentStage {
Label(role.name, systemImage: "person.2")
.font(.caption)
.help(studio.agentSteps.joined(separator: "\n"))
}
if studio.running {
Button("Stop", systemImage: "stop.fill") { studio.stop() }
} else {
Button("Send", systemImage: "arrow.up", action: sendMessage)
.buttonStyle(.borderedProminent)
.keyboardShortcut(.return, modifiers: .command)
.disabled(studio.prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
}
}
}
.padding(16)
}
private func pickLocalFile() {
let panel = NSOpenPanel()
panel.canChooseFiles = true
panel.canChooseDirectories = true
panel.allowsMultipleSelection = false
panel.prompt = "Preview"
panel.begin { response in
guard response == .OK, let url = panel.url else { return }
Task { @MainActor in
let conversation = studio.selected
preparingFilePreview = true
fileError = ""
defer { preparingFilePreview = false }
do {
let preview = try await Task.detached { try ChatFilePreview.read(url) }.value
guard studio.selected == conversation, !studio.running else { return }
filePreview = preview
} catch { fileError = error.localizedDescription }
}
}
}
private func resourceMenu(for target: StudioModel) -> some View {
ChatResourcesMenu(target: target, stacks: studio.knowledgeStacks, snippets: studio.snippets,
openWorkspace: { showingWorkspace = true })
}
private func sendSplitMessage() {
guard splitStudio.selected != nil, splitStudio.selected != studio.selected else { return }
splitStudio.copyInferenceCredentials(from: studio)
try? splitStudio.refreshWorkspace()
send(splitStudio, choice: modelForChat(splitStudio.selected), useDocuments: includesDocuments(splitStudio), allowAgentTools: false)
}
private func sendMessage() {
let draft = studio.prompt
if draft.lowercased().hasPrefix("/write ") {
do {
guard chatFileWriteEnabled else { throw StudioError("Enable file writing in Settings → Local Tools.") }
let request = try ChatFileRequest.Write(draft)
let destination = try ChatFileRequest.destination(request.path, inside: chatFileScope)
writeDestination = destination
replacingFile = FileManager.default.fileExists(atPath: destination.path)
pendingWrite = request
confirmFileWrite = true
fileError = ""
} catch { fileError = error.localizedDescription }
return
}
send(studio, choice: chatModel, useDocuments: includesDocuments(studio), allowAgentTools: agentMCPEnabled)
}
private func send(_ target: StudioModel, choice: ChatModelChoice, useDocuments: Bool, allowAgentTools: Bool) {
target.send(endpoint: choice.backend == .compatible ? compatibleEndpoint : endpoint,
model: choice.model, mlxPath: choice.backend == .mlx ? choice.model : mlxPath,
thinking: choice.thinkingMode(thinking), failover: failover,
mlxOnly: choice.backend == .mlx, compatible: choice.backend == .compatible,
recall: recall, useDocuments: useDocuments, instructions: promptMode.instructions(custom: customPrompt),
settings: GenerationSettings.read(generationSettings), agents: selectedAgents, agentTools: allowAgentTools,
ragEnabled: ragEnabled, lmStudioPlugins: pluginsEnabled && pluginEndpoint == compatibleEndpoint
? CompatibleEndpoint.pluginIDs(pluginIDs) : [])
}
}
private struct ChatDebugOutput: View {
@ObservedObject var studio: StudioModel
private var sections: [(title: String, lines: [String])] {
[
("Web retrieval", [studio.webStatus] + studio.webDiagnostics),
("Knowledge base", [studio.knowledgeStatus] + studio.knowledgeSources),
("Agent run", studio.agentSteps)
].compactMap { title, lines in
let entries = lines.filter { !$0.isEmpty }
return entries.isEmpty ? nil : (title, entries)
}
}
var body: some View {
VStack(alignment: .leading, spacing: 10) {
Label("Debug Output", systemImage: "ladybug")
.font(.caption.weight(.semibold))
.accessibilityAddTraits(.isHeader)
let diagnostics = sections
if diagnostics.isEmpty {
Text("Web, knowledge base, and agent diagnostics appear here when available.")
.font(.caption).foregroundStyle(.secondary)
}
ForEach(diagnostics.indices, id: \.self) { index in
let section = diagnostics[index]
VStack(alignment: .leading, spacing: 3) {
Text(section.title).font(.caption.weight(.semibold))
Text(section.lines.joined(separator: "\n"))
.font(.system(.caption, design: .monospaced))
.textSelection(.enabled)
}
}
}
.padding(12)
.frame(maxWidth: .infinity, alignment: .leading)
.background(.quaternary.opacity(0.45), in: RoundedRectangle(cornerRadius: 10))
.accessibilityElement(children: .contain)
}
}
private struct ChatResourcesMenu: View {
@ObservedObject var target: StudioModel
let stacks: [Conversation]
let snippets: [WorkspaceSnippet]
let openWorkspace: () -> Void
private var count: Int {
let local = [target.activeStack, target.activeSkill, target.activeContext, target.activeWebClip, target.activePrompt].compactMap { $0 }.count
if case .server = target.activeRemoteStack { return local + 1 }
return local
}
var body: some View {
Menu {
Menu("Knowledge Stacks") {
Picker("Knowledge Stack", selection: $target.activeStack) {
Text("None").tag(UUID?.none)
ForEach(stacks) { Text($0.title).tag(Optional($0.id)) }
}
}
Menu("Remote Stacks") { RemoteStackPicker(studio: target, label: "Remote Stack") }
snippetMenu("Skills", kind: .skill, selection: $target.activeSkill)
snippetMenu("Contexts", kind: .context, selection: $target.activeContext)
snippetMenu("Prompt Templates", kind: .prompt, selection: $target.activePrompt)
Menu("Insert Saved Prompt") {
let prompts = snippets.filter { $0.kind == .prompt }
if prompts.isEmpty { Text("No saved prompts") }
ForEach(prompts) { prompt in
Button(prompt.title) {
if target.prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
target.prompt = prompt.content
} else {
target.prompt += "\n\n" + prompt.content
}
}
}
}
snippetMenu("Web Clips", kind: .webClip, selection: $target.activeWebClip)
Divider()
Button("Open Workspace…", action: openWorkspace)
} label: {
Label(count == 0 ? "Resources" : "Resources \(count)", systemImage: "square.stack")
}
.menuStyle(.borderlessButton)
.fixedSize()
.disabled(target.running)
.help("Use saved workspace resources in this conversation")
}
private func snippetMenu(_ title: String, kind: WorkspaceSnippet.Kind, selection: Binding<UUID?>) -> some View {
Menu(title) {
Picker(kind.rawValue, selection: selection) {
Text("None").tag(UUID?.none)
ForEach(snippets.filter { $0.kind == kind }) { Text($0.title).tag(Optional($0.id)) }
}
}
}
}
private struct ChatModelPicker: View {
@ObservedObject var studio: StudioModel
let choice: ChatModelChoice
let defaultChoice: ChatModelChoice
let hasOverride: Bool
let endpoint: String
let ollamaDefault: String
let mlxPaths: () -> [String]
let compatibleEndpoint: String
let compatibleDefault: String
let select: (ChatModelChoice?) -> Void
@State private var showing = false
@State private var compatibleModels: [String] = []
@State private var compatibleStatus = ""
@State private var loadingCompatible = false
var body: some View {
Button {
showing.toggle()
} label: {
Label(choice.displayName, systemImage: choice.backend == .mlx ? "cpu" : "server.rack")
.lineLimit(1)
}
.buttonStyle(.bordered)
.accessibilityLabel("Chat model: " + choice.displayName)
.help("Switch models for this conversation")
.popover(isPresented: $showing) {
Form {
Section("Model for This Chat") {
Button {
choose(nil)
} label: {
optionLabel("Use Default · " + defaultChoice.displayName, selected: !hasOverride)
}
}
Section("Ollama") {
let installed = studio.modelListEndpoint == endpoint ? studio.models.map(\.name) : []
ForEach(names(installed + [ollamaDefault]), id: \.self) { name in
modelButton(.ollama, name)
}
Button("Refresh Ollama Models") { studio.refresh(endpoint: endpoint) }.disabled(studio.managing)
if studio.managing {
ProgressView().controlSize(.small)
} else if installed.isEmpty && !studio.modelStatus.isEmpty {
Text(studio.modelStatus).font(.caption).foregroundStyle(.secondary)
}
}
let installedMLX = mlxPaths()
if !installedMLX.isEmpty {
Section("MLX") {
ForEach(installedMLX, id: \.self) { path in
modelButton(.mlx, path).help(path)
}
}
}
Section("Compatible API") {
ForEach(names(compatibleModels + [compatibleDefault]), id: \.self) { model in
modelButton(.compatible, model)
}
Button("Refresh Compatible Models") { Task { await refreshCompatible() } }.disabled(loadingCompatible)
if loadingCompatible { ProgressView().controlSize(.small) }
if !compatibleStatus.isEmpty {
Text(compatibleStatus).font(.caption).foregroundStyle(.secondary)
}
}
}
.formStyle(.grouped)
.frame(width: 340, height: 420)
.task {
if studio.modelListEndpoint != endpoint { studio.refresh(endpoint: endpoint) }
}
.onChange(of: compatibleEndpoint) {
compatibleModels = []
compatibleStatus = ""
}
}
}
private func names(_ values: [String]) -> [String] {
Array(Set(values.filter { !$0.isEmpty })).sorted { $0.localizedStandardCompare($1) == .orderedAscending }
}
private func choose(_ model: ChatModelChoice?) {
select(model)
showing = false
}
private func modelButton(_ backend: ChatModelChoice.Backend, _ name: String) -> some View {
let model = ChatModelChoice(backend: backend, model: name)
return Button { choose(model) } label: {
optionLabel(model.displayName, selected: hasOverride && choice == model)
}
}
private func optionLabel(_ title: String, selected: Bool) -> some View {
HStack {
Text(title).lineLimit(1)
Spacer()
if selected { Image(systemName: "checkmark").accessibilityLabel("Selected") }
}
}
private func refreshCompatible() async {
let endpoint = compatibleEndpoint
loadingCompatible = true
compatibleStatus = ""
defer { loadingCompatible = false }
do {
let models = try await studio.compatibleClient(endpoint: endpoint).models()
if endpoint == compatibleEndpoint {
compatibleModels = models
if models.isEmpty { compatibleStatus = "No models reported." }
}
} catch {
if endpoint == compatibleEndpoint { compatibleStatus = error.localizedDescription }
}
}
}
struct MessageView: View {
let message: Message
@AppStorage("studioCustomThemes") private var customThemesData = Data()
@AppStorage("studioCustomThemeID") private var customThemeID = ""
@AppStorage("studioPalette") private var palette = StudioPalette.system
@Environment(\.colorScheme) private var colorScheme
var streaming = false
@AppStorage("renderChatMarkdown") private var renderMarkdown = true
@AppStorage("compactChatMessages") private var compactMessages = false
@AppStorage("expandChatThinking") private var expandThinking = false
@State private var thinkingExpanded = false
@State private var webSourcesExpanded = false
private var webSourcesLabel: String {
let kinds = Set(message.webSources.map(\.kind))
if kinds == [.page] { return "Web pages" }
if kinds == [.searchSnippet] { return "Search snippets" }
if kinds == [.savedClip] { return "Saved web clips" }
return "Web sources"
}
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(isExpanded: $thinkingExpanded) {
Text(message.thinking).foregroundStyle(.secondary).textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.vertical, 6)
} label: {
Label(streaming && message.content.isEmpty ? "Thinking…" : "Thinking",
systemImage: "brain.head.profile")
.foregroundStyle(.secondary)
}
.padding(8)
.background(.quaternary.opacity(0.45), in: RoundedRectangle(cornerRadius: 8))
}
if !message.content.isEmpty {
if message.role == .assistant && renderMarkdown {
ChatMarkdown(text: message.content, canRunJavaScript: !streaming)
} else {
Text(message.content).textSelection(.enabled)
}
}
ForEach(message.documentNames, id: \.self) { name in
Label(name, systemImage: "paperclip")
.font(.caption.weight(.semibold))
.foregroundStyle(.secondary)
.accessibilityLabel("Attached document: " + name)
}
if !message.documentCitations.isEmpty {
DisclosureGroup("Document sources") {
ForEach(message.documentCitations) { source in
VStack(alignment: .leading, spacing: 4) {
Text("[D\(source.number)] \(source.title)").font(.caption.weight(.semibold))
Text(source.excerpt).font(.caption).textSelection(.enabled)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.vertical, 4)
}
}
}
if !message.webSources.isEmpty {
DisclosureGroup(isExpanded: $webSourcesExpanded) {
VStack(alignment: .leading, spacing: 6) {
ForEach(message.webSources) { source in
if let url = try? WebClipCapture.url(source.url.absoluteString) {
HStack(alignment: .firstTextBaseline, spacing: 8) {
Link(source.title.isEmpty ? url.absoluteString : source.title, destination: url)
Text(source.kind.rawValue).foregroundStyle(.secondary)
}
}
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.vertical, 5)
} label: {
Label("\(webSourcesLabel) (\(message.webSources.count))", systemImage: "globe")
.font(.caption.weight(.semibold))
.foregroundStyle(Color.accentColor)
}
.font(.caption)
}
if message.content.isEmpty && message.thinking.isEmpty { ProgressView().controlSize(.small) }
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(compactMessages ? 8 : 14)
.onChange(of: expandThinking, initial: true) { _, expanded in thinkingExpanded = expanded }
.onChange(of: streaming && !message.thinking.isEmpty, initial: true) { _, beganThinking in
if beganThinking { thinkingExpanded = true }
}
.background(StudioCustomTheme.selected(customThemeID, in: customThemesData)?.message(dark: colorScheme == .dark, user: message.role == .user) ?? palette.message(dark: colorScheme == .dark, user: message.role == .user),
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 = ""
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") {
studio.refresh(endpoint: endpoint)
}
.disabled(studio.managing)
if studio.managing { Button("Cancel") { studio.cancelManagement() } }
}
if studio.modelListEndpoint == endpoint {
ForEach(studio.models) { entry in
HStack {
Label(entry.name, systemImage: "cube")
Spacer()
Text(ModelLibrarySize.label(entry.size))
.foregroundStyle(.secondary).font(.caption)
Button(model == entry.name && !mlxOnly && !compatibleEnabled ? "Selected" : "Use Model") {
model = entry.name
mlxOnly = false
compatibleEnabled = false
}.disabled(model == entry.name && !mlxOnly && !compatibleEnabled)
}
}
}
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") {
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)
.onAppear {
if !mlxOnly && !compatibleEnabled && studio.modelListEndpoint != endpoint {
studio.refresh(endpoint: endpoint)
}
}
.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) }
}
}
}
private enum SettingsPane {
static let storageKey = "studioSettingsPane"
static let models = "Models"
static let modelLibrary = "Model Library"
}
struct StudioWelcome: View {
@Environment(\.openSettings) private var openSettings
@AppStorage(SettingsPane.storageKey) private var settingsPane = SettingsPane.models
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)
Button("Model Settings", systemImage: "slider.horizontal.3") {
settingsPane = SettingsPane.modelLibrary
openSettings()
}
.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. AI Studio includes excerpts when you send a message. Use the composer toggle to turn this off.")
.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
var canRunJavaScript = false
@State private var sandboxSource: String?
@AppStorage("studioCodeTheme") private var codeTheme = StudioTheme.system
@Environment(\.colorScheme) private var currentScheme
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()
if canRunJavaScript && ["js", "javascript"].contains(language.lowercased()) {
Button("Open in JavaScript Sandbox", systemImage: "play") {
sandboxSource = block.content
}
.buttonStyle(.borderless)
}
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))
.environment(\.colorScheme, codeTheme.colorScheme ?? currentScheme)
} else {
let parsed = try? AttributedString(markdown: block.content,
options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))
Text(parsed ?? AttributedString(block.content)).textSelection(.enabled)
}
}
}
.sheet(isPresented: Binding(
get: { sandboxSource != nil },
set: { if !$0 { sandboxSource = nil } }
)) {
JavaScriptSandboxView(source: sandboxSource ?? "")
.frame(minWidth: 520, minHeight: 400)
}
}
}
enum JavaScriptSandbox {
static func run(_ source: String) throws -> String {
guard source.utf8.count <= 32_768 else { throw StudioError("JavaScript is limited to 32 KB.") }
guard let executable = Bundle.main.executableURL else { throw StudioError("Sandbox executable is unavailable.") }
let child = Process()
let output = Pipe()
child.executableURL = executable
child.arguments = ["--javascript-sandbox", Data(source.utf8).base64EncodedString()]
child.environment = [:]
child.standardInput = FileHandle.nullDevice
child.standardOutput = output
child.standardError = FileHandle.nullDevice
try child.run()
let deadline = DispatchWorkItem {
if child.isRunning { kill(child.processIdentifier, SIGKILL) }
}
DispatchQueue.global().asyncAfter(deadline: .now() + 5, execute: deadline)
defer { deadline.cancel() }
let data = output.fileHandleForReading.readDataToEndOfFile()
child.waitUntilExit()
if child.terminationReason == .uncaughtSignal {
throw StudioError("JavaScript exceeded the time limit or the sandbox stopped unexpectedly.")
}
let result = String(decoding: data, as: UTF8.self)
guard child.terminationStatus == 0 else {
throw StudioError(result.isEmpty ? "Could not run JavaScript." : result)
}
return result
}
static func evaluate(_ encoded: String) -> Int32 {
guard let data = Data(base64Encoded: encoded), data.count <= 32_768,
let source = String(data: data, encoding: .utf8), let context = JSContext() else { return 1 }
// Use a fresh JavaScriptCore context with no host functions or native objects exposed.
let runner = context.evaluateScript(#"""
(source => {
let output = "";
const format = value => {
if (typeof value === "string") return value;
try { return JSON.stringify(value) ?? String(value); }
catch { return String(value); }
};
const log = (...values) => {
for (const value of values) {
if (output.length >= 8000) break;
output += format(value).slice(0, 8000 - output.length) + " ";
}
if (output.length < 8000) output += "\n";
};
globalThis.console = { log, info: log, warn: log, error: log };
try {
const value = (0, eval)(source);
if (value !== undefined) log(value);
return [true, output.trimEnd().slice(0, 8000)];
} catch (error) {
return [false, (output + String(error)).slice(0, 8000)];
}
})
"""#)
guard let result = runner?.call(withArguments: [source]), result.isObject,
let text = result.atIndex(1)?.toString() else { return 1 }
FileHandle.standardOutput.write(Data(text.utf8))
return result.atIndex(0)?.toBool() == true ? 0 : 1
}
}
private struct JavaScriptSandboxView: View {
@Environment(\.dismiss) private var dismiss
var studio: StudioModel?
@State private var source: String
@State private var output = ""
@State private var error = ""
@State private var running = false
init(studio: StudioModel? = nil, source: String = "") {
self.studio = studio
_source = State(initialValue: source)
}
var body: some View {
VStack(alignment: .leading, spacing: 10) {
HStack {
Text("JavaScript Sandbox").font(.headline)
Spacer()
if studio == nil { Button("Done") { dismiss() } }
}
Text("Run JavaScript with console output and a five-second time limit.")
.foregroundStyle(.secondary)
TextEditor(text: $source)
.font(.system(.body, design: .monospaced))
.accessibilityLabel("JavaScript source")
.frame(minHeight: 130)
.border(.quaternary)
.disabled(running)
.onChange(of: source) {
output = ""
error = ""
}
HStack {
Button("Run JavaScript", systemImage: "play", action: run)
.disabled(running || source.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
if running { ProgressView().controlSize(.small) }
Spacer()
if let studio, !output.isEmpty {
Button("Attach Output to Chat") {
studio.attachToolResult(name: "JavaScript Sandbox", output: output)
dismiss()
}
.disabled(studio.running)
}
}
ScrollView {
Text(error.isEmpty ? output : error)
.font(.system(.body, design: .monospaced))
.foregroundStyle(error.isEmpty ? Color.primary : Color.red)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(minHeight: 90)
.accessibilityLabel("JavaScript output")
}
.padding()
}
private func run() {
let code = source
running = true
output = ""
error = ""
Task {
defer { running = false }
do {
output = try await Task.detached { try JavaScriptSandbox.run(code) }.value
if output.isEmpty { error = "Finished with no output." }
} catch {
self.error = error.localizedDescription
}
}
}
}
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("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."))
} 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/s") { run in
Text(run.charactersPerSecond.map { $0.formatted(.number.precision(.fractionLength(1))) } ?? "—")
}
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("Prompt context budget", Binding(
get: { draft.promptBudget ?? "" }, set: { draft.promptBudget = $0 }))
.help("Estimated input tokens plus the reserved output tokens.")
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<String>) -> 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
@AppStorage("chatFileAccessFolder") private var chatFileAccessFolder = ""
@AppStorage("chatFileWriteEnabled") private var chatFileWriteEnabled = false
@State private var confirmFullAccess = false
@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("Chat File Access") {
LabeledContent("Access", value: chatFileAccessFolder.isEmpty ? "Off" :
chatFileAccessFolder == "/" ? "Any readable location" : chatFileAccessFolder)
HStack {
Button("Choose Folder…") {
let panel = NSOpenPanel()
panel.canChooseDirectories = true
panel.canChooseFiles = false
panel.begin { result in
if result == .OK, let url = panel.url { chatFileAccessFolder = url.path }
}
}
Button("Allow Any Readable Location…") { confirmFullAccess = true }
if !chatFileAccessFolder.isEmpty {
Button("Turn Off") { chatFileAccessFolder = ""; chatFileWriteEnabled = false }
}
}
Toggle("Allow file writing", isOn: $chatFileWriteEnabled)
.disabled(chatFileAccessFolder.isEmpty)
Text("Use /read for files, /ls for a folder, or /tree for nested folders. The selected model receives the preview. To save text locally, enter /write and a path, then add the text on the next line. macOS permissions still apply.")
.foregroundStyle(.secondary)
}
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)
.alert("Allow chat to read from any location?", isPresented: $confirmFullAccess) {
Button("Allow Read Access") { chatFileAccessFolder = "/" }
Button("Cancel", role: .cancel) {}
} message: {
Text("A file you ask chat to read may be included in a request to your selected model, including a remote model.")
}
.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
@AppStorage("lmStudioPluginEndpoint") private var pluginEndpoint = ""
@AppStorage("lmStudioPluginIDs") private var pluginIDs = ""
@AppStorage("lmStudioPluginsEnabled") private var pluginsEnabled = false
@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)
TextField("LM Studio plugin IDs", text: $pluginIDs, prompt: Text("mcp/server, mcp/another-server"))
.onChange(of: pluginIDs) { pluginsEnabled = false }
Toggle("Use LM Studio plugins in chat", isOn: Binding(
get: { pluginsEnabled && pluginEndpoint == endpoint },
set: { enabled in
pluginEndpoint = endpoint
pluginsEnabled = enabled
}
))
.disabled(CompatibleEndpoint.pluginIDs(pluginIDs).isEmpty)
Text("Enable authentication and Allow calling servers from mcp.json in LM Studio. Enter the API token above. Enabled servers can run tools during chat.")
.foregroundStyle(.secondary)
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)
pluginsEnabled = false
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 }
}
}
}
}
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
enum Section: String, CaseIterable {
case servers = "MCP Servers"
case search = "Web Search"
case retrieve = "Retrieve Page"
case javascript = "JavaScript"
}
@Binding var section: Section
var body: some View {
VStack(spacing: 0) {
HStack {
Label("Toolbox", systemImage: "wrench.and.screwdriver").font(.headline)
Spacer()
Button("Done") { dismiss() }
}
.padding()
Picker("Toolbox section", selection: $section) {
ForEach(Section.allCases, id: \.self) { Text($0.rawValue).tag($0) }
}
.pickerStyle(.segmented)
.labelsHidden()
.frame(maxWidth: .infinity)
.padding([.horizontal, .bottom])
Divider()
if section == .servers {
MCPSettings(studio: studio)
} else if section == .javascript {
JavaScriptSandboxView(studio: studio)
} else {
WebToolsView(studio: studio, section: $section, done: { dismiss() })
}
}
}
}
struct WorkspaceResourcesView: View {
@Environment(\.dismiss) private var dismiss
@ObservedObject var studio: StudioModel
@State private var page: Page? = .stacks
private enum Page: String, CaseIterable, Identifiable {
case stacks = "Knowledge Stacks"
case skills = "Skills"
case contexts = "Contexts"
case prompts = "Prompt Studio"
case clips = "Web Clips"
var id: Self { self }
var icon: String {
switch self {
case .stacks: "square.stack.3d.up"
case .skills: "bolt"
case .contexts: "doc.text"
case .prompts: "text.bubble"
case .clips: "link"
}
}
}
var body: some View {
VStack(spacing: 0) {
HStack {
Text("Workspace").font(.title2.bold())
Spacer()
Button("Done") { dismiss() }
}
.padding()
Divider()
HSplitView {
List(Page.allCases, selection: $page) { entry in
Label(entry.rawValue, systemImage: entry.icon).tag(entry)
}
.listStyle(.sidebar)
.frame(minWidth: 175, idealWidth: 190, maxWidth: 235)
Group {
switch page ?? .stacks {
case .stacks: KnowledgeStacksView(studio: studio)
case .skills: WorkspaceSnippetsView(studio: studio, kind: .skill).id(Page.skills)
case .contexts: WorkspaceSnippetsView(studio: studio, kind: .context).id(Page.contexts)
case .prompts: WorkspaceSnippetsView(studio: studio, kind: .prompt).id(Page.prompts)
case .clips: WorkspaceSnippetsView(studio: studio, kind: .webClip).id(Page.clips)
}
}
.frame(minWidth: 590, maxWidth: .infinity, maxHeight: .infinity)
}
if !studio.workspaceStatus.isEmpty {
Text(studio.workspaceStatus).foregroundStyle(.red).textSelection(.enabled).padding(8)
}
}
.frame(width: 840, height: 570)
}
}
private struct RemoteStackPicker: View {
@ObservedObject var studio: StudioModel
let label: String
var body: some View {
Picker(label, selection: $studio.activeRemoteStack) {
Text("Automatic").tag(RemoteStackChoice.automatic)
Text("Off").tag(RemoteStackChoice.off)
ForEach(studio.remoteKnowledgeStacks) { stack in
Text(stack.name).tag(RemoteStackChoice.server(stack.id))
}
if case .server(let id) = studio.activeRemoteStack,
!studio.remoteKnowledgeStacks.contains(where: { $0.id == id }) {
Text("Selected stack disconnected").tag(RemoteStackChoice.server(id))
}
}
}
}
private struct RemoteStackInventory: View {
@Environment(\.dismiss) private var dismiss
let stack: RemoteKnowledgeStack
@State private var sources: [String]?
@State private var search = ""
@State private var error = ""
var body: some View {
VStack(alignment: .leading, spacing: 12) {
HStack {
Text(stack.name).font(.headline)
Spacer()
Button("Done") { dismiss() }.keyboardShortcut(.cancelAction)
}
if let sources {
Text("\(sources.count.formatted()) indexed source paths").foregroundStyle(.secondary)
TextField("Filter paths", text: $search)
List(sources.filter { search.isEmpty || $0.localizedCaseInsensitiveContains(search) }, id: \.self) { path in
Text(path).textSelection(.enabled)
}
} else if !error.isEmpty {
Text(error).foregroundStyle(.secondary).textSelection(.enabled)
Spacer()
} else {
ProgressView("Loading indexed sources…")
Spacer()
}
}
.padding(16)
.frame(width: 566, height: 410)
.task {
do { sources = try await KnowledgeInventory.sources(client: stack.client) }
catch { if !Task.isCancelled { self.error = error.localizedDescription } }
}
}
}
struct KnowledgeStacksView: View {
@ObservedObject var studio: StudioModel
@State private var selected: UUID?
@State private var name = ""
@State private var documents: [LibraryDocument] = []
@State private var vectorCount = 0
@State private var importing = false
@State private var busy = false
@State private var removing = false
@State private var inventory: RemoteKnowledgeStack?
var body: some View {
Form {
Section("Local Stacks") {
HStack {
TextField("New stack name", text: $name, prompt: Text("Enter a name for the stack"))
.labelsHidden()
.textFieldStyle(.roundedBorder)
.accessibilityLabel("New stack name")
Button("Create Stack") {
selected = studio.createStack(name.trimmingCharacters(in: .whitespacesAndNewlines))
name = ""
}.buttonStyle(.borderedProminent)
.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") {
LabeledContent("Local vector index", value: "\(vectorCount) embedded passages")
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)
}
}
}
Section("Remote Stacks") {
RemoteStackPicker(studio: studio, label: "Use in this chat").disabled(studio.running)
if studio.remoteKnowledgeStacks.isEmpty {
Text("Connect a knowledge server in Settings → Toolbox to use its index here.")
.foregroundStyle(.secondary)
}
ForEach(studio.remoteKnowledgeStacks) { stack in
HStack {
Label(stack.name, systemImage: "externaldrive.connected.to.line.below")
Spacer()
if stack.supportsInventory {
Button("Browse Sources…") { inventory = stack }
} else {
Text("Search available").foregroundStyle(.secondary)
}
}
}
}
}
.formStyle(.grouped)
.sheet(item: $inventory) { RemoteStackInventory(stack: $0) }
.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) ?? []
vectorCount = selected.map(studio.stackVectorCount) ?? 0
}
}
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 notes = ""
@State private var tags = ""
@State private var examples: [PromptExample] = []
@State private var editingExamples = false
@State private var evaluating = false
@State private var versions: [PromptVersion] = []
@State private var content = ""
@State private var address = ""
@State private var importing = false
@State private var capturing = false
@State private var renderedPage: RenderedClipPage?
@State private var deleting = false
@State private var error = ""
@State private var notice = ""
@FocusState private var draftFocus: DraftField?
private enum DraftField: Hashable { case title, address, content }
private var items: [WorkspaceSnippet] {
studio.snippets.filter {
$0.kind == kind && (search.isEmpty || $0.title.localizedCaseInsensitiveContains(search) || $0.tags.localizedCaseInsensitiveContains(search) || $0.notes.localizedCaseInsensitiveContains(search))
}
}
var body: some View {
HSplitView {
VStack(spacing: 8) {
TextField("Search \(kind.rawValue)s", text: $search)
if items.isEmpty {
ContentUnavailableView(
search.isEmpty ? "No saved \(kind.rawValue.lowercased())s" : "No matches",
systemImage: "tray"
)
.frame(maxHeight: .infinity)
} else {
List(items, selection: $id) { item in Text(item.title).tag(item.id) }
.disabled(capturing)
}
Button("New \(kind.rawValue)", systemImage: "plus") { beginDraft() }
.disabled(capturing)
}
.padding(12)
.frame(minWidth: 180, idealWidth: 220)
VStack(alignment: .leading, spacing: 10) {
TextField("Title", text: $title).focused($draftFocus, equals: .title).disabled(capturing)
if kind == .prompt {
TextField("Notes", text: $notes)
TextField("Tags (comma-separated)", text: $tags)
HStack {
Button("Examples (\(examples.count))") { editingExamples = true }
Button("Evaluate…") { evaluating = true }
.disabled(content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
if let id {
Button(isActive ? "Deactivate Template" : "Use as Template") {
studio.activePrompt = isActive ? nil : id
}
.disabled(studio.running)
.help("Apply the latest saved version to future chat turns.")
}
Spacer()
}
if !versions.isEmpty {
Menu("Version History") {
ForEach(versions) { version in
Button("\(version.savedAt) · \(version.title)") {
title = version.title
content = version.content
notes = version.notes
tags = version.tags
examples = version.examples
}
}
}
}
}
if kind == .webClip {
HStack {
TextField("Source URL", text: $address).focused($draftFocus, equals: .address).disabled(capturing)
Button("Capture & Save") {
capturing = true
let source = address
Task {
defer { capturing = false }
do {
let page = try await WebClipCapture.page(from: source)
address = page.url.absoluteString
content = String(page.text.prefix(12_000))
if title.isEmpty { title = page.title }
save()
} catch { self.error = error.localizedDescription }
}
}.disabled(capturing || address.isEmpty)
if capturing { ProgressView().controlSize(.small) }
Button("Open Rendered Page…") {
do { renderedPage = RenderedClipPage(url: try WebClipCapture.pageURL(address)) }
catch { self.error = error.localizedDescription }
}
.disabled(capturing || address.isEmpty)
}
}
TextEditor(text: $content).accessibilityLabel("\(kind.rawValue) text")
.focused($draftFocus, equals: .content)
.border(.quaternary)
.overlay(alignment: .topLeading) {
if content.isEmpty {
Text(editorHint).foregroundStyle(.secondary).padding(8)
.allowsHitTesting(false).accessibilityHidden(true)
}
}
if !error.isEmpty { Text(error).foregroundStyle(.red).textSelection(.enabled) }
if !notice.isEmpty { Label(notice, systemImage: "checkmark.circle").foregroundStyle(.secondary) }
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(id == nil ? "Save \(kind.rawValue)" : "Save Changes", 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
notes = item.notes
tags = item.tags
examples = item.examples
versions = kind == .prompt ? studio.promptVersions(item.id) : []
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
}
}
}
.sheet(isPresented: $editingExamples) {
PromptExamplesEditor(examples: examples) { examples = $0 }
}
.sheet(isPresented: $evaluating) {
PromptEvaluationView(studio: studio, template: PromptTemplate(body: content, examples: examples))
}
.sheet(item: $renderedPage) { page in
RenderedClipView(url: page.url) { finalURL, pageTitle, text in
address = finalURL.absoluteString
if title.isEmpty { title = pageTitle }
content = text
save()
}
}
.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: studio.activePrompt == id
}
}
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
guard studio.saveSnippet(id: key, kind: kind, title: title.trimmingCharacters(in: .whitespacesAndNewlines),
content: stored, notes: notes, tags: tags, examples: examples) else {
error = studio.workspaceStatus
notice = ""
return
}
search = ""
id = key
notice = "Saved \(kind.rawValue.lowercased())."
if kind == .prompt { versions = studio.promptVersions(key) }
error = ""
}
private var editorHint: String {
switch kind {
case .skill: "Describe what AI Studio should do when this skill is active."
case .context: "Add reference text to use in chat."
case .prompt: "Write a prompt template. Use {{input}} to place the input."
case .webClip: "Enter a URL and use Capture & Save, or paste an excerpt here."
}
}
private func beginDraft() {
clear()
search = ""
if kind == .webClip {
draftFocus = .address
} else {
title = "Untitled \(kind.rawValue)"
draftFocus = .title
}
}
private func clear() {
id = nil
title = ""
content = ""
address = ""
error = ""
notice = ""
notes = ""
tags = ""
versions = []
examples = []
}
}
private struct PromptExamplesEditor: View {
@Environment(\.dismiss) private var dismiss
@State var examples: [PromptExample]
let save: ([PromptExample]) -> Void
var body: some View {
VStack(alignment: .leading) {
Form {
ForEach(examples.indices, id: \.self) { index in
Section {
TextField("Input", text: $examples[index].input, axis: .vertical)
TextField("Expected assistant response", text: $examples[index].output, axis: .vertical)
Button("Remove Example", role: .destructive) { examples.remove(at: index) }
}
}
Button("Add Example", systemImage: "plus") {
examples.append(PromptExample(input: "", output: ""))
}.disabled(examples.count >= 8)
}.formStyle(.grouped)
HStack {
Spacer()
Button("Cancel") { dismiss() }.keyboardShortcut(.cancelAction)
Button("Apply to Draft") {
save(examples)
dismiss()
}
.buttonStyle(.borderedProminent)
.disabled(!examples.allSatisfy { $0.isComplete && $0.input.count <= 4_000 && $0.output.count <= 4_000 })
}.padding()
}.frame(width: 500, height: 420)
}
}
private struct PromptEvaluationView: View {
@Environment(\.dismiss) private var dismiss
let studio: StudioModel
let template: PromptTemplate
@State private var input = ""
@State private var expected = ""
@State private var output = ""
@State private var status = ""
@State private var evaluation: Task<Void, Never>?
var body: some View {
VStack(alignment: .leading) {
Form {
Section("Test Case") {
TextField("Input", text: $input, axis: .vertical)
TextField("Expected output (optional)", text: $expected, axis: .vertical)
LabeledContent("Rendered input") {
Text(template.render(input)).textSelection(.enabled)
}
}
if !output.isEmpty || !status.isEmpty {
Section("Result") {
Text(status)
if !output.isEmpty { Text(output).textSelection(.enabled) }
}
}
}.formStyle(.grouped)
HStack {
Spacer()
if evaluation != nil { Button("Stop") { evaluation?.cancel() } }
Button("Close") { dismiss() }.keyboardShortcut(.cancelAction)
Button("Run Evaluation", action: run)
.buttonStyle(.borderedProminent).disabled(evaluation != nil)
}.padding()
}
.frame(width: 580, height: 460)
.onDisappear { evaluation?.cancel() }
}
private func run() {
let testInput = input
let expectedOutput = expected.trimmingCharacters(in: .whitespacesAndNewlines)
output = ""
status = "Running…"
evaluation = Task {
defer { evaluation = nil }
do {
output = try await studio.evaluatePrompt(template, input: testInput)
status = expectedOutput.isEmpty ? "Completed" :
(PromptEvaluation.matches(output, expected: expectedOutput) ? "Passed" : "Output differed")
} catch {
status = Task.isCancelled ? "Evaluation stopped." : error.localizedDescription
}
}
}
}
private struct RenderedClipPage: Identifiable {
let url: URL
var id: URL { url }
}
private struct RenderedClipView: View {
let url: URL
let capture: (URL, String, String) -> Void
@Environment(\.dismiss) private var dismiss
@State private var browser: WKWebView?
@State private var error = ""
var body: some View {
VStack(spacing: 0) {
HStack {
Text(browser?.url?.host ?? url.host ?? "Web Page").font(.headline)
Spacer()
Button("Cancel") { dismiss() }
Button("Capture Visible Text", action: captureText)
.buttonStyle(.borderedProminent)
.disabled(browser == nil)
}.padding()
if !error.isEmpty { Text(error).foregroundStyle(.red).padding(.horizontal) }
if let browser {
ClipBrowserView(browser: browser)
}
}
.frame(width: 800, height: 570)
.onAppear {
guard browser == nil else { return }
let configuration = WKWebViewConfiguration()
configuration.websiteDataStore = .nonPersistent()
let view = WKWebView(frame: .zero, configuration: configuration)
browser = view
view.load(URLRequest(url: url))
}
}
private func captureText() {
guard let browser, let url = browser.url,
(try? WebClipCapture.url(url.absoluteString)) != nil else {
error = "Wait for an HTTP or HTTPS page to load."
return
}
browser.evaluateJavaScript("document.body?.innerText?.slice(0, 12000) ?? ''") { result, failure in
guard browser.url == url, let text = result as? String,
!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
error = failure?.localizedDescription ?? "The page has no readable text yet."
return
}
capture(url, browser.title ?? url.host ?? "Web Clip", text)
dismiss()
}
}
}
private struct ClipBrowserView: NSViewRepresentable {
let browser: WKWebView
func makeNSView(context: Context) -> WKWebView { browser }
func updateNSView(_ view: WKWebView, context: Context) {}
}
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
@AppStorage(SettingsPane.storageKey) private var page = SettingsPane.models
private let pages = [
(SettingsPane.models, "cpu"), (SettingsPane.modelLibrary, "square.stack"), ("Generation", "slider.horizontal.3"),
("Knowledge Base", "books.vertical"), ("Toolbox", "wrench.and.screwdriver"), ("Local Tools", "terminal"), ("Runtime", "waveform.path"),
("Agents", "person.2"), ("Appearance", "paintpalette"), ("Workspace Data", "externaldrive")
]
var body: some View {
TabView(selection: $page) {
ForEach(pages, id: \.0) { name, icon in
pane(name)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.tabItem { Label(name, systemImage: icon) }
.tag(name)
}
}
.navigationTitle(page)
.frame(width: 780, height: 610)
}
@ViewBuilder private func pane(_ name: String) -> some View {
switch name {
case SettingsPane.modelLibrary: ModelCatalogView(studio: studio)
case "Agents": AgentSettings(studio: studio)
case "Generation": GenerationSettingsView()
case "Knowledge Base": PegasusKnowledgeSettings(studio: studio)
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)
}
}
}
private enum StudioShortcut: String, CaseIterable, Identifiable {
case increase, decrease, reset, theme, workspaceMode
var id: Self { self }
var title: String {
switch self {
case .increase: "Increase chat font"
case .decrease: "Decrease chat font"
case .reset: "Reset chat font"
case .theme: "Cycle theme"
case .workspaceMode: "Cycle workspace mode"
}
}
var defaultKey: String {
switch self {
case .increase: "="
case .decrease: "-"
case .reset: "0"
case .theme: "3"
case .workspaceMode: "9"
}
}
static let choices = ["=", "-", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
func key(in data: Data) -> String {
let saved = (try? JSONDecoder().decode([String: String].self, from: data)) ?? [:]
return saved[rawValue].flatMap { Self.choices.contains($0) ? $0 : nil } ?? defaultKey
}
func shortcut(in data: Data) -> KeyEquivalent {
KeyEquivalent(key(in: data).first ?? "0")
}
}
struct StudioAppearanceView: View {
@AppStorage("studioTheme") private var theme = StudioTheme.system
@AppStorage("studioAccent") private var accent = StudioAccent.storm
@AppStorage("studioCustomThemes") private var customThemesData = Data()
@AppStorage("studioCustomThemeID") private var customThemeID = ""
@AppStorage("studioPalette") private var palette = StudioPalette.system
@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 = ""
@AppStorage("studioShortcutKeys") private var shortcutData = Data()
@AppStorage("renderChatMarkdown") private var renderMarkdown = true
@AppStorage("compactChatMessages") private var compactMessages = false
@AppStorage("expandChatThinking") private var expandThinking = false
@State private var draft: StudioCustomTheme?
private var customThemes: [StudioCustomTheme] {
StudioCustomTheme.decode(customThemesData)
}
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("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("Theme Library") {
ForEach(StudioPalette.allCases) { entry in
Button {
palette = entry
customThemeID = ""
} label: {
themeRow(entry.rawValue, light: entry.surface(dark: false), dark: entry.surface(dark: true),
selected: customThemeID.isEmpty && palette == entry)
}
.buttonStyle(.plain)
}
ForEach(customThemes) { entry in
HStack {
Button {
customThemeID = entry.id
} label: {
themeRow(entry.name, light: entry.surface(dark: false), dark: entry.surface(dark: true),
selected: customThemeID == entry.id)
}
.buttonStyle(.plain)
Button("Edit") { draft = entry }
}
}
Button("New Theme", systemImage: "plus") { draft = StudioCustomTheme() }
Picker("Built-in accent", selection: $accent) {
ForEach(StudioAccent.allCases) { entry in
Label(entry.rawValue, systemImage: "circle.fill").foregroundStyle(entry.color).tag(entry)
}
}
.disabled(!customThemeID.isEmpty)
}
Section("Chat Display") {
Toggle("Render Markdown", isOn: $renderMarkdown)
Toggle("Compact messages", isOn: $compactMessages)
Toggle("Expand thinking by default", isOn: $expandThinking)
}
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(StudioShortcut.allCases.filter { query.isEmpty || $0.title.localizedCaseInsensitiveContains(query) }) { action in
Picker(action.title, selection: Binding(
get: { action.key(in: shortcutData) },
set: { key in
var saved = (try? JSONDecoder().decode([String: String].self, from: shortcutData)) ?? [:]
saved[action.rawValue] = key
if let data = try? JSONEncoder().encode(saved) { shortcutData = data }
}
)) {
let used = Set(StudioShortcut.allCases.filter { $0 != action }.map { $0.key(in: shortcutData) })
ForEach(StudioShortcut.choices.filter { !used.contains($0) }, id: \.self) { key in
Text("⌘ \(key)").tag(key)
}
}
}
Button("Reset Shortcuts") { shortcutData = Data() }
LabeledContent("Send chat message", value: "Return")
LabeledContent("Insert newline", value: "⇧ Return")
}
}
.formStyle(.grouped)
.sheet(item: $draft) { entry in
StudioThemeEditor(theme: entry, canDelete: customThemes.contains { $0.id == entry.id }) { edited in
var entries = customThemes.filter { $0.id != entry.id }
if let edited {
let index = customThemes.firstIndex { $0.id == entry.id } ?? entries.endIndex
entries.insert(edited, at: index)
customThemeID = edited.id
} else if customThemeID == entry.id {
customThemeID = ""
}
if let data = try? JSONEncoder().encode(entries) { customThemesData = data }
draft = nil
}
}
}
private func themeRow(_ name: String, light: Color, dark: Color, selected: Bool) -> some View {
HStack {
RoundedRectangle(cornerRadius: 4).fill(light).frame(width: 18, height: 18)
.overlay(RoundedRectangle(cornerRadius: 4).strokeBorder(.secondary.opacity(0.4)))
RoundedRectangle(cornerRadius: 4).fill(dark).frame(width: 18, height: 18)
.overlay(RoundedRectangle(cornerRadius: 4).strokeBorder(.secondary.opacity(0.4)))
Text(name)
Spacer()
if selected { Image(systemName: "checkmark").accessibilityLabel("Selected") }
}
.contentShape(Rectangle())
}
}
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 = ""
@State private var backups: [URL] = []
@AppStorage("workspaceLocation") private var workspaceLocation = ""
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(workspaceLocation.isEmpty ? StudioModel.workspaceDirectory.path : workspaceLocation).textSelection(.enabled)
Button("Reveal Workspace in Finder") { NSWorkspace.shared.activateFileViewerSelecting([StudioModel.workspaceDirectory]) }
Button("Change Workspace Folder…") {
chooseFolder { folder in
try studio.relocateWorkspace(to: folder)
status = "Workspace copied and opened at the new location."
}
}
.disabled(studio.running || studio.importingDocument)
}
Section("Restore") {
Button("Choose Backup…") { restoring = true }
.disabled(studio.running || studio.importingDocument)
Button("Scan Folder for Backups…") {
chooseFolder { folder in
let files = try FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.isRegularFileKey], options: .skipsHiddenFiles)
backups = files.filter {
["sqlite", "sqlite3", "db"].contains($0.pathExtension.lowercased()) && Store.isWorkspaceBackup($0)
}.sorted { $0.lastPathComponent.localizedStandardCompare($1.lastPathComponent) == .orderedAscending }
status = "Found \(backups.count) workspace backups."
}
}
ForEach(backups, id: \.self) { url in
Button(url.lastPathComponent) { pending = url; confirm = true }
.disabled(studio.running || studio.importingDocument)
.help(url.path)
}
Button("Import Msty Studio Chats…", action: importMsty)
.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 chooseFolder(_ action: @escaping (URL) throws -> Void) {
let panel = NSOpenPanel()
panel.canChooseDirectories = true
panel.canChooseFiles = false
panel.canCreateDirectories = true
panel.begin { result in
guard result == .OK, let url = panel.url else { return }
do { try action(url) }
catch { status = error.localizedDescription }
}
}
private func importMsty() {
let panel = NSOpenPanel()
panel.allowedContentTypes = UTType(filenameExtension: "db").map { [$0] } ?? [.data]
panel.directoryURL = URL.applicationSupportDirectory.appending(path: "MstyStudio/data/workspaces/default")
panel.begin { result in
guard result == .OK, let url = panel.url else { return }
do { status = "Imported \(try studio.importMstyChats(from: url)) Msty chat threads." }
catch { status = error.localizedDescription }
}
}
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 }
}
}
struct WebToolsView: View {
@ObservedObject var studio: StudioModel
@Binding var section: ToolboxSheet.Section
let done: () -> Void
@AppStorage("webSearchEndpoint") private var endpoint = ""
@State private var query = ""
@State private var address = ""
@State private var results: [WebSearchResult] = []
@State private var page: WebPage?
@State private var status = ""
@State private var operation: Task<Void, Never>?
var body: some View {
Form {
if section == .search {
Section("Web Search") {
TextField("SearXNG search URL", text: $endpoint, prompt: Text("https://your-server/search"))
TextField("Search query", text: $query)
HStack {
Button("Search") {
let source = endpoint
let term = query
run {
results = []
results = try await WebSearch.results(endpoint: source, query: term)
if results.isEmpty { status = "No usable search results." }
}
}.disabled(operation != nil || query.isEmpty)
Button("Search in Browser") { searchInBrowser() }.disabled(query.isEmpty)
if operation != nil { Button("Cancel") { operation?.cancel() } }
}
Text("Search uses Bing by default. In chat, ask to search the web and AI Studio fetches result pages and relevant links before the model replies. Enter a SearXNG URL to use your own search instance.")
.foregroundStyle(.secondary)
ForEach(results) { result in
VStack(alignment: .leading, spacing: 5) {
Link(result.title, destination: result.url)
Text(result.url.host ?? "").font(.caption).foregroundStyle(.secondary)
if !result.snippet.isEmpty { Text(result.snippet) }
HStack {
Button("Retrieve") {
section = .retrieve
retrieve(result.url.absoluteString)
}.disabled(operation != nil)
Button("Attach Result") {
attach(result.title, result.reference, source: .init(url: result.url, title: result.title, kind: .searchSnippet))
}
.disabled(studio.running || operation != nil)
}
}
}
}
} else {
Section("Retrieve Page") {
Text("Fetches readable text from a page. Paste a URL into chat to retrieve it automatically, or preview it here before attaching it.")
.foregroundStyle(.secondary)
TextField("Page URL", text: $address, prompt: Text("https://example.com/article"))
Button("Retrieve Page") { retrieve(address) }.disabled(operation != nil || address.isEmpty)
if let page {
Link(page.url.absoluteString, destination: page.url).lineLimit(2)
ScrollView {
Text(page.text).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)
}.frame(height: 145)
Button("Attach Page to Chat") {
attach("Web page", page.reference, source: .init(url: page.url, title: page.title, kind: .page))
}
.disabled(studio.running || operation != nil)
}
}
}
if !status.isEmpty { Text(status).foregroundStyle(.secondary).textSelection(.enabled) }
}
.formStyle(.grouped)
.onDisappear { operation?.cancel() }
}
private func searchInBrowser() {
var url = URLComponents(string: "https://duckduckgo.com/")
url?.queryItems = [URLQueryItem(name: "q", value: query)]
if let destination = url?.url { NSWorkspace.shared.open(destination) }
}
private func retrieve(_ source: String) {
address = source
run {
page = nil
page = try await WebClipCapture.page(from: source)
}
}
private func run(_ work: @escaping @MainActor () async throws -> Void) {
guard operation == nil else { return }
status = "Loading…"
operation = Task {
defer { operation = nil }
do {
status = ""
try await work()
} catch { status = Task.isCancelled ? "Cancelled." : error.localizedDescription }
}
}
private func attach(_ title: String, _ reference: String, source: WebReplySource) {
studio.attachToolResult(name: title, output: reference, webSource: source)
done()
}
}
enum StudioPalette: String, CaseIterable, Identifiable {
case system = "System", storm = "Storm", ash = "Ash", carbon = "Carbon", dusk = "Dusk"
case sage = "Sage", ocean = "Ocean", linen = "Linen", ember = "Ember"
var id: Self { self }
private var hue: Double {
switch self {
case .system: 0
case .storm: 0.61
case .ash: 0.55
case .carbon: 0.68
case .dusk: 0.75
case .sage: 0.30
case .ocean: 0.48
case .linen: 0.10
case .ember: 0.045
}
}
private var saturation: Double {
switch self { case .system, .carbon: 0; case .ash, .linen: 0.18; default: 0.36 }
}
func surface(dark: Bool) -> Color {
if self == .system { return Color(nsColor: .windowBackgroundColor) }
return Color(hue: hue, saturation: dark ? saturation : saturation * 0.34, brightness: dark ? 0.135 : 0.98)
}
func message(dark: Bool, user: Bool) -> Color {
if self == .system { return user ? .accentColor.opacity(0.08) : .secondary.opacity(0.06) }
return Color(hue: hue, saturation: saturation * (user ? 1.1 : 0.60),
brightness: dark ? (user ? 0.24 : 0.19) : (user ? 0.93 : 0.96))
}
}
private struct StudioCustomTheme: Codable, Identifiable {
var id = UUID().uuidString
var name = ""
var light = "F5F6FA"
var dark = "171B26"
var accent = "597CE0"
static func decode(_ data: Data) -> [Self] {
(try? JSONDecoder().decode([Self].self, from: data)) ?? []
}
static func selected(_ id: String, in data: Data) -> Self? {
guard !id.isEmpty else { return nil }
return decode(data).first { $0.id == id }
}
static func color(_ text: String) -> Color? {
let hex = text.trimmingCharacters(in: .whitespacesAndNewlines)
let digits = hex.hasPrefix("#") ? String(hex.dropFirst()) : hex
guard digits.count == 6, digits.allSatisfy({ $0.isASCII && $0.isHexDigit }),
let rgb = Int(digits, radix: 16) else { return nil }
return Color(red: Double((rgb >> 16) & 255) / 255,
green: Double((rgb >> 8) & 255) / 255,
blue: Double(rgb & 255) / 255)
}
var accentColor: Color { Self.color(accent) ?? .accentColor }
func surface(dark isDark: Bool) -> Color {
Self.color(isDark ? dark : light) ?? Color(nsColor: .windowBackgroundColor)
}
func message(dark: Bool, user: Bool) -> Color {
user ? accentColor.opacity(0.16) : (dark ? Color.white : Color.black).opacity(0.06)
}
}
private struct StudioThemeEditor: View {
@State var theme: StudioCustomTheme
let canDelete: Bool
let save: (StudioCustomTheme?) -> Void
@Environment(\.dismiss) private var dismiss
var body: some View {
Form {
TextField("Theme name", text: $theme.name)
colorField("Light background", text: $theme.light)
colorField("Dark background", text: $theme.dark)
colorField("Accent", text: $theme.accent)
Text("Enter six-digit hex colors, such as #597CE0.").foregroundStyle(.secondary)
HStack {
if canDelete { Button("Delete Theme", role: .destructive) { save(nil) } }
Spacer()
Button("Cancel") { dismiss() }.keyboardShortcut(.cancelAction)
Button("Save Theme") {
theme.name = theme.name.trimmingCharacters(in: .whitespacesAndNewlines)
save(theme)
}
.keyboardShortcut(.defaultAction)
.disabled(theme.name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||
[theme.light, theme.dark, theme.accent].contains { StudioCustomTheme.color($0) == nil })
}
}
.padding(24)
.frame(width: 460)
}
private func colorField(_ label: String, text: Binding<String>) -> some View {
LabeledContent(label) {
RoundedRectangle(cornerRadius: 4).fill(StudioCustomTheme.color(text.wrappedValue) ?? .clear)
.frame(width: 20, height: 20)
TextField(label, text: text).labelsHidden().frame(width: 115)
}
}
}
private struct AgentSettings: View {
@ObservedObject var studio: StudioModel
@AppStorage("agentWorkflowEnabled") private var enabled = false
@AppStorage("agentPlannerEnabled") private var planner = true
@AppStorage("agentSpecialistEnabled") private var specialist = true
@AppStorage("agentMCPEnabled") private var mcpEnabled = false
@AppStorage(AgentProfile.storageKey) private var profileData = Data()
@AppStorage(AgentProfile.overridesKey) private var overridesData = Data()
private struct Editing: Identifiable {
let profile: AgentProfile
var role: AgentRole?
var id: UUID { profile.id }
}
@State private var editing: Editing?
private var overrides: [String: AgentProfile] {
(try? JSONDecoder().decode([String: AgentProfile].self, from: overridesData)) ?? [:]
}
@State private var removing: AgentProfile?
private var profiles: [AgentProfile] { AgentProfile.read(profileData) }
var body: some View {
Form {
Section("Chat Agents") {
Toggle("Run agents when sending messages", isOn: $enabled)
builtInRow(.planner, enabled: $planner)
builtInRow(.specialist, enabled: $specialist)
builtInRow(.reviewer)
Toggle("Let the specialist request an MCP tool", isOn: $mcpEnabled)
.disabled(!specialist)
Text("Enable Agents in chat, describe a task, and send it. The planner outlines the work, the specialist drafts a response, and the reviewer checks and delivers it. They share the model selected in Models.")
.foregroundStyle(.secondary)
Text("Connect tools in Toolbox. The specialist can ask for one tool call per run in the main chat. Review the tool, server, and arguments before allowing it. Toolbox results can also be attached before sending.")
.foregroundStyle(.secondary)
}
.disabled(studio.running)
Section("Custom Agents") {
Text("Give each agent a name, a task, and instructions for what it should hand off. Enabled agents run in the order shown, before the reviewer.")
.foregroundStyle(.secondary)
Button("New Agent", systemImage: "plus") {
editing = Editing(profile: AgentProfile(name: "", instructions: ""))
}
.disabled(profiles.count >= AgentProfile.limit)
ForEach(profiles) { profile in
HStack {
Toggle(profile.name, isOn: Binding(get: { profile.enabled }, set: { enabled in
var updated = profile
updated.enabled = enabled
save(updated)
}))
Spacer()
Button("Edit") { editing = Editing(profile: profile) }
Button("Remove…", role: .destructive) { removing = profile }
}
}
}
.disabled(studio.running)
if studio.agentStage != nil || !studio.agentSteps.isEmpty {
Section("Latest Run") {
ForEach(studio.agentSteps.indices, id: \.self) { index in
Label(studio.agentSteps[index], systemImage: "circle")
}
if let role = studio.agentStage {
LabeledContent("Current stage", value: role.name)
}
}
}
}
.formStyle(.grouped)
.sheet(item: $editing) { selection in
AgentProfileEditor(
profile: selection.profile,
promptSettings: selection.profile.promptSettings ?? .init(),
templates: studio.snippets.filter { $0.kind == .prompt },
save: { updated in
if let role = selection.role { saveOverride(updated, for: role) }
else { save(updated) }
editing = nil
},
cancel: { editing = nil },
reset: selection.role.map { role in
{
saveOverride(nil, for: role)
editing = nil
}
}
)
}
.confirmationDialog("Remove this agent?", isPresented: Binding(
get: { removing != nil }, set: { if !$0 { removing = nil } }
), presenting: removing) { profile in
Button("Remove Agent", role: .destructive) {
if let data = try? JSONEncoder().encode(profiles.filter { $0.id != profile.id }) {
profileData = data
}
removing = nil
}
} message: { profile in Text(profile.name) }
}
private func builtInRow(_ role: AgentRole, enabled: Binding<Bool>? = nil) -> some View {
let profile = overrides[role.name] ?? AgentProfile(name: role.name, instructions: role.instructions)
return HStack {
if let enabled {
Toggle(profile.name, isOn: enabled)
} else {
Text(profile.name)
Text("Final response").foregroundStyle(.secondary)
}
Spacer()
Button("Edit") {
editing = Editing(profile: profile, role: role)
}
.accessibilityLabel("Edit " + profile.name)
}
}
private func saveOverride(_ profile: AgentProfile?, for role: AgentRole) {
var saved = overrides
saved[role.name] = profile
if let data = try? JSONEncoder().encode(saved) { overridesData = data }
}
private func save(_ profile: AgentProfile) {
var updated = profiles
if let index = updated.firstIndex(where: { $0.id == profile.id }) {
updated[index] = profile
} else if updated.count < AgentProfile.limit {
updated.append(profile)
}
if let data = try? JSONEncoder().encode(updated) { profileData = data }
}
}
private struct AgentProfileEditor: View {
@State var profile: AgentProfile
@State var promptSettings: AgentPromptSettings
let templates: [WorkspaceSnippet]
let save: (AgentProfile) -> Void
let cancel: () -> Void
var reset: (() -> Void)? = nil
private var name: String { profile.name.trimmingCharacters(in: .whitespacesAndNewlines) }
private var instructions: String { profile.instructions.trimmingCharacters(in: .whitespacesAndNewlines) }
private var validSettings: Bool {
do {
_ = try PromptBudget.limit(promptSettings.contextBudget)
_ = try promptSettings.outputLimit()
return true
} catch { return false }
}
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Agent Profile").font(.headline)
TextField("Name", text: $profile.name, prompt: Text("Technical Editor"))
Text("Instructions").font(.subheadline)
TextEditor(text: $profile.instructions)
.font(.body)
.accessibilityLabel("Agent instructions")
.border(.quaternary)
Text("Describe the work, the evidence to use, and the output to pass to the next agent.")
.foregroundStyle(.secondary)
Picker("Prompt template", selection: $promptSettings.templateID) {
Text("Inherit chat template").tag(nil as UUID?)
ForEach(templates) { Text($0.title).tag(Optional($0.id)) }
if let id = promptSettings.templateID, !templates.contains(where: { $0.id == id }) {
Text("Unavailable template").tag(Optional(id))
}
}
TextField("Context budget (64–1,048,576)", text: $promptSettings.contextBudget)
TextField("Maximum output tokens", text: $promptSettings.outputTokens)
Toggle("Use local document excerpts", isOn: $promptSettings.useDocuments)
HStack {
Spacer()
if let reset { Button("Restore Default", action: reset) }
Button("Cancel", action: cancel).keyboardShortcut(.cancelAction)
Button("Save Agent") {
profile.name = name
profile.instructions = instructions
profile.promptSettings = promptSettings
save(profile)
}
.disabled(name.isEmpty || name.count > 60 || instructions.isEmpty || instructions.count > 4_000 || !validSettings)
.help("Enter a name of up to 60 characters and instructions of up to 4,000 characters.")
}
}
.padding(18)
.frame(width: 510, height: 460)
}
}
private struct AgentToolApprovalView: View {
let approval: StudioModel.AgentToolApproval
let resolve: (Bool) -> Void
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Allow this MCP tool call?").font(.headline)
LabeledContent("Server", value: approval.server)
LabeledContent("Tool", value: approval.tool)
ScrollView {
Text(String(decoding: approval.arguments, as: UTF8.self))
.font(.system(.body, design: .monospaced))
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(8)
}
.background(.quaternary, in: RoundedRectangle(cornerRadius: 6))
HStack {
Spacer()
Button("Decline") { resolve(false) }.keyboardShortcut(.cancelAction)
Button("Allow Once") { resolve(true) }
}
}
.padding(18)
.frame(width: 500, height: 340)
.interactiveDismissDisabled()
}
}