diff --git a/src/main/updater-fallback.ts b/src/main/updater-fallback.ts index 2fc0e94ac..b9265e232 100644 --- a/src/main/updater-fallback.ts +++ b/src/main/updater-fallback.ts @@ -97,12 +97,13 @@ export function isValidVersion(value: string): boolean { return parseVersion(value) !== null } -// Why: a user running a prerelease build (e.g. 1.3.17-rc.1) must stay on the -// RC channel for "Check for Updates" to resolve the next RC (1.3.17-rc.2). -// The default generic feed only advertises non-prerelease releases, so without -// this detection a prerelease user would be stuck unless they knew to -// Shift-click the menu item — effectively trapping them on the RC they -// installed. +// Why: a user running a prerelease build (e.g. 1.3.17-rc.1) needs both: +// (1) the next RC (1.3.17-rc.2), which the default generic feed hides, and +// (2) the next stable release, which electron-updater's GitHubProvider +// channel filter hides when the running build is an RC. +// We detect prerelease builds here so the updater can mine GitHub's atom feed +// itself (any channel) and pin the generic provider at the newest tag. Without +// this detection, a prerelease user would be trapped on the RC they installed. export function isPrereleaseVersion(value: string): boolean { const parsed = parseVersion(value) return parsed !== null && parsed.prerelease.length > 0 diff --git a/src/main/updater-prerelease-feed.test.ts b/src/main/updater-prerelease-feed.test.ts new file mode 100644 index 000000000..d0e95c948 --- /dev/null +++ b/src/main/updater-prerelease-feed.test.ts @@ -0,0 +1,76 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { netFetchMock } = vi.hoisted(() => ({ + netFetchMock: vi.fn() +})) + +vi.mock('electron', () => ({ + net: { fetch: netFetchMock } +})) + +function buildAtomFeed(tags: string[]): string { + const entries = tags + .map( + (tag) => + `${tag}` + ) + .join('') + return `${entries}` +} + +function respondWithAtom(tags: string[]): void { + netFetchMock.mockResolvedValue({ + ok: true, + text: () => Promise.resolve(buildAtomFeed(tags)) + }) +} + +describe('fetchNewerReleaseTag', () => { + beforeEach(() => { + vi.resetModules() + netFetchMock.mockReset() + }) + + it('returns the newest stable tag when the user is on an RC and a newer stable exists', async () => { + respondWithAtom(['v1.3.19', 'v1.3.19-rc.6', 'v1.3.19-rc.4', 'v1.3.18']) + const { fetchNewerReleaseTag } = await import('./updater-prerelease-feed') + expect(await fetchNewerReleaseTag('1.3.19-rc.6')).toBe('v1.3.19') + }) + + it('returns the newest RC tag when no stable is newer than the current RC', async () => { + respondWithAtom(['v1.3.19-rc.6', 'v1.3.19-rc.4', 'v1.3.18']) + const { fetchNewerReleaseTag } = await import('./updater-prerelease-feed') + expect(await fetchNewerReleaseTag('1.3.19-rc.4')).toBe('v1.3.19-rc.6') + }) + + it('returns null when nothing in the feed is newer than the current version', async () => { + respondWithAtom(['v1.3.18', 'v1.3.17']) + const { fetchNewerReleaseTag } = await import('./updater-prerelease-feed') + expect(await fetchNewerReleaseTag('1.3.19-rc.6')).toBe(null) + }) + + it('ignores entries with unparseable tags', async () => { + respondWithAtom(['not-a-version', 'v1.3.20', 'garbage']) + const { fetchNewerReleaseTag } = await import('./updater-prerelease-feed') + expect(await fetchNewerReleaseTag('1.3.19-rc.6')).toBe('v1.3.20') + }) + + it('returns null when the fetch is not ok', async () => { + netFetchMock.mockResolvedValue({ ok: false, text: () => Promise.resolve('') }) + const { fetchNewerReleaseTag } = await import('./updater-prerelease-feed') + expect(await fetchNewerReleaseTag('1.3.19-rc.6')).toBe(null) + }) + + it('returns null when the fetch throws', async () => { + netFetchMock.mockRejectedValue(new Error('network down')) + const { fetchNewerReleaseTag } = await import('./updater-prerelease-feed') + expect(await fetchNewerReleaseTag('1.3.19-rc.6')).toBe(null) + }) + + it('picks semver-newest across a mixed-order feed', async () => { + // atom feed sort by publish time, not version — verify we pick by semver + respondWithAtom(['v1.2.0', 'v1.3.19', 'v1.3.19-rc.6', 'v1.3.20-rc.1', 'v1.3.18']) + const { fetchNewerReleaseTag } = await import('./updater-prerelease-feed') + expect(await fetchNewerReleaseTag('1.3.19-rc.6')).toBe('v1.3.20-rc.1') + }) +}) diff --git a/src/main/updater-prerelease-feed.ts b/src/main/updater-prerelease-feed.ts new file mode 100644 index 000000000..ab905f78f --- /dev/null +++ b/src/main/updater-prerelease-feed.ts @@ -0,0 +1,70 @@ +import { net } from 'electron' +import { compareVersions, isValidVersion } from './updater-fallback' + +const ATOM_FEED_URL = 'https://github.com/stablyai/orca/releases.atom' +const RELEASES_DOWNLOAD_BASE = 'https://github.com/stablyai/orca/releases/download' +const FETCH_TIMEOUT_MS = 5000 + +// Why: GitHub's atom feed lists every release (prerelease or stable) in a +// single flat list. Each entry has a /releases/tag/ URL we can mine +// without any channel filtering. +const TAG_HREF_RE = /href="https:\/\/github\.com\/stablyai\/orca\/releases\/tag\/([^"]+)"/g + +export function getReleaseDownloadUrl(tag: string): string { + return `${RELEASES_DOWNLOAD_BASE}/${encodeURIComponent(tag)}` +} + +export function normalizeTagToVersion(tag: string): string { + return tag.replace(/^v/i, '') +} + +/** + * Walks the GitHub releases atom feed and returns the tag of the newest + * release strictly greater than `currentVersion`, regardless of channel. + * + * Why: electron-updater's GitHubProvider filters the feed by channel — when + * the running build is an RC, it only considers other RC/alpha/beta entries, + * so an RC user never gets offered the next *stable* release. By resolving + * the newest tag ourselves (any channel) and then pinning the generic + * provider at `/releases/download/`, we sidestep that channel filter + * entirely. Generic provider just reads the manifest at the URL we give it. + * + * Returns null if the fetch fails, the feed has no parseable tags, or + * nothing in the feed is newer than `currentVersion`. + */ +export async function fetchNewerReleaseTag(currentVersion: string): Promise { + const controller = new AbortController() + const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS) + + try { + const res = await net.fetch(ATOM_FEED_URL, { signal: controller.signal }) + if (!res.ok) { + return null + } + const body = await res.text() + + let bestTag: string | null = null + let bestVersion: string | null = null + + for (const match of body.matchAll(TAG_HREF_RE)) { + const tag = match[1] + const version = normalizeTagToVersion(tag) + if (!isValidVersion(version)) { + continue + } + if (compareVersions(version, currentVersion) <= 0) { + continue + } + if (bestVersion === null || compareVersions(version, bestVersion) > 0) { + bestTag = tag + bestVersion = version + } + } + + return bestTag + } catch { + return null + } finally { + clearTimeout(timeout) + } +} diff --git a/src/main/updater.test.ts b/src/main/updater.test.ts index 995d75ac8..972eefa52 100644 --- a/src/main/updater.test.ts +++ b/src/main/updater.test.ts @@ -120,6 +120,16 @@ vi.mock('./updater-nudge', () => ({ shouldApplyNudge: shouldApplyNudgeMock })) +const { fetchNewerReleaseTagMock } = vi.hoisted(() => ({ + fetchNewerReleaseTagMock: vi.fn() +})) + +vi.mock('./updater-prerelease-feed', () => ({ + fetchNewerReleaseTag: fetchNewerReleaseTagMock, + getReleaseDownloadUrl: (tag: string) => + `https://github.com/stablyai/orca/releases/download/${tag}` +})) + describe('updater', () => { beforeEach(() => { vi.resetModules() @@ -136,6 +146,7 @@ describe('updater', () => { powerMonitorOnMock.mockReset() fetchNudgeMock.mockReset().mockResolvedValue(null) shouldApplyNudgeMock.mockReset().mockReturnValue(false) + fetchNewerReleaseTagMock.mockReset().mockResolvedValue(null) vi.unstubAllGlobals() vi.useRealTimers() }) @@ -751,42 +762,133 @@ describe('updater', () => { expect((autoUpdaterMock as Record).verifyUpdateCodeSignature).toBeUndefined() }) - // Why: a user running an RC (e.g. 1.3.17-rc.1) must stay on the RC channel - // so the default "Check for Updates" path can find the next RC. The generic - // /releases/latest/download/ feed only exposes non-prerelease releases. - it('auto-enables the RC channel at setup when running a prerelease build', async () => { + // Why: a prerelease user (e.g. 1.3.17-rc.1) must be able to upgrade to BOTH + // a newer RC (1.3.17-rc.2) and a newer stable (1.3.18). We solve this by + // resolving the newest tag ourselves from the atom feed and pinning the + // generic feed at /releases/download//. Using electron-updater's + // native github provider with allowPrerelease would filter out stable + // releases for RC users, trapping them on the RC channel. + it('repins the generic feed to the newest RC tag for a prerelease user', async () => { appMock.getVersion.mockReturnValue('1.3.17-rc.1') + fetchNewerReleaseTagMock.mockResolvedValue('v1.3.17-rc.2') autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined) - const { setupAutoUpdater } = await import('./updater') + const { setupAutoUpdater, checkForUpdatesFromMenu } = await import('./updater') const mainWindow = { webContents: { send: vi.fn() } } setupAutoUpdater(mainWindow as never, { getLastUpdateCheckAt: () => Date.now() }) - expect(autoUpdaterMock.allowPrerelease).toBe(true) - expect(autoUpdaterMock.setFeedURL).toHaveBeenCalledWith({ - provider: 'github', - owner: 'stablyai', - repo: 'orca' + // Setup pins the default generic feed; resolver only runs per check. + expect(autoUpdaterMock.setFeedURL).toHaveBeenLastCalledWith({ + provider: 'generic', + url: 'https://github.com/stablyai/orca/releases/latest/download' + }) + expect(autoUpdaterMock.allowPrerelease).not.toBe(true) + + checkForUpdatesFromMenu() + + await vi.waitFor(() => { + expect(fetchNewerReleaseTagMock).toHaveBeenCalledWith('1.3.17-rc.1') + expect(autoUpdaterMock.setFeedURL).toHaveBeenLastCalledWith({ + provider: 'generic', + url: 'https://github.com/stablyai/orca/releases/download/v1.3.17-rc.2' + }) + expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1) }) - expect(autoUpdaterMock.setFeedURL).not.toHaveBeenCalledWith( - expect.objectContaining({ provider: 'generic' }) - ) }) - it('keeps the generic feed at setup when running a stable release', async () => { + // Why: the original bug in PR #1053 was that RC users couldn't upgrade to a + // newer stable release. The resolver must pick that stable tag for a + // prerelease user so the 'update-available' event fires against it. + it('repins the generic feed to a newer stable tag for a prerelease user', async () => { + appMock.getVersion.mockReturnValue('1.3.19-rc.6') + fetchNewerReleaseTagMock.mockResolvedValue('v1.3.19') + autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined) + + const { setupAutoUpdater, checkForUpdatesFromMenu } = await import('./updater') + + const mainWindow = { webContents: { send: vi.fn() } } + setupAutoUpdater(mainWindow as never, { getLastUpdateCheckAt: () => Date.now() }) + + checkForUpdatesFromMenu() + + await vi.waitFor(() => { + expect(autoUpdaterMock.setFeedURL).toHaveBeenLastCalledWith({ + provider: 'generic', + url: 'https://github.com/stablyai/orca/releases/download/v1.3.19' + }) + }) + expect(autoUpdaterMock.allowPrerelease).not.toBe(true) + }) + + // Why: if the atom-feed resolver fails or finds nothing newer, we must + // fall back to the default /releases/latest/download/ feed so the check + // can still complete and report "not-available" (rather than error out). + it('falls back to /releases/latest/download when the atom resolver returns null', async () => { + appMock.getVersion.mockReturnValue('1.3.19-rc.6') + fetchNewerReleaseTagMock.mockResolvedValue(null) + autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined) + + const { setupAutoUpdater, checkForUpdatesFromMenu } = await import('./updater') + + const mainWindow = { webContents: { send: vi.fn() } } + setupAutoUpdater(mainWindow as never, { getLastUpdateCheckAt: () => Date.now() }) + + checkForUpdatesFromMenu() + + await vi.waitFor(() => { + expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1) + }) + expect(autoUpdaterMock.setFeedURL).toHaveBeenLastCalledWith({ + provider: 'generic', + url: 'https://github.com/stablyai/orca/releases/latest/download' + }) + }) + + it('does not invoke the atom-feed resolver for a stable user', async () => { appMock.getVersion.mockReturnValue('1.3.17') autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined) - const { setupAutoUpdater } = await import('./updater') + const { setupAutoUpdater, checkForUpdatesFromMenu } = await import('./updater') const mainWindow = { webContents: { send: vi.fn() } } setupAutoUpdater(mainWindow as never, { getLastUpdateCheckAt: () => Date.now() }) - expect(autoUpdaterMock.allowPrerelease).not.toBe(true) + checkForUpdatesFromMenu() + + await vi.waitFor(() => { + expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1) + }) + expect(fetchNewerReleaseTagMock).not.toHaveBeenCalled() expect(autoUpdaterMock.setFeedURL).toHaveBeenCalledWith({ provider: 'generic', url: 'https://github.com/stablyai/orca/releases/latest/download' }) }) + + // Why: once the user Shift-clicks to opt into RC channel, we switch to the + // native github provider. The atom-feed resolver must NOT run after that, + // or it would clobber the provider switch with a generic feed URL. + it('does not run the atom resolver after a Shift-click RC opt-in', async () => { + appMock.getVersion.mockReturnValue('1.3.17') + autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined) + + const { setupAutoUpdater, checkForUpdatesFromMenu } = await import('./updater') + + const mainWindow = { webContents: { send: vi.fn() } } + setupAutoUpdater(mainWindow as never, { getLastUpdateCheckAt: () => Date.now() }) + + checkForUpdatesFromMenu({ includePrerelease: true }) + + await vi.waitFor(() => { + expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1) + }) + expect(fetchNewerReleaseTagMock).not.toHaveBeenCalled() + expect(autoUpdaterMock.allowPrerelease).toBe(true) + expect(autoUpdaterMock.setFeedURL).toHaveBeenLastCalledWith({ + provider: 'github', + owner: 'stablyai', + repo: 'orca' + }) + }) }) diff --git a/src/main/updater.ts b/src/main/updater.ts index 21551e6c4..a2d1cdce1 100644 --- a/src/main/updater.ts +++ b/src/main/updater.ts @@ -17,6 +17,7 @@ import { isPrereleaseVersion, statusesEqual } from './updater-fallback' +import { fetchNewerReleaseTag, getReleaseDownloadUrl } from './updater-prerelease-feed' import { fetchNudge, shouldApplyNudge } from './updater-nudge' const AUTO_UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000 @@ -262,6 +263,41 @@ function recordCompletedUpdateCheck(): void { persistLastUpdateCheckAt?.(Date.now()) } +function shouldResolvePrereleaseFeed(): boolean { + // Why: if the user Shift-clicked the menu to opt into RC this process, we've + // already switched to the native github provider — leave that alone. The + // atom-feed resolver only applies to users *running* a prerelease build on + // the default generic feed. + return !includePrereleaseActive && isPrereleaseVersion(app.getVersion()) +} + +async function pinPrereleaseFeed(): Promise { + // Why: for prerelease users we mine the atom feed ourselves and pin the + // generic feed at /releases/download// so the follow-up manifest fetch + // resolves against exactly that release. This handles BOTH RC→newer-RC and + // RC→stable, which is what a prerelease user wants. We avoid the native + // github provider because GitHubProvider.getLatestVersion() filters the feed + // by channel — when currentChannel is "rc", stable releases get skipped and + // the user never sees the GA (trapping them on the RC channel). + // + // If the resolver returns null (no newer release, or fetch failed), we fall + // back to the default /releases/latest/download/ URL. In the "no newer" + // case that feed will report the latest stable and compareVersions in the + // 'update-available' handler will correctly mark it as not-available. + const newerTag = await fetchNewerReleaseTag(app.getVersion()) + if (newerTag) { + autoUpdater.setFeedURL({ + provider: 'generic', + url: getReleaseDownloadUrl(newerTag) + }) + } else { + autoUpdater.setFeedURL({ + provider: 'generic', + url: 'https://github.com/stablyai/orca/releases/latest/download' + }) + } +} + function runBackgroundUpdateCheck( nudgeId: string | null = getPersistedPendingUpdateNudgeId() ): void { @@ -285,7 +321,9 @@ function runBackgroundUpdateCheck( backgroundCheckLaunchPending = true // Don't send 'checking' here — the 'checking-for-update' event handler does it, // and sending it from both places causes duplicate notifications (issue #35). - autoUpdater.checkForUpdates().catch((err) => { + const launch = (): Promise => autoUpdater.checkForUpdates() + const run = shouldResolvePrereleaseFeed() ? pinPrereleaseFeed().then(launch) : launch() + void Promise.resolve(run).catch((err) => { backgroundCheckLaunchPending = false void sendCheckFailureStatus(String(err?.message ?? err)) }) @@ -333,7 +371,9 @@ export function checkForUpdatesFromMenu(options?: { includePrerelease?: boolean // Don't send 'checking' here — the 'checking-for-update' event handler does it, // and sending it from both places causes duplicate notifications (issue #35). - autoUpdater.checkForUpdates().catch((err) => { + const launch = (): Promise => autoUpdater.checkForUpdates() + const run = shouldResolvePrereleaseFeed() ? pinPrereleaseFeed().then(launch) : launch() + void Promise.resolve(run).catch((err) => { userInitiatedCheck = false void sendCheckFailureStatus(String(err?.message ?? err), true) }) @@ -481,24 +521,23 @@ export function setupAutoUpdater( ;(autoUpdater as NsisUpdater).verifyUpdateCodeSignature = () => Promise.resolve(null) } - // Why: a user already running a prerelease (e.g. 1.3.17-rc.1) must stay on - // the RC channel so "Check for Updates" can find the next RC (1.3.17-rc.2). - // The generic /releases/latest/download/ feed only advertises non-prerelease - // releases, so without this they'd never see the follow-up RC. Users on a - // stable release keep the generic feed and must Shift-click to opt in. - if (isPrereleaseVersion(app.getVersion())) { - enableIncludePrerelease() - } else { - // Use the generic provider with GitHub's /releases/latest/download/ URL so - // electron-updater always fetches the manifest (latest-mac.yml, latest.yml, - // latest-linux.yml) from the latest non-prerelease release. This sidesteps - // the broken /releases/latest API endpoint (returns 406) and automatically - // excludes RC/prerelease versions without client-side filtering. - autoUpdater.setFeedURL({ - provider: 'generic', - url: 'https://github.com/stablyai/orca/releases/latest/download' - }) - } + // Use the generic provider with GitHub's /releases/latest/download/ URL so + // electron-updater always fetches the manifest (latest-mac.yml, latest.yml, + // latest-linux.yml) from the latest non-prerelease release. This sidesteps + // the broken /releases/latest API endpoint (returns 406) and automatically + // excludes RC/prerelease versions without client-side filtering. + // + // Why: for users already running a prerelease (e.g. 1.3.19-rc.6) we repin + // this URL to a specific /releases/download// before each check — see + // ensurePrereleaseFeedReady. That handles both RC→newer-RC AND RC→stable. + // We keep the generic provider (rather than switching to electron-updater's + // native github provider + allowPrerelease) because GitHubProvider filters + // the atom feed by channel and would silently skip stable releases when the + // running build is an RC — trapping the user on the RC channel. + autoUpdater.setFeedURL({ + provider: 'generic', + url: 'https://github.com/stablyai/orca/releases/latest/download' + }) if (autoUpdaterInitialized) { return