Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): get the latest version when the user asks to update (PRD-6993) (#3799)

Andrew Mikofalvy70a8e0c7a4f6
diff --git a/.changeset/update-freshness-at-intent.md b/.changeset/update-freshness-at-intent.md
new file mode 100644
index 000000000..e0959827b
--- /dev/null
+++ b/.changeset/update-freshness-at-intent.md
@@ -0,0 +1,9 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Updating no longer immediately asks you to update again. Releases often land less than an hour apart, so the build waiting behind the "ready to install" banner was frequently already superseded by the time you clicked it — and the check that runs as the app comes back up would spot the newer one and put the banner straight back, replacing the "Updated to Version X" confirmation you had just earned.
+
+Clicking Relaunch now re-checks first. If a newer build has appeared since the banner was raised, the app fetches that one and installs it instead, showing "Getting the latest version…" while it does — so finishing an update leaves you on the newest build available at the moment you asked for it. For the minutes right after an update, a build that arrives is downloaded and staged silently rather than announced; it still installs the next time you quit.
+
+This also fixes a class of failed installs. The app could previously call into the installer while a newer build was still being written into place, which surfaced as an update that failed and then worked on retry. Two things close that: a relaunch now waits for any download in progress instead of racing it, and a build that is already staged is no longer needlessly re-staged on every hourly check.
diff --git a/packages/app/src/components/UpdateNotices.shared.ts b/packages/app/src/components/UpdateNotices.shared.ts
index 7f254d004..b5f2ac079 100644
--- a/packages/app/src/components/UpdateNotices.shared.ts
+++ b/packages/app/src/components/UpdateNotices.shared.ts
@@ -28,6 +28,18 @@ export const TOAST_E_ACTION_RESET = 'Reset to defaults';
*/
export const TOAST_A_PROGRESS_BODY = 'Relaunching to install the update…';
+/**
+ * In-progress body shown while a "Relaunch" click re-checks the feed, and for
+ * as long as a newer build found by that check is downloading.
+ *
+ * Separate from `TOAST_A_PROGRESS_BODY` because the two waits differ by orders
+ * of magnitude: the relaunch teardown is seconds, whereas fetching a newer
+ * build can take minutes on a slow connection, and "Relaunching…" held for
+ * minutes reads as a hang. This wording also tells the user why the extra wait
+ * is happening, which is the point of doing it at all.
+ */
+export const TOAST_A_FETCHING_LATEST_BODY = 'Getting the latest version…';
+
/**
* Fallback notice shown when `bridge.update.relaunchNow()` IPC rejects —
* wrong packaging, missing staging dir, Squirrel.Mac throwing. Without
@@ -353,6 +365,25 @@ export function attachUpdateSubscribers(
}),
);
+ unsubscribers.push(
+ bridge.onUpdateFetchingLatest(() => {
+ // A "Relaunch" click is checking whether the staged build is still the
+ // newest one, and will fetch a newer one if it is not. Same shared id and
+ // button-less, non-dismissible shape as the relaunching card, so the
+ // three in-progress states replace each other in place rather than
+ // stacking: fetching, then relaunching, then (on failure) the re-armed
+ // banner. The payload version is unused for the same reason it is unused
+ // there — the body is static, and which version ends up installed is
+ // decided in main after this card is already showing.
+ addNotice({
+ id: downloadedNoticeId,
+ body: TOAST_A_FETCHING_LATEST_BODY,
+ priority: PRIORITY_UPDATE_DOWNLOADED,
+ dismissible: false,
+ });
+ }),
+ );
+
unsubscribers.push(
bridge.onUpdateRelaunchFailed(({ version, message, downloadUrl }) => {
// Boot-detected failed install (a clean quit whose post-quit install
diff --git a/packages/app/src/components/UpdateNotices.test.ts b/packages/app/src/components/UpdateNotices.test.ts
index 5d0913a7f..dae9146bd 100644
--- a/packages/app/src/components/UpdateNotices.test.ts
+++ b/packages/app/src/components/UpdateNotices.test.ts
@@ -24,6 +24,7 @@ import {
pickActiveNotice,
TOAST_A_ACTION,
TOAST_A_ERROR_BODY,
+ TOAST_A_FETCHING_LATEST_BODY,
TOAST_A_PROGRESS_BODY,
TOAST_B_ACTION,
TOAST_C_ACTION,
@@ -39,6 +40,7 @@ import {
type UpdateDownloadedCb = (info: { version: string }) => void;
type RelaunchingCb = (info: { version: string }) => void;
+type FetchingLatestCb = (info: { version: string }) => void;
type RelaunchFailedCb = (info: { version: string; message?: string; downloadUrl?: string }) => void;
type WhatsNewCb = (info: { version: string; releaseUrl: string }) => void;
type WhatsNewDismissedCb = (info: { version: string }) => void;
@@ -47,6 +49,7 @@ type StuckHintCb = (info: { downloadUrl: string }) => void;
interface FakeBridge {
onUpdateDownloaded: ReturnType<typeof vi.fn>;
onUpdateRelaunching: ReturnType<typeof vi.fn>;
+ onUpdateFetchingLatest: ReturnType<typeof vi.fn>;
onUpdateRelaunchFailed: ReturnType<typeof vi.fn>;
onWhatsNew: ReturnType<typeof vi.fn>;
onWhatsNewDismissed: ReturnType<typeof vi.fn>;
@@ -63,12 +66,14 @@ interface FakeBridge {
/** Test-side handles — set by the `on*` mocks so tests can drive dispatches. */
_downloaded?: UpdateDownloadedCb;
_relaunching?: RelaunchingCb;
+ _fetchingLatest?: FetchingLatestCb;
_relaunchFailed?: RelaunchFailedCb;
_whatsNew?: WhatsNewCb;
_whatsNewDismissed?: WhatsNewDismissedCb;
_stuckHint?: StuckHintCb;
_downloadedUnsub: ReturnType<typeof vi.fn>;
_relaunchingUnsub: ReturnType<typeof vi.fn>;
+ _fetchingLatestUnsub: ReturnType<typeof vi.fn>;
_relaunchFailedUnsub: ReturnType<typeof vi.fn>;
_whatsNewUnsub: ReturnType<typeof vi.fn>;
_whatsNewDismissedUnsub: ReturnType<typeof vi.fn>;
@@ -79,12 +84,14 @@ function makeFakeBridge(): FakeBridge {
const b: FakeBridge = {
_downloadedUnsub: vi.fn(() => {}),
_relaunchingUnsub: vi.fn(() => {}),
+ _fetchingLatestUnsub: vi.fn(() => {}),
_relaunchFailedUnsub: vi.fn(() => {}),
_whatsNewUnsub: vi.fn(() => {}),
_whatsNewDismissedUnsub: vi.fn(() => {}),
_stuckHintUnsub: vi.fn(() => {}),
onUpdateDownloaded: vi.fn(() => {}),
onUpdateRelaunching: vi.fn(() => {}),
+ onUpdateFetchingLatest: vi.fn(() => {}),
onUpdateRelaunchFailed: vi.fn(() => {}),
onWhatsNew: vi.fn(() => {}),
onWhatsNewDismissed: vi.fn(() => {}),
@@ -107,6 +114,10 @@ function makeFakeBridge(): FakeBridge {
b._relaunching = cb;
return b._relaunchingUnsub;
});
+ b.onUpdateFetchingLatest = vi.fn((cb: FetchingLatestCb) => {
+ b._fetchingLatest = cb;
+ return b._fetchingLatestUnsub;
+ });
b.onUpdateRelaunchFailed = vi.fn((cb: RelaunchFailedCb) => {
b._relaunchFailed = cb;
return b._relaunchFailedUnsub;
@@ -254,6 +265,47 @@ describe('Notice A cross-window relaunch — ok:update:relaunching', () => {
expect(inProgress.dismissible).toBe(false);
});
+ test('onUpdateFetchingLatest → the fetching card, same id and shape as relaunching', () => {
+ // The click is checking whether the staged build is still the newest one.
+ // Same stable id as the relaunching card so the in-progress states replace
+ // each other in place rather than stacking, and equally button-less: the
+ // relaunch is already committed, so there is nothing to click and nothing
+ // to dismiss.
+ const bridge = makeFakeBridge();
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
+ attachUpdateSubscribers(castBridge(bridge), addNotice);
+
+ bridge._fetchingLatest?.({ version: '0.1.1' });
+ expect(addNotice).toHaveBeenCalledTimes(1);
+ const fetching = addNotice.mock.calls[0]?.[0] as UpdateNotice;
+ expect(fetching.id).toBe('update-downloaded');
+ expect(fetching.body).toBe(TOAST_A_FETCHING_LATEST_BODY);
+ expect(fetching.action).toBeUndefined();
+ expect(fetching.priority).toBe(2);
+ expect(fetching.dismissible).toBe(false);
+ });
+
+ test('the fetching card is worded apart from the relaunching one', () => {
+ // The two waits differ by orders of magnitude — teardown is seconds,
+ // fetching a newer build can be minutes — so they must not share copy.
+ expect(TOAST_A_FETCHING_LATEST_BODY).toBe('Getting the latest version…');
+ expect(TOAST_A_FETCHING_LATEST_BODY).not.toBe(TOAST_A_PROGRESS_BODY);
+ });
+
+ test('the fetching card gives way to the relaunching card in place', () => {
+ const bridge = makeFakeBridge();
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
+ attachUpdateSubscribers(castBridge(bridge), addNotice);
+
+ bridge._fetchingLatest?.({ version: '0.1.1' });
+ bridge._relaunching?.({ version: '0.1.1' });
+
+ const [first, second] = addNotice.mock.calls.map((c) => c[0] as UpdateNotice);
+ expect(first?.id).toBe(second?.id);
+ expect(first?.body).toBe(TOAST_A_FETCHING_LATEST_BODY);
+ expect(second?.body).toBe(TOAST_A_PROGRESS_BODY);
+ });
+
test('does NOT invoke relaunchNow — it is the echo, not the trigger (no loop)', () => {
const bridge = makeFakeBridge();
const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
diff --git a/packages/app/src/components/UpdateNotices.tsx b/packages/app/src/components/UpdateNotices.tsx
index 5468908e1..bb01461d5 100644
--- a/packages/app/src/components/UpdateNotices.tsx
+++ b/packages/app/src/components/UpdateNotices.tsx
@@ -38,6 +38,7 @@ export {
installFailedBody,
TOAST_A_ACTION,
TOAST_A_ERROR_BODY,
+ TOAST_A_FETCHING_LATEST_BODY,
TOAST_A_PROGRESS_BODY,
TOAST_B_ACTION,
TOAST_C_ACTION,
diff --git a/packages/app/src/lib/update-notices-store.test.ts b/packages/app/src/lib/update-notices-store.test.ts
index a6149e5bd..f5574f152 100644
--- a/packages/app/src/lib/update-notices-store.test.ts
+++ b/packages/app/src/lib/update-notices-store.test.ts
@@ -27,6 +27,7 @@ describe('update-notices-store install-time runtime wiring', () => {
);
const downloadedUnsub = vi.fn(() => {});
const relaunchingUnsub = vi.fn(() => {});
+ const fetchingLatestUnsub = vi.fn(() => {});
const relaunchFailedUnsub = vi.fn(() => {});
const whatsNewUnsub = vi.fn(() => {});
const whatsNewDismissedUnsub = vi.fn(() => {});
@@ -34,6 +35,7 @@ describe('update-notices-store install-time runtime wiring', () => {
const bridge = {
onUpdateDownloaded: vi.fn(() => downloadedUnsub),
onUpdateRelaunching: vi.fn(() => relaunchingUnsub),
+ onUpdateFetchingLatest: vi.fn(() => fetchingLatestUnsub),
onUpdateRelaunchFailed: vi.fn(() => relaunchFailedUnsub),
onWhatsNew: vi.fn(() => whatsNewUnsub),
onWhatsNewDismissed: vi.fn(() => whatsNewDismissedUnsub),
@@ -62,6 +64,7 @@ describe('update-notices-store install-time runtime wiring', () => {
expect(bridge.onUpdateDownloaded).toHaveBeenCalledWith(expect.any(Function));
expect(bridge.onUpdateRelaunching).toHaveBeenCalledWith(expect.any(Function));
+ expect(bridge.onUpdateFetchingLatest).toHaveBeenCalledWith(expect.any(Function));
expect(bridge.onUpdateRelaunchFailed).toHaveBeenCalledWith(expect.any(Function));
expect(bridge.onWhatsNew).toHaveBeenCalledWith(expect.any(Function));
expect(bridge.onWhatsNewDismissed).toHaveBeenCalledWith(expect.any(Function));
diff --git a/packages/app/tests/stress/file-tree-create.e2e.ts b/packages/app/tests/stress/file-tree-create.e2e.ts
index dbb678189..fee95c77d 100644
--- a/packages/app/tests/stress/file-tree-create.e2e.ts
+++ b/packages/app/tests/stress/file-tree-create.e2e.ts
@@ -222,6 +222,7 @@ async function installDelayedDesktopSessionBridge(
onMenuAction: () => unsubscribe,
onUpdateDownloaded: () => unsubscribe,
onUpdateRelaunching: () => unsubscribe,
+ onUpdateFetchingLatest: () => unsubscribe,
onUpdateRelaunchFailed: () => unsubscribe,
onWhatsNew: () => unsubscribe,
onWhatsNewDismissed: () => unsubscribe,
diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.ts
index 9c23c9e0f..a54a411d4 100644
--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts
+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts
@@ -363,6 +363,7 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
onMenuAction: () => () => {},
onUpdateDownloaded: () => () => {},
onUpdateRelaunching: () => () => {},
+ onUpdateFetchingLatest: () => () => {},
onUpdateRelaunchFailed: () => () => {},
onWhatsNew: () => () => {},
onWhatsNewDismissed: () => () => {},
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index 6e98a33dc..42465ba1c 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -363,6 +363,17 @@ export interface OkUpdateRelaunchingInfo {
readonly version: string;
}
+/**
+ * Payload delivered to `onUpdateFetchingLatest` subscribers. Fires when a
+ * "Relaunch" click is re-checking the feed before installing, and stays the
+ * active state while a newer build found by that check downloads. `version` is
+ * the build that was staged when the click landed — the one the user saw — and
+ * a newer one may replace it before the install completes.
+ */
+export interface OkUpdateFetchingLatestInfo {
+ readonly version: string;
+}
+
/**
* Payload delivered to `onUpdateRelaunchFailed` subscribers. Fires when a
* committed relaunch fails after the fact — the updater's `error` event
@@ -1313,6 +1324,14 @@ export interface OkDesktopBridge {
* Returns unsubscribe.
*/
onUpdateRelaunching(cb: (info: OkUpdateRelaunchingInfo) => void): OkUnsubscribe;
+ /**
+ * Subscribe to `ok:update:fetching-latest` — a "Relaunch" click is checking
+ * for a newer build before installing, and may then be downloading one. Swap
+ * this window's card to the button-less "Getting the latest version…" state.
+ * Distinct from `onUpdateRelaunching` because this wait can span a full
+ * update download rather than a few seconds of teardown. Returns unsubscribe.
+ */
+ onUpdateFetchingLatest(cb: (info: OkUpdateFetchingLatestInfo) => void): OkUnsubscribe;
/**
* Subscribe to `ok:update:relaunch-failed` — a committed relaunch failed
* (async updater error, no-quit watchdog, or sync throw). Surface the
diff --git a/packages/desktop/src/main/auto-updater.ts b/packages/desktop/src/main/auto-updater.ts
index 1efa90039..af35635b9 100644
--- a/packages/desktop/src/main/auto-updater.ts
+++ b/packages/desktop/src/main/auto-updater.ts
@@ -151,7 +151,15 @@ export type DispatchKind =
| 'cross-channel-blocked'
| 'staged-cache-reclaimed'
| 'linux-manual-fallback-no-auth'
- | 'linux-manual-fallback-after-error';
+ | 'linux-manual-fallback-after-error'
+ | 'download-skipped-already-staged'
+ | 'relaunch-refresh-found-newer'
+ | 'relaunch-refresh-up-to-date'
+ | 'relaunch-refresh-timed-out'
+ | 'relaunch-awaited-in-flight-staging'
+ | 'relaunch-double-invoke-blocked'
+ | 'toast-a-deferred-post-update-quiet'
+ | 'toast-a-quiet-window-elapsed';
interface StartAutoUpdaterOpts {
updater: UpdaterLike;
@@ -354,6 +362,16 @@ export interface StartAutoUpdaterHandle {
* so a project opened shortly after an update still shows the card.
*/
getActiveWhatsNew(): { version: string; releaseUrl: string } | null;
+ /**
+ * True while the post-update quiet window is running, i.e. the user reached
+ * this build recently enough that a fresh "ready to install" banner would
+ * land on top of their update rather than after it.
+ *
+ * `main/index.ts` consults this before re-sending a pending banner to a
+ * newly-opened window: without it, opening a project during the window would
+ * surface the very notice the updater is holding back.
+ */
+ isWithinPostUpdateQuietWindow(): boolean;
/**
* Uninstall path: prevent a staged update from auto-installing on the quit
* that hands control to the detached uninstall helper. Otherwise Squirrel.Mac
@@ -514,6 +532,60 @@ const INSTALL_DEFER_MAX_BOOTS = 3;
*/
export const STUCK_HINT_DOWNLOAD_URL = 'https://github.com/inkeep/open-knowledge/releases';
+/**
+ * How long the click-gated freshness check waits for the manifest poll to
+ * resolve before giving up and installing what is already staged.
+ *
+ * The user has already clicked "Relaunch" and the window is showing an
+ * in-progress card, so this is dead time they are watching. A manifest poll is
+ * a single small GET (CDN-cached at the update proxy), so a few seconds covers
+ * a healthy round trip with slack; past that, a stale-but-working install
+ * beats an app that appears hung. Timing out is not an error — it falls
+ * through to the existing staged version.
+ */
+export const RELAUNCH_REFRESH_CHECK_MS = 4_000;
+
+/**
+ * How long the click-gated refresh waits for a newer build to finish
+ * downloading and staging before falling back.
+ *
+ * Two distinct jobs, which is why it is minutes rather than seconds. It bounds
+ * the wait for a download the refresh itself started, AND the wait for a
+ * download that was already in flight when the click landed. The second is the
+ * safety-critical one: `quitAndInstall()` during a re-stage hands Squirrel a
+ * half-written staging directory, so waiting here is what keeps the install
+ * from failing.
+ *
+ * Sized for a full update zip on a slow connection. On expiry the click falls
+ * through and installs whatever was already staged, which stays safe for the
+ * whole download: electron-updater writes to a temp file and only hands the
+ * result to Squirrel once the download completes, so an unfinished re-download
+ * has not disturbed the previous bundle or the proxy server still serving it.
+ * The dangerous window is the handoff itself, and that is covered by treating
+ * download and stage as one in-flight unit.
+ */
+export const RELAUNCH_REFRESH_DOWNLOAD_MS = 120_000;
+
+/**
+ * How long after arriving on a new version the "ready to install" banner stays
+ * suppressed.
+ *
+ * At the release cadence this app ships, the newest build is often superseded
+ * inside a single check interval, so the boot check that runs on an update
+ * relaunch routinely finds another version and re-arms the banner within
+ * seconds of the user finishing an update. Worse, that banner outranks the
+ * "Updated to Version X" confirmation in the notice priority order, so the
+ * acknowledgement is not merely followed by another demand, it is replaced by
+ * one.
+ *
+ * Suppression costs nothing: the update still downloads, still stages, and
+ * still installs at the next natural quit via `autoInstallOnAppQuit`. Only the
+ * interruption is deferred, and only until the user has had a stretch of
+ * uninterrupted use. If the app is still running when the window elapses, the
+ * banner appears then.
+ */
+export const POST_UPDATE_QUIET_MS = 10 * 60 * 1000;
+
/**
* How long the release-notes (what's-new) notice stays "live" for late-opened
* windows: main re-sends it to a window opened within this window of the notice
@@ -1015,6 +1087,64 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
watchdog: ReturnType<typeof setTimeout>;
} | null = null;
+ // Armed just before `downloadUpdate()` and cleared by whichever of
+ // `update-downloaded` / `error` lands. Non-null means Squirrel may be
+ // mid-swap of the staging directory, which is the one state in which
+ // `quitAndInstall()` must not be called: electron-updater's MacUpdater sets
+ // its internal `squirrelDownloadedUpdate` flag on the FIRST successful stage
+ // and never clears it, so a re-download re-points Squirrel at a fresh proxy
+ // server while that flag still reads true. `quitAndInstall()` then takes the
+ // "already staged, install now" branch and fires at a half-written bundle,
+ // which surfaces to the user as an install that failed and worked on retry.
+ // We cannot fix the upstream flag, so we refuse to call into it while a
+ // stage is running.
+ let stagingInFlight: { version: string } | null = null;
+
+ /** Accessor form, so a read after an `await` is not stale-narrowed. */
+ const currentStaging = (): { version: string } | null => stagingInFlight;
+
+ // One-shot resolvers for the click-gated freshness check. Registered before
+ // the triggering call so an event that lands synchronously is never missed,
+ // and drained (not filtered) on every settle so a timed-out waiter cannot
+ // leak into the next click.
+ let checkOutcomeWaiters: Array<(outcome: 'available' | 'settled') => void> = [];
+ let stagingWaiters: Array<(ok: boolean) => void> = [];
+
+ const settleCheckWaiters = (outcome: 'available' | 'settled'): void => {
+ const waiters = checkOutcomeWaiters;
+ checkOutcomeWaiters = [];
+ for (const resolve of waiters) resolve(outcome);
+ };
+
+ const settleStagingWaiters = (ok: boolean): void => {
+ const waiters = stagingWaiters;
+ stagingWaiters = [];
+ for (const resolve of waiters) resolve(ok);
+ };
+
+ // Wall-clock instant after which the "ready to install" banner may surface
+ // again. Set at boot when the running version differs from the last one seen,
+ // so it covers every route onto a new build (an update relaunch, an
+ // install-on-quit, a hand-replaced bundle) rather than only the click path.
+ // Null means no suppression is active.
+ let postUpdateQuietUntil: number | null = null;
+
+ // Pending deferred Toast A broadcast, held while the quiet window runs.
+ // Cleared by `destroy()` so a teardown mid-window cannot fire into
+ // destroyed windows.
+ let quietWindowTimer: ReturnType<typeof setTimeout> | null = null;
+
+ const withinPostUpdateQuietWindow = (): boolean =>
+ postUpdateQuietUntil !== null && now().getTime() < postUpdateQuietUntil;
+
+ // Set synchronously on the first accepted "Relaunch" click, cleared only by
+ // `failRelaunch` (or the lost-staged-build path). The pre-existing
+ // double-invoke guard relied on `versionPendingInstall` being cleared
+ // synchronously before `quitAndInstall()`; the freshness check now awaits in
+ // front of that persist, so a second click during the await would otherwise
+ // pass the state gate and fire a non-idempotent Squirrel call twice.
+ let installRequested = false;
+
// Absolute path of the staged installer. Captured in-session from
// electron-updater's `update-downloaded` payload (`downloadedFile`) and
// persisted alongside `versionPendingInstall`, then re-seeded from state at
@@ -1101,6 +1231,10 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
clock.clearTimeout(relaunchInFlight.watchdog);
relaunchInFlight = null;
}
+ // The install is no longer committed, so a fresh click must be accepted —
+ // the re-armed banner below is the user's retry affordance and would be
+ // inert without this.
+ installRequested = false;
if (
persistSafely({ ...readState(), versionPendingInstall: version }, 'relaunch-failed-restore')
) {
@@ -1213,10 +1347,30 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
// 7-day stuck-hint gate doesn't fire on a healthy updater serving a
// long stable-only window to a beta cohort (or vice versa).
markCheckSucceeded();
+ settleCheckWaiters('settled');
onDispatch?.('cross-channel-blocked');
return;
}
markCheckSucceeded();
+ // Already staged, and staged bundles are not re-fetched. electron-updater
+ // emits `update-available` on every check for as long as the remote build
+ // is newer than the RUNNING one, so a pending update re-offers itself on
+ // each poll. Re-downloading it is not a no-op even when the file is
+ // already in the cache: the cached path still runs the post-download
+ // handoff, which tears down the Squirrel proxy server and re-stages the
+ // identical bytes. Every one of those re-stages is a window in which a
+ // "Relaunch" click hits a half-written staging directory (see
+ // `stagingInFlight`), so an hourly re-stage of a build we already hold is
+ // pure downside. A version CHANGE still re-downloads, and a download that
+ // failed left `versionPendingInstall` unset, so retries are unaffected.
+ if (offeredVersion && readState().versionPendingInstall === offeredVersion) {
+ logger.debug('update-available for the already-staged version — skipping re-download', {
+ version: offeredVersion,
+ });
+ settleCheckWaiters('settled');
+ onDispatch?.('download-skipped-already-staged');
+ return;
+ }
// Tag the artifact fetch with the version being installed. The Windows and
// Linux installers carry version-less names and stable resolves them
// through GitHub's `latest` alias, so the proxy has nothing to parse and
@@ -1240,6 +1394,10 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
// mid-flight) would only show up in this log line. Match
// `runMenuDrivenCheck`'s classified/unclassified discipline so
// classified codes land at `warn` with code + stack + timestamp.
+ // Arm BEFORE the call: `downloadUpdate()` can reject synchronously, and a
+ // gate armed after the fact would leave a rejection with nothing to clear.
+ stagingInFlight = { version: offeredVersion ?? 'unknown' };
+ settleCheckWaiters('available');
void updater.downloadUpdate().catch((err: unknown) => {
const code = err instanceof Error ? (err as Error & { code?: unknown }).code : undefined;
const logFn = isClassifiedUpdaterError(err) ? logger.warn : logger.debug;
@@ -1248,6 +1406,13 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
err,
timestamp: now().toISOString(),
});
+ // Rejections also reach `onError`, which clears the gate — but a
+ // provider-construction failure rejects without ever engaging the event
+ // bus, and a gate left armed there would block every later relaunch.
+ if (stagingInFlight) {
+ stagingInFlight = null;
+ settleStagingWaiters(false);
+ }
});
};
@@ -1275,6 +1440,7 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
const onUpdateNotAvailable = (info: { version?: string }): void => {
logger.info('update-not-available', { version: info.version });
markCheckSucceeded();
+ settleCheckWaiters('settled');
if (menuCheckPending) {
menuCheckPending = false;
showCheckNowResult?.({
@@ -1295,6 +1461,12 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
const onUpdateDownloaded = (info: { version?: string; downloadedFile?: string }): void => {
logger.info('update-downloaded', { version: info.version });
+ // Release the relaunch gate first, ahead of every early return below: the
+ // stage is finished whether or not this event goes on to dispatch a
+ // banner, and a gate left armed on a deduped or empty-version event would
+ // block relaunches for the rest of the session.
+ stagingInFlight = null;
+ settleStagingWaiters(true);
// Track the staged file even when the dispatch below dedupes or skips —
// the file exists on disk regardless, and the Linux fallback needs it.
if (typeof info.downloadedFile === 'string' && info.downloadedFile !== '') {
@@ -1402,6 +1574,36 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
logger.info('update-downloaded dispatched Toast A (all windows)', { version });
onDispatch?.('update-downloaded-toast-a');
};
+ // Hold the banner while the post-update quiet window runs. The state gate
+ // above is already armed, so the update is fully staged and still installs
+ // at the next quit — the only thing deferred is the interruption. Deferring
+ // rather than dropping matters because the dedupe gate above would never
+ // let this version dispatch again: a dropped banner would be gone for the
+ // rest of the session, and a user who keeps the app open past the window
+ // would never learn the update was waiting.
+ if (withinPostUpdateQuietWindow()) {
+ const remainingMs = (postUpdateQuietUntil ?? 0) - now().getTime();
+ logger.info('update-downloaded within post-update quiet window — deferring Toast A', {
+ version,
+ remainingMs,
+ });
+ onDispatch?.('toast-a-deferred-post-update-quiet');
+ if (quietWindowTimer) clock.clearTimeout(quietWindowTimer);
+ quietWindowTimer = clock.setTimeout(
+ () => {
+ quietWindowTimer = null;
+ // The window has elapsed, so a late-opened window may surface the
+ // banner too — clearing here keeps `withinPostUpdateQuietWindow` and
+ // the deferred fire from disagreeing.
+ postUpdateQuietUntil = null;
+ onDispatch?.('toast-a-quiet-window-elapsed');
+ if (whenRendererReady) whenRendererReady(fireToastA);
+ else fireToastA();
+ },
+ Math.max(0, remainingMs),
+ );
+ return;
+ }
if (whenRendererReady) whenRendererReady(fireToastA);
else fireToastA();
};
@@ -1421,6 +1623,15 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
});
onDispatch?.('error-unclassified');
}
+ // Any updater error ends whatever check or stage was running. Release both
+ // gates before the routing below, which can quit the app: a waiter left
+ // unresolved would hold a "Relaunch" click until its timeout for no reason,
+ // and a `stagingInFlight` left armed would block every later one.
+ settleCheckWaiters('settled');
+ if (stagingInFlight) {
+ stagingInFlight = null;
+ settleStagingWaiters(false);
+ }
// electron-updater surfaces feed/manifest failures primarily through this
// event, not as a checkForUpdates() rejection. If the proxy feed is the
// active source, treat any updater error as the proxy failing and revert to
@@ -1501,6 +1712,125 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
updater.on('update-downloaded', onUpdateDownloaded);
updater.on('error', onError);
+ // ————————————————————————————————————————————————————————
+ // Click-gated freshness check
+ // ————————————————————————————————————————————————————————
+
+ /**
+ * Resolve on the first of any number of signals, with a timeout backstop.
+ *
+ * `register` receives a `finish` callback it may wire to as many sources as
+ * it likes; the first call wins and every later one is ignored. Deliberately
+ * not a `Promise.race` over separately-timed promises: the timer lives here
+ * and is cleared on whichever path settles, so a wait that ends early cannot
+ * strand a timer that later fires into a torn-down updater.
+ */
+ const firstOf = <T>(
+ register: (finish: (value: T) => void) => void,
+ timeoutMs: number,
+ onTimeout: T,
+ ): Promise<T> =>
+ new Promise<T>((resolve) => {
+ let settled = false;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ const finish = (value: T): void => {
+ if (settled) return;
+ settled = true;
+ if (timer !== null) clock.clearTimeout(timer);
+ resolve(value);
+ };
+ timer = clock.setTimeout(() => finish(onTimeout), timeoutMs);
+ register(finish);
+ });
+
+ /**
+ * Bring the staged build up to date before installing it, and never hand
+ * `quitAndInstall()` a staging directory that is still being written.
+ *
+ * Two things make this necessary at click time rather than on the periodic
+ * cadence. The release cadence outruns the check interval, so the staged
+ * build is routinely superseded before the user acts on it — the click is
+ * the first moment we know an install is actually wanted, and the last
+ * moment we can still change which version it lands on. And a stage that is
+ * in flight when the click arrives is exactly the state that breaks the
+ * install, so the wait is a correctness requirement, not just a freshness
+ * nicety.
+ *
+ * Deliberately gated on the click and not on hover: a hover precedes a click
+ * by a few hundred milliseconds, which is nowhere near enough to fetch an
+ * update, so hover could only ever discover staleness, never resolve it.
+ *
+ * Never throws. Every failure and timeout falls through to installing
+ * whatever is currently staged, because a stale install still beats a
+ * refusal to relaunch.
+ */
+ const refreshBeforeInstall = async (): Promise<void> => {
+ // A stage already running is the dangerous case, and it is also the case
+ // where a fresh check would tell us nothing new. Wait it out.
+ if (stagingInFlight) {
+ logger.info('relaunch-now waiting on in-flight staging before install', {
+ version: stagingInFlight.version,
+ });
+ onDispatch?.('relaunch-awaited-in-flight-staging');
+ await firstOf<boolean>(
+ (finish) => stagingWaiters.push(finish),
+ RELAUNCH_REFRESH_DOWNLOAD_MS,
+ false,
+ );
+ return;
+ }
+ const result = await firstOf<'available' | 'settled' | 'timeout'>(
+ (finish) => {
+ // Register the event waiter BEFORE the check so an `update-available`
+ // emitted synchronously from inside it still lands here.
+ checkOutcomeWaiters.push(finish);
+ // The check promise settling is a terminal signal in its own right,
+ // and wiring it alongside the event closes a hole: electron-updater
+ // emits its outcome event from inside the check and only then
+ // resolves, so a promise that resolves with no event means a path
+ // that reported nothing (a disabled updater short-circuits without
+ // emitting). Waiting on the event alone would stall such a click for
+ // the full timeout. The event still wins whenever it fires, because
+ // it fires first.
+ void updater.checkForUpdates().then(
+ () => finish('settled'),
+ (err: unknown) => {
+ // Rejections reach `onError`, which settles the waiter too.
+ logger.debug('relaunch-now refresh checkForUpdates rejected', { err });
+ finish('settled');
+ },
+ );
+ },
+ RELAUNCH_REFRESH_CHECK_MS,
+ 'timeout',
+ );
+ if (result === 'timeout') {
+ logger.info('relaunch-now refresh check timed out — installing the staged build');
+ onDispatch?.('relaunch-refresh-timed-out');
+ return;
+ }
+ // Read through the accessor: the early return above narrowed
+ // `stagingInFlight` to null for the rest of this body, and the handler
+ // that re-arms it ran during the await, which control-flow analysis does
+ // not model.
+ const staging = currentStaging();
+ if (result !== 'available' || !staging) {
+ // Either nothing newer exists, or the offer was vetoed or already
+ // staged. Both mean the staged build is the one to install.
+ onDispatch?.('relaunch-refresh-up-to-date');
+ return;
+ }
+ logger.info('relaunch-now found a newer build — fetching it before installing', {
+ version: staging.version,
+ });
+ onDispatch?.('relaunch-refresh-found-newer');
+ await firstOf<boolean>(
+ (finish) => stagingWaiters.push(finish),
+ RELAUNCH_REFRESH_DOWNLOAD_MS,
+ false,
+ );
+ };
+
// ————————————————————————————————————————————————————————
// IPC handler — Toast A's "Relaunch now"
// ————————————————————————————————————————————————————————
@@ -1518,9 +1848,39 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
// persist spread — Electron's main process is single-threaded so no
// TOCTOU risk exists, and the dedup is cleaner than two reads with
// identical results.
+ if (installRequested) {
+ logger.warn('relaunch-now invoked while an install is already committed — ignoring');
+ onDispatch?.('relaunch-double-invoke-blocked');
+ return undefined;
+ }
+ const preRefresh = readState();
+ if (!preRefresh.versionPendingInstall) {
+ logger.warn('relaunch-now invoked without versionPendingInstall — ignoring');
+ return undefined;
+ }
+ installRequested = true;
+ // Tell every window we are working before the await: the freshness check
+ // can take seconds, and a newer build found by it can take minutes more.
+ // Without this the clicked window sits on its local in-progress swap while
+ // the others keep showing a stale, clickable banner.
+ broadcastToAllWindows('ok:update:fetching-latest', {
+ version: preRefresh.versionPendingInstall,
+ });
+ await refreshBeforeInstall();
+ // Re-read: the refresh may have staged a newer version, which rewrites
+ // `versionPendingInstall`. Installing `preRefresh`'s value here would name
+ // the superseded build in the persist and in every log line downstream.
const snapshot = readState();
if (!snapshot.versionPendingInstall) {
- logger.warn('relaunch-now invoked without versionPendingInstall — ignoring');
+ // The refresh cleared the gate rather than advancing it, which means the
+ // staged build stopped being installable while we waited. Recover the
+ // windows instead of calling into Squirrel with nothing staged.
+ logger.warn('relaunch-now lost its staged build during the freshness check — ignoring');
+ installRequested = false;
+ broadcastToAllWindows('ok:update:relaunch-failed', {
+ version: preRefresh.versionPendingInstall,
+ message: 'the update stopped being available',
+ });
return undefined;
}
const pending = snapshot.versionPendingInstall;
@@ -1540,6 +1900,9 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
manualInstallPlanFor(usableStagedInstallerPath()) !== null &&
!linuxInstallSupport.hasGraphicalAuth()
) {
+ // Nothing was committed, and the banner is being re-armed right above —
+ // release the commit flag so that re-armed banner is clickable again.
+ installRequested = false;
broadcastToAllWindows('ok:update:downloaded', { version: pending });
offerManualInstallFallback(pending, 'linux-manual-fallback-no-auth');
return undefined;
@@ -1601,8 +1964,12 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
},
'relaunch-now',
)
- )
+ ) {
+ // The whole point of bailing here is that the user can click again once
+ // the disk is healthy, so the commit flag has to come back off with it.
+ installRequested = false;
return undefined;
+ }
// Tell EVERY window the relaunch is underway BEFORE the teardown await:
// each renderer swaps its "…ready to install [Relaunch]" banner to the
// button-less "Relaunching…" in-progress card. The clicked window already
@@ -2001,6 +2368,21 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
state.lastSeenVersion !== null && state.lastSeenVersion !== currentVersion;
const needsStateAdvance = state.lastSeenVersion !== currentVersion;
+ // Arriving on a new build starts the quiet window. Armed off the same
+ // condition as the what's-new notice so the two agree by construction:
+ // whenever we tell the user "Updated to Version X", we also stop asking them
+ // to update again for a while. A fresh install (`lastSeenVersion === null`)
+ // is deliberately excluded — nobody just sat through an update, and the
+ // installer is often already a release or two behind.
+ if (shouldShowVersionNotice) {
+ postUpdateQuietUntil = now().getTime() + POST_UPDATE_QUIET_MS;
+ logger.info('post-update quiet window armed', {
+ from: state.lastSeenVersion,
+ to: currentVersion,
+ untilMs: postUpdateQuietUntil,
+ });
+ }
+
// Persist-before-emit — advance
// `lastSeenVersion` BEFORE any broadcast so a disk-write failure cannot
// leave Toast B un-armed-with-broadcast-already-sent (which would re-fire
@@ -2182,6 +2564,9 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
}
return { version: activeWhatsNew.version, releaseUrl: activeWhatsNew.releaseUrl };
},
+ isWithinPostUpdateQuietWindow(): boolean {
+ return withinPostUpdateQuietWindow();
+ },
suppressAutoInstallOnQuit(): void {
updater.autoInstallOnAppQuit = false;
logger.info('autoInstallOnAppQuit suppressed for uninstall');
@@ -2242,6 +2627,16 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
clock.clearTimeout(relaunchInFlight.watchdog);
relaunchInFlight = null;
}
+ if (quietWindowTimer) {
+ clock.clearTimeout(quietWindowTimer);
+ quietWindowTimer = null;
+ }
+ // Release anything still awaiting the freshness check so a relaunch
+ // click that raced teardown resolves now instead of sitting out its
+ // full timeout against a torn-down updater.
+ settleCheckWaiters('settled');
+ stagingInFlight = null;
+ settleStagingWaiters(false);
// Note: listeners detached per-event below.
// Detach each listener under its own try/catch — a single `updater.off`
// throw must not leave the remaining subscribers wired. electron-
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 0f093b669..01adcb342 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -8228,7 +8228,12 @@ function bootPrimaryInstance(): void {
// window resurfaces the staged-update banner the boot path withheld).
if (!(app.isPackaged || process.env.OK_UPDATER_FORCE_DEV === '1')) return;
const pending = appState.versionPendingInstall;
- if (pending) {
+ // Hold the re-send while the post-update quiet window runs, for the
+ // same reason the updater holds the original broadcast: a user who
+ // just updated and then opened a project should not be met by a
+ // fresh update demand. The updater fires the held banner to every
+ // window once the window elapses, so nothing is lost here.
+ if (pending && !autoUpdaterHandle?.isWithinPostUpdateQuietWindow()) {
sendToRenderer(win.webContents, 'ok:update:downloaded', { version: pending });
}
// Late-window release-notes delivery: a project opened while the
diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.ts
index 5e3d25067..3fd702b62 100644
--- a/packages/desktop/src/preload/index.ts
+++ b/packages/desktop/src/preload/index.ts
@@ -58,6 +58,7 @@ import type {
OkShareReceivedPayload,
OkThemeSource,
OkUpdateDownloadedInfo,
+ OkUpdateFetchingLatestInfo,
OkUpdateRelaunchFailedInfo,
OkUpdateRelaunchingInfo,
OkUpdateStuckHintInfo,
@@ -332,6 +333,13 @@ const bridge: OkDesktopBridge = {
return () => ipcRenderer.removeListener('ok:update:relaunching', listener);
},
+ onUpdateFetchingLatest(cb: (info: OkUpdateFetchingLatestInfo) => void) {
+ const listener = (_event: IpcRendererEvent, info: OkUpdateFetchingLatestInfo) => cb(info);
+ // biome-ignore lint/plugin/no-loosely-typed-webcontents-ipc: preload-side subscription wrapper (precedent #14)
+ ipcRenderer.on('ok:update:fetching-latest', listener);
+ return () => ipcRenderer.removeListener('ok:update:fetching-latest', listener);
+ },
+
onUpdateRelaunchFailed(cb: (info: OkUpdateRelaunchFailedInfo) => void) {
const listener = (_event: IpcRendererEvent, info: OkUpdateRelaunchFailedInfo) => cb(info);
// biome-ignore lint/plugin/no-loosely-typed-webcontents-ipc: preload-side subscription wrapper (precedent #14)
diff --git a/packages/desktop/src/shared/ipc-events.ts b/packages/desktop/src/shared/ipc-events.ts
index 7db86c580..5feb85bc0 100644
--- a/packages/desktop/src/shared/ipc-events.ts
+++ b/packages/desktop/src/shared/ipc-events.ts
@@ -73,6 +73,19 @@ export interface EventChannels {
* [Relaunch]" banner for those seconds (and could fire a redundant relaunch).
*/
'ok:update:relaunching': { payload: { version: string } };
+ /**
+ * Main → every window when a "Relaunch" click is re-checking the feed before
+ * installing, and again for as long as a newer build found by that check is
+ * downloading. Renderers swap the card to a button-less "Getting the latest
+ * version…" state.
+ *
+ * Distinct from `ok:update:relaunching` because the two describe different
+ * waits and only one of them is bounded by seconds: this one can span a full
+ * update download, and labelling that "Relaunching…" would read as a hang.
+ * `version` names the build staged when the click landed, which is the one
+ * the user saw — a newer one may replace it before the install.
+ */
+ 'ok:update:fetching-latest': { payload: { version: string } };
/**
* Main → every window when a committed relaunch fails ASYNCHRONOUSLY — the
* updater's `error` event fired while the relaunch was in flight, or the
diff --git a/packages/desktop/tests/integration/auto-updater.test.ts b/packages/desktop/tests/integration/auto-updater.test.ts
index 967f41dde..e00007c9b 100644
--- a/packages/desktop/tests/integration/auto-updater.test.ts
+++ b/packages/desktop/tests/integration/auto-updater.test.ts
@@ -30,6 +30,9 @@ import {
type IpcMainLike,
installReached,
isClassifiedUpdaterError,
+ POST_UPDATE_QUIET_MS,
+ RELAUNCH_REFRESH_CHECK_MS,
+ RELAUNCH_REFRESH_DOWNLOAD_MS,
RELAUNCH_WATCHDOG_MS,
releaseUrlFor,
STUCK_HINT_DOWNLOAD_URL,
@@ -176,6 +179,8 @@ interface TestRig {
*/
windows: CapturedSend[][];
state: AppState;
+ /** Set true to make the next (and every) `writeState` throw. */
+ failNextPersist: boolean;
dispatches: DispatchKind[];
now: Date;
logger: {
@@ -285,6 +290,7 @@ function makeRig(
// lastSeenVersion to the fixture appVersion so the new first-launch
// version notice only appears in tests that opt into that branch.
state: { ...emptyState(), lastSeenVersion: appVersion, ...stateOverrides },
+ failNextPersist: false,
dispatches: [],
now: nowAt ?? new Date('2026-04-21T12:00:00.000Z'),
logger: {
@@ -307,6 +313,10 @@ function makeRig(
ipcMain: rig.ipc,
readState: () => rig.state,
writeState: (next) => {
+ // Flippable mid-test so a persist failure and the retry that follows it
+ // can be exercised against one live updater, the way the user meets them
+ // (full disk, click, free some space, click again).
+ if (rig.failNextPersist) throw new Error('disk full');
rig.state = next;
},
getPrimaryWindow: () => primaryWindow,
@@ -401,12 +411,12 @@ describe('startAutoUpdater — initial configuration (parent §8.10 LOCKED)', ()
expect(rig.state.attemptedInstall).toBeNull();
});
- test('linux: relaunch-now is the install-commit point — it arms attemptedInstall', () => {
+ test('linux: relaunch-now is the install-commit point — it arms attemptedInstall', async () => {
// The click is Linux's commitment; arming here keeps the boot-time
// silent-failure detection working for the path the user actually took.
const { rig } = makeRig({ platform: 'linux' });
rig.updater.emit('update-downloaded', { version: '0.3.2' });
- rig.ipc.invoke('ok:update:relaunch-now');
+ await rig.ipc.invoke('ok:update:relaunch-now');
expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);
expect(rig.state.attemptedInstall).toBe('0.3.2');
expect(rig.state.attemptedInstallSurfacedCount).toBe(0);
@@ -709,14 +719,14 @@ describe('staging age — how long the update sat before the install was request
expect(rig.state.versionPendingInstallStagedAt).toBe(Date.parse('2026-04-21T12:00:00.000Z'));
});
- test('relaunch-now records the staging age and logs it', () => {
+ test('relaunch-now records the staging age and logs it', async () => {
const { rig } = makeRig({ platform: 'darwin' });
rig.now = new Date('2026-04-21T12:00:00.000Z');
rig.updater.emit('update-downloaded', { version: '0.3.2' });
// A couple of seconds: the reported shape is a click landing moments after
// a newer build re-staged underneath an already-open notification.
rig.now = new Date('2026-04-21T12:00:02.060Z');
- rig.ipc.invoke('ok:update:relaunch-now');
+ await rig.ipc.invoke('ok:update:relaunch-now');
expect(rig.state.attemptedInstallStagingAgeMs).toBe(2060);
expect(rig.logger.info).toHaveBeenCalledWith(
@@ -733,12 +743,12 @@ describe('staging age — how long the update sat before the install was request
// `Date.now()` is wall-clock, not monotonic. An NTP correction between
// staging and the click makes the delta negative, and there is no age to
// report — same "unknown" the no-click path yields, not an instant install.
- test('reports null rather than zero when the clock moved backwards while staged', () => {
+ test('reports null rather than zero when the clock moved backwards while staged', async () => {
const { rig } = makeRig({ platform: 'darwin' });
rig.now = new Date('2026-04-21T12:00:00.000Z');
rig.updater.emit('update-downloaded', { version: '0.3.2' });
rig.now = new Date('2026-04-21T11:59:57.000Z');
- rig.ipc.invoke('ok:update:relaunch-now');
+ await rig.ipc.invoke('ok:update:relaunch-now');
expect(rig.state.attemptedInstallStagingAgeMs).toBeNull();
});
@@ -776,12 +786,12 @@ describe('staging age — how long the update sat before the install was request
// NEW version starts a fresh measurement, so a leftover age from an earlier
// click must not travel with it — a stale non-null number reads as real
// signal to a triager and is worse than the age simply being absent.
- test('a newly armed version does not inherit an earlier version staging age', () => {
+ test('a newly armed version does not inherit an earlier version staging age', async () => {
const { rig: session } = makeRig({ platform: 'darwin' });
session.now = new Date('2026-04-21T12:00:00.000Z');
session.updater.emit('update-downloaded', { version: '0.3.2' });
session.now = new Date('2026-04-21T12:00:02.060Z');
- session.ipc.invoke('ok:update:relaunch-now');
+ await session.ipc.invoke('ok:update:relaunch-now');
expect(session.state.attemptedInstallStagingAgeMs).toBe(2060);
// A newer build lands and is committed by a plain quit — no click, so the
@@ -1907,10 +1917,10 @@ describe('boot-time failed-install detection — install still in flight', () =>
* `overrides` moves the version pair and the commit moment off the defaults —
* the two dimensions that change which route through boot the fixture takes.
*/
- function stageAndCommit(
+ async function stageAndCommit(
via: 'relaunch-click' | 'plain-quit' | 'unobserved-quit',
overrides: { running?: string; attempted?: string; committedAt?: Date } = {},
- ): AppState {
+ ): Promise<AppState> {
const { rig, handle } = makeRig({
appVersion: overrides.running ?? RUNNING,
platform: 'darwin',
@@ -1918,7 +1928,7 @@ describe('boot-time failed-install detection — install still in flight', () =>
rig.now = STAGED_AT;
rig.updater.emit('update-downloaded', { version: overrides.attempted ?? ATTEMPTED });
rig.now = overrides.committedAt ?? HANDED_OFF_AT;
- if (via === 'relaunch-click') rig.ipc.invoke('ok:update:relaunch-now');
+ if (via === 'relaunch-click') await rig.ipc.invoke('ok:update:relaunch-now');
else if (via === 'plain-quit') handle.recordInstallHandoffOnQuit();
return rig.state;
}
@@ -1958,11 +1968,11 @@ describe('boot-time failed-install detection — install still in flight', () =>
return rig;
}
- test('reopened while the handed-off install may still be running → no failure verdict', () => {
+ test('reopened while the handed-off install may still be running → no failure verdict', async () => {
// The canonical shape the deferral exists for: a reopen a minute after the
// click, well inside the tolerance, while the swap is still running.
const rig = reopenAt(
- stageAndCommit('relaunch-click'),
+ await stageAndCommit('relaunch-click'),
new Date(HANDED_OFF_AT.getTime() + 62 * SECOND),
);
@@ -1982,12 +1992,12 @@ describe('boot-time failed-install detection — install still in flight', () =>
expect(rig.state.attemptedInstall).toBe(ATTEMPTED);
});
- test('reopened deep in the observed install-duration range → still no failure verdict', () => {
+ test('reopened deep in the observed install-duration range → still no failure verdict', async () => {
// Field installs have run to ~4.5 minutes, and the slow tail is exactly the
// population with time to get impatient and reopen, so the deferral has to
// cover the tail rather than the median.
const rig = reopenAt(
- stageAndCommit('relaunch-click'),
+ await stageAndCommit('relaunch-click'),
new Date(HANDED_OFF_AT.getTime() + 4 * MINUTE),
);
@@ -1997,11 +2007,11 @@ describe('boot-time failed-install detection — install still in flight', () =>
expect(rig.state.attemptedInstallSurfacedCount).toBe(0);
});
- test('reopened long after the handoff → the failure notice still fires', () => {
+ test('reopened long after the handoff → the failure notice still fires', async () => {
// The detector's whole purpose, preserved. A day on, nothing is installing,
// so a still-old running version is a genuinely failed install.
const rig = reopenAt(
- stageAndCommit('relaunch-click'),
+ await stageAndCommit('relaunch-click'),
new Date(HANDED_OFF_AT.getTime() + 24 * HOUR),
);
@@ -2015,12 +2025,12 @@ describe('boot-time failed-install detection — install still in flight', () =>
expect(rig.state.attemptedInstallSurfacedCount).toBe(1);
});
- test('reopened moments after a plain quit committed the install → no failure verdict', () => {
+ test('reopened moments after a plain quit committed the install → no failure verdict', async () => {
// Install-on-quit commits without a click, so the quit itself is the
// handoff — the last moment a live process can record before the swap moves
// into a process no later boot can see.
const rig = reopenAt(
- stageAndCommit('plain-quit'),
+ await stageAndCommit('plain-quit'),
new Date(HANDED_OFF_AT.getTime() + 45 * SECOND),
);
@@ -2031,14 +2041,14 @@ describe('boot-time failed-install detection — install still in flight', () =>
expect(rig.state.attemptedInstall).toBe(ATTEMPTED);
});
- test('a session between the staging and the plain quit is not charged against the install', () => {
+ test('a session between the staging and the plain quit is not charged against the install', async () => {
// The dominant commit path: an update downloads quietly in the background,
// the user works on for hours, then quits and reopens a minute later.
// Reasoning from the staging moment would have spent the whole tolerance on
// the working session and condemned an install that was one minute old.
const QUIT_AT = new Date(STAGED_AT.getTime() + 3 * HOUR);
const rig = reopenAt(
- stageAndCommit('plain-quit', { committedAt: QUIT_AT }),
+ await stageAndCommit('plain-quit', { committedAt: QUIT_AT }),
new Date(QUIT_AT.getTime() + 1 * MINUTE),
);
@@ -2049,9 +2059,9 @@ describe('boot-time failed-install detection — install still in flight', () =>
expect(rig.state.attemptedInstall).toBe(ATTEMPTED);
});
- test('reopened a day after a plain quit committed the install → the failure notice still fires', () => {
+ test('reopened a day after a plain quit committed the install → the failure notice still fires', async () => {
const rig = reopenAt(
- stageAndCommit('plain-quit'),
+ await stageAndCommit('plain-quit'),
new Date(HANDED_OFF_AT.getTime() + 24 * HOUR),
);
@@ -2059,13 +2069,13 @@ describe('boot-time failed-install detection — install still in flight', () =>
expect(rig.dispatches).toContain('install-failed-on-boot' as DispatchKind);
});
- test('a commit no live process observed falls back to the staging moment', () => {
+ test('a commit no live process observed falls back to the staging moment', async () => {
// Nothing recorded the handoff, so the only bound left is that the install
// cannot have begun before the artifact existed. Sound, just not tight: the
// tolerance now runs from the download, so it is whatever remains of the
// window after however long the artifact sat staged.
const rig = reopenAt(
- stageAndCommit('unobserved-quit'),
+ await stageAndCommit('unobserved-quit'),
new Date(STAGED_AT.getTime() + 45 * SECOND),
);
@@ -2082,9 +2092,9 @@ describe('boot-time failed-install detection — install still in flight', () =>
);
});
- test('an unobserved commit long after the staging still fires the notice', () => {
+ test('an unobserved commit long after the staging still fires the notice', async () => {
const rig = reopenAt(
- stageAndCommit('unobserved-quit'),
+ await stageAndCommit('unobserved-quit'),
new Date(STAGED_AT.getTime() + 24 * HOUR),
);
@@ -2092,7 +2102,7 @@ describe('boot-time failed-install detection — install still in flight', () =>
expect(rig.dispatches).toContain('install-failed-on-boot' as DispatchKind);
});
- test('the uninstall quit claims no handoff', () => {
+ test('the uninstall quit claims no handoff', async () => {
// The uninstall path turns install-on-quit off so Squirrel cannot swap the
// bundle out from under the helper trying to trash it. That quit installs
// nothing, so it must not record a handoff — and a boot that then reads the
@@ -2108,13 +2118,13 @@ describe('boot-time failed-install detection — install still in flight', () =>
expect(rig.state.attemptedInstallStagingAgeMs).toBeNull();
});
- test('a quit re-handing off an attempt does not buy it a fresh window', () => {
+ test('a quit re-handing off an attempt does not buy it a fresh window', async () => {
// The tolerance has to terminate, or a broken installer plus a user who
// reopens promptly after every quit would defer forever and the notice
// would never arrive. The moment is stamped once per staging, so the second
// quit measures from the first handoff — and by then the first attempt has
// demonstrably not landed, which is what the notice says.
- const state = stageAndCommit('plain-quit');
+ const state = await stageAndCommit('plain-quit');
const { rig, handle } = makeRig({ ...state, appVersion: RUNNING, platform: 'darwin' });
rig.now = new Date(HANDED_OFF_AT.getTime() + 25 * MINUTE);
handle.recordInstallHandoffOnQuit();
@@ -2129,12 +2139,12 @@ describe('boot-time failed-install detection — install still in flight', () =>
expect(later.dispatches).toContain('install-failed-on-boot' as DispatchKind);
});
- test('deferring does not spend the surfacing budget', () => {
+ test('deferring does not spend the surfacing budget', async () => {
// Two impatient reopens during the install window, then a boot long after.
// If a deferral spent budget the real failure would arrive part-spent, and
// at the cap it would never arrive at all — the notice would be silenced by
// the very impatience that triggered the abort.
- let state = stageAndCommit('relaunch-click');
+ let state = await stageAndCommit('relaunch-click');
const first = reopenAt(state, new Date(HANDED_OFF_AT.getTime() + 20 * SECOND));
expect(failureCards(first)).toHaveLength(0);
state = first.state;
@@ -2148,7 +2158,7 @@ describe('boot-time failed-install detection — install still in flight', () =>
expect(later.state.attemptedInstallSurfacedCount).toBe(1);
});
- test('an install that never lands is reported even when every reopen looks fresh', () => {
+ test('an install that never lands is reported even when every reopen looks fresh', async () => {
// Elapsed time alone cannot end the hold, because nothing about the timing
// ages across a reopen: electron-updater re-fires the cached
// `update-downloaded` on every launch check, the re-arm clears the recorded
@@ -2165,7 +2175,7 @@ describe('boot-time failed-install detection — install still in flight', () =>
const ATTEMPTED_BETA = '0.54.0-beta.1';
const versions = { running: RUNNING_BETA, attempted: ATTEMPTED_BETA };
- let state = stageAndCommit('relaunch-click', versions);
+ let state = await stageAndCommit('relaunch-click', versions);
let reopenedAt = new Date(HANDED_OFF_AT.getTime() + 45 * SECOND);
// Three reopens, each one inside the tolerance and each one leaving behind
// a handoff moment seconds old. On the timing they are indistinguishable
@@ -2204,13 +2214,13 @@ describe('boot-time failed-install detection — install still in flight', () =>
);
});
- test('a boot that cannot record the hold still holds', () => {
+ test('a boot that cannot record the hold still holds', async () => {
// The deferral is the only branch here that persists without deciding
// anything, so a failed write has to leave the boot where it started rather
// than promote it to a verdict: an install that may be seconds from landing
// must not be condemned because the disk was full. The cost is that the
// bound does not advance on this boot, which the deferral log carries.
- const state = stageAndCommit('relaunch-click');
+ const state = await stageAndCommit('relaunch-click');
const captured: CapturedSend[] = [];
const dispatches: DispatchKind[] = [];
startAutoUpdater({
@@ -2241,7 +2251,7 @@ describe('boot-time failed-install detection — install still in flight', () =>
expect(state.attemptedInstallDeferredBoots).toBe(0);
});
- test('a newly attempted version gets its own hold, a re-armed one keeps the old', () => {
+ test('a newly attempted version gets its own hold, a re-armed one keeps the old', async () => {
// The hold is spent per attempt. A re-arm of the version already being
// attempted is the same install being committed again, so it inherits what
// its predecessors spent — that inheritance IS the bound, since the re-arm
@@ -2252,7 +2262,7 @@ describe('boot-time failed-install detection — install still in flight', () =>
const ATTEMPTED_BETA = '0.54.0-beta.1';
const versions = { running: RUNNING_BETA, attempted: ATTEMPTED_BETA };
- let state = stageAndCommit('relaunch-click', versions);
+ let state = await stageAndCommit('relaunch-click', versions);
let reopenedAt = new Date(HANDED_OFF_AT.getTime() + 45 * SECOND);
for (let cycle = 1; cycle <= 3; cycle++) {
const rig = reopenAndQuit(state, reopenedAt, versions);
@@ -2289,14 +2299,14 @@ describe('boot-time failed-install detection — install still in flight', () =>
expect(fresh.state.attemptedInstall).toBe(NEXT);
});
- test('a handoff the clock cannot make sense of → fail closed, the notice fires', () => {
+ test('a handoff the clock cannot make sense of → fail closed, the notice fires', async () => {
// `Date.now()` is wall-clock, not monotonic: an NTP correction or a VM
// resume between the handoff and the boot can leave the recorded moment in
// the future. A negative elapsed time is unknown timing rather than a fresh
// install, and unknown must not silence the detector — the same coercion
// the staging age already makes on the write side.
const rig = reopenAt(
- stageAndCommit('relaunch-click'),
+ await stageAndCommit('relaunch-click'),
new Date(HANDED_OFF_AT.getTime() - 1 * HOUR),
);
@@ -2304,7 +2314,7 @@ describe('boot-time failed-install detection — install still in flight', () =>
expect(rig.dispatches).toContain('install-failed-on-boot' as DispatchKind);
});
- test('same-MMP beta bump committed by a plain quit → no failure verdict', () => {
+ test('same-MMP beta bump committed by a plain quit → no failure verdict', async () => {
// A beta-to-beta bump inside one major.minor.patch is the dominant shape an
// OK update takes, and it reaches the verdict by a different route than the
// fixtures above. The boot's stale-pending reconciliation compares
@@ -2317,7 +2327,7 @@ describe('boot-time failed-install detection — install still in flight', () =>
const RUNNING_BETA = '0.54.0-beta.0';
const ATTEMPTED_BETA = '0.54.0-beta.1';
const rig = reopenAt(
- stageAndCommit('plain-quit', { running: RUNNING_BETA, attempted: ATTEMPTED_BETA }),
+ await stageAndCommit('plain-quit', { running: RUNNING_BETA, attempted: ATTEMPTED_BETA }),
new Date(HANDED_OFF_AT.getTime() + 45 * SECOND),
RUNNING_BETA,
);
@@ -2334,7 +2344,7 @@ describe('boot-time failed-install detection — install still in flight', () =>
expect(rig.state.attemptedInstall).toBe(ATTEMPTED_BETA);
});
- test('a same-MMP beta bump survives a SECOND reopen inside the window', () => {
+ test('a same-MMP beta bump survives a SECOND reopen inside the window', async () => {
// The same-MMP shape reaches the verdict having just lost a field: the
// stale-pending reconciliation fires on an MMP-only compare and persists the
// staging stamp as null, so every boot after the first one reads a state
@@ -2344,7 +2354,7 @@ describe('boot-time failed-install detection — install still in flight', () =>
const RUNNING_BETA = '0.54.0-beta.0';
const ATTEMPTED_BETA = '0.54.0-beta.1';
const first = reopenAt(
- stageAndCommit('plain-quit', { running: RUNNING_BETA, attempted: ATTEMPTED_BETA }),
+ await stageAndCommit('plain-quit', { running: RUNNING_BETA, attempted: ATTEMPTED_BETA }),
new Date(HANDED_OFF_AT.getTime() + 45 * SECOND),
RUNNING_BETA,
);
@@ -2363,7 +2373,7 @@ describe('boot-time failed-install detection — install still in flight', () =>
expect(second.state.attemptedInstallSurfacedCount).toBe(0);
});
- test('a long wait before the click is measured from the click, not from the staging', () => {
+ test('a long wait before the click is measured from the click, not from the staging', async () => {
// The artifact sits staged for however long the user leaves the notice
// alone — three hours here, unbounded in general. Reasoning from the staging
// moment makes the tolerance a function of the user's patience rather than
@@ -2371,7 +2381,7 @@ describe('boot-time failed-install detection — install still in flight', () =>
// condemned because the download happened this morning.
const CLICKED_AT = new Date(STAGED_AT.getTime() + 3 * HOUR);
const rig = reopenAt(
- stageAndCommit('relaunch-click', { committedAt: CLICKED_AT }),
+ await stageAndCommit('relaunch-click', { committedAt: CLICKED_AT }),
new Date(CLICKED_AT.getTime() + 1 * MINUTE),
);
@@ -2382,7 +2392,7 @@ describe('boot-time failed-install detection — install still in flight', () =>
expect(rig.state.attemptedInstall).toBe(ATTEMPTED);
});
- test('a deferred boot records how long ago the install was handed off, and from what', () => {
+ test('a deferred boot records how long ago the install was handed off, and from what', async () => {
// A deferred boot is silent to the user by design, so this line is the only
// place an operator reading a "my update never installed" report can see
// that the boot considered the attempt and how long ago the handoff was —
@@ -2391,7 +2401,7 @@ describe('boot-time failed-install detection — install still in flight', () =>
// came from have to travel with it, or a verdict held off a handoff that was
// never observed is indistinguishable from one held off a real handoff.
const rig = reopenAt(
- stageAndCommit('relaunch-click'),
+ await stageAndCommit('relaunch-click'),
new Date(HANDED_OFF_AT.getTime() + 62 * SECOND),
);
@@ -2407,14 +2417,14 @@ describe('boot-time failed-install detection — install still in flight', () =>
);
});
- test('a boot ten minutes after the handoff still defers', () => {
+ test('a boot ten minutes after the handoff still defers', async () => {
// The tolerance has to clear the observed install tail with real margin
// rather than just cover the median: measured installs have run to about
// four and a half minutes on one machine, and the slow tail — a large bundle
// competing for I/O, or being scanned on first launch — is exactly the
// population that both runs long and gets reopened impatiently.
const rig = reopenAt(
- stageAndCommit('relaunch-click'),
+ await stageAndCommit('relaunch-click'),
new Date(HANDED_OFF_AT.getTime() + 10 * MINUTE),
);
@@ -2423,7 +2433,7 @@ describe('boot-time failed-install detection — install still in flight', () =>
expect(rig.state.attemptedInstallSurfacedCount).toBe(0);
});
- test('a boot two hours after the handoff fires the notice', () => {
+ test('a boot two hours after the handoff fires the notice', async () => {
// The other side of the same calibration. Nothing is still installing two
// hours on, and a tolerance wide enough to swallow a working session would
// defeat the detector for the people it exists for: someone who quits to
@@ -2431,7 +2441,7 @@ describe('boot-time failed-install detection — install still in flight', () =>
// all day. Brackets the tolerance from above without pinning its value, so
// it can be recalibrated from field reports within the bracket.
const rig = reopenAt(
- stageAndCommit('relaunch-click'),
+ await stageAndCommit('relaunch-click'),
new Date(HANDED_OFF_AT.getTime() + 2 * HOUR),
);
@@ -2439,7 +2449,7 @@ describe('boot-time failed-install detection — install still in flight', () =>
expect(rig.dispatches).toContain('install-failed-on-boot' as DispatchKind);
});
- test('a re-armed artifact records its own handoff instead of inheriting the last one', () => {
+ test('a re-armed artifact records its own handoff instead of inheriting the last one', async () => {
// A handoff moment dates one artifact's install. When a second artifact
// arrives, the moment recorded for the first has to go with the staging it
// belonged to: left in place, the once-per-attempt guard reads it as "this
@@ -2821,9 +2831,9 @@ describe('ok:update:relaunch-now IPC handler (AC18)', () => {
expect(rig.ipc.handlers.has('ok:update:relaunch-now')).toBe(true);
});
- test('handler invocation WITH versionPendingInstall calls autoUpdater.quitAndInstall', () => {
+ test('handler invocation WITH versionPendingInstall calls autoUpdater.quitAndInstall', async () => {
const { rig } = makeRig({ versionPendingInstall: '0.3.2' });
- rig.ipc.invoke('ok:update:relaunch-now');
+ await rig.ipc.invoke('ok:update:relaunch-now');
expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);
expect(rig.dispatches).toContain('relaunch-now' as DispatchKind);
});
@@ -2836,14 +2846,14 @@ describe('ok:update:relaunch-now IPC handler (AC18)', () => {
expect(rig.logger.warn).toHaveBeenCalled();
});
- test('broadcasts ok:update:relaunching to EVERY open window so all swap in lockstep', () => {
+ test('broadcasts ok:update:relaunching to EVERY open window so all swap in lockstep', async () => {
// The screenshot bug: clicking Relaunch in one window left the others
// showing a stale "…ready to install [Relaunch]" banner. The commit fans a
// relaunching signal to every window so they all swap to the in-progress
// card. Delivery-only fan-out: one dispatch, not N.
const { rig } = makeRig({ versionPendingInstall: '0.3.2', extraWindowCount: 2 });
expect(rig.windows).toHaveLength(3);
- rig.ipc.invoke('ok:update:relaunch-now');
+ await rig.ipc.invoke('ok:update:relaunch-now');
for (const win of rig.windows) {
const relaunching = win.filter((c) => c.channel === 'ok:update:relaunching');
expect(relaunching).toHaveLength(1);
@@ -2987,12 +2997,12 @@ describe('ok:update:relaunch-now IPC handler (AC18)', () => {
expect(rig.updater.quitAndInstall).not.toHaveBeenCalled();
});
- test('prepareForRelaunch throw does NOT block quitAndInstall', () => {
+ test('prepareForRelaunch throw does NOT block quitAndInstall', async () => {
const prepareForRelaunch = vi.fn(() => {
throw new Error('teardown bug');
});
const { rig } = makeRig({ versionPendingInstall: '0.3.2', prepareForRelaunch });
- rig.ipc.invoke('ok:update:relaunch-now');
+ await rig.ipc.invoke('ok:update:relaunch-now');
expect(prepareForRelaunch).toHaveBeenCalledTimes(1);
expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);
expect(rig.logger.warn).toHaveBeenCalled();
@@ -3889,13 +3899,20 @@ describe('Toast B persist-before-emit + whenRendererReady (Major #1)', () => {
// ————————————————————————————————————————————————————————
describe('relaunch-now idempotency (Major #2)', () => {
- test('second invocation sees cleared versionPendingInstall → no second quitAndInstall', () => {
+ test('second invocation sees the committed install → no second quitAndInstall', async () => {
const { rig } = makeRig({ versionPendingInstall: '0.3.2' });
- rig.ipc.invoke('ok:update:relaunch-now');
- // Simulate rapid double-click — sonner does not debounce action buttons.
- rig.ipc.invoke('ok:update:relaunch-now');
+ // Rapid double-click: BOTH invocations are fired before either resolves,
+ // which is the shape the freshness check made possible. The state gate
+ // alone no longer covers it — `versionPendingInstall` is not cleared until
+ // after the pre-install check awaits, so the second click would otherwise
+ // find the state still armed and fire a second, non-idempotent
+ // `quitAndInstall()`. The in-memory commit flag is what blocks it.
+ const first = rig.ipc.invoke('ok:update:relaunch-now');
+ const second = rig.ipc.invoke('ok:update:relaunch-now');
+ await Promise.all([first, second]);
expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);
- // State is cleared after first invocation.
+ expect(rig.dispatches).toContain('relaunch-double-invoke-blocked' as DispatchKind);
+ // State is cleared by the invocation that committed.
expect(rig.state.versionPendingInstall).toBeNull();
});
@@ -4460,3 +4477,267 @@ describe('linux manual-install fallback', () => {
expect(fallback).not.toHaveBeenCalled();
});
});
+
+// ————————————————————————————————————————————————————————
+// Update freshness at the moment the user asks to install
+// ————————————————————————————————————————————————————————
+
+/**
+ * Fire the timer registered for exactly `ms`, newest first.
+ *
+ * `clock.lastCallback` is not usable here: the fixture remembers only the most
+ * recent timer, and the periodic-check timer re-arms itself from a microtask
+ * that lands in the middle of these tests, so `lastCallback` routinely points
+ * at the periodic check rather than the timer under test.
+ */
+function fireTimerFor(clock: FakeClock, ms: number): void {
+ const call = [...clock.setTimeout.mock.calls].reverse().find((c) => c[1] === ms);
+ if (!call) throw new Error(`no timer registered for ${ms}ms`);
+ (call[0] as () => void)();
+}
+
+describe('same-version download guard', () => {
+ test('an offer for the already-staged version does not re-download', () => {
+ const { rig } = makeRig({ versionPendingInstall: '0.3.2' });
+ rig.updater.downloadUpdate.mockClear();
+
+ rig.updater.emit('update-available', { version: '0.3.2' });
+
+ expect(rig.updater.downloadUpdate).not.toHaveBeenCalled();
+ expect(rig.dispatches).toContain('download-skipped-already-staged' as DispatchKind);
+ });
+
+ test('the skipped offer still counts as a successful check', () => {
+ // The pipeline reached a parsed manifest; only the download was declined.
+ // Treating it as a failure would march the 7-day stuck-hint toward firing
+ // on a healthy updater that simply has nothing new to fetch.
+ const { rig } = makeRig({ versionPendingInstall: '0.3.2' });
+ rig.updater.emit('update-available', { version: '0.3.2' });
+ expect(rig.dispatches).toContain('check-success' as DispatchKind);
+ });
+
+ test('a genuinely newer offer still downloads', () => {
+ const { rig } = makeRig({ versionPendingInstall: '0.3.2' });
+ rig.updater.downloadUpdate.mockClear();
+
+ rig.updater.emit('update-available', { version: '0.3.3' });
+
+ expect(rig.updater.downloadUpdate).toHaveBeenCalledTimes(1);
+ expect(rig.dispatches).not.toContain('download-skipped-already-staged' as DispatchKind);
+ });
+
+ test('a retry after a failed download is not mistaken for an already-staged build', () => {
+ // A download that never completed left `versionPendingInstall` unset, so
+ // the guard must not latch on the version alone.
+ const { rig } = makeRig({ versionPendingInstall: null });
+ rig.updater.emit('update-available', { version: '0.3.2' });
+ rig.updater.emit('error', new Error('network died'));
+ rig.updater.downloadUpdate.mockClear();
+
+ rig.updater.emit('update-available', { version: '0.3.2' });
+
+ expect(rig.updater.downloadUpdate).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('click-gated freshness check', () => {
+ test('nothing newer → installs the staged build', async () => {
+ const { rig } = makeRig({ versionPendingInstall: '0.3.2' });
+ await rig.ipc.invoke('ok:update:relaunch-now');
+
+ expect(rig.updater.checkForUpdates).toHaveBeenCalled();
+ expect(rig.dispatches).toContain('relaunch-refresh-up-to-date' as DispatchKind);
+ expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);
+ });
+
+ test('every window is told the click is fetching before the wait begins', async () => {
+ const { rig } = makeRig({ versionPendingInstall: '0.3.2', extraWindowCount: 2 });
+ await rig.ipc.invoke('ok:update:relaunch-now');
+
+ for (const win of rig.windows) {
+ const fetching = win.filter((c) => c.channel === 'ok:update:fetching-latest');
+ expect(fetching).toHaveLength(1);
+ expect(fetching[0]?.payload).toEqual({ version: '0.3.2' });
+ }
+ });
+
+ test('a newer build found at click time is installed instead of the staged one', async () => {
+ const { rig } = makeRig({ versionPendingInstall: '0.3.2' });
+ // The check the click fires turns up a newer build. The download it starts
+ // is left in flight so the wait is the one under test; the test completes
+ // it below.
+ rig.updater.checkForUpdates.mockImplementation(() => {
+ rig.updater.emit('update-available', { version: '0.3.3' });
+ return Promise.resolve(undefined);
+ });
+
+ const pending = rig.ipc.invoke('ok:update:relaunch-now');
+ await Promise.resolve();
+ expect(rig.dispatches).toContain('relaunch-refresh-found-newer' as DispatchKind);
+ expect(rig.updater.quitAndInstall).not.toHaveBeenCalled();
+
+ rig.updater.emit('update-downloaded', { version: '0.3.3' });
+ await pending;
+
+ expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);
+ // The handoff record names the build actually installed, not the one the
+ // banner happened to be showing when it was clicked.
+ expect(rig.state.attemptedInstall).toBe('0.3.3');
+ });
+
+ test('a click landing mid-stage waits instead of installing over the write', async () => {
+ // The install-failure shape this guards: electron-updater keeps its
+ // "already staged" flag set from the previous stage, so quitAndInstall
+ // during a re-stage fires at a half-written bundle.
+ const { rig } = makeRig({ versionPendingInstall: '0.3.2' });
+ rig.updater.emit('update-available', { version: '0.3.3' });
+
+ const pending = rig.ipc.invoke('ok:update:relaunch-now');
+ await Promise.resolve();
+ expect(rig.updater.quitAndInstall).not.toHaveBeenCalled();
+ expect(rig.dispatches).toContain('relaunch-awaited-in-flight-staging' as DispatchKind);
+
+ rig.updater.emit('update-downloaded', { version: '0.3.3' });
+ await pending;
+
+ expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);
+ });
+
+ test('a stage that errors out releases the click rather than stranding it', async () => {
+ const { rig } = makeRig({ versionPendingInstall: '0.3.2' });
+ rig.updater.emit('update-available', { version: '0.3.3' });
+
+ const pending = rig.ipc.invoke('ok:update:relaunch-now');
+ await Promise.resolve();
+ rig.updater.emit('error', new Error('download died'));
+ await pending;
+
+ // The newer build never staged, so the one still on disk is installed.
+ expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);
+ });
+
+ test('a newer build that never finishes downloading falls through on the timeout', async () => {
+ // Falling through is safe: an unfinished re-download has not disturbed the
+ // previously-staged bundle, so the user still gets an install rather than
+ // a click that did nothing.
+ const { rig } = makeRig({ versionPendingInstall: '0.3.2' });
+ rig.updater.emit('update-available', { version: '0.3.3' });
+
+ const pending = rig.ipc.invoke('ok:update:relaunch-now');
+ await Promise.resolve();
+ expect(rig.updater.quitAndInstall).not.toHaveBeenCalled();
+
+ fireTimerFor(rig.clock, RELAUNCH_REFRESH_DOWNLOAD_MS);
+ await pending;
+
+ expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);
+ // The install went ahead against the build that was already staged, not
+ // the one whose download never finished.
+ const relaunching = rig.captured.filter((c) => c.channel === 'ok:update:relaunching');
+ expect(relaunching).toHaveLength(1);
+ expect(relaunching[0]?.payload).toEqual({ version: '0.3.2' });
+ expect(rig.state.versionPendingInstall).toBeNull();
+ });
+
+ test('a check that never reports back falls through on the timeout', async () => {
+ const { rig } = makeRig({ versionPendingInstall: '0.3.2' });
+ rig.updater.checkForUpdates.mockImplementation(() => new Promise(() => {}));
+
+ const pending = rig.ipc.invoke('ok:update:relaunch-now');
+ await Promise.resolve();
+ expect(rig.updater.quitAndInstall).not.toHaveBeenCalled();
+
+ fireTimerFor(rig.clock, RELAUNCH_REFRESH_CHECK_MS);
+ await pending;
+
+ expect(rig.dispatches).toContain('relaunch-refresh-timed-out' as DispatchKind);
+ expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('the commit flag releases on every path that re-offers the click', () => {
+ // The flag exists to stop a rapid double-click firing a non-idempotent
+ // install twice. Every path that declines to install has to hand it back, or
+ // the banner it re-arms would be dead to the next click for the rest of the
+ // session.
+ test('a persist failure leaves the banner clickable again', async () => {
+ const { rig } = makeRig({ versionPendingInstall: '0.3.2' });
+ rig.failNextPersist = true;
+
+ await rig.ipc.invoke('ok:update:relaunch-now');
+ expect(rig.updater.quitAndInstall).not.toHaveBeenCalled();
+
+ rig.failNextPersist = false;
+ await rig.ipc.invoke('ok:update:relaunch-now');
+
+ expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);
+ });
+
+ test('the linux no-graphical-auth preflight leaves the banner clickable again', async () => {
+ const hasGraphicalAuth = vi.fn(() => false);
+ const { rig } = makeRig({
+ platform: 'linux',
+ versionPendingInstall: '0.3.2',
+ linuxInstallSupport: {
+ hasGraphicalAuth,
+ showManualInstallFallback: vi.fn(() => Promise.resolve()),
+ },
+ });
+ rig.updater.emit('update-downloaded', {
+ version: '0.3.2',
+ downloadedFile: '/home/u/.cache/ok-updater/pending/ok_0.3.2_arm64.deb',
+ });
+
+ await rig.ipc.invoke('ok:update:relaunch-now');
+ expect(rig.updater.quitAndInstall).not.toHaveBeenCalled();
+
+ // The user installs a polkit agent and clicks the re-armed banner again.
+ hasGraphicalAuth.mockReturnValue(true);
+ await rig.ipc.invoke('ok:update:relaunch-now');
+
+ expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('post-update quiet window', () => {
+ test('a banner arriving right after an update is held, not dropped', () => {
+ const { rig, handle } = makeRig({ lastSeenVersion: '0.3.0', appVersion: '0.3.1' });
+ expect(handle.isWithinPostUpdateQuietWindow()).toBe(true);
+
+ rig.updater.emit('update-downloaded', { version: '0.3.2' });
+
+ expect(rig.captured.filter((c) => c.channel === 'ok:update:downloaded')).toHaveLength(0);
+ expect(rig.dispatches).toContain('toast-a-deferred-post-update-quiet' as DispatchKind);
+ // Held, not lost: the update is fully staged and still installs on quit.
+ expect(rig.state.versionPendingInstall).toBe('0.3.2');
+
+ fireTimerFor(rig.clock, POST_UPDATE_QUIET_MS);
+
+ expect(rig.captured.filter((c) => c.channel === 'ok:update:downloaded')).toHaveLength(1);
+ expect(rig.dispatches).toContain('toast-a-quiet-window-elapsed' as DispatchKind);
+ expect(handle.isWithinPostUpdateQuietWindow()).toBe(false);
+ });
+
+ test('a fresh install does not arm it', () => {
+ // Nobody sat through an update, and the installer is often already a
+ // release or two behind, so suppressing here would only delay a wanted
+ // update.
+ const { handle } = makeRig({ lastSeenVersion: null, appVersion: '0.3.1' });
+ expect(handle.isWithinPostUpdateQuietWindow()).toBe(false);
+ });
+
+ test('a plain relaunch on the same version does not arm it', () => {
+ const { handle } = makeRig({ lastSeenVersion: '0.3.1', appVersion: '0.3.1' });
+ expect(handle.isWithinPostUpdateQuietWindow()).toBe(false);
+ });
+
+ test('outside the window the banner fires immediately, as before', () => {
+ const { rig, handle } = makeRig({ lastSeenVersion: '0.3.1', appVersion: '0.3.1' });
+ expect(handle.isWithinPostUpdateQuietWindow()).toBe(false);
+
+ rig.updater.emit('update-downloaded', { version: '0.3.2' });
+
+ expect(rig.captured.filter((c) => c.channel === 'ok:update:downloaded')).toHaveLength(1);
+ expect(rig.dispatches).toContain('update-downloaded-toast-a' as DispatchKind);
+ });
+});