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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(webdav): honor last upload time when scheduling auto-upload (#11921)
lxk9551e9f3386eab6
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vueindex 2afc5da3e3..c6251da1fa 100644--- a/apps/desktop/src/App.vue+++ b/apps/desktop/src/App.vue@@ -74,7 +74,7 @@ import { useVisibilityChange } from "@/composables/useVisibilityChange";import { useExternalSqlFileChanges } from "@/composables/useExternalSqlFileChanges";import { useWebDavAutoUpload } from "@/composables/useWebDavAutoUpload";import { useSnippetAutoUpload } from "@/composables/useSnippetAutoUpload";-import { readSyncMethod, readWebDavAutoUploadConfig, readWebDavBackupSelection, recordWebDavSyncSuccess } from "@/lib/webdav/webdavAutoUploadConfig";+import { readSyncMethod, readWebDavAutoUploadConfig, readWebDavBackupSelection, recordWebDavSyncSuccess, writeWebDavLastUploadAt, webDavSyncTarget } from "@/lib/webdav/webdavAutoUploadConfig";import { useScheduledDatabaseBackups } from "@/composables/useScheduledDatabaseBackups";import { appShellMinSizeStyleForScale, shouldDrawDesktopWindowFrame, shouldDrawLinuxFloatingFrame, useWindowControls } from "@/composables/useWindowControls";import { createOpenTabsRestorationBarrier, initializeDesktopOpenTabs, initializeOpenTabs, type OpenTabsRestorationBarrier } from "@/lib/app/openTabsStartup";@@ -1363,6 +1363,9 @@ async function openImmediateSync() {const includeSecrets = Boolean((selection?.includeSecrets ?? secretsStatus.enabled) && secretsStatus.enabled && secretsStatus.hasSavedPassphrase);const summary = await api.webdavSyncUpload(webDavConfig, settingsStore.editorSettings, undefined, includeSecrets, selection);recordWebDavSyncSuccess(webDavConfig);+ const currentConfig = readWebDavAutoUploadConfig();+ const isCurrent = Boolean(currentConfig.enabled && currentConfig.webDavConfig && webDavSyncTarget(currentConfig.webDavConfig) === webDavSyncTarget(webDavConfig));+ writeWebDavLastUploadAt(webDavConfig, Date.now(), isCurrent);toast(t("settings.syncUploadSuccess", { bytes: summary.bytes, path: summary.remotePath }), 3000);} catch (error: any) {toast(error?.message || String(error), 5000);diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vueindex 368b0a64a3..3c51d8c8d1 100644--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue@@ -403,8 +403,11 @@ import {readSyncMethod,WEB_DAV_LAST_SUCCESSFUL_SYNC_STORAGE_KEY,WEB_DAV_SYNC_SUCCESS_EVENT,+ readWebDavAutoUploadConfig,+ webDavSyncTarget,writeWebDavAutoUploadFields,writeWebDavBackupSelection,+ writeWebDavLastUploadAt,writeSyncMethod,type SyncMethod,} from "@/lib/webdav/webdavAutoUploadConfig";@@ -5554,6 +5557,9 @@ async function confirmSyncSelection(selection: SyncSelection) {const summary = await webdavSyncUpload(config, settingsStore.editorSettings, selection.includeSecrets ? webdavSecretsPassphrase.value || undefined : undefined, selection.includeSecrets, selection);recordWebDavSyncSuccess(config);writeWebDavBackupSelection(selection);+ const currentConfig = readWebDavAutoUploadConfig();+ const isCurrent = Boolean(currentConfig.enabled && currentConfig.webDavConfig && webDavSyncTarget(currentConfig.webDavConfig) === webDavSyncTarget(config));+ writeWebDavLastUploadAt(config, Date.now(), isCurrent);return t("settings.syncUploadSuccess", { bytes: summary.bytes, path: summary.remotePath });});return;diff --git a/apps/desktop/src/composables/useWebDavAutoUpload.ts b/apps/desktop/src/composables/useWebDavAutoUpload.tsindex 7139cb503d..d46f28a892 100644--- a/apps/desktop/src/composables/useWebDavAutoUpload.ts+++ b/apps/desktop/src/composables/useWebDavAutoUpload.ts@@ -2,37 +2,68 @@ 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, readWebDavBackupSelection, recordWebDavSyncSuccess, WEB_DAV_AUTO_UPLOAD_STORAGE_KEYS } from "@/lib/webdav/webdavAutoUploadConfig";+import { readWebDavAutoUploadConfig, readWebDavBackupSelection, readWebDavLastUploadAt, recordWebDavSyncSuccess, webDavSyncTarget, writeWebDavLastUploadAt, type WebDavAutoUploadConfig, WEB_DAV_AUTO_UPLOAD_STORAGE_KEYS } from "@/lib/webdav/webdavAutoUploadConfig";export function useWebDavAutoUpload() {const settingsStore = useSettingsStore();const maxTimeoutDelayMs = 2_147_000_000;let timer: ReturnType<typeof window.setTimeout> | undefined;+ let timerSequence = 0;let nextUploadAt = 0;let uploading = false;function clearTimer() {+ timerSequence++;if (timer === undefined) return;window.clearTimeout(timer);timer = undefined;}+ function computeNextUploadAt(config: WebDavAutoUploadConfig): number {+ const intervalMs = config.intervalMinutes * 60_000;+ const lastUploadAt = readWebDavLastUploadAt(config.webDavConfig);+ const now = Date.now();+ if (lastUploadAt === null) {+ if (config.webDavConfig) {+ writeWebDavLastUploadAt(config.webDavConfig, now, false);+ }+ return now + intervalMs;+ }+ if (lastUploadAt > now) {+ return now + intervalMs;+ }+ return lastUploadAt + intervalMs;+ }+function armTimer() {+ clearTimer();+ const sequence = timerSequence;const remainingMs = Math.max(0, nextUploadAt - Date.now());timer = window.setTimeout(- () => {+ async () => {+ if (sequence !== timerSequence) return;+ timer = undefined;+if (Date.now() < nextUploadAt) {armTimer();return;}- void runAutoUpload();+ const success = await runAutoUpload(sequence);+ if (sequence !== timerSequence) return;+const config = readWebDavAutoUploadConfig();if (!config.enabled || !config.webDavConfig) {- clearTimer();return;}- nextUploadAt = Date.now() + config.intervalMinutes * 60_000;++ const intervalMs = config.intervalMinutes * 60_000;+ if (success) {+ nextUploadAt = (readWebDavLastUploadAt(config.webDavConfig) ?? Date.now()) + intervalMs;+ } else {+ const retryDelayMs = Math.min(intervalMs, 5 * 60_000);+ nextUploadAt = Date.now() + retryDelayMs;+ }armTimer();},Math.min(remainingMs, maxTimeoutDelayMs),@@ -44,29 +75,40 @@ export function useWebDavAutoUpload() {const config = readWebDavAutoUploadConfig();if (!config.enabled || !config.webDavConfig) return;- nextUploadAt = Date.now() + config.intervalMinutes * 60_000;+ nextUploadAt = computeNextUploadAt(config);armTimer();}- async function runAutoUpload() {- if (uploading) return;+ async function runAutoUpload(expectedSequence?: number): Promise<boolean> {+ if (uploading) return false;const config = readWebDavAutoUploadConfig();- if (!config.enabled || !config.webDavConfig) return;+ if (!config.enabled || !config.webDavConfig) return false;++ const requestConfig = { ...config.webDavConfig };+ const requestTarget = webDavSyncTarget(requestConfig);+ const startSequence = expectedSequence ?? timerSequence;uploading = true;try {const secretsStatus = await webdavSyncSecretsStatus();const selection = readWebDavBackupSelection();const includeSecrets = (selection?.includeSecrets ?? secretsStatus.enabled) && secretsStatus.enabled && secretsStatus.hasSavedPassphrase;- const summary = await webdavSyncUpload(config.webDavConfig, settingsStore.editorSettings, undefined, includeSecrets, selection);- recordWebDavSyncSuccess(config.webDavConfig);+ const summary = await webdavSyncUpload(requestConfig, settingsStore.editorSettings, undefined, includeSecrets, selection);++ const currentConfig = readWebDavAutoUploadConfig();+ const isStillCurrent = Boolean(startSequence === timerSequence && currentConfig.enabled && currentConfig.webDavConfig && webDavSyncTarget(currentConfig.webDavConfig) === requestTarget);++ recordWebDavSyncSuccess(requestConfig);+ writeWebDavLastUploadAt(requestConfig, Date.now(), false);appendDebugLog("info", "[DBX][webdav:auto-upload:success]", {bytes: summary.bytes,remotePath: summary.remotePath,exportedAt: summary.exportedAt,});+ return isStillCurrent;} catch (error) {appendDebugLog("error", "[DBX][webdav:auto-upload:error]", error);+ return false;} finally {uploading = false;}diff --git a/apps/desktop/src/lib/webdav/webdavAutoUploadConfig.spec.ts b/apps/desktop/src/lib/webdav/webdavAutoUploadConfig.spec.tsindex 71414ff05b..a335d1e3ee 100644--- a/apps/desktop/src/lib/webdav/webdavAutoUploadConfig.spec.ts+++ b/apps/desktop/src/lib/webdav/webdavAutoUploadConfig.spec.ts@@ -1,5 +1,17 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { DEFAULT_WEB_DAV_AUTO_UPLOAD_INTERVAL_MINUTES, MAX_WEB_DAV_AUTO_UPLOAD_INTERVAL_MINUTES, WEB_DAV_LAST_SUCCESSFUL_SYNC_STORAGE_KEY, formatWebDavAutoUploadInterval, normalizedWebDavAutoUploadInterval, readWebDavLastSuccessfulSync, recordWebDavSyncSuccess } from "./webdavAutoUploadConfig";+import {+ DEFAULT_WEB_DAV_AUTO_UPLOAD_INTERVAL_MINUTES,+ MAX_WEB_DAV_AUTO_UPLOAD_INTERVAL_MINUTES,+ WEB_DAV_LAST_SUCCESSFUL_SYNC_STORAGE_KEY,+ clearWebDavLastUploadAt,+ formatWebDavAutoUploadInterval,+ normalizedWebDavAutoUploadInterval,+ readWebDavLastSuccessfulSync,+ readWebDavLastUploadAt,+ recordWebDavSyncSuccess,+ writeWebDavAutoUploadFields,+ writeWebDavLastUploadAt,+} from "./webdavAutoUploadConfig";const zhCnUnits = { minute: "分钟", hour: "小时", day: "天" };@@ -33,6 +45,7 @@ describe("WebDAV last successful sync", () => {vi.stubGlobal("localStorage", {getItem: (key: string) => values.get(key) ?? null,setItem: (key: string, value: string) => values.set(key, String(value)),+ removeItem: (key: string) => values.delete(key),clear: () => values.clear(),});});@@ -53,3 +66,86 @@ describe("WebDAV last successful sync", () => {expect(readWebDavLastSuccessfulSync(target)).toBeNull();});});++describe("WebDAV last upload timestamp storage", () => {+ const values = new Map<string, string>();++ beforeEach(() => {+ values.clear();+ vi.stubGlobal("localStorage", {+ getItem: (key: string) => values.get(key) ?? null,+ setItem: (key: string, value: string) => values.set(key, String(value)),+ removeItem: (key: string) => values.delete(key),+ clear: () => values.clear(),+ });+ });++ afterEach(() => vi.unstubAllGlobals());++ it("reads null when last upload timestamp is not stored or invalid", () => {+ const config = { endpoint: "https://dav.example.com" };+ expect(readWebDavLastUploadAt(config)).toBeNull();++ values.set("dbx-webdav-last-upload-at", "0");+ expect(readWebDavLastUploadAt(config)).toBeNull();++ values.set("dbx-webdav-last-upload-at", "-123");+ expect(readWebDavLastUploadAt(config)).toBeNull();++ values.set("dbx-webdav-last-upload-at", "not-a-number");+ expect(readWebDavLastUploadAt(config)).toBeNull();++ values.set("dbx-webdav-last-upload-at", JSON.stringify({ other: "invalid" }));+ expect(readWebDavLastUploadAt(config)).toBeNull();+ });++ it("reads and writes last upload timestamp bound to target", () => {+ const config = { endpoint: "https://dav.example.com" };+ const now = 1_700_000_000_000;+ writeWebDavLastUploadAt(config, now, false);+ expect(readWebDavLastUploadAt(config)).toBe(now);++ clearWebDavLastUploadAt(config, false);+ expect(readWebDavLastUploadAt(config)).toBeNull();+ });++ it("isolates upload timestamps across different endpoints, usernames, and remote paths", () => {+ const targetA = { endpoint: "https://dav.one.example.com", username: "userA", remotePath: "a.json" };+ const targetB = { endpoint: "https://dav.two.example.com", username: "userA", remotePath: "a.json" };+ const targetC = { endpoint: "https://dav.one.example.com", username: "userB", remotePath: "a.json" };+ const targetD = { endpoint: "https://dav.one.example.com", username: "userA", remotePath: "b.json" };++ writeWebDavLastUploadAt(targetA, 1_000, false);+ writeWebDavLastUploadAt(targetB, 2_000, false);++ expect(readWebDavLastUploadAt(targetA)).toBe(1_000);+ expect(readWebDavLastUploadAt(targetB)).toBe(2_000);+ expect(readWebDavLastUploadAt(targetC)).toBeNull();+ expect(readWebDavLastUploadAt(targetD)).toBeNull();++ clearWebDavLastUploadAt(targetA, false);+ expect(readWebDavLastUploadAt(targetA)).toBeNull();+ expect(readWebDavLastUploadAt(targetB)).toBe(2_000);+ });++ it("does not leak last upload timestamp when WebDAV endpoint changes", () => {+ const initialConfig = {+ endpoint: "https://dav.one.example.com",+ remotePath: "DBX/sync/snapshot.json",+ };+ writeWebDavAutoUploadFields(initialConfig, { enabled: true, intervalMinutes: 60 });+ writeWebDavLastUploadAt(initialConfig, 1_700_000_000_000, false);+ expect(readWebDavLastUploadAt()).toBe(1_700_000_000_000);++ // Same endpoint and remote path - timestamp preserved+ writeWebDavAutoUploadFields(initialConfig, { enabled: true, intervalMinutes: 120 });+ expect(readWebDavLastUploadAt()).toBe(1_700_000_000_000);++ // Changed endpoint - active config timestamp is null for new endpoint+ const newConfig = { ...initialConfig, endpoint: "https://dav.two.example.com" };+ writeWebDavAutoUploadFields(newConfig, { enabled: true, intervalMinutes: 120 });+ expect(readWebDavLastUploadAt()).toBeNull();+ // Previous config still retains its timestamp+ expect(readWebDavLastUploadAt(initialConfig)).toBe(1_700_000_000_000);+ });+});diff --git a/apps/desktop/src/lib/webdav/webdavAutoUploadConfig.ts b/apps/desktop/src/lib/webdav/webdavAutoUploadConfig.tsindex 9b71316383..08ea83e7dd 100644--- a/apps/desktop/src/lib/webdav/webdavAutoUploadConfig.ts+++ b/apps/desktop/src/lib/webdav/webdavAutoUploadConfig.ts@@ -1,11 +1,21 @@import type { SyncSelection, WebDavConfig } from "@/lib/backend/api";-import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";+import { safeLocalStorageGet, safeLocalStorageRemove, safeLocalStorageSet } from "@/lib/backend/safeStorage";export const WEB_DAV_BACKUP_SELECTION_STORAGE_KEY = "dbx-webdav-backup-selection";export const WEB_DAV_LAST_SUCCESSFUL_SYNC_STORAGE_KEY = "dbx-webdav-last-successful-sync";export const WEB_DAV_SYNC_SUCCESS_EVENT = "dbx:webdav-sync-succeeded";export const SYNC_METHOD_STORAGE_KEY = "dbx-sync-method";-export const WEB_DAV_AUTO_UPLOAD_STORAGE_KEYS = ["dbx-webdav-endpoint", "dbx-webdav-username", "dbx-webdav-user-agent", "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 WEB_DAV_LAST_UPLOAD_AT_STORAGE_KEY = "dbx-webdav-last-upload-at";+export const WEB_DAV_AUTO_UPLOAD_STORAGE_KEYS = [+ "dbx-webdav-endpoint",+ "dbx-webdav-username",+ "dbx-webdav-user-agent",+ "dbx-webdav-remote-path",+ "dbx-webdav-auto-upload-enabled",+ "dbx-webdav-auto-upload-interval-minutes",+ WEB_DAV_BACKUP_SELECTION_STORAGE_KEY,+ WEB_DAV_LAST_UPLOAD_AT_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;@@ -33,7 +43,7 @@ interface StoredWebDavSyncSuccess {completedAt: string;}-function webDavSyncTarget(config: WebDavConfig): string {+export function webDavSyncTarget(config: WebDavConfig): string {return JSON.stringify({endpoint: config.endpoint.trim(),username: config.username?.trim() || "",@@ -129,11 +139,100 @@ export function readWebDavAutoUploadConfig(): WebDavAutoUploadConfig {};}+function parseLastUploadMap(): Record<string, number> {+ const value = safeLocalStorageGet(WEB_DAV_LAST_UPLOAD_AT_STORAGE_KEY);+ if (!value) return {};+ try {+ const parsed = JSON.parse(value);+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {+ const result: Record<string, number> = {};+ for (const [k, v] of Object.entries(parsed)) {+ const num = Number(v);+ if (Number.isFinite(num) && num > 0) {+ result[k] = Math.round(num);+ }+ }+ return result;+ }+ } catch {+ // Malformed storage value+ }+ return {};+}++export function readWebDavLastUploadAt(config?: WebDavConfig | null): number | null {+ const targetConfig = config ?? readWebDavAutoUploadConfig().webDavConfig;+ if (!targetConfig) return null;+ const target = webDavSyncTarget(targetConfig);+ const map = parseLastUploadMap();+ const timestamp = map[target];+ if (!timestamp || !Number.isFinite(timestamp) || timestamp <= 0) return null;+ return timestamp;+}++export function writeWebDavLastUploadAt(targetOrTimestamp?: WebDavConfig | number | null, timestampOrNotify?: number | boolean, notify = true) {+ let targetConfig: WebDavConfig | null = null;+ let timestamp = Date.now();+ let shouldNotify = notify;++ if (typeof targetOrTimestamp === "number") {+ timestamp = targetOrTimestamp;+ shouldNotify = typeof timestampOrNotify === "boolean" ? timestampOrNotify : true;+ targetConfig = readWebDavAutoUploadConfig().webDavConfig;+ } else {+ targetConfig = targetOrTimestamp ?? readWebDavAutoUploadConfig().webDavConfig;+ if (typeof timestampOrNotify === "number") {+ timestamp = timestampOrNotify;+ shouldNotify = notify;+ } else if (typeof timestampOrNotify === "boolean") {+ shouldNotify = timestampOrNotify;+ }+ }++ if (!targetConfig) return;+ const target = webDavSyncTarget(targetConfig);+ const map = parseLastUploadMap();+ map[target] = Math.round(timestamp);+ safeLocalStorageSet(WEB_DAV_LAST_UPLOAD_AT_STORAGE_KEY, JSON.stringify(map));+ if (shouldNotify && typeof window !== "undefined") {+ window.dispatchEvent(new Event("dbx:webdav-auto-upload-config-changed"));+ }+}++export function clearWebDavLastUploadAt(configOrNotify?: WebDavConfig | boolean | null, notify = false) {+ let targetConfig: WebDavConfig | null = null;+ let shouldNotify = notify;++ if (typeof configOrNotify === "boolean") {+ shouldNotify = configOrNotify;+ } else if (configOrNotify) {+ targetConfig = configOrNotify;+ }++ if (targetConfig) {+ const target = webDavSyncTarget(targetConfig);+ const map = parseLastUploadMap();+ if (target in map) {+ delete map[target];+ safeLocalStorageSet(WEB_DAV_LAST_UPLOAD_AT_STORAGE_KEY, JSON.stringify(map));+ }+ } else {+ safeLocalStorageRemove(WEB_DAV_LAST_UPLOAD_AT_STORAGE_KEY);+ }++ if (shouldNotify && typeof window !== "undefined") {+ window.dispatchEvent(new Event("dbx:webdav-auto-upload-config-changed"));+ }+}+export function writeWebDavAutoUploadFields(config: WebDavConfig, autoUpload: { enabled: boolean; intervalMinutes: unknown }) {- safeLocalStorageSet("dbx-webdav-endpoint", config.endpoint.trim());+ const nextEndpoint = config.endpoint.trim();+ const nextRemotePath = config.remotePath?.trim() || DEFAULT_WEB_DAV_REMOTE_PATH;++ safeLocalStorageSet("dbx-webdav-endpoint", nextEndpoint);safeLocalStorageSet("dbx-webdav-username", config.username?.trim() || "");safeLocalStorageSet("dbx-webdav-user-agent", config.userAgent?.trim() || "");- safeLocalStorageSet("dbx-webdav-remote-path", config.remotePath?.trim() || DEFAULT_WEB_DAV_REMOTE_PATH);+ safeLocalStorageSet("dbx-webdav-remote-path", nextRemotePath);safeLocalStorageSet("dbx-webdav-auto-upload-enabled", String(autoUpload.enabled));safeLocalStorageSet("dbx-webdav-auto-upload-interval-minutes", String(normalizedWebDavAutoUploadInterval(autoUpload.intervalMinutes)));}diff --git a/packages/app-tests/webdavAutoUpload.test.ts b/packages/app-tests/webdavAutoUpload.test.tsindex 2624520309..6ab6e6cdae 100644--- a/packages/app-tests/webdavAutoUpload.test.ts+++ b/packages/app-tests/webdavAutoUpload.test.ts@@ -2,7 +2,7 @@ import assert from "node:assert/strict";import { afterEach, beforeEach, test, vi } from "vitest";import { createPinia, setActivePinia } from "pinia";import { useWebDavAutoUpload } from "@/composables/useWebDavAutoUpload";-import { readWebDavAutoUploadConfig } from "@/lib/webdav/webdavAutoUploadConfig";+import { readWebDavAutoUploadConfig, readWebDavLastUploadAt, writeWebDavLastUploadAt } from "@/lib/webdav/webdavAutoUploadConfig";const { webdavSyncSecretsStatusMock, webdavSyncUploadMock } = vi.hoisted(() => ({webdavSyncSecretsStatusMock: vi.fn(),@@ -158,3 +158,190 @@ test("keeps WebDAV auto-upload running outside the settings dialog", async () =>assert.equal(webdavSyncUploadMock.mock.calls.length, 1);});++test("triggers upload immediately on startup when last upload time is older than configured interval", async () => {+ localStorage.setItem("dbx-webdav-endpoint", "https://dav.example.com/");+ localStorage.setItem("dbx-webdav-auto-upload-enabled", "true");+ localStorage.setItem("dbx-webdav-auto-upload-interval-minutes", "1440");++ const threeDaysAgo = Date.now() - 3 * 24 * 60 * 60_000;+ writeWebDavLastUploadAt(threeDaysAgo, false);++ useWebDavAutoUpload();++ assert.equal(webdavSyncUploadMock.mock.calls.length, 0);++ await vi.advanceTimersByTimeAsync(0);++ assert.equal(webdavSyncUploadMock.mock.calls.length, 1);+ const updatedLastUploadAt = readWebDavLastUploadAt();+ assert.ok(updatedLastUploadAt !== null && updatedLastUploadAt >= Date.now() - 1000);+});++test("schedules upload for the remaining duration when last upload was within interval", async () => {+ localStorage.setItem("dbx-webdav-endpoint", "https://dav.example.com/");+ localStorage.setItem("dbx-webdav-auto-upload-enabled", "true");+ localStorage.setItem("dbx-webdav-auto-upload-interval-minutes", "1440");++ const tenHoursAgo = Date.now() - 10 * 60 * 60_000;+ writeWebDavLastUploadAt(tenHoursAgo, false);++ useWebDavAutoUpload();++ await vi.advanceTimersByTimeAsync(13 * 60 * 60_000);+ assert.equal(webdavSyncUploadMock.mock.calls.length, 0);++ await vi.advanceTimersByTimeAsync(1 * 60 * 60_000);+ assert.equal(webdavSyncUploadMock.mock.calls.length, 1);+});++test("manual upload resets the auto-upload countdown", async () => {+ localStorage.setItem("dbx-webdav-endpoint", "https://dav.example.com/");+ localStorage.setItem("dbx-webdav-auto-upload-enabled", "true");+ localStorage.setItem("dbx-webdav-auto-upload-interval-minutes", "60");++ useWebDavAutoUpload();++ await vi.advanceTimersByTimeAsync(30 * 60_000);+ assert.equal(webdavSyncUploadMock.mock.calls.length, 0);++ writeWebDavLastUploadAt(Date.now());++ await vi.advanceTimersByTimeAsync(30 * 60_000);+ assert.equal(webdavSyncUploadMock.mock.calls.length, 0);++ await vi.advanceTimersByTimeAsync(30 * 60_000);+ assert.equal(webdavSyncUploadMock.mock.calls.length, 1);+});++test("retries after backoff when auto-upload fails instead of infinite loop", async () => {+ webdavSyncUploadMock.mockRejectedValueOnce(new Error("Network offline"));+ localStorage.setItem("dbx-webdav-endpoint", "https://dav.example.com/");+ localStorage.setItem("dbx-webdav-auto-upload-enabled", "true");+ localStorage.setItem("dbx-webdav-auto-upload-interval-minutes", "1440");++ const threeDaysAgo = Date.now() - 3 * 24 * 60 * 60_000;+ writeWebDavLastUploadAt(threeDaysAgo, false);++ useWebDavAutoUpload();++ await vi.advanceTimersByTimeAsync(0);+ assert.equal(webdavSyncUploadMock.mock.calls.length, 1);++ await vi.advanceTimersByTimeAsync(4 * 60_000);+ assert.equal(webdavSyncUploadMock.mock.calls.length, 1);++ webdavSyncUploadMock.mockResolvedValueOnce({ bytes: 42, remotePath: "DBX/sync/snapshot.json" });+ await vi.advanceTimersByTimeAsync(1 * 60_000);+ assert.equal(webdavSyncUploadMock.mock.calls.length, 2);+});++test("auto-upload in-flight switching target records old target success without overwriting new target schedule", async () => {+ const targetA = { endpoint: "https://dav.a.example.com/" };+ const targetB = { endpoint: "https://dav.b.example.com/" };++ localStorage.setItem("dbx-webdav-endpoint", targetA.endpoint);+ localStorage.setItem("dbx-webdav-auto-upload-enabled", "true");+ localStorage.setItem("dbx-webdav-auto-upload-interval-minutes", "60");++ let resolveUploadA!: (value: any) => void;+ webdavSyncUploadMock.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveUploadA = resolve;+ }),+ );++ useWebDavAutoUpload();++ // Advance timer to trigger Target A upload+ await vi.advanceTimersByTimeAsync(60 * 60_000);+ assert.equal(webdavSyncUploadMock.mock.calls.length, 1);+ assert.equal(webdavSyncUploadMock.mock.calls[0][0].endpoint, targetA.endpoint);++ // While Target A upload is in flight, user switches target to Target B with 1440 min interval+ localStorage.setItem("dbx-webdav-endpoint", targetB.endpoint);+ localStorage.setItem("dbx-webdav-auto-upload-interval-minutes", "1440");+ window.dispatchEvent(new Event("dbx:webdav-auto-upload-config-changed"));++ const targetBBaseline = readWebDavLastUploadAt(targetB);+ assert.ok(targetBBaseline !== null);++ // Now Target A's upload completes+ const uploadCompletedAt = Date.now() + 10_000;+ vi.setSystemTime(uploadCompletedAt);+ resolveUploadA({ bytes: 100, remotePath: "DBX/sync/snapshot.json" });+ await vi.advanceTimersByTimeAsync(0);++ // Target A's last upload time was recorded for Target A+ assert.equal(readWebDavLastUploadAt(targetA), uploadCompletedAt);++ // Target B's last upload time was NOT overwritten by Target A's completion+ assert.equal(readWebDavLastUploadAt(targetB), targetBBaseline);++ // Target B must not have triggered prematurely+ assert.equal(webdavSyncUploadMock.mock.calls.length, 1);+});++test("auto-upload in-flight disabling auto-upload prevents rescheduling", async () => {+ localStorage.setItem("dbx-webdav-endpoint", "https://dav.example.com/");+ localStorage.setItem("dbx-webdav-auto-upload-enabled", "true");+ localStorage.setItem("dbx-webdav-auto-upload-interval-minutes", "60");++ let resolveUpload!: (value: any) => void;+ webdavSyncUploadMock.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveUpload = resolve;+ }),+ );++ useWebDavAutoUpload();++ await vi.advanceTimersByTimeAsync(60 * 60_000);+ assert.equal(webdavSyncUploadMock.mock.calls.length, 1);++ // Disable while upload is in progress+ localStorage.setItem("dbx-webdav-auto-upload-enabled", "false");+ window.dispatchEvent(new Event("dbx:webdav-auto-upload-config-changed"));++ resolveUpload({ bytes: 42, remotePath: "DBX/sync/snapshot.json" });+ await vi.advanceTimersByTimeAsync(0);++ // Advancing time should not trigger any more uploads+ await vi.advanceTimersByTimeAsync(120 * 60_000);+ assert.equal(webdavSyncUploadMock.mock.calls.length, 1);+});++test("manual upload in-flight switching target preserves target isolation", async () => {+ const targetA = { endpoint: "https://dav.a.example.com/" };+ const targetB = { endpoint: "https://dav.b.example.com/" };++ localStorage.setItem("dbx-webdav-endpoint", targetA.endpoint);+ localStorage.setItem("dbx-webdav-auto-upload-enabled", "true");+ localStorage.setItem("dbx-webdav-auto-upload-interval-minutes", "60");++ useWebDavAutoUpload();++ // Target A is configured+ writeWebDavLastUploadAt(targetA, 1_000, false);++ // User starts manual sync for Target A+ const uploadConfig = { ...targetA };+ // While manual upload is running, user switches settings to Target B+ localStorage.setItem("dbx-webdav-endpoint", targetB.endpoint);+ window.dispatchEvent(new Event("dbx:webdav-auto-upload-config-changed"));++ // Manual sync completes for Target A; checks whether targetA is still current+ const currentConfig = readWebDavAutoUploadConfig();+ const isCurrent = Boolean(currentConfig.enabled && currentConfig.webDavConfig && targetA.endpoint === currentConfig.webDavConfig.endpoint);+ assert.equal(isCurrent, false);++ const completionTime = Date.now() + 5000;+ writeWebDavLastUploadAt(uploadConfig, completionTime, isCurrent);++ // Target A has the updated timestamp+ assert.equal(readWebDavLastUploadAt(targetA), completionTime);+ // Target B does not have Target A's timestamp+ assert.notEqual(readWebDavLastUploadAt(targetB), completionTime);+});