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。

fix(updater): guard installs during active tasks

zipg0d1d6e18a466
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index 745ed0cbd5..e3ceec281d 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -19,6 +19,7 @@ import { useSavedSqlStore } from "@/stores/savedSqlStore";
import { useToast } from "@/composables/useToast";
import { useTheme } from "@/composables/useTheme";
import { useAppUpdater } from "@/composables/useAppUpdater";
+import { useExportTracker } from "@/composables/useExportTracker";
import { useFileDrop } from "@/composables/useFileDrop";
import { usePanelResize } from "@/composables/usePanelResize";
import { useDatabaseOptions } from "@/composables/useDatabaseOptions";
@@ -84,6 +85,7 @@ import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStor
import { apiUrl, webPath } from "@/lib/common/webPath";
import { APP_FONT_SANS_CSS_VAR, DEFAULT_UI_FONT_FAMILY } from "@/lib/app/appFonts";
import { rankSavedSqlHistory } from "@/lib/savedSql/savedSqlHistory";
+import { countActiveUpdateBlockingTasks } from "@/lib/app/appUpdateTaskGuard";
import { initSavedSqlEditorPositions } from "@/lib/app/savedSqlEditorPosition";
import { isSchemaAware, isSingleDatabase, usesTreeSchemaMode } from "@/lib/database/databaseFeatureSupport";
import { codeMirrorSqlDialect, connectionUsesDatabaseObjectTreeMode, effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";
@@ -123,7 +125,29 @@ const savedSqlStore = useSavedSqlStore();
connectionStore.setBeforeConnectHandler((config) => ensureJdbcxRuntimeDrivers(config, api).then(() => undefined));
const { message: toastMessage, visible: toastVisible, toast } = useToast();
const { isDark, themeMode, applyTheme, setThemeMode } = useTheme();
-const { checkingUpdates, updateInfo, updateCheckMessage, showUpdateDialog, isDownloadingUpdate, downloadProgress, updateReady, hasUpdateAvailable, openUrl, checkUpdates, openLatestRelease, downloadAndInstallUpdate, restartApp } = useAppUpdater();
+const { activeCount: activeBackgroundTaskCount } = useExportTracker();
+const trackedUpdateTaskCount = computed(() => countActiveUpdateBlockingTasks(activeBackgroundTaskCount.value, queryStore.tabs));
+const {
+ checkingUpdates,
+ updateInfo,
+ updateCheckMessage,
+ showUpdateDialog,
+ isDownloadingUpdate,
+ downloadProgress,
+ updateDownloaded,
+ isInstallingUpdate,
+ updateReady,
+ activeTaskCount: activeUpdateTaskCount,
+ hasUpdateAvailable,
+ openUrl,
+ checkUpdates,
+ openLatestRelease,
+ downloadAndInstallUpdate,
+ installDownloadedUpdate,
+ restartApp,
+} = useAppUpdater({
+ getActiveTaskCount: () => trackedUpdateTaskCount.value,
+});
const { setupFileDrop } = useFileDrop();
const isDesktop = isTauriRuntime();
@@ -2270,9 +2294,13 @@ onUnmounted(() => {
:update-check-message="updateCheckMessage"
:is-downloading-update="isDownloadingUpdate"
:download-progress="downloadProgress"
+ :update-downloaded="updateDownloaded"
+ :is-installing-update="isInstallingUpdate"
:update-ready="updateReady"
+ :active-task-count="activeUpdateTaskCount"
@open-latest-release="openLatestRelease"
@download-and-install="downloadAndInstallUpdate"
+ @install-downloaded="installDownloadedUpdate"
@restart="restartApp"
/>
<CloseActionPromptDialog v-if="isDesktop && showCloseActionPrompt" :open="showCloseActionPrompt" @update:open="handleCloseActionPromptOpenChange" @quit="chooseQuit" @minimize="chooseMinimize" />
diff --git a/apps/desktop/src/components/layout/UpdateDialog.spec.ts b/apps/desktop/src/components/layout/UpdateDialog.spec.ts
new file mode 100644
index 0000000000..298c86d11e
--- /dev/null
+++ b/apps/desktop/src/components/layout/UpdateDialog.spec.ts
@@ -0,0 +1,222 @@
+// @vitest-environment happy-dom
+
+import { createApp, defineComponent, h, nextTick, reactive, type App } from "vue";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import i18n from "@/i18n";
+import UpdateDialog from "@/components/layout/UpdateDialog.vue";
+
+vi.mock("@/lib/backend/tauriRuntime", () => ({
+ isTauriRuntime: () => true,
+}));
+
+const mountedApps: App[] = [];
+
+interface DialogState {
+ open: boolean;
+ isDownloadingUpdate: boolean;
+ downloadProgress: number;
+ updateDownloaded: boolean;
+ isInstallingUpdate: boolean;
+ updateReady: boolean;
+}
+
+async function flushDialog() {
+ await nextTick();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+async function mountDialog(activeTaskCount: number, initialState: Partial<DialogState> = {}, installDownloaded = vi.fn(async () => {})) {
+ const state = reactive<DialogState>({
+ open: true,
+ isDownloadingUpdate: false,
+ downloadProgress: 0,
+ updateDownloaded: false,
+ isInstallingUpdate: false,
+ updateReady: false,
+ ...initialState,
+ });
+ const downloadAndInstall = vi.fn();
+ const container = document.createElement("div");
+ document.body.append(container);
+ const app = createApp(
+ defineComponent({
+ setup() {
+ async function handleInstallDownloaded() {
+ state.isInstallingUpdate = true;
+ try {
+ await installDownloaded();
+ state.updateDownloaded = false;
+ state.updateReady = true;
+ } catch {
+ // The real updater reports the error but retains the downloaded package for retry.
+ } finally {
+ state.isInstallingUpdate = false;
+ }
+ }
+
+ return () =>
+ h(UpdateDialog, {
+ open: state.open,
+ "onUpdate:open": (value: boolean) => {
+ state.open = value;
+ },
+ updateInfo: {
+ current_version: "0.5.60",
+ latest_version: "0.5.61",
+ update_available: true,
+ portable_mode: false,
+ release_name: "DBX v0.5.61",
+ release_url: "https://github.com/t8y2/dbx/releases/tag/v0.5.61",
+ release_notes: "",
+ },
+ updateCheckMessage: "",
+ isDownloadingUpdate: state.isDownloadingUpdate,
+ downloadProgress: state.downloadProgress,
+ updateDownloaded: state.updateDownloaded,
+ isInstallingUpdate: state.isInstallingUpdate,
+ updateReady: state.updateReady,
+ activeTaskCount,
+ "onDownload-and-install": downloadAndInstall,
+ "onInstall-downloaded": handleInstallDownloaded,
+ });
+ },
+ }),
+ );
+ mountedApps.push(app);
+ app.use(i18n);
+ app.mount(container);
+ await flushDialog();
+
+ return { state, downloadAndInstall, installDownloaded };
+}
+
+function buttonWithText(text: string): HTMLButtonElement | undefined {
+ return Array.from(document.body.querySelectorAll("button")).find((button) => button.textContent?.includes(text));
+}
+
+function downloadButton(): HTMLButtonElement | undefined {
+ return buttonWithText("Download & Install");
+}
+
+function installDownloadedButton(): HTMLButtonElement | undefined {
+ return buttonWithText("Exit & Update");
+}
+
+async function pressEscape() {
+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }));
+ await flushDialog();
+}
+
+afterEach(() => {
+ for (const app of mountedApps.splice(0)) app.unmount();
+ document.body.innerHTML = "";
+});
+
+describe("UpdateDialog active task guard", () => {
+ it("shows the task warning and disables installation while work is running", async () => {
+ await mountDialog(2);
+
+ expect(document.body.querySelector('[role="alert"]')?.textContent).toContain("2");
+ expect(downloadButton()?.disabled).toBe(true);
+ });
+
+ it("allows installation after all tasks finish", async () => {
+ await mountDialog(0);
+
+ expect(document.body.querySelector('[role="alert"]')).toBeNull();
+ expect(downloadButton()?.disabled).toBe(false);
+ });
+
+ it("retains the downloaded update and enables installation only after tasks finish", async () => {
+ await mountDialog(1, { updateDownloaded: true, downloadProgress: 100 });
+
+ expect(downloadButton()).toBeUndefined();
+ expect(installDownloadedButton()?.disabled).toBe(true);
+
+ for (const app of mountedApps.splice(0)) app.unmount();
+ document.body.innerHTML = "";
+ await mountDialog(0, { updateDownloaded: true, downloadProgress: 100 });
+
+ expect(installDownloadedButton()?.disabled).toBe(false);
+ });
+});
+
+describe("UpdateDialog close protection", () => {
+ it("allows closing while a downloaded update is idle", async () => {
+ const { state } = await mountDialog(0, { updateDownloaded: true, downloadProgress: 100 });
+
+ expect(buttonWithText("Cancel")).toBeDefined();
+ expect(document.body.querySelector('[data-slot="dialog-close"]')).not.toBeNull();
+ await pressEscape();
+
+ expect(state.open).toBe(false);
+ });
+
+ it("prevents closing while installation is in progress", async () => {
+ const { state } = await mountDialog(0, { updateDownloaded: true, isInstallingUpdate: true });
+
+ expect(buttonWithText("Cancel")).toBeUndefined();
+ expect(document.body.querySelector('[data-slot="dialog-close"]')).toBeNull();
+ await pressEscape();
+
+ expect(state.open).toBe(true);
+ });
+
+ it("allows closing after installation rejects", async () => {
+ let rejectInstall!: (error: Error) => void;
+ const installDownloaded = vi.fn(
+ () =>
+ new Promise<void>((_resolve, reject) => {
+ rejectInstall = reject;
+ }),
+ );
+ const { state } = await mountDialog(0, { updateDownloaded: true }, installDownloaded);
+
+ installDownloadedButton()?.click();
+ await flushDialog();
+ await pressEscape();
+ expect(state.open).toBe(true);
+
+ rejectInstall(new Error("install failed"));
+ await flushDialog();
+ expect(buttonWithText("Cancel")).toBeDefined();
+ await pressEscape();
+
+ expect(state.open).toBe(false);
+ });
+
+ it("retries the retained download after reopening without downloading again", async () => {
+ const installDownloaded = vi.fn(async () => {
+ throw new Error("install failed");
+ });
+ const { state, downloadAndInstall } = await mountDialog(0, { updateDownloaded: true }, installDownloaded);
+
+ installDownloadedButton()?.click();
+ await flushDialog();
+ await pressEscape();
+ state.open = true;
+ await flushDialog();
+ installDownloadedButton()?.click();
+ await flushDialog();
+
+ expect(installDownloaded).toHaveBeenCalledTimes(2);
+ expect(downloadAndInstall).not.toHaveBeenCalled();
+ });
+
+ it("keeps the successful install flow protected", async () => {
+ const installDownloaded = vi.fn(async () => {});
+ const { state, downloadAndInstall } = await mountDialog(0, { updateDownloaded: true }, installDownloaded);
+
+ installDownloadedButton()?.click();
+ await flushDialog();
+
+ expect(state.updateDownloaded).toBe(false);
+ expect(state.updateReady).toBe(true);
+ expect(buttonWithText("Restart")).toBeDefined();
+ expect(buttonWithText("Cancel")).toBeUndefined();
+ await pressEscape();
+ expect(state.open).toBe(true);
+ expect(installDownloaded).toHaveBeenCalledOnce();
+ expect(downloadAndInstall).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/components/layout/UpdateDialog.vue b/apps/desktop/src/components/layout/UpdateDialog.vue
index f2e4f76c1b..93f658dda2 100644
--- a/apps/desktop/src/components/layout/UpdateDialog.vue
+++ b/apps/desktop/src/components/layout/UpdateDialog.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
-import { ref, watch } from "vue";
+import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
-import { Loader2 } from "@lucide/vue";
+import { AlertTriangle, Loader2 } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import type { UpdateInfo } from "@/lib/backend/api";
@@ -15,12 +15,16 @@ const props = defineProps<{
updateCheckMessage: string;
isDownloadingUpdate: boolean;
downloadProgress: number;
+ updateDownloaded: boolean;
+ isInstallingUpdate: boolean;
updateReady: boolean;
+ activeTaskCount: number;
}>();
const emit = defineEmits<{
"open-latest-release": [];
"download-and-install": [];
+ "install-downloaded": [];
restart: [];
}>();
@@ -28,6 +32,8 @@ const { t } = useI18n();
const isDesktop = isTauriRuntime();
const renderedNotes = ref("");
+// Keep a downloaded package retryable after install errors; only active transitions must trap the dialog.
+const isCloseBlocked = computed(() => props.isDownloadingUpdate || props.isInstallingUpdate || props.updateReady);
function handleReleaseNotesClick(event: MouseEvent) {
const target = event.target as HTMLElement;
@@ -62,14 +68,15 @@ watch(
<Dialog v-model:open="open">
<DialogContent
class="sm:max-w-[520px]"
+ :show-close-button="!isCloseBlocked"
@interact-outside="
(e: Event) => {
- if (isDownloadingUpdate || updateReady) e.preventDefault();
+ if (isCloseBlocked) e.preventDefault();
}
"
@escape-key-down="
(e: Event) => {
- if (isDownloadingUpdate || updateReady) e.preventDefault();
+ if (isCloseBlocked) e.preventDefault();
}
"
>
@@ -102,18 +109,27 @@ watch(
<p v-if="isDesktop && updateInfo?.update_available && updateInfo.portable_mode" class="text-xs text-muted-foreground">
{{ t("updates.portableManualUpdate") }}
</p>
+ <div v-if="canDownloadAndInstallUpdate(updateInfo, isDesktop) && activeTaskCount > 0" role="alert" class="flex items-start gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-300">
+ <AlertTriangle class="mt-0.5 h-4 w-4 shrink-0" />
+ <span>{{ t("updates.activeTasksBlockUpdate", { count: activeTaskCount }) }}</span>
+ </div>
</div>
<DialogFooter>
- <Button v-if="!isDownloadingUpdate && !updateReady" variant="outline" @click="open = false">{{ t("dangerDialog.cancel") }}</Button>
+ <Button v-if="!isCloseBlocked" variant="outline" @click="open = false">{{ t("dangerDialog.cancel") }}</Button>
<template v-if="updateInfo?.update_available">
<Button variant="outline" @click="emit('open-latest-release')">{{ t("updates.openRelease") }}</Button>
<template v-if="canDownloadAndInstallUpdate(updateInfo, isDesktop)">
- <Button v-if="updateReady" @click="emit('restart')">{{ t("updates.restart") }}</Button>
+ <Button v-if="updateReady" :disabled="activeTaskCount > 0" @click="emit('restart')">{{ t("updates.restart") }}</Button>
+ <Button v-else-if="isInstallingUpdate" disabled>
+ <Loader2 class="h-4 w-4 animate-spin" />
+ {{ t("updates.installing") }}
+ </Button>
<Button v-else-if="isDownloadingUpdate" disabled>
<Loader2 class="h-4 w-4 animate-spin" />
{{ t("updates.downloading", { progress: downloadProgress }) }}
</Button>
- <Button v-else @click="emit('download-and-install')">{{ t("updates.downloadAndInstall") }}</Button>
+ <Button v-else-if="updateDownloaded" :disabled="activeTaskCount > 0" @click="emit('install-downloaded')">{{ t("updates.exitAndUpdate") }}</Button>
+ <Button v-else :disabled="activeTaskCount > 0" @click="emit('download-and-install')">{{ t("updates.downloadAndInstall") }}</Button>
</template>
</template>
<Button v-else-if="updateCheckMessage" @click="emit('open-latest-release')">{{ t("updates.openRelease") }}</Button>
diff --git a/apps/desktop/src/composables/useAppUpdater.ts b/apps/desktop/src/composables/useAppUpdater.ts
index 385ff7819d..d6d65e1366 100644
--- a/apps/desktop/src/composables/useAppUpdater.ts
+++ b/apps/desktop/src/composables/useAppUpdater.ts
@@ -7,6 +7,12 @@ import { useSettingsStore } from "@/stores/settingsStore";
import type { UpdateDownloadSource as SettingsUpdateDownloadSource } from "@/stores/settingsStore";
import type { UpdateDownloadProgress } from "@/lib/backend/tauri";
import { currentLocale } from "@/i18n";
+import { shouldBlockAppUpdate } from "@/lib/app/appUpdateTaskGuard";
+import { downloadAndInstallUpdateWhenIdle, installDownloadedUpdateWhenIdle } from "@/lib/app/appUpdateInstallFlow";
+
+interface UseAppUpdaterOptions {
+ getActiveTaskCount?: () => number;
+}
export function shouldOpenUpdateDialog(options: { silent?: boolean }) {
return options.silent !== true;
@@ -45,7 +51,7 @@ export async function resolveUpdaterProxy(): Promise<string | undefined> {
}
}
-export function useAppUpdater() {
+export function useAppUpdater(options: UseAppUpdaterOptions = {}) {
const { t } = useI18n();
const { toast } = useToast();
const settingsStore = useSettingsStore();
@@ -56,7 +62,10 @@ export function useAppUpdater() {
const showUpdateDialog = ref(false);
const isDownloadingUpdate = ref(false);
const downloadProgress = ref(0);
+ const updateDownloaded = ref(false);
+ const isInstallingUpdate = ref(false);
const updateReady = ref(false);
+ const activeTaskCount = computed(() => Math.max(0, Math.trunc(options.getActiveTaskCount?.() ?? 0)));
const hasUpdateAvailable = computed(() => updateInfo.value?.update_available === true);
const latestReleaseUrl = "https://github.com/t8y2/dbx/releases/latest";
@@ -106,35 +115,84 @@ export function useAppUpdater() {
openUrl(url);
}
+ function blockUpdateForActiveTasks(): boolean {
+ if (!shouldBlockAppUpdate(activeTaskCount.value)) return false;
+ toast(t("updates.activeTasksBlockUpdate", { count: activeTaskCount.value }), 5000);
+ return true;
+ }
+
async function downloadAndInstallUpdate() {
- if (!isTauriRuntime() || isDownloadingUpdate.value) return;
+ if (!isTauriRuntime() || isDownloadingUpdate.value || isInstallingUpdate.value || updateDownloaded.value || updateReady.value) return;
if (!canDownloadAndInstallUpdate(updateInfo.value, true)) {
openLatestRelease();
return;
}
+ if (blockUpdateForActiveTasks()) return;
isDownloadingUpdate.value = true;
downloadProgress.value = 0;
let unlisten: (() => void) | undefined;
const latestVersion = updateInfo.value?.latest_version;
+ let failureMessageKey = "updates.downloadFailed";
try {
const { listen } = await import("@tauri-apps/api/event");
unlisten = await listen<UpdateDownloadProgress>("update-download-progress", (event) => {
const total = event.payload.total ?? 0;
downloadProgress.value = total > 0 ? Math.round((event.payload.downloaded / total) * 100) : 0;
});
- await api.downloadAndInstallUpdate(normalizeUpdateDownloadSource(settingsStore.editorSettings.updateDownloadSource), latestVersion);
- downloadProgress.value = 100;
- updateReady.value = true;
+ const result = await downloadAndInstallUpdateWhenIdle({
+ getActiveTaskCount: () => activeTaskCount.value,
+ download: async () => {
+ try {
+ await api.downloadUpdate(normalizeUpdateDownloadSource(settingsStore.editorSettings.updateDownloadSource), latestVersion);
+ downloadProgress.value = 100;
+ updateDownloaded.value = true;
+ } finally {
+ isDownloadingUpdate.value = false;
+ }
+ },
+ install: async () => {
+ failureMessageKey = "updates.installFailed";
+ await installPendingUpdate();
+ },
+ });
+ if (result === "blocked" || result === "downloaded") {
+ blockUpdateForActiveTasks();
+ }
} catch (e: any) {
- toast(t("updates.downloadFailed", { error: e?.message || String(e) }), 5000);
+ toast(t(failureMessageKey, { error: e?.message || String(e) }), 5000);
} finally {
unlisten?.();
isDownloadingUpdate.value = false;
}
}
+ async function installPendingUpdate() {
+ isInstallingUpdate.value = true;
+ try {
+ await api.installDownloadedUpdate();
+ updateDownloaded.value = false;
+ updateReady.value = true;
+ } finally {
+ isInstallingUpdate.value = false;
+ }
+ }
+
+ async function installDownloadedUpdate() {
+ if (!isTauriRuntime() || isDownloadingUpdate.value || isInstallingUpdate.value || !updateDownloaded.value) return;
+ try {
+ const installed = await installDownloadedUpdateWhenIdle({
+ getActiveTaskCount: () => activeTaskCount.value,
+ install: installPendingUpdate,
+ });
+ if (!installed) blockUpdateForActiveTasks();
+ } catch (e: any) {
+ toast(t("updates.installFailed", { error: e?.message || String(e) }), 5000);
+ }
+ }
+
async function restartApp() {
if (!isTauriRuntime()) return;
+ if (blockUpdateForActiveTasks()) return;
try {
const { relaunch } = await import("@tauri-apps/plugin-process");
await relaunch();
@@ -150,7 +208,10 @@ export function useAppUpdater() {
showUpdateDialog,
isDownloadingUpdate,
downloadProgress,
+ updateDownloaded,
+ isInstallingUpdate,
updateReady,
+ activeTaskCount,
hasUpdateAvailable,
latestReleaseUrl,
openUrl,
@@ -158,6 +219,7 @@ export function useAppUpdater() {
formatUpdateError,
openLatestRelease,
downloadAndInstallUpdate,
+ installDownloadedUpdate,
restartApp,
};
}
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index a6d88d3cf0..59c297f95c 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -68,9 +68,12 @@ export default {
rateLimited: "GitHub update checks are temporarily rate limited. You can still open the release page to check manually.",
openRelease: "Open Release",
downloadAndInstall: "Download & Install",
+ activeTasksBlockUpdate: "{count} task(s) are still running. Wait for them to finish before updating DBX.",
portableManualUpdate: "Portable builds cannot use the in-app installer. Download the portable ZIP from the release page, then extract it over the current DBX folder to keep portable.dbx and data.",
downloading: "Downloading {progress}%",
downloadFailed: "Update download failed: {error}",
+ installing: "Installing update...",
+ installFailed: "Update installation failed: {error}",
restart: "Exit & Restart",
restartFailed: "Failed to restart app: {error}",
exitAndUpdate: "Exit & Update",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 8ee39cefb5..55b1d0e235 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -70,9 +70,12 @@ export default withEnglishFallback({
rateLimited: "Las verificaciones de actualizaciones de GitHub están temporalmente limitadas. Puedes abrir la página de lanzamientos para verificar manualmente.",
openRelease: "Abrir lanzamiento",
downloadAndInstall: "Descargar e instalar",
+ activeTasksBlockUpdate: "Hay {count} tarea(s) en ejecución. Espera a que terminen antes de actualizar DBX.",
portableManualUpdate: "Las versiones portables no pueden usar el instalador integrado. Descarga el ZIP portable desde la página de lanzamiento y extráelo sobre la carpeta actual de DBX para conservar portable.dbx y data.",
downloading: "Descargando {progress}%",
downloadFailed: "Error al descargar la actualización: {error}",
+ installing: "Instalando actualización...",
+ installFailed: "Error al instalar la actualización: {error}",
restart: "Salir y reiniciar",
restartFailed: "Error al reiniciar la aplicación: {error}",
exitAndUpdate: "Salir y actualizar",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 69a61a2659..54f755d35d 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -69,9 +69,12 @@ export default withEnglishFallback({
rateLimited: "Le verifiche degli aggiornamenti di GitHub sono temporaneamente limitate. Puoi comunque aprire la pagina delle release per verificare manualmente.",
openRelease: "Apri Release",
downloadAndInstall: "Scarica e Installa",
+ activeTasksBlockUpdate: "Ci sono {count} attività in esecuzione. Attendi che terminino prima di aggiornare DBX.",
portableManualUpdate: "Le build portatili non possono utilizzare l'installer in-app. Scarica lo ZIP portatile dalla pagina delle release, quindi estrailo nella cartella DBX corrente per mantenere portable.dbx e i dati.",
downloading: "Download in corso {progress}%",
downloadFailed: "Download dell'aggiornamento non riuscito: {error}",
+ installing: "Installazione dell'aggiornamento...",
+ installFailed: "Installazione dell'aggiornamento non riuscita: {error}",
restart: "Esci e Riavvia",
restartFailed: "Impossibile riavviare l'app: {error}",
exitAndUpdate: "Esci e Aggiorna",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 0380025a44..ddf75001f8 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -70,9 +70,12 @@ export default withEnglishFallback({
rateLimited: "GitHubのアップデート確認が一時的に制限されています。リリースページで手動確認できます。",
openRelease: "リリースページを開く",
downloadAndInstall: "ダウンロード & インストール",
+ activeTasksBlockUpdate: "{count} 件のタスクが実行中です。完了してから DBX を更新してください。",
portableManualUpdate: "ポータブル版はアプリ内インストーラーを使用できません。リリースページからポータブルZIPをダウンロードし、現在のDBXフォルダに上書き展開してください。portable.dbxとデータは保持されます。",
downloading: "ダウンロード中 {progress}%",
downloadFailed: "アップデートのダウンロードに失敗しました: {error}",
+ installing: "アップデートをインストール中...",
+ installFailed: "アップデートのインストールに失敗しました: {error}",
restart: "終了して再起動",
restartFailed: "アプリの再起動に失敗しました: {error}",
exitAndUpdate: "終了してアップデート",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 9650532bf9..49a0a576b4 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -70,9 +70,12 @@ export default withEnglishFallback({
rateLimited: "As verificações de atualização do GitHub estão temporariamente limitadas. Você ainda pode abrir a página de lançamento para verificar manualmente.",
openRelease: "Abrir Lançamento",
downloadAndInstall: "Baixar e Instalar",
+ activeTasksBlockUpdate: "Há {count} tarefa(s) em execução. Aguarde a conclusão antes de atualizar o DBX.",
portableManualUpdate: "Versões portáteis não podem usar o instalador interno. Baixe o ZIP portátil da página de lançamento e extraia-o sobre a pasta atual do DBX para manter o portable.dbx e os dados.",
downloading: "Baixando {progress}%",
downloadFailed: "Falha ao baixar a atualização: {error}",
+ installing: "Instalando atualização...",
+ installFailed: "Falha ao instalar a atualização: {error}",
restart: "Sair e Reiniciar",
restartFailed: "Falha ao reiniciar o aplicativo: {error}",
exitAndUpdate: "Sair e Atualizar",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 741f0eb807..a95ffa58f3 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -70,9 +70,12 @@ export default withEnglishFallback({
rateLimited: "GitHub 更新检查暂时触发频率限制。你仍然可以打开下载页手动查看。",
openRelease: "打开下载页",
downloadAndInstall: "下载并安装",
+ activeTasksBlockUpdate: "有 {count} 个任务正在执行,请等待任务完成后再更新 DBX。",
portableManualUpdate: "便携版不能使用应用内安装器更新。请从 release 下载便携版 ZIP,并解压覆盖当前 DBX 目录,以保留 portable.dbx 和 data。",
downloading: "下载中 {progress}%",
downloadFailed: "更新下载失败:{error}",
+ installing: "正在安装更新...",
+ installFailed: "更新安装失败:{error}",
restart: "退出并重启",
restartFailed: "重启应用失败:{error}",
exitAndUpdate: "退出并更新",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 86bd2c97c7..1b43abe532 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -70,9 +70,12 @@ export default withEnglishFallback({
rateLimited: "GitHub 更新檢查暫時觸發頻率限制。你仍然可以開啟下載頁手動檢視。",
openRelease: "開啟下載頁",
downloadAndInstall: "下載並安裝",
+ activeTasksBlockUpdate: "有 {count} 個任務正在執行,請等待任務完成後再更新 DBX。",
portableManualUpdate: "可攜版無法使用應用程式內建安裝器更新。請從發行頁下載可攜版 ZIP,並解壓縮覆蓋目前的 DBX 目錄,以保留 portable.dbx 和 data。",
downloading: "下載中 {progress}%",
downloadFailed: "更新下載失敗:{error}",
+ installing: "正在安裝更新...",
+ installFailed: "更新安裝失敗:{error}",
restart: "結束並重新啟動",
restartFailed: "重新啟動應用程式失敗:{error}",
exitAndUpdate: "結束並更新",
diff --git a/apps/desktop/src/lib/app/appUpdateInstallFlow.ts b/apps/desktop/src/lib/app/appUpdateInstallFlow.ts
new file mode 100644
index 0000000000..80d0b37765
--- /dev/null
+++ b/apps/desktop/src/lib/app/appUpdateInstallFlow.ts
@@ -0,0 +1,31 @@
+import { shouldBlockAppUpdate } from "@/lib/app/appUpdateTaskGuard";
+
+export type UpdateDownloadFlowResult = "blocked" | "downloaded" | "installed";
+
+interface UpdateDownloadFlowOptions {
+ getActiveTaskCount: () => number;
+ download: () => Promise<void>;
+ install: () => Promise<void>;
+}
+
+interface DownloadedUpdateInstallOptions {
+ getActiveTaskCount: () => number;
+ install: () => Promise<void>;
+}
+
+export async function downloadAndInstallUpdateWhenIdle(options: UpdateDownloadFlowOptions): Promise<UpdateDownloadFlowResult> {
+ if (shouldBlockAppUpdate(options.getActiveTaskCount())) return "blocked";
+
+ await options.download();
+ if (shouldBlockAppUpdate(options.getActiveTaskCount())) return "downloaded";
+
+ await options.install();
+ return "installed";
+}
+
+export async function installDownloadedUpdateWhenIdle(options: DownloadedUpdateInstallOptions): Promise<boolean> {
+ if (shouldBlockAppUpdate(options.getActiveTaskCount())) return false;
+
+ await options.install();
+ return true;
+}
diff --git a/apps/desktop/src/lib/app/appUpdateTaskGuard.ts b/apps/desktop/src/lib/app/appUpdateTaskGuard.ts
new file mode 100644
index 0000000000..98fef0faf9
--- /dev/null
+++ b/apps/desktop/src/lib/app/appUpdateTaskGuard.ts
@@ -0,0 +1,17 @@
+export interface UpdateQueryTaskState {
+ isExecuting?: boolean;
+ explainExecutionId?: string;
+}
+
+function normalizedTaskCount(value: number): number {
+ return Number.isFinite(value) ? Math.max(0, Math.trunc(value)) : 0;
+}
+
+export function countActiveUpdateBlockingTasks(backgroundTaskCount: number, queryTasks: UpdateQueryTaskState[]): number {
+ const activeQueryCount = queryTasks.filter((task) => task.isExecuting || Boolean(task.explainExecutionId?.trim())).length;
+ return normalizedTaskCount(backgroundTaskCount) + activeQueryCount;
+}
+
+export function shouldBlockAppUpdate(activeTaskCount: number): boolean {
+ return normalizedTaskCount(activeTaskCount) > 0;
+}
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index 6dfc9adf16..688e99ae45 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -488,7 +488,8 @@ export const installMcpServer = forward("installMcpServer");
export const checkForUpdates = forward("checkForUpdates");
export const fetchChangelog = forward("fetchChangelog");
export const getSystemProxyUrl = forward("getSystemProxyUrl");
-export const downloadAndInstallUpdate = forward("downloadAndInstallUpdate");
+export const downloadUpdate = forward("downloadUpdate");
+export const installDownloadedUpdate = forward("installDownloadedUpdate");
export const getAppVersion = forward("getAppVersion");
export const getAppSupportInfo = forward("getAppSupportInfo");
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index fd9678f70d..95c09508d3 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -2287,7 +2287,11 @@ export async function getSystemProxyUrl(): Promise<string | null> {
return null;
}
-export async function downloadAndInstallUpdate(_source: UpdateDownloadSource, _latestVersion?: string): Promise<void> {
+export async function downloadUpdate(_source: UpdateDownloadSource, _latestVersion?: string): Promise<void> {
+ throw new Error("In-app update downloads are only available in the desktop app.");
+}
+
+export async function installDownloadedUpdate(): Promise<void> {
throw new Error("In-app update installation is only available in the desktop app.");
}
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index 6d6e062fe2..d466b1a79a 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -1458,8 +1458,12 @@ export async function getSystemProxyUrl(): Promise<string | null> {
return invoke("get_system_proxy_url");
}
-export async function downloadAndInstallUpdate(source: UpdateDownloadSource, latestVersion?: string): Promise<void> {
- return invoke("download_and_install_update", { source, latestVersion });
+export async function downloadUpdate(source: UpdateDownloadSource, latestVersion?: string): Promise<void> {
+ return invoke("download_update", { source, latestVersion });
+}
+
+export async function installDownloadedUpdate(): Promise<void> {
+ return invoke("install_downloaded_update");
}
export async function getAppVersion(): Promise<string> {
diff --git a/packages/app-tests/appUpdater.test.ts b/packages/app-tests/appUpdater.test.ts
index 767fb79ef8..16f9b8bdee 100644
--- a/packages/app-tests/appUpdater.test.ts
+++ b/packages/app-tests/appUpdater.test.ts
@@ -1,7 +1,10 @@
import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
import { test } from "vitest";
import { canDownloadAndInstallUpdate, normalizeUpdateDownloadSource, resolveUpdateReleaseUrl, tagVersion } from "../../apps/desktop/src/composables/useAppUpdater.ts";
+import { downloadAndInstallUpdateWhenIdle, installDownloadedUpdateWhenIdle } from "../../apps/desktop/src/lib/app/appUpdateInstallFlow.ts";
+import { countActiveUpdateBlockingTasks, shouldBlockAppUpdate } from "../../apps/desktop/src/lib/app/appUpdateTaskGuard.ts";
import type { UpdateInfo } from "../../apps/desktop/src/lib/backend/api.ts";
function updateInfo(overrides: Partial<UpdateInfo> = {}): UpdateInfo {
@@ -49,3 +52,56 @@ test("resolves release page URL from update download source", () => {
assert.equal(resolveUpdateReleaseUrl(updateInfo({ release_url: "https://github.com/t8y2/dbx/releases/tag/v0.5.39" }), "official", fallbackUrl), "https://github.com/t8y2/dbx/releases/tag/v0.5.39");
assert.equal(resolveUpdateReleaseUrl(null, "cnb", fallbackUrl), fallbackUrl);
});
+
+test("counts background and query tasks that must finish before updating", () => {
+ assert.equal(countActiveUpdateBlockingTasks(2, [{ isExecuting: true }, { explainExecutionId: "explain-1" }, { isExecuting: true, explainExecutionId: "explain-2" }, { isExecuting: false, explainExecutionId: "" }]), 5);
+ assert.equal(countActiveUpdateBlockingTasks(-1, []), 0);
+ assert.equal(shouldBlockAppUpdate(0), false);
+ assert.equal(shouldBlockAppUpdate(1), true);
+});
+
+test("retains a downloaded update when a task starts during download and installs it later without downloading again", async () => {
+ let activeTaskCount = 0;
+ let downloadCount = 0;
+ let installCount = 0;
+ let finishDownload!: () => void;
+ const downloadGate = new Promise<void>((resolve) => {
+ finishDownload = resolve;
+ });
+ const operations = {
+ getActiveTaskCount: () => activeTaskCount,
+ download: async () => {
+ downloadCount += 1;
+ await downloadGate;
+ },
+ install: async () => {
+ installCount += 1;
+ },
+ };
+
+ const firstAttempt = downloadAndInstallUpdateWhenIdle(operations);
+ assert.equal(downloadCount, 1);
+ assert.equal(installCount, 0);
+
+ activeTaskCount = 1;
+ finishDownload();
+ assert.equal(await firstAttempt, "downloaded");
+ assert.equal(installCount, 0);
+
+ activeTaskCount = 0;
+ assert.equal(await installDownloadedUpdateWhenIdle(operations), true);
+ assert.equal(downloadCount, 1);
+ assert.equal(installCount, 1);
+});
+
+test("wires the active task guard into update installation and restart", () => {
+ const appSource = readFileSync("apps/desktop/src/App.vue", "utf8");
+ const updaterSource = readFileSync("apps/desktop/src/composables/useAppUpdater.ts", "utf8");
+ const dialogSource = readFileSync("apps/desktop/src/components/layout/UpdateDialog.vue", "utf8");
+
+ assert.match(appSource, /countActiveUpdateBlockingTasks\(activeBackgroundTaskCount\.value, queryStore\.tabs\)/);
+ assert.match(appSource, /getActiveTaskCount: \(\) => trackedUpdateTaskCount\.value/);
+ assert.equal(updaterSource.match(/if \(blockUpdateForActiveTasks\(\)\) return;/g)?.length, 2);
+ assert.match(dialogSource, /role="alert"[\s\S]*updates\.activeTasksBlockUpdate/);
+ assert.equal(dialogSource.match(/:disabled="activeTaskCount > 0"/g)?.length, 3);
+});
diff --git a/src-tauri/src/commands/update.rs b/src-tauri/src/commands/update.rs
index 36308b6889..2a74e22f82 100644
--- a/src-tauri/src/commands/update.rs
+++ b/src-tauri/src/commands/update.rs
@@ -1,12 +1,12 @@
use std::sync::{
atomic::{AtomicU64, Ordering},
- Arc,
+ Arc, Mutex,
};
pub use dbx_core::update::UpdateInfo;
use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Emitter};
-use tauri_plugin_updater::UpdaterExt;
+use tauri_plugin_updater::{Update, UpdaterExt};
const OFFICIAL_UPDATE_ENDPOINTS: [&str; 2] = [
"https://dl.dbxio.com/releases/latest/latest.json",
@@ -30,6 +30,41 @@ pub struct UpdateDownloadProgress {
pub total: Option<u64>,
}
+enum PendingUpdate {
+ Downloading,
+ Ready { update: Box<Update>, bytes: Vec<u8> },
+}
+
+#[derive(Default)]
+pub struct PendingUpdateState {
+ pending: Mutex<Option<PendingUpdate>>,
+}
+
+impl PendingUpdateState {
+ fn begin_download(&self) -> Result<(), String> {
+ let mut pending = self.pending.lock().map_err(|_| "Update state is unavailable.".to_string())?;
+ if pending.is_some() {
+ return Err("An update is already downloading or ready to install.".to_string());
+ }
+ *pending = Some(PendingUpdate::Downloading);
+ Ok(())
+ }
+
+ fn finish_download(&self, update: Update, bytes: Vec<u8>) -> Result<(), String> {
+ let mut pending = self.pending.lock().map_err(|_| "Update state is unavailable.".to_string())?;
+ *pending = Some(PendingUpdate::Ready { update: Box::new(update), bytes });
+ Ok(())
+ }
+
+ fn cancel_download(&self) {
+ if let Ok(mut pending) = self.pending.lock() {
+ if matches!(pending.as_ref(), Some(PendingUpdate::Downloading)) {
+ *pending = None;
+ }
+ }
+ }
+}
+
impl UpdateDownloadSource {
fn label(&self) -> &'static str {
match self {
@@ -118,8 +153,9 @@ pub async fn get_system_proxy_url() -> Option<String> {
}
#[tauri::command]
-pub async fn download_and_install_update(
+pub async fn download_update(
app: AppHandle,
+ state: tauri::State<'_, PendingUpdateState>,
source: UpdateDownloadSource,
latest_version: Option<String>,
) -> Result<(), String> {
@@ -127,7 +163,23 @@ pub async fn download_and_install_update(
return Err("Portable builds cannot use the in-app installer.".to_string());
}
- let endpoint_urls = source.endpoints(latest_version.as_deref())?;
+ state.begin_download()?;
+ let result = download_update_inner(&app, &source, latest_version.as_deref()).await;
+ match result {
+ Ok((update, bytes)) => state.finish_download(update, bytes),
+ Err(error) => {
+ state.cancel_download();
+ Err(error)
+ }
+ }
+}
+
+async fn download_update_inner(
+ app: &AppHandle,
+ source: &UpdateDownloadSource,
+ latest_version: Option<&str>,
+) -> Result<(Update, Vec<u8>), String> {
+ let endpoint_urls = source.endpoints(latest_version)?;
println!("[DBX updater] checking from {} endpoints: {}", source.label(), endpoint_urls.join(", "));
let mut endpoints = Vec::with_capacity(endpoint_urls.len());
for endpoint_url in endpoint_urls {
@@ -159,8 +211,8 @@ pub async fn download_and_install_update(
let downloaded = Arc::new(AtomicU64::new(0));
let finished_downloaded = Arc::clone(&downloaded);
- update
- .download_and_install(
+ let bytes = update
+ .download(
|chunk_len, total| {
let downloaded =
downloaded.fetch_add(chunk_len as u64, Ordering::Relaxed).saturating_add(chunk_len as u64);
@@ -175,7 +227,19 @@ pub async fn download_and_install_update(
},
)
.await
- .map_err(|e| format!("Failed to download and install update: {e}"))
+ .map_err(|e| format!("Failed to download update: {e}"))?;
+ Ok((update, bytes))
+}
+
+#[tauri::command]
+pub fn install_downloaded_update(state: tauri::State<'_, PendingUpdateState>) -> Result<(), String> {
+ let mut pending = state.pending.lock().map_err(|_| "Update state is unavailable.".to_string())?;
+ let Some(PendingUpdate::Ready { update, bytes }) = pending.as_ref() else {
+ return Err("No downloaded update is ready to install.".to_string());
+ };
+ update.install(bytes).map_err(|e| format!("Failed to install update: {e}"))?;
+ *pending = None;
+ Ok(())
}
async fn update_url_is_available(url: &str) -> bool {
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index e1dc6a4d10..5aa2c3adf6 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -969,6 +969,7 @@ pub fn run() {
app.manage(commands::external_db::ExternalDbOpenState::default());
app.manage(commands::deep_link::DeepLinkOpenState::default());
app.manage(CloseBehaviorState::new());
+ app.manage(commands::update::PendingUpdateState::default());
#[cfg(target_os = "macos")]
macos_app_delegate::install_dock_quit_handler(app.handle());
let startup_links = commands::deep_link::connection_deep_links_from_args(std::env::args().skip(1));
@@ -1413,7 +1414,8 @@ pub fn run() {
commands::update::check_for_updates,
commands::update::fetch_changelog,
commands::update::get_system_proxy_url,
- commands::update::download_and_install_update,
+ commands::update::download_update,
+ commands::update::install_downloaded_update,
commands::transfer::start_transfer,
commands::transfer::preview_transfer_ownership,
commands::transfer::cancel_transfer,