diff --git a/src/main/index.ts b/src/main/index.ts index f4fa875ba..c581e4452 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -5,7 +5,7 @@ import { Store } from './persistence' import { killAllPty } from './ipc/pty' import { registerCoreHandlers } from './ipc/register-core-handlers' import { registerAppMenu } from './menu/register-app-menu' -import { checkForUpdatesFromMenu } from './updater' +import { checkForUpdatesFromMenu, isQuittingForUpdate } from './updater' import { enableMainProcessGpuFeatures, installUncaughtPipeErrorGuard, @@ -63,7 +63,10 @@ app.whenReady().then(() => { openMainWindow() app.on('activate', () => { - if (BrowserWindow.getAllWindows().length === 0) { + // Don't re-open a window while Squirrel's ShipIt is replacing the .app + // bundle. Without this guard the old version gets resurrected and the + // update never applies. + if (BrowserWindow.getAllWindows().length === 0 && !isQuittingForUpdate()) { openMainWindow() } }) diff --git a/src/main/updater-fallback.ts b/src/main/updater-fallback.ts index c25969f87..3b6a1bc69 100644 --- a/src/main/updater-fallback.ts +++ b/src/main/updater-fallback.ts @@ -31,29 +31,89 @@ export function isGitHubReleaseTransitionFailure(normalizedMessage: string): boo ) } -function parseVersion(value: string): number[] | null { - const normalized = value.trim().replace(/^v/i, '') - if (!/^\d+\.\d+\.\d+$/.test(normalized)) { - return null - } - return normalized.split('.').map((part) => Number(part)) +type ParsedVersion = { + core: [number, number, number] + prerelease: string[] } -function compareVersions(left: string, right: string): number { - const leftParts = parseVersion(left) - const rightParts = parseVersion(right) - if (!leftParts || !rightParts) { +function parseVersion(value: string): ParsedVersion | null { + const normalized = value.trim().replace(/^v/i, '') + const match = normalized.match( + /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-.]+))?(?:\+([0-9A-Za-z-.]+))?$/ + ) + if (!match) { + return null + } + + return { + core: [Number(match[1]), Number(match[2]), Number(match[3])], + // We must preserve prerelease ordering because the updater enables + // allowPrerelease to work around GitHub's latest endpoint. Falling back to + // "equal" for `1.2.3-rc.1` would silently suppress valid updates. + prerelease: match[4]?.split('.') ?? [] + } +} + +function compareIdentifiers(left: string, right: string): number { + const leftNumeric = /^\d+$/.test(left) + const rightNumeric = /^\d+$/.test(right) + + if (leftNumeric && rightNumeric) { + return Number(left) - Number(right) + } + if (leftNumeric) { + return -1 + } + if (rightNumeric) { + return 1 + } + return left.localeCompare(right) +} + +/** Returns negative if left < right, 0 if equal, positive if left > right. */ +export function compareVersions(left: string, right: string): number { + const leftVersion = parseVersion(left) + const rightVersion = parseVersion(right) + if (!leftVersion || !rightVersion) { return 0 } - for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) { - const leftPart = leftParts[index] ?? 0 - const rightPart = rightParts[index] ?? 0 + for (let index = 0; index < leftVersion.core.length; index += 1) { + const leftPart = leftVersion.core[index] + const rightPart = rightVersion.core[index] if (leftPart !== rightPart) { return leftPart - rightPart } } + const leftPrerelease = leftVersion.prerelease + const rightPrerelease = rightVersion.prerelease + if (leftPrerelease.length === 0 && rightPrerelease.length === 0) { + return 0 + } + if (leftPrerelease.length === 0) { + return 1 + } + if (rightPrerelease.length === 0) { + return -1 + } + + for (let index = 0; index < Math.max(leftPrerelease.length, rightPrerelease.length); index += 1) { + const leftPart = leftPrerelease[index] + const rightPart = rightPrerelease[index] + if (leftPart === undefined) { + return -1 + } + if (rightPart === undefined) { + return 1 + } + + const comparison = compareIdentifiers(leftPart, rightPart) + if (comparison !== 0) { + return comparison + } + } + return 0 } diff --git a/src/main/updater.fallback.test.ts b/src/main/updater.fallback.test.ts index ccad5dd79..ec983caee 100644 --- a/src/main/updater.fallback.test.ts +++ b/src/main/updater.fallback.test.ts @@ -139,6 +139,15 @@ describe('updater fallback', () => { vi.unstubAllGlobals() }) + it('compares prerelease and build semver strings correctly', async () => { + const { compareVersions } = await import('./updater-fallback') + + expect(compareVersions('1.0.70-rc.1', '1.0.69')).toBeGreaterThan(0) + expect(compareVersions('1.0.70', '1.0.70-rc.1')).toBeGreaterThan(0) + expect(compareVersions('1.0.70+build.5', '1.0.70')).toBe(0) + expect(compareVersions('v1.0.70-beta.2', '1.0.70-beta.1')).toBeGreaterThan(0) + }) + it('falls back to the latest stable GitHub release when GitHub reports no published versions', async () => { mockReleaseLookupResponse() mockCheckFailure('No published versions on GitHub') diff --git a/src/main/updater.ts b/src/main/updater.ts index 893ea132e..fbb797631 100644 --- a/src/main/updater.ts +++ b/src/main/updater.ts @@ -3,7 +3,11 @@ import { autoUpdater } from 'electron-updater' import { is } from '@electron-toolkit/utils' import type { UpdateStatus } from '../shared/types' import { killAllPty } from './ipc/pty' -import { findFallbackReleaseVersion, isGitHubReleaseTransitionFailure } from './updater-fallback' +import { + compareVersions, + findFallbackReleaseVersion, + isGitHubReleaseTransitionFailure +} from './updater-fallback' let mainWindowRef: BrowserWindow | null = null let currentStatus: UpdateStatus = { state: 'idle' } @@ -14,6 +18,9 @@ let availableVersion: string | null = null let availableReleaseUrl: string | null = null let pendingCheckFailureKey: string | null = null let pendingCheckFailurePromise: Promise | null = null +/** Guards against the macOS `activate` handler re-opening the old version + * while Squirrel's ShipIt is replacing the .app bundle. */ +let quittingForUpdate = false /** Whether Squirrel.Mac has finished downloading the update from the localhost proxy. */ let squirrelReady = false @@ -195,16 +202,22 @@ export function checkForUpdatesFromMenu(): void { }) } +export function isQuittingForUpdate(): boolean { + return quittingForUpdate +} + export function quitAndInstall(): void { + // Set this BEFORE anything else so the `activate` handler in index.ts + // won't re-open the old version while Squirrel's ShipIt is replacing + // the .app bundle. Without this guard the quit triggers window + // destruction → BrowserWindow.getAllWindows().length === 0 → activate + // fires → openMainWindow() resurrects the old process and ShipIt + // either can't replace it or the user ends up on the old version. + quittingForUpdate = true + killAllPty() onBeforeQuitCleanup?.() - // Remove close listeners so windows don't block the quit, but do NOT - // destroy them yet. On macOS, MacUpdater.quitAndInstall() delegates to - // Squirrel.Mac's nativeUpdater.quitAndInstall() which handles quitting - // the app. If we destroy windows before Squirrel is ready, the app ends - // up with zero windows and the dock "activate" handler re-opens the old - // version instead of actually updating. for (const win of BrowserWindow.getAllWindows()) { win.removeAllListeners('close') } @@ -245,8 +258,9 @@ export function setupAutoUpdater( if (process.platform === 'darwin') { nativeUpdater.on('update-downloaded', () => { squirrelReady = true - // If we were holding the 'downloaded' status, send it now - if (availableVersion && availableVersion !== app.getVersion()) { + // If we were holding the 'downloaded' status, send it now — but only + // when the staged version is actually newer than what's running. + if (availableVersion && compareVersions(availableVersion, app.getVersion()) > 0) { sendStatus({ state: 'downloaded', version: availableVersion, @@ -264,10 +278,12 @@ export function setupAutoUpdater( autoUpdater.on('update-available', (info) => { const wasUserInitiated = userInitiatedCheck userInitiatedCheck = false - // Guard against re-downloading the version we're already running. - // With allowPrerelease enabled, electron-updater may consider the - // current version as an "available" update (same-version match). - if (info.version === app.getVersion()) { + // Guard against showing an update that isn't actually newer than what's running. + // With allowPrerelease enabled, electron-updater may report the current or + // even an older version as "available". Use semver comparison, not strict + // equality, so we never prompt the user to "update" to a version they already + // have (or an older one). + if (compareVersions(info.version, app.getVersion()) <= 0) { clearAvailableUpdateContext() sendStatus({ state: 'not-available', userInitiated: wasUserInitiated || undefined }) return @@ -293,8 +309,10 @@ export function setupAutoUpdater( }) autoUpdater.on('update-downloaded', (info) => { - // Don't show the banner if the downloaded version is the one already running. - if (info.version === app.getVersion()) { + // Don't show the banner if the downloaded version isn't actually newer + // than what's running. This catches the exact-same-version case as well + // as stale cached updates from an older release. + if (compareVersions(info.version, app.getVersion()) <= 0) { clearAvailableUpdateContext() sendStatus({ state: 'not-available' }) return