Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(cloud-sync): add selective backup and restore

_Mr丶s ゛😁®a75d34366674
diff --git a/apps/desktop/src/components/editor/CloudSyncSelectionDialog.vue b/apps/desktop/src/components/editor/CloudSyncSelectionDialog.vue
new file mode 100644
index 0000000000..ec00933598
--- /dev/null
+++ b/apps/desktop/src/components/editor/CloudSyncSelectionDialog.vue
@@ -0,0 +1,431 @@
+<script setup lang="ts">
+import { computed, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import type { SyncCatalogItem, SyncSelection, SyncSnapshotCatalog } from "@/lib/backend/api";
+import { transferCategoryForKey, type SettingsTransferCategoryId } from "@/lib/settings/settingsTransfer";
+
+type BackupSettingsCategoryId = Exclude<SettingsTransferCategoryId, "other"> | "ai";
+
+const props = defineProps<{
+ open: boolean;
+ mode: "upload" | "restore";
+ catalog: SyncSnapshotCatalog | null;
+ defaultIncludeSecrets?: boolean;
+}>();
+const { t } = useI18n();
+
+const emit = defineEmits<{
+ "update:open": [value: boolean];
+ confirm: [selection: SyncSelection];
+}>();
+
+const selection = ref<SyncSelection>(emptySelection());
+const isRestore = computed(() => props.mode === "restore");
+
+const backupSettingsCategoryOrder: readonly BackupSettingsCategoryId[] = ["appearance", "editor", "formatter", "navigation", "data", "shortcuts", "snippets", "ai"];
+const backupSettingsCategoryLabelKeys: Record<BackupSettingsCategoryId, string> = {
+ appearance: "settings.appearanceTab",
+ ai: "settings.aiTab",
+ editor: "settings.editorTab",
+ formatter: "settings.sqlFormatterTab",
+ navigation: "settings.navigationTab",
+ data: "settings.dataTab",
+ shortcuts: "settings.shortcutsTab",
+ snippets: "settings.snippetsTab",
+};
+const nonSyncableEditorSettingIds = new Set(["updateNotificationsEnabled", "autoDownloadUpdates", "autoUpdateApp", "autoUpdateDrivers", "autoUpdateJdbc", "autoUpdateMcp", "autoUpdatePlugins", "updateDownloadSource", "ignoredUpdateVersion"]);
+const desktopSettingCategories: Record<string, BackupSettingsCategoryId> = {
+ show_tray_icon: "appearance",
+ icon_theme: "appearance",
+ quit_on_close: "appearance",
+ close_action_prompted: "appearance",
+ sidebar_table_page_size: "navigation",
+ metadata_cache_max_memory_mb: "data",
+ duckdb_worker_process_isolation: "data",
+ duckdb_worker_max_processes: "data",
+};
+const editorSettingCategoryOverrides: Partial<Record<string, BackupSettingsCategoryId>> = {
+ aiFontFamily: "ai",
+ aiFontSize: "ai",
+ customThemeColors: "appearance",
+ appLayout: "appearance",
+ tabLayout: "appearance",
+ tabPlacement: "appearance",
+ tabGroupMode: "appearance",
+ tabGroupCustomizations: "appearance",
+ tabSortMode: "appearance",
+ compactTabTitle: "appearance",
+ executeModeDefaultVersion: "editor",
+ globalConnectTimeoutSecs: "editor",
+ connectTimeoutInheritConnectionIds: "editor",
+ globalQueryTimeoutSecs: "editor",
+ queryTimeoutInheritConnectionIds: "editor",
+ timeoutInheritanceMigrationVersion: "editor",
+ blockDangerousRedisCommands: "editor",
+ tableDdlWordWrap: "editor",
+ refreshDdlOnOpen: "editor",
+ excludeDdlStorage: "editor",
+ sqlSemanticDiagnosticsEnabled: "editor",
+ infiniteScrollMaxRows: "data",
+ tableFontSize: "data",
+ mongoViewMode: "data",
+ dataGridMultiRowTranspose: "data",
+ dataGridHideNullColumns: "data",
+ dataGridBooleanDisplayMode: "data",
+ numericColumnRightAlign: "data",
+ structureEditorDensity: "data",
+ tableInfoActiveTab: "data",
+ tableInfoDrawerPinned: "data",
+ tableInfoDrawerWidth: "data",
+ cellDetailDrawerWidth: "data",
+ cellDetailPanelLayout: "data",
+ cellDetailJsonFormatted: "data",
+ cellDetailMetadataCollapsed: "data",
+ localFilterPopoverWidth: "data",
+ dataGridRenderMode: "data",
+ dataGridSearchMode: "data",
+ dataGridRowNumberMode: "data",
+ dataGridCopyExtractor: "data",
+ dataGridExtractorOptions: "data",
+ dataGridExtractorOptionsMigrationVersion: "data",
+ resultRunDisplayMode: "data",
+ dataGridTextFilterPanelHeight: "data",
+ columnWidthDensity: "data",
+ dataGridColumnWidthMode: "data",
+ sidebarConnectionSortMode: "navigation",
+ sidebarTableSearchLocal: "navigation",
+ sidebarGlobalSearchLocal: "navigation",
+ sidebarBrowseObjectsOnDatabaseActivationMigrationVersion: "navigation",
+ rememberedConnectionDatabases: "navigation",
+ sidebarShowConnectionNotes: "navigation",
+ customColumnFormatters: "data",
+ columnFormatters: "data",
+ pluginShortcuts: "shortcuts",
+ objectBrowserShowCheckbox: "data",
+ objectBrowserViewMode: "data",
+};
+
+function editorSettingCategory(id: string): BackupSettingsCategoryId {
+ const transferCategory = transferCategoryForKey(id);
+ if (transferCategory === "other") return "editor";
+ return editorSettingCategoryOverrides[id] ?? transferCategory ?? "editor";
+}
+
+function selectableDesktopSettings(catalog: SyncSnapshotCatalog): SyncCatalogItem[] {
+ return catalog.desktopSettings.filter((item) => Object.prototype.hasOwnProperty.call(desktopSettingCategories, item.id));
+}
+
+function selectableEditorSettings(catalog: SyncSnapshotCatalog): SyncCatalogItem[] {
+ return catalog.editorSettings.filter((item) => !nonSyncableEditorSettingIds.has(item.id));
+}
+
+function selectedSettings(savedIds: string[] | undefined, items: SyncCatalogItem[]): string[] {
+ if (savedIds === undefined) return items.map((item) => item.id);
+ const saved = new Set(savedIds);
+ return items.filter((item) => saved.has(item.id)).map((item) => item.id);
+}
+
+const backupSettingsCategories = computed(() => {
+ const catalog = props.catalog;
+ if (!catalog) return [];
+ const groups = new Map<BackupSettingsCategoryId, { desktop: SyncCatalogItem[]; editor: SyncCatalogItem[] }>();
+ for (const category of backupSettingsCategoryOrder) groups.set(category, { desktop: [], editor: [] });
+ for (const item of selectableDesktopSettings(catalog)) groups.get(desktopSettingCategories[item.id])?.desktop.push(item);
+ for (const item of selectableEditorSettings(catalog)) groups.get(editorSettingCategory(item.id))?.editor.push(item);
+ return backupSettingsCategoryOrder.flatMap((category) => {
+ const group = groups.get(category)!;
+ const desktopSelected = group.desktop.filter((item) => selection.value.desktopSettings?.includes(item.id)).length;
+ const editorSelected = group.editor.filter((item) => selection.value.editorSettings?.includes(item.id)).length;
+ const total = group.desktop.length + group.editor.length;
+ if (!total) return [];
+ return [{ id: category, labelKey: backupSettingsCategoryLabelKeys[category], desktop: group.desktop, editor: group.editor, total, selected: desktopSelected + editorSelected }];
+ });
+});
+
+function emptySelection(): SyncSelection {
+ return {
+ connections: [],
+ connectionSecrets: [],
+ tunnelProfiles: [],
+ tunnelSecrets: [],
+ savedSqlFolders: [],
+ savedSqlFiles: [],
+ desktopSettings: [],
+ editorSettings: [],
+ aiConfigs: [],
+ pluginUiStorage: [],
+ sidebarLayout: false,
+ pinnedTreeNodeIds: false,
+ includeSecrets: false,
+ syncCredentials: false,
+ };
+}
+
+function resetFromCatalog() {
+ const catalog = props.catalog;
+ if (!catalog) return;
+ const saved = catalog.selection;
+ const desktopSettings = selectableDesktopSettings(catalog);
+ const editorSettings = selectableEditorSettings(catalog);
+ selection.value = {
+ ...emptySelection(),
+ connections: saved?.connections ?? catalog.connections.map((item) => item.id),
+ connectionSecrets: saved?.connectionSecrets ?? (catalog.hasEncryptedSecrets ? catalog.connectionSecrets : []),
+ tunnelProfiles: saved?.tunnelProfiles ?? catalog.tunnelProfiles.map((item) => item.id),
+ tunnelSecrets: saved?.tunnelSecrets ?? (catalog.hasEncryptedSecrets ? catalog.tunnelSecrets : []),
+ savedSqlFolders: saved?.savedSqlFolders ?? catalog.savedSqlFolders.map((item) => item.id),
+ savedSqlFiles: saved?.savedSqlFiles ?? catalog.savedSqlFiles.map((item) => item.id),
+ desktopSettings: selectedSettings(saved?.desktopSettings, desktopSettings),
+ editorSettings: selectedSettings(saved?.editorSettings, editorSettings),
+ aiConfigs: saved?.aiConfigs ?? (catalog.aiConfigsLocked ? undefined : catalog.aiConfigs.map((item) => item.id)),
+ pluginUiStorage: saved?.pluginUiStorage ?? (catalog.pluginUiStorageLocked ? undefined : catalog.pluginUiStorage),
+ sidebarLayout: saved?.sidebarLayout ?? catalog.hasSidebarLayout,
+ pinnedTreeNodeIds: saved?.pinnedTreeNodeIds ?? catalog.hasPinnedTreeNodeIds,
+ includeSecrets: saved?.includeSecrets ?? (isRestore.value ? catalog.hasEncryptedSecrets : !!props.defaultIncludeSecrets),
+ syncCredentials: saved?.syncCredentials ?? (isRestore.value ? catalog.hasEncryptedSecrets : !!props.defaultIncludeSecrets),
+ };
+ if (selection.value.includeSecrets && !saved) onSecretsChanged();
+}
+
+watch(
+ () => [props.open, props.catalog] as const,
+ ([open]) => {
+ if (open) resetFromCatalog();
+ },
+ { immediate: true },
+);
+
+function ids(key: "connections" | "connectionSecrets" | "tunnelProfiles" | "tunnelSecrets" | "savedSqlFolders" | "savedSqlFiles" | "desktopSettings" | "editorSettings" | "aiConfigs") {
+ return selection.value[key] ?? [];
+}
+
+function toggleId(key: "connections" | "connectionSecrets" | "tunnelProfiles" | "tunnelSecrets" | "savedSqlFolders" | "savedSqlFiles" | "desktopSettings" | "editorSettings" | "aiConfigs", id: string) {
+ const current = ids(key);
+ selection.value[key] = current.includes(id) ? current.filter((item) => item !== id) : [...current, id];
+}
+
+function toggleAll(key: "connections" | "tunnelProfiles" | "savedSqlFolders" | "savedSqlFiles" | "desktopSettings" | "editorSettings" | "aiConfigs", items: SyncCatalogItem[]) {
+ const current = ids(key);
+ selection.value[key] = current.length === items.length ? [] : items.map((item) => item.id);
+}
+
+function toggleSettingsCategory(category: BackupSettingsCategoryId) {
+ const catalog = props.catalog;
+ const group = backupSettingsCategories.value.find((item) => item.id === category);
+ if (!catalog || !group) return;
+ const include = group.selected !== group.total;
+ const desktopIds = new Set(selectedSettings(selection.value.desktopSettings, selectableDesktopSettings(catalog)));
+ const editorIds = new Set(selectedSettings(selection.value.editorSettings, selectableEditorSettings(catalog)));
+ for (const item of group.desktop) {
+ if (include) desktopIds.add(item.id);
+ else desktopIds.delete(item.id);
+ }
+ for (const item of group.editor) {
+ if (include) editorIds.add(item.id);
+ else editorIds.delete(item.id);
+ }
+ selection.value.desktopSettings = [...desktopIds];
+ selection.value.editorSettings = [...editorIds];
+}
+
+function togglePluginItem(pluginId: string, key: string) {
+ const current = selection.value.pluginUiStorage ?? [];
+ const exists = current.some((item) => item.pluginId === pluginId && item.key === key);
+ selection.value.pluginUiStorage = exists ? current.filter((item) => item.pluginId !== pluginId || item.key !== key) : [...current, props.catalog?.pluginUiStorage.find((item) => item.pluginId === pluginId && item.key === key)!];
+}
+
+function togglePluginAll() {
+ if (props.catalog?.pluginUiStorageLocked) {
+ selection.value.pluginUiStorage = selection.value.pluginUiStorage === undefined ? [] : undefined;
+ return;
+ }
+ const all = props.catalog?.pluginUiStorage ?? [];
+ selection.value.pluginUiStorage = selection.value.pluginUiStorage?.length === all.length ? [] : [...all];
+}
+
+function toggleAllAiConfigs() {
+ if (props.catalog?.aiConfigsLocked) {
+ selection.value.aiConfigs = selection.value.aiConfigs === undefined ? [] : undefined;
+ return;
+ }
+ toggleAll("aiConfigs", props.catalog?.aiConfigs ?? []);
+}
+
+function onSecretsChanged() {
+ if (!selection.value.includeSecrets || !props.catalog) return;
+ if (!selection.value.connectionSecrets?.length) selection.value.connectionSecrets = [...props.catalog.connectionSecrets];
+ if (!selection.value.tunnelSecrets?.length) selection.value.tunnelSecrets = [...props.catalog.tunnelSecrets];
+ if (!selection.value.aiConfigs?.length && props.catalog.aiConfigs.length) selection.value.aiConfigs = props.catalog.aiConfigs.map((item) => item.id);
+ if (!selection.value.pluginUiStorage?.length && !props.catalog.pluginUiStorageLocked) selection.value.pluginUiStorage = [...props.catalog.pluginUiStorage];
+ selection.value.syncCredentials = true;
+}
+
+function checked(key: "connections" | "connectionSecrets" | "tunnelProfiles" | "tunnelSecrets" | "savedSqlFolders" | "savedSqlFiles" | "desktopSettings" | "editorSettings" | "aiConfigs", id: string) {
+ return ids(key).includes(id);
+}
+
+function confirmSelection() {
+ if (props.catalog) {
+ selection.value.desktopSettings = selectedSettings(selection.value.desktopSettings, selectableDesktopSettings(props.catalog));
+ selection.value.editorSettings = selectedSettings(selection.value.editorSettings, selectableEditorSettings(props.catalog));
+ }
+ emit("confirm", structuredClone(selection.value));
+ emit("update:open", false);
+}
+</script>
+
+<template>
+ <Dialog :open="open" @update:open="emit('update:open', $event)">
+ <DialogContent class="flex max-h-[min(88vh,calc(var(--dbx-viewport-height)-4rem))] flex-col gap-0 overflow-hidden border border-border !bg-background-solid p-0 text-foreground shadow-2xl !backdrop-blur-none sm:max-w-[760px]">
+ <DialogHeader class="shrink-0 border-b px-5 py-4">
+ <DialogTitle>{{ isRestore ? t("settings.syncSelectionRestoreTitle") : t("settings.syncSelectionUploadTitle") }}</DialogTitle>
+ <DialogDescription>
+ {{ isRestore ? t("settings.syncSelectionRestoreNote") : t("settings.syncSelectionBackupNote") }}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div v-if="catalog" class="min-h-0 flex-1 space-y-2 overflow-y-auto px-5 py-4">
+ <details open class="border-b pb-2">
+ <summary class="flex cursor-pointer list-none items-center gap-2 py-2 text-sm font-medium">
+ <input :checked="selection.connections?.length === catalog.connections.length" type="checkbox" class="size-4 accent-primary" @click.stop.prevent="toggleAll('connections', catalog.connections)" />
+ <span>{{ t("settings.syncSelectionConnections") }}</span>
+ <span class="ml-auto text-xs text-muted-foreground">{{ selection.connections?.length ?? 0 }}/{{ catalog.connections.length }}</span>
+ </summary>
+ <div class="ml-6 space-y-1 pb-2">
+ <div v-for="item in catalog.connections" :key="item.id" class="py-1">
+ <label class="flex min-h-7 items-center gap-2 text-sm">
+ <input :checked="checked('connections', item.id)" type="checkbox" class="size-4 accent-primary" @change="toggleId('connections', item.id)" />
+ <span class="min-w-0 truncate">{{ item.label || item.id }}</span>
+ </label>
+ <label v-if="catalog.connectionSecrets.includes(item.id)" class="ml-6 flex min-h-7 items-center gap-2 text-xs text-muted-foreground">
+ <input :checked="checked('connectionSecrets', item.id)" :disabled="!selection.includeSecrets || !selection.connections?.includes(item.id)" type="checkbox" class="size-3.5 accent-primary" @change="toggleId('connectionSecrets', item.id)" />
+ <span>{{ t("settings.syncSelectionConnectionSecrets") }}</span>
+ </label>
+ </div>
+ <p v-if="!catalog.connections.length" class="py-1 text-xs text-muted-foreground">{{ t("settings.syncSelectionNoConnections") }}</p>
+ </div>
+ </details>
+
+ <details open class="border-b pb-2">
+ <summary class="flex cursor-pointer list-none items-center gap-2 py-2 text-sm font-medium">
+ <input :checked="selection.tunnelProfiles?.length === catalog.tunnelProfiles.length" type="checkbox" class="size-4 accent-primary" @click.stop.prevent="toggleAll('tunnelProfiles', catalog.tunnelProfiles)" />
+ <span>{{ t("settings.syncSelectionTunnels") }}</span>
+ <span class="ml-auto text-xs text-muted-foreground">{{ selection.tunnelProfiles?.length ?? 0 }}/{{ catalog.tunnelProfiles.length }}</span>
+ </summary>
+ <div class="ml-6 space-y-1 pb-2">
+ <div v-for="item in catalog.tunnelProfiles" :key="item.id" class="py-1">
+ <label class="flex min-h-7 items-center gap-2 text-sm">
+ <input :checked="checked('tunnelProfiles', item.id)" type="checkbox" class="size-4 accent-primary" @change="toggleId('tunnelProfiles', item.id)" />
+ <span class="min-w-0 truncate">{{ item.label || item.id }}</span>
+ </label>
+ <label v-if="catalog.tunnelSecrets.includes(item.id)" class="ml-6 flex min-h-7 items-center gap-2 text-xs text-muted-foreground">
+ <input :checked="checked('tunnelSecrets', item.id)" :disabled="!selection.includeSecrets || !selection.tunnelProfiles?.includes(item.id)" type="checkbox" class="size-3.5 accent-primary" @change="toggleId('tunnelSecrets', item.id)" />
+ <span>{{ t("settings.syncSelectionTunnelSecrets") }}</span>
+ </label>
+ </div>
+ <p v-if="!catalog.tunnelProfiles.length" class="py-1 text-xs text-muted-foreground">{{ t("settings.syncSelectionNoTunnels") }}</p>
+ </div>
+ </details>
+
+ <details open class="border-b pb-2">
+ <summary class="flex cursor-pointer list-none items-center gap-2 py-2 text-sm font-medium">{{ t("settings.syncSelectionSavedSql") }}</summary>
+ <div class="ml-6 space-y-2 pb-2">
+ <div>
+ <button type="button" class="mb-1 text-xs font-medium text-muted-foreground hover:text-foreground" @click="toggleAll('savedSqlFolders', catalog.savedSqlFolders)">
+ {{ t("settings.syncSelectionFolders") }} ({{ selection.savedSqlFolders?.length ?? 0 }}/{{ catalog.savedSqlFolders.length }})
+ </button>
+ <label v-for="item in catalog.savedSqlFolders" :key="item.id" class="flex min-h-7 items-center gap-2 pl-1 text-sm">
+ <input :checked="checked('savedSqlFolders', item.id)" type="checkbox" class="size-4 accent-primary" @change="toggleId('savedSqlFolders', item.id)" />
+ <span class="min-w-0 truncate">{{ item.label || item.id }}</span>
+ </label>
+ </div>
+ <div>
+ <button type="button" class="mb-1 text-xs font-medium text-muted-foreground hover:text-foreground" @click="toggleAll('savedSqlFiles', catalog.savedSqlFiles)">{{ t("settings.syncSelectionFiles") }} ({{ selection.savedSqlFiles?.length ?? 0 }}/{{ catalog.savedSqlFiles.length }})</button>
+ <label v-for="item in catalog.savedSqlFiles" :key="item.id" class="flex min-h-7 items-center gap-2 pl-1 text-sm">
+ <input :checked="checked('savedSqlFiles', item.id)" type="checkbox" class="size-4 accent-primary" @change="toggleId('savedSqlFiles', item.id)" />
+ <span class="min-w-0 truncate">{{ item.label || item.id }}</span>
+ </label>
+ </div>
+ </div>
+ </details>
+
+ <details open class="border-b pb-2">
+ <summary class="flex cursor-pointer list-none items-center gap-2 py-2 text-sm font-medium">{{ t("settings.syncSelectionPersonalSettings") }}</summary>
+ <div class="ml-6 space-y-1 py-2">
+ <label v-for="category in backupSettingsCategories" :key="category.id" class="flex min-h-7 items-center gap-2 text-sm">
+ <input :checked="category.total > 0 && category.selected === category.total" type="checkbox" class="size-4 accent-primary" @change="toggleSettingsCategory(category.id)" />
+ <span>{{ t(category.labelKey) }}</span>
+ <span class="ml-auto text-xs text-muted-foreground">{{ category.selected }}/{{ category.total }}</span>
+ </label>
+ </div>
+ </details>
+
+ <details open class="border-b pb-2">
+ <summary class="flex cursor-pointer list-none items-center gap-2 py-2 text-sm font-medium">
+ <input v-model="selection.includeSecrets" type="checkbox" class="size-4 accent-primary" @click.stop @change="onSecretsChanged" />
+ <span>{{ t("settings.syncSelectionEncrypted") }}</span>
+ </summary>
+ <div class="ml-6 space-y-2 pb-2">
+ <label class="flex min-h-7 items-center gap-2 text-sm">
+ <input v-model="selection.syncCredentials" :disabled="!selection.includeSecrets" type="checkbox" class="size-4 accent-primary" />
+ <span>{{ t("settings.syncSelectionSyncCredentials") }}</span>
+ </label>
+ <div>
+ <label v-if="catalog.aiConfigsLocked" class="flex min-h-7 items-center gap-2 text-sm">
+ <input :checked="selection.aiConfigs === undefined" :disabled="!selection.includeSecrets" type="checkbox" class="size-4 accent-primary" @change="toggleAllAiConfigs" />
+ <span>{{ t("settings.syncSelectionAiLocked") }}</span>
+ </label>
+ <template v-else>
+ <button type="button" class="mb-1 text-xs font-medium text-muted-foreground hover:text-foreground" :disabled="!selection.includeSecrets" @click="toggleAllAiConfigs">
+ {{ t("settings.syncSelectionAiConfigs") }} ({{ selection.aiConfigs?.length ?? 0 }}/{{ catalog.aiConfigs.length }})
+ </button>
+ <label v-for="item in catalog.aiConfigs" :key="item.id" class="flex min-h-7 items-center gap-2 text-sm">
+ <input :checked="checked('aiConfigs', item.id)" :disabled="!selection.includeSecrets" type="checkbox" class="size-4 accent-primary" @change="toggleId('aiConfigs', item.id)" />
+ <span class="min-w-0 truncate">{{ item.label || item.id }}</span>
+ </label>
+ </template>
+ </div>
+ <div>
+ <label v-if="catalog.pluginUiStorageLocked" class="flex min-h-7 items-center gap-2 text-sm">
+ <input :checked="selection.pluginUiStorage === undefined" :disabled="!selection.includeSecrets" type="checkbox" class="size-4 accent-primary" @change="togglePluginAll" />
+ <span>{{ t("settings.syncSelectionPluginLocked") }}</span>
+ </label>
+ <template v-else>
+ <button type="button" class="mb-1 text-xs font-medium text-muted-foreground hover:text-foreground" :disabled="!selection.includeSecrets" @click="togglePluginAll">
+ {{ t("settings.syncSelectionPluginData") }} ({{ selection.pluginUiStorage?.length ?? 0 }}/{{ catalog.pluginUiStorage.length }})
+ </button>
+ <label v-for="item in catalog.pluginUiStorage" :key="item.pluginId + '/' + item.key" class="flex min-h-7 items-center gap-2 text-sm">
+ <input :checked="selection.pluginUiStorage?.some((entry) => entry.pluginId === item.pluginId && entry.key === item.key)" :disabled="!selection.includeSecrets" type="checkbox" class="size-4 accent-primary" @change="togglePluginItem(item.pluginId, item.key)" />
+ <span class="min-w-0 truncate">{{ item.pluginName || item.pluginId }} / {{ item.key }}</span>
+ </label>
+ <p v-if="!catalog.pluginUiStorage.length" class="text-xs text-muted-foreground">{{ t("settings.syncSelectionNoPluginData") }}</p>
+ </template>
+ </div>
+ <p v-if="!catalog.hasEncryptedSecrets && isRestore" class="text-xs text-muted-foreground">{{ t("settings.syncSelectionNoEncrypted") }}</p>
+ </div>
+ </details>
+
+ <details open class="pb-1">
+ <summary class="flex cursor-pointer list-none items-center gap-2 py-2 text-sm font-medium">{{ t("settings.syncSelectionWorkspace") }}</summary>
+ <div class="ml-6 space-y-1 pb-2">
+ <label class="flex min-h-7 items-center gap-2 text-sm">
+ <input v-model="selection.sidebarLayout" :disabled="!catalog.hasSidebarLayout" type="checkbox" class="size-4 accent-primary" />
+ <span>{{ t("settings.syncSelectionSidebar") }}</span>
+ </label>
+ <label class="flex min-h-7 items-center gap-2 text-sm">
+ <input v-model="selection.pinnedTreeNodeIds" :disabled="!catalog.hasPinnedTreeNodeIds" type="checkbox" class="size-4 accent-primary" />
+ <span>{{ t("settings.syncSelectionPinned") }}</span>
+ </label>
+ </div>
+ </details>
+ </div>
+
+ <DialogFooter class="mx-0 mb-0 shrink-0 border-t px-5 pb-4 pt-3">
+ <Button variant="outline" @click="emit('update:open', false)">{{ t("settings.syncSelectionCancel") }}</Button>
+ <Button :disabled="!catalog" @click="confirmSelection">{{ isRestore ? t("settings.syncSelectionRestoreAction") : t("settings.syncSelectionUploadAction") }}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+</template>
diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
index 38f55254f0..6e7172cfc7 100644
--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue
+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
@@ -124,6 +124,7 @@ import ThemeCustomizerDialog from "./ThemeCustomizerDialog.vue";
import DataGridTypeColorSchemeDialog from "@/components/grid/DataGridTypeColorSchemeDialog.vue";
import { DATA_GRID_TYPE_COLOR_SCHEME_AUTO_ID, cloneDataGridTypeColorSchemes, type DataGridTypeColorScheme } from "@/lib/dataGrid/dataGridTypeColorScheme";
import TunnelProfileManager from "@/components/connection/TunnelProfileManager.vue";
+import CloudSyncSelectionDialog from "@/components/editor/CloudSyncSelectionDialog.vue";
import DangerConfirmDialog from "./DangerConfirmDialog.vue";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { useTheme } from "@/composables/useTheme";
@@ -149,6 +150,7 @@ import {
forgetWebdavSavedPassword,
getAppSupportInfo,
checkBackgroundImage,
+ cloudSyncLocalCatalog,
clearBackgroundImage,
saveBackgroundImage,
loadMaxAgentTurns,
@@ -163,12 +165,14 @@ import {
saveSnippetSyncId,
retrySnippetLegacyCleanup,
snippetSyncDownload,
+ snippetSyncInspect,
snippetSyncSettings,
snippetSyncTest,
snippetSyncUpload,
snippetTokenStatus,
webdavPasswordStatus,
webdavSyncDownload,
+ webdavSyncInspect,
webdavSyncSecretsStatus,
webdavSyncTest,
webdavSyncUpload,
@@ -181,6 +185,8 @@ import {
type McpServerStatus,
type SnippetProvider,
type SnippetSyncConfig,
+ type SyncSelection,
+ type SyncSnapshotCatalog,
type WebDavConfig,
} from "@/lib/backend/api";
import { eventToModifierOnlyShortcut, eventToShortcut } from "@/lib/editor/keyboardShortcuts";
@@ -295,7 +301,7 @@ import {
type ToolbarVisibilityItem,
} from "@/lib/settings/settingsSearch";
import { LOCALE_OPTIONS } from "@/lib/app/localeOptions";
-import { DEFAULT_WEB_DAV_AUTO_UPLOAD_INTERVAL_MINUTES, DEFAULT_WEB_DAV_REMOTE_PATH, normalizedWebDavAutoUploadInterval, writeWebDavAutoUploadFields } from "@/lib/webdav/webdavAutoUploadConfig";
+import { DEFAULT_WEB_DAV_AUTO_UPLOAD_INTERVAL_MINUTES, DEFAULT_WEB_DAV_REMOTE_PATH, normalizedWebDavAutoUploadInterval, writeWebDavAutoUploadFields, writeWebDavBackupSelection } from "@/lib/webdav/webdavAutoUploadConfig";
import { apiUrl, webPath } from "@/lib/common/webPath";
import { DEFAULT_DATA_GRID_FONT_FAMILY, DEFAULT_UI_FONT_FAMILY, normalizeCustomFontFamilyInput, readableFontFamily, SYSTEM_UI_FONT_FAMILY } from "@/lib/app/appFonts";
import { buildFontFamilyOptions, displayFontFamily, isPresetFontFamily, loadSystemFontNames } from "@/lib/app/fontFamilyOptions";
@@ -4215,6 +4221,9 @@ const webdavBusy = ref<"" | "test" | "upload" | "download">("");
const webdavMessage = ref("");
const webdavError = ref(false);
const syncMethodTab = ref<"webdav" | "snippet">("webdav");
+const syncSelectionOpen = ref(false);
+const syncSelectionMode = ref<"upload" | "restore">("upload");
+const syncSelectionCatalog = ref<SyncSnapshotCatalog | null>(null);
const snippetProvider = ref<SnippetProvider>((localStorage.getItem("dbx-snippet-provider") as SnippetProvider) || "github");
const snippetInstanceUrl = ref(localStorage.getItem("dbx-gitlab-instance-url") || "https://gitlab.com");
@@ -4236,13 +4245,13 @@ const legacySnippetId = ref("");
const pendingLegacyCleanupId = ref("");
const snippetSyncSettingsLoading = ref(true);
-const webdavReady = computed(() => !!webdavEndpoint.value.trim() && !webdavBusy.value && (!webdavSyncSecrets.value || !!webdavSecretsPassphrase.value.trim() || webdavHasSavedSecretsPassphrase.value));
+const webdavReady = computed(() => !!webdavEndpoint.value.trim() && !webdavBusy.value);
const snippetReady = computed(() => !snippetSyncSettingsLoading.value && !snippetBusy.value && (snippetProvider.value !== "gitlab" || (!snippetInstanceError.value && snippetInstanceUrl.value === activeSnippetInstanceUrl.value)) && (!!snippetToken.value.trim() || snippetHasSavedToken.value));
-const snippetUploadReady = computed(() => snippetReady.value && !!snippetPassphrase.value.trim() && (!snippetIncludeSecrets.value || !!snippetSecretsPassphrase.value.trim()));
+const snippetUploadReady = computed(() => snippetReady.value && !!snippetPassphrase.value.trim());
// Legacy plaintext snippets have no outer encryption password. Let the
// backend require one only after it detects an encrypted envelope so those
// snapshots remain recoverable for migration.
-const snippetDownloadReady = computed(() => snippetReady.value && (!snippetRestoreSecrets.value || !!snippetSecretsPassphrase.value.trim()));
+const snippetDownloadReady = computed(() => snippetReady.value);
function currentSnippetConfig(replaceLegacySnippet = false): SnippetSyncConfig {
return {
@@ -4373,13 +4382,10 @@ async function uploadSnippetSnapshot() {
return;
}
await runSnippetAction("upload", async () => {
- const summary = await snippetSyncUpload(currentSnippetConfig(), settingsStore.editorSettings, snippetPassphrase.value, snippetIncludeSecrets.value, snippetIncludeSecrets.value ? snippetSecretsPassphrase.value : undefined);
- snippetId.value = summary.snippetId;
- await persistSnippetSyncId();
- return t("settings.syncSnippetUploadSuccess", {
- bytes: summary.bytes,
- id: summary.snippetId,
- });
+ syncSelectionCatalog.value = await cloudSyncLocalCatalog(settingsStore.editorSettings);
+ syncSelectionMode.value = "upload";
+ syncSelectionOpen.value = true;
+ return "";
});
}
@@ -4420,24 +4426,12 @@ async function retryLegacySnippetCleanup() {
}
async function downloadSnippetSnapshot() {
- if (!snippetId.value.trim() || !window.confirm(t("settings.syncDownloadConfirm"))) return;
+ if (!snippetId.value.trim()) return;
await runSnippetAction("download", async () => {
- const result = await snippetSyncDownload(currentSnippetConfig(), snippetPassphrase.value, snippetRestoreSecrets.value, snippetRestoreSecrets.value ? snippetSecretsPassphrase.value : undefined);
- if (result.editorSettings && typeof result.editorSettings === "object") settingsStore.updateEditorSettings(result.editorSettings as any);
- await settingsStore.updateDesktopSettings(result.desktopSettings);
- await connectionStore.initFromDisk();
- await savedSqlStore.initFromStorage();
- // Snapshot downloads replace backend-managed tunnel profiles, so refresh
- // the already-loaded Pinia store instead of leaving the UI stale.
- await tunnelProfileStore.refresh();
- await settingsStore.reloadAiConfigs();
- let message = t("settings.syncSnippetDownloadSuccess", {
- bytes: result.summary.bytes,
- id: result.summary.snippetId,
- });
- if (result.applySummary.encryptedSecretsPresent && !result.applySummary.secretsApplied) message += ` ${t("settings.syncSecretsSkipped")}`;
- if (result.applySummary.secretsApplied) message += ` ${t("settings.syncSecretsApplied")}`;
- return message;
+ syncSelectionCatalog.value = await snippetSyncInspect(currentSnippetConfig(), snippetPassphrase.value || undefined, snippetSecretsPassphrase.value || undefined);
+ syncSelectionMode.value = "restore";
+ syncSelectionOpen.value = true;
+ return "";
});
}
@@ -4555,37 +4549,72 @@ async function testWebDav() {
async function uploadWebDavSnapshot() {
await runWebDavAction("upload", async () => {
- const summary = await webdavSyncUpload(currentWebDavConfig(), settingsStore.editorSettings, webdavSyncSecrets.value ? webdavSecretsPassphrase.value : undefined, webdavSyncSecrets.value);
- return t("settings.syncUploadSuccess", {
- bytes: summary.bytes,
- path: summary.remotePath,
- });
+ syncSelectionCatalog.value = await cloudSyncLocalCatalog(settingsStore.editorSettings);
+ syncSelectionMode.value = "upload";
+ syncSelectionOpen.value = true;
+ return "";
});
}
async function downloadWebDavSnapshot() {
- if (!window.confirm(t("settings.syncDownloadConfirm"))) return;
await runWebDavAction("download", async () => {
- const result = await webdavSyncDownload(currentWebDavConfig(), webdavSyncSecrets.value ? webdavSecretsPassphrase.value : undefined, webdavSyncSecrets.value);
- if (result.editorSettings && typeof result.editorSettings === "object") {
- settingsStore.updateEditorSettings(result.editorSettings as any);
+ syncSelectionCatalog.value = await webdavSyncInspect(currentWebDavConfig(), webdavSecretsPassphrase.value || undefined);
+ syncSelectionMode.value = "restore";
+ syncSelectionOpen.value = true;
+ return "";
+ });
+}
+
+async function confirmSyncSelection(selection: SyncSelection) {
+ if (syncMethodTab.value === "snippet") {
+ if (syncSelectionMode.value === "upload") {
+ snippetIncludeSecrets.value = selection.includeSecrets;
+ await runSnippetAction("upload", async () => {
+ const summary = await snippetSyncUpload(currentSnippetConfig(), settingsStore.editorSettings, snippetPassphrase.value, selection.includeSecrets, selection.includeSecrets ? snippetSecretsPassphrase.value : undefined, selection);
+ snippetId.value = summary.snippetId;
+ await persistSnippetSyncId();
+ return t("settings.syncSnippetUploadSuccess", { bytes: summary.bytes, id: summary.snippetId });
+ });
+ return;
}
+ snippetRestoreSecrets.value = selection.includeSecrets;
+ await runSnippetAction("download", async () => {
+ const result = await snippetSyncDownload(currentSnippetConfig(), snippetPassphrase.value, selection.includeSecrets, selection.includeSecrets ? snippetSecretsPassphrase.value : undefined, selection);
+ if (result.editorSettings && typeof result.editorSettings === "object") settingsStore.updateEditorSettings(result.editorSettings as any);
+ await settingsStore.updateDesktopSettings(result.desktopSettings);
+ await connectionStore.initFromDisk();
+ await savedSqlStore.initFromStorage();
+ await tunnelProfileStore.refresh();
+ await settingsStore.reloadAiConfigs();
+ let message = t("settings.syncSnippetDownloadSuccess", { bytes: result.summary.bytes, id: result.summary.snippetId });
+ if (result.applySummary.encryptedSecretsPresent && !result.applySummary.secretsApplied) message += ` ${t("settings.syncSecretsSkipped")}`;
+ if (result.applySummary.secretsApplied) message += ` ${t("settings.syncSecretsApplied")}`;
+ return message;
+ });
+ return;
+ }
+
+ webdavSyncSecrets.value = selection.includeSecrets;
+ if (syncSelectionMode.value === "upload") {
+ await runWebDavAction("upload", async () => {
+ const summary = await webdavSyncUpload(currentWebDavConfig(), settingsStore.editorSettings, selection.includeSecrets ? webdavSecretsPassphrase.value || undefined : undefined, selection.includeSecrets, selection);
+ writeWebDavBackupSelection(selection);
+ return t("settings.syncUploadSuccess", { bytes: summary.bytes, path: summary.remotePath });
+ });
+ return;
+ }
+
+ await runWebDavAction("download", async () => {
+ const result = await webdavSyncDownload(currentWebDavConfig(), selection.includeSecrets ? webdavSecretsPassphrase.value || undefined : undefined, selection.includeSecrets, selection);
+ if (result.editorSettings && typeof result.editorSettings === "object") settingsStore.updateEditorSettings(result.editorSettings as any);
await settingsStore.updateDesktopSettings(result.desktopSettings);
await connectionStore.initFromDisk();
await savedSqlStore.initFromStorage();
- // Keep the shared tunnel profile UI consistent with the downloaded snapshot.
await tunnelProfileStore.refresh();
await settingsStore.reloadAiConfigs();
- const message = t("settings.syncDownloadSuccess", {
- bytes: result.summary.bytes,
- path: result.summary.remotePath,
- });
- if (result.applySummary.encryptedSecretsPresent && !result.applySummary.secretsApplied) {
- return `${message} ${t("settings.syncSecretsSkipped")}`;
- }
- if (result.applySummary.secretsApplied) {
- return `${message} ${t("settings.syncSecretsApplied")}`;
- }
+ const message = t("settings.syncDownloadSuccess", { bytes: result.summary.bytes, path: result.summary.remotePath });
+ if (result.applySummary.encryptedSecretsPresent && !result.applySummary.secretsApplied) return `${message} ${t("settings.syncSecretsSkipped")}`;
+ if (result.applySummary.secretsApplied) return `${message} ${t("settings.syncSecretsApplied")}`;
return message;
});
}
@@ -9277,6 +9306,7 @@ LIMIT 100;</pre
</p>
</div>
</div>
+ <CloudSyncSelectionDialog v-model:open="syncSelectionOpen" :mode="syncSelectionMode" :catalog="syncSelectionCatalog" :default-include-secrets="syncMethodTab === 'snippet' ? snippetIncludeSecrets : webdavSyncSecrets" @confirm="confirmSyncSelection" />
</section>
<!-- AI Settings Tab -->
diff --git a/apps/desktop/src/composables/useWebDavAutoUpload.ts b/apps/desktop/src/composables/useWebDavAutoUpload.ts
index 6f50b57e28..c7ccc3799e 100644
--- a/apps/desktop/src/composables/useWebDavAutoUpload.ts
+++ b/apps/desktop/src/composables/useWebDavAutoUpload.ts
@@ -2,7 +2,7 @@ import { onMounted, onUnmounted } from "vue";
import { useSettingsStore } from "@/stores/settingsStore";
import { appendDebugLog } from "@/lib/backend/debugLog";
import { webdavSyncSecretsStatus, webdavSyncUpload } from "@/lib/backend/api";
-import { readWebDavAutoUploadConfig, WEB_DAV_AUTO_UPLOAD_STORAGE_KEYS } from "@/lib/webdav/webdavAutoUploadConfig";
+import { readWebDavAutoUploadConfig, readWebDavBackupSelection, WEB_DAV_AUTO_UPLOAD_STORAGE_KEYS } from "@/lib/webdav/webdavAutoUploadConfig";
export function useWebDavAutoUpload() {
const settingsStore = useSettingsStore();
@@ -33,7 +33,9 @@ export function useWebDavAutoUpload() {
uploading = true;
try {
const secretsStatus = await webdavSyncSecretsStatus();
- const summary = await webdavSyncUpload(config.webDavConfig, settingsStore.editorSettings, undefined, secretsStatus.enabled && secretsStatus.hasSavedPassphrase);
+ const selection = readWebDavBackupSelection();
+ const includeSecrets = (selection?.includeSecrets ?? secretsStatus.enabled) && secretsStatus.enabled && secretsStatus.hasSavedPassphrase;
+ const summary = await webdavSyncUpload(config.webDavConfig, settingsStore.editorSettings, undefined, includeSecrets, selection);
appendDebugLog("info", "[DBX][webdav:auto-upload:success]", {
bytes: summary.bytes,
remotePath: summary.remotePath,
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 298882f678..49ac768245 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -8293,6 +8293,36 @@ export default {
sqlShortcutsSelectLimitHint: "At run time, SQL is generated for the active connection dialect.",
syncWebDavTitle: "WebDAV Sync",
syncWebDavDescription: "Upload or restore a DBX snapshot, including saved SQL library entries, from a WebDAV-compatible storage service.",
+ syncSelectionUploadTitle: "Select backup content",
+ syncSelectionRestoreTitle: "Select restore content",
+ syncSelectionBackupNote: "Sensitive credentials and plugin data are stored only in encrypted snapshots.",
+ syncSelectionRestoreNote: "Unchecked local content will be kept.",
+ syncSelectionConnections: "Connections and SSH",
+ syncSelectionConnectionSecrets: "Passwords, SSH passwords/key passphrases, and connection credentials",
+ syncSelectionNoConnections: "No connections",
+ syncSelectionTunnels: "Shared tunnel profiles",
+ syncSelectionTunnelSecrets: "Tunnel credentials",
+ syncSelectionNoTunnels: "No tunnel profiles",
+ syncSelectionSavedSql: "Saved SQL",
+ syncSelectionFolders: "SQL folders",
+ syncSelectionFiles: "SQL files",
+ syncSelectionPersonalSettings: "Personal settings",
+ syncSelectionDesktopSettings: "Desktop settings",
+ syncSelectionEditorSettings: "Editor settings",
+ syncSelectionEncrypted: "Encrypted sensitive information",
+ syncSelectionSyncCredentials: "Saved sync service credentials",
+ syncSelectionAiConfigs: "AI configurations",
+ syncSelectionAiLocked: "Remote AI configurations (encrypted contents locked)",
+ syncSelectionPluginData: "Plugin settings data",
+ syncSelectionPluginLocked: "Remote plugin settings (encrypted contents locked)",
+ syncSelectionNoPluginData: "No plugin settings data",
+ syncSelectionNoEncrypted: "The remote snapshot has no encrypted sensitive information.",
+ syncSelectionWorkspace: "Workspace layout",
+ syncSelectionSidebar: "Sidebar layout",
+ syncSelectionPinned: "Pinned tree nodes",
+ syncSelectionCancel: "Cancel",
+ syncSelectionRestoreAction: "Restore selected",
+ syncSelectionUploadAction: "Back up selected",
syncWebDavWebDescription: "In Web mode, the DBX server accesses WebDAV without browser CORS restrictions. Saved passwords remain in the current DBX instance.",
syncEndpoint: "WebDAV URL",
syncUsername: "Username",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 695e397296..1ecd6f47ad 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -7640,6 +7640,36 @@ export default withEnglishFallback({
sqlShortcutsSelectLimitHint: "At run time, SQL is generated for the active connection dialect.",
syncWebDavTitle: "Sincronización WebDAV",
syncWebDavDescription: "Sube o restaura una instantánea de DBX, incluida la biblioteca SQL guardada, desde almacenamiento compatible con WebDAV.",
+ syncSelectionUploadTitle: "Seleccionar contenido de copia de seguridad",
+ syncSelectionRestoreTitle: "Seleccionar contenido para restaurar",
+ syncSelectionBackupNote: "Las credenciales sensibles y los datos de plugins solo se incluyen en instantáneas cifradas.",
+ syncSelectionRestoreNote: "El contenido local sin seleccionar se conservará.",
+ syncSelectionConnections: "Conexiones y SSH",
+ syncSelectionConnectionSecrets: "Contraseñas, contraseñas de SSH/frases de contraseña de claves y credenciales de conexión",
+ syncSelectionNoConnections: "No hay conexiones",
+ syncSelectionTunnels: "Perfiles de túnel compartidos",
+ syncSelectionTunnelSecrets: "Credenciales del túnel",
+ syncSelectionNoTunnels: "No hay perfiles de túnel",
+ syncSelectionSavedSql: "SQL guardado",
+ syncSelectionFolders: "Carpetas SQL",
+ syncSelectionFiles: "Archivos SQL",
+ syncSelectionPersonalSettings: "Configuración personal",
+ syncSelectionDesktopSettings: "Configuración del escritorio",
+ syncSelectionEditorSettings: "Configuración del editor",
+ syncSelectionEncrypted: "Información confidencial cifrada",
+ syncSelectionSyncCredentials: "Credenciales guardadas de servicios de sincronización",
+ syncSelectionAiConfigs: "Configuraciones de IA",
+ syncSelectionAiLocked: "Configuraciones remotas de IA (contenido cifrado bloqueado)",
+ syncSelectionPluginData: "Datos de configuración de plugins",
+ syncSelectionPluginLocked: "Configuración remota de plugins (contenido cifrado bloqueado)",
+ syncSelectionNoPluginData: "No hay datos de configuración de plugins",
+ syncSelectionNoEncrypted: "La instantánea remota no contiene información confidencial cifrada.",
+ syncSelectionWorkspace: "Distribución del espacio de trabajo",
+ syncSelectionSidebar: "Distribución de la barra lateral",
+ syncSelectionPinned: "Nodos fijados del árbol",
+ syncSelectionCancel: "Cancelar",
+ syncSelectionRestoreAction: "Restaurar selección",
+ syncSelectionUploadAction: "Respaldar selección",
syncWebDavWebDescription: "En modo Web, el servidor DBX accede a WebDAV sin las restricciones CORS del navegador. Las contraseñas guardadas permanecen en la instancia DBX actual.",
syncEndpoint: "URL WebDAV",
syncUsername: "Usuario",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index f1a2e4a4f0..d24230a3ea 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -7565,6 +7565,36 @@ export default withEnglishFallback({
sqlShortcutsSelectLimitHint: "At run time, SQL is generated for the active connection dialect.",
syncWebDavTitle: "Sincronizzazione WebDAV",
syncWebDavDescription: "Carica o ripristina uno snapshot di DBX, inclusa la libreria SQL salvata, da un servizio di archiviazione compatibile con WebDAV.",
+ syncSelectionUploadTitle: "Seleziona i contenuti da salvare",
+ syncSelectionRestoreTitle: "Seleziona i contenuti da ripristinare",
+ syncSelectionBackupNote: "Le credenziali sensibili e i dati dei plugin vengono inclusi solo negli snapshot crittografati.",
+ syncSelectionRestoreNote: "I contenuti locali non selezionati verranno mantenuti.",
+ syncSelectionConnections: "Connessioni e SSH",
+ syncSelectionConnectionSecrets: "Password, password SSH/passphrase delle chiavi e credenziali di connessione",
+ syncSelectionNoConnections: "Nessuna connessione",
+ syncSelectionTunnels: "Profili tunnel condivisi",
+ syncSelectionTunnelSecrets: "Credenziali del tunnel",
+ syncSelectionNoTunnels: "Nessun profilo tunnel",
+ syncSelectionSavedSql: "SQL salvati",
+ syncSelectionFolders: "Cartelle SQL",
+ syncSelectionFiles: "File SQL",
+ syncSelectionPersonalSettings: "Impostazioni personali",
+ syncSelectionDesktopSettings: "Impostazioni desktop",
+ syncSelectionEditorSettings: "Impostazioni dell'editor",
+ syncSelectionEncrypted: "Informazioni sensibili crittografate",
+ syncSelectionSyncCredentials: "Credenziali salvate dei servizi di sincronizzazione",
+ syncSelectionAiConfigs: "Configurazioni IA",
+ syncSelectionAiLocked: "Configurazioni IA remote (contenuto crittografato bloccato)",
+ syncSelectionPluginData: "Dati delle impostazioni dei plugin",
+ syncSelectionPluginLocked: "Impostazioni remote dei plugin (contenuto crittografato bloccato)",
+ syncSelectionNoPluginData: "Nessun dato delle impostazioni dei plugin",
+ syncSelectionNoEncrypted: "Lo snapshot remoto non contiene informazioni sensibili crittografate.",
+ syncSelectionWorkspace: "Layout dell'area di lavoro",
+ syncSelectionSidebar: "Layout della barra laterale",
+ syncSelectionPinned: "Nodi fissati nell'albero",
+ syncSelectionCancel: "Annulla",
+ syncSelectionRestoreAction: "Ripristina selezionati",
+ syncSelectionUploadAction: "Salva selezionati",
syncWebDavWebDescription: "In modalità Web, il server DBX accede a WebDAV senza le limitazioni CORS del browser. Le password salvate restano nell'istanza DBX corrente.",
syncEndpoint: "URL WebDAV",
syncUsername: "Nome utente",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 1f6b69bf4d..bf0ca73950 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -7581,6 +7581,36 @@ export default withEnglishFallback({
sqlShortcutsSelectLimitHint: "At run time, SQL is generated for the active connection dialect.",
syncWebDavTitle: "WebDAV同期",
syncWebDavDescription: "保存済みSQLライブラリを含むDBXスナップショットをWebDAV互換ストレージへアップロードまたは復元します。",
+ syncSelectionUploadTitle: "バックアップする内容を選択",
+ syncSelectionRestoreTitle: "復元する内容を選択",
+ syncSelectionBackupNote: "機密性の高い認証情報とプラグインデータは、暗号化されたスナップショットにのみ保存されます。",
+ syncSelectionRestoreNote: "選択されていないローカルデータは保持されます。",
+ syncSelectionConnections: "接続情報とSSH",
+ syncSelectionConnectionSecrets: "パスワード、SSHパスワード/鍵のパスフレーズ、接続認証情報",
+ syncSelectionNoConnections: "接続情報はありません",
+ syncSelectionTunnels: "共有トンネルプロファイル",
+ syncSelectionTunnelSecrets: "トンネル認証情報",
+ syncSelectionNoTunnels: "トンネルプロファイルはありません",
+ syncSelectionSavedSql: "保存済みSQL",
+ syncSelectionFolders: "SQLフォルダー",
+ syncSelectionFiles: "SQLファイル",
+ syncSelectionPersonalSettings: "個人設定",
+ syncSelectionDesktopSettings: "デスクトップ設定",
+ syncSelectionEditorSettings: "エディター設定",
+ syncSelectionEncrypted: "暗号化された機密情報",
+ syncSelectionSyncCredentials: "保存済みの同期サービス認証情報",
+ syncSelectionAiConfigs: "AI設定",
+ syncSelectionAiLocked: "リモートAI設定(暗号化された内容はロック中)",
+ syncSelectionPluginData: "プラグイン設定データ",
+ syncSelectionPluginLocked: "リモートプラグイン設定(暗号化された内容はロック中)",
+ syncSelectionNoPluginData: "プラグイン設定データはありません",
+ syncSelectionNoEncrypted: "リモートスナップショットに暗号化された機密情報はありません。",
+ syncSelectionWorkspace: "ワークスペースレイアウト",
+ syncSelectionSidebar: "サイドバーのレイアウト",
+ syncSelectionPinned: "ツリーの固定ノード",
+ syncSelectionCancel: "キャンセル",
+ syncSelectionRestoreAction: "選択した項目を復元",
+ syncSelectionUploadAction: "選択した項目をバックアップ",
syncWebDavWebDescription: "WebモードではDBXサーバーがWebDAVへ接続するため、ブラウザーのCORS制限を受けません。保存したパスワードは現在のDBXインスタンス内に保持されます。",
syncEndpoint: "WebDAV URL",
syncUsername: "ユーザー名",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 37f92e27de..415d35e2cb 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -7331,6 +7331,36 @@ export default withEnglishFallback({
sqlShortcutsSelectLimitHint: "At run time, SQL is generated for the active connection dialect.",
syncWebDavTitle: "WebDAV 동기화",
syncWebDavDescription: "WebDAV 호환 저장 서비스에서 DBX 스냅샷을 업로드하거나 복원합니다(저장된 SQL 라이브러리 항목 포함).",
+ syncSelectionUploadTitle: "백업할 콘텐츠 선택",
+ syncSelectionRestoreTitle: "복원할 콘텐츠 선택",
+ syncSelectionBackupNote: "민감한 자격 증명과 플러그인 데이터는 암호화된 스냅샷에만 저장됩니다.",
+ syncSelectionRestoreNote: "선택하지 않은 로컬 콘텐츠는 유지됩니다.",
+ syncSelectionConnections: "연결 정보 및 SSH",
+ syncSelectionConnectionSecrets: "비밀번호, SSH 비밀번호/키 암호 및 연결 자격 증명",
+ syncSelectionNoConnections: "연결 정보가 없습니다",
+ syncSelectionTunnels: "공유 터널 프로필",
+ syncSelectionTunnelSecrets: "터널 자격 증명",
+ syncSelectionNoTunnels: "터널 프로필이 없습니다",
+ syncSelectionSavedSql: "저장된 SQL",
+ syncSelectionFolders: "SQL 폴더",
+ syncSelectionFiles: "SQL 파일",
+ syncSelectionPersonalSettings: "개인 설정",
+ syncSelectionDesktopSettings: "데스크톱 설정",
+ syncSelectionEditorSettings: "편집기 설정",
+ syncSelectionEncrypted: "암호화된 민감 정보",
+ syncSelectionSyncCredentials: "저장된 동기화 서비스 자격 증명",
+ syncSelectionAiConfigs: "AI 구성",
+ syncSelectionAiLocked: "원격 AI 구성 (암호화된 콘텐츠 잠김)",
+ syncSelectionPluginData: "플러그인 설정 데이터",
+ syncSelectionPluginLocked: "원격 플러그인 설정 (암호화된 콘텐츠 잠김)",
+ syncSelectionNoPluginData: "플러그인 설정 데이터가 없습니다",
+ syncSelectionNoEncrypted: "원격 스냅샷에 암호화된 민감 정보가 없습니다.",
+ syncSelectionWorkspace: "작업 공간 레이아웃",
+ syncSelectionSidebar: "사이드바 레이아웃",
+ syncSelectionPinned: "고정된 트리 노드",
+ syncSelectionCancel: "취소",
+ syncSelectionRestoreAction: "선택 항목 복원",
+ syncSelectionUploadAction: "선택 항목 백업",
syncWebDavWebDescription: "Web 모드에서는 DBX 서버가 WebDAV에 연결하므로 브라우저 CORS 제한을 받지 않습니다. 저장된 비밀번호는 현재 DBX 인스턴스에 유지됩니다.",
syncEndpoint: "WebDAV URL",
syncUsername: "사용자 이름",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index c7d5187c1e..18bb44c0e3 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -7566,6 +7566,36 @@ export default withEnglishFallback({
sqlShortcutsSelectLimitHint: "At run time, SQL is generated for the active connection dialect.",
syncWebDavTitle: "Sincronização WebDAV",
syncWebDavDescription: "Envie ou restaure um snapshot do DBX, incluindo a biblioteca SQL salva, a partir de um serviço de armazenamento compatível com WebDAV.",
+ syncSelectionUploadTitle: "Selecionar conteúdo para backup",
+ syncSelectionRestoreTitle: "Selecionar conteúdo para restauração",
+ syncSelectionBackupNote: "Credenciais confidenciais e dados de plugins são incluídos somente em snapshots criptografados.",
+ syncSelectionRestoreNote: "O conteúdo local não selecionado será mantido.",
+ syncSelectionConnections: "Conexões e SSH",
+ syncSelectionConnectionSecrets: "Senhas, senhas SSH/frases secretas de chaves e credenciais de conexão",
+ syncSelectionNoConnections: "Nenhuma conexão",
+ syncSelectionTunnels: "Perfis de túnel compartilhados",
+ syncSelectionTunnelSecrets: "Credenciais do túnel",
+ syncSelectionNoTunnels: "Nenhum perfil de túnel",
+ syncSelectionSavedSql: "SQL salvo",
+ syncSelectionFolders: "Pastas SQL",
+ syncSelectionFiles: "Arquivos SQL",
+ syncSelectionPersonalSettings: "Configurações pessoais",
+ syncSelectionDesktopSettings: "Configurações da área de trabalho",
+ syncSelectionEditorSettings: "Configurações do editor",
+ syncSelectionEncrypted: "Informações confidenciais criptografadas",
+ syncSelectionSyncCredentials: "Credenciais salvas dos serviços de sincronização",
+ syncSelectionAiConfigs: "Configurações de IA",
+ syncSelectionAiLocked: "Configurações remotas de IA (conteúdo criptografado bloqueado)",
+ syncSelectionPluginData: "Dados de configurações de plugins",
+ syncSelectionPluginLocked: "Configurações remotas de plugins (conteúdo criptografado bloqueado)",
+ syncSelectionNoPluginData: "Nenhum dado de configurações de plugins",
+ syncSelectionNoEncrypted: "O snapshot remoto não contém informações confidenciais criptografadas.",
+ syncSelectionWorkspace: "Layout do espaço de trabalho",
+ syncSelectionSidebar: "Layout da barra lateral",
+ syncSelectionPinned: "Nós fixados na árvore",
+ syncSelectionCancel: "Cancelar",
+ syncSelectionRestoreAction: "Restaurar selecionados",
+ syncSelectionUploadAction: "Fazer backup dos selecionados",
syncWebDavWebDescription: "No modo Web, o servidor DBX acessa o WebDAV sem as restrições de CORS do navegador. As senhas salvas permanecem na instância DBX atual.",
syncEndpoint: "URL do WebDAV",
syncUsername: "Nome de usuário",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index eede3cb95f..e26b471415 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -8796,6 +8796,36 @@ export default withEnglishFallback({
sqlShortcutsSelectLimitHint: "Во время выполнения SQL формируется для диалекта активного подключения.",
syncWebDavTitle: "Синхронизация WebDAV",
syncWebDavDescription: "Загружать или восстанавливать снимок DBX, включая сохранённые записи библиотеки SQL, из совместимого с WebDAV хранилища.",
+ syncSelectionUploadTitle: "Выберите данные для резервного копирования",
+ syncSelectionRestoreTitle: "Выберите данные для восстановления",
+ syncSelectionBackupNote: "Конфиденциальные учетные данные и данные плагинов сохраняются только в зашифрованных снимках.",
+ syncSelectionRestoreNote: "Невыбранные локальные данные останутся без изменений.",
+ syncSelectionConnections: "Подключения и SSH",
+ syncSelectionConnectionSecrets: "Пароли, пароли SSH/парольные фразы ключей и учетные данные подключений",
+ syncSelectionNoConnections: "Нет подключений",
+ syncSelectionTunnels: "Общие профили туннелей",
+ syncSelectionTunnelSecrets: "Учетные данные туннеля",
+ syncSelectionNoTunnels: "Нет профилей туннелей",
+ syncSelectionSavedSql: "Сохраненные SQL-запросы",
+ syncSelectionFolders: "Папки SQL",
+ syncSelectionFiles: "Файлы SQL",
+ syncSelectionPersonalSettings: "Личные настройки",
+ syncSelectionDesktopSettings: "Настройки рабочего стола",
+ syncSelectionEditorSettings: "Настройки редактора",
+ syncSelectionEncrypted: "Зашифрованная конфиденциальная информация",
+ syncSelectionSyncCredentials: "Сохраненные учетные данные служб синхронизации",
+ syncSelectionAiConfigs: "Конфигурации ИИ",
+ syncSelectionAiLocked: "Удаленные конфигурации ИИ (зашифрованные данные заблокированы)",
+ syncSelectionPluginData: "Данные настроек плагинов",
+ syncSelectionPluginLocked: "Удаленные настройки плагинов (зашифрованные данные заблокированы)",
+ syncSelectionNoPluginData: "Нет данных настроек плагинов",
+ syncSelectionNoEncrypted: "В удаленном снимке нет зашифрованной конфиденциальной информации.",
+ syncSelectionWorkspace: "Макет рабочего пространства",
+ syncSelectionSidebar: "Макет боковой панели",
+ syncSelectionPinned: "Закрепленные узлы дерева",
+ syncSelectionCancel: "Отмена",
+ syncSelectionRestoreAction: "Восстановить выбранное",
+ syncSelectionUploadAction: "Сохранить выбранное",
syncWebDavWebDescription: "В веб-режиме сервер DBX обращается к WebDAV без ограничений CORS браузера. Сохранённые пароли остаются в текущем экземпляре DBX.",
syncEndpoint: "URL WebDAV",
syncUsername: "Имя пользователя",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 6066249950..8114bce0d7 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -8258,6 +8258,36 @@ export default withEnglishFallback({
sqlShortcutsSelectLimitHint: "执行时会按当前连接的数据库类型生成 SQL。",
syncWebDavTitle: "WebDAV 同步",
syncWebDavDescription: "将包含 SQL 库的 DBX 快照上传到兼容 WebDAV 的存储服务,或从远端恢复。",
+ syncSelectionUploadTitle: "选择备份内容",
+ syncSelectionRestoreTitle: "选择恢复内容",
+ syncSelectionBackupNote: "敏感凭据和插件数据只会写入加密快照。",
+ syncSelectionRestoreNote: "未勾选的本地内容会保留。",
+ syncSelectionConnections: "连接信息与 SSH",
+ syncSelectionConnectionSecrets: "密码、SSH 密码/密钥口令及连接凭据",
+ syncSelectionNoConnections: "无连接项目",
+ syncSelectionTunnels: "共享隧道配置",
+ syncSelectionTunnelSecrets: "隧道凭据",
+ syncSelectionNoTunnels: "无隧道配置",
+ syncSelectionSavedSql: "保存的 SQL",
+ syncSelectionFolders: "SQL 文件夹",
+ syncSelectionFiles: "SQL 文件",
+ syncSelectionPersonalSettings: "个人设置",
+ syncSelectionDesktopSettings: "桌面设置",
+ syncSelectionEditorSettings: "编辑器设置",
+ syncSelectionEncrypted: "加密敏感信息",
+ syncSelectionSyncCredentials: "已保存的同步服务凭据",
+ syncSelectionAiConfigs: "AI 配置",
+ syncSelectionAiLocked: "远端 AI 配置(加密目录未解锁)",
+ syncSelectionPluginData: "插件设置数据",
+ syncSelectionPluginLocked: "远端插件设置数据(加密目录未解锁)",
+ syncSelectionNoPluginData: "无插件设置数据",
+ syncSelectionNoEncrypted: "远端快照不含加密敏感信息。",
+ syncSelectionWorkspace: "工作区布局",
+ syncSelectionSidebar: "侧边栏布局",
+ syncSelectionPinned: "固定的树节点",
+ syncSelectionCancel: "取消",
+ syncSelectionRestoreAction: "恢复所选",
+ syncSelectionUploadAction: "备份所选",
syncWebDavWebDescription: "Web 模式下由 DBX 服务端访问 WebDAV,不受浏览器 CORS 限制;保存的密码会留在当前 DBX 实例中。",
syncEndpoint: "WebDAV 地址",
syncUsername: "用户名",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 1de5e10429..24a8d97fb6 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -6883,6 +6883,36 @@ export default withEnglishFallback({
sqlShortcutsSelectLimitHint: "執行時會依目前連線的資料庫類型產生 SQL。",
syncWebDavTitle: "WebDAV 同步",
syncWebDavDescription: "上傳包含 SQL 庫的 DBX 快照到相容 WebDAV 的儲存服務,或從該服務還原快照。",
+ syncSelectionUploadTitle: "選擇備份內容",
+ syncSelectionRestoreTitle: "選擇還原內容",
+ syncSelectionBackupNote: "敏感憑證與外掛資料只會寫入加密快照。",
+ syncSelectionRestoreNote: "未勾選的本機內容會保留。",
+ syncSelectionConnections: "連線資訊與 SSH",
+ syncSelectionConnectionSecrets: "密碼、SSH 密碼/金鑰密語及連線憑證",
+ syncSelectionNoConnections: "沒有連線項目",
+ syncSelectionTunnels: "共用通道設定",
+ syncSelectionTunnelSecrets: "通道憑證",
+ syncSelectionNoTunnels: "沒有通道設定",
+ syncSelectionSavedSql: "已儲存的 SQL",
+ syncSelectionFolders: "SQL 資料夾",
+ syncSelectionFiles: "SQL 檔案",
+ syncSelectionPersonalSettings: "個人設定",
+ syncSelectionDesktopSettings: "桌面設定",
+ syncSelectionEditorSettings: "編輯器設定",
+ syncSelectionEncrypted: "加密的敏感資訊",
+ syncSelectionSyncCredentials: "已儲存的同步服務憑證",
+ syncSelectionAiConfigs: "AI 設定",
+ syncSelectionAiLocked: "遠端 AI 設定(加密內容未解鎖)",
+ syncSelectionPluginData: "外掛設定資料",
+ syncSelectionPluginLocked: "遠端外掛設定(加密內容未解鎖)",
+ syncSelectionNoPluginData: "沒有外掛設定資料",
+ syncSelectionNoEncrypted: "遠端快照不含加密的敏感資訊。",
+ syncSelectionWorkspace: "工作區版面配置",
+ syncSelectionSidebar: "側邊欄版面配置",
+ syncSelectionPinned: "釘選的樹狀節點",
+ syncSelectionCancel: "取消",
+ syncSelectionRestoreAction: "還原所選項目",
+ syncSelectionUploadAction: "備份所選項目",
syncWebDavWebDescription: "Web 模式由 DBX 伺服器端存取 WebDAV,不受瀏覽器 CORS 限制;儲存的密碼會保留在目前 DBX 執行個體中。",
syncEndpoint: "WebDAV 地址",
syncUsername: "使用者名稱",
diff --git a/apps/desktop/src/lib/backend/__tests__/cloudSyncWebApi.spec.ts b/apps/desktop/src/lib/backend/__tests__/cloudSyncWebApi.spec.ts
index 54ddaeb34c..12c2366155 100644
--- a/apps/desktop/src/lib/backend/__tests__/cloudSyncWebApi.spec.ts
+++ b/apps/desktop/src/lib/backend/__tests__/cloudSyncWebApi.spec.ts
@@ -74,6 +74,49 @@ describe("WebDAV sync HTTP API", () => {
});
});
+ it("requests a selectable catalog and sends the selected snapshot items", async () => {
+ const fetchMock = stubFetch({ connections: [{ id: "db-1", label: "Production" }] });
+ const { cloudSyncLocalCatalog, webdavSyncInspect, webdavSyncUpload, webdavSyncDownload } = await import("@/lib/backend/http");
+ const editorSettings = { theme: "dark" };
+ const catalog = await cloudSyncLocalCatalog(editorSettings);
+ expect(catalog.connections).toEqual([{ id: "db-1", label: "Production" }]);
+ expect(lastCall(fetchMock)).toEqual({ url: "/api/cloud-sync/catalog/local", body: { editorSettings } });
+
+ await webdavSyncInspect(config, "sync-password");
+ expect(lastCall(fetchMock)).toEqual({
+ url: "/api/cloud-sync/webdav/inspect",
+ body: { config, secretsPassphrase: "sync-password" },
+ });
+
+ const selection = {
+ connections: ["db-1"],
+ connectionSecrets: ["db-1"],
+ tunnelProfiles: [],
+ tunnelSecrets: [],
+ savedSqlFolders: [],
+ savedSqlFiles: [],
+ desktopSettings: ["iconTheme"],
+ editorSettings: ["theme"],
+ aiConfigs: [],
+ pluginUiStorage: [],
+ sidebarLayout: false,
+ pinnedTreeNodeIds: false,
+ includeSecrets: true,
+ syncCredentials: false,
+ };
+ await webdavSyncUpload(config, editorSettings, "sync-password", true, selection);
+ expect(lastCall(fetchMock)).toEqual({
+ url: "/api/cloud-sync/webdav/upload",
+ body: { config, editorSettings, secretsPassphrase: "sync-password", includeSecrets: true, selection },
+ });
+
+ await webdavSyncDownload(config, "sync-password", true, selection);
+ expect(lastCall(fetchMock)).toEqual({
+ url: "/api/cloud-sync/webdav/download",
+ body: { config, secretsPassphrase: "sync-password", restoreSecrets: true, selection },
+ });
+ });
+
it("accepts the migration cleanup endpoint's empty 204 response", async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
vi.stubGlobal("fetch", fetchMock);
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index 2f0fc6354c..cb3fc9807b 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -420,6 +420,8 @@ export const forgetWebdavSavedPassword = forward("forgetWebdavSavedPassword");
export const webdavSyncSecretsStatus = forward("webdavSyncSecretsStatus");
export const saveWebdavSyncSecretsPreference = forward("saveWebdavSyncSecretsPreference");
export const forgetWebdavSyncSecretsPassphrase = forward("forgetWebdavSyncSecretsPassphrase");
+export const cloudSyncLocalCatalog = forward("cloudSyncLocalCatalog");
+export const webdavSyncInspect = forward("webdavSyncInspect");
export const webdavSyncUpload = forward("webdavSyncUpload");
export const webdavSyncDownload = forward("webdavSyncDownload");
export const snippetSyncTest = forward("snippetSyncTest");
@@ -427,6 +429,7 @@ export const snippetTokenStatus = forward("snippetTokenStatus");
export const saveSnippetSavedToken = forward("saveSnippetSavedToken");
export const forgetSnippetSavedToken = forward("forgetSnippetSavedToken");
export const snippetSyncSettings = forward("snippetSyncSettings");
+export const snippetSyncInspect = forward("snippetSyncInspect");
export const saveSnippetSyncId = forward("saveSnippetSyncId");
export const retrySnippetLegacyCleanup = forward("retrySnippetLegacyCleanup");
export const snippetSyncUpload = forward("snippetSyncUpload");
@@ -996,6 +999,10 @@ export type {
WebDavConfig,
WebDavPasswordStatus,
WebDavSyncSummary,
+ SyncCatalogItem,
+ PluginUiStorageItemRef,
+ SyncSelection,
+ SyncSnapshotCatalog,
WebDavDownloadResult,
SnippetProvider,
SnippetSyncConfig,
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index 584fd221f3..6adfcffc09 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -2,6 +2,7 @@ import type { MongoDumpFormat, MongoDumpSourceInput, MongoDumpCatalog, MongoRest
import type { MongoRestoreUpload, MongoSourceReadOptions } from "./mongodbDumpTypes";
import type { UserSkillRootSettings, UserSkillsListResult, UserSkillsReadResult } from "@/types/userSkills";
import type { DatabaseBackupCommand, DatabaseBackupBackgroundStatus } from "@/lib/backup/backgroundDatabaseBackup";
+import type { PluginUiStorageItemRef, SyncCatalogItem, SyncSelection, SyncSnapshotCatalog } from "@/lib/backend/tauri";
export function databaseBackupCommand<T = unknown>(command: DatabaseBackupCommand): Promise<T> {
return post("/api/database-backups", command);
@@ -2443,6 +2444,8 @@ export interface WebDavSyncSummary {
appVersion?: string;
}
+export type { PluginUiStorageItemRef, SyncCatalogItem, SyncSelection, SyncSnapshotCatalog };
+
export interface WebDavDownloadResult {
summary: WebDavSyncSummary;
editorSettings?: unknown;
@@ -2528,17 +2531,26 @@ export async function forgetWebdavSyncSecretsPassphrase(): Promise<void> {
return post("/api/cloud-sync/webdav/forget-sync-secrets-passphrase", {});
}
-export async function webdavSyncUpload(config: WebDavConfig, editorSettings?: unknown, secretsPassphrase?: string, includeSecrets = false): Promise<WebDavSyncSummary> {
+export async function cloudSyncLocalCatalog(editorSettings?: unknown): Promise<SyncSnapshotCatalog> {
+ return post("/api/cloud-sync/catalog/local", { editorSettings });
+}
+
+export async function webdavSyncInspect(config: WebDavConfig, secretsPassphrase?: string): Promise<SyncSnapshotCatalog> {
+ return post("/api/cloud-sync/webdav/inspect", { config, secretsPassphrase });
+}
+
+export async function webdavSyncUpload(config: WebDavConfig, editorSettings?: unknown, secretsPassphrase?: string, includeSecrets = false, selection?: SyncSelection): Promise<WebDavSyncSummary> {
return post("/api/cloud-sync/webdav/upload", {
config,
editorSettings,
secretsPassphrase,
includeSecrets,
+ selection,
});
}
-export async function webdavSyncDownload(config: WebDavConfig, secretsPassphrase?: string, restoreSecrets = true): Promise<WebDavDownloadResult> {
- return post("/api/cloud-sync/webdav/download", { config, secretsPassphrase, restoreSecrets });
+export async function webdavSyncDownload(config: WebDavConfig, secretsPassphrase?: string, restoreSecrets = true, selection?: SyncSelection): Promise<WebDavDownloadResult> {
+ return post("/api/cloud-sync/webdav/download", { config, secretsPassphrase, restoreSecrets, selection });
}
export async function snippetSyncTest(config: SnippetSyncConfig): Promise<void> {
@@ -2569,22 +2581,28 @@ export async function retrySnippetLegacyCleanup(config: SnippetSyncConfig): Prom
return post("/api/cloud-sync/snippet/retry-legacy-cleanup", { config });
}
-export async function snippetSyncUpload(config: SnippetSyncConfig, editorSettings?: unknown, snippetPassphrase?: string, includeSecrets = false, secretsPassphrase?: string): Promise<SnippetSyncSummary> {
+export async function snippetSyncInspect(config: SnippetSyncConfig, snippetPassphrase?: string, secretsPassphrase?: string): Promise<SyncSnapshotCatalog> {
+ return post("/api/cloud-sync/snippet/inspect", { config, snippetPassphrase, secretsPassphrase });
+}
+
+export async function snippetSyncUpload(config: SnippetSyncConfig, editorSettings?: unknown, snippetPassphrase?: string, includeSecrets = false, secretsPassphrase?: string, selection?: SyncSelection): Promise<SnippetSyncSummary> {
return post("/api/cloud-sync/snippet/upload", {
config,
editorSettings,
snippetPassphrase,
includeSecrets,
secretsPassphrase,
+ selection,
});
}
-export async function snippetSyncDownload(config: SnippetSyncConfig, snippetPassphrase?: string, restoreSecrets = false, secretsPassphrase?: string): Promise<SnippetDownloadResult> {
+export async function snippetSyncDownload(config: SnippetSyncConfig, snippetPassphrase?: string, restoreSecrets = false, secretsPassphrase?: string, selection?: SyncSelection): Promise<SnippetDownloadResult> {
return post("/api/cloud-sync/snippet/download", {
config,
snippetPassphrase,
restoreSecrets,
secretsPassphrase,
+ selection,
});
}
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index 6d51163bbb..0f1f243fab 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -389,6 +389,55 @@ export interface WebDavSyncSummary {
appVersion?: string;
}
+export interface SyncCatalogItem {
+ id: string;
+ label: string;
+}
+
+export interface PluginUiStorageItemRef {
+ pluginId: string;
+ key: string;
+ pluginName?: string;
+}
+
+export interface SyncSelection {
+ connections?: string[];
+ connectionSecrets?: string[];
+ tunnelProfiles?: string[];
+ tunnelSecrets?: string[];
+ savedSqlFolders?: string[];
+ savedSqlFiles?: string[];
+ desktopSettings?: string[];
+ editorSettings?: string[];
+ aiConfigs?: string[];
+ pluginUiStorage?: PluginUiStorageItemRef[];
+ sidebarLayout?: boolean;
+ pinnedTreeNodeIds?: boolean;
+ includeSecrets: boolean;
+ syncCredentials: boolean;
+}
+
+export interface SyncSnapshotCatalog {
+ exportedAt: string;
+ appVersion: string;
+ hasEncryptedSecrets: boolean;
+ connections: SyncCatalogItem[];
+ connectionSecrets: string[];
+ tunnelProfiles: SyncCatalogItem[];
+ tunnelSecrets: string[];
+ savedSqlFolders: SyncCatalogItem[];
+ savedSqlFiles: SyncCatalogItem[];
+ desktopSettings: SyncCatalogItem[];
+ editorSettings: SyncCatalogItem[];
+ aiConfigs: SyncCatalogItem[];
+ aiConfigsLocked: boolean;
+ pluginUiStorage: PluginUiStorageItemRef[];
+ pluginUiStorageLocked: boolean;
+ hasSidebarLayout: boolean;
+ hasPinnedTreeNodeIds: boolean;
+ selection?: SyncSelection;
+}
+
export interface WebDavDownloadResult {
summary: WebDavSyncSummary;
editorSettings?: unknown;
@@ -1061,17 +1110,26 @@ export async function forgetWebdavSyncSecretsPassphrase(): Promise<void> {
return invoke("forget_webdav_sync_secrets_passphrase");
}
-export async function webdavSyncUpload(config: WebDavConfig, editorSettings?: unknown, secretsPassphrase?: string, includeSecrets = false): Promise<WebDavSyncSummary> {
+export async function cloudSyncLocalCatalog(editorSettings?: unknown): Promise<SyncSnapshotCatalog> {
+ return invoke("cloud_sync_local_catalog", { editorSettings });
+}
+
+export async function webdavSyncInspect(config: WebDavConfig, secretsPassphrase?: string): Promise<SyncSnapshotCatalog> {
+ return invoke("webdav_sync_inspect", { config, secretsPassphrase });
+}
+
+export async function webdavSyncUpload(config: WebDavConfig, editorSettings?: unknown, secretsPassphrase?: string, includeSecrets = false, selection?: SyncSelection): Promise<WebDavSyncSummary> {
return invoke("webdav_sync_upload", {
config,
editorSettings,
secretsPassphrase,
includeSecrets,
+ selection,
});
}
-export async function webdavSyncDownload(config: WebDavConfig, secretsPassphrase?: string, restoreSecrets = true): Promise<WebDavDownloadResult> {
- return invoke("webdav_sync_download", { config, secretsPassphrase, restoreSecrets });
+export async function webdavSyncDownload(config: WebDavConfig, secretsPassphrase?: string, restoreSecrets = true, selection?: SyncSelection): Promise<WebDavDownloadResult> {
+ return invoke("webdav_sync_download", { config, secretsPassphrase, restoreSecrets, selection });
}
export async function snippetSyncTest(config: SnippetSyncConfig): Promise<void> {
@@ -1102,18 +1160,23 @@ export async function retrySnippetLegacyCleanup(config: SnippetSyncConfig): Prom
return invoke("retry_snippet_legacy_cleanup", { config });
}
-export async function snippetSyncUpload(config: SnippetSyncConfig, editorSettings?: unknown, snippetPassphrase?: string, includeSecrets = false, secretsPassphrase?: string): Promise<SnippetSyncSummary> {
+export async function snippetSyncInspect(config: SnippetSyncConfig, snippetPassphrase?: string, secretsPassphrase?: string): Promise<SyncSnapshotCatalog> {
+ return invoke("snippet_sync_inspect", { config, snippetPassphrase, secretsPassphrase });
+}
+
+export async function snippetSyncUpload(config: SnippetSyncConfig, editorSettings?: unknown, snippetPassphrase?: string, includeSecrets = false, secretsPassphrase?: string, selection?: SyncSelection): Promise<SnippetSyncSummary> {
return invoke("snippet_sync_upload", {
config,
editorSettings,
snippetPassphrase,
includeSecrets,
secretsPassphrase,
+ selection,
});
}
-export async function snippetSyncDownload(config: SnippetSyncConfig, snippetPassphrase?: string, restoreSecrets = false, secretsPassphrase?: string): Promise<SnippetDownloadResult> {
- return invoke("snippet_sync_download", { config, snippetPassphrase, restoreSecrets, secretsPassphrase });
+export async function snippetSyncDownload(config: SnippetSyncConfig, snippetPassphrase?: string, restoreSecrets = false, secretsPassphrase?: string, selection?: SyncSelection): Promise<SnippetDownloadResult> {
+ return invoke("snippet_sync_download", { config, snippetPassphrase, restoreSecrets, secretsPassphrase, selection });
}
export async function loadPinnedTreeNodeIds(): Promise<string[]> {
diff --git a/apps/desktop/src/lib/webdav/webdavAutoUploadConfig.ts b/apps/desktop/src/lib/webdav/webdavAutoUploadConfig.ts
index 81ab200899..6aed9ab941 100644
--- a/apps/desktop/src/lib/webdav/webdavAutoUploadConfig.ts
+++ b/apps/desktop/src/lib/webdav/webdavAutoUploadConfig.ts
@@ -1,7 +1,8 @@
-import type { WebDavConfig } from "@/lib/backend/api";
+import type { SyncSelection, WebDavConfig } from "@/lib/backend/api";
import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";
-export const WEB_DAV_AUTO_UPLOAD_STORAGE_KEYS = ["dbx-webdav-endpoint", "dbx-webdav-username", "dbx-webdav-remote-path", "dbx-webdav-auto-upload-enabled", "dbx-webdav-auto-upload-interval-minutes"] as const;
+export const WEB_DAV_BACKUP_SELECTION_STORAGE_KEY = "dbx-webdav-backup-selection";
+export const WEB_DAV_AUTO_UPLOAD_STORAGE_KEYS = ["dbx-webdav-endpoint", "dbx-webdav-username", "dbx-webdav-remote-path", "dbx-webdav-auto-upload-enabled", "dbx-webdav-auto-upload-interval-minutes", WEB_DAV_BACKUP_SELECTION_STORAGE_KEY] as const;
export const DEFAULT_WEB_DAV_REMOTE_PATH = "DBX/sync/snapshot.json";
export const DEFAULT_WEB_DAV_AUTO_UPLOAD_INTERVAL_MINUTES = 30;
@@ -43,3 +44,20 @@ export function writeWebDavAutoUploadFields(config: WebDavConfig, autoUpload: {
safeLocalStorageSet("dbx-webdav-auto-upload-enabled", String(autoUpload.enabled));
safeLocalStorageSet("dbx-webdav-auto-upload-interval-minutes", String(normalizedWebDavAutoUploadInterval(autoUpload.intervalMinutes)));
}
+
+export function readWebDavBackupSelection(): SyncSelection | undefined {
+ const serialized = safeLocalStorageGet(WEB_DAV_BACKUP_SELECTION_STORAGE_KEY);
+ if (!serialized) return undefined;
+ try {
+ const selection = JSON.parse(serialized) as SyncSelection;
+ if (typeof selection !== "object" || selection === null || typeof selection.includeSecrets !== "boolean") return undefined;
+ return selection;
+ } catch {
+ return undefined;
+ }
+}
+
+export function writeWebDavBackupSelection(selection: SyncSelection) {
+ safeLocalStorageSet(WEB_DAV_BACKUP_SELECTION_STORAGE_KEY, JSON.stringify(selection));
+ if (typeof window !== "undefined") window.dispatchEvent(new Event("dbx:webdav-auto-upload-config-changed"));
+}
diff --git a/crates/dbx-core/src/persistence/cloud_sync.rs b/crates/dbx-core/src/persistence/cloud_sync.rs
index b3e3ea54fa..993289ba11 100644
--- a/crates/dbx-core/src/persistence/cloud_sync.rs
+++ b/crates/dbx-core/src/persistence/cloud_sync.rs
@@ -8,7 +8,8 @@ use chrono::Utc;
use reqwest::{header, Client, Method, StatusCode, Url};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
+use std::fs;
use std::net::{IpAddr, Ipv4Addr};
use crate::ai::AiConfigItem;
@@ -21,13 +22,13 @@ use crate::connection_secrets::{
use crate::models::connection::{ConnectionConfig, DatabaseType, TransportLayerConfig};
use crate::saved_sql::SavedSqlLibrary;
use crate::storage::{
- DesktopSettings, SnippetPendingCleanup, Storage, SyncImportCredential, SyncImportPlan, SyncImportSecret,
+ clear_ai_config_device_paths, DesktopSettings, SnippetPendingCleanup, Storage, SyncImportCredential,
+ SyncImportPlan, SyncImportSecret,
};
-/// Version 2 introduces an explicit, versioned secrets transport payload. We
-/// still accept version 1 snapshots on import so upgrading does not strand
-/// existing devices.
-const SNAPSHOT_SCHEMA_VERSION: u32 = 2;
+/// Version 2 introduced encrypted secret payloads; version 3 adds selective
+/// backup metadata. Older snapshots remain importable for compatibility.
+const SNAPSHOT_SCHEMA_VERSION: u32 = 3;
const LEGACY_SNAPSHOT_SCHEMA_VERSION: u32 = 1;
const SENSITIVE_PAYLOAD_VERSION: u32 = 2;
const SENSITIVE_PAYLOAD_TYPE: &str = "dbx-sync-secrets";
@@ -35,6 +36,7 @@ const ENCRYPTED_SNIPPET_SNAPSHOT_FORMAT: &str = "dbx-encrypted-sync-snapshot";
const ENCRYPTED_SNIPPET_SNAPSHOT_VERSION: u32 = 1;
const DEFAULT_REMOTE_PATH: &str = "DBX/sync/snapshot.json";
const DEFAULT_SNIPPET_FILE_NAME: &str = "dbx-sync.json";
+const LEGACY_AI_CONFIG_SELECTION_ID: &str = "__legacy_ai_config__";
const GITHUB_API_BASE: &str = "https://api.github.com";
const GITEE_API_BASE: &str = "https://gitee.com/api/v5";
const GITLAB_DEFAULT_INSTANCE: &str = "https://gitlab.com";
@@ -60,6 +62,26 @@ const SECRET_KEYS: &[&str] = &[
];
const SSH_TUNNEL_SECRET_PREFIX: &str = "ssh_tunnels.";
const TRANSPORT_LAYER_SECRET_PREFIX: &str = "transport_layers.";
+const DESKTOP_DEVICE_LOCAL_SETTINGS: &[&str] = &[
+ "saved_sql_sync_dir",
+ "driver_store_dir",
+ "plugin_store_dir",
+ "agent_store_dir",
+ "custom_ai_skill_root_enabled",
+ "custom_ai_skill_root",
+];
+const NON_SYNCABLE_DESKTOP_SETTINGS: &[&str] = &["debug_logging_enabled"];
+const NON_SYNCABLE_EDITOR_SETTINGS: &[&str] = &[
+ "updateNotificationsEnabled",
+ "autoDownloadUpdates",
+ "autoUpdateApp",
+ "autoUpdateDrivers",
+ "autoUpdateJdbc",
+ "autoUpdateMcp",
+ "autoUpdatePlugins",
+ "updateDownloadSource",
+ "ignoredUpdateVersion",
+];
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -144,6 +166,299 @@ pub struct SyncSnapshot {
pub desktop_settings: DesktopSettings,
pub editor_settings: Option<serde_json::Value>,
pub encrypted_secrets: Option<EncryptedSecretsBlob>,
+ /// Selection captured at export time. `None` means a legacy snapshot that
+ /// predates selective backup and therefore contains the complete dataset.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub selection: Option<SyncSelection>,
+}
+
+/// `None` for an item list means include the whole category. An explicit list
+/// can be empty, which is how a user chooses to omit a category.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SyncSelection {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub connections: Option<Vec<String>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub connection_secrets: Option<Vec<String>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tunnel_profiles: Option<Vec<String>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tunnel_secrets: Option<Vec<String>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub saved_sql_folders: Option<Vec<String>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub saved_sql_files: Option<Vec<String>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub desktop_settings: Option<Vec<String>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub editor_settings: Option<Vec<String>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ai_configs: Option<Vec<String>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[serde(skip_serializing)]
+ pub plugin_ui_storage: Option<Vec<PluginUiStorageItemRef>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub sidebar_layout: Option<bool>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub pinned_tree_node_ids: Option<bool>,
+ /// Sensitive values are never exported unless the user explicitly opts in.
+ #[serde(default)]
+ pub include_secrets: bool,
+ /// Saved WebDAV/snippet account passwords are a separate sensitive item.
+ #[serde(default = "default_selected")]
+ pub sync_credentials: bool,
+}
+
+fn default_selected() -> bool {
+ true
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginUiStorageItemRef {
+ pub plugin_id: String,
+ pub key: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub plugin_name: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginUiStorageEntry {
+ pub plugin_id: String,
+ pub key: String,
+ pub value: serde_json::Value,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SyncCatalogItem {
+ pub id: String,
+ pub label: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SyncSnapshotCatalog {
+ pub exported_at: String,
+ pub app_version: String,
+ pub has_encrypted_secrets: bool,
+ pub connections: Vec<SyncCatalogItem>,
+ pub connection_secrets: Vec<String>,
+ pub tunnel_profiles: Vec<SyncCatalogItem>,
+ pub tunnel_secrets: Vec<String>,
+ pub saved_sql_folders: Vec<SyncCatalogItem>,
+ pub saved_sql_files: Vec<SyncCatalogItem>,
+ pub desktop_settings: Vec<SyncCatalogItem>,
+ pub editor_settings: Vec<SyncCatalogItem>,
+ pub ai_configs: Vec<SyncCatalogItem>,
+ pub ai_configs_locked: bool,
+ pub plugin_ui_storage: Vec<PluginUiStorageItemRef>,
+ pub plugin_ui_storage_locked: bool,
+ pub has_sidebar_layout: bool,
+ pub has_pinned_tree_node_ids: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub selection: Option<SyncSelection>,
+}
+
+pub fn describe_sync_snapshot(
+ snapshot: &SyncSnapshot,
+ secrets_passphrase: Option<&str>,
+) -> Result<SyncSnapshotCatalog, String> {
+ let mut ai_configs = snapshot
+ .selection
+ .as_ref()
+ .and_then(|selection| selection.ai_configs.as_ref())
+ .map(|ids| ids.iter().map(|id| SyncCatalogItem { id: id.clone(), label: id.clone() }).collect())
+ .unwrap_or_default();
+ let mut ai_configs_locked = snapshot.encrypted_secrets.is_some()
+ && normalized_passphrase(secrets_passphrase).is_none()
+ && snapshot.selection.as_ref().is_none_or(|selection| selection.ai_configs.is_none());
+ let mut plugin_ui_storage = Vec::new();
+ let mut plugin_ui_storage_locked =
+ snapshot.encrypted_secrets.is_some() && normalized_passphrase(secrets_passphrase).is_none();
+ let mut connection_secrets = snapshot
+ .selection
+ .as_ref()
+ .and_then(|selection| selection.connection_secrets.clone())
+ .unwrap_or_else(|| snapshot.connections.iter().map(|config| config.id.clone()).collect());
+ let mut tunnel_secrets =
+ snapshot.selection.as_ref().and_then(|selection| selection.tunnel_secrets.clone()).unwrap_or_else(|| {
+ snapshot
+ .tunnel_profiles
+ .as_deref()
+ .unwrap_or_default()
+ .iter()
+ .map(|profile| profile.id().to_string())
+ .collect()
+ });
+ if let (Some(blob), Some(passphrase)) = (&snapshot.encrypted_secrets, normalized_passphrase(secrets_passphrase)) {
+ let payload = decrypt_sensitive_payload(blob, passphrase)?;
+ ai_configs_locked = false;
+ plugin_ui_storage_locked = false;
+ connection_secrets = payload
+ .connection_secrets
+ .iter()
+ .map(|secret| secret.connection_id.clone())
+ .collect::<HashSet<_>>()
+ .into_iter()
+ .collect();
+ tunnel_secrets = payload
+ .tunnel_profiles
+ .as_deref()
+ .unwrap_or_default()
+ .iter()
+ .map(|profile| profile.id().to_string())
+ .collect();
+ ai_configs = match payload.ai_configs {
+ Some(configs) => {
+ configs.into_iter().map(|config| SyncCatalogItem { id: config.id, label: config.name }).collect()
+ }
+ None => payload
+ .ai_config
+ .map(|config| {
+ vec![SyncCatalogItem {
+ id: LEGACY_AI_CONFIG_SELECTION_ID.to_string(),
+ label: config.provider.as_str().to_string(),
+ }]
+ })
+ .unwrap_or_default(),
+ };
+ plugin_ui_storage = payload
+ .plugin_ui_storage
+ .unwrap_or_default()
+ .into_iter()
+ .map(|entry| PluginUiStorageItemRef { plugin_id: entry.plugin_id, key: entry.key, plugin_name: None })
+ .collect();
+ }
+ let settings = serde_json::to_value(&snapshot.desktop_settings).map_err(|error| error.to_string())?;
+ let mut desktop_settings = settings
+ .as_object()
+ .into_iter()
+ .flat_map(|object| object.keys())
+ .filter(|key| {
+ !DESKTOP_DEVICE_LOCAL_SETTINGS.contains(&key.as_str())
+ && !NON_SYNCABLE_DESKTOP_SETTINGS.contains(&key.as_str())
+ })
+ .map(|key| SyncCatalogItem { id: key.clone(), label: key.clone() })
+ .collect::<Vec<_>>();
+ let mut editor_settings = snapshot
+ .editor_settings
+ .as_ref()
+ .and_then(serde_json::Value::as_object)
+ .into_iter()
+ .flat_map(|object| object.keys())
+ .filter(|key| !NON_SYNCABLE_EDITOR_SETTINGS.contains(&key.as_str()))
+ .map(|key| SyncCatalogItem { id: key.clone(), label: key.clone() })
+ .collect::<Vec<_>>();
+ if let Some(selection) = &snapshot.selection {
+ if let Some(keys) = &selection.desktop_settings {
+ desktop_settings.retain(|item| keys.contains(&item.id));
+ }
+ if let Some(keys) = &selection.editor_settings {
+ editor_settings.retain(|item| keys.contains(&item.id));
+ }
+ }
+ Ok(SyncSnapshotCatalog {
+ exported_at: snapshot.exported_at.clone(),
+ app_version: snapshot.app_version.clone(),
+ has_encrypted_secrets: snapshot.encrypted_secrets.is_some(),
+ connections: snapshot
+ .connections
+ .iter()
+ .map(|config| SyncCatalogItem { id: config.id.clone(), label: config.name.clone() })
+ .collect(),
+ connection_secrets,
+ tunnel_profiles: snapshot
+ .tunnel_profiles
+ .as_deref()
+ .unwrap_or_default()
+ .iter()
+ .map(|profile| {
+ let label = match profile {
+ TransportLayerConfig::Ssh(config) => &config.name,
+ TransportLayerConfig::Proxy(config) => &config.name,
+ TransportLayerConfig::HttpTunnel(config) => &config.name,
+ };
+ SyncCatalogItem { id: profile.id().to_string(), label: label.clone() }
+ })
+ .collect(),
+ tunnel_secrets,
+ saved_sql_folders: snapshot
+ .saved_sql
+ .folders
+ .iter()
+ .map(|folder| SyncCatalogItem { id: folder.id.clone(), label: folder.name.clone() })
+ .collect(),
+ saved_sql_files: snapshot
+ .saved_sql
+ .files
+ .iter()
+ .map(|file| SyncCatalogItem { id: file.id.clone(), label: file.name.clone() })
+ .collect(),
+ desktop_settings,
+ editor_settings,
+ ai_configs,
+ ai_configs_locked,
+ plugin_ui_storage,
+ plugin_ui_storage_locked,
+ has_sidebar_layout: snapshot.sidebar_layout.is_some(),
+ has_pinned_tree_node_ids: snapshot
+ .selection
+ .as_ref()
+ .and_then(|selection| selection.pinned_tree_node_ids)
+ .unwrap_or(!snapshot.pinned_tree_node_ids.is_empty()),
+ selection: snapshot.selection.clone().map(|mut selection| {
+ if let Some(keys) = selection.desktop_settings.as_mut() {
+ keys.retain(|key| !NON_SYNCABLE_DESKTOP_SETTINGS.contains(&key.as_str()));
+ }
+ if let Some(keys) = selection.editor_settings.as_mut() {
+ keys.retain(|key| !NON_SYNCABLE_EDITOR_SETTINGS.contains(&key.as_str()));
+ }
+ selection
+ }),
+ })
+}
+
+pub async fn describe_local_sync_state(
+ storage: &Storage,
+ editor_settings: Option<serde_json::Value>,
+ plugin_registry: Option<&crate::plugins::PluginRegistry>,
+) -> Result<SyncSnapshotCatalog, String> {
+ let snapshot = build_sync_snapshot_with_selection(
+ storage,
+ env!("CARGO_PKG_VERSION"),
+ editor_settings,
+ SyncExportOptions::default(),
+ None,
+ None,
+ )
+ .await?;
+ let mut catalog = describe_sync_snapshot(&snapshot, None)?;
+ catalog.connection_secrets = catalog.connections.iter().map(|item| item.id.clone()).collect();
+ catalog.tunnel_secrets = catalog.tunnel_profiles.iter().map(|item| item.id.clone()).collect();
+ catalog.ai_configs = storage
+ .load_ai_configs()
+ .await?
+ .into_iter()
+ .map(|config| SyncCatalogItem { id: config.id, label: config.name })
+ .collect();
+ catalog.ai_configs_locked = false;
+ catalog.plugin_ui_storage = plugin_registry
+ .map(load_plugin_ui_storage)
+ .transpose()?
+ .unwrap_or_default()
+ .into_iter()
+ .map(|entry| PluginUiStorageItemRef {
+ plugin_id: entry.plugin_id.clone(),
+ key: entry.key,
+ plugin_name: plugin_registry_name(plugin_registry, &entry.plugin_id),
+ })
+ .collect();
+ catalog.plugin_ui_storage_locked = false;
+ catalog.has_encrypted_secrets = false;
+ Ok(catalog)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -222,6 +537,10 @@ pub struct SensitiveSyncPayload {
/// Full tunnel profiles including their secrets.
#[serde(default)]
pub tunnel_profiles: Option<Vec<TransportLayerConfig>>,
+ /// Plugin UI data is always protected by the sync passphrase because
+ /// plugins may store credentials alongside ordinary preferences.
+ #[serde(default)]
+ pub plugin_ui_storage: Option<Vec<PluginUiStorageEntry>>,
}
fn default_plugin_secrets_included() -> bool {
@@ -265,6 +584,159 @@ pub struct SyncExportOptions<'a> {
pub include_plugin_secrets: bool,
}
+fn select_by_id<T: Clone>(items: &[T], selected: Option<&Vec<String>>, id: impl Fn(&T) -> String) -> Vec<T> {
+ let Some(selected) = selected else { return items.to_vec() };
+ let selected = selected.iter().map(String::as_str).collect::<HashSet<_>>();
+ items.iter().filter(|item| selected.contains(id(item).as_str())).cloned().collect()
+}
+
+fn select_saved_sql_library(
+ library: &SavedSqlLibrary,
+ selected_folders: Option<&Vec<String>>,
+ selected_files: Option<&Vec<String>>,
+) -> SavedSqlLibrary {
+ let mut folders = select_by_id(&library.folders, selected_folders, |folder| folder.id.clone());
+ let files = select_by_id(&library.files, selected_files, |file| file.id.clone());
+ let mut folder_ids = folders.iter().map(|folder| folder.id.clone()).collect::<HashSet<_>>();
+ let folder_by_id = library.folders.iter().map(|folder| (folder.id.as_str(), folder)).collect::<HashMap<_, _>>();
+ let required_parents = folders
+ .iter()
+ .filter_map(|folder| folder.parent_folder_id.clone())
+ .chain(files.iter().filter_map(|file| file.folder_id.clone()))
+ .collect::<Vec<_>>();
+ for mut parent in required_parents.into_iter().map(Some) {
+ while let Some(parent_id) = parent {
+ if !folder_ids.insert(parent_id.clone()) {
+ break;
+ }
+ let Some(folder) = folder_by_id.get(parent_id.as_str()) else { break };
+ folders.push((*folder).clone());
+ parent = folder.parent_folder_id.clone();
+ }
+ }
+ SavedSqlLibrary { folders, files }
+}
+
+fn plugin_registry_name(registry: Option<&crate::plugins::PluginRegistry>, plugin_id: &str) -> Option<String> {
+ registry?
+ .list_installed()
+ .ok()?
+ .into_iter()
+ .find(|plugin| plugin.manifest.id == plugin_id)
+ .map(|plugin| plugin.manifest.name)
+}
+
+fn valid_plugin_storage_id(value: &str) -> bool {
+ let mut chars = value.chars();
+ chars.next().is_some_and(|first| first.is_ascii_lowercase() || first.is_ascii_digit())
+ && value.len() <= 128
+ && chars.all(|character| {
+ character.is_ascii_lowercase() || character.is_ascii_digit() || matches!(character, '.' | '_' | '-')
+ })
+}
+
+fn valid_plugin_storage_key(value: &str) -> bool {
+ !value.is_empty() && value.chars().count() <= 256 && !value.chars().any(char::is_control)
+}
+
+fn load_plugin_ui_storage(registry: &crate::plugins::PluginRegistry) -> Result<Vec<PluginUiStorageEntry>, String> {
+ let plugins = registry.list_installed()?;
+ let mut entries = Vec::new();
+ for plugin in plugins {
+ let plugin_id = plugin.manifest.id;
+ if !valid_plugin_storage_id(&plugin_id) {
+ continue;
+ }
+ let path = registry.plugin_data_dir(&plugin_id).join("ui-storage.json");
+ let metadata = match fs::symlink_metadata(&path) {
+ Ok(metadata) if metadata.file_type().is_file() => metadata,
+ Ok(_) => return Err(format!("plugin UI storage is not a regular file: {}", path.display())),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
+ Err(error) => return Err(format!("cannot inspect plugin UI storage: {error}")),
+ };
+ if metadata.len() > 1024 * 1024 {
+ return Err(format!("plugin UI storage exceeds 1048576 bytes: {}", path.display()));
+ }
+ let contents = fs::read(&path).map_err(|error| format!("cannot read plugin UI storage: {error}"))?;
+ let map = serde_json::from_slice::<serde_json::Map<String, serde_json::Value>>(&contents)
+ .map_err(|error| format!("cannot parse plugin UI storage {}: {error}", path.display()))?;
+ for (key, value) in map {
+ let encoded = serde_json::to_vec(&value).map_err(|error| error.to_string())?;
+ if !valid_plugin_storage_key(&key) || encoded.len() > 256 * 1024 {
+ return Err(format!("plugin UI storage contains an invalid or oversized entry: {plugin_id}/{key}"));
+ }
+ entries.push(PluginUiStorageEntry { plugin_id: plugin_id.clone(), key, value });
+ }
+ }
+ Ok(entries)
+}
+
+fn select_plugin_ui_storage(
+ entries: &[PluginUiStorageEntry],
+ selected: Option<&Vec<PluginUiStorageItemRef>>,
+) -> Vec<PluginUiStorageEntry> {
+ let Some(selected) = selected else { return entries.to_vec() };
+ let selected = selected.iter().map(|entry| (entry.plugin_id.as_str(), entry.key.as_str())).collect::<HashSet<_>>();
+ entries.iter().filter(|entry| selected.contains(&(entry.plugin_id.as_str(), entry.key.as_str()))).cloned().collect()
+}
+
+fn prepare_plugin_ui_storage_restore(
+ registry: &crate::plugins::PluginRegistry,
+ entries: &[PluginUiStorageEntry],
+) -> Result<Vec<(std::path::PathBuf, Vec<u8>)>, String> {
+ let mut by_plugin = HashMap::<String, HashMap<String, serde_json::Value>>::new();
+ for entry in entries {
+ if !valid_plugin_storage_id(&entry.plugin_id) || !valid_plugin_storage_key(&entry.key) {
+ return Err("sync snapshot contains an invalid plugin UI storage identifier".to_string());
+ }
+ let encoded = serde_json::to_vec(&entry.value).map_err(|error| error.to_string())?;
+ if encoded.len() > 256 * 1024 {
+ return Err(format!("plugin UI storage value exceeds 262144 bytes: {}/{}", entry.plugin_id, entry.key));
+ }
+ by_plugin.entry(entry.plugin_id.clone()).or_default().insert(entry.key.clone(), entry.value.clone());
+ }
+ let mut prepared = Vec::with_capacity(by_plugin.len());
+ for (plugin_id, selected) in by_plugin {
+ let dir = registry.plugin_data_dir(&plugin_id);
+ let path = dir.join("ui-storage.json");
+ let mut current = match fs::symlink_metadata(&path) {
+ Ok(metadata) if metadata.file_type().is_file() => {
+ serde_json::from_slice::<serde_json::Map<String, serde_json::Value>>(
+ &fs::read(&path).map_err(|error| error.to_string())?,
+ )
+ .map_err(|error| format!("cannot parse local plugin UI storage {}: {error}", path.display()))?
+ }
+ Ok(_) => return Err(format!("plugin UI storage is not a regular file: {}", path.display())),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => serde_json::Map::new(),
+ Err(error) => return Err(format!("cannot inspect plugin UI storage: {error}")),
+ };
+ current.extend(selected);
+ let bytes = serde_json::to_vec(&current).map_err(|error| error.to_string())?;
+ if current.len() > 1024 || bytes.len() > 1024 * 1024 {
+ return Err(format!("plugin UI storage exceeds its configured size limit: {}", path.display()));
+ }
+ prepared.push((path, bytes));
+ }
+ Ok(prepared)
+}
+
+fn write_plugin_ui_storage_restore(prepared: Vec<(std::path::PathBuf, Vec<u8>)>) -> Result<(), String> {
+ for (path, bytes) in prepared {
+ let dir = path.parent().ok_or_else(|| "plugin UI storage has no parent directory".to_string())?;
+ fs::create_dir_all(dir).map_err(|error| format!("cannot create plugin data directory: {error}"))?;
+ let temp = path.with_extension("json.sync-tmp");
+ {
+ use std::io::Write;
+ let mut file = fs::File::create(&temp)
+ .map_err(|error| format!("cannot create plugin UI storage temp file: {error}"))?;
+ file.write_all(&bytes).map_err(|error| format!("cannot write plugin UI storage: {error}"))?;
+ file.sync_all().map_err(|error| format!("cannot flush plugin UI storage: {error}"))?;
+ }
+ fs::rename(&temp, &path).map_err(|error| format!("cannot replace plugin UI storage: {error}"))?;
+ }
+ Ok(())
+}
+
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplySnapshotSummary {
@@ -332,12 +804,105 @@ pub async fn build_sync_snapshot_with_options(
editor_settings: Option<serde_json::Value>,
options: SyncExportOptions<'_>,
) -> Result<SyncSnapshot, String> {
- let mut connections = storage.load_connections().await?;
- let mut tunnel_profiles = storage.load_tunnel_profiles().await?;
- let encrypted_secrets = if options.include_secrets {
+ build_sync_snapshot_with_selection(storage, app_version, editor_settings, options, None, None).await
+}
+
+pub async fn build_sync_snapshot_with_selection(
+ storage: &Storage,
+ app_version: impl Into<String>,
+ editor_settings: Option<serde_json::Value>,
+ options: SyncExportOptions<'_>,
+ selection: Option<&SyncSelection>,
+ plugin_registry: Option<&crate::plugins::PluginRegistry>,
+) -> Result<SyncSnapshot, String> {
+ let source_connections = storage.load_connections().await?;
+ let source_tunnel_profiles = storage.load_tunnel_profiles().await?;
+ let source_saved_sql = storage.load_saved_sql_library().await?;
+ let mut connections =
+ select_by_id(&source_connections, selection.and_then(|selection| selection.connections.as_ref()), |item| {
+ item.id.clone()
+ });
+ let mut tunnel_profiles = select_by_id(
+ &source_tunnel_profiles,
+ selection.and_then(|selection| selection.tunnel_profiles.as_ref()),
+ |profile| profile.id().to_string(),
+ );
+ for config in &mut connections {
+ clear_device_local_connection_paths(config);
+ }
+ let saved_sql = select_saved_sql_library(
+ &source_saved_sql,
+ selection.and_then(|selection| selection.saved_sql_folders.as_ref()),
+ selection.and_then(|selection| selection.saved_sql_files.as_ref()),
+ );
+ let plugin_ui_storage = match plugin_registry {
+ Some(registry) => load_plugin_ui_storage(registry)?,
+ None => Vec::new(),
+ };
+ let plugin_ui_storage = select_plugin_ui_storage(
+ &plugin_ui_storage,
+ selection.and_then(|selection| selection.plugin_ui_storage.as_ref()),
+ );
+ let include_secrets = options.include_secrets && selection.is_none_or(|selection| selection.include_secrets);
+ let mut included_selection = selection.cloned();
+ if let Some(selection) = included_selection.as_mut() {
+ if let Some(keys) = selection.desktop_settings.as_mut() {
+ keys.retain(|key| !NON_SYNCABLE_DESKTOP_SETTINGS.contains(&key.as_str()));
+ }
+ if let Some(keys) = selection.editor_settings.as_mut() {
+ keys.retain(|key| !NON_SYNCABLE_EDITOR_SETTINGS.contains(&key.as_str()));
+ }
+ if selection.saved_sql_folders.is_some() {
+ selection.saved_sql_folders = Some(saved_sql.folders.iter().map(|folder| folder.id.clone()).collect());
+ }
+ selection.include_secrets = include_secrets;
+ if !include_secrets {
+ selection.connection_secrets = Some(Vec::new());
+ selection.tunnel_secrets = Some(Vec::new());
+ selection.ai_configs = Some(Vec::new());
+ selection.sync_credentials = false;
+ }
+ selection.plugin_ui_storage = None;
+ if !include_secrets {
+ selection.plugin_ui_storage = Some(Vec::new());
+ }
+ }
+ let encrypted_secrets = if include_secrets {
let passphrase = normalized_passphrase(options.sync_passphrase)
.ok_or_else(|| "A sync password is required when including synced secrets.".to_string())?;
- let payload = build_sensitive_payload_with_options(storage, &connections, &tunnel_profiles, options).await?;
+ let mut payload =
+ build_sensitive_payload_with_options(storage, &connections, &tunnel_profiles, options).await?;
+ if let Some(profiles) = payload.tunnel_profiles.as_mut() {
+ for profile in profiles {
+ clear_device_local_tunnel_path(profile);
+ }
+ }
+ if selection.is_some_and(|selection| !selection.sync_credentials) {
+ payload.sync_credentials = None;
+ }
+ payload.plugin_ui_storage = Some(plugin_ui_storage);
+ if let Some(selection) = selection {
+ if let Some(ids) = &selection.connection_secrets {
+ let ids = ids.iter().map(String::as_str).collect::<HashSet<_>>();
+ let metadata_ids = connections.iter().map(|config| config.id.as_str()).collect::<HashSet<_>>();
+ payload.connection_secrets.retain(|secret| {
+ ids.contains(secret.connection_id.as_str()) && metadata_ids.contains(secret.connection_id.as_str())
+ });
+ }
+ if let Some(ids) = &selection.tunnel_secrets {
+ let ids = ids.iter().map(String::as_str).collect::<HashSet<_>>();
+ let metadata_ids = tunnel_profiles.iter().map(|profile| profile.id()).collect::<HashSet<_>>();
+ if let Some(profiles) = payload.tunnel_profiles.as_mut() {
+ profiles.retain(|profile| ids.contains(profile.id()) && metadata_ids.contains(profile.id()));
+ }
+ }
+ if let Some(ids) = &selection.ai_configs {
+ let ids = ids.iter().map(String::as_str).collect::<HashSet<_>>();
+ if let Some(configs) = payload.ai_configs.as_mut() {
+ configs.retain(|item| ids.contains(item.id.as_str()));
+ }
+ }
+ }
Some(encrypt_sensitive_payload(&payload, passphrase)?)
} else {
None
@@ -347,6 +912,7 @@ pub async fn build_sync_snapshot_with_options(
scrub_connection_secrets(config);
}
for profile in &mut tunnel_profiles {
+ clear_device_local_tunnel_path(profile);
profile.scrub_secrets();
}
@@ -357,15 +923,217 @@ pub async fn build_sync_snapshot_with_options(
connections,
mqtt_subscriptions,
tunnel_profiles: Some(tunnel_profiles),
- sidebar_layout: storage.load_sidebar_layout().await?,
- pinned_tree_node_ids: storage.load_pinned_tree_node_ids().await?,
- saved_sql: storage.load_saved_sql_library().await?,
- desktop_settings: storage.load_desktop_settings().await?,
- editor_settings,
+ sidebar_layout: if selection.and_then(|selection| selection.sidebar_layout) == Some(false) {
+ None
+ } else {
+ storage.load_sidebar_layout().await?
+ },
+ pinned_tree_node_ids: if selection.and_then(|selection| selection.pinned_tree_node_ids) == Some(false) {
+ Vec::new()
+ } else {
+ storage.load_pinned_tree_node_ids().await?
+ },
+ saved_sql,
+ desktop_settings: select_syncable_desktop_settings(
+ storage.load_desktop_settings().await?,
+ selection.and_then(|selection| selection.desktop_settings.as_ref()),
+ )?,
+ editor_settings: select_syncable_editor_settings(
+ editor_settings,
+ selection.and_then(|selection| selection.editor_settings.as_ref()),
+ ),
encrypted_secrets,
+ selection: included_selection,
})
}
+fn syncable_desktop_settings(mut settings: DesktopSettings) -> DesktopSettings {
+ settings.saved_sql_sync_dir = None;
+ settings.driver_store_dir = None;
+ settings.plugin_store_dir = None;
+ settings.agent_store_dir = None;
+ settings.custom_ai_skill_root_enabled = false;
+ settings.custom_ai_skill_root = None;
+ settings.debug_logging_enabled = false;
+ settings
+}
+
+fn select_syncable_desktop_settings(
+ settings: DesktopSettings,
+ selected: Option<&Vec<String>>,
+) -> Result<DesktopSettings, String> {
+ let settings = syncable_desktop_settings(settings);
+ let Some(selected) = selected else { return Ok(settings) };
+ let source = serde_json::to_value(settings).map_err(|error| error.to_string())?;
+ let mut filtered = serde_json::to_value(DesktopSettings::default()).map_err(|error| error.to_string())?;
+ let (Some(source), Some(filtered)) = (source.as_object(), filtered.as_object_mut()) else {
+ return Err("desktop settings must serialize as an object".to_string());
+ };
+ for key in selected {
+ if DESKTOP_DEVICE_LOCAL_SETTINGS.contains(&key.as_str())
+ || NON_SYNCABLE_DESKTOP_SETTINGS.contains(&key.as_str())
+ {
+ continue;
+ }
+ if let Some(value) = source.get(key) {
+ filtered.insert(key.clone(), value.clone());
+ }
+ }
+ serde_json::from_value(serde_json::Value::Object(filtered.clone())).map_err(|error| error.to_string())
+}
+
+fn select_syncable_editor_settings(
+ value: Option<serde_json::Value>,
+ selected: Option<&Vec<String>>,
+) -> Option<serde_json::Value> {
+ let value = value?;
+ let Some(mut object) = value.as_object().cloned() else { return Some(value) };
+ let selected = selected.map(|keys| keys.iter().map(String::as_str).collect::<HashSet<_>>());
+ object.retain(|key, _| {
+ !NON_SYNCABLE_EDITOR_SETTINGS.contains(&key.as_str())
+ && selected.as_ref().is_none_or(|keys| keys.contains(key.as_str()))
+ });
+ Some(serde_json::Value::Object(object))
+}
+
+fn clear_device_local_connection_paths(config: &mut ConnectionConfig) {
+ match config.db_type {
+ DatabaseType::Sqlite | DatabaseType::DuckDb if config.host.trim() != ":memory:" => config.host.clear(),
+ DatabaseType::Access => config.host.clear(),
+ DatabaseType::H2 if config.port == 0 => {
+ config.host.clear();
+ config.connection_string = None;
+ }
+ _ => {}
+ }
+ config.docs_notes_path = None;
+ config.ca_cert_path.clear();
+ config.client_cert_path.clear();
+ config.client_key_path.clear();
+ config.jdbc_driver_paths.clear();
+ for attached_database in &mut config.attached_databases {
+ attached_database.path.clear();
+ }
+ for layer in &mut config.transport_layers {
+ if let TransportLayerConfig::Ssh(ssh) = layer {
+ ssh.key_path.clear();
+ ssh.ssh_agent_sock_path.clear();
+ }
+ }
+ match config.db_type {
+ DatabaseType::Mqtt => {
+ clear_external_config_path_fields(config, "auth", &["caCertPath", "clientCertPath", "clientKeyPath"])
+ }
+ DatabaseType::Cassandra => {
+ clear_external_config_path_fields(config, "tls", &["truststore_path", "keystore_path"])
+ }
+ _ => {}
+ }
+}
+
+fn clear_external_config_path_fields(config: &mut ConnectionConfig, section: &str, fields: &[&str]) {
+ let Some(section) = config
+ .external_config
+ .as_mut()
+ .and_then(|external| external.get_mut(section))
+ .and_then(serde_json::Value::as_object_mut)
+ else {
+ return;
+ };
+ for field in fields {
+ section.remove(*field);
+ }
+}
+
+fn preserve_external_config_path_fields(
+ remote: &mut ConnectionConfig,
+ local: &ConnectionConfig,
+ section: &str,
+ fields: &[&str],
+) {
+ let Some(local_section) = local
+ .external_config
+ .as_ref()
+ .and_then(|external| external.get(section))
+ .and_then(serde_json::Value::as_object)
+ else {
+ return;
+ };
+ let Some(remote_section) = remote
+ .external_config
+ .as_mut()
+ .and_then(|external| external.get_mut(section))
+ .and_then(serde_json::Value::as_object_mut)
+ else {
+ return;
+ };
+ if section == "auth" && remote_section.get("kind") != local_section.get("kind") {
+ return;
+ }
+ for field in fields {
+ if let Some(value) = local_section.get(*field) {
+ remote_section.insert((*field).to_string(), value.clone());
+ }
+ }
+}
+
+fn clear_device_local_tunnel_path(profile: &mut TransportLayerConfig) {
+ if let TransportLayerConfig::Ssh(ssh) = profile {
+ ssh.key_path.clear();
+ ssh.ssh_agent_sock_path.clear();
+ }
+}
+
+fn preserve_local_transport_paths(remote: &mut ConnectionConfig, local: &ConnectionConfig) {
+ if remote.db_type == local.db_type {
+ match remote.db_type {
+ DatabaseType::Sqlite | DatabaseType::DuckDb | DatabaseType::Access => remote.host.clone_from(&local.host),
+ DatabaseType::H2 if remote.port == 0 && local.port == 0 => {
+ remote.host.clone_from(&local.host);
+ remote.connection_string.clone_from(&local.connection_string);
+ }
+ _ => {}
+ }
+ remote.docs_notes_path.clone_from(&local.docs_notes_path);
+ remote.ca_cert_path.clone_from(&local.ca_cert_path);
+ remote.client_cert_path.clone_from(&local.client_cert_path);
+ remote.client_key_path.clone_from(&local.client_key_path);
+ remote.jdbc_driver_paths.clone_from(&local.jdbc_driver_paths);
+ for attached_database in &mut remote.attached_databases {
+ if let Some(local_database) =
+ local.attached_databases.iter().find(|candidate| candidate.name == attached_database.name)
+ {
+ attached_database.path.clone_from(&local_database.path);
+ }
+ }
+ match remote.db_type {
+ DatabaseType::Mqtt => preserve_external_config_path_fields(
+ remote,
+ local,
+ "auth",
+ &["caCertPath", "clientCertPath", "clientKeyPath"],
+ ),
+ DatabaseType::Cassandra => {
+ preserve_external_config_path_fields(remote, local, "tls", &["truststore_path", "keystore_path"])
+ }
+ _ => {}
+ }
+ }
+ for layer in &mut remote.transport_layers {
+ let Some(local_layer) = local
+ .transport_layers
+ .iter()
+ .find(|candidate| candidate.id() == layer.id() && candidate.same_type_as(layer))
+ else {
+ continue;
+ };
+ if let (TransportLayerConfig::Ssh(remote), TransportLayerConfig::Ssh(local)) = (layer, local_layer) {
+ remote.key_path.clone_from(&local.key_path);
+ remote.ssh_agent_sock_path.clone_from(&local.ssh_agent_sock_path);
+ }
+ }
+}
+
pub async fn build_sync_snapshot_with_saved_secrets(
storage: &Storage,
app_version: impl Into<String>,
@@ -412,30 +1180,68 @@ pub async fn apply_sync_snapshot(
snapshot: &SyncSnapshot,
options: ApplySnapshotOptions<'_>,
) -> Result<ApplySnapshotSummary, String> {
- if !matches!(snapshot.schema_version, LEGACY_SNAPSHOT_SCHEMA_VERSION | SNAPSHOT_SCHEMA_VERSION) {
+ apply_sync_snapshot_with_selection(storage, snapshot, options, None, None).await
+}
+
+pub async fn apply_sync_snapshot_with_selection(
+ storage: &Storage,
+ snapshot: &SyncSnapshot,
+ options: ApplySnapshotOptions<'_>,
+ restore_selection: Option<&SyncSelection>,
+ plugin_registry: Option<&crate::plugins::PluginRegistry>,
+) -> Result<ApplySnapshotSummary, String> {
+ const INTERMEDIATE_SNAPSHOT_SCHEMA_VERSION: u32 = 2;
+ if !matches!(
+ snapshot.schema_version,
+ LEGACY_SNAPSHOT_SCHEMA_VERSION | INTERMEDIATE_SNAPSHOT_SCHEMA_VERSION | SNAPSHOT_SCHEMA_VERSION
+ ) {
return Err(format!("Unsupported sync snapshot schema version: {}", snapshot.schema_version));
}
validate_sync_snapshot_metadata(snapshot)?;
+ let selection = restore_selection.or(snapshot.selection.as_ref());
+ let merge_selected_items = selection.is_some();
+ let selected_connections =
+ select_by_id(&snapshot.connections, selection.and_then(|selection| selection.connections.as_ref()), |item| {
+ item.id.clone()
+ });
+ let selected_tunnel_profiles = snapshot.tunnel_profiles.as_ref().map(|profiles| {
+ select_by_id(profiles, selection.and_then(|selection| selection.tunnel_profiles.as_ref()), |profile| {
+ profile.id().to_string()
+ })
+ });
+ let selected_saved_sql = select_saved_sql_library(
+ &snapshot.saved_sql,
+ selection.and_then(|selection| selection.saved_sql_folders.as_ref()),
+ selection.and_then(|selection| selection.saved_sql_files.as_ref()),
+ );
+ let include_selected_secrets = selection.is_none_or(|selection| selection.include_secrets);
+
let encrypted_secrets_present = snapshot.encrypted_secrets.is_some();
- let mut sensitive_payload =
- match (options.restore_secrets, &snapshot.encrypted_secrets, normalized_passphrase(options.secrets_passphrase))
- {
- (true, Some(blob), Some(passphrase)) => Some(decrypt_sensitive_payload(blob, passphrase)?),
- // Restore intent is explicit. Do not silently leave a user with a
- // partial restore when the remote snapshot contains secrets.
- (true, Some(_), None) => return Err("A sync password is required to restore synced secrets.".to_string()),
- _ => None,
- };
+ let mut sensitive_payload = match (
+ options.restore_secrets && include_selected_secrets,
+ &snapshot.encrypted_secrets,
+ normalized_passphrase(options.secrets_passphrase),
+ ) {
+ (true, Some(blob), Some(passphrase)) => Some(decrypt_sensitive_payload(blob, passphrase)?),
+ // Restore intent is explicit. Do not silently leave a user with a
+ // partial restore when the remote snapshot contains secrets.
+ (true, Some(_), None) => return Err("A sync password is required to restore synced secrets.".to_string()),
+ _ => None,
+ };
// Version-1 snapshots could carry hydrated credentials directly in the
// public connection JSON. Treat an explicit secret restore as the
// migration consent: extract those values before scrubbing metadata, then
// send them through the same destination SecretStore transaction used by
// modern encrypted payloads. With restore disabled, metadata still
// imports but legacy plaintext credentials are discarded.
- if sensitive_payload.is_none() && options.restore_secrets && snapshot.encrypted_secrets.is_none() {
- let tunnel_profiles = snapshot.tunnel_profiles.clone().unwrap_or_default();
- let has_legacy_secrets = snapshot.connections.iter().any(connection_has_inline_secrets)
+ if sensitive_payload.is_none()
+ && options.restore_secrets
+ && include_selected_secrets
+ && snapshot.encrypted_secrets.is_none()
+ {
+ let tunnel_profiles = selected_tunnel_profiles.clone().unwrap_or_default();
+ let has_legacy_secrets = selected_connections.iter().any(connection_has_inline_secrets)
|| tunnel_profiles.iter().any(|profile| {
let mut scrubbed = profile.clone();
scrubbed.scrub_secrets();
@@ -445,7 +1251,7 @@ pub async fn apply_sync_snapshot(
sensitive_payload = Some(
build_sensitive_payload_with_options(
storage,
- &snapshot.connections,
+ &selected_connections,
&tunnel_profiles,
SyncExportOptions {
include_secrets: false,
@@ -459,8 +1265,55 @@ pub async fn apply_sync_snapshot(
);
}
}
+ if let Some(payload) = sensitive_payload.as_mut() {
+ if let Some(ids) = selection.and_then(|selection| selection.connections.as_ref()) {
+ let ids = ids.iter().map(String::as_str).collect::<HashSet<_>>();
+ payload.connection_secrets.retain(|secret| ids.contains(secret.connection_id.as_str()));
+ }
+ if let Some(ids) = selection.and_then(|selection| selection.connection_secrets.as_ref()) {
+ let ids = ids.iter().map(String::as_str).collect::<HashSet<_>>();
+ let metadata_ids = selected_connections.iter().map(|config| config.id.as_str()).collect::<HashSet<_>>();
+ payload.connection_secrets.retain(|secret| {
+ ids.contains(secret.connection_id.as_str()) && metadata_ids.contains(secret.connection_id.as_str())
+ });
+ }
+ if let Some(ids) = selection.and_then(|selection| selection.tunnel_secrets.as_ref()) {
+ let ids = ids.iter().map(String::as_str).collect::<HashSet<_>>();
+ let metadata_ids = selected_tunnel_profiles
+ .as_deref()
+ .unwrap_or_default()
+ .iter()
+ .map(|profile| profile.id())
+ .collect::<HashSet<_>>();
+ if let Some(profiles) = payload.tunnel_profiles.as_mut() {
+ profiles.retain(|profile| ids.contains(profile.id()) && metadata_ids.contains(profile.id()));
+ }
+ }
+ if let Some(ids) = selection.and_then(|selection| selection.tunnel_profiles.as_ref()) {
+ let ids = ids.iter().map(String::as_str).collect::<HashSet<_>>();
+ if let Some(profiles) = payload.tunnel_profiles.as_mut() {
+ profiles.retain(|profile| ids.contains(profile.id()));
+ }
+ }
+ if let Some(ids) = selection.and_then(|selection| selection.ai_configs.as_ref()) {
+ let ids = ids.iter().map(String::as_str).collect::<HashSet<_>>();
+ if let Some(configs) = payload.ai_configs.as_mut() {
+ configs.retain(|item| ids.contains(item.id.as_str()));
+ }
+ if !ids.contains(LEGACY_AI_CONFIG_SELECTION_ID) {
+ payload.ai_config = None;
+ }
+ }
+ if let Some(items) = selection.and_then(|selection| selection.plugin_ui_storage.as_ref()) {
+ payload.plugin_ui_storage =
+ payload.plugin_ui_storage.take().map(|entries| select_plugin_ui_storage(&entries, Some(items)));
+ }
+ if selection.is_some_and(|selection| !selection.sync_credentials) {
+ payload.sync_credentials = None;
+ }
+ }
if let Some(payload) = &sensitive_payload {
- validate_sensitive_payload_targets(payload, &snapshot.connections, snapshot.tunnel_profiles.as_deref())?;
+ validate_sensitive_payload_targets(payload, &selected_connections, selected_tunnel_profiles.as_deref())?;
}
if let Some(payload) = &sensitive_payload {
// Validate the complete decrypted payload before touching metadata or
@@ -469,9 +1322,24 @@ pub async fn apply_sync_snapshot(
validate_sensitive_payload(payload)?;
}
- let mut connections = snapshot.connections.clone();
+ let mut connections = selected_connections;
+ for config in &mut connections {
+ clear_device_local_connection_paths(config);
+ }
+ preserve_local_connection_paths(storage, &mut connections).await?;
+ let preserve_local_connection_strings = connections
+ .iter()
+ .filter(|config| config.db_type == DatabaseType::H2 && config.port == 0 && config.connection_string.is_some())
+ .map(|config| config.id.clone())
+ .collect::<Vec<_>>();
if let Some(mqtt_subscriptions) = &snapshot.mqtt_subscriptions {
- apply_mqtt_subscriptions(&mut connections, mqtt_subscriptions)?;
+ let selected_ids = connections.iter().map(|config| config.id.as_str()).collect::<HashSet<_>>();
+ let subscriptions = mqtt_subscriptions
+ .iter()
+ .filter(|entry| selected_ids.contains(entry.connection_id.as_str()))
+ .cloned()
+ .collect::<Vec<_>>();
+ apply_mqtt_subscriptions(&mut connections, &subscriptions)?;
} else {
// Snapshots created before MQTT subscription sync may still contain a
// stale `savedTopics` value inside `externalConfig`. Preserve the
@@ -483,48 +1351,53 @@ pub async fn apply_sync_snapshot(
scrub_connection_secrets(config);
}
- let (connection_secrets, preserve_plugin_secrets, ai_configs, tunnel_secret_profiles, sync_payload_credentials) =
- if let Some(payload) = &sensitive_payload {
- let ai_configs = if let Some(configs) = &payload.ai_configs {
- Some(configs.clone())
- } else {
- payload.ai_config.as_ref().map(|old_config| {
- vec![AiConfigItem {
- id: AiConfigItem::new_id(),
- name: old_config.provider.as_str().to_string(),
- is_default: true,
- config: old_config.clone(),
- }]
- })
- };
- (
- Some(
- payload
- .connection_secrets
- .iter()
- .filter(|secret| {
- !(matches!(
- secret.key.as_str(),
- "password" | NACOS_AUTH_PASSWORD_KEY | NACOS_RNACOS_CONSOLE_PASSWORD_KEY
- ) && connections
- .iter()
- .any(|config| config.id == secret.connection_id && !config.save_password))
- })
- .map(|secret| SyncImportSecret {
- connection_id: secret.connection_id.clone(),
- key: secret.key.clone(),
- secret: secret.secret.clone(),
- })
- .collect(),
- ),
- !payload.plugin_secrets_included,
- ai_configs,
- payload.tunnel_profiles.clone(),
- payload.sync_credentials.clone(),
- )
+ let (
+ mut connection_secrets,
+ preserve_plugin_secrets,
+ ai_configs,
+ mut tunnel_secret_profiles,
+ sync_payload_credentials,
+ ) = if let Some(payload) = &sensitive_payload {
+ let ai_configs = if let Some(configs) = &payload.ai_configs {
+ Some(configs.clone())
} else {
- (None, false, None, None, None)
+ payload.ai_config.as_ref().map(|old_config| {
+ vec![AiConfigItem {
+ id: AiConfigItem::new_id(),
+ name: old_config.provider.as_str().to_string(),
+ is_default: true,
+ config: old_config.clone(),
+ }]
+ })
};
+ (
+ Some(
+ payload
+ .connection_secrets
+ .iter()
+ .filter(|secret| {
+ !(matches!(
+ secret.key.as_str(),
+ "password" | NACOS_AUTH_PASSWORD_KEY | NACOS_RNACOS_CONSOLE_PASSWORD_KEY
+ ) && connections
+ .iter()
+ .any(|config| config.id == secret.connection_id && !config.save_password))
+ })
+ .map(|secret| SyncImportSecret {
+ connection_id: secret.connection_id.clone(),
+ key: secret.key.clone(),
+ secret: secret.secret.clone(),
+ })
+ .collect::<Vec<_>>(),
+ ),
+ !payload.plugin_secrets_included,
+ ai_configs,
+ payload.tunnel_profiles.clone(),
+ payload.sync_credentials.clone(),
+ )
+ } else {
+ (None, false, None, None, None)
+ };
let sync_credentials = if let Some(credentials) = sync_payload_credentials {
let local_secret =
if credentials.is_empty() { None } else { Some(storage.load_or_create_local_device_secret().await?) };
@@ -544,7 +1417,12 @@ pub async fn apply_sync_snapshot(
} else {
None
};
- let sync_tunnel_profiles = snapshot.tunnel_profiles.clone().or_else(|| {
+ if let Some(profiles) = tunnel_secret_profiles.as_mut() {
+ for profile in profiles {
+ clear_device_local_tunnel_path(profile);
+ }
+ }
+ let mut sync_tunnel_profiles = selected_tunnel_profiles.clone().or_else(|| {
tunnel_secret_profiles.as_ref().map(|profiles| {
profiles
.iter()
@@ -556,22 +1434,101 @@ pub async fn apply_sync_snapshot(
.collect()
})
});
+ if let Some(profiles) = sync_tunnel_profiles.as_mut() {
+ for profile in profiles {
+ clear_device_local_tunnel_path(profile);
+ }
+ }
+ let selected_connection_ids = connections.iter().map(|config| config.id.clone()).collect::<HashSet<_>>();
+ let h2_file_connection_ids = connections
+ .iter()
+ .filter(|config| config.db_type == DatabaseType::H2 && config.port == 0)
+ .map(|config| config.id.clone())
+ .collect::<HashSet<_>>();
+ if let Some(secrets) = connection_secrets.as_mut() {
+ secrets.retain(|secret| {
+ secret.key != "connection_string" || !h2_file_connection_ids.contains(&secret.connection_id)
+ });
+ }
+ let connection_secret_ids = sensitive_payload.as_ref().map(|_| {
+ selection
+ .and_then(|selection| selection.connection_secrets.as_ref())
+ .map(|ids| ids.iter().filter(|id| selected_connection_ids.contains(*id)).cloned().collect())
+ .unwrap_or_else(|| selected_connection_ids.iter().cloned().collect())
+ });
+ let available_desktop_settings = serde_json::to_value(&snapshot.desktop_settings)
+ .map_err(|error| error.to_string())?
+ .as_object()
+ .map(|settings| {
+ settings
+ .keys()
+ .filter(|key| {
+ !DESKTOP_DEVICE_LOCAL_SETTINGS.contains(&key.as_str())
+ && !NON_SYNCABLE_DESKTOP_SETTINGS.contains(&key.as_str())
+ })
+ .cloned()
+ .collect::<HashSet<_>>()
+ })
+ .unwrap_or_default();
+ let desktop_settings_keys = Some(
+ selection
+ .and_then(|selection| selection.desktop_settings.as_ref())
+ .cloned()
+ .unwrap_or_else(|| available_desktop_settings.iter().cloned().collect())
+ .into_iter()
+ .filter(|key| {
+ available_desktop_settings.contains(key)
+ && !DESKTOP_DEVICE_LOCAL_SETTINGS.contains(&key.as_str())
+ && !NON_SYNCABLE_DESKTOP_SETTINGS.contains(&key.as_str())
+ })
+ .collect(),
+ );
+ let plugin_ui_storage_restore =
+ match sensitive_payload.as_ref().and_then(|payload| payload.plugin_ui_storage.as_ref()) {
+ Some(entries) if !entries.is_empty() => {
+ let registry = plugin_registry
+ .ok_or_else(|| "plugin storage is unavailable for restoring plugin settings".to_string())?;
+ prepare_plugin_ui_storage_restore(registry, entries)?
+ }
+ _ => Vec::new(),
+ };
storage
.apply_sync_import_transaction(SyncImportPlan {
connections,
+ merge_connections: merge_selected_items,
tunnel_profiles: sync_tunnel_profiles,
tunnel_secret_profiles,
- sidebar_layout: snapshot.sidebar_layout.clone(),
- pinned_tree_node_ids: snapshot.pinned_tree_node_ids.clone(),
- saved_sql: snapshot.saved_sql.clone(),
+ merge_tunnel_profiles: merge_selected_items,
+ sidebar_layout: if selection.and_then(|selection| selection.sidebar_layout) == Some(false) {
+ None
+ } else {
+ snapshot.sidebar_layout.clone()
+ },
+ pinned_tree_node_ids: if selection.and_then(|selection| selection.pinned_tree_node_ids) == Some(false) {
+ None
+ } else {
+ Some(snapshot.pinned_tree_node_ids.clone())
+ },
+ saved_sql: selected_saved_sql,
+ merge_saved_sql: merge_selected_items,
desktop_settings: snapshot.desktop_settings.clone(),
- editor_settings: snapshot.editor_settings.clone(),
+ desktop_settings_keys,
+ editor_settings: select_syncable_editor_settings(
+ snapshot.editor_settings.clone(),
+ selection.and_then(|selection| selection.editor_settings.as_ref()),
+ ),
+ merge_editor_settings: true,
+ editor_settings_keys: selection.and_then(|selection| selection.editor_settings.clone()),
connection_secrets,
+ connection_secret_ids,
+ preserve_local_connection_strings,
preserve_plugin_secrets,
sync_credentials,
ai_configs,
+ merge_ai_configs: merge_selected_items,
})
.await?;
+ write_plugin_ui_storage_restore(plugin_ui_storage_restore)?;
Ok(ApplySnapshotSummary { encrypted_secrets_present, secrets_applied: sensitive_payload.is_some() })
}
@@ -1273,6 +2230,19 @@ async fn preserve_local_mqtt_subscriptions_for_legacy_snapshot(
Ok(())
}
+async fn preserve_local_connection_paths(
+ storage: &Storage,
+ connections: &mut [ConnectionConfig],
+) -> Result<(), String> {
+ let local_connections = storage.load_connections().await?;
+ for remote in connections {
+ if let Some(local) = local_connections.iter().find(|connection| connection.id == remote.id) {
+ preserve_local_transport_paths(remote, local);
+ }
+ }
+ Ok(())
+}
+
fn validate_mqtt_subscriptions(
config: &ConnectionConfig,
subscriptions: &[MqttSubscriptionSyncTopic],
@@ -1476,7 +2446,15 @@ async fn build_sensitive_payload_with_options(
// provider/decryption failure must abort the export: treating it as an
// empty list would produce a valid-looking snapshot that clears AI
// configurations on the destination during restore.
- let ai_configs = if options.include_ai_secrets { Some(storage.load_ai_configs().await?) } else { None };
+ let ai_configs = if options.include_ai_secrets {
+ let mut configs = storage.load_ai_configs().await?;
+ for item in &mut configs {
+ clear_ai_config_device_paths(&mut item.config);
+ }
+ Some(configs)
+ } else {
+ None
+ };
let sync_credentials = if options.include_secrets { Some(load_sync_credentials(storage).await?) } else { None };
Ok(SensitiveSyncPayload {
connection_secrets,
@@ -1485,6 +2463,7 @@ async fn build_sensitive_payload_with_options(
ai_configs,
ai_config: None,
tunnel_profiles: options.include_tunnel_secrets.then(|| tunnel_profiles.to_vec()),
+ plugin_ui_storage: None,
})
}
@@ -2939,6 +3918,7 @@ mod tests {
fn encrypted_sensitive_payload_round_trips() {
let payload = SensitiveSyncPayload {
tunnel_profiles: None,
+ plugin_ui_storage: None,
plugin_secrets_included: true,
connection_secrets: vec![
ConnectionSecretSnapshot {
@@ -2967,6 +3947,7 @@ mod tests {
fn encrypted_sensitive_payload_rejects_wrong_passphrase() {
let payload = SensitiveSyncPayload {
tunnel_profiles: None,
+ plugin_ui_storage: None,
plugin_secrets_included: true,
connection_secrets: vec![ConnectionSecretSnapshot {
connection_id: "c1".to_string(),
@@ -2985,6 +3966,7 @@ mod tests {
fn encrypted_sensitive_payload_keeps_v1_compatibility() {
let payload = SensitiveSyncPayload {
tunnel_profiles: None,
+ plugin_ui_storage: None,
plugin_secrets_included: true,
connection_secrets: vec![ConnectionSecretSnapshot {
connection_id: "legacy".to_string(),
@@ -4151,6 +5133,7 @@ mod tests {
}));
let legacy_payload = SensitiveSyncPayload {
+ plugin_ui_storage: None,
plugin_secrets_included: true,
connection_secrets: vec![
ConnectionSecretSnapshot {
@@ -4224,6 +5207,7 @@ mod tests {
// No ai_configs in payload — fall through to ai_config (legacy) branch
let payload = SensitiveSyncPayload {
+ plugin_ui_storage: None,
plugin_secrets_included: true,
connection_secrets: vec![],
sync_credentials: Some(vec![]),
@@ -4246,6 +5230,7 @@ mod tests {
// Some([]) — explicit clear
let payload = SensitiveSyncPayload {
+ plugin_ui_storage: None,
plugin_secrets_included: true,
connection_secrets: vec![],
sync_credentials: Some(vec![]),
@@ -4273,6 +5258,7 @@ mod tests {
cursor_cfg.config.cursor_cli_path = Some("~/.local/bin/agent".to_string());
cursor_cfg.config.cursor_cli_env.insert("NO_PROXY".to_string(), "localhost".to_string());
let payload = SensitiveSyncPayload {
+ plugin_ui_storage: None,
plugin_secrets_included: true,
connection_secrets: vec![],
sync_credentials: Some(vec![]),
@@ -4307,6 +5293,7 @@ mod tests {
let mut legacy_config = make_test_config("unused", true).config;
legacy_config.model = "snapshot-model".to_string();
let payload = SensitiveSyncPayload {
+ plugin_ui_storage: None,
plugin_secrets_included: true,
connection_secrets: vec![],
sync_credentials: Some(vec![]),
diff --git a/crates/dbx-core/src/persistence/storage.rs b/crates/dbx-core/src/persistence/storage.rs
index 6b74b9c296..6e2b600907 100644
--- a/crates/dbx-core/src/persistence/storage.rs
+++ b/crates/dbx-core/src/persistence/storage.rs
@@ -319,19 +319,28 @@ pub struct MigrationReport {
/// re-encryption inside the storage boundary.
pub(crate) struct SyncImportPlan {
pub connections: Vec<ConnectionConfig>,
+ pub merge_connections: bool,
pub tunnel_profiles: Option<Vec<TransportLayerConfig>>,
pub tunnel_secret_profiles: Option<Vec<TransportLayerConfig>>,
+ pub merge_tunnel_profiles: bool,
pub sidebar_layout: Option<serde_json::Value>,
- pub pinned_tree_node_ids: Vec<String>,
+ pub pinned_tree_node_ids: Option<Vec<String>>,
pub saved_sql: SavedSqlLibrary,
+ pub merge_saved_sql: bool,
pub desktop_settings: DesktopSettings,
+ pub desktop_settings_keys: Option<Vec<String>>,
pub editor_settings: Option<serde_json::Value>,
+ pub merge_editor_settings: bool,
+ pub editor_settings_keys: Option<Vec<String>>,
pub connection_secrets: Option<Vec<SyncImportSecret>>,
+ pub connection_secret_ids: Option<Vec<String>>,
+ pub preserve_local_connection_strings: Vec<String>,
/// Keep destination plugin credentials when the transport payload
/// intentionally omitted plugin secrets.
pub preserve_plugin_secrets: bool,
pub sync_credentials: Option<Vec<SyncImportCredential>>,
pub ai_configs: Option<Vec<AiConfigItem>>,
+ pub merge_ai_configs: bool,
}
pub(crate) struct SyncImportSecret {
@@ -5924,25 +5933,47 @@ impl Storage {
self.with_conn(move |conn| {
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|e| e.to_string())?;
- apply_sync_connections_in_tx(&tx, &codec, &plan.connections)?;
+ apply_sync_connections_in_tx(&tx, &codec, &plan.connections, plan.merge_connections)?;
if let Some(profiles) = &plan.tunnel_profiles {
- apply_sync_tunnel_profiles_in_tx(&tx, &codec, profiles, plan.tunnel_secret_profiles.as_deref())?;
+ apply_sync_tunnel_profiles_in_tx(
+ &tx,
+ &codec,
+ profiles,
+ plan.tunnel_secret_profiles.as_deref(),
+ plan.merge_tunnel_profiles,
+ )?;
}
if let Some(layout) = &plan.sidebar_layout {
let json = serde_json::to_string(layout).map_err(|e| e.to_string())?;
tx.execute("INSERT OR REPLACE INTO sidebar_layout (id, layout_json) VALUES (1, ?1)", [json])
.map_err(|e| e.to_string())?;
}
- let pinned = serde_json::to_string(&plan.pinned_tree_node_ids).map_err(|e| e.to_string())?;
- update_app_settings_key_in_tx(
- &tx,
- "pinned_tree_node_ids",
- serde_json::from_str(&pinned).map_err(|e| e.to_string())?,
- )?;
- apply_saved_sql_in_tx(&tx, &plan.saved_sql)?;
- apply_desktop_settings_in_tx(&tx, &plan.desktop_settings)?;
+ if let Some(pinned_tree_node_ids) = &plan.pinned_tree_node_ids {
+ let pinned = serde_json::to_string(pinned_tree_node_ids).map_err(|e| e.to_string())?;
+ update_app_settings_key_in_tx(
+ &tx,
+ "pinned_tree_node_ids",
+ serde_json::from_str(&pinned).map_err(|e| e.to_string())?,
+ )?;
+ }
+ apply_saved_sql_in_tx(&tx, &plan.saved_sql, plan.merge_saved_sql)?;
+ apply_desktop_settings_in_tx(&tx, &plan.desktop_settings, plan.desktop_settings_keys.as_deref())?;
if let Some(editor_settings) = &plan.editor_settings {
- let value = serde_json::to_string(editor_settings).map_err(|e| e.to_string())?;
+ let mut value = editor_settings.clone();
+ if plan.merge_editor_settings {
+ let current = tx
+ .query_row(
+ "SELECT value_json FROM app_state WHERE key = ?1",
+ [APP_STATE_EDITOR_SETTINGS_KEY],
+ |row| row.get::<_, String>(0),
+ )
+ .optional()
+ .map_err(|e| e.to_string())?
+ .and_then(|json| serde_json::from_str::<serde_json::Value>(&json).ok())
+ .unwrap_or_else(|| serde_json::json!({}));
+ value = merge_json_object_fields(current, value, plan.editor_settings_keys.as_deref());
+ }
+ let value = serde_json::to_string(&value).map_err(|e| e.to_string())?;
tx.execute(
"INSERT OR REPLACE INTO app_state (key, value_json) VALUES (?1, ?2)",
params![APP_STATE_EDITOR_SETTINGS_KEY, value],
@@ -5950,10 +5981,15 @@ impl Storage {
.map_err(|e| e.to_string())?;
}
if let Some(ai_configs) = &plan.ai_configs {
- apply_ai_configs_in_tx(&tx, &codec, ai_configs)?;
+ apply_ai_configs_in_tx(&tx, &codec, ai_configs, plan.merge_ai_configs)?;
}
if let Some(secrets) = &plan.connection_secrets {
- clear_sync_connection_secrets_in_tx(&tx, &plan.connections, plan.preserve_plugin_secrets)?;
+ clear_sync_connection_secrets_in_tx(
+ &tx,
+ plan.connection_secret_ids.as_deref().unwrap_or(&[]),
+ &plan.preserve_local_connection_strings,
+ plan.preserve_plugin_secrets,
+ )?;
for secret in secrets {
if secret.secret.is_empty() {
continue;
@@ -7949,12 +7985,17 @@ fn apply_sync_connections_in_tx(
tx: &Transaction<'_>,
codec: &SecretCodec,
configs: &[ConnectionConfig],
+ merge_existing: bool,
) -> Result<(), String> {
- let replacement_ids = configs.iter().map(|config| config.id.clone()).collect::<HashSet<_>>();
- let mut retained_ids = preserve_unreadable_connections_for_replacement(tx, &replacement_ids)?;
+ let mut retained_ids = if merge_existing {
+ Vec::new()
+ } else {
+ let replacement_ids = configs.iter().map(|config| config.id.clone()).collect::<HashSet<_>>();
+ preserve_unreadable_connections_for_replacement(tx, &replacement_ids)?
+ };
for config in configs {
let config = config.canonicalized();
- if !config.save_password {
+ if !config.save_password && !merge_existing {
persist_secret_in_tx(tx, codec, &config.id, "password", "")?;
delete_secret_prefix_in_tx(tx, &config.id, NACOS_AUTH_SECRET_PREFIX)?;
}
@@ -7965,29 +8006,51 @@ fn apply_sync_connections_in_tx(
}
let sanitized = sanitized_connection_config(&config);
let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
- tx.execute("INSERT INTO connections (id, config_json) VALUES (?1, ?2)", params![config.id, json])
+ tx.execute("INSERT OR REPLACE INTO connections (id, config_json) VALUES (?1, ?2)", params![config.id, json])
.map_err(|e| e.to_string())?;
}
retained_ids.extend(configs.iter().map(|config| config.id.clone()));
- delete_unreferenced_connection_secrets_in_tx(tx, &retained_ids)
+ if merge_existing {
+ Ok(())
+ } else {
+ delete_unreferenced_connection_secrets_in_tx(tx, &retained_ids)
+ }
}
fn clear_sync_connection_secrets_in_tx(
tx: &Transaction<'_>,
- configs: &[ConnectionConfig],
+ connection_ids: &[String],
+ preserve_connection_strings: &[String],
preserve_plugin_secrets: bool,
) -> Result<(), String> {
- for config in configs {
- if preserve_plugin_secrets {
+ let preserve_connection_strings = preserve_connection_strings.iter().map(String::as_str).collect::<HashSet<_>>();
+ for connection_id in connection_ids {
+ let preserve_connection_string = preserve_connection_strings.contains(connection_id.as_str());
+ if preserve_plugin_secrets && preserve_connection_string {
+ tx.execute(
+ "DELETE FROM connection_secrets
+ WHERE connection_id = ?1
+ AND key NOT LIKE 'plugin_connection.%'
+ AND key <> 'connection_string'",
+ [connection_id],
+ )
+ .map_err(|e| e.to_string())?;
+ } else if preserve_plugin_secrets {
tx.execute(
"DELETE FROM connection_secrets
WHERE connection_id = ?1
AND key NOT LIKE 'plugin_connection.%'",
- [&config.id],
+ [connection_id],
+ )
+ .map_err(|e| e.to_string())?;
+ } else if preserve_connection_string {
+ tx.execute(
+ "DELETE FROM connection_secrets WHERE connection_id = ?1 AND key <> 'connection_string'",
+ [connection_id],
)
.map_err(|e| e.to_string())?;
} else {
- tx.execute("DELETE FROM connection_secrets WHERE connection_id = ?1", [&config.id])
+ tx.execute("DELETE FROM connection_secrets WHERE connection_id = ?1", [connection_id])
.map_err(|e| e.to_string())?;
}
}
@@ -7999,6 +8062,7 @@ fn apply_sync_tunnel_profiles_in_tx(
codec: &SecretCodec,
profiles: &[TransportLayerConfig],
secret_profiles: Option<&[TransportLayerConfig]>,
+ merge_existing: bool,
) -> Result<(), String> {
let mut existing = HashMap::<String, TransportLayerConfig>::new();
let mut statement = tx.prepare("SELECT id, config_json FROM tunnel_profiles").map_err(|e| e.to_string())?;
@@ -8029,6 +8093,9 @@ fn apply_sync_tunnel_profiles_in_tx(
Some(profile) => (profile, true),
None => (profile.clone(), false),
};
+ if let Some(previous) = existing.get(profile.id()) {
+ preserve_tunnel_profile_local_paths(&mut profile, previous);
+ }
if !has_synced_secrets {
if let Some(previous) = existing.get(profile.id()) {
merge_missing_tunnel_profile_secrets(&mut profile, previous);
@@ -8037,10 +8104,19 @@ fn apply_sync_tunnel_profiles_in_tx(
effective.push(profile);
}
- tx.execute("DELETE FROM tunnel_profiles", []).map_err(|e| e.to_string())?;
- tx.execute("DELETE FROM connection_secrets WHERE connection_id LIKE 'tunnel_profile.%'", [])
- .map_err(|e| e.to_string())?;
+ if !merge_existing {
+ tx.execute("DELETE FROM tunnel_profiles", []).map_err(|e| e.to_string())?;
+ tx.execute("DELETE FROM connection_secrets WHERE connection_id LIKE 'tunnel_profile.%'", [])
+ .map_err(|e| e.to_string())?;
+ }
for profile in effective {
+ if merge_existing {
+ tx.execute(
+ "DELETE FROM connection_secrets WHERE connection_id = ?1",
+ [format!("{TUNNEL_SECRET_NAMESPACE_PREFIX}{}", profile.id())],
+ )
+ .map_err(|e| e.to_string())?;
+ }
let mut sanitized = profile.clone();
sanitized.scrub_secrets();
let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
@@ -8059,14 +8135,64 @@ fn apply_sync_tunnel_profiles_in_tx(
Ok(())
}
-fn apply_ai_configs_in_tx(tx: &Transaction<'_>, codec: &SecretCodec, configs: &[AiConfigItem]) -> Result<(), String> {
- tx.execute("DELETE FROM ai_configs", []).map_err(|e| e.to_string())?;
- tx.execute("DELETE FROM ai_config", []).map_err(|e| e.to_string())?;
- tx.execute("DELETE FROM ai_provider_configs", []).map_err(|e| e.to_string())?;
- tx.execute("DELETE FROM connection_secrets WHERE connection_id LIKE 'ai_config.%'", [])
- .map_err(|e| e.to_string())?;
+fn preserve_tunnel_profile_local_paths(remote: &mut TransportLayerConfig, local: &TransportLayerConfig) {
+ if let (TransportLayerConfig::Ssh(remote), TransportLayerConfig::Ssh(local)) = (remote, local) {
+ if remote.key_path.is_empty() {
+ remote.key_path.clone_from(&local.key_path);
+ }
+ if remote.ssh_agent_sock_path.is_empty() {
+ remote.ssh_agent_sock_path.clone_from(&local.ssh_agent_sock_path);
+ }
+ }
+}
+
+fn apply_ai_configs_in_tx(
+ tx: &Transaction<'_>,
+ codec: &SecretCodec,
+ configs: &[AiConfigItem],
+ merge_existing: bool,
+) -> Result<(), String> {
+ let existing_configs = {
+ let mut statement = tx.prepare("SELECT id, config_json FROM ai_configs").map_err(|error| error.to_string())?;
+ let rows = statement
+ .query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))
+ .map_err(|error| error.to_string())?
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|error| error.to_string())?;
+ let mut existing = HashMap::with_capacity(rows.len());
+ for (id, json) in rows {
+ let config: AiConfig = serde_json::from_str(&json).map_err(|error| error.to_string())?;
+ existing.insert(id, config);
+ }
+ existing
+ };
+ if !merge_existing {
+ tx.execute("DELETE FROM ai_configs", []).map_err(|e| e.to_string())?;
+ tx.execute("DELETE FROM ai_config", []).map_err(|e| e.to_string())?;
+ tx.execute("DELETE FROM ai_provider_configs", []).map_err(|e| e.to_string())?;
+ tx.execute("DELETE FROM connection_secrets WHERE connection_id LIKE 'ai_config.%'", [])
+ .map_err(|e| e.to_string())?;
+ }
for item in configs {
- let (sanitized, secrets) = split_ai_config_secrets(&item.config)?;
+ if merge_existing {
+ tx.execute("DELETE FROM connection_secrets WHERE connection_id = ?1", [format!("ai_config.{}", item.id)])
+ .map_err(|e| e.to_string())?;
+ if item.is_default {
+ tx.execute("UPDATE ai_configs SET is_default = 0", []).map_err(|e| e.to_string())?;
+ }
+ }
+ let mut config = item.config.clone();
+ clear_ai_config_device_paths(&mut config);
+ let local = existing_configs.get(&item.id).or_else(|| {
+ let mut matching_provider =
+ existing_configs.values().filter(|local| local.provider.as_str() == config.provider.as_str());
+ let candidate = matching_provider.next()?;
+ matching_provider.next().is_none().then_some(candidate)
+ });
+ if let Some(local) = local {
+ preserve_ai_config_device_paths(&mut config, local);
+ }
+ let (sanitized, secrets) = split_ai_config_secrets(&config)?;
let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
let models_json = serde_json::to_string(&sanitized.models).map_err(|e| e.to_string())?;
tx.execute(
@@ -8087,6 +8213,39 @@ fn apply_ai_configs_in_tx(tx: &Transaction<'_>, codec: &SecretCodec, configs: &[
Ok(())
}
+pub(crate) fn clear_ai_config_device_paths(config: &mut AiConfig) {
+ config.codex_cli_path = None;
+ config.claude_code_cli_path = None;
+ config.pi_agent_cli_path = None;
+ config.opencode_cli_path = None;
+ config.cursor_cli_path = None;
+ config.grok_cli_path = None;
+ config.codebuddy_cli_path = None;
+ config.qoder_cli_path = None;
+}
+
+fn preserve_ai_config_device_paths(remote: &mut AiConfig, local: &AiConfig) {
+ match (&remote.provider, &local.provider) {
+ (AiProvider::CodexCli, AiProvider::CodexCli) => remote.codex_cli_path.clone_from(&local.codex_cli_path),
+ (AiProvider::ClaudeCodeCli, AiProvider::ClaudeCodeCli) => {
+ remote.claude_code_cli_path.clone_from(&local.claude_code_cli_path)
+ }
+ (AiProvider::PiAgentCli, AiProvider::PiAgentCli) => {
+ remote.pi_agent_cli_path.clone_from(&local.pi_agent_cli_path)
+ }
+ (AiProvider::OpenCodeCli, AiProvider::OpenCodeCli) => {
+ remote.opencode_cli_path.clone_from(&local.opencode_cli_path)
+ }
+ (AiProvider::CursorCli, AiProvider::CursorCli) => remote.cursor_cli_path.clone_from(&local.cursor_cli_path),
+ (AiProvider::GrokCli, AiProvider::GrokCli) => remote.grok_cli_path.clone_from(&local.grok_cli_path),
+ (AiProvider::CodeBuddyCli, AiProvider::CodeBuddyCli) => {
+ remote.codebuddy_cli_path.clone_from(&local.codebuddy_cli_path)
+ }
+ (AiProvider::QoderCli, AiProvider::QoderCli) => remote.qoder_cli_path.clone_from(&local.qoder_cli_path),
+ _ => {}
+ }
+}
+
fn update_app_settings_key_in_tx(tx: &Transaction<'_>, key: &str, value: serde_json::Value) -> Result<(), String> {
let current: Option<String> = tx
.query_row("SELECT settings_json FROM app_settings WHERE id = 1", [], |row| row.get(0))
@@ -8107,7 +8266,27 @@ fn update_app_settings_key_in_tx(tx: &Transaction<'_>, key: &str, value: serde_j
.map_err(|e| e.to_string())
}
-fn apply_desktop_settings_in_tx(tx: &Transaction<'_>, settings: &DesktopSettings) -> Result<(), String> {
+fn merge_json_object_fields(
+ local: serde_json::Value,
+ remote: serde_json::Value,
+ selected_keys: Option<&[String]>,
+) -> serde_json::Value {
+ let Some(remote) = remote.as_object() else { return remote };
+ let mut merged = local.as_object().cloned().unwrap_or_default();
+ for (key, value) in remote {
+ if selected_keys.is_some_and(|keys| !keys.iter().any(|selected| selected == key)) {
+ continue;
+ }
+ merged.insert(key.clone(), value.clone());
+ }
+ serde_json::Value::Object(merged)
+}
+
+fn apply_desktop_settings_in_tx(
+ tx: &Transaction<'_>,
+ settings: &DesktopSettings,
+ selected_keys: Option<&[String]>,
+) -> Result<(), String> {
let mut values = serde_json::Map::new();
values.insert("show_tray_icon".to_string(), serde_json::Value::Bool(settings.show_tray_icon));
values.insert("icon_theme".to_string(), serde_json::to_value(settings.icon_theme).map_err(|e| e.to_string())?);
@@ -8158,6 +8337,9 @@ fn apply_desktop_settings_in_tx(tx: &Transaction<'_>, settings: &DesktopSettings
.transpose()?
.unwrap_or_default();
for (key, value) in values {
+ if selected_keys.is_some_and(|keys| !keys.iter().any(|selected| selected == &key)) {
+ continue;
+ }
merged.insert(key, value);
}
tx.execute(
@@ -8168,19 +8350,34 @@ fn apply_desktop_settings_in_tx(tx: &Transaction<'_>, settings: &DesktopSettings
.map_err(|e| e.to_string())
}
-fn apply_saved_sql_in_tx(tx: &Transaction<'_>, library: &SavedSqlLibrary) -> Result<(), String> {
- tx.execute("DELETE FROM saved_sql_files", []).map_err(|e| e.to_string())?;
- tx.execute("DELETE FROM saved_sql_folders", []).map_err(|e| e.to_string())?;
+fn apply_saved_sql_in_tx(tx: &Transaction<'_>, library: &SavedSqlLibrary, merge_existing: bool) -> Result<(), String> {
+ let mut folder_ids = HashSet::with_capacity(library.folders.len());
+ for folder in &library.folders {
+ if !folder_ids.insert(folder.id.as_str()) {
+ return Err(format!("duplicate saved SQL folder id: {}", folder.id));
+ }
+ }
+ let mut file_ids = HashSet::with_capacity(library.files.len());
+ for file in &library.files {
+ if !file_ids.insert(file.id.as_str()) {
+ return Err(format!("duplicate saved SQL file id: {}", file.id));
+ }
+ }
+
+ if !merge_existing {
+ tx.execute("DELETE FROM saved_sql_files", []).map_err(|e| e.to_string())?;
+ tx.execute("DELETE FROM saved_sql_folders", []).map_err(|e| e.to_string())?;
+ }
for folder in &library.folders {
tx.execute(
- "INSERT INTO saved_sql_folders (id, connection_id, parent_folder_id, name, order_index, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
+ "INSERT OR REPLACE INTO saved_sql_folders (id, connection_id, parent_folder_id, name, order_index, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
params![folder.id, folder.connection_id, folder.parent_folder_id, folder.name, folder.order_index, folder.created_at, folder.updated_at],
)
.map_err(|e| e.to_string())?;
}
for file in &library.files {
tx.execute(
- "INSERT INTO saved_sql_files (id, connection_id, folder_id, name, database_name, catalog_name, schema_name, sql_text, order_index, open_count, opened_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ "INSERT OR REPLACE INTO saved_sql_files (id, connection_id, folder_id, name, database_name, catalog_name, schema_name, sql_text, order_index, open_count, opened_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
params![file.id, file.connection_id, file.folder_id, file.name, file.database, file.catalog, file.schema, file.sql, file.order_index, file.open_count, file.opened_at, file.created_at, file.updated_at],
)
.map_err(|e| e.to_string())?;
@@ -13402,10 +13599,12 @@ mod tests {
incoming.url_params = Some("applicationName=dbx&sslmode=require".to_string());
let plan = SyncImportPlan {
connections: vec![incoming],
+ merge_connections: false,
tunnel_profiles: Some(Vec::new()),
tunnel_secret_profiles: None,
+ merge_tunnel_profiles: false,
sidebar_layout: None,
- pinned_tree_node_ids: Vec::new(),
+ pinned_tree_node_ids: Some(Vec::new()),
saved_sql: SavedSqlLibrary {
folders: vec![
SavedSqlFolder {
@@ -13429,12 +13628,19 @@ mod tests {
],
files: Vec::new(),
},
+ merge_saved_sql: false,
desktop_settings: settings,
+ desktop_settings_keys: None,
editor_settings: None,
+ merge_editor_settings: false,
+ editor_settings_keys: None,
connection_secrets: None,
+ connection_secret_ids: None,
+ preserve_local_connection_strings: Vec::new(),
preserve_plugin_secrets: false,
sync_credentials: None,
ai_configs: None,
+ merge_ai_configs: false,
};
assert!(storage.apply_sync_import_transaction(plan).await.is_err());
let connections = storage.load_connections().await.unwrap();
diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rs
index 90c29c33a7..ac93da5ed1 100644
--- a/crates/dbx-web/src/main.rs
+++ b/crates/dbx-web/src/main.rs
@@ -1337,6 +1337,8 @@ async fn serve() {
post(routes::cloud_sync::forget_webdav_sync_secrets_passphrase),
)
.route("/cloud-sync/webdav/upload", post(routes::cloud_sync::webdav_sync_upload))
+ .route("/cloud-sync/catalog/local", post(routes::cloud_sync::cloud_sync_local_catalog))
+ .route("/cloud-sync/webdav/inspect", post(routes::cloud_sync::webdav_sync_inspect))
.route("/cloud-sync/webdav/download", post(routes::cloud_sync::webdav_sync_download))
.route("/cloud-sync/snippet/test", post(routes::cloud_sync::snippet_sync_test))
.route("/cloud-sync/snippet/token-status", post(routes::cloud_sync::snippet_token_status))
@@ -1346,6 +1348,7 @@ async fn serve() {
.route("/cloud-sync/snippet/save-id", post(routes::cloud_sync::save_snippet_sync_id))
.route("/cloud-sync/snippet/retry-legacy-cleanup", post(routes::cloud_sync::retry_snippet_legacy_cleanup))
.route("/cloud-sync/snippet/upload", post(routes::cloud_sync::snippet_sync_upload))
+ .route("/cloud-sync/snippet/inspect", post(routes::cloud_sync::snippet_sync_inspect))
.route("/cloud-sync/snippet/download", post(routes::cloud_sync::snippet_sync_download));
// Do not expose DuckDB-only handlers from builds that omit DuckDB sidecar support.
diff --git a/crates/dbx-web/src/routes/cloud_sync.rs b/crates/dbx-web/src/routes/cloud_sync.rs
index 8a55f1cf80..766f69dc1d 100644
--- a/crates/dbx-web/src/routes/cloud_sync.rs
+++ b/crates/dbx-web/src/routes/cloud_sync.rs
@@ -3,15 +3,16 @@ use std::sync::Arc;
use axum::extract::State;
use axum::Json;
use dbx_core::cloud_sync::{
- apply_sync_snapshot, build_sync_snapshot_with_options, finalize_snippet_migration, forget_snippet_token,
- forget_webdav_password, forget_webdav_sync_secrets_passphrase as core_forget_webdav_sync_secrets_passphrase,
- resolve_snippet_token, resolve_webdav_password, resolve_webdav_sync_secrets_passphrase,
- retry_pending_snippet_cleanup, save_snippet_sync_id_for_instance as core_save_snippet_sync_id, save_snippet_token,
- save_webdav_password, save_webdav_sync_secrets_preference as core_save_webdav_sync_secrets_preference,
- snippet_saved_token_status, snippet_sync_settings_for_instance as core_snippet_sync_settings,
- webdav_saved_password_status, webdav_sync_secrets_status as core_webdav_sync_secrets_status, ApplySnapshotOptions,
- ApplySnapshotSummary, SnippetProvider, SnippetSyncClient, SnippetSyncConfig, SnippetSyncSettings,
- SnippetSyncSummary, SnippetTokenStatus, WebDavClient, WebDavConfig, WebDavPasswordStatus, WebDavSyncSecretsStatus,
+ apply_sync_snapshot_with_selection, build_sync_snapshot_with_selection, describe_local_sync_state,
+ describe_sync_snapshot, finalize_snippet_migration, forget_snippet_token, forget_webdav_password,
+ forget_webdav_sync_secrets_passphrase as core_forget_webdav_sync_secrets_passphrase, resolve_snippet_token,
+ resolve_webdav_password, resolve_webdav_sync_secrets_passphrase, retry_pending_snippet_cleanup,
+ save_snippet_sync_id_for_instance as core_save_snippet_sync_id, save_snippet_token, save_webdav_password,
+ save_webdav_sync_secrets_preference as core_save_webdav_sync_secrets_preference, snippet_saved_token_status,
+ snippet_sync_settings_for_instance as core_snippet_sync_settings, webdav_saved_password_status,
+ webdav_sync_secrets_status as core_webdav_sync_secrets_status, ApplySnapshotOptions, ApplySnapshotSummary,
+ SnippetProvider, SnippetSyncClient, SnippetSyncConfig, SnippetSyncSettings, SnippetSyncSummary, SnippetTokenStatus,
+ SyncSelection, SyncSnapshotCatalog, WebDavClient, WebDavConfig, WebDavPasswordStatus, WebDavSyncSecretsStatus,
WebDavSyncSummary,
};
use dbx_core::storage::DesktopSettings;
@@ -60,6 +61,8 @@ pub struct WebDavUploadRequest {
/// Explicit opt-in for exporting credentials.
#[serde(default)]
pub include_secrets: bool,
+ #[serde(default)]
+ pub selection: Option<SyncSelection>,
}
#[derive(Debug, Clone, Deserialize)]
@@ -72,6 +75,21 @@ pub struct WebDavDownloadRequest {
/// restore behavior.
#[serde(default = "default_restore_secrets")]
pub restore_secrets: bool,
+ #[serde(default)]
+ pub selection: Option<SyncSelection>,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct WebDavInspectRequest {
+ pub config: WebDavConfig,
+ pub secrets_passphrase: Option<String>,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LocalCatalogRequest {
+ pub editor_settings: Option<serde_json::Value>,
}
fn default_restore_secrets() -> bool {
@@ -107,6 +125,8 @@ pub struct SnippetUploadRequest {
#[serde(default)]
pub include_secrets: bool,
pub secrets_passphrase: Option<String>,
+ #[serde(default)]
+ pub selection: Option<SyncSelection>,
}
#[derive(Debug, Clone, Deserialize)]
@@ -117,6 +137,16 @@ pub struct SnippetDownloadRequest {
#[serde(default)]
pub restore_secrets: bool,
pub secrets_passphrase: Option<String>,
+ #[serde(default)]
+ pub selection: Option<SyncSelection>,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SnippetInspectRequest {
+ pub config: SnippetSyncConfig,
+ pub snippet_passphrase: Option<String>,
+ pub secrets_passphrase: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
@@ -202,7 +232,7 @@ pub async fn webdav_sync_upload(
None
};
let passphrase = explicit_passphrase.or(saved_passphrase.as_deref());
- let snapshot = build_sync_snapshot_with_options(
+ let snapshot = build_sync_snapshot_with_selection(
&state.app.storage,
env!("CARGO_PKG_VERSION"),
req.editor_settings,
@@ -213,12 +243,39 @@ pub async fn webdav_sync_upload(
include_tunnel_secrets: req.include_secrets,
include_plugin_secrets: req.include_secrets,
},
+ req.selection.as_ref(),
+ Some(&state.app.plugins),
)
.await
.map_err(AppError::from)?;
WebDavClient::new(req.config).put_snapshot(&snapshot).await.map(Json).map_err(AppError::from)
}
+pub async fn cloud_sync_local_catalog(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<LocalCatalogRequest>,
+) -> Result<Json<SyncSnapshotCatalog>, AppError> {
+ describe_local_sync_state(&state.app.storage, req.editor_settings, Some(&state.app.plugins))
+ .await
+ .map(Json)
+ .map_err(AppError::from)
+}
+
+pub async fn webdav_sync_inspect(
+ State(state): State<Arc<WebState>>,
+ Json(mut req): Json<WebDavInspectRequest>,
+) -> Result<Json<SyncSnapshotCatalog>, AppError> {
+ resolve_webdav_password(&state.app.storage, &mut req.config).await.map_err(AppError::from)?;
+ let (snapshot, _) = WebDavClient::new(req.config).get_snapshot().await.map_err(AppError::from)?;
+ let explicit = req.secrets_passphrase.as_deref().map(str::trim).filter(|value| !value.is_empty());
+ let saved = if explicit.is_none() {
+ resolve_webdav_sync_secrets_passphrase(&state.app.storage).await.map_err(AppError::from)?
+ } else {
+ None
+ };
+ describe_sync_snapshot(&snapshot, explicit.or(saved.as_deref())).map(Json).map_err(AppError::from)
+}
+
pub async fn webdav_sync_download(
State(state): State<Arc<WebState>>,
Json(mut req): Json<WebDavDownloadRequest>,
@@ -231,20 +288,22 @@ pub async fn webdav_sync_download(
} else {
resolve_webdav_sync_secrets_passphrase(&state.app.storage).await.map_err(AppError::from)?
};
- let apply_summary = apply_sync_snapshot(
+ let apply_summary = apply_sync_snapshot_with_selection(
&state.app.storage,
&snapshot,
ApplySnapshotOptions {
secrets_passphrase: explicit_passphrase.or(saved_passphrase.as_deref()),
restore_secrets: req.restore_secrets,
},
+ req.selection.as_ref(),
+ Some(&state.app.plugins),
)
.await
.map_err(AppError::from)?;
Ok(Json(WebDavDownloadResult {
summary,
- editor_settings: snapshot.editor_settings,
- desktop_settings: snapshot.desktop_settings,
+ editor_settings: state.app.storage.load_editor_settings().await.map_err(AppError::from)?,
+ desktop_settings: state.app.storage.load_desktop_settings().await.map_err(AppError::from)?,
apply_summary,
}))
}
@@ -328,7 +387,7 @@ pub async fn snippet_sync_upload(
None
};
let include_secrets = req.include_secrets;
- let snapshot = build_sync_snapshot_with_options(
+ let snapshot = build_sync_snapshot_with_selection(
&state.app.storage,
env!("CARGO_PKG_VERSION"),
req.editor_settings,
@@ -339,6 +398,8 @@ pub async fn snippet_sync_upload(
include_tunnel_secrets: include_secrets,
include_plugin_secrets: include_secrets,
},
+ req.selection.as_ref(),
+ Some(&state.app.plugins),
)
.await
.map_err(AppError::from)?;
@@ -361,24 +422,45 @@ pub async fn snippet_sync_download(
.get_snapshot(req.snippet_passphrase.as_deref())
.await
.map_err(AppError::from)?;
- let apply_summary = apply_sync_snapshot(
+ let apply_summary = apply_sync_snapshot_with_selection(
&state.app.storage,
&snapshot,
ApplySnapshotOptions {
secrets_passphrase: req.secrets_passphrase.as_deref(),
restore_secrets: req.restore_secrets,
},
+ req.selection.as_ref(),
+ Some(&state.app.plugins),
)
.await
.map_err(AppError::from)?;
Ok(Json(SnippetDownloadResult {
summary,
- editor_settings: snapshot.editor_settings,
- desktop_settings: snapshot.desktop_settings,
+ editor_settings: state.app.storage.load_editor_settings().await.map_err(AppError::from)?,
+ desktop_settings: state.app.storage.load_desktop_settings().await.map_err(AppError::from)?,
apply_summary,
}))
}
+pub async fn snippet_sync_inspect(
+ State(state): State<Arc<WebState>>,
+ Json(mut req): Json<SnippetInspectRequest>,
+) -> Result<Json<SyncSnapshotCatalog>, AppError> {
+ resolve_snippet_token(&state.app.storage, &mut req.config).await.map_err(AppError::from)?;
+ let (snapshot, _) = SnippetSyncClient::new(req.config)
+ .map_err(AppError::from)?
+ .get_snapshot(req.snippet_passphrase.as_deref())
+ .await
+ .map_err(AppError::from)?;
+ let explicit = req.secrets_passphrase.as_deref().map(str::trim).filter(|value| !value.is_empty());
+ let saved = if explicit.is_none() {
+ resolve_webdav_sync_secrets_passphrase(&state.app.storage).await.map_err(AppError::from)?
+ } else {
+ None
+ };
+ describe_sync_snapshot(&snapshot, explicit.or(saved.as_deref())).map(Json).map_err(AppError::from)
+}
+
#[cfg(test)]
mod tests {
use std::sync::Arc;
diff --git a/src-tauri/src/commands/cloud_sync.rs b/src-tauri/src/commands/cloud_sync.rs
index 4d8f4a2e40..a1c92b7e18 100644
--- a/src-tauri/src/commands/cloud_sync.rs
+++ b/src-tauri/src/commands/cloud_sync.rs
@@ -1,15 +1,16 @@
use std::sync::Arc;
use dbx_core::cloud_sync::{
- apply_sync_snapshot, build_sync_snapshot_with_options, finalize_snippet_migration, forget_snippet_token,
- forget_webdav_password, forget_webdav_sync_secrets_passphrase as core_forget_webdav_sync_secrets_passphrase,
- resolve_snippet_token, resolve_webdav_password, resolve_webdav_sync_secrets_passphrase,
- retry_pending_snippet_cleanup, save_snippet_sync_id_for_instance as core_save_snippet_sync_id, save_snippet_token,
- save_webdav_password, save_webdav_sync_secrets_preference as core_save_webdav_sync_secrets_preference,
- snippet_saved_token_status, snippet_sync_settings_for_instance as core_snippet_sync_settings,
- webdav_saved_password_status, webdav_sync_secrets_status as core_webdav_sync_secrets_status, ApplySnapshotOptions,
- ApplySnapshotSummary, SnippetProvider, SnippetSyncClient, SnippetSyncConfig, SnippetSyncSettings,
- SnippetSyncSummary, SnippetTokenStatus, SyncExportOptions, WebDavClient, WebDavConfig, WebDavPasswordStatus,
+ apply_sync_snapshot_with_selection, build_sync_snapshot_with_selection, describe_local_sync_state,
+ describe_sync_snapshot, finalize_snippet_migration, forget_snippet_token, forget_webdav_password,
+ forget_webdav_sync_secrets_passphrase as core_forget_webdav_sync_secrets_passphrase, resolve_snippet_token,
+ resolve_webdav_password, resolve_webdav_sync_secrets_passphrase, retry_pending_snippet_cleanup,
+ save_snippet_sync_id_for_instance as core_save_snippet_sync_id, save_snippet_token, save_webdav_password,
+ save_webdav_sync_secrets_preference as core_save_webdav_sync_secrets_preference, snippet_saved_token_status,
+ snippet_sync_settings_for_instance as core_snippet_sync_settings, webdav_saved_password_status,
+ webdav_sync_secrets_status as core_webdav_sync_secrets_status, ApplySnapshotOptions, ApplySnapshotSummary,
+ SnippetProvider, SnippetSyncClient, SnippetSyncConfig, SnippetSyncSettings, SnippetSyncSummary, SnippetTokenStatus,
+ SyncExportOptions, SyncSelection, SyncSnapshotCatalog, WebDavClient, WebDavConfig, WebDavPasswordStatus,
WebDavSyncSecretsStatus, WebDavSyncSummary,
};
use dbx_core::storage::DesktopSettings;
@@ -121,6 +122,7 @@ pub async fn webdav_sync_upload(
editor_settings: Option<serde_json::Value>,
secrets_passphrase: Option<String>,
include_secrets: bool,
+ selection: Option<SyncSelection>,
) -> Result<WebDavSyncSummary, String> {
resolve_webdav_password(&state.storage, &mut config).await?;
let explicit_passphrase = secrets_passphrase.as_deref().and_then(|value| {
@@ -133,7 +135,7 @@ pub async fn webdav_sync_upload(
None
};
let passphrase = explicit_passphrase.or(saved_passphrase.as_deref());
- let snapshot = build_sync_snapshot_with_options(
+ let snapshot = build_sync_snapshot_with_selection(
&state.storage,
env!("CARGO_PKG_VERSION"),
editor_settings,
@@ -144,6 +146,8 @@ pub async fn webdav_sync_upload(
include_tunnel_secrets: include_secrets,
include_plugin_secrets: include_secrets,
},
+ selection.as_ref(),
+ Some(&state.plugins),
)
.await?;
WebDavClient::new(config).put_snapshot(&snapshot).await
@@ -155,6 +159,7 @@ pub async fn webdav_sync_download(
mut config: WebDavConfig,
secrets_passphrase: Option<String>,
restore_secrets: bool,
+ selection: Option<SyncSelection>,
) -> Result<WebDavDownloadResult, String> {
resolve_webdav_password(&state.storage, &mut config).await?;
let (snapshot, summary) = WebDavClient::new(config).get_snapshot().await?;
@@ -164,23 +169,46 @@ pub async fn webdav_sync_download(
} else {
resolve_webdav_sync_secrets_passphrase(&state.storage).await?
};
- let apply_summary = apply_sync_snapshot(
+ let apply_summary = apply_sync_snapshot_with_selection(
&state.storage,
&snapshot,
ApplySnapshotOptions {
secrets_passphrase: explicit_passphrase.or(saved_passphrase.as_deref()),
restore_secrets,
},
+ selection.as_ref(),
+ Some(&state.plugins),
)
.await?;
Ok(WebDavDownloadResult {
summary,
- editor_settings: snapshot.editor_settings,
- desktop_settings: snapshot.desktop_settings,
+ editor_settings: state.storage.load_editor_settings().await?,
+ desktop_settings: state.storage.load_desktop_settings().await?,
apply_summary,
})
}
+#[tauri::command]
+pub async fn cloud_sync_local_catalog(
+ state: State<'_, Arc<AppState>>,
+ editor_settings: Option<serde_json::Value>,
+) -> Result<SyncSnapshotCatalog, String> {
+ describe_local_sync_state(&state.storage, editor_settings, Some(&state.plugins)).await
+}
+
+#[tauri::command]
+pub async fn webdav_sync_inspect(
+ state: State<'_, Arc<AppState>>,
+ mut config: WebDavConfig,
+ secrets_passphrase: Option<String>,
+) -> Result<SyncSnapshotCatalog, String> {
+ resolve_webdav_password(&state.storage, &mut config).await?;
+ let (snapshot, _) = WebDavClient::new(config).get_snapshot().await?;
+ let explicit = secrets_passphrase.as_deref().map(str::trim).filter(|value| !value.is_empty());
+ let saved = if explicit.is_none() { resolve_webdav_sync_secrets_passphrase(&state.storage).await? } else { None };
+ describe_sync_snapshot(&snapshot, explicit.or(saved.as_deref()))
+}
+
#[tauri::command]
pub async fn snippet_sync_test(state: State<'_, Arc<AppState>>, mut config: SnippetSyncConfig) -> Result<(), String> {
resolve_snippet_token(&state.storage, &mut config).await?;
@@ -250,6 +278,7 @@ pub async fn snippet_sync_upload(
snippet_passphrase: Option<String>,
include_secrets: bool,
secrets_passphrase: Option<String>,
+ selection: Option<SyncSelection>,
) -> Result<SnippetSyncSummary, String> {
resolve_snippet_token(&state.storage, &mut config).await?;
let secrets_passphrase = if include_secrets {
@@ -263,7 +292,7 @@ pub async fn snippet_sync_upload(
} else {
None
};
- let snapshot = build_sync_snapshot_with_options(
+ let snapshot = build_sync_snapshot_with_selection(
&state.storage,
env!("CARGO_PKG_VERSION"),
editor_settings,
@@ -274,6 +303,8 @@ pub async fn snippet_sync_upload(
include_tunnel_secrets: include_secrets,
include_plugin_secrets: include_secrets,
},
+ selection.as_ref(),
+ Some(&state.plugins),
)
.await?;
let client = SnippetSyncClient::new(config)?;
@@ -289,23 +320,40 @@ pub async fn snippet_sync_download(
snippet_passphrase: Option<String>,
restore_secrets: bool,
secrets_passphrase: Option<String>,
+ selection: Option<SyncSelection>,
) -> Result<SnippetDownloadResult, String> {
resolve_snippet_token(&state.storage, &mut config).await?;
let (snapshot, summary) = SnippetSyncClient::new(config)?.get_snapshot(snippet_passphrase.as_deref()).await?;
- let apply_summary = apply_sync_snapshot(
+ let apply_summary = apply_sync_snapshot_with_selection(
&state.storage,
&snapshot,
ApplySnapshotOptions { secrets_passphrase: secrets_passphrase.as_deref(), restore_secrets },
+ selection.as_ref(),
+ Some(&state.plugins),
)
.await?;
Ok(SnippetDownloadResult {
summary,
- editor_settings: snapshot.editor_settings,
- desktop_settings: snapshot.desktop_settings,
+ editor_settings: state.storage.load_editor_settings().await?,
+ desktop_settings: state.storage.load_desktop_settings().await?,
apply_summary,
})
}
+#[tauri::command]
+pub async fn snippet_sync_inspect(
+ state: State<'_, Arc<AppState>>,
+ mut config: SnippetSyncConfig,
+ snippet_passphrase: Option<String>,
+ secrets_passphrase: Option<String>,
+) -> Result<SyncSnapshotCatalog, String> {
+ resolve_snippet_token(&state.storage, &mut config).await?;
+ let (snapshot, _) = SnippetSyncClient::new(config)?.get_snapshot(snippet_passphrase.as_deref()).await?;
+ let explicit = secrets_passphrase.as_deref().map(str::trim).filter(|value| !value.is_empty());
+ let saved = if explicit.is_none() { resolve_webdav_sync_secrets_passphrase(&state.storage).await? } else { None };
+ describe_sync_snapshot(&snapshot, explicit.or(saved.as_deref()))
+}
+
#[cfg(test)]
mod tests {
use std::sync::Arc;
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 75086af559..f0008b6dee 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1902,6 +1902,8 @@ pub fn run() {
commands::cloud_sync::forget_webdav_sync_secrets_passphrase,
commands::cloud_sync::webdav_sync_upload,
commands::cloud_sync::webdav_sync_download,
+ commands::cloud_sync::webdav_sync_inspect,
+ commands::cloud_sync::cloud_sync_local_catalog,
commands::cloud_sync::snippet_sync_test,
commands::cloud_sync::snippet_token_status,
commands::cloud_sync::save_snippet_saved_token,
@@ -1911,6 +1913,7 @@ pub fn run() {
commands::cloud_sync::retry_snippet_legacy_cleanup,
commands::cloud_sync::snippet_sync_upload,
commands::cloud_sync::snippet_sync_download,
+ commands::cloud_sync::snippet_sync_inspect,
commands::connection::test_connection,
commands::connection::test_connection_with_info,
commands::connection::test_ssh_tunnel,