Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 7aaff3abcc 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.
2026-11-25 10:45:00 +01:00
32 changed files with 1909 additions and 187 deletions
@@ -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<DesktopSettings["updates"]>;
notifications?: Partial<DesktopSettings["notifications"]>;
daemon?: Partial<DesktopSettings["daemon"]>;
}
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<string, unknown> {
return {
...(updates.releaseChannel ? { releaseChannel: updates.releaseChannel } : {}),
...(updates.updates ? { updates: updates.updates } : {}),
...(updates.notifications ? { notifications: updates.notifications } : {}),
...(updates.daemon ? { daemon: updates.daemon } : {}),
};
@@ -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,26 @@ 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("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 +519,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 {
@@ -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;
@@ -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,
});
@@ -307,10 +384,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 +416,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
commit({
...state,
status: "error",
downloadProgress: null,
errorMessage: message,
isInstalling: false,
});
@@ -341,6 +432,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
listeners.delete(listener);
};
},
setDownloadProgress,
checkForUpdates,
installUpdate,
};
@@ -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<DesktopEventUnlisten> {
if (!shouldShowDesktopUpdateSection()) {
return () => {};
}
return listenToDesktopEvent<unknown>("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 } : {}),
};
}
@@ -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 }),
@@ -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,
});
@@ -34,9 +34,12 @@ type InstallOutcome =
function buildCheckResult(
overrides: Partial<DesktopAppUpdateCheckResult> = {},
): 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,
@@ -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<typeof useTranslation>["t"]): ReactNode {
if (body.kind === "downloading") {
return (
<UpdateDownloadingDescription
versionLabel={body.versionLabel ?? undefined}
percent={body.percent}
t={t}
/>
);
}
if (body.kind === "installing") return t("desktop.updates.callout.installingDescription");
if (body.kind === "error") return body.message;
return <UpdateAvailableDescription versionLabel={body.versionLabel ?? undefined} t={t} />;
return (
<UpdateAvailableDescription
versionLabel={body.versionLabel ?? undefined}
readyToInstall={body.readyToInstall !== false}
t={t}
/>
);
}
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<typeof useTranslation>["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<typeof useTranslation>["t"];
}) {
const summary = formatAvailableSummary(t, versionLabel, readyToInstall);
return (
<>
<SidebarCalloutDescriptionText>
{versionLabel
? t("desktop.updates.callout.versionReady", { version: versionLabel })
: t("desktop.updates.callout.newVersionReady")}
</SidebarCalloutDescriptionText>
<SidebarCalloutDescriptionText>{summary}</SidebarCalloutDescriptionText>
<SidebarCalloutDescriptionText>
{t("desktop.updates.callout.restartWarning")}
</SidebarCalloutDescriptionText>
</>
);
}
function UpdateDownloadingDescription({
versionLabel,
percent,
t,
}: {
versionLabel?: string;
percent: number;
t: ReturnType<typeof useTranslation>["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 (
<View style={styles.progressContainer}>
<SidebarCalloutDescriptionText>
{versionLabel
? t("desktop.updates.callout.downloadingVersionDescription", {
version: versionLabel,
percent: clampedPercent,
})
: t("desktop.updates.callout.downloadingDescription", { percent: clampedPercent })}
</SidebarCalloutDescriptionText>
<View
style={styles.progressTrack}
accessibilityRole="progressbar"
accessibilityValue={accessibilityValue}
>
<View style={progressFillStyle} />
</View>
</View>
);
}
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,
},
}));
@@ -4,11 +4,13 @@ import {
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,
@@ -22,9 +24,12 @@ export type { DesktopAppUpdateStatus };
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,8 +43,9 @@ 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 = useMemo(
@@ -84,13 +90,40 @@ export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
useEffect(() => {
if (!isDesktopApp) {
return undefined;
}
let active = true;
let unlisten: (() => void) | null = null;
void subscribeDesktopAppUpdateDownloadProgress((progress) => {
if (active) {
updater.setDownloadProgress(progress);
}
})
.then((cleanup) => {
if (active) {
unlisten = cleanup;
} else {
cleanup();
}
return undefined;
})
.catch(() => undefined);
return () => {
active = false;
unlisten?.();
};
}, [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 +134,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,
@@ -32,6 +32,9 @@ export interface FakeDesktopBridge extends DesktopSettingsBridge {
const DEFAULT_DESKTOP: DesktopSettings = {
releaseChannel: "stable",
updates: {
mode: "automatic",
},
notifications: {
playSound: true,
},
@@ -656,6 +656,7 @@ describe("loadSettingsFromStorage", () => {
isElectron: true,
settings: {
releaseChannel: "beta",
updates: { mode: "automatic" },
notifications: { playSound: true },
daemon: { manageBuiltInDaemon: false, keepRunningAfterQuit: true },
},
+36
View File
@@ -1539,6 +1539,8 @@ export const ar: TranslationResources = {
status: {
checking: "جارٍ التحقق من وجود تحديثات للتطبيق...",
installing: "جارٍ تثبيت تحديث التطبيق...",
downloadingVersionProgress: "جارٍ تنزيل {{version}}... {{percent}}%",
downloadingProgress: "جارٍ تنزيل تحديث التطبيق... {{percent}}%",
upToDate: "التطبيق محدث.",
upToDateWithLastChecked: "Up to date. Last checked at {{time}}.",
pending: "سنخبرك عندما يصبح التحديث جاهزًا.",
@@ -1546,6 +1548,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: "تحديث التطبيق جاهز للتثبيت.",
@@ -1556,14 +1566,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: "ستؤدي ترقية التطبيق إلى إيقاف تشغيل الوكلاء وإغلاق الجلسات الطرفية.",
@@ -2640,9 +2657,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: "تثبيت التحديث",
+36
View File
@@ -1566,6 +1566,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.",
@@ -1574,6 +1576,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.",
@@ -1584,14 +1594,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.",
@@ -2736,9 +2753,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",
+38
View File
@@ -1576,6 +1576,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.",
@@ -1584,6 +1586,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}}.",
@@ -1596,14 +1608,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:
@@ -2661,9 +2680,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",
+38
View File
@@ -1569,6 +1569,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.",
@@ -1577,6 +1579,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}}.",
@@ -1589,14 +1601,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:
@@ -2661,9 +2680,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",
+37
View File
@@ -1554,6 +1554,8 @@ export const ja: TranslationResources = {
status: {
checking: "アプリの更新を確認中...",
installing: "アプリの更新をインストール中...",
downloadingVersionProgress: "{{version}} をダウンロード中... {{percent}}%",
downloadingProgress: "アプリの更新をダウンロード中... {{percent}}%",
upToDate: "アプリは最新です。",
upToDateWithLastChecked: "最新の状態です。最終確認: {{time}}。",
pending: "更新の準備ができたらお知らせします。",
@@ -1561,6 +1563,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}}。",
@@ -1572,14 +1583,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:
@@ -2628,9 +2646,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: "更新をインストール",
+37
View File
@@ -1545,6 +1545,8 @@ export const ko: TranslationResources = {
status: {
checking: "앱 업데이트 확인 중...",
installing: "앱 업데이트 설치 중...",
downloadingVersionProgress: "{{version}} 다운로드 중... {{percent}}%",
downloadingProgress: "앱 업데이트 다운로드 중... {{percent}}%",
upToDate: "앱이 최신 상태입니다.",
upToDateWithLastChecked: "최신 상태입니다. 마지막 확인: {{time}}.",
pending: "업데이트가 준비되면 알려드리겠습니다.",
@@ -1553,6 +1555,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}}에서 마지막으로 확인했습니다.",
@@ -1565,14 +1576,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: "앱을 업그레이드하면 실행 중인 에이전트가 중지되고 터미널 세션이 닫힙니다.",
@@ -2618,9 +2636,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: "업데이트 설치",
+37
View File
@@ -1566,6 +1566,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.",
@@ -1574,6 +1576,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}}.",
@@ -1586,14 +1597,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:
@@ -2643,9 +2661,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",
+37
View File
@@ -1560,6 +1560,8 @@ export const ru: TranslationResources = {
status: {
checking: "Проверка обновлений приложения...",
installing: "Установка обновления приложения...",
downloadingVersionProgress: "Загрузка {{version}}... {{percent}}%",
downloadingProgress: "Загрузка обновления приложения... {{percent}}%",
upToDate: "Установлена последняя версия приложения.",
upToDateWithLastChecked:
"Установлена последняя версия приложения. Последняя проверка: {{time}}.",
@@ -1569,6 +1571,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}}.",
@@ -1581,14 +1592,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:
@@ -2650,9 +2668,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: "Установить обновление",
+36
View File
@@ -1526,6 +1526,8 @@ export const zhCN: TranslationResources = {
status: {
checking: "正在检查 app 更新...",
installing: "正在安装 app 更新...",
downloadingVersionProgress: "正在下载 {{version}}... {{percent}}%",
downloadingProgress: "正在下载 app 更新... {{percent}}%",
upToDate: "App 已是最新版本。",
upToDateWithLastChecked: "已是最新版本。上次检查时间:{{time}}。",
pending: "更新准备好后会通知你。",
@@ -1533,6 +1535,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 更新可安装。",
@@ -1543,14 +1553,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 会话。",
@@ -2577,9 +2594,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: "安装更新",
+135 -19
View File
@@ -83,6 +83,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";
@@ -609,25 +610,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 (
<View
style={styles.aboutUpdateProgressTrack}
accessibilityRole="progressbar"
accessibilityValue={accessibilityValue}
testID="settings-about-update-progress"
>
<View style={fillStyle} />
</View>
);
}
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,
@@ -637,12 +705,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(() => {
@@ -666,17 +734,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;
@@ -691,10 +778,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;
@@ -715,6 +799,18 @@ function DesktopAppUpdateRow() {
options={releaseChannelOptions}
/>
</View>
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{t("settings.about.autoUpdate.label")}</Text>
<Text style={settingsStyles.rowHint}>{getUpdateModeDescription(t, updateMode)}</Text>
</View>
<SegmentedControl
value={updateMode}
onValueChange={handleUpdateModeChange}
options={updateModeOptions}
testID="settings-about-update-mode"
/>
</View>
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{t("settings.about.updates.label")}</Text>
@@ -726,6 +822,7 @@ function DesktopAppUpdateRow() {
})}
</Text>
) : null}
{downloadPercent !== null ? <DesktopUpdateProgressBar percent={downloadPercent} /> : null}
{errorMessage ? <Text style={styles.aboutErrorText}>{errorMessage}</Text> : null}
</View>
<View style={styles.aboutUpdateActions}>
@@ -739,9 +836,15 @@ function DesktopAppUpdateRow() {
<Button
variant="default"
onPress={handleInstallUpdate}
disabled={isChecking || isInstalling || !isUpdateReady}
disabled={isChecking || isInstalling || !isUpdateActionable}
>
{getUpdateButtonLabel(t, isInstalling, readyUpdateVersion)}
{getUpdateButtonLabel(t, {
isInstalling,
isDownloading: isInstalling && downloadProgress != null,
isActionable: isUpdateActionable,
readyToInstall: isUpdateReady,
latestVersion: actionableVersion,
})}
</Button>
</View>
</View>
@@ -1506,6 +1609,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",
+109 -34
View File
@@ -55,9 +55,12 @@ export async function loadRealDaemonState(): Promise<RealDaemonState> {
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<Record<string, unknown> | undefined>;
__capturedUpdateChecks?: Array<{ intent: unknown; releaseChannel: unknown }>;
__recordDesktopEditorOpen?: (input: DesktopEditorOpenRecord) => Promise<void>;
__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<string, Set<(payload: unknown) => 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<void>((resolve) => setTimeout(resolve, 600));
}
}
if (cfg.slowInstall) {
await new Promise<void>((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<string, unknown>) {
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<string, unknown>) => Promise<string | string[] | null>;
};
getPendingOpenProject: () => Promise<string | null>;
events: { on: () => Promise<() => void> };
events: {
on: (event: string, handler: (payload: unknown) => void) => Promise<() => void>;
};
editor?: {
listTargets: () => Promise<DesktopEditorTargetConfig[]>;
openTarget: (input: DesktopEditorOpenRecord) => Promise<void>;
@@ -226,18 +307,15 @@ export async function installDesktopRuntime(
platform: "darwin",
invoke: async (command: string, args?: Record<string, unknown>) => {
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<void>((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) {
+41
View File
@@ -91,6 +91,47 @@ 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.describe("Desktop daemon management", () => {
@@ -15,12 +15,20 @@ import {
const mocks = vi.hoisted(() => ({
paseoHome: "",
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 +49,7 @@ vi.mock("electron", () => ({
getVersion: vi.fn(() => "1.2.3"),
isPackaged: true,
},
BrowserWindow: { getAllWindows: vi.fn(() => []) },
ipcMain: { handle: vi.fn() },
powerMonitor: { getSystemIdleTime: vi.fn(() => 0) },
}));
@@ -79,6 +88,12 @@ vi.mock("./runtime-paths.js", () => ({
})),
}));
vi.mock("../features/auto-updater.js", async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
checkForAppUpdate: mocks.checkForAppUpdate,
downloadAndInstallUpdate: mocks.downloadAndInstallUpdate,
}));
vi.mock("./cli/external.js", async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
runExternalCliJsonCommand: mocks.runExternalCliJsonCommand,
@@ -93,6 +108,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 +199,69 @@ describe("daemon-manager commands", () => {
writeFileSync(lockPath, JSON.stringify({ ...lock, desktopManaged: false }));
expect(await handler({ listen: "localhost:6799" })).toBeNull();
});
it("blocks automatic update checks when updates.mode is off", async () => {
mocks.settings = {
...DEFAULT_DESKTOP_SETTINGS,
updates: { mode: "off" },
};
const result = await createDaemonCommandHandlers().check_app_update({
intent: "automatic",
});
expect(mocks.checkForAppUpdate).not.toHaveBeenCalled();
expect(result).toEqual({
hasUpdate: false,
readyToInstall: false,
downloading: false,
currentVersion: "1.2.3",
latestVersion: "1.2.3",
body: null,
date: null,
errorMessage: null,
});
});
it("checks without auto-downloading when updates.mode is notify or manual in off mode", async () => {
mocks.checkForAppUpdate.mockResolvedValue({
hasUpdate: true,
readyToInstall: false,
downloading: false,
currentVersion: "1.2.3",
latestVersion: "1.2.4",
body: null,
date: null,
errorMessage: null,
});
mocks.settings = { ...DEFAULT_DESKTOP_SETTINGS, updates: { mode: "notify" } };
await createDaemonCommandHandlers().check_app_update({ intent: "automatic" });
expect(mocks.checkForAppUpdate).toHaveBeenLastCalledWith({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "automatic",
autoDownload: false,
});
mocks.settings = { ...DEFAULT_DESKTOP_SETTINGS, updates: { mode: "off" } };
await createDaemonCommandHandlers().check_app_update({ intent: "manual" });
expect(mocks.checkForAppUpdate).toHaveBeenLastCalledWith({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "manual",
autoDownload: false,
});
mocks.settings = { ...DEFAULT_DESKTOP_SETTINGS, updates: { mode: "automatic" } };
await createDaemonCommandHandlers().check_app_update({ intent: "automatic" });
expect(mocks.checkForAppUpdate).toHaveBeenLastCalledWith({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "automatic",
autoDownload: true,
});
});
});
describe("desktop stops and terminals", () => {
+18 -2
View File
@@ -541,10 +541,26 @@ export function createDaemonCommandHandlers(): Record<string, DesktopCommandHand
},
check_app_update: async (args) => {
const currentVersion = resolveDesktopAppVersion();
const settings = await getDesktopSettingsStore().get();
const intent = parseAppUpdateCheckIntent(args);
const updateMode = settings.updates.mode;
if (intent === "automatic" && updateMode === "off") {
return {
hasUpdate: false,
readyToInstall: false,
downloading: false,
currentVersion,
latestVersion: currentVersion,
body: null,
date: null,
errorMessage: null,
};
}
return checkForAppUpdate({
currentVersion,
releaseChannel: await resolveRequestedReleaseChannel(args),
intent: parseAppUpdateCheckIntent(args),
releaseChannel: parseReleaseChannel(args) ?? settings.releaseChannel,
intent,
autoDownload: updateMode === "automatic",
});
},
install_app_update: async (args) => {
@@ -2,9 +2,12 @@ import { describe, expect, it } from "vitest";
import {
createAppUpdateService,
type AppUpdateDownloadProgress,
type AppUpdateInstallRequest,
type AppUpdateRuntime,
type AppUpdateRuntimeConfiguration,
type RuntimeDownloadProgressInfo,
type RuntimeUpdateCheckResult,
type RuntimeUpdateInfo,
} from "./app-update-service";
@@ -26,6 +29,7 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime {
resolve(): void;
reject(error: Error): void;
} | null = null;
lastAutoDownload: boolean | null = null;
checkCount = 0;
downloadCallCount = 0;
requestedDownloadVersions: string[] = [];
@@ -35,9 +39,14 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime {
configure(input: AppUpdateRuntimeConfiguration): void {
this.configuration = input;
this.lastAutoDownload = input.autoDownload;
this.gate = input.shouldAdmitUpdate;
}
emitDownloadProgress(progress: RuntimeDownloadProgressInfo): void {
this.configuration?.onDownloadProgress(progress);
}
nextCheck(result: { isUpdateAvailable: boolean; updateInfo: RuntimeUpdateInfo } | null): void {
this.checks.push(result);
}
@@ -151,13 +160,18 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime {
}
}
function createService(input?: { now?: () => number; bucket?: () => Promise<number> }) {
function createService(input?: {
now?: () => number;
bucket?: () => Promise<number>;
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),
onDownloadProgress: input?.onDownloadProgress,
});
return { runtime, service };
}
@@ -182,6 +196,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 +218,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 +347,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 +378,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 +587,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 +609,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 +640,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 +670,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 +713,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 +744,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 +763,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 +827,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 +860,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 +868,246 @@ describe("app update service", () => {
errorMessage: null,
});
});
it("reports an available update without downloading when autoDownload is false", async () => {
const progressEvents: Array<AppUpdateDownloadProgress | null> = [];
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<AppUpdateDownloadProgress | null> = [];
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<void>((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<AppUpdateDownloadProgress | null> = [];
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,
});
});
});
@@ -5,9 +5,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 +28,7 @@ export interface AppUpdateInstallResult {
installed: boolean;
version: string | null;
message: string;
errorMessage?: string | null;
}
export interface RuntimeUpdateInfo {
@@ -28,6 +38,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 +52,10 @@ export interface RuntimeUpdateCheckResult {
export interface AppUpdateRuntimeConfiguration {
releaseChannel: AppReleaseChannel;
autoDownload: boolean;
shouldAdmitUpdate(info: RuntimeUpdateInfo): boolean | Promise<boolean>;
onUpdateAvailable(info: RuntimeUpdateInfo): void;
onDownloadProgress(progress: RuntimeDownloadProgressInfo): void;
onUpdateDownloaded(info: RuntimeUpdateInfo): void;
onError(error: unknown): void;
}
@@ -59,6 +78,7 @@ export interface AppUpdateService {
currentVersion: string;
releaseChannel: AppReleaseChannel;
intent: AppUpdateCheckIntent;
autoDownload?: boolean;
}): Promise<AppUpdateCheckResult>;
downloadAndInstallUpdate(
input: {
@@ -79,6 +99,7 @@ export interface AppUpdateServiceDeps {
isPackaged(): boolean;
now(): number;
bucket(): Promise<number>;
onDownloadProgress?(progress: AppUpdateDownloadProgress | null): void;
reportCheckError?(error: unknown): void;
reportRuntimeError?(error: unknown): void;
reportInstallError?(message: string): void;
@@ -88,14 +109,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,
@@ -145,6 +175,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<void> = Promise.resolve();
function isReadyToInstallVersion(version: string): boolean {
@@ -156,6 +187,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
downloadedUpdateVersion = null;
preparationError = null;
preparingUpdateVersion = null;
deps.onDownloadProgress?.(null);
}
function buildPreviouslyAdmittedUpdateResult(
@@ -167,23 +199,31 @@ 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 {
function configureRuntime(
releaseChannel: AppReleaseChannel,
intent: AppUpdateCheckIntent,
autoDownload: boolean,
): void {
if (configuredReleaseChannel !== releaseChannel) {
clearUpdateState();
configuredReleaseChannel = releaseChannel;
}
currentAutoDownload = autoDownload;
deps.runtime.configure({
releaseChannel,
autoDownload,
shouldAdmitUpdate: async (info) => {
const parsed = rolloutManifestSchema.parse(info);
return shouldAdmitAppUpdate({
@@ -199,10 +239,22 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
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 +266,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
if (preparationError?.version === info.version) {
preparationError = null;
}
deps.onDownloadProgress?.(null);
},
onError(error) {
if (preparingUpdateVersion) {
@@ -223,6 +276,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
};
preparingUpdateVersion = null;
}
deps.onDownloadProgress?.(null);
deps.reportRuntimeError?.(error);
},
});
@@ -241,10 +295,12 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
currentVersion,
releaseChannel,
intent,
autoDownload = true,
}: {
currentVersion: string;
releaseChannel: AppReleaseChannel;
intent: AppUpdateCheckIntent;
autoDownload?: boolean;
}): Promise<AppUpdateCheckResult> {
if (!deps.isPackaged()) {
return buildCheckResult({
@@ -255,7 +311,10 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
}
return runCheckExclusively(async () => {
configureRuntime(releaseChannel, intent);
if (intent === "manual") {
preparationError = null;
}
configureRuntime(releaseChannel, intent, autoDownload);
try {
const result = await deps.runtime.checkForUpdates();
@@ -291,15 +350,23 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
if (hasUpdate) {
cachedUpdateInfo = info;
const readyToInstall = isReadyToInstallVersion(latestVersion);
const errorMessage =
preparationError?.version === latestVersion ? preparationError.message : null;
if (!errorMessage) {
preparationError = null;
}
if (!readyToInstall && !errorMessage && autoDownload && preparingUpdateVersion === null) {
preparingUpdateVersion = latestVersion;
}
return buildCheckResult({
currentVersion,
hasUpdate: true,
readyToInstall: isReadyToInstallVersion(latestVersion),
readyToInstall,
downloading:
!readyToInstall &&
!errorMessage &&
(autoDownload || preparingUpdateVersion === latestVersion),
info,
errorMessage,
});
@@ -345,18 +412,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 +455,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 +473,7 @@ 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);
}
}
@@ -454,12 +542,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,
};
}
}
@@ -4,9 +4,10 @@ import path from "node:path";
import { UUID } from "builder-util-runtime";
import { describe, expect, it, vi } from "vitest";
const { autoUpdaterMock } = vi.hoisted(() => {
const { autoUpdaterMock, getAllWindowsMock } = vi.hoisted(() => {
const handlers = new Map<string, (value: unknown) => void>();
return {
getAllWindowsMock: vi.fn<() => unknown[]>(() => []),
autoUpdaterMock: {
handlers,
logger: {
@@ -30,6 +31,9 @@ vi.mock("electron", () => ({
getPath: vi.fn(),
isPackaged: true,
},
BrowserWindow: {
getAllWindows: getAllWindowsMock,
},
}));
vi.mock("electron-updater", () => ({
@@ -67,6 +71,7 @@ describe("checkForAppUpdate", () => {
expect(result).toEqual({
hasUpdate: false,
readyToInstall: false,
downloading: false,
currentVersion: "1.2.3",
latestVersion: "1.2.3",
body: null,
@@ -97,6 +102,104 @@ 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("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("logs the update handoff with current and selected target versions", () => {
const info = vi.fn();
const lifecycleLog = createAppUpdateLifecycleLogger({ info });
+48 -6
View File
@@ -1,17 +1,19 @@
import { randomBytes } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { app } from "electron";
import { app, BrowserWindow } from "electron";
import { UUID } from "builder-util-runtime";
import log from "electron-log/main";
import { autoUpdater } from "electron-updater";
import {
createAppUpdateService,
type AppUpdateCheckResult,
type AppUpdateDownloadProgress,
type AppUpdateInstallRequest,
type AppUpdateInstallResult,
type AppUpdateRuntime,
type AppUpdateRuntimeConfiguration,
type RuntimeDownloadProgressInfo,
type RuntimeUpdateCheckResult,
type RuntimeUpdateInfo,
} from "./app-update-service.js";
@@ -30,6 +32,7 @@ export {
type AppReleaseChannel,
type AppUpdateCheckIntent,
type AppUpdateCheckResult,
type AppUpdateDownloadProgress,
type AppUpdateInstallResult,
};
@@ -140,11 +143,42 @@ 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 {
if (typeof BrowserWindow?.getAllWindows !== "function") {
return;
}
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.
}
}
}
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 +189,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,16 +213,19 @@ 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);
});
}
@@ -212,6 +249,7 @@ class ElectronAppUpdateRuntime implements AppUpdateRuntime {
}
quitAndInstall({ targetVersion, isSilent, isForceRunAfter }: AppUpdateInstallRequest): void {
broadcastDownloadProgress(null);
autoUpdater.autoRunAppAfterInstall = isForceRunAfter;
updateLifecycleLog.quitAndInstallRequested({
targetVersion,
@@ -227,6 +265,7 @@ const appUpdateService = createAppUpdateService({
isPackaged: () => app.isPackaged,
now: () => Date.now(),
bucket: async () => bucketFromStagingUserId(await getStagingUserId()),
onDownloadProgress: broadcastDownloadProgress,
reportCheckError: (error) => {
console.error("[auto-updater] Failed to check for updates:", error);
},
@@ -246,16 +285,19 @@ export async function checkForAppUpdate({
currentVersion,
releaseChannel,
intent,
autoDownload = true,
}: {
currentVersion: string;
releaseChannel: AppReleaseChannel;
intent: AppUpdateCheckIntent;
autoDownload?: boolean;
}): Promise<AppUpdateCheckResult> {
updateLifecycleLog.checkStarted({ currentVersion, releaseChannel, intent });
const result = await appUpdateService.checkForAppUpdate({
currentVersion,
releaseChannel,
intent,
autoDownload,
});
updateLifecycleLog.checkCompleted({
currentVersion,
+3
View File
@@ -1059,6 +1059,9 @@ const quitLifecycle = createQuitLifecycle({
}),
installAppUpdateOnQuit: async (signal) => {
const settings = await getDesktopSettingsStore().get();
if (settings.updates.mode !== "automatic") {
return false;
}
return installAppUpdateOnQuit({
currentVersion: app.getVersion(),
releaseChannel: settings.releaseChannel,
@@ -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,32 @@ 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("defaults notification sounds on for existing settings documents", async () => {
const userDataPath = await createTempUserDataDir();
directories.add(userDataPath);
@@ -270,6 +299,7 @@ describe("desktop-settings", () => {
expect(migrated).toEqual({
releaseChannel: "beta",
updates: { mode: "automatic" },
notifications: { playSound: true },
daemon: {
manageBuiltInDaemon: false,
@@ -315,6 +345,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 },
});
@@ -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<DesktopSettings["updates"]>;
notifications?: Partial<DesktopSettings["notifications"]>;
daemon?: Partial<DesktopSettings["daemon"]>;
}
@@ -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 },
};