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): harden workspace data against auth and deletion races

Chadpiha227fbed977c9
diff --git a/preload.js b/preload.js
index 4fcc6ad7b..85451465d 100644
--- a/preload.js
+++ b/preload.js
@@ -146,7 +146,7 @@ contextBridge.exposeInMainWorld("electronAPI", {
// Space functions
getSpaces: () => ipcRenderer.invoke("db-get-spaces"),
updateSpace: (id, updates) => ipcRenderer.invoke("db-update-space", id, updates),
- purgeSpace: (id) => ipcRenderer.invoke("db-purge-space", id),
+ purgeSpace: (id, options) => ipcRenderer.invoke("db-purge-space", id, options),
upsertSpaceFromCloud: (space) => ipcRenderer.invoke("db-upsert-space-from-cloud", space),
setSpaceSyncStatus: (id, status) => ipcRenderer.invoke("db-set-space-sync-status", id, status),
onSpacePurged: (callback) => {
@@ -580,7 +580,13 @@ contextBridge.exposeInMainWorld("electronAPI", {
openWhisperModelsFolder: () => ipcRenderer.invoke("open-whisper-models-folder"),
authClearSession: () => ipcRenderer.invoke("auth-clear-session"),
authGetToken: () => ipcRenderer.invoke("auth-get-token"),
- authSetToken: (token) => ipcRenderer.invoke("auth-set-token", token),
+ authGetTokenState: () => ipcRenderer.invoke("auth-get-token-state"),
+ authSetToken: (token, expectedGeneration) =>
+ ipcRenderer.invoke("auth-set-token", token, expectedGeneration),
+ onAuthTokenStateChanged: registerListener(
+ "auth-token-state-changed",
+ (callback) => (_event, state) => callback(state)
+ ),
// OpenWhispr Cloud API
cloudHealthCheck: () => ipcRenderer.invoke("cloud-health-check"),
@@ -911,14 +917,22 @@ contextBridge.exposeInMainWorld("electronAPI", {
getNoteByClientId: (clientNoteId) => ipcRenderer.invoke("db-get-note-by-client-id", clientNoteId),
upsertNoteFromCloud: (cloudNote, localFolderId, localSpaceId) =>
ipcRenderer.invoke("db-upsert-note-from-cloud", cloudNote, localFolderId, localSpaceId),
- markNoteSynced: (id, cloudId, cloudUpdatedAt, ownerUserId) =>
- ipcRenderer.invoke("db-mark-note-synced", id, cloudId, cloudUpdatedAt, ownerUserId),
- markNoteSyncedIfUnchanged: (id, cloudId, snapshotUpdatedAt, cloudUpdatedAt, ownerUserId) =>
+ acknowledgeNoteCreate: (id, snapshot, cloudId, cloudUpdatedAt, ownerUserId, settleIfUnchanged) =>
ipcRenderer.invoke(
- "db-mark-note-synced-if-unchanged",
+ "db-acknowledge-note-create",
id,
+ snapshot,
cloudId,
- snapshotUpdatedAt,
+ cloudUpdatedAt,
+ ownerUserId,
+ settleIfUnchanged
+ ),
+ markNoteSyncedIfUnchanged: (id, snapshot, expectedCloudId, cloudUpdatedAt, ownerUserId) =>
+ ipcRenderer.invoke(
+ "db-mark-note-synced-if-unchanged",
+ id,
+ snapshot,
+ expectedCloudId,
cloudUpdatedAt,
ownerUserId
),
@@ -928,6 +942,8 @@ contextBridge.exposeInMainWorld("electronAPI", {
ipcRenderer.invoke("db-set-note-owner-from-cloud", id, ownerUserId),
countTeamNotesMissingOwner: () => ipcRenderer.invoke("db-count-team-notes-missing-owner"),
markNoteSyncError: (id) => ipcRenderer.invoke("db-mark-note-sync-error", id),
+ restoreNoteAfterDeniedDelete: (id) =>
+ ipcRenderer.invoke("db-restore-note-after-denied-delete", id),
hardDeleteNote: (id) => ipcRenderer.invoke("db-hard-delete-note", id),
getPendingFolders: (spaceKind) => ipcRenderer.invoke("db-get-pending-folders", spaceKind),
@@ -935,13 +951,29 @@ contextBridge.exposeInMainWorld("electronAPI", {
ipcRenderer.invoke("db-get-folder-by-client-id", clientFolderId),
upsertFolderFromCloud: (cloudFolder, localSpaceId) =>
ipcRenderer.invoke("db-upsert-folder-from-cloud", cloudFolder, localSpaceId),
- markFolderSynced: (id, cloudId) => ipcRenderer.invoke("db-mark-folder-synced", id, cloudId),
- markFolderSyncedIfUnchanged: (id, cloudId, snapshotUpdatedAt) =>
- ipcRenderer.invoke("db-mark-folder-synced-if-unchanged", id, cloudId, snapshotUpdatedAt),
- adoptFolderIdentity: (id, clientFolderId, cloudId, updatedAt) =>
- ipcRenderer.invoke("db-adopt-folder-identity", id, clientFolderId, cloudId, updatedAt),
+ acknowledgeFolderCreate: (
+ id,
+ snapshot,
+ expectedCloudId,
+ responseClientFolderId,
+ cloudId,
+ cloudUpdatedAt
+ ) =>
+ ipcRenderer.invoke(
+ "db-acknowledge-folder-create",
+ id,
+ snapshot,
+ expectedCloudId,
+ responseClientFolderId,
+ cloudId,
+ cloudUpdatedAt
+ ),
+ markFolderSyncedIfUnchanged: (id, snapshot, expectedCloudId) =>
+ ipcRenderer.invoke("db-mark-folder-synced-if-unchanged", id, snapshot, expectedCloudId),
getFolderIdMap: () => ipcRenderer.invoke("db-get-folder-id-map"),
getPendingFolderDeletes: () => ipcRenderer.invoke("db-get-pending-folder-deletes"),
+ restoreFolderAfterDeniedDelete: (id) =>
+ ipcRenderer.invoke("db-restore-folder-after-denied-delete", id),
hardDeleteFolder: (id) => ipcRenderer.invoke("db-hard-delete-folder", id),
relocateRevokedFolder: (id, privateSpaceId, preserveFolder) =>
ipcRenderer.invoke("db-relocate-revoked-folder", id, privateSpaceId, preserveFolder),
diff --git a/src/AppRouter.jsx b/src/AppRouter.jsx
index ccb35dc5f..e27f78728 100644
--- a/src/AppRouter.jsx
+++ b/src/AppRouter.jsx
@@ -58,14 +58,16 @@ function MainApp() {
}
}
- // Sync runs in every non-agent window, so tray-only sessions where the
- // control panel is never opened still stay fresh.
- if (!isAgentPanel) {
+ // Sync starts only after auth settles, so a new bearer token cannot touch
+ // the previous account's rows while validation is still running. A failed
+ // (guest/offline) resolution also counts as settled: canSync() then no-ops
+ // because no validated auth context exists.
+ if (!isAgentPanel && authLoaded) {
import("./services/SyncService.js")
.then(({ syncService }) => syncService.startAutoSync())
.catch(() => {});
}
- }, [isAgentPanel, isControlPanel]);
+ }, [authLoaded, isAgentPanel, isControlPanel]);
useEffect(() => {
if (!authLoaded) return;
@@ -109,6 +111,8 @@ function MainApp() {
localStorage.setItem("onboardingCompleted", "true");
};
+ // The agent overlay never touches account-scoped data, so it renders
+ // without waiting for auth resolution (guests can use it offline).
if (isAgentPanel) {
return (
<Suspense fallback={<LoadingFallback />}>
@@ -117,6 +121,9 @@ function MainApp() {
);
}
+ // isLoading clears once the onboarding effect has run, which itself waits
+ // for authLoaded — and authLoaded terminates even when the session cannot
+ // resolve (guest/offline presents as signed out).
if (isLoading) {
return <LoadingFallback />;
}
diff --git a/src/components/AcceptInvitationModal.tsx b/src/components/AcceptInvitationModal.tsx
index 09b4e7360..1a670a68e 100644
--- a/src/components/AcceptInvitationModal.tsx
+++ b/src/components/AcceptInvitationModal.tsx
@@ -45,10 +45,23 @@ export default function AcceptInvitationModal({ token, onClose, onAccepted }: Pr
setError(null);
if (!token) return;
setLoading(true);
+ // Ignore stale resolutions: a slower preview for a previous token must
+ // not overwrite the current one, or the modal would describe invitation
+ // A while accepting B.
+ let cancelled = false;
InvitationsService.preview(token)
- .then(setPreview)
- .catch((err) => setError(err instanceof Error ? err.message : t("common.unknownError")))
- .finally(() => setLoading(false));
+ .then((result) => {
+ if (!cancelled) setPreview(result);
+ })
+ .catch((err) => {
+ if (!cancelled) setError(err instanceof Error ? err.message : t("common.unknownError"));
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
}, [token, t]);
const wrongAccount =
@@ -83,9 +96,13 @@ export default function AcceptInvitationModal({ token, onClose, onAccepted }: Pr
: undefined,
});
onClose();
+ // Navigate with the accept response, not the preview: the invitation
+ // may have been re-targeted since it was previewed, and the server's
+ // team_ids are authoritative. The preview only fills in for API
+ // responses that predate team_ids.
onAccepted?.({
workspaceId: accepted.workspace_id,
- teamIds: preview?.team_ids ?? [],
+ teamIds: accepted.team_ids ?? preview?.team_ids ?? [],
});
} catch (err) {
toast({
diff --git a/src/components/chat/useChatPersistence.ts b/src/components/chat/useChatPersistence.ts
index d57c86c63..ecded3d86 100644
--- a/src/components/chat/useChatPersistence.ts
+++ b/src/components/chat/useChatPersistence.ts
@@ -41,7 +41,10 @@ export function useChatPersistence(options: UseChatPersistenceOptions = {}): Cha
scope?.spaceId,
scope?.folderId ?? undefined
);
- const id = conv?.id ?? 0;
+ if (!conv) {
+ throw new Error("Conversation scope is no longer available");
+ }
+ const id = conv.id;
conversationIdRef.current = id;
setConversationId(id);
options.onConversationCreated?.(id, title);
diff --git a/src/components/notes/NoteBottomBar.tsx b/src/components/notes/NoteBottomBar.tsx
index ffddaebda..b1ba39c72 100644
--- a/src/components/notes/NoteBottomBar.tsx
+++ b/src/components/notes/NoteBottomBar.tsx
@@ -16,6 +16,8 @@ interface NoteBottomBarProps {
askDisabled?: boolean;
actionPicker?: React.ReactNode;
hideInput?: boolean;
+ /** False hides the record control (e.g. read-only shared notes). */
+ canRecord?: boolean;
}
export default function NoteBottomBar({
@@ -28,6 +30,7 @@ export default function NoteBottomBar({
askDisabled,
actionPicker,
hideInput,
+ canRecord = true,
}: NoteBottomBarProps) {
const { t } = useTranslation();
const [inputText, setInputText] = useState("");
@@ -98,71 +101,73 @@ export default function NoteBottomBar({
<div
className={cn("flex items-end gap-2 pointer-events-auto", hideInput && "justify-center")}
>
- <div
- className={cn(
- "shrink-0 transition-all duration-300 ease-out overflow-hidden",
- !hideInput && isExpanded && !isRecording ? "w-0 opacity-0" : "w-auto opacity-100"
- )}
- >
- {isRecording ? (
- <button
- onClick={onStopRecording}
- className={cn(
- "flex items-center gap-2 h-10 pl-3.5 pr-3 rounded-xl",
- "bg-primary/6 dark:bg-primary/10",
- "border border-primary/20 dark:border-primary/25",
- "transition-colors duration-150",
- "hover:bg-primary/10 dark:hover:bg-primary/15"
- )}
- >
- <div className="flex items-end gap-0.5 h-3.5">
- {Array.from({ length: BAR_COUNT }, (_, i) => (
- <div
- key={i}
- className="w-0.5 rounded-full bg-primary/60 dark:bg-primary/70 origin-bottom"
- style={{
- height: "100%",
- animation: `waveform-bar ${0.5 + i * 0.07}s ease-in-out infinite`,
- animationDelay: `${i * 0.04}s`,
- }}
- />
- ))}
+ {canRecord && (
+ <div
+ className={cn(
+ "shrink-0 transition-all duration-300 ease-out overflow-hidden",
+ !hideInput && isExpanded && !isRecording ? "w-0 opacity-0" : "w-auto opacity-100"
+ )}
+ >
+ {isRecording ? (
+ <button
+ onClick={onStopRecording}
+ className={cn(
+ "flex items-center gap-2 h-10 pl-3.5 pr-3 rounded-xl",
+ "bg-primary/6 dark:bg-primary/10",
+ "border border-primary/20 dark:border-primary/25",
+ "transition-colors duration-150",
+ "hover:bg-primary/10 dark:hover:bg-primary/15"
+ )}
+ >
+ <div className="flex items-end gap-0.5 h-3.5">
+ {Array.from({ length: BAR_COUNT }, (_, i) => (
+ <div
+ key={i}
+ className="w-0.5 rounded-full bg-primary/60 dark:bg-primary/70 origin-bottom"
+ style={{
+ height: "100%",
+ animation: `waveform-bar ${0.5 + i * 0.07}s ease-in-out infinite`,
+ animationDelay: `${i * 0.04}s`,
+ }}
+ />
+ ))}
+ </div>
+ <span className="text-[11px] font-medium tabular-nums text-primary/60 dark:text-primary/70">
+ {elapsedLabel}
+ </span>
+ <Square size={9} fill="currentColor" className="text-primary/50" />
+ </button>
+ ) : isProcessing ? (
+ <div
+ className={cn(
+ "flex items-center justify-center w-10 h-10 rounded-xl",
+ "bg-foreground/3 dark:bg-white/4",
+ "border border-border/20 dark:border-white/6"
+ )}
+ >
+ <Loader2 size={14} className="animate-spin text-foreground/25" />
</div>
- <span className="text-[11px] font-medium tabular-nums text-primary/60 dark:text-primary/70">
- {elapsedLabel}
- </span>
- <Square size={9} fill="currentColor" className="text-primary/50" />
- </button>
- ) : isProcessing ? (
- <div
- className={cn(
- "flex items-center justify-center w-10 h-10 rounded-xl",
- "bg-foreground/3 dark:bg-white/4",
- "border border-border/20 dark:border-white/6"
- )}
- >
- <Loader2 size={14} className="animate-spin text-foreground/25" />
- </div>
- ) : (
- <button
- onClick={onStartRecording}
- className={cn(
- "flex items-center justify-center w-10 h-10 rounded-xl",
- "bg-foreground/3 dark:bg-white/4",
- "border border-border/20 dark:border-white/6",
- "text-foreground/30 dark:text-foreground/20",
- "transition-all duration-200",
- "hover:bg-foreground/6 dark:hover:bg-white/8",
- "hover:text-foreground/50 dark:hover:text-foreground/35",
- "hover:border-border/30 dark:hover:border-white/10",
- "active:scale-95"
- )}
- aria-label={t("notes.editor.transcribe")}
- >
- <Mic size={15} />
- </button>
- )}
- </div>
+ ) : (
+ <button
+ onClick={onStartRecording}
+ className={cn(
+ "flex items-center justify-center w-10 h-10 rounded-xl",
+ "bg-foreground/3 dark:bg-white/4",
+ "border border-border/20 dark:border-white/6",
+ "text-foreground/30 dark:text-foreground/20",
+ "transition-all duration-200",
+ "hover:bg-foreground/6 dark:hover:bg-white/8",
+ "hover:text-foreground/50 dark:hover:text-foreground/35",
+ "hover:border-border/30 dark:hover:border-white/10",
+ "active:scale-95"
+ )}
+ aria-label={t("notes.editor.transcribe")}
+ >
+ <Mic size={15} />
+ </button>
+ )}
+ </div>
+ )}
{!hideInput && (
<div
diff --git a/src/components/notes/NoteEditor.tsx b/src/components/notes/NoteEditor.tsx
index 322a4d841..fde300ee7 100644
--- a/src/components/notes/NoteEditor.tsx
+++ b/src/components/notes/NoteEditor.tsx
@@ -26,6 +26,7 @@ import {
} from "lucide-react";
import ShareNoteDialog from "./ShareNoteDialog";
import {
+ canOrganizeNote,
noteCapabilities,
resolveNotePermission,
type NoteAclState,
@@ -265,19 +266,25 @@ export default function NoteEditor({
: aclRequest?.cloudId === note.cloud_id
? aclRequest.state
: "loading";
- const shareCapabilities = noteCapabilities(
- resolveNotePermission({
- cachedPermission: shareCache?.access?.my_permission,
- aclState,
- isTeamNote,
- })
- );
+ const notePermission = resolveNotePermission({
+ cachedPermission: shareCache?.access?.my_permission,
+ aclState,
+ isTeamNote,
+ });
+ const shareCapabilities = noteCapabilities(notePermission);
const canShare =
isSignedIn &&
(!note.cloud_id || isTeamNote || aclState === "loaded") &&
shareCapabilities.canShare &&
(isSubscribed || Boolean(note.is_shared));
const canEditNote = shareCapabilities.canEdit;
+ // Re-filing is owner-only on shared personal notes (a denied folder_id
+ // PATCH would fork an unexpected Personal copy); team members keep
+ // same-space folder moves.
+ const canMoveToFolders = canOrganizeNote(notePermission, {
+ isTeamNote,
+ hasCloudCopy: Boolean(note.cloud_id),
+ });
useEffect(() => {
if (!isSignedIn || !note.cloud_id || shareCache) return;
const cloudId = note.cloud_id;
@@ -839,14 +846,20 @@ export default function NoteEditor({
)}
<span className="truncate max-w-32">{space.name}</span>
</button>
- {folders && onMoveToFolder && (
+ {folders && onMoveToFolder && (canMoveToFolders || folderName) && (
<span aria-hidden="true" className="text-[11px] text-foreground/25">
/
</span>
)}
</>
)}
- {folders && onMoveToFolder && (
+ {folders && onMoveToFolder && !canMoveToFolders && folderName && (
+ <span className={cn(CHIP_BUTTON_CLASS, "cursor-default")}>
+ <FolderOpen size={11} className="shrink-0" />
+ {folderName}
+ </span>
+ )}
+ {folders && onMoveToFolder && canMoveToFolders && (
<DropdownMenu
onOpenChange={(open) => {
if (!open) {
@@ -1243,7 +1256,8 @@ export default function NoteEditor({
onStopRecording={onStopRecording}
onAskSubmit={handleAskSubmit}
onInputFocus={handleChatInputFocus}
- actionPicker={isRecording ? undefined : actionPicker}
+ canRecord={canEditNote}
+ actionPicker={isRecording || !canEditNote ? undefined : actionPicker}
hideInput={chatMode !== "hidden"}
/>
{chatMode === "floating" && (
diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsx
index 7103b0347..c72175cbc 100644
--- a/src/components/notes/PersonalNotesView.tsx
+++ b/src/components/notes/PersonalNotesView.tsx
@@ -56,6 +56,10 @@ import { useAuth } from "../../hooks/useAuth";
import NotesOnboarding from "./NotesOnboarding";
import { isRegenerableNoteTitle } from "../../helpers/regenerableNoteTitle";
import { markIntroSeen, NOTES_STRUCTURE_INTRO, shouldShowIntro } from "../../lib/versionedIntro";
+import {
+ buildPendingNoteUpdates,
+ shouldCancelPendingSavesForDelete,
+} from "../../lib/noteEditorPendingSave";
function makeContentHash(content: string): string {
return String(content.length) + "-" + content.slice(0, 50);
@@ -113,12 +117,49 @@ export default function PersonalNotesView({
activeNoteRef.current = id;
setSyncedNoteIdState(id);
};
+ // Conflict-banner Refresh applies an external cloud copy: a queued
+ // debounced save would clobber it with the pre-refresh buffer, so the
+ // editor cancels pending saves before the copy is applied. With the timers
+ // cleared, the external-update resync effect picks up the fresh note.
+ const cancelPendingSaves = useCallback(() => {
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ saveTimeoutRef.current = null;
+ }
+ if (enhancedSaveTimeoutRef.current) {
+ clearTimeout(enhancedSaveTimeoutRef.current);
+ enhancedSaveTimeoutRef.current = null;
+ }
+ }, []);
+ const flushPendingSaves = useCallback(
+ (reason: "switch" | "overview" | "unmount") => {
+ const noteId = activeNoteRef.current;
+ const updates = buildPendingNoteUpdates({
+ title: localTitleRef.current,
+ content: localContentRef.current,
+ enhancedContent: localEnhancedContentRef.current,
+ documentPending: saveTimeoutRef.current != null,
+ enhancedPending: enhancedSaveTimeoutRef.current != null,
+ });
+ cancelPendingSaves();
+ if (!noteId || !updates) return;
+
+ void window.electronAPI.updateNote(noteId, updates).catch((err: unknown) => {
+ logger.warn(
+ `Failed to flush note before ${reason}`,
+ { error: (err as Error).message },
+ "notes"
+ );
+ });
+ },
+ [cancelPendingSaves]
+ );
const { toast } = useToast();
const isCloudMode = useSettingsStore(selectIsCloudNoteFormattingMode);
const effectiveModelId = useSettingsStore((s) => selectResolvedNoteFormatting(s).model);
const { isComplete: isOnboardingComplete, complete: completeOnboarding } = useNotesOnboarding();
const { isSignedIn } = useAuth();
- const teamSpacesAvailable = useTeamSpacesCapability();
+ const teamSpacesAvailable = useTeamSpacesCapability(isSignedIn);
const isTreeLoading = useIsTreeLoading();
const [structureIntroPending, setStructureIntroPending] = useState(() =>
shouldShowIntro(localStorage, NOTES_STRUCTURE_INTRO)
@@ -257,45 +298,21 @@ export default function PersonalNotesView({
useEffect(() => {
if (activeNote && activeNote.id !== activeNoteRef.current) {
- // --- Switching notes ---
- // 1. Capture old note state before anything changes
- const oldNoteId = activeNoteRef.current;
- const oldTitle = localTitleRef.current;
- const oldContent = localContentRef.current;
- const hadPendingSave = !!saveTimeoutRef.current;
-
- // 2. Clear all pending timers
- if (saveTimeoutRef.current) {
- clearTimeout(saveTimeoutRef.current);
- saveTimeoutRef.current = null;
- }
- if (enhancedSaveTimeoutRef.current) {
- clearTimeout(enhancedSaveTimeoutRef.current);
- enhancedSaveTimeoutRef.current = null;
- }
-
- // 3. Switch to new note IMMEDIATELY (no await, eliminates race window)
+ // Drain the old note before changing the ref that owns its save timers.
+ flushPendingSaves("switch");
markNoteAsSynced(activeNote.id);
setLocalTitle(activeNote.title);
setLocalContent(activeNote.content);
setLocalEnhancedContent(activeNote.enhanced_content ?? null);
- // Also update refs directly so callbacks are correct before next render
localTitleRef.current = activeNote.title;
localContentRef.current = activeNote.content;
-
- // 4. Flush old note data fire-and-forget (uses captured values, not refs)
- if (hadPendingSave && oldNoteId) {
- window.electronAPI
- .updateNote(oldNoteId, { title: oldTitle, content: oldContent })
- .catch((err: unknown) => {
- logger.warn(
- "Failed to flush note on switch",
- { error: (err as Error).message },
- "notes"
- );
- });
- }
- } else if (activeNote && activeNote.id === activeNoteRef.current && !saveTimeoutRef.current) {
+ localEnhancedContentRef.current = activeNote.enhanced_content ?? null;
+ } else if (
+ activeNote &&
+ activeNote.id === activeNoteRef.current &&
+ !saveTimeoutRef.current &&
+ !enhancedSaveTimeoutRef.current
+ ) {
// External update (e.g. AI chat tool) — resync only when no user save is pending
if (activeNote.title !== localTitleRef.current) setLocalTitle(activeNote.title);
if (activeNote.content !== localContentRef.current) setLocalContent(activeNote.content);
@@ -303,35 +320,15 @@ export default function PersonalNotesView({
setLocalEnhancedContent(activeNote.enhanced_content ?? null);
}
} else if (!activeNote) {
- if (saveTimeoutRef.current) {
- clearTimeout(saveTimeoutRef.current);
- saveTimeoutRef.current = null;
- }
- if (enhancedSaveTimeoutRef.current) {
- clearTimeout(enhancedSaveTimeoutRef.current);
- enhancedSaveTimeoutRef.current = null;
- }
+ // Space/folder activation shows its overview by clearing activeNoteId.
+ // Persist pending editor buffers before that navigation discards them.
+ flushPendingSaves("overview");
markNoteAsSynced(null);
setLocalTitle("");
setLocalContent("");
setLocalEnhancedContent(null);
}
- }, [activeNote]);
-
- // Conflict-banner Refresh applies an external cloud copy: a queued
- // debounced save would clobber it with the pre-refresh buffer, so the
- // editor cancels pending saves before the copy is applied. With the timers
- // cleared, the external-update resync effect above picks up the fresh note.
- const cancelPendingSaves = useCallback(() => {
- if (saveTimeoutRef.current) {
- clearTimeout(saveTimeoutRef.current);
- saveTimeoutRef.current = null;
- }
- if (enhancedSaveTimeoutRef.current) {
- clearTimeout(enhancedSaveTimeoutRef.current);
- enhancedSaveTimeoutRef.current = null;
- }
- }, []);
+ }, [activeNote, flushPendingSaves]);
const debouncedSave = useCallback((noteId: number, title: string, content: string) => {
if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);
@@ -349,14 +346,12 @@ export default function PersonalNotesView({
}, []);
useEffect(() => {
- return () => {
- if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);
- if (enhancedSaveTimeoutRef.current) clearTimeout(enhancedSaveTimeoutRef.current);
- };
- }, []);
+ return () => flushPendingSaves("unmount");
+ }, [flushPendingSaves]);
const handleTitleChange = useCallback(
(title: string) => {
+ localTitleRef.current = title;
setLocalTitle(title);
if (activeNoteRef.current)
debouncedSave(activeNoteRef.current, title, localContentRef.current);
@@ -366,6 +361,7 @@ export default function PersonalNotesView({
const handleContentChange = useCallback(
(content: string) => {
+ localContentRef.current = content;
setLocalContent(content);
if (activeNoteRef.current)
debouncedSave(activeNoteRef.current, localTitleRef.current, content);
@@ -374,6 +370,7 @@ export default function PersonalNotesView({
);
const handleEnhancedContentChange = useCallback((content: string) => {
+ localEnhancedContentRef.current = content;
setLocalEnhancedContent(content);
if (!activeNoteRef.current) return;
const noteId = activeNoteRef.current;
@@ -431,13 +428,15 @@ export default function PersonalNotesView({
loadFolders();
}, [activeFolderId]);
- const handleDelete = useCallback(async (id: number) => {
- if (saveTimeoutRef.current) {
- clearTimeout(saveTimeoutRef.current);
- saveTimeoutRef.current = null;
- }
- await window.electronAPI.deleteNote(id);
- }, []);
+ const handleDelete = useCallback(
+ async (id: number) => {
+ if (shouldCancelPendingSavesForDelete(activeNoteRef.current, id)) {
+ cancelPendingSaves();
+ }
+ await window.electronAPI.deleteNote(id);
+ },
+ [cancelPendingSaves]
+ );
const handleMoveNote = useCallback(
async (noteId: number, target: NoteMoveTarget) => {
@@ -759,7 +758,11 @@ export default function PersonalNotesView({
</>
) : activeContext && overviewSpace ? (
<ContainerOverview
- key={activeContext.folderId != null ? `f:${activeContext.folderId}` : `s:${activeContext.spaceId}`}
+ key={
+ activeContext.folderId != null
+ ? `f:${activeContext.folderId}`
+ : `s:${activeContext.spaceId}`
+ }
space={overviewSpace}
folder={overviewFolder}
onOpenNote={setActiveNoteId}
diff --git a/src/components/notes/ShareNoteDialog.tsx b/src/components/notes/ShareNoteDialog.tsx
index 32922ba47..b60d6159d 100644
--- a/src/components/notes/ShareNoteDialog.tsx
+++ b/src/components/notes/ShareNoteDialog.tsx
@@ -61,8 +61,9 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD
);
const isTeamNote = space?.kind === "team";
- // A note synced from this dialog: markNoteSynced doesn't broadcast, so the
- // note prop can lag behind the local DB until the next note-updated event.
+ // A note synced from this dialog: the create acknowledgement doesn't
+ // broadcast, so the note prop can lag behind the local DB until the next
+ // note-updated event.
const [syncedFor, setSyncedFor] = useState<{ noteId: number; cloudId: string } | null>(null);
const cloudId = note.cloud_id ?? (syncedFor?.noteId === note.id ? syncedFor.cloudId : null);
const cached = useShareCacheEntry(cloudId);
@@ -134,8 +135,9 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD
[cloudId]
);
- // The store's note can miss a cloud_id assigned by a background sync
- // (markNoteSynced doesn't broadcast); read the DB before offering to sync.
+ // The store's note can miss a cloud_id assigned by a background sync (the
+ // create acknowledgement doesn't broadcast); read the DB before offering to
+ // sync.
useEffect(() => {
if (!open || note.cloud_id) return;
let cancelled = false;
diff --git a/src/components/notes/SpacesTree.tsx b/src/components/notes/SpacesTree.tsx
index 9c47b5887..b39efac2b 100644
--- a/src/components/notes/SpacesTree.tsx
+++ b/src/components/notes/SpacesTree.tsx
@@ -46,6 +46,11 @@ import {
canMoveBetweenSpaces,
canMoveOrDeleteSpaceFolder,
} from "../../lib/spacePermissions";
+import {
+ canOrganizeNote as canOrganizeSharedNote,
+ resolveNotePermission,
+ sharedNoteBlocksDelete,
+} from "../../lib/notePermissions";
import { groupTeamSpacesByWorkspace } from "../../lib/workspaceSelection";
import { localMutationErrorKey } from "../../lib/localMutationError";
import { readIsSubscribed, subscribeIsSubscribed } from "../../lib/subscriptionFlag";
@@ -82,6 +87,7 @@ import {
getNoteFromStore,
getFoldersValue,
getSpacesValue,
+ useShareCache,
} from "../../stores/noteStore";
const FOLDER_INPUT_CLASS =
@@ -783,6 +789,7 @@ function NoteLeaf({
noteFilesEnabled,
fileManagerName,
canDelete,
+ canMove,
onOpen,
onMove,
onCreateFolderAndMove,
@@ -805,6 +812,7 @@ function NoteLeaf({
noteFilesEnabled: boolean;
fileManagerName: string;
canDelete: boolean;
+ canMove: boolean;
onOpen: () => void;
onMove: (target: NoteMoveTarget) => void;
onCreateFolderAndMove: (noteId: number, folderName: string) => void;
@@ -881,7 +889,7 @@ function NoteLeaf({
onFocus={a11y.onFocus}
onClick={onOpen}
title={title}
- {...dragHandlers}
+ {...(canMove ? dragHandlers : {})}
className={cn(
ROW_BASE_CLASS,
"h-7 pr-2",
@@ -925,152 +933,158 @@ function NoteLeaf({
>
{formatRelativeTime(note.updated_at, t)}
</span>
- <DropdownMenu
- onOpenChange={(open) => {
- if (!open) {
- setMoveSearch("");
- setIsCreating(false);
- setNewFolderName("");
- }
- }}
- >
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- size="icon"
- aria-label={t("common.actions")}
- onClick={(e) => e.stopPropagation()}
- className={KEBAB_TRIGGER_CLASS}
- >
- <MoreHorizontal size={12} />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" sideOffset={4} className="min-w-40">
- {noteFilesEnabled && (
- <>
- <DropdownMenuItem
- onClick={(e) => {
- e.stopPropagation();
- window.electronAPI?.showNoteFile?.(note.id);
- }}
- className={MENU_ITEM_CLASS}
- >
- <ExternalLink size={11} className="text-muted-foreground/60" />
- {t("notes.context.showInFileManager", { manager: fileManagerName })}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- </>
- )}
- <SearchableMoveSubmenu
- icon={<FolderOpen size={11} className="text-muted-foreground/60" />}
- label={multiSpace ? t("notes.spaces.moveTo") : t("notes.context.moveToFolder")}
- itemCount={moveOptions.length}
- search={moveSearch}
- onSearchChange={setMoveSearch}
- searchPlaceholder={t("notes.context.searchFolders")}
- footer={
- isCreating ? (
- <div className="px-1">
- <input
- autoFocus
- value={newFolderName}
- onChange={(e) => setNewFolderName(e.target.value)}
- onKeyDown={(e) => {
- e.stopPropagation();
- if (e.key === "Enter" && newFolderName.trim()) {
- onCreateFolderAndMove(note.id, newFolderName.trim());
- setNewFolderName("");
- setIsCreating(false);
- }
- if (e.key === "Escape") {
- setIsCreating(false);
- setNewFolderName("");
- }
- }}
- placeholder={t("notes.folders.folderName")}
- className="input-inline w-full px-2 py-1.5 rounded-md bg-transparent text-xs text-foreground placeholder:text-foreground/20 outline-none border-none appearance-none"
- />
- </div>
- ) : (
+ {(noteFilesEnabled || canMove || canDelete) && (
+ <DropdownMenu
+ onOpenChange={(open) => {
+ if (!open) {
+ setMoveSearch("");
+ setIsCreating(false);
+ setNewFolderName("");
+ }
+ }}
+ >
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ aria-label={t("common.actions")}
+ onClick={(e) => e.stopPropagation()}
+ className={KEBAB_TRIGGER_CLASS}
+ >
+ <MoreHorizontal size={12} />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" sideOffset={4} className="min-w-40">
+ {noteFilesEnabled && (
+ <>
<DropdownMenuItem
- onSelect={(e) => {
- e.preventDefault();
- setIsCreating(true);
+ onClick={(e) => {
+ e.stopPropagation();
+ window.electronAPI?.showNoteFile?.(note.id);
}}
- className={cn(MENU_ITEM_CLASS, "text-foreground/40")}
+ className={MENU_ITEM_CLASS}
>
- <Plus size={10} />
- {t("notes.context.newFolder")}
+ <ExternalLink size={11} className="text-muted-foreground/60" />
+ {t("notes.context.showInFileManager", { manager: fileManagerName })}
</DropdownMenuItem>
- )
- }
- >
- {moveSearch ? (
- <>
- {filteredOptions.map((option) =>
- renderOption(
- option,
- multiSpace && option.target.folderId != null
- ? `${spaceDisplayName(option.space, t)} / ${option.label}`
- : option.label
+ {(canMove || canDelete) && <DropdownMenuSeparator />}
+ </>
+ )}
+ {canMove && (
+ <SearchableMoveSubmenu
+ icon={<FolderOpen size={11} className="text-muted-foreground/60" />}
+ label={multiSpace ? t("notes.spaces.moveTo") : t("notes.context.moveToFolder")}
+ itemCount={moveOptions.length}
+ search={moveSearch}
+ onSearchChange={setMoveSearch}
+ searchPlaceholder={t("notes.context.searchFolders")}
+ footer={
+ isCreating ? (
+ <div className="px-1">
+ <input
+ autoFocus
+ value={newFolderName}
+ onChange={(e) => setNewFolderName(e.target.value)}
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (e.key === "Enter" && newFolderName.trim()) {
+ onCreateFolderAndMove(note.id, newFolderName.trim());
+ setNewFolderName("");
+ setIsCreating(false);
+ }
+ if (e.key === "Escape") {
+ setIsCreating(false);
+ setNewFolderName("");
+ }
+ }}
+ placeholder={t("notes.folders.folderName")}
+ className="input-inline w-full px-2 py-1.5 rounded-md bg-transparent text-xs text-foreground placeholder:text-foreground/20 outline-none border-none appearance-none"
+ />
+ </div>
+ ) : (
+ <DropdownMenuItem
+ onSelect={(e) => {
+ e.preventDefault();
+ setIsCreating(true);
+ }}
+ className={cn(MENU_ITEM_CLASS, "text-foreground/40")}
+ >
+ <Plus size={10} />
+ {t("notes.context.newFolder")}
+ </DropdownMenuItem>
)
+ }
+ >
+ {moveSearch ? (
+ <>
+ {filteredOptions.map((option) =>
+ renderOption(
+ option,
+ multiSpace && option.target.folderId != null
+ ? `${spaceDisplayName(option.space, t)} / ${option.label}`
+ : option.label
+ )
+ )}
+ {filteredOptions.length === 0 && (
+ <p className="text-xs text-foreground/20 text-center py-1.5">
+ {t("notes.context.noResults")}
+ </p>
+ )}
+ </>
+ ) : multiSpace ? (
+ spaces.map((space) => {
+ const spaceOptions = moveOptions.filter(
+ (option) => option.space.id === space.id
+ );
+ if (spaceOptions.length === 0) return null;
+ return (
+ <DropdownMenuSub key={space.id}>
+ <DropdownMenuSubTrigger className={SUB_TRIGGER_CLASS}>
+ <SpaceMenuIcon space={space} />
+ <span className="truncate flex-1">{spaceDisplayName(space, t)}</span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent
+ sideOffset={4}
+ className={cn(SUB_CONTENT_CLASS, "max-h-40 overflow-y-auto")}
+ >
+ {spaceOptions.map((option) =>
+ renderOption(
+ option,
+ option.target.folderId == null
+ ? t("notes.spaces.spaceRoot")
+ : option.label
+ )
+ )}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+ })
+ ) : (
+ moveOptions.map((option) => renderOption(option, option.label))
)}
- {filteredOptions.length === 0 && (
- <p className="text-xs text-foreground/20 text-center py-1.5">
- {t("notes.context.noResults")}
- </p>
- )}
+ </SearchableMoveSubmenu>
+ )}
+ {canDelete && (
+ <>
+ {canMove && <DropdownMenuSeparator />}
+ <DropdownMenuItem
+ onClick={(e) => {
+ e.stopPropagation();
+ onDelete(note.id);
+ }}
+ className={cn(
+ MENU_ITEM_CLASS,
+ "text-destructive focus:text-destructive focus:bg-destructive/10"
+ )}
+ >
+ <Trash2 size={11} />
+ {t("notes.context.delete")}
+ </DropdownMenuItem>
</>
- ) : multiSpace ? (
- spaces.map((space) => {
- const spaceOptions = moveOptions.filter((option) => option.space.id === space.id);
- if (spaceOptions.length === 0) return null;
- return (
- <DropdownMenuSub key={space.id}>
- <DropdownMenuSubTrigger className={SUB_TRIGGER_CLASS}>
- <SpaceMenuIcon space={space} />
- <span className="truncate flex-1">{spaceDisplayName(space, t)}</span>
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent
- sideOffset={4}
- className={cn(SUB_CONTENT_CLASS, "max-h-40 overflow-y-auto")}
- >
- {spaceOptions.map((option) =>
- renderOption(
- option,
- option.target.folderId == null
- ? t("notes.spaces.spaceRoot")
- : option.label
- )
- )}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- );
- })
- ) : (
- moveOptions.map((option) => renderOption(option, option.label))
)}
- </SearchableMoveSubmenu>
- {canDelete && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onClick={(e) => {
- e.stopPropagation();
- onDelete(note.id);
- }}
- className={cn(
- MENU_ITEM_CLASS,
- "text-destructive focus:text-destructive focus:bg-destructive/10"
- )}
- >
- <Trash2 size={11} />
- {t("notes.context.delete")}
- </DropdownMenuItem>
- </>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
</div>
);
}
@@ -1114,11 +1128,12 @@ export default function SpacesTree({
const activeContext = useActiveContext();
const activeNoteId = useActiveNoteId();
const isTreeLoading = useIsTreeLoading();
- const teamCapability = useTeamSpacesCapability();
const isSubscribed = useSyncExternalStore(subscribeIsSubscribed, readIsSubscribed);
const { isSignedIn, user } = useAuth();
+ const teamCapability = useTeamSpacesCapability(isSignedIn);
const { workspaces, loaded: workspacesLoaded } = useWorkspace();
const noteFilesEnabled = useSettingsStore((s) => s.noteFilesEnabled);
+ const shareByCloudId = useShareCache();
const [creatingFolderSpaceId, setCreatingFolderSpaceId] = useState<number | null>(null);
const [newFolderName, setNewFolderName] = useState("");
@@ -1192,10 +1207,29 @@ export default function SpacesTree({
const canManageTeamSpace = (space: SpaceItem): boolean =>
!space.cloud_space_id || canManageSpace(space, workspaceRoleFor(space));
+ // Note-level ACL for cloud-backed personal notes shared with this user.
+ // Without a cache entry (note never opened this session, offline) the
+ // owner fallback keeps today's behavior; once the ACL loads, editors and
+ // viewers lose owner-only actions. Team notes follow space roles instead.
+ const sharedNoteScope = (note: NoteItem) => ({
+ isTeamNote: spacesById.get(note.space_id)?.kind === "team",
+ hasCloudCopy: !!note.cloud_id,
+ });
+ const sharedNotePermission = (note: NoteItem) => {
+ const entry = note.cloud_id ? shareByCloudId.get(note.cloud_id) : null;
+ return resolveNotePermission({
+ cachedPermission: entry?.access?.my_permission,
+ aclState: entry ? "loaded" : "unavailable",
+ isTeamNote: sharedNoteScope(note).isTeamNote,
+ });
+ };
+
// Destructive/scope-changing note and folder actions mirror the server's
- // rules (spacePermissions). Menus, keyboard, drag/drop, and undo all route
- // through these so no path bypasses them; the server enforces regardless.
+ // rules (spacePermissions + per-note ACLs). Menus, keyboard, drag/drop,
+ // and undo all route through these so no path bypasses them; the server
+ // enforces regardless.
const canDeleteNote = (note: NoteItem): boolean => {
+ if (sharedNoteBlocksDelete(sharedNotePermission(note), sharedNoteScope(note))) return false;
const space = spacesById.get(note.space_id);
return canDeleteSpaceNote(note, space, currentUserId, workspaceRoleFor(space));
};
@@ -1203,6 +1237,11 @@ export default function SpacesTree({
const space = spacesById.get(note.space_id);
return canChangeSpaceNoteScope(note, space, currentUserId, workspaceRoleFor(space));
};
+ // Any local re-filing (same-space folder moves included): owner-only on
+ // shared personal notes — a denied folder_id PATCH would fork an
+ // unexpected Personal copy.
+ const canMoveNote = (note: NoteItem): boolean =>
+ canOrganizeSharedNote(sharedNotePermission(note), sharedNoteScope(note));
const canManageFolderDestructive = (folder: FolderItem): boolean => {
const space = spacesById.get(folder.space_id);
return canMoveOrDeleteSpaceFolder(space, workspaceRoleFor(space));
@@ -1303,9 +1342,12 @@ export default function SpacesTree({
return;
}
// Undo restores across spaces outside the normal one-way policy, but it
- // must not bypass scope-change permissions after a role change.
+ // must not bypass move/scope permissions after a role or ACL change.
const current = getNoteFromStore(noteId);
- if (current && current.space_id !== prev.spaceId && !canChangeNoteScope(current)) {
+ if (
+ current &&
+ (!canMoveNote(current) || (current.space_id !== prev.spaceId && !canChangeNoteScope(current)))
+ ) {
toast({ title: t("notes.spaces.couldNotMoveNote"), variant: "destructive" });
return;
}
@@ -1320,6 +1362,9 @@ export default function SpacesTree({
const commitMoveNote = async (noteId: number, target: NoteMoveTarget): Promise<void> => {
const note = getNoteFromStore(noteId);
+ // Defense in depth behind the menu/drag gating: shared personal notes
+ // are re-filed by their owner only.
+ if (note && !canMoveNote(note)) return;
const prev: NoteMoveTarget | null = note
? { spaceId: note.space_id, folderId: note.folder_id }
: null;
@@ -1339,7 +1384,7 @@ export default function SpacesTree({
const requestMoveNote = (noteId: number, target: NoteMoveTarget): void => {
const note = getNoteFromStore(noteId);
- if (!note) return;
+ if (!note || !canMoveNote(note)) return;
if (note.space_id !== target.spaceId) {
if (!allowsCrossSpaceMove(note.space_id, target.spaceId)) return;
if (!canChangeNoteScope(note)) return;
@@ -1400,7 +1445,7 @@ export default function SpacesTree({
canCrossSpaceDrop: (note, target) => {
if (!allowsCrossSpaceMove(note.spaceId, target.spaceId)) return false;
const stored = getNoteFromStore(note.id);
- return !!stored && canChangeNoteScope(stored);
+ return !!stored && canMoveNote(stored) && canChangeNoteScope(stored);
},
onCrossSpaceVeto: (note) => {
const stored = getNoteFromStore(note.id);
@@ -1728,6 +1773,7 @@ export default function SpacesTree({
noteFilesEnabled={noteFilesEnabled}
fileManagerName={fileManagerName}
canDelete={canDeleteNote(note)}
+ canMove={canMoveNote(note)}
onOpen={() => activateRow({ type: "note", key: `n:${note.id}`, note, parentKey, level })}
onMove={(target) => requestMoveNote(note.id, target)}
onCreateFolderAndMove={onCreateFolderAndMove}
diff --git a/src/helpers/cloudApiRequest.js b/src/helpers/cloudApiRequest.js
new file mode 100644
index 000000000..c1bbb012b
--- /dev/null
+++ b/src/helpers/cloudApiRequest.js
@@ -0,0 +1,163 @@
+class AuthContextError extends Error {
+ constructor(message, code = "AUTH_CONTEXT_CHANGED") {
+ super(message);
+ this.name = "AuthContextError";
+ this.code = code;
+ }
+}
+
+function authFailure(error) {
+ return {
+ success: false,
+ error: error.message,
+ code: error.code,
+ status: 0,
+ };
+}
+
+function captureAuthFence(tokenStore, expectedGeneration) {
+ if (!Number.isSafeInteger(expectedGeneration) || expectedGeneration < 0) {
+ throw new AuthContextError(
+ "Authenticated request has no validated credential generation",
+ "AUTH_CONTEXT_UNVALIDATED"
+ );
+ }
+
+ const captured = tokenStore.getState();
+ if (!captured.token) {
+ throw new AuthContextError(
+ "Authenticated request has no bearer credential",
+ "AUTH_CONTEXT_UNVALIDATED"
+ );
+ }
+ if (captured.generation !== expectedGeneration) {
+ throw new AuthContextError("Authentication context changed before request");
+ }
+
+ const assertCurrent = () => {
+ const current = tokenStore.getState();
+ if (current.generation !== captured.generation || current.token !== captured.token) {
+ throw new AuthContextError("Authentication context changed during request");
+ }
+ };
+
+ const awaitBound = async (operation) => {
+ assertCurrent();
+ try {
+ const result = await operation();
+ assertCurrent();
+ return result;
+ } catch (error) {
+ // If both the network operation and credential context changed, the
+ // auth boundary is the actionable failure and must dominate.
+ assertCurrent();
+ throw error;
+ }
+ };
+
+ return {
+ generation: captured.generation,
+ authorization: `Bearer ${captured.token}`,
+ assertCurrent,
+ awaitBound,
+ };
+}
+
+function createCloudApiRequestHandler({
+ getApiUrl,
+ getAppVersion,
+ proxyFetch,
+ tokenStore,
+ logger,
+}) {
+ return async function handleCloudApiRequest(opts) {
+ try {
+ const apiUrl = getApiUrl();
+ if (!apiUrl) throw new Error("OpenWhispr API URL not configured");
+
+ if (typeof opts?.path !== "string" || !opts.path.startsWith("/")) {
+ return { success: false, error: "Invalid API path" };
+ }
+ const targetUrl = new URL(opts.path, apiUrl);
+ if (targetUrl.origin !== new URL(apiUrl).origin) {
+ return { success: false, error: "Invalid API path" };
+ }
+ // Concatenation (not targetUrl) preserves any base path in apiUrl; the
+ // origin check above still rejects protocol-relative "//host" paths.
+ const requestUrl = `${apiUrl}${opts.path}`;
+
+ // Public calls deliberately carry no ambient bearer/cookie. They need
+ // no account fence and remain usable while auth is unresolved.
+ const fence = opts.public ? null : captureAuthFence(tokenStore, opts.expectedAuthGeneration);
+ const method = (opts.method || "GET").toUpperCase();
+ const headers = {
+ "x-openwhispr-version": getAppVersion(),
+ ...(fence ? { Authorization: fence.authorization } : {}),
+ };
+ const fetchOptions = {
+ method,
+ headers,
+ useSessionCookies: false,
+ };
+ if (opts.body !== undefined) {
+ headers["Content-Type"] = "application/json";
+ fetchOptions.body = JSON.stringify(opts.body);
+ }
+
+ const response = fence
+ ? await fence.awaitBound(() => proxyFetch(requestUrl, fetchOptions))
+ : await proxyFetch(requestUrl, fetchOptions);
+
+ if (response.status === 401) {
+ fence?.assertCurrent();
+ return {
+ success: false,
+ error: "Session expired",
+ code: "AUTH_EXPIRED",
+ status: 401,
+ };
+ }
+ if (response.status === 503) {
+ fence?.assertCurrent();
+ return {
+ success: false,
+ error: "Service temporarily unavailable",
+ code: "SERVER_ERROR",
+ status: 503,
+ };
+ }
+
+ const data = fence
+ ? await fence.awaitBound(() => response.json().catch(() => null))
+ : await response.json().catch(() => null);
+
+ if (!response.ok) {
+ fence?.assertCurrent();
+ const message = data?.error?.message || data?.error || `API error: ${response.status}`;
+ return {
+ success: false,
+ error: message,
+ status: response.status,
+ code: data?.code,
+ details: data?.data,
+ };
+ }
+
+ fence?.assertCurrent();
+ return { success: true, data };
+ } catch (error) {
+ if (error instanceof AuthContextError) return authFailure(error);
+ logger?.error?.(
+ `Cloud API request error (${opts?.path}): ${error?.message || error} ${error?.code || ""}`.trim(),
+ error?.stack
+ );
+ return { success: false, error: error?.message || String(error) };
+ }
+ };
+}
+
+module.exports = {
+ AuthContextError,
+ captureAuthFence,
+ createCloudApiRequestHandler,
+};
diff --git a/src/helpers/cloudSyncGuards.js b/src/helpers/cloudSyncGuards.js
index 9826f49f6..497af2ef7 100644
--- a/src/helpers/cloudSyncGuards.js
+++ b/src/helpers/cloudSyncGuards.js
@@ -48,3 +48,12 @@ export function buildNoteUpdatePayload(note, cloudFolderId) {
...(note.cloud_updated_at ? { base_updated_at: note.cloud_updated_at } : {}),
};
}
+
+// POST creates a new cloud identity and therefore has no prior server
+// revision to compare. Forks from older databases can retain a stale base, so
+// derive create payloads explicitly rather than forwarding base_updated_at.
+export function buildNoteCreatePayload(note, cloudFolderId) {
+ const payload = buildNoteUpdatePayload(note, cloudFolderId);
+ delete payload.base_updated_at;
+ return payload;
+}
diff --git a/src/helpers/database.js b/src/helpers/database.js
index be3a7b353..f1dd2a9c8 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -10,6 +10,61 @@ const { app } = require("electron");
// trigger can't 400 the whole sync batch.
const MAX_SNIPPET_TRIGGER_LENGTH = 100;
+// Every local field a note create (POST) carries; the acknowledgement compares
+// these atomically against the pushed snapshot. Must mirror NotePushSnapshot
+// in src/types/electron.ts.
+const NOTE_CREATE_ACK_FIELDS = [
+ "client_note_id",
+ "title",
+ "content",
+ "enhanced_content",
+ "enhancement_prompt",
+ "enhanced_at_content_hash",
+ "note_type",
+ "source_file",
+ "audio_duration_seconds",
+ "folder_id",
+ "space_id",
+ "transcript",
+ "calendar_event_id",
+ "participants",
+ "diarization_enabled",
+ "expected_speaker_count",
+ "created_at",
+ "updated_at",
+ "sync_status",
+ "deleted_at",
+];
+// A PATCH additionally pins the server base and any pending scope retraction.
+const NOTE_PATCH_ACK_FIELDS = [...NOTE_CREATE_ACK_FIELDS, "cloud_updated_at", "left_team"];
+// Must mirror FolderPushSnapshot in src/types/electron.ts.
+const FOLDER_ACK_FIELDS = [
+ "client_folder_id",
+ "name",
+ "is_default",
+ "sort_order",
+ "space_id",
+ "created_at",
+ "updated_at",
+ "sync_status",
+ "deleted_at",
+ "left_team",
+];
+
+function rowMatchesSnapshot(row, snapshot, fields) {
+ return fields.every((field) => {
+ const expected = snapshot[field] === undefined ? null : snapshot[field];
+ return row[field] === expected;
+ });
+}
+
+// An optimistically deleted folder still holds its server-side name until the
+// DELETE is confirmed, so it must keep blocking reuse of that name.
+const FOLDER_NAME_TAKEN_FILTER = `(deleted_at IS NULL OR EXISTS (
+ SELECT 1 FROM optimistic_folder_delete_rows r
+ WHERE r.folder_id = folders.id AND r.entity_type = 'folder'
+))`;
+
class DatabaseManager {
constructor() {
this.db = null;
@@ -505,6 +560,26 @@ class DatabaseManager {
)
`);
+ // A cloud folder delete is optimistic until the API answers. Keep the
+ // exact pre-delete row state in a durable journal so a permission denial
+ // can revive the same folder, notes, speakers, and conversations even
+ // after an app restart. Content stays in its owning tables; the journal
+ // contains only identity and sync metadata.
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS optimistic_folder_delete_rows (
+ folder_id INTEGER NOT NULL,
+ entity_type TEXT NOT NULL,
+ entity_id INTEGER NOT NULL,
+ original_sync_status TEXT,
+ original_deleted_at TEXT,
+ original_updated_at TEXT,
+ PRIMARY KEY (folder_id, entity_type, entity_id)
+ )
+ `);
+ this.db.exec(
+ "CREATE INDEX IF NOT EXISTS idx_optimistic_folder_delete_entity ON optimistic_folder_delete_rows(entity_type, entity_id)"
+ );
+
// Sync columns for notes
try {
this.db.exec("ALTER TABLE notes ADD COLUMN client_note_id TEXT");
@@ -1950,6 +2025,9 @@ class DatabaseManager {
"deleted_at",
"client_note_id",
"cloud_id",
+ "cloud_updated_at",
+ "owner_user_id",
+ "updated_by_user_id",
"left_team",
];
const fields = [];
@@ -2006,7 +2084,10 @@ class DatabaseManager {
if (!trimmed) return { success: false, error: "Folder name is required" };
if (spaceId == null) spaceId = this.getPrivateSpaceId();
const existing = this.db
- .prepare("SELECT id FROM folders WHERE name = ? AND space_id = ? AND deleted_at IS NULL")
+ .prepare(
+ `SELECT id FROM folders
+ WHERE name = ? AND space_id = ? AND ${FOLDER_NAME_TAKEN_FILTER}`
+ )
.get(trimmed, spaceId);
if (existing) return { success: false, error: "A folder with that name already exists" };
const maxOrder = this.db
@@ -2032,25 +2113,116 @@ class DatabaseManager {
deleteFolder(id) {
try {
if (!this.db) throw new Error("Database not initialized");
- const folder = this.db.prepare("SELECT * FROM folders WHERE id = ?").get(id);
+ const folder = this.db
+ .prepare("SELECT * FROM folders WHERE id = ? AND deleted_at IS NULL")
+ .get(id);
if (!folder) return { success: false, error: "Folder not found" };
if (folder.is_default) return { success: false, error: "Cannot delete default folders" };
+ const allChildNotes = "SELECT id FROM notes WHERE folder_id = ?";
+ const childNotes = `${allChildNotes} AND deleted_at IS NULL`;
const noteIds = this.db
- .prepare("SELECT id FROM notes WHERE folder_id = ?")
+ .prepare(childNotes)
.all(id)
.map((row) => row.id);
- // Server cascades note deletes on folder delete; sync pull picks up note tombstones.
- const hardDeleteNotes = this.db.prepare("DELETE FROM notes WHERE folder_id = ?");
- const tombstoneFolder = this.db.prepare(
- "UPDATE folders SET deleted_at = datetime('now'), updated_at = datetime('now'), sync_status = 'pending', name = '__deleted_' || id || '_' || name WHERE id = ?"
- );
- const hardDeleteFolder = this.db.prepare("DELETE FROM folders WHERE id = ?");
this.db.transaction(() => {
- this._deleteSpeakerRowsForNotes("SELECT id FROM notes WHERE folder_id = ?", id);
- hardDeleteNotes.run(id);
- this._retireConversationsWhere("folder_id = ?", [id]);
- if (folder.cloud_id) tombstoneFolder.run(id);
- else hardDeleteFolder.run(id);
+ if (!folder.cloud_id) {
+ // There is no server operation to deny. Local-only folders can
+ // finalize immediately, including their local-only child content.
+ this._retireConversationsWhere(`note_id IN (${allChildNotes})`, [id], {
+ scrubSyncedMessages: true,
+ });
+ this._deleteSpeakerRowsForNotes(allChildNotes, id);
+ this.db.prepare("DELETE FROM notes WHERE folder_id = ?").run(id);
+ this._retireConversationsWhere("folder_id = ?", [id], {
+ scrubSyncedMessages: true,
+ });
+ this.db.prepare("DELETE FROM folders WHERE id = ?").run(id);
+ return;
+ }
+
+ const journal = this.db.prepare(
+ `INSERT OR IGNORE INTO optimistic_folder_delete_rows
+ (folder_id, entity_type, entity_id, original_sync_status,
+ original_deleted_at, original_updated_at)
+ VALUES (?, ?, ?, ?, ?, ?)`
+ );
+ journal.run(
+ id,
+ "folder",
+ id,
+ folder.sync_status ?? "synced",
+ folder.deleted_at ?? null,
+ folder.updated_at ?? null
+ );
+
+ const activeNotes = this.db.prepare(
+ "SELECT id, sync_status, deleted_at, updated_at FROM notes WHERE folder_id = ? AND deleted_at IS NULL"
+ );
+ for (const note of activeNotes.all(id)) {
+ journal.run(
+ id,
+ "note",
+ note.id,
+ note.sync_status ?? "pending",
+ note.deleted_at ?? null,
+ note.updated_at ?? null
+ );
+ }
+
+ // Only live conversations belong to this rollback. A tombstone that
+ // predates the folder action is an independent user-requested delete
+ // and must remain pending on both denial and confirmation.
+ const activeConversations = this.db
+ .prepare(
+ `SELECT id, sync_status, deleted_at, updated_at
+ FROM agent_conversations
+ WHERE deleted_at IS NULL
+ AND (folder_id = ? OR note_id IN (${childNotes}))`
+ )
+ .all(id, id);
+ for (const conversation of activeConversations) {
+ journal.run(
+ id,
+ "conversation",
+ conversation.id,
+ conversation.sync_status ?? "pending",
+ conversation.deleted_at ?? null,
+ conversation.updated_at ?? null
+ );
+ }
+
+ // Keep every child row and message body in place while hiding them
+ // from normal readers and all per-note/per-conversation sync queues.
+ this.db
+ .prepare(
+ `UPDATE notes
+ SET deleted_at = datetime('now'), sync_status = 'folder_delete_pending',
+ updated_at = datetime('now')
+ WHERE id IN (
+ SELECT entity_id FROM optimistic_folder_delete_rows
+ WHERE folder_id = ? AND entity_type = 'note'
+ )`
+ )
+ .run(id);
+ this.db
+ .prepare(
+ `UPDATE agent_conversations
+ SET deleted_at = datetime('now'), sync_status = 'folder_delete_pending',
+ updated_at = datetime('now')
+ WHERE id IN (
+ SELECT entity_id FROM optimistic_folder_delete_rows
+ WHERE folder_id = ? AND entity_type = 'conversation'
+ )`
+ )
+ .run(id);
+ this.db
+ .prepare(
+ `UPDATE folders
+ SET deleted_at = datetime('now'), updated_at = datetime('now'),
+ sync_status = 'pending'
+ WHERE id = ?`
+ )
+ .run(id);
})();
return { success: true, id, noteIds };
} catch (error) {
@@ -2062,14 +2234,17 @@ class DatabaseManager {
renameFolder(id, name) {
try {
if (!this.db) throw new Error("Database not initialized");
- const folder = this.db.prepare("SELECT * FROM folders WHERE id = ?").get(id);
+ const folder = this.db
+ .prepare("SELECT * FROM folders WHERE id = ? AND deleted_at IS NULL")
+ .get(id);
if (!folder) return { success: false, error: "Folder not found" };
if (folder.is_default) return { success: false, error: "Cannot rename default folders" };
const trimmed = (name || "").trim();
if (!trimmed) return { success: false, error: "Folder name is required" };
const existing = this.db
.prepare(
- "SELECT id FROM folders WHERE name = ? AND space_id = ? AND deleted_at IS NULL AND id != ?"
+ `SELECT id FROM folders
+ WHERE name = ? AND space_id = ? AND id != ? AND ${FOLDER_NAME_TAKEN_FILTER}`
)
.get(trimmed, folder.space_id, id);
if (existing) return { success: false, error: "A folder with that name already exists" };
@@ -2089,7 +2264,9 @@ class DatabaseManager {
moveFolderToSpace(id, spaceId) {
try {
if (!this.db) throw new Error("Database not initialized");
- const folder = this.db.prepare("SELECT * FROM folders WHERE id = ?").get(id);
+ const folder = this.db
+ .prepare("SELECT * FROM folders WHERE id = ? AND deleted_at IS NULL")
+ .get(id);
if (!folder) return { success: false, error: "Folder not found" };
if (folder.is_default) return { success: false, error: "Cannot move default folders" };
const space = this.db
@@ -2099,7 +2276,8 @@ class DatabaseManager {
if (folder.space_id === spaceId) return { success: true, folder, notes: [] };
const existing = this.db
.prepare(
- "SELECT id FROM folders WHERE name = ? AND space_id = ? AND deleted_at IS NULL AND id != ?"
+ `SELECT id FROM folders
+ WHERE name = ? AND space_id = ? AND id != ? AND ${FOLDER_NAME_TAKEN_FILTER}`
)
.get(folder.name, spaceId, id);
if (existing) return { success: false, error: "A folder with that name already exists" };
@@ -2340,37 +2518,78 @@ class DatabaseManager {
.run(param);
}
- // Container-scoped agent conversations die with their container — a
- // surviving row would dangle and resurface if SQLite ever reuses the
- // container's rowid. Synced rows tombstone (like deleteAgentConversation)
- // so the next push retires the cloud copy; a hard local delete would let
- // the next pull resurrect the conversation as a global one. Never-synced
- // rows hard-delete: there is no server row to retire, and a bare tombstone
- // would linger forever (getPendingConversationDeletes requires a cloud_id).
- _retireConversationsWhere(containerFilter, params) {
+ // Conversations whose note or container is being removed must not survive
+ // as global chats. Synced rows tombstone (like deleteAgentConversation) so
+ // the next push retires the cloud copy; a hard local delete would let the
+ // next pull resurrect the conversation. Irreversible purge/revocation
+ // callers also scrub their messages, while an optimistic ordinary delete
+ // retains synced messages until the server accepts it. Never-synced rows
+ // hard-delete: there is no server row to retire, and a bare tombstone would
+ // linger forever (getPendingConversationDeletes requires a cloud_id).
+ _retireConversationsWhere(
+ filter,
+ params,
+ { scrubSyncedMessages = false, syncedTombstoneStatus = "pending" } = {}
+ ) {
+ const messageFilter = scrubSyncedMessages ? filter : `cloud_id IS NULL AND (${filter})`;
this.db
.prepare(
- `DELETE FROM agent_messages WHERE conversation_id IN (SELECT id FROM agent_conversations WHERE cloud_id IS NULL AND (${containerFilter}))`
+ `DELETE FROM agent_messages WHERE conversation_id IN (SELECT id FROM agent_conversations WHERE ${messageFilter})`
)
.run(...params);
this.db
- .prepare(`DELETE FROM agent_conversations WHERE cloud_id IS NULL AND (${containerFilter})`)
+ .prepare(`DELETE FROM agent_conversations WHERE cloud_id IS NULL AND (${filter})`)
.run(...params);
this.db
.prepare(
- `UPDATE agent_conversations SET deleted_at = datetime('now'), sync_status = 'pending', updated_at = datetime('now') WHERE cloud_id IS NOT NULL AND deleted_at IS NULL AND (${containerFilter})`
+ `UPDATE agent_conversations SET deleted_at = datetime('now'), sync_status = ?, updated_at = datetime('now') WHERE cloud_id IS NOT NULL AND deleted_at IS NULL AND (${filter})`
+ )
+ .run(syncedTombstoneStatus, ...params);
+ }
+
+ // Account transitions are a local privacy boundary, not a cloud mutation:
+ // no old-account conversation row (including a pending cloud tombstone)
+ // may remain for the next account to see or push.
+ _hardDeleteConversationsWhere(filter, params) {
+ this.db
+ .prepare(
+ `DELETE FROM agent_messages WHERE conversation_id IN (SELECT id FROM agent_conversations WHERE ${filter})`
)
.run(...params);
+ this.db.prepare(`DELETE FROM agent_conversations WHERE ${filter}`).run(...params);
}
- purgeSpace(localSpaceId) {
+ purgeSpace(localSpaceId, options = {}) {
try {
if (!this.db) throw new Error("Database not initialized");
+ const mode = options?.mode ?? "preserve-dirty";
+ if (mode !== "preserve-dirty" && mode !== "destructive") {
+ return { success: false, error: "Invalid purge mode" };
+ }
+ const destructive = mode === "destructive";
const space = this.db.prepare("SELECT * FROM spaces WHERE id = ?").get(localSpaceId);
if (!space) return { success: false, error: "Space not found" };
if (space.kind === "private") {
return { success: false, error: "Cannot purge the private space" };
}
+ if (!destructive) {
+ // Space revocation supersedes any unresolved folder delete. Recover
+ // the held rows first so dirty/local-only children are classified by
+ // their real pre-delete state and can still relocate to Personal.
+ const heldFolderIds = this.db
+ .prepare(
+ `SELECT DISTINCT r.folder_id
+ FROM optimistic_folder_delete_rows r
+ JOIN folders f ON f.id = r.folder_id
+ WHERE r.entity_type = 'folder' AND f.space_id = ?`
+ )
+ .all(localSpaceId)
+ .map((row) => row.folder_id);
+ for (const folderId of heldFolderIds) {
+ const rollback = this.restoreFolderAfterDeniedDelete(folderId);
+ if (!rollback.success) return rollback;
+ }
+ }
const privateSpaceId = this.getPrivateSpaceId();
const { noteIds, folderNames, relocatedNotes } = this.db.transaction(() => {
// Dirty or never-synced notes are the only surviving content (plan
@@ -2378,7 +2597,7 @@ class DatabaseManager {
// space root with forked identities — the server row (if any) stays
// the team's, so the next push re-creates them as personal notes.
let relocated = [];
- if (privateSpaceId != null) {
+ if (!destructive && privateSpaceId != null) {
const preservedIds = this.db
.prepare(
"SELECT id FROM notes WHERE space_id = ? AND deleted_at IS NULL AND (sync_status != 'synced' OR cloud_id IS NULL)"
@@ -2387,10 +2606,17 @@ class DatabaseManager {
.map((row) => row.id);
if (preservedIds.length > 0) {
const relocateNote = this.db.prepare(
- "UPDATE notes SET space_id = ?, folder_id = NULL, client_note_id = ?, cloud_id = NULL, sync_status = 'pending', left_team = 0, is_shared = 0, share_token = NULL, updated_at = datetime('now') WHERE id = ?"
+ "UPDATE notes SET space_id = ?, folder_id = NULL, client_note_id = ?, cloud_id = NULL, cloud_updated_at = NULL, owner_user_id = NULL, updated_by_user_id = NULL, sync_status = 'pending', left_team = 0, is_shared = 0, share_token = NULL, updated_at = datetime('now') WHERE id = ?"
+ );
+ const detachNoteConversation = this.db.prepare(
+ "UPDATE agent_conversations SET space_id = NULL, folder_id = NULL WHERE note_id = ?"
);
for (const noteId of preservedIds) {
relocateNote.run(privateSpaceId, randomUUID(), noteId);
+ // A note chat follows the dirty note fork into Personal. Clear
+ // any redundant team-container scope so the container cleanup
+ // below cannot retire a conversation whose note survived.
+ detachNoteConversation.run(noteId);
}
const getNote = this.db.prepare("SELECT * FROM notes WHERE id = ?");
relocated = preservedIds.map((id) => getNote.get(id));
@@ -2404,6 +2630,32 @@ class DatabaseManager {
.prepare("SELECT name FROM folders WHERE space_id = ?")
.all(localSpaceId)
.map((row) => row.name);
+ // Note chats normally carry only note_id, so container cleanup alone
+ // cannot see them. Retire them while the doomed note rows still
+ // identify the space; relocated dirty-note chats were moved above.
+ if (destructive) {
+ // Account-boundary cleanup must leave neither visible chats nor
+ // cloud-delete tombstones. Match note-only chats and both kinds of
+ // container scope before deleting their parent rows.
+ this._hardDeleteConversationsWhere(
+ `note_id IN (SELECT id FROM notes WHERE space_id = ?)
+ OR space_id = ?
+ OR folder_id IN (SELECT id FROM folders WHERE space_id = ?)`,
+ [localSpaceId, localSpaceId, localSpaceId]
+ );
+ this.db
+ .prepare(
+ `DELETE FROM optimistic_folder_delete_rows
+ WHERE folder_id IN (SELECT id FROM folders WHERE space_id = ?)`
+ )
+ .run(localSpaceId);
+ } else {
+ this._retireConversationsWhere(
+ "note_id IN (SELECT id FROM notes WHERE space_id = ?)",
+ [localSpaceId],
+ { scrubSyncedMessages: true }
+ );
+ }
this._deleteSpeakerRowsForNotes("SELECT id FROM notes WHERE space_id = ?", localSpaceId);
this.db.prepare("DELETE FROM notes WHERE space_id = ?").run(localSpaceId);
// Deleted-note tombstones in other spaces can still reference folders
@@ -2414,10 +2666,13 @@ class DatabaseManager {
"UPDATE notes SET folder_id = NULL WHERE space_id != ? AND folder_id IN (SELECT id FROM folders WHERE space_id = ?)"
)
.run(localSpaceId, localSpaceId);
- this._retireConversationsWhere(
- "space_id = ? OR folder_id IN (SELECT id FROM folders WHERE space_id = ?)",
- [localSpaceId, localSpaceId]
- );
+ if (!destructive) {
+ this._retireConversationsWhere(
+ "space_id = ? OR folder_id IN (SELECT id FROM folders WHERE space_id = ?)",
+ [localSpaceId, localSpaceId],
+ { scrubSyncedMessages: true }
+ );
+ }
this.db.prepare("DELETE FROM folders WHERE space_id = ?").run(localSpaceId);
this.db.prepare("DELETE FROM spaces WHERE id = ?").run(localSpaceId);
return { noteIds: ids, folderNames: names, relocatedNotes: relocated };
@@ -2572,15 +2827,55 @@ class DatabaseManager {
createAgentConversation(title = "Untitled", noteId = null, spaceId = null, folderId = null) {
try {
if (!this.db) throw new Error("Database not initialized");
- const clientConversationId = randomUUID();
- const result = this.db
- .prepare(
- "INSERT INTO agent_conversations (title, note_id, space_id, folder_id, client_conversation_id) VALUES (?, ?, ?, ?, ?)"
- )
- .run(title, noteId, spaceId, folderId, clientConversationId);
- return this.db
- .prepare("SELECT * FROM agent_conversations WHERE id = ?")
- .get(result.lastInsertRowid);
+ return this.db.transaction(() => {
+ let note = null;
+ let space = null;
+ let folder = null;
+
+ if (noteId != null) {
+ note = this.db
+ .prepare(
+ `SELECT n.id, n.space_id, n.folder_id
+ FROM notes n
+ JOIN spaces s ON s.id = n.space_id AND s.deleted_at IS NULL
+ LEFT JOIN folders f ON f.id = n.folder_id AND f.deleted_at IS NULL
+ WHERE n.id = ? AND n.deleted_at IS NULL
+ AND (n.folder_id IS NULL OR (f.id IS NOT NULL AND f.space_id = n.space_id))`
+ )
+ .get(noteId);
+ if (!note) return null;
+ }
+ if (spaceId != null) {
+ space = this.db
+ .prepare("SELECT id FROM spaces WHERE id = ? AND deleted_at IS NULL")
+ .get(spaceId);
+ if (!space) return null;
+ }
+ if (folderId != null) {
+ folder = this.db
+ .prepare(
+ `SELECT f.id, f.space_id
+ FROM folders f
+ JOIN spaces s ON s.id = f.space_id AND s.deleted_at IS NULL
+ WHERE f.id = ? AND f.deleted_at IS NULL`
+ )
+ .get(folderId);
+ if (!folder) return null;
+ }
+ if (folder && spaceId != null && folder.space_id !== spaceId) return null;
+ if (note && spaceId != null && note.space_id !== spaceId) return null;
+ if (note && folderId != null && note.folder_id !== folderId) return null;
+
+ const clientConversationId = randomUUID();
+ const result = this.db
+ .prepare(
+ "INSERT INTO agent_conversations (title, note_id, space_id, folder_id, client_conversation_id) VALUES (?, ?, ?, ?, ?)"
+ )
+ .run(title, noteId, spaceId, folderId, clientConversationId);
+ return this.db
+ .prepare("SELECT * FROM agent_conversations WHERE id = ?")
+ .get(result.lastInsertRowid);
+ })();
} catch (error) {
debugLogger.error("Error creating agent conversation", { error: error.message }, "database");
throw error;
@@ -2596,7 +2891,7 @@ class DatabaseManager {
COUNT(m.id) AS message_count
FROM agent_conversations c
LEFT JOIN agent_messages m ON m.conversation_id = c.id
- WHERE c.note_id = ?
+ WHERE c.note_id = ? AND c.deleted_at IS NULL
GROUP BY c.id
ORDER BY c.updated_at DESC
LIMIT ?`
@@ -2660,7 +2955,7 @@ class DatabaseManager {
try {
if (!this.db) throw new Error("Database not initialized");
const conversation = this.db
- .prepare("SELECT * FROM agent_conversations WHERE id = ?")
+ .prepare("SELECT * FROM agent_conversations WHERE id = ? AND deleted_at IS NULL")
.get(id);
if (!conversation) return null;
const messages = this.db
@@ -2691,12 +2986,12 @@ class DatabaseManager {
updateAgentConversationTitle(id, title) {
try {
if (!this.db) throw new Error("Database not initialized");
- this.db
+ const result = this.db
.prepare(
- "UPDATE agent_conversations SET title = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?"
+ "UPDATE agent_conversations SET title = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND deleted_at IS NULL"
)
.run(title, id);
- return { success: true };
+ return { success: result.changes > 0 };
} catch (error) {
debugLogger.error(
"Error updating agent conversation title",
@@ -2760,18 +3055,27 @@ class DatabaseManager {
addAgentMessage(conversationId, role, content, metadata) {
try {
if (!this.db) throw new Error("Database not initialized");
- const metadataStr = metadata ? JSON.stringify(metadata) : null;
- const result = this.db
- .prepare(
- "INSERT INTO agent_messages (conversation_id, role, content, metadata) VALUES (?, ?, ?, ?)"
- )
- .run(conversationId, role, content, metadataStr);
- this.db
- .prepare("UPDATE agent_conversations SET updated_at = CURRENT_TIMESTAMP WHERE id = ?")
- .run(conversationId);
- return this.db
- .prepare("SELECT * FROM agent_messages WHERE id = ?")
- .get(result.lastInsertRowid);
+ return this.db.transaction(() => {
+ const conversation = this.db
+ .prepare("SELECT id FROM agent_conversations WHERE id = ? AND deleted_at IS NULL")
+ .get(conversationId);
+ if (!conversation) return null;
+
+ const metadataStr = metadata ? JSON.stringify(metadata) : null;
+ const result = this.db
+ .prepare(
+ "INSERT INTO agent_messages (conversation_id, role, content, metadata) VALUES (?, ?, ?, ?)"
+ )
+ .run(conversationId, role, content, metadataStr);
+ this.db
+ .prepare(
+ "UPDATE agent_conversations SET updated_at = CURRENT_TIMESTAMP WHERE id = ? AND deleted_at IS NULL"
+ )
+ .run(conversationId);
+ return this.db
+ .prepare("SELECT * FROM agent_messages WHERE id = ?")
+ .get(result.lastInsertRowid);
+ })();
} catch (error) {
debugLogger.error("Error adding agent message", { error: error.message }, "database");
throw error;
@@ -3283,10 +3587,12 @@ class DatabaseManager {
archiveAgentConversation(id) {
try {
if (!this.db) throw new Error("Database not initialized");
- this.db
- .prepare("UPDATE agent_conversations SET archived_at = CURRENT_TIMESTAMP WHERE id = ?")
+ const result = this.db
+ .prepare(
+ "UPDATE agent_conversations SET archived_at = CURRENT_TIMESTAMP WHERE id = ? AND deleted_at IS NULL"
+ )
.run(id);
- return { success: true };
+ return { success: result.changes > 0 };
} catch (error) {
debugLogger.error("Error archiving agent conversation", { error: error.message }, "database");
throw error;
@@ -3296,8 +3602,12 @@ class DatabaseManager {
unarchiveAgentConversation(id) {
try {
if (!this.db) throw new Error("Database not initialized");
- this.db.prepare("UPDATE agent_conversations SET archived_at = NULL WHERE id = ?").run(id);
- return { success: true };
+ const result = this.db
+ .prepare(
+ "UPDATE agent_conversations SET archived_at = NULL WHERE id = ? AND deleted_at IS NULL"
+ )
+ .run(id);
+ return { success: result.changes > 0 };
} catch (error) {
debugLogger.error(
"Error unarchiving agent conversation",
@@ -3311,8 +3621,10 @@ class DatabaseManager {
updateAgentConversationCloudId(id, cloudId) {
try {
if (!this.db) throw new Error("Database not initialized");
- this.db.prepare("UPDATE agent_conversations SET cloud_id = ? WHERE id = ?").run(cloudId, id);
- return { success: true };
+ const result = this.db
+ .prepare("UPDATE agent_conversations SET cloud_id = ? WHERE id = ? AND deleted_at IS NULL")
+ .run(cloudId, id);
+ return { success: result.changes > 0 };
} catch (error) {
debugLogger.error(
"Error updating agent conversation cloud_id",
@@ -3584,7 +3896,13 @@ class DatabaseManager {
if (!this.db) throw new Error("Database not initialized");
return this.db
.prepare(
- "SELECT * FROM notes WHERE deleted_at IS NOT NULL AND cloud_id IS NOT NULL AND sync_status = 'pending'"
+ `SELECT * FROM notes n
+ WHERE deleted_at IS NOT NULL AND cloud_id IS NOT NULL
+ AND sync_status = 'pending'
+ AND NOT EXISTS (
+ SELECT 1 FROM optimistic_folder_delete_rows r
+ WHERE r.entity_type = 'note' AND r.entity_id = n.id
+ )`
)
.all();
} catch (error) {
@@ -3597,7 +3915,17 @@ class DatabaseManager {
try {
if (!this.db) throw new Error("Database not initialized");
return (
- this.db.prepare("SELECT * FROM notes WHERE client_note_id = ?").get(clientNoteId) || null
+ this.db
+ .prepare(
+ `SELECT n.*,
+ EXISTS (
+ SELECT 1 FROM optimistic_folder_delete_rows r
+ WHERE r.entity_type = 'note' AND r.entity_id = n.id
+ ) AS folder_delete_pending
+ FROM notes n
+ WHERE n.client_note_id = ?`
+ )
+ .get(clientNoteId) || null
);
} catch (error) {
debugLogger.error("Error getting note by client id", { error: error.message }, "database");
@@ -3701,36 +4029,170 @@ class DatabaseManager {
}
}
- // Settles a row after an async push, but only if it wasn't edited while the
- // PATCH was in flight — a mid-flight edit must stay pending so its content
- // still pushes (a blind settle would let the next pass re-PATCH the stale
- // snapshot over a teammate's newer server copy).
- markNoteSyncedIfUnchanged(
+ // A row moved from a team space to Personal while its push was in flight
+ // still owes the server a scope retraction for the returned team-side copy.
+ _leftTeamDuringPush(snapshotSpaceId, currentSpaceId) {
+ const kindOf = this.db.prepare("SELECT kind FROM spaces WHERE id = ?");
+ return kindOf.get(snapshotSpaceId)?.kind === "team" &&
+ kindOf.get(currentSpaceId)?.kind === "private"
+ ? 1
+ : 0;
+ }
+
+ // A create response arrives after an arbitrary network delay. Adopt it only
+ // for the exact local identity that issued the request, and settle only when
+ // every pushed field still matches that request's snapshot. A newer edit
+ // adopts the cloud identity/base but remains pending. Response metadata is
+ // assigned even when null because a fork may still carry the old identity's
+ // base/owner. A purge forks the client_note_id, so the relocated Personal
+ // row is never mutated. Partial migration creates explicitly opt out of
+ // settling so a later full PATCH still delivers fields the POST omitted.
+ acknowledgeNoteCreate(
id,
+ snapshot,
cloudId,
- snapshotUpdatedAt,
cloudUpdatedAt = null,
- ownerUserId = null
+ ownerUserId = null,
+ settleIfUnchanged = true
) {
try {
if (!this.db) throw new Error("Database not initialized");
- // The base advances unconditionally: even when a mid-flight edit keeps
- // the row pending, the PATCH landed — the next push must echo the new
- // server revision or it would 409 against this device's own write.
- // The owner rides along the same way (COALESCE keeps a known owner).
- if (cloudUpdatedAt || ownerUserId) {
+ const expectedClientNoteId = snapshot?.client_note_id;
+ if (!expectedClientNoteId || !cloudId) {
+ return { success: false, outcome: "unresolved" };
+ }
+
+ return this.db.transaction(() => {
+ const current = this.db.prepare("SELECT * FROM notes WHERE id = ?").get(id);
+ if (!current || current.client_note_id !== expectedClientNoteId) {
+ // If the same identity exists under an unexpected numeric row, do
+ // not mutate it and do not authorize deletion of its cloud result.
+ const identityStillExists = this.db
+ .prepare("SELECT 1 FROM notes WHERE client_note_id = ?")
+ .get(expectedClientNoteId);
+ return {
+ success: true,
+ outcome: identityStillExists ? "unresolved" : "orphaned",
+ };
+ }
+
+ if (current.cloud_id) {
+ // Concurrent creates should be idempotent and return the same id.
+ // A different id is ambiguous, though, so never replace the adopted
+ // identity or authorize destructive cleanup in that case.
+ return {
+ success: true,
+ outcome: current.cloud_id === cloudId ? "already-linked" : "unresolved",
+ };
+ }
+
+ const unchanged = rowMatchesSnapshot(current, snapshot, NOTE_CREATE_ACK_FIELDS);
+
+ // If a team note was moved to Personal while POST was in flight, the
+ // returned cloud row still lives in the old team. Mark the attached
+ // identity as owing a scope retraction even when backup is disabled.
+ const leftTeam = this._leftTeamDuringPush(snapshot.space_id, current.space_id);
+
+ if (unchanged && settleIfUnchanged) {
+ this.db
+ .prepare(
+ `UPDATE notes
+ SET sync_status = 'synced', cloud_id = ?, left_team = 0,
+ cloud_updated_at = ?,
+ owner_user_id = ?
+ WHERE id = ? AND client_note_id = ? AND cloud_id IS NULL`
+ )
+ .run(cloudId, cloudUpdatedAt, ownerUserId, id, expectedClientNoteId);
+ return { success: true, outcome: "synced" };
+ }
+
this.db
.prepare(
- "UPDATE notes SET cloud_updated_at = COALESCE(?, cloud_updated_at), owner_user_id = COALESCE(?, owner_user_id) WHERE id = ?"
+ `UPDATE notes
+ SET cloud_id = ?,
+ cloud_updated_at = ?,
+ owner_user_id = ?,
+ sync_status = 'pending',
+ left_team = CASE WHEN ? = 1 THEN 1 ELSE left_team END
+ WHERE id = ? AND client_note_id = ? AND cloud_id IS NULL`
)
- .run(cloudUpdatedAt, ownerUserId, id);
+ .run(cloudId, cloudUpdatedAt, ownerUserId, leftTeam, id, expectedClientNoteId);
+ return { success: true, outcome: "pending" };
+ })();
+ } catch (error) {
+ debugLogger.error("Error acknowledging note create", { error: error.message }, "database");
+ throw error;
+ }
+ }
+
+ // A PATCH response belongs to both the local client identity and the cloud
+ // identity that issued it. Purge/revocation forks in place, so numeric id
+ // alone is never sufficient. An exact pushed snapshot settles; newer work
+ // on the same identity remains pending while advancing its server base.
+ markNoteSyncedIfUnchanged(
+ id,
+ snapshot,
+ expectedCloudId,
+ cloudUpdatedAt = null,
+ ownerUserId = null
+ ) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ if (!snapshot?.client_note_id || !expectedCloudId) {
+ return { success: false, outcome: "identity-changed", changes: 0 };
}
- const result = this.db
- .prepare(
- "UPDATE notes SET sync_status = 'synced', cloud_id = ?, left_team = 0 WHERE id = ? AND updated_at = ?"
- )
- .run(cloudId, id, snapshotUpdatedAt);
- return { success: true, changes: result.changes };
+
+ return this.db.transaction(() => {
+ const current = this.db.prepare("SELECT * FROM notes WHERE id = ?").get(id);
+ if (
+ !current ||
+ current.client_note_id !== snapshot.client_note_id ||
+ current.cloud_id !== expectedCloudId
+ ) {
+ return { success: true, outcome: "identity-changed", changes: 0 };
+ }
+
+ const unchanged = rowMatchesSnapshot(current, snapshot, NOTE_PATCH_ACK_FIELDS);
+ const nextCloudUpdatedAt = (() => {
+ if (!cloudUpdatedAt) return current.cloud_updated_at;
+ if (!current.cloud_updated_at) return cloudUpdatedAt;
+ const incomingMs = Date.parse(cloudUpdatedAt);
+ const currentMs = Date.parse(current.cloud_updated_at);
+ if (Number.isFinite(incomingMs) && Number.isFinite(currentMs)) {
+ return incomingMs > currentMs ? cloudUpdatedAt : current.cloud_updated_at;
+ }
+ return cloudUpdatedAt > current.cloud_updated_at
+ ? cloudUpdatedAt
+ : current.cloud_updated_at;
+ })();
+
+ if (unchanged) {
+ const result = this.db
+ .prepare(
+ `UPDATE notes
+ SET sync_status = 'synced', left_team = 0,
+ cloud_updated_at = ?,
+ owner_user_id = COALESCE(?, owner_user_id)
+ WHERE id = ? AND client_note_id = ? AND cloud_id = ?`
+ )
+ .run(nextCloudUpdatedAt, ownerUserId, id, snapshot.client_note_id, expectedCloudId);
+ return { success: true, outcome: "synced", changes: result.changes };
+ }
+
+ // The delivered PATCH still advances this identity's base; otherwise
+ // the next push would 409 against this device's own write. An older
+ // response arriving out of order must not regress a newer base. Never
+ // run this update for an identity/cloud mismatch.
+ this.db
+ .prepare(
+ `UPDATE notes
+ SET cloud_updated_at = ?,
+ owner_user_id = COALESCE(?, owner_user_id)
+ WHERE id = ? AND client_note_id = ? AND cloud_id = ?`
+ )
+ .run(nextCloudUpdatedAt, ownerUserId, id, snapshot.client_note_id, expectedCloudId);
+ return { success: true, outcome: "pending", changes: 0 };
+ })();
} catch (error) {
debugLogger.error(
"Error marking note synced if unchanged",
@@ -3808,10 +4270,41 @@ class DatabaseManager {
}
}
+ // A denied optimistic delete leaves the server row untouched. Revive the
+ // local tombstone in place so its numeric id, chats and speaker rows survive;
+ // the deliberately old timestamp lets the mandatory snapshot pull replace
+ // it with the authoritative cloud row.
+ restoreNoteAfterDeniedDelete(id) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const result = this.db
+ .prepare(
+ `UPDATE notes
+ SET deleted_at = NULL, sync_status = 'synced',
+ updated_at = '1970-01-01 00:00:00'
+ WHERE id = ? AND deleted_at IS NOT NULL`
+ )
+ .run(id);
+ return { success: result.changes > 0, id };
+ } catch (error) {
+ debugLogger.error(
+ "Error restoring note after denied delete",
+ { error: error.message },
+ "database"
+ );
+ throw error;
+ }
+ }
+
+ // Confirmed cloud deletes and access revocation retire note chats; denied
+ // deletes use the restore method above instead.
hardDeleteNote(id) {
try {
if (!this.db) throw new Error("Database not initialized");
const result = this.db.transaction(() => {
+ this._retireConversationsWhere("note_id = ?", [id], {
+ scrubSyncedMessages: true,
+ });
this._deleteSpeakerRowsForNotes("SELECT id FROM notes WHERE id = ?", id);
return this.db.prepare("DELETE FROM notes WHERE id = ?").run(id);
})();
@@ -3850,7 +4343,12 @@ class DatabaseManager {
if (!this.db) throw new Error("Database not initialized");
return this.db
.prepare(
- "SELECT * FROM folders WHERE deleted_at IS NOT NULL AND cloud_id IS NOT NULL AND sync_status = 'pending'"
+ `SELECT * FROM folders f
+ WHERE deleted_at IS NOT NULL AND cloud_id IS NOT NULL
+ AND (sync_status = 'pending' OR EXISTS (
+ SELECT 1 FROM optimistic_folder_delete_rows r
+ WHERE r.folder_id = f.id AND r.entity_type = 'folder'
+ ))`
)
.all();
} catch (error) {
@@ -3863,19 +4361,168 @@ class DatabaseManager {
}
}
+ // A folder DELETE permission denial means the server changed nothing.
+ // Restore only rows hidden by that exact optimistic operation; independent
+ // note/conversation tombstones were never journaled and remain deleted.
+ restoreFolderAfterDeniedDelete(id) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ return this.db.transaction(() => {
+ const journalRows = this.db
+ .prepare(
+ `SELECT * FROM optimistic_folder_delete_rows
+ WHERE folder_id = ?
+ ORDER BY CASE entity_type
+ WHEN 'folder' THEN 0 WHEN 'note' THEN 1 ELSE 2 END, entity_id`
+ )
+ .all(id);
+ const folderState = journalRows.find((row) => row.entity_type === "folder");
+ if (!folderState) {
+ return { success: false, id, error: "Folder delete rollback not found" };
+ }
+
+ const folder = this.db.prepare("SELECT * FROM folders WHERE id = ?").get(id);
+ if (!folder) {
+ return { success: false, id, error: "Folder row is missing" };
+ }
+ const collision = this.db
+ .prepare(
+ "SELECT id FROM folders WHERE name = ? AND space_id = ? AND deleted_at IS NULL AND id != ?"
+ )
+ .get(folder.name, folder.space_id, id);
+ if (collision) {
+ return { success: false, id, error: "Folder name is no longer available" };
+ }
+
+ const noteStates = journalRows.filter((row) => row.entity_type === "note");
+ const conversationStates = journalRows.filter((row) => row.entity_type === "conversation");
+ const noteExists = this.db.prepare("SELECT 1 FROM notes WHERE id = ?");
+ const conversationExists = this.db.prepare(
+ "SELECT 1 FROM agent_conversations WHERE id = ?"
+ );
+ if (noteStates.some((row) => !noteExists.get(row.entity_id))) {
+ return { success: false, id, error: "A folder note row is missing" };
+ }
+ if (conversationStates.some((row) => !conversationExists.get(row.entity_id))) {
+ return { success: false, id, error: "A folder conversation row is missing" };
+ }
+
+ this.db
+ .prepare(
+ `UPDATE folders
+ SET deleted_at = ?, sync_status = ?, updated_at = ?
+ WHERE id = ?`
+ )
+ .run(
+ folderState.original_deleted_at,
+ folderState.original_sync_status,
+ folderState.original_updated_at,
+ id
+ );
+ const restoreNote = this.db.prepare(
+ `UPDATE notes
+ SET deleted_at = ?, sync_status = ?, updated_at = ?
+ WHERE id = ?`
+ );
+ for (const state of noteStates) {
+ restoreNote.run(
+ state.original_deleted_at,
+ state.original_sync_status,
+ state.original_updated_at,
+ state.entity_id
+ );
+ }
+ const restoreConversation = this.db.prepare(
+ `UPDATE agent_conversations
+ SET deleted_at = ?, sync_status = ?, updated_at = ?
+ WHERE id = ?`
+ );
+ for (const state of conversationStates) {
+ restoreConversation.run(
+ state.original_deleted_at,
+ state.original_sync_status,
+ state.original_updated_at,
+ state.entity_id
+ );
+ }
+
+ this.db.prepare("DELETE FROM optimistic_folder_delete_rows WHERE folder_id = ?").run(id);
+ const getNote = this.db.prepare("SELECT * FROM notes WHERE id = ?");
+ return {
+ success: true,
+ id,
+ folder: this.db.prepare("SELECT * FROM folders WHERE id = ?").get(id),
+ notes: noteStates.map((state) => getNote.get(state.entity_id)),
+ conversationIds: conversationStates.map((state) => state.entity_id),
+ };
+ })();
+ } catch (error) {
+ debugLogger.error(
+ "Error restoring folder after denied delete",
+ { error: error.message },
+ "database"
+ );
+ throw error;
+ }
+ }
+
hardDeleteFolder(id) {
try {
if (!this.db) throw new Error("Database not initialized");
const folder = this.db.prepare("SELECT name FROM folders WHERE id = ?").get(id);
+ if (!folder) return { success: false, id, error: "Folder not found" };
+ const childNotes = "SELECT id FROM notes WHERE folder_id = ?";
+ const heldNotes =
+ "SELECT entity_id FROM optimistic_folder_delete_rows WHERE folder_id = ? AND entity_type = 'note'";
+ const heldConversations =
+ "SELECT entity_id FROM optimistic_folder_delete_rows WHERE folder_id = ? AND entity_type = 'conversation'";
const noteIds = this.db
- .prepare("SELECT id FROM notes WHERE folder_id = ?")
+ .prepare(childNotes)
.all(id)
.map((row) => row.id);
const result = this.db.transaction(() => {
- this._deleteSpeakerRowsForNotes("SELECT id FROM notes WHERE folder_id = ?", id);
- this.db.prepare("DELETE FROM notes WHERE folder_id = ?").run(id);
- this._retireConversationsWhere("folder_id = ?", [id]);
- return this.db.prepare("DELETE FROM folders WHERE id = ?").run(id);
+ // Note chats normally have note_id only. Retire them while the child
+ // rows still identify which chats belong to this folder cleanup, then
+ // handle independently folder-scoped conversations.
+ this._retireConversationsWhere(`note_id IN (${childNotes})`, [id], {
+ scrubSyncedMessages: true,
+ });
+ // The journal is the authoritative ownership record for the
+ // optimistic operation. Use it as well as current parent columns so a
+ // late stale write cannot strand a held row by changing its scope.
+ this.db
+ .prepare(
+ `DELETE FROM agent_messages
+ WHERE conversation_id IN (${heldConversations})`
+ )
+ .run(id);
+ this.db
+ .prepare(
+ `DELETE FROM agent_conversations
+ WHERE cloud_id IS NULL AND id IN (${heldConversations})`
+ )
+ .run(id);
+ this.db
+ .prepare(
+ `UPDATE agent_conversations
+ SET deleted_at = COALESCE(deleted_at, datetime('now')),
+ sync_status = 'pending', updated_at = datetime('now')
+ WHERE cloud_id IS NOT NULL AND id IN (${heldConversations})`
+ )
+ .run(id);
+ this._deleteSpeakerRowsForNotes(childNotes, id);
+ this._deleteSpeakerRowsForNotes(heldNotes, id);
+ this.db.prepare(`DELETE FROM notes WHERE id IN (${heldNotes})`).run(id);
+ this.db.prepare(`DELETE FROM notes WHERE id IN (${childNotes})`).run(id);
+ this._retireConversationsWhere("folder_id = ?", [id], {
+ scrubSyncedMessages: true,
+ });
+ // Held cloud chats now become ordinary pending cloud deletes. Rows
+ // tombstoned before the folder action were never journaled and keep
+ // their existing pending state.
+ const deleted = this.db.prepare("DELETE FROM folders WHERE id = ?").run(id);
+ this.db.prepare("DELETE FROM optimistic_folder_delete_rows WHERE folder_id = ?").run(id);
+ return deleted;
})();
return { success: result.changes > 0, id, noteIds, name: folder?.name ?? null };
} catch (error) {
@@ -3896,6 +4543,19 @@ class DatabaseManager {
relocateRevokedFolder(id, privateSpaceId, preserveFolder = false) {
try {
if (!this.db) throw new Error("Database not initialized");
+ // If access revocation overtakes an optimistic delete, first recover the
+ // held rows so the normal dirty-note preservation rules can classify
+ // them from their real pre-delete state.
+ const held = this.db
+ .prepare(
+ "SELECT 1 FROM optimistic_folder_delete_rows WHERE folder_id = ? AND entity_type = 'folder'"
+ )
+ .get(id);
+ if (held) {
+ const rollback = this.restoreFolderAfterDeniedDelete(id);
+ if (!rollback.success) return rollback;
+ }
+
const folder = this.db.prepare("SELECT * FROM folders WHERE id = ?").get(id);
if (!folder) return { success: false, error: "Folder not found" };
const serverOwnedChildren =
@@ -3911,13 +4571,24 @@ class DatabaseManager {
.prepare(serverOwnedChildren)
.all(id)
.map((row) => row.id);
+ // Note chats have no folder_id, so retire them before deleting the
+ // server-owned notes that prove they belonged to this revoked folder.
+ this._retireConversationsWhere(`note_id IN (${serverOwnedChildren})`, [id], {
+ scrubSyncedMessages: true,
+ });
this._deleteSpeakerRowsForNotes(serverOwnedChildren, id);
this.db.prepare(`DELETE FROM notes WHERE id IN (${serverOwnedChildren})`).run(id);
const relocateNote = this.db.prepare(
- "UPDATE notes SET space_id = ?, folder_id = ?, client_note_id = ?, cloud_id = NULL, sync_status = 'pending', left_team = 0, is_shared = 0, share_token = NULL, updated_at = datetime('now') WHERE id = ?"
+ "UPDATE notes SET space_id = ?, folder_id = ?, client_note_id = ?, cloud_id = NULL, cloud_updated_at = NULL, owner_user_id = NULL, updated_by_user_id = NULL, sync_status = 'pending', left_team = 0, is_shared = 0, share_token = NULL, updated_at = datetime('now') WHERE id = ?"
+ );
+ const detachNoteConversation = this.db.prepare(
+ "UPDATE agent_conversations SET space_id = NULL, folder_id = NULL WHERE note_id = ?"
);
for (const noteId of preservedIds) {
relocateNote.run(privateSpaceId, preserveFolder ? id : null, randomUUID(), noteId);
+ // Note-scoped chats follow a preserved dirty note, not the revoked
+ // team container. Folder-only chats are handled separately below.
+ detachNoteConversation.run(noteId);
}
let preservedFolder = null;
if (preserveFolder) {
@@ -3940,7 +4611,9 @@ class DatabaseManager {
.prepare("UPDATE agent_conversations SET space_id = ? WHERE folder_id = ?")
.run(privateSpaceId, id);
} else {
- this._retireConversationsWhere("folder_id = ?", [id]);
+ this._retireConversationsWhere("folder_id = ?", [id], {
+ scrubSyncedMessages: true,
+ });
this.db.prepare("DELETE FROM folders WHERE id = ?").run(id);
}
const getNote = this.db.prepare("SELECT * FROM notes WHERE id = ?");
@@ -4058,19 +4731,125 @@ class DatabaseManager {
}
}
- // Folder twin of markNoteSyncedIfUnchanged: settles a row after an async
- // PATCH only if it wasn't edited while the PATCH was in flight — a blind
- // settle would mark a newer local rename 'synced', letting the next pull's
- // LWW (server timestamps run later) silently revert it.
- markFolderSyncedIfUnchanged(id, cloudId, snapshotUpdatedAt) {
+ // A folder create or pull-side name adoption may return a canonical client
+ // identity different from the local one. Adopt it only while both identities
+ // captured before the request still occupy this numeric row. A newer rename
+ // or move adopts the cloud identity but remains pending for its follow-up
+ // PATCH; an in-place revocation fork is never touched.
+ acknowledgeFolderCreate(
+ id,
+ snapshot,
+ expectedCloudId,
+ responseClientFolderId,
+ cloudId,
+ cloudUpdatedAt = null
+ ) {
try {
if (!this.db) throw new Error("Database not initialized");
- const result = this.db
- .prepare(
- "UPDATE folders SET sync_status = 'synced', cloud_id = ?, left_team = 0 WHERE id = ? AND updated_at = ?"
- )
- .run(cloudId, id, snapshotUpdatedAt);
- return { success: true, changes: result.changes };
+ if (
+ !snapshot?.client_folder_id ||
+ (expectedCloudId !== null && typeof expectedCloudId !== "string") ||
+ !responseClientFolderId ||
+ !cloudId
+ ) {
+ return { success: false, outcome: "unresolved", changes: 0 };
+ }
+
+ return this.db.transaction(() => {
+ const current = this.db.prepare("SELECT * FROM folders WHERE id = ?").get(id);
+ if (
+ !current ||
+ current.client_folder_id !== snapshot.client_folder_id ||
+ current.cloud_id !== expectedCloudId
+ ) {
+ return { success: true, outcome: "identity-changed", changes: 0 };
+ }
+ if (expectedCloudId !== null && expectedCloudId !== cloudId) {
+ return { success: true, outcome: "unresolved", changes: 0 };
+ }
+ const responseIdentityHolder = this.db
+ .prepare("SELECT id FROM folders WHERE client_folder_id = ? AND id != ?")
+ .get(responseClientFolderId, id);
+ if (responseIdentityHolder) {
+ return { success: true, outcome: "unresolved", changes: 0 };
+ }
+
+ const unchanged = rowMatchesSnapshot(current, snapshot, FOLDER_ACK_FIELDS);
+ const leftTeam = this._leftTeamDuringPush(snapshot.space_id, current.space_id);
+
+ if (unchanged) {
+ const result = this.db
+ .prepare(
+ `UPDATE folders
+ SET client_folder_id = ?, cloud_id = ?, sync_status = 'synced',
+ left_team = 0, updated_at = COALESCE(?, updated_at)
+ WHERE id = ? AND client_folder_id = ? AND cloud_id IS ?`
+ )
+ .run(
+ responseClientFolderId,
+ cloudId,
+ cloudUpdatedAt,
+ id,
+ snapshot.client_folder_id,
+ expectedCloudId
+ );
+ return { success: true, outcome: "synced", changes: result.changes };
+ }
+
+ const result = this.db
+ .prepare(
+ `UPDATE folders
+ SET client_folder_id = ?, cloud_id = ?, sync_status = 'pending',
+ left_team = CASE WHEN ? = 1 THEN 1 ELSE left_team END
+ WHERE id = ? AND client_folder_id = ? AND cloud_id IS ?`
+ )
+ .run(
+ responseClientFolderId,
+ cloudId,
+ leftTeam,
+ id,
+ snapshot.client_folder_id,
+ expectedCloudId
+ );
+ return { success: true, outcome: "pending", changes: result.changes };
+ })();
+ } catch (error) {
+ debugLogger.error("Error acknowledging folder create", { error: error.message }, "database");
+ throw error;
+ }
+ }
+
+ // Folder PATCH twin of the guarded note acknowledgement. Bind the response
+ // to both client and cloud identity and compare every pushed field so a
+ // same-second rename or an in-place revocation fork cannot be settled.
+ markFolderSyncedIfUnchanged(id, snapshot, expectedCloudId) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ if (!snapshot?.client_folder_id || !expectedCloudId) {
+ return { success: false, outcome: "identity-changed", changes: 0 };
+ }
+ return this.db.transaction(() => {
+ const current = this.db.prepare("SELECT * FROM folders WHERE id = ?").get(id);
+ if (
+ !current ||
+ current.client_folder_id !== snapshot.client_folder_id ||
+ current.cloud_id !== expectedCloudId
+ ) {
+ return { success: true, outcome: "identity-changed", changes: 0 };
+ }
+ const unchanged = rowMatchesSnapshot(current, snapshot, FOLDER_ACK_FIELDS);
+ if (!unchanged) {
+ return { success: true, outcome: "pending", changes: 0 };
+ }
+ const result = this.db
+ .prepare(
+ `UPDATE folders
+ SET sync_status = 'synced', left_team = 0
+ WHERE id = ? AND client_folder_id = ? AND cloud_id = ?`
+ )
+ .run(id, snapshot.client_folder_id, expectedCloudId);
+ return { success: true, outcome: "synced", changes: result.changes };
+ })();
} catch (error) {
debugLogger.error(
"Error marking folder synced if unchanged",
@@ -4099,21 +4878,6 @@ class DatabaseManager {
}
}
- adoptFolderIdentity(id, clientFolderId, cloudId, updatedAt) {
- try {
- if (!this.db) throw new Error("Database not initialized");
- this.db
- .prepare(
- "UPDATE folders SET client_folder_id = ?, cloud_id = ?, sync_status = 'synced', left_team = 0, updated_at = COALESCE(?, updated_at) WHERE id = ?"
- )
- .run(clientFolderId, cloudId, updatedAt ?? null, id);
- return { success: true };
- } catch (error) {
- debugLogger.error("Error adopting folder identity", { error: error.message }, "database");
- throw error;
- }
- }
-
getFolderIdMap() {
try {
if (!this.db) throw new Error("Database not initialized");
@@ -4150,7 +4914,13 @@ class DatabaseManager {
if (!this.db) throw new Error("Database not initialized");
return this.db
.prepare(
- "SELECT * FROM agent_conversations WHERE deleted_at IS NOT NULL AND cloud_id IS NOT NULL AND sync_status = 'pending'"
+ `SELECT * FROM agent_conversations c
+ WHERE deleted_at IS NOT NULL AND cloud_id IS NOT NULL
+ AND sync_status = 'pending'
+ AND NOT EXISTS (
+ SELECT 1 FROM optimistic_folder_delete_rows r
+ WHERE r.entity_type = 'conversation' AND r.entity_id = c.id
+ )`
)
.all();
} catch (error) {
@@ -4168,7 +4938,15 @@ class DatabaseManager {
if (!this.db) throw new Error("Database not initialized");
return (
this.db
- .prepare("SELECT * FROM agent_conversations WHERE client_conversation_id = ?")
+ .prepare(
+ `SELECT c.*,
+ EXISTS (
+ SELECT 1 FROM optimistic_folder_delete_rows r
+ WHERE r.entity_type = 'conversation' AND r.entity_id = c.id
+ ) AS folder_delete_pending
+ FROM agent_conversations c
+ WHERE c.client_conversation_id = ?`
+ )
.get(clientId) || null
);
} catch (error) {
@@ -4185,6 +4963,23 @@ class DatabaseManager {
try {
if (!this.db) throw new Error("Database not initialized");
const transaction = this.db.transaction(() => {
+ // A local tombstone represents an unacknowledged delete. A newer live
+ // cloud revision must not cancel that intent or restore message bodies
+ // while the delete retries. Match by cloud id as a fallback for legacy
+ // rows without a client_conversation_id.
+ let existing = null;
+ if (cloudConv.client_conversation_id != null) {
+ existing = this.db
+ .prepare("SELECT * FROM agent_conversations WHERE client_conversation_id = ?")
+ .get(cloudConv.client_conversation_id);
+ }
+ if (!existing && cloudConv.id != null) {
+ existing = this.db
+ .prepare("SELECT * FROM agent_conversations WHERE cloud_id = ?")
+ .get(cloudConv.id);
+ }
+ if (existing?.deleted_at) return existing;
+
const convStmt = this.db.prepare(`
INSERT INTO agent_conversations (client_conversation_id, cloud_id, title, note_id, sync_status, created_at, updated_at)
VALUES (?, ?, ?, ?, 'synced', ?, ?)
@@ -4237,10 +5032,15 @@ class DatabaseManager {
markConversationSynced(id, cloudId) {
try {
if (!this.db) throw new Error("Database not initialized");
- this.db
- .prepare("UPDATE agent_conversations SET sync_status = 'synced', cloud_id = ? WHERE id = ?")
+ const result = this.db
+ .prepare(
+ `UPDATE agent_conversations
+ SET cloud_id = COALESCE(cloud_id, ?),
+ sync_status = CASE WHEN deleted_at IS NULL THEN 'synced' ELSE 'pending' END
+ WHERE id = ?`
+ )
.run(cloudId, id);
- return { success: true };
+ return { success: result.changes > 0 };
} catch (error) {
debugLogger.error("Error marking conversation synced", { error: error.message }, "database");
throw error;
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 80ad67ec0..bf70f5388 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -6,6 +6,7 @@ const crypto = require("crypto");
const debugLogger = require("./debugLogger");
const { BYOK_API_KEYS } = require("../config/secretKeys");
const tokenStore = require("./tokenStore");
+const { createCloudApiRequestHandler } = require("./cloudApiRequest");
const { classifyAndLog } = require("./networkErrors");
const { resolveLocalServerNeeds } = require("./localServerPolicy");
const GnomeShortcutManager = require("./gnomeShortcut");
@@ -528,6 +529,13 @@ class IPCHandlers {
this._setupRetentionCleanup();
this._logDetectedGpus();
this.setupHandlers();
+ // Lives for the app's lifetime; IPCHandlers has no teardown path.
+ tokenStore.subscribe(({ generation, token }) => {
+ this.broadcastToWindows("auth-token-state-changed", {
+ generation,
+ hasToken: Boolean(token),
+ });
+ });
if (this.whisperManager?.serverManager) {
this.whisperManager.serverManager.on("cuda-fallback", () => {
@@ -1550,8 +1558,18 @@ class IPCHandlers {
return result;
});
- ipcMain.handle("db-purge-space", async (event, id) => {
- const result = this.databaseManager.purgeSpace(id);
+ ipcMain.handle("db-purge-space", async (event, id, options) => {
+ if (options?.expectedAuthGeneration !== undefined) {
+ const state = tokenStore.getState();
+ if (!state.token || state.generation !== options.expectedAuthGeneration) {
+ return {
+ success: false,
+ error: "Authentication context changed before account cleanup",
+ code: "AUTH_CONTEXT_CHANGED",
+ };
+ }
+ }
+ const result = this.databaseManager.purgeSpace(id, options);
if (result?.success) {
this.databaseManager.addPendingVectorPurge(result.spaceId);
this.drainPendingVectorPurges();
@@ -1658,7 +1676,7 @@ class IPCHandlers {
content,
metadata
);
- if (this.vectorIndex?.isReady?.()) {
+ if (result && this.vectorIndex?.isReady?.()) {
const conv = this.databaseManager.getAgentConversation(conversationId);
if (conv && conv.messages?.length % 3 === 0) {
this.vectorIndex
@@ -1742,16 +1760,25 @@ class IPCHandlers {
}
return note;
});
- ipcMain.handle("db-mark-note-synced", (_, id, cloudId, cloudUpdatedAt, ownerUserId) =>
- this.databaseManager.markNoteSynced(id, cloudId, cloudUpdatedAt, ownerUserId)
+ ipcMain.handle(
+ "db-acknowledge-note-create",
+ (_, id, snapshot, cloudId, cloudUpdatedAt, ownerUserId, settleIfUnchanged) =>
+ this.databaseManager.acknowledgeNoteCreate(
+ id,
+ snapshot,
+ cloudId,
+ cloudUpdatedAt,
+ ownerUserId,
+ settleIfUnchanged
+ )
);
ipcMain.handle(
"db-mark-note-synced-if-unchanged",
- (_, id, cloudId, snapshotUpdatedAt, cloudUpdatedAt, ownerUserId) =>
+ (_, id, snapshot, expectedCloudId, cloudUpdatedAt, ownerUserId) =>
this.databaseManager.markNoteSyncedIfUnchanged(
id,
- cloudId,
- snapshotUpdatedAt,
+ snapshot,
+ expectedCloudId,
cloudUpdatedAt,
ownerUserId
)
@@ -1768,6 +1795,9 @@ class IPCHandlers {
ipcMain.handle("db-mark-note-sync-error", (_, id) =>
this.databaseManager.markNoteSyncError(id)
);
+ ipcMain.handle("db-restore-note-after-denied-delete", (_, id) =>
+ this.databaseManager.restoreNoteAfterDeniedDelete(id)
+ );
ipcMain.handle("db-hard-delete-note", (_, id) => {
const result = this.databaseManager.hardDeleteNote(id);
if (result?.success) {
@@ -1790,19 +1820,41 @@ class IPCHandlers {
if (folder) setImmediate(() => this.broadcastToWindows("folder-synced", folder));
return folder;
});
- ipcMain.handle("db-mark-folder-synced", (_, id, cloudId) =>
- this.databaseManager.markFolderSynced(id, cloudId)
- );
- ipcMain.handle("db-mark-folder-synced-if-unchanged", (_, id, cloudId, snapshotUpdatedAt) =>
- this.databaseManager.markFolderSyncedIfUnchanged(id, cloudId, snapshotUpdatedAt)
+ ipcMain.handle(
+ "db-acknowledge-folder-create",
+ (_, id, snapshot, expectedCloudId, responseClientFolderId, cloudId, cloudUpdatedAt) =>
+ this.databaseManager.acknowledgeFolderCreate(
+ id,
+ snapshot,
+ expectedCloudId,
+ responseClientFolderId,
+ cloudId,
+ cloudUpdatedAt
+ )
);
- ipcMain.handle("db-adopt-folder-identity", (_, id, clientFolderId, cloudId, updatedAt) =>
- this.databaseManager.adoptFolderIdentity(id, clientFolderId, cloudId, updatedAt)
+ ipcMain.handle("db-mark-folder-synced-if-unchanged", (_, id, snapshot, expectedCloudId) =>
+ this.databaseManager.markFolderSyncedIfUnchanged(id, snapshot, expectedCloudId)
);
ipcMain.handle("db-get-folder-id-map", () => this.databaseManager.getFolderIdMap());
ipcMain.handle("db-get-pending-folder-deletes", () =>
this.databaseManager.getPendingFolderDeletes()
);
+ ipcMain.handle("db-restore-folder-after-denied-delete", (_, id) => {
+ const result = this.databaseManager.restoreFolderAfterDeniedDelete(id);
+ if (result?.success) {
+ for (const note of result.notes ?? []) {
+ this._asyncVectorUpsert(note);
+ this._asyncMirrorWrite(note);
+ }
+ setImmediate(() => {
+ if (result.folder) this.broadcastToWindows("folder-synced", result.folder);
+ for (const note of result.notes ?? []) {
+ this.broadcastToWindows("note-synced", note);
+ }
+ });
+ }
+ return result;
+ });
ipcMain.handle("db-hard-delete-folder", (_, id) => {
const result = this.databaseManager.hardDeleteFolder(id);
if (result?.success) {
@@ -4396,12 +4448,16 @@ class IPCHandlers {
ipcMain.handle("auth-clear-session", async (event) => {
try {
- tokenStore.clear();
+ const tokenState = tokenStore.clear();
const win = BrowserWindow.fromWebContents(event.sender);
if (win) {
await win.webContents.session.clearStorageData({ storages: ["cookies"] });
}
- return { success: true };
+ return {
+ success: tokenState.success,
+ tokenState,
+ ...(tokenState.success ? {} : { error: "Could not clear persisted bearer token" }),
+ };
} catch (error) {
debugLogger.error("Failed to clear auth session:", error);
return { success: false, error: error.message };
@@ -4409,16 +4465,21 @@ class IPCHandlers {
});
ipcMain.handle("auth-get-token", () => tokenStore.get());
- ipcMain.handle("auth-set-token", (_event, token) => {
- if (typeof token === "string" && token) {
- tokenStore.set(token);
- } else {
+ ipcMain.handle("auth-get-token-state", () => tokenStore.getState());
+ ipcMain.handle("auth-set-token", (_event, token, expectedGeneration) => {
+ if (typeof token !== "string" || !token) {
// Surface silent rotation-to-empty so we can spot regressions where the
// renderer thinks it's persisting a token but the value never lands.
debugLogger.debug("auth-set-token ignored: empty or non-string token", {
type: typeof token,
});
+ return {
+ success: false,
+ code: "AUTH_CONTEXT_UNVALIDATED",
+ ...tokenStore.getState(),
+ };
}
+ return tokenStore.setIfGeneration(token, expectedGeneration);
});
// In production, VITE_* env vars aren't available in the main process because
@@ -4514,6 +4575,13 @@ class IPCHandlers {
// Honors system proxy via Electron's net stack. useSessionCookies:false so
// Electron doesn't auto-attach jar cookies on top of our explicit headers.
const proxyFetch = (url, init = {}) => net.fetch(url, { ...init, useSessionCookies: false });
+ const handleCloudApiRequest = createCloudApiRequestHandler({
+ getApiUrl,
+ getAppVersion: () => app.getVersion(),
+ proxyFetch,
+ tokenStore,
+ logger: debugLogger,
+ });
ipcMain.handle("cloud-transcribe", async (event, audioBuffer, opts = {}) => {
try {
@@ -7508,85 +7576,7 @@ class IPCHandlers {
}
});
- ipcMain.handle("cloud-api-request", async (event, opts) => {
- try {
- const apiUrl = getApiUrl();
- if (!apiUrl) throw new Error("OpenWhispr API URL not configured");
-
- if (typeof opts?.path !== "string" || !opts.path.startsWith("/")) {
- return { success: false, error: "Invalid API path" };
- }
- const targetUrl = new URL(opts.path, apiUrl);
- if (targetUrl.origin !== new URL(apiUrl).origin) {
- return { success: false, error: "Invalid API path" };
- }
-
- const authHeader = await getAuthHeader(event);
- // Public endpoints (e.g. invitation previews) work without a session.
- if (!Object.keys(authHeader).length && !opts.public) throw new Error("Not authenticated");
-
- const method = (opts.method || "GET").toUpperCase();
- const sendWith = (header) => {
- // Set after the spread so no caller-provided header can shadow it:
- // the API's adoption tracking keys off this version on every
- // request, authenticated or public, including the 401 cookie retry.
- const headers = { ...header, "x-openwhispr-version": app.getVersion() };
- const fetchOpts = { method, headers };
- if (opts.body !== undefined) {
- headers["Content-Type"] = "application/json";
- fetchOpts.body = JSON.stringify(opts.body);
- }
- return proxyFetch(`${apiUrl}${opts.path}`, fetchOpts);
- };
-
- let response = await sendWith(authHeader);
-
- // A stale bearer is rejected even when the window still holds a valid session
- // cookie; retry with the cookie alone (a tagging-along bearer overrides it).
- if (response.status === 401 && authHeader.Authorization) {
- const cookieHeader = await getSessionCookies(event);
- if (cookieHeader) response = await sendWith({ Cookie: cookieHeader });
- }
-
- if (response.status === 401) {
- return {
- success: false,
- error: "Session expired",
- code: "AUTH_EXPIRED",
- status: 401,
- };
- }
- if (response.status === 503) {
- return {
- success: false,
- error: "Service temporarily unavailable",
- code: "SERVER_ERROR",
- status: 503,
- };
- }
-
- const data = await response.json().catch(() => null);
-
- if (!response.ok) {
- const message = data?.error?.message || data?.error || `API error: ${response.status}`;
- return {
- success: false,
- error: message,
- status: response.status,
- code: data?.code,
- details: data?.data,
- };
- }
-
- return { success: true, data };
- } catch (error) {
- debugLogger.error(
- `Cloud API request error (${opts?.path}): ${error?.message || error} ${error?.code || ""}`.trim(),
- error?.stack
- );
- return { success: false, error: error.message };
- }
- });
+ ipcMain.handle("cloud-api-request", (_event, opts) => handleCloudApiRequest(opts));
ipcMain.handle("get-stt-config", async (event) => {
try {
diff --git a/src/helpers/tokenStore.js b/src/helpers/tokenStore.js
index 2d9a97114..610406892 100644
--- a/src/helpers/tokenStore.js
+++ b/src/helpers/tokenStore.js
@@ -7,6 +7,32 @@ const secretCrypto = require("./secretCrypto");
const tokenFile = () => path.join(app.getPath("userData"), "auth-token.bin");
let cached = null;
+let generation = 0;
+const listeners = new Set();
+
+function state() {
+ return { token: get(), generation };
+}
+
+function publish() {
+ const next = state();
+ for (const listener of listeners) {
+ try {
+ listener(next);
+ } catch (err) {
+ debugLogger.error("tokenStore listener failed", { error: err?.message });
+ }
+ }
+ return next;
+}
+
+function persist(token) {
+ const file = tokenFile();
+ const data = secretCrypto.isAvailable()
+ ? secretCrypto.encrypt(token)
+ : Buffer.from(token, "utf8");
+ fs.writeFileSync(file, data, { mode: 0o600 });
+}
function get() {
if (cached !== null) return cached || null;
@@ -20,7 +46,15 @@ function get() {
}
const { value, needsReencrypt } = secretCrypto.decrypt(buf);
cached = value;
- if (needsReencrypt) set(value);
+ if (needsReencrypt) {
+ try {
+ persist(value);
+ } catch (err) {
+ // Re-encryption is maintenance, not an authentication boundary. Keep
+ // the successfully decrypted credential for this process.
+ debugLogger.error("tokenStore re-encryption failed", { error: err?.message });
+ }
+ }
return cached || null;
} catch (err) {
debugLogger.error("tokenStore.get failed", { error: err?.message });
@@ -30,25 +64,62 @@ function get() {
}
function set(token) {
+ if (typeof token !== "string" || !token) return { success: false, ...state() };
+ const current = get();
+ if (current === token) return { success: true, ...state() };
try {
- const file = tokenFile();
- const data = secretCrypto.isAvailable()
- ? secretCrypto.encrypt(token)
- : Buffer.from(token, "utf8");
- fs.writeFileSync(file, data, { mode: 0o600 });
+ persist(token);
cached = token;
+ generation += 1;
+ return { success: true, ...publish() };
} catch (err) {
debugLogger.error("tokenStore.set failed", { error: err?.message });
+ return { success: false, ...state() };
}
}
+function setIfGeneration(token, expectedGeneration) {
+ if (!Number.isSafeInteger(expectedGeneration) || expectedGeneration !== generation) {
+ return {
+ success: false,
+ code: "AUTH_CONTEXT_CHANGED",
+ ...state(),
+ };
+ }
+ return set(token);
+}
+
function clear() {
cached = "";
+ let success = true;
try {
fs.rmSync(tokenFile(), { force: true });
} catch (err) {
debugLogger.error("tokenStore.clear failed", { error: err?.message });
+ try {
+ // A valid encrypted empty value prevents the old bearer resurfacing on
+ // restart when unlinking is temporarily unavailable.
+ persist("");
+ } catch (persistError) {
+ success = false;
+ debugLogger.error("tokenStore clear fallback failed", {
+ error: persistError?.message,
+ });
+ }
}
+ // Clearing is an explicit credential boundary even when no bearer was
+ // cached (a window may still have an in-flight cookie-era request).
+ generation += 1;
+ return { success, ...publish() };
+}
+
+function getState() {
+ return state();
+}
+
+function subscribe(listener) {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
}
-module.exports = { get, set, clear };
+module.exports = { get, getState, set, setIfGeneration, clear, subscribe };
diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.ts
index 410b9b45b..cdf66718c 100644
--- a/src/hooks/useAuth.ts
+++ b/src/hooks/useAuth.ts
@@ -1,5 +1,30 @@
-import { useEffect, useRef } from "react";
-import { authClient, isWithinGracePeriod } from "../lib/auth";
+import { useEffect, useState, useSyncExternalStore } from "react";
+import { authClient, getGracePeriodRemainingMs, isWithinGracePeriod } from "../lib/auth";
+import {
+ accountScopeHasMandatoryReconciliation,
+ accountScopeRequiresPurge,
+ accountScopeRequiresReconciliation,
+ getAccountScopeRevision,
+ getAccountScopeServerRevision,
+ isAccountScopeRetryWaiting,
+ markAccountScopePurgeRequired,
+ reconcileAccountScope,
+ resetAccountScopeRetry,
+ scheduleAccountScopeRetry,
+ shouldBlockAccountScope,
+ shouldReconcileAccountScope,
+ subscribeAccountScope,
+} from "../lib/authAccountScope";
+import {
+ assertAuthGenerationCurrent,
+ commitValidatedAuthContext,
+ getAuthRequestContextServerSnapshot,
+ getAuthRequestContextSnapshot,
+ getBoundSessionGeneration,
+ getValidatedAuthGeneration,
+ invalidateValidatedAuthContext,
+ subscribeAuthRequestContext,
+} from "../lib/authRequestContext";
import logger from "../utils/logger";
import { useSettingsStore } from "../stores/settingsStore";
@@ -10,36 +35,180 @@ const useStaticSession = () => ({
refetch: async () => null,
});
+async function loadAccountDependencies() {
+ const [
+ { syncService },
+ { invalidateSpaceRoster },
+ { resetForAccountChange },
+ { useWorkspaceStore },
+ ] = await Promise.all([
+ import("../services/SyncService.js"),
+ import("../lib/spaceRosterCache"),
+ import("../stores/noteStore"),
+ import("../stores/workspaceStore"),
+ ]);
+
+ const resetRendererCaches = () => {
+ invalidateSpaceRoster();
+ resetForAccountChange();
+ useWorkspaceStore.getState().resetForAccountChange();
+ };
+ return { syncService, resetRendererCaches };
+}
+
export function useAuth() {
const useSession = authClient?.useSession ?? useStaticSession;
- const { data: session, isPending } = useSession();
- const user = session?.user ?? null;
- const rawIsSignedIn = Boolean(user);
- const gracePeriodActive = isWithinGracePeriod();
+ const { data: ambientSession, isPending, error: sessionError } = useSession();
+ const accountRevision = useSyncExternalStore(
+ subscribeAccountScope,
+ getAccountScopeRevision,
+ getAccountScopeServerRevision
+ );
+ const authContext = useSyncExternalStore(
+ subscribeAuthRequestContext,
+ getAuthRequestContextSnapshot,
+ getAuthRequestContextServerSnapshot
+ );
+ const [, setGraceExpiryTick] = useState(0);
- // Only sync true to the store — signOut() handles setting false via localStorage + reload.
- // Better Auth's useSession() flickers in Electron (renderer can't see the main-process cookie until reload).
- const isSignedIn = rawIsSignedIn || gracePeriodActive;
+ const ambientUser = ambientSession?.user ?? null;
+ const ambientUserId = typeof ambientUser?.id === "string" ? ambientUser.id : null;
+ const boundGeneration =
+ !isPending && !sessionError ? getBoundSessionGeneration(ambientUserId) : null;
+ const sessionIsBound = boundGeneration != null;
+ const resolvedUserId = sessionIsBound ? ambientUserId : null;
+ const rawIsSignedIn = sessionIsBound && Boolean(ambientUser);
+ const gracePeriodActive = sessionIsBound && !rawIsSignedIn && isWithinGracePeriod();
+ const sessionResolutionFailed = Boolean(sessionError) || (!isPending && !sessionIsBound);
+ const requiresReconciliation = sessionIsBound
+ ? accountScopeRequiresReconciliation(resolvedUserId)
+ : true;
+ const cloudContextReady = !rawIsSignedIn || getValidatedAuthGeneration() === boundGeneration;
+ const accountScopeBlocked =
+ isPending ||
+ shouldBlockAccountScope(
+ isPending,
+ gracePeriodActive,
+ rawIsSignedIn,
+ requiresReconciliation,
+ accountScopeHasMandatoryReconciliation(),
+ sessionResolutionFailed
+ ) ||
+ !cloudContextReady;
+ const isSignedIn = rawIsSignedIn && !accountScopeBlocked;
+ // 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
+ // hasValidatedAuthContext either way.
+ const isLoaded = !isPending && (sessionResolutionFailed || !accountScopeBlocked);
- const lastSyncedRef = useRef(false);
+ useEffect(() => {
+ if (!gracePeriodActive) return;
+ const remaining = getGracePeriodRemainingMs();
+ if (remaining <= 0) return;
+ const timer = window.setTimeout(() => setGraceExpiryTick((value) => value + 1), remaining + 10);
+ return () => window.clearTimeout(timer);
+ }, [gracePeriodActive]);
+
+ useEffect(() => {
+ if (!sessionError) return;
+ invalidateValidatedAuthContext();
+ }, [sessionError]);
useEffect(() => {
- if (!isPending && isSignedIn && !lastSyncedRef.current) {
- logger.debug(
- "Auth state sync",
- { isSignedIn, rawIsSignedIn, gracePeriod: gracePeriodActive },
- "auth"
- );
- useSettingsStore.getState().setIsSignedIn(true);
- lastSyncedRef.current = true;
+ if (
+ boundGeneration == null ||
+ !shouldReconcileAccountScope(isPending, gracePeriodActive, rawIsSignedIn, sessionResolutionFailed)
+ ) {
+ return;
}
- }, [isSignedIn, rawIsSignedIn, gracePeriodActive, isPending]);
+ const retryKey = `${boundGeneration}:${resolvedUserId ?? "signed-out"}`;
+ if (isAccountScopeRetryWaiting(retryKey)) return;
+
+ let cancelled = false;
+ const run = async () => {
+ const { syncService, resetRendererCaches } = await loadAccountDependencies();
+ const purgeCachedTeamContent = async () => {
+ resetRendererCaches();
+ let lastError: unknown;
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ try {
+ await syncService.purgeTeamSpacesForSignOut();
+ const spaces = await window.electronAPI?.getSpaces?.();
+ if (!spaces) {
+ throw new Error("Cannot verify account cleanup: database bridge unavailable");
+ }
+ if (!spaces.some((space) => space.kind === "team")) {
+ resetRendererCaches();
+ return;
+ }
+ lastError = new Error("Team content remained after account cleanup");
+ } catch (error) {
+ lastError = error;
+ }
+ }
+ throw lastError ?? new Error("Team content remained after account cleanup");
+ };
+ const verifyCachedTeamContent = async () => {
+ const purged = await syncService.verifyTeamSpacesForAccount(boundGeneration);
+ if (purged > 0) resetRendererCaches();
+ };
+
+ if (accountScopeRequiresPurge(resolvedUserId)) {
+ markAccountScopePurgeRequired();
+ }
+ if (accountScopeRequiresReconciliation(resolvedUserId)) {
+ // This legacy marker drives every already-running SyncService window;
+ // its generation gate provides the immediate fence.
+ useSettingsStore.getState().setIsSignedIn(false);
+ }
+
+ await reconcileAccountScope(resolvedUserId, {
+ purge: purgeCachedTeamContent,
+ verify: verifyCachedTeamContent,
+ });
+
+ if (resolvedUserId) {
+ await assertAuthGenerationCurrent(boundGeneration);
+ if (!commitValidatedAuthContext(boundGeneration, resolvedUserId)) {
+ throw new Error("Resolved session no longer matches the active credential");
+ }
+ if (!cancelled) {
+ logger.debug("Auth state sync", { isSignedIn: true, userId: resolvedUserId }, "auth");
+ useSettingsStore.getState().setIsSignedIn(true);
+ }
+ } else {
+ invalidateValidatedAuthContext();
+ if (!cancelled) useSettingsStore.getState().setIsSignedIn(false);
+ }
+ resetAccountScopeRetry();
+ };
+
+ void run().catch((error) => {
+ invalidateValidatedAuthContext();
+ scheduleAccountScopeRetry(retryKey);
+ logger.error("Account-scoped content reconciliation failed", { error }, "auth");
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [
+ accountRevision,
+ authContext.revision,
+ boundGeneration,
+ gracePeriodActive,
+ isPending,
+ rawIsSignedIn,
+ resolvedUserId,
+ sessionResolutionFailed,
+ ]);
return {
isSignedIn,
- isGracePeriodOnly: !rawIsSignedIn && gracePeriodActive,
- isLoaded: !isPending,
- session,
- user,
+ isGracePeriodOnly: gracePeriodActive,
+ isLoaded,
+ session: sessionIsBound && !accountScopeBlocked ? ambientSession : null,
+ user: isSignedIn ? ambientUser : null,
};
}
diff --git a/src/hooks/useTeamSpacesCapability.ts b/src/hooks/useTeamSpacesCapability.ts
index 1314fd02a..d84d9fb7a 100644
--- a/src/hooks/useTeamSpacesCapability.ts
+++ b/src/hooks/useTeamSpacesCapability.ts
@@ -15,8 +15,11 @@ function hasTeamSpacesDevOverride(): boolean {
* probe (written by the spaces sync pass), the dev override, or locally known
* team spaces.
*/
-export function useTeamSpacesCapability(): boolean {
+export function useTeamSpacesCapability(isSignedIn: boolean): boolean {
const spaces = useSpaces();
const capability = useSyncExternalStore(subscribeTeamSpacesCapability, readTeamSpacesCapability);
- return hasTeamSpacesDevOverride() || capability || spaces.some((space) => space.kind === "team");
+ return (
+ isSignedIn &&
+ (hasTeamSpacesDevOverride() || capability || spaces.some((space) => space.kind === "team"))
+ );
}
diff --git a/src/lib/auth.ts b/src/lib/auth.ts
index 1cd361585..07945cd10 100644
--- a/src/lib/auth.ts
+++ b/src/lib/auth.ts
@@ -2,24 +2,43 @@ import { createAuthClient } from "better-auth/react";
import { ssoClient } from "@better-auth/sso/client";
import { OPENWHISPR_API_URL } from "../config/constants";
import { openExternalLink } from "../utils/externalLinks";
+import {
+ authContextFetch,
+ handleAuthRequestError,
+ handleAuthRequestResponse,
+ handleAuthRequestSuccess,
+ observeAuthTokenStateEvent,
+ prepareAuthRequest,
+} from "./authRequestContext";
export const AUTH_URL = import.meta.env.VITE_AUTH_URL || "https://auth.openwhispr.com";
export const authClient = createAuthClient({
baseURL: AUTH_URL,
plugins: [ssoClient()],
fetchOptions: {
- auth: {
- type: "Bearer",
- token: async () => (await window.electronAPI?.authGetToken?.()) ?? "",
- },
+ credentials: "omit",
+ customFetchImpl: authContextFetch,
headers: { "x-openwhispr-source": "desktop" },
- onSuccess: async (ctx: { response: Response }) => {
- const newToken = ctx.response.headers.get("set-auth-token");
- if (newToken) await window.electronAPI?.authSetToken?.(newToken);
- },
+ onRequest: prepareAuthRequest,
+ onResponse: handleAuthRequestResponse,
+ onSuccess: handleAuthRequestSuccess,
+ onError: handleAuthRequestError,
},
});
+let authRefetchTimer: ReturnType<typeof setTimeout> | null = null;
+window.electronAPI?.onAuthTokenStateChanged?.((state) => {
+ observeAuthTokenStateEvent(state);
+ // Main broadcasts a successful compare-and-set rotation before the IPC
+ // invocation resolves. Deferring avoids aborting the exact session request
+ // that is about to bind the new generation.
+ if (authRefetchTimer) clearTimeout(authRefetchTimer);
+ authRefetchTimer = setTimeout(() => {
+ authRefetchTimer = null;
+ authClient.$store.notify("$sessionSignal");
+ }, 0);
+});
+
export type SocialProvider = "google" | "microsoft" | "apple";
const LAST_SIGN_IN_STORAGE_KEY = "openwhispr:lastSignInTime";
@@ -107,6 +126,12 @@ export function isWithinGracePeriod(): boolean {
return elapsed < GRACE_PERIOD_MS;
}
+export function getGracePeriodRemainingMs(): number {
+ const startedAt = getLastSignInTime();
+ if (!startedAt) return 0;
+ return Math.max(0, GRACE_PERIOD_MS - Math.max(0, Date.now() - startedAt));
+}
+
export async function deleteAccount(): Promise<{ error?: Error }> {
if (!OPENWHISPR_API_URL) {
return { error: new Error("API not configured") };
@@ -132,12 +157,14 @@ export async function deleteAccount(): Promise<{ error?: Error }> {
export async function signOut(): Promise<void> {
try {
await authClient.signOut();
+ } catch {
+ // Local sign-out must still cross a credential generation boundary when
+ // the server is offline; the remote session can expire independently.
+ } finally {
if (window.electronAPI?.authClearSession) {
- await window.electronAPI.authClearSession();
+ await window.electronAPI.authClearSession().catch(() => undefined);
}
markSignedOutState();
- } catch {
- markSignedOutState();
}
}
diff --git a/src/lib/authAccountScope.ts b/src/lib/authAccountScope.ts
new file mode 100644
index 000000000..f14600a68
--- /dev/null
+++ b/src/lib/authAccountScope.ts
@@ -0,0 +1,272 @@
+const ACCOUNT_SCOPE_USER_KEY = "openwhispr:accountScopeUserId";
+const ACCOUNT_SCOPE_VALIDATED_KEY = "openwhispr:accountScopeValidated";
+const ACCOUNT_SCOPE_PURGE_REQUIRED_KEY = "openwhispr:accountScopePurgeRequired";
+
+export type AccountScopeAction = "none" | "remember-user" | "verify" | "purge";
+
+export interface AccountScopeDecisionInput {
+ userId: string | null;
+ previousUserId: string | null;
+ wasSignedIn: boolean;
+ hasTeamSpaces: boolean;
+ scopeValidated: boolean;
+ purgeRequired?: boolean;
+ pendingAction?: "verify" | "purge" | null;
+}
+
+/**
+ * A known user replacement/sign-out requires destructive cleanup. A
+ * marker-less upgrade with a resolved user is different: prove its local
+ * space memberships before deciding which rows are foreign.
+ */
+export function decideAccountScopeAction({
+ userId,
+ previousUserId,
+ wasSignedIn,
+ hasTeamSpaces,
+ scopeValidated,
+ purgeRequired = false,
+ pendingAction = null,
+}: AccountScopeDecisionInput): AccountScopeAction {
+ if (purgeRequired) return "purge";
+ if (pendingAction) return pendingAction;
+ if (!scopeValidated) {
+ if (userId) return "verify";
+ return wasSignedIn || previousUserId != null || hasTeamSpaces ? "purge" : "remember-user";
+ }
+
+ if (!userId) {
+ return wasSignedIn || previousUserId != null || hasTeamSpaces ? "purge" : "none";
+ }
+ if (previousUserId != null && previousUserId !== userId) return "purge";
+ if (!wasSignedIn && (previousUserId != null || hasTeamSpaces)) return "purge";
+ return previousUserId === userId ? "none" : "remember-user";
+}
+
+export interface AccountScopeReconcileCallbacks {
+ purge: () => Promise<void>;
+ verify: () => Promise<void>;
+}
+
+let pendingAction: "verify" | "purge" | null = null;
+let revision = 0;
+let activeReconcile: Promise<void> | null = null;
+let queuedReconcile:
+ | {
+ userId: string | null;
+ callbacks: AccountScopeReconcileCallbacks;
+ }
+ | undefined;
+let retryTimer: ReturnType<typeof setTimeout> | null = null;
+let retryKey: string | null = null;
+let retryAttempt = 0;
+const subscribers = new Set<() => void>();
+
+function storage(): Storage | null {
+ if (typeof window === "undefined") return null;
+ try {
+ return window.localStorage;
+ } catch {
+ return null;
+ }
+}
+
+function notify(): void {
+ revision += 1;
+ subscribers.forEach((subscriber) => subscriber());
+}
+
+function readPreviousUserId(): string | null {
+ return storage()?.getItem(ACCOUNT_SCOPE_USER_KEY) ?? null;
+}
+
+function writePreviousUserId(userId: string | null): void {
+ const target = storage();
+ if (!target) return;
+ if (userId) target.setItem(ACCOUNT_SCOPE_USER_KEY, userId);
+ else target.removeItem(ACCOUNT_SCOPE_USER_KEY);
+}
+
+function markScopeValidated(): void {
+ storage()?.setItem(ACCOUNT_SCOPE_VALIDATED_KEY, "true");
+}
+
+export function getAccountScopeAction(userId: string | null): AccountScopeAction {
+ const target = storage();
+ return decideAccountScopeAction({
+ userId,
+ previousUserId: readPreviousUserId(),
+ wasSignedIn: target?.getItem("isSignedIn") === "true",
+ hasTeamSpaces: target?.getItem("teamSpacesCapability") === "true",
+ scopeValidated: target?.getItem(ACCOUNT_SCOPE_VALIDATED_KEY) === "true",
+ purgeRequired: target?.getItem(ACCOUNT_SCOPE_PURGE_REQUIRED_KEY) === "true",
+ pendingAction,
+ });
+}
+
+export function accountScopeRequiresPurge(userId: string | null): boolean {
+ return getAccountScopeAction(userId) === "purge";
+}
+
+export function accountScopeRequiresReconciliation(userId: string | null): boolean {
+ return getAccountScopeAction(userId) !== "none";
+}
+
+export function accountScopeHasMandatoryReconciliation(): boolean {
+ const target = storage();
+ return (
+ pendingAction != null ||
+ target?.getItem(ACCOUNT_SCOPE_PURGE_REQUIRED_KEY) === "true" ||
+ target?.getItem(ACCOUNT_SCOPE_VALIDATED_KEY) !== "true"
+ );
+}
+
+export function markAccountScopePurgeRequired(): void {
+ storage()?.setItem(ACCOUNT_SCOPE_PURGE_REQUIRED_KEY, "true");
+ notify();
+}
+
+export function subscribeAccountScope(onChange: () => void): () => void {
+ subscribers.add(onChange);
+ const onStorage = (event: StorageEvent) => {
+ if (
+ event.key === ACCOUNT_SCOPE_USER_KEY ||
+ event.key === ACCOUNT_SCOPE_VALIDATED_KEY ||
+ event.key === ACCOUNT_SCOPE_PURGE_REQUIRED_KEY ||
+ event.key === "isSignedIn" ||
+ event.key === "teamSpacesCapability"
+ ) {
+ notify();
+ }
+ };
+ window.addEventListener("storage", onStorage);
+ return () => {
+ subscribers.delete(onChange);
+ window.removeEventListener("storage", onStorage);
+ };
+}
+
+export function getAccountScopeRevision(): number {
+ return revision;
+}
+
+export function getAccountScopeServerRevision(): number {
+ return 0;
+}
+
+async function applyReconcile(
+ userId: string | null,
+ callbacks: AccountScopeReconcileCallbacks
+): Promise<void> {
+ const action = getAccountScopeAction(userId);
+ if (action === "none") return;
+ if (action === "remember-user") {
+ writePreviousUserId(userId);
+ markScopeValidated();
+ storage()?.setItem("isSignedIn", userId ? "true" : "false");
+ notify();
+ return;
+ }
+
+ if (action === "purge") {
+ // Persist before cleanup starts: capability flags may disappear even when
+ // a database operation fails, and must not reopen the gate.
+ markAccountScopePurgeRequired();
+ }
+ pendingAction = action;
+ notify();
+ try {
+ if (action === "purge") await callbacks.purge();
+ else await callbacks.verify();
+ writePreviousUserId(userId);
+ markScopeValidated();
+ const target = storage();
+ target?.setItem("isSignedIn", userId ? "true" : "false");
+ target?.removeItem(ACCOUNT_SCOPE_PURGE_REQUIRED_KEY);
+ } finally {
+ pendingAction = null;
+ notify();
+ }
+}
+
+export function shouldBlockAccountScope(
+ isPending: boolean,
+ gracePeriodActive: boolean,
+ rawIsSignedIn: boolean,
+ requiresReconciliation: boolean,
+ mandatoryReconciliation = false,
+ sessionResolutionFailed = false
+): boolean {
+ if (sessionResolutionFailed) {
+ return !isPending && (requiresReconciliation || mandatoryReconciliation);
+ }
+ return (
+ !isPending &&
+ requiresReconciliation &&
+ (mandatoryReconciliation || !gracePeriodActive || rawIsSignedIn)
+ );
+}
+
+export function shouldReconcileAccountScope(
+ isPending: boolean,
+ gracePeriodActive: boolean,
+ rawIsSignedIn: boolean,
+ sessionResolutionFailed = false
+): boolean {
+ return !isPending && !sessionResolutionFailed && (!gracePeriodActive || rawIsSignedIn);
+}
+
+/**
+ * Serialize reconciliation across all useAuth consumers in this renderer. A
+ * later identity is queued and re-evaluated after the current operation.
+ */
+export function reconcileAccountScope(
+ userId: string | null,
+ callbacks: AccountScopeReconcileCallbacks
+): Promise<void> {
+ queuedReconcile = { userId, callbacks };
+ if (activeReconcile) return activeReconcile;
+
+ activeReconcile = (async () => {
+ while (queuedReconcile) {
+ const next = queuedReconcile;
+ queuedReconcile = undefined;
+ await applyReconcile(next.userId, next.callbacks);
+ }
+ })().finally(() => {
+ activeReconcile = null;
+ });
+ return activeReconcile;
+}
+
+export function accountScopeRetryDelay(attempt: number): number {
+ return Math.min(1000 * 2 ** Math.max(0, attempt), 30_000);
+}
+
+export function scheduleAccountScopeRetry(key: string): void {
+ if (retryKey !== key) {
+ if (retryTimer) clearTimeout(retryTimer);
+ retryTimer = null;
+ retryKey = key;
+ retryAttempt = 0;
+ }
+ if (retryTimer) return;
+ const delay = accountScopeRetryDelay(retryAttempt);
+ retryAttempt += 1;
+ retryTimer = setTimeout(() => {
+ retryTimer = null;
+ notify();
+ }, delay);
+}
+
+export function isAccountScopeRetryWaiting(key: string): boolean {
+ return retryKey === key && retryTimer != null;
+}
+
+export function resetAccountScopeRetry(key?: string): void {
+ if (key && retryKey !== key) return;
+ if (retryTimer) clearTimeout(retryTimer);
+ retryTimer = null;
+ retryKey = null;
+ retryAttempt = 0;
+}
diff --git a/src/lib/authRequestContext.ts b/src/lib/authRequestContext.ts
new file mode 100644
index 000000000..de4d6b4e3
--- /dev/null
+++ b/src/lib/authRequestContext.ts
@@ -0,0 +1,332 @@
+const AUTH_REQUEST_GENERATION = "openWhisprAuthGeneration";
+
+export interface AuthTokenState {
+ token: string | null;
+ generation: number;
+}
+
+export interface AuthTokenStateEvent {
+ generation: number;
+ hasToken: boolean;
+}
+
+export interface RendererAuthContextSnapshot {
+ revision: number;
+ observedGeneration: number | null;
+ hasToken: boolean;
+ sessionResolved: boolean;
+ sessionGeneration: number | null;
+ sessionUserId: string | null;
+ validatedGeneration: number | null;
+}
+
+type AuthRequest = {
+ url?: URL | string;
+ headers?: Headers | Record<string, string>;
+ credentials?: RequestCredentials;
+ [AUTH_REQUEST_GENERATION]?: number;
+};
+
+type AuthSuccessContext = {
+ data?: unknown;
+ response: Response;
+ request: AuthRequest;
+};
+
+let snapshot: RendererAuthContextSnapshot = {
+ revision: 0,
+ observedGeneration: null,
+ hasToken: false,
+ sessionResolved: false,
+ sessionGeneration: null,
+ sessionUserId: null,
+ validatedGeneration: null,
+};
+const subscribers = new Set<() => void>();
+
+function publish(next: Omit<RendererAuthContextSnapshot, "revision">): void {
+ snapshot = { ...next, revision: snapshot.revision + 1 };
+ subscribers.forEach((subscriber) => subscriber());
+}
+
+function update(
+ updater: (current: RendererAuthContextSnapshot) => Omit<RendererAuthContextSnapshot, "revision">
+): void {
+ const next = updater(snapshot);
+ const comparableCurrent = { ...snapshot, revision: 0 };
+ const comparableNext = { ...next, revision: 0 };
+ if (JSON.stringify(comparableCurrent) === JSON.stringify(comparableNext)) return;
+ publish(next);
+}
+
+function validGeneration(value: unknown): value is number {
+ return Number.isSafeInteger(value) && (value as number) >= 0;
+}
+
+function observeState(generation: number, hasToken: boolean): void {
+ if (!validGeneration(generation)) return;
+ update((current) => {
+ const generationChanged = current.observedGeneration !== generation;
+ const dropSession = generationChanged && current.sessionGeneration !== generation;
+ const dropValidated = generationChanged && current.validatedGeneration !== generation;
+ return {
+ ...current,
+ observedGeneration: generation,
+ hasToken,
+ sessionResolved: dropSession ? false : current.sessionResolved,
+ sessionGeneration: dropSession ? null : current.sessionGeneration,
+ sessionUserId: dropSession ? null : current.sessionUserId,
+ validatedGeneration: dropValidated ? null : current.validatedGeneration,
+ };
+ });
+}
+
+export function observeAuthTokenState(state: AuthTokenState): void {
+ observeState(state.generation, Boolean(state.token));
+}
+
+export function observeAuthTokenStateEvent(state: AuthTokenStateEvent): void {
+ observeState(state.generation, state.hasToken);
+}
+
+export function subscribeAuthRequestContext(onChange: () => void): () => void {
+ subscribers.add(onChange);
+ return () => subscribers.delete(onChange);
+}
+
+export function getAuthRequestContextSnapshot(): RendererAuthContextSnapshot {
+ return snapshot;
+}
+
+export function getAuthRequestContextServerSnapshot(): RendererAuthContextSnapshot {
+ return snapshot;
+}
+
+export async function readAuthTokenState(): Promise<AuthTokenState> {
+ const state = await window.electronAPI?.authGetTokenState?.();
+ if (!state || !validGeneration(state.generation)) {
+ throw Object.assign(new Error("Authentication token state is unavailable"), {
+ code: "AUTH_CONTEXT_UNVALIDATED",
+ });
+ }
+ const normalized = {
+ token: typeof state.token === "string" && state.token ? state.token : null,
+ generation: state.generation,
+ };
+ observeAuthTokenState(normalized);
+ return normalized;
+}
+
+function requestGeneration(request: AuthRequest | RequestInit | undefined): number {
+ const generation = (request as AuthRequest | undefined)?.[AUTH_REQUEST_GENERATION];
+ if (!validGeneration(generation)) {
+ throw Object.assign(new Error("Authentication request has no credential generation"), {
+ code: "AUTH_CONTEXT_UNVALIDATED",
+ });
+ }
+ return generation;
+}
+
+function requestAuthorization(request: AuthRequest | RequestInit | undefined): string | null {
+ const headers = new Headers(request?.headers);
+ return headers.get("Authorization");
+}
+
+export async function assertAuthRequestCurrent(
+ request: AuthRequest | RequestInit | undefined
+): Promise<AuthTokenState> {
+ const expectedGeneration = requestGeneration(request);
+ const state = await readAuthTokenState();
+ const expectedAuthorization = state.token ? `Bearer ${state.token}` : null;
+ if (
+ state.generation !== expectedGeneration ||
+ requestAuthorization(request) !== expectedAuthorization
+ ) {
+ throw Object.assign(new Error("Authentication context changed during request"), {
+ code: "AUTH_CONTEXT_CHANGED",
+ });
+ }
+ return state;
+}
+
+export async function prepareAuthRequest<T extends AuthRequest>(request: T): Promise<T> {
+ const state = await readAuthTokenState();
+ const headers = new Headers(request.headers);
+ headers.delete("Cookie");
+ if (state.token) headers.set("Authorization", `Bearer ${state.token}`);
+ else headers.delete("Authorization");
+ return Object.assign(request, {
+ headers,
+ credentials: "omit" as RequestCredentials,
+ [AUTH_REQUEST_GENERATION]: state.generation,
+ });
+}
+
+export async function authContextFetch(
+ input: RequestInfo | URL,
+ init?: RequestInit
+): Promise<Response> {
+ await assertAuthRequestCurrent(init);
+ try {
+ const response = await globalThis.fetch(input, { ...init, credentials: "omit" });
+ await assertAuthRequestCurrent(init);
+ return response;
+ } catch (error) {
+ // A credential boundary is more actionable than a simultaneous network
+ // failure and must prevent stale session data from being trusted.
+ await assertAuthRequestCurrent(init);
+ if (isGetSessionRequest((init ?? {}) as AuthRequest)) {
+ clearSessionResolutionFor(requestGeneration(init));
+ invalidateValidatedAuthContext();
+ }
+ throw error;
+ }
+}
+
+function isGetSessionRequest(request: AuthRequest): boolean {
+ try {
+ const path = new URL(String(request.url), window.location.origin).pathname;
+ return path.endsWith("/get-session");
+ } catch {
+ return false;
+ }
+}
+
+function resolvedUserId(data: unknown): string | null {
+ if (!data || typeof data !== "object") return null;
+ const user = (data as { user?: unknown }).user;
+ if (!user || typeof user !== "object") return null;
+ const id = (user as { id?: unknown }).id;
+ return typeof id === "string" ? id : null;
+}
+
+function recordSessionResolution(generation: number, userId: string | null): void {
+ update((current) => ({
+ ...current,
+ sessionResolved: true,
+ sessionGeneration: generation,
+ sessionUserId: userId,
+ // A stable refresh for the same user may keep its validated lease. A null
+ // or changed-user response stops sync immediately, including while
+ // destructive cleanup waits out the grace period.
+ validatedGeneration:
+ userId &&
+ current.sessionResolved &&
+ current.sessionUserId === userId &&
+ current.sessionGeneration === generation
+ ? current.validatedGeneration
+ : null,
+ }));
+}
+
+function clearSessionResolutionFor(generation: number): void {
+ update((current) => {
+ if (current.sessionGeneration !== generation) return current;
+ return {
+ ...current,
+ sessionResolved: false,
+ sessionGeneration: null,
+ sessionUserId: null,
+ validatedGeneration: null,
+ };
+ });
+}
+
+export async function handleAuthRequestResponse(context: { request: AuthRequest }): Promise<void> {
+ await assertAuthRequestCurrent(context.request);
+}
+
+export async function handleAuthRequestSuccess(context: AuthSuccessContext): Promise<void> {
+ const requestState = await assertAuthRequestCurrent(context.request);
+ let resolvedState = requestState;
+ const rotatedToken = context.response.headers.get("set-auth-token");
+ if (rotatedToken) {
+ const result = await window.electronAPI?.authSetToken?.(rotatedToken, requestState.generation);
+ if (!result?.success || !validGeneration(result.generation)) {
+ throw Object.assign(new Error("Authentication token changed before rotation completed"), {
+ code: result?.code ?? "AUTH_CONTEXT_CHANGED",
+ });
+ }
+ resolvedState = {
+ token: typeof result.token === "string" && result.token ? result.token : null,
+ generation: result.generation,
+ };
+ observeAuthTokenState(resolvedState);
+ }
+ const current = await readAuthTokenState();
+ if (current.generation !== resolvedState.generation || current.token !== resolvedState.token) {
+ throw Object.assign(new Error("Authentication context changed after response"), {
+ code: "AUTH_CONTEXT_CHANGED",
+ });
+ }
+ if (isGetSessionRequest(context.request)) {
+ recordSessionResolution(current.generation, resolvedUserId(context.data));
+ }
+}
+
+export async function handleAuthRequestError(context: { request: AuthRequest }): Promise<void> {
+ const generation = requestGeneration(context.request);
+ await assertAuthRequestCurrent(context.request);
+ if (isGetSessionRequest(context.request)) clearSessionResolutionFor(generation);
+}
+
+export function getBoundSessionGeneration(userId: string | null): number | null {
+ if (
+ !snapshot.sessionResolved ||
+ snapshot.sessionGeneration == null ||
+ snapshot.sessionGeneration !== snapshot.observedGeneration ||
+ snapshot.sessionUserId !== userId
+ ) {
+ return null;
+ }
+ if (userId && !snapshot.hasToken) return null;
+ return snapshot.sessionGeneration;
+}
+
+export function commitValidatedAuthContext(generation: number, userId: string): boolean {
+ if (
+ !validGeneration(generation) ||
+ !userId ||
+ getBoundSessionGeneration(userId) !== generation ||
+ !snapshot.hasToken
+ ) {
+ return false;
+ }
+ update((current) => ({ ...current, validatedGeneration: generation }));
+ return true;
+}
+
+export function invalidateValidatedAuthContext(): void {
+ update((current) => ({ ...current, validatedGeneration: null }));
+}
+
+export function getValidatedAuthGeneration(): number | null {
+ return snapshot.validatedGeneration === snapshot.observedGeneration && snapshot.hasToken
+ ? snapshot.validatedGeneration
+ : null;
+}
+
+export function hasValidatedAuthContext(): boolean {
+ return getValidatedAuthGeneration() != null;
+}
+
+export async function assertAuthGenerationCurrent(generation: number): Promise<void> {
+ const state = await readAuthTokenState();
+ if (state.generation !== generation || !state.token) {
+ throw Object.assign(new Error("Authentication context changed during reconciliation"), {
+ code: "AUTH_CONTEXT_CHANGED",
+ });
+ }
+}
+
+export function resetAuthRequestContextForTests(): void {
+ snapshot = {
+ revision: snapshot.revision + 1,
+ observedGeneration: null,
+ hasToken: false,
+ sessionResolved: false,
+ sessionGeneration: null,
+ sessionUserId: null,
+ validatedGeneration: null,
+ };
+}
diff --git a/src/lib/noteConflictRegistry.ts b/src/lib/noteConflictRegistry.ts
index e7836d320..728069ce8 100644
--- a/src/lib/noteConflictRegistry.ts
+++ b/src/lib/noteConflictRegistry.ts
@@ -55,3 +55,11 @@ export function removeNoteConflictId(clientNoteId: string): void {
// surface the conflict again.
}
}
+
+export function clearNoteConflicts(): void {
+ try {
+ localStorage.removeItem(KEY);
+ } catch {
+ // Account transitions still clear the in-memory copy.
+ }
+}
diff --git a/src/lib/noteEditorPendingSave.ts b/src/lib/noteEditorPendingSave.ts
new file mode 100644
index 000000000..f02cf613f
--- /dev/null
+++ b/src/lib/noteEditorPendingSave.ts
@@ -0,0 +1,37 @@
+export interface PendingNoteSnapshot {
+ title: string;
+ content: string;
+ enhancedContent: string | null;
+ documentPending: boolean;
+ enhancedPending: boolean;
+}
+
+export type PendingNoteUpdates = {
+ title?: string;
+ content?: string;
+ enhanced_content?: string | null;
+};
+
+export function shouldCancelPendingSavesForDelete(
+ activeNoteId: number | null,
+ deletedNoteId: number
+): boolean {
+ return activeNoteId === deletedNoteId;
+}
+
+/**
+ * Build the smallest update that drains the editor's pending save timers.
+ * Keeping this decision separate from the timers makes note-to-note and
+ * note-to-overview navigation share the same lossless behavior.
+ */
+export function buildPendingNoteUpdates(snapshot: PendingNoteSnapshot): PendingNoteUpdates | null {
+ const updates: PendingNoteUpdates = {};
+ if (snapshot.documentPending) {
+ updates.title = snapshot.title;
+ updates.content = snapshot.content;
+ }
+ if (snapshot.enhancedPending) {
+ updates.enhanced_content = snapshot.enhancedContent;
+ }
+ return Object.keys(updates).length > 0 ? updates : null;
+}
diff --git a/src/lib/notePermissions.ts b/src/lib/notePermissions.ts
index f071d1c37..030b01713 100644
--- a/src/lib/notePermissions.ts
+++ b/src/lib/notePermissions.ts
@@ -73,3 +73,44 @@ export function resolveNotePermission({
if (!isTeamNote && aclState === "loading") return null;
return isTeamNote ? "editor" : "owner";
}
+
+interface SharedNoteScope {
+ isTeamNote: boolean;
+ hasCloudCopy: boolean;
+}
+
+// Per-note ACL grants only exist on cloud-backed personal notes: team notes
+// follow space roles (spacePermissions), and rows without a cloud copy belong
+// to this device.
+function aclApplies({ isTeamNote, hasCloudCopy }: SharedNoteScope): boolean {
+ return !isTeamNote && hasCloudCopy;
+}
+
+/**
+ * Whether note-level ACLs veto deleting the note: an editor/viewer of a
+ * directly shared personal note must not be offered Delete just because the
+ * note sits in the (unenforced) private space. Composes with — never
+ * replaces — the space-level rules in spacePermissions.
+ */
+export function sharedNoteBlocksDelete(
+ permission: NotePermission | null,
+ scope: SharedNoteScope
+): boolean {
+ if (!aclApplies(scope)) return false;
+ return !noteCapabilities(permission).canDelete;
+}
+
+/**
+ * Whether the note may be re-filed locally (folder or space moves). Moving
+ * pushes a folder_id/scope PATCH the server denies for non-owners of a shared
+ * personal note — the denial would fork an unexpected Personal copy — so
+ * organization stays owner-only there. Team and local-only notes remain
+ * freely movable (spacePermissions gates cross-space moves).
+ */
+export function canOrganizeNote(
+ permission: NotePermission | null,
+ scope: SharedNoteScope
+): boolean {
+ if (!aclApplies(scope)) return true;
+ return permission === "owner";
+}
diff --git a/src/lib/spacePermissions.ts b/src/lib/spacePermissions.ts
index 24054f6b4..3137ef298 100644
--- a/src/lib/spacePermissions.ts
+++ b/src/lib/spacePermissions.ts
@@ -62,6 +62,9 @@ export function ownsNote(note: NoteOwnership, currentUserId: string | null | und
/**
* Delete a team-space note: the note's owner, a space admin, or a workspace
* owner/admin. Mirrors the server rule — client checks are cosmetic.
+ * Space rules only: a cloud-backed PERSONAL note shared with this user
+ * passes here (private space is unenforced) but may still be vetoed by its
+ * note-level ACL — compose with sharedNoteBlocksDelete (notePermissions).
*/
export function canDeleteSpaceNote(
note: NoteOwnership,
diff --git a/src/services/InvitationsService.ts b/src/services/InvitationsService.ts
index 8a6d19fb6..8b9fa6444 100644
--- a/src/services/InvitationsService.ts
+++ b/src/services/InvitationsService.ts
@@ -40,10 +40,15 @@ async function preview(token: string): Promise<InvitationPreview> {
return res.data;
}
-async function accept(token: string): Promise<{ workspace_id: string; role: string }> {
- const res = await cloudPost<DataWrap<{ workspace_id: string; role: string }>>(
- `/api/invitations/${encodeURIComponent(token)}/accept`
- );
+// team_ids is the authoritative post-accept team list (the invitation may
+// have been edited since it was previewed); optional only because older API
+// responses predate it.
+async function accept(
+ token: string
+): Promise<{ workspace_id: string; role: string; team_ids?: string[] }> {
+ const res = await cloudPost<
+ DataWrap<{ workspace_id: string; role: string; team_ids?: string[] }>
+ >(`/api/invitations/${encodeURIComponent(token)}/accept`);
return res.data;
}
diff --git a/src/services/SpacesService.ts b/src/services/SpacesService.ts
index defbb3599..e76dcb2b4 100644
--- a/src/services/SpacesService.ts
+++ b/src/services/SpacesService.ts
@@ -1,4 +1,11 @@
-import { cloudGet, cloudPost, cloudPatch, cloudDelete, type DataWrap } from "./cloudApi.js";
+import {
+ cloudGet,
+ cloudGetForAuthValidation,
+ cloudPost,
+ cloudPatch,
+ cloudDelete,
+ type DataWrap,
+} from "./cloudApi.js";
import type { SpaceTeamRef, TeamMember, TeamRole } from "../types/electron";
export interface MySpace {
@@ -34,6 +41,11 @@ async function mySpaces(): Promise<MySpace[]> {
return res.data;
}
+async function mySpacesForAuthValidation(generation: number): Promise<MySpace[]> {
+ const res = await cloudGetForAuthValidation<DataWrap<MySpace[]>>("/api/me/spaces", generation);
+ return res.data;
+}
+
async function create(
workspaceId: string,
input: { name: string; emoji?: string | null; description?: string; team_ids: string[] }
@@ -74,6 +86,7 @@ async function listMembers(spaceId: string): Promise<SpaceMemberEntry[]> {
export const SpacesService = {
mySpaces,
+ mySpacesForAuthValidation,
create,
update,
remove,
diff --git a/src/services/SyncService.ts b/src/services/SyncService.ts
index be8dd83ac..3d6bdadf1 100644
--- a/src/services/SyncService.ts
+++ b/src/services/SyncService.ts
@@ -12,7 +12,13 @@ import { SpacesService, type MySpace } from "./SpacesService.js";
import { TranscriptionsService } from "./TranscriptionsService.js";
import { DictionaryService } from "./DictionaryService.js";
import { SnippetService, type CloudSnippetEntry } from "./SnippetService.js";
-import { CloudApiError } from "./cloudApi.js";
+import { CloudApiError, isAuthContextError } from "./cloudApi.js";
+import {
+ assertAuthGenerationCurrent,
+ getValidatedAuthGeneration,
+ hasValidatedAuthContext,
+} from "../lib/authRequestContext";
+import { partitionLocalTeamSpaces } from "./accountSpaceValidation";
import {
clearTeamSpacesCapability,
readTeamSpacesCapability,
@@ -21,10 +27,12 @@ import {
import { readIsSubscribed, subscribeIsSubscribed } from "../lib/subscriptionFlag";
import { readNoteConflictIds } from "../lib/noteConflictRegistry";
import {
+ buildNoteCreatePayload,
buildNoteUpdatePayload,
isCloudEntryNewer,
normalizeTimestamp,
} from "../helpers/cloudSyncGuards.js";
+import { resolveRendererCloudNoteCreate, type CloudNoteCreateResult } from "./noteCreateAck";
import {
clearUpdate404,
isPermissionDenialCode,
@@ -207,6 +215,7 @@ class SyncService {
canSync(): boolean {
return (
+ hasValidatedAuthContext() &&
localStorage.getItem("isSignedIn") === "true" &&
localStorage.getItem("cloudBackupEnabled") === "true" &&
readIsSubscribed()
@@ -216,7 +225,11 @@ class SyncService {
// Sharing a note is per-note consent: shared notes keep syncing even when
// the global cloud-backup toggle is off, as long as the account can sync.
private canSyncSharedNotes(): boolean {
- return localStorage.getItem("isSignedIn") === "true" && readIsSubscribed();
+ return (
+ hasValidatedAuthContext() &&
+ localStorage.getItem("isSignedIn") === "true" &&
+ readIsSubscribed()
+ );
}
// Team-space membership, like sharing, is per-space consent: team content
@@ -254,6 +267,57 @@ class SyncService {
}
}
+ /**
+ * Marker-less upgrades cannot trust legacy auth flags. Under the same lock
+ * as normal sync, prove local team rows against the candidate account and
+ * destructively remove only rows that account cannot access.
+ */
+ async verifyTeamSpacesForAccount(authGeneration: number): Promise<number> {
+ let purgedCount = 0;
+ await navigator.locks.request(SYNC_ALL_LOCK, async () => {
+ await assertAuthGenerationCurrent(authGeneration);
+ let localSpaces = (await window.electronAPI.getSpaces?.()) ?? [];
+ const localTeamSpaces = localSpaces.filter((space) => space.kind === "team");
+ if (localTeamSpaces.length === 0) {
+ await assertAuthGenerationCurrent(authGeneration);
+ return;
+ }
+
+ const remoteSpaces = await SpacesService.mySpacesForAuthValidation(authGeneration);
+ await assertAuthGenerationCurrent(authGeneration);
+ const initial = partitionLocalTeamSpaces(localTeamSpaces, remoteSpaces);
+ for (const space of initial.unproven) {
+ await assertAuthGenerationCurrent(authGeneration);
+ const result = await window.electronAPI.purgeSpace?.(space.id, {
+ mode: "destructive",
+ expectedAuthGeneration: authGeneration,
+ });
+ if (!result?.success) {
+ if (result?.code === "AUTH_CONTEXT_CHANGED") {
+ throw new CloudApiError(
+ result.error ?? "Authentication context changed during account cleanup",
+ 0,
+ result.code
+ );
+ }
+ throw new Error(`Could not remove unverified team space ${space.id}`);
+ }
+ purgedCount += 1;
+ await assertAuthGenerationCurrent(authGeneration);
+ }
+
+ // Re-read instead of trusting best-effort delete results. No membership
+ // marker is committed while an inaccessible row remains.
+ localSpaces = (await window.electronAPI.getSpaces?.()) ?? [];
+ const remaining = partitionLocalTeamSpaces(localSpaces, remoteSpaces);
+ if (remaining.unproven.length > 0) {
+ throw new Error("Unverified team content remained after account validation");
+ }
+ await assertAuthGenerationCurrent(authGeneration);
+ });
+ return purgedCount;
+ }
+
private async purgeAllTeamSpaces(): Promise<void> {
try {
const spaces = (await window.electronAPI.getSpaces?.()) ?? [];
@@ -264,7 +328,7 @@ class SyncService {
// sign-out purge completes, and if that removal ever fails a revoked
// entry self-heals on the next pass instead of locking the space out.
if (space.cloud_space_id) await markSpacePurged(space.cloud_space_id, "revoked");
- await window.electronAPI.purgeSpace?.(space.id);
+ await window.electronAPI.purgeSpace?.(space.id, { mode: "destructive" });
} catch (err) {
console.error(`Purging space ${space.id} on sign-out failed:`, err);
}
@@ -338,6 +402,8 @@ class SyncService {
async syncAll(waitForLock = false): Promise<void> {
const full = this.canSync();
if (!full && !this.canSyncTeamSpaces()) return;
+ const authGeneration = getValidatedAuthGeneration();
+ if (authGeneration == null) return;
// A pass already running may have synced past the data this request covers,
// so flag a re-run instead of dropping it.
if (this.syncing) {
@@ -352,12 +418,17 @@ class SyncService {
// 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;
- teamSpacesReady = await this.syncSpaces();
+ teamSpacesReady = await this.syncSpaces(authGeneration);
+ if (!hasValidatedAuthContext()) return;
if (full) {
await this.syncFolders();
+ if (!hasValidatedAuthContext()) return;
await this.syncNotes();
+ if (!hasValidatedAuthContext()) return;
await this.syncConversations();
+ if (!hasValidatedAuthContext()) return;
await this.syncTranscriptions();
+ if (!hasValidatedAuthContext()) return;
// Edits during the awaits above set dictionaryDirty (syncing is already
// true), so re-run until clean rather than stalling until the next trigger.
do {
@@ -373,8 +444,10 @@ class SyncService {
// consent, D7) and note deletes still propagate so revoked/deleted
// shared notes stop being served (edits flow via debouncedPush).
await this.syncFolders(true);
+ if (!hasValidatedAuthContext()) return;
await this.syncNotes(true);
}
+ if (!hasValidatedAuthContext()) return;
if (teamSpacesReady) {
if (this.teamSpacesRetryTimer) {
clearTimeout(this.teamSpacesRetryTimer);
@@ -391,6 +464,7 @@ class SyncService {
localStorage.setItem("lastSyncedAt", new Date().toISOString());
});
} catch (err) {
+ if (isAuthContextError(err)) return;
console.error("Sync failed:", err);
// A throw mid-pass skips the retry scheduling above; recover discovery
// only when this pass never confirmed the team probe.
@@ -548,11 +622,7 @@ class SyncService {
// over a teammate's newer rename on the next pass. Guarded settle: a
// rename landing mid-flight stays pending so it still pushes (a blind
// settle would let the next pull's LWW revert it).
- await window.electronAPI.markFolderSyncedIfUnchanged?.(
- folder.id,
- folder.cloud_id,
- folder.updated_at
- );
+ await window.electronAPI.markFolderSyncedIfUnchanged?.(folder.id, folder, folder.cloud_id);
} catch (err) {
if (isFolderNameTakenError(err)) {
this.dispatchFolderNameTaken(folder.name);
@@ -590,16 +660,14 @@ class SyncService {
sort_order: folder.sort_order,
...scope,
});
- if (cloud.client_folder_id && cloud.client_folder_id !== folder.client_folder_id) {
- await window.electronAPI.adoptFolderIdentity?.(
- folder.id,
- cloud.client_folder_id,
- cloud.id,
- cloud.updated_at
- );
- } else {
- await window.electronAPI.markFolderSynced?.(folder.id, cloud.id);
- }
+ await window.electronAPI.acknowledgeFolderCreate?.(
+ folder.id,
+ folder,
+ folder.cloud_id,
+ cloud.client_folder_id ?? folder.client_folder_id,
+ cloud.id,
+ cloud.updated_at
+ );
}
// Full note payload for pushes, built on the tested #1290 guard (a
@@ -647,8 +715,8 @@ class SyncService {
// later pass re-PATCH it over a teammate's newer edit.
await window.electronAPI.markNoteSyncedIfUnchanged?.(
note.id,
+ note,
note.cloud_id,
- note.updated_at,
cloud.updated_at,
cloud.user_id ?? null
);
@@ -690,6 +758,13 @@ class SyncService {
// Single-note create shared by the debounced push and the batch-create
// isolation fallback. The returned row carries the server-assigned owner
// (user_id), persisted so the UI can tell "my note" from a teammate's.
+ private async acknowledgeCloudNoteCreate(
+ note: NoteItem,
+ cloud: CloudNoteCreateResult
+ ): Promise<void> {
+ await resolveRendererCloudNoteCreate(note, cloud, (cloudId) => NotesService.delete(cloudId));
+ }
+
private async createCloudNote(
note: NoteItem,
cloudFolderId: string | null,
@@ -697,15 +772,11 @@ class SyncService {
): Promise<void> {
const cloud = await NotesService.create({
client_note_id: note.client_note_id,
- ...this.notePushPayload(note, cloudFolderId, scope),
+ ...buildNoteCreatePayload(note, cloudFolderId),
+ ...scope,
created_at: note.created_at,
});
- await window.electronAPI.markNoteSynced?.(
- note.id,
- cloud.id,
- cloud.updated_at,
- cloud.user_id ?? null
- );
+ await this.acknowledgeCloudNoteCreate(note, cloud);
}
// Batch-create fallback row push: recognized terminal rejections settle the
@@ -720,6 +791,7 @@ class SyncService {
const cloudFolderId = note.folder_id ? (localToCloud.get(note.folder_id) ?? null) : null;
await this.createCloudNote(note, cloudFolderId, scope);
} catch (err) {
+ if (isAuthContextError(err)) throw err;
if (isSpaceAccessError(err) || isPermissionDenialError(err)) {
await this.handleRevokedNotePush(note, ctx);
this.clear404(NOTE_UPDATE_404_KEY, note.client_note_id);
@@ -763,7 +835,12 @@ class SyncService {
: null,
})),
});
- await window.electronAPI.markConversationSynced?.(full.id, cloud.id);
+ const linked = await window.electronAPI.markConversationSynced?.(full.id, cloud.id);
+ if (linked?.success === false) {
+ // The local row was purged while POST was in flight. It cannot carry a
+ // delete tombstone, so retire the orphaned cloud row immediately.
+ await ConversationsService.delete(cloud.id);
+ }
}
}
@@ -788,12 +865,14 @@ class SyncService {
// cloud spaces into local rows, purges spaces that vanished (deleted,
// archived, or every assigned team's membership revoked) and backfills new
// ones.
- private async syncSpaces(): Promise<boolean> {
+ private async syncSpaces(authGeneration: number): Promise<boolean> {
if (!this.canSyncTeamSpaces()) return true;
let cloudSpaces: MySpace[];
try {
cloudSpaces = await SpacesService.mySpaces();
+ await assertAuthGenerationCurrent(authGeneration);
} catch (err) {
+ if (isAuthContextError(err)) throw err;
// 404 = endpoint not deployed yet (rollout probe): remember and skip
// silently so pulls and pushes stay personal-only until a probe succeeds.
if (isHttpStatus(err, 404)) {
@@ -818,7 +897,19 @@ class SyncService {
continue;
}
await markSpacePurged(space.cloud_space_id, "revoked");
- const purged = await window.electronAPI.purgeSpace?.(space.id);
+ const purged = await window.electronAPI.purgeSpace?.(space.id, {
+ expectedAuthGeneration: authGeneration,
+ });
+ if (!purged?.success) {
+ if (purged?.code === "AUTH_CONTEXT_CHANGED") {
+ throw new CloudApiError(
+ purged.error ?? "Authentication context changed before space cleanup",
+ 0,
+ purged.code
+ );
+ }
+ throw new Error(`Could not purge revoked team space ${space.id}`);
+ }
this.dispatchSpaceRevoked(space.name, space.id);
// Never-synced notes survive the purge in Personal (plan §10.6) —
// surface them, never silently.
@@ -1040,11 +1131,11 @@ class SyncService {
this.emitSyncUiEvent("note-update-denied", { title: note.title });
}
- // A note DELETE was denied: only the owner or an admin may delete it. The
- // tombstone can never succeed — drop it and let the caller snapshot-pull
- // the server note back.
+ // A note DELETE was denied: only the owner or an admin may delete it. Revive
+ // the local row in place (preserving chat/speaker identity) and let the
+ // caller snapshot-pull the authoritative server note over it.
private async handleDeniedNoteDelete(note: NoteItem): Promise<void> {
- await window.electronAPI.hardDeleteNote?.(note.id);
+ await window.electronAPI.restoreNoteAfterDeniedDelete?.(note.id);
this.clear404(NOTE_UPDATE_404_KEY, note.client_note_id);
this.emitSyncUiEvent("note-delete-denied", { title: note.title });
}
@@ -1065,20 +1156,26 @@ class SyncService {
// A folder DELETE was denied: only a space admin may delete a space folder.
private async handleDeniedFolderDelete(folder: FolderItem): Promise<void> {
- await window.electronAPI.hardDeleteFolder?.(folder.id);
+ 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"}`
+ );
+ }
this.clear404(FOLDER_UPDATE_404_KEY, folder.client_folder_id);
this.emitSyncUiEvent("folder-delete-denied", { name: folder.name });
}
- // After a permission denial the server rows are unchanged but the local
- // copies were forked away or tombstone-dropped; only a snapshot pull can
- // restore them (their updated_at never moved, so delta pulls skip them).
- // Folders pull before notes so restored notes find their folder; snapshot
- // passes never advance the delta cursors (resolvePullCursorAdvance).
+ // After a permission denial the server rows are unchanged. Rollback first
+ // revives delete tombstones in place (updates may still fork dirty work);
+ // a snapshot then reconciles any server changes that happened meanwhile.
+ // Folders pull before notes so notes always find their parent, and snapshot
+ // passes never advance the ordinary delta cursors.
private async restoreDeniedRows(kind: "note" | "folder"): Promise<void> {
const teamOnly = !this.canSync();
if (kind === "folder") await this.pullFolders(teamOnly, true);
await this.pullNotes(teamOnly, true);
+ if (kind === "folder" && this.canSync()) await this.pullConversations(true);
}
// Sync passes run in whichever window holds the web lock (often the always-
@@ -1148,8 +1245,10 @@ class SyncService {
for (const local of unlinkedDefaults) {
const match = cloudByName.get(local.name.toLowerCase());
if (!match) continue;
- await window.electronAPI.adoptFolderIdentity?.(
+ await window.electronAPI.acknowledgeFolderCreate?.(
local.id,
+ local,
+ local.cloud_id,
match.client_folder_id ?? local.client_folder_id,
match.id,
match.updated_at
@@ -1209,13 +1308,13 @@ class SyncService {
let denied = false;
for (const { folder, scope } of migration) {
try {
- await FoldersService.update(folder.cloud_id!, { name: folder.name, ...scope });
+ await FoldersService.update(folder.cloud_id!, {
+ name: folder.name,
+ sort_order: folder.sort_order,
+ ...scope,
+ });
// Settle only if the row wasn't edited while the PATCH was in flight.
- await window.electronAPI.markFolderSyncedIfUnchanged?.(
- folder.id,
- folder.cloud_id!,
- folder.updated_at
- );
+ await window.electronAPI.markFolderSyncedIfUnchanged?.(folder.id, folder, folder.cloud_id!);
this.clear404(FOLDER_UPDATE_404_KEY, folder.client_folder_id);
} catch (err) {
if (isFolderNameTakenError(err)) {
@@ -1260,19 +1359,14 @@ class SyncService {
}
for (const [i, cloudFolder] of created.entries()) {
const local = fresh[i].folder;
- if (
- cloudFolder.client_folder_id &&
- cloudFolder.client_folder_id !== local.client_folder_id
- ) {
- await window.electronAPI.adoptFolderIdentity?.(
- local.id,
- cloudFolder.client_folder_id,
- cloudFolder.id,
- cloudFolder.updated_at
- );
- } else {
- await window.electronAPI.markFolderSynced?.(local.id, cloudFolder.id);
- }
+ await window.electronAPI.acknowledgeFolderCreate?.(
+ local.id,
+ local,
+ local.cloud_id,
+ cloudFolder.client_folder_id ?? local.client_folder_id,
+ cloudFolder.id,
+ cloudFolder.updated_at
+ );
}
} catch (err) {
if (isSpaceAccessError(err) || isPermissionDenialError(err)) {
@@ -1431,8 +1525,10 @@ class SyncService {
f.name.toLowerCase() === cloudFolder.name.toLowerCase()
);
if (nameMatch) {
- await window.electronAPI.adoptFolderIdentity?.(
+ await window.electronAPI.acknowledgeFolderCreate?.(
nameMatch.id,
+ nameMatch,
+ nameMatch.cloud_id,
cloudFolder.client_folder_id ?? nameMatch.client_folder_id,
cloudFolder.id,
cloudFolder.updated_at
@@ -1564,13 +1660,14 @@ class SyncService {
// Settle only if the row wasn't edited while the PATCH was in flight.
await window.electronAPI.markNoteSyncedIfUnchanged?.(
note.id,
+ note,
note.cloud_id!,
- note.updated_at,
cloud.updated_at,
cloud.user_id ?? null
);
this.clear404(NOTE_UPDATE_404_KEY, note.client_note_id);
} catch (err) {
+ if (isAuthContextError(err)) throw err;
if (isNoteVersionConflictError(err)) {
// Stays pending (not error): unpushed local work awaiting the
// user's Keep/Refresh choice; the registry gate above skips the
@@ -1600,28 +1697,26 @@ class SyncService {
const { created } = await NotesService.batchCreate(
chunk.map(({ note: n, scope }) => ({
client_note_id: n.client_note_id,
- title: n.title,
- content: n.content,
- enhanced_content: n.enhanced_content,
- enhancement_prompt: n.enhancement_prompt,
- enhanced_at_content_hash: n.enhanced_at_content_hash,
- note_type: n.note_type,
- source_file: n.source_file,
- audio_duration_seconds: n.audio_duration_seconds,
- transcript: n.transcript,
- folder_id: n.folder_id ? (localToCloud.get(n.folder_id) ?? undefined) : undefined,
+ ...buildNoteCreatePayload(
+ n,
+ n.folder_id ? (localToCloud.get(n.folder_id) ?? null) : null
+ ),
created_at: n.created_at,
- updated_at: n.updated_at,
...scope,
}))
);
for (const { client_note_id, id: cloudId, updated_at } of created) {
const local = chunk.find(({ note }) => note.client_note_id === client_note_id);
if (local) {
- await window.electronAPI.markNoteSynced?.(local.note.id, cloudId, updated_at ?? null);
+ await this.acknowledgeCloudNoteCreate(local.note, {
+ id: cloudId,
+ client_note_id,
+ updated_at: updated_at ?? null,
+ });
}
}
} catch (err) {
+ if (isAuthContextError(err)) throw err;
if (isSpaceAccessError(err) || isPermissionDenialError(err)) {
// A typed rejection can't be attributed to a row from the batch
// response; create individually so one rejected note settles
@@ -1648,6 +1743,9 @@ class SyncService {
try {
await NotesService.delete(note.cloud_id!);
await window.electronAPI.hardDeleteNote?.(note.id);
+ // A settled tombstone can never resolve a conflict; drop the entry
+ // (and its full cloud snapshot) from the durable registry.
+ await this.settleNoteConflict(note.client_note_id);
} catch (err) {
if (isPermissionDenialError(err)) {
await this.handleDeniedNoteDelete(note);
@@ -1658,6 +1756,7 @@ class SyncService {
// update-404 streak the row carried) instead of retrying forever.
await window.electronAPI.hardDeleteNote?.(note.id);
this.clear404(NOTE_UPDATE_404_KEY, note.client_note_id);
+ await this.settleNoteConflict(note.client_note_id);
} else {
console.error("Note delete sync failed:", err);
}
@@ -1695,6 +1794,12 @@ class SyncService {
cloudNote.client_note_id ?? ""
);
+ // A parent folder DELETE owns this note until its server result is
+ // known. Do not turn a newer live row into a conflict or apply a
+ // per-note tombstone; denial restores the journaled row in place,
+ // while confirmation removes it with the folder cascade.
+ if (local?.folder_delete_pending) continue;
+
// Copy the cloud owner before any last-write-wins decision: an
// unchanged note skips the upsert but must still gain its owner
// (the owner_user_id backfill relies on this).
@@ -1719,8 +1824,12 @@ class SyncService {
await window.electronAPI.hardDeleteNote?.(local.id);
}
// The pull disambiguated a 404'd push as a revocation and resolved
- // it, so the fallback fork must stand down.
+ // it, so the fallback fork must stand down. Any unresolved
+ // conflict is moot too — its cloud copy is no longer ours to
+ // resolve — and settling drops the full snapshot the durable
+ // registry keeps in localStorage.
this.clear404(NOTE_UPDATE_404_KEY, local.client_note_id);
+ await this.settleNoteConflict(local.client_note_id);
continue;
}
@@ -1731,6 +1840,7 @@ class SyncService {
if (local && !local.deleted_at && ctx.byId.get(local.space_id)?.kind === "team") {
if (cloudNote.deleted_at) {
await window.electronAPI.hardDeleteNote?.(local.id);
+ await this.settleNoteConflict(local.client_note_id);
} else if (isCloudEntryNewer(cloudNote.updated_at, local.updated_at)) {
// 'error' rows carry unpushed work just like 'pending' ones.
if (local.sync_status !== "synced") {
@@ -1763,8 +1873,11 @@ class SyncService {
if (local) {
await window.electronAPI.hardDeleteNote?.(local.id);
// A tombstone disambiguates a 404'd push as a genuine delete;
- // drop any streak so it can't resurrect the note in Personal.
+ // drop any streak so it can't resurrect the note in Personal,
+ // and settle any conflict so the registry doesn't keep the
+ // deleted note's full cloud snapshot forever.
this.clear404(NOTE_UPDATE_404_KEY, local.client_note_id);
+ await this.settleNoteConflict(local.client_note_id);
}
continue;
}
@@ -1873,7 +1986,10 @@ class SyncService {
: null,
})),
});
- await window.electronAPI.markConversationSynced?.(conv.id, cloudConv.id);
+ const linked = await window.electronAPI.markConversationSynced?.(conv.id, cloudConv.id);
+ if (linked?.success === false) {
+ await ConversationsService.delete(cloudConv.id);
+ }
} catch (err) {
console.error("Conversation sync failed:", err);
}
@@ -1892,9 +2008,11 @@ class SyncService {
}
}
- private async pullConversations(): Promise<void> {
+ private async pullConversations(snapshot = false): Promise<void> {
try {
- const since = localStorage.getItem("lastSyncedAt.conversations") ?? undefined;
+ const since = snapshot
+ ? undefined
+ : (localStorage.getItem("lastSyncedAt.conversations") ?? undefined);
const syncStartedAt = new Date().toISOString();
let cursor: string | undefined = since;
@@ -1909,11 +2027,21 @@ class SyncService {
cloudConv.client_conversation_id ?? ""
);
+ // As with held notes, the parent folder operation owns this row.
+ // A denial revives it first and immediately runs this same pull in
+ // snapshot mode, so authoritative remote changes are not lost.
+ if (local?.folder_delete_pending) continue;
+
if (cloudConv.deleted_at) {
if (local) await window.electronAPI.hardDeleteConversation?.(local.id);
continue;
}
+ // A live cloud row cannot override a local pending delete. The
+ // tombstone stays queued for push; only the cloud tombstone branch
+ // above is authoritative enough to hard-delete it locally.
+ if (local?.deleted_at) continue;
+
if (!local || isCloudEntryNewer(cloudConv.updated_at, local.updated_at)) {
await window.electronAPI.upsertConversationFromCloud?.(
cloudConv as unknown as Record<string, unknown>,
@@ -1929,7 +2057,7 @@ class SyncService {
cursor = next;
}
- localStorage.setItem("lastSyncedAt.conversations", syncStartedAt);
+ if (!snapshot) localStorage.setItem("lastSyncedAt.conversations", syncStartedAt);
} catch (err) {
console.error("Conversation pull failed:", err);
}
diff --git a/src/services/accountSpaceValidation.ts b/src/services/accountSpaceValidation.ts
new file mode 100644
index 000000000..5bb5439f4
--- /dev/null
+++ b/src/services/accountSpaceValidation.ts
@@ -0,0 +1,38 @@
+import type { SpaceItem } from "../types/electron";
+import type { MySpace } from "./SpacesService";
+
+export interface AccountSpacePartition {
+ proven: SpaceItem[];
+ unproven: SpaceItem[];
+}
+
+function legacyMatch(local: SpaceItem, remoteSpaces: MySpace[]): MySpace | null {
+ if (local.cloud_space_id || !local.cloud_team_id) return null;
+ const candidates = remoteSpaces.filter(
+ (space) => space.teams.length === 1 && space.teams[0]?.id === local.cloud_team_id
+ );
+ return candidates.length === 1 ? candidates[0] : null;
+}
+
+/**
+ * Exact cloud-space identity is authoritative. A pre-spaces row may instead
+ * be proven by one unambiguous remote space whose sole assigned team is the
+ * row's legacy cloud_team_id; broad membership or name matching is unsafe.
+ */
+export function partitionLocalTeamSpaces(
+ localSpaces: SpaceItem[],
+ remoteSpaces: MySpace[]
+): AccountSpacePartition {
+ const remoteIds = new Set(remoteSpaces.map((space) => space.id));
+ const proven: SpaceItem[] = [];
+ const unproven: SpaceItem[] = [];
+
+ for (const local of localSpaces.filter((space) => space.kind === "team")) {
+ const matched =
+ (local.cloud_space_id != null && remoteIds.has(local.cloud_space_id)) ||
+ legacyMatch(local, remoteSpaces) != null;
+ (matched ? proven : unproven).push(local);
+ }
+
+ return { proven, unproven };
+}
diff --git a/src/services/cloudApi.ts b/src/services/cloudApi.ts
index f389d5a91..36af61755 100644
--- a/src/services/cloudApi.ts
+++ b/src/services/cloudApi.ts
@@ -1,3 +1,9 @@
+import {
+ getValidatedAuthGeneration,
+ invalidateValidatedAuthContext,
+ readAuthTokenState,
+} from "../lib/authRequestContext";
+
interface CloudApiResponse<T = unknown> {
success: boolean;
data?: T;
@@ -28,16 +34,25 @@ async function cloudRequest<T = unknown>(
method: string,
path: string,
body?: unknown,
- isPublic?: boolean
+ isPublic?: boolean,
+ authGenerationOverride?: number
): Promise<T> {
+ const expectedAuthGeneration = isPublic
+ ? undefined
+ : (authGenerationOverride ?? getValidatedAuthGeneration() ?? undefined);
const result = (await window.electronAPI?.cloudApiRequest?.({
method,
path,
body,
public: isPublic,
+ expectedAuthGeneration,
})) as (CloudApiResponse<T> & { details?: unknown }) | undefined;
if (!result?.success) {
+ if (result?.code === "AUTH_CONTEXT_CHANGED" || result?.code === "AUTH_CONTEXT_UNVALIDATED") {
+ await readAuthTokenState().catch(() => undefined);
+ invalidateValidatedAuthContext();
+ }
throw new CloudApiError(
result?.error ?? "Cloud API request failed",
result?.status ?? 0,
@@ -53,6 +68,15 @@ export async function cloudGet<T = unknown>(path: string): Promise<T> {
return cloudRequest<T>("GET", path);
}
+// Account-scope bootstrap is the only authenticated call allowed before the
+// candidate session generation has been committed for ordinary sync.
+export async function cloudGetForAuthValidation<T = unknown>(
+ path: "/api/me/spaces",
+ generation: number
+): Promise<T> {
+ return cloudRequest<T>("GET", path, undefined, false, generation);
+}
+
// For endpoints that work without a session (e.g. invitation previews).
export async function cloudGetPublic<T = unknown>(path: string): Promise<T> {
return cloudRequest<T>("GET", path, undefined, true);
@@ -69,3 +93,10 @@ export async function cloudPatch<T = unknown>(path: string, body?: unknown): Pro
export async function cloudDelete<T = unknown>(path: string, body?: unknown): Promise<T> {
return cloudRequest<T>("DELETE", path, body);
}
+
+export function isAuthContextError(error: unknown): boolean {
+ return (
+ error instanceof CloudApiError &&
+ (error.code === "AUTH_CONTEXT_CHANGED" || error.code === "AUTH_CONTEXT_UNVALIDATED")
+ );
+}
diff --git a/src/services/noteCreateAck.ts b/src/services/noteCreateAck.ts
new file mode 100644
index 000000000..a098a94ac
--- /dev/null
+++ b/src/services/noteCreateAck.ts
@@ -0,0 +1,156 @@
+import type { NoteCreateAckResult, NoteCreateSnapshot, NoteItem } from "../types/electron";
+
+export interface CloudNoteCreateResult {
+ id: string;
+ client_note_id: string | null;
+ updated_at?: string | null;
+ user_id?: string | null;
+}
+
+export interface NoteCreateAckDependencies {
+ acknowledge: (
+ id: number,
+ snapshot: NoteCreateSnapshot,
+ cloudId: string,
+ cloudUpdatedAt: string | null,
+ ownerUserId: string | null,
+ settleIfUnchanged: boolean
+ ) => Promise<NoteCreateAckResult | undefined>;
+ deleteCloud: (cloudId: string) => Promise<void>;
+ onInvalidResponse?: (expectedClientNoteId: string, receivedClientNoteId: string | null) => void;
+ onCleanupError?: (cloud: CloudNoteCreateResult, error: unknown) => void;
+ onUnmatchedResponse?: (cloud: CloudNoteCreateResult) => void;
+}
+
+export type NoteCreateResolution =
+ | NoteCreateAckResult["outcome"]
+ | "bridge-unavailable"
+ | "invalid-response"
+ | "unmatched-response"
+ | "orphan-cleaned"
+ | "orphan-cleanup-failed";
+
+export interface NoteCreateAckOptions {
+ // Full sync creates send every mutable field and may settle an unchanged
+ // row. Legacy migration creates are partial and must stay pending for the
+ // subsequent full PATCH.
+ settleIfUnchanged?: boolean;
+ // Renderer account/reset generations can invalidate a request even when
+ // its local note identity still exists. Such a response is an orphan of the
+ // old request context and must be cleaned up without touching SQLite.
+ requestStillCurrent?: () => boolean;
+}
+
+async function cleanupOrphanedCreate(
+ cloud: CloudNoteCreateResult,
+ dependencies: NoteCreateAckDependencies
+): Promise<NoteCreateResolution> {
+ try {
+ await dependencies.deleteCloud(cloud.id);
+ return "orphan-cleaned";
+ } catch (error) {
+ dependencies.onCleanupError?.(cloud, error);
+ return "orphan-cleanup-failed";
+ }
+}
+
+// Couples the atomic local acknowledgement to best-effort cleanup of a POST
+// whose local identity disappeared. Keeping this small coordinator separate
+// makes the destructive half of the race directly testable.
+export async function resolveCloudNoteCreate(
+ note: NoteItem,
+ cloud: CloudNoteCreateResult,
+ dependencies: NoteCreateAckDependencies,
+ options: NoteCreateAckOptions = {}
+): Promise<NoteCreateResolution> {
+ if (!cloud.client_note_id || cloud.client_note_id !== note.client_note_id) {
+ dependencies.onInvalidResponse?.(note.client_note_id, cloud.client_note_id);
+ return "invalid-response";
+ }
+ if (options.requestStillCurrent && !options.requestStillCurrent()) {
+ return cleanupOrphanedCreate(cloud, dependencies);
+ }
+
+ const result = await dependencies.acknowledge(
+ note.id,
+ note,
+ cloud.id,
+ cloud.updated_at ?? null,
+ cloud.user_id ?? null,
+ options.settleIfUnchanged ?? true
+ );
+ if (!result) return "bridge-unavailable";
+ if (result.outcome !== "orphaned") return result.outcome;
+
+ return cleanupOrphanedCreate(cloud, dependencies);
+}
+
+export async function resolveCloudNoteCreateBatch(
+ notes: NoteItem[],
+ created: CloudNoteCreateResult[],
+ dependencies: NoteCreateAckDependencies,
+ options: NoteCreateAckOptions = {}
+): Promise<NoteCreateResolution[]> {
+ const notesByClientId = new Map(notes.map((note) => [note.client_note_id, note]));
+ return Promise.all(
+ created.map((cloud) => {
+ const local = cloud.client_note_id ? notesByClientId.get(cloud.client_note_id) : undefined;
+ if (!local) {
+ dependencies.onUnmatchedResponse?.(cloud);
+ return Promise.resolve<NoteCreateResolution>("unmatched-response");
+ }
+ return resolveCloudNoteCreate(local, cloud, dependencies, options);
+ })
+ );
+}
+
+function rendererDependencies(
+ deleteCloud: (cloudId: string) => Promise<void>
+): NoteCreateAckDependencies {
+ return {
+ acknowledge: async (id, snapshot, cloudId, cloudUpdatedAt, ownerUserId, settleIfUnchanged) =>
+ window.electronAPI.acknowledgeNoteCreate?.(
+ id,
+ snapshot,
+ cloudId,
+ cloudUpdatedAt,
+ ownerUserId,
+ settleIfUnchanged
+ ),
+ deleteCloud,
+ onInvalidResponse: (expected, received) =>
+ console.error("Ignoring note create response with mismatched client identity", {
+ expected,
+ received,
+ }),
+ onCleanupError: (orphan, error) =>
+ console.warn("Failed to clean up orphaned cloud note create", {
+ cloudId: orphan.id,
+ clientNoteId: orphan.client_note_id,
+ error,
+ }),
+ onUnmatchedResponse: (cloud) =>
+ console.error("Ignoring note create response without a matching local snapshot", {
+ cloudId: cloud.id,
+ clientNoteId: cloud.client_note_id,
+ }),
+ };
+}
+
+export function resolveRendererCloudNoteCreate(
+ note: NoteItem,
+ cloud: CloudNoteCreateResult,
+ deleteCloud: (cloudId: string) => Promise<void>,
+ options: NoteCreateAckOptions = {}
+): Promise<NoteCreateResolution> {
+ return resolveCloudNoteCreate(note, cloud, rendererDependencies(deleteCloud), options);
+}
+
+export function resolveRendererCloudNoteCreateBatch(
+ notes: NoteItem[],
+ created: CloudNoteCreateResult[],
+ deleteCloud: (cloudId: string) => Promise<void>,
+ options: NoteCreateAckOptions = {}
+): Promise<NoteCreateResolution[]> {
+ return resolveCloudNoteCreateBatch(notes, created, rendererDependencies(deleteCloud), options);
+}
diff --git a/src/services/syncPassPolicy.ts b/src/services/syncPassPolicy.ts
index e87c3d42d..89a40ba53 100644
--- a/src/services/syncPassPolicy.ts
+++ b/src/services/syncPassPolicy.ts
@@ -101,6 +101,9 @@ export interface RevokedNoteFork {
folder_id?: null;
client_note_id?: string;
cloud_id: null;
+ cloud_updated_at: null;
+ owner_user_id: null;
+ updated_by_user_id: null;
left_team?: 0;
};
relocated: boolean;
@@ -112,7 +115,8 @@ export interface RevokedNoteFork {
// drop the cloud link, and fork the client identity so the next push
// re-creates it as a new personal note. Push-side rejections fork the
// identity only when a server row exists (cloud_id) and clear the pending
-// left_team retraction the server will never accept; the pull-side
+// left_team retraction the server will never accept. Every new identity also
+// drops the old server revision/owner/editor metadata; the pull-side
// access_removed stub always forks — the server row exists by construction.
export function revokedNoteForkUpdate(
note: { space_id: number; cloud_id?: string | null },
@@ -126,6 +130,9 @@ export function revokedNoteForkUpdate(
...(relocated ? { space_id: privateSpaceId, folder_id: null } : {}),
...(source === "pull" || note.cloud_id ? { client_note_id: crypto.randomUUID() } : {}),
cloud_id: null,
+ cloud_updated_at: null,
+ owner_user_id: null,
+ updated_by_user_id: null,
...(source === "push" ? { left_team: 0 as const } : {}),
},
};
diff --git a/src/stores/noteListOps.ts b/src/stores/noteListOps.ts
index 89a9d0b6d..b8ecf0136 100644
--- a/src/stores/noteListOps.ts
+++ b/src/stores/noteListOps.ts
@@ -20,6 +20,31 @@ export interface TeardownContainersResult extends NoteContainerState {
removedNotes: NoteItem[];
}
+export function createClearedAccountNoteState<TSpace, TFolder, TShare, TConflict>() {
+ return {
+ notes: [] as NoteItem[],
+ spaces: [] as TSpace[],
+ folders: [] as TFolder[],
+ folderCounts: {} as Record<number, number>,
+ spaceRootCounts: {} as Record<number, number>,
+ notesByContainer: {} as Record<string, NoteItem[]>,
+ expandedContainers: new Set<string>(),
+ activeContext: null,
+ activeNoteId: null,
+ isTreeLoading: true,
+ migration: null,
+ shareByCloudId: new Map<string, TShare>(),
+ noteConflicts: {} as Record<string, TConflict>,
+ };
+}
+
+/** Make every currently running keyed load stale without reusing generations. */
+export function invalidateKeyedLoadGenerations(generations: Map<string, number>): void {
+ generations.forEach((generation, key) => {
+ generations.set(key, generation + 1);
+ });
+}
+
/**
* Remove a note from every container list AND the flat `notes` list. The flat
* list can hold notes absent from every loaded container (flat-only loads,
diff --git a/src/stores/noteStore.ts b/src/stores/noteStore.ts
index 215790714..60aaea371 100644
--- a/src/stores/noteStore.ts
+++ b/src/stores/noteStore.ts
@@ -1,8 +1,15 @@
import { create } from "zustand";
import { syncService } from "../services/SyncService.js";
-import { removeNoteFromLists, teardownNoteContainers } from "./noteListOps";
+import { resolveRendererCloudNoteCreateBatch } from "../services/noteCreateAck";
+import {
+ createClearedAccountNoteState,
+ invalidateKeyedLoadGenerations,
+ removeNoteFromLists,
+ teardownNoteContainers,
+} from "./noteListOps";
import {
addNoteConflict,
+ clearNoteConflicts,
readNoteConflicts,
removeNoteConflictId,
} from "../lib/noteConflictRegistry";
@@ -93,6 +100,8 @@ let loadGeneration = 0;
let treeLoadGeneration = 0;
let spacesLoadGeneration = 0;
let foldersLoadGeneration = 0;
+let migrationGeneration = 0;
+let accountGeneration = 0;
// Folder navigation requested before folders load; consumed once by initializeNotesTree.
let pendingFolderPreset: number | null = null;
@@ -341,6 +350,36 @@ export async function loadFolders(): Promise<FolderItem[]> {
const containerLoadGenerations = new Map<string, number>();
const containerLoadsInFlight = new Map<string, Promise<NoteItem[]>>();
+/**
+ * Synchronously remove account-scoped renderer state and invalidate every
+ * async load that could otherwise repopulate it after the database purge.
+ * IPC listeners stay bound; the next mounted notes view reloads clean state.
+ */
+export function resetForAccountChange(): void {
+ currentLimit = DEFAULT_LIMIT;
+ loadGeneration += 1;
+ treeLoadGeneration += 1;
+ spacesLoadGeneration += 1;
+ foldersLoadGeneration += 1;
+ migrationGeneration += 1;
+ accountGeneration += 1;
+ pendingFolderPreset = null;
+ purgeDisplacedNote = null;
+
+ invalidateKeyedLoadGenerations(containerLoadGenerations);
+ containerLoadsInFlight.clear();
+
+ try {
+ localStorage.removeItem(EXPANDED_STORAGE_KEY);
+ } catch {
+ // In-memory state is still cleared below.
+ }
+ clearNoteConflicts();
+ useNoteStore.setState(
+ createClearedAccountNoteState<SpaceItem, FolderItem, NoteShareCacheEntry, CloudNote>()
+ );
+}
+
export async function loadContainerNotes(
key: string,
noteType: string | null = null,
@@ -849,7 +888,10 @@ export function useMigration(): { total: number; done: number } | null {
}
export async function startMigration(): Promise<void> {
+ const gen = ++migrationGeneration;
+ const accountGen = accountGeneration;
const allNotes = (await window.electronAPI.getNotes(null, 9999, null)) ?? [];
+ if (gen !== migrationGeneration) return;
const unsynced = allNotes.filter((n) => !n.cloud_id);
if (unsynced.length === 0) return;
@@ -859,6 +901,7 @@ export async function startMigration(): Promise<void> {
const CHUNK_SIZE = 50;
for (let i = 0; i < unsynced.length; i += CHUNK_SIZE) {
+ if (gen !== migrationGeneration) return;
const chunk = unsynced.slice(i, i + CHUNK_SIZE);
try {
const { created } = await NotesService.batchCreate(
@@ -875,15 +918,25 @@ export async function startMigration(): Promise<void> {
updated_at: n.updated_at,
}))
);
- const notesByClientId = new Map(chunk.map((n) => [n.client_note_id, n]));
- await Promise.all(
- created.map(({ client_note_id, id: cloudId }) => {
- const local = notesByClientId.get(client_note_id);
- return local
- ? window.electronAPI.updateNoteCloudId(local.id, cloudId)
- : Promise.resolve();
- })
+ // A reset may invalidate the UI migration while the POST is in flight.
+ // Still run every response through the atomic identity/snapshot guard so
+ // a purged fork is untouched and its proven cloud orphan is cleaned up.
+ await resolveRendererCloudNoteCreateBatch(
+ chunk,
+ created,
+ (cloudId) => NotesService.delete(cloudId),
+ // Migration POSTs intentionally omit transcript/diarization fields,
+ // folder mapping, and space scope. Adopt the id/base but leave the row
+ // pending so SyncService follows with the complete PATCH.
+ {
+ settleIfUnchanged: false,
+ // Starting a newer migration supersedes only this run's progress.
+ // Both runs target the same account and idempotent cloud identity;
+ // only an account reset makes the response an orphan to delete.
+ requestStillCurrent: () => accountGen === accountGeneration,
+ }
);
+ if (gen !== migrationGeneration) return;
useNoteStore.setState((s) => ({
migration: s.migration
? {
@@ -897,7 +950,7 @@ export async function startMigration(): Promise<void> {
}
}
- useNoteStore.setState({ migration: null });
+ if (gen === migrationGeneration) useNoteStore.setState({ migration: null });
}
export function setNoteConflict(clientNoteId: string, cloudNote: CloudNote): void {
@@ -956,3 +1009,9 @@ export function updateShareCache(
export function useShareCacheEntry(cloudId: string | null): NoteShareCacheEntry | null {
return useNoteStore((state) => (cloudId ? (state.shareByCloudId.get(cloudId) ?? null) : null));
}
+
+// Whole-map subscription for list surfaces (the tree gates per-note actions
+// on loaded ACLs); per-note consumers should prefer useShareCacheEntry.
+export function useShareCache(): Map<string, NoteShareCacheEntry> {
+ return useNoteStore((state) => state.shareByCloudId);
+}
diff --git a/src/stores/workspaceStore.ts b/src/stores/workspaceStore.ts
index f3390a25b..ad344e3ac 100644
--- a/src/stores/workspaceStore.ts
+++ b/src/stores/workspaceStore.ts
@@ -12,6 +12,7 @@ interface WorkspaceState {
members: WorkspaceMember[];
setActiveWorkspaceId: (id: string | null) => void;
+ resetForAccountChange: () => void;
refresh: () => Promise<void>;
createWorkspace: (name: string) => Promise<Workspace>;
refreshMembers: (workspaceId: string) => Promise<void>;
@@ -32,6 +33,7 @@ function writeActiveWorkspaceId(id: string | null): void {
let refreshPromise: Promise<void> | null = null;
let membersRequestSeq = 0;
+let accountGeneration = 0;
export const useWorkspaceStore = create<WorkspaceState>((set, get) => ({
workspaces: [],
@@ -49,12 +51,32 @@ export const useWorkspaceStore = create<WorkspaceState>((set, get) => ({
set({ activeWorkspaceId: id, members: [] });
},
+ resetForAccountChange: () => {
+ accountGeneration += 1;
+ membersRequestSeq += 1;
+ // Let the next account start its own request. The identity check in the
+ // old request prevents its result/finally block from touching new state.
+ refreshPromise = null;
+ writeActiveWorkspaceId(null);
+ set({
+ workspaces: [],
+ loaded: false,
+ loading: false,
+ error: false,
+ activeWorkspaceId: null,
+ members: [],
+ });
+ },
+
refresh: () => {
if (refreshPromise) return refreshPromise;
+ const generation = accountGeneration;
set({ loading: true });
- refreshPromise = (async () => {
+ let request!: Promise<void>;
+ request = (async () => {
try {
const workspaces = await WorkspacesService.list();
+ if (generation !== accountGeneration) return;
const activeId = get().activeWorkspaceId;
const stillValid = activeId && workspaces.some((w) => w.id === activeId);
set({
@@ -66,6 +88,7 @@ export const useWorkspaceStore = create<WorkspaceState>((set, get) => ({
});
if (!stillValid && activeId) writeActiveWorkspaceId(null);
} catch (error) {
+ if (generation !== accountGeneration) return;
logger.error(
"Failed to load workspaces",
{ error: (error as Error).message },
@@ -73,15 +96,19 @@ export const useWorkspaceStore = create<WorkspaceState>((set, get) => ({
);
set({ loading: false, loaded: true, error: true });
} finally {
- refreshPromise = null;
+ if (refreshPromise === request) refreshPromise = null;
}
})();
- return refreshPromise;
+ refreshPromise = request;
+ return request;
},
createWorkspace: async (name) => {
+ const generation = accountGeneration;
const workspace = await WorkspacesService.create(name);
- set((s) => ({ workspaces: [...s.workspaces, workspace] }));
+ if (generation === accountGeneration) {
+ set((s) => ({ workspaces: [...s.workspaces, workspace] }));
+ }
return workspace;
},
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 3920fb0d3..6ddb2ce35 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -23,6 +23,16 @@ export type TranscriptionErrorCode =
| "MODEL_NOT_AVAILABLE"
| null;
+export interface AuthTokenState {
+ token: string | null;
+ generation: number;
+}
+
+export interface AuthTokenMutationResult extends AuthTokenState {
+ success: boolean;
+ code?: string;
+}
+
export interface TranscriptionItem {
id: number;
text: string;
@@ -78,11 +88,57 @@ export interface NoteItem {
client_note_id: string;
sync_status: "synced" | "pending" | "error";
deleted_at: string | null;
+ // Computed by getNoteByClientId while a parent folder DELETE awaits its
+ // server result. Held notes stay hidden and must not be pulled/queued alone.
+ folder_delete_pending?: number;
// 1 while a cloud-backed row that left a team space still owes its scope
// retraction push (D6); cleared when the row settles.
left_team?: number;
}
+// Immutable view of every local field that affects a note push. The main
+// process compares this atomically when the cloud response returns, so an
+// in-flight create/PATCH cannot settle a newer edit or a purged identity.
+export type NotePushSnapshot = Pick<
+ NoteItem,
+ | "client_note_id"
+ | "title"
+ | "content"
+ | "enhanced_content"
+ | "enhancement_prompt"
+ | "enhanced_at_content_hash"
+ | "note_type"
+ | "source_file"
+ | "audio_duration_seconds"
+ | "folder_id"
+ | "space_id"
+ | "transcript"
+ | "calendar_event_id"
+ | "participants"
+ | "diarization_enabled"
+ | "expected_speaker_count"
+ | "created_at"
+ | "updated_at"
+ | "sync_status"
+ | "deleted_at"
+ | "cloud_updated_at"
+ | "left_team"
+>;
+
+export type NoteCreateSnapshot = NotePushSnapshot;
+export type NoteUpdateSnapshot = NotePushSnapshot;
+
+export interface NoteCreateAckResult {
+ success: boolean;
+ outcome: "synced" | "pending" | "already-linked" | "orphaned" | "unresolved";
+}
+
+export interface NoteUpdateAckResult {
+ success: boolean;
+ outcome: "synced" | "pending" | "identity-changed";
+ changes: number;
+}
+
export type ShareVisibility = "private" | "link" | "domain" | "invited";
export type NotePermission = "owner" | "editor" | "viewer";
@@ -152,6 +208,26 @@ export interface FolderItem {
left_team?: number;
}
+export type FolderPushSnapshot = Pick<
+ FolderItem,
+ | "client_folder_id"
+ | "name"
+ | "is_default"
+ | "sort_order"
+ | "space_id"
+ | "created_at"
+ | "updated_at"
+ | "sync_status"
+ | "deleted_at"
+ | "left_team"
+>;
+
+export interface FolderAckResult {
+ success: boolean;
+ outcome: "synced" | "pending" | "already-linked" | "identity-changed" | "unresolved";
+ changes: number;
+}
+
/** A team assigned to a space, as mirrored from GET /api/me/spaces. */
export interface SpaceTeamRef {
id: string;
@@ -168,6 +244,8 @@ export interface SpaceItem {
id: number;
client_space_id: string;
cloud_space_id: string | null;
+ // Retained only for unambiguous adoption of pre-spaces team rows.
+ cloud_team_id?: string | null;
workspace_id: string | null;
kind: "private" | "team";
name: string;
@@ -614,6 +692,8 @@ export interface ConversationPreview {
client_conversation_id?: string;
sync_status?: "synced" | "pending" | "error";
deleted_at?: string | null;
+ // Computed for sync lookups while the parent folder delete is unresolved.
+ folder_delete_pending?: number;
message_count: number;
last_message?: string | null;
last_message_role?: "user" | "assistant" | "system" | null;
@@ -790,6 +870,9 @@ declare global {
expected_speaker_count?: number | null;
client_note_id?: string;
cloud_id?: string | null;
+ cloud_updated_at?: string | null;
+ owner_user_id?: string | null;
+ updated_by_user_id?: string | null;
left_team?: number;
}
) => Promise<{ success: boolean; note?: NoteItem }>;
@@ -850,15 +933,22 @@ declare global {
id: number,
updates: { name?: string; emoji?: string | null }
) => Promise<{ success: boolean; space?: SpaceItem; error?: string }>;
- purgeSpace?: (id: number) => Promise<{
+ purgeSpace?: (
+ id: number,
+ options?: {
+ mode?: "preserve-dirty" | "destructive";
+ expectedAuthGeneration?: number;
+ }
+ ) => Promise<{
success: boolean;
+ code?: string;
+ error?: string;
noteIds?: number[];
folderNames?: string[];
spaceId?: number;
relocatedNotes?: NoteItem[];
relocatedCount?: number;
relocatedTitles?: string[];
- error?: string;
}>;
upsertSpaceFromCloud?: (space: Record<string, unknown>) => Promise<SpaceItem>;
setSpaceSyncStatus?: (
@@ -1431,9 +1521,20 @@ declare global {
setAutoStartEnabled?: (enabled: boolean) => Promise<{ success: boolean; error?: string }>;
// Auth
- authClearSession?: () => Promise<void>;
+ authClearSession?: () => Promise<{
+ success: boolean;
+ tokenState?: AuthTokenState;
+ error?: string;
+ }>;
authGetToken?: () => Promise<string | null>;
- authSetToken?: (token: string) => Promise<void>;
+ authGetTokenState?: () => Promise<AuthTokenState>;
+ authSetToken?: (
+ token: string,
+ expectedGeneration: number
+ ) => Promise<AuthTokenMutationResult>;
+ onAuthTokenStateChanged?: (
+ callback: (state: { generation: number; hasToken: boolean }) => void
+ ) => () => void;
// OpenWhispr Cloud API
cloudTranscribe?: (
@@ -1564,6 +1665,7 @@ declare global {
path: string;
body?: unknown;
public?: boolean;
+ expectedAuthGeneration?: number;
}) => Promise<{
success: boolean;
data?: unknown;
@@ -1717,7 +1819,7 @@ declare global {
folder_id?: number | null;
created_at: string;
updated_at: string;
- }>;
+ } | null>;
getConversationsForNote?: (
noteId: number,
limit?: number
@@ -1784,7 +1886,7 @@ declare global {
content: string;
metadata?: string;
created_at: string;
- }>;
+ } | null>;
getAgentMessages?: (conversationId: number) => Promise<
Array<{
id: number;
@@ -2243,23 +2345,26 @@ declare global {
localFolderId: number | null,
localSpaceId?: number | null
) => Promise<NoteItem>;
- markNoteSynced?: (
+ acknowledgeNoteCreate?: (
id: number,
+ snapshot: NoteCreateSnapshot,
cloudId: string,
cloudUpdatedAt?: string | null,
- ownerUserId?: string | null
- ) => Promise<void>;
+ ownerUserId?: string | null,
+ settleIfUnchanged?: boolean
+ ) => Promise<NoteCreateAckResult>;
markNoteSyncedIfUnchanged?: (
id: number,
- cloudId: string,
- snapshotUpdatedAt: string,
+ snapshot: NoteUpdateSnapshot,
+ expectedCloudId: string,
cloudUpdatedAt?: string | null,
ownerUserId?: string | null
- ) => Promise<{ success: boolean; changes: number }>;
+ ) => Promise<NoteUpdateAckResult>;
setNoteCloudBase?: (id: number, cloudUpdatedAt: string | null) => Promise<void>;
setNoteOwnerFromCloud?: (id: number, ownerUserId: string) => Promise<void>;
countTeamNotesMissingOwner?: () => Promise<number>;
markNoteSyncError?: (id: number) => Promise<void>;
+ restoreNoteAfterDeniedDelete?: (id: number) => Promise<{ success: boolean; id: number }>;
hardDeleteNote?: (id: number) => Promise<void>;
getPendingFolders?: (spaceKind?: "private" | "team") => Promise<FolderItem[]>;
@@ -2268,20 +2373,29 @@ declare global {
cloudFolder: Record<string, unknown>,
localSpaceId?: number | null
) => Promise<FolderItem>;
- markFolderSynced?: (id: number, cloudId: string) => Promise<void>;
- markFolderSyncedIfUnchanged?: (
+ acknowledgeFolderCreate?: (
id: number,
+ snapshot: FolderPushSnapshot,
+ expectedCloudId: string | null,
+ responseClientFolderId: string,
cloudId: string,
- snapshotUpdatedAt: string
- ) => Promise<{ success: boolean; changes: number }>;
- adoptFolderIdentity?: (
+ cloudUpdatedAt?: string | null
+ ) => Promise<FolderAckResult>;
+ markFolderSyncedIfUnchanged?: (
id: number,
- clientFolderId: string,
- cloudId: string,
- updatedAt?: string
- ) => Promise<void>;
+ snapshot: FolderPushSnapshot,
+ expectedCloudId: string
+ ) => Promise<FolderAckResult>;
getFolderIdMap?: () => Promise<FolderItem[]>;
getPendingFolderDeletes?: () => Promise<FolderItem[]>;
+ restoreFolderAfterDeniedDelete?: (id: number) => Promise<{
+ success: boolean;
+ id: number;
+ folder?: FolderItem;
+ notes?: NoteItem[];
+ conversationIds?: number[];
+ error?: string;
+ }>;
hardDeleteFolder?: (id: number) => Promise<{ success: boolean; id: number }>;
relocateRevokedFolder?: (
id: number,
@@ -2303,7 +2417,10 @@ declare global {
cloudConv: Record<string, unknown>,
messages: Array<Record<string, unknown>>
) => Promise<void>;
- markConversationSynced?: (id: number, cloudId: string) => Promise<void>;
+ markConversationSynced?: (
+ id: number,
+ cloudId: string
+ ) => Promise<{ success: boolean } | undefined>;
hardDeleteConversation?: (id: number) => Promise<void>;
getPendingTranscriptions?: () => Promise<TranscriptionItem[]>;
diff --git a/test/helpers/cloudApiRequest.test.js b/test/helpers/cloudApiRequest.test.js
new file mode 100644
index 000000000..754d704b9
--- /dev/null
+++ b/test/helpers/cloudApiRequest.test.js
@@ -0,0 +1,116 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const { createCloudApiRequestHandler } = require("../../src/helpers/cloudApiRequest");
+
+function createHandler(state, proxyFetch) {
+ return createCloudApiRequestHandler({
+ getApiUrl: () => "https://api.openwhispr.test",
+ getAppVersion: () => "1.2.3",
+ proxyFetch,
+ tokenStore: {
+ getState: () => ({ ...state.current }),
+ },
+ logger: { error: () => {} },
+ });
+}
+
+test("an unvalidated or stale generation never reaches the network", async () => {
+ const state = { current: { token: "token-b", generation: 2 } };
+ let fetchCalls = 0;
+ const handler = createHandler(state, async () => {
+ fetchCalls += 1;
+ return new Response("{}");
+ });
+
+ const missing = await handler({ method: "GET", path: "/api/me/spaces" });
+ const stale = await handler({
+ method: "GET",
+ path: "/api/me/spaces",
+ expectedAuthGeneration: 1,
+ });
+
+ assert.equal(missing.code, "AUTH_CONTEXT_UNVALIDATED");
+ assert.equal(stale.code, "AUTH_CONTEXT_CHANGED");
+ assert.equal(fetchCalls, 0);
+});
+
+test("a token replacement while the request is in flight discards the response", async () => {
+ const state = { current: { token: "token-a", generation: 4 } };
+ let release;
+ const fetchGate = new Promise((resolve) => {
+ release = resolve;
+ });
+ const handler = createHandler(state, async (_url, options) => {
+ assert.equal(options.headers.Authorization, "Bearer token-a");
+ return fetchGate;
+ });
+
+ const request = handler({
+ method: "GET",
+ path: "/api/me/spaces",
+ expectedAuthGeneration: 4,
+ });
+ state.current = { token: "token-b", generation: 5 };
+ release(new Response(JSON.stringify({ data: [{ id: "space-a" }] })));
+
+ const result = await request;
+ assert.equal(result.success, false);
+ assert.equal(result.code, "AUTH_CONTEXT_CHANGED");
+ assert.equal(result.data, undefined);
+});
+
+test("an auth-context change dominates a simultaneous network failure", async () => {
+ const state = { current: { token: "token-a", generation: 8 } };
+ const handler = createHandler(state, async () => {
+ state.current = { token: "token-b", generation: 9 };
+ throw new Error("socket closed");
+ });
+
+ const result = await handler({
+ method: "PATCH",
+ path: "/api/notes/note-a",
+ body: { title: "old account data" },
+ expectedAuthGeneration: 8,
+ });
+
+ assert.equal(result.code, "AUTH_CONTEXT_CHANGED");
+ assert.doesNotMatch(result.error, /socket closed/);
+});
+
+test("a stable authenticated request is bearer-only and returns parsed data", async () => {
+ const state = { current: { token: "token-a", generation: 13 } };
+ const handler = createHandler(state, async (url, options) => {
+ assert.equal(url, "https://api.openwhispr.test/api/me/spaces");
+ assert.equal(options.useSessionCookies, false);
+ assert.equal(options.headers.Authorization, "Bearer token-a");
+ assert.equal(options.headers["x-openwhispr-version"], "1.2.3");
+ return new Response(JSON.stringify({ data: [{ id: "space-a" }] }));
+ });
+
+ const result = await handler({
+ method: "GET",
+ path: "/api/me/spaces",
+ expectedAuthGeneration: 13,
+ });
+ assert.deepEqual(result, {
+ success: true,
+ data: { data: [{ id: "space-a" }] },
+ });
+});
+
+test("public requests carry neither bearer nor cookies", async () => {
+ const state = { current: { token: "token-a", generation: 21 } };
+ const handler = createHandler(state, async (_url, options) => {
+ assert.equal(options.useSessionCookies, false);
+ assert.equal(options.headers.Authorization, undefined);
+ return new Response(JSON.stringify({ data: { invite: "preview" } }));
+ });
+
+ const result = await handler({
+ method: "GET",
+ path: "/api/invitations/preview",
+ public: true,
+ });
+ assert.equal(result.success, true);
+});
diff --git a/test/helpers/cloudSyncGuards.test.js b/test/helpers/cloudSyncGuards.test.js
index eec342d65..bce51e163 100644
--- a/test/helpers/cloudSyncGuards.test.js
+++ b/test/helpers/cloudSyncGuards.test.js
@@ -123,8 +123,18 @@ test("pre-guard rows omit base_updated_at entirely (legacy last-write-wins)", as
const { buildNoteUpdatePayload } = await load();
assert.equal("base_updated_at" in buildNoteUpdatePayload(localNote, null), false);
assert.equal(
- "base_updated_at" in
- buildNoteUpdatePayload({ ...localNote, cloud_updated_at: null }, null),
+ "base_updated_at" in buildNoteUpdatePayload({ ...localNote, cloud_updated_at: null }, null),
false
);
});
+
+test("note create payloads never send a stale optimistic-concurrency base", async () => {
+ const { buildNoteCreatePayload } = await load();
+ const payload = buildNoteCreatePayload(
+ { ...localNote, cloud_updated_at: "2026-07-22T08:40:00.123Z" },
+ "cloud-folder-3"
+ );
+ assert.equal("base_updated_at" in payload, false);
+ assert.equal(payload.content, localNote.content);
+ assert.equal(payload.folder_id, "cloud-folder-3");
+});
diff --git a/test/helpers/containerConversationsDatabase.test.js b/test/helpers/containerConversationsDatabase.test.js
index c31a92aa4..b4b3d2481 100644
--- a/test/helpers/containerConversationsDatabase.test.js
+++ b/test/helpers/containerConversationsDatabase.test.js
@@ -86,6 +86,13 @@ test("container scope migration is idempotent across launches", (t) => {
const noteColumns = db.db.pragma("table_info('notes')").map((col) => col.name);
assert.ok(noteColumns.includes("updated_by_user_id"));
+ assert.ok(
+ db.db
+ .prepare(
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'optimistic_folder_delete_rows'"
+ )
+ .get()
+ );
db.db.close();
@@ -97,6 +104,13 @@ test("container scope migration is idempotent across launches", (t) => {
.all()
.map((row) => row.name);
assert.ok(indexes.includes("idx_agent_conversations_container"));
+ assert.ok(
+ db2.db
+ .prepare(
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'optimistic_folder_delete_rows'"
+ )
+ .get()
+ );
});
test("createAgentConversation stores container scope", (t) => {
@@ -124,9 +138,10 @@ test("getPendingConversations excludes scopes the cloud contract cannot preserve
if (!db) return;
const space = createTestTeamSpace(db, { name: "Eng" }).space;
const folder = db.createFolder("Docs", space.id).folder;
+ const note = db.saveNote("Note", "body").note;
const global = db.createAgentConversation("Global");
- const noteScoped = db.createAgentConversation("Note chat", 123);
+ const noteScoped = db.createAgentConversation("Note chat", note.id);
db.createAgentConversation("Space chat", null, space.id);
db.createAgentConversation("Folder chat", null, space.id, folder.id);
@@ -177,10 +192,11 @@ test("global conversation lists and search exclude space and folder chats", (t)
if (!db) return;
const space = createTestTeamSpace(db, { name: "Eng" }).space;
const folder = db.createFolder("Docs", space.id).folder;
+ const note = db.saveNote("Roadmap source", "body").note;
const global = db.createAgentConversation("Roadmap global");
const archivedGlobal = db.createAgentConversation("Roadmap archived");
- const noteScoped = db.createAgentConversation("Roadmap note", 123);
+ const noteScoped = db.createAgentConversation("Roadmap note", note.id);
const spaceScoped = db.createAgentConversation("Roadmap space", null, space.id);
const folderScoped = db.createAgentConversation("Roadmap folder", null, space.id, folder.id);
db.archiveAgentConversation(archivedGlobal.id);
@@ -358,29 +374,486 @@ test("purgeSpace retires the space's container conversations", (t) => {
assert.equal(global.deleted_at, null, "unscoped conversations are untouched");
});
-test("deleteFolder and hardDeleteFolder retire the folder's conversations", (t) => {
+test("live cloud upserts never rehydrate local conversation tombstones", (t) => {
const db = createDb(t);
if (!db) return;
+ const space = createTestTeamSpace(db, { name: "Secret" }).space;
+
+ const purged = db.createAgentConversation("Purged chat", null, space.id);
+ db.markConversationSynced(purged.id, "cloud-conv-purged");
+ db.addAgentMessage(purged.id, "user", "sensitive team content");
+ assert.equal(db.purgeSpace(space.id).success, true);
+ assert.equal(db.getAgentMessages(purged.id).length, 0);
+
+ const ignored = db.upsertConversationFromCloud(
+ {
+ id: "cloud-conv-purged",
+ client_conversation_id: purged.client_conversation_id,
+ title: "Newer cloud copy",
+ updated_at: "2099-01-01T00:00:00.000Z",
+ },
+ [{ role: "assistant", content: "must not come back" }]
+ );
+ assert.equal(ignored.id, purged.id);
+ const stillPurged = db.db
+ .prepare("SELECT * FROM agent_conversations WHERE id = ?")
+ .get(purged.id);
+ assert.ok(stillPurged.deleted_at);
+ assert.equal(stillPurged.sync_status, "pending");
+ assert.equal(stillPurged.title, "Purged chat");
+ assert.equal(db.getAgentMessages(purged.id).length, 0);
+
+ const optimistic = db.createAgentConversation("Recoverable chat");
+ db.markConversationSynced(optimistic.id, "cloud-conv-optimistic");
+ db.addAgentMessage(optimistic.id, "user", "original local message");
+ assert.equal(db.deleteAgentConversation(optimistic.id).success, true);
+ db.upsertConversationFromCloud(
+ {
+ id: "cloud-conv-optimistic",
+ client_conversation_id: optimistic.client_conversation_id,
+ title: "Cloud tried to restore this",
+ updated_at: "2099-01-01T00:00:00.000Z",
+ },
+ [{ role: "assistant", content: "replacement cloud message" }]
+ );
+ assert.equal(
+ db.getAgentMessages(optimistic.id)[0].content,
+ "original local message",
+ "an optimistic tombstone retains its prior recoverable content without accepting cloud updates"
+ );
+
+ const inFlightCreate = db.createAgentConversation("Delete raced create");
+ assert.equal(db.deleteAgentConversation(inFlightCreate.id).success, true);
+ assert.equal(db.markConversationSynced(inFlightCreate.id, "cloud-conv-late-ack").success, true);
+ const queuedLateAck = db.db
+ .prepare("SELECT * FROM agent_conversations WHERE id = ?")
+ .get(inFlightCreate.id);
+ assert.equal(queuedLateAck.cloud_id, "cloud-conv-late-ack");
+ assert.ok(queuedLateAck.deleted_at);
+ assert.equal(queuedLateAck.sync_status, "pending");
+ assert.ok(
+ db
+ .getPendingConversationDeletes()
+ .some((conversation) => conversation.id === inFlightCreate.id),
+ "a late create acknowledgement becomes a pending cloud delete"
+ );
+
+ // This is the database action used by the cloud-tombstone branch: an
+ // acknowledged remote delete still removes the local tombstone completely.
+ assert.equal(db.hardDeleteConversation(purged.id).success, true);
+ assert.equal(
+ db.db.prepare("SELECT COUNT(*) AS n FROM agent_conversations WHERE id = ?").get(purged.id).n,
+ 0
+ );
+});
+
+test("purge rejects late writes and conversations for stale parents", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const space = createTestTeamSpace(db, { name: "Secret" }).space;
+ const folder = db.createFolder("Vault", space.id).folder;
+ const note = db.saveNote("Secret note", "body", "personal", null, null, folder.id).note;
+ db.markNoteSynced(note.id, "cloud-note-late-write");
+ const conversation = db.createAgentConversation("Original title", note.id);
+ db.markConversationSynced(conversation.id, "cloud-conv-late-write");
+ db.addAgentMessage(conversation.id, "user", "purge this message");
+ const localConversation = db.createAgentConversation("Local in-flight chat", note.id);
+ db.addAgentMessage(localConversation.id, "user", "purge local message");
+
+ assert.equal(db.purgeSpace(space.id).success, true);
+ const tombstone = db.db
+ .prepare("SELECT * FROM agent_conversations WHERE id = ?")
+ .get(conversation.id);
+ assert.ok(tombstone.deleted_at);
+ assert.equal(db.getAgentMessages(conversation.id).length, 0);
+ assert.equal(db.getAgentConversation(localConversation.id), null);
+ assert.equal(db.addAgentMessage(localConversation.id, "assistant", "late local response"), null);
+ assert.equal(
+ db.updateAgentConversationTitle(localConversation.id, "late local title").success,
+ false
+ );
+
+ assert.equal(db.addAgentMessage(conversation.id, "assistant", "late sensitive response"), null);
+ assert.equal(db.getAgentMessages(conversation.id).length, 0);
+ assert.equal(
+ db.updateAgentConversationTitle(conversation.id, "late sensitive title").success,
+ false
+ );
+ assert.equal(db.archiveAgentConversation(conversation.id).success, false);
+ assert.equal(db.unarchiveAgentConversation(conversation.id).success, false);
+ assert.equal(db.updateAgentConversationCloudId(conversation.id, "late-cloud-id").success, false);
+ assert.equal(db.markConversationSynced(conversation.id, "late-cloud-id").success, true);
+ const unchanged = db.db
+ .prepare("SELECT * FROM agent_conversations WHERE id = ?")
+ .get(conversation.id);
+ assert.equal(unchanged.title, "Original title");
+ assert.equal(unchanged.cloud_id, "cloud-conv-late-write");
+ assert.equal(unchanged.sync_status, "pending");
+
+ assert.equal(db.createAgentConversation("Late note chat", note.id), null);
+ assert.equal(db.createAgentConversation("Late space chat", null, space.id), null);
+ assert.equal(db.createAgentConversation("Late folder chat", null, space.id, folder.id), null);
+ assert.ok(db.createAgentConversation("Unscoped chat"), "global chats remain valid");
+
+ const deletedNote = db.saveNote("Soft-deleted", "body").note;
+ db.deleteNote(deletedNote.id);
+ assert.equal(db.createAgentConversation("Deleted note chat", deletedNote.id), null);
+
+ const deletedSpace = createTestTeamSpace(db, { name: "Deleted scope" }).space;
+ db.db.prepare("UPDATE spaces SET deleted_at = datetime('now') WHERE id = ?").run(deletedSpace.id);
+ assert.equal(db.createAgentConversation("Deleted space chat", null, deletedSpace.id), null);
+
+ const liveSpace = createTestTeamSpace(db, { name: "Live scope" }).space;
+ const deletedFolder = db.createFolder("Deleted folder", liveSpace.id).folder;
+ db.markFolderSynced(deletedFolder.id, "cloud-folder-deleted-parent");
+ db.deleteFolder(deletedFolder.id);
+ assert.equal(
+ db.createAgentConversation("Deleted folder chat", null, liveSpace.id, deletedFolder.id),
+ null
+ );
+});
+
+test("destructive note cleanup retires chats while denied-delete cleanup preserves them", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ const doomed = db.saveNote("Doomed", "body").note;
+ const syncedChat = db.createAgentConversation("Synced note chat", doomed.id);
+ db.markConversationSynced(syncedChat.id, "cloud-conv-doomed");
+ db.addAgentMessage(syncedChat.id, "user", "remove after confirmed delete");
+ const localChat = db.createAgentConversation("Local note chat", doomed.id);
+ db.addAgentMessage(localChat.id, "user", "remove local chat");
+
+ assert.equal(db.hardDeleteNote(doomed.id).success, true);
+ const syncedTombstone = db.db
+ .prepare("SELECT * FROM agent_conversations WHERE id = ?")
+ .get(syncedChat.id);
+ assert.ok(syncedTombstone.deleted_at);
+ assert.equal(syncedTombstone.sync_status, "pending");
+ assert.equal(db.getAgentMessages(syncedChat.id).length, 0);
+ assert.equal(db.getAgentConversation(localChat.id), null);
+ assert.deepEqual(db.getConversationsForNote(doomed.id), []);
+
+ const recoverable = db.saveNote("Denied delete", "body").note;
+ db.markNoteSynced(recoverable.id, "cloud-note-recoverable");
+ const recoverableChat = db.createAgentConversation("Keep on denial", recoverable.id);
+ db.markConversationSynced(recoverableChat.id, "cloud-conv-recoverable");
+ db.addAgentMessage(recoverableChat.id, "user", "restore with server note");
+
+ assert.equal(db.deleteNote(recoverable.id).success, true);
+ assert.equal(db.restoreNoteAfterDeniedDelete(recoverable.id).success, true);
+ const revived = db.getNote(recoverable.id);
+ assert.equal(revived.id, recoverable.id);
+ assert.equal(revived.deleted_at, null);
+ assert.equal(revived.sync_status, "synced");
+ assert.equal(revived.updated_at, "1970-01-01 00:00:00");
+
+ const pulled = db.upsertNoteFromCloud(
+ {
+ id: "cloud-note-recoverable",
+ client_note_id: recoverable.client_note_id,
+ title: "Authoritative server note",
+ content: "server body",
+ created_at: recoverable.created_at,
+ updated_at: "2026-07-29 12:00:00",
+ },
+ null,
+ db.getPrivateSpaceId()
+ );
+ assert.equal(pulled.id, recoverable.id, "snapshot restore keeps the numeric note identity");
+ assert.equal(pulled.title, "Authoritative server note");
+ const preserved = db.getAgentConversation(recoverableChat.id);
+ assert.equal(preserved.note_id, recoverable.id);
+ assert.equal(preserved.deleted_at, null);
+ assert.equal(preserved.messages.length, 1);
+});
+
+test("denied folder delete restores the same notes, speakers, and conversations in place", (t) => {
+ let db = createDb(t);
+ if (!db) return;
const space = createTestTeamSpace(db, { name: "Eng" }).space;
const folder = db.createFolder("Docs", space.id).folder;
- const folderConv = db.createAgentConversation("Folder chat", null, space.id, folder.id);
+ db.markFolderSynced(folder.id, "cloud-folder-denied");
+ const child = db.saveNote("Child", "body", "personal", null, null, folder.id).note;
+ db.markNoteSynced(child.id, "cloud-note-child");
+ const localChild = db.saveNote(
+ "Local draft",
+ "never uploaded",
+ "personal",
+ null,
+ null,
+ folder.id
+ ).note;
+ db.setSpeakerMapping(child.id, "SPEAKER_00", null, "Alice");
+ db.saveNoteSpeakerEmbeddings(child.id, { SPEAKER_00: Buffer.from([1, 2, 3, 4]) });
+
+ const childNoteConv = db.createAgentConversation("Child note chat", child.id);
+ db.markConversationSynced(childNoteConv.id, "cloud-conv-child");
+ db.addAgentMessage(childNoteConv.id, "user", "keep while folder delete is pending");
+ const localNoteConv = db.createAgentConversation("Local note chat", localChild.id);
+ db.addAgentMessage(localNoteConv.id, "user", "local note chat survives denial");
+ const localFolderConv = db.createAgentConversation("Folder chat", null, space.id, folder.id);
+ db.addAgentMessage(localFolderConv.id, "user", "local folder chat survives denial");
+ const syncedFolderConv = db.createAgentConversation(
+ "Synced folder chat",
+ null,
+ space.id,
+ folder.id
+ );
+ db.markConversationSynced(syncedFolderConv.id, "cloud-conv-1");
+ db.addAgentMessage(syncedFolderConv.id, "user", "recoverable until delete is accepted");
+ const alreadyDeleted = db.createAgentConversation("Already deleted", null, space.id, folder.id);
+ db.markConversationSynced(alreadyDeleted.id, "cloud-conv-already-deleted");
+ db.addAgentMessage(alreadyDeleted.id, "user", "independent tombstone");
+ db.deleteAgentConversation(alreadyDeleted.id);
const spaceConv = db.createAgentConversation("Space chat", null, space.id);
assert.equal(db.deleteFolder(folder.id).success, true);
+ const hiddenFolder = db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id);
+ assert.ok(hiddenFolder.deleted_at);
+ assert.equal(hiddenFolder.name, "Docs", "rollback keeps the original folder name in place");
+ assert.ok(!db.getFolders(space.id).some((candidate) => candidate.id === folder.id));
+ assert.deepEqual(db.getNotes(null, 100, folder.id), []);
assert.equal(
- db.db.prepare("SELECT COUNT(*) AS n FROM agent_conversations WHERE id = ?").get(folderConv.id)
- .n,
- 0
+ db.createFolder("Docs", space.id).success,
+ false,
+ "a held folder reserves its name so rollback cannot collide"
+ );
+
+ const hiddenChild = db.getNote(child.id);
+ const hiddenLocalChild = db.getNote(localChild.id);
+ assert.ok(hiddenChild.deleted_at);
+ assert.ok(hiddenLocalChild.deleted_at);
+ assert.equal(hiddenChild.sync_status, "folder_delete_pending");
+ assert.equal(hiddenLocalChild.sync_status, "folder_delete_pending");
+ assert.equal(db.getNoteByClientId(child.client_note_id).folder_delete_pending, 1);
+ assert.equal(hiddenLocalChild.content, "never uploaded");
+ assert.deepEqual(
+ db.getSpeakerMappings(child.id).map((row) => row.display_name),
+ ["Alice"]
+ );
+ assert.equal(db.getNoteSpeakerEmbeddings(child.id).length, 1);
+
+ const childChatTombstone = db.db
+ .prepare("SELECT * FROM agent_conversations WHERE id = ?")
+ .get(childNoteConv.id);
+ assert.ok(childChatTombstone.deleted_at, "note-only chat is hidden with the optimistic delete");
+ assert.equal(childChatTombstone.note_id, child.id);
+ assert.equal(childChatTombstone.folder_id, null);
+ assert.equal(childChatTombstone.sync_status, "folder_delete_pending");
+ assert.equal(
+ db.getAgentMessages(childNoteConv.id).length,
+ 1,
+ "synced note-chat content remains recoverable until the folder delete is accepted"
+ );
+ assert.deepEqual(db.getConversationsForNote(child.id), []);
+ assert.ok(db.db.prepare("SELECT id FROM agent_conversations WHERE id = ?").get(localNoteConv.id));
+ assert.ok(
+ db.db.prepare("SELECT id FROM agent_conversations WHERE id = ?").get(localFolderConv.id)
+ );
+ const optimisticTombstone = db.db
+ .prepare("SELECT * FROM agent_conversations WHERE id = ?")
+ .get(syncedFolderConv.id);
+ assert.ok(optimisticTombstone.deleted_at);
+ assert.equal(optimisticTombstone.sync_status, "folder_delete_pending");
+ assert.equal(
+ db.getConversationByClientId(syncedFolderConv.client_conversation_id).folder_delete_pending,
+ 1
+ );
+ assert.equal(
+ db.getAgentMessages(syncedFolderConv.id).length,
+ 1,
+ "an optimistic folder delete keeps synced messages recoverable until server acceptance"
+ );
+ assert.equal(db.getAgentMessages(localNoteConv.id).length, 1);
+ assert.equal(db.getAgentMessages(localFolderConv.id).length, 1);
+ // A late async acknowledgement may rewrite sync_status after the hold. The
+ // durable journal, not that transient status, must still own both queues.
+ db.db.prepare("UPDATE notes SET sync_status = 'pending' WHERE id = ?").run(child.id);
+ db.db
+ .prepare("UPDATE agent_conversations SET sync_status = 'pending' WHERE id = ?")
+ .run(childNoteConv.id);
+ assert.ok(
+ !db
+ .getPendingConversationDeletes()
+ .some(
+ (conversation) =>
+ conversation.id === childNoteConv.id ||
+ conversation.id === syncedFolderConv.id ||
+ conversation.id === localNoteConv.id ||
+ conversation.id === localFolderConv.id
+ ),
+ "conversation deletes wait for the folder-delete result"
+ );
+ assert.ok(
+ db
+ .getPendingConversationDeletes()
+ .some((conversation) => conversation.id === alreadyDeleted.id),
+ "a pre-existing conversation tombstone remains independently queued"
+ );
+ assert.ok(
+ !db.getPendingNoteDeletes().some((note) => note.id === child.id),
+ "held child notes are not individually queued for deletion"
);
assert.equal(db.getConversationsForContainer(space.id, null)[0].id, spaceConv.id);
+ db.db.close();
+ db = new DatabaseManager();
+ const restored = db.restoreFolderAfterDeniedDelete(folder.id);
+ assert.equal(restored.success, true);
+ assert.equal(restored.folder.id, folder.id);
+ assert.deepEqual(
+ db
+ .getNotes(null, 100, folder.id)
+ .map((note) => note.id)
+ .sort((a, b) => a - b),
+ [child.id, localChild.id].sort((a, b) => a - b),
+ "both cloud-backed and local-only notes become visible with their original ids"
+ );
+ assert.equal(db.getNote(child.id).sync_status, "synced");
+ assert.equal(db.getNote(localChild.id).sync_status, "pending");
+ assert.equal(db.getNote(localChild.id).content, "never uploaded");
+ assert.deepEqual(
+ db.getConversationsForNote(child.id).map((conversation) => conversation.id),
+ [childNoteConv.id]
+ );
+ assert.equal(
+ db.db.prepare("SELECT sync_status FROM agent_conversations WHERE id = ?").get(childNoteConv.id)
+ .sync_status,
+ "synced",
+ "rollback restores metadata captured before a late acknowledgement"
+ );
+ assert.deepEqual(
+ db.getConversationsForNote(localChild.id).map((conversation) => conversation.id),
+ [localNoteConv.id]
+ );
+ assert.deepEqual(
+ db
+ .getConversationsForContainer(space.id, folder.id)
+ .map((conversation) => conversation.id)
+ .sort((a, b) => a - b),
+ [localFolderConv.id, syncedFolderConv.id].sort((a, b) => a - b)
+ );
+ assert.equal(db.getAgentConversation(childNoteConv.id).messages.length, 1);
+ assert.equal(
+ db.getAgentConversation(localNoteConv.id).messages[0].content,
+ "local note chat survives denial"
+ );
+ assert.equal(
+ db.getAgentConversation(localFolderConv.id).messages[0].content,
+ "local folder chat survives denial"
+ );
+ assert.deepEqual(
+ db.getSpeakerMappings(child.id).map((row) => row.display_name),
+ ["Alice"]
+ );
+ assert.deepEqual([...db.getNoteSpeakerEmbeddings(child.id)[0].embedding], [1, 2, 3, 4]);
+ assert.equal(
+ db.db.prepare("SELECT deleted_at FROM agent_conversations WHERE id = ?").get(alreadyDeleted.id)
+ .deleted_at !== null,
+ true,
+ "rollback does not revive a conversation deleted before the folder action"
+ );
+ assert.equal(
+ db.db.prepare("SELECT sync_status FROM agent_conversations WHERE id = ?").get(alreadyDeleted.id)
+ .sync_status,
+ "pending"
+ );
+ assert.equal(
+ db.db
+ .prepare("SELECT COUNT(*) AS count FROM optimistic_folder_delete_rows WHERE folder_id = ?")
+ .get(folder.id).count,
+ 0
+ );
+});
+
+test("confirmed folder delete scrubs chats and finalizes held rows", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const space = createTestTeamSpace(db, { name: "Eng" }).space;
const folder2 = db.createFolder("Specs", space.id).folder;
+ const childNote = db.saveNote(
+ "Folder note",
+ "sensitive body",
+ "personal",
+ null,
+ null,
+ folder2.id
+ ).note;
+ const noteConv = db.createAgentConversation("Note-only chat", childNote.id);
+ db.markConversationSynced(noteConv.id, "cloud-conv-note");
+ db.addAgentMessage(noteConv.id, "user", "note-scoped sensitive content");
const conv2 = db.createAgentConversation("Specs chat", null, space.id, folder2.id);
db.markConversationSynced(conv2.id, "cloud-conv-2");
+ db.addAgentMessage(conv2.id, "user", "confirmed delete must scrub this");
db.hardDeleteFolder(folder2.id);
+ assert.equal(db.getNote(childNote.id), null);
+ const noteTombstone = db.db
+ .prepare("SELECT * FROM agent_conversations WHERE id = ?")
+ .get(noteConv.id);
+ assert.ok(noteTombstone.deleted_at);
+ assert.equal(noteTombstone.sync_status, "pending");
+ assert.equal(noteTombstone.folder_id, null, "regression fixture is scoped only by note_id");
+ assert.equal(db.getAgentMessages(noteConv.id).length, 0);
+ assert.deepEqual(db.getConversationsForNote(childNote.id), []);
const tombstoned = db.db.prepare("SELECT * FROM agent_conversations WHERE id = ?").get(conv2.id);
assert.ok(tombstoned.deleted_at);
assert.equal(tombstoned.sync_status, "pending");
+ assert.equal(
+ db.getAgentMessages(conv2.id).length,
+ 0,
+ "a confirmed hard delete scrubs synced messages"
+ );
+
+ const folder3 = db.createFolder("Accepted", space.id).folder;
+ db.markFolderSynced(folder3.id, "cloud-folder-accepted");
+ const acceptedLocalNote = db.saveNote(
+ "Accepted local child",
+ "delete after confirmation",
+ "personal",
+ null,
+ null,
+ folder3.id
+ ).note;
+ const acceptedLocalConv = db.createAgentConversation("Accepted local chat", acceptedLocalNote.id);
+ db.addAgentMessage(acceptedLocalConv.id, "user", "local content is held until confirmation");
+ const acceptedConv = db.createAgentConversation("Accepted chat", null, space.id, folder3.id);
+ db.markConversationSynced(acceptedConv.id, "cloud-conv-accepted");
+ db.addAgentMessage(acceptedConv.id, "user", "scrub after server acceptance");
+ const acceptedPredeleted = db.createAgentConversation(
+ "Accepted predeleted",
+ null,
+ space.id,
+ folder3.id
+ );
+ db.markConversationSynced(acceptedPredeleted.id, "cloud-conv-predeleted");
+ db.addAgentMessage(acceptedPredeleted.id, "user", "scrub but keep delete intent");
+ db.deleteAgentConversation(acceptedPredeleted.id);
+ assert.equal(db.deleteFolder(folder3.id).success, true);
+ assert.equal(
+ db.db.prepare("SELECT sync_status FROM agent_conversations WHERE id = ?").get(acceptedConv.id)
+ .sync_status,
+ "folder_delete_pending"
+ );
+ assert.equal(db.hardDeleteFolder(folder3.id).success, true);
+ const acceptedTombstone = db.db
+ .prepare("SELECT * FROM agent_conversations WHERE id = ?")
+ .get(acceptedConv.id);
+ assert.equal(acceptedTombstone.sync_status, "pending");
+ assert.equal(db.getAgentMessages(acceptedConv.id).length, 0);
+ assert.equal(db.getNote(acceptedLocalNote.id), null);
+ assert.equal(db.getAgentConversation(acceptedLocalConv.id), null);
+ const predeletedAfterConfirmation = db.db
+ .prepare("SELECT * FROM agent_conversations WHERE id = ?")
+ .get(acceptedPredeleted.id);
+ assert.ok(predeletedAfterConfirmation.deleted_at);
+ assert.equal(predeletedAfterConfirmation.sync_status, "pending");
+ assert.equal(db.getAgentMessages(acceptedPredeleted.id).length, 0);
+ const acceptedDeleteIds = new Set(
+ db.getPendingConversationDeletes().map((conversation) => conversation.id)
+ );
+ assert.ok(acceptedDeleteIds.has(acceptedConv.id));
+ assert.ok(acceptedDeleteIds.has(acceptedPredeleted.id));
});
test("relocateRevokedFolder moves or retires the folder's conversations", (t) => {
diff --git a/test/helpers/noteListOps.test.js b/test/helpers/noteListOps.test.js
index 7af4e618d..12d04850a 100644
--- a/test/helpers/noteListOps.test.js
+++ b/test/helpers/noteListOps.test.js
@@ -141,3 +141,41 @@ test("container teardown preserves active notes outside the removed containers",
assert.equal(result.notesByContainer["f:2"], state.notesByContainer["f:2"]);
assert.equal(result.activeNoteId, 2);
});
+
+test("account reset state contains no cached content, context, shares, or conflicts", async () => {
+ const { createClearedAccountNoteState } = await load();
+
+ const state = createClearedAccountNoteState();
+
+ assert.deepEqual(state.notes, []);
+ assert.deepEqual(state.spaces, []);
+ assert.deepEqual(state.folders, []);
+ assert.deepEqual(state.folderCounts, {});
+ assert.deepEqual(state.spaceRootCounts, {});
+ assert.deepEqual(state.notesByContainer, {});
+ assert.deepEqual([...state.expandedContainers], []);
+ assert.equal(state.activeContext, null);
+ assert.equal(state.activeNoteId, null);
+ assert.equal(state.isTreeLoading, true);
+ assert.equal(state.migration, null);
+ assert.deepEqual([...state.shareByCloudId], []);
+ assert.deepEqual(state.noteConflicts, {});
+});
+
+test("account reset invalidates every in-flight keyed load generation", async () => {
+ const { invalidateKeyedLoadGenerations } = await load();
+ const generations = new Map([
+ ["s:1", 2],
+ ["f:8", 7],
+ ]);
+
+ invalidateKeyedLoadGenerations(generations);
+
+ assert.deepEqual(
+ [...generations],
+ [
+ ["s:1", 3],
+ ["f:8", 8],
+ ]
+ );
+});
diff --git a/test/helpers/notesOwnerDatabase.test.js b/test/helpers/notesOwnerDatabase.test.js
index 4f35e5863..d7c50df64 100644
--- a/test/helpers/notesOwnerDatabase.test.js
+++ b/test/helpers/notesOwnerDatabase.test.js
@@ -169,15 +169,20 @@ test("markNoteSynced and markNoteSyncedIfUnchanged persist the returned owner",
assert.equal(row.owner_user_id, null);
// The owner advances with the base even when a mid-flight edit keeps the
- // row pending (updated_at mismatch prevents the settle).
- db.db.prepare("UPDATE notes SET owner_user_id = NULL WHERE id = ?").run(note.id);
+ // row pending.
+ db.updateNote(note.id, { content: "body v2" });
+ const snapshot = db.getNote(note.id);
+ db.db
+ .prepare("UPDATE notes SET content = 'body v3', sync_status = 'pending' WHERE id = ?")
+ .run(note.id);
const settle = db.markNoteSyncedIfUnchanged(
note.id,
+ snapshot,
"cloud-9",
- "not-the-current-updated-at",
"2026-07-02T12:00:00.000Z",
"owner-9"
);
+ assert.equal(settle.outcome, "pending");
assert.equal(settle.changes, 0);
row = db.getNote(note.id);
assert.equal(row.owner_user_id, "owner-9");
diff --git a/test/helpers/preloadAuthBridge.test.js b/test/helpers/preloadAuthBridge.test.js
new file mode 100644
index 000000000..d6aa04aee
--- /dev/null
+++ b/test/helpers/preloadAuthBridge.test.js
@@ -0,0 +1,52 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+const test = require("node:test");
+const vm = require("node:vm");
+
+function loadPreloadApi() {
+ let exposedApi;
+ const listeners = new Map();
+ const ipcRenderer = {
+ invoke: async () => undefined,
+ on: (channel, listener) => listeners.set(channel, listener),
+ removeListener: (channel, listener) => {
+ if (listeners.get(channel) === listener) listeners.delete(channel);
+ },
+ send: () => undefined,
+ sendSync: () => undefined,
+ };
+ const electron = {
+ contextBridge: {
+ exposeInMainWorld: (_name, api) => {
+ exposedApi = api;
+ },
+ },
+ ipcRenderer,
+ webUtils: {},
+ };
+ const source = fs.readFileSync(path.join(__dirname, "../../preload.js"), "utf8");
+ vm.runInNewContext(source, {
+ require: (specifier) => {
+ if (specifier === "electron") return electron;
+ throw new Error(`Unexpected preload dependency: ${specifier}`);
+ },
+ process,
+ });
+ return { api: exposedApi, listeners };
+}
+
+test("auth token-state listener strips the Electron event object", () => {
+ const { api, listeners } = loadPreloadApi();
+ const payload = { generation: 7, hasToken: true };
+ let received;
+ const unsubscribe = api.onAuthTokenStateChanged((state) => {
+ received = state;
+ });
+
+ listeners.get("auth-token-state-changed")?.({ sender: "ipc" }, payload);
+
+ assert.equal(received, payload);
+ unsubscribe();
+ assert.equal(listeners.has("auth-token-state-changed"), false);
+});
diff --git a/test/helpers/spacesDatabase.test.js b/test/helpers/spacesDatabase.test.js
index f12d39bee..8edd9433b 100644
--- a/test/helpers/spacesDatabase.test.js
+++ b/test/helpers/spacesDatabase.test.js
@@ -277,6 +277,170 @@ test("purgeSpace leaves zero residue for the space and spares the private space"
assert.equal(count("SELECT COUNT(*) as count FROM spaces WHERE id = ?", privateId), 1);
});
+test("purgeSpace retires team-note chats and preserves chats for relocated drafts", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const privateId = db.getPrivateSpaceId();
+ const team = createTestTeamSpace(db, { name: "Secret" }).space;
+ const folder = db.createFolder("Vault", team.id).folder;
+
+ const clean = db.saveNote("Team plan", "server copy", "personal", null, null, folder.id).note;
+ db.markNoteSynced(clean.id, "cloud-note-1");
+ const localChat = db.createAgentConversation("Local team chat", clean.id);
+ db.addAgentMessage(localChat.id, "user", "local classified chat");
+ const syncedChat = db.createAgentConversation("Synced team chat", clean.id);
+ db.markConversationSynced(syncedChat.id, "cloud-conversation-1");
+ db.addAgentMessage(syncedChat.id, "assistant", "synced classified chat");
+
+ const draft = db.saveNote("Draft", "unpushed work", "personal", null, null, folder.id).note;
+ // Exercise defensive normalization for a legacy note chat that also carries
+ // redundant team-container scope.
+ const draftChat = db.createAgentConversation("Draft chat", draft.id, team.id, folder.id);
+ db.addAgentMessage(draftChat.id, "user", "keep with my draft");
+
+ const privateNote = db.saveNote("Mine", "personal").note;
+ const privateChat = db.createAgentConversation("Private chat", privateNote.id);
+ db.addAgentMessage(privateChat.id, "user", "keep private");
+
+ db.markFolderSynced(folder.id, "cloud-folder-revoked-during-delete");
+ assert.equal(db.deleteFolder(folder.id).success, true);
+ assert.equal(db.purgeSpace(team.id).success, true);
+
+ const count = (sql, ...args) => db.db.prepare(sql).get(...args).count;
+ assert.equal(
+ count("SELECT COUNT(*) AS count FROM agent_conversations WHERE id = ?", localChat.id),
+ 0,
+ "a never-synced team-note chat has no cloud row to retire"
+ );
+ assert.equal(
+ count("SELECT COUNT(*) AS count FROM agent_messages WHERE conversation_id = ?", localChat.id),
+ 0
+ );
+
+ const tombstone = db.db
+ .prepare("SELECT * FROM agent_conversations WHERE id = ?")
+ .get(syncedChat.id);
+ assert.ok(tombstone.deleted_at, "a synced team-note chat leaves a cloud delete tombstone");
+ assert.equal(tombstone.sync_status, "pending");
+ assert.equal(
+ count("SELECT COUNT(*) AS count FROM agent_messages WHERE conversation_id = ?", syncedChat.id),
+ 0,
+ "team chat content is removed even while its cloud delete is pending"
+ );
+ assert.deepEqual(db.getConversationsForNote(clean.id), []);
+ assert.ok(!db.getAgentConversations().some((conversation) => conversation.id === syncedChat.id));
+
+ const relocatedDraft = db.getNote(draft.id);
+ assert.equal(relocatedDraft.space_id, privateId);
+ assert.equal(relocatedDraft.folder_id, null);
+ const keptDraftChat = db.getAgentConversation(draftChat.id);
+ assert.equal(keptDraftChat.note_id, draft.id);
+ assert.equal(keptDraftChat.space_id, null);
+ assert.equal(keptDraftChat.folder_id, null);
+ assert.equal(keptDraftChat.deleted_at, null);
+ assert.equal(keptDraftChat.messages.length, 1);
+
+ assert.equal(db.getAgentConversation(privateChat.id).messages.length, 1);
+});
+
+test("purgeSpace destructive mode removes dirty team notes and chats without relocation", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const privateId = db.getPrivateSpaceId();
+ const team = createTestTeamSpace(db, { name: "Old account" }).space;
+ const folder = db.createFolder("Secrets", team.id).folder;
+
+ const dirty = db.saveNote(
+ "Pending team edit",
+ "old-account content",
+ "personal",
+ null,
+ null,
+ folder.id
+ ).note;
+ db.markNoteSynced(
+ dirty.id,
+ "cloud-dirty-account-note",
+ "2026-07-29T10:00:00.000Z",
+ "old-account-user"
+ );
+ db.updateNote(dirty.id, { content: "old-account content edited offline" });
+ assert.equal(db.getNote(dirty.id).sync_status, "pending");
+
+ const noteChat = db.createAgentConversation("Old account note chat", dirty.id);
+ db.markConversationSynced(noteChat.id, "cloud-old-account-note-chat");
+ db.addAgentMessage(noteChat.id, "user", "old-account private message");
+ const containerChat = db.createAgentConversation(
+ "Old account folder chat",
+ null,
+ team.id,
+ folder.id
+ );
+ db.markConversationSynced(containerChat.id, "cloud-old-account-folder-chat");
+ db.addAgentMessage(containerChat.id, "assistant", "old-account scoped response");
+ db.markFolderSynced(folder.id, "cloud-old-account-folder");
+ assert.equal(db.deleteFolder(folder.id).success, true);
+ assert.ok(
+ db.db
+ .prepare(
+ "SELECT 1 FROM optimistic_folder_delete_rows WHERE folder_id = ? AND entity_type = 'folder'"
+ )
+ .get(folder.id),
+ "fixture includes an unresolved optimistic folder delete"
+ );
+
+ const privateNote = db.saveNote("Device note", "keep local device content").note;
+ const privateChat = db.createAgentConversation("Device chat", privateNote.id);
+ db.addAgentMessage(privateChat.id, "user", "keep this message");
+
+ const result = db.purgeSpace(team.id, { mode: "destructive" });
+ assert.equal(result.success, true);
+ assert.deepEqual(result.noteIds, [dirty.id]);
+ assert.equal(result.relocatedCount, 0);
+ assert.deepEqual(result.relocatedNotes, []);
+
+ const count = (sql, ...args) => db.db.prepare(sql).get(...args).count;
+ assert.equal(count("SELECT COUNT(*) AS count FROM notes WHERE id = ?", dirty.id), 0);
+ assert.equal(
+ count("SELECT COUNT(*) AS count FROM notes WHERE space_id = ?", privateId),
+ 1,
+ "a dirty team note must not fork into Personal during an account transition"
+ );
+ for (const conversation of [noteChat, containerChat]) {
+ assert.equal(
+ count("SELECT COUNT(*) AS count FROM agent_conversations WHERE id = ?", conversation.id),
+ 0,
+ "even a synced chat must be hard-deleted rather than left as a cloud-delete tombstone"
+ );
+ assert.equal(
+ count(
+ "SELECT COUNT(*) AS count FROM agent_messages WHERE conversation_id = ?",
+ conversation.id
+ ),
+ 0
+ );
+ }
+ assert.equal(db.getAgentConversation(privateChat.id).messages.length, 1);
+ assert.equal(
+ count(
+ "SELECT COUNT(*) AS count FROM optimistic_folder_delete_rows WHERE folder_id = ?",
+ folder.id
+ ),
+ 0,
+ "account-destructive purge clears rollback metadata"
+ );
+
+ // A late editor flush is UPDATE-only. Once destructive purge commits, it
+ // cannot recreate the deleted note under Personal or any other space.
+ const lateSave = db.updateNote(dirty.id, {
+ title: "Late old-account save",
+ content: "must not reappear",
+ });
+ assert.equal(lateSave.note, undefined);
+ assert.equal(count("SELECT COUNT(*) AS count FROM notes WHERE id = ?", dirty.id), 0);
+ assert.equal(count("SELECT COUNT(*) AS count FROM notes WHERE space_id = ?", privateId), 1);
+});
+
test("saveNote resolves default folders within the target space", (t) => {
const db = createDb(t);
if (!db) return;
@@ -619,26 +783,280 @@ test("moveFolderToSpace team→private flags the folder and its cloud-backed not
assert.equal(db.getNote(cloudNote.id).left_team, 0);
});
-test("markNoteSyncedIfUnchanged settles only rows untouched since the push snapshot", (t) => {
+test("markNoteSyncedIfUnchanged settles an exact identity and push snapshot", (t) => {
const db = createDb(t);
if (!db) return;
const note = db.saveNote("Doc", "v1").note;
+ db.markNoteSynced(note.id, "cloud-1", "2026-07-29T08:00:00.000Z", "owner-1");
+ db.updateNote(note.id, { content: "v2" });
const snapshot = db.getNote(note.id);
- const settled = db.markNoteSyncedIfUnchanged(note.id, "cloud-1", snapshot.updated_at);
+ const settled = db.markNoteSyncedIfUnchanged(
+ note.id,
+ snapshot,
+ "cloud-1",
+ "2026-07-29T09:00:00.000Z",
+ "owner-1"
+ );
+ assert.equal(settled.outcome, "synced");
assert.equal(settled.changes, 1);
assert.equal(db.getNote(note.id).sync_status, "synced");
assert.equal(db.getNote(note.id).cloud_id, "cloud-1");
+ assert.equal(db.getNote(note.id).cloud_updated_at, "2026-07-29T09:00:00.000Z");
+});
- // Simulate an edit landing while the PATCH was in flight.
+test("markNoteSyncedIfUnchanged keeps a same-second newer edit pending and advances its base", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const note = db.saveNote("Doc", "v1").note;
+ db.markNoteSynced(note.id, "cloud-1", "2026-07-29T08:00:00.000Z", "owner-1");
+ db.updateNote(note.id, { content: "v2" });
+ const snapshot = db.getNote(note.id);
+
+ // Do not touch updated_at: SQLite timestamps have second precision, so the
+ // full pushed snapshot—not the timestamp—must detect this newer edit.
db.db
- .prepare(
- "UPDATE notes SET content = 'v2', sync_status = 'pending', updated_at = datetime('now', '+1 hour') WHERE id = ?"
- )
+ .prepare("UPDATE notes SET content = 'v3', sync_status = 'pending' WHERE id = ?")
.run(note.id);
- const stale = db.markNoteSyncedIfUnchanged(note.id, "cloud-1", snapshot.updated_at);
+ const stale = db.markNoteSyncedIfUnchanged(
+ note.id,
+ snapshot,
+ "cloud-1",
+ "2026-07-29T09:00:00.000Z",
+ "owner-2"
+ );
+ assert.equal(stale.outcome, "pending");
assert.equal(stale.changes, 0);
- assert.equal(db.getNote(note.id).sync_status, "pending", "the mid-flight edit must still push");
+ const current = db.getNote(note.id);
+ assert.equal(current.content, "v3");
+ assert.equal(current.sync_status, "pending", "the mid-flight edit must still push");
+ assert.equal(current.cloud_id, "cloud-1");
+ assert.equal(current.cloud_updated_at, "2026-07-29T09:00:00.000Z");
+ assert.equal(current.owner_user_id, "owner-2");
+
+ // Reverting the local content to the first request's bytes does not make a
+ // late, older response safe to settle: the newer base proves PATCH 2 may be
+ // what the server currently stores.
+ db.db
+ .prepare("UPDATE notes SET content = ?, sync_status = 'pending', updated_at = ? WHERE id = ?")
+ .run(snapshot.content, snapshot.updated_at, note.id);
+ const late = db.markNoteSyncedIfUnchanged(
+ note.id,
+ snapshot,
+ "cloud-1",
+ "2026-07-29T08:30:00.000Z",
+ "owner-2"
+ );
+ assert.equal(late.outcome, "pending");
+ assert.equal(db.getNote(note.id).sync_status, "pending");
+ assert.equal(
+ db.getNote(note.id).cloud_updated_at,
+ "2026-07-29T09:00:00.000Z",
+ "an out-of-order response must not regress the newer server base"
+ );
+});
+
+test("markNoteSyncedIfUnchanged rejects a late PATCH response after an in-place identity fork", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const note = db.saveNote("Team draft", "v1").note;
+ db.markNoteSynced(note.id, "team-cloud-id", "2026-07-29T08:00:00.000Z", "team-owner");
+ db.updateNote(note.id, { content: "unpushed team edit" });
+ const teamSnapshot = db.getNote(note.id);
+
+ db.updateNote(note.id, {
+ content: "Personal fork",
+ client_note_id: "personal-fork-client-id",
+ cloud_id: null,
+ cloud_updated_at: null,
+ owner_user_id: null,
+ updated_by_user_id: null,
+ });
+ const forked = db.getNote(note.id);
+ const rejected = db.markNoteSyncedIfUnchanged(
+ note.id,
+ teamSnapshot,
+ "team-cloud-id",
+ "2026-07-29T09:00:00.000Z",
+ "team-owner"
+ );
+
+ assert.equal(rejected.outcome, "identity-changed");
+ assert.equal(rejected.changes, 0);
+ const afterResponse = db.getNote(note.id);
+ assert.equal(afterResponse.client_note_id, forked.client_note_id);
+ assert.equal(afterResponse.content, "Personal fork");
+ assert.equal(afterResponse.cloud_id, null);
+ assert.equal(afterResponse.cloud_updated_at, null);
+ assert.equal(afterResponse.owner_user_id, null);
+ assert.equal(afterResponse.sync_status, "pending");
+});
+
+test("acknowledgeNoteCreate settles only the exact create snapshot", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const note = db.saveNote("Doc", "v1").note;
+
+ const settled = db.acknowledgeNoteCreate(
+ note.id,
+ note,
+ "cloud-create-1",
+ "2026-07-29T10:00:00.000Z",
+ "owner-1"
+ );
+ assert.equal(settled.outcome, "synced");
+ assert.deepEqual(
+ {
+ cloud_id: db.getNote(note.id).cloud_id,
+ cloud_updated_at: db.getNote(note.id).cloud_updated_at,
+ owner_user_id: db.getNote(note.id).owner_user_id,
+ sync_status: db.getNote(note.id).sync_status,
+ },
+ {
+ cloud_id: "cloud-create-1",
+ cloud_updated_at: "2026-07-29T10:00:00.000Z",
+ owner_user_id: "owner-1",
+ sync_status: "synced",
+ }
+ );
+ const ambiguous = db.acknowledgeNoteCreate(
+ note.id,
+ note,
+ "different-cloud-id",
+ "2026-07-29T10:01:00.000Z",
+ "owner-1"
+ );
+ assert.equal(ambiguous.outcome, "unresolved");
+ assert.equal(
+ db.getNote(note.id).cloud_id,
+ "cloud-create-1",
+ "an ambiguous response must not replace or delete the adopted identity"
+ );
+
+ const racing = db.saveNote("Racing", "v1").note;
+ // Keep updated_at identical to the request snapshot: the acknowledgement
+ // must compare pushed fields too, because SQLite timestamps have only
+ // second precision and two edits can otherwise look unchanged.
+ db.db
+ .prepare("UPDATE notes SET content = 'v2', sync_status = 'pending' WHERE id = ?")
+ .run(racing.id);
+ const pending = db.acknowledgeNoteCreate(
+ racing.id,
+ racing,
+ "cloud-create-2",
+ "2026-07-29T11:00:00.000Z",
+ "owner-2"
+ );
+ const afterRace = db.getNote(racing.id);
+ assert.equal(pending.outcome, "pending");
+ assert.equal(afterRace.content, "v2");
+ assert.equal(afterRace.cloud_id, "cloud-create-2", "the next PATCH must target the created row");
+ assert.equal(afterRace.cloud_updated_at, "2026-07-29T11:00:00.000Z");
+ assert.equal(afterRace.owner_user_id, "owner-2");
+ assert.equal(afterRace.sync_status, "pending", "the intervening edit must still push");
+
+ const partial = db.saveNote("Migration", "body").note;
+ const partialAck = db.acknowledgeNoteCreate(
+ partial.id,
+ partial,
+ "migration-cloud-id",
+ "2026-07-29T11:30:00.000Z",
+ null,
+ false
+ );
+ const afterPartial = db.getNote(partial.id);
+ assert.equal(partialAck.outcome, "pending");
+ assert.equal(afterPartial.cloud_id, "migration-cloud-id");
+ assert.equal(
+ afterPartial.sync_status,
+ "pending",
+ "a partial migration create must still receive a full PATCH"
+ );
+
+ const recreated = db.saveNote("Fork", "local copy").note;
+ db.markNoteSynced(recreated.id, "old-cloud-id", "2026-07-28T09:00:00.000Z", "old-owner");
+ db.updateNote(recreated.id, {
+ client_note_id: "forked-client-note-id",
+ cloud_id: null,
+ sync_status: "pending",
+ });
+ const forkSnapshot = db.getNote(recreated.id);
+ assert.equal(forkSnapshot.cloud_updated_at, "2026-07-28T09:00:00.000Z");
+ assert.equal(forkSnapshot.owner_user_id, "old-owner");
+
+ const recreatedAck = db.acknowledgeNoteCreate(
+ recreated.id,
+ forkSnapshot,
+ "new-cloud-id",
+ null,
+ null
+ );
+ const afterRecreate = db.getNote(recreated.id);
+ assert.equal(recreatedAck.outcome, "synced");
+ assert.equal(afterRecreate.cloud_id, "new-cloud-id");
+ assert.equal(
+ afterRecreate.cloud_updated_at,
+ null,
+ "a null create base must clear the old identity's revision"
+ );
+ assert.equal(
+ afterRecreate.owner_user_id,
+ null,
+ "a null create owner must clear the old identity's owner"
+ );
+});
+
+test("acknowledgeNoteCreate never mutates an identity forked by purgeSpace", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const team = createTestTeamSpace(db, { name: "Create race" }).space;
+ const note = db.saveNote("Draft", "team work", "personal", null, null, null, team.id).note;
+ const originalClientNoteId = note.client_note_id;
+
+ const purge = db.purgeSpace(team.id);
+ assert.equal(purge.success, true);
+ const forked = db.getNote(note.id);
+ assert.notEqual(forked.client_note_id, originalClientNoteId);
+ assert.equal(forked.space_id, db.getPrivateSpaceId());
+
+ const ack = db.acknowledgeNoteCreate(
+ note.id,
+ note,
+ "stale-team-cloud-id",
+ "2026-07-29T12:00:00.000Z",
+ "owner-3"
+ );
+ const afterAck = db.getNote(note.id);
+ assert.equal(ack.outcome, "orphaned", "the caller may delete the stale cloud create");
+ assert.equal(afterAck.client_note_id, forked.client_note_id);
+ assert.equal(afterAck.cloud_id, null);
+ assert.equal(afterAck.owner_user_id, null);
+ assert.equal(afterAck.space_id, db.getPrivateSpaceId());
+ assert.equal(afterAck.sync_status, "pending");
+});
+
+test("acknowledgeNoteCreate queues a team-to-Personal move for scope retraction", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const team = createTestTeamSpace(db, { name: "Move race" }).space;
+ const note = db.saveNote("Draft", "team work", "personal", null, null, null, team.id).note;
+
+ db.updateNote(note.id, { space_id: db.getPrivateSpaceId(), folder_id: null });
+ const ack = db.acknowledgeNoteCreate(
+ note.id,
+ note,
+ "team-cloud-id",
+ "2026-07-29T13:00:00.000Z",
+ "owner-4"
+ );
+ const moved = db.getNote(note.id);
+ assert.equal(ack.outcome, "pending");
+ assert.equal(moved.cloud_id, "team-cloud-id");
+ assert.equal(moved.left_team, 1);
+ assert.ok(
+ db.getPendingNotes("team").some((candidate) => candidate.id === note.id),
+ "the retraction must push even when personal backup is disabled"
+ );
});
test("cloud_updated_at follows the pull, edit, push, and conflict lifecycle", (t) => {
@@ -674,8 +1092,8 @@ test("cloud_updated_at follows the pull, edit, push, and conflict lifecycle", (t
const settled = db.markNoteSyncedIfUnchanged(
pulled.id,
+ pushSnapshot,
pulled.cloud_id,
- pushSnapshot.updated_at,
pushedCloudRevision
);
assert.equal(settled.changes, 1);
@@ -691,8 +1109,8 @@ test("cloud_updated_at follows the pull, edit, push, and conflict lifecycle", (t
.run(pulled.id);
const raced = db.markNoteSyncedIfUnchanged(
pulled.id,
+ racingSnapshot,
pulled.cloud_id,
- racingSnapshot.updated_at,
conflictCloudRevision
);
assert.equal(raced.changes, 0);
@@ -715,27 +1133,203 @@ test("cloud_updated_at follows the pull, edit, push, and conflict lifecycle", (t
);
});
-test("markFolderSyncedIfUnchanged settles only rows untouched since the push snapshot", (t) => {
+test("markFolderSyncedIfUnchanged compares the full pushed folder snapshot", (t) => {
const db = createDb(t);
if (!db) return;
const folder = db.createFolder("Design").folder;
const readFolder = () => db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id);
- const snapshot = readFolder();
+ db.markFolderSynced(folder.id, "cloud-folder-1");
+ db.renameFolder(folder.id, "Design queued");
+ const exactSnapshot = readFolder();
- const settled = db.markFolderSyncedIfUnchanged(folder.id, "cloud-folder-1", snapshot.updated_at);
+ const settled = db.markFolderSyncedIfUnchanged(folder.id, exactSnapshot, "cloud-folder-1");
+ assert.equal(settled.outcome, "synced");
assert.equal(settled.changes, 1);
assert.equal(readFolder().sync_status, "synced");
assert.equal(readFolder().cloud_id, "cloud-folder-1");
- // Simulate a rename landing while the PATCH was in flight.
+ db.renameFolder(folder.id, "Design v2");
+ const racingSnapshot = readFolder();
+ // Simulate a second rename landing in the same SQLite timestamp tick while
+ // the PATCH is in flight. Timestamp-only guards cannot distinguish this.
db.db
- .prepare(
- "UPDATE folders SET name = 'Design v2', sync_status = 'pending', updated_at = datetime('now', '+1 hour') WHERE id = ?"
- )
+ .prepare("UPDATE folders SET name = 'Design v3', sync_status = 'pending' WHERE id = ?")
.run(folder.id);
- const stale = db.markFolderSyncedIfUnchanged(folder.id, "cloud-folder-1", snapshot.updated_at);
+ assert.equal(readFolder().updated_at, racingSnapshot.updated_at);
+ const stale = db.markFolderSyncedIfUnchanged(folder.id, racingSnapshot, "cloud-folder-1");
+ assert.equal(stale.outcome, "pending");
assert.equal(stale.changes, 0);
assert.equal(readFolder().sync_status, "pending", "the mid-flight rename must still push");
+ assert.equal(readFolder().name, "Design v3");
+});
+
+test("folder PATCH acknowledgement never mutates an in-place revocation fork", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const privateId = db.getPrivateSpaceId();
+ const team = createTestTeamSpace(db, { name: "Folder PATCH race" }).space;
+ const folder = db.createFolder("Team designs", team.id).folder;
+ db.markFolderSynced(folder.id, "old-cloud-folder");
+ db.renameFolder(folder.id, "Team designs queued");
+ const snapshot = db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id);
+
+ const relocation = db.relocateRevokedFolder(folder.id, privateId, true);
+ assert.equal(relocation.success, true);
+ const forked = db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id);
+ assert.notEqual(forked.client_folder_id, snapshot.client_folder_id);
+ assert.equal(forked.cloud_id, null);
+
+ const ack = db.markFolderSyncedIfUnchanged(folder.id, snapshot, "old-cloud-folder");
+ const afterAck = db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id);
+ assert.equal(ack.outcome, "identity-changed");
+ assert.equal(ack.changes, 0);
+ assert.deepEqual(afterAck, forked);
+
+ const adoptAck = db.acknowledgeFolderCreate(
+ folder.id,
+ snapshot,
+ snapshot.cloud_id,
+ "canonical-old-client-folder",
+ "old-cloud-folder",
+ "2026-07-29T13:30:00.000Z"
+ );
+ assert.equal(adoptAck.outcome, "identity-changed");
+ assert.equal(adoptAck.changes, 0);
+ assert.deepEqual(
+ db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id),
+ forked,
+ "a late pull-side identity adoption must not overwrite the fork either"
+ );
+});
+
+test("acknowledgeFolderCreate settles an exact snapshot and adopts collision identity", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const folder = db.createFolder("Collision candidate").folder;
+ const snapshot = db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id);
+ const cloudUpdatedAt = "2026-07-29T14:00:00.000Z";
+
+ const ack = db.acknowledgeFolderCreate(
+ folder.id,
+ snapshot,
+ snapshot.cloud_id,
+ "cloud-winner-client-folder",
+ "cloud-winner-folder",
+ cloudUpdatedAt
+ );
+ const linked = db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id);
+ assert.equal(ack.outcome, "synced");
+ assert.equal(ack.changes, 1);
+ assert.equal(linked.client_folder_id, "cloud-winner-client-folder");
+ assert.equal(linked.cloud_id, "cloud-winner-folder");
+ assert.equal(linked.sync_status, "synced");
+ assert.equal(linked.updated_at, cloudUpdatedAt);
+});
+
+test("acknowledgeFolderCreate guards pull-side adoption with the pre-request cloud id", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const folder = db.createFolder("Already linked").folder;
+ db.markFolderSynced(folder.id, "cloud-linked-folder");
+ db.renameFolder(folder.id, "Already linked queued");
+ const snapshot = db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id);
+
+ const ack = db.acknowledgeFolderCreate(
+ folder.id,
+ snapshot,
+ snapshot.cloud_id,
+ "canonical-linked-client-folder",
+ "cloud-linked-folder",
+ "2026-07-29T14:30:00.000Z"
+ );
+ const adopted = db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id);
+ assert.equal(ack.outcome, "synced");
+ assert.equal(ack.changes, 1);
+ assert.equal(adopted.client_folder_id, "canonical-linked-client-folder");
+ assert.equal(adopted.cloud_id, "cloud-linked-folder");
+ assert.equal(adopted.sync_status, "synced");
+});
+
+test("acknowledgeFolderCreate adopts onto a newer same-identity edit without settling it", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const folder = db.createFolder("Roadmap").folder;
+ const snapshot = db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id);
+
+ db.db
+ .prepare("UPDATE folders SET name = 'Roadmap v2', sync_status = 'pending' WHERE id = ?")
+ .run(folder.id);
+ const ack = db.acknowledgeFolderCreate(
+ folder.id,
+ snapshot,
+ snapshot.cloud_id,
+ folder.client_folder_id,
+ "cloud-roadmap",
+ "2026-07-29T15:00:00.000Z"
+ );
+ const linked = db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id);
+ assert.equal(linked.updated_at, snapshot.updated_at, "the edit shares the request timestamp");
+ assert.equal(ack.outcome, "pending");
+ assert.equal(ack.changes, 1);
+ assert.equal(linked.name, "Roadmap v2");
+ assert.equal(linked.cloud_id, "cloud-roadmap");
+ assert.equal(linked.sync_status, "pending");
+});
+
+test("acknowledgeFolderCreate queues a team-to-Personal move for scope retraction", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const team = createTestTeamSpace(db, { name: "Folder move race" }).space;
+ const folder = db.createFolder("Moving folder", team.id).folder;
+ const snapshot = db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id);
+
+ const move = db.moveFolderToSpace(folder.id, db.getPrivateSpaceId());
+ assert.equal(move.success, true);
+ const ack = db.acknowledgeFolderCreate(
+ folder.id,
+ snapshot,
+ snapshot.cloud_id,
+ folder.client_folder_id,
+ "team-folder-created-in-flight",
+ "2026-07-29T15:30:00.000Z"
+ );
+ const moved = db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id);
+ assert.equal(ack.outcome, "pending");
+ assert.equal(moved.cloud_id, "team-folder-created-in-flight");
+ assert.equal(moved.left_team, 1);
+ assert.ok(
+ db.getPendingFolders("team").some((candidate) => candidate.id === folder.id),
+ "the scope retraction must push even when personal backup is disabled"
+ );
+});
+
+test("acknowledgeFolderCreate never reattaches a folder forked during the request", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const privateId = db.getPrivateSpaceId();
+ const team = createTestTeamSpace(db, { name: "Folder create race" }).space;
+ const folder = db.createFolder("Fresh team folder", team.id).folder;
+ const snapshot = db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id);
+
+ const relocation = db.relocateRevokedFolder(folder.id, privateId, true);
+ assert.equal(relocation.success, true);
+ const forked = db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id);
+ assert.notEqual(forked.client_folder_id, snapshot.client_folder_id);
+
+ const ack = db.acknowledgeFolderCreate(
+ folder.id,
+ snapshot,
+ snapshot.cloud_id,
+ snapshot.client_folder_id,
+ "stale-team-cloud-folder",
+ "2026-07-29T16:00:00.000Z"
+ );
+ const afterAck = db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id);
+ assert.equal(ack.outcome, "identity-changed");
+ assert.equal(ack.changes, 0);
+ assert.deepEqual(afterAck, forked);
+ assert.equal(afterAck.cloud_id, null);
+ assert.equal(afterAck.sync_status, "pending");
});
test("relocateRevokedFolder preserves dirty children and hard-deletes server-owned ones", (t) => {
@@ -749,10 +1343,15 @@ test("relocateRevokedFolder preserves dirty children and hard-deletes server-own
const clean = db.saveNote("Recap", "server copy", "personal", null, null, folder.id).note;
db.markNoteSynced(clean.id, "cloud-note-1");
const dirty = db.saveNote("Edits", "unpushed work", "personal", null, null, folder.id).note;
- db.markNoteSynced(dirty.id, "cloud-note-2");
+ db.markNoteSynced(dirty.id, "cloud-note-2", "2026-07-28T07:00:00.000Z", "revoked-folder-owner");
db.updateNote(dirty.id, { content: "unpushed work v2" });
db.updateNoteShareState(dirty.id, { is_shared: 1, share_token: "revoked-folder-token" });
const draft = db.saveNote("Draft", "never synced", "personal", null, null, folder.id).note;
+ const cleanChat = db.createAgentConversation("Clean note chat", clean.id);
+ db.markConversationSynced(cleanChat.id, "cloud-conversation-1");
+ db.addAgentMessage(cleanChat.id, "user", "revoked team content");
+ const dirtyChat = db.createAgentConversation("Dirty note chat", dirty.id, team.id, folder.id);
+ db.addAgentMessage(dirtyChat.id, "user", "keep this local edit");
db.db
.prepare(
"INSERT INTO speaker_mappings (note_id, speaker_id, display_name) VALUES (?, 'spk_0', 'Alice')"
@@ -783,8 +1382,27 @@ test("relocateRevokedFolder preserves dirty children and hard-deletes server-own
assert.equal(survivor.sync_status, "pending");
}
assert.notEqual(db.getNote(dirty.id).client_note_id, dirty.client_note_id, "identity forked");
+ assert.equal(db.getNote(dirty.id).cloud_updated_at, null, "fork clears the old cloud base");
+ assert.equal(db.getNote(dirty.id).owner_user_id, null, "fork clears the old owner");
assert.equal(db.getNote(dirty.id).is_shared, 0, "forked note is private");
assert.equal(db.getNote(dirty.id).share_token, null, "forked note drops its share token");
+ const retiredChat = db.db
+ .prepare("SELECT * FROM agent_conversations WHERE id = ?")
+ .get(cleanChat.id);
+ assert.ok(retiredChat.deleted_at, "the removed note's synced chat is retired");
+ assert.equal(
+ db.db
+ .prepare("SELECT COUNT(*) AS count FROM agent_messages WHERE conversation_id = ?")
+ .get(cleanChat.id).count,
+ 0,
+ "revoked team chat content is removed"
+ );
+ assert.deepEqual(db.getConversationsForNote(clean.id), []);
+ const relocatedChat = db.getAgentConversation(dirtyChat.id);
+ assert.equal(relocatedChat.note_id, dirty.id);
+ assert.equal(relocatedChat.space_id, null);
+ assert.equal(relocatedChat.folder_id, null);
+ assert.equal(relocatedChat.messages.length, 1, "the dirty note's chat follows its Personal fork");
// Dirty folder: preserved in Personal with a forked identity, children keep
// their folder link, and a name collision falls back to a suffixed rename.
@@ -932,7 +1550,7 @@ test("purgeSpace preserves dirty cloud-backed notes with forked identities", (t)
null,
folder.id
).note;
- db.markNoteSynced(dirty.id, "cloud-dirty-note");
+ db.markNoteSynced(dirty.id, "cloud-dirty-note", "2026-07-28T08:00:00.000Z", "old-team-owner");
db.updateNote(dirty.id, { content: "walrus intel v2" });
db.updateNoteShareState(dirty.id, { is_shared: 1, share_token: "purged-space-token" });
const errored = db.saveNote(
@@ -943,7 +1561,7 @@ test("purgeSpace preserves dirty cloud-backed notes with forked identities", (t)
null,
folder.id
).note;
- db.markNoteSynced(errored.id, "cloud-error-note");
+ db.markNoteSynced(errored.id, "cloud-error-note", "2026-07-28T08:30:00.000Z", "old-team-owner");
db.updateNote(errored.id, { content: "narwhal v2" });
db.markNoteSyncError(errored.id);
const clean = db.saveNote("Clean", "synced beluga", "personal", null, null, folder.id).note;
@@ -964,6 +1582,8 @@ test("purgeSpace preserves dirty cloud-backed notes with forked identities", (t)
assert.equal(relocated.space_id, privateId);
assert.equal(relocated.folder_id, null);
assert.equal(relocated.cloud_id, null);
+ assert.equal(relocated.cloud_updated_at, null);
+ assert.equal(relocated.owner_user_id, null);
assert.equal(relocated.sync_status, "pending");
assert.equal(relocated.left_team, 0);
assert.notEqual(relocated.client_note_id, prior.client_note_id);
diff --git a/test/lib/authAccountScope.test.js b/test/lib/authAccountScope.test.js
new file mode 100644
index 000000000..2eeba1dda
--- /dev/null
+++ b/test/lib/authAccountScope.test.js
@@ -0,0 +1,262 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const {
+ accountScopeRequiresPurge,
+ accountScopeRetryDelay,
+ decideAccountScopeAction,
+ getAccountScopeRevision,
+ markAccountScopePurgeRequired,
+ reconcileAccountScope,
+ resetAccountScopeRetry,
+ scheduleAccountScopeRetry,
+ shouldBlockAccountScope,
+ shouldReconcileAccountScope,
+} = require("../../src/lib/authAccountScope.ts");
+
+const decide = (overrides = {}) =>
+ decideAccountScopeAction({
+ userId: null,
+ previousUserId: null,
+ wasSignedIn: false,
+ hasTeamSpaces: false,
+ scopeValidated: true,
+ purgeRequired: false,
+ ...overrides,
+ });
+
+function installStorage(initial = {}) {
+ const values = new Map(Object.entries(initial));
+ const previousWindow = global.window;
+ global.window = {
+ localStorage: {
+ getItem: (key) => values.get(key) ?? null,
+ setItem: (key, value) => values.set(key, String(value)),
+ removeItem: (key) => values.delete(key),
+ },
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ };
+ return {
+ values,
+ restore: () => {
+ global.window = previousWindow;
+ },
+ };
+}
+
+test("passive session loss purges the previous account scope", () => {
+ assert.equal(
+ decide({ previousUserId: "user-a", wasSignedIn: true, hasTeamSpaces: true }),
+ "purge"
+ );
+});
+
+test("a direct account replacement purges before remembering the new user", () => {
+ assert.equal(decide({ userId: "user-b", previousUserId: "user-a", wasSignedIn: true }), "purge");
+});
+
+test("reauthentication after signed-out state purges any retained account scope", () => {
+ assert.equal(decide({ userId: "user-a", previousUserId: "user-a", wasSignedIn: false }), "purge");
+});
+
+test("cached team capability is purged even when an older build stored no user id", () => {
+ assert.equal(decide({ userId: "user-b", hasTeamSpaces: true }), "purge");
+});
+
+test("the current signed-in account remains ready without a destructive purge", () => {
+ assert.equal(decide({ userId: "user-a", previousUserId: "user-a", wasSignedIn: true }), "none");
+});
+
+test("an unvalidated clean signed-out install validates locally while a signed-in install verifies", () => {
+ assert.equal(decide({ scopeValidated: false }), "remember-user");
+ assert.equal(decide({ userId: "user-a", scopeValidated: false }), "verify");
+});
+
+test("an upgrade validates its local database even with an existing signed-in marker", () => {
+ assert.equal(decide({ userId: "user-a", wasSignedIn: true, scopeValidated: false }), "verify");
+});
+
+test("validated clean signed-out state remains local-only", () => {
+ assert.equal(decide(), "none");
+});
+
+test("a failed or interrupted purge keeps the scope blocked after capability is cleared", () => {
+ assert.equal(
+ decide({
+ userId: "user-b",
+ wasSignedIn: false,
+ hasTeamSpaces: false,
+ scopeValidated: true,
+ purgeRequired: true,
+ }),
+ "purge"
+ );
+});
+
+test("grace suppresses a null-session flicker but never a resolved account replacement", () => {
+ assert.equal(shouldBlockAccountScope(false, true, false, true), false);
+ assert.equal(shouldReconcileAccountScope(false, true, false), false);
+ assert.equal(shouldBlockAccountScope(false, true, true, true), true);
+ assert.equal(shouldReconcileAccountScope(false, true, true), true);
+});
+
+test("grace cannot release an account transition after its purge becomes mandatory", () => {
+ assert.equal(shouldBlockAccountScope(false, true, false, true, true), true);
+});
+
+test("a session fetch error blocks cached account scope without authorizing purge", () => {
+ assert.equal(
+ shouldBlockAccountScope(false, true, false, true, false, true),
+ true,
+ "unverified old-account content stays behind the auth gate even during grace"
+ );
+ assert.equal(
+ shouldReconcileAccountScope(false, false, false, true),
+ false,
+ "a network error must not be interpreted as definitive sign-out"
+ );
+
+ assert.equal(
+ shouldReconcileAccountScope(false, false, false, false),
+ true,
+ "resolved data:null/error:null remains a definitive no-session result"
+ );
+});
+
+test("a rejected purge persists the required marker even after capability disappears", async (t) => {
+ const { values, restore } = installStorage({
+ "openwhispr:accountScopeUserId": "user-a",
+ "openwhispr:accountScopeValidated": "true",
+ isSignedIn: "true",
+ teamSpacesCapability: "true",
+ });
+ t.after(restore);
+
+ await assert.rejects(
+ reconcileAccountScope(null, {
+ purge: async () => {
+ values.delete("teamSpacesCapability");
+ throw new Error("database unavailable");
+ },
+ verify: async () => {
+ throw new Error("unexpected verification");
+ },
+ }),
+ /database unavailable/
+ );
+
+ assert.equal(values.get("openwhispr:accountScopePurgeRequired"), "true");
+ assert.equal(accountScopeRequiresPurge(null), true);
+});
+
+test("the required marker survives clearing the legacy signed-in evidence", async (t) => {
+ const { values, restore } = installStorage({
+ "openwhispr:accountScopeValidated": "true",
+ isSignedIn: "true",
+ });
+ t.after(restore);
+
+ assert.equal(accountScopeRequiresPurge(null), true);
+ markAccountScopePurgeRequired();
+ values.set("isSignedIn", "false");
+
+ let purgeCalls = 0;
+ await reconcileAccountScope(null, {
+ purge: async () => {
+ purgeCalls += 1;
+ },
+ verify: async () => {
+ throw new Error("unexpected verification");
+ },
+ });
+
+ assert.equal(purgeCalls, 1);
+ assert.equal(values.has("openwhispr:accountScopePurgeRequired"), false);
+});
+
+test("concurrent hook reconciliations share one purge and release only after verification", async (t) => {
+ const { values, restore } = installStorage({
+ "openwhispr:accountScopeUserId": "user-a",
+ "openwhispr:accountScopeValidated": "true",
+ isSignedIn: "true",
+ teamSpacesCapability: "true",
+ });
+ t.after(restore);
+
+ let release;
+ const verificationGate = new Promise((resolve) => {
+ release = resolve;
+ });
+ let purgeCalls = 0;
+ const purge = async () => {
+ purgeCalls += 1;
+ await verificationGate;
+ values.delete("teamSpacesCapability");
+ };
+
+ const callbacks = {
+ purge,
+ verify: async () => {
+ throw new Error("unexpected verification");
+ },
+ };
+ const reconciliations = [
+ reconcileAccountScope(null, callbacks),
+ reconcileAccountScope(null, callbacks),
+ reconcileAccountScope(null, callbacks),
+ ];
+ release();
+ await Promise.all(reconciliations);
+
+ assert.equal(purgeCalls, 1);
+ assert.equal(values.get("isSignedIn"), "false");
+ assert.equal(values.has("openwhispr:accountScopeUserId"), false);
+ assert.equal(values.has("openwhispr:accountScopePurgeRequired"), false);
+ assert.equal(accountScopeRequiresPurge(null), false);
+});
+
+test("failed first-upgrade verification stays non-destructive and unvalidated", async (t) => {
+ const { values, restore } = installStorage({
+ isSignedIn: "true",
+ teamSpacesCapability: "true",
+ });
+ t.after(restore);
+
+ let purgeCalls = 0;
+ await assert.rejects(
+ reconcileAccountScope("user-a", {
+ purge: async () => {
+ purgeCalls += 1;
+ },
+ verify: async () => {
+ throw new Error("offline");
+ },
+ }),
+ /offline/
+ );
+
+ assert.equal(purgeCalls, 0);
+ assert.equal(values.get("teamSpacesCapability"), "true");
+ assert.equal(values.has("openwhispr:accountScopePurgeRequired"), false);
+ assert.equal(values.has("openwhispr:accountScopeValidated"), false);
+});
+
+test("account reconciliation retry backoff is bounded", () => {
+ assert.equal(accountScopeRetryDelay(0), 1000);
+ assert.equal(accountScopeRetryDelay(1), 2000);
+ assert.equal(accountScopeRetryDelay(5), 30000);
+ assert.equal(accountScopeRetryDelay(100), 30000);
+});
+
+test("a failed reconciliation schedules a new revision without a reload", (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ resetAccountScopeRetry();
+ const before = getAccountScopeRevision();
+ scheduleAccountScopeRetry("4:user-a");
+ t.mock.timers.tick(999);
+ assert.equal(getAccountScopeRevision(), before);
+ t.mock.timers.tick(1);
+ assert.equal(getAccountScopeRevision(), before + 1);
+ resetAccountScopeRetry();
+});
diff --git a/test/lib/authRequestContext.test.js b/test/lib/authRequestContext.test.js
new file mode 100644
index 000000000..1b7a21054
--- /dev/null
+++ b/test/lib/authRequestContext.test.js
@@ -0,0 +1,154 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+function installWindow(state) {
+ const previousWindow = global.window;
+ global.window = {
+ location: { origin: "https://desktop.openwhispr.test" },
+ electronAPI: {
+ authGetTokenState: async () => ({ ...state.current }),
+ authSetToken: async (token, expectedGeneration) => {
+ if (state.current.generation !== expectedGeneration) {
+ return {
+ success: false,
+ code: "AUTH_CONTEXT_CHANGED",
+ ...state.current,
+ };
+ }
+ if (state.current.token !== token) {
+ state.current = {
+ token,
+ generation: state.current.generation + 1,
+ };
+ }
+ state.onSet?.(state.current);
+ return { success: true, ...state.current };
+ },
+ },
+ };
+ return () => {
+ global.window = previousWindow;
+ };
+}
+
+function sessionRequest(generation, token) {
+ return {
+ url: "https://auth.openwhispr.test/api/auth/get-session",
+ headers: new Headers(token ? { Authorization: `Bearer ${token}` } : {}),
+ openWhisprAuthGeneration: generation,
+ };
+}
+
+test("only the exact session user and credential generation can be committed", async (t) => {
+ const auth = await import("../../src/lib/authRequestContext.ts");
+ auth.resetAuthRequestContextForTests();
+ const state = { current: { token: "token-a", generation: 4 } };
+ t.after(installWindow(state));
+
+ await auth.handleAuthRequestSuccess({
+ data: { user: { id: "user-a" }, session: { id: "session-a" } },
+ response: new Response("{}", { status: 200 }),
+ request: sessionRequest(4, "token-a"),
+ });
+
+ assert.equal(auth.getBoundSessionGeneration("user-a"), 4);
+ assert.equal(auth.getBoundSessionGeneration("user-b"), null);
+ assert.equal(auth.commitValidatedAuthContext(4, "user-b"), false);
+ assert.equal(auth.commitValidatedAuthContext(4, "user-a"), true);
+ assert.equal(auth.getValidatedAuthGeneration(), 4);
+
+ await auth.handleAuthRequestSuccess({
+ data: null,
+ response: new Response("null", { status: 200 }),
+ request: sessionRequest(4, "token-a"),
+ });
+ assert.equal(auth.getBoundSessionGeneration(null), 4);
+ assert.equal(auth.getValidatedAuthGeneration(), null);
+
+ auth.observeAuthTokenStateEvent({ generation: 5, hasToken: true });
+ assert.equal(auth.getBoundSessionGeneration("user-a"), null);
+ assert.equal(auth.getValidatedAuthGeneration(), null);
+});
+
+test("a compare-and-set rotation binds the session response to the new generation", async (t) => {
+ const auth = await import("../../src/lib/authRequestContext.ts");
+ auth.resetAuthRequestContextForTests();
+ const state = {
+ current: { token: "token-a", generation: 1 },
+ onSet: (next) => {
+ // Main broadcasts before the invoke response resolves.
+ auth.observeAuthTokenStateEvent({
+ generation: next.generation,
+ hasToken: Boolean(next.token),
+ });
+ },
+ };
+ t.after(installWindow(state));
+
+ await auth.handleAuthRequestSuccess({
+ data: { user: { id: "user-a" } },
+ response: new Response("{}", {
+ status: 200,
+ headers: { "set-auth-token": "token-a-rotated" },
+ }),
+ request: sessionRequest(1, "token-a"),
+ });
+
+ assert.equal(state.current.generation, 2);
+ assert.equal(auth.getBoundSessionGeneration("user-a"), 2);
+ assert.equal(auth.commitValidatedAuthContext(2, "user-a"), true);
+});
+
+test("a token replacement before fetch prevents the request from leaving", async (t) => {
+ const auth = await import("../../src/lib/authRequestContext.ts");
+ auth.resetAuthRequestContextForTests();
+ const state = { current: { token: "token-a", generation: 7 } };
+ t.after(installWindow(state));
+ const request = await auth.prepareAuthRequest({
+ url: "https://auth.openwhispr.test/api/auth/get-session",
+ headers: new Headers(),
+ });
+
+ state.current = { token: "token-b", generation: 8 };
+ let fetchCalls = 0;
+ const previousFetch = global.fetch;
+ global.fetch = async () => {
+ fetchCalls += 1;
+ return new Response("{}");
+ };
+ t.after(() => {
+ global.fetch = previousFetch;
+ });
+
+ await assert.rejects(auth.authContextFetch(request.url, request), {
+ code: "AUTH_CONTEXT_CHANGED",
+ });
+ assert.equal(fetchCalls, 0);
+});
+
+test("a token replacement while fetch is in flight discards the old response", async (t) => {
+ const auth = await import("../../src/lib/authRequestContext.ts");
+ auth.resetAuthRequestContextForTests();
+ const state = { current: { token: "token-a", generation: 11 } };
+ t.after(installWindow(state));
+ const request = await auth.prepareAuthRequest({
+ url: "https://auth.openwhispr.test/api/auth/get-session",
+ headers: new Headers(),
+ });
+
+ let release;
+ const pending = new Promise((resolve) => {
+ release = resolve;
+ });
+ const previousFetch = global.fetch;
+ global.fetch = async () => pending;
+ t.after(() => {
+ global.fetch = previousFetch;
+ });
+
+ const responsePromise = auth.authContextFetch(request.url, request);
+ state.current = { token: "token-b", generation: 12 };
+ release(new Response(JSON.stringify({ user: { id: "user-a" } })));
+
+ await assert.rejects(responsePromise, { code: "AUTH_CONTEXT_CHANGED" });
+});
diff --git a/test/lib/noteConflictRegistry.test.js b/test/lib/noteConflictRegistry.test.js
index cf0efbdce..e36c0589b 100644
--- a/test/lib/noteConflictRegistry.test.js
+++ b/test/lib/noteConflictRegistry.test.js
@@ -71,3 +71,13 @@ test("drops legacy id-only storage so a guarded push can re-surface it", async (
assert.equal(localStorage.getItem("noteConflicts.clientIds"), null);
assert.deepEqual([...readNoteConflictIds()], []);
});
+
+test("account transition clears every persisted cloud conflict snapshot", async () => {
+ const { addNoteConflict, clearNoteConflicts, readNoteConflicts } = await load();
+
+ addNoteConflict("client-note", cloudNote);
+ clearNoteConflicts();
+
+ assert.deepEqual(readNoteConflicts(), {});
+ assert.equal(localStorage.getItem("noteConflicts.clientIds"), null);
+});
diff --git a/test/lib/noteEditorPendingSave.test.js b/test/lib/noteEditorPendingSave.test.js
new file mode 100644
index 000000000..91dd00688
--- /dev/null
+++ b/test/lib/noteEditorPendingSave.test.js
@@ -0,0 +1,65 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../src/lib/noteEditorPendingSave.ts");
+
+test("returns no update when the editor has no pending timers", async () => {
+ const { buildPendingNoteUpdates } = await load();
+
+ assert.equal(
+ buildPendingNoteUpdates({
+ title: "Title",
+ content: "Body",
+ enhancedContent: "Enhanced",
+ documentPending: false,
+ enhancedPending: false,
+ }),
+ null
+ );
+});
+
+test("flushes only the editor buffers represented by pending timers", async () => {
+ const { buildPendingNoteUpdates } = await load();
+ const snapshot = {
+ title: "Latest title",
+ content: "Latest body",
+ enhancedContent: "Latest enhancement",
+ };
+
+ assert.deepEqual(
+ buildPendingNoteUpdates({
+ ...snapshot,
+ documentPending: true,
+ enhancedPending: false,
+ }),
+ { title: "Latest title", content: "Latest body" }
+ );
+ assert.deepEqual(
+ buildPendingNoteUpdates({
+ ...snapshot,
+ documentPending: false,
+ enhancedPending: true,
+ }),
+ { enhanced_content: "Latest enhancement" }
+ );
+ assert.deepEqual(
+ buildPendingNoteUpdates({
+ ...snapshot,
+ documentPending: true,
+ enhancedPending: true,
+ }),
+ {
+ title: "Latest title",
+ content: "Latest body",
+ enhanced_content: "Latest enhancement",
+ }
+ );
+});
+
+test("deleting another sidebar note keeps the active note's pending save", async () => {
+ const { shouldCancelPendingSavesForDelete } = await load();
+
+ assert.equal(shouldCancelPendingSavesForDelete(17, 23), false);
+ assert.equal(shouldCancelPendingSavesForDelete(17, 17), true);
+ assert.equal(shouldCancelPendingSavesForDelete(null, 17), false);
+});
diff --git a/test/lib/notePermissions.test.js b/test/lib/notePermissions.test.js
new file mode 100644
index 000000000..a8972efc3
--- /dev/null
+++ b/test/lib/notePermissions.test.js
@@ -0,0 +1,66 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const {
+ canOrganizeNote,
+ noteCapabilities,
+ resolveNotePermission,
+ sharedNoteBlocksDelete,
+} = require("../../src/lib/notePermissions.ts");
+
+// The scopes where per-note ACLs apply: only cloud-backed personal notes.
+const sharedPersonal = { isTeamNote: false, hasCloudCopy: true };
+const localPersonal = { isTeamNote: false, hasCloudCopy: false };
+const teamNote = { isTeamNote: true, hasCloudCopy: true };
+
+test("sharedNoteBlocksDelete: editors and viewers of a shared personal note lose Delete", () => {
+ assert.equal(sharedNoteBlocksDelete("editor", sharedPersonal), true);
+ assert.equal(sharedNoteBlocksDelete("viewer", sharedPersonal), true);
+ assert.equal(sharedNoteBlocksDelete(null, sharedPersonal), true);
+ assert.equal(sharedNoteBlocksDelete("owner", sharedPersonal), false);
+});
+
+test("sharedNoteBlocksDelete: never vetoes team or local-only notes", () => {
+ // Team notes follow space roles (spacePermissions) — the ACL "editor"
+ // fallback must not strip a space admin's delete.
+ assert.equal(sharedNoteBlocksDelete("editor", teamNote), false);
+ assert.equal(sharedNoteBlocksDelete("viewer", teamNote), false);
+ assert.equal(sharedNoteBlocksDelete("editor", localPersonal), false);
+ assert.equal(sharedNoteBlocksDelete(null, localPersonal), false);
+});
+
+test("canOrganizeNote: re-filing a shared personal note is owner-only", () => {
+ assert.equal(canOrganizeNote("owner", sharedPersonal), true);
+ assert.equal(canOrganizeNote("editor", sharedPersonal), false);
+ assert.equal(canOrganizeNote("viewer", sharedPersonal), false);
+ assert.equal(canOrganizeNote(null, sharedPersonal), false);
+});
+
+test("canOrganizeNote: team and local-only notes stay freely movable", () => {
+ assert.equal(canOrganizeNote("editor", teamNote), true);
+ assert.equal(canOrganizeNote("viewer", teamNote), true);
+ assert.equal(canOrganizeNote(null, localPersonal), true);
+});
+
+test("unknown ACLs keep the owner fallback for personal notes", () => {
+ // A note never opened this session (no share-cache entry) resolves through
+ // the "unavailable" state and must not lose actions it had before.
+ const fallback = resolveNotePermission({
+ cachedPermission: undefined,
+ aclState: "unavailable",
+ isTeamNote: false,
+ });
+ assert.equal(fallback, "owner");
+ assert.equal(sharedNoteBlocksDelete(fallback, sharedPersonal), false);
+ assert.equal(canOrganizeNote(fallback, sharedPersonal), true);
+});
+
+test("loaded ACLs drive the veto end to end", () => {
+ const editor = resolveNotePermission({
+ cachedPermission: "editor",
+ aclState: "loaded",
+ isTeamNote: false,
+ });
+ assert.equal(noteCapabilities(editor).canDelete, false);
+ assert.equal(sharedNoteBlocksDelete(editor, sharedPersonal), true);
+ assert.equal(canOrganizeNote(editor, sharedPersonal), false);
+});
diff --git a/test/services/accountSpaceValidation.test.js b/test/services/accountSpaceValidation.test.js
new file mode 100644
index 000000000..5cefb10a0
--- /dev/null
+++ b/test/services/accountSpaceValidation.test.js
@@ -0,0 +1,69 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const localSpace = (overrides) => ({
+ id: 1,
+ kind: "team",
+ cloud_space_id: null,
+ cloud_team_id: null,
+ ...overrides,
+});
+const remoteSpace = (id, teams) => ({ id, teams });
+
+test("exact cloud space identity proves the local account scope", async () => {
+ const { partitionLocalTeamSpaces } = await import("../../src/services/accountSpaceValidation.ts");
+ const exact = localSpace({ id: 10, cloud_space_id: "space-a" });
+ const foreign = localSpace({ id: 11, cloud_space_id: "space-b" });
+ const result = partitionLocalTeamSpaces(
+ [exact, foreign],
+ [remoteSpace("space-a", [{ id: "team-a" }])]
+ );
+
+ assert.deepEqual(
+ result.proven.map((space) => space.id),
+ [10]
+ );
+ assert.deepEqual(
+ result.unproven.map((space) => space.id),
+ [11]
+ );
+});
+
+test("legacy identity requires one unambiguous single-team remote space", async () => {
+ const { partitionLocalTeamSpaces } = await import("../../src/services/accountSpaceValidation.ts");
+ const legacy = localSpace({ id: 20, cloud_team_id: "team-a" });
+
+ assert.deepEqual(
+ partitionLocalTeamSpaces([legacy], [remoteSpace("space-a", [{ id: "team-a" }])]).proven.map(
+ (space) => space.id
+ ),
+ [20]
+ );
+ assert.deepEqual(
+ partitionLocalTeamSpaces(
+ [legacy],
+ [remoteSpace("space-a", [{ id: "team-a" }, { id: "team-b" }])]
+ ).unproven.map((space) => space.id),
+ [20],
+ "broad membership in a multi-team space is not a legacy identity proof"
+ );
+ assert.deepEqual(
+ partitionLocalTeamSpaces(
+ [legacy],
+ [remoteSpace("space-a", [{ id: "team-a" }]), remoteSpace("space-b", [{ id: "team-a" }])]
+ ).unproven.map((space) => space.id),
+ [20],
+ "an ambiguous migration match is not trusted"
+ );
+});
+
+test("private rows never participate in account-scoped team cleanup", async () => {
+ const { partitionLocalTeamSpaces } = await import("../../src/services/accountSpaceValidation.ts");
+ const privateSpace = localSpace({
+ id: 30,
+ kind: "private",
+ cloud_space_id: "missing",
+ });
+ const result = partitionLocalTeamSpaces([privateSpace], []);
+ assert.deepEqual(result, { proven: [], unproven: [] });
+});
diff --git a/test/services/noteCreateAck.test.js b/test/services/noteCreateAck.test.js
new file mode 100644
index 000000000..17291928b
--- /dev/null
+++ b/test/services/noteCreateAck.test.js
@@ -0,0 +1,233 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const note = {
+ id: 42,
+ client_note_id: "client-note-42",
+};
+
+test("resolveCloudNoteCreate deletes a proven orphan create", async () => {
+ const { resolveCloudNoteCreate } = await import("../../src/services/noteCreateAck.ts");
+ const calls = [];
+ const result = await resolveCloudNoteCreate(
+ note,
+ {
+ id: "cloud-note-42",
+ client_note_id: note.client_note_id,
+ updated_at: "2026-07-29T10:00:00.000Z",
+ user_id: "owner-42",
+ },
+ {
+ acknowledge: async (...args) => {
+ calls.push(["acknowledge", ...args]);
+ return { success: true, outcome: "orphaned" };
+ },
+ deleteCloud: async (cloudId) => calls.push(["delete", cloudId]),
+ }
+ );
+
+ assert.equal(result, "orphan-cleaned");
+ assert.deepEqual(calls[0], [
+ "acknowledge",
+ note.id,
+ note,
+ "cloud-note-42",
+ "2026-07-29T10:00:00.000Z",
+ "owner-42",
+ true,
+ ]);
+ assert.deepEqual(calls[1], ["delete", "cloud-note-42"]);
+});
+
+test("resolveCloudNoteCreate never deletes a mismatched response", async () => {
+ const { resolveCloudNoteCreate } = await import("../../src/services/noteCreateAck.ts");
+ let acknowledged = false;
+ let deleted = false;
+ let invalid = null;
+ const result = await resolveCloudNoteCreate(
+ note,
+ { id: "foreign-cloud-note", client_note_id: "someone-else" },
+ {
+ acknowledge: async () => {
+ acknowledged = true;
+ return { success: true, outcome: "orphaned" };
+ },
+ deleteCloud: async () => {
+ deleted = true;
+ },
+ onInvalidResponse: (expected, received) => {
+ invalid = { expected, received };
+ },
+ }
+ );
+
+ assert.equal(result, "invalid-response");
+ assert.equal(acknowledged, false);
+ assert.equal(deleted, false);
+ assert.deepEqual(invalid, {
+ expected: note.client_note_id,
+ received: "someone-else",
+ });
+});
+
+test("resolveCloudNoteCreate leaves newer local work pending without cleanup", async () => {
+ const { resolveCloudNoteCreate } = await import("../../src/services/noteCreateAck.ts");
+ let deleted = false;
+ const result = await resolveCloudNoteCreate(
+ note,
+ { id: "cloud-note-42", client_note_id: note.client_note_id },
+ {
+ acknowledge: async () => ({ success: true, outcome: "pending" }),
+ deleteCloud: async () => {
+ deleted = true;
+ },
+ }
+ );
+
+ assert.equal(result, "pending");
+ assert.equal(deleted, false);
+});
+
+test("resolveCloudNoteCreate treats orphan cleanup as best-effort", async () => {
+ const { resolveCloudNoteCreate } = await import("../../src/services/noteCreateAck.ts");
+ const failure = new Error("signed out");
+ let reported = null;
+ const result = await resolveCloudNoteCreate(
+ note,
+ { id: "cloud-note-42", client_note_id: note.client_note_id },
+ {
+ acknowledge: async () => ({ success: true, outcome: "orphaned" }),
+ deleteCloud: async () => {
+ throw failure;
+ },
+ onCleanupError: (cloud, error) => {
+ reported = { cloud, error };
+ },
+ }
+ );
+
+ assert.equal(result, "orphan-cleanup-failed");
+ assert.equal(reported.cloud.id, "cloud-note-42");
+ assert.equal(reported.error, failure);
+});
+
+test("resolveCloudNoteCreateBatch routes migration results by snapshot identity", async () => {
+ const { resolveCloudNoteCreateBatch } = await import("../../src/services/noteCreateAck.ts");
+ const otherNote = { id: 84, client_note_id: "client-note-84" };
+ const acknowledgements = [];
+ const deleted = [];
+ const results = await resolveCloudNoteCreateBatch(
+ [note, otherNote],
+ [
+ {
+ id: "cloud-note-84",
+ client_note_id: otherNote.client_note_id,
+ updated_at: "2026-07-29T14:00:00.000Z",
+ },
+ ],
+ {
+ acknowledge: async (...args) => {
+ acknowledgements.push(args);
+ return { success: true, outcome: "orphaned" };
+ },
+ deleteCloud: async (cloudId) => deleted.push(cloudId),
+ },
+ { settleIfUnchanged: false }
+ );
+
+ assert.deepEqual(acknowledgements, [
+ [otherNote.id, otherNote, "cloud-note-84", "2026-07-29T14:00:00.000Z", null, false],
+ ]);
+ assert.deepEqual(deleted, ["cloud-note-84"]);
+ assert.deepEqual(results, ["orphan-cleaned"]);
+});
+
+test("resolveCloudNoteCreateBatch does not delete an unmatched migration response", async () => {
+ const { resolveCloudNoteCreateBatch } = await import("../../src/services/noteCreateAck.ts");
+ let acknowledged = false;
+ let deleted = false;
+ let unmatched = null;
+ const cloud = { id: "unknown-cloud", client_note_id: "unknown-client" };
+ const results = await resolveCloudNoteCreateBatch([note], [cloud], {
+ acknowledge: async () => {
+ acknowledged = true;
+ return { success: true, outcome: "orphaned" };
+ },
+ deleteCloud: async () => {
+ deleted = true;
+ },
+ onUnmatchedResponse: (response) => {
+ unmatched = response;
+ },
+ });
+
+ assert.deepEqual(results, ["unmatched-response"]);
+ assert.equal(acknowledged, false);
+ assert.equal(deleted, false);
+ assert.equal(unmatched, cloud);
+});
+
+test("a superseded migration run acknowledges instead of deleting the idempotent row", async () => {
+ const { resolveCloudNoteCreateBatch } = await import("../../src/services/noteCreateAck.ts");
+ let migrationGeneration = 1;
+ let accountGeneration = 7;
+ const run = {
+ migrationGeneration,
+ accountGeneration,
+ };
+ migrationGeneration += 1;
+
+ let acknowledged = false;
+ let deleted = false;
+ const results = await resolveCloudNoteCreateBatch(
+ [note],
+ [{ id: "shared-idempotent-cloud", client_note_id: note.client_note_id }],
+ {
+ acknowledge: async () => {
+ acknowledged = true;
+ return { success: true, outcome: "already-linked" };
+ },
+ deleteCloud: async () => {
+ deleted = true;
+ },
+ },
+ {
+ settleIfUnchanged: false,
+ requestStillCurrent: () => run.accountGeneration === accountGeneration,
+ }
+ );
+
+ assert.notEqual(run.migrationGeneration, migrationGeneration);
+ assert.equal(acknowledged, true);
+ assert.equal(deleted, false);
+ assert.deepEqual(results, ["already-linked"]);
+});
+
+test("an account reset cleans an invalidated migration without touching SQLite", async () => {
+ const { resolveCloudNoteCreateBatch } = await import("../../src/services/noteCreateAck.ts");
+ let accountGeneration = 7;
+ const runAccountGeneration = accountGeneration;
+ accountGeneration += 1;
+ let acknowledged = false;
+ const deleted = [];
+ const cloud = { id: "old-account-cloud", client_note_id: note.client_note_id };
+ const results = await resolveCloudNoteCreateBatch(
+ [note],
+ [cloud],
+ {
+ acknowledge: async () => {
+ acknowledged = true;
+ return { success: true, outcome: "synced" };
+ },
+ deleteCloud: async (cloudId) => deleted.push(cloudId),
+ },
+ {
+ settleIfUnchanged: false,
+ requestStillCurrent: () => runAccountGeneration === accountGeneration,
+ }
+ );
+
+ assert.equal(acknowledged, false);
+ assert.deepEqual(deleted, ["old-account-cloud"]);
+ assert.deepEqual(results, ["orphan-cleaned"]);
+});
diff --git a/test/services/syncPassPolicy.test.js b/test/services/syncPassPolicy.test.js
index 92feeaf3a..e2b1f0d5b 100644
--- a/test/services/syncPassPolicy.test.js
+++ b/test/services/syncPassPolicy.test.js
@@ -156,6 +156,9 @@ test("revoked fork: a push rejection moves, forks and clears the retraction", as
assert.equal(update.space_id, 1);
assert.equal(update.folder_id, null);
assert.equal(update.cloud_id, null);
+ assert.equal(update.cloud_updated_at, null);
+ assert.equal(update.owner_user_id, null);
+ assert.equal(update.updated_by_user_id, null);
assert.equal(update.left_team, 0);
assert.equal(typeof update.client_note_id, "string");
});