Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatConversations/Sources/Sync.swift3// Description: SyncableStore conformance: change feed and last-writer-wins application of remote records (tombstones included).4import Foundation5import GRDB6import LocalChatCore78extension ConversationStore: SyncableStore {9 public func changes(since: Date?) async throws -> [SyncRecord] {10 try await db.read { db in11 let cut = since?.dbValue ?? -Double.greatestFiniteMagnitude12 var out: [SyncRecord] = []13 for row in try Row.fetchAll(db, sql: "SELECT id, updatedAt, deletedAt, json FROM conversation WHERE updatedAt > ? ORDER BY updatedAt", arguments: [cut]) {14 let c = try DBCoding.decode(Conversation.self, row["json"])15 out.append(SyncRecord(kind: .conversation, id: row["id"], updatedAt: Date(dbValue: row["updatedAt"]),16 isDeleted: (row["deletedAt"] as Double?) != nil, payload: try SyncCoding.encode(c)))17 }18 for row in try Row.fetchAll(db, sql: "SELECT id, updatedAt, deletedAt, json FROM message WHERE updatedAt > ? ORDER BY updatedAt", arguments: [cut]) {19 let m = try DBCoding.decode(ChatMessage.self, row["json"])20 if m.status == .streaming && (row["deletedAt"] as Double?) == nil { continue } // never ship a half-written answer21 out.append(SyncRecord(kind: .message, id: row["id"], updatedAt: Date(dbValue: row["updatedAt"]),22 isDeleted: (row["deletedAt"] as Double?) != nil, payload: try SyncCoding.encode(m)))23 }24 for row in try Row.fetchAll(db, sql: "SELECT kind, id, updatedAt, deletedAt, json FROM entity WHERE updatedAt > ? ORDER BY updatedAt", arguments: [cut]) {25 guard let kind = SyncRecord.Kind(rawValue: row["kind"]) else { continue }26 let json: String = row["json"]27 let payload: Data28 switch kind {29 case .folder: payload = try SyncCoding.encode(try DBCoding.decode(ChatFolder.self, json))30 case .template:31 let t = try DBCoding.decode(PromptTemplate.self, json)32 if t.isBuiltIn { continue }33 payload = try SyncCoding.encode(t)34 case .workspace: payload = try SyncCoding.encode(try DBCoding.decode(ModelWorkspace.self, json))35 case .agent: payload = try SyncCoding.encode(try DBCoding.decode(AgentConfiguration.self, json))36 case .collection: payload = try SyncCoding.encode(try DBCoding.decode(KnowledgeCollection.self, json))37 case .preferences: payload = try SyncCoding.encode(try DBCoding.decode(AppPreferences.self, json))38 case .conversation, .message: continue39 }40 out.append(SyncRecord(kind: kind, id: row["id"], updatedAt: Date(dbValue: row["updatedAt"]),41 isDeleted: (row["deletedAt"] as Double?) != nil, payload: payload))42 }43 return out44 }45 }4647 public func apply(_ records: [SyncRecord]) async throws -> Int {48 try await db.write { db in49 var applied = 050 for r in records {51 let table = r.kind == .conversation ? "conversation" : r.kind == .message ? "message" : "entity"52 let local: Double? = table == "entity"53 ? try Double.fetchOne(db, sql: "SELECT updatedAt FROM entity WHERE kind = ? AND id = ?", arguments: [r.kind.rawValue, r.id])54 : try Double.fetchOne(db, sql: "SELECT updatedAt FROM \(table) WHERE id = ?", arguments: [r.id])55 if let local, local >= r.updatedAt.dbValue { continue }56 do {57 switch r.kind {58 case .conversation:59 var c = try SyncCoding.decode(Conversation.self, r.payload)60 c.updatedAt = r.updatedAt61 if r.isDeleted {62 c.deletedAt = c.deletedAt ?? r.updatedAt63 try db.execute(sql: "DELETE FROM search WHERE rowid IN (SELECT rowid FROM message WHERE conversationID = ?)", arguments: [c.id.uuidString])64 } else { c.deletedAt = nil }65 try Self.putConversation(db, c)66 case .message:67 let m = try SyncCoding.decode(ChatMessage.self, r.payload)68 try Self.putMessage(db, m, updatedAt: r.updatedAt, deletedAt: r.isDeleted ? r.updatedAt : nil)69 case .folder: try Self.applyEntity(db, ChatFolder.self, r)70 case .template: try Self.applyEntity(db, PromptTemplate.self, r)71 case .workspace: try Self.applyEntity(db, ModelWorkspace.self, r)72 case .agent: try Self.applyEntity(db, AgentConfiguration.self, r)73 case .collection: try Self.applyEntity(db, KnowledgeCollection.self, r)74 case .preferences:75 var p = try SyncCoding.decode(AppPreferences.self, r.payload)76 p.updatedAt = r.updatedAt77 try Self.putPreferences(db, p)78 }79 applied += 180 } catch is DecodingError { continue } // a record from a newer, incompatible version is skipped, not fatal81 }82 return applied83 }84 }8586 static func applyEntity<T: StoredEntity>(_ db: Database, _ type: T.Type, _ r: SyncRecord) throws {87 var e = try SyncCoding.decode(T.self, r.payload)88 e.updatedAt = r.updatedAt89 e.deletedAt = r.isDeleted ? (e.deletedAt ?? r.updatedAt) : nil90 try putEntity(db, e)91 }92}93