Repository Public
1// SP Notes Core2// File: Tests/SPNotesStoreTests/SyncTests.swift3// Description: Sync-facing primitives: push ordering, markPushed with a concurrent edit, applyRemote for every4// case (unknown, clean, dirty/diverged, tombstones, tags, attachments), conflicts and resolution.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Testing10@testable import SPNotesStore1112@Suite struct SyncTests {13 let later = Date(timeIntervalSince1970: 1_790_000_000)1415 @Test func pagesNeedingPushCreatesParentsFirst() async throws {16 let store = try NotesStore.inMemory()17 try await store.applyRemote(pages: [remote("s1", "Synced 1", "x"), remote("s2", "Synced 2", "y")])18 // Created child-first in time, and a synced page edited before the creations.19 try await store.edit("s1", text: "edited")20 try await store.createPage(draft("Grandchild", id: "c3"))21 try await store.createPage(draft("Child", id: "c2"))22 try await store.createPage(draft("Parent", id: "c1"))23 try await store.move(id: "c3", parentId: "c2")24 try await store.move(id: "c2", parentId: "c1")25 try await store.move(id: "s2", parentId: "c3")26 let pending = try await store.pagesNeedingPush()27 #expect(pending.map(\.page.id) == ["c1", "c2", "c3", "s1", "s2"])28 #expect(pending[3].base == PageBase(title: "Synced 1", content: doc("x"), properties: Data("{}".utf8), version: 1))29 #expect(pending[0].base == nil && pending[4].base == nil)30 #expect(pending[3].page.content == doc("edited"))31 #expect(try await store.pagesNeedingPush(limit: 2).map(\.page.id) == ["c1", "c2"])32 #expect(try await store.pendingPushCount() == 5)33 // Pages in conflict wait for a resolution.34 try await store.recordConflict(pageId: "s1", server: ServerCopy(version: 2, title: "S", content: doc("srv"), properties: Data("{}".utf8), updatedAt: later))35 #expect(try await store.pagesNeedingPush().map(\.page.id) == ["c1", "c2", "c3", "s2"])36 #expect(try await store.pagesNeedingPush(includeConflicts: true).count == 5)37 }3839 @Test func markPushedOfACreation() async throws {40 let store = try NotesStore.inMemory()41 let page = try await store.createPage(draft("New", "body", tags: ["t"]))42 let normalised = doc("body (normalised by the server)")43 try await store.markPushed(id: page.id, serverVersion: 1, updatedAt: later, pushedEditSeq: page.editSeq, serverContent: normalised)44 let after = try await store.must(page.id)45 #expect(!after.needsCreate && !after.isDirty && after.syncState == .synced && after.serverVersion == 1)46 #expect(after.content == normalised && after.updatedAt == later && after.editSeq == page.editSeq)47 #expect(try await store.pagesNeedingPush().isEmpty)48 await #expect(throws: StoreError.notFound("page gone")) {49 try await store.markPushed(id: "gone", serverVersion: 1, updatedAt: later, pushedEditSeq: 1)50 }51 }5253 @Test func markPushedWithAConcurrentEditKeepsThePageDirty() async throws {54 let store = try NotesStore.inMemory()55 try await store.applyRemote(pages: [remote("p", "T", "v1", version: 1)])56 try await store.edit("p", text: "v2 local")57 let sent = try await store.must("p") // the engine reads this row and sends it58 // The user keeps typing while the request is in flight.59 try await store.edit("p", text: "v3 typed during the push")60 try await store.markPushed(id: "p", serverVersion: 2, updatedAt: later, pushedEditSeq: sent.editSeq,61 pushed: PushedCopy(title: sent.title, content: sent.content, properties: sent.properties),62 serverContent: doc("v2 local"))63 let after = try await store.must("p")64 #expect(after.content == doc("v3 typed during the push") && after.plainText == "v3 typed during the push") // nothing lost65 #expect(after.dirtyContent && after.syncState == .pending && after.serverVersion == 2)66 // The base is now what the server holds, at the new version: the next push is a clean fast-forward.67 #expect(try await store.pageBase(id: "p") == PageBase(title: "T", content: doc("v2 local"), properties: Data("{}".utf8), version: 2))68 #expect(try await store.pagesNeedingPush().map(\.page.id) == ["p"])6970 // Second round, no edit in between: clean.71 let again = try await store.must("p")72 try await store.markPushed(id: "p", serverVersion: 3, updatedAt: later, pushedEditSeq: again.editSeq)73 #expect(try await store.must("p").isDirty == false)74 #expect(try await store.pageBase(id: "p") == nil)75 }7677 @Test func markPushedWithAConcurrentMetaOrCreateEdit() async throws {78 let store = try NotesStore.inMemory()79 // Only a meta field changed during the push: content is clean, the meta change stays to push.80 try await store.applyRemote(pages: [remote("p", "T", "v1", version: 1)])81 try await store.edit("p", text: "v2")82 let sent = try await store.must("p")83 try await store.setPinned(id: "p", true)84 try await store.markPushed(id: "p", serverVersion: 2, updatedAt: later, pushedEditSeq: sent.editSeq,85 pushed: PushedCopy(title: sent.title, content: sent.content, properties: sent.properties))86 var after = try await store.must("p")87 #expect(!after.dirtyContent && after.dirtyMeta == [.pinned] && after.serverVersion == 2 && after.syncState == .pending)88 #expect(try await store.pageBase(id: "p") == nil)8990 // A creation edited during its push: created on the server, still dirty, base = what was created.91 let created = try await store.createPage(draft("New", "first"))92 try await store.edit(created.id, text: "second")93 try await store.markPushed(id: created.id, serverVersion: 1, updatedAt: later, pushedEditSeq: created.editSeq,94 pushed: PushedCopy(title: created.title, content: created.content, properties: created.properties))95 after = try await store.must(created.id)96 #expect(!after.needsCreate && after.dirtyContent && after.serverVersion == 1 && after.content == doc("second"))97 #expect(try await store.pageBase(id: created.id)?.content == doc("first"))9899 // Without the pushed copy the store stays on the safe side: still dirty.100 try await store.applyRemote(pages: [remote("q", "Q", "v1", version: 1)])101 try await store.edit("q", text: "v2")102 try await store.edit("q", text: "v3")103 try await store.markPushed(id: "q", serverVersion: 2, updatedAt: later, pushedEditSeq: 1)104 #expect(try await store.must("q").dirtyContent)105 #expect(try await store.must("q").serverVersion == 2)106 }107108 @Test func markPushFailedSetsErrorState() async throws {109 let store = try NotesStore.inMemory()110 let page = try await store.createPage(draft("New", "body"))111 try await store.markPushFailed(id: page.id, error: "HTTP 500")112 var after = try await store.must(page.id)113 #expect(after.syncState == .error && after.syncError == "HTTP 500" && after.needsCreate)114 #expect(try await store.pagesNeedingPush().count == 1)115 try await store.edit(page.id, text: "retry") // a new edit clears the error116 after = try await store.must(page.id)117 #expect(after.syncState == .pending && after.syncError == nil)118 }119120 @Test func applyRemoteUnknownAndClean() async throws {121 let store = try NotesStore.inMemory()122 var summary = try await store.applyRemote(123 pages: [remote("p", "Remote title", "remote body", version: 2, tags: ["a", "b"], properties: #"{"favorite":true}"#, pinned: true, icon: "🧪", rev: 10)],124 tags: [RemoteTag(name: "a", color: "red"), RemoteTag(name: "b")], cursor: 10)125 #expect(summary.insertedPageIds == ["p"] && summary.updatedPageIds.isEmpty && summary.diverged.isEmpty && summary.tagsChanged)126 var page = try await store.must("p")127 #expect(page.syncState == .synced && !page.isDirty && page.serverVersion == 2 && page.rev == 10 && page.editSeq == 0)128 #expect(page.favorite && page.pinned && page.icon == "🧪" && page.tags == ["a", "b"] && page.plainText == "remote body")129 #expect(page.createdAt == epoch && page.updatedAt == epoch)130 #expect(try await store.syncCursor() == 10)131 #expect(try await store.search(query: "remote").map(\.id) == ["p"])132133 // Applying the same batch again changes nothing.134 summary = try await store.applyRemote(pages: [remote("p", "Remote title", "remote body", version: 2, tags: ["b", "a"], properties: #"{"favorite":true}"#, pinned: true, icon: "🧪", rev: 10)])135 #expect(summary == ApplySummary())136137 // Clean local page: everything is replaced, tags and index included, and nothing is snapshotted.138 summary = try await store.applyRemote(139 pages: [remote("p", "Renamed", "second body", version: 3, parent: nil, section: "documents", tags: ["c"], updatedAt: later, rev: 11)], cursor: 11)140 #expect(summary.updatedPageIds == ["p"] && summary.insertedPageIds.isEmpty && summary.diverged.isEmpty)141 page = try await store.must("p")142 #expect(page.title == "Renamed" && page.content == doc("second body") && page.serverVersion == 3 && page.section == "documents")143 #expect(!page.favorite && !page.pinned && page.icon == nil && page.tags == ["c"] && page.updatedAt == later)144 #expect(page.syncState == .synced && !page.isDirty)145 #expect(try await store.search(query: "remote").isEmpty)146 #expect(try await store.search(query: "second").map(\.id) == ["p"])147 #expect(try await store.localVersions(pageId: "p").isEmpty)148 #expect(try await store.pageBase(id: "p") == nil)149150 // A stale feed page (older version than the one already held) does not roll the content back.151 _ = try await store.applyRemote(pages: [remote("p", "Remote title", "remote body", version: 2, rev: 10)])152 #expect(try await store.must("p").title == "Renamed")153 #expect(try await store.must("p").serverVersion == 3)154 }155156 @Test func applyRemoteOnDirtyPageNeverOverwritesLocalEdits() async throws {157 let store = try NotesStore.inMemory()158 try await store.applyRemote(pages: [remote("p", "T", "v1", version: 1, tags: ["old"])])159 try await store.edit("p", title: "My title", text: "my unsynced words")160 try await store.setPinned(id: "p", true)161 let local = try await store.must("p")162163 // Same version on the server (only meta moved): nothing to do for the content, non-dirty meta adopted.164 var summary = try await store.applyRemote(pages: [remote("p", "T", "v1", version: 1, tags: ["srv"], pinned: false, archived: true, icon: "🌍", position: 9, rev: 2)])165 #expect(summary.diverged.isEmpty && summary.updatedPageIds == ["p"])166 var page = try await store.must("p")167 #expect(page.title == "My title" && page.content == local.content && page.plainText == "my unsynced words")168 #expect(page.pinned) // local pending change wins169 #expect(page.archived && page.icon == "🌍" && page.position == 9 && page.tags == ["srv"]) // remote wins elsewhere170 #expect(page.dirtyContent && page.dirtyMeta == [.pinned] && page.serverVersion == 1 && page.editSeq == local.editSeq)171172 // The server moved on: reported as diverged, local content, base and version untouched.173 let theirs = remote("p", "Their title", "their words", version: 2, tags: ["srv2"], updatedAt: later, rev: 3)174 summary = try await store.applyRemote(pages: [theirs], cursor: 3)175 #expect(summary.diverged == [DivergedPage(id: "p", remote: theirs)])176 page = try await store.must("p")177 #expect(page.title == "My title" && page.content == local.content && page.plainText == "my unsynced words")178 #expect(page.serverVersion == 1 && page.dirtyContent && page.syncState == .pending && page.updatedAt == local.updatedAt)179 #expect(page.tags == ["srv2"] && page.rev == 3)180 #expect(try await store.pageBase(id: "p") == PageBase(title: "T", content: doc("v1"), properties: Data("{}".utf8), version: 1))181 #expect(try await store.search(query: "unsynced").map(\.id) == ["p"])182 #expect(try await store.search(query: "their").isEmpty)183 #expect(try await store.syncCursor() == 3)184185 // Locally edited tags are not replaced either.186 try await store.setTags(id: "p", names: ["mine"])187 _ = try await store.applyRemote(pages: [remote("p", "Their title", "their words", version: 2, tags: ["srv3"], rev: 4)])188 #expect(try await store.must("p").tags == ["mine"])189 }190191 @Test func applyRemoteRecognisesItsOwnLostAcknowledgement() async throws {192 let store = try NotesStore.inMemory()193 // An edit was pushed, the app died before markPushed; the feed returns exactly what was sent.194 try await store.applyRemote(pages: [remote("p", "T", "v1", version: 1)])195 try await store.edit("p", text: "v2")196 var summary = try await store.applyRemote(pages: [remote("p", "T", "v2", version: 2, updatedAt: later)])197 #expect(summary.diverged.isEmpty)198 var page = try await store.must("p")199 #expect(!page.isDirty && page.serverVersion == 2 && page.syncState == .synced && page.updatedAt == later)200 #expect(try await store.pageBase(id: "p") == nil)201202 // Same for a creation: no duplicate, the local row becomes the synced row.203 let created = try await store.createPage(draft("Offline", "offline body", id: "c"))204 summary = try await store.applyRemote(pages: [remote("c", "Offline", "offline body", version: 1)])205 #expect(summary.diverged.isEmpty && summary.insertedPageIds.isEmpty)206 page = try await store.must("c")207 #expect(!page.needsCreate && !page.isDirty && page.serverVersion == 1 && page.editSeq == created.editSeq)208 #expect(try await store.pageCount() == 2)209 }210211 @Test func tombstones() async throws {212 let store = try NotesStore.inMemory()213 try await store.applyRemote(214 pages: [remote("clean", "Clean", "to be removed", tags: ["t"]), remote("dirty", "Dirty", "v1", version: 4, parent: "clean", tags: ["t"]),215 remote("meta", "Meta dirty", "m", version: 2)],216 attachments: [RemoteAttachment(id: "att", pageId: "clean", filename: "f.png", mime: "image/png", size: 5, createdAt: epoch)])217 try await store.markAttachmentDownloaded(id: "att", localPath: "at/f.png")218 try await store.snapshot(pageId: "clean", reason: "x")219 try await store.enqueueOp(kind: OpKind.restore, targetId: "clean") // a queued op for a page the server purged220 try await store.edit("dirty", text: "precious unsynced work")221 try await store.setPinned(id: "meta", true)222 let offline = try await store.createPage(draft("Offline child", "new", parent: "clean"))223224 let summary = try await store.applyRemote(tombstones: [225 Tombstone(id: "clean", kind: .page), Tombstone(id: "dirty", kind: .page), Tombstone(id: "meta", kind: .page),226 Tombstone(id: "unknown", kind: .page), Tombstone(id: "att", kind: .attachment), Tombstone(id: "unknown", kind: .attachment),227 ], cursor: 50)228 #expect(summary.deletedPageIds == ["clean"] && Set(summary.resurrectedPageIds) == ["dirty", "meta"])229 #expect(summary.orphanedFiles == ["at/f.png"])230231 // The clean page is gone with everything attached to it.232 #expect(try await store.page(id: "clean") == nil)233 #expect(try await store.search(query: "removed", filters: SearchFilters(includeTrash: true)).isEmpty)234 #expect(try await store.attachment(id: "att") == nil)235 #expect(try await store.localVersions(pageId: "clean").isEmpty)236 #expect(try await store.opCount() == 0)237238 // The dirty page keeps the user's work and will be created again, at the root since its parent is gone.239 let dirty = try await store.must("dirty")240 #expect(dirty.content == doc("precious unsynced work") && dirty.plainText == "precious unsynced work")241 #expect(dirty.needsCreate && dirty.dirtyContent && dirty.tagsDirty && dirty.serverVersion == 0 && dirty.syncState == .pending)242 #expect(dirty.parentId == nil && dirty.tags == ["t"] && dirty.deletedAt == nil)243 #expect(try await store.pageBase(id: "dirty") == nil)244 let meta = try await store.must("meta")245 #expect(meta.needsCreate && meta.pinned && meta.serverVersion == 0)246 // A page created offline under the purged parent is re-rooted too.247 #expect(try await store.must(offline.id).parentId == nil)248 #expect(Set(try await store.pagesNeedingPush().map(\.page.id)) == ["dirty", "meta", offline.id])249 #expect(try await store.search(query: "precious").map(\.id) == ["dirty"])250 #expect(try await store.integrityCheck().isEmpty)251 }252253 @Test func remoteAttachmentsKeepLocalFileState() async throws {254 let store = try NotesStore.inMemory()255 try await store.applyRemote(pages: [remote("p", "P", "b")],256 attachments: [RemoteAttachment(id: "A1", pageId: "p", filename: "a.pdf", mime: "application/pdf", size: 100, sha256: "h1", pageCount: 3, createdAt: epoch, rev: 5)])257 var record = try #require(try await store.attachment(id: "a1"))258 #expect(record.state == .remote && record.uploaded && record.localPath == nil && record.pageCount == 3 && record.rev == 5)259 try await store.markAttachmentDownloaded(id: "a1", localPath: "a1/a.pdf")260 try await store.setAttachmentKeepOffline(id: "a1", true)261262 // An update from the server changes server fields only.263 var summary = try await store.applyRemote(attachments: [RemoteAttachment(id: "a1", pageId: "p", filename: "renamed.pdf", mime: "application/pdf", size: 100, sha256: "h1", createdAt: epoch, rev: 6)])264 #expect(summary.changedAttachmentIds == ["a1"])265 record = try #require(try await store.attachment(id: "a1"))266 #expect(record.filename == "renamed.pdf" && record.rev == 6 && record.state == .local && record.localPath == "a1/a.pdf" && record.keepOffline && record.pageCount == 3)267268 // A pending upload that the server already knows (lost acknowledgement) becomes uploaded.269 try await store.addLocalAttachment(id: "up", pageId: "p", filename: "u.png", mime: "image/png", size: 9, sha256: "h2", localPath: "up/u.png")270 summary = try await store.applyRemote(attachments: [RemoteAttachment(id: "up", pageId: "p", filename: "u.png", mime: "image/png", size: 9, sha256: "h2", createdAt: epoch, rev: 7)])271 record = try #require(try await store.attachment(id: "up"))272 #expect(record.uploaded && record.state == .local && record.localPath == "up/u.png")273 #expect(try await store.pendingUploads().isEmpty)274275 // A local deletion waiting in the queue is not undone by a feed that still lists the attachment.276 try await store.markAttachmentDeleted(id: "a1")277 _ = try await store.applyRemote(attachments: [RemoteAttachment(id: "a1", pageId: "p", filename: "renamed.pdf", mime: "application/pdf", size: 100, createdAt: epoch, rev: 8)])278 #expect(try await store.attachment(id: "a1")?.deletedAt != nil)279 #expect(try await store.attachments(pageId: "p").map(\.id) == ["up"])280 // Server-side deletion.281 _ = try await store.applyRemote(attachments: [RemoteAttachment(id: "up", pageId: "p", filename: "u.png", mime: "image/png", size: 9, createdAt: epoch, deletedAt: later, rev: 9)])282 #expect(try await store.attachments(pageId: "p").isEmpty)283 #expect(try await store.attachments(pageId: "p", includeDeleted: true).count == 2)284 }285286 @Test func localTrashIsNotUndoneByTheFeed() async throws {287 let store = try NotesStore.inMemory()288 try await store.applyRemote(pages: [remote("f", "Folder", "f"), remote("c", "Child", "c", parent: "f")])289 try await store.trash(id: "f")290 // The feed (fetched before the trash op was pushed) still says "not deleted".291 _ = try await store.applyRemote(pages: [remote("c", "Child renamed", "c", version: 2, parent: "f", rev: 2), remote("f", "Folder", "f", rev: 2)])292 #expect(try await store.must("c").deletedAt != nil)293 #expect(try await store.must("f").deletedAt != nil)294 #expect(try await store.must("c").title == "Child renamed")295 // Once the op is done, the server is the reference again.296 for op in try await store.nextOps() { try await store.completeOp(id: op.id) }297 _ = try await store.applyRemote(pages: [remote("c", "Child renamed", "c", version: 2, parent: "f", deletedAt: later, rev: 3)])298 #expect(try await store.must("c").deletedAt == later)299 _ = try await store.applyRemote(pages: [remote("c", "Child renamed", "c", version: 2, parent: "f", rev: 4)])300 #expect(try await store.must("c").deletedAt == nil) // restored from another device301 }302303 @Test func resetKeepsEverythingLocal() async throws {304 let temp = TempDatabase()305 let store = try NotesStore(url: temp.url)306 try await store.applyRemote(pages: [remote("p", "P", "b")], cursor: 5)307 try await store.edit("p", text: "local")308 let local = try await store.createPage(draft("Local", "l"))309 try await store.enqueueOp(kind: "custom")310311 // A refused batch stores neither its pages nor its cursor.312 let reader = try NotesStore(url: temp.url, readOnly: true)313 await #expect(throws: StoreError.readOnly) { try await reader.applyRemote(pages: [remote("x", "X", "x")], cursor: 9) }314 #expect(try await store.syncCursor() == 5)315 #expect(try await store.page(id: "x") == nil)316317 try await store.resetSyncState()318 #expect(try await store.syncCursor() == 0)319 #expect(try await store.must("p").content == doc("local"))320 #expect(try await store.must("p").dirtyContent)321 #expect(try await store.page(id: local.id) != nil)322 #expect(try await store.opCount() == 1)323324 // After the complete re-download, synced pages the server no longer has are removed; local work stays.325 try await store.applyRemote(pages: [remote("gone", "Gone", "g"), remote("kept", "Kept", "k")])326 let removed = try await store.removeSyncedPages(notIn: ["kept", "p"])327 #expect(removed.pageIds == ["gone"])328 #expect(Set(try await store.summaries(list: .all).map(\.id)) == ["p", "kept", local.id])329 }330331 @Test func conflictsRecordListClear() async throws {332 let store = try NotesStore.inMemory()333 try await store.applyRemote(pages: [remote("p", "T", "v1"), remote("q", "U", "w1")])334 try await store.edit("p", text: "mine")335 try await store.edit("q", text: "mine too")336 let server = ServerCopy(version: 2, title: "Theirs", content: doc("theirs"), properties: Data(#"{"x":1}"#.utf8), updatedAt: later)337 try await store.recordConflict(pageId: "p", server: server, detectedAt: epoch)338 try await store.recordConflict(pageId: "q", server: server, detectedAt: later)339 #expect(try await store.must("p").syncState == .conflict)340 #expect(try await store.must("p").content == doc("mine"))341 #expect(try await store.conflict(pageId: "p") == ConflictRecord(pageId: "p", server: server, detectedAt: epoch))342 #expect(try await store.conflicts().map(\.pageId) == ["p", "q"])343 #expect(try await store.counts().conflicts == 2)344 // Recording again replaces the copy (one row per page).345 var newer = server346 newer.version = 3347 try await store.recordConflict(pageId: "p", server: newer, detectedAt: epoch)348 #expect(try await store.conflicts().count == 2)349 #expect(try await store.conflict(pageId: "p")?.server.version == 3)350 // An edit during a conflict keeps the conflict state.351 try await store.edit("p", text: "mine again")352 #expect(try await store.must("p").syncState == .conflict)353 try await store.clearConflict(pageId: "p")354 #expect(try await store.conflict(pageId: "p") == nil)355 #expect(try await store.must("p").syncState == .pending)356 await #expect(throws: StoreError.self) { try await store.recordConflict(pageId: "missing", server: server) }357 }358359 @Test func resolveConflictUsingTheServerCopy() async throws {360 let store = try NotesStore.inMemory()361 try await store.applyRemote(pages: [remote("p", "T", "v1")])362 try await store.edit("p", title: "Mine", text: "my words")363 try await store.setPinned(id: "p", true)364 try await store.recordConflict(pageId: "p", server: ServerCopy(version: 5, title: "Theirs", content: doc("their words"), properties: Data(#"{"favorite":true}"#.utf8), updatedAt: later))365 let copy = ContentCopy(title: "Theirs", content: doc("their words"), properties: Data(#"{"favorite":true}"#.utf8), plainText: "their words", wordCount: 2, preview: "their words")366 try await store.resolveConflictUsingCopy(id: "p", copy: copy, version: 5, updatedAt: later)367 let page = try await store.must("p")368 #expect(page.title == "Theirs" && page.content == doc("their words") && page.favorite && page.serverVersion == 5 && page.updatedAt == later)369 #expect(!page.dirtyContent && page.dirtyMeta == [.pinned] && page.syncState == .pending) // the pin is still to push370 #expect(try await store.conflict(pageId: "p") == nil)371 #expect(try await store.pageBase(id: "p") == nil)372 #expect(try await store.search(query: "their").map(\.id) == ["p"])373 // The local text it replaced is not lost: it is in the local history.374 let versions = try await store.localVersions(pageId: "p")375 #expect(versions.map(\.reason) == ["conflict-local"] && versions[0].title == "Mine")376 #expect(try await store.localVersion(id: versions[0].id)?.content == doc("my words"))377 }378379 @Test func resolveConflictKeepingLocalOrMerged() async throws {380 let store = try NotesStore.inMemory()381 try await store.applyRemote(pages: [remote("p", "T", "v1"), remote("q", "T", "v1")])382 try await store.edit("p", text: "my words")383 let server = ServerCopy(version: 7, title: "Theirs", content: doc("their words"), properties: Data("{}".utf8), updatedAt: later)384 try await store.recordConflict(pageId: "p", server: server)385 try await store.resolveConflictKeepingLocal(id: "p", server: server)386 var page = try await store.must("p")387 #expect(page.content == doc("my words") && page.dirtyContent && page.serverVersion == 7 && page.syncState == .pending)388 #expect(try await store.pageBase(id: "p") == PageBase(title: "Theirs", content: doc("their words"), properties: Data("{}".utf8), version: 7))389 #expect(try await store.conflict(pageId: "p") == nil)390 #expect(try await store.pagesNeedingPush().map(\.page.id) == ["p"])391392 // With a merge result.393 try await store.edit("q", text: "my words")394 let merged = ContentCopy(title: "Theirs", content: doc("my words + their words"), properties: Data("{}".utf8), plainText: "my words + their words", wordCount: 5, preview: "my words")395 try await store.resolveConflictKeepingLocal(id: "q", server: server, merged: merged)396 page = try await store.must("q")397 #expect(page.title == "Theirs" && page.content == doc("my words + their words") && page.dirtyContent && page.serverVersion == 7)398 #expect(try await store.localVersions(pageId: "q").map(\.reason) == ["conflict-local"])399 #expect(try await store.search(query: "their").map(\.id) == ["q"])400 }401}402