Skip to content

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

fix: session refetech, decrease sync interval

Chadpihaa37022a245a4
diff --git a/src/helpers/database.js b/src/helpers/database.js
index f1dd2a9c8..de36b4bbf 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -4391,7 +4391,12 @@ class DatabaseManager {
)
.get(folder.name, folder.space_id, id);
if (collision) {
- return { success: false, id, error: "Folder name is no longer available" };
+ return {
+ success: false,
+ id,
+ reason: "name-taken",
+ error: "Folder name is no longer available",
+ };
}
const noteStates = journalRows.filter((row) => row.entity_type === "note");
diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.ts
index cdf66718c..d6649b83b 100644
--- a/src/hooks/useAuth.ts
+++ b/src/hooks/useAuth.ts
@@ -73,8 +73,9 @@ export function useAuth() {
const ambientUser = ambientSession?.user ?? null;
const ambientUserId = typeof ambientUser?.id === "string" ? ambientUser.id : null;
- const boundGeneration =
- !isPending && !sessionError ? getBoundSessionGeneration(ambientUserId) : null;
+ // Not gated on sessionError: the binding survives a transient refetch failure
+ // and is cleared on its own by a 401 or a credential-generation change.
+ const boundGeneration = isPending ? null : getBoundSessionGeneration(ambientUserId);
const sessionIsBound = boundGeneration != null;
const resolvedUserId = sessionIsBound ? ambientUserId : null;
const rawIsSignedIn = sessionIsBound && Boolean(ambientUser);
@@ -95,7 +96,16 @@ export function useAuth() {
sessionResolutionFailed
) ||
!cloudContextReady;
- const isSignedIn = rawIsSignedIn && !accountScopeBlocked;
+ // A reconciled session whose refetch failed transiently keeps its binding but
+ // loses its validated lease. Keep presenting it instead of flashing to guest;
+ // sync stays fenced by getValidatedAuthGeneration() until a refetch succeeds.
+ const transientlyAuthenticated =
+ Boolean(sessionError) &&
+ rawIsSignedIn &&
+ !requiresReconciliation &&
+ !accountScopeHasMandatoryReconciliation();
+ const accountScopePresentable = !accountScopeBlocked || transientlyAuthenticated;
+ const isSignedIn = rawIsSignedIn && accountScopePresentable;
// Loaded means the session settled: fully validated, or failed/signed-out
// (presented as a guest). Resolution failure must not hold windows hostage —
// dictation works without an account, and sync stays fenced by
@@ -118,7 +128,12 @@ export function useAuth() {
useEffect(() => {
if (
boundGeneration == null ||
- !shouldReconcileAccountScope(isPending, gracePeriodActive, rawIsSignedIn, sessionResolutionFailed)
+ !shouldReconcileAccountScope(
+ isPending,
+ gracePeriodActive,
+ rawIsSignedIn,
+ sessionResolutionFailed
+ )
) {
return;
}
@@ -208,7 +223,7 @@ export function useAuth() {
isSignedIn,
isGracePeriodOnly: gracePeriodActive,
isLoaded,
- session: sessionIsBound && !accountScopeBlocked ? ambientSession : null,
+ session: sessionIsBound && accountScopePresentable ? ambientSession : null,
user: isSignedIn ? ambientUser : null,
};
}
diff --git a/src/lib/authRequestContext.ts b/src/lib/authRequestContext.ts
index de4d6b4e3..15ea6be26 100644
--- a/src/lib/authRequestContext.ts
+++ b/src/lib/authRequestContext.ts
@@ -176,7 +176,8 @@ export async function authContextFetch(
// failure and must prevent stale session data from being trusted.
await assertAuthRequestCurrent(init);
if (isGetSessionRequest((init ?? {}) as AuthRequest)) {
- clearSessionResolutionFor(requestGeneration(init));
+ // Fence sync, but keep the session binding so a transient refetch failure
+ // keeps presenting the account. A real 401 clears it via handleAuthRequestError.
invalidateValidatedAuthContext();
}
throw error;
diff --git a/src/services/SyncService.ts b/src/services/SyncService.ts
index 3d6bdadf1..a11eac606 100644
--- a/src/services/SyncService.ts
+++ b/src/services/SyncService.ts
@@ -109,6 +109,9 @@ const SNIPPET_BATCH_SIZE = 200;
// any window (the stamp lives in shared localStorage).
const AUTO_SYNC_THROTTLE_MS = 20000;
const AUTO_SYNC_INTERVAL_MS = 5 * 60 * 1000;
+// While a note is open, pull on this much shorter cadence so a teammate's edits
+// surface in seconds rather than at the ambient interval above.
+const OPEN_NOTE_SYNC_INTERVAL_MS = 30_000;
const TEAM_SPACES_RETRY_MS = 10_000;
const TEAM_SPACES_MAX_RETRY_MS = AUTO_SYNC_INTERVAL_MS;
// Web Lock name serializing syncAll() across windows (each renderer has its
@@ -212,6 +215,7 @@ class SyncService {
private pushTimers = new Map<string, ReturnType<typeof setTimeout>>();
private teamSpacesRetryTimer: ReturnType<typeof setTimeout> | null = null;
private teamSpacesRetryAttempt = 0;
+ private openNoteSyncTimer: ReturnType<typeof setInterval> | null = null;
canSync(): boolean {
return (
@@ -386,6 +390,26 @@ class SyncService {
setInterval(() => this.requestSyncAll("interval"), AUTO_SYNC_INTERVAL_MS);
}
+ // Called by noteStore when a note opens or closes: while one is open, keep an
+ // extra fast pull running so remote edits land in seconds. Reuses
+ // requestSyncAll, so the shared throttle and cross-window lock still bound the
+ // real passes — this only adds a recurring trigger.
+ setNoteOpen(open: boolean): void {
+ if (!open) {
+ if (this.openNoteSyncTimer) {
+ clearInterval(this.openNoteSyncTimer);
+ this.openNoteSyncTimer = null;
+ }
+ return;
+ }
+ this.requestSyncAll("interval");
+ if (this.openNoteSyncTimer) return;
+ this.openNoteSyncTimer = setInterval(
+ () => this.requestSyncAll("interval"),
+ OPEN_NOTE_SYNC_INTERVAL_MS
+ );
+ }
+
private scheduleTeamSpacesRetry(): void {
if (this.teamSpacesRetryTimer) return;
const delay = Math.min(
@@ -908,7 +932,10 @@ class SyncService {
purged.code
);
}
- throw new Error(`Could not purge revoked team space ${space.id}`);
+ // Isolate one space's failure instead of aborting the whole pass; it
+ // stays marked revoked, so the next pass retries.
+ console.error(`Could not purge revoked team space ${space.id}`);
+ continue;
}
this.dispatchSpaceRevoked(space.name, space.id);
// Never-synced notes survive the purge in Personal (plan §10.6) —
@@ -1158,9 +1185,17 @@ class SyncService {
private async handleDeniedFolderDelete(folder: FolderItem): Promise<void> {
const restored = await window.electronAPI.restoreFolderAfterDeniedDelete?.(folder.id);
if (!restored?.success) {
- throw new Error(
- `Could not roll back denied folder delete ${folder.id}: ${restored?.error ?? "unknown error"}`
- );
+ // Must not throw: this runs in pushFolderDeletes' per-row catch, so a
+ // throw would abort the whole pass. Surface a name clash for the user to
+ // resolve; the tombstone stays journaled and retries next pass.
+ if (restored?.reason === "name-taken") {
+ this.dispatchFolderNameTaken(folder.name);
+ } else {
+ console.error(
+ `Could not roll back denied folder delete ${folder.id}: ${restored?.error ?? "unknown error"}`
+ );
+ }
+ return;
}
this.clear404(FOLDER_UPDATE_404_KEY, folder.client_folder_id);
this.emitSyncUiEvent("folder-delete-denied", { name: folder.name });
diff --git a/src/stores/noteStore.ts b/src/stores/noteStore.ts
index 60aaea371..123f6cadd 100644
--- a/src/stores/noteStore.ts
+++ b/src/stores/noteStore.ts
@@ -93,6 +93,16 @@ const useNoteStore = create<NoteState>()(() => ({
noteConflicts: readNoteConflicts(),
}));
+// Drive SyncService's faster pull off the open note. Keyed on activeNoteId (not
+// just open/closed) so switching notes also refreshes, and so account-reset
+// teardown that clears it via setState stops the fast pull too.
+let syncedActiveNoteId: number | null = null;
+useNoteStore.subscribe((state) => {
+ if (state.activeNoteId === syncedActiveNoteId) return;
+ syncedActiveNoteId = state.activeNoteId;
+ syncService.setNoteOpen(state.activeNoteId != null);
+});
+
let hasBoundIpcListeners = false;
const DEFAULT_LIMIT = 50;
let currentLimit = DEFAULT_LIMIT;
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 6ddb2ce35..480783f36 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -2394,6 +2394,7 @@ declare global {
folder?: FolderItem;
notes?: NoteItem[];
conversationIds?: number[];
+ reason?: "name-taken";
error?: string;
}>;
hardDeleteFolder?: (id: number) => Promise<{ success: boolean; id: number }>;
diff --git a/test/helpers/containerConversationsDatabase.test.js b/test/helpers/containerConversationsDatabase.test.js
index b4b3d2481..7c4f54c8b 100644
--- a/test/helpers/containerConversationsDatabase.test.js
+++ b/test/helpers/containerConversationsDatabase.test.js
@@ -767,6 +767,57 @@ test("denied folder delete restores the same notes, speakers, and conversations
);
});
+test("denied folder delete rollback reports a name clash instead of failing hard", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const space = createTestTeamSpace(db, { name: "Eng" }).space;
+ const folder = db.createFolder("Docs", space.id).folder;
+ db.markFolderSynced(folder.id, "cloud-folder-held");
+ const child = db.saveNote("Child", "body", "personal", null, null, folder.id).note;
+
+ assert.equal(db.deleteFolder(folder.id).success, true);
+ const journalBefore = db.db
+ .prepare("SELECT COUNT(*) AS count FROM optimistic_folder_delete_rows WHERE folder_id = ?")
+ .get(folder.id).count;
+ assert.ok(journalBefore > 0);
+
+ // A pull inserts a teammate's live folder reusing the held name (the pull
+ // path bypasses the local name reservation, and the held row is deleted_at so
+ // the partial unique index doesn't stop the insert), so the name is no longer
+ // free when the server later denies the delete.
+ db.upsertFolderFromCloud(
+ {
+ client_folder_id: "cf-remote-docs",
+ id: "cloud-folder-live",
+ name: "Docs",
+ sort_order: 0,
+ created_at: "2026-07-01T00:00:00.000Z",
+ updated_at: "2026-07-02T00:00:00.000Z",
+ },
+ space.id
+ );
+
+ const restored = db.restoreFolderAfterDeniedDelete(folder.id);
+ assert.equal(restored.success, false);
+ assert.equal(
+ restored.reason,
+ "name-taken",
+ "a name clash is a recoverable, surfaced outcome — not a hard error the sync pass rethrows"
+ );
+
+ // The rollback transaction is atomic: a clash restores nothing, so the held
+ // folder and its journal stay intact for the next pass to retry once the user
+ // frees the name.
+ assert.ok(db.db.prepare("SELECT deleted_at FROM folders WHERE id = ?").get(folder.id).deleted_at);
+ assert.equal(
+ db.db
+ .prepare("SELECT COUNT(*) AS count FROM optimistic_folder_delete_rows WHERE folder_id = ?")
+ .get(folder.id).count,
+ journalBefore
+ );
+ assert.equal(db.getNote(child.id).sync_status, "folder_delete_pending");
+});
+
test("confirmed folder delete scrubs chats and finalizes held rows", (t) => {
const db = createDb(t);
if (!db) return;
diff --git a/test/lib/authRequestContext.test.js b/test/lib/authRequestContext.test.js
index 1b7a21054..4a17ad426 100644
--- a/test/lib/authRequestContext.test.js
+++ b/test/lib/authRequestContext.test.js
@@ -152,3 +152,57 @@ test("a token replacement while fetch is in flight discards the old response", a
await assert.rejects(responsePromise, { code: "AUTH_CONTEXT_CHANGED" });
});
+
+test("a transient get-session network failure keeps the binding but fences sync", async (t) => {
+ const auth = await import("../../src/lib/authRequestContext.ts");
+ auth.resetAuthRequestContextForTests();
+ const state = { current: { token: "token-a", generation: 3 } };
+ t.after(installWindow(state));
+
+ await auth.handleAuthRequestSuccess({
+ data: { user: { id: "user-a" } },
+ response: new Response("{}", { status: 200 }),
+ request: sessionRequest(3, "token-a"),
+ });
+ assert.equal(auth.commitValidatedAuthContext(3, "user-a"), true);
+ assert.equal(auth.getValidatedAuthGeneration(), 3);
+
+ const request = await auth.prepareAuthRequest({
+ url: "https://auth.openwhispr.test/api/auth/get-session",
+ headers: new Headers(),
+ });
+ const previousFetch = global.fetch;
+ global.fetch = async () => {
+ throw new TypeError("network down");
+ };
+ t.after(() => {
+ global.fetch = previousFetch;
+ });
+
+ await assert.rejects(auth.authContextFetch(request.url, request), { message: "network down" });
+
+ // The credential never changed, so the session stays presentable...
+ assert.equal(auth.getBoundSessionGeneration("user-a"), 3);
+ // ...but sync is fenced until a refetch succeeds.
+ assert.equal(auth.getValidatedAuthGeneration(), null);
+});
+
+test("a get-session 401 clears the binding so the app drops to guest", async (t) => {
+ const auth = await import("../../src/lib/authRequestContext.ts");
+ auth.resetAuthRequestContextForTests();
+ const state = { current: { token: "token-a", generation: 9 } };
+ t.after(installWindow(state));
+
+ await auth.handleAuthRequestSuccess({
+ data: { user: { id: "user-a" } },
+ response: new Response("{}", { status: 200 }),
+ request: sessionRequest(9, "token-a"),
+ });
+ assert.equal(auth.getBoundSessionGeneration("user-a"), 9);
+
+ // better-fetch routes a received 401 to onError (handleAuthRequestError),
+ // never through authContextFetch's network catch.
+ await auth.handleAuthRequestError({ request: sessionRequest(9, "token-a") });
+
+ assert.equal(auth.getBoundSessionGeneration("user-a"), null);
+});