Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(sync): preserve dictionary entries during first sync and edits (#2879)

Joshua89a884fe3e7e
diff --git a/preload.js b/preload.js
index b1e87c587..2370ffa82 100644
--- a/preload.js
+++ b/preload.js
@@ -1280,8 +1280,23 @@ contextBridge.exposeInMainWorld("electronAPI", {
ipcRenderer.invoke("db-get-dictionary-by-client-id", clientDictId),
upsertDictionaryFromCloud: (cloudEntry) =>
ipcRenderer.invoke("db-upsert-dictionary-from-cloud", cloudEntry),
- markDictionarySynced: (id, cloudId) =>
- ipcRenderer.invoke("db-mark-dictionary-synced", id, cloudId),
+ markDictionarySynced: (
+ id,
+ cloudId,
+ serverUpdatedAt,
+ expectedWord,
+ expectedSource,
+ serverSource
+ ) =>
+ ipcRenderer.invoke(
+ "db-mark-dictionary-synced",
+ id,
+ cloudId,
+ serverUpdatedAt,
+ expectedWord,
+ expectedSource,
+ serverSource
+ ),
hardDeleteDictionary: (id) => ipcRenderer.invoke("db-hard-delete-dictionary", id),
clearDictionaryCloudId: (id) => ipcRenderer.invoke("db-clear-dictionary-cloud-id", id),
broadcastDictionaryUpdated: () => ipcRenderer.invoke("db-broadcast-dictionary-updated"),
diff --git a/src/helpers/database.js b/src/helpers/database.js
index ef4d6f147..1f15014ff 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -2789,6 +2789,16 @@ class DatabaseManager {
// Manual is sticky — a pull never demotes a local manual row to learned.
const mergedSource =
existing.source === "manual" || incomingSource === "manual" ? "manual" : "learned";
+ // A local edit can follow the push ACK within the same SQLite second.
+ // Its timestamp cannot safely order it against the server's echo.
+ if (existing.sync_status === "pending") {
+ this.db
+ .prepare(
+ "UPDATE custom_dictionary SET cloud_id = COALESCE(cloud_id, ?), source = ? WHERE id = ?"
+ )
+ .run(cloudEntry.id, mergedSource, existing.id);
+ return this.db.prepare("SELECT * FROM custom_dictionary WHERE id = ?").get(existing.id);
+ }
this.db
.prepare(
`UPDATE custom_dictionary
@@ -2820,18 +2830,41 @@ class DatabaseManager {
}
}
- markDictionaryEntrySynced(id, cloudId) {
+ markDictionaryEntrySynced(
+ id,
+ cloudId,
+ serverUpdatedAt = null,
+ expectedWord = null,
+ expectedSource = null,
+ serverSource = null
+ ) {
try {
if (!this.db) throw new Error("Database not initialized");
- // Guard on deleted_at so a delete or tombstone that raced the push isn't
- // flipped back to 'synced' (which would strand the deletion). changes=0
- // signals that race to SyncService, which reconciles the cloud row.
- const result = this.db
- .prepare(
- "UPDATE custom_dictionary SET sync_status = 'synced', cloud_id = ? WHERE id = ? AND deleted_at IS NULL"
- )
- .run(cloudId, id);
- return { success: result.changes > 0, changes: result.changes };
+ return this.db.transaction(() => {
+ const current = this.db.prepare("SELECT * FROM custom_dictionary WHERE id = ?").get(id);
+ if (!current || current.deleted_at) return { success: false, changes: 0 };
+
+ const unchanged =
+ (expectedWord === null || current.word === expectedWord) &&
+ (expectedSource === null || current.source === expectedSource);
+ // Edited rows still adopt the cloud identity, so they can PATCH next
+ // pass. Only missing/deleted rows authorize orphan cleanup (changes=0).
+ const result = this.db
+ .prepare(
+ `UPDATE custom_dictionary
+ SET cloud_id = ?, sync_status = ?, updated_at = COALESCE(?, updated_at),
+ source = CASE WHEN ? = 'manual' THEN 'manual' ELSE source END
+ WHERE id = ?`
+ )
+ .run(
+ cloudId,
+ unchanged ? "synced" : "pending",
+ unchanged ? serverUpdatedAt : null,
+ serverSource,
+ id
+ );
+ return { success: result.changes > 0, changes: result.changes };
+ })();
} catch (error) {
debugLogger.error(
"Error marking dictionary entry synced",
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 719fe8cce..7a2314760 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -2152,9 +2152,19 @@ class IPCHandlers {
return this.databaseManager.upsertDictionaryFromCloud(cloudEntry);
});
- ipcMain.handle("db-mark-dictionary-synced", async (_event, id, cloudId) => {
- return this.databaseManager.markDictionaryEntrySynced(id, cloudId);
- });
+ ipcMain.handle(
+ "db-mark-dictionary-synced",
+ async (_event, id, cloudId, serverUpdatedAt, expectedWord, expectedSource, serverSource) => {
+ return this.databaseManager.markDictionaryEntrySynced(
+ id,
+ cloudId,
+ serverUpdatedAt,
+ expectedWord,
+ expectedSource,
+ serverSource
+ );
+ }
+ );
ipcMain.handle("db-hard-delete-dictionary", async (_event, id) => {
return this.databaseManager.hardDeleteDictionaryEntry(id);
diff --git a/src/services/DictionaryService.ts b/src/services/DictionaryService.ts
index 9116756f3..aca01649b 100644
--- a/src/services/DictionaryService.ts
+++ b/src/services/DictionaryService.ts
@@ -39,7 +39,22 @@ async function deleteEntry(id: string): Promise<void> {
await cloudDelete("/api/dictionary/delete", { id });
}
-async function list(
+async function listSnapshot(
+ cursor?: string,
+ limit?: number,
+ cursorId?: string
+): Promise<{ entries: CloudDictionaryEntry[]; hasMore: boolean }> {
+ const params = new URLSearchParams();
+ if (cursor) params.set("cursor", cursor);
+ if (cursorId) params.set("cursor_id", cursorId);
+ if (limit) params.set("limit", String(limit));
+ const query = params.toString() ? `?${params}` : "";
+ return cloudGet<{ entries: CloudDictionaryEntry[]; hasMore: boolean }>(
+ `/api/dictionary/list${query}`
+ );
+}
+
+async function listDelta(
since?: string,
limit?: number,
sinceId?: string
@@ -58,5 +73,6 @@ export const DictionaryService = {
batchCreate,
update,
delete: deleteEntry,
- list,
+ listSnapshot,
+ listDelta,
};
diff --git a/src/services/SyncService.ts b/src/services/SyncService.ts
index c949bf85a..4544f522c 100644
--- a/src/services/SyncService.ts
+++ b/src/services/SyncService.ts
@@ -17,7 +17,7 @@ import { FoldersService } from "./FoldersService.js";
import { SpacesService, type MySpace } from "./SpacesService.js";
import { TranscriptionsService } from "./TranscriptionsService.js";
import { syncPendingAnalytics } from "./AnalyticsService.js";
-import { DictionaryService } from "./DictionaryService.js";
+import { DictionaryService, type CloudDictionaryEntry } from "./DictionaryService.js";
import { SnippetService, type CloudSnippetEntry } from "./SnippetService.js";
import { CloudApiError, isAuthContextError } from "./cloudApi.js";
import { LeaderboardService } from "./LeaderboardService";
@@ -2567,11 +2567,18 @@ export class SyncService {
for (const entry of updates) {
try {
- await DictionaryService.update(entry.cloud_id!, {
+ const server = await DictionaryService.update(entry.cloud_id!, {
word: entry.word,
source: entry.source,
});
- await window.electronAPI.markDictionarySynced?.(entry.id, entry.cloud_id!);
+ await window.electronAPI.markDictionarySynced?.(
+ entry.id,
+ server.id,
+ server.updated_at,
+ entry.word,
+ entry.source,
+ server.source
+ );
} catch (err) {
// 404: another device purged the cloud row. Clear the stale cloud_id so
// the next push re-creates it via batchCreate instead of retrying PATCH.
@@ -2605,7 +2612,14 @@ export class SyncService {
}
// 0 changes means the local row was deleted between snapshot and ack —
// delete the freshly-created server row so we don't orphan it.
- const result = await window.electronAPI.markDictionarySynced?.(local.id, server.id);
+ const result = await window.electronAPI.markDictionarySynced?.(
+ local.id,
+ server.id,
+ server.updated_at,
+ local.word,
+ local.source,
+ server.source
+ );
if (result && result.changes === 0) {
try {
await DictionaryService.delete(server.id);
@@ -2653,13 +2667,17 @@ export class SyncService {
let cursorId: string | undefined = sinceId;
let maxUpdatedAt = normalizeTimestamp(since);
let maxId = sinceId ?? "";
+ // With no saved cursor, walk the (created_at, id) snapshot to the end. The
+ // first page arrives in created_at order, so continuing it on the
+ // (updated_at, id) delta keyset skips later-created words edited earlier.
+ const cursorField: keyof Pick<CloudDictionaryEntry, "created_at" | "updated_at"> = since
+ ? "updated_at"
+ : "created_at";
while (true) {
- const { entries, hasMore } = await DictionaryService.list(
- cursor,
- DICTIONARY_BATCH_SIZE,
- cursorId
- );
+ const { entries, hasMore } = since
+ ? await DictionaryService.listDelta(cursor, DICTIONARY_BATCH_SIZE, cursorId)
+ : await DictionaryService.listSnapshot(cursor, DICTIONARY_BATCH_SIZE, cursorId);
if (entries.length === 0) break;
for (const cloudEntry of entries) {
@@ -2695,10 +2713,11 @@ export class SyncService {
if (!hasMore) break;
const last = entries[entries.length - 1];
- // Stall guard: if the (updated_at, id) cursor didn't advance after a
- // full page, bail rather than loop forever.
- if (last.updated_at === cursor && last.id === cursorId) break;
- cursor = last.updated_at;
+ const nextCursor = last[cursorField];
+ // Stall guard: if the (cursor, id) keyset didn't advance after a full
+ // page, bail rather than loop forever.
+ if (nextCursor === cursor && last.id === cursorId) break;
+ cursor = nextCursor;
cursorId = last.id;
}
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 20eb50657..ed84c5427 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -3734,7 +3734,11 @@ declare global {
) => Promise<DictionaryEntryItem | null>;
markDictionarySynced?: (
id: number,
- cloudId: string
+ cloudId: string,
+ serverUpdatedAt?: string,
+ expectedWord?: string,
+ expectedSource?: DictionaryEntryItem["source"],
+ serverSource?: DictionaryEntryItem["source"]
) => Promise<{ success: boolean; changes: number }>;
hardDeleteDictionary?: (id: number) => Promise<{ success: boolean; id: number }>;
clearDictionaryCloudId?: (id: number) => Promise<{ success: boolean }>;
diff --git a/test/helpers/harness/electronApiBridge.js b/test/helpers/harness/electronApiBridge.js
index 33319133b..017e8c586 100644
--- a/test/helpers/harness/electronApiBridge.js
+++ b/test/helpers/harness/electronApiBridge.js
@@ -7,22 +7,8 @@
const AUTH_TOKEN = "harness-token";
const AUTH_GENERATION = 0;
-// syncAll() asserts the whole dictionary and snippet surface exists before doing
-// any work and aborts the pass if a name is missing, so both are present but
-// inert — this harness covers notes and folders.
-function inertDictionaryApi() {
- return {
- getPendingDictionary: async () => [],
- getPendingDictionaryDeletes: async () => [],
- getDictionaryByClientId: async () => null,
- upsertDictionaryFromCloud: async () => undefined,
- markDictionarySynced: async () => ({ success: true, changes: 1 }),
- hardDeleteDictionary: async () => ({ success: true }),
- clearDictionaryCloudId: async () => ({ success: true }),
- broadcastDictionaryUpdated: async () => undefined,
- };
-}
-
+// syncAll() asserts the whole snippet surface exists before doing any work and
+// aborts the pass if a name is missing, so it is present but inert.
function inertSnippetApi() {
return {
getPendingSnippets: async () => [],
@@ -185,7 +171,17 @@ function createElectronApi(db, options = {}) {
markTranscriptionSynced: async (id, cloudId) => db.markTranscriptionSynced(id, cloudId),
hardDeleteTranscription: async (id) => db.hardDeleteTranscription(id),
- ...inertDictionaryApi(),
+ // Dictionary
+ getPendingDictionary: async () => db.getPendingDictionary(),
+ getPendingDictionaryDeletes: async () => db.getPendingDictionaryDeletes(),
+ getDictionaryByClientId: async (clientDictId) => db.getDictionaryEntryByClientId(clientDictId),
+ upsertDictionaryFromCloud: async (cloudEntry) => db.upsertDictionaryFromCloud(cloudEntry),
+ markDictionarySynced: async (...args) => db.markDictionaryEntrySynced(...args),
+ hardDeleteDictionary: async (id) => db.hardDeleteDictionaryEntry(id),
+ clearDictionaryCloudId: async (id) => db.clearDictionaryCloudId(id),
+ // The real handler re-reads the words to broadcast them; there are no windows here.
+ broadcastDictionaryUpdated: async () => ({ success: true }),
+
...inertSnippetApi(),
...inertAnalyticsApi(),
};
diff --git a/test/helpers/harness/fakeCloud.js b/test/helpers/harness/fakeCloud.js
index 5cd6fc3d6..d53130157 100644
--- a/test/helpers/harness/fakeCloud.js
+++ b/test/helpers/harness/fakeCloud.js
@@ -1,7 +1,8 @@
// In-memory stand-in for the cloud API behind window.electronAPI.cloudApiRequest.
// Notes and folders are modelled with the hardened server's real write rules,
-// conversations only on the read side; the other entity types exist only so a
-// full syncAll() pass can complete.
+// conversations only on the read side, dictionary words on the read side plus
+// delete; the other entity types exist only so a full syncAll() pass can
+// complete.
//
// Each hardening rule sits behind its own flag so a test can flip the server
// back to the legacy behaviour and prove the client still does not lose data:
@@ -58,6 +59,8 @@ const FOLDER_FIELDS = ["name", "is_default", "sort_order"];
// rides along as a plain stored field.
const CONVERSATION_FIELDS = ["title", "archived_at", "messages"];
+const DICTIONARY_FIELDS = ["word", "source"];
+
const NOTE_DEFAULTS = {
title: null,
content: "",
@@ -79,6 +82,8 @@ const FOLDER_DEFAULTS = { name: "", is_default: false, sort_order: 0 };
const CONVERSATION_DEFAULTS = { title: "Untitled", archived_at: null, messages: [] };
+const DICTIONARY_DEFAULTS = { word: "", source: "manual" };
+
function createFakeCloud(config = {}) {
const cfg = {
materialPatchGate: true,
@@ -91,6 +96,7 @@ function createFakeCloud(config = {}) {
const notes = new Map();
const folders = new Map();
const conversations = new Map();
+ const dictionary = new Map();
const log = [];
const failures = [];
let seq = 0;
@@ -219,6 +225,13 @@ function createFakeCloud(config = {}) {
clientKey: "client_conversation_id",
prefix: "conv",
};
+ const dictionaryCollection = {
+ store: dictionary,
+ fields: DICTIONARY_FIELDS,
+ defaults: DICTIONARY_DEFAULTS,
+ clientKey: "client_dict_id",
+ prefix: "dict",
+ };
// Snapshot paging walks created_at backwards from `before` and hides
// tombstones; delta paging walks updated_at forwards from `since` and must
@@ -262,6 +275,47 @@ function createFakeCloud(config = {}) {
return rows.slice(0, limit).map((row) => structuredClone(row));
}
+ // The dictionary list pages forwards, unlike notes: the default list and its
+ // `cursor` continuation walk live rows by (created_at, id); `since` streams
+ // every row, tombstones included, by (updated_at, id). Either timestamp
+ // without its id half is an inclusive bound, as on the server.
+ function dictionaryPage(query) {
+ const limitRaw = Number(query.get("limit"));
+ const limit = Number.isFinite(limitRaw) && limitRaw > 0 ? limitRaw : 200;
+ const since = query.get("since");
+ const cursor = query.get("cursor");
+ const sinceId = query.get("since_id");
+ const cursorId = query.get("cursor_id");
+ if ((sinceId && !since) || (cursorId && !cursor) || (since && cursor)) {
+ throw new HttpError(400, "malformed dictionary keyset", "bad_request");
+ }
+
+ const orderKey = since ? "updated_at" : "created_at";
+ const bound = since ?? cursor;
+ const boundId = since ? sinceId : cursorId;
+ let rows = [...dictionary.values()];
+ if (!since) rows = rows.filter((r) => !r.deleted_at);
+ if (bound) {
+ const at = normalizeTimestamp(bound);
+ rows = rows.filter((r) => {
+ const timestampOrder = compare(normalizeTimestamp(r[orderKey]), at);
+ return boundId
+ ? timestampOrder > 0 || (timestampOrder === 0 && r.id > boundId)
+ : timestampOrder >= 0;
+ });
+ }
+ rows.sort(
+ (a, b) =>
+ compare(normalizeTimestamp(a[orderKey]), normalizeTimestamp(b[orderKey])) ||
+ compare(a.id, b.id)
+ );
+
+ return {
+ entries: rows.slice(0, limit).map((row) => structuredClone(row)),
+ hasMore: rows.length > limit,
+ };
+ }
+
function handle(method, pathname, query, body) {
const route = `${method} ${pathname}`;
switch (route) {
@@ -368,7 +422,10 @@ function createFakeCloud(config = {}) {
case "GET /api/transcriptions/list":
return { transcriptions: [] };
case "GET /api/dictionary/list":
- return { entries: [], hasMore: false };
+ return dictionaryPage(query);
+ case "DELETE /api/dictionary/delete":
+ tombstone(dictionaryCollection, body?.id);
+ return {};
case "POST /api/dictionary/batch-create":
return { created: [] };
case "GET /api/snippets/list":
@@ -448,6 +505,7 @@ function createFakeCloud(config = {}) {
if (input.deleted_at) row.deleted_at = toIso(input.deleted_at);
return structuredClone(row);
},
+ seedDictionaryEntry: (input) => structuredClone(insertRow(dictionaryCollection, input)),
notes: () => [...notes.values()].map((row) => structuredClone(row)),
folders: () => [...folders.values()].map((row) => structuredClone(row)),
conversations: () => [...conversations.values()].map((row) => structuredClone(row)),
diff --git a/test/helpers/syncServiceDictionary.test.js b/test/helpers/syncServiceDictionary.test.js
new file mode 100644
index 000000000..4288d46bf
--- /dev/null
+++ b/test/helpers/syncServiceDictionary.test.js
@@ -0,0 +1,320 @@
+// Dictionary half of SyncService over a real DatabaseManager, with only the
+// HTTP boundary faked. With no saved cursor, the first pull used to read the
+// server's default list, ordered by (created_at, id), then continue it on the
+// (updated_at, id) delta keyset from that page's last row. Every word created
+// after the first page but last edited before that row was skipped, and the
+// cursor saved at the end kept it skipped on every later pass.
+
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const { createDb } = require("./harness/db.js");
+const {
+ installBrowserGlobals,
+ resetBrowserGlobals,
+ enableSync,
+ establishValidatedAuth,
+ stopSyncTimers,
+ localStorage: localStorageStub,
+ window: windowStub,
+} = require("./harness/browserGlobals.js");
+const { createElectronApi } = require("./harness/electronApiBridge.js");
+const { createFakeCloud } = require("./harness/fakeCloud.js");
+const { SyncService } = require("../../src/services/SyncService.ts");
+const { DictionaryService } = require("../../src/services/DictionaryService.ts");
+
+// One more page than the 200-word pull batch holds.
+const WORD_COUNT = 250;
+const EDITED_LAST = 199;
+const T0 = Date.parse("2026-10-18T09:00:00.000Z");
+const minute = (n) => new Date(T0 + n * 60_000).toISOString();
+
+async function setup(t) {
+ const db = createDb(t);
+ if (!db) return null;
+ resetBrowserGlobals();
+ installBrowserGlobals();
+ enableSync();
+ const cloud = createFakeCloud();
+ windowStub.electronAPI = createElectronApi(db, { cloud });
+ await establishValidatedAuth();
+ const service = new SyncService();
+ t.after(() => stopSyncTimers(service));
+ return { db, cloud, service };
+}
+
+function seedWords(cloud, stamp) {
+ return Array.from({ length: WORD_COUNT }, (_, i) =>
+ cloud.seedDictionaryEntry({ word: `word-${i}`, ...stamp(i) })
+ );
+}
+
+// Words created a minute apart, then the 200th-created, the last row of the
+// first page, edited after every create: it holds the newest updated_at.
+const editedAfterCreates = (i) => ({
+ created_at: minute(i),
+ updated_at: minute(i === EDITED_LAST ? WORD_COUNT : i),
+});
+
+const listQueries = (cloud) =>
+ cloud
+ .logFor("/api/dictionary/list")
+ .map((call) => new URLSearchParams(call.path.split("?")[1] ?? ""));
+
+test("a fresh device pulls every word when the newest edit ends the first page", async (t) => {
+ const ctx = await setup(t);
+ if (!ctx) return;
+ const { db, cloud, service } = ctx;
+ const words = seedWords(cloud, editedAfterCreates);
+
+ await service.syncAll(true);
+
+ assert.equal(db.getDictionary().length, WORD_COUNT, "every cloud word reaches the device");
+ assert.equal(localStorageStub.getItem("lastSyncedAt.dictionary"), words[EDITED_LAST].updated_at);
+ assert.equal(localStorageStub.getItem("lastSyncedAt.dictionary.id"), words[EDITED_LAST].id);
+});
+
+test("a fresh device pages a bulk import that shares one timestamp by id", async (t) => {
+ const ctx = await setup(t);
+ if (!ctx) return;
+ const { db, cloud, service } = ctx;
+ seedWords(cloud, () => ({ created_at: minute(0), updated_at: minute(0) }));
+
+ await service.syncAll(true);
+
+ assert.equal(db.getDictionary().length, WORD_COUNT, "every imported word reaches the device");
+});
+
+test("the pass after a first pull streams changes from its newest word", async (t) => {
+ const ctx = await setup(t);
+ if (!ctx) return;
+ const { db, cloud, service } = ctx;
+ const words = seedWords(cloud, editedAfterCreates);
+ await service.syncAll(true);
+ const firstPassCalls = listQueries(cloud).length;
+
+ // Another device adds one word and deletes another after that pull.
+ cloud.setClock(() => minute(WORD_COUNT + 10));
+ cloud.seedDictionaryEntry({ word: "added-later" });
+ await cloud.request({
+ method: "DELETE",
+ path: "/api/dictionary/delete",
+ body: { id: words[0].id },
+ });
+ await service.syncAll(true);
+
+ const [delta, ...rest] = listQueries(cloud).slice(firstPassCalls);
+ assert.equal(rest.length, 0, "both changes fit one delta page");
+ assert.equal(delta.get("since"), words[EDITED_LAST].updated_at);
+ assert.equal(delta.get("since_id"), words[EDITED_LAST].id);
+ const local = db.getDictionary();
+ assert.equal(local.length, WORD_COUNT);
+ assert.ok(local.includes("added-later"), "the new word arrives");
+ assert.ok(!local.includes(words[0].word), "the tombstone removes the deleted word");
+});
+
+const CREATED_AT = "2026-10-14 08:00:00";
+const LOCAL_SECOND = "2026-10-14 09:00:00";
+const SERVER_AT = "2026-10-14T09:00:00.105Z";
+const NEXT_SERVER_AT = "2026-10-14T09:00:01.205Z";
+
+function setupWrite(t, source = "manual") {
+ const db = createDb(t);
+ if (!db) return null;
+ resetBrowserGlobals();
+ installBrowserGlobals();
+ db.setDictionary(["alpha"], source);
+ db.db
+ .prepare("UPDATE custom_dictionary SET created_at = ?, updated_at = ?")
+ .run(CREATED_AT, CREATED_AT);
+ const [local] = db.getPendingDictionary();
+ const cloud = { entry: null, afterWrite: () => {} };
+ const api = createElectronApi(db);
+ windowStub.electronAPI = api;
+ t.mock.method(DictionaryService, "batchCreate", async ([entry]) => {
+ cloud.entry = { ...entry, id: "cloud-alpha", deleted_at: null, updated_at: SERVER_AT };
+ cloud.afterWrite();
+ return { created: [{ ...cloud.entry }] };
+ });
+ t.mock.method(DictionaryService, "update", async (id, fields) => {
+ assert.equal(id, cloud.entry.id);
+ cloud.entry = { ...cloud.entry, ...fields, updated_at: NEXT_SERVER_AT };
+ cloud.afterWrite();
+ return { ...cloud.entry };
+ });
+ for (const method of ["listSnapshot", "listDelta"]) {
+ t.mock.method(DictionaryService, method, async () => ({
+ entries: cloud.entry ? [{ ...cloud.entry }] : [],
+ hasMore: false,
+ }));
+ }
+ t.mock.method(DictionaryService, "delete", async (id) => {
+ assert.equal(id, cloud.entry.id);
+ cloud.entry.deleted_at = NEXT_SERVER_AT;
+ });
+ const service = new SyncService();
+ t.after(() => stopSyncTimers(service));
+ return { db, api, cloud, local, service };
+}
+
+function editInServerSecond(db, word = "ALPHA", source = "manual") {
+ db.applyDictionaryChanges({ add: [word] }, source);
+ // Pin SQLite's second precision below the fractional server echo without
+ // depending on wall-clock timing or waiting for a second boundary.
+ db.db.prepare("UPDATE custom_dictionary SET updated_at = ?").run(LOCAL_SECOND);
+}
+
+test("an unchanged dictionary create acknowledges the server revision and preserves creation time", async (t) => {
+ const ctx = setupWrite(t);
+ if (!ctx) return;
+ const { db, local, service } = ctx;
+ await service.pushPendingDictionary();
+
+ const row = db.getDictionaryEntryByClientId(local.client_dict_id);
+ assert.equal(row.word, "alpha");
+ assert.equal(row.source, "manual");
+ assert.equal(row.created_at, CREATED_AT);
+ assert.equal(row.updated_at, SERVER_AT);
+ assert.equal(row.sync_status, "synced");
+ assert.equal(row.cloud_id, "cloud-alpha");
+ await service.pullDictionary();
+ assert.deepEqual(db.getDictionaryEntryByClientId(local.client_dict_id), row);
+});
+
+for (const kind of ["create ACK", "in-flight create edit", "cloud merge"]) {
+ test(`manual dictionary provenance survives ${kind} and a subsequent learned casing edit`, async (t) => {
+ const ctx = setupWrite(t, "learned");
+ if (!ctx) return;
+ const { db, api, cloud, local, service } = ctx;
+ if (kind === "cloud merge") {
+ await service.syncDictionary();
+ cloud.entry.source = "manual";
+ cloud.entry.updated_at = NEXT_SERVER_AT;
+ api.upsertDictionaryFromCloud = async (entry) => {
+ editInServerSecond(db, "ALPHA", "learned");
+ return db.upsertDictionaryFromCloud(entry);
+ };
+ await service.pullDictionary();
+ } else {
+ cloud.afterWrite = () => {
+ // A batch-create deduplicated against a manual word keeps its source.
+ cloud.entry.source = "manual";
+ if (kind === "in-flight create edit") editInServerSecond(db, "ALPHA", "learned");
+ cloud.afterWrite = () => {};
+ };
+ await service.syncDictionary();
+ }
+
+ const row = db.getDictionaryEntryByClientId(local.client_dict_id);
+ assert.equal(row.source, "manual");
+ assert.equal(row.word, kind === "create ACK" ? "alpha" : "ALPHA");
+ assert.equal(row.created_at, CREATED_AT);
+ assert.equal(row.updated_at, kind === "create ACK" ? SERVER_AT : LOCAL_SECOND);
+ assert.equal(row.sync_status, kind === "create ACK" ? "synced" : "pending");
+ assert.equal(row.cloud_id, cloud.entry.id);
+
+ if (kind === "create ACK") editInServerSecond(db, "ALPHA", "learned");
+ await service.syncDictionary();
+ assert.equal(cloud.entry.word, "ALPHA");
+ assert.equal(cloud.entry.source, "manual");
+ assert.equal(db.getDictionaryEntryByClientId(local.client_dict_id).sync_status, "synced");
+ assert.equal(DictionaryService.delete.mock.callCount(), 0);
+ assert.equal(DictionaryService.batchCreate.mock.callCount(), 1);
+ assert.equal(DictionaryService.update.mock.callCount(), 1);
+ });
+}
+
+test("a same-second casing edit after create ACK survives the echo and reaches the next PATCH", async (t) => {
+ const ctx = setupWrite(t);
+ if (!ctx) return;
+ const { db, api, cloud, local, service } = ctx;
+ const acknowledge = api.markDictionarySynced;
+ api.markDictionarySynced = async (...args) => {
+ const result = await acknowledge(...args);
+ editInServerSecond(db);
+ api.markDictionarySynced = acknowledge;
+ return result;
+ };
+
+ await service.syncDictionary();
+ const row = db.getDictionaryEntryByClientId(local.client_dict_id);
+ assert.equal(row.word, "ALPHA");
+ assert.equal(row.sync_status, "pending");
+ assert.equal(row.updated_at, LOCAL_SECOND);
+ assert.equal(row.cloud_id, cloud.entry.id);
+ assert.equal(DictionaryService.delete.mock.callCount(), 0);
+
+ await service.syncDictionary();
+ assert.equal(cloud.entry.word, "ALPHA");
+ assert.equal(db.getDictionaryEntryByClientId(local.client_dict_id).sync_status, "synced");
+ assert.equal(DictionaryService.batchCreate.mock.callCount(), 1);
+ assert.equal(DictionaryService.update.mock.callCount(), 1);
+});
+
+for (const kind of ["create", "PATCH", "source promotion"]) {
+ test(`a dictionary edit during ${kind} stays pending without deleting its cloud row`, async (t) => {
+ const ctx = setupWrite(t, kind === "source promotion" ? "learned" : "manual");
+ if (!ctx) return;
+ const { db, cloud, local, service } = ctx;
+ if (kind === "PATCH") {
+ await service.syncDictionary();
+ db.applyDictionaryChanges({ add: ["Alpha"] });
+ }
+ cloud.afterWrite = () => {
+ editInServerSecond(db, kind === "source promotion" ? "alpha" : "ALPHA");
+ cloud.afterWrite = () => {};
+ };
+
+ await service.syncDictionary();
+ const row = db.getDictionaryEntryByClientId(local.client_dict_id);
+ assert.equal(row.word, kind === "source promotion" ? "alpha" : "ALPHA");
+ assert.equal(row.source, "manual");
+ assert.equal(row.sync_status, "pending");
+ assert.equal(row.updated_at, LOCAL_SECOND);
+ assert.equal(row.cloud_id, cloud.entry.id);
+ assert.equal(DictionaryService.delete.mock.callCount(), 0);
+
+ await service.syncDictionary();
+ assert.equal(cloud.entry.word, row.word);
+ assert.equal(cloud.entry.source, "manual");
+ assert.equal(db.getDictionaryEntryByClientId(local.client_dict_id).sync_status, "synced");
+ assert.equal(DictionaryService.batchCreate.mock.callCount(), 1);
+ });
+}
+
+test("an edit between dictionary pull lookup and SQLite merge survives a newer cloud copy", async (t) => {
+ const ctx = setupWrite(t);
+ if (!ctx) return;
+ const { db, api, cloud, local, service } = ctx;
+ await service.syncDictionary();
+ cloud.entry.updated_at = NEXT_SERVER_AT;
+ api.upsertDictionaryFromCloud = async (entry) => {
+ editInServerSecond(db);
+ return db.upsertDictionaryFromCloud(entry);
+ };
+
+ await service.pullDictionary();
+ const row = db.getDictionaryEntryByClientId(local.client_dict_id);
+ assert.equal(row.word, "ALPHA");
+ assert.equal(row.sync_status, "pending");
+ assert.equal(row.updated_at, LOCAL_SECOND);
+});
+
+for (const kind of ["create", "PATCH"]) {
+ test(`a dictionary deletion during ${kind} still cleans up the cloud row`, async (t) => {
+ const ctx = setupWrite(t);
+ if (!ctx) return;
+ const { db, cloud, local, service } = ctx;
+ if (kind === "PATCH") {
+ await service.syncDictionary();
+ db.applyDictionaryChanges({ add: ["ALPHA"] });
+ }
+ cloud.afterWrite = () => db.applyDictionaryChanges({ remove: ["alpha"] });
+
+ await service.syncDictionary();
+ assert.equal(db.getDictionaryEntryByClientId(local.client_dict_id), null);
+ assert.ok(cloud.entry.deleted_at);
+ assert.equal(DictionaryService.delete.mock.callCount(), 1);
+ assert.deepEqual(db.getDictionary(), []);
+ });
+}