From eaef730f1ec2b49d09a7b70d471dbadc053806df Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 26 Nov 2026 10:18:03 +0700 Subject: [PATCH] Allow opting out of automatic desktop update checks and background downloads (#10785) * feat(desktop): add automatic update modes and download progress Give desktop users control over background updater network traffic with a persisted updates.mode setting (automatic, notify, off; default automatic). Enforce off and notify behavior in the Electron main process as well as the renderer so automatic checks never leave the machine when opted out, quit-time installs only run in automatic mode, and explicit downloads stream live progress to both the OS window progress bar and the in-app UI. * fix(desktop): harden update mode races, installer errors, and shared UI state Address review findings across the desktop updater and settings store: - Re-evaluate the saved updates.mode before authorizing background downloads during an in-flight manifest check. - Serialize read-merge-write operations in the desktop settings store so overlapping patches cannot overwrite each other. - Capture synchronous installer launch errors from quitAndInstall and report failures on both cached and downloaded install paths. - Share updater state across Settings and the sidebar callout and guard against duplicate install commands and stale download loops. * fix(desktop): gate queued update checks and await macOS install handoff * fix(desktop): preserve quit-lifecycle handoff deadline on macOS * fix(desktop): consolidate update mode ownership and harden settings fallback * fix(desktop): read update mode after rollout bucket lookup --- .../src/desktop/settings/desktop-settings.ts | 25 + .../updates/desktop-app-updater.test.ts | 127 +++++ .../desktop/updates/desktop-app-updater.ts | 240 ++++++--- .../src/desktop/updates/desktop-updates.ts | 51 +- .../updates/resolve-update-callout.test.ts | 44 ++ .../desktop/updates/resolve-update-callout.ts | 92 +++- .../fake-desktop-app-updater-port.ts | 7 +- .../desktop/updates/update-callout-source.tsx | 112 ++++- .../updates/use-desktop-app-updater.ts | 104 +++- packages/app/src/hooks/use-settings/fakes.ts | 3 + .../src/hooks/use-settings/storage.test.ts | 1 + packages/app/src/i18n/resources/ar.ts | 36 ++ packages/app/src/i18n/resources/en.ts | 36 ++ packages/app/src/i18n/resources/es.ts | 38 ++ packages/app/src/i18n/resources/fr.ts | 38 ++ packages/app/src/i18n/resources/ja.ts | 37 ++ packages/app/src/i18n/resources/ko.ts | 37 ++ packages/app/src/i18n/resources/pt-BR.ts | 37 ++ packages/app/src/i18n/resources/ru.ts | 37 ++ packages/app/src/i18n/resources/zh-CN.ts | 36 ++ packages/app/src/screens/settings-screen.tsx | 154 +++++- packages/desktop/e2e/support/runtime.ts | 143 ++++-- packages/desktop/e2e/updates.spec.ts | 68 +++ .../desktop/src/daemon/daemon-manager.test.ts | 76 ++- packages/desktop/src/daemon/daemon-manager.ts | 18 +- .../src/features/app-update-service.test.ts | 467 +++++++++++++++++- .../src/features/app-update-service.ts | 282 ++++++++--- .../desktop/src/features/auto-updater.test.ts | 293 ++++++++++- packages/desktop/src/features/auto-updater.ts | 182 ++++++- packages/desktop/src/main.ts | 12 +- .../src/settings/desktop-settings.test.ts | 64 +++ .../desktop/src/settings/desktop-settings.ts | 139 ++++-- 32 files changed, 2725 insertions(+), 311 deletions(-) diff --git a/packages/app/src/desktop/settings/desktop-settings.ts b/packages/app/src/desktop/settings/desktop-settings.ts index bbe86baab..58d2ccbd8 100644 --- a/packages/app/src/desktop/settings/desktop-settings.ts +++ b/packages/app/src/desktop/settings/desktop-settings.ts @@ -11,8 +11,13 @@ import { i18n } from "@/i18n/i18next"; const DESKTOP_SETTINGS_QUERY_KEY = ["desktop-settings"] as const; +export type DesktopUpdateMode = "automatic" | "notify" | "off"; + export interface DesktopSettings { releaseChannel: ReleaseChannel; + updates: { + mode: DesktopUpdateMode; + }; notifications: { playSound: boolean; }; @@ -24,12 +29,16 @@ export interface DesktopSettings { export interface DesktopSettingsPatch { releaseChannel?: ReleaseChannel; + updates?: Partial; notifications?: Partial; daemon?: Partial; } export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = { releaseChannel: "stable", + updates: { + mode: "automatic", + }, notifications: { playSound: true, }, @@ -149,13 +158,24 @@ export async function migrateLegacyDesktopSettings(input: { await invokeDesktopCommand("migrate_legacy_desktop_settings", input); } +function parseUpdateMode(value: unknown): DesktopUpdateMode { + if (value === "automatic" || value === "notify" || value === "off") { + return value; + } + return DEFAULT_DESKTOP_SETTINGS.updates.mode; +} + function parseDesktopSettings(raw: unknown): DesktopSettings { const record = isRecord(raw) ? raw : {}; + const updates = isRecord(record.updates) ? record.updates : {}; const notifications = isRecord(record.notifications) ? record.notifications : {}; const daemon = isRecord(record.daemon) ? record.daemon : {}; return { releaseChannel: record.releaseChannel === "beta" ? "beta" : "stable", + updates: { + mode: parseUpdateMode(updates.mode), + }, notifications: { playSound: typeof notifications.playSound === "boolean" @@ -181,6 +201,10 @@ function mergeDesktopSettings( ): DesktopSettings { return { releaseChannel: updates.releaseChannel ?? current.releaseChannel, + updates: { + ...current.updates, + ...updates.updates, + }, notifications: { ...current.notifications, ...updates.notifications, @@ -195,6 +219,7 @@ function mergeDesktopSettings( function normalizePatch(updates: DesktopSettingsPatch): Record { return { ...(updates.releaseChannel ? { releaseChannel: updates.releaseChannel } : {}), + ...(updates.updates ? { updates: updates.updates } : {}), ...(updates.notifications ? { notifications: updates.notifications } : {}), ...(updates.daemon ? { daemon: updates.daemon } : {}), }; diff --git a/packages/app/src/desktop/updates/desktop-app-updater.test.ts b/packages/app/src/desktop/updates/desktop-app-updater.test.ts index e6f4e7608..76612d8f9 100644 --- a/packages/app/src/desktop/updates/desktop-app-updater.test.ts +++ b/packages/app/src/desktop/updates/desktop-app-updater.test.ts @@ -128,6 +128,43 @@ describe("desktop app updater — check", () => { }); }); + it("reports 'available' when an update is available to download without auto-downloading", async () => { + const { updater, port } = createUpdater({ now: () => 42 }); + port.nextCheckResult( + buildFakeCheckResult({ + hasUpdate: true, + readyToInstall: false, + downloading: false, + latestVersion: "1.2.3", + }), + ); + + await updater.checkForUpdates({ releaseChannel: "stable" }); + + expect(updater.getSnapshot()).toMatchObject({ + status: "available", + availableUpdate: { latestVersion: "1.2.3", readyToInstall: false, downloading: false }, + lastCheckedAt: 42, + }); + }); + + it("tracks download progress updates and clears them once install completes", async () => { + const { updater, port } = createUpdater(); + port.nextInstallResult(buildFakeInstallResult({ installed: true })); + + updater.setDownloadProgress({ + version: "1.2.3", + percent: 42.4, + transferred: 42, + total: 100, + bytesPerSecond: 10, + }); + expect(updater.getSnapshot().downloadProgress?.percent).toBe(42.4); + + await updater.installUpdate({ releaseChannel: "stable" }); + expect(updater.getSnapshot().downloadProgress).toBeNull(); + }); + it("reports 'up-to-date' when the check resolves with no update", async () => { const { updater, port } = createUpdater(); port.nextCheckResult(buildFakeCheckResult({ hasUpdate: false, readyToInstall: false })); @@ -340,6 +377,55 @@ describe("desktop app updater — install", () => { expect(updater.getSnapshot().status).toBe("up-to-date"); }); + it("moves to 'error' instead of 'up-to-date' when the install returns an errorMessage", async () => { + const { updater, port } = createUpdater(); + port.nextInstallResult( + buildFakeInstallResult({ + installed: false, + message: "Update failed: ECONNRESET", + errorMessage: "ECONNRESET", + }), + ); + + await updater.installUpdate({ releaseChannel: "stable" }); + + expect(updater.getSnapshot()).toMatchObject({ + status: "error", + errorMessage: "ECONNRESET", + downloadProgress: null, + isInstalling: false, + }); + }); + + it("ignores duplicate install requests and silent checks while an install is in progress", async () => { + const { updater, port } = createUpdater(); + let resolveInstall!: (result: ReturnType) => void; + port.installDesktopAppUpdate = async (input) => { + port.recordedInstalls.push(input); + return new Promise((resolve) => { + resolveInstall = resolve; + }); + }; + + const firstInstall = updater.installUpdate({ releaseChannel: "stable" }); + const secondInstall = await updater.installUpdate({ releaseChannel: "stable" }); + const silentCheck = await updater.checkForUpdates({ + releaseChannel: "stable", + intent: "automatic", + silent: true, + }); + + expect(secondInstall).toBeNull(); + expect(silentCheck).toBeNull(); + expect(port.recordedInstalls).toHaveLength(1); + expect(port.recordedChecks).toHaveLength(0); + expect(updater.getSnapshot().status).toBe("installing"); + + resolveInstall(buildFakeInstallResult({ installed: true })); + await firstInstall; + expect(updater.getSnapshot().status).toBe("installed"); + }); + it("reports the install error and moves to 'error' when the install throws", async () => { const { updater, port, reportedInstallErrors } = createUpdater(); const error = new Error("install failed"); @@ -462,6 +548,47 @@ describe("formatStatusText", () => { ).toBe("Restart now"); }); + it("formats download-available and live download progress status text", () => { + expect( + formatStatusText({ + status: "available", + availableUpdate: buildFakeCheckResult({ + hasUpdate: true, + readyToInstall: false, + downloading: false, + latestVersion: "1.2.3", + }), + installMessage: null, + lastCheckedAt: 42, + formatVersion, + formatLastCheckedAt, + }), + ).toBe("Update available: v1.2.3. Last checked at time-42."); + + expect( + formatStatusText({ + status: "installing", + availableUpdate: buildFakeCheckResult({ + hasUpdate: true, + readyToInstall: false, + downloading: false, + latestVersion: "1.2.3", + }), + downloadProgress: { + version: "1.2.3", + percent: 64.6, + transferred: 65, + total: 100, + bytesPerSecond: 10, + }, + installMessage: null, + lastCheckedAt: null, + formatVersion, + formatLastCheckedAt, + }), + ).toBe("Downloading v1.2.3... 65%"); + }); + it("uses the active app language for local status wrappers", async () => { await i18n.changeLanguage("zh-CN"); try { diff --git a/packages/app/src/desktop/updates/desktop-app-updater.ts b/packages/app/src/desktop/updates/desktop-app-updater.ts index eea1b6eff..432c423c6 100644 --- a/packages/app/src/desktop/updates/desktop-app-updater.ts +++ b/packages/app/src/desktop/updates/desktop-app-updater.ts @@ -1,6 +1,7 @@ import type { DesktopAppUpdateCheckResult, DesktopAppUpdateCheckIntent, + DesktopAppUpdateDownloadProgress, DesktopAppUpdateInstallResult, DesktopReleaseChannel, } from "@/desktop/updates/desktop-updates"; @@ -21,6 +22,7 @@ export const PENDING_RECHECK_MS = 10_000; export interface DesktopAppUpdaterSnapshot { status: DesktopAppUpdateStatus; availableUpdate: DesktopAppUpdateCheckResult | null; + downloadProgress: DesktopAppUpdateDownloadProgress | null; errorMessage: string | null; installMessage: string | null; lastCheckedAt: number | null; @@ -53,6 +55,7 @@ export interface DesktopAppUpdaterDeps { export interface DesktopAppUpdater { getSnapshot(): DesktopAppUpdaterSnapshot; subscribe(listener: () => void): () => void; + setDownloadProgress(progress: DesktopAppUpdateDownloadProgress | null): void; checkForUpdates(options?: { releaseChannel: DesktopReleaseChannel; intent?: DesktopAppUpdateCheckIntent; @@ -66,6 +69,7 @@ export interface DesktopAppUpdater { interface InternalState { status: DesktopAppUpdateStatus; availableUpdate: DesktopAppUpdateCheckResult | null; + downloadProgress: DesktopAppUpdateDownloadProgress | null; errorMessage: string | null; installMessage: string | null; lastCheckedAt: number | null; @@ -76,6 +80,7 @@ interface InternalState { const INITIAL_STATE: InternalState = { status: "idle", availableUpdate: null, + downloadProgress: null, errorMessage: null, installMessage: null, lastCheckedAt: null, @@ -87,6 +92,7 @@ function buildSnapshot(state: InternalState): DesktopAppUpdaterSnapshot { return { status: state.status, availableUpdate: state.availableUpdate, + downloadProgress: state.downloadProgress, errorMessage: state.errorMessage, installMessage: state.installMessage, lastCheckedAt: state.lastCheckedAt, @@ -102,9 +108,113 @@ function getErrorMessage(error: unknown): string { return String(error); } +function formatInstallingStatusText(input: { + availableUpdate: DesktopAppUpdateCheckResult | null; + downloadProgress: DesktopAppUpdateDownloadProgress | null; + formatVersion: (version: string | null | undefined) => string; +}): string { + const { availableUpdate, downloadProgress, formatVersion } = input; + if (downloadProgress == null) { + return i18n.t("desktop.updates.status.installing"); + } + const percent = Math.round(downloadProgress.percent); + const version = downloadProgress.version ?? availableUpdate?.latestVersion; + if (version) { + return i18n.t("desktop.updates.status.downloadingVersionProgress", { + version: formatVersion(version), + percent, + }); + } + return i18n.t("desktop.updates.status.downloadingProgress", { percent }); +} + +function formatPendingStatusText(input: { + availableUpdate: DesktopAppUpdateCheckResult | null; + downloadProgress: DesktopAppUpdateDownloadProgress | null; + lastCheckedAt: number | null; + formatVersion: (version: string | null | undefined) => string; + formatLastCheckedAt: (timestamp: number) => string; +}): string { + const { availableUpdate, downloadProgress, lastCheckedAt, formatVersion, formatLastCheckedAt } = + input; + const time = lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined; + if (availableUpdate?.latestVersion) { + const version = formatVersion(availableUpdate.latestVersion); + if (downloadProgress != null) { + return i18n.t( + time !== undefined + ? "desktop.updates.status.pendingWithVersionProgressAndLastChecked" + : "desktop.updates.status.pendingWithVersionProgress", + { version, percent: Math.round(downloadProgress.percent), time }, + ); + } + return i18n.t( + time !== undefined + ? "desktop.updates.status.pendingWithVersionAndLastChecked" + : "desktop.updates.status.pendingWithVersion", + { version, time }, + ); + } + if (time !== undefined) { + return i18n.t("desktop.updates.status.pendingWithLastChecked", { time }); + } + return i18n.t("desktop.updates.status.pending"); +} + +function formatAvailableStatusText(input: { + availableUpdate: DesktopAppUpdateCheckResult | null; + lastCheckedAt: number | null; + formatVersion: (version: string | null | undefined) => string; + formatLastCheckedAt: (timestamp: number) => string; +}): string { + const { availableUpdate, lastCheckedAt, formatVersion, formatLastCheckedAt } = input; + const time = lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined; + const isDownloadRequired = + availableUpdate?.hasUpdate === true && availableUpdate.readyToInstall === false; + if (availableUpdate?.latestVersion) { + const version = formatVersion(availableUpdate.latestVersion); + if (isDownloadRequired) { + return i18n.t( + time !== undefined + ? "desktop.updates.status.downloadAvailableWithVersionAndLastChecked" + : "desktop.updates.status.downloadAvailableWithVersion", + { version, time }, + ); + } + return i18n.t( + time !== undefined + ? "desktop.updates.status.availableWithVersionAndLastChecked" + : "desktop.updates.status.availableWithVersion", + { version, time }, + ); + } + if (isDownloadRequired) { + return time !== undefined + ? i18n.t("desktop.updates.status.downloadAvailableWithLastChecked", { time }) + : i18n.t("desktop.updates.status.downloadAvailable"); + } + return time !== undefined + ? i18n.t("desktop.updates.status.availableWithLastChecked", { time }) + : i18n.t("desktop.updates.status.available"); +} + +function resolveCheckOutcome(result: DesktopAppUpdateCheckResult): { + status: DesktopAppUpdateStatus; + availableUpdate: DesktopAppUpdateCheckResult | null; +} { + if (result.readyToInstall || (result.hasUpdate && !result.downloading)) { + return { status: "available", availableUpdate: result }; + } + if (result.hasUpdate) { + return { status: "pending", availableUpdate: result }; + } + return { status: "up-to-date", availableUpdate: null }; +} + export function formatStatusText(input: { status: DesktopAppUpdateStatus; availableUpdate: DesktopAppUpdateCheckResult | null; + downloadProgress?: DesktopAppUpdateDownloadProgress | null; installMessage: string | null; lastCheckedAt: number | null; formatVersion: (version: string | null | undefined) => string; @@ -113,79 +223,45 @@ export function formatStatusText(input: { const { status, availableUpdate, + downloadProgress = null, installMessage, lastCheckedAt, formatVersion, formatLastCheckedAt, } = input; - if (status === "checking") { - return i18n.t("desktop.updates.status.checking"); - } - + if (status === "checking") return i18n.t("desktop.updates.status.checking"); if (status === "installing") { - return i18n.t("desktop.updates.status.installing"); + return formatInstallingStatusText({ availableUpdate, downloadProgress, formatVersion }); } - if (status === "up-to-date") { - if (lastCheckedAt != null) { - return i18n.t("desktop.updates.status.upToDateWithLastChecked", { - time: formatLastCheckedAt(lastCheckedAt), - }); - } - return i18n.t("desktop.updates.status.upToDate"); + return lastCheckedAt != null + ? i18n.t("desktop.updates.status.upToDateWithLastChecked", { + time: formatLastCheckedAt(lastCheckedAt), + }) + : i18n.t("desktop.updates.status.upToDate"); } - if (status === "pending") { - if (availableUpdate?.latestVersion) { - return i18n.t( - lastCheckedAt != null - ? "desktop.updates.status.pendingWithVersionAndLastChecked" - : "desktop.updates.status.pendingWithVersion", - { - version: formatVersion(availableUpdate.latestVersion), - time: lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined, - }, - ); - } - - if (lastCheckedAt != null) { - return i18n.t("desktop.updates.status.pendingWithLastChecked", { - time: formatLastCheckedAt(lastCheckedAt), - }); - } - return i18n.t("desktop.updates.status.pending"); + return formatPendingStatusText({ + availableUpdate, + downloadProgress, + lastCheckedAt, + formatVersion, + formatLastCheckedAt, + }); } - if (status === "available") { - if (availableUpdate?.latestVersion) { - return i18n.t( - lastCheckedAt != null - ? "desktop.updates.status.availableWithVersionAndLastChecked" - : "desktop.updates.status.availableWithVersion", - { - version: formatVersion(availableUpdate.latestVersion), - time: lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined, - }, - ); - } - - if (lastCheckedAt != null) { - return i18n.t("desktop.updates.status.availableWithLastChecked", { - time: formatLastCheckedAt(lastCheckedAt), - }); - } - return i18n.t("desktop.updates.status.available"); + return formatAvailableStatusText({ + availableUpdate, + lastCheckedAt, + formatVersion, + formatLastCheckedAt, + }); } - if (status === "installed") { return installMessage ?? i18n.t("desktop.updates.status.installed"); } - - if (status === "error") { - return i18n.t("desktop.updates.status.failed"); - } - + if (status === "error") return i18n.t("desktop.updates.status.failed"); return i18n.t("desktop.updates.status.idle"); } @@ -202,6 +278,16 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp } } + function setDownloadProgress(progress: DesktopAppUpdateDownloadProgress | null): void { + if (progress === null && state.downloadProgress === null) { + return; + } + commit({ + ...state, + downloadProgress: progress, + }); + } + async function checkForUpdates(options?: { releaseChannel: DesktopReleaseChannel; intent?: DesktopAppUpdateCheckIntent; @@ -211,7 +297,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp return null; } const { releaseChannel, intent = "manual", silent = false } = options; - if (silent && state.status === "checking") { + if (silent && (state.status === "checking" || state.isInstalling)) { return null; } @@ -241,6 +327,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp ...state, status: "error", availableUpdate: null, + downloadProgress: null, errorMessage: result.errorMessage, installMessage: null, lastCheckedAt: nextLastCheckedAt, @@ -248,24 +335,13 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp return result; } - let nextStatus: DesktopAppUpdateStatus; - let nextAvailable: DesktopAppUpdateCheckResult | null; - - if (result.readyToInstall) { - nextStatus = "available"; - nextAvailable = result; - } else if (result.hasUpdate) { - nextStatus = "pending"; - nextAvailable = result; - } else { - nextStatus = "up-to-date"; - nextAvailable = null; - } + const outcome = resolveCheckOutcome(result); commit({ ...state, - status: nextStatus, - availableUpdate: nextAvailable, + status: outcome.status, + availableUpdate: outcome.availableUpdate, + downloadProgress: outcome.status === "pending" ? state.downloadProgress : null, errorMessage: null, installMessage: null, lastCheckedAt: nextLastCheckedAt, @@ -284,6 +360,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp commit({ ...state, status: "error", + downloadProgress: null, errorMessage: message, lastCheckedAt: intent === "manual" ? deps.now() : state.lastCheckedAt, }); @@ -295,6 +372,10 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp async function installUpdate(options: { releaseChannel: DesktopReleaseChannel; }): Promise { + if (state.isInstalling) { + return null; + } + commit({ ...state, status: "installing", @@ -307,10 +388,23 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp releaseChannel: options.releaseChannel, }); const nextLastCheckedAt = deps.now(); + if (!result.installed && result.errorMessage) { + commit({ + ...state, + status: "error", + downloadProgress: null, + errorMessage: result.errorMessage, + installMessage: null, + lastCheckedAt: nextLastCheckedAt, + isInstalling: false, + }); + return result; + } commit({ ...state, status: result.installed ? "installed" : "up-to-date", availableUpdate: null, + downloadProgress: null, installMessage: result.message, lastCheckedAt: nextLastCheckedAt, isInstalling: false, @@ -326,6 +420,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp commit({ ...state, status: "error", + downloadProgress: null, errorMessage: message, isInstalling: false, }); @@ -341,6 +436,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp listeners.delete(listener); }; }, + setDownloadProgress, checkForUpdates, installUpdate, }; diff --git a/packages/app/src/desktop/updates/desktop-updates.ts b/packages/app/src/desktop/updates/desktop-updates.ts index 1246a6b86..526cda764 100644 --- a/packages/app/src/desktop/updates/desktop-updates.ts +++ b/packages/app/src/desktop/updates/desktop-updates.ts @@ -1,11 +1,21 @@ import { isElectronRuntime } from "@/desktop/host"; +import { listenToDesktopEvent, type DesktopEventUnlisten } from "@/desktop/electron/events"; import { invokeDesktopCommand } from "@/desktop/electron/invoke"; import { isWeb } from "@/constants/platform"; import { i18n } from "@/i18n/i18next"; +export interface DesktopAppUpdateDownloadProgress { + version: string | null; + percent: number; + transferred: number; + total: number; + bytesPerSecond: number; +} + export interface DesktopAppUpdateCheckResult { hasUpdate: boolean; readyToInstall: boolean; + downloading: boolean; currentVersion: string | null; latestVersion: string | null; body: string | null; @@ -17,6 +27,7 @@ export interface DesktopAppUpdateInstallResult { installed: boolean; version: string | null; message: string; + errorMessage?: string | null; } export interface DesktopRuntimeInfo { @@ -115,9 +126,13 @@ export async function checkDesktopAppUpdate({ throw new Error("Unexpected response while checking desktop updates."); } + const hasUpdate = result.hasUpdate === true; + const readyToInstall = result.readyToInstall === true; return { - hasUpdate: result.hasUpdate === true, - readyToInstall: result.readyToInstall === true, + hasUpdate, + readyToInstall, + downloading: + typeof result.downloading === "boolean" ? result.downloading : hasUpdate && !readyToInstall, currentVersion: toStringOrNull(result.currentVersion), latestVersion: toStringOrNull(result.latestVersion), body: toStringOrNull(result.body), @@ -126,6 +141,36 @@ export async function checkDesktopAppUpdate({ }; } +export function parseDesktopAppUpdateDownloadProgress( + raw: unknown, +): DesktopAppUpdateDownloadProgress | null { + if (!isRecord(raw)) { + return null; + } + const percent = toNumberOr(Number.NaN, raw.percent); + if (!Number.isFinite(percent)) { + return null; + } + return { + version: toStringOrNull(raw.version), + percent: Math.max(0, Math.min(100, percent)), + transferred: toNumberOr(0, raw.transferred), + total: toNumberOr(0, raw.total), + bytesPerSecond: toNumberOr(0, raw.bytesPerSecond), + }; +} + +export async function subscribeDesktopAppUpdateDownloadProgress( + handler: (progress: DesktopAppUpdateDownloadProgress | null) => void, +): Promise { + if (!shouldShowDesktopUpdateSection()) { + return () => {}; + } + return listenToDesktopEvent("app-update-download-progress", (payload) => { + handler(payload === null ? null : parseDesktopAppUpdateDownloadProgress(payload)); + }); +} + export async function installDesktopAppUpdate({ releaseChannel, }: { @@ -136,10 +181,12 @@ export async function installDesktopAppUpdate({ throw new Error("Unexpected response while installing desktop update."); } + const errorMessage = toStringOrNull(result.errorMessage); return { installed: result.installed === true, version: toStringOrNull(result.version), message: toStringOrNull(result.message) ?? i18n.t("desktop.updates.status.installed"), + ...(errorMessage ? { errorMessage } : {}), }; } diff --git a/packages/app/src/desktop/updates/resolve-update-callout.test.ts b/packages/app/src/desktop/updates/resolve-update-callout.test.ts index e5ecc09ec..ab9ccd740 100644 --- a/packages/app/src/desktop/updates/resolve-update-callout.test.ts +++ b/packages/app/src/desktop/updates/resolve-update-callout.test.ts @@ -76,6 +76,50 @@ describe("resolveUpdateCalloutDescriptor", () => { expect(descriptor?.dismissalKey).toBe("desktop-update:installing:1.2.3"); }); + it("labels the callout as Download when the update has not been downloaded yet", () => { + const descriptor = resolveUpdateCalloutDescriptor( + input({ availableUpdate: { latestVersion: "1.2.3", readyToInstall: false } }), + ); + + expect(descriptor?.title).toBe("Update available"); + expect(descriptor?.body).toEqual({ + kind: "available", + versionLabel: "v1.2.3", + readyToInstall: false, + }); + expect(descriptor?.actions).toEqual([ + { role: "changelog", label: "What's new" }, + { role: "install", label: "Download", variant: "primary", disabled: false }, + ]); + }); + + it("shows download progress while downloading an update", () => { + const descriptor = resolveUpdateCalloutDescriptor( + input({ + status: "installing", + isInstalling: true, + downloadProgress: { + version: "1.2.3", + percent: 42.2, + transferred: 42, + total: 100, + bytesPerSecond: 10, + }, + }), + ); + + expect(descriptor?.title).toBe("Downloading update"); + expect(descriptor?.body).toEqual({ + kind: "downloading", + versionLabel: "v1.2.3", + percent: 42, + }); + expect(descriptor?.actions).toEqual([ + { role: "changelog", label: "What's new" }, + { role: "install", label: "Downloading...", variant: "primary", disabled: true }, + ]); + }); + it("shows a retry action and surfaces the error message on error", () => { const descriptor = resolveUpdateCalloutDescriptor( input({ status: "error", errorMessage: "Download failed", availableUpdate: null }), diff --git a/packages/app/src/desktop/updates/resolve-update-callout.ts b/packages/app/src/desktop/updates/resolve-update-callout.ts index 7b80cec3e..fb4f8ace0 100644 --- a/packages/app/src/desktop/updates/resolve-update-callout.ts +++ b/packages/app/src/desktop/updates/resolve-update-callout.ts @@ -1,8 +1,10 @@ import type { DesktopAppUpdateStatus } from "@/desktop/updates/use-desktop-app-updater"; +import type { DesktopAppUpdateDownloadProgress } from "@/desktop/updates/desktop-updates"; import { i18n } from "@/i18n/i18next"; export type UpdateCalloutBody = - | { kind: "available"; versionLabel: string | null } + | { kind: "available"; versionLabel: string | null; readyToInstall?: boolean } + | { kind: "downloading"; versionLabel: string | null; percent: number } | { kind: "installing" } | { kind: "error"; message: string }; @@ -31,7 +33,8 @@ export interface ResolveUpdateCalloutInput { isDesktopApp: boolean; status: DesktopAppUpdateStatus; isInstalling: boolean; - availableUpdate: { latestVersion?: string | null } | null; + availableUpdate: { latestVersion?: string | null; readyToInstall?: boolean } | null; + downloadProgress?: DesktopAppUpdateDownloadProgress | null; errorMessage: string | null; } @@ -40,6 +43,59 @@ function formatVersionLabel(latestVersion: string | null | undefined): string | return `v${latestVersion.replace(/^v/i, "")}`; } +function resolveCalloutPresentation(input: { + isError: boolean; + isInstalling: boolean; + readyToInstall: boolean; + latestVersion: string | null; + downloadProgress: DesktopAppUpdateDownloadProgress | null | undefined; + errorMessage: string | null; +}): { title: string; body: UpdateCalloutBody } { + if (input.isInstalling && input.downloadProgress != null) { + return { + title: i18n.t("desktop.updates.callout.downloadingTitle"), + body: { + kind: "downloading", + versionLabel: formatVersionLabel(input.latestVersion), + percent: Math.round(input.downloadProgress.percent), + }, + }; + } + if (input.isInstalling) { + return { + title: i18n.t("desktop.updates.callout.installingTitle"), + body: { kind: "installing" }, + }; + } + if (input.isError) { + return { + title: i18n.t("desktop.updates.callout.failedTitle"), + body: { + kind: "error", + message: input.errorMessage ?? i18n.t("desktop.updates.callout.genericError"), + }, + }; + } + const versionLabel = formatVersionLabel(input.latestVersion); + return { + title: i18n.t("desktop.updates.callout.availableTitle"), + body: input.readyToInstall + ? { kind: "available", versionLabel } + : { kind: "available", versionLabel, readyToInstall: false }, + }; +} + +function resolveInstallActionLabel(input: { + isDownloading: boolean; + isInstalling: boolean; + readyToInstall: boolean; +}): string { + if (input.isDownloading) return i18n.t("desktop.updates.callout.downloadingAction"); + if (input.isInstalling) return i18n.t("desktop.updates.callout.installingAction"); + if (input.readyToInstall) return i18n.t("desktop.updates.callout.installAndRestart"); + return i18n.t("desktop.updates.callout.downloadAndRestart"); +} + export function resolveUpdateCalloutDescriptor( input: ResolveUpdateCalloutInput, ): UpdateCalloutDescriptor | null { @@ -50,26 +106,22 @@ export function resolveUpdateCalloutDescriptor( const isError = input.status === "error"; const isInstalling = input.isInstalling; + const isDownloading = isInstalling && input.downloadProgress != null; const isAvailable = !isInstalling && !isError; + const readyToInstall = input.availableUpdate?.readyToInstall !== false; - const latestVersion = input.availableUpdate?.latestVersion ?? null; + const latestVersion = + input.availableUpdate?.latestVersion ?? input.downloadProgress?.version ?? null; const dismissalKey = `desktop-update:${input.status}:${latestVersion ?? "unknown"}`; - let title: string; - let body: UpdateCalloutBody; - if (isInstalling) { - title = i18n.t("desktop.updates.callout.installingTitle"); - body = { kind: "installing" }; - } else if (isError) { - title = i18n.t("desktop.updates.callout.failedTitle"); - body = { - kind: "error", - message: input.errorMessage ?? i18n.t("desktop.updates.callout.genericError"), - }; - } else { - title = i18n.t("desktop.updates.callout.availableTitle"); - body = { kind: "available", versionLabel: formatVersionLabel(latestVersion) }; - } + const { title, body } = resolveCalloutPresentation({ + isError, + isInstalling, + readyToInstall, + latestVersion, + downloadProgress: input.downloadProgress, + errorMessage: input.errorMessage, + }); const actions: UpdateCalloutActionDescriptor[] = [ { role: "changelog", label: i18n.t("desktop.updates.callout.whatsNew") }, @@ -79,9 +131,7 @@ export function resolveUpdateCalloutDescriptor( } else { actions.push({ role: "install", - label: isInstalling - ? i18n.t("desktop.updates.callout.installingAction") - : i18n.t("desktop.updates.callout.installAndRestart"), + label: resolveInstallActionLabel({ isDownloading, isInstalling, readyToInstall }), variant: "primary", disabled: isInstalling, }); diff --git a/packages/app/src/desktop/updates/test-utils/fake-desktop-app-updater-port.ts b/packages/app/src/desktop/updates/test-utils/fake-desktop-app-updater-port.ts index 471bb8e01..905aa0554 100644 --- a/packages/app/src/desktop/updates/test-utils/fake-desktop-app-updater-port.ts +++ b/packages/app/src/desktop/updates/test-utils/fake-desktop-app-updater-port.ts @@ -34,9 +34,12 @@ type InstallOutcome = function buildCheckResult( overrides: Partial = {}, ): DesktopAppUpdateCheckResult { + const hasUpdate = overrides.hasUpdate ?? false; + const readyToInstall = overrides.readyToInstall ?? false; return { - hasUpdate: false, - readyToInstall: false, + hasUpdate, + readyToInstall, + downloading: overrides.downloading ?? (hasUpdate && !readyToInstall), currentVersion: null, latestVersion: null, body: null, diff --git a/packages/app/src/desktop/updates/update-callout-source.tsx b/packages/app/src/desktop/updates/update-callout-source.tsx index 62cf7fede..790d9af92 100644 --- a/packages/app/src/desktop/updates/update-callout-source.tsx +++ b/packages/app/src/desktop/updates/update-callout-source.tsx @@ -1,7 +1,8 @@ import { Gift } from "lucide-react-native"; -import { type ReactNode, useEffect, useRef } from "react"; +import { type ReactNode, useEffect, useMemo, useRef } from "react"; +import { View } from "react-native"; import { useTranslation } from "react-i18next"; -import { useUnistyles } from "react-native-unistyles"; +import { StyleSheet, useUnistyles } from "react-native-unistyles"; import { type SidebarCalloutAction, SidebarCalloutDescriptionText, @@ -19,9 +20,24 @@ import { openChangelog } from "@/changelog"; const CHECK_INTERVAL_MS = 30 * 60 * 1000; function renderBody(body: UpdateCalloutBody, t: ReturnType["t"]): ReactNode { + if (body.kind === "downloading") { + return ( + + ); + } if (body.kind === "installing") return t("desktop.updates.callout.installingDescription"); if (body.kind === "error") return body.message; - return ; + return ( + + ); } function materializeActions( @@ -42,8 +58,11 @@ export function UpdateCalloutSource() { const { theme } = useUnistyles(); const { isDesktopApp, + updateMode, + isLoadingSettings, status, availableUpdate, + downloadProgress, errorMessage, checkForUpdates, installUpdate, @@ -58,7 +77,7 @@ export function UpdateCalloutSource() { void checkForUpdates(); }); useEffect(() => { - if (!isDesktopApp) return; + if (!isDesktopApp || isLoadingSettings || updateMode === "off") return; void checkForUpdates({ intent: "automatic", silent: true }); @@ -71,7 +90,7 @@ export function UpdateCalloutSource() { clearInterval(intervalRef.current); } }; - }, [isDesktopApp, checkForUpdates]); + }, [isDesktopApp, isLoadingSettings, updateMode, checkForUpdates]); useEffect(() => { const descriptor = resolveUpdateCalloutDescriptor({ @@ -79,6 +98,7 @@ export function UpdateCalloutSource() { status, isInstalling, availableUpdate, + downloadProgress, errorMessage, }); if (!descriptor) return; @@ -103,6 +123,7 @@ export function UpdateCalloutSource() { }, [ availableUpdate, callouts, + downloadProgress, errorMessage, install, isDesktopApp, @@ -117,23 +138,94 @@ export function UpdateCalloutSource() { return null; } +function formatAvailableSummary( + t: ReturnType["t"], + versionLabel: string | undefined, + readyToInstall: boolean, +): string { + if (readyToInstall) { + return versionLabel + ? t("desktop.updates.callout.versionReady", { version: versionLabel }) + : t("desktop.updates.callout.newVersionReady"); + } + return versionLabel + ? t("desktop.updates.callout.versionAvailable", { version: versionLabel }) + : t("desktop.updates.callout.newVersionAvailable"); +} + function UpdateAvailableDescription({ versionLabel, + readyToInstall, t, }: { versionLabel?: string; + readyToInstall: boolean; t: ReturnType["t"]; }) { + const summary = formatAvailableSummary(t, versionLabel, readyToInstall); + return ( <> - - {versionLabel - ? t("desktop.updates.callout.versionReady", { version: versionLabel }) - : t("desktop.updates.callout.newVersionReady")} - + {summary} {t("desktop.updates.callout.restartWarning")} ); } + +function UpdateDownloadingDescription({ + versionLabel, + percent, + t, +}: { + versionLabel?: string; + percent: number; + t: ReturnType["t"]; +}) { + const clampedPercent = Math.max(0, Math.min(100, percent)); + const accessibilityValue = useMemo( + () => ({ min: 0, max: 100, now: clampedPercent }), + [clampedPercent], + ); + const progressFillStyle = useMemo( + () => [styles.progressFill, { width: `${clampedPercent}%` as const }], + [clampedPercent], + ); + return ( + + + {versionLabel + ? t("desktop.updates.callout.downloadingVersionDescription", { + version: versionLabel, + percent: clampedPercent, + }) + : t("desktop.updates.callout.downloadingDescription", { percent: clampedPercent })} + + + + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + progressContainer: { + gap: theme.spacing[2], + }, + progressTrack: { + height: 4, + borderRadius: theme.borderRadius.full, + backgroundColor: theme.colors.surface3, + overflow: "hidden", + }, + progressFill: { + height: "100%", + borderRadius: theme.borderRadius.full, + backgroundColor: theme.colors.accent, + }, +})); diff --git a/packages/app/src/desktop/updates/use-desktop-app-updater.ts b/packages/app/src/desktop/updates/use-desktop-app-updater.ts index 16f8eb52f..f17792816 100644 --- a/packages/app/src/desktop/updates/use-desktop-app-updater.ts +++ b/packages/app/src/desktop/updates/use-desktop-app-updater.ts @@ -1,30 +1,94 @@ -import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react"; +import { useCallback, useEffect, useSyncExternalStore } from "react"; import { checkDesktopAppUpdate, formatVersionWithPrefix, installDesktopAppUpdate, shouldShowDesktopUpdateSection, + subscribeDesktopAppUpdateDownloadProgress, type DesktopAppUpdateCheckResult, type DesktopAppUpdateCheckIntent, + type DesktopAppUpdateDownloadProgress, type DesktopAppUpdateInstallResult, } from "@/desktop/updates/desktop-updates"; -import { useDesktopSettings } from "@/desktop/settings/desktop-settings"; +import { useDesktopSettings, type DesktopUpdateMode } from "@/desktop/settings/desktop-settings"; import { useDesktopIpcErrorReporter } from "@/desktop/hooks/desktop-ipc-error"; import { PENDING_RECHECK_MS, createDesktopAppUpdater, formatStatusText, + type DesktopAppUpdater, + type DesktopAppUpdaterErrorReport, type DesktopAppUpdateStatus, } from "@/desktop/updates/desktop-app-updater"; import { formatMessageTimestamp } from "@/utils/time"; export type { DesktopAppUpdateStatus }; +let activeInstallErrorReporter: ((report: DesktopAppUpdaterErrorReport) => void) | null = null; +let sharedDesktopAppUpdater: DesktopAppUpdater | null = null; +let progressSubscriptionCount = 0; +let progressUnsubscribe: (() => void) | null = null; + +function getSharedDesktopAppUpdater(): DesktopAppUpdater { + if (!sharedDesktopAppUpdater) { + sharedDesktopAppUpdater = createDesktopAppUpdater({ + port: { + checkDesktopAppUpdate, + installDesktopAppUpdate, + }, + now: () => Date.now(), + reportInstallError: (report) => { + activeInstallErrorReporter?.(report); + }, + }); + } + return sharedDesktopAppUpdater; +} + +function retainDownloadProgressSubscription(updater: DesktopAppUpdater): () => void { + progressSubscriptionCount += 1; + if (progressSubscriptionCount === 1) { + let active = true; + const teardown = () => { + active = false; + }; + progressUnsubscribe = teardown; + void subscribeDesktopAppUpdateDownloadProgress((progress) => { + if (active) { + updater.setDownloadProgress(progress); + } + }) + .then((cleanup) => { + if (active) { + progressUnsubscribe = () => { + active = false; + cleanup(); + }; + } else { + cleanup(); + } + return undefined; + }) + .catch(() => undefined); + } + + return () => { + progressSubscriptionCount = Math.max(0, progressSubscriptionCount - 1); + if (progressSubscriptionCount === 0) { + progressUnsubscribe?.(); + progressUnsubscribe = null; + } + }; +} + export interface UseDesktopAppUpdaterReturn { isDesktopApp: boolean; + updateMode: DesktopUpdateMode; + isLoadingSettings: boolean; status: DesktopAppUpdateStatus; statusText: string; availableUpdate: DesktopAppUpdateCheckResult | null; + downloadProgress: DesktopAppUpdateDownloadProgress | null; errorMessage: string | null; lastCheckedAt: number | null; isChecking: boolean; @@ -38,22 +102,15 @@ export interface UseDesktopAppUpdaterReturn { export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn { const isDesktopApp = shouldShowDesktopUpdateSection(); - const { settings: desktopSettings } = useDesktopSettings(); + const { settings: desktopSettings, isLoading: isLoadingSettings } = useDesktopSettings(); const releaseChannel = desktopSettings.releaseChannel; + const updateMode = desktopSettings.updates.mode; const reportError = useDesktopIpcErrorReporter(); + const updater = getSharedDesktopAppUpdater(); - const updater = useMemo( - () => - createDesktopAppUpdater({ - port: { - checkDesktopAppUpdate, - installDesktopAppUpdate, - }, - now: () => Date.now(), - reportInstallError: reportError, - }), - [reportError], - ); + useEffect(() => { + activeInstallErrorReporter = reportError; + }, [reportError]); const snapshot = useSyncExternalStore( updater.subscribe, @@ -84,13 +141,20 @@ export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn { useEffect(() => { if (!isDesktopApp) { + return undefined; + } + return retainDownloadProgressSubscription(updater); + }, [isDesktopApp, updater]); + + useEffect(() => { + if (!isDesktopApp || isLoadingSettings || updateMode === "off") { return; } void checkForUpdates({ intent: "automatic", silent: true }); - }, [checkForUpdates, isDesktopApp]); + }, [checkForUpdates, isDesktopApp, isLoadingSettings, updateMode]); useEffect(() => { - if (!isDesktopApp || snapshot.status !== "pending") { + if (!isDesktopApp || snapshot.status !== "pending" || updateMode === "off") { return undefined; } @@ -101,20 +165,24 @@ export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn { return () => { clearInterval(intervalId); }; - }, [checkForUpdates, isDesktopApp, snapshot.status]); + }, [checkForUpdates, isDesktopApp, snapshot.status, updateMode]); return { isDesktopApp, + updateMode, + isLoadingSettings, status: snapshot.status, statusText: formatStatusText({ status: snapshot.status, availableUpdate: snapshot.availableUpdate, + downloadProgress: snapshot.downloadProgress, installMessage: snapshot.installMessage, lastCheckedAt: snapshot.lastCheckedAt, formatVersion: formatVersionWithPrefix, formatLastCheckedAt: (timestamp) => formatMessageTimestamp(new Date(timestamp)), }), availableUpdate: snapshot.availableUpdate, + downloadProgress: snapshot.downloadProgress, errorMessage: snapshot.errorMessage, lastCheckedAt: snapshot.lastCheckedAt, isChecking: snapshot.isChecking, diff --git a/packages/app/src/hooks/use-settings/fakes.ts b/packages/app/src/hooks/use-settings/fakes.ts index 691c3e9c1..cc921afed 100644 --- a/packages/app/src/hooks/use-settings/fakes.ts +++ b/packages/app/src/hooks/use-settings/fakes.ts @@ -32,6 +32,9 @@ export interface FakeDesktopBridge extends DesktopSettingsBridge { const DEFAULT_DESKTOP: DesktopSettings = { releaseChannel: "stable", + updates: { + mode: "automatic", + }, notifications: { playSound: true, }, diff --git a/packages/app/src/hooks/use-settings/storage.test.ts b/packages/app/src/hooks/use-settings/storage.test.ts index 6400e15fc..20cba8824 100644 --- a/packages/app/src/hooks/use-settings/storage.test.ts +++ b/packages/app/src/hooks/use-settings/storage.test.ts @@ -656,6 +656,7 @@ describe("loadSettingsFromStorage", () => { isElectron: true, settings: { releaseChannel: "beta", + updates: { mode: "automatic" }, notifications: { playSound: true }, daemon: { manageBuiltInDaemon: false, keepRunningAfterQuit: true }, }, diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 023e88b7a..36ffc325e 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -1550,6 +1550,8 @@ export const ar: TranslationResources = { status: { checking: "جارٍ التحقق من وجود تحديثات للتطبيق...", installing: "جارٍ تثبيت تحديث التطبيق...", + downloadingVersionProgress: "جارٍ تنزيل {{version}}... {{percent}}%", + downloadingProgress: "جارٍ تنزيل تحديث التطبيق... {{percent}}%", upToDate: "التطبيق محدث.", upToDateWithLastChecked: "Up to date. Last checked at {{time}}.", pending: "سنخبرك عندما يصبح التحديث جاهزًا.", @@ -1557,6 +1559,14 @@ export const ar: TranslationResources = { pendingWithVersion: "تم العثور على تحديث: {{version}}. جارٍ التنزيل...", pendingWithVersionAndLastChecked: "تم العثور على تحديث: {{version}}. جارٍ التنزيل... آخر فحص في {{time}}.", + pendingWithVersionProgress: "تم العثور على تحديث: {{version}}. جارٍ التنزيل... {{percent}}%", + pendingWithVersionProgressAndLastChecked: + "تم العثور على تحديث: {{version}}. جارٍ التنزيل... {{percent}}% آخر فحص في {{time}}.", + downloadAvailableWithVersion: "التحديث متاح: {{version}}", + downloadAvailableWithVersionAndLastChecked: + "التحديث متاح: {{version}}. آخر فحص في {{time}}.", + downloadAvailable: "يتوفر تحديث للتطبيق.", + downloadAvailableWithLastChecked: "يتوفر تحديث للتطبيق. آخر فحص في {{time}}.", availableWithVersion: "التحديث جاهز:{{version}}", availableWithVersionAndLastChecked: "التحديث جاهز:{{version}}. آخر فحص في {{time}}.", available: "تحديث التطبيق جاهز للتثبيت.", @@ -1567,14 +1577,21 @@ export const ar: TranslationResources = { }, installError: "غير قادر على تثبيت تحديث تطبيق سطح المكتب.", callout: { + downloadingTitle: "جارٍ تنزيل التحديث", installingTitle: "تثبيت التحديث", failedTitle: "فشل التحديث", availableTitle: "التحديث متاح", genericError: "حدث خطأ ما.", whatsNew: "ما هو الجديد", + downloadingAction: "جارٍ التنزيل...", installingAction: "جارٍ التثبيت...", + downloadAndRestart: "تنزيل", installAndRestart: "التثبيت وإعادة التشغيل", + downloadingVersionDescription: "جارٍ تنزيل {{version}}... {{percent}}%", + downloadingDescription: "جارٍ تنزيل التحديث... {{percent}}%", installingDescription: "التثبيت وإعادة التشغيل...", + versionAvailable: "{{version}} متاح للتنزيل.", + newVersionAvailable: "يتوفر إصدار جديد للتنزيل.", versionReady: "{{version}}جاهز للتثبيت.", newVersionReady: "إصدار جديد جاهز للتثبيت.", restartWarning: "ستؤدي ترقية التطبيق إلى إيقاف تشغيل الوكلاء وإغلاق الجلسات الطرفية.", @@ -2676,9 +2693,28 @@ export const ar: TranslationResources = { stable: "Stable", beta: "Beta", }, + autoUpdate: { + label: "التحديثات التلقائية", + options: { + automatic: "تلقائي", + notify: "إشعار", + off: "إيقاف", + }, + descriptions: { + automatic: "التحقق من التحديثات وتنزيلها في الخلفية", + notify: "التحقق من التحديثات وتنزيلها فقط عند اختيارك", + off: "عدم التحقق تلقائيًا. يتم التحقق فقط عند النقر على فحص", + }, + }, updates: { label: "تحديثات التطبيق", readyToInstall: "جاهز للتثبيت:{{version}}", + downloadTitle: "تنزيل تحديث سطح المكتب", + downloadMessage: "سيؤدي هذا إلى تنزيل تحديث Paseo وتثبيته على هذا الكمبيوتر", + downloadConfirm: "تنزيل وتثبيت", + download: "تنزيل", + downloadTo: "تنزيل {{version}}", + downloading: "جارٍ التنزيل...", installTitle: "تثبيت تحديث سطح المكتب", installMessage: "يؤدي هذا إلى تحديث Paseo على هذا الكمبيوتر", installConfirm: "تثبيت التحديث", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index dd441625f..8d1582d88 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -1577,6 +1577,8 @@ export const en = { status: { checking: "Checking for app updates...", installing: "Installing app update...", + downloadingVersionProgress: "Downloading {{version}}... {{percent}}%", + downloadingProgress: "Downloading app update... {{percent}}%", upToDate: "App is up to date.", upToDateWithLastChecked: "Up to date. Last checked at {{time}}.", pending: "We'll let you know when the update is ready.", @@ -1585,6 +1587,14 @@ export const en = { pendingWithVersion: "Update found: {{version}}. Downloading...", pendingWithVersionAndLastChecked: "Update found: {{version}}. Downloading... Last checked at {{time}}.", + pendingWithVersionProgress: "Update found: {{version}}. Downloading... {{percent}}%", + pendingWithVersionProgressAndLastChecked: + "Update found: {{version}}. Downloading... {{percent}}% Last checked at {{time}}.", + downloadAvailableWithVersion: "Update available: {{version}}", + downloadAvailableWithVersionAndLastChecked: + "Update available: {{version}}. Last checked at {{time}}.", + downloadAvailable: "An app update is available.", + downloadAvailableWithLastChecked: "An app update is available. Last checked at {{time}}.", availableWithVersion: "Update ready: {{version}}", availableWithVersionAndLastChecked: "Update ready: {{version}}. Last checked at {{time}}.", available: "An app update is ready to install.", @@ -1595,14 +1605,21 @@ export const en = { }, installError: "Unable to install the desktop app update.", callout: { + downloadingTitle: "Downloading update", installingTitle: "Installing update", failedTitle: "Update failed", availableTitle: "Update available", genericError: "Something went wrong.", whatsNew: "What's new", + downloadingAction: "Downloading...", installingAction: "Installing...", + downloadAndRestart: "Download", installAndRestart: "Install & restart", + downloadingVersionDescription: "Downloading {{version}}... {{percent}}%", + downloadingDescription: "Downloading update... {{percent}}%", installingDescription: "Installing and restarting...", + versionAvailable: "{{version}} is available to download.", + newVersionAvailable: "A new version is available to download.", versionReady: "{{version}} is ready to install.", newVersionReady: "A new version is ready to install.", restartWarning: "Upgrading the app will stop running agents and close terminal sessions.", @@ -2773,9 +2790,28 @@ export const en = { stable: "Stable", beta: "Beta", }, + autoUpdate: { + label: "Automatic updates", + options: { + automatic: "Auto", + notify: "Notify", + off: "Off", + }, + descriptions: { + automatic: "Check and download updates in the background", + notify: "Check for updates, but only download when you choose", + off: "Never check automatically. Only check when you click Check", + }, + }, updates: { label: "App updates", readyToInstall: "Ready to install: {{version}}", + downloadTitle: "Download desktop update", + downloadMessage: "This downloads and installs the Paseo update on this computer", + downloadConfirm: "Download & install", + download: "Download", + downloadTo: "Download {{version}}", + downloading: "Downloading...", installTitle: "Install desktop update", installMessage: "This updates Paseo on this computer", installConfirm: "Install update", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index f4733c9e8..62e57dca0 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -1587,6 +1587,8 @@ export const es: TranslationResources = { status: { checking: "Buscando actualizaciones de la aplicación...", installing: "Instalando actualización de la aplicación...", + downloadingVersionProgress: "Descargando {{version}}... {{percent}}%", + downloadingProgress: "Descargando actualización de la aplicación... {{percent}}%", upToDate: "La aplicación está actualizada.", upToDateWithLastChecked: "Up to date. Last checked at {{time}}.", pending: "Le avisaremos cuando la actualización esté lista.", @@ -1595,6 +1597,16 @@ export const es: TranslationResources = { pendingWithVersion: "Actualización encontrada: {{version}}. Descargando...", pendingWithVersionAndLastChecked: "Actualización encontrada: {{version}}. Descargando... Última comprobación a las {{time}}.", + pendingWithVersionProgress: + "Actualización encontrada: {{version}}. Descargando... {{percent}}%", + pendingWithVersionProgressAndLastChecked: + "Actualización encontrada: {{version}}. Descargando... {{percent}}% Última comprobación a las {{time}}.", + downloadAvailableWithVersion: "Actualización disponible: {{version}}", + downloadAvailableWithVersionAndLastChecked: + "Actualización disponible: {{version}}. Última comprobación a las {{time}}.", + downloadAvailable: "Hay una actualización de la aplicación disponible.", + downloadAvailableWithLastChecked: + "Hay una actualización de la aplicación disponible. Última comprobación a las {{time}}.", availableWithVersion: "Actualización lista:{{version}}", availableWithVersionAndLastChecked: "Actualización lista:{{version}}. Última comprobación a las {{time}}.", @@ -1607,14 +1619,21 @@ export const es: TranslationResources = { }, installError: "No se puede instalar la actualización de la aplicación de escritorio.", callout: { + downloadingTitle: "Descargando actualización", installingTitle: "Instalando actualización", failedTitle: "La actualización falló", availableTitle: "Actualización disponible", genericError: "Algo salió mal.", whatsNew: "Qué hay de nuevo", + downloadingAction: "Descargando...", installingAction: "Instalando...", + downloadAndRestart: "Descargar", installAndRestart: "Instalar y reiniciar", + downloadingVersionDescription: "Descargando {{version}}... {{percent}}%", + downloadingDescription: "Descargando actualización... {{percent}}%", installingDescription: "Instalando y reiniciando...", + versionAvailable: "{{version}} está disponible para descargar.", + newVersionAvailable: "Una nueva versión está disponible para descargar.", versionReady: "{{version}}está listo para instalar.", newVersionReady: "Una nueva versión está lista para instalar.", restartWarning: @@ -2698,9 +2717,28 @@ export const es: TranslationResources = { stable: "Stable", beta: "Beta", }, + autoUpdate: { + label: "Actualizaciones automáticas", + options: { + automatic: "Auto", + notify: "Notificar", + off: "Desactivado", + }, + descriptions: { + automatic: "Buscar y descargar actualizaciones en segundo plano", + notify: "Buscar actualizaciones, pero descargar solo cuando lo elijas", + off: "No buscar automáticamente. Solo buscar al hacer clic en Comprobar", + }, + }, updates: { label: "Actualizaciones de aplicaciones", readyToInstall: "Listo para instalar:{{version}}", + downloadTitle: "Descargar actualización de escritorio", + downloadMessage: "Esto descarga e instala la actualización de Paseo en esta computadora.", + downloadConfirm: "Descargar e instalar", + download: "Descargar", + downloadTo: "Descargar {{version}}", + downloading: "Descargando...", installTitle: "Instalar actualización de escritorio", installMessage: "Esto actualizaPaseoen esta computadora.", installConfirm: "Instalar actualización", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 35bdfdd70..79824b9b6 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -1580,6 +1580,8 @@ export const fr: TranslationResources = { status: { checking: "Recherche de mises à jour de l’application…", installing: "Installation de la mise à jour de l’application…", + downloadingVersionProgress: "Téléchargement de {{version}}… {{percent}} %", + downloadingProgress: "Téléchargement de la mise à jour… {{percent}} %", upToDate: "L’application est à jour.", upToDateWithLastChecked: "À jour. Dernière vérification à {{time}}.", pending: "Nous vous préviendrons quand la mise à jour sera prête.", @@ -1588,6 +1590,16 @@ export const fr: TranslationResources = { pendingWithVersion: "Mise à jour trouvée : {{version}}. Téléchargement…", pendingWithVersionAndLastChecked: "Mise à jour trouvée : {{version}}. Téléchargement… Dernière vérification à {{time}}.", + pendingWithVersionProgress: + "Mise à jour trouvée : {{version}}. Téléchargement… {{percent}} %", + pendingWithVersionProgressAndLastChecked: + "Mise à jour trouvée : {{version}}. Téléchargement… {{percent}} % Dernière vérification à {{time}}.", + downloadAvailableWithVersion: "Mise à jour disponible : {{version}}", + downloadAvailableWithVersionAndLastChecked: + "Mise à jour disponible : {{version}}. Dernière vérification à {{time}}.", + downloadAvailable: "Une mise à jour de l’application est disponible.", + downloadAvailableWithLastChecked: + "Une mise à jour de l’application est disponible. Dernière vérification à {{time}}.", availableWithVersion: "Mise à jour prête : {{version}}", availableWithVersionAndLastChecked: "Mise à jour prête : {{version}}. Dernière vérification à {{time}}.", @@ -1600,14 +1612,21 @@ export const fr: TranslationResources = { }, installError: "Impossible d’installer la mise à jour de l’application de bureau.", callout: { + downloadingTitle: "Téléchargement de la mise à jour", installingTitle: "Installation de la mise à jour", failedTitle: "Échec de la mise à jour", availableTitle: "Mise à jour disponible", genericError: "Une erreur s’est produite.", whatsNew: "Nouveautés", + downloadingAction: "Téléchargement…", installingAction: "Installation…", + downloadAndRestart: "Télécharger", installAndRestart: "Installer et redémarrer", + downloadingVersionDescription: "Téléchargement de {{version}}… {{percent}} %", + downloadingDescription: "Téléchargement de la mise à jour… {{percent}} %", installingDescription: "Installation et redémarrage…", + versionAvailable: "La version {{version}} est disponible au téléchargement.", + newVersionAvailable: "Une nouvelle version est disponible au téléchargement.", versionReady: "La version {{version}} est prête à être installée.", newVersionReady: "Une nouvelle version est prête à être installée.", restartWarning: @@ -2697,9 +2716,28 @@ export const fr: TranslationResources = { stable: "Stable", beta: "Bêta", }, + autoUpdate: { + label: "Mises à jour automatiques", + options: { + automatic: "Auto", + notify: "Notifier", + off: "Désactivé", + }, + descriptions: { + automatic: "Vérifier et télécharger les mises à jour en arrière-plan", + notify: "Vérifier les mises à jour, mais ne télécharger que lorsque vous choisissez", + off: "Ne jamais vérifier automatiquement. Vérifier uniquement sur clic sur Vérifier", + }, + }, updates: { label: "Mises à jour de l’application", readyToInstall: "Prête à installer : {{version}}", + downloadTitle: "Télécharger la mise à jour de l’app de bureau", + downloadMessage: "La mise à jour de Paseo sera téléchargée et installée sur cet ordinateur", + downloadConfirm: "Télécharger et installer", + download: "Télécharger", + downloadTo: "Télécharger {{version}}", + downloading: "Téléchargement…", installTitle: "Installer la mise à jour de l’app de bureau", installMessage: "Paseo sera mis à jour sur cet ordinateur", installConfirm: "Installer la mise à jour", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index b5b61ba83..da2f2df0d 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -1565,6 +1565,8 @@ export const ja: TranslationResources = { status: { checking: "アプリの更新を確認中...", installing: "アプリの更新をインストール中...", + downloadingVersionProgress: "{{version}} をダウンロード中... {{percent}}%", + downloadingProgress: "アプリの更新をダウンロード中... {{percent}}%", upToDate: "アプリは最新です。", upToDateWithLastChecked: "最新の状態です。最終確認: {{time}}。", pending: "更新の準備ができたらお知らせします。", @@ -1572,6 +1574,15 @@ export const ja: TranslationResources = { pendingWithVersion: "更新が見つかりました: {{version}}。ダウンロード中...", pendingWithVersionAndLastChecked: "更新が見つかりました: {{version}}。ダウンロード中... 最終確認: {{time}}。", + pendingWithVersionProgress: + "更新が見つかりました: {{version}}。ダウンロード中... {{percent}}%", + pendingWithVersionProgressAndLastChecked: + "更新が見つかりました: {{version}}。ダウンロード中... {{percent}}% 最終確認: {{time}}。", + downloadAvailableWithVersion: "利用可能な更新: {{version}}", + downloadAvailableWithVersionAndLastChecked: + "利用可能な更新: {{version}}。最終確認: {{time}}。", + downloadAvailable: "アプリの更新が利用可能です。", + downloadAvailableWithLastChecked: "アプリの更新が利用可能です。最終確認: {{time}}。", availableWithVersion: "更新の準備ができました: {{version}}", availableWithVersionAndLastChecked: "更新の準備ができました: {{version}}。最終確認: {{time}}。", @@ -1583,14 +1594,21 @@ export const ja: TranslationResources = { }, installError: "デスクトップアプリの更新をインストールできません。", callout: { + downloadingTitle: "更新をダウンロード中", installingTitle: "更新をインストール中", failedTitle: "更新に失敗しました", availableTitle: "更新が利用可能", genericError: "問題が発生しました。", whatsNew: "新機能", + downloadingAction: "ダウンロード中...", installingAction: "インストール中...", + downloadAndRestart: "ダウンロード", installAndRestart: "インストールして再起動", + downloadingVersionDescription: "{{version}} をダウンロード中... {{percent}}%", + downloadingDescription: "更新をダウンロード中... {{percent}}%", installingDescription: "インストールして再起動中...", + versionAvailable: "{{version}} をダウンロードできます。", + newVersionAvailable: "新しいバージョンをダウンロードできます。", versionReady: "{{version}}のインストール準備ができました。", newVersionReady: "新しいバージョンのインストール準備ができました。", restartWarning: @@ -2664,9 +2682,28 @@ export const ja: TranslationResources = { stable: "安定版", beta: "ベータ", }, + autoUpdate: { + label: "自動更新", + options: { + automatic: "自動", + notify: "通知のみ", + off: "オフ", + }, + descriptions: { + automatic: "バックグラウンドで更新を確認してダウンロードします", + notify: "更新を確認しますが、選択したときだけダウンロードします", + off: "自動で更新を確認しません。「確認」をクリックしたときだけ確認します", + }, + }, updates: { label: "アプリの更新", readyToInstall: "インストール準備完了: {{version}}", + downloadTitle: "デスクトップの更新をダウンロード", + downloadMessage: "このコンピューターにPaseoの更新をダウンロードしてインストールします", + downloadConfirm: "ダウンロードしてインストール", + download: "ダウンロード", + downloadTo: "{{version}}をダウンロード", + downloading: "ダウンロード中...", installTitle: "デスクトップの更新をインストール", installMessage: "このコンピューターのPaseoを更新します", installConfirm: "更新をインストール", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 366988115..41cac266f 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -1556,6 +1556,8 @@ export const ko: TranslationResources = { status: { checking: "앱 업데이트 확인 중...", installing: "앱 업데이트 설치 중...", + downloadingVersionProgress: "{{version}} 다운로드 중... {{percent}}%", + downloadingProgress: "앱 업데이트 다운로드 중... {{percent}}%", upToDate: "앱이 최신 상태입니다.", upToDateWithLastChecked: "최신 상태입니다. 마지막 확인: {{time}}.", pending: "업데이트가 준비되면 알려드리겠습니다.", @@ -1564,6 +1566,15 @@ export const ko: TranslationResources = { pendingWithVersion: "업데이트 발견: {{version}}. 다운로드 중...", pendingWithVersionAndLastChecked: "업데이트 발견: {{version}}. 다운로드 중... {{time}}에서 마지막으로 확인했습니다.", + pendingWithVersionProgress: "업데이트 발견: {{version}}. 다운로드 중... {{percent}}%", + pendingWithVersionProgressAndLastChecked: + "업데이트 발견: {{version}}. 다운로드 중... {{percent}}% {{time}}에서 마지막으로 확인했습니다.", + downloadAvailableWithVersion: "사용 가능한 업데이트: {{version}}", + downloadAvailableWithVersionAndLastChecked: + "사용 가능한 업데이트: {{version}}. {{time}}에서 마지막으로 확인했습니다.", + downloadAvailable: "사용 가능한 앱 업데이트가 있습니다.", + downloadAvailableWithLastChecked: + "사용 가능한 앱 업데이트가 있습니다. {{time}}에서 마지막으로 확인했습니다.", availableWithVersion: "업데이트 준비됨: {{version}}", availableWithVersionAndLastChecked: "업데이트 준비됨: {{version}}. {{time}}에서 마지막으로 확인했습니다.", @@ -1576,14 +1587,21 @@ export const ko: TranslationResources = { }, installError: "데스크톱 앱 업데이트를 설치할 수 없습니다.", callout: { + downloadingTitle: "업데이트 다운로드 중", installingTitle: "업데이트 설치 중", failedTitle: "업데이트 실패", availableTitle: "업데이트 사용 가능", genericError: "문제가 발생했습니다.", whatsNew: "새로운 기능", + downloadingAction: "다운로드 중...", installingAction: "설치 중...", + downloadAndRestart: "다운로드", installAndRestart: "설치 후 재시작", + downloadingVersionDescription: "{{version}} 다운로드 중... {{percent}}%", + downloadingDescription: "업데이트 다운로드 중... {{percent}}%", installingDescription: "설치 후 재시작 중...", + versionAvailable: "{{version}} 버전을 다운로드할 수 있습니다.", + newVersionAvailable: "새 버전을 다운로드할 수 있습니다.", versionReady: "{{version}} 설치가 준비되었습니다.", newVersionReady: "새 버전 설치가 준비되었습니다.", restartWarning: "앱을 업그레이드하면 실행 중인 에이전트가 중지되고 터미널 세션이 닫힙니다.", @@ -2654,9 +2672,28 @@ export const ko: TranslationResources = { stable: "안정", beta: "베타", }, + autoUpdate: { + label: "자동 업데이트", + options: { + automatic: "자동", + notify: "알림만", + off: "끄기", + }, + descriptions: { + automatic: "백그라운드에서 업데이트를 확인하고 다운로드합니다", + notify: "업데이트를 확인하지만 선택할 때만 다운로드합니다", + off: "자동으로 확인하지 않습니다. 확인 버튼을 누를 때만 확인합니다", + }, + }, updates: { label: "앱 업데이트", readyToInstall: "설치 준비됨: {{version}}", + downloadTitle: "데스크톱 업데이트 다운로드", + downloadMessage: "이 컴퓨터에 Paseo 업데이트를 다운로드하고 설치합니다", + downloadConfirm: "다운로드 및 설치", + download: "다운로드", + downloadTo: "{{version}} 다운로드", + downloading: "다운로드 중...", installTitle: "데스크톱 업데이트 설치", installMessage: "이 컴퓨터의 Paseo를 업데이트합니다", installConfirm: "업데이트 설치", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 0241ea80a..0bcdb09f8 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -1577,6 +1577,8 @@ export const ptBR: TranslationResources = { status: { checking: "Verificando atualizações do app...", installing: "Instalando atualização do app...", + downloadingVersionProgress: "Baixando {{version}}... {{percent}}%", + downloadingProgress: "Baixando atualização do app... {{percent}}%", upToDate: "O app está atualizado.", upToDateWithLastChecked: "Atualizado. Última verificação às {{time}}.", pending: "Avisaremos quando a atualização estiver pronta.", @@ -1585,6 +1587,15 @@ export const ptBR: TranslationResources = { pendingWithVersion: "Atualização encontrada: {{version}}. Baixando...", pendingWithVersionAndLastChecked: "Atualização encontrada: {{version}}. Baixando... Última verificação às {{time}}.", + pendingWithVersionProgress: "Atualização encontrada: {{version}}. Baixando... {{percent}}%", + pendingWithVersionProgressAndLastChecked: + "Atualização encontrada: {{version}}. Baixando... {{percent}}% Última verificação às {{time}}.", + downloadAvailableWithVersion: "Atualização disponível: {{version}}", + downloadAvailableWithVersionAndLastChecked: + "Atualização disponível: {{version}}. Última verificação às {{time}}.", + downloadAvailable: "Há uma atualização do app disponível.", + downloadAvailableWithLastChecked: + "Há uma atualização do app disponível. Última verificação às {{time}}.", availableWithVersion: "Atualização pronta: {{version}}", availableWithVersionAndLastChecked: "Atualização pronta: {{version}}. Última verificação às {{time}}.", @@ -1597,14 +1608,21 @@ export const ptBR: TranslationResources = { }, installError: "Não foi possível instalar a atualização do app desktop.", callout: { + downloadingTitle: "Baixando atualização", installingTitle: "Instalando atualização", failedTitle: "Falha na atualização", availableTitle: "Atualização disponível", genericError: "Algo deu errado.", whatsNew: "Novidades", + downloadingAction: "Baixando...", installingAction: "Instalando...", + downloadAndRestart: "Baixar", installAndRestart: "Instalar e reiniciar", + downloadingVersionDescription: "Baixando {{version}}... {{percent}}%", + downloadingDescription: "Baixando atualização... {{percent}}%", installingDescription: "Instalando e reiniciando...", + versionAvailable: "{{version}} está disponível para download.", + newVersionAvailable: "Uma nova versão está disponível para download.", versionReady: "{{version}} está pronta para instalar.", newVersionReady: "Uma nova versão está pronta para instalar.", restartWarning: @@ -2680,9 +2698,28 @@ export const ptBR: TranslationResources = { stable: "Stable", beta: "Beta", }, + autoUpdate: { + label: "Atualizações automáticas", + options: { + automatic: "Auto", + notify: "Notificar", + off: "Desativado", + }, + descriptions: { + automatic: "Verificar e baixar atualizações em segundo plano", + notify: "Verificar atualizações, mas baixar apenas quando você escolher", + off: "Nunca verificar automaticamente. Verificar apenas ao clicar em Verificar", + }, + }, updates: { label: "Atualizações do app", readyToInstall: "Pronta para instalar: {{version}}", + downloadTitle: "Baixar atualização desktop", + downloadMessage: "Isso baixa e instala a atualização do Paseo neste computador", + downloadConfirm: "Baixar e instalar", + download: "Baixar", + downloadTo: "Baixar {{version}}", + downloading: "Baixando...", installTitle: "Instalar atualização desktop", installMessage: "Isso atualiza o Paseo neste computador", installConfirm: "Instalar atualização", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 5a3211d22..5782e57aa 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -1571,6 +1571,8 @@ export const ru: TranslationResources = { status: { checking: "Проверка обновлений приложения...", installing: "Установка обновления приложения...", + downloadingVersionProgress: "Загрузка {{version}}... {{percent}}%", + downloadingProgress: "Загрузка обновления приложения... {{percent}}%", upToDate: "Установлена последняя версия приложения.", upToDateWithLastChecked: "Установлена последняя версия приложения. Последняя проверка: {{time}}.", @@ -1580,6 +1582,15 @@ export const ru: TranslationResources = { pendingWithVersion: "Найдено обновление: {{version}}. Загрузка...", pendingWithVersionAndLastChecked: "Найдено обновление: {{version}}. Загрузка... Последняя проверка в {{time}}.", + pendingWithVersionProgress: "Найдено обновление: {{version}}. Загрузка... {{percent}}%", + pendingWithVersionProgressAndLastChecked: + "Найдено обновление: {{version}}. Загрузка... {{percent}}% Последняя проверка в {{time}}.", + downloadAvailableWithVersion: "Доступно обновление: {{version}}", + downloadAvailableWithVersionAndLastChecked: + "Доступно обновление: {{version}}. Последняя проверка: {{time}}.", + downloadAvailable: "Доступно обновление приложения.", + downloadAvailableWithLastChecked: + "Доступно обновление приложения. Последняя проверка: {{time}}.", availableWithVersion: "Обновление готово: {{version}}", availableWithVersionAndLastChecked: "Обновление готово: {{version}}. Последняя проверка: {{time}}.", @@ -1592,14 +1603,21 @@ export const ru: TranslationResources = { }, installError: "Не удалось установить обновление настольного приложения.", callout: { + downloadingTitle: "Загрузка обновления", installingTitle: "Установка обновления", failedTitle: "Обновление не выполнено", availableTitle: "Доступно обновление", genericError: "Что-то пошло не так.", whatsNew: "Что нового", + downloadingAction: "Загрузка...", installingAction: "Установка...", + downloadAndRestart: "Скачать", installAndRestart: "Установить и перезапустить", + downloadingVersionDescription: "Загрузка {{version}}... {{percent}}%", + downloadingDescription: "Загрузка обновления... {{percent}}%", installingDescription: "Установка и перезапуск...", + versionAvailable: "Версия {{version}} доступна для загрузки.", + newVersionAvailable: "Новая версия доступна для загрузки.", versionReady: "Версия {{version}} готова к установке.", newVersionReady: "Новая версия готова к установке.", restartWarning: @@ -2686,9 +2704,28 @@ export const ru: TranslationResources = { stable: "Стабильный", beta: "Бета", }, + autoUpdate: { + label: "Автообновления", + options: { + automatic: "Авто", + notify: "Уведомлять", + off: "Выкл.", + }, + descriptions: { + automatic: "Проверять и загружать обновления в фоновом режиме", + notify: "Проверять обновления, но загружать только по вашему выбору", + off: "Не проверять автоматически. Проверять только по нажатию кнопки Проверить", + }, + }, updates: { label: "Обновления приложения", readyToInstall: "Версия {{version}} готова к установке", + downloadTitle: "Загрузить обновление настольного приложения", + downloadMessage: "Это загрузит и установит обновление Paseo на этом компьютере.", + downloadConfirm: "Загрузить и установить", + download: "Загрузить", + downloadTo: "Загрузить {{version}}", + downloading: "Загрузка...", installTitle: "Установить обновление настольного приложения", installMessage: "Это обновит Paseo на этом компьютере.", installConfirm: "Установить обновление", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 73d632709..9062bf6c0 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -1537,6 +1537,8 @@ export const zhCN: TranslationResources = { status: { checking: "正在检查 app 更新...", installing: "正在安装 app 更新...", + downloadingVersionProgress: "正在下载 {{version}}... {{percent}}%", + downloadingProgress: "正在下载 app 更新... {{percent}}%", upToDate: "App 已是最新版本。", upToDateWithLastChecked: "已是最新版本。上次检查时间:{{time}}。", pending: "更新准备好后会通知你。", @@ -1544,6 +1546,14 @@ export const zhCN: TranslationResources = { pendingWithVersion: "发现更新:{{version}}。正在下载...", pendingWithVersionAndLastChecked: "发现更新:{{version}}。正在下载... 上次检查时间:{{time}}。", + pendingWithVersionProgress: "发现更新:{{version}}。正在下载... {{percent}}%", + pendingWithVersionProgressAndLastChecked: + "发现更新:{{version}}。正在下载... {{percent}}% 上次检查时间:{{time}}。", + downloadAvailableWithVersion: "有可用更新:{{version}}", + downloadAvailableWithVersionAndLastChecked: + "有可用更新:{{version}}。上次检查时间:{{time}}。", + downloadAvailable: "有 app 更新可用。", + downloadAvailableWithLastChecked: "有 app 更新可用。上次检查时间:{{time}}。", availableWithVersion: "更新已就绪:{{version}}", availableWithVersionAndLastChecked: "更新已就绪:{{version}}。上次检查时间:{{time}}。", available: "有 app 更新可安装。", @@ -1554,14 +1564,21 @@ export const zhCN: TranslationResources = { }, installError: "无法安装 desktop app 更新。", callout: { + downloadingTitle: "正在下载更新", installingTitle: "正在安装更新", failedTitle: "更新失败", availableTitle: "有可用更新", genericError: "出了点问题。", whatsNew: "更新内容", + downloadingAction: "正在下载...", installingAction: "正在安装...", + downloadAndRestart: "下载", installAndRestart: "安装并重启", + downloadingVersionDescription: "正在下载 {{version}}... {{percent}}%", + downloadingDescription: "正在下载更新... {{percent}}%", installingDescription: "正在安装并重启...", + versionAvailable: "{{version}} 可供下载。", + newVersionAvailable: "有新版本可供下载。", versionReady: "{{version}} 已准备好安装。", newVersionReady: "新版本已准备好安装。", restartWarning: "升级 app 会停止正在运行的 agents,并关闭 terminal 会话。", @@ -2613,9 +2630,28 @@ export const zhCN: TranslationResources = { stable: "Stable", beta: "Beta", }, + autoUpdate: { + label: "自动更新", + options: { + automatic: "自动", + notify: "仅通知", + off: "关闭", + }, + descriptions: { + automatic: "在后台检查并下载更新", + notify: "检查更新,但仅在你选择时才下载", + off: "从不自动检查,仅在点击检查时检查更新", + }, + }, updates: { label: "应用更新", readyToInstall: "可安装:{{version}}", + downloadTitle: "下载桌面版更新", + downloadMessage: "这会在此电脑上下载并安装 Paseo 更新", + downloadConfirm: "下载并安装", + download: "下载", + downloadTo: "下载 {{version}}", + downloading: "正在下载...", installTitle: "安装桌面版更新", installMessage: "这会更新此电脑上的 Paseo", installConfirm: "安装更新", diff --git a/packages/app/src/screens/settings-screen.tsx b/packages/app/src/screens/settings-screen.tsx index 59d6f472f..37efdbcef 100644 --- a/packages/app/src/screens/settings-screen.tsx +++ b/packages/app/src/screens/settings-screen.tsx @@ -85,6 +85,7 @@ import { DesktopNotificationsSection } from "@/desktop/components/desktop-notifi import { BrowserDataSection } from "@/desktop/browser/settings/browser-data-section"; import { IntegrationsSection } from "@/desktop/components/integrations-section"; import { isElectronRuntime } from "@/desktop/host"; +import { useDesktopSettings, type DesktopUpdateMode } from "@/desktop/settings/desktop-settings"; import { useDesktopAppUpdater } from "@/desktop/updates/use-desktop-app-updater"; import { formatVersionWithPrefix } from "@/desktop/updates/desktop-updates"; import { resolveAppVersion } from "@/utils/app-version"; @@ -616,25 +617,92 @@ function HostVersionRow({ function getUpdateButtonLabel( t: TFunction, - isInstalling: boolean, - latestVersion: string | null | undefined, + input: { + isInstalling: boolean; + isDownloading: boolean; + isActionable: boolean; + readyToInstall: boolean; + latestVersion: string | null | undefined; + }, ): string { - if (isInstalling) return t("settings.about.updates.installing"); - if (latestVersion) { + if (input.isInstalling) { + return input.isDownloading + ? t("settings.about.updates.downloading") + : t("settings.about.updates.installing"); + } + if (input.isActionable && !input.readyToInstall) { + if (input.latestVersion) { + return t("settings.about.updates.downloadTo", { + version: formatVersionWithPrefix(input.latestVersion), + }); + } + return t("settings.about.updates.download"); + } + if (input.latestVersion) { return t("settings.about.updates.updateTo", { - version: formatVersionWithPrefix(latestVersion), + version: formatVersionWithPrefix(input.latestVersion), }); } return t("settings.about.updates.update"); } +function getUpdateModeDescription(t: TFunction, mode: DesktopUpdateMode): string { + if (mode === "off") return t("settings.about.autoUpdate.descriptions.off"); + if (mode === "notify") return t("settings.about.autoUpdate.descriptions.notify"); + return t("settings.about.autoUpdate.descriptions.automatic"); +} + +function getUpdateConfirmDialogCopy(t: TFunction, isUpdateReady: boolean) { + if (isUpdateReady) { + return { + title: t("settings.about.updates.installTitle"), + message: t("settings.about.updates.installMessage"), + confirmLabel: t("settings.about.updates.installConfirm"), + cancelLabel: t("common.actions.cancel"), + }; + } + return { + title: t("settings.about.updates.downloadTitle"), + message: t("settings.about.updates.downloadMessage"), + confirmLabel: t("settings.about.updates.downloadConfirm"), + cancelLabel: t("common.actions.cancel"), + }; +} + +function DesktopUpdateProgressBar({ percent }: { percent: number }) { + const accessibilityValue = useMemo(() => ({ min: 0, max: 100, now: percent }), [percent]); + const fillStyle = useMemo( + () => [styles.aboutUpdateProgressFill, { width: `${percent}%` as const }], + [percent], + ); + + return ( + + + + ); +} + function DesktopAppUpdateRow() { const { t } = useTranslation(); const { settings, updateSettings } = useSettings(); + const { + settings: desktopSettings, + isLoading: isLoadingDesktopSettings, + updateSettings: updateDesktopSettings, + } = useDesktopSettings(); + const updateMode = desktopSettings.updates.mode; const { isDesktopApp, + status, statusText, availableUpdate, + downloadProgress, errorMessage, isChecking, isInstalling, @@ -644,12 +712,12 @@ function DesktopAppUpdateRow() { useFocusEffect( useCallback(() => { - if (!isDesktopApp) { + if (!isDesktopApp || isLoadingDesktopSettings || updateMode === "off") { return undefined; } void checkForUpdates({ intent: "automatic", silent: true }); return undefined; - }, [checkForUpdates, isDesktopApp]), + }, [checkForUpdates, isDesktopApp, isLoadingDesktopSettings, updateMode]), ); const handleCheckForUpdates = useCallback(() => { @@ -673,17 +741,36 @@ function DesktopAppUpdateRow() { [t], ); + const handleUpdateModeChange = useCallback( + (mode: DesktopUpdateMode) => { + void updateDesktopSettings({ updates: { mode } }); + }, + [updateDesktopSettings], + ); + const updateModeOptions = useMemo( + () => [ + { value: "automatic" as const, label: t("settings.about.autoUpdate.options.automatic") }, + { value: "notify" as const, label: t("settings.about.autoUpdate.options.notify") }, + { value: "off" as const, label: t("settings.about.autoUpdate.options.off") }, + ], + [t], + ); + + const isUpdateReady = availableUpdate?.readyToInstall === true; + const isUpdateActionable = status === "available" && availableUpdate?.hasUpdate === true; + const readyUpdateVersion = isUpdateReady ? availableUpdate?.latestVersion : null; + const actionableVersion = isUpdateActionable ? availableUpdate?.latestVersion : null; + const downloadPercent = + (isInstalling || status === "pending") && downloadProgress + ? Math.max(0, Math.min(100, Math.round(downloadProgress.percent))) + : null; + const handleInstallUpdate = useCallback(() => { if (!isDesktopApp) { return; } - void confirmDialog({ - title: t("settings.about.updates.installTitle"), - message: t("settings.about.updates.installMessage"), - confirmLabel: t("settings.about.updates.installConfirm"), - cancelLabel: t("common.actions.cancel"), - }) + void confirmDialog(getUpdateConfirmDialogCopy(t, isUpdateReady)) .then((confirmed) => { if (!confirmed) { return; @@ -698,10 +785,7 @@ function DesktopAppUpdateRow() { t("settings.about.updates.alertMessage"), ); }); - }, [installUpdate, isDesktopApp, t]); - - const isUpdateReady = availableUpdate?.readyToInstall === true; - const readyUpdateVersion = isUpdateReady ? availableUpdate?.latestVersion : null; + }, [installUpdate, isDesktopApp, isUpdateReady, t]); if (!isDesktopApp) { return null; @@ -722,6 +806,18 @@ function DesktopAppUpdateRow() { options={releaseChannelOptions} /> + + + {t("settings.about.autoUpdate.label")} + {getUpdateModeDescription(t, updateMode)} + + + {t("settings.about.updates.label")} @@ -733,6 +829,7 @@ function DesktopAppUpdateRow() { })} ) : null} + {downloadPercent !== null ? : null} {errorMessage ? {errorMessage} : null} @@ -746,9 +843,15 @@ function DesktopAppUpdateRow() { @@ -1640,6 +1743,19 @@ const styles = StyleSheet.create((theme) => ({ alignItems: "center", gap: theme.spacing[2], }, + aboutUpdateProgressTrack: { + marginTop: theme.spacing[2], + height: 4, + maxWidth: 260, + borderRadius: theme.borderRadius.full, + backgroundColor: theme.colors.surface3, + overflow: "hidden", + }, + aboutUpdateProgressFill: { + height: "100%", + borderRadius: theme.borderRadius.full, + backgroundColor: theme.colors.accent, + }, placeholder: { flex: 1, alignItems: "center", diff --git a/packages/desktop/e2e/support/runtime.ts b/packages/desktop/e2e/support/runtime.ts index 9032e5c56..b2bb33d59 100644 --- a/packages/desktop/e2e/support/runtime.ts +++ b/packages/desktop/e2e/support/runtime.ts @@ -55,9 +55,12 @@ export async function loadRealDaemonState(): Promise { export interface DesktopRuntimeConfig { serverId: string; + updateMode?: "automatic" | "notify" | "off"; updateAvailable?: boolean; latestVersion?: string; updateReadyToInstall?: boolean; + updateDownloading?: boolean; + downloadProgressSteps?: number[]; manualUpdateBypassesRollout?: boolean; slowInstall?: boolean; /** Initial PID reported by desktop_daemon_status. Defaults to null. */ @@ -110,6 +113,7 @@ declare global { interface Window { __capturedDialogCall: ConfirmDialogCall | undefined; __capturedDialogOpenCalls: Array | undefined>; + __capturedUpdateChecks?: Array<{ intent: unknown; releaseChannel: unknown }>; __recordDesktopEditorOpen?: (input: DesktopEditorOpenRecord) => Promise; __desktopDaemonStartRequested?: boolean; } @@ -140,11 +144,22 @@ export async function installDesktopRuntime( await page.addInitScript((cfg) => { // Mutable state shared across IPC calls within this page let manageDaemon = cfg.manageBuiltInDaemon ?? false; + let updateMode = cfg.updateMode ?? "automatic"; let daemonRunning = true; let currentPid: number | null = cfg.daemonPid ?? null; let ownedByDesktop = cfg.ownedByDesktop ?? false; let manualUpdateAdmitted = false; + const eventListeners = new Map void>>(); window.__desktopDaemonStartRequested = false; + window.__capturedUpdateChecks = []; + + function emitDesktopEvent(event: string, payload: unknown) { + const listeners = eventListeners.get(event); + if (!listeners) return; + for (const listener of listeners) { + listener(payload); + } + } function buildDaemonStatus() { return { @@ -182,10 +197,15 @@ export async function installDesktopRuntime( } } - function buildAppUpdateCheckResult(hasUpdate: boolean, readyToInstall: boolean) { + function buildAppUpdateCheckResult( + hasUpdate: boolean, + readyToInstall: boolean, + downloading = hasUpdate && !readyToInstall, + ) { return { hasUpdate, readyToInstall, + downloading, currentVersion: "1.0.0", latestVersion: hasUpdate ? (cfg.latestVersion ?? "1.2.3") : null, body: null, @@ -194,19 +214,78 @@ export async function installDesktopRuntime( } function checkAppUpdate(intent: unknown) { + if (intent === "automatic" && updateMode === "off") { + return buildAppUpdateCheckResult(false, false, false); + } if (!cfg.manualUpdateBypassesRollout) { - return buildAppUpdateCheckResult( - cfg.updateAvailable === true, - cfg.updateAvailable === true && (cfg.updateReadyToInstall ?? true), - ); + const hasUpdate = cfg.updateAvailable === true; + const readyToInstall = + hasUpdate && (cfg.updateReadyToInstall ?? updateMode === "automatic"); + const downloading = + cfg.updateDownloading ?? (hasUpdate && !readyToInstall && updateMode === "automatic"); + return buildAppUpdateCheckResult(hasUpdate, readyToInstall, downloading); } if (intent === "manual") { manualUpdateAdmitted = true; - return buildAppUpdateCheckResult(true, false); + return buildAppUpdateCheckResult(true, false, updateMode === "automatic"); } - return buildAppUpdateCheckResult(manualUpdateAdmitted, manualUpdateAdmitted); + return buildAppUpdateCheckResult(manualUpdateAdmitted, manualUpdateAdmitted, false); + } + + async function installAppUpdate() { + if (cfg.downloadProgressSteps?.length) { + for (const percent of cfg.downloadProgressSteps) { + emitDesktopEvent("app-update-download-progress", { + version: cfg.latestVersion ?? "1.2.3", + percent, + transferred: percent * 1_000_000, + total: 100_000_000, + bytesPerSecond: 5_000_000, + }); + await new Promise((resolve) => setTimeout(resolve, 600)); + } + } + if (cfg.slowInstall) { + await new Promise((resolve) => setTimeout(resolve, 3000)); + } + emitDesktopEvent("app-update-download-progress", null); + return { + installed: true, + version: cfg.latestVersion ?? "1.2.3", + message: "App update installed. Restart required.", + }; + } + + function buildDesktopSettings() { + return { + releaseChannel: "stable", + updates: { mode: updateMode }, + daemon: { manageBuiltInDaemon: manageDaemon, keepRunningAfterQuit: true }, + }; + } + + function patchDesktopSettings(args?: Record) { + const updates = args?.updates; + if ( + updates !== null && + typeof updates === "object" && + "mode" in updates && + (updates.mode === "automatic" || updates.mode === "notify" || updates.mode === "off") + ) { + updateMode = updates.mode; + } + const daemon = args?.daemon; + if ( + daemon !== null && + typeof daemon === "object" && + "manageBuiltInDaemon" in daemon && + typeof daemon.manageBuiltInDaemon === "boolean" + ) { + manageDaemon = daemon.manageBuiltInDaemon; + } + return buildDesktopSettings(); } const desktopBridge: { @@ -217,7 +296,9 @@ export async function installDesktopRuntime( open: (options?: Record) => Promise; }; getPendingOpenProject: () => Promise; - events: { on: () => Promise<() => void> }; + events: { + on: (event: string, handler: (payload: unknown) => void) => Promise<() => void>; + }; editor?: { listTargets: () => Promise; openTarget: (input: DesktopEditorOpenRecord) => Promise; @@ -226,18 +307,15 @@ export async function installDesktopRuntime( platform: "darwin", invoke: async (command: string, args?: Record) => { if (command === "check_app_update") { + window.__capturedUpdateChecks?.push({ + intent: args?.intent, + releaseChannel: args?.releaseChannel, + }); return checkAppUpdate(args?.intent); } if (command === "install_app_update") { - if (cfg.slowInstall) { - await new Promise((resolve) => setTimeout(resolve, 3000)); - } - return { - installed: true, - version: cfg.latestVersion ?? "1.2.3", - message: "App update installed. Restart required.", - }; + return installAppUpdate(); } if (command === "desktop_daemon_status") { @@ -250,26 +328,11 @@ export async function installDesktopRuntime( if (command === "get_desktop_settings") { await waitForDesktopSettingsResponse(); - return { - releaseChannel: "stable", - daemon: { manageBuiltInDaemon: manageDaemon, keepRunningAfterQuit: true }, - }; + return buildDesktopSettings(); } if (command === "patch_desktop_settings") { - const daemon = args?.daemon; - if ( - daemon !== null && - typeof daemon === "object" && - "manageBuiltInDaemon" in daemon && - typeof daemon.manageBuiltInDaemon === "boolean" - ) { - manageDaemon = daemon.manageBuiltInDaemon; - } - return { - releaseChannel: "stable", - daemon: { manageBuiltInDaemon: manageDaemon, keepRunningAfterQuit: true }, - }; + return patchDesktopSettings(args); } if (command === "stop_desktop_daemon") { @@ -299,7 +362,19 @@ export async function installDesktopRuntime( }, }, getPendingOpenProject: async () => null, - events: { on: async () => () => undefined }, + events: { + on: async (event: string, handler: (payload: unknown) => void) => { + let listeners = eventListeners.get(event); + if (!listeners) { + listeners = new Set(); + eventListeners.set(event, listeners); + } + listeners.add(handler); + return () => { + listeners?.delete(handler); + }; + }, + }, }; if (cfg.editorTargets) { diff --git a/packages/desktop/e2e/updates.spec.ts b/packages/desktop/e2e/updates.spec.ts index 9919acddb..5dfcbf709 100644 --- a/packages/desktop/e2e/updates.spec.ts +++ b/packages/desktop/e2e/updates.spec.ts @@ -91,6 +91,74 @@ test.describe("Desktop updates", () => { await expectPendingUpdateCheckResult(page, "1.2.3"); await expectReadyUpdateCheckResult(page, "1.2.3"); }); + + test("off mode skips automatic update checks until Check is clicked", async ({ page }) => { + await installDesktopRuntime(page, { + serverId: getServerId(), + updateMode: "off", + updateAvailable: true, + latestVersion: "1.2.3", + }); + await gotoAppShell(page); + await openDesktopAboutSettings(page); + + await expect( + page.getByText("Never check automatically. Only check when you click Check"), + ).toBeVisible(); + await expect(page.getByTestId("update-callout")).toHaveCount(0); + const automaticChecks = await page.evaluate(() => window.__capturedUpdateChecks ?? []); + expect(automaticChecks).toEqual([]); + + await clickCheckForUpdates(page); + await expect(page.getByText(/Update available: v1\.2\.3/)).toBeVisible(); + await expect(page.getByRole("button", { name: "Download v1.2.3" })).toBeEnabled(); + }); + + test("notify mode shows Download and live download progress", async ({ page }) => { + await installDesktopRuntime(page, { + serverId: getServerId(), + updateMode: "notify", + updateAvailable: true, + latestVersion: "1.2.3", + downloadProgressSteps: [42, 78], + slowInstall: true, + }); + await gotoAppShell(page); + + const callout = page.getByTestId("update-callout"); + await expect(callout).toBeVisible({ timeout: 15_000 }); + await expect(callout).toContainText("v1.2.3 is available to download."); + await page.getByRole("button", { name: "Download", exact: true }).click(); + await expect(callout).toContainText("Downloading v1.2.3... 42%"); + await expect(callout.getByRole("progressbar")).toBeVisible(); + }); + + test("starting download in About updates the sidebar callout and disables its action", async ({ + page, + }) => { + await installDesktopRuntime(page, { + serverId: getServerId(), + updateMode: "notify", + updateAvailable: true, + latestVersion: "1.2.3", + downloadProgressSteps: [55], + slowInstall: true, + confirmShouldAccept: true, + }); + await gotoAppShell(page); + await expect(page.getByTestId("update-callout")).toBeVisible({ timeout: 15_000 }); + + await openDesktopAboutSettings(page); + await page.getByRole("button", { name: "Download v1.2.3" }).click(); + await expect( + page.getByTestId("settings-detail-scroll-body").getByText("Downloading v1.2.3... 55%"), + ).toBeVisible(); + + await page.getByRole("button", { name: "Back" }).click(); + const callout = page.getByTestId("update-callout"); + await expect(callout).toContainText("Downloading v1.2.3... 55%"); + await expect(callout.getByRole("button", { name: "Downloading..." })).toBeDisabled(); + }); }); test.describe("Desktop daemon management", () => { diff --git a/packages/desktop/src/daemon/daemon-manager.test.ts b/packages/desktop/src/daemon/daemon-manager.test.ts index ff830666a..420b81574 100644 --- a/packages/desktop/src/daemon/daemon-manager.test.ts +++ b/packages/desktop/src/daemon/daemon-manager.test.ts @@ -14,13 +14,22 @@ import { const mocks = vi.hoisted(() => ({ paseoHome: "", + settingsError: null as Error | null, settings: { - releaseChannel: "stable", + releaseChannel: "stable" as "stable" | "beta", + updates: { + mode: "automatic" as "automatic" | "notify" | "off", + }, + notifications: { + playSound: true, + }, daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: true, }, }, + checkForAppUpdate: vi.fn(), + downloadAndInstallUpdate: vi.fn(), runExternalCliJsonCommand: vi.fn(), runExternalCliTextCommand: vi.fn(), createNodeEntrypointInvocation: vi.fn(() => ({ @@ -41,6 +50,8 @@ vi.mock("electron", () => ({ getVersion: vi.fn(() => "1.2.3"), isPackaged: true, }, + autoUpdater: undefined, + BrowserWindow: { getAllWindows: vi.fn(() => []) }, ipcMain: { handle: vi.fn() }, powerMonitor: { getSystemIdleTime: vi.fn(() => 0) }, })); @@ -65,7 +76,12 @@ vi.mock("@getpaseo/server/daemon-control", async (importOriginal) => ({ vi.mock("../settings/desktop-settings-electron.js", () => ({ getDesktopSettingsStore: () => ({ - get: async () => mocks.settings, + get: async () => { + if (mocks.settingsError) { + throw mocks.settingsError; + } + return mocks.settings; + }, patch: vi.fn(), migrateLegacyRendererSettings: vi.fn(), }), @@ -79,6 +95,12 @@ vi.mock("./runtime-paths.js", () => ({ })), })); +vi.mock("../features/auto-updater.js", async (importOriginal) => ({ + ...(await importOriginal>()), + checkForAppUpdate: mocks.checkForAppUpdate, + downloadAndInstallUpdate: mocks.downloadAndInstallUpdate, +})); + vi.mock("./cli/external.js", async (importOriginal) => ({ ...(await importOriginal>()), runExternalCliJsonCommand: mocks.runExternalCliJsonCommand, @@ -93,6 +115,8 @@ describe("daemon-manager commands", () => { mocks.paseoHome = path.join(fixtureRoot, "home"); mocks.appLogPath = path.join(fixtureRoot, "main.log"); mocks.settings = DEFAULT_DESKTOP_SETTINGS; + mocks.checkForAppUpdate.mockReset(); + mocks.downloadAndInstallUpdate.mockReset(); mocks.runExternalCliJsonCommand.mockReset(); mocks.runExternalCliTextCommand.mockReset(); mocks.createNodeEntrypointInvocation.mockReset(); @@ -182,6 +206,54 @@ describe("daemon-manager commands", () => { writeFileSync(lockPath, JSON.stringify({ ...lock, desktopManaged: false })); expect(await handler({ listen: "localhost:6799" })).toBeNull(); }); + + it("delegates update checks to checkForAppUpdate even when desktop-settings.json cannot be read", async () => { + const consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + mocks.checkForAppUpdate.mockResolvedValue({ + hasUpdate: true, + readyToInstall: false, + downloading: true, + currentVersion: "1.2.3", + latestVersion: "1.2.4", + body: null, + date: null, + errorMessage: null, + }); + mocks.downloadAndInstallUpdate.mockResolvedValue({ + installed: true, + version: "1.2.4", + message: "Update downloaded.", + }); + + mocks.settingsError = new SyntaxError("Unexpected token } in JSON"); + try { + await createDaemonCommandHandlers().check_app_update({ + intent: "manual", + releaseChannel: "beta", + }); + expect(mocks.checkForAppUpdate).toHaveBeenLastCalledWith({ + currentVersion: "1.2.3", + releaseChannel: "beta", + intent: "manual", + }); + + await createDaemonCommandHandlers().check_app_update({ intent: "automatic" }); + expect(mocks.checkForAppUpdate).toHaveBeenLastCalledWith({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "automatic", + }); + + await createDaemonCommandHandlers().install_app_update({}); + expect(mocks.downloadAndInstallUpdate).toHaveBeenLastCalledWith( + { currentVersion: "1.2.3", releaseChannel: "stable" }, + expect.any(Function), + ); + } finally { + mocks.settingsError = null; + consoleWarn.mockRestore(); + } + }); }); describe("desktop stops and terminals", () => { diff --git a/packages/desktop/src/daemon/daemon-manager.ts b/packages/desktop/src/daemon/daemon-manager.ts index 44076bbc4..53bada4ba 100644 --- a/packages/desktop/src/daemon/daemon-manager.ts +++ b/packages/desktop/src/daemon/daemon-manager.ts @@ -481,7 +481,17 @@ async function getLocalDaemonVersion(): Promise<{ version: string | null; error: async function resolveRequestedReleaseChannel( args: Record | undefined, ): Promise { - return parseReleaseChannel(args) ?? (await getDesktopSettingsStore().get()).releaseChannel; + const explicit = parseReleaseChannel(args); + if (explicit) return explicit; + try { + return (await getDesktopSettingsStore().get()).releaseChannel; + } catch (error) { + console.warn( + "[auto-updater] Failed to read release channel from desktop settings, defaulting to stable:", + error, + ); + return "stable"; + } } // --------------------------------------------------------------------------- @@ -541,10 +551,12 @@ export function createDaemonCommandHandlers(): Record { const currentVersion = resolveDesktopAppVersion(); + const releaseChannel = await resolveRequestedReleaseChannel(args); + const intent = parseAppUpdateCheckIntent(args); return checkForAppUpdate({ currentVersion, - releaseChannel: await resolveRequestedReleaseChannel(args), - intent: parseAppUpdateCheckIntent(args), + releaseChannel, + intent, }); }, install_app_update: async (args) => { diff --git a/packages/desktop/src/features/app-update-service.test.ts b/packages/desktop/src/features/app-update-service.test.ts index 5f55ff609..ab6ad8182 100644 --- a/packages/desktop/src/features/app-update-service.test.ts +++ b/packages/desktop/src/features/app-update-service.test.ts @@ -1,10 +1,14 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; +import type { DesktopUpdateMode } from "../settings/desktop-settings"; import { createAppUpdateService, + type AppUpdateDownloadProgress, type AppUpdateInstallRequest, type AppUpdateRuntime, type AppUpdateRuntimeConfiguration, + type RuntimeDownloadProgressInfo, + type RuntimeUpdateCheckResult, type RuntimeUpdateInfo, } from "./app-update-service"; @@ -26,6 +30,8 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime { resolve(): void; reject(error: Error): void; } | null = null; + lastAutoDownload: boolean | null = null; + nextQuitAndInstallResult: { started: boolean; errorMessage?: string } | null = null; checkCount = 0; downloadCallCount = 0; requestedDownloadVersions: string[] = []; @@ -35,9 +41,18 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime { configure(input: AppUpdateRuntimeConfiguration): void { this.configuration = input; + this.lastAutoDownload = input.autoDownload; this.gate = input.shouldAdmitUpdate; } + setAutoDownload(enabled: boolean): void { + this.lastAutoDownload = enabled; + } + + emitDownloadProgress(progress: RuntimeDownloadProgressInfo): void { + this.configuration?.onDownloadProgress(progress); + } + nextCheck(result: { isUpdateAvailable: boolean; updateInfo: RuntimeUpdateInfo } | null): void { this.checks.push(result); } @@ -143,21 +158,36 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime { } } - quitAndInstall({ targetVersion, isSilent, isForceRunAfter }: AppUpdateInstallRequest): void { + quitAndInstall({ targetVersion, isSilent, isForceRunAfter }: AppUpdateInstallRequest) { + if (this.nextQuitAndInstallResult) { + const outcome = this.nextQuitAndInstallResult; + this.nextQuitAndInstallResult = null; + return outcome; + } if (this.downloadedUpdate) { this.installedVersions.push(this.downloadedUpdate.version); this.installModes.push({ targetVersion, isSilent, isForceRunAfter }); } + return { started: true }; } } -function createService(input?: { now?: () => number; bucket?: () => Promise }) { +function createService(input?: { + now?: () => number; + bucket?: () => Promise; + updateMode?: () => DesktopUpdateMode | Promise; + reportSettingsError?: (error: unknown) => void; + onDownloadProgress?: (progress: AppUpdateDownloadProgress | null) => void; +}) { const runtime = new FakeAppUpdateRuntime(); const service = createAppUpdateService({ runtime, isPackaged: () => true, now: input?.now ?? (() => Date.parse("2026-04-28T12:00:00.000Z")), bucket: input?.bucket ?? (async () => 0.99), + updateMode: input?.updateMode, + reportSettingsError: input?.reportSettingsError, + onDownloadProgress: input?.onDownloadProgress, }); return { runtime, service }; } @@ -182,6 +212,7 @@ describe("app update service", () => { expect(result).toEqual({ hasUpdate: false, readyToInstall: false, + downloading: false, currentVersion: "1.2.3", latestVersion: "1.2.3", body: null, @@ -203,6 +234,7 @@ describe("app update service", () => { expect(result).toEqual({ hasUpdate: true, readyToInstall: false, + downloading: true, currentVersion: "1.2.3", latestVersion: "1.2.4", body: null, @@ -331,6 +363,7 @@ describe("app update service", () => { expect(result).toEqual({ hasUpdate: true, readyToInstall: false, + downloading: true, currentVersion: "1.2.3", latestVersion: "1.2.5", body: null, @@ -361,6 +394,7 @@ describe("app update service", () => { expect(result).toEqual({ hasUpdate: true, readyToInstall: false, + downloading: true, currentVersion: "1.2.3", latestVersion: "1.2.5", body: null, @@ -569,6 +603,7 @@ describe("app update service", () => { expect(result).toEqual({ hasUpdate: false, readyToInstall: false, + downloading: false, currentVersion: "1.2.3", latestVersion: "1.2.3", body: null, @@ -590,6 +625,7 @@ describe("app update service", () => { expect(result).toEqual({ hasUpdate: false, readyToInstall: false, + downloading: false, currentVersion: "1.2.3", latestVersion: "1.2.3", body: null, @@ -620,6 +656,7 @@ describe("app update service", () => { expect(retryResult).toEqual({ hasUpdate: false, readyToInstall: false, + downloading: false, currentVersion: "1.2.3", latestVersion: "1.2.3", body: null, @@ -649,6 +686,7 @@ describe("app update service", () => { expect(automaticResult).toEqual({ hasUpdate: false, readyToInstall: false, + downloading: false, currentVersion: "1.2.3", latestVersion: "1.2.3", body: null, @@ -691,6 +729,7 @@ describe("app update service", () => { expect(automaticResult).toEqual({ hasUpdate: false, readyToInstall: false, + downloading: false, currentVersion: "1.2.3", latestVersion: "1.2.3", body: null, @@ -721,6 +760,7 @@ describe("app update service", () => { expect(failedPreparation).toEqual({ hasUpdate: true, readyToInstall: false, + downloading: false, currentVersion: "1.2.3", latestVersion: "1.2.4", body: null, @@ -739,6 +779,7 @@ describe("app update service", () => { expect(result).toEqual({ hasUpdate: true, readyToInstall: false, + downloading: true, currentVersion: "1.2.3", latestVersion: "1.2.5", body: null, @@ -802,6 +843,7 @@ describe("app update service", () => { expect(result).toEqual({ hasUpdate: true, readyToInstall: false, + downloading: true, currentVersion: "1.2.3", latestVersion: "1.2.5", body: null, @@ -834,6 +876,7 @@ describe("app update service", () => { expect(result).toEqual({ hasUpdate: true, readyToInstall: true, + downloading: false, currentVersion: "1.2.3", latestVersion: "1.2.4", body: null, @@ -841,4 +884,422 @@ describe("app update service", () => { errorMessage: null, }); }); + + it("reports an available update without downloading when autoDownload is false", async () => { + const progressEvents: Array = []; + const { runtime, service } = createService({ + bucket: async () => 0, + onDownloadProgress: (progress) => progressEvents.push(progress), + }); + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + + const result = await service.checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "automatic", + autoDownload: false, + }); + + expect(runtime.lastAutoDownload).toBe(false); + expect(result).toEqual({ + hasUpdate: true, + readyToInstall: false, + downloading: false, + currentVersion: "1.2.3", + latestVersion: "1.2.4", + body: null, + date: "2026-04-28T00:00:00.000Z", + errorMessage: null, + }); + + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + const activeDownload = runtime.beginUpdateDownload(rolledOutUpdate); + const installPending = service.downloadAndInstallUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + }); + await Promise.resolve(); + runtime.emitDownloadProgress({ + percent: 45, + transferred: 45, + total: 100, + bytesPerSecond: 10, + }); + activeDownload.resolve(); + const installResult = await installPending; + + expect(installResult.installed).toBe(true); + expect(progressEvents).toContainEqual({ + version: "1.2.4", + percent: 45, + transferred: 45, + total: 100, + bytesPerSecond: 10, + }); + expect(progressEvents[progressEvents.length - 1]).toBeNull(); + }); + + it("allows retrying the same version after a transient download failure in notify/off mode", async () => { + const progressEvents: Array = []; + const { runtime, service } = createService({ + bucket: async () => 0, + onDownloadProgress: (progress) => progressEvents.push(progress), + }); + + // 1. Discover v1.2.4 without auto-downloading. + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + const discovered = await service.checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "manual", + autoDownload: false, + }); + expect(discovered).toMatchObject({ + hasUpdate: true, + readyToInstall: false, + downloading: false, + latestVersion: "1.2.4", + }); + + // 2. First explicit download fails transiently mid-transfer. + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + const failingDownload = runtime.beginUpdateDownload(rolledOutUpdate); + const failedInstallPromise = service.downloadAndInstallUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + }); + await new Promise((resolve) => setImmediate(resolve)); + expect(runtime.downloadCallCount).toBe(1); + runtime.emitDownloadProgress({ + percent: 37, + transferred: 37, + total: 100, + bytesPerSecond: 10, + }); + failingDownload.reject(new Error("ECONNRESET")); + const failedInstall = await failedInstallPromise; + + expect(failedInstall).toMatchObject({ + installed: false, + errorMessage: "ECONNRESET", + }); + expect(progressEvents[progressEvents.length - 1]).toBeNull(); + + // 3. User retries manual Check for the SAME version (v1.2.4) — must not be stranded on stale error! + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + const retryCheck = await service.checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "manual", + autoDownload: false, + }); + expect(retryCheck).toMatchObject({ + hasUpdate: true, + readyToInstall: false, + downloading: false, + latestVersion: "1.2.4", + errorMessage: null, + }); + + // 4. Second explicit download succeeds and installs cleanly. + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + const retryInstall = await service.downloadAndInstallUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + }); + expect(retryInstall.installed).toBe(true); + expect(runtime.installedVersions).toEqual(["1.2.4"]); + }); + + it("downloads and installs a newer release if one ships after notify discovery", async () => { + const { runtime, service } = createService({ bucket: async () => 0 }); + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + await service.checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "automatic", + autoDownload: false, + }); + + const newerUpdate = { ...rolledOutUpdate, version: "1.2.5" }; + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: newerUpdate }); + const result = await service.downloadAndInstallUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + }); + + expect(result.installed).toBe(true); + expect(runtime.installedVersions).toEqual(["1.2.5"]); + }); + + it("reuses an already-downloaded update when installing manually after switching to notify/off", async () => { + const { runtime, service } = createService({ bucket: async () => 0 }); + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + await service.checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "automatic", + autoDownload: true, + }); + runtime.finishUpdateDownload(rolledOutUpdate); + + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + const result = await service.downloadAndInstallUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + }); + + expect(result.installed).toBe(true); + expect(runtime.downloadCallCount).toBe(0); + expect(runtime.installedVersions).toEqual(["1.2.4"]); + }); + + it("transitions cleanly from notify discovery to automatic background download", async () => { + const { runtime, service } = createService({ bucket: async () => 0 }); + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + const notifyCheck = await service.checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "automatic", + autoDownload: false, + }); + expect(notifyCheck).toMatchObject({ + hasUpdate: true, + readyToInstall: false, + downloading: false, + }); + + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + const autoCheck = await service.checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "automatic", + autoDownload: true, + }); + expect(runtime.lastAutoDownload).toBe(true); + expect(autoCheck).toMatchObject({ + hasUpdate: true, + readyToInstall: false, + downloading: true, + }); + }); + + it("clamps NaN and out-of-range download progress values safely", async () => { + const progressEvents: Array = []; + const { runtime, service } = createService({ + bucket: async () => 0, + onDownloadProgress: (progress) => progressEvents.push(progress), + }); + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + await service.checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "automatic", + autoDownload: true, + }); + + runtime.emitDownloadProgress({ + percent: Number.NaN, + transferred: Number.NaN, + total: Number.POSITIVE_INFINITY, + bytesPerSecond: Number.NaN, + }); + runtime.emitDownloadProgress({ + percent: 140, + transferred: 200, + total: 100, + bytesPerSecond: 50, + }); + + expect(progressEvents).toContainEqual({ + version: "1.2.4", + percent: 0, + transferred: 0, + total: 0, + bytesPerSecond: 0, + }); + expect(progressEvents).toContainEqual({ + version: "1.2.4", + percent: 100, + transferred: 200, + total: 100, + bytesPerSecond: 50, + }); + }); + + it("applies updated updateMode after rollout bucket lookup before authorizing download", async () => { + let mode: DesktopUpdateMode = "automatic"; + let resolveBucket!: (value: number) => void; + const { runtime, service } = createService({ + bucket: () => + new Promise((resolve) => { + resolveBucket = resolve; + }), + updateMode: async () => mode, + }); + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + const check = service.checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "automatic", + }); + await vi.waitFor(() => { + expect(resolveBucket).toBeDefined(); + }); + mode = "notify"; + resolveBucket(0); + const result = await check; + + expect(runtime.lastAutoDownload).toBe(false); + expect(result).toMatchObject({ + hasUpdate: true, + readyToInstall: false, + downloading: false, + latestVersion: "1.2.4", + }); + }); + + it("skips a queued automatic check after Off is saved while an earlier check is in flight", async () => { + let mode: DesktopUpdateMode = "automatic"; + const { runtime, service } = createService({ + bucket: async () => 0, + updateMode: async () => mode, + }); + const firstCheck = runtime.deferNextCheck(); + + const firstPending = service.checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "automatic", + }); + const queuedPending = service.checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "automatic", + }); + + await vi.waitFor(() => { + expect(runtime.checkCount).toBe(1); + }); + mode = "off"; + firstCheck.resolve({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + + const [firstResult, queuedResult] = await Promise.all([firstPending, queuedPending]); + expect(runtime.checkCount).toBe(1); + expect(firstResult.hasUpdate).toBe(false); + expect(queuedResult.hasUpdate).toBe(false); + }); + + it("falls back to automatic mode when reading updateMode fails so updates are never stranded", async () => { + const settingsErrors: unknown[] = []; + const { runtime, service } = createService({ + bucket: async () => 0, + updateMode: async () => { + throw new SyntaxError("Unexpected token } in JSON"); + }, + reportSettingsError: (error) => settingsErrors.push(error), + }); + + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + const autoResult = await service.checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "automatic", + }); + expect(autoResult).toMatchObject({ + hasUpdate: true, + downloading: true, + latestVersion: "1.2.4", + errorMessage: null, + }); + + runtime.finishUpdateDownload(rolledOutUpdate); + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + const installedOnQuit = await service.installUpdateOnQuit({ + currentVersion: "1.2.3", + releaseChannel: "stable", + signal: new AbortController().signal, + }); + expect(installedOnQuit).toBe(true); + expect(settingsErrors.length).toBeGreaterThan(0); + }); + + it("skips installUpdateOnQuit when updateMode is notify or off", async () => { + let mode: DesktopUpdateMode = "automatic"; + const { runtime, service } = createService({ + bucket: async () => 0, + updateMode: async () => mode, + }); + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + await service.checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "automatic", + }); + runtime.finishUpdateDownload(rolledOutUpdate); + + mode = "notify"; + expect( + await service.installUpdateOnQuit({ + currentVersion: "1.2.3", + releaseChannel: "stable", + signal: new AbortController().signal, + }), + ).toBe(false); + + mode = "off"; + expect( + await service.installUpdateOnQuit({ + currentVersion: "1.2.3", + releaseChannel: "stable", + signal: new AbortController().signal, + }), + ).toBe(false); + + expect(runtime.installedVersions).toEqual([]); + }); + + it("reports installer launch failures instead of success on both cached and downloaded paths", async () => { + const { runtime, service } = createService({ bucket: async () => 0 }); + + // Path 1: already downloaded, installer fails to launch + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + await service.checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "automatic", + autoDownload: true, + }); + runtime.finishUpdateDownload(rolledOutUpdate); + + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate }); + runtime.nextQuitAndInstallResult = { + started: false, + errorMessage: "EROFS: read-only file system", + }; + const cachedFailure = await service.downloadAndInstallUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + }); + expect(cachedFailure).toMatchObject({ + installed: false, + errorMessage: "EROFS: read-only file system", + }); + + // Path 2: fresh download, installer fails to launch + const newerUpdate = { ...rolledOutUpdate, version: "1.2.5" }; + runtime.nextCheck({ isUpdateAvailable: true, updateInfo: newerUpdate }); + runtime.nextQuitAndInstallResult = { + started: false, + errorMessage: "Neither dpkg nor apt command found", + }; + const freshFailure = await service.downloadAndInstallUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + }); + expect(freshFailure).toMatchObject({ + installed: false, + errorMessage: "Neither dpkg nor apt command found", + }); + }); }); diff --git a/packages/desktop/src/features/app-update-service.ts b/packages/desktop/src/features/app-update-service.ts index 21789950b..e3d8d32d4 100644 --- a/packages/desktop/src/features/app-update-service.ts +++ b/packages/desktop/src/features/app-update-service.ts @@ -1,3 +1,4 @@ +import type { DesktopUpdateMode } from "../settings/desktop-settings.js"; import { rolloutManifestSchema, shouldAdmitAppUpdate, @@ -5,9 +6,18 @@ import { type AppUpdateCheckIntent, } from "./app-update-rollout.js"; +export interface AppUpdateDownloadProgress { + version: string | null; + percent: number; + transferred: number; + total: number; + bytesPerSecond: number; +} + export interface AppUpdateCheckResult { hasUpdate: boolean; readyToInstall: boolean; + downloading: boolean; currentVersion: string; latestVersion: string; body: string | null; @@ -19,6 +29,7 @@ export interface AppUpdateInstallResult { installed: boolean; version: string | null; message: string; + errorMessage?: string | null; } export interface RuntimeUpdateInfo { @@ -28,6 +39,13 @@ export interface RuntimeUpdateInfo { rolloutHours?: unknown; } +export interface RuntimeDownloadProgressInfo { + percent: number; + transferred: number; + total: number; + bytesPerSecond: number; +} + export interface RuntimeUpdateCheckResult { isUpdateAvailable: boolean; updateInfo: RuntimeUpdateInfo; @@ -35,8 +53,10 @@ export interface RuntimeUpdateCheckResult { export interface AppUpdateRuntimeConfiguration { releaseChannel: AppReleaseChannel; + autoDownload: boolean; shouldAdmitUpdate(info: RuntimeUpdateInfo): boolean | Promise; onUpdateAvailable(info: RuntimeUpdateInfo): void; + onDownloadProgress(progress: RuntimeDownloadProgressInfo): void; onUpdateDownloaded(info: RuntimeUpdateInfo): void; onError(error: unknown): void; } @@ -47,11 +67,19 @@ export interface AppUpdateInstallRequest { isForceRunAfter: boolean; } +export interface AppUpdateInstallLaunchResult { + started: boolean; + errorMessage?: string; +} + export interface AppUpdateRuntime { configure(input: AppUpdateRuntimeConfiguration): void; + setAutoDownload?(enabled: boolean): void; checkForUpdates(): Promise; downloadUpdate(targetVersion: string): Promise; - quitAndInstall(input: AppUpdateInstallRequest): void; + quitAndInstall( + input: AppUpdateInstallRequest, + ): Promise | AppUpdateInstallLaunchResult; } export interface AppUpdateService { @@ -59,6 +87,7 @@ export interface AppUpdateService { currentVersion: string; releaseChannel: AppReleaseChannel; intent: AppUpdateCheckIntent; + autoDownload?: boolean; }): Promise; downloadAndInstallUpdate( input: { @@ -79,6 +108,9 @@ export interface AppUpdateServiceDeps { isPackaged(): boolean; now(): number; bucket(): Promise; + updateMode?: () => DesktopUpdateMode | Promise; + onDownloadProgress?(progress: AppUpdateDownloadProgress | null): void; + reportSettingsError?(error: unknown): void; reportCheckError?(error: unknown): void; reportRuntimeError?(error: unknown): void; reportInstallError?(message: string): void; @@ -88,14 +120,23 @@ function buildCheckResult(input: { currentVersion: string; hasUpdate: boolean; readyToInstall: boolean; + downloading?: boolean; info?: RuntimeUpdateInfo | null; errorMessage?: string | null; }): AppUpdateCheckResult { - const { currentVersion, hasUpdate, readyToInstall, info, errorMessage = null } = input; + const { + currentVersion, + hasUpdate, + readyToInstall, + downloading = false, + info, + errorMessage = null, + } = input; return { hasUpdate, readyToInstall, + downloading, currentVersion, latestVersion: info?.version ?? currentVersion, body: typeof info?.releaseNotes === "string" ? info.releaseNotes : null, @@ -117,11 +158,14 @@ async function performQuitAndInstall( }, ): Promise { if (onBeforeQuit) await onBeforeQuit(); - runtime.quitAndInstall({ + const launch = await runtime.quitAndInstall({ targetVersion, isSilent: !restart, isForceRunAfter: restart, }); + if (!launch.started) { + throw new Error(launch.errorMessage ?? "Failed to launch update installer."); + } } function getErrorMessage(error: unknown): string { @@ -145,6 +189,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer let configuredReleaseChannel: AppReleaseChannel | null = null; let preparationError: { version: string; message: string } | null = null; let preparingUpdateVersion: string | null = null; + let currentAutoDownload = true; let checkQueue: Promise = Promise.resolve(); function isReadyToInstallVersion(version: string): boolean { @@ -156,6 +201,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer downloadedUpdateVersion = null; preparationError = null; preparingUpdateVersion = null; + deps.onDownloadProgress?.(null); } function buildPreviouslyAdmittedUpdateResult( @@ -167,42 +213,89 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer return null; } + const readyToInstall = isReadyToInstallVersion(info.version); return buildCheckResult({ currentVersion, hasUpdate: true, - readyToInstall: isReadyToInstallVersion(info.version), + readyToInstall, + downloading: !readyToInstall && preparingUpdateVersion === info.version, info, errorMessage: preparationError?.version === info.version ? preparationError.message : null, }); } - function configureRuntime(releaseChannel: AppReleaseChannel, intent: AppUpdateCheckIntent): void { + async function resolveUpdateMode(): Promise { + if (!deps.updateMode) { + return "automatic"; + } + try { + return await deps.updateMode(); + } catch (error) { + deps.reportSettingsError?.(error); + return "automatic"; + } + } + + function resolveAutoDownload(mode: DesktopUpdateMode, override: boolean | undefined): boolean { + return override ?? mode === "automatic"; + } + + function configureRuntime( + releaseChannel: AppReleaseChannel, + intent: AppUpdateCheckIntent, + initialAutoDownload: boolean, + autoDownloadOverride: boolean | undefined, + ): void { if (configuredReleaseChannel !== releaseChannel) { clearUpdateState(); configuredReleaseChannel = releaseChannel; } + currentAutoDownload = initialAutoDownload; deps.runtime.configure({ releaseChannel, + autoDownload: initialAutoDownload, shouldAdmitUpdate: async (info) => { const parsed = rolloutManifestSchema.parse(info); - return shouldAdmitAppUpdate({ + const bucket = await deps.bucket(); + const liveMode = await resolveUpdateMode(); + if (intent === "automatic" && liveMode === "off") { + return false; + } + const admitted = shouldAdmitAppUpdate({ channel: releaseChannel, intent, rolloutHours: parsed.rolloutHours, releaseDate: parsed.releaseDate, now: deps.now(), - bucket: await deps.bucket(), + bucket, }); + if (admitted) { + currentAutoDownload = resolveAutoDownload(liveMode, autoDownloadOverride); + deps.runtime.setAutoDownload?.(currentAutoDownload); + } + return admitted; }, onUpdateAvailable(info) { const alreadyReady = downloadedUpdateVersion === info.version; cachedUpdateInfo = info; downloadedUpdateVersion = alreadyReady ? info.version : null; - if (!alreadyReady && preparingUpdateVersion === null) { + if (!alreadyReady && currentAutoDownload && preparingUpdateVersion === null) { preparingUpdateVersion = info.version; } }, + onDownloadProgress(progress) { + const percent = Number.isFinite(progress.percent) + ? Math.max(0, Math.min(100, progress.percent)) + : 0; + deps.onDownloadProgress?.({ + version: preparingUpdateVersion ?? cachedUpdateInfo?.version ?? null, + percent, + transferred: Number.isFinite(progress.transferred) ? progress.transferred : 0, + total: Number.isFinite(progress.total) ? progress.total : 0, + bytesPerSecond: Number.isFinite(progress.bytesPerSecond) ? progress.bytesPerSecond : 0, + }); + }, onUpdateDownloaded(info) { // A superseded download can finish after a newer manifest check. Keep // the validated manifest as the install target in that case. @@ -214,6 +307,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer if (preparationError?.version === info.version) { preparationError = null; } + deps.onDownloadProgress?.(null); }, onError(error) { if (preparingUpdateVersion) { @@ -223,6 +317,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer }; preparingUpdateVersion = null; } + deps.onDownloadProgress?.(null); deps.reportRuntimeError?.(error); }, }); @@ -237,14 +332,58 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer return result; } + function resolveAvailableUpdateResult( + currentVersion: string, + info: RuntimeUpdateInfo, + ): AppUpdateCheckResult { + const latestVersion = info.version; + if (latestVersion === currentVersion) { + clearUpdateState(); + return buildCheckResult({ + currentVersion, + hasUpdate: false, + readyToInstall: false, + }); + } + + cachedUpdateInfo = info; + const readyToInstall = isReadyToInstallVersion(latestVersion); + const errorMessage = + preparationError?.version === latestVersion ? preparationError.message : null; + if (!errorMessage) { + preparationError = null; + } + if ( + !readyToInstall && + !errorMessage && + currentAutoDownload && + preparingUpdateVersion === null + ) { + preparingUpdateVersion = latestVersion; + } + return buildCheckResult({ + currentVersion, + hasUpdate: true, + readyToInstall, + downloading: + !readyToInstall && + !errorMessage && + (currentAutoDownload || preparingUpdateVersion === latestVersion), + info, + errorMessage, + }); + } + async function checkForAppUpdate({ currentVersion, releaseChannel, intent, + autoDownload, }: { currentVersion: string; releaseChannel: AppReleaseChannel; intent: AppUpdateCheckIntent; + autoDownload?: boolean; }): Promise { if (!deps.isPackaged()) { return buildCheckResult({ @@ -255,10 +394,33 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer } return runCheckExclusively(async () => { - configureRuntime(releaseChannel, intent); + const mode = deps.updateMode ? await resolveUpdateMode() : "automatic"; + if (intent === "automatic" && mode === "off") { + return buildCheckResult({ + currentVersion, + hasUpdate: false, + readyToInstall: false, + }); + } + if (intent === "manual") { + preparationError = null; + } + configureRuntime( + releaseChannel, + intent, + resolveAutoDownload(mode, autoDownload), + autoDownload, + ); try { const result = await deps.runtime.checkForUpdates(); + if (intent === "automatic" && deps.updateMode && (await resolveUpdateMode()) === "off") { + return buildCheckResult({ + currentVersion, + hasUpdate: false, + readyToInstall: false, + }); + } if (!result || !result.updateInfo) { clearUpdateState(); return buildCheckResult({ @@ -285,32 +447,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer }); } - const info = result.updateInfo; - const latestVersion = info.version; - const hasUpdate = latestVersion !== currentVersion; - - if (hasUpdate) { - cachedUpdateInfo = info; - const errorMessage = - preparationError?.version === latestVersion ? preparationError.message : null; - if (!errorMessage) { - preparationError = null; - } - return buildCheckResult({ - currentVersion, - hasUpdate: true, - readyToInstall: isReadyToInstallVersion(latestVersion), - info, - errorMessage, - }); - } - - clearUpdateState(); - return buildCheckResult({ - currentVersion, - hasUpdate: false, - readyToInstall: false, - }); + return resolveAvailableUpdateResult(currentVersion, result.updateInfo); } catch (error) { deps.reportCheckError?.(error); return buildCheckResult({ @@ -345,18 +482,39 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer currentVersion, releaseChannel, intent: "manual", + autoDownload: false, }); if (!check.hasUpdate) { return { installed: false, version: currentVersion, message: check.errorMessage ?? "No update available.", + ...(check.errorMessage ? { errorMessage: check.errorMessage } : {}), }; } return installCachedUpdate(currentVersion, { onBeforeQuit, restart: true }); } + function clearPreparingVersion(version: string): void { + if (preparingUpdateVersion === version) { + preparingUpdateVersion = null; + } + deps.onDownloadProgress?.(null); + } + + function shouldRetryStaleDownloadError( + attemptedVersion: string, + readyVersion: string, + signal?: AbortSignal, + ): boolean { + return ( + attemptedVersion !== readyVersion && + cachedUpdateInfo?.version === readyVersion && + !signal?.aborted + ); + } + async function ensureUpdateDownloaded( readyVersion: string, signal?: AbortSignal, @@ -367,14 +525,14 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer const attemptedVersion: string = preparingUpdateVersion ?? readyVersion; preparingUpdateVersion ??= readyVersion; + if (preparationError?.version === attemptedVersion) { + preparationError = null; + } try { await deps.runtime.downloadUpdate(attemptedVersion); } catch (error) { - if ( - attemptedVersion !== readyVersion && - cachedUpdateInfo?.version === readyVersion && - !signal?.aborted - ) { + clearPreparingVersion(attemptedVersion); + if (shouldRetryStaleDownloadError(attemptedVersion, readyVersion, signal)) { continue; } throw error; @@ -385,7 +543,9 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer // validated release instead of treating the stale artifact as ready. if (attemptedVersion === readyVersion && !isReadyToInstallVersion(readyVersion)) { downloadedUpdateVersion = readyVersion; - preparingUpdateVersion = null; + clearPreparingVersion(readyVersion); + } else if (preparingUpdateVersion === attemptedVersion) { + clearPreparingVersion(attemptedVersion); } } @@ -417,30 +577,19 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer return buildDeferredInstallResult(currentVersion); } - if (isReadyToInstallVersion(readyVersion)) { - await performQuitAndInstall(deps.runtime, { - targetVersion: readyVersion, - onBeforeQuit, - restart, - }); - return { - installed: true, - version: readyVersion, - message: "Update downloaded. The app will restart shortly.", - }; - } - try { - const preparation = await ensureUpdateDownloaded(readyVersion, signal); - if (preparation === "aborted") { - return buildDeferredInstallResult(currentVersion); - } - if (preparation === "superseded") { - return { - installed: false, - version: currentVersion, - message: "A newer update was found and will be installed later.", - }; + if (!isReadyToInstallVersion(readyVersion)) { + const preparation = await ensureUpdateDownloaded(readyVersion, signal); + if (preparation === "aborted") { + return buildDeferredInstallResult(currentVersion); + } + if (preparation === "superseded") { + return { + installed: false, + version: currentVersion, + message: "A newer update was found and will be installed later.", + }; + } } await performQuitAndInstall(deps.runtime, { targetVersion: readyVersion, @@ -454,12 +603,14 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer message: "Update downloaded. The app will restart shortly.", }; } catch (error) { + deps.onDownloadProgress?.(null); const message = error instanceof Error ? error.message : String(error); deps.reportInstallError?.(message); return { installed: false, version: currentVersion, message: `Update failed: ${message}`, + errorMessage: message, }; } } @@ -476,6 +627,9 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer if (!deps.isPackaged() || !downloadedUpdateVersion) { return false; } + if ((await resolveUpdateMode()) !== "automatic") { + return false; + } const check = await checkForAppUpdate({ currentVersion, diff --git a/packages/desktop/src/features/auto-updater.test.ts b/packages/desktop/src/features/auto-updater.test.ts index 6cd6da2c7..7374966e9 100644 --- a/packages/desktop/src/features/auto-updater.test.ts +++ b/packages/desktop/src/features/auto-updater.test.ts @@ -1,14 +1,26 @@ +import { EventEmitter } from "node:events"; import { mkdtemp, readFile, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { UUID } from "builder-util-runtime"; import { describe, expect, it, vi } from "vitest"; -const { autoUpdaterMock } = vi.hoisted(() => { - const handlers = new Map void>(); +const { autoUpdaterMock, getAllWindowsMock, desktopSettingsMock } = vi.hoisted(() => { + const handlers = new Map void>>(); return { + getAllWindowsMock: vi.fn<() => unknown[]>(() => []), + desktopSettingsMock: { + mode: "automatic" as "automatic" | "notify" | "off", + error: null as Error | null, + }, autoUpdaterMock: { - handlers, + handlers: { + get: (event: string) => (value: unknown) => { + for (const listener of handlers.get(event) ?? []) { + listener(value); + } + }, + }, logger: { debug: vi.fn(), error: vi.fn((message: unknown) => console.error(message)), @@ -18,7 +30,15 @@ const { autoUpdaterMock } = vi.hoisted(() => { checkForUpdates: vi.fn(), downloadUpdate: vi.fn(), on: vi.fn((event: string, handler: (value: unknown) => void) => { - handlers.set(event, handler); + let set = handlers.get(event); + if (!set) { + set = new Set(); + handlers.set(event, set); + } + set.add(handler); + }), + removeListener: vi.fn((event: string, handler: (value: unknown) => void) => { + handlers.get(event)?.delete(handler); }), quitAndInstall: vi.fn(), }, @@ -30,6 +50,26 @@ vi.mock("electron", () => ({ getPath: vi.fn(), isPackaged: true, }, + autoUpdater: undefined, + BrowserWindow: { + getAllWindows: getAllWindowsMock, + }, +})); + +vi.mock("../settings/desktop-settings-electron.js", () => ({ + getDesktopSettingsStore: () => ({ + get: async () => { + if (desktopSettingsMock.error) { + throw desktopSettingsMock.error; + } + return { + releaseChannel: "stable", + updates: { mode: desktopSettingsMock.mode }, + notifications: { playSound: true }, + daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: true }, + }; + }, + }), })); vi.mock("electron-updater", () => ({ @@ -40,8 +80,10 @@ import { bucketFromStagingUserId, checkForAppUpdate, createAppUpdateLifecycleLogger, + downloadAndInstallUpdate, resolveStagingUserId, rolloutManifestSchema, + runElectronQuitAndInstall, shouldAdmitToRollout, shouldInstallAppUpdateOnQuit, } from "./auto-updater"; @@ -67,6 +109,7 @@ describe("checkForAppUpdate", () => { expect(result).toEqual({ hasUpdate: false, readyToInstall: false, + downloading: false, currentVersion: "1.2.3", latestVersion: "1.2.3", body: null, @@ -97,6 +140,248 @@ describe("checkForAppUpdate", () => { consoleError.mockRestore(); }); + it("configures electron-updater autoDownload from checkForAppUpdate options", async () => { + autoUpdaterMock.checkForUpdates.mockResolvedValueOnce({ + isUpdateAvailable: true, + updateInfo: { version: "1.2.5" }, + }); + + const result = await checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "automatic", + autoDownload: false, + }); + + expect((autoUpdaterMock as unknown as { autoDownload?: boolean }).autoDownload).toBe(false); + expect(result).toMatchObject({ + hasUpdate: true, + readyToInstall: false, + downloading: false, + latestVersion: "1.2.5", + }); + }); + + it("forwards download-progress to window progress bars and renderer events", async () => { + const setProgressBar = vi.fn(); + const send = vi.fn(); + getAllWindowsMock.mockReturnValue([ + { isDestroyed: () => false, setProgressBar, webContents: { send } }, + ]); + autoUpdaterMock.checkForUpdates.mockResolvedValueOnce({ + isUpdateAvailable: true, + updateInfo: { version: "1.2.6" }, + }); + + await checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "automatic", + autoDownload: true, + }); + autoUpdaterMock.handlers.get("download-progress")?.({ + percent: 42, + transferred: 420, + total: 1000, + bytesPerSecond: 100, + }); + + expect(setProgressBar).toHaveBeenCalledWith(0.42); + expect(send).toHaveBeenCalledWith("paseo:event:app-update-download-progress", { + version: "1.2.6", + percent: 42, + transferred: 420, + total: 1000, + bytesPerSecond: 100, + }); + + autoUpdaterMock.handlers.get("update-downloaded")?.({ version: "1.2.6" }); + expect(setProgressBar).toHaveBeenLastCalledWith(-1); + expect(send).toHaveBeenLastCalledWith("paseo:event:app-update-download-progress", null); + getAllWindowsMock.mockReturnValue([]); + }); + + it("gates automatic checks and autoDownload from desktop settings and falls back to automatic on read failure", async () => { + const consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + try { + autoUpdaterMock.checkForUpdates.mockClear(); + desktopSettingsMock.mode = "off"; + const offAuto = await checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "automatic", + }); + expect(offAuto.hasUpdate).toBe(false); + expect(autoUpdaterMock.checkForUpdates).not.toHaveBeenCalled(); + + autoUpdaterMock.checkForUpdates.mockResolvedValueOnce({ + isUpdateAvailable: true, + updateInfo: { version: "1.2.9" }, + }); + const offManual = await checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "manual", + }); + expect(offManual).toMatchObject({ + hasUpdate: true, + downloading: false, + latestVersion: "1.2.9", + }); + + desktopSettingsMock.mode = "automatic"; + desktopSettingsMock.error = new SyntaxError("Unexpected token } in JSON"); + autoUpdaterMock.checkForUpdates.mockResolvedValueOnce({ + isUpdateAvailable: true, + updateInfo: { version: "1.2.10" }, + }); + const fallbackResult = await checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "automatic", + }); + expect(fallbackResult).toMatchObject({ + hasUpdate: true, + downloading: true, + latestVersion: "1.2.10", + }); + expect(consoleWarn).toHaveBeenCalled(); + autoUpdaterMock.handlers.get("update-downloaded")?.({ version: "1.2.10" }); + } finally { + desktopSettingsMock.mode = "automatic"; + desktopSettingsMock.error = null; + consoleWarn.mockRestore(); + } + }); + + it("does not fail update events when setProgressBar throws", async () => { + const send = vi.fn(); + getAllWindowsMock.mockReturnValue([ + { + isDestroyed: () => false, + setProgressBar: () => { + throw new Error("unsupported desktop environment"); + }, + webContents: { send }, + }, + ]); + autoUpdaterMock.checkForUpdates.mockResolvedValueOnce({ + isUpdateAvailable: true, + updateInfo: { version: "1.2.7" }, + }); + + await checkForAppUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + intent: "automatic", + autoDownload: true, + }); + expect(() => { + autoUpdaterMock.handlers.get("download-progress")?.({ + percent: 50, + transferred: 50, + total: 100, + bytesPerSecond: 10, + }); + }).not.toThrow(); + expect(send).toHaveBeenCalledWith( + "paseo:event:app-update-download-progress", + expect.objectContaining({ version: "1.2.7", percent: 50 }), + ); + getAllWindowsMock.mockReturnValue([]); + }); + + it("reports a failure when quitAndInstall emits an installer error and returns normally", async () => { + const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined); + autoUpdaterMock.checkForUpdates.mockResolvedValueOnce({ + isUpdateAvailable: true, + updateInfo: { version: "1.2.8" }, + }); + autoUpdaterMock.downloadUpdate.mockResolvedValueOnce(undefined); + autoUpdaterMock.quitAndInstall.mockImplementationOnce(() => { + autoUpdaterMock.handlers.get("error")?.(new Error("EROFS: read-only file system")); + }); + + const result = await downloadAndInstallUpdate({ + currentVersion: "1.2.3", + releaseChannel: "stable", + }); + + expect(result).toMatchObject({ + installed: false, + errorMessage: "EROFS: read-only file system", + }); + consoleError.mockRestore(); + }); + + it("waits on macOS explicit installs until Squirrel reports an error or signals quit, while returning immediately on quit-time handoff", async () => { + const updater = Object.assign(new EventEmitter(), { + quitAndInstall: vi.fn(), + }); + const nativeUpdater = new EventEmitter(); + + const failedInstall = runElectronQuitAndInstall({ + platform: "darwin", + updater, + nativeUpdater, + isSilent: false, + isForceRunAfter: true, + }); + expect( + await Promise.race([failedInstall.then(() => "settled"), Promise.resolve("pending")]), + ).toBe("pending"); + + nativeUpdater.emit("error", new Error("Code signature invalid")); + await expect(failedInstall).resolves.toEqual({ + started: false, + errorMessage: "Code signature invalid", + }); + expect(updater.listenerCount("error")).toBe(0); + expect(nativeUpdater.listenerCount("error")).toBe(0); + expect(nativeUpdater.listenerCount("before-quit-for-update")).toBe(0); + + const restartInstall = runElectronQuitAndInstall({ + platform: "darwin", + updater, + nativeUpdater, + isSilent: false, + isForceRunAfter: true, + }); + nativeUpdater.emit("before-quit-for-update"); + await expect(restartInstall).resolves.toEqual({ started: true }); + + // Quit-time install (isForceRunAfter: false) returns immediately so + // quit-lifecycle owns its separate handoff deadline. + await expect( + runElectronQuitAndInstall({ + platform: "darwin", + updater, + nativeUpdater, + isSilent: true, + isForceRunAfter: false, + }), + ).resolves.toEqual({ started: true }); + expect(nativeUpdater.listenerCount("before-quit-for-update")).toBe(0); + + // Explicit install times out cleanly instead of hanging forever if Squirrel never emits. + await expect( + runElectronQuitAndInstall({ + platform: "darwin", + updater, + nativeUpdater, + isSilent: false, + isForceRunAfter: true, + timeoutMs: 10, + }), + ).resolves.toEqual({ + started: false, + errorMessage: "Timed out waiting for the update installer to start.", + }); + expect(updater.listenerCount("error")).toBe(0); + expect(nativeUpdater.listenerCount("error")).toBe(0); + expect(nativeUpdater.listenerCount("before-quit-for-update")).toBe(0); + }); + it("logs the update handoff with current and selected target versions", () => { const info = vi.fn(); const lifecycleLog = createAppUpdateLifecycleLogger({ info }); diff --git a/packages/desktop/src/features/auto-updater.ts b/packages/desktop/src/features/auto-updater.ts index ef71dc25b..c99b73173 100644 --- a/packages/desktop/src/features/auto-updater.ts +++ b/packages/desktop/src/features/auto-updater.ts @@ -1,17 +1,21 @@ import { randomBytes } from "node:crypto"; import { mkdir, readFile, writeFile } from "node:fs/promises"; import path from "node:path"; -import { app } from "electron"; +import { app, autoUpdater as electronAutoUpdater, BrowserWindow } from "electron"; import { UUID } from "builder-util-runtime"; import log from "electron-log/main"; import { autoUpdater } from "electron-updater"; +import { getDesktopSettingsStore } from "../settings/desktop-settings-electron.js"; import { createAppUpdateService, type AppUpdateCheckResult, + type AppUpdateDownloadProgress, + type AppUpdateInstallLaunchResult, type AppUpdateInstallRequest, type AppUpdateInstallResult, type AppUpdateRuntime, type AppUpdateRuntimeConfiguration, + type RuntimeDownloadProgressInfo, type RuntimeUpdateCheckResult, type RuntimeUpdateInfo, } from "./app-update-service.js"; @@ -30,6 +34,7 @@ export { type AppReleaseChannel, type AppUpdateCheckIntent, type AppUpdateCheckResult, + type AppUpdateDownloadProgress, type AppUpdateInstallResult, }; @@ -140,11 +145,143 @@ export function shouldInstallAppUpdateOnQuit(input: { return !(input.platform === "linux" && input.isAppImage); } +const APP_UPDATE_DOWNLOAD_PROGRESS_EVENT = "paseo:event:app-update-download-progress"; + +function resolveProgressBarValue(progress: AppUpdateDownloadProgress | null): number { + if (progress === null) return -1; + if (!Number.isFinite(progress.percent)) return 0; + return Math.max(0, Math.min(1, progress.percent / 100)); +} + +function broadcastDownloadProgress(progress: AppUpdateDownloadProgress | null): void { + const normalizedBar = resolveProgressBarValue(progress); + for (const win of BrowserWindow.getAllWindows()) { + if (win.isDestroyed()) continue; + try { + win.setProgressBar(normalizedBar); + } catch { + // Progress bar support is optional across desktop environments. + } + try { + win.webContents.send(APP_UPDATE_DOWNLOAD_PROGRESS_EVENT, progress); + } catch { + // Window may be tearing down during quitAndInstall. + } + } +} + +export const MACOS_INSTALL_HANDOFF_TIMEOUT_MS = 2 * 60 * 1000; + +export interface QuitAndInstallEventSource { + on(event: string, listener: (...args: unknown[]) => void): unknown; + removeListener?(event: string, listener: (...args: unknown[]) => void): unknown; +} + +function formatLaunchError(error: unknown): string { + return error instanceof Error && typeof error.message === "string" + ? error.message + : String(error); +} + +export function runElectronQuitAndInstall({ + platform, + updater, + nativeUpdater, + isSilent, + isForceRunAfter, + timeoutMs = MACOS_INSTALL_HANDOFF_TIMEOUT_MS, +}: { + platform: NodeJS.Platform; + updater: QuitAndInstallEventSource & { + quitAndInstall(isSilent?: boolean, isForceRunAfter?: boolean): void; + }; + nativeUpdater?: QuitAndInstallEventSource; + isSilent: boolean; + isForceRunAfter: boolean; + timeoutMs?: number; +}): Promise { + // Only await macOS Squirrel preparation for explicit Download / Restart Now + // installs (isForceRunAfter === true). Quit-time installs (isForceRunAfter === false) + // return immediately so quit-lifecycle owns its separate handoff deadline. + if (platform !== "darwin" || !isForceRunAfter || typeof nativeUpdater?.on !== "function") { + let launchError: unknown = null; + const captureLaunchError = (error: unknown) => { + launchError ??= error; + }; + updater.on("error", captureLaunchError); + try { + updater.quitAndInstall(isSilent, isForceRunAfter); + } catch (error) { + launchError ??= error; + } finally { + updater.removeListener?.("error", captureLaunchError); + } + if (launchError !== null) { + return Promise.resolve({ started: false, errorMessage: formatLaunchError(launchError) }); + } + return Promise.resolve({ started: true }); + } + + // With autoInstallOnAppQuit disabled, electron-updater's MacUpdater starts + // native Squirrel preparation asynchronously inside quitAndInstall(). Keep + // the explicit install promise pending until Squirrel hands off to quit, fails, + // or hits the safety timeout. + return new Promise((resolve) => { + let settled = false; + let timer: ReturnType | undefined; + const cleanup = () => { + if (timer !== undefined) { + clearTimeout(timer); + } + updater.removeListener?.("error", handleError); + nativeUpdater.removeListener?.("error", handleError); + nativeUpdater.removeListener?.("update-not-available", handleNotAvailable); + nativeUpdater.removeListener?.("before-quit-for-update", handleQuitStarted); + }; + const finish = (result: AppUpdateInstallLaunchResult) => { + if (settled) return; + settled = true; + cleanup(); + resolve(result); + }; + + const handleError = (error: unknown) => { + finish({ started: false, errorMessage: formatLaunchError(error) }); + }; + const handleNotAvailable = () => { + finish({ started: false, errorMessage: "Update could not be prepared for installation." }); + }; + const handleQuitStarted = () => { + finish({ started: true }); + }; + + timer = setTimeout(() => { + finish({ + started: false, + errorMessage: "Timed out waiting for the update installer to start.", + }); + }, timeoutMs); + + updater.on("error", handleError); + nativeUpdater.on("error", handleError); + nativeUpdater.on("update-not-available", handleNotAvailable); + nativeUpdater.on("before-quit-for-update", handleQuitStarted); + + try { + updater.quitAndInstall(isSilent, isForceRunAfter); + } catch (error) { + handleError(error); + } + }); +} + class ElectronAppUpdateRuntime implements AppUpdateRuntime { private configured = false; + private configuration: AppUpdateRuntimeConfiguration | null = null; configure(input: AppUpdateRuntimeConfiguration): void { - autoUpdater.autoDownload = true; + this.configuration = input; + autoUpdater.autoDownload = input.autoDownload; autoUpdater.autoRunAppAfterInstall = true; // Paseo revalidates the current manifest before explicitly installing on quit. // Electron's built-in handler would install an older download without checking @@ -155,7 +292,7 @@ class ElectronAppUpdateRuntime implements AppUpdateRuntime { autoUpdater.allowDowngrade = false; autoUpdater.isUserWithinRollout = async (info) => { try { - return await input.shouldAdmitUpdate(info as RuntimeUpdateInfo); + return await (this.configuration?.shouldAdmitUpdate(info as RuntimeUpdateInfo) ?? true); } catch { return true; } @@ -179,19 +316,26 @@ class ElectronAppUpdateRuntime implements AppUpdateRuntime { autoUpdater.on("update-available", (info) => { const updateInfo = info as RuntimeUpdateInfo; updateLifecycleLog.updateAvailable(updateInfo.version); - input.onUpdateAvailable(updateInfo); + this.configuration?.onUpdateAvailable(updateInfo); + }); + autoUpdater.on("download-progress", (progress) => { + this.configuration?.onDownloadProgress(progress as RuntimeDownloadProgressInfo); }); autoUpdater.on("update-downloaded", (info) => { const updateInfo = info as RuntimeUpdateInfo; updateLifecycleLog.updateDownloaded(updateInfo.version); - input.onUpdateDownloaded(updateInfo); + this.configuration?.onUpdateDownloaded(updateInfo); }); autoUpdater.on("error", (error) => { if (isUpdateChannelNotPublished(error)) return; - input.onError(error); + this.configuration?.onError(error); }); } + setAutoDownload(enabled: boolean): void { + autoUpdater.autoDownload = enabled; + } + async checkForUpdates(): Promise { try { const result = await autoUpdater.checkForUpdates(); @@ -211,14 +355,25 @@ class ElectronAppUpdateRuntime implements AppUpdateRuntime { return autoUpdater.downloadUpdate(); } - quitAndInstall({ targetVersion, isSilent, isForceRunAfter }: AppUpdateInstallRequest): void { + quitAndInstall({ + targetVersion, + isSilent, + isForceRunAfter, + }: AppUpdateInstallRequest): Promise { + broadcastDownloadProgress(null); autoUpdater.autoRunAppAfterInstall = isForceRunAfter; updateLifecycleLog.quitAndInstallRequested({ targetVersion, isSilent, isForceRunAfter, }); - autoUpdater.quitAndInstall(isSilent, isForceRunAfter); + return runElectronQuitAndInstall({ + platform: process.platform, + updater: autoUpdater, + nativeUpdater: electronAutoUpdater, + isSilent, + isForceRunAfter, + }); } } @@ -227,6 +382,14 @@ const appUpdateService = createAppUpdateService({ isPackaged: () => app.isPackaged, now: () => Date.now(), bucket: async () => bucketFromStagingUserId(await getStagingUserId()), + updateMode: async () => (await getDesktopSettingsStore().get()).updates.mode, + onDownloadProgress: broadcastDownloadProgress, + reportSettingsError: (error) => { + console.warn( + "[auto-updater] Failed to read desktop update mode, defaulting to automatic:", + error, + ); + }, reportCheckError: (error) => { console.error("[auto-updater] Failed to check for updates:", error); }, @@ -246,16 +409,19 @@ export async function checkForAppUpdate({ currentVersion, releaseChannel, intent, + autoDownload, }: { currentVersion: string; releaseChannel: AppReleaseChannel; intent: AppUpdateCheckIntent; + autoDownload?: boolean; }): Promise { updateLifecycleLog.checkStarted({ currentVersion, releaseChannel, intent }); const result = await appUpdateService.checkForAppUpdate({ currentVersion, releaseChannel, intent, + autoDownload, }); updateLifecycleLog.checkCompleted({ currentVersion, diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.ts index c59d3f27a..2c1603842 100644 --- a/packages/desktop/src/main.ts +++ b/packages/desktop/src/main.ts @@ -1058,10 +1058,18 @@ const quitLifecycle = createQuitLifecycle({ showShutdownFeedback: showDaemonShutdownDialog, }), installAppUpdateOnQuit: async (signal) => { - const settings = await getDesktopSettingsStore().get(); + let releaseChannel: "stable" | "beta" = "stable"; + try { + releaseChannel = (await getDesktopSettingsStore().get()).releaseChannel; + } catch (error) { + log.warn( + "[auto-updater] Failed to read desktop settings on quit, defaulting to stable:", + error, + ); + } return installAppUpdateOnQuit({ currentVersion: app.getVersion(), - releaseChannel: settings.releaseChannel, + releaseChannel, signal, }); }, diff --git a/packages/desktop/src/settings/desktop-settings.test.ts b/packages/desktop/src/settings/desktop-settings.test.ts index 488118af3..62d78c5d8 100644 --- a/packages/desktop/src/settings/desktop-settings.test.ts +++ b/packages/desktop/src/settings/desktop-settings.test.ts @@ -81,6 +81,7 @@ describe("desktop-settings", () => { expect(settings).toEqual({ releaseChannel: "stable", + updates: { mode: "automatic" }, notifications: { playSound: true }, daemon: { manageBuiltInDaemon: true, @@ -97,12 +98,14 @@ describe("desktop-settings", () => { await store.get(); const next = await store.patch({ releaseChannel: "beta", + updates: { mode: "notify" }, daemon: { keepRunningAfterQuit: false }, }); const files = await readdir(userDataPath); expect(next).toEqual({ releaseChannel: "beta", + updates: { mode: "notify" }, notifications: { playSound: true }, daemon: { manageBuiltInDaemon: true, @@ -112,6 +115,65 @@ describe("desktop-settings", () => { expect(files).toEqual(["desktop-settings.json"]); }); + it("defaults updates.mode to automatic and persists explicit choices across restarts", async () => { + const userDataPath = await createTempUserDataDir(); + directories.add(userDataPath); + await writeFile( + settingsFilePath(userDataPath), + JSON.stringify({ + version: 1, + settings: { + releaseChannel: "stable", + updates: { mode: "invalid" }, + }, + migrations: { + legacyRendererSettingsImported: true, + daemonStopOnQuitDefaultApplied: true, + }, + }), + ); + + const defaulted = await createDesktopSettingsStore({ userDataPath }).get(); + expect(defaulted.updates.mode).toBe("automatic"); + + await createDesktopSettingsStore({ userDataPath }).patch({ updates: { mode: "off" } }); + const persisted = await createDesktopSettingsStore({ userDataPath }).get(); + expect(persisted.updates.mode).toBe("off"); + }); + + it("serializes overlapping patches so neither update mode nor release channel is lost", async () => { + const userDataPath = await createTempUserDataDir(); + directories.add(userDataPath); + const store = createDesktopSettingsStore({ userDataPath }); + + const [offResult, betaResult] = await Promise.all([ + store.patch({ updates: { mode: "off" } }), + store.patch({ releaseChannel: "beta" }), + ]); + + expect(offResult.updates.mode).toBe("off"); + expect(betaResult.updates.mode).toBe("off"); + expect(betaResult.releaseChannel).toBe("beta"); + + const reloaded = await createDesktopSettingsStore({ userDataPath }).get(); + expect(reloaded.updates.mode).toBe("off"); + expect(reloaded.releaseChannel).toBe("beta"); + }); + + it("waits for an in-flight patch before resolving get() from cache", async () => { + const userDataPath = await createTempUserDataDir(); + directories.add(userDataPath); + const store = createDesktopSettingsStore({ userDataPath }); + + await store.patch({ updates: { mode: "off" } }); + const patchPromise = store.patch({ updates: { mode: "automatic" } }); + const readDuringPatch = store.get(); + + const [patched, read] = await Promise.all([patchPromise, readDuringPatch]); + expect(patched.updates.mode).toBe("automatic"); + expect(read.updates.mode).toBe("automatic"); + }); + it("defaults notification sounds on for existing settings documents", async () => { const userDataPath = await createTempUserDataDir(); directories.add(userDataPath); @@ -270,6 +332,7 @@ describe("desktop-settings", () => { expect(migrated).toEqual({ releaseChannel: "beta", + updates: { mode: "automatic" }, notifications: { playSound: true }, daemon: { manageBuiltInDaemon: false, @@ -315,6 +378,7 @@ describe("desktop-settings", () => { expect(persisted.settings.releaseChannel).toBe("beta"); expect(next).toEqual({ releaseChannel: "beta", + updates: { mode: "automatic" }, notifications: { playSound: false }, daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: false }, }); diff --git a/packages/desktop/src/settings/desktop-settings.ts b/packages/desktop/src/settings/desktop-settings.ts index eba54b89a..4bf6e0a17 100644 --- a/packages/desktop/src/settings/desktop-settings.ts +++ b/packages/desktop/src/settings/desktop-settings.ts @@ -6,8 +6,13 @@ import { z } from "zod"; import type { AppReleaseChannel } from "../features/auto-updater.js"; +export type DesktopUpdateMode = "automatic" | "notify" | "off"; + export interface DesktopSettings { releaseChannel: AppReleaseChannel; + updates: { + mode: DesktopUpdateMode; + }; notifications: { playSound: boolean; }; @@ -19,6 +24,7 @@ export interface DesktopSettings { interface DesktopSettingsPatch { releaseChannel?: AppReleaseChannel; + updates?: Partial; notifications?: Partial; daemon?: Partial; } @@ -31,6 +37,9 @@ export interface DesktopSettingsStore { export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = { releaseChannel: "stable", + updates: { + mode: "automatic", + }, notifications: { playSound: true, }, @@ -43,6 +52,13 @@ export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = { const DESKTOP_SETTINGS_FILENAME = "desktop-settings.json"; const ReleaseChannelSchema = z.enum(["stable", "beta"]); +const UpdateModeSchema = z.enum(["automatic", "notify", "off"]); + +const UpdatesSchema = z + .looseObject({ + mode: UpdateModeSchema.catch(DEFAULT_DESKTOP_SETTINGS.updates.mode), + }) + .catch(() => ({ ...DEFAULT_DESKTOP_SETTINGS.updates })); const NotificationsSchema = z .looseObject({ @@ -60,6 +76,7 @@ const DaemonSchema = z const DesktopSettingsSchema = z .looseObject({ releaseChannel: ReleaseChannelSchema.catch(DEFAULT_DESKTOP_SETTINGS.releaseChannel), + updates: UpdatesSchema, notifications: NotificationsSchema, daemon: DaemonSchema, }) @@ -95,6 +112,11 @@ function coerceReleaseChannel(value: unknown): AppReleaseChannel | null { return result.success ? result.data : null; } +function coerceUpdateMode(value: unknown): DesktopUpdateMode | null { + const result = UpdateModeSchema.safeParse(value); + return result.success ? result.data : null; +} + function coerceBoolean(value: unknown): boolean | null { return typeof value === "boolean" ? value : null; } @@ -106,6 +128,7 @@ function isNodeError(error: unknown): error is NodeJS.ErrnoException { function buildDefaultSettings(): StoredDesktopSettings { return { releaseChannel: DEFAULT_DESKTOP_SETTINGS.releaseChannel, + updates: { ...DEFAULT_DESKTOP_SETTINGS.updates }, notifications: { ...DEFAULT_DESKTOP_SETTINGS.notifications }, daemon: { ...DEFAULT_DESKTOP_SETTINGS.daemon }, }; @@ -125,6 +148,7 @@ function buildDefaultDocument(): PersistedDesktopSettingsDocument { function toDesktopSettings(stored: StoredDesktopSettings): DesktopSettings { return { releaseChannel: stored.releaseChannel, + updates: { mode: stored.updates.mode }, notifications: { playSound: stored.notifications.playSound }, daemon: { manageBuiltInDaemon: stored.daemon.manageBuiltInDaemon, @@ -144,6 +168,13 @@ function coerceDesktopSettingsPatch(input: unknown): DesktopSettingsPatch { patch.releaseChannel = releaseChannel; } + if (isRecord(input.updates)) { + const mode = coerceUpdateMode(input.updates.mode); + if (mode) { + patch.updates = { mode }; + } + } + if (isRecord(input.notifications)) { const playSound = coerceBoolean(input.notifications.playSound); if (playSound !== null) { @@ -197,6 +228,7 @@ function mergeDesktopSettings( return { ...current, releaseChannel: patch.releaseChannel ?? current.releaseChannel, + updates: { ...current.updates, ...patch.updates }, notifications: { ...current.notifications, ...patch.notifications }, daemon: { ...current.daemon, ...patch.daemon }, }; @@ -232,22 +264,26 @@ export function createDesktopSettingsStore({ }): DesktopSettingsStore { const filePath = path.join(userDataPath, DESKTOP_SETTINGS_FILENAME); let cachedDocument: PersistedDesktopSettingsDocument | null = null; - let persistQueue: Promise = Promise.resolve(); + let operationQueue: Promise = Promise.resolve(); - async function persistDocument(document: PersistedDesktopSettingsDocument): Promise { - const write = async () => { - await mkdir(userDataPath, { recursive: true }); - const tempFilePath = `${filePath}.tmp.${process.pid}.${randomUUID()}`; - await writeFile(tempFilePath, `${JSON.stringify(document, null, 2)}\n`, "utf8"); - await rename(tempFilePath, filePath); - cachedDocument = document; - }; - const queued = persistQueue.then(write, write); - persistQueue = queued.catch(() => undefined); - await queued; + function enqueueOperation(operation: () => Promise): Promise { + const result = operationQueue.then(operation, operation); + operationQueue = result.then( + () => undefined, + () => undefined, + ); + return result; } - async function loadDocument(): Promise { + async function writeDocument(document: PersistedDesktopSettingsDocument): Promise { + await mkdir(userDataPath, { recursive: true }); + const tempFilePath = `${filePath}.tmp.${process.pid}.${randomUUID()}`; + await writeFile(tempFilePath, `${JSON.stringify(document, null, 2)}\n`, "utf8"); + await rename(tempFilePath, filePath); + cachedDocument = document; + } + + async function loadDocumentUnlocked(): Promise { if (cachedDocument) { return cachedDocument; } @@ -260,7 +296,7 @@ export function createDesktopSettingsStore({ throw error; } const document = buildDefaultDocument(); - await persistDocument(document); + await writeDocument(document); return document; } const document = coerceDocument(JSON.parse(raw)); @@ -268,58 +304,67 @@ export function createDesktopSettingsStore({ return document; } - async function initializeLegacyRendererMigration(): Promise { + async function initializeLegacyRendererMigrationUnlocked(): Promise { try { - return await loadDocument(); + return await loadDocumentUnlocked(); } catch { const document = buildDefaultDocument(); - await persistDocument(document); + await writeDocument(document); return document; } } return { async get(): Promise { - const document = await loadDocument(); + const document = await enqueueOperation(async () => { + if (cachedDocument) { + return cachedDocument; + } + return loadDocumentUnlocked(); + }); return toDesktopSettings(document.settings); }, async patch(patch: unknown): Promise { - const current = await loadDocument(); - const coercedPatch = coerceDesktopSettingsPatch(patch); - const next = mergeDesktopSettings(current.settings, coercedPatch); - await persistDocument({ - ...current, - settings: next, - migrations: { - ...current.migrations, - legacyRendererSettingsImported: - current.migrations.legacyRendererSettingsImported || - hasLegacyRendererOwnedPatch(coercedPatch), - }, + return enqueueOperation(async () => { + const current = await loadDocumentUnlocked(); + const coercedPatch = coerceDesktopSettingsPatch(patch); + const next = mergeDesktopSettings(current.settings, coercedPatch); + await writeDocument({ + ...current, + settings: next, + migrations: { + ...current.migrations, + legacyRendererSettingsImported: + current.migrations.legacyRendererSettingsImported || + hasLegacyRendererOwnedPatch(coercedPatch), + }, + }); + return toDesktopSettings(next); }); - return toDesktopSettings(next); }, async migrateLegacyRendererSettings(legacySettings: unknown): Promise { - const current = await initializeLegacyRendererMigration(); - if (current.migrations.legacyRendererSettingsImported) { - return toDesktopSettings(current.settings); - } + return enqueueOperation(async () => { + const current = await initializeLegacyRendererMigrationUnlocked(); + if (current.migrations.legacyRendererSettingsImported) { + return toDesktopSettings(current.settings); + } - const next = mergeDesktopSettings( - current.settings, - pickDesktopSettingsFromLegacyRendererSettings(legacySettings), - ); - await persistDocument({ - ...current, - settings: next, - migrations: { - ...current.migrations, - legacyRendererSettingsImported: true, - }, + const next = mergeDesktopSettings( + current.settings, + pickDesktopSettingsFromLegacyRendererSettings(legacySettings), + ); + await writeDocument({ + ...current, + settings: next, + migrations: { + ...current.migrations, + legacyRendererSettingsImported: true, + }, + }); + return toDesktopSettings(next); }); - return toDesktopSettings(next); }, }; }