Complete workspace recovery, migration, and compatibility checks

This commit is contained in:
Mark Gregory
2026-11-17 10:45:55 +00:00
parent 47338fbeaa
commit 64afccf5ae
5 changed files with 550 additions and 44 deletions
+281 -22
View File
@@ -2,6 +2,7 @@ import SwiftUI
import AppKit
import Charts
import UniformTypeIdentifiers
import WebKit
@main
struct AIStudioApp: App {
@@ -12,6 +13,7 @@ struct AIStudioApp: App {
@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") {
@@ -33,11 +35,11 @@ struct AIStudioApp: App {
.defaultSize(width: 1000, height: 700)
.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")
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 {
@@ -70,6 +72,8 @@ struct ChatView: View {
@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?
@State private var showingWorkspace = false
@State private var showingToolbox = false
@AppStorage("chatDebugOutput") private var showDebugOutput = false
@@ -137,10 +141,13 @@ struct ChatView: View {
}
} detail: {
VStack(spacing: 0) {
if studio.messages.isEmpty && studio.partial == nil {
StudioWelcome(loading: false)
if showingComparison {
HSplitView {
currentTranscript.frame(minWidth: 280)
comparisonTranscript.frame(minWidth: 260)
}
} else {
transcript
currentTranscript
}
Divider()
composer
@@ -152,6 +159,11 @@ struct ChatView: View {
.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 { comparisonChat = studio.conversations.first { $0.id != studio.selected }?.id }
}
.disabled(studio.conversations.count < 2 && !showingComparison)
Button("Performance", systemImage: "chart.xyaxis.line") { showingPerformance = true }
SettingsLink { Label("Settings", systemImage: "gear") }
}
@@ -220,6 +232,43 @@ struct ChatView: View {
}
}
@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)
Divider()
if let comparisonChat, comparisonChat != studio.selected,
studio.conversations.contains(where: { $0.id == comparisonChat }) {
ScrollView {
LazyVStack(alignment: .leading, spacing: 12) {
ForEach(studio.conversationMessages(comparisonChat)) { MessageView(message: $0) }
}.padding(12)
}
.font(chatFont.font(size: chatSize))
} 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 {
@@ -389,6 +438,11 @@ struct MessageView: View {
@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
var body: some View {
VStack(alignment: .leading, spacing: 8) {
HStack {
@@ -407,13 +461,13 @@ struct MessageView: View {
}
}
if !message.thinking.isEmpty {
DisclosureGroup("Thinking") {
DisclosureGroup("Thinking", isExpanded: $thinkingExpanded) {
Text(message.thinking).foregroundStyle(.secondary).textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
if !message.content.isEmpty {
if message.role == .assistant {
if message.role == .assistant && renderMarkdown {
ChatMarkdown(text: message.content)
} else {
Text(message.content).textSelection(.enabled)
@@ -422,7 +476,8 @@ struct MessageView: View {
if message.content.isEmpty && message.thinking.isEmpty { ProgressView().controlSize(.small) }
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(14)
.padding(compactMessages ? 8 : 14)
.onChange(of: expandThinking, initial: true) { _, expanded in thinkingExpanded = expanded }
.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))
}
@@ -1464,16 +1519,20 @@ struct WorkspaceSnippetsView: View {
@State private var search = ""
@State private var id: UUID?
@State private var title = ""
@State private var notes = ""
@State private var tags = ""
@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 = ""
private var items: [WorkspaceSnippet] {
studio.snippets.filter {
$0.kind == kind && (search.isEmpty || $0.title.localizedCaseInsensitiveContains(search))
$0.kind == kind && (search.isEmpty || $0.title.localizedCaseInsensitiveContains(search) || $0.tags.localizedCaseInsensitiveContains(search) || $0.notes.localizedCaseInsensitiveContains(search))
}
}
@@ -1488,6 +1547,22 @@ struct WorkspaceSnippetsView: View {
.frame(minWidth: 180, idealWidth: 220)
VStack(alignment: .leading, spacing: 10) {
TextField("Title", text: $title)
if kind == .prompt {
TextField("Notes", text: $notes)
TextField("Tags (comma-separated)", text: $tags)
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
}
}
}
}
}
if kind == .webClip {
HStack {
TextField("Source URL", text: $address)
@@ -1503,6 +1578,11 @@ struct WorkspaceSnippetsView: View {
} catch { self.error = error.localizedDescription }
}
}.disabled(capturing || address.isEmpty)
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")
@@ -1528,6 +1608,9 @@ struct WorkspaceSnippetsView: View {
.onChange(of: id) { _, value in
if let item = studio.snippets.first(where: { $0.id == value }) {
title = item.title
notes = item.notes
tags = item.tags
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))
@@ -1537,6 +1620,14 @@ struct WorkspaceSnippetsView: View {
}
}
}
.sheet(item: $renderedPage) { page in
RenderedClipView(url: page.url) { finalURL, pageTitle, text in
address = finalURL.absoluteString
if title.isEmpty { title = pageTitle }
content = text
error = ""
}
}
.fileImporter(isPresented: $importing, allowedContentTypes: [
.plainText, UTType(filenameExtension: "md") ?? .plainText
]) { result in
@@ -1582,12 +1673,75 @@ struct WorkspaceSnippetsView: View {
}
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)
studio.saveSnippet(id: key, kind: kind, title: title.trimmingCharacters(in: .whitespacesAndNewlines), content: stored, notes: notes, tags: tags)
id = key
if kind == .prompt { versions = studio.promptVersions(key) }
error = ""
}
private func clear() { id = nil; title = ""; content = ""; address = ""; error = "" }
private func clear() { id = nil; title = ""; content = ""; address = ""; error = ""; notes = ""; tags = ""; versions = [] }
}
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 {
@@ -1662,6 +1816,43 @@ struct StudioSettingsView: View {
}
}
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
@@ -1675,6 +1866,10 @@ struct StudioAppearanceView: View {
@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] {
@@ -1730,15 +1925,35 @@ struct StudioAppearanceView: View {
}
.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(shortcuts.filter { query.isEmpty || $0.0.localizedCaseInsensitiveContains(query) }, id: \.0) {
LabeledContent($0.0, value: $0.1)
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)
@@ -1771,11 +1986,7 @@ struct StudioAppearanceView: View {
.contentShape(Rectangle())
}
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 {
@@ -1786,6 +1997,8 @@ struct WorkspaceDataView: View {
@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 {
@@ -1804,12 +2017,35 @@ struct WorkspaceDataView: View {
.foregroundStyle(.secondary)
}
Section("Storage") {
Text(StudioModel.workspaceDirectory.path).textSelection(.enabled)
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) }
}
}
@@ -1825,6 +2061,29 @@ struct WorkspaceDataView: View {
}
}
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"