Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Update vault push logic to wait for server response in web app for item edits (#2413)

Leendert de Borstffcab41fbcb5
diff --git a/apps/web/src/components/items/FieldHistoryModal.tsx b/apps/web/src/components/items/FieldHistoryModal.tsx
index aee0c985f..25a7a01d0 100644
--- a/apps/web/src/components/items/FieldHistoryModal.tsx
+++ b/apps/web/src/components/items/FieldHistoryModal.tsx
@@ -41,7 +41,7 @@ const formatDate = (value: string): string => new Date(value).toLocaleString('en
const FieldHistoryModal: React.FC<FieldHistoryModalProps> = ({ item, fieldKey, fieldLabel, isHidden, onClose }) => {
const { t } = useTranslation();
const dbContext = useDb();
- const { executeVaultMutationAsync } = useVaultMutate();
+ const { executeVaultMutationInBackground } = useVaultMutate();
const [isLoading, setIsLoading] = useState(true);
const [records, setRecords] = useState<FieldHistory[]>([]);
const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);
@@ -74,7 +74,7 @@ const FieldHistoryModal: React.FC<FieldHistoryModalProps> = ({ item, fieldKey, f
* Delete a history record and sync.
*/
const deleteRecord = async (historyId: string): Promise<void> => {
- await executeVaultMutationAsync(async () => {
+ await executeVaultMutationInBackground(async () => {
await dbContext.sqliteClient?.items.deleteFieldHistory(historyId, item.ManifestId);
});
setConfirmDeleteId(null);
diff --git a/apps/web/src/components/items/ItemContextMenu.tsx b/apps/web/src/components/items/ItemContextMenu.tsx
index ac73a2e9d..5304d6e50 100644
--- a/apps/web/src/components/items/ItemContextMenu.tsx
+++ b/apps/web/src/components/items/ItemContextMenu.tsx
@@ -7,7 +7,7 @@ import FormModal from '@/components/shared/FormModal';
import { useDb } from '@/context/DbContext';
import { useNotifications } from '@/context/NotificationContext';
import { useClickOutside } from '@/hooks/useClickOutside';
-import { useVaultMutate } from '@/hooks/useVaultMutate';
+import { useVaultMutate, VaultPushFailedError } from '@/hooks/useVaultMutate';
import { itemRoute } from '@/utils/ItemRoute';
import type { ItemRef } from '@aliasvault/client/database/ItemRef';
@@ -90,7 +90,10 @@ const ItemContextMenu = forwardRef<ItemContextMenuHandle, ItemContextMenuProps>(
onMutated();
} catch (error) {
console.error('Failed to duplicate item:', error);
- notifications.addErrorMessage(t('sharedResources.DuplicateErrorMessage'), true);
+ // Failed push (e.g. server not reachable).
+ if (!(error instanceof VaultPushFailedError)) {
+ notifications.addErrorMessage(t('sharedResources.DuplicateErrorMessage'), true);
+ }
} finally {
setIsDuplicating(false);
}
@@ -111,6 +114,11 @@ const ItemContextMenu = forwardRef<ItemContextMenuHandle, ItemContextMenuProps>(
notifications.addSuccessMessage(t('pages.main.items.delete.DeleteSuccessMessage'), true);
setShowDeleteModal(false);
onMutated();
+ } catch (error) {
+ // Failed push (e.g. server not reachable).
+ if (!(error instanceof VaultPushFailedError)) {
+ throw error;
+ }
} finally {
setIsDeleting(false);
}
diff --git a/apps/web/src/components/layout/DbStatusIndicator.tsx b/apps/web/src/components/layout/DbStatusIndicator.tsx
index 9a5c453ba..eac5a4c62 100644
--- a/apps/web/src/components/layout/DbStatusIndicator.tsx
+++ b/apps/web/src/components/layout/DbStatusIndicator.tsx
@@ -1,22 +1,32 @@
+import { getPlatform } from '@aliasvault/client/platform';
+import { hasUnsyncedUserChanges } from '@aliasvault/client/sync/VaultDirtyState';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import SmallLoadingIndicator from '@/components/loading/SmallLoadingIndicator';
import { useDb } from '@/context/DbContext';
+import { useNotifications } from '@/context/NotificationContext';
import { useVaultSync } from '@/hooks/useVaultSync';
+import { StorageKeys } from '@/utils/StorageKeys';
+import { vaultStore } from '@/vault/VaultStore';
/** How long the indicator keeps spinning after a sync started, so a fast sync is still visible. */
const MIN_SPIN_MS = 600;
/**
- * Vault sync indicator in the top bar. Spins while syncing; otherwise a refresh button that pulls the latest vault.
+ * Vault sync indicator in the top bar. Spins while syncing; otherwise a refresh button that pulls the latest vault,
+ * marked with a red dot once a sync failed while the vault holds changes of the user the server does not have yet
+ * (e.g. a background save that failed), so a click retries the push.
*/
const DbStatusIndicator: React.FC = () => {
const { t } = useTranslation();
const dbContext = useDb();
const { syncVault } = useVaultSync();
+ const notifications = useNotifications();
const [isRefreshing, setIsRefreshing] = useState(false);
const [holdSpinning, setHoldSpinning] = useState(false);
+ const [hasUnsyncedChanges, setHasUnsyncedChanges] = useState(false);
+ const [lastSyncFailed, setLastSyncFailed] = useState(false);
const holdTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const isBusy = dbContext.isSyncing || dbContext.isUploading || isRefreshing;
@@ -41,17 +51,71 @@ const DbStatusIndicator: React.FC = () => {
const isSpinning = isBusy || holdSpinning;
+ useEffect(() => vaultStore.onSyncFailureChange(setLastSyncFailed), []);
+
+ // Re-check the pending changes whenever a sync finishes or the dirty flag changes.
+ useEffect(() => {
+ if (isBusy) {
+ return undefined;
+ }
+ let cancelled = false;
+ /**
+ * Read whether the vault holds unsynced changes of the user.
+ */
+ const check = (): void => {
+ void hasUnsyncedUserChanges().then(value => {
+ if (!cancelled) {
+ setHasUnsyncedChanges(value);
+ }
+ });
+ };
+ check();
+ const unwatch = getPlatform().storage.watch(StorageKeys.IS_DIRTY, check);
+ return (): void => {
+ cancelled = true;
+ unwatch();
+ };
+ }, [isBusy]);
+
+ // Only a sync that failed makes pending changes an error; before the first attempt they are simply on their way.
+ const showSyncError = lastSyncFailed && hasUnsyncedChanges;
+
/**
- * Pull the latest vault from the server.
+ * Sync with the server. When the user's changes still did not get through, say so again.
*/
const onRefreshClick = useCallback(async (): Promise<void> => {
setIsRefreshing(true);
+ let wasOffline = false;
+ let errorMessage: string | null = null;
try {
- await syncVault();
+ await syncVault({
+ /**
+ * The server was not reachable.
+ */
+ onOffline: (): void => {
+ wasOffline = true;
+ },
+ /**
+ * The sync failed, or threw.
+ */
+ onError: (message: string): void => {
+ errorMessage = message;
+ },
+ });
+ if (wasOffline) {
+ notifications.addErrorMessage(t('common.errors.serverNotAvailable'), true);
+ } else if (errorMessage !== null) {
+ // A sync error with details already shows in the sync error dialog; anything else (e.g. an exception) shows here.
+ if (await getPlatform().storage.get(StorageKeys.LAST_SYNC_ERROR) === null) {
+ notifications.addErrorMessage(errorMessage, true);
+ }
+ } else if (await hasUnsyncedUserChanges()) {
+ notifications.addErrorMessage(t('sharedResources.VaultSaveError'), true);
+ }
} finally {
setIsRefreshing(false);
}
- }, [syncVault]);
+ }, [notifications, syncVault, t]);
/**
* The tooltip for the current state.
@@ -63,6 +127,9 @@ const DbStatusIndicator: React.FC = () => {
if (dbContext.isSyncing) {
return t('sharedResources.LoadingVault');
}
+ if (showSyncError) {
+ return t('sharedResources.VaultSaveError');
+ }
return t('sharedResources.SyncVaultData');
};
@@ -74,6 +141,7 @@ const DbStatusIndicator: React.FC = () => {
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-gray-400" viewBox="0 0 20 20" fill="currentColor">
<path fillRule="evenodd" d="M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z" clipRule="evenodd" />
</svg>
+ {showSyncError && <span className="absolute top-1 right-1 w-2 h-2 rounded-full bg-red-500" aria-hidden="true"></span>}
</button>
)}
</SmallLoadingIndicator>
diff --git a/apps/web/src/components/loading/FullScreenLoadingIndicator.tsx b/apps/web/src/components/loading/FullScreenLoadingIndicator.tsx
index dfbadb02d..f4e94cf40 100644
--- a/apps/web/src/components/loading/FullScreenLoadingIndicator.tsx
+++ b/apps/web/src/components/loading/FullScreenLoadingIndicator.tsx
@@ -14,7 +14,7 @@ const FullScreenLoadingIndicator: React.FC<FullScreenLoadingIndicatorProps> = ({
}
return (
- <div className="loading fixed inset-0 w-full h-full z-50 bg-gray-200 !m-0 !p-0 dark:bg-gray-500" style={{ zIndex: 2147483641 }}>
+ <div className="fixed inset-0 w-full h-full z-50 !m-0 !p-0 bg-white/90 dark:bg-gray-500/90" style={{ zIndex: 2147483641 }}>
<div className="aliasvault-fullscreen-spinner mx-auto">
<div className="cloud-shape-inverted">
<div className="dot-inverted delay-1"></div>
diff --git a/apps/web/src/components/settings/PasswordSettingsPopup.tsx b/apps/web/src/components/settings/PasswordSettingsPopup.tsx
index 3d7d301e4..2b91d1786 100644
--- a/apps/web/src/components/settings/PasswordSettingsPopup.tsx
+++ b/apps/web/src/components/settings/PasswordSettingsPopup.tsx
@@ -87,10 +87,17 @@ const PasswordSettingsPopup: React.FC<PasswordSettingsPopupProps> = ({ passwordS
*/
const onSaveGlobal = async (): Promise<void> => {
showLoading();
- await executeVaultMutationAsync(async () => {
- dbContext.sqliteClient?.settings.setPasswordSettings(settings);
- });
- hideLoading();
+ try {
+ await executeVaultMutationAsync(async () => {
+ dbContext.sqliteClient?.settings.setPasswordSettings(settings);
+ });
+ } catch (error) {
+ // Failed push (e.g. server not reachable).
+ console.error('Failed to save the password settings:', error);
+ return;
+ } finally {
+ hideLoading();
+ }
notifications.addSuccessMessage(t(`${tk}.SettingsUpdatedMessage`), true);
onSaveSettings(settings, previewPassword);
onClose();
diff --git a/apps/web/src/components/settings/importexport/ImportServiceCard.tsx b/apps/web/src/components/settings/importexport/ImportServiceCard.tsx
index 86e8e1b1f..b9de46f54 100644
--- a/apps/web/src/components/settings/importexport/ImportServiceCard.tsx
+++ b/apps/web/src/components/settings/importexport/ImportServiceCard.tsx
@@ -14,7 +14,7 @@ import Modal from '@/components/shared/Modal';
import { useDb } from '@/context/DbContext';
import { useNotifications } from '@/context/NotificationContext';
import { useWebApi } from '@/context/WebApiContext';
-import { useVaultMutate } from '@/hooks/useVaultMutate';
+import { useVaultMutate, VaultPushFailedError } from '@/hooks/useVaultMutate';
import { delay } from '@/utils/Delay';
import { formatBytes } from '@/utils/FormatBytes';
@@ -437,28 +437,36 @@ const ImportServiceCard: React.FC<ImportServiceCardProps> = ({ serviceName, desc
setCredentialSaveProgress(0);
setTotalCredentialsToSave(importedCredentials.length);
- await executeVaultMutationAsync(async () => {
- const folderNameToId = importFolders && detectedFolderPaths.length > 0 ? await VaultImportWriter.createOrGetFolders(sqliteClient, detectedFolderPaths) : null;
-
- await VaultImportWriter.importCredentialsToVault(sqliteClient, importedCredentials, {
- folderNameToId,
- importAttachments,
- extractedFavicons: extractedFavicons.current,
- /**
- * Show the save progress, letting the browser paint every few items.
- */
- onProgress: async (saved: number): Promise<void> => {
- setCredentialSaveProgress(saved);
- if (saved % SAVE_PROGRESS_EVERY === 0) {
- await yieldToPaint();
- }
- },
+ try {
+ await executeVaultMutationAsync(async () => {
+ const folderNameToId = importFolders && detectedFolderPaths.length > 0 ? await VaultImportWriter.createOrGetFolders(sqliteClient, detectedFolderPaths) : null;
+
+ await VaultImportWriter.importCredentialsToVault(sqliteClient, importedCredentials, {
+ folderNameToId,
+ importAttachments,
+ extractedFavicons: extractedFavicons.current,
+ /**
+ * Show the save progress, letting the browser paint every few items.
+ */
+ onProgress: async (saved: number): Promise<void> => {
+ setCredentialSaveProgress(saved);
+ if (saved % SAVE_PROGRESS_EVERY === 0) {
+ await yieldToPaint();
+ }
+ },
+ });
+
+ await delay(50);
+ setIsSavingCredentials(false);
+ setIsSyncingVault(true);
});
-
- await delay(50);
- setIsSavingCredentials(false);
- setIsSyncingVault(true);
- });
+ } catch (error) {
+ if (!(error instanceof VaultPushFailedError)) {
+ throw error;
+ }
+ // Failed push (e.g. server not reachable), try again.
+ return;
+ }
notifications.addSuccessMessage(t(`${tk}.ImportSuccessMessage`, { 0: importedCredentials.length }));
navigate('/items');
diff --git a/apps/web/src/hooks/useClipboardCopy.ts b/apps/web/src/hooks/useClipboardCopy.ts
index 33d9585d5..d9e8ad997 100644
--- a/apps/web/src/hooks/useClipboardCopy.ts
+++ b/apps/web/src/hooks/useClipboardCopy.ts
@@ -16,7 +16,7 @@ const DEFAULT_CLIPBOARD_CLEAR_SECONDS = 10;
*/
export function useClipboardCopy(id: string, item?: ItemRef): { copied: boolean; copyToClipboard: (value: string) => Promise<void> } {
const dbContext = useDb();
- const { executeVaultMutationAsync } = useVaultMutate();
+ const { executeVaultMutationInBackground } = useVaultMutate();
const [copied, setCopied] = useState(clipboardCopyService.getCopiedId() === id);
const itemId = item?.Id;
const manifestId = item?.ManifestId;
@@ -32,12 +32,12 @@ export function useClipboardCopy(id: string, item?: ItemRef): { copied: boolean;
}
// Stats-only writes push silently, without the sync indicator.
- executeVaultMutationAsync(async () => {
+ executeVaultMutationInBackground(async () => {
if (!dbContext.sqliteClient?.itemStats.recordUsage({ Id: itemId, ManifestId: manifestId }, 'copy')) {
throw new Error('Item not found');
}
}).catch((error) => devLog('[Clipboard] Failed to record item usage', error));
- }, [dbContext.sqliteClient, executeVaultMutationAsync, id, itemId, manifestId]);
+ }, [dbContext.sqliteClient, executeVaultMutationInBackground, id, itemId, manifestId]);
return { copied, copyToClipboard };
}
diff --git a/apps/web/src/hooks/useVaultMutate.ts b/apps/web/src/hooks/useVaultMutate.ts
index 4e14c148d..7552f4496 100644
--- a/apps/web/src/hooks/useVaultMutate.ts
+++ b/apps/web/src/hooks/useVaultMutate.ts
@@ -1,26 +1,61 @@
import { encryptVaultBlob } from '@aliasvault/client/crypto/VaultBlob';
-import { hasSyncError } from '@aliasvault/client/sync/VaultSync';
+import { syncErrorMessage } from '@aliasvault/client/sync/SyncErrorMessage';
+import { hasUserVisibleScope, type VaultMutationScope } from '@aliasvault/client/sync/VaultMutationScope';
+import { hasSyncError, type FullVaultSyncResult } from '@aliasvault/client/sync/VaultSync';
import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useAuth } from '@/context/AuthContext';
import { useDb } from '@/context/DbContext';
+import { useNotifications } from '@/context/NotificationContext';
import { devLog } from '@/utils/DevLogger';
import { vaultStore } from '@/vault/VaultStore';
+/**
+ * Server push failed.
+ */
+export class VaultPushFailedError extends Error {
+ /**
+ * Create the error.
+ */
+ public constructor() {
+ super('The vault change could not be pushed to the server');
+ this.name = 'VaultPushFailedError';
+ }
+}
+
+/**
+ * Whether a sync failed to bring the local changes to the server.
+ */
+const pushFailed = (result: FullVaultSyncResult): boolean => !result.success || result.wasOffline || result.requiresLogout || result.sqliteBlobUpgradeRequired || result.manifestMigrationRequired === true;
+
/**
* Hook to execute a vault mutation.
*
* Flow:
* 1. Execute the mutation on the in-memory database
* 2. Save the encrypted vault locally and mark it dirty (bumps the mutation sequence)
- * 3. Trigger a sync which handles upload, merge if needed and offline mode; the sync drives the upload indicator
+ * 3. Sync, which handles upload, merge if needed; the sync drives the upload indicator
+ *
+ * The web app has no offline mode so a save the user asked for (executeVaultMutationAsync) blocks until the push is
+ * done. Changes the user does not wait on (settings, usage stats) push in the background and stay stored locally for
+ * the next sync and error is indicated by the sync indicator icon in the top bar.
*/
-export function useVaultMutate(): { executeVaultMutationAsync: (operation: () => Promise<void>) => Promise<void>; } {
+export function useVaultMutate(): {
+ executeVaultMutationAsync: (operation: () => Promise<void>) => Promise<void>;
+ executeVaultMutationInBackground: (operation: () => Promise<void>) => Promise<void>;
+ executeVaultMutationLocally: (operation: () => Promise<void>) => Promise<void>;
+ } {
+ const { t } = useTranslation();
+ const auth = useAuth();
const dbContext = useDb();
+ const notifications = useNotifications();
/**
* Execute the operation and save the result locally, marking the vault dirty with the scopes it wrote into.
+ * @returns The scopes the operation wrote into
*/
- const saveLocally = useCallback(async (operation: () => Promise<void>): Promise<void> => {
+ const saveLocally = useCallback(async (operation: () => Promise<void>): Promise<VaultMutationScope[]> => {
await operation();
const sqliteClient = dbContext.sqliteClient;
@@ -41,31 +76,78 @@ export function useVaultMutate(): { executeVaultMutationAsync: (operation: () =>
scopes.forEach(scope => sqliteClient.recordMutationScope(scope));
throw error;
}
+ return scopes;
}, [dbContext]);
/**
- * Trigger the sync that pushes the mutation.
+ * Sync the stored mutation to the server.
+ * @param notifyFailure - whether a failure is reported to the user
+ * @returns Whether the push succeeded
*/
- const triggerSync = useCallback((): void => {
- vaultStore.fullVaultSync().then(async (result) => {
- if (hasSyncError(result)) {
- devLog('[VaultMutate] Sync after mutation reported an error', result);
- }
- if (result.hasNewVault) {
- await dbContext.loadStoredDatabase();
- }
- }).catch((error) => {
+ const pushMutation = useCallback(async (notifyFailure: boolean): Promise<boolean> => {
+ let result: FullVaultSyncResult;
+ try {
+ result = await vaultStore.fullVaultSync({ waitForRunningSync: notifyFailure, reportErrorToPopup: notifyFailure });
+ } catch (error) {
console.error('[VaultMutate] Sync after mutation failed:', error);
- });
- }, [dbContext]);
+ if (notifyFailure) {
+ notifications.addErrorMessage(t('sharedResources.VaultSaveError'), true);
+ }
+ return false;
+ }
+
+ if (result.hasNewVault) {
+ await dbContext.loadStoredDatabase();
+ }
+ if (!pushFailed(result)) {
+ return true;
+ }
+
+ devLog('[VaultMutate] Sync after mutation did not push', result);
+ if (result.requiresLogout) {
+ await auth.logout({ errorMessage: syncErrorMessage(result, t) });
+ } else if (notifyFailure && (result.wasOffline || !hasSyncError(result))) {
+ // A sync error with details already shows in the sync error dialog (see VaultStore.fullVaultSync).
+ notifications.addErrorMessage(t(result.wasOffline ? 'common.errors.serverNotAvailable' : 'sharedResources.VaultSaveError'), true);
+ }
+ return false;
+ }, [auth, dbContext, notifications, t]);
/**
- * Execute a vault mutation: apply it locally, persist it, and sync it to the server.
+ * Execute a vault mutation, persist it and wait for the push. Throws VaultPushFailedError when the push failed, after
+ * rolling the change back.
*/
const executeVaultMutationAsync = useCallback(async (operation: () => Promise<void>): Promise<void> => {
+ const snapshot = await vaultStore.snapshotLocalVault();
+ await saveLocally(operation);
+ if (await pushMutation(true)) {
+ return;
+ }
+
+ // Roll back the change the server did not get.
+ const { isLoggedIn } = await vaultStore.checkAuthStatus();
+ if (isLoggedIn) {
+ await vaultStore.restoreLocalVault(snapshot);
+ await dbContext.loadStoredDatabase();
+ }
+ throw new VaultPushFailedError();
+ }, [dbContext, saveLocally, pushMutation]);
+
+ /**
+ * Execute a vault mutation and persist it, then push it without waiting. A failed push of a change the user
+ * sees is reported; one of silent data (usage stats) is not.
+ */
+ const executeVaultMutationInBackground = useCallback(async (operation: () => Promise<void>): Promise<void> => {
+ const scopes = await saveLocally(operation);
+ void pushMutation(hasUserVisibleScope(scopes));
+ }, [saveLocally, pushMutation]);
+
+ /**
+ * Execute a vault mutation and persist it without syncing, for a caller whose next step pushes it itself.
+ */
+ const executeVaultMutationLocally = useCallback(async (operation: () => Promise<void>): Promise<void> => {
await saveLocally(operation);
- triggerSync();
- }, [saveLocally, triggerSync]);
+ }, [saveLocally]);
- return { executeVaultMutationAsync };
+ return { executeVaultMutationAsync, executeVaultMutationInBackground, executeVaultMutationLocally };
}
diff --git a/apps/web/src/i18n/locales/en.json b/apps/web/src/i18n/locales/en.json
index ff0505667..7ace40220 100644
--- a/apps/web/src/i18n/locales/en.json
+++ b/apps/web/src/i18n/locales/en.json
@@ -701,6 +701,7 @@
},
"loadingScreen": {
"errors": {
+ "unhandledError": "An unhandled error has occurred. Please try reloading the page. If the issue persists, please contact support.",
"webAssemblyError": "AliasVault requires WebAssembly, which this browser does not support. Try using a more modern browser that supports WebAssembly."
},
"loading": {
diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx
index 475ccf61b..097d9b36a 100644
--- a/apps/web/src/main.tsx
+++ b/apps/web/src/main.tsx
@@ -52,4 +52,5 @@ const bootstrap = async (): Promise<void> => {
bootstrap().catch((error) => {
console.error('Failed to start AliasVault:', error);
+ (window as { showAppLoadError?: () => void }).showAppLoadError?.();
});
diff --git a/apps/web/src/pages/items/AddEdit.tsx b/apps/web/src/pages/items/AddEdit.tsx
index f38ab44d8..ca45c1ba9 100644
--- a/apps/web/src/pages/items/AddEdit.tsx
+++ b/apps/web/src/pages/items/AddEdit.tsx
@@ -29,6 +29,7 @@ import { useNotifications } from '@/context/NotificationContext';
import { useWebApi } from '@/context/WebApiContext';
import { usePageTitle } from '@/hooks/usePageTitle';
import { useSaveItem } from '@/hooks/useSaveItem';
+import { VaultPushFailedError } from '@/hooks/useVaultMutate';
import {
addCustomField, createNewItemEdit, DEFAULT_SERVICE_URL, getCustomFields, getFieldValue, getFieldValues, hasAliasValues, hasFieldValue,
type ItemEdit, itemEditFromItem, removeCustomField, reorderCustomFields, setFieldValue, setFieldValues, setFolder, updateCustomField,
@@ -78,6 +79,7 @@ const ItemAddEdit: React.FC = () => {
usePageTitle(editMode ? t(`${tk}.EditItemTitle`) : t(`${tk}.AddItemTitle`));
const [loading, setLoading] = useState(true);
+ const initializedFor = useRef<string | null>(null);
const [edit, setEdit] = useState<ItemEdit>(() => ({ Id: '', ManifestId: '', ItemType: ItemTypes.Login, ServiceName: '', FolderId: null, CreatedAt: '', Fields: [], Attachments: [], TotpCodes: [], Passkeys: [] }));
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
const [passkeyMarkedForDeletion, setPasskeyMarkedForDeletion] = useState(false);
@@ -164,7 +166,8 @@ const ItemAddEdit: React.FC = () => {
// Load the item (edit) or prefill the form from the quick create widget's query (create).
useEffect(() => {
const client = dbContext.sqliteClient;
- if (!client) {
+ const routeKey = `${manifestId}/${id}${location.search}`;
+ if (!client || initializedFor.current === routeKey) {
return;
}
let cancelled = false;
@@ -207,6 +210,7 @@ const ItemAddEdit: React.FC = () => {
crumbs.push({ displayName: t(`${tk}.ViewItemBreadcrumb`), url: itemRoute(ref) });
crumbs.push({ displayName: t(`${tk}.EditItemBreadcrumb`) });
if (!cancelled) {
+ initializedFor.current = routeKey;
setEdit(loaded);
setBreadcrumbItems(crumbs);
setLoading(false);
@@ -238,6 +242,7 @@ const ItemAddEdit: React.FC = () => {
const crumbs = folder ? buildFolderBreadcrumbs(folder, allFolders) : [];
crumbs.push({ displayName: t(`${tk}.AddNewItemBreadcrumb`) });
if (!cancelled) {
+ initializedFor.current = routeKey;
setEdit(created);
setBreadcrumbItems(crumbs);
setLoading(false);
@@ -387,7 +392,10 @@ const ItemAddEdit: React.FC = () => {
navigate(itemRoute(saved));
} catch (error) {
console.error('Error saving item:', error);
- notifications.addErrorMessage(t(`${tk}.ErrorSavingItem`), true);
+ // Failed push (e.g. server not reachable).
+ if (!(error instanceof VaultPushFailedError)) {
+ notifications.addErrorMessage(t(`${tk}.ErrorSavingItem`), true);
+ }
} finally {
hideLoading();
setIsSaving(false);
diff --git a/apps/web/src/pages/items/Home.tsx b/apps/web/src/pages/items/Home.tsx
index 34d921304..7f1f847d0 100644
--- a/apps/web/src/pages/items/Home.tsx
+++ b/apps/web/src/pages/items/Home.tsx
@@ -26,7 +26,7 @@ import { useDb } from '@/context/DbContext';
import { useNotifications } from '@/context/NotificationContext';
import { useClickOutside } from '@/hooks/useClickOutside';
import { usePageTitle } from '@/hooks/usePageTitle';
-import { useVaultMutate } from '@/hooks/useVaultMutate';
+import { useVaultMutate, VaultPushFailedError } from '@/hooks/useVaultMutate';
import { useVaultSync } from '@/hooks/useVaultSync';
import { folderRoute } from '@/utils/ItemRoute';
import { getLocalPreferenceJson, setLocalPreferenceJson } from '@/utils/LocalPreferences';
@@ -76,7 +76,7 @@ const ItemsHome: React.FC = () => {
const dbContext = useDb();
const notifications = useNotifications();
const { syncVault } = useVaultSync();
- const { executeVaultMutationAsync } = useVaultMutate();
+ const { executeVaultMutationAsync, executeVaultMutationInBackground } = useVaultMutate();
usePageTitle('Home');
const folderRef = useMemo((): FolderRef | null => (folderIdParam && manifestIdParam ? { Id: folderIdParam, ManifestId: manifestIdParam } : null), [folderIdParam, manifestIdParam]);
@@ -166,7 +166,7 @@ const ItemsHome: React.FC = () => {
setViewModeState(mode);
const client = dbContext.sqliteClient;
if (client) {
- void executeVaultMutationAsync(async () => {
+ void executeVaultMutationInBackground(async () => {
client.settings.updateSetting('CredentialsViewMode', mode);
});
}
@@ -181,7 +181,7 @@ const ItemsHome: React.FC = () => {
setVisibleItemCount(BATCH_SIZE);
const client = dbContext.sqliteClient;
if (client) {
- void executeVaultMutationAsync(async () => {
+ void executeVaultMutationInBackground(async () => {
client.settings.setCredentialsSortOrder(order);
});
}
@@ -371,7 +371,10 @@ const ItemsHome: React.FC = () => {
setAllFolders(client.folders.getAll());
} catch (error) {
console.error('Failed to create folder:', error);
- notifications.addErrorMessage(t('pages.main.items.home.FailedToCreateFolder'), true);
+ // Failed push (e.g. server not reachable).
+ if (!(error instanceof VaultPushFailedError)) {
+ notifications.addErrorMessage(t('pages.main.items.home.FailedToCreateFolder'), true);
+ }
}
};
@@ -390,7 +393,9 @@ const ItemsHome: React.FC = () => {
setAllFolders(client.folders.getAll());
} catch (error) {
console.error('Failed to rename folder:', error);
- notifications.addErrorMessage(t('sharedResources.ErrorGeneric'), true);
+ if (!(error instanceof VaultPushFailedError)) {
+ notifications.addErrorMessage(t('sharedResources.ErrorGeneric'), true);
+ }
}
};
@@ -414,7 +419,9 @@ const ItemsHome: React.FC = () => {
navigate(buildItemsUrl(parentFolderId ? { Id: parentFolderId, ManifestId: folderRef.ManifestId } : null, filterType));
} catch (error) {
console.error('Failed to delete folder:', error);
- notifications.addErrorMessage(t('pages.main.items.home.FailedToDeleteFolder'), true);
+ if (!(error instanceof VaultPushFailedError)) {
+ notifications.addErrorMessage(t('pages.main.items.home.FailedToDeleteFolder'), true);
+ }
}
};
diff --git a/apps/web/src/pages/settings/General.tsx b/apps/web/src/pages/settings/General.tsx
index 61112c751..08246866d 100644
--- a/apps/web/src/pages/settings/General.tsx
+++ b/apps/web/src/pages/settings/General.tsx
@@ -28,7 +28,7 @@ const hasValidPrivateDomains = (domains: string[]): boolean => domains.length >
const GeneralSettings: React.FC = () => {
const { t, i18n } = useTranslation();
const dbContext = useDb();
- const { executeVaultMutationAsync } = useVaultMutate();
+ const { executeVaultMutationInBackground } = useVaultMutate();
const tk = 'pages.main.settings.general';
usePageTitle(t(`${tk}.PageTitle`));
@@ -48,10 +48,10 @@ const GeneralSettings: React.FC = () => {
* Write a vault setting and push it.
*/
const updateSetting = useCallback(async (key: string, value: string): Promise<void> => {
- await executeVaultMutationAsync(async () => {
+ await executeVaultMutationInBackground(async () => {
dbContext.sqliteClient?.settings.updateSetting(key, value);
});
- }, [dbContext.sqliteClient, executeVaultMutationAsync]);
+ }, [dbContext.sqliteClient, executeVaultMutationInBackground]);
/**
* The identity language: the explicit setting, or the one matching the UI language.
diff --git a/apps/web/src/pages/settings/StorageInsights.tsx b/apps/web/src/pages/settings/StorageInsights.tsx
index 003902ac9..979c6bd6c 100644
--- a/apps/web/src/pages/settings/StorageInsights.tsx
+++ b/apps/web/src/pages/settings/StorageInsights.tsx
@@ -15,7 +15,7 @@ import { useDb } from '@/context/DbContext';
import { useNotifications } from '@/context/NotificationContext';
import { useWebApi } from '@/context/WebApiContext';
import { usePageTitle } from '@/hooks/usePageTitle';
-import { useVaultMutate } from '@/hooks/useVaultMutate';
+import { useVaultMutate, VaultPushFailedError } from '@/hooks/useVaultMutate';
import { formatBytes } from '@/utils/FormatBytes';
import { itemRoute } from '@/utils/ItemRoute';
@@ -218,7 +218,9 @@ const StorageInsights: React.FC = () => {
notifications.addSuccessMessage(t(`${tk}.DeleteAllLogosSuccessMessage`, { 0: removed }), true);
} catch (error) {
console.error('Failed to delete the logos:', error);
- notifications.addErrorMessage(t('sharedResources.ErrorGeneric'), true);
+ if (!(error instanceof VaultPushFailedError)) {
+ notifications.addErrorMessage(t('sharedResources.ErrorGeneric'), true);
+ }
} finally {
setIsDeletingLogos(false);
reload();
@@ -253,7 +255,9 @@ const StorageInsights: React.FC = () => {
}
} catch (error) {
console.error('Failed to re-download the logos:', error);
- notifications.addErrorMessage(t('sharedResources.ErrorGeneric'), true);
+ if (!(error instanceof VaultPushFailedError)) {
+ notifications.addErrorMessage(t('sharedResources.ErrorGeneric'), true);
+ }
} finally {
setRedownloadProgress(null);
reload();
diff --git a/apps/web/src/pages/sync/Sync.tsx b/apps/web/src/pages/sync/Sync.tsx
index d89a63150..2f16f4c1f 100644
--- a/apps/web/src/pages/sync/Sync.tsx
+++ b/apps/web/src/pages/sync/Sync.tsx
@@ -35,7 +35,7 @@ const Sync: React.FC = () => {
const navigate = useNavigate();
const auth = useAuth();
const dbContext = useDb();
- const { executeVaultMutationAsync } = useVaultMutate();
+ const { executeVaultMutationLocally } = useVaultMutate();
usePageTitle(t('pages.main.sync.sync.PageTitle'));
const [status, setStatus] = useState<SyncStatus>('loading');
@@ -175,7 +175,7 @@ const Sync: React.FC = () => {
* The migration SQL contains PRAGMA statements that only take effect outside a transaction, so every
* command runs as-is; each script handles its own transactions.
*/
- await executeVaultMutationAsync(async () => {
+ await executeVaultMutationLocally(async () => {
for (const sqlCommand of upgrade.sqlCommands) {
client.executeRaw(sqlCommand);
}
diff --git a/apps/web/src/style.css b/apps/web/src/style.css
index b7260d8e5..2a123fded 100644
--- a/apps/web/src/style.css
+++ b/apps/web/src/style.css
@@ -110,14 +110,6 @@ TODO: migrate all styles to native Tailwind CSS and components where possible.
50% { opacity: 1; transform: scale(1.3); }
}
-.loading {
- background-color: rgba(255, 255, 255, 0.9);
-}
-
-.dark .loading {
- background-color: rgba(107, 114, 128, 0.9);
-}
-
.loading-message {
font-size: 0.875rem;
line-height: 1.25rem;
diff --git a/apps/web/src/vault/VaultStore.ts b/apps/web/src/vault/VaultStore.ts
index 8962179b7..80e67d6f9 100644
--- a/apps/web/src/vault/VaultStore.ts
+++ b/apps/web/src/vault/VaultStore.ts
@@ -38,18 +38,30 @@ export type VaultMetadata = {
hiddenPrivateEmailDomains: string[];
};
+/** The local vault as it was before a mutation, to put back when the mutation could not be pushed. */
+export type LocalVaultSnapshot = {
+ vaultBlob: string | null;
+ isDirty: boolean;
+ dirtyScopes: VaultMutationScope[];
+};
+
/** What a full sync may be asked beyond what the revisions decide. */
export type FullVaultSyncRequest = VaultSyncOptions & {
/** Persist a failure so the UI shows it (default true). A login-time pull reports its own errors. */
reportErrorToPopup?: boolean;
+ /** Wait for a running sync and then run one, instead of queueing a follow-up and returning at once. */
+ waitForRunningSync?: boolean;
};
let cachedSqliteClient: SqliteClient | null = null;
let cachedVaultBlob: string | null = null;
let isSyncInProgress = false;
+let runningSync: Promise<FullVaultSyncResult> | null = null;
let hasPendingSync = false;
const phaseListeners = new Set<(phase: VaultSyncPhase) => void>();
+let lastSyncFailed = false;
+const syncFailureListeners = new Set<(failed: boolean) => void>();
/**
* Tell the UI what the sync is doing.
@@ -256,24 +268,34 @@ async function syncIsOnHold(): Promise<boolean> {
/**
* Full vault sync (push and pull based on revision counters), one at a time.
* @param options - what the caller asks beyond what the revisions decide
+ * @param waitForRunningSync - wait for a running sync and then run, so the result covers every mutation stored before the call
*/
-async function fullVaultSyncInternal(options?: VaultSyncOptions): Promise<FullVaultSyncResult> {
+async function fullVaultSyncInternal(options?: VaultSyncOptions, waitForRunningSync = false): Promise<FullVaultSyncResult> {
if (await syncIsOnHold()) {
return syncResult({ success: false });
}
- if (isSyncInProgress) {
+ if (isSyncInProgress && !waitForRunningSync) {
hasPendingSync = true;
devLog('[VaultSync] Sync already in progress, queued for retry after completion');
return syncResult();
}
+ while (isSyncInProgress && runningSync) {
+ await runningSync.catch(() => undefined);
+ }
+
isSyncInProgress = true;
hasPendingSync = false;
try {
- return await vaultSync.syncVaultWithServer(options);
+ runningSync = vaultSync.syncVaultWithServer(options);
+ const result = await runningSync;
+ lastSyncFailed = !result.success || result.wasOffline;
+ syncFailureListeners.forEach(listener => listener(lastSyncFailed));
+ return result;
} finally {
+ runningSync = null;
isSyncInProgress = false;
broadcastSyncPhase('idle');
@@ -302,9 +324,51 @@ export const vaultStore = {
};
},
+ /**
+ * Subscribe to whether the last sync that ran failed to reach or update the server. Called with the current state.
+ * @param listener - called with true when the last sync failed
+ */
+ onSyncFailureChange(listener: (failed: boolean) => void): () => void {
+ syncFailureListeners.add(listener);
+ listener(lastSyncFailed);
+ return (): void => {
+ syncFailureListeners.delete(listener);
+ };
+ },
+
getEncryptionKey,
getEncryptedVault,
storeEncryptedVault,
+
+ /**
+ * Capture the stored vault and its pending-sync state.
+ */
+ async snapshotLocalVault(): Promise<LocalVaultSnapshot> {
+ const storage = getPlatform().storage;
+ const [vaultBlob, isDirty, dirtyScopes] = await Promise.all([getEncryptedVault(), storage.get<boolean>(StorageKeys.IS_DIRTY), getDirtyScopes()]);
+ return { vaultBlob, isDirty: isDirty === true, dirtyScopes };
+ },
+
+ /**
+ * Put a snapshot back. Bumps the mutation sequence, so a sync that started before cannot store over it.
+ * @param snapshot - the state from snapshotLocalVault
+ */
+ async restoreLocalVault(snapshot: LocalVaultSnapshot): Promise<void> {
+ if (snapshot.vaultBlob === null) {
+ return;
+ }
+ const storage = getPlatform().storage;
+ const mutationSequence = (await storage.get<number>(StorageKeys.MUTATION_SEQUENCE) ?? 0) + 1;
+ await clearDirtyScopes();
+ await storage.setMany([
+ { key: StorageKeys.ENCRYPTED_VAULT, value: snapshot.vaultBlob },
+ { key: StorageKeys.MUTATION_SEQUENCE, value: mutationSequence },
+ { key: StorageKeys.IS_DIRTY, value: snapshot.isDirty },
+ ...snapshot.dirtyScopes.map(scope => ({ key: dirtyScopeStorageKey(scope), value: true })),
+ ]);
+ cachedSqliteClient = null;
+ cachedVaultBlob = null;
+ },
createVaultSqliteClient,
/**
@@ -405,8 +469,9 @@ export const vaultStore = {
* @param options - what the caller asks of the sync beyond what the revisions decide
*/
async fullVaultSync(options?: FullVaultSyncRequest): Promise<FullVaultSyncResult> {
- const result = await fullVaultSyncInternal(options);
- if (options?.reportErrorToPopup !== false) {
+ const { reportErrorToPopup, waitForRunningSync, ...syncOptions } = options ?? {};
+ const result = await fullVaultSyncInternal(syncOptions, waitForRunningSync);
+ if (reportErrorToPopup !== false) {
await persistSyncErrorState(result);
}
return result;