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

This commit is contained in:
_Mr丶s ゛😁® authored and GitHub committed 2026-09-28 21:23:15 +08:00
1 parent e432304dbc
commit a75d343666
23 files changed
+2427 -216

No files matched your search

@@ -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>
@@ -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 -->
@@ -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,
+30
View File
@@ -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",
+30
View File
@@ -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",
+30
View File
@@ -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",
+30
View File
@@ -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: "ユーザー名",
+30
View File
@@ -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: "사용자 이름",
+30
View File
@@ -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",
+30
View File
@@ -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: "Имя пользователя",
+30
View File
@@ -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: "用户名",
+30
View File
@@ -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: "使用者名稱",
@@ -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);
+7
View File
@@ -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,
+23 -5
View File
@@ -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,
});
}
+69 -6
View File
@@ -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[]> {
@@ -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"));
}