Skip to content

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

refactor(sync): move ambient sync scheduling into SyncService (#1072)

Gabriel Stein659b690e1f7f
diff --git a/src/AppRouter.jsx b/src/AppRouter.jsx
index 4939ad224..ccb35dc5f 100644
--- a/src/AppRouter.jsx
+++ b/src/AppRouter.jsx
@@ -57,6 +57,14 @@ function MainApp() {
import("./components/OnboardingFlow.tsx").catch(() => {});
}
}
+
+ // Sync runs in every non-agent window, so tray-only sessions where the
+ // control panel is never opened still stay fresh.
+ if (!isAgentPanel) {
+ import("./services/SyncService.js")
+ .then(({ syncService }) => syncService.startAutoSync())
+ .catch(() => {});
+ }
}, [isAgentPanel, isControlPanel]);
useEffect(() => {
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsx
index 301f8de56..7d671303b 100644
--- a/src/components/ControlPanel.tsx
+++ b/src/components/ControlPanel.tsx
@@ -374,31 +374,6 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
return () => cleanup?.();
}, [toast, t]);
- useEffect(() => {
- // Keep syncing during a long session, not just once at launch.
- syncService.requestSyncAll("mount");
-
- const onFocus = () => syncService.requestSyncAll("focus");
- const onVisibility = () => {
- if (document.visibilityState === "visible") {
- syncService.requestSyncAll("focus");
- }
- };
- const onOnline = () => syncService.requestSyncAll("online");
- window.addEventListener("focus", onFocus);
- document.addEventListener("visibilitychange", onVisibility);
- window.addEventListener("online", onOnline);
-
- const interval = setInterval(() => syncService.requestSyncAll("interval"), 5 * 60 * 1000);
-
- return () => {
- window.removeEventListener("focus", onFocus);
- document.removeEventListener("visibilitychange", onVisibility);
- window.removeEventListener("online", onOnline);
- clearInterval(interval);
- };
- }, []);
-
useEffect(() => {
fetchStreamingProviders();
}, []);
diff --git a/src/services/SyncService.ts b/src/services/SyncService.ts
index 1ea0aa364..fe3bf21b5 100644
--- a/src/services/SyncService.ts
+++ b/src/services/SyncService.ts
@@ -21,8 +21,16 @@ const BATCH_SIZE = 50;
const TRANSCRIPTION_BATCH_SIZE = 100;
const DICTIONARY_BATCH_SIZE = 200;
const SNIPPET_BATCH_SIZE = 200;
-// Skip a redundant syncAll() if focus + interval fire close together.
+// Minimum gap between auto syncs, measured from the last completed pass in
+// any window (the stamp lives in shared localStorage).
const AUTO_SYNC_THROTTLE_MS = 20000;
+const AUTO_SYNC_INTERVAL_MS = 5 * 60 * 1000;
+// Web Lock name serializing syncAll() across windows (each renderer has its
+// own SyncService instance, but localStorage and the local DB are shared).
+const SYNC_ALL_LOCK = "openwhispr-sync-all";
+// localStorage keys gating canSync(); a change in another window means sync
+// may have just become possible (sign-in, subscription, backup enabled).
+const CAN_SYNC_KEYS = ["isSignedIn", "cloudBackupEnabled", "isSubscribed"];
// SQLite `datetime('now')` yields "YYYY-MM-DD HH:MM:SS" (no T, no millis, no Z);
// the cloud sends ISO 8601 "YYYY-MM-DDTHH:MM:SS.sssZ". Normalize both to
@@ -38,10 +46,10 @@ function normalizeTimestamp(value: string | null | undefined): string {
class SyncService {
private syncing = false;
private syncAllPending = false;
+ private autoSyncStarted = false;
private dictionaryDirty = false;
private snippetsDirty = false;
private pushTimers = new Map<string, ReturnType<typeof setTimeout>>();
- private lastSyncAllAt = 0;
canSync(): boolean {
return (
@@ -51,7 +59,39 @@ class SyncService {
);
}
- async syncAll(): Promise<void> {
+ // lastSyncedAt is written only when a syncAll() pass completes, and
+ // localStorage is shared across windows, so it doubles as the global
+ // "last completed sync" stamp for throttling.
+ private lastCompletedSyncAt(): number {
+ const iso = localStorage.getItem("lastSyncedAt");
+ return iso ? Date.parse(iso) : 0;
+ }
+
+ // Runs in every window for the whole session; the throttle and Web Lock
+ // dedupe across windows.
+ startAutoSync(): void {
+ if (this.autoSyncStarted) return;
+ this.autoSyncStarted = true;
+
+ this.requestSyncAll("start");
+ window.addEventListener("focus", () => this.requestSyncAll("focus"));
+ document.addEventListener("visibilitychange", () => {
+ if (document.visibilityState === "visible") {
+ this.requestSyncAll("focus");
+ }
+ });
+ window.addEventListener("online", () => this.requestSyncAll("online"));
+ // storage events fire only in the windows that didn't write the change,
+ // which is exactly where a first sync is still needed.
+ window.addEventListener("storage", (e) => {
+ if (e.key && CAN_SYNC_KEYS.includes(e.key)) {
+ this.requestSyncAll("start");
+ }
+ });
+ setInterval(() => this.requestSyncAll("interval"), AUTO_SYNC_INTERVAL_MS);
+ }
+
+ async syncAll(waitForLock = false): Promise<void> {
if (!this.canSync()) return;
// A pass already running may have synced past the data this request covers,
// so flag a re-run instead of dropping it.
@@ -61,22 +101,27 @@ class SyncService {
}
this.syncing = true;
try {
- await this.syncFolders();
- await this.syncNotes();
- await this.syncConversations();
- await this.syncTranscriptions();
- // Edits during the awaits above set dictionaryDirty (syncing is already
- // true), so re-run until clean rather than stalling until the next trigger.
- do {
- this.dictionaryDirty = false;
- await this.syncDictionary();
- } while (this.dictionaryDirty);
- do {
- this.snippetsDirty = false;
- await this.syncSnippets();
- } while (this.snippetsDirty);
- localStorage.setItem("lastSyncedAt", new Date().toISOString());
- this.lastSyncAllAt = Date.now();
+ // Ambient passes skip when another window holds the lock — that pass
+ // reads the same local DB and cloud state, so it covers this request.
+ // Manual passes wait so a user action is never silently dropped.
+ await navigator.locks.request(SYNC_ALL_LOCK, { ifAvailable: !waitForLock }, async (lock) => {
+ if (!lock) return;
+ await this.syncFolders();
+ await this.syncNotes();
+ await this.syncConversations();
+ await this.syncTranscriptions();
+ // Edits during the awaits above set dictionaryDirty (syncing is already
+ // true), so re-run until clean rather than stalling until the next trigger.
+ do {
+ this.dictionaryDirty = false;
+ await this.syncDictionary();
+ } while (this.dictionaryDirty);
+ do {
+ this.snippetsDirty = false;
+ await this.syncSnippets();
+ } while (this.snippetsDirty);
+ localStorage.setItem("lastSyncedAt", new Date().toISOString());
+ });
} catch (err) {
console.error("Sync failed:", err);
} finally {
@@ -88,15 +133,15 @@ class SyncService {
}
}
- requestSyncAll(reason: "mount" | "focus" | "interval" | "online" | "manual"): void {
+ requestSyncAll(reason: "start" | "focus" | "interval" | "online" | "manual"): void {
if (!this.canSync()) return;
if (
reason !== "manual" &&
- (this.syncing || Date.now() - this.lastSyncAllAt < AUTO_SYNC_THROTTLE_MS)
+ (this.syncing || Date.now() - this.lastCompletedSyncAt() < AUTO_SYNC_THROTTLE_MS)
) {
return;
}
- void this.syncAll();
+ void this.syncAll(reason === "manual");
}
async syncDictionaryNow(): Promise<void> {