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"
+122 -8
View File
@@ -20,6 +20,17 @@ struct WorkspaceSnippet: Identifiable {
let kind: Kind
let title: String
let content: String
var notes = ""
var tags = ""
}
struct PromptVersion: Identifiable {
let id: String
let savedAt: String
let title: String
let content: String
let notes: String
let tags: String
}
final class Store {
@@ -67,6 +78,21 @@ final class Store {
DELETE FROM document_index WHERE document=old.id;
END;
""")
try preparePromptLibrary()
}
private func preparePromptLibrary() throws {
try execute("""
CREATE TABLE IF NOT EXISTS prompt_metadata (
prompt TEXT PRIMARY KEY REFERENCES workspace_snippets(id) ON DELETE CASCADE,
notes TEXT NOT NULL, tags TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS prompt_versions (
id TEXT PRIMARY KEY, prompt TEXT NOT NULL REFERENCES workspace_snippets(id) ON DELETE CASCADE,
saved_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
title TEXT NOT NULL, content TEXT NOT NULL, notes TEXT NOT NULL, tags TEXT NOT NULL
);
""")
}
deinit { sqlite3_close(db) }
@@ -113,11 +139,11 @@ final class Store {
}
func snippets() throws -> [WorkspaceSnippet] {
try query("SELECT id,kind,title,content FROM workspace_snippets ORDER BY rowid DESC") {
try query("SELECT s.id,s.kind,s.title,s.content,m.notes,m.tags FROM workspace_snippets s LEFT JOIN prompt_metadata m ON m.prompt=s.id ORDER BY s.rowid DESC") {
guard let kind = WorkspaceSnippet.Kind(rawValue: string($0, 1)) else {
throw StudioError("Invalid workspace resource.")
}
return WorkspaceSnippet(id: try uuid($0, 0), kind: kind, title: string($0, 2), content: string($0, 3))
return WorkspaceSnippet(id: try uuid($0, 0), kind: kind, title: string($0, 2), content: string($0, 3), notes: string($0, 4), tags: string($0, 5))
}
}
@@ -128,6 +154,31 @@ final class Store {
""", [id.uuidString, kind.rawValue, title, content])
}
func promptVersions(_ id: UUID) throws -> [PromptVersion] {
try query("SELECT id,saved_at,title,content,notes,tags FROM prompt_versions WHERE prompt=? ORDER BY rowid DESC", [id.uuidString]) {
PromptVersion(id: string($0, 0), savedAt: string($0, 1), title: string($0, 2),
content: string($0, 3), notes: string($0, 4), tags: string($0, 5))
}
}
func savePrompt(id: UUID, title: String, content: String, notes: String, tags: String) throws {
try execute("BEGIN IMMEDIATE")
do {
try saveSnippet(id: id, kind: .prompt, title: title, content: content)
try mutate("""
INSERT INTO prompt_metadata(prompt,notes,tags) VALUES(?,?,?)
ON CONFLICT(prompt) DO UPDATE SET notes=excluded.notes, tags=excluded.tags
""", [id.uuidString, notes, tags])
try mutate("""
INSERT INTO prompt_versions(id,prompt,title,content,notes,tags) VALUES(?,?,?,?,?,?)
""", [UUID().uuidString, id.uuidString, title, content, notes, tags])
try execute("COMMIT")
} catch {
try? execute("ROLLBACK")
throw error
}
}
func deleteSnippet(_ id: UUID) throws {
try mutate("DELETE FROM workspace_snippets WHERE id=?", [id.uuidString])
}
@@ -250,6 +301,73 @@ final class Store {
return excerpts
}
static func isWorkspaceBackup(_ url: URL) -> Bool {
var input: OpaquePointer?
let result = sqlite3_open_v2(url.path, &input, SQLITE_OPEN_READONLY, nil)
defer { if let input { sqlite3_close(input) } }
guard result == SQLITE_OK, let input else { return false }
return hasWorkspaceSchema(input)
}
private static func hasWorkspaceSchema(_ input: OpaquePointer) -> Bool {
let sql = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name IN ('chats','messages','documents','workspace_snippets','knowledge_stacks')"
var statement: OpaquePointer?
guard sqlite3_prepare_v2(input, sql, -1, &statement, nil) == SQLITE_OK, let statement else { return false }
defer { sqlite3_finalize(statement) }
return sqlite3_step(statement) == SQLITE_ROW && sqlite3_column_int(statement, 0) == 5
}
func importMstyChats(from url: URL) throws -> Int {
var input: OpaquePointer?
let opened = sqlite3_open_v2(url.path, &input, SQLITE_OPEN_READONLY, nil)
defer { if let input { sqlite3_close(input) } }
guard opened == SQLITE_OK, let input else { throw StudioError("Could not open the Msty database.") }
let sql = """
SELECT s.id, c.title, m.role, m.content
FROM conversationTexts c
JOIN conversationTextChatSplits s ON s.conversationId = c.id
JOIN conversationTextMessages m ON m.chatSplitId = s.id
WHERE m.role IN ('user','assistant') AND length(m.content) > 0
ORDER BY c.createdAt, s.createdAt, s.id, m.createdAt, m.rowid
"""
var statement: OpaquePointer?
guard sqlite3_prepare_v2(input, sql, -1, &statement, nil) == SQLITE_OK, let statement else {
throw StudioError("The database does not match the supported Msty Studio chat format.")
}
defer { sqlite3_finalize(statement) }
try execute("BEGIN IMMEDIATE")
var count = 0
do {
try execute("CREATE TABLE IF NOT EXISTS msty_imports (source_id TEXT PRIMARY KEY)")
var previous = ""
var destination: UUID?
while true {
let step = sqlite3_step(statement)
if step == SQLITE_DONE { break }
guard step == SQLITE_ROW else { throw StudioError("The Msty chat database could not be read.") }
let split = string(statement, 0)
if split != previous {
previous = split
destination = nil
let exists = try query("SELECT source_id FROM msty_imports WHERE source_id=?", [split]) { string($0, 0) }
if exists.isEmpty {
destination = try create(title: String(string(statement, 1).prefix(100))).id
try mutate("INSERT INTO msty_imports(source_id) VALUES(?)", [split])
count += 1
}
}
if let destination, let role = Role(rawValue: string(statement, 2)) {
try save(Message(role: role, content: string(statement, 3)), in: destination)
}
}
try execute("COMMIT")
return count
} catch {
try? execute("ROLLBACK")
throw error
}
}
func exportWorkspace(to url: URL) throws {
guard !FileManager.default.fileExists(atPath: url.path) else {
throw StudioError("Choose a new filename for the workspace backup.")
@@ -265,14 +383,9 @@ final class Store {
throw StudioError("The workspace backup could not be opened.")
}
defer { sqlite3_close(input) }
let check = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name IN ('chats','messages','documents','workspace_snippets','knowledge_stacks')"
var prepared: OpaquePointer?
guard sqlite3_prepare_v2(input, check, -1, &prepared, nil) == SQLITE_OK, let prepared else {
guard Self.hasWorkspaceSchema(input) else {
throw StudioError("The selected file is not an AI Studio workspace backup.")
}
let valid = sqlite3_step(prepared) == SQLITE_ROW && sqlite3_column_int(prepared, 0) == 5
sqlite3_finalize(prepared)
guard valid else { throw StudioError("The selected file is not an AI Studio workspace backup.") }
var checkHandle: OpaquePointer?
guard sqlite3_prepare_v2(input, "PRAGMA quick_check", -1, &checkHandle, nil) == SQLITE_OK,
let integrity = checkHandle else { throw StudioError("Could not verify backup integrity.") }
@@ -283,6 +396,7 @@ final class Store {
let step = sqlite3_backup_step(backup, -1)
let finish = sqlite3_backup_finish(backup)
guard step == SQLITE_DONE, finish == SQLITE_OK else { throw failure }
try preparePromptLibrary()
}
private func execute(_ sql: String) throws {
+42 -3
View File
@@ -84,6 +84,10 @@ final class StudioModel: ObservableObject {
catch { status = error.localizedDescription }
}
func conversationMessages(_ id: UUID) -> [Message] {
(try? store?.messages(in: id)) ?? []
}
func searchConversations(_ term: String) -> [Conversation] {
(try? store?.searchConversations(term)) ?? []
}
@@ -341,7 +345,29 @@ final class StudioModel: ObservableObject {
}
static var workspaceDirectory: URL {
URL.applicationSupportDirectory.appending(path: "AIStudio", directoryHint: .isDirectory)
if let path = UserDefaults.standard.string(forKey: "workspaceLocation"), !path.isEmpty {
return URL(fileURLWithPath: path, isDirectory: true)
}
return URL.applicationSupportDirectory.appending(path: "AIStudio", directoryHint: .isDirectory)
}
func relocateWorkspace(to folder: URL, defaults: UserDefaults = .standard) throws {
guard !running, !importingDocument else { throw StudioError("Wait for the current operation to finish.") }
let url = folder.appending(path: "studio.sqlite")
try database().exportWorkspace(to: url)
let relocated = try Store(url: url)
_ = try relocated.conversations()
store = relocated
defaults.set(folder.path, forKey: "workspaceLocation")
try refreshWorkspace()
}
func importMstyChats(from url: URL) throws -> Int {
guard !running, !importingDocument else { throw StudioError("Wait for the current operation to finish.") }
let count = try database().importMstyChats(from: url)
conversations = try database().conversations()
if selected == nil { selected = conversations.first?.id }
return count
}
func exportWorkspace(to url: URL) throws {
@@ -412,9 +438,22 @@ final class StudioModel: ObservableObject {
} catch { workspaceStatus = error.localizedDescription }
}
func saveSnippet(id: UUID, kind: WorkspaceSnippet.Kind, title: String, content: String) {
func promptVersions(_ id: UUID) -> [PromptVersion] {
(try? database().promptVersions(id)) ?? []
}
func saveSnippet(id: UUID, kind: WorkspaceSnippet.Kind, title: String, content: String,
notes: String = "", tags: String = "") {
do {
try database().saveSnippet(id: id, kind: kind, title: String(title.prefix(100)), content: String(content.prefix(12000)))
let store = try database()
let title = String(title.prefix(100))
let content = String(content.prefix(12000))
if kind == .prompt {
try store.savePrompt(id: id, title: title, content: content,
notes: String(notes.prefix(1000)), tags: String(tags.prefix(250)))
} else {
try store.saveSnippet(id: id, kind: kind, title: title, content: content)
}
try refreshWorkspace()
workspaceStatus = ""
} catch { workspaceStatus = error.localizedDescription }