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): add shared test harness and tsx loader

Alcahestfa194d8d3c77
diff --git a/package-lock.json b/package-lock.json
index 1f6b85b72..23157c1fe 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -91,6 +91,7 @@
"postcss": "^8.5.10",
"prettier": "^3.8.3",
"tailwindcss": "^4.1.10",
+ "tsx": "^4.23.1",
"typescript": "^6.0.2",
"typescript-eslint": "^8.58.1",
"vite": "^8.1.4"
@@ -1631,6 +1632,448 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
+ "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",
+ "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",
+ "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",
+ "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",
+ "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",
+ "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",
+ "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",
+ "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",
+ "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",
+ "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",
+ "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",
+ "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",
+ "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",
+ "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",
+ "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",
+ "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",
+ "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",
+ "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",
+ "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",
+ "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",
+ "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",
+ "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",
+ "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",
+ "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",
+ "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",
+ "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/@eslint-community/eslint-utils": {
"version": "4.9.1",
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz",
@@ -7343,6 +7786,48 @@
"license": "MIT",
"optional": true
},
+ "node_modules/esbuild": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
+ "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.28.1",
+ "@esbuild/android-arm": "0.28.1",
+ "@esbuild/android-arm64": "0.28.1",
+ "@esbuild/android-x64": "0.28.1",
+ "@esbuild/darwin-arm64": "0.28.1",
+ "@esbuild/darwin-x64": "0.28.1",
+ "@esbuild/freebsd-arm64": "0.28.1",
+ "@esbuild/freebsd-x64": "0.28.1",
+ "@esbuild/linux-arm": "0.28.1",
+ "@esbuild/linux-arm64": "0.28.1",
+ "@esbuild/linux-ia32": "0.28.1",
+ "@esbuild/linux-loong64": "0.28.1",
+ "@esbuild/linux-mips64el": "0.28.1",
+ "@esbuild/linux-ppc64": "0.28.1",
+ "@esbuild/linux-riscv64": "0.28.1",
+ "@esbuild/linux-s390x": "0.28.1",
+ "@esbuild/linux-x64": "0.28.1",
+ "@esbuild/netbsd-arm64": "0.28.1",
+ "@esbuild/netbsd-x64": "0.28.1",
+ "@esbuild/openbsd-arm64": "0.28.1",
+ "@esbuild/openbsd-x64": "0.28.1",
+ "@esbuild/openharmony-arm64": "0.28.1",
+ "@esbuild/sunos-x64": "0.28.1",
+ "@esbuild/win32-arm64": "0.28.1",
+ "@esbuild/win32-ia32": "0.28.1",
+ "@esbuild/win32-x64": "0.28.1"
+ }
+ },
"node_modules/escalade": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
@@ -12190,6 +12675,25 @@
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
+ "node_modules/tsx": {
+ "version": "4.23.1",
+ "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.1.tgz",
+ "integrity": "sha512-GQHnkIfxyx1wYCOS/wonik5MVRZU9hi1TEZmzGZSCJB1y9YgoZ8H6itNE/u4suE+yLmOzuE4E5S4TZ/ZX2wcWQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "~0.28.0"
+ },
+ "bin": {
+ "tsx": "dist/cli.mjs"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ }
+ },
"node_modules/tunnel-agent": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
diff --git a/package.json b/package.json
index 7e9b44b01..84b2a32a4 100644
--- a/package.json
+++ b/package.json
@@ -73,7 +73,7 @@
"format": "npm run format:js",
"format:check": "eslint . && cd src && eslint . && prettier --check \"**/*.{js,jsx,ts,tsx,json,css,md}\"",
"lint": "eslint . && cd src && eslint .",
- "test": "node --test \"test/**/*.test.js\"",
+ "test": "node --import tsx --test \"test/**/*.test.js\"",
"typecheck": "cd src && tsc --noEmit",
"quality-check": "npm run format:check && npm run typecheck",
"i18n:check": "node scripts/check-i18n.js",
@@ -112,6 +112,7 @@
"postcss": "^8.5.10",
"prettier": "^3.8.3",
"tailwindcss": "^4.1.10",
+ "tsx": "^4.23.1",
"typescript": "^6.0.2",
"typescript-eslint": "^8.58.1",
"vite": "^8.1.4"
diff --git a/src/services/SyncService.ts b/src/services/SyncService.ts
index a11eac606..990866249 100644
--- a/src/services/SyncService.ts
+++ b/src/services/SyncService.ts
@@ -204,7 +204,7 @@ export async function upsertCloudSpaces(cloudSpaces: MySpace[]): Promise<number[
return backfillIds;
}
-class SyncService {
+export class SyncService {
private syncing = false;
private syncAllPending = false;
private autoSyncStarted = false;
diff --git a/test/helpers/harness/browserGlobals.js b/test/helpers/harness/browserGlobals.js
new file mode 100644
index 000000000..db1ca4b80
--- /dev/null
+++ b/test/helpers/harness/browserGlobals.js
@@ -0,0 +1,189 @@
+// The renderer globals syncAll() actually reads: localStorage for the canSync
+// gate and the sync cursors, navigator.locks for the cross-window lock.
+
+const store = new Map();
+
+const localStorageStub = {
+ getItem(key) {
+ const value = store.get(String(key));
+ return value === undefined ? null : value;
+ },
+ setItem(key, value) {
+ store.set(String(key), String(value));
+ },
+ removeItem(key) {
+ store.delete(String(key));
+ },
+ clear() {
+ store.clear();
+ },
+ key(index) {
+ return [...store.keys()][index] ?? null;
+ },
+ get length() {
+ return store.size;
+ },
+};
+
+const held = new Set();
+const waiters = new Map();
+
+function queueFor(name) {
+ let queue = waiters.get(name);
+ if (!queue) {
+ queue = [];
+ waiters.set(name, queue);
+ }
+ return queue;
+}
+
+async function holdAndRun(name, callback) {
+ held.add(name);
+ try {
+ return await callback({ name, mode: "exclusive" });
+ } finally {
+ held.delete(name);
+ const next = waiters.get(name)?.shift();
+ if (next) next();
+ }
+}
+
+async function requestLock(name, optionsOrCallback, maybeCallback) {
+ const options = typeof optionsOrCallback === "function" ? {} : (optionsOrCallback ?? {});
+ const callback = typeof optionsOrCallback === "function" ? optionsOrCallback : maybeCallback;
+ if (typeof callback !== "function") {
+ throw new TypeError("navigator.locks.request requires a callback");
+ }
+
+ if (held.has(String(name))) {
+ // ifAvailable hands the caller a null lock instead of queueing, which is how
+ // an ambient sync pass bows out while another window holds the lock.
+ if (options.ifAvailable) return callback(null);
+ return new Promise((resolve, reject) => {
+ queueFor(String(name)).push(() => holdAndRun(String(name), callback).then(resolve, reject));
+ });
+ }
+ return holdAndRun(String(name), callback);
+}
+
+const navigatorStub = { locks: { request: requestLock } };
+
+const documentStub = {
+ visibilityState: "visible",
+ addEventListener() {},
+ removeEventListener() {},
+};
+
+const windowStub = {
+ addEventListener() {},
+ removeEventListener() {},
+ localStorage: localStorageStub,
+ navigator: navigatorStub,
+ document: documentStub,
+ // authRequestContext resolves get-session URLs against the window origin.
+ location: { origin: "https://harness.openwhispr.test" },
+};
+
+function define(name, value) {
+ Object.defineProperty(globalThis, name, {
+ value,
+ configurable: true,
+ writable: true,
+ });
+}
+
+function installBrowserGlobals() {
+ define("localStorage", localStorageStub);
+ define("navigator", navigatorStub);
+ define("document", documentStub);
+ define("window", windowStub);
+ return windowStub;
+}
+
+// Marks the three keys canSync() requires; without all three every sync path
+// returns before doing any work.
+function enableSync() {
+ localStorageStub.setItem("isSignedIn", "true");
+ localStorageStub.setItem("cloudBackupEnabled", "true");
+ localStorageStub.setItem("isSubscribed", "true");
+}
+
+function resetBrowserGlobals() {
+ store.clear();
+ held.clear();
+ waiters.clear();
+ documentStub.visibilityState = "visible";
+ delete windowStub.electronAPI;
+ delete globalThis.electronAPI;
+}
+
+// Takes the lock out of band so a test can drive the "another window is
+// syncing" path. Returns the release function.
+async function acquireLock(name) {
+ let release;
+ const acquired = new Promise((resolve) => {
+ void requestLock(
+ name,
+ () =>
+ new Promise((done) => {
+ release = done;
+ resolve();
+ })
+ );
+ });
+ await acquired;
+ return () => release();
+}
+
+// syncAll() refuses to run without a validated auth context: a token
+// generation bound to a resolved get-session user. Drive the real
+// authRequestContext module through its exported surface so the harness holds
+// the same lease the renderer would after sign-in. Requires
+// window.electronAPI.authGetTokenState (the bridge provides it).
+async function establishValidatedAuth(userId = "user-harness") {
+ const auth = require("../../../src/lib/authRequestContext.ts");
+ auth.resetAuthRequestContextForTests();
+ const request = await auth.prepareAuthRequest({
+ url: `${windowStub.location.origin}/api/auth/get-session`,
+ headers: {},
+ });
+ await auth.handleAuthRequestSuccess({
+ data: { user: { id: userId } },
+ response: new Response(null),
+ request,
+ });
+ const { generation } = await auth.readAuthTokenState();
+ if (!auth.commitValidatedAuthContext(generation, userId)) {
+ throw new Error("harness auth bootstrap failed to validate the session");
+ }
+}
+
+// A failed team-spaces probe schedules a real-timer retry that would fire long
+// after the test closed its database; every SyncService a test creates must be
+// swept before the test ends.
+function stopSyncTimers(service) {
+ if (!service) return;
+ if (service.teamSpacesRetryTimer) {
+ clearTimeout(service.teamSpacesRetryTimer);
+ service.teamSpacesRetryTimer = null;
+ }
+ if (service.openNoteSyncTimer) {
+ clearInterval(service.openNoteSyncTimer);
+ service.openNoteSyncTimer = null;
+ }
+ for (const timer of service.pushTimers?.values?.() ?? []) clearTimeout(timer);
+ service.pushTimers?.clear?.();
+}
+
+module.exports = {
+ installBrowserGlobals,
+ resetBrowserGlobals,
+ enableSync,
+ establishValidatedAuth,
+ stopSyncTimers,
+ acquireLock,
+ localStorage: localStorageStub,
+ navigator: navigatorStub,
+ document: documentStub,
+ window: windowStub,
+};
diff --git a/test/helpers/harness/db.js b/test/helpers/harness/db.js
index 25a5e33ed..5f3271acb 100644
--- a/test/helpers/harness/db.js
+++ b/test/helpers/harness/db.js
@@ -28,4 +28,51 @@ function skipOrFail(t, error) {
t.skip("better-sqlite3 native binding is not available for this Node runtime");
}
-module.exports = { isNativeBindingUnavailable, skipOrFail };
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const { installElectronStub, setUserDataDir } = require("./electronStub.js");
+
+installElectronStub();
+const DatabaseManager = require("../../../src/helpers/database.js");
+
+// A real DatabaseManager over a private tmpdir. Returns null when the caller
+// must bail because skipOrFail marked the test skipped.
+function createDb(t) {
+ const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-sync-harness-"));
+ setUserDataDir(userDataDir);
+
+ // Probe first: a binding failure here is the loader's, not schema setup's.
+ try {
+ const BetterSqlite = require("better-sqlite3");
+ const probe = new BetterSqlite(path.join(userDataDir, "probe.db"));
+ probe.close();
+ fs.rmSync(path.join(userDataDir, "probe.db"), { force: true });
+ } catch (error) {
+ fs.rmSync(userDataDir, { recursive: true, force: true });
+ skipOrFail(t, error);
+ return null;
+ }
+
+ let db;
+ try {
+ db = new DatabaseManager();
+ } catch (error) {
+ fs.rmSync(userDataDir, { recursive: true, force: true });
+ skipOrFail(t, error);
+ return null;
+ }
+
+ t.after(() => {
+ try {
+ db.db?.close();
+ } catch {
+ // an already-closed handle must not mask the test's own failure
+ }
+ fs.rmSync(userDataDir, { recursive: true, force: true });
+ });
+
+ return db;
+}
+
+module.exports = { isNativeBindingUnavailable, skipOrFail, createDb };
diff --git a/test/helpers/harness/electronApiBridge.js b/test/helpers/harness/electronApiBridge.js
new file mode 100644
index 000000000..415fe84ab
--- /dev/null
+++ b/test/helpers/harness/electronApiBridge.js
@@ -0,0 +1,155 @@
+// window.electronAPI as the renderer sees it: every method here mirrors the
+// name, argument order and return value of its ipcHandlers.js passthrough, so a
+// drift between SyncService and the real IPC surface shows up as a test failure.
+
+// Fixed credential state for the whole test process; establishValidatedAuth()
+// in browserGlobals.js turns it into a validated renderer auth context.
+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,
+ };
+}
+
+function inertSnippetApi() {
+ return {
+ getPendingSnippets: async () => [],
+ getPendingSnippetDeletes: async () => [],
+ getSnippetForCloudMerge: async () => null,
+ upsertSnippetFromCloud: async () => undefined,
+ markSnippetSynced: async () => ({ success: true, changes: 1 }),
+ hardDeleteSnippet: async () => ({ success: true }),
+ clearSnippetCloudId: async () => ({ success: true }),
+ broadcastSnippetsUpdated: async () => undefined,
+ };
+}
+
+function createElectronApi(db, options = {}) {
+ if (!db) throw new TypeError("createElectronApi requires a DatabaseManager");
+ const cloud = options.cloud;
+ // UI signals SyncService rebroadcasts through the main process
+ // (space-revoked, note-relocated, …), recorded for assertions.
+ const syncEvents = [];
+
+ return {
+ syncEvents,
+
+ cloudApiRequest: async (opts) => {
+ if (!cloud) throw new Error("no fake cloud wired into this electronAPI");
+ return cloud.request(opts);
+ },
+
+ // Auth
+ authGetTokenState: async () => ({ token: AUTH_TOKEN, generation: AUTH_GENERATION }),
+
+ emitSyncEvent: async (name, payload) => {
+ syncEvents.push({ name, payload });
+ return { success: true };
+ },
+
+ // Notes
+ getNote: async (id) => db.getNote(id),
+ updateNote: async (id, updates) => db.updateNote(id, updates),
+ getPendingNotes: async (spaceKind) => db.getPendingNotes(spaceKind),
+ getPendingNoteDeletes: async () => db.getPendingNoteDeletes(),
+ getNoteByClientId: async (clientNoteId) => db.getNoteByClientId(clientNoteId),
+ upsertNoteFromCloud: async (cloudNote, localFolderId, localSpaceId) =>
+ db.upsertNoteFromCloud(cloudNote, localFolderId, localSpaceId),
+ acknowledgeNoteCreate: async (id, snapshot, cloudId, cloudUpdatedAt, ownerUserId, settleIfUnchanged) =>
+ db.acknowledgeNoteCreate(id, snapshot, cloudId, cloudUpdatedAt, ownerUserId, settleIfUnchanged),
+ markNoteSyncedIfUnchanged: async (id, snapshot, expectedCloudId, cloudUpdatedAt, ownerUserId) =>
+ db.markNoteSyncedIfUnchanged(id, snapshot, expectedCloudId, cloudUpdatedAt, ownerUserId),
+ markNoteSyncError: async (id) => db.markNoteSyncError(id),
+ setNoteOwnerFromCloud: async (id, ownerUserId) => db.setNoteOwnerFromCloud(id, ownerUserId),
+ countTeamNotesMissingOwner: async () => db.countTeamNotesMissingOwner(),
+ restoreNoteAfterDeniedDelete: async (id) => db.restoreNoteAfterDeniedDelete(id),
+ hardDeleteNote: async (id) => db.hardDeleteNote(id),
+
+ // Folders
+ getFolders: async (spaceId) => db.getFolders(spaceId),
+ getPendingFolders: async (spaceKind) => db.getPendingFolders(spaceKind),
+ getPendingFolderDeletes: async () => db.getPendingFolderDeletes(),
+ getFolderByClientId: async (clientFolderId) => db.getFolderByClientId(clientFolderId),
+ upsertFolderFromCloud: async (cloudFolder, localSpaceId) =>
+ db.upsertFolderFromCloud(cloudFolder, localSpaceId),
+ acknowledgeFolderCreate: async (
+ id,
+ snapshot,
+ expectedCloudId,
+ responseClientFolderId,
+ cloudId,
+ cloudUpdatedAt
+ ) =>
+ db.acknowledgeFolderCreate(
+ id,
+ snapshot,
+ expectedCloudId,
+ responseClientFolderId,
+ cloudId,
+ cloudUpdatedAt
+ ),
+ markFolderSyncedIfUnchanged: async (id, snapshot, expectedCloudId) =>
+ db.markFolderSyncedIfUnchanged(id, snapshot, expectedCloudId),
+ restoreFolderAfterDeniedDelete: async (id) => db.restoreFolderAfterDeniedDelete(id),
+ relocateRevokedFolder: async (id, privateSpaceId, preserveFolder) =>
+ db.relocateRevokedFolder(id, privateSpaceId, preserveFolder),
+ getFolderIdMap: async () => db.getFolderIdMap(),
+ hardDeleteFolder: async (id) => db.hardDeleteFolder(id),
+
+ // Spaces
+ getSpaces: async () => db.getSpaces(),
+ upsertSpaceFromCloud: async (cloudSpace) => db.upsertSpaceFromCloud(cloudSpace),
+ setSpaceSyncStatus: async (id, status) => db.setSpaceSyncStatus(id, status),
+ purgeSpace: async (id, purgeOptions) => {
+ // Mirrors the db-purge-space handler's stale-generation refusal.
+ if (
+ purgeOptions?.expectedAuthGeneration !== undefined &&
+ purgeOptions.expectedAuthGeneration !== AUTH_GENERATION
+ ) {
+ return {
+ success: false,
+ error: "Authentication context changed before account cleanup",
+ code: "AUTH_CONTEXT_CHANGED",
+ };
+ }
+ return db.purgeSpace(id, purgeOptions);
+ },
+
+ // Conversations
+ getAgentConversation: async (id) => db.getAgentConversation(id),
+ getPendingConversations: async () => db.getPendingConversations(),
+ getPendingConversationDeletes: async () => db.getPendingConversationDeletes(),
+ getConversationByClientId: async (clientId) => db.getConversationByClientId(clientId),
+ upsertConversationFromCloud: async (cloudConv, messages) =>
+ db.upsertConversationFromCloud(cloudConv, messages),
+ markConversationSynced: async (id, cloudId) => db.markConversationSynced(id, cloudId),
+ hardDeleteConversation: async (id) => db.hardDeleteConversation(id),
+
+ // Transcriptions
+ getTranscriptionById: async (id) => db.getTranscriptionById(id),
+ getPendingTranscriptions: async () => db.getPendingTranscriptions(),
+ getPendingTranscriptionDeletes: async () => db.getPendingTranscriptionDeletes(),
+ getTranscriptionByClientId: async (clientId) => db.getTranscriptionByClientId(clientId),
+ upsertTranscriptionFromCloud: async (cloudTranscription) =>
+ db.upsertTranscriptionFromCloud(cloudTranscription),
+ markTranscriptionSynced: async (id, cloudId) => db.markTranscriptionSynced(id, cloudId),
+ hardDeleteTranscription: async (id) => db.hardDeleteTranscription(id),
+
+ ...inertDictionaryApi(),
+ ...inertSnippetApi(),
+ };
+}
+
+module.exports = { createElectronApi, AUTH_TOKEN, AUTH_GENERATION };
diff --git a/test/helpers/harness/electronStub.js b/test/helpers/harness/electronStub.js
new file mode 100644
index 000000000..2e2cae697
--- /dev/null
+++ b/test/helpers/harness/electronStub.js
@@ -0,0 +1,41 @@
+const Module = require("node:module");
+
+// DatabaseManager requires electron at load time, which is unloadable under plain
+// node, so the module loader hands it a stub whose userData path tests repoint.
+let userDataDir = process.cwd();
+let patched = false;
+
+function installElectronStub() {
+ if (patched) return;
+ patched = true;
+ const originalLoad = Module._load;
+ Module._load = function patchedLoad(request, parent, isMain) {
+ if (request === "electron") {
+ return {
+ app: {
+ getPath: () => userDataDir,
+ getAppPath: () => process.cwd(),
+ isReady: () => false,
+ },
+ };
+ }
+ return originalLoad.call(this, request, parent, isMain);
+ };
+}
+
+// Must be set before DatabaseManager loads: it picks the dev database filename
+// from NODE_ENV.
+process.env.NODE_ENV = "test";
+
+function setUserDataDir(dir) {
+ if (typeof dir !== "string" || dir.length === 0) {
+ throw new TypeError("setUserDataDir requires a non-empty path");
+ }
+ userDataDir = dir;
+}
+
+function getUserDataDir() {
+ return userDataDir;
+}
+
+module.exports = { installElectronStub, setUserDataDir, getUserDataDir };
diff --git a/test/helpers/harness/fakeCloud.js b/test/helpers/harness/fakeCloud.js
new file mode 100644
index 000000000..afa971772
--- /dev/null
+++ b/test/helpers/harness/fakeCloud.js
@@ -0,0 +1,410 @@
+// 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.
+//
+// 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:
+// materialPatchGate a PATCH that changes nothing does not bump updated_at
+// coalesceOnConflict an absent/null incoming field keeps the stored value
+// staleWriteGuard a write whose basis predates the stored row is rejected
+// updatedAtClamp a stored updated_at never moves backwards
+
+// The server compares timestamps itself; it must not borrow the client's guard,
+// or a client-side regression would be invisible here.
+function normalizeTimestamp(value) {
+ if (!value) return "";
+ const iso = String(value).replace(" ", "T").replace(/Z$/, "");
+ return (/\.\d+$/.test(iso) ? iso : `${iso}.000`) + "Z";
+}
+
+function sameValue(a, b) {
+ return (a ?? null) === (b ?? null);
+}
+
+function compare(a, b) {
+ if (a === b) return 0;
+ return a < b ? -1 : 1;
+}
+
+class HttpError extends Error {
+ constructor(status, message, code) {
+ super(message);
+ this.status = status;
+ this.code = code;
+ }
+}
+
+const NOTE_FIELDS = [
+ "title",
+ "content",
+ "enhanced_content",
+ "note_type",
+ "enhancement_prompt",
+ "source_file",
+ "audio_duration_seconds",
+ "folder_id",
+ "transcript",
+ "enhanced_at_content_hash",
+ "participants",
+ "calendar_event_id",
+ "diarization_enabled",
+ "expected_speaker_count",
+];
+
+const FOLDER_FIELDS = ["name", "is_default", "sort_order"];
+
+const NOTE_DEFAULTS = {
+ title: null,
+ content: "",
+ enhanced_content: null,
+ note_type: "personal",
+ enhancement_prompt: null,
+ source_file: null,
+ audio_duration_seconds: null,
+ folder_id: null,
+ transcript: null,
+ enhanced_at_content_hash: null,
+ participants: null,
+ calendar_event_id: null,
+ diarization_enabled: null,
+ expected_speaker_count: null,
+};
+
+const FOLDER_DEFAULTS = { name: "", is_default: false, sort_order: 0 };
+
+function createFakeCloud(config = {}) {
+ const cfg = {
+ materialPatchGate: true,
+ coalesceOnConflict: true,
+ staleWriteGuard: true,
+ updatedAtClamp: true,
+ ...config,
+ };
+
+ const notes = new Map();
+ const folders = new Map();
+ const log = [];
+ const failures = [];
+ let seq = 0;
+ let clock = () => new Date().toISOString();
+
+ const nextId = (prefix) => `${prefix}-${String(++seq).padStart(4, "0")}`;
+
+ // The server stores timestamps and serves them back as ISO, whatever format
+ // the client sent. Local rows carry SQLite's "YYYY-MM-DD HH:MM:SS", so echoing
+ // the input back would hide the format skew every pull comparison has to
+ // survive.
+ const toIso = (value) => normalizeTimestamp(value);
+
+ // A stored updated_at only ever moves forward under the clamp.
+ function bump(row, proposed) {
+ const candidate = toIso(proposed ?? clock());
+ if (cfg.updatedAtClamp && candidate < toIso(row.updated_at)) {
+ return row.updated_at;
+ }
+ return candidate;
+ }
+
+ function applyWrite(collection, row, incoming) {
+ if (
+ cfg.staleWriteGuard &&
+ incoming.updated_at &&
+ normalizeTimestamp(incoming.updated_at) < normalizeTimestamp(row.updated_at)
+ ) {
+ throw new HttpError(409, "stale write rejected: basis is older than the stored row", "stale");
+ }
+
+ const next = {};
+ let material = false;
+ for (const key of collection.fields) {
+ if (!(key in incoming)) {
+ next[key] = row[key];
+ continue;
+ }
+ const value = incoming[key];
+ if (cfg.coalesceOnConflict && (value === null || value === undefined) && row[key] != null) {
+ next[key] = row[key];
+ continue;
+ }
+ next[key] = value ?? null;
+ if (!sameValue(next[key], row[key])) material = true;
+ }
+
+ // Without the gate a no-op PATCH still bumps updated_at, which is what hands
+ // the next pull a cloud copy that never received the local edit.
+ if (cfg.materialPatchGate && !material) return row;
+
+ Object.assign(row, next);
+ row.updated_at = bump(row, incoming.updated_at);
+ return row;
+ }
+
+ function insertRow(collection, input) {
+ const clientId = input[collection.clientKey] ?? nextId(`${collection.prefix}-client`);
+ const createdAt = toIso(input.created_at ?? clock());
+ const row = {
+ id: nextId(collection.prefix),
+ [collection.clientKey]: clientId,
+ ...collection.defaults,
+ deleted_at: null,
+ created_at: createdAt,
+ updated_at: toIso(input.updated_at ?? createdAt),
+ };
+ for (const key of collection.fields) {
+ if (input[key] !== undefined && input[key] !== null) row[key] = input[key];
+ }
+ collection.store.set(row.id, row);
+ return row;
+ }
+
+ function findByClientId(collection, clientId) {
+ if (!clientId) return null;
+ for (const row of collection.store.values()) {
+ if (row[collection.clientKey] === clientId) return row;
+ }
+ return null;
+ }
+
+ // batch-create is idempotent by client id: a retried batch must return the
+ // existing row instead of forking a duplicate.
+ function upsertRow(collection, input) {
+ const existing = findByClientId(collection, input[collection.clientKey]);
+ if (!existing) return insertRow(collection, input);
+ if (existing.deleted_at) return existing;
+ return applyWrite(collection, existing, input);
+ }
+
+ function requireLive(collection, id) {
+ const row = collection.store.get(id);
+ if (!row || row.deleted_at)
+ throw new HttpError(404, `${collection.prefix} not found`, "not_found");
+ return row;
+ }
+
+ function tombstone(collection, id) {
+ const row = collection.store.get(id);
+ if (!row) throw new HttpError(404, `${collection.prefix} not found`, "not_found");
+ const at = bump(row, clock());
+ row.deleted_at = at;
+ row.updated_at = at;
+ return row;
+ }
+
+ const noteCollection = {
+ store: notes,
+ fields: NOTE_FIELDS,
+ defaults: NOTE_DEFAULTS,
+ clientKey: "client_note_id",
+ prefix: "note",
+ };
+ const folderCollection = {
+ store: folders,
+ fields: FOLDER_FIELDS,
+ defaults: FOLDER_DEFAULTS,
+ clientKey: "client_folder_id",
+ prefix: "folder",
+ };
+
+ // Snapshot paging walks created_at backwards from `before` and hides
+ // tombstones; delta paging walks updated_at forwards from `since` and must
+ // carry tombstones, since that is how a delete reaches the other device.
+ function page(collection, query, orderKey) {
+ const limitRaw = Number(query.get("limit"));
+ const limit = Number.isFinite(limitRaw) && limitRaw > 0 ? limitRaw : 50;
+ const since = query.get("since");
+ const before = query.get("before");
+ let rows = [...collection.store.values()];
+
+ if (since) {
+ const bound = normalizeTimestamp(since);
+ rows = rows.filter((r) => normalizeTimestamp(r.updated_at) > bound);
+ rows.sort(
+ (a, b) =>
+ compare(normalizeTimestamp(a.updated_at), normalizeTimestamp(b.updated_at)) ||
+ compare(a.id, b.id)
+ );
+ } else {
+ rows = rows.filter((r) => !r.deleted_at);
+ if (before) {
+ const bound = normalizeTimestamp(before);
+ rows = rows.filter((r) => normalizeTimestamp(r[orderKey]) < bound);
+ }
+ rows.sort(
+ (a, b) =>
+ compare(normalizeTimestamp(b[orderKey]), normalizeTimestamp(a[orderKey])) ||
+ compare(b.id, a.id)
+ );
+ }
+
+ return rows.slice(0, limit).map((row) => structuredClone(row));
+ }
+
+ function handle(method, pathname, query, body) {
+ const route = `${method} ${pathname}`;
+ switch (route) {
+ case "POST /api/notes/create":
+ return upsertRow(noteCollection, body ?? {});
+ case "POST /api/notes/batch-create": {
+ const inputs = Array.isArray(body?.notes) ? body.notes : [];
+ return {
+ created: inputs.map((input) => {
+ const row = upsertRow(noteCollection, input);
+ return { client_note_id: row.client_note_id, id: row.id };
+ }),
+ };
+ }
+ case "PATCH /api/notes/update": {
+ const { id, ...updates } = body ?? {};
+ return applyWrite(noteCollection, requireLive(noteCollection, id), updates);
+ }
+ case "DELETE /api/notes/delete":
+ tombstone(noteCollection, body?.id);
+ return {};
+ case "DELETE /api/notes/delete-all": {
+ let deleted = 0;
+ for (const row of notes.values()) {
+ if (row.deleted_at) continue;
+ tombstone(noteCollection, row.id);
+ deleted += 1;
+ }
+ return { deleted };
+ }
+ case "GET /api/notes/list":
+ return { notes: page(noteCollection, query, "created_at") };
+ case "POST /api/notes/search":
+ return { notes: [] };
+
+ case "POST /api/folders/create":
+ return upsertRow(folderCollection, body ?? {});
+ case "POST /api/folders/batch-create": {
+ const inputs = Array.isArray(body?.folders) ? body.folders : [];
+ return { created: inputs.map((input) => upsertRow(folderCollection, input)) };
+ }
+ case "PATCH /api/folders/update": {
+ const { id, ...updates } = body ?? {};
+ return applyWrite(folderCollection, requireLive(folderCollection, id), updates);
+ }
+ case "DELETE /api/folders/delete":
+ tombstone(folderCollection, body?.id);
+ return {};
+ case "GET /api/folders/list": {
+ const since = query.get("since");
+ let rows = [...folders.values()];
+ if (since) {
+ const bound = normalizeTimestamp(since);
+ rows = rows.filter((r) => normalizeTimestamp(r.updated_at) > bound);
+ } else {
+ rows = rows.filter((r) => !r.deleted_at);
+ }
+ rows.sort((a, b) => a.sort_order - b.sort_order || compare(a.id, b.id));
+ return { folders: rows.map((row) => structuredClone(row)) };
+ }
+
+ // Not modelled: enough shape for a full pass, nothing more.
+ 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 "POST /api/transcriptions/batch-create":
+ return {
+ created: (body?.transcriptions ?? []).map((t) => ({ ...t, id: nextId("trans") })),
+ };
+ case "POST /api/transcriptions/create":
+ return { ...body, id: nextId("trans") };
+ case "POST /api/transcriptions/batch-delete":
+ return { deleted: body?.ids ?? [] };
+ case "DELETE /api/transcriptions/delete":
+ return {};
+ case "GET /api/transcriptions/list":
+ return { transcriptions: [] };
+ case "GET /api/dictionary/list":
+ return { entries: [], hasMore: false };
+ case "POST /api/dictionary/batch-create":
+ return { created: [] };
+ case "GET /api/snippets/list":
+ return { entries: [], hasMore: false };
+ case "POST /api/snippets/batch-create":
+ return { created: [] };
+ default:
+ throw new HttpError(404, `fake cloud has no route for ${route}`, "no_route");
+ }
+ }
+
+ function toMatcher(matcher) {
+ if (typeof matcher === "function") return matcher;
+ const wanted = String(matcher);
+ return (call) =>
+ call.path.split("?")[0] === wanted || `${call.method} ${call.path.split("?")[0]}` === wanted;
+ }
+
+ function takeFailure(call) {
+ const index = failures.findIndex((entry) => entry.matcher(call));
+ if (index === -1) return null;
+ const entry = failures[index];
+ if (entry.once) failures.splice(index, 1);
+ return entry.failure;
+ }
+
+ async function request(opts) {
+ const method = String(opts?.method ?? "GET").toUpperCase();
+ const path = String(opts?.path ?? "");
+ const body = structuredClone(opts?.body ?? null);
+ const call = { method, path, body };
+ // The log keeps its own copy so a handler can never rewrite history.
+ log.push({ method, path, body: structuredClone(body) });
+
+ const failure = takeFailure(call);
+ if (failure) {
+ return {
+ success: false,
+ error: failure.error ?? "fake cloud failure",
+ status: failure.status ?? 500,
+ code: failure.code,
+ };
+ }
+
+ const [pathname, rawQuery] = path.split("?");
+ try {
+ const data = handle(method, pathname, new URLSearchParams(rawQuery ?? ""), body);
+ return { success: true, data: structuredClone(data) };
+ } catch (err) {
+ if (err instanceof HttpError) {
+ return { success: false, error: err.message, status: err.status, code: err.code };
+ }
+ throw err;
+ }
+ }
+
+ return {
+ request,
+ log,
+ logFor: (pathname) => log.filter((c) => c.path.split("?")[0] === pathname),
+ failNext: (matcher, failure = {}) =>
+ failures.push({ matcher: toMatcher(matcher), failure, once: true }),
+ failWith: (matcher, failure = {}) =>
+ failures.push({ matcher: toMatcher(matcher), failure, once: false }),
+ clearFailures: () => failures.splice(0, failures.length),
+ setClock: (fn) => {
+ clock = fn;
+ },
+ seedNote: (input) => structuredClone(insertRow(noteCollection, input)),
+ seedFolder: (input) => structuredClone(insertRow(folderCollection, input)),
+ notes: () => [...notes.values()].map((row) => structuredClone(row)),
+ folders: () => [...folders.values()].map((row) => structuredClone(row)),
+ note: (id) => {
+ const row = notes.get(id) ?? findByClientId(noteCollection, id);
+ return row ? structuredClone(row) : null;
+ },
+ folder: (id) => {
+ const row = folders.get(id) ?? findByClientId(folderCollection, id);
+ return row ? structuredClone(row) : null;
+ },
+ config: cfg,
+ };
+}
+
+module.exports = { createFakeCloud, normalizeTimestamp };
diff --git a/test/helpers/harness/invariants.js b/test/helpers/harness/invariants.js
new file mode 100644
index 000000000..317d6803a
--- /dev/null
+++ b/test/helpers/harness/invariants.js
@@ -0,0 +1,64 @@
+const assert = require("node:assert/strict");
+
+// The single user-visible harm this suite exists to catch: a sync pass replacing
+// text the user actually has with nothing.
+const CONTENT_FIELDS = ["content", "transcript", "enhanced_content"];
+
+function normalizeTimestamp(value) {
+ if (!value) return "";
+ const iso = String(value).replace(" ", "T").replace(/Z$/, "");
+ return (/\.\d+$/.test(iso) ? iso : `${iso}.000`) + "Z";
+}
+
+function isEmpty(value) {
+ return value === null || value === undefined || value === "";
+}
+
+// Every note row, soft-deleted ones included: a delete that empties the row is
+// still a regression.
+function snapshotNotes(db) {
+ if (!db?.db) throw new TypeError("snapshotNotes requires a DatabaseManager");
+ return db.db.prepare("SELECT * FROM notes").all();
+}
+
+function indexByClientId(rows) {
+ const map = new Map();
+ for (const row of rows ?? []) {
+ if (row?.client_note_id) map.set(row.client_note_id, row);
+ }
+ return map;
+}
+
+// An erasure is excused only when the cloud legitimately won: its copy is
+// strictly newer than the local row we started from, it is not an empty shell,
+// and the value we ended up with is exactly what the cloud holds.
+function erasureExcused(cloudRow, before, after, field) {
+ if (!cloudRow) return false;
+ if (normalizeTimestamp(cloudRow.updated_at) <= normalizeTimestamp(before.updated_at))
+ return false;
+ if (!CONTENT_FIELDS.some((f) => !isEmpty(cloudRow[f]))) return false;
+ return (cloudRow[field] ?? null) === (after[field] ?? null);
+}
+
+function assertNoContentRegression(dbBefore, dbAfter, cloudTruth) {
+ const before = indexByClientId(dbBefore);
+ const cloud = indexByClientId(
+ cloudTruth instanceof Map ? [...cloudTruth.values()] : (cloudTruth ?? [])
+ );
+
+ for (const after of dbAfter ?? []) {
+ const prior = before.get(after.client_note_id);
+ if (!prior) continue;
+ for (const field of CONTENT_FIELDS) {
+ if (isEmpty(prior[field]) || !isEmpty(after[field])) continue;
+ if (erasureExcused(cloud.get(after.client_note_id), prior, after, field)) continue;
+ assert.fail(
+ `sync erased ${field} on note ${after.id} (client_note_id ${after.client_note_id}): ` +
+ `had ${JSON.stringify(String(prior[field]).slice(0, 60))}, now ${JSON.stringify(after[field])}` +
+ " — and no strictly-newer non-empty cloud copy explains it"
+ );
+ }
+ }
+}
+
+module.exports = { assertNoContentRegression, snapshotNotes, CONTENT_FIELDS };