- Unsaved edits from an earlier session are available.
- Editing is paused until you restore or discard these edits. They stay in this browser for up to seven days, or until saved or discarded. Restoring does not overwrite a newer version without review.
+ {noteSessions.current.active.recoveryDraft.awaitingSync
+ ? This note changed elsewhere : Unsaved edits from an earlier session are available.}
+ {!noteSessions.current.active.recoveryDraft.awaitingSync && Editing is paused until you restore or discard these edits. They stay in this browser for up to seven days, or until saved or discarded. Restoring does not overwrite a newer version without review.
}
Review recovered text
{noteSessions.current.active.recoveryDraft.body}
{Object.keys(noteSessions.current.active.recoveryDraft.patch).length > 0 && {JSON.stringify(noteSessions.current.active.recoveryDraft.patch, null, 2)}}
diff --git a/apps/editor/src/CollectionRail.tsx b/apps/editor/src/CollectionRail.tsx
index 26b1ac8da..a92065af7 100644
--- a/apps/editor/src/CollectionRail.tsx
+++ b/apps/editor/src/CollectionRail.tsx
@@ -332,6 +332,7 @@ export function ConnectionStatus({ state, issue, onReconnect }: { state: ShownCo
stopped: t`Collection stopped`,
offline: t`Collection offline`,
saved_on_device: t`Collection changes are saved on this device and will sync automatically when the connection returns`,
+ rejected: label,
unsynced: label
}[state];
const title = issue ?? (state === "saved_on_device" ? t`Changes are saved on this device and will sync automatically when the connection returns.` : label);
@@ -346,6 +347,7 @@ export type ShownConnectionState = ConnectionState | Exclude = {
get connected() { return t`Connected`; },
get reconnecting() { return t`Reconnecting`; },
+ get rejected() { return t`The note change was rejected.`; },
get stopped() { return t`Sync stopped`; },
get offline() { return t`Offline`; },
get saved_on_device() { return t`Saved on this device · syncs automatically when online`; },
diff --git a/apps/editor/src/app-state-types.ts b/apps/editor/src/app-state-types.ts
index 3fc4f64e5..12f1cd074 100644
--- a/apps/editor/src/app-state-types.ts
+++ b/apps/editor/src/app-state-types.ts
@@ -7,7 +7,7 @@ export type ConnectionState = "connected" | "reconnecting" | "stopped";
/** Whether changes reach the collection: "offline" while it can't be reached,
* "saved_on_device" while changes are kept on this device until they sync,
* "unsynced" in work before connecting, which is saved only in this browser. */
-export type EditorSyncState = "synced" | "offline" | "saved_on_device" | "unsynced";
+export type EditorSyncState = "synced" | "rejected" | "offline" | "saved_on_device" | "unsynced";
export type ContractCatalogLoadState =
| { status: "idle" | "loading" }
| { status: "ready"; catalog: ContractCatalog }
diff --git a/apps/editor/src/draft-recovery.test.ts b/apps/editor/src/draft-recovery.test.ts
index 2bf0f2d1c..15bf84cca 100644
--- a/apps/editor/src/draft-recovery.test.ts
+++ b/apps/editor/src/draft-recovery.test.ts
@@ -35,6 +35,18 @@ it("expires recovery copies after seven days and clears malformed copies", () =>
now.mockRestore();
});
+it("keeps an unconfirmed checkpoint past ordinary draft expiry and through an optimistic read", () => {
+ const store = new DraftRecovery(localStorage, "server");
+ const now = vi.spyOn(Date, "now").mockReturnValue(1000);
+ store.write("one", "note.md", { ...draft, awaitingSync: true }, ignored);
+ store.flush();
+ now.mockReturnValue(1001 + DRAFT_RETENTION_MS);
+ const saved = { body: draft.body, frontmatter: { title: "New" } };
+ expect(store.read("one", "note.md", { ...saved, pendingSync: true })).toMatchObject(draft);
+ expect(store.read("one", "note.md", saved)).toBeUndefined();
+ now.mockRestore();
+});
+
it("does not hide storage failures or confuse deletions with unchanged properties", () => {
const store = new DraftRecovery(localStorage, "server");
const write = vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { throw new DOMException("Full", "QuotaExceededError"); });
diff --git a/apps/editor/src/draft-recovery.ts b/apps/editor/src/draft-recovery.ts
index 7bad032a8..44a676360 100644
--- a/apps/editor/src/draft-recovery.ts
+++ b/apps/editor/src/draft-recovery.ts
@@ -13,9 +13,11 @@ export interface RecoveryDraft {
patch: JsonObject;
baseFrontmatter: JsonObject;
savedAt: number;
+ /** An accepted device write may remain offline beyond the unsent draft retention window. */
+ awaitingSync?: true;
}
-interface SavedDraftRecord { body?: string; frontmatter: JsonObject }
+interface SavedDraftRecord { pendingSync?: true; body?: string; frontmatter: JsonObject }
/** A checkpoint is unnecessary only when its body AND every edited property are saved. */
export function recoveryDraftMatchesRecord(draft: RecoveryDraft, record: SavedDraftRecord): boolean {
@@ -46,7 +48,7 @@ export class DraftRecovery {
read(collection: string, path: string, saved?: SavedDraftRecord): RecoveryDraft | undefined {
const draft = this.readKey(this.key(collection, path));
- if (draft && saved && recoveryDraftMatchesRecord(draft, saved)) {
+ if (draft && saved && !saved.pendingSync && recoveryDraftMatchesRecord(draft, saved)) {
this.remove(collection, path, saved);
return;
}
@@ -61,7 +63,7 @@ export class DraftRecovery {
catch { this.storage.removeItem(key); return; }
if (!value || typeof value.body !== "string" || typeof value.baseBody !== "string"
|| !object(value.patch) || !object(value.baseFrontmatter)
- || !Number.isFinite(value.savedAt) || Date.now() - value.savedAt > DRAFT_RETENTION_MS) {
+ || !Number.isFinite(value.savedAt) || (value.awaitingSync !== true && Date.now() - value.savedAt > DRAFT_RETENTION_MS)) {
this.storage.removeItem(key);
return;
}
diff --git a/apps/editor/src/i18n/locales/de/messages.po b/apps/editor/src/i18n/locales/de/messages.po
index e67859fcb..de693b0d8 100644
--- a/apps/editor/src/i18n/locales/de/messages.po
+++ b/apps/editor/src/i18n/locales/de/messages.po
@@ -5882,6 +5882,7 @@ msgstr "Der native Schreibvorgang hat seine Änderungsidentität gewechselt."
msgid "The new type definition hasn’t been saved."
msgstr "Die neue Typdefinition wurde noch nicht gespeichert."
+#: src/CollectionRail.tsx
#: src/next-editor-records.ts
msgid "The note change was rejected."
msgstr "Die Notizänderung wurde abgelehnt."
@@ -6251,6 +6252,7 @@ msgstr "Diese Notizänderung ist nicht bestätigt. Prüfen Sie den unterbrochene
msgid "This note changed after it was opened. Reload before saving."
msgstr "Diese Notiz wurde nach dem Öffnen geändert. Laden Sie sie vor dem Speichern neu."
+#: src/App.tsx
#: src/ConflictResolver.tsx
msgid "This note changed elsewhere"
msgstr "Diese Notiz wurde an anderer Stelle geändert"
diff --git a/apps/editor/src/i18n/locales/en/messages.po b/apps/editor/src/i18n/locales/en/messages.po
index 865d0ce4f..bc7345ca0 100644
--- a/apps/editor/src/i18n/locales/en/messages.po
+++ b/apps/editor/src/i18n/locales/en/messages.po
@@ -5882,6 +5882,7 @@ msgstr "The native write changed its mutation identity."
msgid "The new type definition hasn’t been saved."
msgstr "The new type definition hasn’t been saved."
+#: src/CollectionRail.tsx
#: src/next-editor-records.ts
msgid "The note change was rejected."
msgstr "The note change was rejected."
@@ -6251,6 +6252,7 @@ msgstr "This note change is not confirmed. Check the interrupted operation befor
msgid "This note changed after it was opened. Reload before saving."
msgstr "This note changed after it was opened. Reload before saving."
+#: src/App.tsx
#: src/ConflictResolver.tsx
msgid "This note changed elsewhere"
msgstr "This note changed elsewhere"
diff --git a/apps/editor/src/i18n/locales/es/messages.po b/apps/editor/src/i18n/locales/es/messages.po
index 19781137e..c39253491 100644
--- a/apps/editor/src/i18n/locales/es/messages.po
+++ b/apps/editor/src/i18n/locales/es/messages.po
@@ -5882,6 +5882,7 @@ msgstr "La escritura nativa cambió su identidad de mutación."
msgid "The new type definition hasn’t been saved."
msgstr "La nueva definición de tipo no se ha guardado."
+#: src/CollectionRail.tsx
#: src/next-editor-records.ts
msgid "The note change was rejected."
msgstr "Se rechazó el cambio de la nota."
@@ -6251,6 +6252,7 @@ msgstr "Este cambio en la nota sigue sin confirmar. Revisa la operación interru
msgid "This note changed after it was opened. Reload before saving."
msgstr "Esta nota cambió después de abrirse. Vuelve a cargarla antes de guardar."
+#: src/App.tsx
#: src/ConflictResolver.tsx
msgid "This note changed elsewhere"
msgstr "Esta nota cambió en otro lugar"
diff --git a/apps/editor/src/i18n/locales/fr/messages.po b/apps/editor/src/i18n/locales/fr/messages.po
index b967e8b44..3baf77e6e 100644
--- a/apps/editor/src/i18n/locales/fr/messages.po
+++ b/apps/editor/src/i18n/locales/fr/messages.po
@@ -5882,6 +5882,7 @@ msgstr "L’écriture native a modifié l’identité de sa mutation."
msgid "The new type definition hasn’t been saved."
msgstr "La nouvelle définition de type n’a pas été enregistrée."
+#: src/CollectionRail.tsx
#: src/next-editor-records.ts
msgid "The note change was rejected."
msgstr "La modification de la note a été rejetée."
@@ -6251,6 +6252,7 @@ msgstr "La modification de cette note n’est pas confirmée. Vérifiez l’opé
msgid "This note changed after it was opened. Reload before saving."
msgstr "Cette note a changé après son ouverture. Rechargez-la avant d’enregistrer."
+#: src/App.tsx
#: src/ConflictResolver.tsx
msgid "This note changed elsewhere"
msgstr "Cette note a changé ailleurs"
diff --git a/apps/editor/src/i18n/locales/it/messages.po b/apps/editor/src/i18n/locales/it/messages.po
index f5c53c870..72ef5ddb7 100644
--- a/apps/editor/src/i18n/locales/it/messages.po
+++ b/apps/editor/src/i18n/locales/it/messages.po
@@ -5882,6 +5882,7 @@ msgstr "La scrittura nativa ha cambiato la sua identità di mutazione."
msgid "The new type definition hasn’t been saved."
msgstr "La nuova definizione di tipo non è stata salvata."
+#: src/CollectionRail.tsx
#: src/next-editor-records.ts
msgid "The note change was rejected."
msgstr "La modifica della nota è stata respinta."
@@ -6251,6 +6252,7 @@ msgstr "Questa modifica della nota non è confermata. Controllare l'operazione i
msgid "This note changed after it was opened. Reload before saving."
msgstr "Questa nota è cambiata dopo essere stata aperta. Ricarica prima di salvare."
+#: src/App.tsx
#: src/ConflictResolver.tsx
msgid "This note changed elsewhere"
msgstr "Questa nota è cambiata altrove"
diff --git a/apps/editor/src/i18n/locales/ja/messages.po b/apps/editor/src/i18n/locales/ja/messages.po
index a7f65cadd..c5d897067 100644
--- a/apps/editor/src/i18n/locales/ja/messages.po
+++ b/apps/editor/src/i18n/locales/ja/messages.po
@@ -5882,6 +5882,7 @@ msgstr "ネイティブの書き込みで変更操作の識別子が変わりま
msgid "The new type definition hasn’t been saved."
msgstr "新しい型定義はまだ保存されていません。"
+#: src/CollectionRail.tsx
#: src/next-editor-records.ts
msgid "The note change was rejected."
msgstr "ノートの変更は拒否されました。"
@@ -6251,6 +6252,7 @@ msgstr "このノートの変更は未確認です。再試行前に中断され
msgid "This note changed after it was opened. Reload before saving."
msgstr "このノートは開いた後に変更されました。保存前に再読み込みしてください。"
+#: src/App.tsx
#: src/ConflictResolver.tsx
msgid "This note changed elsewhere"
msgstr "このノートは別の場所で変更されました"
diff --git a/apps/editor/src/i18n/locales/ko/messages.po b/apps/editor/src/i18n/locales/ko/messages.po
index af0d7a8ce..9fe16793f 100644
--- a/apps/editor/src/i18n/locales/ko/messages.po
+++ b/apps/editor/src/i18n/locales/ko/messages.po
@@ -5882,6 +5882,7 @@ msgstr "네이티브 쓰기의 변경 ID가 달라졌습니다."
msgid "The new type definition hasn’t been saved."
msgstr "새 유형 정의가 저장되지 않았습니다."
+#: src/CollectionRail.tsx
#: src/next-editor-records.ts
msgid "The note change was rejected."
msgstr "노트 변경이 거부되었습니다."
@@ -6251,6 +6252,7 @@ msgstr "이 노트 변경은 확인되지 않았습니다. 다시 시도하기
msgid "This note changed after it was opened. Reload before saving."
msgstr "노트를 연 후 변경되었습니다. 저장하기 전에 새로고침하세요."
+#: src/App.tsx
#: src/ConflictResolver.tsx
msgid "This note changed elsewhere"
msgstr "이 노트가 다른 곳에서 변경됨"
diff --git a/apps/editor/src/i18n/locales/pt/messages.po b/apps/editor/src/i18n/locales/pt/messages.po
index 837ba7077..c61c9c42f 100644
--- a/apps/editor/src/i18n/locales/pt/messages.po
+++ b/apps/editor/src/i18n/locales/pt/messages.po
@@ -5882,6 +5882,7 @@ msgstr "A gravação nativa alterou sua identidade de mutação."
msgid "The new type definition hasn’t been saved."
msgstr "A nova definição de tipo ainda não foi salva."
+#: src/CollectionRail.tsx
#: src/next-editor-records.ts
msgid "The note change was rejected."
msgstr "A alteração da nota foi rejeitada."
@@ -6251,6 +6252,7 @@ msgstr "A alteração desta nota não foi confirmada. Verifique a operação int
msgid "This note changed after it was opened. Reload before saving."
msgstr "Esta nota mudou depois de ser aberta. Recarregue antes de salvar."
+#: src/App.tsx
#: src/ConflictResolver.tsx
msgid "This note changed elsewhere"
msgstr "Esta nota mudou em outro lugar"
diff --git a/apps/editor/src/i18n/locales/ru/messages.po b/apps/editor/src/i18n/locales/ru/messages.po
index 6b5c98bae..0e7db7a56 100644
--- a/apps/editor/src/i18n/locales/ru/messages.po
+++ b/apps/editor/src/i18n/locales/ru/messages.po
@@ -5882,6 +5882,7 @@ msgstr "При записи в источник изменился иденти
msgid "The new type definition hasn’t been saved."
msgstr "Новое определение типа ещё не сохранено."
+#: src/CollectionRail.tsx
#: src/next-editor-records.ts
msgid "The note change was rejected."
msgstr "Изменение заметки отклонено."
@@ -6251,6 +6252,7 @@ msgstr "Изменение заметки не подтверждено. Про
msgid "This note changed after it was opened. Reload before saving."
msgstr "Заметка изменилась после открытия. Перезагрузите её перед сохранением."
+#: src/App.tsx
#: src/ConflictResolver.tsx
msgid "This note changed elsewhere"
msgstr "Эта заметка изменена в другом месте"
diff --git a/apps/editor/src/i18n/locales/zh/messages.po b/apps/editor/src/i18n/locales/zh/messages.po
index a22d71457..c0022fc97 100644
--- a/apps/editor/src/i18n/locales/zh/messages.po
+++ b/apps/editor/src/i18n/locales/zh/messages.po
@@ -5882,6 +5882,7 @@ msgstr "原生写入的变更标识发生了变化。"
msgid "The new type definition hasn’t been saved."
msgstr "新的类型定义尚未保存。"
+#: src/CollectionRail.tsx
#: src/next-editor-records.ts
msgid "The note change was rejected."
msgstr "笔记更改已被拒绝。"
@@ -6251,6 +6252,7 @@ msgstr "此笔记更改尚未确认。请先检查中断的操作,再重试。
msgid "This note changed after it was opened. Reload before saving."
msgstr "此笔记在打开后发生了更改。请在保存前重新加载。"
+#: src/App.tsx
#: src/ConflictResolver.tsx
msgid "This note changed elsewhere"
msgstr "此笔记已在其他位置更改"
diff --git a/apps/editor/src/model.ts b/apps/editor/src/model.ts
index 4f2d3e0ae..cb868b24d 100644
--- a/apps/editor/src/model.ts
+++ b/apps/editor/src/model.ts
@@ -18,7 +18,10 @@ export interface NoteSummary extends QueryRecord {
effectiveFrontmatter: NoteFrontmatter;
}
-export type NoteDocument = RecordDocument;
+export type NoteDocument = RecordDocument & {
+ /** The native record includes changes that can still be refused at the log head. */
+ pendingSync?: true;
+};
export interface CollectionSnapshot {
description: CollectionDescription;
diff --git a/apps/editor/src/native-gateway.ts b/apps/editor/src/native-gateway.ts
index 1a0834548..c5bf79e82 100644
--- a/apps/editor/src/native-gateway.ts
+++ b/apps/editor/src/native-gateway.ts
@@ -181,7 +181,8 @@ export class NativeEditorGateway implements CollectionGateway {
if (!this.current()) return "synced";
const phase = this.application.getSnapshot?.().phase;
if (phase?.kind === "unsynced" && phase.collectionId === this.connection.id) return "unsynced";
- if (this.client.ledger.getSnapshot().saveState === "saved_on_device") return "saved_on_device";
+ const { saveState } = this.client.ledger.getSnapshot();
+ if (saveState === "rejected" || saveState === "saved_on_device") return saveState;
const sync = phase?.kind === "ready" && phase.collectionId === this.connection.id ? this.application.getSnapshot?.().sync : null;
return sync?.connection === "offline" || sync?.health === "unreachable" || this.client.status.connection === "offline" || this.client.link !== "open" ? "offline" : "synced";
}
@@ -636,8 +637,9 @@ export class NativeEditorGateway implements CollectionGateway {
private summary(): ConnectionSummary {
const missing = this.missingCapabilities();
+ const entry = this.entry();
return { collectionId: this.connection.id, role: this.role(), displayName: this.connection.displayName, operations: this.operations(), fileActions: this.fileActions(),
- ...(this.entry()?.kind === "private" ? { private: true as const } : {}),
+ ...(entry?.kind === "private" || entry?.mode === "private" ? { private: true as const } : {}),
...(missing.length ? { missingCapabilities: missing } : {}) };
}
diff --git a/apps/editor/src/next-editor-records.test.ts b/apps/editor/src/next-editor-records.test.ts
index 0b00dd7f7..32ca5bdff 100644
--- a/apps/editor/src/next-editor-records.test.ts
+++ b/apps/editor/src/next-editor-records.test.ts
@@ -48,8 +48,8 @@ describe("NextEditorRecords (SDK stand-in, not LAB)", () => {
expect(saved.body).toBe("Changed body\n");
expect(saved.frontmatter.status).toBe("done");
expect(update).toHaveBeenCalledWith(expect.objectContaining({ id: f.record.id, revision: base.revision }),
- { patch: { status: "done" }, body: "Changed body\n", ifRevision: base.revision },
- expect.objectContaining({ mutationId: expect.any(String), signal: expect.any(AbortSignal) }));
+ { patch: { status: "done" }, body: "Changed body\n", ifRevision: base.revision, requireLive: true },
+ expect.objectContaining({ mutationId: expect.any(String), conflictMode: "reject", signal: expect.any(AbortSignal) }));
expect(f.adapter.pendingMutations()).toEqual([]);
});
@@ -176,7 +176,7 @@ describe("NextEditorRecords (SDK stand-in, not LAB)", () => {
const f = await fixture(true);
const base = await f.adapter.read(f.record.path);
vi.spyOn(f.client, "awaitReceipt").mockImplementation(async mutation => ({ mutation, state: "pending" }));
- expect((await f.adapter.updateProperties(base.path, { status: "done" }, base.revision))?.frontmatter.status).toBe("done");
+ expect(await f.adapter.updateProperties(base.path, { status: "done" }, base.revision)).toMatchObject({ pendingSync: true, frontmatter: { status: "done" } });
expect(f.adapter.pendingMutations()).toEqual([]);
});
diff --git a/apps/editor/src/next-editor-records.ts b/apps/editor/src/next-editor-records.ts
index e5cdd854d..fcb89834a 100644
--- a/apps/editor/src/next-editor-records.ts
+++ b/apps/editor/src/next-editor-records.ts
@@ -89,7 +89,8 @@ export class NextEditorRecords {
patch: (change.patch ?? {}) as Record,
...(change.body === undefined ? {} : { body: change.body }),
ifRevision: base.revision,
- }, options), current) as Promise;
+ requireLive: true,
+ }, { ...options, conflictMode: "reject" }), current) as Promise;
}
async updateProperties(path: string, patch: JsonObject, revision: string, signal?: AbortSignal): Promise {
@@ -218,10 +219,10 @@ export class NextEditorRecords {
if (record.state.hold || record.state.unresolved)
throw new MdbaseError({ code: "outcome_unknown", reason: "unqualified_readback", recovery: "resolve_outcome", message: t`The current note is protected. Keep the original operation for recovery before reporting it as saved.` });
this.unknown.delete(mutation.mutationId);
- return this.remember(record);
+ return this.remember(record, receipt.state === "pending");
}
- private remember(record: RecordView): NoteDocument {
+ private remember(record: RecordView, pendingReceipt = false): NoteDocument {
completeSource(record);
const key = JSON.stringify([record.path, record.revision]);
const previous = this.seen.get(key);
@@ -239,7 +240,8 @@ export class NextEditorRecords {
this.seenBytes -= this.seen.get(oldest)!.bytes;
this.seen.delete(oldest);
}
- return { path: record.path, revision: record.revision, types: [...record.types],
+ return { ...(pendingReceipt || record.state.state === "pending" ? { pendingSync: true as const } : {}),
+ path: record.path, revision: record.revision, types: [...record.types],
frontmatter: record.frontmatter, effectiveFrontmatter: record.effective ?? record.frontmatter,
body: record.body, document: record.document,
file: { path: record.path, ...(record.mtime === undefined ? {} : { mtime: new Date(record.mtime).toISOString() }) } };
diff --git a/apps/editor/src/note-session.test.ts b/apps/editor/src/note-session.test.ts
index 6ff4c5454..fb133d6f6 100644
--- a/apps/editor/src/note-session.test.ts
+++ b/apps/editor/src/note-session.test.ts
@@ -17,7 +17,7 @@ function document(path: string, overrides: Partial = {}): NoteDocu
};
}
-function session(note: NoteDocument, update = vi.fn(async (base: NoteDocument, change: MdbaseRecordChange) => ({
+function session(note: NoteDocument, update = vi.fn(async (base: NoteDocument, change: MdbaseRecordChange): Promise => ({
...base, revision: "2", body: change.body ?? base.body
}))) {
const gateway = { update, read: vi.fn(async () => note), recoverNoteMutation: vi.fn(), pendingNoteMutations: () => [] };
@@ -67,6 +67,25 @@ describe("note sessions", () => {
expect(note.draft).toMatchObject({ title: "Remote", body: "New body\n" });
});
+ it.each([true, false])("reconciles a confirmed save with a newer readback (continued typing %s)", async (continued) => {
+ const base = document("one.md", { body: "Original" });
+ const result = { ...base, revision: "3", body: "Later confirmed edit" };
+ let acknowledge!: (record: NoteDocument) => void;
+ const update = vi.fn(() => new Promise(resolve => { acknowledge = resolve; }));
+ const { session: note } = session(base, update);
+ note.record.setBody("Submitted");
+ const saving = note.record.save();
+ await vi.waitFor(() => expect(update).toHaveBeenCalledOnce());
+ if (continued) note.record.setBody("Typing continued");
+ acknowledge(result);
+ await saving;
+ expect(note.record.snapshot.body).toBe(continued ? "Typing continued" : result.body);
+ expect(note.record.snapshot.state).toBe(continued ? "conflict" : "saved");
+ expect(note.record.snapshot.remote).toEqual(continued ? result : null);
+ expect(update).toHaveBeenCalledOnce();
+ note.record.dispose();
+ });
+
it("moves one session identity between paths", () => {
const store = new NoteSessionStore();
const { session: note } = session(document("old.md"));
diff --git a/apps/editor/src/note-session.ts b/apps/editor/src/note-session.ts
index 26eb3c4de..672c8422c 100644
--- a/apps/editor/src/note-session.ts
+++ b/apps/editor/src/note-session.ts
@@ -112,6 +112,7 @@ export function noteRecordAdapter(
): MdbaseRecordSessionAdapter {
return {
revision: (note) => note.revision,
+ pendingSync: (note) => Boolean(note.pendingSync),
body: (note) => note.body ?? "",
frontmatter: (note) => note.frontmatter,
write: (base, change) => outcome(() => guard(() => gateway.update(base, change))),
diff --git a/apps/editor/src/record-session.ts b/apps/editor/src/record-session.ts
index 8a603f43f..fc80e8cf5 100644
--- a/apps/editor/src/record-session.ts
+++ b/apps/editor/src/record-session.ts
@@ -23,6 +23,7 @@ export type MdbaseRecordSessionState =
export interface MdbaseRecordSessionAdapter {
revision(record: R): string;
body(record: R): string;
+ pendingSync?(record: R): boolean;
frontmatter?(record: R): JsonObject;
write(base: R, change: MdbaseRecordChange, options?: ConnectRequestOptions): Promise>;
read?(base: R, options?: ConnectRequestOptions): Promise>;
@@ -358,7 +359,17 @@ export class MdbaseRecordSession {
private acknowledge(result: R, sent: Sent): void {
this.seen.add(this.adapter.revision(result));
this.record = result;
- if (sent.body !== undefined) this.baseBody = sent.body;
+ const returned = this.adapter.body(result);
+ const submitted = sent.body ?? this.baseBody;
+ if (this.adapter.pendingSync?.(result)) {
+ // The pending receipt can race a rollback. The checkpoint owns the
+ // submitted text until the device learns the outcome.
+ this.baseBody = submitted;
+ } else {
+ if (this.body === submitted) this.body = returned;
+ else if (returned !== submitted && this.body !== returned) this.remote = result;
+ this.baseBody = returned;
+ }
for (const [key, value] of Object.entries(sent.patch ?? {})) {
if (key in this.patch && sameJson(this.patch[key], value)) delete this.patch[key];
}
@@ -401,7 +412,10 @@ export class MdbaseRecordSession {
}
private classify(record: R): void {
- if (this.adapter.revision(record) === this.adapter.revision(this.record)) return;
+ if (this.adapter.revision(record) === this.adapter.revision(this.record)) {
+ if (this.adapter.pendingSync?.(this.record) && !this.adapter.pendingSync(record)) this.record = record;
+ return;
+ }
const baseBody = this.adapter.body(this.record);
const remoteBody = this.adapter.body(record);
const bodyChanged = remoteBody !== baseBody;
diff --git a/apps/editor/tests/editor-regressions.spec.ts b/apps/editor/tests/editor-regressions.spec.ts
index 62d93208f..aa05fa9be 100644
--- a/apps/editor/tests/editor-regressions.spec.ts
+++ b/apps/editor/tests/editor-regressions.spec.ts
@@ -134,3 +134,49 @@ test("the self-hosted form reports invalid codes and sends a full pasted code",
await submit.click();
await expect.poll(() => submitted).toEqual(["12345678"]);
});
+
+for (const reload of [true, false]) {
+ test(`an offline edit survives a rejected write in Chromium (reload ${reload})`, async ({ page, context }) => {
+ type ReplicaWindow = Window & { offlineFixture: import("@mdbase-dev/sdk/testing").TestApp };
+ await page.goto(`${fixture}?scenario=offline-replica`);
+ const editor = page.frameLocator('iframe[title="Editor"]');
+ const body = editor.getByRole("textbox", { name: "Note body" });
+ await expect(body).toHaveText("Base text");
+ await page.evaluate(async () => {
+ await navigator.serviceWorker.register("/mdbase-shell-sw.js", { type: "module" });
+ await navigator.serviceWorker.ready;
+ });
+ await page.waitForFunction(() => !!navigator.serviceWorker.controller);
+ await context.setOffline(true);
+ await page.evaluate(() => (window as ReplicaWindow).offlineFixture.replica().setOnline(false));
+ await body.fill("Browser offline edit");
+ await expect.poll(() => page.evaluate(() => {
+ const key = Object.keys(localStorage).find(key => key.startsWith("mdbase-editor:draft:v1:"));
+ return key && JSON.parse(localStorage.getItem(key)!).awaitingSync;
+ })).toBe(true);
+ if (reload) {
+ const navigation = page.waitForEvent("framenavigated", frame => frame.url().endsWith("?scenario=offline-editor"));
+ await editor.locator("body").evaluate(() => location.reload());
+ const reloaded = await navigation;
+ expect(await reloaded.evaluate(() => navigator.onLine)).toBe(false);
+ await expect(body).toHaveText("Browser offline edit");
+ await expect(body).toBeEditable();
+ }
+ await context.setOffline(false);
+ await page.evaluate(() => {
+ const fixture = (window as ReplicaWindow).offlineFixture;
+ const [pending] = fixture.client().ledger.getSnapshot().pending;
+ fixture.replica().reject(pending.mutationId);
+ fixture.replica().editElsewhere(pending.records[0], { body: "Concurrent remote edit" });
+ fixture.replica().setOnline(true);
+ });
+ const recovery = editor.getByRole("status", { name: "Unsaved draft found" });
+ await expect(body).toHaveText("Concurrent remote edit");
+ await recovery.getByText("Review recovered text").click();
+ await expect(recovery.locator("pre")).toHaveText("Browser offline edit");
+ await recovery.getByRole("button", { name: "Restore unsaved edits" }).click();
+ await editor.getByRole("button", { name: "Keep my edits" }).click();
+ await expect.poll(() => page.evaluate(() =>
+ (window as ReplicaWindow).offlineFixture.replica().allRecords[0].body)).toBe("Browser offline edit");
+ });
+}
diff --git a/apps/editor/tests/fixtures/editor-regressions.tsx b/apps/editor/tests/fixtures/editor-regressions.tsx
index 2a502c24c..1fac6d5ce 100644
--- a/apps/editor/tests/fixtures/editor-regressions.tsx
+++ b/apps/editor/tests/fixtures/editor-regressions.tsx
@@ -25,6 +25,27 @@ function render(content: React.ReactNode) {
}
async function start() {
+ if (scenario === "local-stack") {
+ // Served only by the loopback CLI/Chromium runner, with its own build-time trust.
+ const module = "/local-sdk/application/editor.js";
+ const { sdk } = await import(/* @vite-ignore */ module);
+ render();
+ return;
+ }
+ if (scenario === "offline-replica") {
+ // Keep the SDK test replica in the parent while the iframe reloads Editor.
+ const fixture = await createTestApp({ collections: [{ name: "Offline notes",
+ records: [{ path: "note.md", body: "Base text" }] }] });
+ Object.assign(window, { offlineFixture: fixture });
+ render();
+ return;
+ }
+ if (scenario === "offline-editor") {
+ const parent = window.parent as Window & { offlineFixture: Awaited> };
+ render();
+ return;
+ }
if (scenario === "pairing") {
await import("../../direct/style.css");
render();
diff --git a/changelog.d/editor-offline-conflicts.md b/changelog.d/editor-offline-conflicts.md
new file mode 100644
index 000000000..b8781356d
--- /dev/null
+++ b/changelog.d/editor-offline-conflicts.md
@@ -0,0 +1,3 @@
+## Fixed
+
+- Editor preserves offline note edits for review when another device changes the note before it syncs. The SDK’s record editor also preserves rejected body edits, field changes, and field removals for explicit resolution.
diff --git a/runtime/packages/sdk/scripts/app-private-device-local-e2e.mjs b/runtime/packages/sdk/scripts/app-private-device-local-e2e.mjs
index b782dbda9..820f75265 100644
--- a/runtime/packages/sdk/scripts/app-private-device-local-e2e.mjs
+++ b/runtime/packages/sdk/scripts/app-private-device-local-e2e.mjs
@@ -5,6 +5,10 @@
*
* node runtime/packages/sdk/scripts/app-private-device-local-e2e.mjs
*
+ * --editor-offline runs the Editor cloud-copy trials on the CLI stack with real
+ * hosted and escrow Workers. Build prerequisites are listed at the top of
+ * apps/editor/scripts/offline-conflict-e2e.mjs.
+ *
* Options: `--rebuild` rebuilds the cargo artifacts; `--keep` keeps the run's
* scratch directory and logs. Environment: `PLAYWRIGHT_MODULE` (a Playwright
* `index.mjs` with Chromium installed; default as the browser smokes),
@@ -77,7 +81,7 @@
* never contacted. The browser uses its own WebCrypto and IndexedDB in a
* throwaway Chromium profile. */
import assert from "node:assert/strict";
-import { spawn } from "node:child_process";
+import { execFileSync, spawn } from "node:child_process";
import { randomBytes, randomUUID } from "node:crypto";
import { createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
@@ -88,7 +92,6 @@ import { tmpdir } from "node:os";
import { extname, join, normalize, resolve, sep } from "node:path";
import { pathToFileURL } from "node:url";
import { build } from "esbuild";
-import { startHostedPostgres } from "../../../../scripts/lib/hosted-postgres-container.mjs";
import { availableTcpPort, delay, poll } from "../../../../scripts/lib/test-runtime.mjs";
import { bundleLocalServer, checkout, e2eRoot, ensureAppRuntime, ensureDesktop, ensureLocalSdk, ensureStack, ensureTools, runtimeRoot } from "./app-private-device-local-stack.mjs";
@@ -145,7 +148,7 @@ try {
`;
const flags = new Set(process.argv.slice(2));
-for (const flag of flags) if (!["--rebuild", "--keep"].includes(flag)) throw Error(`unknown option ${flag}`);
+for (const flag of flags) if (!["--rebuild", "--keep", "--editor-offline"].includes(flag)) throw Error(`unknown option ${flag}`);
const rebuild = flags.has("--rebuild"), keep = flags.has("--keep");
const step = name => console.log(`ok - ${name}`);
const section = name => console.log(`\n== ${name}`);
@@ -168,7 +171,7 @@ step(`local stack ${connectOrigin} (Connect), ${logOrigin} (log service)`);
// --------------------------------------------------------------------- the run
const run = join(e2eRoot, "runs", `${new Date().toISOString().replace(/[:.]/g, "-")}-${process.pid}`);
-mkdirSync(run, { recursive: true });
+mkdirSync(run, { recursive: true, mode: 0o700 });
// Short: the daemon's Unix sockets live under its state directory.
const scratch = await mkdtemp(join(tmpdir(), "mdpd-"));
const cleanup = [];
@@ -274,17 +277,24 @@ const json = exchange => { try { return JSON.parse(exchange.reply.toString("utf8
const bearer = exchange => /^Bearer (.+)$/.exec(exchange.headers.authorization ?? "")?.[1] ?? null;
const pathOf = exchange => exchange.path.split("?")[0];
-let pg, postgres, connect_, log, hold = null;
+let pg, connect_, log, hold = null;
let failed = false;
-try {
+async function runStack() {
// ------------------------------------------------------------ the local stack
section("local stack");
const connectPort = await portFree(connectOrigin), logPort = await portFree(logOrigin);
- postgres = await startHostedPostgres("private-device-e2e");
- cleanup.push(() => postgres.stop());
- await postgres.createDatabase("private_device_e2e_test");
- const databaseUrl = postgres.databaseUrl("private_device_e2e_test");
- step(`disposable PostgreSQL container ${postgres.container}`);
+ const container = `private-device-e2e-${nonce}`, pgPassword = randomUUID();
+ const docker = (...args) => execFileSync("docker", args, { encoding: "utf8", env: { ...process.env, POSTGRES_PASSWORD: pgPassword }, stdio: ["ignore", "pipe", "pipe"] }).trim();
+ docker("run", "--rm", "-d", "--name", container, "--tmpfs", "/var/lib/postgresql", "-e", "POSTGRES_USER=mdbase",
+ "-e", "POSTGRES_PASSWORD", "-e", "POSTGRES_DB=private_device_e2e_test", "-p", "127.0.0.1::5432", "postgres:18-alpine");
+ cleanup.push(() => docker("stop", container));
+ const port = docker("port", container, "5432/tcp").split(":").pop();
+ await poll(() => {
+ docker("exec", container, "pg_isready", "-h", "127.0.0.1", "-U", "mdbase");
+ return true;
+ }, "the disposable PostgreSQL server did not start", 300, 250);
+ const databaseUrl = `postgres://mdbase:${pgPassword}@127.0.0.1:${port}/private_device_e2e_test`;
+ step(`disposable PostgreSQL container ${container}`);
const logInner = await availableTcpPort(), connectInner = await availableTcpPort();
const logServer = child("log-service", tools.log, ["--listen", `127.0.0.1:${logInner}`, "--backend", "mem", "--public-base", logOrigin],
@@ -293,11 +303,14 @@ try {
await poll(async () => (await fetch(`${logOrigin}/health`)).ok, "the log service never answered", 100, 100);
step("native log service (memory backend) behind its recording front");
+ const editor = flags.has("--editor-offline")
+ ? await import("../../../../apps/editor/scripts/offline-conflict-e2e.mjs") : null;
// Outbound cloud-copy service settings the listing route's mount requires; nothing listens there.
const token = () => randomBytes(24).toString("hex");
const serverEnv = { PATH: process.env.PATH, ...stack.serverEnv, PORT: String(connectInner), DATABASE_URL: databaseUrl,
MDBASE_NEXT_CLOUD_COPY_BOOTSTRAP: "1", MDBASE_NEXT_HOSTED_SERVICE_URL: "http://127.0.0.1:9", MDBASE_NEXT_ESCROW_SERVICE_URL: "http://127.0.0.1:9",
MDBASE_NEXT_HOSTED_SERVICE_TOKEN: token(), MDBASE_NEXT_ESCROW_SERVICE_TOKEN: token(), MDBASE_NEXT_HOSTED_INTERNAL_TOKEN: token(), MDBASE_NEXT_ESCROW_INTERNAL_TOKEN: token() };
+ const startCloudServices = editor && await editor.cloudCopyServices({ checkout, run, sdkLocal, stack, env: serverEnv, cleanup });
// The stand-in for the portal build: one inert page, served by the real server's approval-page rule.
const portalDist = join(run, "portal"); mkdirSync(portalDist, { recursive: true });
writeFileSync(join(portalDist, "index.html"), 'Portal stand-inPortal stand-in: the test performs the portal\'s requests.
');
@@ -311,8 +324,8 @@ try {
exited.catch(() => {});
await Promise.race([exited, poll(async () => (await fetch(`${connectOrigin}/health`)).ok, "the Connect server never answered", 300, 100)]);
}
- await bootConnect(false);
- step("Connect server (own entry, PostgreSQL, private bootstrap, app devices OFF)");
+ await bootConnect(flags.has("--editor-offline"));
+ step("Connect server (own entry, PostgreSQL, private bootstrap)");
const require_ = createRequire(join(checkout, "services/server/package.json"));
pg = new (require_("pg").Pool)({ connectionString: databaseUrl, max: 2 });
@@ -338,7 +351,7 @@ try {
};
// ------------------------------------------------------- step 1: the desktop
- section("1. the desktop creates a Private collection, sets the account key and writes a record");
+ section(editor ? "1. the desktop creates a cloud copy and writes a record" : "1. the desktop creates a Private collection, sets the account key and writes a record");
const state = join(scratch, "s"), folder = join(scratch, "notes"), home = join(scratch, "h");
await mkdir(home, { recursive: true });
// Nothing of the person's desktop session is inherited: its own HOME, XDG
@@ -369,7 +382,8 @@ try {
const cli = spawn(desktopBinary, ["--state-dir", state, "--json", ...args], { env: desktopEnv, cwd: scratch, stdio: ["pipe", "pipe", "pipe"] });
let out = "", err = ""; cli.stdout.on("data", part => { out += part; }); cli.stderr.on("data", part => { err += part; });
cli.once("error", refused);
- cli.once("exit", code => {
+ cli.stdin.on("error", error => { if (error.code !== "EPIPE") refused(error); });
+ cli.once("close", code => {
if (code === 0) { try { done(out.trim() ? JSON.parse(out) : null); } catch { refused(Error(`mdbase ${args.join(" ")}: unreadable output:\n${out}`)); } return; }
const error = Error(`mdbase ${args.join(" ")} failed (${code}):\n${out}${err}`); error.stdout = out; refused(error);
});
@@ -398,19 +412,25 @@ try {
const added = await mdbase(["collection", "add", folder, "--name", "Private notes"]);
await poll(async () => (await mdbase(["collection", "list"])).some(c => c.id === added.id && c.state === "ready"), "the collection never became ready", 300, 100);
const collectionId = added.id;
- const enabled = await mdbase(["sync", "enable", collectionId, "--mode", "private"]);
- console.log(` sync enable: ${JSON.stringify(enabled)}`);
- await poll(async () => (await rows("SELECT sync FROM next_collections WHERE collection_id=$1", [collectionId]))[0]?.sync === "private", "Connect never recorded the Private collection", 300, 100);
- const recorded = (await rows("SELECT * FROM next_collections WHERE collection_id=$1", [collectionId]))[0];
- console.log(` next_collections row: ${JSON.stringify(recorded)}`);
- const setup = await mdbase(["private", "setup"], password);
- const recoveryKey = setup.recovery_key;
- assert.equal(typeof recoveryKey, "string", "private setup returns the recovery key once");
- console.log(` private setup: ${JSON.stringify({ ...setup, recovery_key: "(kept)" })}`);
- console.log(` private status: ${JSON.stringify(await mdbase(["private", "status"]))}`);
+ let recoveryKey, activateHosted;
+ if (startCloudServices) {
+ activateHosted = await startCloudServices(collectionId);
+ await mdbase(["sync", "enable", collectionId, "--mode", "cloud-copy", "--yes"]);
+ } else {
+ const enabled = await mdbase(["sync", "enable", collectionId, "--mode", "private"]);
+ console.log(` sync enable: ${JSON.stringify(enabled)}`);
+ await poll(async () => (await rows("SELECT sync FROM next_collections WHERE collection_id=$1", [collectionId]))[0]?.sync === "private", "Connect never recorded the Private collection", 300, 100);
+ const recorded = (await rows("SELECT * FROM next_collections WHERE collection_id=$1", [collectionId]))[0];
+ console.log(` next_collections row: ${JSON.stringify(recorded)}`);
+ const setup = await mdbase(["private", "setup"], password);
+ recoveryKey = setup.recovery_key;
+ assert.equal(typeof recoveryKey, "string", "private setup returns the recovery key once");
+ console.log(` private setup: ${JSON.stringify({ ...setup, recovery_key: "(kept)" })}`);
+ console.log(` private status: ${JSON.stringify(await mdbase(["private", "status"]))}`);
+ }
await mdbase(["create", "--path", desktopPath, "--type", "task", "--fields", JSON.stringify({ title: desktopMarker, status: "open" }), "-C", folder]);
assert.match(readFileSync(join(folder, desktopPath), "utf8"), new RegExp(desktopMarker));
- step(`Private collection ${collectionId}, account key set with an encryption password, record ${desktopPath} written`);
+ step(`${editor ? "Cloud copy" : "Private collection"} ${collectionId}, record ${desktopPath} written`);
// ------------------------------------------------------------------ the app
section("the app (Chromium, the SDK's local application build, real app-runtime WASM)");
const appPort = await availableTcpPort(), appOrigin = `http://127.0.0.1:${appPort}`;
@@ -423,6 +443,7 @@ try {
await build({ entryPoints: [join(appDirectory, "page.mjs")], outfile: join(appDirectory, "e2e-page.js"), bundle: true, format: "esm", platform: "browser", target: "es2022", logLevel: "error" });
const types = { ".js": "text/javascript", ".mjs": "text/javascript", ".wasm": "application/wasm", ".json": "application/json", ".map": "application/json", ".html": "text/html" };
const sdkDist = join(sdkLocal, "dist");
+ const editorShell = editor && await editor.prepare({ checkout, run, sdkLocal, declaration });
const appServer = createServer((request, response) => {
const path = new URL(request.url, appOrigin).pathname;
const send = (file, type) => { response.writeHead(200, { "content-type": type, "cache-control": "no-store" }); createReadStream(file).pipe(response); };
@@ -434,6 +455,7 @@ try {
const file = normalize(join(sdkDist, path.slice(5)));
if (file.startsWith(sdkDist + sep) && existsSync(file) && statSync(file).isFile()) return send(file, types[extname(file)] ?? "application/octet-stream");
}
+ if (editorShell && editor.serve(editorShell, path, response)) return;
response.writeHead(404); response.end();
});
await new Promise((ready, refused) => { appServer.once("error", refused); appServer.listen(appPort, "127.0.0.1", ready); });
@@ -448,7 +470,7 @@ try {
const browserLog = createWriteStream(join(run, `browser-${profile}.log`), { flags: "a" });
page.on("console", message => browserLog.write(`${message.type()}: ${message.text()}\n`));
page.on("pageerror", error => browserLog.write(`pageerror: ${error?.stack ?? error}\n`));
- await page.goto(`${appOrigin}/`);
+ await page.goto(`${appOrigin}/`, { waitUntil: "commit", timeout: 90_000 });
await page.waitForFunction(() => window.e2eReady === true || typeof window.e2eFailed === "string", null, { timeout: 60_000 });
const broken = await page.evaluate(() => window.e2eFailed ?? null);
if (broken) throw Error(`the app page failed to load: ${broken}`);
@@ -484,6 +506,22 @@ try {
const view = await settle(browser, ["choosing", "ready", "needs_unlock", "needs_setup", "opening", "problem", "signed_out"]);
return { from, pairingId, shown, approval: approval.value, receipt, token: receipt.token, connectorId, view };
}
+ if (editor) {
+ section("Editor offline conflict trials");
+ await editor.seedTrials({ folder, mdbase, collectionId });
+ const browser = await open("editor");
+ const signed = await signInApp(browser, () => ({
+ collection_ids: [collectionId], create_collections: false, selected_collection_id: collectionId,
+ }));
+ if (signed.view.phase.kind === "choosing") await app(browser, "select", collectionId);
+ await awaitExchange(signed.from, exchange => exchange.method === "POST" &&
+ pathOf(exchange) === `/v1/next/collections/${collectionId}/devices` && exchange.status === 200, "browser enrollment");
+ await activateHosted();
+ await settle(browser, ["ready"]);
+ await app(browser, "close");
+ await editor.runTrials({ ...browser, appOrigin, collectionId, folder, mdbase });
+ return;
+ }
const listing = (from, token_) => awaitExchange(from, exchange => exchange.method === "GET" && pathOf(exchange) === "/v1/next/collections" && bearer(exchange) === token_ && exchange.status === 200, "the installation's collection listing");
const scopeRows = connectorId => rows("SELECT collection_id, private_device FROM installation_collection_scopes WHERE connector_id=$1 ORDER BY collection_id", [connectorId]);
/** A request as an installation credential alone would send it (no proof can be signed outside the app). */
@@ -846,13 +884,17 @@ try {
step(`${log.exchanges.length} requests and ${log.streams.length} sockets, ${total(fromApp)} bytes from the app and ${total(fromOthers)} from the desktop and Connect: no record title, body or path in the clear`);
console.log("\nPASS: the Private device path, end to end on the local stack");
+}
+
+try {
+ await runStack();
} catch (error) {
failed = true;
console.error(`\nFAILED: ${error?.stack ?? error}`);
console.error(`logs: ${run}`);
} finally {
// What Connect was asked and answered (throwaway credentials of a disposable database), for reading a failure.
- if (connect_) writeFileSync(join(run, "connect-exchanges.jsonl"), connect_.exchanges.map(exchange => JSON.stringify({ method: exchange.method, path: exchange.path, status: exchange.status,
+ if (connect_ && !flags.has("--editor-offline")) writeFileSync(join(run, "connect-exchanges.jsonl"), connect_.exchanges.map(exchange => JSON.stringify({ method: exchange.method, path: exchange.path, status: exchange.status,
origin: exchange.headers.origin ?? null, request: exchange.body.toString("utf8").slice(0, 2000), reply: exchange.reply?.toString("utf8").slice(0, 4000) ?? null })).join("\n") + "\n");
// Bounded: a step that hangs must not keep the container or a child alive.
for (const close of cleanup.reverse()) await Promise.race([Promise.resolve().then(close).catch(() => {}), delay(15_000)]);
diff --git a/runtime/packages/sdk/src/records/session.ts b/runtime/packages/sdk/src/records/session.ts
index 67b66ed25..0f44853e0 100644
--- a/runtime/packages/sdk/src/records/session.ts
+++ b/runtime/packages/sdk/src/records/session.ts
@@ -3,7 +3,7 @@ import type { MdbaseClient, UpdateInput, Write } from "../client.js";
import { MdbaseError, mdbaseError } from "../errors.js";
import { WriteRefusal } from "../session.js";
import { toPlain, toValue, uuidv7, type PlainValue } from "../values.js";
-import type { JsonValue, Receipt, RecordView } from "../plain.js";
+import { fieldOf, type JsonValue, type Receipt, type RecordView } from "../plain.js";
import type { Problem } from "../wire.js";
import {
complete,
@@ -36,12 +36,26 @@ type Captured = {
body: string;
patch: Map;
};
+// A null key denotes the body. Each field keeps only its latest local intent,
+// even when several writes are accepted on the device before going online.
+type PendingEdits = Map;
+
+function matches(record: RecordView, key: string | null, value: CborValue | undefined): boolean {
+ if (key === null) return value === record.body;
+ const actual = fieldOf(record.frontmatter, key);
+ if (actual === undefined || value === undefined) return actual === value;
+ // RecordView exposes the SDK's plain projection of native values.
+ return equal(toValue(actual), toValue(toPlain(value)));
+}
+
export class RecordSessionImpl {
private base: RecordView;
private body: string;
private patch = new Map();
private remote: RecordView | null = null;
private captured: Captured | null = null;
+ private pendingEdits: PendingEdits = new Map();
+ private driveGeneration = 0;
private lastReceipt: Receipt | null = null;
private state: RecordSessionState;
private why: Problem | null = null;
@@ -66,7 +80,7 @@ export class RecordSessionImpl {
complete(record);
this.base = copy(record);
this.body = record.body!;
- this.state = isProtected(record) ? "conflict" : resting(record);
+ this.state = isProtected(record) ? "conflict" : this.restState;
this.publish();
}
async restore(
@@ -96,8 +110,26 @@ export class RecordSessionImpl {
recovery: { ...hint, receipt: null, write: null },
};
}
- // A pending write from an earlier session is kept on this device and
- // settled by the write ledger; the record stays editable.
+ if (!this.active && !hint && this.base.state.state === "pending" && !this.pendingEdits.size) {
+ const edits: PendingEdits = new Map();
+ for (const { ops, receipt } of await this.client.pendingWrites({ signal })) {
+ for (const op of ops) {
+ if (op.kind !== "update" || op.id !== this.id) continue;
+ const mutation = receipt.mutation;
+ // SDK body writes may be encoded as splices. The replica
+ // already applied them; keep its projected body verbatim.
+ if (op.body !== undefined || op.bodyEdits?.length) {
+ const body = op.body ?? receipt.records?.find(record => record.id === this.id)?.body ?? this.base.body!;
+ edits.set(null, { mutation, value: body });
+ }
+ for (const [key, value] of Object.entries(op.patch ?? {}))
+ edits.set(key, { mutation, value: toValue(value) });
+ for (const key of op.unset ?? []) edits.set(key, { mutation, value: undefined });
+ }
+ }
+ this.charge(this.body, this.patch, this.base, this.remote, this.lastReceipt, this.captured, edits);
+ this.pendingEdits = edits;
+ }
signal?.throwIfAborted();
if (this.captured) {
this.state = "recovery";
@@ -115,8 +147,11 @@ export class RecordSessionImpl {
get dirty(): boolean {
return this.body !== this.base.body || this.patch.size > 0;
}
+ private get restState(): "saved" | "saved_on_device" {
+ return !this.pendingEdits.size && confirmed(this.base) ? "saved" : "saved_on_device";
+ }
get retained(): boolean {
- return this.dirty || this.captured !== null || !confirmed(this.base);
+ return this.dirty || this.captured !== null || this.pendingEdits.size > 0 || !confirmed(this.base);
}
getSnapshot = (): RecordSessionSnapshot => this.snapshot;
subscribe = (listener: () => void): (() => void) => {
@@ -187,7 +222,7 @@ export class RecordSessionImpl {
this.state !== "conflict" &&
this.state !== "deleted"
) {
- this.state = this.dirty ? "unsaved" : resting(this.base);
+ this.state = this.dirty ? "unsaved" : this.restState;
this.why = null;
}
this.publish();
@@ -200,6 +235,7 @@ export class RecordSessionImpl {
remote = this.remote,
receipt = this.lastReceipt,
captured = this.captured,
+ pendingEdits = this.pendingEdits,
): void {
let bytes =
retainedBytes(base) +
@@ -217,6 +253,8 @@ export class RecordSessionImpl {
),
).byteLength *
2;
+ for (const [key, edit] of pendingEdits)
+ bytes += encode([key, edit.mutation, edit.value ?? null]).byteLength * 2;
if (receipt) bytes += retainedBytes(receipt);
this.reserve(bytes);
}
@@ -275,6 +313,77 @@ export class RecordSessionImpl {
complete(record, this.id);
return record;
}
+ /** The projection can change after either a refusal or a successful write
+ * followed by a peer edit. Only the original MID distinguishes them. */
+ private async readWithReceipts(signal: AbortSignal) {
+ const receipts = new Map();
+ for (;;) {
+ const current = await this.read(signal);
+ if (this.captured) return { current, receipts };
+ const count = receipts.size;
+ for (const [key, { mutation, value }] of this.pendingEdits) {
+ const present = matches(current, key, value);
+ if (!confirmed(current) && present) continue;
+ if (!receipts.has(mutation)) {
+ const receipt = await this.client.receipt(mutation, { signal });
+ signal.throwIfAborted();
+ if (receipt.mutation !== mutation)
+ throw refusal("outcome_unknown", "native receipt changed identity", "mutation_identity_mismatch");
+ receipts.set(mutation, receipt);
+ }
+ const receipt = receipts.get(mutation)!;
+ if (receipt.state === "unknown" || (receipt.state === "pending" && !present))
+ throw refusal("outcome_unknown", "the projection does not qualify this device write yet", "unqualified_readback");
+ }
+ // The projection can advance during receipt lookup. Re-read after
+ // each newly consulted group, including any other mutations exposed by that read.
+ if (receipts.size === count) return { current, receipts };
+ }
+ }
+
+ /** Restore only a refused write's missing edits. Newer typing and field
+ * edits win, including an explicit unset; unrelated remote fields survive. */
+ private reconcilePending(current: RecordView, receipts: Map): void {
+ if (!receipts.size) return;
+ const remaining = new Map(this.pendingEdits);
+ const patch = new Map(this.patch);
+ const bodyEdited = this.body !== this.base.body;
+ let body = bodyEdited ? this.body : current.body!;
+ let rolledBack = false;
+ for (const [key, { mutation, value }] of this.pendingEdits) {
+ const receipt = receipts.get(mutation);
+ if (!receipt || receipt.state === "pending" || receipt.state === "unknown") continue;
+ remaining.delete(key);
+ if ((receipt.state !== "rejected" && receipt.status !== "conflicted") || matches(current, key, value)) continue;
+ rolledBack = true;
+ if (key === null) {
+ if (!bodyEdited) body = value as string;
+ } else if (!patch.has(key)) {
+ patch.set(key, value);
+ }
+ }
+ const last = this.lastReceipt && (receipts.get(this.lastReceipt.mutation) ?? this.lastReceipt);
+ if (rolledBack) {
+ for (const [key, value] of patch) {
+ if (matches(current, key, value)) patch.delete(key);
+ }
+ const differs = body !== current.body || patch.size > 0;
+ this.charge(body, patch, current, differs ? current : null, last, this.captured, remaining);
+ this.base = copy(current);
+ this.remote = differs ? copy(current) : null;
+ this.body = body;
+ this.patch = patch;
+ if (differs) {
+ this.state = "conflict";
+ this.why = refusal("conflict", "a device write was refused at head", "record_session_conflict").toProblem();
+ }
+ } else {
+ this.charge(this.body, this.patch, this.base, this.remote, last, this.captured, remaining);
+ }
+ this.pendingEdits = remaining;
+ this.lastReceipt = last;
+ }
+
/** Native change notifications are hints only; hydrate the same UUID. */
refresh = (): Promise => {
if (!this.active) return Promise.resolve();
@@ -286,8 +395,13 @@ export class RecordSessionImpl {
this.refreshRunning = (async () => {
do {
this.refreshAgain = false;
+ const generation = this.driveGeneration;
try {
- const current = await this.read(signal);
+ const { current, receipts } = await this.readWithReceipts(signal);
+ if (generation !== this.driveGeneration) {
+ this.refreshAgain = true;
+ continue;
+ }
if (this.captured || this.running) {
// A captured write settles from its receipt, never from
// this hint; re-settle it here so a write that confirms
@@ -296,6 +410,7 @@ export class RecordSessionImpl {
void this.start(false, {}).catch(() => {});
continue;
}
+ this.reconcilePending(current, receipts);
this.charge(this.body, this.patch, this.base, current);
if (!this.dirty) {
this.base = copy(current);
@@ -303,7 +418,7 @@ export class RecordSessionImpl {
this.remote = null;
this.state = isProtected(current)
? "conflict"
- : resting(current);
+ : this.restState;
this.why = null;
} else if (
current.revision !== this.base.revision ||
@@ -320,6 +435,10 @@ export class RecordSessionImpl {
this.publish();
} catch (error) {
if (signal.aborted) return;
+ if (generation !== this.driveGeneration || this.running) {
+ this.refreshAgain = !this.running;
+ continue;
+ }
this.why = problem(error);
this.state =
this.why.code === "not_found"
@@ -372,10 +491,14 @@ export class RecordSessionImpl {
until: Date.now() + duration,
margin: Math.min(2_000, Math.floor(duration / 4)),
};
- const drive = () => this.drive(signal, budget, write);
+ const drive = () => {
+ this.driveGeneration++;
+ return this.drive(signal, budget, write);
+ };
const run: Promise = (
prior ? prior.then(drive, drive) : drive()
).finally(() => {
+ this.driveGeneration++;
limit.clear();
if (this.running !== run) return;
this.running = null;
@@ -399,14 +522,15 @@ export class RecordSessionImpl {
continue;
}
if (!submit)
- return confirmed(this.base)
+ return this.restState === "saved"
? { ok: true, record: copy(this.base) }
: {
ok: true,
record: copy(this.base),
saved: "on_device",
};
- const current = await this.read(signal);
+ const { current, receipts } = await this.readWithReceipts(signal);
+ this.reconcilePending(current, receipts);
if (isProtected(current)) {
this.charge(this.body, this.patch, this.base, current);
this.remote = copy(current);
@@ -427,10 +551,10 @@ export class RecordSessionImpl {
this.base = copy(current);
this.body = current.body!;
this.remote = null;
- this.state = resting(current);
+ this.state = this.restState;
this.why = null;
this.publish();
- return confirmed(current)
+ return this.restState === "saved"
? { ok: true, record: copy(current) }
: { ok: true, record: copy(current), saved: "on_device" };
}
@@ -594,14 +718,26 @@ export class RecordSessionImpl {
// Still pending after the wait: the write is kept on this device and the
// ledger settles it. Not a failure, and nothing is resubmitted.
const kept = receipt.state === "pending";
- if (kept ? isProtected(current) : !confirmed(current))
+ const edits: PendingEdits = new Map(this.pendingEdits);
+ const submitted = new Map(captured.patch);
+ if (captured.body !== this.base.body) submitted.set(null, captured.body);
+ for (const [key, value] of submitted) {
+ if (kept) edits.set(key, { mutation: receipt.mutation, value });
+ else edits.delete(key);
+ }
+ if (kept ? isProtected(current) || [...submitted].some(([key, value]) => !matches(current, key, value))
+ : !confirmed(current))
throw refusal(
"outcome_unknown",
- "confirmed receipt has pending/protected current readback",
+ "record readback does not qualify the native receipt",
"unqualified_readback",
);
- this.charge(this.body, this.patch, current, null);
const sameBody = this.body === captured.body;
+ // More typing was based on the submitted text. If a peer changed it
+ // after confirmation, the next save needs an explicit choice of body.
+ const conflict = !kept && !sameBody && current.body !== captured.body && current.body !== this.body;
+ this.charge(this.body, this.patch, current, conflict ? current : null, receipt, null, edits);
+ this.pendingEdits = edits;
for (const [key, value] of captured.patch) {
const latest = this.patch.get(key);
if (
@@ -615,8 +751,10 @@ export class RecordSessionImpl {
this.base = copy(current);
if (sameBody) this.body = current.body!;
this.captured = null;
- this.remote = null;
- this.state = this.dirty ? "unsaved" : resting(current);
+ this.remote = conflict ? copy(current) : null;
+ if (conflict)
+ throw refusal("conflict", "record body changed while saving an earlier draft", "record_session_conflict");
+ this.state = this.dirty ? "unsaved" : this.restState;
this.why = null;
this.publish();
}
@@ -638,7 +776,7 @@ export class RecordSessionImpl {
const body =
"body" in choice
? choice.body
- : choice.keep === "theirs"
+ : choice.keep === "theirs" || this.body === this.base.body
? remote.body!
: this.body;
const patch =
@@ -656,10 +794,6 @@ export class RecordSessionImpl {
this.schedule();
};
}
-/** A clean record's state: confirmed is saved, pending is saved on this device. */
-function resting(record: RecordView): RecordSessionState {
- return confirmed(record) ? "saved" : "saved_on_device";
-}
function equal(a: CborValue, b: CborValue): boolean {
const x = encode(a),
y = encode(b);
diff --git a/runtime/packages/sdk/test/record-leases.test.ts b/runtime/packages/sdk/test/record-leases.test.ts
index d5860e80d..0a71b0bd2 100644
--- a/runtime/packages/sdk/test/record-leases.test.ts
+++ b/runtime/packages/sdk/test/record-leases.test.ts
@@ -134,6 +134,212 @@ describe("shared native record leases", () => {
expect(update).toHaveBeenCalledTimes(1);
lease.release();
});
+ it.each([false, true])("keeps both bodies after a late rejection (reopen %s)", async (reopen) => {
+ const f = await fixture(true);
+ let lease = await f.client.records.open(f.record.id);
+ vi.spyOn(f.client, "awaitReceipt").mockImplementation(async mutation => ({ mutation, state: "pending" }));
+ lease.session.setBody("Offline body");
+ expect(await lease.session.flush()).toMatchObject({ ok: true, saved: "on_device" });
+ const { receipt } = (await f.client.pendingWrites())[0]!;
+ if (reopen) {
+ lease.release();
+ const client = await f.replica.client();
+ clients.push(client);
+ lease = await client.records.open(f.record.id);
+ expect(lease.session.getSnapshot().body).toBe("Offline body");
+ }
+ f.replica.reject(receipt.mutation);
+ f.replica.editElsewhere(f.record.id, { body: "Other device" });
+ await vi.waitFor(() => expect(lease.session.getSnapshot()).toMatchObject({
+ state: "conflict", body: "Offline body", remote: { body: "Other device" },
+ }));
+ expect(await lease.session.flush()).toMatchObject({ ok: false });
+ expect(lease.session.getSnapshot().body).toBe("Offline body");
+ lease.session.resolve({ keep: "mine" });
+ expect(lease.session.getSnapshot()).toMatchObject({ state: "unsaved", body: "Offline body" });
+ lease.release();
+ });
+ it("keeps the original mutation while its pending receipt and body readback disagree", async () => {
+ const f = await fixture(true);
+ const lease = await f.client.records.open(f.record.id);
+ const update = vi.spyOn(f.client, "update");
+ const receipt = vi.spyOn(f.client, "awaitReceipt").mockImplementationOnce(async mutation => {
+ f.replica.reject(mutation);
+ f.replica.editElsewhere(f.record.id, { body: "Other device" });
+ return { mutation, state: "pending" };
+ });
+ lease.session.setBody("Offline body");
+ expect(await lease.session.flush()).toMatchObject({ ok: false, problem: { reason: "unqualified_readback" } });
+ expect(lease.session.getSnapshot()).toMatchObject({ body: "Offline body", recovery: { mutationId: expect.any(String) } });
+ receipt.mockRestore();
+ expect(await lease.session.flush()).toMatchObject({ ok: false });
+ expect(lease.session.getSnapshot()).toMatchObject({ body: "Offline body", recovery: null });
+ expect(update).toHaveBeenCalledTimes(1);
+ lease.release();
+ });
+ it.each([false, true])("restores refused fields and unsets without reverting peer edits (reopen %s)", async reopen => {
+ const f = await fixture(true);
+ let client = f.client;
+ let lease = await client.records.open(f.record.id);
+ vi.spyOn(f.client, "awaitReceipt").mockImplementation(async mutation => ({ mutation, state: "pending" }));
+ lease.session.patchFrontmatter({ category: "local", title: undefined });
+ expect(await lease.session.flush()).toMatchObject({ ok: true, saved: "on_device" });
+ const { mutationId } = f.client.ledger.getSnapshot().pending[0]!;
+ if (reopen) {
+ lease.release();
+ client = await f.replica.client();
+ clients.push(client);
+ lease = await client.records.open(f.record.id);
+ }
+ // An edit made after local acceptance must survive rejection too.
+ lease.session.patchFrontmatter({ category: "later typing" });
+ f.replica.reject(mutationId);
+ await vi.waitFor(() => expect(lease.session.getSnapshot().state).toBe("conflict"));
+ f.replica.editElsewhere(f.record.id, { body: "peer body", frontmatter: { extra: "peer field" } });
+ await vi.waitFor(() => expect(lease.session.getSnapshot()).toMatchObject({
+ state: "conflict", remote: { body: "peer body", frontmatter: { title: "Original", extra: "peer field" } },
+ }));
+ lease.session.resolve({ keep: "mine" });
+ expect(lease.session.getSnapshot().body).toBe("peer body");
+ expect(lease.session.getSnapshot().frontmatter).toEqual({ category: "later typing", extra: "peer field" });
+ vi.spyOn(client, "awaitReceipt").mockImplementationOnce(async mutation => {
+ f.replica.confirmAll();
+ return client.receipt(mutation);
+ });
+ expect(await lease.session.flush()).toMatchObject({ ok: true });
+ const saved = await client.get(f.record.id, { include: { body: true } });
+ expect(saved.body).toBe("peer body");
+ expect(saved.frontmatter).toEqual({ category: "later typing", extra: "peer field" });
+ lease.release();
+ });
+ it.each(["set", "unset"])("retains a divergent pending field %s and subsequent typing", async mode => {
+ const f = await fixture(true), lease = await f.client.records.open(f.record.id);
+ const update = vi.spyOn(f.client, "update");
+ vi.spyOn(f.client, "awaitReceipt").mockImplementationOnce(async mutation => {
+ lease.session.patchFrontmatter({ later: "typed during save" });
+ f.replica.reject(mutation);
+ return { mutation, state: "pending" };
+ });
+ lease.session.patchFrontmatter({ title: mode === "set" ? "local" : undefined });
+ const expected = mode === "set" ? { title: "local", later: "typed during save" } : { later: "typed during save" };
+ expect(await lease.session.flush()).toMatchObject({ ok: false, problem: { reason: "unqualified_readback" } });
+ expect(lease.session.getSnapshot().frontmatter).toEqual(expected);
+ const mutation = update.mock.calls[0]![2]!.mutationId;
+ expect(lease.session.getSnapshot().recovery?.mutationId).toBe(mutation);
+ expect(await lease.session.flush()).toMatchObject({ ok: false, problem: { code: "conflict" } });
+ expect(lease.session.getSnapshot().lastReceipt).toMatchObject({ mutation, state: "rejected" });
+ expect(lease.session.getSnapshot().frontmatter).toEqual(expected);
+ expect(update).toHaveBeenCalledTimes(1);
+ lease.release();
+ });
+ it("accepts another offline edit and adopts a peer edit following genuine confirmation", async () => {
+ const f = await fixture(true), lease = await f.client.records.open(f.record.id);
+ const update = vi.spyOn(f.client, "update");
+ vi.spyOn(f.client, "awaitReceipt").mockImplementation(async mutation => ({ mutation, state: "pending" }));
+ lease.session.patchFrontmatter({ title: "Offline title" });
+ expect(await lease.session.flush()).toMatchObject({ ok: true, saved: "on_device" });
+ lease.session.setBody("Offline body");
+ expect(await lease.session.flush()).toMatchObject({ ok: true, saved: "on_device" });
+ f.replica.confirmAll();
+ f.replica.editElsewhere(f.record.id, { body: "Later peer body", frontmatter: { title: "Later peer title" } });
+ await vi.waitFor(() => expect(lease.session.getSnapshot()).toMatchObject({
+ state: "saved", body: "Later peer body", frontmatter: { title: "Later peer title" }, remote: null,
+ }));
+ expect(update).toHaveBeenCalledTimes(2);
+ lease.release();
+ });
+ it("adopts a confirmed record that already contains the newer draft after rollback", async () => {
+ const f = await fixture(true), lease = await f.client.records.open(f.record.id);
+ const update = vi.spyOn(f.client, "update");
+ vi.spyOn(f.client, "awaitReceipt").mockImplementation(async mutation => ({ mutation, state: "pending" }));
+ lease.session.setBody("First");
+ lease.session.patchFrontmatter({ title: undefined });
+ expect(await lease.session.flush()).toMatchObject({ ok: true, saved: "on_device" });
+ const { mutationId } = f.client.ledger.getSnapshot().pending[0]!;
+ lease.session.setBody("Second");
+ lease.session.patchFrontmatter({ title: "Second" });
+ f.replica.reject(mutationId);
+ f.replica.editElsewhere(f.record.id, { body: "Second", frontmatter: { title: "Second" } });
+ await vi.waitFor(() => expect(lease.session.getSnapshot()).toMatchObject({
+ state: "saved", dirty: false, body: "Second", frontmatter: { title: "Second" }, remote: null,
+ lastReceipt: { mutation: mutationId, state: "rejected" },
+ }));
+ expect(update).toHaveBeenCalledTimes(1);
+ lease.release();
+ });
+ it("holds later typing for review when a peer edits the body between confirmation and readback", async () => {
+ const f = await fixture(true), lease = await f.client.records.open(f.record.id);
+ const update = vi.spyOn(f.client, "update");
+ vi.spyOn(f.client, "awaitReceipt").mockImplementationOnce(async mutation => {
+ lease.session.setBody("Later typing");
+ f.replica.confirmAll();
+ f.replica.editElsewhere(f.record.id, { body: "Peer after confirmation" });
+ return f.client.receipt(mutation);
+ });
+ lease.session.setBody("First draft");
+ expect(await lease.session.flush()).toMatchObject({ ok: false, problem: { code: "conflict" } });
+ expect(lease.session.getSnapshot()).toMatchObject({
+ state: "conflict", body: "Later typing", remote: { body: "Peer after confirmation" },
+ recovery: null, lastReceipt: { state: "confirmed" },
+ });
+ expect(await lease.session.flush()).toMatchObject({ ok: false });
+ expect(update).toHaveBeenCalledTimes(1);
+ expect((await f.client.get(f.record.id, { include: { body: true } })).body).toBe("Peer after confirmation");
+ lease.session.resolve({ keep: "mine" });
+ expect(lease.session.getSnapshot()).toMatchObject({ state: "unsaved", body: "Later typing" });
+ lease.release();
+ });
+ it("keeps matching readbacks editable on device until the exact receipt confirms", async () => {
+ const f = await fixture(true), lease = await f.client.records.open(f.record.id);
+ const get = f.client.get.bind(f.client);
+ vi.spyOn(f.client, "get").mockImplementation(async (...args) => {
+ const row = await get(...args);
+ return { ...row, state: { ...row.state, state: "confirmed" } };
+ });
+ vi.spyOn(f.client, "awaitReceipt").mockImplementation(async mutation => ({ mutation, state: "pending" }));
+ lease.session.setBody("Local");
+ expect(await lease.session.flush()).toMatchObject({ ok: true, saved: "on_device" });
+ lease.session.patchFrontmatter({ title: undefined });
+ expect(await lease.session.flush()).toMatchObject({ ok: true, saved: "on_device" });
+ expect(lease.session.getSnapshot().lastReceipt?.state).toBe("pending");
+ expect(lease.session.getSnapshot().frontmatter).toEqual({});
+ f.replica.confirmAll();
+ await vi.waitFor(() => expect(lease.session.getSnapshot()).toMatchObject({
+ state: "saved", lastReceipt: { state: "confirmed" },
+ }));
+ lease.release();
+ });
+ it.each([false, true])("discards a refresh spanning an offline write (stale failure %s)", async fail => {
+ const f = await fixture(true);
+ const original = f.client.get.bind(f.client);
+ let finish!: () => void;
+ const blocked = new Promise(resolve => { finish = resolve; });
+ let replayed!: () => void;
+ const replay = new Promise(resolve => { replayed = resolve; });
+ const get = vi.spyOn(f.client, "get").mockImplementationOnce(original)
+ .mockImplementationOnce(async (...args) => {
+ const earlier = await original(...args);
+ await blocked;
+ if (fail) throw mdbaseError("not_found", "stale refresh");
+ return earlier;
+ });
+ const lease = await f.client.records.open(f.record.id);
+ const states: string[] = [];
+ lease.session.subscribe(() => states.push(lease.session.getSnapshot().state));
+ vi.spyOn(f.client, "awaitReceipt").mockImplementation(async mutation => ({ mutation, state: "pending" }));
+ lease.session.setBody("Offline body");
+ expect(await lease.session.flush()).toMatchObject({ ok: true, saved: "on_device" });
+ get.mockImplementationOnce(async (...args) => {
+ replayed();
+ return original(...args);
+ });
+ finish();
+ await replay;
+ expect(states).not.toContain("conflict");
+ expect(states).not.toContain("deleted");
+ expect(lease.session.getSnapshot()).toMatchObject({ state: "saved_on_device", body: "Offline body" });
+ lease.release();
+ });
it("an offline autosave whose receipt wait runs out is saved on device, then saved once online", async () => {
const f = await fixture(false),
update = vi.spyOn(f.client, "update");