Complete workspace recovery, migration, and compatibility checks
This commit is contained in:
+122
-8
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user