Add custom MCP profiles and reusable workspace libraries

This commit is contained in:
Mark Gregory
2026-11-16 14:50:20 +00:00
parent bc2ae8ec02
commit 32c4b9f91c
12 changed files with 1398 additions and 76 deletions
+603 -28
View File
@@ -6,6 +6,10 @@ import UniformTypeIdentifiers
@main
struct AIStudioApp: App {
@StateObject private var studio = StudioModel()
@AppStorage("studioTheme") private var theme = StudioTheme.system
@AppStorage("studioAccent") private var accent = StudioAccent.storm
@AppStorage("studioChatSize") private var chatSize = 14
@AppStorage("studioMode") private var mode = StudioMode.normal
var body: some Scene {
Window("AI Studio", id: "studio") {
@@ -17,29 +21,33 @@ struct AIStudioApp: App {
}
}
.frame(minWidth: 740, minHeight: 500)
.preferredColorScheme(theme.colorScheme)
.tint(accent.color)
.task {
await Task.yield()
studio.open()
}
}
.defaultSize(width: 1000, height: 700)
Settings {
TabView {
BackendSettings(studio: studio)
.tabItem { Label("Models", systemImage: "cpu") }
ModelCatalogView(studio: studio)
.tabItem { Label("MLX Catalog", systemImage: "arrow.down.circle") }
GenerationSettingsView()
.tabItem { Label("Generation", systemImage: "slider.horizontal.3") }
LocalToolsView(studio: studio)
.tabItem { Label("Local Tools", systemImage: "terminal") }
RuntimeSettingsView(studio: studio)
.tabItem { Label("Runtime", systemImage: "waveform.path") }
MCPSettings(studio: studio)
.tabItem { Label("MCP Tools", systemImage: "wrench.and.screwdriver") }
.commands {
CommandMenu("Appearance") {
Button("Increase Chat Font Size") { chatSize = min(28, chatSize + 1) }.keyboardShortcut("=")
Button("Decrease Chat Font Size") { chatSize = max(10, chatSize - 1) }.keyboardShortcut("-")
Button("Reset Chat Font Size") { chatSize = 14 }.keyboardShortcut("0")
Button("Cycle Theme") { theme = nextValue(theme) }.keyboardShortcut("3")
Button("Cycle Workspace Mode") { mode = nextValue(mode) }.keyboardShortcut("9")
}
.frame(width: 630, height: 600)
}
Settings {
StudioSettingsView(studio: studio)
.preferredColorScheme(theme.colorScheme)
.tint(accent.color)
}
}
private func nextValue<Value: CaseIterable & Equatable>(_ current: Value) -> Value {
let all = Array(Value.allCases)
return all[((all.firstIndex(of: current) ?? 0) + 1) % all.count]
}
}
@@ -60,6 +68,14 @@ struct ChatView: View {
@AppStorage(GenerationSettings.key) private var generationSettings = Data()
@State private var showingPromptBuilder = false
@State private var showingPerformance = false
@State private var showingWorkspace = false
@State private var showingToolbox = false
@AppStorage("composerSpellCheck") private var spellCheck = true
@AppStorage("composerAutoCorrect") private var autoCorrect = false
@AppStorage("studioChatSize") private var chatSize = 14
@AppStorage("studioChatFont") private var chatFont = StudioFont.system
@AppStorage("studioMode") private var mode = StudioMode.normal
@State private var columns: NavigationSplitViewVisibility = .all
@State private var confirmDelete = false
@State private var search = ""
@State private var renaming = false
@@ -77,7 +93,7 @@ struct ChatView: View {
@State private var useDocuments = false
var body: some View {
NavigationSplitView {
NavigationSplitView(columnVisibility: $columns) {
List(visibleChats, selection: $studio.selected) { chat in
Label(chat.title, systemImage: "bubble.left").tag(chat.id)
}
@@ -113,12 +129,19 @@ struct ChatView: View {
Button("Documents", systemImage: "doc.on.doc") { showingLibrary = true }
.disabled(studio.selected == nil)
Button("Prompt Builder", systemImage: "wand.and.stars") { showingPromptBuilder = true }
Button("Workspace", systemImage: "square.stack.3d.up") { showingWorkspace = true }
Button("Performance", systemImage: "chart.xyaxis.line") { showingPerformance = true }
SettingsLink { Label("Settings", systemImage: "gear") }
}
}
.toolbar(mode == .zen ? .hidden : .visible, for: .windowToolbar)
.onChange(of: mode, initial: true) { _, value in columns = value == .normal ? .all : .detailOnly }
.sheet(isPresented: $showingLibrary) { DocumentLibraryView(studio: studio) }
.sheet(isPresented: $showingPerformance) { PerformanceDashboard(studio: studio) }
.sheet(isPresented: $showingWorkspace) { WorkspaceResourcesView(studio: studio) }
.sheet(isPresented: $showingToolbox) {
ToolboxSheet(studio: studio).frame(width: 650, height: 620)
}
.sheet(isPresented: $showingPromptBuilder) {
PromptBuilder(customPrompt: $customPrompt) { instructions, global in
if global {
@@ -129,7 +152,15 @@ struct ChatView: View {
}
}
}
.onChange(of: studio.selected) { _, _ in useDocuments = false }
.onChange(of: studio.selected) { old, _ in
useDocuments = false
if old != nil {
studio.activeStack = nil
studio.activeSkill = nil
studio.activeContext = nil
studio.activeWebClip = nil
}
}
.alert("Rename Chat", isPresented: $renaming) {
TextField("Title", text: $newTitle)
Button("Rename") { studio.renameSelectedChat(newTitle) }
@@ -154,6 +185,7 @@ struct ChatView: View {
.padding(24)
.frame(maxWidth: .infinity)
}
.font(chatFont.font(size: chatSize))
.onChange(of: studio.messages.count, initial: true) { _, _ in proxy.scrollTo("end", anchor: .bottom) }
.onChange(of: studio.partial) { _, _ in proxy.scrollTo("end", anchor: .bottom) }
}
@@ -196,25 +228,38 @@ struct ChatView: View {
}
.font(.caption)
}
TextEditor(text: $studio.prompt)
.font(.body)
HStack(spacing: 10) {
Button {
showingToolbox = true
} label: {
Label(studio.activeToolset == nil ? "Toolbox" : "1 Active Toolset",
systemImage: "wrench.and.screwdriver")
}
.buttonStyle(.bordered)
if let toolset = studio.activeToolset {
Text("\(toolset.name) · \(toolset.tools.count) tools").lineLimit(1).foregroundStyle(.secondary)
}
if studio.activeStack != nil || studio.activeSkill != nil ||
studio.activeContext != nil || studio.activeWebClip != nil {
Button("Active Resources", systemImage: "square.stack") { showingWorkspace = true }
.buttonStyle(.borderless)
}
Spacer()
}
.font(.caption)
ChatComposerInput(text: $studio.prompt, canSend: !studio.running, spellCheck: spellCheck,
autoCorrect: autoCorrect, font: chatFont.appKit(size: chatSize), send: sendMessage)
.frame(height: 62)
.padding(5)
.background(.background, in: RoundedRectangle(cornerRadius: 8))
.overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(.quaternary))
.accessibilityLabel("Message")
HStack {
Text(studio.status).font(.caption).foregroundStyle(.secondary).textSelection(.enabled)
Spacer()
if studio.running {
Button("Stop", systemImage: "stop.fill") { studio.stop() }
} else {
Button("Send", systemImage: "arrow.up") {
studio.send(endpoint: activeEndpoint, model: activeModel, mlxPath: mlxPath, thinking: thinking,
failover: failover, mlxOnly: mlxOnly, compatible: compatibleEnabled, recall: recall, useDocuments: useDocuments,
instructions: promptMode.instructions(custom: customPrompt),
settings: GenerationSettings.read(generationSettings))
}
Button("Send", systemImage: "arrow.up", action: sendMessage)
.buttonStyle(.borderedProminent)
.keyboardShortcut(.return, modifiers: .command)
.disabled(studio.prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
@@ -223,6 +268,13 @@ struct ChatView: View {
}
.padding(16)
}
private func sendMessage() {
studio.send(endpoint: activeEndpoint, model: activeModel, mlxPath: mlxPath, thinking: thinking,
failover: failover, mlxOnly: mlxOnly, compatible: compatibleEnabled, recall: recall, useDocuments: useDocuments,
instructions: promptMode.instructions(custom: customPrompt),
settings: GenerationSettings.read(generationSettings))
}
}
struct MessageView: View {
@@ -472,6 +524,8 @@ private func copyChatText(_ text: String) {
struct ChatMarkdown: View {
let text: String
@AppStorage("studioCodeTheme") private var codeTheme = StudioTheme.system
@Environment(\.colorScheme) private var currentScheme
struct Block: Equatable {
let content: String
@@ -527,6 +581,7 @@ struct ChatMarkdown: View {
}
.padding(10)
.background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 8))
.environment(\.colorScheme, codeTheme.colorScheme ?? currentScheme)
} else {
let parsed = try? AttributedString(markdown: block.content,
options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))
@@ -625,8 +680,11 @@ struct PerformanceDashboard: View {
Spacer()
Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)
}
Text("Up to 50 generations from this session. First output includes model loading and any fallback.")
Text("Last 50 generations. First output includes model loading and any fallback.")
.foregroundStyle(.secondary)
if studio.running {
Label("Generation in progress…", systemImage: "ellipsis").foregroundStyle(.secondary)
}
if studio.measurements.isEmpty {
ContentUnavailableView("No measurements yet", systemImage: "chart.xyaxis.line",
description: Text("Send a chat message to collect timing and throughput."))
@@ -646,7 +704,9 @@ struct PerformanceDashboard: View {
TableColumn("Total") { Text(seconds($0.seconds)) }
TableColumn("Tokens/s") { Text($0.provider?.tokensPerSecond.map { $0.formatted(.number.precision(.fractionLength(1))) } ?? "—") }
TableColumn("Tokens") { Text($0.provider?.tokens.formatted() ?? "—") }
TableColumn("Characters") { Text($0.characters.formatted()) }
TableColumn("Characters/s") { run in
Text(run.charactersPerSecond.map { $0.formatted(.number.precision(.fractionLength(1))) } ?? "—")
}
TableColumn("Outcome", value: \.outcome)
}
}
@@ -1035,3 +1095,518 @@ struct RuntimeSettingsView: View {
}
}
}
struct ChatComposerInput: NSViewRepresentable {
@Binding var text: String
var canSend: Bool
var spellCheck: Bool
var autoCorrect: Bool
var font: NSFont
var send: () -> Void
func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeNSView(context: Context) -> NSScrollView {
let scroll = NSTextView.scrollableTextView()
guard let editor = scroll.documentView as? NSTextView else { return scroll }
editor.isRichText = false
editor.font = font
editor.delegate = context.coordinator
editor.drawsBackground = false
scroll.drawsBackground = false
editor.setAccessibilityLabel("Message")
return scroll
}
func updateNSView(_ scroll: NSScrollView, context: Context) {
context.coordinator.parent = self
if let editor = scroll.documentView as? NSTextView {
editor.font = font
editor.isContinuousSpellCheckingEnabled = spellCheck
editor.isAutomaticSpellingCorrectionEnabled = autoCorrect
if editor.string != text {
editor.string = text
editor.setSelectedRange(NSRange(location: text.utf16.count, length: 0))
}
}
}
static func sendsReturn(modifiers: NSEvent.ModifierFlags, marked: Bool) -> Bool {
!marked && modifiers.intersection([.shift, .command, .option, .control]).isEmpty
}
final class Coordinator: NSObject, NSTextViewDelegate {
var parent: ChatComposerInput
init(_ parent: ChatComposerInput) { self.parent = parent }
func textDidChange(_ notification: Notification) {
guard let editor = notification.object as? NSTextView else { return }
parent.text = editor.string
}
func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
guard commandSelector == #selector(NSResponder.insertNewline(_:)),
let event = NSApp.currentEvent,
event.type == .keyDown,
ChatComposerInput.sendsReturn(modifiers: event.modifierFlags, marked: textView.hasMarkedText()) else {
return false
}
if parent.canSend { parent.send() }
return true
}
}
}
struct ToolboxSheet: View {
@Environment(\.dismiss) private var dismiss
@ObservedObject var studio: StudioModel
var body: some View {
VStack(spacing: 0) {
HStack {
Label("Toolbox", systemImage: "wrench.and.screwdriver").font(.headline)
Spacer()
Button("Done") { dismiss() }
}
.padding()
MCPSettings(studio: studio)
}
}
}
struct WorkspaceResourcesView: View {
@Environment(\.dismiss) private var dismiss
@ObservedObject var studio: StudioModel
var body: some View {
VStack(spacing: 0) {
HStack {
Text("Workspace").font(.title2.bold())
Spacer()
Button("Done") { dismiss() }
}
.padding()
TabView {
KnowledgeStacksView(studio: studio).tabItem { Label("Stacks", systemImage: "square.stack.3d.up") }
WorkspaceSnippetsView(studio: studio, kind: .skill).tabItem { Label("Skills", systemImage: "bolt") }
WorkspaceSnippetsView(studio: studio, kind: .context).tabItem { Label("Contexts", systemImage: "doc.text") }
WorkspaceSnippetsView(studio: studio, kind: .prompt).tabItem { Label("Prompts", systemImage: "text.bubble") }
WorkspaceSnippetsView(studio: studio, kind: .webClip).tabItem { Label("Web Clips", systemImage: "link") }
}
if !studio.workspaceStatus.isEmpty {
Text(studio.workspaceStatus).foregroundStyle(.red).textSelection(.enabled).padding(8)
}
}
.frame(width: 720, height: 560)
}
}
struct KnowledgeStacksView: View {
@ObservedObject var studio: StudioModel
@State private var selected: UUID?
@State private var name = ""
@State private var documents: [LibraryDocument] = []
@State private var importing = false
@State private var busy = false
@State private var removing = false
var body: some View {
Form {
Section("Knowledge Stacks") {
HStack {
TextField("New stack name", text: $name)
Button("Create") {
selected = studio.createStack(name.trimmingCharacters(in: .whitespacesAndNewlines))
name = ""
}.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || busy)
}
Picker("Manage stack", selection: $selected) {
Text("Select a stack").tag(UUID?.none)
ForEach(studio.knowledgeStacks) { Text($0.title).tag(Optional($0.id)) }
}
Picker("Use in this chat", selection: $studio.activeStack) {
Text("None").tag(UUID?.none)
ForEach(studio.knowledgeStacks) { Text($0.title).tag(Optional($0.id)) }
}
Text("Matching passages from the active stack are included in inference requests.")
.foregroundStyle(.secondary)
}
if let selected {
Section("Indexed Documents") {
ForEach(documents) { document in
HStack {
Text(document.title)
Spacer()
Button("Remove", role: .destructive) {
studio.deleteStackDocument(document, in: selected)
refresh()
}.disabled(busy)
}
}
HStack {
Button("Import Document…") { importing = true }.disabled(busy)
if busy { ProgressView().controlSize(.small) }
Spacer()
Button("Delete Stack…", role: .destructive) { removing = true }.disabled(busy)
}
}
}
}
.formStyle(.grouped)
.onAppear { selected = studio.activeStack; refresh() }
.onChange(of: selected) { _, _ in refresh() }
.fileImporter(isPresented: $importing, allowedContentTypes: [
.pdf, .plainText, .commaSeparatedText, UTType(filenameExtension: "md") ?? .plainText
]) { result in
guard let url = try? result.get(), let selected else { return }
busy = true
Task {
await studio.importStackDocument(url, in: selected)
refresh()
busy = false
}
}
.confirmationDialog("Delete this stack and its index?", isPresented: $removing) {
Button("Delete Stack", role: .destructive) {
if let selected { studio.deleteStack(selected) }
selected = nil
}
}
}
private func refresh() { documents = selected.map(studio.stackDocuments) ?? [] }
}
struct WorkspaceSnippetsView: View {
@ObservedObject var studio: StudioModel
let kind: WorkspaceSnippet.Kind
@State private var search = ""
@State private var id: UUID?
@State private var title = ""
@State private var content = ""
@State private var address = ""
@State private var importing = false
@State private var capturing = false
@State private var deleting = false
@State private var error = ""
private var items: [WorkspaceSnippet] {
studio.snippets.filter {
$0.kind == kind && (search.isEmpty || $0.title.localizedCaseInsensitiveContains(search))
}
}
var body: some View {
HSplitView {
VStack(spacing: 8) {
TextField("Search \(kind.rawValue)s", text: $search)
List(items, selection: $id) { item in Text(item.title).tag(item.id) }
Button("New \(kind.rawValue)") { clear() }
}
.padding(12)
.frame(minWidth: 180, idealWidth: 220)
VStack(alignment: .leading, spacing: 10) {
TextField("Title", text: $title)
if kind == .webClip {
HStack {
TextField("Source URL", text: $address)
Button("Capture Text") {
capturing = true
let source = address
Task {
defer { capturing = false }
do {
content = try await WebClipCapture.text(from: source)
if title.isEmpty { title = URL(string: source)?.host ?? "Web Clip" }
error = ""
} catch { self.error = error.localizedDescription }
}
}.disabled(capturing || address.isEmpty)
}
}
TextEditor(text: $content).accessibilityLabel("\(kind.rawValue) text")
.border(.quaternary)
if !error.isEmpty { Text(error).foregroundStyle(.red).textSelection(.enabled) }
HStack {
if kind != .webClip { Button("Import Text…") { importing = true } }
if id != nil { Button("Delete…", role: .destructive) { deleting = true } }
Spacer()
if id != nil {
Button(kind == .prompt ? "Use in Composer" : isActive ? "Remove from Chat" : "Use in Chat") {
apply()
}.disabled(studio.running)
}
Button("Save", action: save).buttonStyle(.borderedProminent)
.disabled(title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||
content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || capturing)
}
}
.padding(15)
.frame(minWidth: 400)
}
.onChange(of: id) { _, value in
if let item = studio.snippets.first(where: { $0.id == value }) {
title = item.title
if kind == .webClip {
let parts = item.content.components(separatedBy: "\n\n")
address = String((parts.first ?? "").dropFirst("Source: ".count))
content = parts.dropFirst().joined(separator: "\n\n")
} else {
content = item.content
}
}
}
.fileImporter(isPresented: $importing, allowedContentTypes: [
.plainText, UTType(filenameExtension: "md") ?? .plainText
]) { result in
do {
let file = try result.get()
content = try LocalFilePreview.read(file, limit: 12000)
if title.isEmpty { title = file.deletingPathExtension().lastPathComponent }
error = ""
} catch { self.error = error.localizedDescription }
}
.confirmationDialog("Delete saved \(kind.rawValue.lowercased())?", isPresented: $deleting) {
Button("Delete", role: .destructive) {
if let id { studio.removeSnippet(id) }
clear()
}
}
}
private var isActive: Bool {
guard let id else { return false }
return switch kind {
case .skill: studio.activeSkill == id
case .context: studio.activeContext == id
case .webClip: studio.activeWebClip == id
case .prompt: false
}
}
private func apply() {
guard let item = studio.snippets.first(where: { $0.id == id }) else { return }
switch kind {
case .skill: studio.activeSkill = isActive ? nil : item.id
case .context: studio.activeContext = isActive ? nil : item.id
case .webClip: studio.activeWebClip = isActive ? nil : item.id
case .prompt: studio.prompt = item.content
}
}
private func save() {
if kind == .webClip {
do { _ = try WebClipCapture.url(address) }
catch { self.error = error.localizedDescription; return }
}
let key = id ?? UUID()
let stored = kind == .webClip ? "Source: \(address)\n\n\(content)" : content
studio.saveSnippet(id: key, kind: kind, title: title.trimmingCharacters(in: .whitespacesAndNewlines), content: stored)
id = key
error = ""
}
private func clear() { id = nil; title = ""; content = ""; address = ""; error = "" }
}
enum StudioTheme: String, CaseIterable, Identifiable {
case system = "System", light = "Light", dark = "Dark"
var id: Self { self }
var colorScheme: ColorScheme? {
switch self { case .system: nil; case .light: .light; case .dark: .dark }
}
}
enum StudioAccent: String, CaseIterable, Identifiable {
case storm = "Storm", moss = "Moss", ocean = "Ocean", dusk = "Dusk", ember = "Ember"
var id: Self { self }
var color: Color {
switch self { case .storm: .blue; case .moss: .green; case .ocean: .teal; case .dusk: .purple; case .ember: .orange }
}
}
enum StudioMode: String, CaseIterable, Identifiable {
case normal = "Normal", focus = "Focus", zen = "Zen"
var id: Self { self }
}
enum StudioFont: String, CaseIterable, Identifiable {
case system = "System", serif = "Serif", mono = "Monospaced"
var id: Self { self }
func font(size: Int) -> Font {
.system(size: CGFloat(size), design: self == .serif ? .serif : self == .mono ? .monospaced : .default)
}
func appKit(size: Int) -> NSFont {
switch self {
case .system: .systemFont(ofSize: CGFloat(size))
case .serif: NSFont(name: "Georgia", size: CGFloat(size)) ?? .systemFont(ofSize: CGFloat(size))
case .mono: .monospacedSystemFont(ofSize: CGFloat(size), weight: .regular)
}
}
}
struct StudioSettingsView: View {
@ObservedObject var studio: StudioModel
@State private var page: String? = "Models"
private let pages = [
("Models", "cpu"), ("MLX Library", "square.stack"), ("Generation", "slider.horizontal.3"),
("Toolbox", "wrench.and.screwdriver"), ("Local Tools", "terminal"), ("Runtime", "waveform.path"),
("Appearance", "paintpalette"), ("Workspace Data", "externaldrive")
]
var body: some View {
HSplitView {
List(selection: $page) {
ForEach(pages, id: \.0) { name, icon in Label(name, systemImage: icon).tag(name) }
}
.listStyle(.sidebar)
.frame(minWidth: 160, idealWidth: 180, maxWidth: 210)
Group {
switch page {
case "MLX Library": ModelCatalogView(studio: studio)
case "Generation": GenerationSettingsView()
case "Toolbox": MCPSettings(studio: studio)
case "Local Tools": LocalToolsView(studio: studio)
case "Runtime": RuntimeSettingsView(studio: studio)
case "Appearance": StudioAppearanceView()
case "Workspace Data": WorkspaceDataView(studio: studio)
default: BackendSettings(studio: studio)
}
}
.frame(minWidth: 570, maxWidth: .infinity, maxHeight: .infinity)
}
.frame(width: 780, height: 610)
}
}
struct StudioAppearanceView: View {
@AppStorage("studioTheme") private var theme = StudioTheme.system
@AppStorage("studioAccent") private var accent = StudioAccent.storm
@AppStorage("studioMode") private var mode = StudioMode.normal
@AppStorage("studioChatFont") private var font = StudioFont.system
@AppStorage("studioChatSize") private var size = 14
@AppStorage("studioCodeTheme") private var codeTheme = StudioTheme.system
@AppStorage("composerSpellCheck") private var spell = true
@AppStorage("composerAutoCorrect") private var correct = false
@State private var query = ""
var body: some View {
Form {
Section("Appearance") {
Picker("Color preference", selection: $theme) {
ForEach(StudioTheme.allCases) { Text($0.rawValue).tag($0) }
}
Picker("Workspace mode", selection: $mode) {
ForEach(StudioMode.allCases) { Text($0.rawValue).tag($0) }
}.pickerStyle(.segmented)
Picker("Accent", selection: $accent) {
ForEach(StudioAccent.allCases) { entry in
Label(entry.rawValue, systemImage: "circle.fill").foregroundStyle(entry.color).tag(entry)
}
}
Picker("Chat font", selection: $font) {
ForEach(StudioFont.allCases) { Text($0.rawValue).tag($0) }
}
Stepper(value: $size, in: 10...28) { LabeledContent("Chat font size", value: "\(size) pt") }
Picker("Code block appearance", selection: $codeTheme) {
ForEach(StudioTheme.allCases) { Text($0.rawValue).tag($0) }
}
}
Section("Composer") {
Toggle("Check spelling as you type", isOn: $spell)
Toggle("Correct spelling automatically", isOn: $correct)
}
Section("Keyboard Shortcuts") {
TextField("Find a shortcut", text: $query)
ForEach(shortcuts.filter { query.isEmpty || $0.0.localizedCaseInsensitiveContains(query) }, id: \.0) {
LabeledContent($0.0, value: $0.1)
}
}
}
.formStyle(.grouped)
}
private var shortcuts: [(String, String)] {
[("Send chat message", "Return"), ("Insert newline", "⇧ Return"), ("Open Settings", "⌘ ,"),
("Increase chat font", "⌘ ="), ("Decrease chat font", "⌘ −"), ("Reset chat font", "⌘ 0"),
("Cycle theme", "⌘ 3"), ("Cycle workspace mode", "⌘ 9")]
}
}
struct WorkspaceDataView: View {
@ObservedObject var studio: StudioModel
@AppStorage("workspaceBackupTime") private var lastBackup = 0.0
@AppStorage("workspaceBackupReminderDays") private var reminderDays = 0
@State private var restoring = false
@State private var pending: URL?
@State private var confirm = false
@State private var status = ""
var body: some View {
Form {
Section("Backup") {
LabeledContent("Last export", value: lastBackup > 0
? Date(timeIntervalSince1970: lastBackup).formatted(date: .abbreviated, time: .shortened)
: "None")
Button("Export Workspace…", action: export)
Stepper(value: $reminderDays, in: 0...30) {
LabeledContent("Remind every", value: reminderDays > 0 ? "\(reminderDays) day(s)" : "Off")
}
if reminderDays > 0 && (lastBackup == 0 || Date.now.timeIntervalSince1970 - lastBackup >= Double(reminderDays) * 86_400) {
Label("Workspace backup is due", systemImage: "exclamationmark.circle").foregroundStyle(.orange)
}
Text("Exports include chats, document indexes, stacks and saved resources.")
.foregroundStyle(.secondary)
}
Section("Storage") {
Text(StudioModel.workspaceDirectory.path).textSelection(.enabled)
Button("Reveal Workspace in Finder") { NSWorkspace.shared.activateFileViewerSelecting([StudioModel.workspaceDirectory]) }
}
Section("Restore") {
Button("Choose Backup…") { restoring = true }
.disabled(studio.running || studio.importingDocument)
if !status.isEmpty { Text(status).textSelection(.enabled).foregroundStyle(.secondary) }
}
}
.formStyle(.grouped)
.fileImporter(isPresented: $restoring, allowedContentTypes: [.data]) { result in
do { pending = try result.get(); confirm = true }
catch { status = error.localizedDescription }
}
.confirmationDialog("Replace the current workspace with this backup?", isPresented: $confirm) {
Button("Restore Workspace", role: .destructive) { restore() }
} message: {
Text("The current chats and saved resources will be replaced. Export a backup first if you need to keep them.")
}
}
private func export() {
let panel = NSSavePanel()
panel.nameFieldStringValue = "AIStudio-Workspace-\(Date.now.formatted(.iso8601.year().month().day())).sqlite"
panel.canCreateDirectories = true
panel.begin { response in
guard response == .OK, let url = panel.url else { return }
do {
try studio.exportWorkspace(to: url)
lastBackup = Date.now.timeIntervalSince1970
status = "Exported \(url.lastPathComponent)."
} catch { status = error.localizedDescription }
}
}
private func restore() {
guard let url = pending else { return }
let scoped = url.startAccessingSecurityScopedResource()
defer {
if scoped { url.stopAccessingSecurityScopedResource() }
pending = nil
}
do {
try studio.restoreWorkspace(from: url)
status = "Restored \(url.lastPathComponent)."
} catch { status = error.localizedDescription }
}
}