diff --git a/public/journal.css b/public/journal.css index 1909480..e7ce7d8 100644 --- a/public/journal.css +++ b/public/journal.css @@ -1,6 +1,6 @@ -:root { --bg:#f7f5f0; --ink:#22201c; --muted:#6f6a61; --faint:#d9d4c9; --panel:#fffdf8; --accent:#5b6b4e; --warn:#9a5b1e; --caret:#5b6b4e; } -@media (prefers-color-scheme:dark) { :root:not([data-theme="light"]) { --bg:#161513; --ink:#e8e4da; --muted:#8b867b; --faint:#34312c; --panel:#1f1d1a; --accent:#a9b897; --warn:#d9a066; --caret:#a9b897; } } -:root[data-theme="dark"] { --bg:#161513; --ink:#e8e4da; --muted:#8b867b; --faint:#34312c; --panel:#1f1d1a; --accent:#a9b897; --warn:#d9a066; --caret:#a9b897; } +:root { color-scheme:light; --bg:#f7f5f0; --ink:#22201c; --muted:#6f6a61; --faint:#d9d4c9; --panel:#fffdf8; --accent:#5b6b4e; --warn:#9a5b1e; --caret:#5b6b4e; } +@media (prefers-color-scheme:dark) { :root:not([data-theme="light"]) { color-scheme:dark; --bg:#161513; --ink:#e8e4da; --muted:#a29c90; --faint:#34312c; --panel:#1f1d1a; --accent:#a9b897; --warn:#d9a066; --caret:#a9b897; } } +:root[data-theme="dark"] { color-scheme:dark; --bg:#161513; --ink:#e8e4da; --muted:#a29c90; --faint:#34312c; --panel:#1f1d1a; --accent:#a9b897; --warn:#d9a066; --caret:#a9b897; } * { box-sizing:border-box; } html { scrollbar-width:none; scroll-padding-bottom:calc(5rem + env(safe-area-inset-bottom)); } html::-webkit-scrollbar { display:none; } diff --git a/src/draft-opens.ts b/src/draft-opens.ts index 07558cd..64fa50a 100644 --- a/src/draft-opens.ts +++ b/src/draft-opens.ts @@ -24,7 +24,7 @@ export class DraftOpens { if (this.jobs.has(id) || this.releasing.has(id)) continue; const draft = this.drafts.get(id), record = this.data.snapshot(id); if (draft?.deletedElsewhere || id !== viewedId && draft?.body === draft?.savedBody && (!record || record.state === "saved" && !record.dirty) || - draft?.reviewRequired && record?.state === "conflict") { + draft?.reviewRequired && (!record || record.state === "conflict")) { const finish = () => {this.data.close(id); this.owners.delete(id); release();}; if (!record || record.state === "conflict" || draft?.deletedElsewhere) {finish(); continue;} // Saved is published before the SDK's original drive has returned. @@ -50,7 +50,7 @@ export class DraftOpens { request(id: string, type?: JournalEntryType, viewed = false, edited = false): void { if (this.disposed || !this.isCurrent()) return; const draft = this.drafts.get(id); - if (!draft || draft.deletedElsewhere || draft.legacyKey || !draft.body.trim() || draft.body === draft.savedBody && (!viewed || !draft.recordId) || + if (!draft || draft.deletedElsewhere || draft.reviewRequired || draft.legacyKey || !draft.body.trim() || draft.body === draft.savedBody && (!viewed || !draft.recordId) || draft.targetCollectionId && draft.targetCollectionId !== this.data.connection.id || this.data.snapshot(id) || this.jobs.has(id)) return; this.types.set(id, type); if (!this.owns(id)) { diff --git a/src/drafts.ts b/src/drafts.ts index 9579ce9..8f34e51 100644 --- a/src/drafts.ts +++ b/src/drafts.ts @@ -27,6 +27,10 @@ export interface JournalDraft { targetCollectionId: string | null; recordId: string | null; savedBody: string | null; + /** Native revision associated with savedBody, separate from the local text revision. */ + savedRecordRevision?: string | undefined; + /** Last revision witnessed in this draft's on-device write. */ + pendingRecordRevision?: string | undefined; createAttempt: CreateAttempt | null; finished: boolean; touchedMs: number; @@ -45,6 +49,8 @@ function validDraft(value: unknown): value is JournalDraft { if (value.legacyKey !== undefined && (typeof value.legacyKey !== "string" || !value.legacyKey.startsWith("journal.note.") || value.legacyKey.length > 1024 || value.createAttempt !== null || value.recordId !== null)) return false; if (value.reviewRequired !== undefined && typeof value.reviewRequired !== "boolean") return false; if (value.deletedElsewhere !== undefined && typeof value.deletedElsewhere !== "boolean") return false; + if (value.savedRecordRevision !== undefined && typeof value.savedRecordRevision !== "string" || + value.pendingRecordRevision !== undefined && typeof value.pendingRecordRevision !== "string") return false; const attempt = value.createAttempt; if (attempt !== null && (!object(attempt) || ["body", "typeName", "createdField", "path", "created", "account", "installation"].some(key => typeof attempt[key] !== "string") || !uuid(attempt.mutationId) || !uuid(attempt.recordId) || attempt.created !== value.created || attempt.path !== value.path || !value.targetCollectionId)) return false; @@ -140,7 +146,7 @@ export class JournalDrafts { return this.put({...existing ?? base, body, path: existing?.path ?? path, touchedMs: Date.now()}); } private canPrune(draft: JournalDraft, now: number): boolean { - return !this.pins.has(draft.id) && draft.finished && !!draft.recordId && !draft.legacyKey && + return !this.pins.has(draft.id) && draft.finished && !!draft.recordId && !draft.legacyKey && !draft.reviewRequired && !draft.pendingRecordRevision && draft.body === draft.savedBody && draft.touchedMs <= now - 6 * 60 * 60 * 1000; } /** Reclaim old confirmed copies on a new visit, before hitting a quota. diff --git a/src/journal-data.ts b/src/journal-data.ts index 5bec8cd..e7c66a2 100644 --- a/src/journal-data.ts +++ b/src/journal-data.ts @@ -4,6 +4,17 @@ export const JOURNAL_CONTRACT = Object.freeze({id: "journal.entry", version: "0. export interface JournalEntryType {readonly name: string; readonly createdField: string} export interface JournalEntry {readonly id: string; readonly created: string; readonly createdMs: number; readonly path: string} export const DELETED_ENTRY_NOTICE = "This entry was deleted elsewhere. Your text stays on this device."; +const EDITED_ENTRY_NOTICE = "This note changed elsewhere. Your local text has been preserved."; +function witnessedSave(snapshot: RecordSessionSnapshot, capture?: {mutationId: string; body: string}): boolean { + const receipt = snapshot.lastReceipt; + return !!capture && snapshot.record.body === capture.body && receipt?.mutation === capture.mutationId && + (receipt.state === "confirmed" || receipt.state === "pending") && receipt.status !== "conflicted" && + !!receipt.records?.some(record => record.id === snapshot.record.id && record.revision === snapshot.record.revision); +} +function matchesDraftBase(draft: JournalDraft, record: RecordView): boolean { + return record.revision === draft.pendingRecordRevision || record.body === draft.savedBody && + (!draft.savedRecordRevision || record.revision === draft.savedRecordRevision); +} /** The collection's catalog cannot give Journal an entry type. SDK readiness * checks only that the contract exists and some type claims it; these are the * further bindings Journal needs. The message is shown to the writer. */ @@ -120,8 +131,11 @@ export class JournalData { if (local) return local; const record = await this.connection.records.get(entry.id, {include: {body: true, document: true}, signal: this.caller.signal}); this.ensure(); currentRecord(record, entry.id); + const confirmed = record.state.state === "confirmed"; const draft = await this.drafts.mutate(() => this.drafts.put({...this.drafts.blank(this.connection.id, new Date(entry.createdMs)), id: entry.id, - created: entry.created, body: record.body!, savedBody: record.body!, path: record.path, recordId: record.id})); + created: entry.created, body: record.body!, savedBody: confirmed ? record.body! : null, + savedRecordRevision: confirmed ? record.revision : undefined, pendingRecordRevision: confirmed ? undefined : record.revision, + path: record.path, recordId: record.id})); this.ensure(); return this.drafts.get(draft.id)!; } @@ -174,36 +188,44 @@ export class JournalData { .catch(() => {throw new Error("Keep this page open while its original save is unresolved.");}); this.ensure(draft); currentRecord(record, attempt.recordId); if (record.body !== attempt.body) throw new Error("The original saved note has changed. Your local text has been preserved."); - draft = await this.drafts.mutate(() => this.drafts.patch(id, {recordId: attempt.recordId, savedBody: record.state.state === "confirmed" ? attempt.body : null})); + const confirmed = record.state.state === "confirmed"; + draft = await this.drafts.mutate(() => this.drafts.patch(id, {recordId: attempt.recordId, savedBody: confirmed ? attempt.body : null, + savedRecordRevision: confirmed ? record.revision : undefined, pendingRecordRevision: confirmed ? undefined : record.revision})); } // An unconfirmed write from an earlier visit is in the SDK write ledger; the record stays editable. const lease = await this.connection.records.records.open(draft.recordId!, {signal: this.caller.signal, autosave: {idleMs: 1200}, requireLive: true}); try { - this.ensure(draft); - const snapshot = lease.session.getSnapshot(); - if (snapshot.state === "deleted") {await this.markDeleted(id, snapshot.record.id); throw new Error(DELETED_ENTRY_NOTICE);} - if (snapshot.state === "saved" && snapshot.body !== draft.savedBody && draft.body !== snapshot.body) throw new Error("This note changed elsewhere. Your local text has been preserved."); + let settling = !!lease.session.getSnapshot().recovery; const unsubscribe = lease.session.subscribe(() => { if (this.disposed || !this.connection.isCurrent() || this.problems.has(id)) return; const value = lease.session.getSnapshot(), capture = value.recovery; + const completed = settling && !capture; + settling = !!capture; if (value.state === "deleted") { void this.markDeleted(id, value.record.id) .catch(() => {this.problems.set(id, "Keep this page open: Journal cannot preserve the deletion notice on this device."); this.notify();}); } - if (value.state === "conflict" && !this.drafts.get(id)?.reviewRequired) { - void this.drafts.mutate(() => this.drafts.patch(id, {reviewRequired: true})) - .catch(() => {this.problems.set(id, "Keep this page open: Journal cannot preserve its conflict on this device.");}) - .finally(() => this.notify()); - } if (value.state === "saving" && capture?.baseRevision && capture.recordId === value.record.id && this.capturedEdits.get(id)?.mutationId !== capture.mutationId) { this.capturedEdits.set(id, {mutationId: capture.mutationId, baseRevision: capture.baseRevision, body: value.body}); } - if (value.state === "saved" && !value.dirty) { + const own = witnessedSave(value, this.capturedEdits.get(id)); + let replaced = false; + if (completed && !own && (value.state === "saved" || value.state === "saved_on_device" || value.state === "unsaved")) { + const local = this.drafts.get(id); + // A retained session can finish a capture that predates this lease. + // With no capture witness, only an already-known base is safe. + replaced = this.capturedEdits.has(id) || !local || value.record.body !== local.body && !matchesDraftBase(local, value.record); + } + if (replaced) { + // Stop the SDK drive before it can save newer typing onto the unrelated + // readback. The complete text already lives in the origin store. + this.problems.set(id, EDITED_ENTRY_NOTICE); + this.close(id); + } + if (replaced || value.state === "conflict" || value.state === "saved" || value.state === "saved_on_device" || completed && own) { void this.drafts.mutate(() => { - const local = this.drafts.get(id); - if (!local) throw new Error("The original local draft is missing."); - // Clean text follows its SDK source; unsent writing stays put. - this.drafts.patch(id, local.body === local.savedBody ? {body: value.body, savedBody: value.body} : {savedBody: value.body}); + if (replaced || !this.disposed && this.connection.isCurrent()) this.reconcile(id, value, own, replaced); + if (replaced) this.problems.delete(id); }).catch(() => {this.problems.set(id, "Keep this page open: Journal cannot preserve the original save outcome on this device.");}) .finally(() => this.notify()); } @@ -211,10 +233,17 @@ export class JournalData { }); this.unsubscriptions.set(id, unsubscribe); this.leases.set(id, lease); - const latest = this.drafts.get(id); - if (!latest) throw new Error("The original local draft is missing. Keep this page open."); - this.ensure(latest); - if (snapshot.state === "saved" || snapshot.state === "saved_on_device" || snapshot.state === "unsaved") lease.session.setBody(latest.body); + await this.drafts.mutate(() => { + this.ensure(); + const snapshot = lease.session.getSnapshot(); + if (snapshot.state === "deleted") return; + const latest = this.reconcile(id, snapshot); + if (latest.reviewRequired) throw new Error(EDITED_ENTRY_NOTICE); + this.ensure(latest); + if (snapshot.state === "saved" || snapshot.state === "saved_on_device" || snapshot.state === "unsaved") lease.session.setBody(latest.body); + }); + const snapshot = lease.session.getSnapshot(); + if (snapshot.state === "deleted") {await this.markDeleted(id, snapshot.record.id); throw new Error(DELETED_ENTRY_NOTICE);} if (this.problems.has(id)) throw new Error(this.problems.get(id)); return lease; } catch (error) { @@ -222,6 +251,26 @@ export class JournalData { lease.release(); throw error; } } + /** Check and advance the durable save base under the same lock as typing. */ + private reconcile(id: string, snapshot: RecordSessionSnapshot, own = false, replaced = false): JournalDraft { + const local = this.drafts.get(id); + if (!local) throw new Error("The original local draft is missing. Keep this page open."); + if (local.reviewRequired || local.deletedElsewhere) return local; + const {body, revision, state} = snapshot.record; + const pending = state.state === "pending"; + const knownBase = matchesDraftBase(local, snapshot.record); + const clean = local.body === local.savedBody && !local.pendingRecordRevision && !snapshot.dirty; + if (replaced || snapshot.state === "conflict" || body !== local.body && !knownBase && !own && (!clean || pending)) { + return this.drafts.patch(id, {reviewRequired: true}); + } + if (pending) { + return (own || body === local.body || knownBase) && revision !== local.pendingRecordRevision + ? this.drafts.patch(id, {pendingRecordRevision: revision}) : local; + } + if (state.state !== "confirmed" || typeof body !== "string") return local; + if (body === local.savedBody && revision === local.savedRecordRevision && !local.pendingRecordRevision) return local; + return this.drafts.patch(id, {body: clean ? body : local.body, savedBody: body, savedRecordRevision: revision, pendingRecordRevision: undefined}); + } setBody(id: string, body: string, source?: {body: string; revision: string | null}): Promise { const expectedRevision = this.drafts.get(id)?.revision; return this.drafts.mutate(() => { @@ -233,18 +282,16 @@ export class JournalData { if (this.problems.has(id)) throw new Error(this.problems.get(id)); const session = this.leases.get(id)?.session; const actual = session?.getSnapshot(); - const capture = this.capturedEdits.get(id), receipt = actual?.lastReceipt; + const capture = this.capturedEdits.get(id); // A completed original SDK capture may advance the source before this // input gets the origin lock. Require its exact base/body, mutation and // receipt's current-record witness; outside/unknown outcomes still refuse. const ownSave = source && actual && capture && capture.baseRevision === source.revision && capture.body === source.body && actual.body === source.body && - (actual.state === "saved" || actual.state === "saved_on_device") && receipt?.mutation === capture.mutationId && - (receipt.state === "confirmed" || receipt.state === "pending") && receipt.status !== "conflicted" && - receipt.records?.some(record => record.id === actual.record.id && record.revision === actual.record.revision); + (actual.state === "saved" || actual.state === "saved_on_device") && witnessedSave(actual, capture); // Never attach stale displayed text to a freshly advanced outside revision. if (source && actual && actual.body !== body && (actual.body !== source.body || !actual.dirty && source.revision !== null && actual.record.revision !== source.revision && !ownSave)) { this.drafts.patch(id, {reviewRequired: true}); - throw new Error("This note changed elsewhere. Your local text has been preserved."); + throw new Error(EDITED_ENTRY_NOTICE); } session?.setBody(body); }); @@ -257,6 +304,7 @@ export class JournalData { this.ensure(original, true); const record = await this.connection.records.get(original.recordId, {include: {body: true, document: true}, signal: this.caller.signal}); this.ensure(original, true); currentRecord(record, original.recordId); + if (record.state.state !== "confirmed") throw new Error("Wait for the saved version to sync. Your text stays on this device."); const owned = this.leases.get(id); // A released conflict can still be retained by this SDK client. Reopen it // only for this explicit discard, without seeding an autosaving draft. @@ -266,8 +314,11 @@ export class JournalData { return await this.drafts.mutate(() => { const latest = this.drafts.get(id); if (!latest || latest.revision !== original.revision) throw new Error("Your text changed while the saved version was opening. Copy it before trying again."); - if (lease.session.getSnapshot().state === "conflict") lease.session.resolve({keep: "theirs"}); - return this.drafts.patch(id, {body: record.body!, savedBody: record.body!, reviewRequired: false}); + const snapshot = lease.session.getSnapshot(); + if (snapshot.state === "conflict") lease.session.resolve({keep: "theirs"}); + else if (snapshot.dirty && !snapshot.recovery && snapshot.record.revision === record.revision) lease.session.setBody(record.body!); + return this.drafts.patch(id, {body: record.body!, savedBody: record.body!, savedRecordRevision: record.revision, + pendingRecordRevision: undefined, reviewRequired: false}); }); } finally {if (!owned) lease.release();} } diff --git a/src/view.ts b/src/view.ts index 3a20c15..7bb593b 100644 --- a/src/view.ts +++ b/src/view.ts @@ -103,7 +103,7 @@ export function mountJournal(document: Document, drafts: JournalDrafts, mdbase: let observedCollectionId = mdbase?.getSnapshot().selectedCollectionId ?? null; let current = drafts.blank(observedCollectionId); try { - const earlier = drafts.list().filter(draft => !draft.legacyKey && (draft.body.trim() || draft.deletedElsewhere && draft.body !== draft.savedBody) && + const earlier = drafts.list().filter(draft => !draft.legacyKey && (draft.body.trim() || draft.reviewRequired || draft.deletedElsewhere && draft.body !== draft.savedBody) && (!draft.deletedElsewhere || draft.body !== draft.savedBody) && (!observedCollectionId || draft.targetCollectionId === observedCollectionId)) .sort((a, b) => Number(a.finished) - Number(b.finished) || b.touchedMs - a.touchedMs)[0]; if (earlier) current = drafts.patch(earlier.id, {finished: false}); @@ -235,7 +235,7 @@ export function mountJournal(document: Document, drafts: JournalDrafts, mdbase: try { const localDrafts = drafts.list(); if (entriesDialog.open) renderEntries(localDrafts); - unresolved = localDrafts.filter(draft => !!draft.body.trim() && draft.body !== draft.savedBody); + unresolved = localDrafts.filter(draft => draft.reviewRequired || !!draft.body.trim() && draft.body !== draft.savedBody); } catch { if (entriesDialog.open) {entriesProblem = "Earlier notes could not be read on this device."; renderEntries([]);} problem = "Keep this page open: Journal cannot read its drafts on this device."; @@ -392,7 +392,7 @@ export function mountJournal(document: Document, drafts: JournalDrafts, mdbase: function visibleEntries(bounds: [number, number] | null, localDrafts: readonly JournalDraft[]): {entry: JournalEntry; draft: JournalDraft | null}[] { const collection = snapshot()?.selectedCollectionId ?? current.targetCollectionId; const local = localDrafts.filter(draft => draft.targetCollectionId === collection && - (draft.deletedElsewhere ? draft.body !== draft.savedBody : draft.body.trim())); + (draft.deletedElsewhere ? draft.body !== draft.savedBody : draft.reviewRequired || draft.body.trim())); const [start, end] = bounds ?? [-Infinity, Infinity]; const saved = bounds ? entries.slice(firstOlderThan(entries, end), firstOlderThan(entries, start)) : entries; const localRecordIds = new Set(local.map(draft => draft.recordId)); diff --git a/tests/journal-data.test.ts b/tests/journal-data.test.ts index bd4f717..8b477f4 100644 --- a/tests/journal-data.test.ts +++ b/tests/journal-data.test.ts @@ -156,6 +156,120 @@ test("stale displayed native text cannot use a fresh SDK revision, including aft } finally {update.mock.restore();} } finally {data.release(); h.close();} }); +test("a remote edit delivered during reconnect cannot become the base of a stored offline draft", async () => { + const h = await applicationFixture(), drafts = new JournalDrafts(memoryStorage()); + const id = drafts.put({...drafts.blank(h.connection.id), body: "Seed", path: "offline-draft.md"}).id; + const data = new JournalData(h.connection, drafts); + try { + const lease = await data.open(id, journalEntryTypes(catalog())[0]!); + const recordId = lease.session.getSnapshot().record.id; + h.replica.setOnline(false); + // The origin store holds the edit before it can reach a borrowed SDK lease. + drafts.patch(id, {body: "Offline writing"}); + h.replica.setOnline(true); + h.replica.editElsewhere(recordId, {body: "Other device"}); + for (let i = 0; i < 100 && lease.session.getSnapshot().body !== "Other device"; i++) await new Promise(resolve => setTimeout(resolve, 5)); + assert.equal(lease.session.getSnapshot().body, "Other device"); + assert.equal(drafts.get(id)?.body, "Offline writing"); + assert.equal(drafts.get(id)?.savedBody, "Seed"); + assert.equal(drafts.get(id)?.reviewRequired, true); + data.release(); + const reopened = new JournalData(h.connection, drafts); + try { + await assert.rejects(reopened.open(id), /changed elsewhere/); + assert.equal((await h.records.get(recordId, {include: {body: true}})).body, "Other device"); + assert.equal((await reopened.useSavedVersion(id)).body, "Other device"); + } finally {reopened.release();} + } finally {data.release(); h.close();} +}); +for (const newerTyping of [false, true]) test(`an offline capture replaced on reconnect retains ${newerTyping ? "newer typing" : "the captured text"}`, async () => { + const h = await applicationFixture(), drafts = new JournalDrafts(memoryStorage()); + const id = drafts.put({...drafts.blank(h.connection.id), body: "Seed", path: "offline-capture.md"}).id; + const data = new JournalData(h.connection, drafts); + try { + const lease = await data.open(id, journalEntryTypes(catalog())[0]!); + const recordId = lease.session.getSnapshot().record.id; + h.replica.setOnline(false); + await data.setBody(id, "Offline writing"); + const reconnect = deferred(), submit = h.records.update.bind(h.records); + const update = mock.method(h.records, "update", async (...args: Parameters) => { + const write = await submit(...args); + reconnect.resolve(); + return write; + }); + const saving = lease.session.flush({timeoutMs: 2000}); + await reconnect.promise; + if (newerTyping) await data.setBody(id, "Offline writing plus more"); + h.replica.editElsewhere(recordId, {body: "Other device"}); + h.replica.setOnline(true); h.replica.confirmAll(); + await saving; + assert.equal(update.mock.callCount(), 1); + assert.equal(drafts.get(id)?.body, newerTyping ? "Offline writing plus more" : "Offline writing"); + assert.equal(drafts.get(id)?.savedBody, "Seed"); + assert.equal(drafts.get(id)?.reviewRequired, true); + assert.equal((await h.records.get(recordId, {include: {body: true}})).body, "Other device"); + const saved = await data.useSavedVersion(id); + assert.equal(saved.body, "Other device"); + assert.equal(saved.reviewRequired, false); + assert.equal((await data.open(id)).session.getSnapshot().dirty, false); + assert.equal(update.mock.callCount(), 1); + update.mock.restore(); + } finally {data.release(); h.close();} +}); +test("reopening a pending offline edit in a fresh client keeps its witnessed base until review", async () => { + const h = await applicationFixture(), drafts = new JournalDrafts(memoryStorage()), data = new JournalData(h.connection, drafts); + const id = drafts.put({...drafts.blank(h.connection.id), body: "Seed", path: "offline-reopen.md"}).id; + const records = await h.replica.client(); + const reopened = new JournalData({...h.connection, records, files: records.files}, drafts); + try { + const lease = await data.open(id, journalEntryTypes(catalog())[0]!); + const recordId = lease.session.getSnapshot().record.id; + h.replica.setOnline(false); + await data.setBody(id, "Offline writing"); + assert.equal((await lease.session.flush({timeoutMs: 150})).ok, true); + assert.equal(lease.session.getSnapshot().state, "saved_on_device"); + assert.equal(drafts.get(id)?.pendingRecordRevision, lease.session.getSnapshot().record.revision); + await data.setBody(id, "Offline writing plus more"); + data.release(); + h.replica.editElsewhere(recordId, {body: "Other device"}); + h.replica.setOnline(true); h.replica.confirmAll(); + await assert.rejects(reopened.open(id), /changed elsewhere/); + assert.equal(drafts.get(id)?.body, "Offline writing plus more"); + assert.equal(drafts.get(id)?.reviewRequired, true); + assert.equal((await h.records.get(recordId, {include: {body: true}})).body, "Other device"); + } finally {reopened.release(); records.close(); data.release(); h.close();} +}); +test("an SDK capture retained across lease release cannot replay newer typing against another editor's text", async () => { + const h = await applicationFixture(), drafts = new JournalDrafts(memoryStorage()), data = new JournalData(h.connection, drafts); + const id = drafts.put({...drafts.blank(h.connection.id), body: "Seed", path: "offline-retained.md"}).id; + const reopened = new JournalData(h.connection, drafts); + const captured = deferred(), submit = h.records.update.bind(h.records); + const update = mock.method(h.records, "update", async (...args: Parameters) => { + const write = await submit(...args); + captured.resolve(); + return write; + }); + try { + const lease = await data.open(id, journalEntryTypes(catalog())[0]!); + const recordId = lease.session.getSnapshot().record.id; + h.replica.setOnline(false); + await data.setBody(id, "Offline writing"); + const saving = lease.session.flush({timeoutMs: 2000}); + await captured.promise; + await data.setBody(id, "Offline writing plus more"); + data.release(); + await saving; + await reopened.open(id); + h.replica.editElsewhere(recordId, {body: "Other device"}); + h.replica.setOnline(true); h.replica.confirmAll(); + for (let i = 0; i < 100 && !drafts.get(id)?.reviewRequired; i++) await new Promise(resolve => setTimeout(resolve, 5)); + assert.equal(drafts.get(id)?.reviewRequired, true); + assert.equal(drafts.get(id)?.body, "Offline writing plus more"); + await assert.rejects(reopened.flush(id), /changed elsewhere/); + assert.equal(update.mock.callCount(), 1); + assert.equal((await h.records.get(recordId, {include: {body: true}})).body, "Other device"); + } finally {update.mock.restore(); reopened.release(); data.release(); h.close();} +}); test("clean native SDK source updates reconcile text as well as its saved baseline", async () => { const h = await applicationFixture(), drafts = new JournalDrafts(memoryStorage()); const draft = drafts.put({...drafts.blank(h.connection.id), body: "Seed", path: "native-clean-update.md"});