Skip to content

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

test(sync): cover the conversations pull gate

Alcahest8fc14fc815ef
diff --git a/test/helpers/harness/fakeCloud.js b/test/helpers/harness/fakeCloud.js
index afa971772..f779edeac 100644
--- a/test/helpers/harness/fakeCloud.js
+++ b/test/helpers/harness/fakeCloud.js
@@ -1,6 +1,7 @@
// 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;
-// the other entity types exist only so a full syncAll() pass can complete.
+// 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.
//
// 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:
@@ -53,6 +54,10 @@ const NOTE_FIELDS = [
const FOLDER_FIELDS = ["name", "is_default", "sort_order"];
+// Conversations are read-only here: only the pull is modelled, so `messages`
+// rides along as a plain stored field.
+const CONVERSATION_FIELDS = ["title", "archived_at", "messages"];
+
const NOTE_DEFAULTS = {
title: null,
content: "",
@@ -72,6 +77,8 @@ const NOTE_DEFAULTS = {
const FOLDER_DEFAULTS = { name: "", is_default: false, sort_order: 0 };
+const CONVERSATION_DEFAULTS = { title: "Untitled", archived_at: null, messages: [] };
+
function createFakeCloud(config = {}) {
const cfg = {
materialPatchGate: true,
@@ -83,6 +90,7 @@ function createFakeCloud(config = {}) {
const notes = new Map();
const folders = new Map();
+ const conversations = new Map();
const log = [];
const failures = [];
let seq = 0;
@@ -204,6 +212,13 @@ function createFakeCloud(config = {}) {
clientKey: "client_folder_id",
prefix: "folder",
};
+ const conversationCollection = {
+ store: conversations,
+ fields: CONVERSATION_FIELDS,
+ defaults: CONVERSATION_DEFAULTS,
+ clientKey: "client_conversation_id",
+ prefix: "conv",
+ };
// Snapshot paging walks created_at backwards from `before` and hides
// tombstones; delta paging walks updated_at forwards from `since` and must
@@ -300,15 +315,27 @@ function createFakeCloud(config = {}) {
return { folders: rows.map((row) => structuredClone(row)) };
}
- // Not modelled: enough shape for a full pass, nothing more.
+ // Conversation writes stay echo-stubs; only the read side is modelled,
+ // because the pull is what has to survive the ISO/SQLite format skew.
case "POST /api/conversations/create":
return { ...body, id: nextId("conv") };
case "PATCH /api/conversations/update":
return { ...body };
case "DELETE /api/conversations/delete":
return {};
- case "GET /api/conversations/list":
- return { conversations: [] };
+ case "GET /api/conversations/list": {
+ const rows = page(conversationCollection, query, "created_at");
+ // The client asks for include=messages; a page that stopped asking must
+ // not silently keep receiving them.
+ if (
+ !String(query.get("include") ?? "")
+ .split(",")
+ .includes("messages")
+ ) {
+ for (const row of rows) delete row.messages;
+ }
+ return { conversations: rows };
+ }
case "POST /api/transcriptions/batch-create":
return {
created: (body?.transcriptions ?? []).map((t) => ({ ...t, id: nextId("trans") })),
@@ -393,8 +420,18 @@ function createFakeCloud(config = {}) {
},
seedNote: (input) => structuredClone(insertRow(noteCollection, input)),
seedFolder: (input) => structuredClone(insertRow(folderCollection, input)),
+ // Conversation deletes are echo-stubs, so a tombstone has to be seeded here
+ // rather than produced by the DELETE route.
+ seedConversation: (input = {}) => {
+ const row = insertRow(conversationCollection, input);
+ // The defaults object is spread, not cloned, so every row needs its own array.
+ row.messages = structuredClone(input.messages ?? []);
+ if (input.deleted_at) row.deleted_at = toIso(input.deleted_at);
+ return structuredClone(row);
+ },
notes: () => [...notes.values()].map((row) => structuredClone(row)),
folders: () => [...folders.values()].map((row) => structuredClone(row)),
+ conversations: () => [...conversations.values()].map((row) => structuredClone(row)),
note: (id) => {
const row = notes.get(id) ?? findByClientId(noteCollection, id);
return row ? structuredClone(row) : null;
@@ -403,6 +440,10 @@ function createFakeCloud(config = {}) {
const row = folders.get(id) ?? findByClientId(folderCollection, id);
return row ? structuredClone(row) : null;
},
+ conversation: (id) => {
+ const row = conversations.get(id) ?? findByClientId(conversationCollection, id);
+ return row ? structuredClone(row) : null;
+ },
config: cfg,
};
}
diff --git a/test/helpers/syncServiceConversations.test.js b/test/helpers/syncServiceConversations.test.js
new file mode 100644
index 000000000..7bbeb70e1
--- /dev/null
+++ b/test/helpers/syncServiceConversations.test.js
@@ -0,0 +1,171 @@
+// Conversation half of SyncService: the real service drives the real
+// ConversationsService/cloudApi stack over a real DatabaseManager, with only the
+// HTTP boundary faked. The pull gate is the target — local rows carry SQLite's
+// "YYYY-MM-DD HH:MM:SS" while the cloud answers in ISO, and on the same UTC day
+// a raw string compare hands every cloud copy the win.
+
+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");
+
+// SQLite's datetime() format, the one local rows actually carry.
+const LOCAL_EARLY = "2026-07-20 10:00:00";
+
+async function setup(t) {
+ const db = createDb(t);
+ if (!db) return null;
+ resetBrowserGlobals();
+ installBrowserGlobals();
+ enableSync();
+ const cloud = createFakeCloud();
+ const api = createElectronApi(db, { cloud });
+ windowStub.electronAPI = api;
+ await establishValidatedAuth();
+ const service = new SyncService();
+ t.after(() => stopSyncTimers(service));
+ return { db, cloud, api, service };
+}
+
+// Deterministic timestamps come from SQL, never from a fake clock.
+function updateConversation(db, id, fields) {
+ const keys = Object.keys(fields);
+ db.db
+ .prepare(
+ `UPDATE agent_conversations SET ${keys.map((k) => `${k} = ?`).join(", ")} WHERE id = ?`
+ )
+ .run(...keys.map((k) => fields[k]), id);
+ return db.getAgentConversation(id);
+}
+
+function messageCount(db) {
+ return db.db.prepare("SELECT COUNT(*) AS c FROM agent_messages").get().c;
+}
+
+function queryParam(path, name) {
+ const [, query] = path.split("?");
+ return new URLSearchParams(query ?? "").get(name);
+}
+
+test("pullConversations applies a strictly newer cloud copy and rejects older and tied ones", async (t) => {
+ const ctx = await setup(t);
+ if (!ctx) return;
+ const { db, cloud, service } = ctx;
+
+ // All three cloud copies sit on the same UTC day as the local rows, where a
+ // raw string compare wrongly elects the cloud value ('T' > ' ' at index 10).
+ const cases = [
+ { key: "older", cloudUpdatedAt: "2026-07-20T09:00:00.000Z", applied: false },
+ { key: "newer", cloudUpdatedAt: "2026-07-20T11:00:00.000Z", applied: true },
+ { key: "tied", cloudUpdatedAt: "2026-07-20T10:00:00.000Z", applied: false },
+ ];
+
+ for (const c of cases) {
+ const cloudRow = cloud.seedConversation({
+ client_conversation_id: `client-${c.key}`,
+ title: `Cloud ${c.key}`,
+ created_at: "2026-07-20T08:00:00.000Z",
+ updated_at: c.cloudUpdatedAt,
+ messages: [
+ { role: "user", content: `cloud message ${c.key}`, created_at: "2026-07-20T08:30:00.000Z" },
+ ],
+ });
+ const local = db.createAgentConversation(`Local ${c.key}`);
+ db.addAgentMessage(local.id, "user", `local message ${c.key}`);
+ // Set updated_at last: addAgentMessage bumps it to CURRENT_TIMESTAMP.
+ updateConversation(db, local.id, {
+ client_conversation_id: cloudRow.client_conversation_id,
+ cloud_id: cloudRow.id,
+ sync_status: "synced",
+ created_at: LOCAL_EARLY,
+ updated_at: LOCAL_EARLY,
+ });
+ c.localId = local.id;
+ }
+
+ await service.syncAll(true);
+
+ const listCalls = cloud.logFor("/api/conversations/list");
+ assert.equal(listCalls.length, 1, "three cloud rows must take exactly one page");
+ assert.equal(queryParam(listCalls[0].path, "include"), "messages");
+ assert.equal(queryParam(listCalls[0].path, "since"), null, "a fresh pull carries no cursor");
+ assert.equal(
+ cloud.logFor("/api/conversations/create").length,
+ 0,
+ "the local rows are already synced, so nothing may be pushed ahead of the pull"
+ );
+
+ for (const c of cases) {
+ const row = db.getAgentConversation(c.localId);
+ const contents = row.messages.map((m) => m.content);
+ if (c.applied) {
+ assert.equal(row.title, `Cloud ${c.key}`, "a strictly newer cloud copy must win");
+ assert.deepEqual(contents, [`cloud message ${c.key}`]);
+ assert.equal(row.sync_status, "synced");
+ } else {
+ assert.equal(
+ row.title,
+ `Local ${c.key}`,
+ `the ${c.key} cloud copy must not overwrite the local row`
+ );
+ assert.equal(row.updated_at, LOCAL_EARLY, "a rejected pull must not move updated_at");
+ assert.deepEqual(
+ contents,
+ [`local message ${c.key}`],
+ `the ${c.key} cloud copy must not replace the local messages`
+ );
+ }
+ }
+});
+
+test("a cloud conversation tombstone hard-deletes the local row and its messages", async (t) => {
+ const ctx = await setup(t);
+ if (!ctx) return;
+ const { db, cloud, service } = ctx;
+
+ const cloudRow = cloud.seedConversation({
+ client_conversation_id: "client-tombstoned",
+ title: "Deleted elsewhere",
+ created_at: "2026-07-20T08:00:00.000Z",
+ updated_at: "2026-07-20T12:00:00.000Z",
+ deleted_at: "2026-07-20T12:00:00.000Z",
+ });
+ const local = db.createAgentConversation("Deleted elsewhere");
+ db.addAgentMessage(local.id, "user", "gone");
+ updateConversation(db, local.id, {
+ client_conversation_id: cloudRow.client_conversation_id,
+ cloud_id: cloudRow.id,
+ sync_status: "synced",
+ created_at: LOCAL_EARLY,
+ updated_at: LOCAL_EARLY,
+ });
+
+ // Tombstones only travel on the delta page, so the cursor must already exist.
+ localStorageStub.setItem("lastSyncedAt.conversations", "2026-07-01T00:00:00.000Z");
+ await service.syncAll(true);
+
+ const listCalls = cloud.logFor("/api/conversations/list");
+ assert.equal(
+ queryParam(listCalls[0].path, "since"),
+ "2026-07-01T00:00:00.000Z",
+ "the delta page must be requested with the stored cursor"
+ );
+ assert.equal(
+ db.getConversationByClientId("client-tombstoned"),
+ null,
+ "the local row must be removed"
+ );
+ assert.equal(messageCount(db), 0, "the messages go with the conversation");
+});