fix(updater): improve download cancellation and stall handling

This commit is contained in:
rihkddd authored and GitHub committed 2026-07-31 03:09:19 +08:00
1 parent c697d0c7ad
commit 27d1ad53ce
18 files changed
+631 -110

No files matched your search

@@ -0,0 +1,118 @@
// @vitest-environment happy-dom
import { createApp, defineComponent, h, type App } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import i18n from "@/i18n";
import { useAppUpdater } from "@/composables/useAppUpdater";
const apiMock = vi.hoisted(() => ({
cancelUpdateDownload: vi.fn<() => Promise<void>>(),
downloadUpdate: vi.fn<() => Promise<void>>(),
installDownloadedUpdate: vi.fn<() => Promise<void>>(),
}));
const listenMock = vi.hoisted(() => vi.fn());
vi.mock("@/lib/backend/api", () => apiMock);
vi.mock("@/lib/backend/tauriRuntime", () => ({
isTauriRuntime: () => true,
}));
vi.mock("@/composables/useToast", () => ({
useToast: () => ({ toast: vi.fn() }),
}));
vi.mock("@/stores/settingsStore", () => ({
useSettingsStore: () => ({ editorSettings: { updateDownloadSource: "official" } }),
}));
vi.mock("@tauri-apps/api/event", () => ({
listen: listenMock,
}));
interface Deferred<T> {
promise: Promise<T>;
resolve: (value: T | PromiseLike<T>) => void;
reject: (reason?: unknown) => void;
}
function deferred<T>(): Deferred<T> {
let resolve!: Deferred<T>["resolve"];
let reject!: Deferred<T>["reject"];
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, resolve, reject };
}
let app: App | undefined;
let container: HTMLDivElement | undefined;
beforeEach(() => {
vi.clearAllMocks();
listenMock.mockResolvedValue(vi.fn());
apiMock.installDownloadedUpdate.mockResolvedValue();
});
afterEach(() => {
app?.unmount();
container?.remove();
app = undefined;
container = undefined;
});
describe("useAppUpdater download attempts", () => {
it("waits for cancellation and ignores stale completion from the previous attempt", async () => {
const firstDownload = deferred<void>();
const secondDownload = deferred<void>();
const cancellation = deferred<void>();
apiMock.downloadUpdate.mockImplementationOnce(() => firstDownload.promise).mockImplementationOnce(() => secondDownload.promise);
apiMock.cancelUpdateDownload.mockReturnValueOnce(cancellation.promise);
let updater!: ReturnType<typeof useAppUpdater>;
container = document.createElement("div");
document.body.append(container);
app = createApp(
defineComponent({
setup() {
updater = useAppUpdater();
return () => h("div");
},
}),
);
app.use(i18n);
app.mount(container);
updater.updateInfo.value = {
current_version: "0.5.69",
latest_version: "0.5.70",
update_available: true,
release_name: "DBX v0.5.70",
release_url: "https://github.com/t8y2/dbx/releases/tag/v0.5.70",
release_notes: "",
};
const firstAttempt = updater.downloadAndInstallUpdate();
await vi.waitFor(() => expect(apiMock.downloadUpdate).toHaveBeenCalledTimes(1));
const cancelAttempt = updater.cancelDownload();
expect(updater.isDownloadingUpdate.value).toBe(false);
const retryAttempt = updater.downloadAndInstallUpdate();
await Promise.resolve();
expect(apiMock.downloadUpdate).toHaveBeenCalledTimes(1);
expect(updater.isDownloadingUpdate.value).toBe(true);
cancellation.resolve();
await cancelAttempt;
await vi.waitFor(() => expect(apiMock.downloadUpdate).toHaveBeenCalledTimes(2));
firstDownload.reject(new Error("Download canceled by user."));
await firstAttempt;
expect(updater.isDownloadingUpdate.value).toBe(true);
expect(updater.downloadProgress.value).toBe(0);
secondDownload.resolve();
await retryAttempt;
expect(apiMock.installDownloadedUpdate).toHaveBeenCalledOnce();
expect(updater.isDownloadingUpdate.value).toBe(false);
expect(updater.updateReady.value).toBe(true);
});
});
+50 -12
View File
@@ -68,6 +68,8 @@ export function useAppUpdater(options: UseAppUpdaterOptions = {}) {
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";
let activeDownloadAttempt = 0;
let pendingCancellation: Promise<void> | undefined;
function openUrl(url: string) {
if (isTauriRuntime()) {
@@ -104,10 +106,16 @@ export function useAppUpdater(options: UseAppUpdaterOptions = {}) {
function formatUpdateError(message: string): string {
const lower = message.toLowerCase();
if (lower.includes("canceled") || lower.includes("cancelled")) {
return t("updates.downloadCanceled");
}
if (lower.includes("403") || lower.includes("rate limit")) {
return t("updates.rateLimited");
}
return t("updates.failed", { error: message });
if (lower.includes("stalled") || lower.includes("timeout") || lower.includes("all available mirrors") || lower.includes("error sending request") || lower.includes("failed to download")) {
return t("updates.networkOrMirrorFailed");
}
return t("updates.downloadFailed", { error: message });
}
function openLatestRelease() {
@@ -128,30 +136,30 @@ export function useAppUpdater(options: UseAppUpdaterOptions = {}) {
return;
}
if (blockUpdateForActiveTasks()) return;
const attempt = ++activeDownloadAttempt;
isDownloadingUpdate.value = true;
downloadProgress.value = 0;
let unlisten: (() => void) | undefined;
const latestVersion = updateInfo.value?.latest_version;
let failureMessageKey = "updates.downloadFailed";
try {
await pendingCancellation;
if (attempt !== activeDownloadAttempt) return;
const { listen } = await import("@tauri-apps/api/event");
unlisten = await listen<UpdateDownloadProgress>("update-download-progress", (event) => {
if (attempt !== activeDownloadAttempt) return;
const total = event.payload.total ?? 0;
downloadProgress.value = total > 0 ? Math.round((event.payload.downloaded / total) * 100) : 0;
});
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;
}
await api.downloadUpdate(normalizeUpdateDownloadSource(settingsStore.editorSettings.updateDownloadSource), latestVersion);
if (attempt !== activeDownloadAttempt) throw new Error("Download canceled by user.");
downloadProgress.value = 100;
updateDownloaded.value = true;
isDownloadingUpdate.value = false;
},
install: async () => {
failureMessageKey = "updates.installFailed";
await installPendingUpdate();
},
});
@@ -159,10 +167,20 @@ export function useAppUpdater(options: UseAppUpdaterOptions = {}) {
blockUpdateForActiveTasks();
}
} catch (e: any) {
toast(t(failureMessageKey, { error: e?.message || String(e) }), 5000);
if (attempt !== activeDownloadAttempt) return;
downloadProgress.value = 0;
const rawMsg = e?.message || String(e);
console.error("[DBX update error]", rawMsg);
const lower = rawMsg.toLowerCase();
if (lower.includes("canceled") || lower.includes("cancelled")) {
return;
}
toast(formatUpdateError(rawMsg), 5000);
} finally {
unlisten?.();
isDownloadingUpdate.value = false;
if (attempt === activeDownloadAttempt) {
isDownloadingUpdate.value = false;
}
}
}
@@ -203,6 +221,25 @@ export function useAppUpdater(options: UseAppUpdaterOptions = {}) {
}
}
async function cancelDownload() {
if (isDownloadingUpdate.value) {
activeDownloadAttempt += 1;
isDownloadingUpdate.value = false;
downloadProgress.value = 0;
if (isTauriRuntime()) {
const cancellation = api.cancelUpdateDownload().catch(() => {});
pendingCancellation = cancellation;
try {
await cancellation;
} finally {
if (pendingCancellation === cancellation) {
pendingCancellation = undefined;
}
}
}
}
}
return {
checkingUpdates,
updateInfo,
@@ -221,6 +258,7 @@ export function useAppUpdater(options: UseAppUpdaterOptions = {}) {
formatUpdateError,
openLatestRelease,
downloadAndInstallUpdate,
cancelDownload,
installDownloadedUpdate,
restartApp,
};