Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok/desktop): boot check races ShipIt install window (PRD-7995) (#3577)

Andrew Mikofalvy9e902fbb5b2a
diff --git a/.changeset/install-in-flight-verdict.md b/.changeset/install-in-flight-verdict.md
new file mode 100644
index 000000000..0f32061d0
--- /dev/null
+++ b/.changeset/install-in-flight-verdict.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Reopening the app while a macOS update is still installing no longer shows a false "Update to X didn't install" notice, and no longer spends one of the three chances that notice gets. The install runs after the app quits, inside a separate process the next launch cannot see, so reopening a minute later booted the old version and that was read as a failed install. It was also self-defeating: the reopen is what interrupts the install, and an interrupted attempt re-stages, so the update being declared dead is the one that would have landed on the next quit. The app now holds the verdict while the install may still be underway, and reports a genuinely failed install on a later launch instead.
+
+The wait now runs from the moment the install actually starts, which is when you quit or click Relaunch now, rather than from when the download finished. An update that downloaded quietly in the background hours before you quit still gets the full window.
diff --git a/packages/desktop/src/main/auto-updater.ts b/packages/desktop/src/main/auto-updater.ts
index 72a0b3656..c3c194879 100644
--- a/packages/desktop/src/main/auto-updater.ts
+++ b/packages/desktop/src/main/auto-updater.ts
@@ -144,6 +144,7 @@ export type DispatchKind =
| 'skipped-dev-mode'
| 'stale-pending-cleared'
| 'attempted-install-reconciled'
+ | 'install-in-flight-deferred'
| 'install-failed-on-boot'
| 'install-failed-giveup'
| 'attempted-install-cross-channel'
@@ -229,10 +230,10 @@ interface StartAutoUpdaterOpts {
* Synchronous teardown hook fired immediately before
* `autoUpdater.quitAndInstall()` from the `ok:update:relaunch-now`
* IPC handler. Production wires this to a hard SIGKILL of every
- * project-window utility process. Squirrel.Mac's pre-swap check
- * runs `pgrep` against the bundle path and aborts with
+ * project-window utility process. Squirrel.Mac's ShipIt runs a final
+ * not-still-running validation and aborts the swap with
* `SQRLInstallerErrorDomain Code=-9 "App Still Running Error"` if
- * any utility is still alive when the swap window opens — the
+ * it still sees the app running when the swap window opens — the
* standard `app.quit()` path posts a graceful `{type:'shutdown'}`
* to each utility, but Hocuspocus / file-watcher cleanup can take
* longer than ShipIt's poll budget, leaving the swap silently
@@ -359,6 +360,24 @@ export interface StartAutoUpdaterHandle {
* can swap/relaunch the bundle while the helper is trying to trash it.
*/
suppressAutoInstallOnQuit(): void;
+ /**
+ * Record that this quit is where the staged install gets handed off, so the
+ * next boot can tell "the install may still be running" from "the install
+ * failed". Wired to `app.on('before-quit')`: with install-on-quit armed an
+ * ordinary quit IS the commit point, and it is the last moment a live process
+ * can observe it — the swap runs after the exit, in a process no later boot
+ * can see. Without this the boot would have only the staging moment to reason
+ * from, so a background download followed by an afternoon of work would leave
+ * the whole tolerance already spent by the time the user actually quit.
+ *
+ * Stamps once per armed attempt. A quit that re-hands off an attempt an
+ * earlier quit already handed off buys no fresh tolerance: otherwise a user
+ * who reopens promptly after every quit would keep resetting the clock on a
+ * genuinely broken installer and never be told about it. A "Relaunch now"
+ * click does re-stamp — that is an explicit request for a fresh attempt, and
+ * the surfacing budget bounds how many of those can pass silently.
+ */
+ recordInstallHandoffOnQuit(): void;
}
interface Logger {
@@ -443,6 +462,48 @@ export const STUCK_HINT_THRESHOLD_MS = 7 * 24 * 60 * 60 * 1000;
*/
export const INSTALL_FAILURE_MAX_SURFACES = 3;
+/**
+ * How long after an install was handed off a boot still treats a running
+ * version that has not caught up as "the install may be underway" rather than
+ * as a failure. The swap runs after the app exits, in a process no later boot
+ * can observe, so elapsed time is the only discriminator available — and
+ * reopening mid-install boots the OLD version, which is the expected state
+ * inside that window rather than evidence of anything.
+ *
+ * Calibrated well above the observed install tail (successful installs have run
+ * ~1s to ~4.5 min) so a slow-but-healthy install is not condemned, and well
+ * below a working session so a genuinely dead install is still reported the
+ * same day. Widening it delays a true notice by a boot; narrowing it re-opens
+ * the false-positive window. `handoffAgeMs` on the failure logs is the field
+ * evidence needed to move it.
+ *
+ * The window is measured from the handoff both install paths record — the
+ * "Relaunch now" click, or the quit install-on-quit commits on. It shrinks only
+ * when no live process got to observe the commit (a force-quit, a power loss),
+ * where the staging moment is the sole lower bound left and the effective
+ * tolerance is this minus however long the artifact sat staged. `recordedHandoff`
+ * on the boot logs says which of the two a given verdict used.
+ */
+const INSTALL_IN_FLIGHT_GRACE_MS = 30 * 60 * 1000;
+
+/**
+ * How many boots may hold the failed-install verdict on the grounds that the
+ * install might still be running, before the verdict is decided on its merits
+ * however recent the handoff looks.
+ *
+ * The handoff moment cannot bound the hold by itself. electron-updater re-fires
+ * `update-downloaded` from its on-disk cache on every launch check, and that
+ * re-arm clears the recorded handoff whenever the pending gate is not already
+ * set for the same version — after a "Relaunch now" click, and on every boot of
+ * a same-major.minor.patch bump, whose stale-pending reconciliation strips the
+ * gate. The next quit then stamps a fresh moment, so an install that never lands
+ * keeps looking newly handed off to anyone whose quit-to-reopen gaps stay inside
+ * the tolerance, and the notice would never arrive. The count is the part of the
+ * hold that survives that re-arm, which is what makes it the termination
+ * guarantee; three mirrors the surfacing budget's shape.
+ */
+const INSTALL_DEFER_MAX_BOOTS = 3;
+
/**
* "Download manually" target for the stuck-hint and boot-detected install-failed
* notices. Points at the GitHub Releases index, the canonical home of the signed
@@ -637,6 +698,27 @@ export function installReached(running: string, attempted: string): boolean {
return r.pre.length >= a.pre.length;
}
+/**
+ * How long ago the install for the armed attempt was handed off, given the
+ * handoff instant a live process recorded before it quit. The boot that judges
+ * the install runs in a different process than the install itself, so this is
+ * the only elapsed time available to it.
+ *
+ * Returns null for timing that cannot be reasoned from, which callers must
+ * treat as "no in-flight claim" rather than as a fresh install:
+ * - no `handoffAt` — nothing recorded the commit and no fallback moment
+ * survived either; the process that could have stamped it is gone.
+ * - negative elapsed — `Date.now()` is wall-clock, not monotonic, and this
+ * record crosses a process quit, so an NTP correction or a VM resume can
+ * leave the recorded handoff in the future. Same coercion the write side
+ * makes on the staging age.
+ */
+function installHandoffAgeMs(handoffAt: number | null, nowMs: number): number | null {
+ if (handoffAt === null) return null;
+ const elapsed = nowMs - handoffAt;
+ return elapsed < 0 ? null : elapsed;
+}
+
// ————————————————————————————————————————————————————————
// Main entry
// ————————————————————————————————————————————————————————
@@ -1274,6 +1356,11 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
// and so survives a same-version re-arm, this is scoped to the
// staging and resets with it.
attemptedInstallStagingAgeMs: null,
+ // Reset with the staging for the same reason: a handoff recorded
+ // against the PREVIOUS artifact would otherwise be read as this
+ // attempt's, and a stale instant hours in the past condemns an
+ // install that was just committed.
+ attemptedInstallHandoffAt: null,
...(installCommittedAtDownload
? {
attemptedInstall: version,
@@ -1283,6 +1370,13 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
// boot-nag cap isn't reset.
attemptedInstallSurfacedCount:
state.attemptedInstall === version ? state.attemptedInstallSurfacedCount : 0,
+ // Same version scoping, and load-bearing here rather than
+ // merely tidy: this re-arm is what clears the handoff stamp, so
+ // a count that reset alongside it would leave the deferral with
+ // nothing that outlives a re-arm — and an install that never
+ // lands could be held quiet forever.
+ attemptedInstallDeferredBoots:
+ state.attemptedInstall === version ? state.attemptedInstallDeferredBoots : 0,
}
: {}),
},
@@ -1486,6 +1580,11 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
...snapshot,
versionPendingInstall: null,
attemptedInstallStagingAgeMs: stagingAgeMs,
+ // The click IS the handoff. Re-stamped on every click, unlike the
+ // quit path: a Retry is an explicit request for a fresh install
+ // attempt, and the surfacing budget already bounds how many of those
+ // a persistently-failing install can hide behind.
+ attemptedInstallHandoffAt: now().getTime(),
...(platform === 'linux'
? {
attemptedInstall: pending,
@@ -1493,6 +1592,10 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
snapshot.attemptedInstall === pending
? snapshot.attemptedInstallSurfacedCount
: 0,
+ attemptedInstallDeferredBoots:
+ snapshot.attemptedInstall === pending
+ ? snapshot.attemptedInstallDeferredBoots
+ : 0,
}
: {}),
},
@@ -1514,8 +1617,8 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
onDispatch?.('relaunching-broadcast');
// Fire the pre-relaunch teardown hook BEFORE `quitAndInstall()`. Wrap
// in try/catch so a hook bug never blocks the user's relaunch — the
- // worst case if the hook throws is the original failure mode (Squirrel
- // pgrep aborts with code -9), which the user can recover from by
+ // worst case if the hook throws is the original failure mode (ShipIt's
+ // not-still-running validation aborts with code -9), which the user can recover from by
// quitting the app manually. We log the throw so the diagnostic is
// visible in main process stderr.
if (opts.prepareForRelaunch) {
@@ -1603,6 +1706,15 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
const currentVersion = getAppVersion();
let state = readState();
+ // Snapshot the staging stamp before the stale-pending reconciliation below
+ // can clear it. That reconciliation compares major.minor.patch only, so a
+ // same-MMP beta bump — the dominant OK update shape — reads as "caught up"
+ // and drops the stamp, while the prerelease-aware failed-install verdict
+ // right after still sees an install that never landed. Only the fallback
+ // needs it: a recorded handoff lives in the `attemptedInstall` group, which
+ // this reconciliation does not touch.
+ const attemptStagedAt = state.versionPendingInstallStagedAt;
+
// Boot-time stale-pending reconciliation. `versionPendingInstall` is cleared
// by exactly one site (`ok:update:relaunch-now` IPC, the "Relaunch" button).
// The other install path — `autoInstallOnAppQuit` (non-Linux; Linux keeps
@@ -1663,6 +1775,8 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
attemptedInstall: null,
attemptedInstallSurfacedCount: 0,
attemptedInstallStagingAgeMs: null,
+ attemptedInstallHandoffAt: null,
+ attemptedInstallDeferredBoots: 0,
};
if (persistSafely(next, 'attempted-install-reconciled')) {
state = next;
@@ -1702,6 +1816,8 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
stagedInstallerPath: null,
versionPendingInstallStagedAt: null,
attemptedInstallStagingAgeMs: null,
+ attemptedInstallHandoffAt: null,
+ attemptedInstallDeferredBoots: 0,
};
if (persistSafely(next, 'attempted-install-cross-channel')) {
state = next;
@@ -1715,9 +1831,76 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
// Gated on `updatesEnabled`: in a dev build a non-reached attemptedInstall
// is stale dev/test residue, not a real failed install — leave it armed
// (a later production build reconciles it) but don't surface the notice.
- // Running did NOT reach the attempted version → the install silently
- // failed.
- if (state.attemptedInstallSurfacedCount >= INSTALL_FAILURE_MAX_SURFACES) {
+
+ // Running did NOT reach the attempted version — which is equally the
+ // expected state while the install for it is still underway, so the two
+ // have to be separated before either failure verdict below is reachable.
+ // The recorded handoff, or — when no live process saw the commit (a
+ // force-quit, a power loss, a state file predating the stamp) — the
+ // staging moment. The install cannot have begun before the artifact
+ // existed, so staging is a sound lower bound on the handoff, just not a
+ // tight one, and it degrades further once the reconciliation clears it.
+ const handoffAt = state.attemptedInstallHandoffAt ?? attemptStagedAt;
+ const handoffAgeMs = installHandoffAgeMs(handoffAt, now().getTime());
+ if (
+ handoffAgeMs !== null &&
+ handoffAgeMs <= INSTALL_IN_FLIGHT_GRACE_MS &&
+ state.attemptedInstallDeferredBoots < INSTALL_DEFER_MAX_BOOTS
+ ) {
+ // Inside the install window, and the hold has boots left: decide
+ // nothing about the attempt. `attemptedInstall` stays armed so a later
+ // boot still reconciles it as success or as failure,
+ // `versionPendingInstall` is not re-armed behind an install that is
+ // about to land, and the surfacing budget stays unspent so user
+ // impatience cannot exhaust the notice before the real verdict is due.
+ // Deferring is also the only direction that can be wrong cheaply: on
+ // Squirrel.Mac the reopen is itself what aborts the swap, and an
+ // aborted attempt re-stages, so the install this boot would condemn is
+ // the one that lands on the next quit.
+ //
+ // The one thing the boot does record is that it held — the count is
+ // what survives a same-version re-arm clearing the handoff stamp, so
+ // without writing it the hold has nothing to terminate on.
+ const next = {
+ ...state,
+ attemptedInstallDeferredBoots: state.attemptedInstallDeferredBoots + 1,
+ };
+ if (persistSafely(next, 'install-in-flight-deferred')) {
+ state = next;
+ } else {
+ // Still defer: a write failure is no reason to condemn an install
+ // that may be landing. The bound just does not advance this boot, so
+ // log the pair the way the reconciliation branch does — a count that
+ // never moves across boots is how this shows up in a field report.
+ logger.warn('failed to persist install-in-flight-deferred', {
+ attempted,
+ running: currentVersion,
+ });
+ }
+ // Logged at info, like the sibling reconciliation branches — a held
+ // verdict is an expected outcome, and this line is the only trace of it
+ // since a deferred boot is silent to the user.
+ logger.info('attempted install may still be running — deferring the failure verdict', {
+ attempted,
+ running: currentVersion,
+ handoffAgeMs,
+ // The instant `handoffAgeMs` was derived from, plus how long the
+ // artifact had sat staged when it was committed. A deferred boot is
+ // silent to the user, so this line is the only record of a held
+ // verdict — carrying the inputs is what lets an operator reading a
+ // "my update never installed" report tell a verdict held correctly
+ // from one held off a fallback moment rather than a real handoff.
+ handoffAt,
+ recordedHandoff: state.attemptedInstallHandoffAt !== null,
+ stagingAgeMs: state.attemptedInstallStagingAgeMs,
+ surfaced: state.attemptedInstallSurfacedCount,
+ // How much of the hold this attempt has spent, after this boot. Reads
+ // the effective count rather than the intended one, so a bound that
+ // stops advancing (a failing persist) is visible from the log alone.
+ deferredBoots: state.attemptedInstallDeferredBoots,
+ });
+ onDispatch?.('install-in-flight-deferred');
+ } else if (state.attemptedInstallSurfacedCount >= INSTALL_FAILURE_MAX_SURFACES) {
// Budget spent — drop `attemptedInstall` so a persistently-failing
// ShipIt or an unreachable attempted version (a yanked release, a
// channel move) stops re-firing the notice on every boot. The 7-day
@@ -1734,6 +1917,8 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
stagedInstallerPath: null,
versionPendingInstallStagedAt: null,
attemptedInstallStagingAgeMs: null,
+ attemptedInstallHandoffAt: null,
+ attemptedInstallDeferredBoots: 0,
};
if (persistSafely(next, 'install-failed-giveup')) {
state = next;
@@ -1742,6 +1927,7 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
attempted,
running: currentVersion,
surfaced: INSTALL_FAILURE_MAX_SURFACES,
+ handoffAgeMs,
});
onDispatch?.('install-failed-giveup');
}
@@ -1769,10 +1955,21 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
attempted,
running: currentVersion,
surfaced: next.attemptedInstallSurfacedCount,
- // Null when the install was committed by a plain quit rather than a
- // "Relaunch now" click — there is no request moment to measure to,
- // and a zero here would read as an instant install.
+ // Null when no live process saw the install committed — a quit that
+ // never ran its handlers — and a zero would read as an instant
+ // install, so unknown is reported as unknown.
stagingAgeMs: state.attemptedInstallStagingAgeMs,
+ // Pairs with the age below so the two `handoffAgeMs === null`
+ // causes are distinguishable from the line alone: absent here means
+ // no handoff moment survived at all, present with a null age means
+ // the clock moved backwards between the handoff and this boot.
+ handoffAt,
+ recordedHandoff: state.attemptedInstallHandoffAt !== null,
+ // How long ago the install was handed off, which the staging age
+ // cannot say: it measures staged-to-request, not request-to-now.
+ // Null means the timing on record could not be reasoned from, and
+ // the verdict fired on the fail-closed path.
+ handoffAgeMs,
});
// Reuse the relaunch-failed channel: both mean "a committed update did
// not install". The boot-detected case carries a `downloadUrl` so the
@@ -1989,6 +2186,53 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
updater.autoInstallOnAppQuit = false;
logger.info('autoInstallOnAppQuit suppressed for uninstall');
},
+ recordInstallHandoffOnQuit(): void {
+ // Install-on-quit is what makes an ordinary quit a handoff at all. Off on
+ // Linux, and turned off for the uninstall quit — neither of those quits
+ // installs anything, so neither gets to claim a handoff moment.
+ if (!updater.autoInstallOnAppQuit) return;
+ const current = readState();
+ // No install is committed, so this quit hands nothing off.
+ if (current.attemptedInstall === null) return;
+ // Already stamped — by the "Relaunch now" click, or by an earlier quit
+ // that handed the same staging off. Not refreshed; see the interface doc.
+ if (current.attemptedInstallHandoffAt !== null) return;
+ const handoffAt = now().getTime();
+ // How long the artifact had sat staged when this quit committed it —
+ // diagnostic only, and unavailable once a boot's stale-pending
+ // reconciliation has dropped the staging stamp. Same coercion the click
+ // path makes: a non-positive delta means the wall clock moved backwards
+ // since staging, not an instant handoff.
+ const stagedAt = current.versionPendingInstallStagedAt;
+ const rawStagingAge = stagedAt === null ? null : handoffAt - stagedAt;
+ const stagingAgeMs = rawStagingAge !== null && rawStagingAge > 0 ? rawStagingAge : null;
+ if (
+ persistSafely(
+ {
+ ...current,
+ attemptedInstallHandoffAt: handoffAt,
+ attemptedInstallStagingAgeMs: stagingAgeMs,
+ },
+ 'handoff-on-quit',
+ )
+ ) {
+ logger.info('quit commits the staged install — recording the handoff moment', {
+ attempted: current.attemptedInstall,
+ handoffAt,
+ stagingAgeMs,
+ });
+ } else {
+ // The next boot will read `recordedHandoff: false` and fall back to the
+ // staging moment, which can age out faster than the real handoff — so
+ // the lost write is worth a version-identified trace of its own beyond
+ // persistSafely's generic error.
+ logger.warn('failed to persist install handoff moment — next boot uses staging fallback', {
+ attempted: current.attemptedInstall,
+ handoffAt,
+ stagingAgeMs,
+ });
+ }
+ },
destroy(): void {
if (timerHandle) {
clock.clearTimeout(timerHandle);
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 1b83e0384..8f2e6bb6d 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -8428,8 +8428,8 @@ function bootPrimaryInstance(): void {
: {}),
// Pre-relaunch teardown — synchronously hard-kill every project-window
// utility (Hocuspocus host) right before
- // `autoUpdater.quitAndInstall()` so Squirrel.Mac's `pgrep` against
- // the bundle path doesn't see a stale process and abort with code -9
+ // `autoUpdater.quitAndInstall()` so Squirrel.Mac's pre-swap
+ // not-still-running validation doesn't see a stale process and abort with code -9
// ("App Still Running Error"). The graceful `{type:'shutdown'}`
// window-close IPC isn't fast enough — Hocuspocus drain + file-watcher
// teardown can outlast ShipIt's poll budget.
@@ -8452,7 +8452,7 @@ function bootPrimaryInstance(): void {
// until they release or 10 s elapses, then escalate to SIGKILL on
// detached pids whose drain ran long. Awaiting here means the
// updater's `quitAndInstall` waits for the process tree to be
- // genuinely clean before ShipIt's pre-swap `pgrep` runs.
+ // genuinely clean before ShipIt's pre-swap validation runs.
await wm?.stopAllOwnedServers();
// Drain the async log buffer before `quitAndInstall()` hands off to
// Squirrel, which SIGKILLs this process for the bundle swap. Without
@@ -8566,6 +8566,14 @@ function bootPrimaryInstance(): void {
// update`) already captured the richer pre-teardown set, so this no-ops
// there and only fires for a normal quit.
captureWindowRestoreSnapshot('before-quit');
+ // Stamp the handoff moment while a live process still exists to observe it.
+ // With a staged update armed, this quit is what commits the install, and
+ // the swap then runs after the exit inside a process the next boot cannot
+ // see — so the next boot's "did the install take?" verdict has only what is
+ // recorded here to tell an install still underway from one that failed.
+ // No-ops when nothing is staged or the moment was already stamped (the
+ // "Relaunch now" path records its own).
+ autoUpdaterHandle?.recordInstallHandoffOnQuit();
// Flush pending startup telemetry before exit. `emitStartupWaterfall`
// covers a quit during the post-window-shown flush-deadline window (the
// `.unref()`'d deadline timer won't fire once the process is exiting): it
diff --git a/packages/desktop/src/main/state-store.ts b/packages/desktop/src/main/state-store.ts
index c7e3cff26..5776d5862 100644
Binary files a/packages/desktop/src/main/state-store.ts and b/packages/desktop/src/main/state-store.ts differ
diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.ts
index bb872cd33..43caccf8d 100644
--- a/packages/desktop/src/main/window-manager.ts
+++ b/packages/desktop/src/main/window-manager.ts
@@ -1200,9 +1200,9 @@ export class WindowManager {
async stopAllOwnedServers(): Promise<void> {
// Utility-fork pids (dev path) — hard-kill immediately. These are
// children of Electron's process tree and would die anyway on
- // `quitAndInstall`, but ShipIt's pre-swap `pgrep` check (the
- // `SQRLInstallerErrorDomain Code=-9 "App Still Running"` failure)
- // wants the tree clean BEFORE it polls.
+ // `quitAndInstall`, but ShipIt's pre-swap not-still-running validation
+ // (the `SQRLInstallerErrorDomain Code=-9 "App Still Running"` failure)
+ // wants the tree clean BEFORE it looks.
signalStopOwnedUtilityForks(this.windowsByPath.values(), this.deps.log);
// Detached-spawn pids — two-phase SIGTERM → poll → SIGKILL.
diff --git a/packages/desktop/tests/integration/auto-updater.test.ts b/packages/desktop/tests/integration/auto-updater.test.ts
index a2fd906c6..967f41dde 100644
--- a/packages/desktop/tests/integration/auto-updater.test.ts
+++ b/packages/desktop/tests/integration/auto-updater.test.ts
@@ -245,6 +245,13 @@ function makeRig(
* (a stub returning a fresh value each call).
*/
random?: () => number;
+ /**
+ * Wall clock the boot itself observes. `rig.now` is mutable, but
+ * `startAutoUpdater` runs inside this factory, so a test that needs the
+ * BOOT-time reconciliation to see a specific instant has to supply it
+ * here. Defaults to the fixture's fixed timestamp.
+ */
+ nowAt?: Date;
},
): {
rig: TestRig;
@@ -264,6 +271,7 @@ function makeRig(
reclaimStagedUpdateCache,
linuxInstallSupport,
random = () => 0,
+ nowAt,
...stateOverrides
} = overrides ?? {};
const primaryCaptured: CapturedSend[] = [];
@@ -278,7 +286,7 @@ function makeRig(
// version notice only appears in tests that opt into that branch.
state: { ...emptyState(), lastSeenVersion: appVersion, ...stateOverrides },
dispatches: [],
- now: new Date('2026-04-21T12:00:00.000Z'),
+ now: nowAt ?? new Date('2026-04-21T12:00:00.000Z'),
logger: {
info: vi.fn(() => {}),
warn: vi.fn(() => {}),
@@ -1395,7 +1403,14 @@ describe('boot-time stale versionPendingInstall reconciliation', () => {
// ————————————————————————————————————————————————————————
describe('boot-time failed-install detection', () => {
- test('attempted not reached (same-MMP beta) → relaunch-failed w/ downloadUrl, re-arm, stays armed', () => {
+ // Fail-closed case: this fixture carries no staging/handoff timestamps, so
+ // the boot has no basis for judging whether the install could still be
+ // running (legacy or corrupt `state.json` — every path that arms
+ // `attemptedInstall` also stamps `versionPendingInstallStagedAt`). With no
+ // timing to defer to, the detector still speaks. The complementary case —
+ // an attempt whose handoff IS on record and is recent enough that the
+ // install may still be in flight — lives in its own describe block below.
+ test('attempted not reached, no handoff timing on record (same-MMP beta) → relaunch-failed w/ downloadUrl, re-arm, stays armed', () => {
const { rig } = makeRig({
attemptedInstall: '0.16.0-beta.3',
appVersion: '0.16.0-beta.1',
@@ -1798,6 +1813,665 @@ describe('boot-time failed-install detection', () => {
expect(state.attemptedInstall).toBe('0.16.0-beta.3');
expect(dispatches).not.toContain('attempted-install-reconciled' as DispatchKind);
});
+
+ test('retiring the attempted-install record retires its handoff moment with it', () => {
+ // The moment and the spent hold both date exactly one armed attempt. Every
+ // branch that retires the attempt has to retire them alongside it, or the
+ // record outlives the thing it describes: whatever reads it next is dating
+ // an attempt that no longer exists, and the next attempt inherits a hold it
+ // never spent. Seeded far enough in the past that the in-flight tolerance
+ // cannot swallow the boot before it reaches the give-up branch.
+ const STALE_HANDOFF = new Date('2026-04-20T12:00:00.000Z').getTime();
+
+ // Reconciled as a success: the running version caught up to the attempt.
+ const { rig: reconciled } = makeRig({
+ attemptedInstall: '0.16.0-beta.3',
+ appVersion: '0.16.0-beta.3',
+ attemptedInstallHandoffAt: STALE_HANDOFF,
+ attemptedInstallDeferredBoots: 2,
+ });
+ expect(reconciled.dispatches).toContain('attempted-install-reconciled' as DispatchKind);
+ expect(reconciled.state.attemptedInstall).toBeNull();
+ expect(reconciled.state.attemptedInstallHandoffAt).toBeNull();
+ expect(reconciled.state.attemptedInstallDeferredBoots).toBe(0);
+
+ // Cross-channel residue: this build can never reach the attempt at all.
+ const { rig: crossChannel } = makeRig({
+ attemptedInstall: '0.23.0-beta.5',
+ appVersion: '0.22.0',
+ attemptedInstallHandoffAt: STALE_HANDOFF,
+ attemptedInstallDeferredBoots: 2,
+ });
+ expect(crossChannel.dispatches).toContain('attempted-install-cross-channel' as DispatchKind);
+ expect(crossChannel.state.attemptedInstall).toBeNull();
+ expect(crossChannel.state.attemptedInstallHandoffAt).toBeNull();
+ expect(crossChannel.state.attemptedInstallDeferredBoots).toBe(0);
+
+ // Retry budget exhausted: the notice has said its piece and the record goes.
+ const { rig: gaveUp } = makeRig({
+ attemptedInstall: '0.17.0-beta.1',
+ appVersion: '0.16.0-beta.1',
+ attemptedInstallSurfacedCount: INSTALL_FAILURE_MAX_SURFACES,
+ attemptedInstallHandoffAt: STALE_HANDOFF,
+ attemptedInstallDeferredBoots: 2,
+ });
+ expect(gaveUp.dispatches).toContain('install-failed-giveup' as DispatchKind);
+ expect(gaveUp.state.attemptedInstall).toBeNull();
+ expect(gaveUp.state.attemptedInstallHandoffAt).toBeNull();
+ expect(gaveUp.state.attemptedInstallDeferredBoots).toBe(0);
+ });
+});
+
+// ————————————————————————————————————————————————————————
+// Boot-time failed-install detection vs. an install that may STILL BE RUNNING.
+//
+// On macOS the swap happens after the app exits, inside a separate ShipIt
+// process, and it is not instantaneous — successful installs have been observed
+// taking anywhere from ~1s to ~4.5 minutes. Reopening the app inside that window
+// boots the OLD version, which is the EXPECTED state mid-install, not evidence
+// of failure. It is also self-fulfilling: the reopen is what trips ShipIt's
+// final "the target app is not running" check, and an aborted request re-stages,
+// so the update being declared dead would have installed on the next quit.
+//
+// So the verdict has to separate "not reached, and no install for this attempt
+// can still be running" from "not reached, install may still be in flight".
+// These tests drive the commit through the production write paths
+// (`update-downloaded`, then either the `relaunch-now` IPC handler or
+// install-on-quit) and then boot, so they pin the OUTCOME rather than whichever
+// record the handoff happens to leave behind.
+// ————————————————————————————————————————————————————————
+
+describe('boot-time failed-install detection — install still in flight', () => {
+ const RUNNING = '0.53.0-beta.0';
+ const ATTEMPTED = '0.54.0-beta.0';
+ /** Download completes: the artifact is staged and the install is requestable. */
+ const STAGED_AT = new Date('2026-08-12T00:24:18.000Z');
+ /**
+ * The handoff: ~16 min after staging the session ends and the install is
+ * committed — by clicking "Relaunch now", or by quitting with install-on-quit
+ * armed. Both paths reach it the same way, so the fixtures below share it.
+ */
+ const HANDED_OFF_AT = new Date('2026-08-12T00:40:04.000Z');
+ const SECOND = 1_000;
+ const MINUTE = 60 * SECOND;
+ const HOUR = 60 * MINUTE;
+
+ /**
+ * The pre-update session: stage the update, then end the session the way that
+ * commits the install — the "Relaunch now" click, or a plain quit that
+ * install-on-quit commits on. `'unobserved-quit'` ends the session without
+ * either, modelling the commits no live process gets to record: a force-quit,
+ * a power loss, or a `state.json` written by a build predating the quit stamp.
+ * Returns the `state.json` that boot reads.
+ *
+ * `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(
+ via: 'relaunch-click' | 'plain-quit' | 'unobserved-quit',
+ overrides: { running?: string; attempted?: string; committedAt?: Date } = {},
+ ): AppState {
+ const { rig, handle } = makeRig({
+ appVersion: overrides.running ?? RUNNING,
+ platform: 'darwin',
+ });
+ 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');
+ else if (via === 'plain-quit') handle.recordInstallHandoffOnQuit();
+ return rig.state;
+ }
+
+ /** The reopen: a fresh boot on the pre-update version at a given wall clock. */
+ function reopenAt(state: AppState, at: Date, running: string = RUNNING): TestRig {
+ const { rig } = makeRig({ ...state, appVersion: running, platform: 'darwin', nowAt: at });
+ return rig;
+ }
+
+ const failureCards = (rig: TestRig): CapturedSend[] =>
+ rig.captured.filter((c) => c.channel === 'ok:update:relaunch-failed');
+
+ /**
+ * A reopen the user does not stay in: boot, let the launch check re-fire
+ * electron-updater's cached `update-downloaded`, then quit — which commits
+ * the same staged artifact all over again. `reopenAt` models the boots that
+ * only need a verdict; this models the cycle someone waiting on an install
+ * actually produces, where the re-fire and the quit between two boots rewrite
+ * the timing a verdict would otherwise reason from.
+ */
+ function reopenAndQuit(
+ state: AppState,
+ at: Date,
+ versions: { running: string; attempted: string },
+ ): TestRig {
+ const { rig, handle } = makeRig({
+ ...state,
+ appVersion: versions.running,
+ platform: 'darwin',
+ nowAt: at,
+ });
+ rig.now = new Date(at.getTime() + 10 * SECOND);
+ rig.updater.emit('update-downloaded', { version: versions.attempted });
+ rig.now = new Date(at.getTime() + 20 * SECOND);
+ handle.recordInstallHandoffOnQuit();
+ return rig;
+ }
+
+ test('reopened while the handed-off install may still be running → no failure verdict', () => {
+ // 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'),
+ new Date(HANDED_OFF_AT.getTime() + 62 * SECOND),
+ );
+
+ expect(failureCards(rig)).toHaveLength(0);
+ // The deferral branch specifically, not merely the absence of a verdict:
+ // an accidental no-op that reached neither branch would satisfy every
+ // assertion below.
+ expect(rig.dispatches).toContain('install-in-flight-deferred' as DispatchKind);
+ expect(rig.dispatches).not.toContain('install-failed-on-boot' as DispatchKind);
+ // Nothing about the attempt is consumed: the banner gate stays clear (the
+ // click cleared it, and there is no failure to offer a Retry for yet) and
+ // the surfacing budget is untouched.
+ expect(rig.state.versionPendingInstall).toBeNull();
+ expect(rig.state.attemptedInstallSurfacedCount).toBe(0);
+ // The record stays armed — the verdict is deferred, not decided. A later
+ // boot still reconciles it, as success or as failure.
+ expect(rig.state.attemptedInstall).toBe(ATTEMPTED);
+ });
+
+ test('reopened deep in the observed install-duration range → still no failure verdict', () => {
+ // 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'),
+ new Date(HANDED_OFF_AT.getTime() + 4 * MINUTE),
+ );
+
+ expect(failureCards(rig)).toHaveLength(0);
+ expect(rig.dispatches).toContain('install-in-flight-deferred' as DispatchKind);
+ expect(rig.dispatches).not.toContain('install-failed-on-boot' as DispatchKind);
+ expect(rig.state.attemptedInstallSurfacedCount).toBe(0);
+ });
+
+ test('reopened long after the handoff → the failure notice still fires', () => {
+ // 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'),
+ new Date(HANDED_OFF_AT.getTime() + 24 * HOUR),
+ );
+
+ expect(failureCards(rig)).toHaveLength(1);
+ expect(failureCards(rig)[0]?.payload).toEqual({
+ version: ATTEMPTED,
+ downloadUrl: STUCK_HINT_DOWNLOAD_URL,
+ });
+ expect(rig.dispatches).toContain('install-failed-on-boot' as DispatchKind);
+ expect(rig.state.versionPendingInstall).toBe(ATTEMPTED);
+ expect(rig.state.attemptedInstallSurfacedCount).toBe(1);
+ });
+
+ test('reopened moments after a plain quit committed the install → no failure verdict', () => {
+ // 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'),
+ new Date(HANDED_OFF_AT.getTime() + 45 * SECOND),
+ );
+
+ expect(failureCards(rig)).toHaveLength(0);
+ expect(rig.dispatches).toContain('install-in-flight-deferred' as DispatchKind);
+ expect(rig.dispatches).not.toContain('install-failed-on-boot' as DispatchKind);
+ expect(rig.state.attemptedInstallSurfacedCount).toBe(0);
+ expect(rig.state.attemptedInstall).toBe(ATTEMPTED);
+ });
+
+ test('a session between the staging and the plain quit is not charged against the install', () => {
+ // 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 }),
+ new Date(QUIT_AT.getTime() + 1 * MINUTE),
+ );
+
+ expect(failureCards(rig)).toHaveLength(0);
+ expect(rig.dispatches).toContain('install-in-flight-deferred' as DispatchKind);
+ expect(rig.dispatches).not.toContain('install-failed-on-boot' as DispatchKind);
+ expect(rig.state.attemptedInstallSurfacedCount).toBe(0);
+ expect(rig.state.attemptedInstall).toBe(ATTEMPTED);
+ });
+
+ test('reopened a day after a plain quit committed the install → the failure notice still fires', () => {
+ const rig = reopenAt(
+ stageAndCommit('plain-quit'),
+ new Date(HANDED_OFF_AT.getTime() + 24 * HOUR),
+ );
+
+ expect(failureCards(rig)).toHaveLength(1);
+ expect(rig.dispatches).toContain('install-failed-on-boot' as DispatchKind);
+ });
+
+ test('a commit no live process observed falls back to the staging moment', () => {
+ // 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'),
+ new Date(STAGED_AT.getTime() + 45 * SECOND),
+ );
+
+ expect(rig.state.attemptedInstallHandoffAt).toBeNull();
+ expect(failureCards(rig)).toHaveLength(0);
+ expect(rig.dispatches).toContain('install-in-flight-deferred' as DispatchKind);
+ expect(rig.state.attemptedInstallSurfacedCount).toBe(0);
+ // The log says which moment the verdict leaned on, so a field report can be
+ // read without guessing whether the tolerance was the full window or
+ // whatever was left of it after the artifact sat staged.
+ expect(rig.logger.info).toHaveBeenCalledWith(
+ expect.stringContaining('defer'),
+ expect.objectContaining({ recordedHandoff: false, handoffAt: STAGED_AT.getTime() }),
+ );
+ });
+
+ test('an unobserved commit long after the staging still fires the notice', () => {
+ const rig = reopenAt(
+ stageAndCommit('unobserved-quit'),
+ new Date(STAGED_AT.getTime() + 24 * HOUR),
+ );
+
+ expect(failureCards(rig)).toHaveLength(1);
+ expect(rig.dispatches).toContain('install-failed-on-boot' as DispatchKind);
+ });
+
+ test('the uninstall quit claims no handoff', () => {
+ // 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
+ // record would defer a verdict for an install that was never handed off.
+ const { rig, handle } = makeRig({ appVersion: RUNNING, platform: 'darwin' });
+ rig.now = STAGED_AT;
+ rig.updater.emit('update-downloaded', { version: ATTEMPTED });
+ handle.suppressAutoInstallOnQuit();
+ rig.now = HANDED_OFF_AT;
+ handle.recordInstallHandoffOnQuit();
+
+ expect(rig.state.attemptedInstallHandoffAt).toBeNull();
+ expect(rig.state.attemptedInstallStagingAgeMs).toBeNull();
+ });
+
+ test('a quit re-handing off an attempt does not buy it a fresh window', () => {
+ // 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 { rig, handle } = makeRig({ ...state, appVersion: RUNNING, platform: 'darwin' });
+ rig.now = new Date(HANDED_OFF_AT.getTime() + 25 * MINUTE);
+ handle.recordInstallHandoffOnQuit();
+
+ expect(rig.state.attemptedInstallHandoffAt).toBe(HANDED_OFF_AT.getTime());
+ expect(rig.state.attemptedInstallStagingAgeMs).toBe(
+ HANDED_OFF_AT.getTime() - STAGED_AT.getTime(),
+ );
+
+ const later = reopenAt(rig.state, new Date(HANDED_OFF_AT.getTime() + 31 * MINUTE));
+ expect(failureCards(later)).toHaveLength(1);
+ expect(later.dispatches).toContain('install-failed-on-boot' as DispatchKind);
+ });
+
+ test('deferring does not spend the surfacing budget', () => {
+ // 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');
+ const first = reopenAt(state, new Date(HANDED_OFF_AT.getTime() + 20 * SECOND));
+ expect(failureCards(first)).toHaveLength(0);
+ state = first.state;
+
+ const second = reopenAt(state, new Date(HANDED_OFF_AT.getTime() + 90 * SECOND));
+ expect(failureCards(second)).toHaveLength(0);
+ state = second.state;
+
+ const later = reopenAt(state, new Date(HANDED_OFF_AT.getTime() + 24 * HOUR));
+ expect(failureCards(later)).toHaveLength(1);
+ expect(later.state.attemptedInstallSurfacedCount).toBe(1);
+ });
+
+ test('an install that never lands is reported even when every reopen looks fresh', () => {
+ // 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
+ // handoff, and the next quit stamps a new one. So a broken install plus a
+ // user who reopens within the tolerance every time is deferred on the
+ // timing forever, and the notice the whole detector exists to deliver never
+ // arrives. Something has to count the holds and stop them.
+ //
+ // Driven on a same-major.minor.patch beta bump — the dominant shape an OK
+ // update takes, and the one where the re-fire re-arms on EVERY boot: the
+ // stale-pending reconciliation compares major.minor.patch only, so each
+ // boot strips the pending gate the dedupe would otherwise catch on.
+ const RUNNING_BETA = '0.54.0-beta.0';
+ const ATTEMPTED_BETA = '0.54.0-beta.1';
+ const versions = { running: RUNNING_BETA, attempted: ATTEMPTED_BETA };
+
+ let state = 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
+ // from the healthy mid-install reopens above.
+ for (let cycle = 1; cycle <= 3; cycle++) {
+ const rig = reopenAndQuit(state, reopenedAt, versions);
+ expect(failureCards(rig)).toHaveLength(0);
+ expect(rig.dispatches).toContain('install-in-flight-deferred' as DispatchKind);
+ expect(rig.state.attemptedInstallSurfacedCount).toBe(0);
+ // The premise the bound exists for. If a future change makes the re-fire
+ // dedupe here, the handoff would age by itself and these cycles would
+ // stop exercising the hazard.
+ expect(rig.dispatches).not.toContain('update-downloaded-deduped' as DispatchKind);
+ expect(rig.state.attemptedInstallHandoffAt).toBe(reopenedAt.getTime() + 20 * SECOND);
+ state = rig.state;
+ reopenedAt = new Date(reopenedAt.getTime() + 1 * MINUTE);
+ }
+
+ // The next reopen is timed exactly like the three before it, and it is the
+ // one that finally tells the user.
+ const reported = reopenAt(state, reopenedAt, RUNNING_BETA);
+ expect(failureCards(reported)).toHaveLength(1);
+ expect(failureCards(reported)[0]?.payload).toEqual({
+ version: ATTEMPTED_BETA,
+ downloadUrl: STUCK_HINT_DOWNLOAD_URL,
+ });
+ expect(reported.dispatches).toContain('install-failed-on-boot' as DispatchKind);
+ expect(reported.dispatches).not.toContain('install-in-flight-deferred' as DispatchKind);
+ expect(reported.state.attemptedInstallSurfacedCount).toBe(1);
+ // And it fired for the right reason: the handoff on record was 40 seconds
+ // old, deep inside the window every earlier boot deferred on. The verdict
+ // came from the exhausted hold, not from a clock that finally ran out.
+ expect(reported.logger.warn).toHaveBeenCalledWith(
+ expect.stringContaining('did not take'),
+ expect.objectContaining({ handoffAgeMs: 40 * SECOND }),
+ );
+ });
+
+ test('a boot that cannot record the hold still holds', () => {
+ // 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 captured: CapturedSend[] = [];
+ const dispatches: DispatchKind[] = [];
+ startAutoUpdater({
+ updater: new FakeUpdater(),
+ ipcMain: makeFakeIpc(),
+ readState: () => state,
+ writeState: () => {
+ throw new Error('EACCES');
+ },
+ getPrimaryWindow: () => makeFakeWindow(captured),
+ getAppVersion: () => RUNNING,
+ isPackaged: true,
+ platform: 'darwin',
+ clock: makeFakeClock(),
+ now: () => new Date(HANDED_OFF_AT.getTime() + 62 * SECOND),
+ onDispatch: (k) => dispatches.push(k),
+ logger: {
+ info: vi.fn(() => {}),
+ warn: vi.fn(() => {}),
+ error: vi.fn(() => {}),
+ debug: vi.fn(() => {}),
+ },
+ });
+
+ expect(captured.filter((c) => c.channel === 'ok:update:relaunch-failed')).toHaveLength(0);
+ expect(dispatches).toContain('install-in-flight-deferred' as DispatchKind);
+ expect(dispatches).not.toContain('install-failed-on-boot' as DispatchKind);
+ expect(state.attemptedInstallDeferredBoots).toBe(0);
+ });
+
+ test('a newly attempted version gets its own hold, a re-armed one keeps the old', () => {
+ // 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
+ // is what wipes the handoff moment. A genuinely new version is a different
+ // install, and starts from a full hold: charging it for the last one's
+ // failures would condemn a healthy install mid-swap.
+ const RUNNING_BETA = '0.54.0-beta.0';
+ const ATTEMPTED_BETA = '0.54.0-beta.1';
+ const versions = { running: RUNNING_BETA, attempted: ATTEMPTED_BETA };
+
+ let state = 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);
+ expect(failureCards(rig)).toHaveLength(0);
+ state = rig.state;
+ reopenedAt = new Date(reopenedAt.getTime() + 1 * MINUTE);
+ }
+ // The hold is spent: another reopen on this attempt would report it.
+ expect(failureCards(reopenAt(state, reopenedAt, RUNNING_BETA))).toHaveLength(1);
+
+ // A newer version arrives and is committed by the quit that follows.
+ const NEXT = '0.55.0-beta.0';
+ const { rig: restaged, handle } = makeRig({
+ ...state,
+ appVersion: RUNNING_BETA,
+ platform: 'darwin',
+ nowAt: reopenedAt,
+ });
+ restaged.now = new Date(reopenedAt.getTime() + 1 * MINUTE);
+ restaged.updater.emit('update-downloaded', { version: NEXT });
+ expect(restaged.state.attemptedInstall).toBe(NEXT);
+ restaged.now = new Date(reopenedAt.getTime() + 2 * MINUTE);
+ handle.recordInstallHandoffOnQuit();
+
+ // Reopened mid-swap, exactly like the impatient reopens the deferral was
+ // built for — and it is deferred, because this attempt has its own hold.
+ const fresh = reopenAt(
+ restaged.state,
+ new Date(reopenedAt.getTime() + 3 * MINUTE),
+ RUNNING_BETA,
+ );
+ expect(failureCards(fresh)).toHaveLength(0);
+ expect(fresh.dispatches).toContain('install-in-flight-deferred' as DispatchKind);
+ expect(fresh.state.attemptedInstall).toBe(NEXT);
+ });
+
+ test('a handoff the clock cannot make sense of → fail closed, the notice fires', () => {
+ // `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'),
+ new Date(HANDED_OFF_AT.getTime() - 1 * HOUR),
+ );
+
+ expect(failureCards(rig)).toHaveLength(1);
+ expect(rig.dispatches).toContain('install-failed-on-boot' as DispatchKind);
+ });
+
+ test('same-MMP beta bump committed by a plain quit → no failure verdict', () => {
+ // 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
+ // major.minor.patch only, so a running 0.54.0-beta.0 reads as having caught
+ // up to a pending 0.54.0-beta.1 and the staging stamp is cleared — while the
+ // prerelease-aware verdict immediately after still sees an install that
+ // never landed. Whatever the verdict reasons from has to survive that clear,
+ // or this path goes on condemning healthy installs after every other path
+ // is fixed.
+ 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 }),
+ new Date(HANDED_OFF_AT.getTime() + 45 * SECOND),
+ RUNNING_BETA,
+ );
+
+ // The premise: this boot really does take the clearing path. If a future
+ // change stops it firing here, the fixture has drifted off the hazard and
+ // the assertions below would pass for the wrong reason.
+ expect(rig.dispatches).toContain('stale-pending-cleared' as DispatchKind);
+
+ expect(failureCards(rig)).toHaveLength(0);
+ expect(rig.dispatches).toContain('install-in-flight-deferred' as DispatchKind);
+ expect(rig.dispatches).not.toContain('install-failed-on-boot' as DispatchKind);
+ expect(rig.state.attemptedInstallSurfacedCount).toBe(0);
+ expect(rig.state.attemptedInstall).toBe(ATTEMPTED_BETA);
+ });
+
+ test('a same-MMP beta bump survives a SECOND reopen inside the window', () => {
+ // 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
+ // the first boot already stripped. Impatience is repetitive — the user who
+ // reopens once mid-install reopens again — so a tolerance that only holds
+ // for one boot condemns the same healthy install on the next.
+ 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 }),
+ new Date(HANDED_OFF_AT.getTime() + 45 * SECOND),
+ RUNNING_BETA,
+ );
+ expect(first.dispatches).toContain('stale-pending-cleared' as DispatchKind);
+ expect(failureCards(first)).toHaveLength(0);
+
+ const second = reopenAt(
+ first.state,
+ new Date(HANDED_OFF_AT.getTime() + 3 * MINUTE),
+ RUNNING_BETA,
+ );
+
+ expect(failureCards(second)).toHaveLength(0);
+ expect(second.dispatches).toContain('install-in-flight-deferred' as DispatchKind);
+ expect(second.dispatches).not.toContain('install-failed-on-boot' as DispatchKind);
+ expect(second.state.attemptedInstallSurfacedCount).toBe(0);
+ });
+
+ test('a long wait before the click is measured from the click, not from the staging', () => {
+ // 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
+ // of how long an install takes: a click that landed sixty seconds ago gets
+ // 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 }),
+ new Date(CLICKED_AT.getTime() + 1 * MINUTE),
+ );
+
+ expect(failureCards(rig)).toHaveLength(0);
+ expect(rig.dispatches).toContain('install-in-flight-deferred' as DispatchKind);
+ expect(rig.dispatches).not.toContain('install-failed-on-boot' as DispatchKind);
+ expect(rig.state.attemptedInstallSurfacedCount).toBe(0);
+ expect(rig.state.attemptedInstall).toBe(ATTEMPTED);
+ });
+
+ test('a deferred boot records how long ago the install was handed off, and from what', () => {
+ // 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 —
+ // the number that separates a verdict held too eagerly from one held
+ // correctly. The derived age alone cannot be audited: the two moments it
+ // 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'),
+ new Date(HANDED_OFF_AT.getTime() + 62 * SECOND),
+ );
+
+ expect(rig.logger.info).toHaveBeenCalledWith(
+ expect.stringContaining('defer'),
+ expect.objectContaining({
+ attempted: ATTEMPTED,
+ handoffAgeMs: 62 * SECOND,
+ handoffAt: HANDED_OFF_AT.getTime(),
+ recordedHandoff: true,
+ stagingAgeMs: HANDED_OFF_AT.getTime() - STAGED_AT.getTime(),
+ }),
+ );
+ });
+
+ test('a boot ten minutes after the handoff still defers', () => {
+ // 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'),
+ new Date(HANDED_OFF_AT.getTime() + 10 * MINUTE),
+ );
+
+ expect(failureCards(rig)).toHaveLength(0);
+ expect(rig.dispatches).toContain('install-in-flight-deferred' as DispatchKind);
+ expect(rig.state.attemptedInstallSurfacedCount).toBe(0);
+ });
+
+ test('a boot two hours after the handoff fires the notice', () => {
+ // 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
+ // install in the morning and reopens through the day would be told nothing
+ // 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'),
+ new Date(HANDED_OFF_AT.getTime() + 2 * HOUR),
+ );
+
+ expect(failureCards(rig)).toHaveLength(1);
+ 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', () => {
+ // 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
+ // attempt already handed off", so the quit that actually commits the new
+ // install never stamps anything and the new install is dated to whenever the
+ // OLD one was committed — by then old enough to be condemned on reopen.
+ const NEXT = '0.55.0-beta.0';
+ const RESTAGED_AT = new Date(HANDED_OFF_AT.getTime() + 5 * HOUR);
+ const REQUIT_AT = new Date(RESTAGED_AT.getTime() + 10 * MINUTE);
+
+ const { rig, handle } = makeRig({ appVersion: RUNNING, platform: 'darwin' });
+ rig.now = STAGED_AT;
+ rig.updater.emit('update-downloaded', { version: ATTEMPTED });
+ rig.now = HANDED_OFF_AT;
+ handle.recordInstallHandoffOnQuit();
+
+ rig.now = RESTAGED_AT;
+ rig.updater.emit('update-downloaded', { version: NEXT });
+ expect(rig.state.attemptedInstall).toBe(NEXT);
+ expect(rig.state.attemptedInstallHandoffAt).toBeNull();
+
+ // Which is what leaves the quit that commits the new artifact free to stamp
+ // its own moment.
+ rig.now = REQUIT_AT;
+ handle.recordInstallHandoffOnQuit();
+ expect(rig.state.attemptedInstallHandoffAt).toBe(REQUIT_AT.getTime());
+
+ const reopened = reopenAt(rig.state, new Date(REQUIT_AT.getTime() + 45 * SECOND));
+ expect(failureCards(reopened)).toHaveLength(0);
+ expect(reopened.dispatches).toContain('install-in-flight-deferred' as DispatchKind);
+ expect(reopened.dispatches).not.toContain('install-failed-on-boot' as DispatchKind);
+ });
});
describe('installReached (prerelease-aware compare)', () => {