Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatConversations/Sources/ConversationStore.swift3// Description: Persistent store of conversations, the message tree, folders, templates, workspaces, agents and preferences (GRDB / SQLite, soft deletes for sync).4import Foundation5import GRDB6import LocalChatCore78public enum ConversationStoreError: LocalizedError, Sendable, Equatable {9 case conversationNotFound, messageNotFound, invalidOperation(String), invalidImport(String)10 public var errorDescription: String? {11 switch self {12 case .conversationNotFound: "Conversation not found."13 case .messageNotFound: "Message not found."14 case .invalidOperation(let m): m15 case .invalidImport(let m): "The file could not be imported: \(m)"16 }17 }18}1920public struct ConversationFilter: Sendable, Hashable {21 public enum FolderScope: Sendable, Hashable { case any, unfiled, folder(UUID) }22 public enum Sort: Sendable, Hashable { case updated, created, title }23 public var folder: FolderScope24 public var tag: String?25 public var favoritesOnly: Bool26 public var archived: Bool? // nil = both27 public var text: String? // title contains (case and diacritic insensitive)28 public var sort: Sort29 public var limit: Int?30 public init(folder: FolderScope = .any, tag: String? = nil, favoritesOnly: Bool = false, archived: Bool? = false, text: String? = nil,31 sort: Sort = .updated, limit: Int? = nil) {32 self.folder = folder; self.tag = tag; self.favoritesOnly = favoritesOnly; self.archived = archived; self.text = text; self.sort = sort; self.limit = limit33 }34}3536public struct TagCount: Sendable, Hashable, Identifiable {37 public var tag: String; public var count: Int38 public var id: String { tag }39 public init(tag: String, count: Int) { self.tag = tag; self.count = count }40}4142public final class ConversationStore: Sendable {43 let db: any DatabaseWriter4445 /// Opens (or creates) the store at `url`.46 public init(url: URL) throws {47 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)48 var config = Configuration()49 config.foreignKeysEnabled = false50 db = try DatabasePool(path: url.path, configuration: config)51 try Schema.migrator().migrate(db)52 #if os(iOS)53 for suffix in ["", "-wal", "-shm"] {54 try? FileManager.default.setAttributes([.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication], ofItemAtPath: url.path + suffix)55 }56 #endif57 try seed()58 }5960 private init(inMemory: Void) throws {61 db = try DatabaseQueue()62 try Schema.migrator().migrate(db)63 try seed()64 }6566 public static func inMemory() throws -> ConversationStore { try ConversationStore(inMemory: ()) }6768 private func seed() throws {69 try db.write { db in70 guard try String.fetchOne(db, sql: "SELECT value FROM meta WHERE key = 'seededTemplates'") == nil else { return }71 for t in BuiltInTemplates.all where try !Self.entityExists(db, kind: .template, id: t.id.uuidString) { try Self.putEntity(db, t) }72 try db.execute(sql: "INSERT INTO meta(key, value) VALUES ('seededTemplates', '1')")73 }74 }7576 // MARK: Conversations7778 /// Saves a conversation. `touch` stamps `updatedAt` with now (leave false to keep the caller's value).79 @discardableResult80 public func saveConversation(_ conversation: Conversation, touch: Bool = true) throws -> Conversation {81 var c = conversation82 if touch { c.updatedAt = Date() }83 try db.write { try Self.putConversation($0, c) }84 return c85 }8687 public func conversation(_ id: UUID) throws -> Conversation? {88 try db.read { try Self.fetchConversation($0, id) }89 }9091 public func conversations(_ filter: ConversationFilter = .init()) throws -> [Conversation] {92 try db.read { try Self.fetchConversations($0, filter) }93 }9495 /// Soft-deletes a conversation and its messages (tombstones are kept for sync).96 public func deleteConversation(_ id: UUID) throws {97 try db.write { db in98 guard var c = try Self.fetchConversation(db, id, includeDeleted: true) else { return }99 let now = Date()100 c.deletedAt = now; c.updatedAt = now101 try Self.putConversation(db, c)102 try db.execute(sql: "DELETE FROM search WHERE rowid IN (SELECT rowid FROM message WHERE conversationID = ?)", arguments: [id.uuidString])103 try db.execute(sql: "UPDATE message SET deletedAt = ?, updatedAt = ? WHERE conversationID = ? AND deletedAt IS NULL",104 arguments: [now.dbValue, now.dbValue, id.uuidString])105 }106 }107108 public func tags() throws -> [TagCount] {109 let all = try conversations(ConversationFilter(archived: nil))110 var counts: [String: Int] = [:]111 for c in all { for t in Set(c.tags) { counts[t, default: 0] += 1 } }112 return counts.map { TagCount(tag: $0.key, count: $0.value) }.sorted { ($1.count, $0.tag) < ($0.count, $1.tag) }113 }114115 public func setSummary(_ summary: ContextSummary?, for conversationID: UUID) throws {116 try db.write { db in117 guard var c = try Self.fetchConversation(db, conversationID) else { throw ConversationStoreError.conversationNotFound }118 c.summary = summary; c.updatedAt = Date()119 try Self.putConversation(db, c)120 }121 }122123 public func setActiveLeaf(_ leaf: UUID?, for conversationID: UUID) throws {124 try db.write { db in125 guard var c = try Self.fetchConversation(db, conversationID) else { throw ConversationStoreError.conversationNotFound }126 c.activeLeafID = leaf; c.updatedAt = Date()127 try Self.putConversation(db, c)128 }129 }130131 // MARK: Messages132133 public func messages(in conversationID: UUID) throws -> [ChatMessage] {134 try db.read { try Self.fetchMessages($0, conversationID) }135 }136137 public func message(_ id: UUID) throws -> ChatMessage? {138 try db.read { try Self.fetchMessage($0, id) }139 }140141 public func tree(_ conversationID: UUID) throws -> ConversationTree { ConversationTree(try messages(in: conversationID)) }142143 /// Root → active leaf.144 public func activeBranch(_ conversationID: UUID) throws -> [ChatMessage] {145 try db.read { db in146 guard let c = try Self.fetchConversation(db, conversationID) else { return [] }147 return ConversationTree(try Self.fetchMessages(db, conversationID)).path(to: c.activeLeafID)148 }149 }150151 /// Appends `message` under the conversation's active leaf and makes it the new active leaf. The message's `parentID` is overwritten.152 @discardableResult153 public func appendMessage(_ message: ChatMessage) throws -> ChatMessage {154 try db.write { db in155 guard var c = try Self.fetchConversation(db, message.conversationID) else { throw ConversationStoreError.conversationNotFound }156 var m = message157 var parent = c.activeLeafID158 if let p = parent, try Self.fetchMessage(db, p) == nil { parent = nil }159 if parent == nil { parent = ConversationTree(try Self.fetchMessages(db, c.id)).newestLeaf()?.id }160 m.parentID = parent161 try Self.putMessage(db, m, updatedAt: Date())162 c.activeLeafID = m.id; c.updatedAt = Date()163 try Self.putConversation(db, c)164 return m165 }166 }167168 /// Inserts or fully rewrites a message with its explicit `parentID` (also the "finalize" path after streaming: re-indexes search).169 public func saveMessage(_ message: ChatMessage, makeActiveLeaf: Bool = false) throws {170 try db.write { db in171 try Self.putMessage(db, message, updatedAt: Date())172 guard var c = try Self.fetchConversation(db, message.conversationID) else { return }173 if makeActiveLeaf { c.activeLeafID = message.id }174 c.updatedAt = Date()175 try Self.putConversation(db, c)176 }177 }178179 /// Cheap path used many times per second while tokens stream: rewrites only the text inside the stored JSON. Search is indexed by `saveMessage` on completion.180 public func updateStreamingMessage(id: UUID, content: String, reasoning: String? = nil) throws {181 try db.write { db in182 if let reasoning {183 try db.execute(sql: "UPDATE message SET json = json_set(json, '$.content', ?, '$.reasoning', ?) WHERE id = ?", arguments: [content, reasoning, id.uuidString])184 } else {185 try db.execute(sql: "UPDATE message SET json = json_set(json, '$.content', ?) WHERE id = ?", arguments: [content, id.uuidString])186 }187 }188 }189190 /// Editing a user message creates a NEW sibling (same parent) holding the new text; the original and its answers stay as another branch.191 @discardableResult192 public func editUserMessage(_ id: UUID, newContent: String, attachments: [Attachment]? = nil) throws -> ChatMessage {193 try db.write { db in194 guard let original = try Self.fetchMessage(db, id) else { throw ConversationStoreError.messageNotFound }195 guard original.role == .user else { throw ConversationStoreError.invalidOperation("Only user messages can be edited.") }196 let now = Date()197 let edited = ChatMessage(conversationID: original.conversationID, parentID: original.parentID, role: .user, content: newContent,198 attachments: attachments ?? original.attachments, createdAt: now, editedAt: now)199 try Self.putMessage(db, edited, updatedAt: now)200 try Self.activate(db, conversation: original.conversationID, leaf: edited.id)201 return edited202 }203 }204205 /// Regeneration creates a new assistant sibling under the same parent (empty, `.streaming`) and activates it.206 @discardableResult207 public func regenerate(_ assistantMessageID: UUID, modelID: String? = nil, modelName: String? = nil, backend: BackendKind? = nil) throws -> ChatMessage {208 try db.write { db in209 guard let original = try Self.fetchMessage(db, assistantMessageID) else { throw ConversationStoreError.messageNotFound }210 guard original.role == .assistant else { throw ConversationStoreError.invalidOperation("Only assistant messages can be regenerated.") }211 let fresh = ChatMessage(conversationID: original.conversationID, parentID: original.parentID, role: .assistant, content: "",212 modelID: modelID ?? original.modelID, modelName: modelName ?? original.modelName,213 backend: backend ?? original.backend, status: .streaming)214 try Self.putMessage(db, fresh, updatedAt: Date())215 try Self.activate(db, conversation: original.conversationID, leaf: fresh.id)216 return fresh217 }218 }219220 /// Steps to the previous (-1) / next (+1) alternative of `messageID`. Returns the new active leaf, or nil when there is none in that direction.221 @discardableResult222 public func switchBranch(from messageID: UUID, offset: Int) throws -> UUID? {223 try db.write { db in224 guard let m = try Self.fetchMessage(db, messageID) else { throw ConversationStoreError.messageNotFound }225 let tree = ConversationTree(try Self.fetchMessages(db, m.conversationID))226 guard let leaf = tree.leafAfterSwitching(from: messageID, offset: offset) else { return nil }227 try Self.activate(db, conversation: m.conversationID, leaf: leaf)228 return leaf229 }230 }231232 /// Soft-deletes a message and everything below it. The active leaf moves to the newest remaining branch around the parent.233 public func deleteMessageSubtree(_ id: UUID) throws {234 try db.write { db in235 guard let m = try Self.fetchMessage(db, id) else { throw ConversationStoreError.messageNotFound }236 let tree = ConversationTree(try Self.fetchMessages(db, m.conversationID))237 var doomed: [UUID] = []; var stack = [id]238 while let next = stack.popLast() { doomed.append(next); stack.append(contentsOf: tree.children[next] ?? []) }239 let now = Date().dbValue240 for d in doomed {241 try db.execute(sql: "DELETE FROM search WHERE rowid = (SELECT rowid FROM message WHERE id = ?)", arguments: [d.uuidString])242 try db.execute(sql: "UPDATE message SET deletedAt = ?, updatedAt = ? WHERE id = ?", arguments: [now, now, d.uuidString])243 }244 guard var c = try Self.fetchConversation(db, m.conversationID) else { return }245 if let leaf = c.activeLeafID, doomed.contains(leaf) || tree.messages[leaf] == nil {246 let remaining = ConversationTree(try Self.fetchMessages(db, c.id))247 c.activeLeafID = m.parentID.flatMap { remaining.messages[$0] != nil ? remaining.leaf(under: $0) : nil } ?? remaining.newestLeaf()?.id248 }249 if let s = c.summary, doomed.contains(s.coversThroughMessageID) { c.summary = nil }250 c.updatedAt = Date()251 try Self.putConversation(db, c)252 }253 }254255 /// New conversation holding a copy of the path root → `messageID`.256 @discardableResult257 public func forkConversation(from messageID: UUID, title: String? = nil) throws -> Conversation {258 try db.write { db in259 guard let m = try Self.fetchMessage(db, messageID), let source = try Self.fetchConversation(db, m.conversationID) else {260 throw ConversationStoreError.messageNotFound261 }262 let path = ConversationTree(try Self.fetchMessages(db, source.id)).path(to: messageID)263 return try Self.copy(db, source: source, messages: path, title: title ?? source.title + " (fork)", activeLeaf: messageID)264 }265 }266267 /// Full copy (every branch) of a conversation.268 @discardableResult269 public func duplicateConversation(_ id: UUID, title: String? = nil) throws -> Conversation {270 try db.write { db in271 guard let source = try Self.fetchConversation(db, id) else { throw ConversationStoreError.conversationNotFound }272 return try Self.copy(db, source: source, messages: try Self.fetchMessages(db, id), title: title ?? source.title + " (copy)", activeLeaf: source.activeLeafID)273 }274 }275276 /// Stored names of every attachment still referenced by a live message.277 public func referencedAttachmentNames() throws -> Set<String> {278 try db.read { db in279 var names = Set<String>()280 for json in try String.fetchAll(db, sql: "SELECT json FROM message WHERE deletedAt IS NULL AND json LIKE '%storedName%'") {281 for a in try DBCoding.decode(ChatMessage.self, json).attachments { names.insert(a.storedName) }282 }283 return names284 }285 }286287 // MARK: Generic entities (folders, templates, workspaces, agents, knowledge collection metadata)288289 public func all<T: StoredEntity>(_ type: T.Type, includeDeleted: Bool = false) throws -> [T] {290 try db.read { try Self.fetchEntities($0, type, includeDeleted: includeDeleted) }291 }292293 public func get<T: StoredEntity>(_ type: T.Type, id: UUID) throws -> T? {294 try db.read { db in295 try String.fetchOne(db, sql: "SELECT json FROM entity WHERE kind = ? AND id = ? AND deletedAt IS NULL",296 arguments: [T.entityKind.rawValue, id.uuidString]).map { try DBCoding.decode(T.self, $0) }297 }298 }299300 @discardableResult301 public func save<T: StoredEntity>(_ entity: T, touch: Bool = true) throws -> T {302 var e = entity303 if touch { e.updatedAt = Date() }304 try db.write { try Self.putEntity($0, e) }305 return e306 }307308 /// Soft delete. Deleting a folder un-files its conversations.309 public func delete<T: StoredEntity>(_ type: T.Type, id: UUID) throws {310 try db.write { db in311 guard let json = try String.fetchOne(db, sql: "SELECT json FROM entity WHERE kind = ? AND id = ?", arguments: [T.entityKind.rawValue, id.uuidString]) else { return }312 var e = try DBCoding.decode(T.self, json)313 let now = Date()314 e.deletedAt = now; e.updatedAt = now315 try Self.putEntity(db, e)316 if T.entityKind == .folder {317 for var c in try Self.fetchConversations(db, ConversationFilter(folder: .folder(id), archived: nil)) {318 c.folderID = nil; c.updatedAt = now319 try Self.putConversation(db, c)320 }321 }322 }323 }324325 public func folders() throws -> [ChatFolder] { try all(ChatFolder.self).sorted { ($0.sortIndex, $0.name) < ($1.sortIndex, $1.name) } }326 public func templates() throws -> [PromptTemplate] { try all(PromptTemplate.self).sorted { ($0.isBuiltIn ? 1 : 0, $0.name) < ($1.isBuiltIn ? 1 : 0, $1.name) } }327 public func workspaces() throws -> [ModelWorkspace] { try all(ModelWorkspace.self).sorted { $0.name < $1.name } }328 public func agents() throws -> [AgentConfiguration] { try all(AgentConfiguration.self).sorted { $0.name < $1.name } }329330 // MARK: Preferences331332 public func preferences() throws -> AppPreferences {333 try db.read { db in334 try String.fetchOne(db, sql: "SELECT json FROM entity WHERE kind = 'preferences' AND id = 'preferences'").map { try DBCoding.decode(AppPreferences.self, $0) }335 } ?? AppPreferences(updatedAt: Date(timeIntervalSince1970: 0))336 }337338 @discardableResult339 public func savePreferences(_ preferences: AppPreferences, touch: Bool = true) throws -> AppPreferences {340 var p = preferences341 if touch { p.updatedAt = Date() }342 try db.write { try Self.putPreferences($0, p) }343 return p344 }345346 // MARK: Maintenance347348 /// Permanently removes tombstones older than `date`. Returns the number of rows removed.349 @discardableResult350 public func purgeTombstones(olderThan date: Date) throws -> Int {351 try db.write { db in352 var n = 0353 for table in ["message", "conversation", "entity"] {354 try db.execute(sql: "DELETE FROM \(table) WHERE deletedAt IS NOT NULL AND deletedAt < ?", arguments: [date.dbValue])355 n += db.changesCount356 }357 return n358 }359 }360361 // MARK: Observation362363 public func observeConversations(_ filter: ConversationFilter = .init()) -> AsyncStream<[Conversation]> {364 observe { try Self.fetchConversations($0, filter) }365 }366367 public func observeMessages(in conversationID: UUID) -> AsyncStream<[ChatMessage]> {368 observe { try Self.fetchMessages($0, conversationID) }369 }370371 public func observeConversation(_ id: UUID) -> AsyncStream<Conversation?> {372 observe { try Self.fetchConversation($0, id) }373 }374375 func observe<T: Sendable>(_ fetch: @escaping @Sendable (Database) throws -> T) -> AsyncStream<T> {376 let db = self.db377 return AsyncStream { continuation in378 let task = Task {379 do { for try await value in ValueObservation.tracking(fetch).values(in: db) { continuation.yield(value) } } catch {}380 continuation.finish()381 }382 continuation.onTermination = { _ in task.cancel() }383 }384 }385}386387// MARK: - Database helpers (run inside a transaction)388389extension ConversationStore {390 static func putConversation(_ db: Database, _ c: Conversation) throws {391 try db.execute(sql: """392 INSERT INTO conversation(id, title, folderID, isFavorite, isArchived, createdAt, updatedAt, deletedAt, json) VALUES (?,?,?,?,?,?,?,?,?)393 ON CONFLICT(id) DO UPDATE SET title = excluded.title, folderID = excluded.folderID, isFavorite = excluded.isFavorite,394 isArchived = excluded.isArchived, createdAt = excluded.createdAt, updatedAt = excluded.updatedAt, deletedAt = excluded.deletedAt, json = excluded.json395 """, arguments: [c.id.uuidString, c.title, c.folderID?.uuidString, c.isFavorite, c.isArchived, c.createdAt.dbValue, c.updatedAt.dbValue,396 c.deletedAt?.dbValue, try DBCoding.encode(c)])397 guard let rowid = try Int64.fetchOne(db, sql: "SELECT rowid FROM conversation WHERE id = ?", arguments: [c.id.uuidString]) else { return }398 try db.execute(sql: "DELETE FROM search WHERE rowid = ?", arguments: [-rowid])399 if c.deletedAt == nil {400 try db.execute(sql: "INSERT INTO search(rowid, content, kind, conversationID, messageID, role) VALUES (?, ?, 'c', ?, NULL, NULL)",401 arguments: [-rowid, c.title, c.id.uuidString])402 }403 }404405 static func putMessage(_ db: Database, _ m: ChatMessage, updatedAt: Date, deletedAt: Date? = nil) throws {406 try db.execute(sql: """407 INSERT INTO message(id, conversationID, parentID, role, createdAt, updatedAt, deletedAt, json) VALUES (?,?,?,?,?,?,?,?)408 ON CONFLICT(id) DO UPDATE SET conversationID = excluded.conversationID, parentID = excluded.parentID, role = excluded.role,409 createdAt = excluded.createdAt, updatedAt = excluded.updatedAt, deletedAt = excluded.deletedAt, json = excluded.json410 """, arguments: [m.id.uuidString, m.conversationID.uuidString, m.parentID?.uuidString, m.role.rawValue, m.createdAt.dbValue,411 updatedAt.dbValue, deletedAt?.dbValue, try DBCoding.encode(m)])412 guard let rowid = try Int64.fetchOne(db, sql: "SELECT rowid FROM message WHERE id = ?", arguments: [m.id.uuidString]) else { return }413 try db.execute(sql: "DELETE FROM search WHERE rowid = ?", arguments: [rowid])414 if deletedAt == nil, !m.content.isEmpty {415 try db.execute(sql: "INSERT INTO search(rowid, content, kind, conversationID, messageID, role) VALUES (?, ?, 'm', ?, ?, ?)",416 arguments: [rowid, m.content, m.conversationID.uuidString, m.id.uuidString, m.role.rawValue])417 }418 }419420 static func putEntity<T: StoredEntity>(_ db: Database, _ e: T) throws {421 try db.execute(sql: """422 INSERT INTO entity(kind, id, updatedAt, deletedAt, json) VALUES (?,?,?,?,?)423 ON CONFLICT(kind, id) DO UPDATE SET updatedAt = excluded.updatedAt, deletedAt = excluded.deletedAt, json = excluded.json424 """, arguments: [T.entityKind.rawValue, e.id.uuidString, e.updatedAt.dbValue, e.deletedAt?.dbValue, try DBCoding.encode(e)])425 }426427 static func putPreferences(_ db: Database, _ p: AppPreferences) throws {428 try db.execute(sql: """429 INSERT INTO entity(kind, id, updatedAt, deletedAt, json) VALUES ('preferences', 'preferences', ?, NULL, ?)430 ON CONFLICT(kind, id) DO UPDATE SET updatedAt = excluded.updatedAt, json = excluded.json431 """, arguments: [p.updatedAt.dbValue, try DBCoding.encode(p)])432 }433434 static func entityExists(_ db: Database, kind: SyncRecord.Kind, id: String) throws -> Bool {435 try Bool.fetchOne(db, sql: "SELECT EXISTS(SELECT 1 FROM entity WHERE kind = ? AND id = ?)", arguments: [kind.rawValue, id]) ?? false436 }437438 static func fetchEntities<T: StoredEntity>(_ db: Database, _ type: T.Type, includeDeleted: Bool) throws -> [T] {439 try String.fetchAll(db, sql: "SELECT json FROM entity WHERE kind = ?" + (includeDeleted ? "" : " AND deletedAt IS NULL"),440 arguments: [T.entityKind.rawValue]).map { try DBCoding.decode(T.self, $0) }441 }442443 static func fetchConversation(_ db: Database, _ id: UUID, includeDeleted: Bool = false) throws -> Conversation? {444 try String.fetchOne(db, sql: "SELECT json FROM conversation WHERE id = ?" + (includeDeleted ? "" : " AND deletedAt IS NULL"),445 arguments: [id.uuidString]).map { try DBCoding.decode(Conversation.self, $0) }446 }447448 static func fetchConversations(_ db: Database, _ filter: ConversationFilter) throws -> [Conversation] {449 var sql = "SELECT json FROM conversation WHERE deletedAt IS NULL"; var args: [any DatabaseValueConvertible] = []450 switch filter.folder {451 case .any: break452 case .unfiled: sql += " AND folderID IS NULL"453 case .folder(let id): sql += " AND folderID = ?"; args.append(id.uuidString)454 }455 if filter.favoritesOnly { sql += " AND isFavorite = 1" }456 if let archived = filter.archived { sql += " AND isArchived = ?"; args.append(archived) }457 switch filter.sort {458 case .updated: sql += " ORDER BY updatedAt DESC"459 case .created: sql += " ORDER BY createdAt DESC"460 case .title: sql += " ORDER BY title COLLATE NOCASE ASC"461 }462 var out = try String.fetchAll(db, sql: sql, arguments: StatementArguments(args)).map { try DBCoding.decode(Conversation.self, $0) }463 if let tag = filter.tag { out = out.filter { $0.tags.contains(tag) } }464 if let text = filter.text?.trimmingCharacters(in: .whitespaces), !text.isEmpty {465 out = out.filter { $0.title.range(of: text, options: [.caseInsensitive, .diacriticInsensitive]) != nil }466 }467 if let limit = filter.limit { out = Array(out.prefix(limit)) }468 return out469 }470471 static func fetchMessages(_ db: Database, _ conversationID: UUID) throws -> [ChatMessage] {472 try String.fetchAll(db, sql: "SELECT json FROM message WHERE conversationID = ? AND deletedAt IS NULL ORDER BY createdAt, id",473 arguments: [conversationID.uuidString]).map { try DBCoding.decode(ChatMessage.self, $0) }474 }475476 static func fetchMessage(_ db: Database, _ id: UUID) throws -> ChatMessage? {477 try String.fetchOne(db, sql: "SELECT json FROM message WHERE id = ? AND deletedAt IS NULL", arguments: [id.uuidString])478 .map { try DBCoding.decode(ChatMessage.self, $0) }479 }480481 static func activate(_ db: Database, conversation: UUID, leaf: UUID) throws {482 guard var c = try fetchConversation(db, conversation) else { throw ConversationStoreError.conversationNotFound }483 c.activeLeafID = leaf; c.updatedAt = Date()484 try putConversation(db, c)485 }486487 /// Copies `messages` (a closed set: parents outside the set become roots) into a new conversation with fresh ids.488 static func copy(_ db: Database, source: Conversation, messages: [ChatMessage], title: String, activeLeaf: UUID?) throws -> Conversation {489 var map: [UUID: UUID] = [:]490 for m in messages { map[m.id] = UUID() }491 let now = Date()492 var c = source493 c.id = UUID(); c.title = title; c.createdAt = now; c.updatedAt = now; c.deletedAt = nil; c.isArchived = false494 c.activeLeafID = activeLeaf.flatMap { map[$0] }495 if let s = c.summary {496 if let mapped = map[s.coversThroughMessageID] { c.summary?.coversThroughMessageID = mapped } else { c.summary = nil }497 }498 for var m in messages {499 m.id = map[m.id]!; m.conversationID = c.id; m.parentID = m.parentID.flatMap { map[$0] }500 if m.status == .streaming { m.status = .cancelled }501 try putMessage(db, m, updatedAt: now)502 }503 try putConversation(db, c)504 return c505 }506}507