:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(desktop): keep polling after an update is staged (#76331)
Charles Vien044fdb51cb1b
diff --git a/.github/workflows/desktop-update-e2e.yml b/.github/workflows/desktop-update-e2e.ymlindex 02b587e5afa6..84addace861f 100644--- a/.github/workflows/desktop-update-e2e.yml+++ b/.github/workflows/desktop-update-e2e.yml@@ -6,9 +6,13 @@ name: Desktop Update E2E (macOS)# installed app became 2.0.0. Nightly and on demand only, never on PRs: it builds# twice and exercises a real install, so it is too slow and too flaky for the gate.#-# Two legs run against the same new (2.0.0) feed:-# 1. electron-builder -> electron-builder: the forward-compatibility baseline.-# 2. Forge -> electron-builder: a real Electron Forge build (v0.55.132, the last+# Three legs run:+# 1. electron-builder -> electron-builder: the forward-compatibility baseline+# against the new (2.0.0) feed.+# 2. Chained re-stage: with 2.0.0 already staged, the feed bumps to 3.0.0 and+# the background poll downloads and re-stages it; the restart must land on+# 3.0.0. Proves replacing a staged Squirrel.Mac update is safe.+# 3. Forge -> electron-builder: a real Electron Forge build (v0.55.132, the last# Forge release, what users run today) updating via the genuine built-in# Squirrel.Mac client to the electron-builder build we ship now.@@ -105,8 +109,10 @@ jobs:pnpm --filter @posthog/harness run buildpnpm --filter @posthog/agent run build- - name: Build old + new update pair+ - name: Build old + new update pair (and 3.0.0 chain feed)working-directory: products/desktop/apps/code+ env:+ CHAIN_VERSION: '3.0.0'run: bash scripts/dev-update/build-pair.sh- name: Install Playwright@@ -128,6 +134,24 @@ jobs:}'+ # Chained re-stage leg: reuses the same old app and feeds built above, so+ # it only costs one more download/install cycle, not another build.+ - name: Run macOS chained update E2E+ working-directory: products/desktop/apps/code+ env:+ PLAYWRIGHT_JSON_OUTPUT_NAME: ${{ github.workspace }}/products/desktop/apps/code/out/update-chain-report.json+ run: |+ pnpm exec playwright test --config=tests/e2e/playwright.update-chain.config.ts+ node -e '+ const r = require(process.env.GITHUB_WORKSPACE + "/products/desktop/apps/code/out/update-chain-report.json");+ const s = r.stats || {};+ console.log("chain update e2e stats:", JSON.stringify(s));+ if (s.expected !== 1 || s.skipped || s.unexpected || s.flaky) {+ console.error("FAIL: expected exactly one passing chained update test");+ process.exit(1);+ }+ '+# Forge -> electron-builder leg. The old Forge app is a fixed pinned build# (cb0ca68db), byte-identical on every run, so cache it and skip the ~11 min# rebuild that dominates this job. The key tracks the build script, which@@ -182,6 +206,7 @@ jobs:const fs = require("fs");const proofs = [["out/update-proof/proof.json", "macOS auto-update proof (builder -> builder)"],+ ["out/update-proof-chain/proof.json", "macOS auto-update proof (chained re-stage)"],["out/update-proof-forge/proof.json", "macOS auto-update proof (Forge -> builder)"],];const cell = (v) => v === undefined || v === null ? "-" : String(v).replace(/\|/g, "\\|").replace(/\n/g, " ");@@ -194,6 +219,8 @@ jobs:["New version", d.newVersion],["Booted on", d.bootedOn],["Feed offered", d.feedAvailableVersion],+ ["Intermediate version", d.intermediateVersion],+ ["Re-staged version", d.restagedVersion],["Downloaded", d.downloaded],["Bundle after swap", d.bundleVersionAfterSwap],["Auto-relaunched exe", d.autoRelaunchedExecutable],@@ -218,12 +245,18 @@ jobs:name: update-e2e-macospath: |products/desktop/apps/code/out/update-proof/+ products/desktop/apps/code/out/update-proof-chain/products/desktop/apps/code/out/update-proof-forge/products/desktop/apps/code/out/update-report.json+ products/desktop/apps/code/out/update-chain-report.jsonproducts/desktop/apps/code/out/update-forge-report.jsonproducts/desktop/apps/code/playwright-results//Users/runner/.posthog-code/logs//Users/runner/Library/Caches/com.posthog.array.ShipIt/+ !/Users/runner/Library/Caches/com.posthog.array.ShipIt/update.*/**+ # The app log dir lives under hidden ~/.posthog-code and is silently+ # dropped without this.+ include-hidden-files: trueif-no-files-found: ignoreretention-days: 7diff --git a/products/desktop/apps/code/scripts/dev-update/build-pair.sh b/products/desktop/apps/code/scripts/dev-update/build-pair.shindex 029ed5a74fc1..77127c25b30c 100644--- a/products/desktop/apps/code/scripts/dev-update/build-pair.sh+++ b/products/desktop/apps/code/scripts/dev-update/build-pair.sh@@ -2,19 +2,36 @@# Build a signed OLD (1.0.0) app to run plus a signed NEW (2.0.0) feed for the# macOS auto-update E2E. Real signing needs CSC_LINK (set in CI); locally it uses# whatever identity electron-builder finds. Run from apps/code.+#+# Set CHAIN_VERSION (e.g. 3.0.0) to also build a second, newer feed into+# out/dev-update-feed-chain for the chained update E2E (update-chain.spec.ts).set -euo pipefailcd "$(dirname "$0")/../.."OLD_VERSION="${OLD_VERSION:-1.0.0}"NEW_VERSION="${NEW_VERSION:-2.0.0}"+CHAIN_VERSION="${CHAIN_VERSION:-}"FEED_DIR="out/dev-update-feed"+CHAIN_FEED_DIR="out/dev-update-feed-chain"export SKIP_NOTARIZE="${SKIP_NOTARIZE:-1}"echo "==> electron-vite build"pnpm exec electron-vite build+if [[ -n "$CHAIN_VERSION" ]]; then+ echo "==> build CHAIN $CHAIN_VERSION (second feed artifacts)"+ pnpm exec electron-builder build --mac zip --arm64 --publish never \+ -c.extraMetadata.version="$CHAIN_VERSION" --config electron-builder.ts++ rm -rf "$CHAIN_FEED_DIR"+ mkdir -p "$CHAIN_FEED_DIR"+ cp "out/PostHog-Code-${CHAIN_VERSION}-arm64-mac.zip" "$CHAIN_FEED_DIR/"+ cp "out/PostHog-Code-${CHAIN_VERSION}-arm64-mac.zip.blockmap" "$CHAIN_FEED_DIR/"+ cp "out/latest-mac.yml" "$CHAIN_FEED_DIR/"+fi+echo "==> build NEW $NEW_VERSION (feed artifacts)"pnpm exec electron-builder build --mac zip --arm64 --publish never \-c.extraMetadata.version="$NEW_VERSION" --config electron-builder.ts@@ -30,4 +47,7 @@ pnpm exec electron-builder build --mac zip --arm64 --publish never \-c.extraMetadata.version="$OLD_VERSION" --config electron-builder.tsecho "==> feed=$FEED_DIR"+if [[ -n "$CHAIN_VERSION" ]]; then+ echo "==> chain feed=$CHAIN_FEED_DIR ($CHAIN_VERSION)"+fiecho "==> app=out/mac-arm64/PostHog.app ($OLD_VERSION)"diff --git a/products/desktop/apps/code/src/main/index.ts b/products/desktop/apps/code/src/main/index.tsindex 38545ed82693..21709c56aa2e 100644--- a/products/desktop/apps/code/src/main/index.ts+++ b/products/desktop/apps/code/src/main/index.ts@@ -438,9 +438,14 @@ app.whenReady().then(async () => {if (process.env.POSTHOG_E2E_UPDATE_FEED) {const updates = container.get<UpdatesService>(UPDATES_SERVICE);+ // Pin the re-staging rollout on: the packaged e2e app boots posthog with+ // an anonymous user whose flags would otherwise sync this off mid-test.+ updates.setStagedUpdatesEnabled(true);+ updates.setStagedUpdatesEnabled = () => {};Object.assign(globalThis, {__e2eUpdates: {check: () => updates.checkForUpdates(),+ periodicCheck: () => updates.checkForUpdates("periodic"),download: () => updates.requestDownload(),install: () => updates.installUpdate(),status: () => updates.getStatus(),diff --git a/products/desktop/apps/code/src/main/platform-adapters/electron-updater.ts b/products/desktop/apps/code/src/main/platform-adapters/electron-updater.tsindex b47a34abdc37..8a26a4f90f09 100644--- a/products/desktop/apps/code/src/main/platform-adapters/electron-updater.ts+++ b/products/desktop/apps/code/src/main/platform-adapters/electron-updater.ts@@ -35,9 +35,8 @@ export class ElectronUpdater implements IUpdater {constructor() {autoUpdater.logger = log;autoUpdater.disableDifferentialDownload = true;- // Default to manual download; the "Download updates automatically" setting- // flips this via setAutoDownload(). A downloaded update always installs on the- // next quit, with an in-app Restart button for immediate install.+ // Must stay false: UpdatesService is the sole caller of download(). If true,+ // every checkForUpdates() poll re-downloads and re-stages the same build.autoUpdater.autoDownload = false;autoUpdater.autoInstallOnAppQuit = true;@@ -62,18 +61,19 @@ export class ElectronUpdater implements IUpdater {void autoUpdater.checkForUpdates().catch(() => undefined);}- public download(): void {- void autoUpdater.downloadUpdate().catch(() => undefined);+ // Failures surface through the "error" event; the returned promise only+ // signals settlement so the service can serialize downloads.+ public download(): Promise<void> {+ return autoUpdater.downloadUpdate().then(+ () => undefined,+ () => undefined,+ );}public quitAndInstall(): void {autoUpdater.quitAndInstall(false, true);}- public setAutoDownload(enabled: boolean): void {- autoUpdater.autoDownload = enabled;- }-public onCheckStart(handler: () => void): () => void {autoUpdater.on("checking-for-update", handler);return () => autoUpdater.off("checking-for-update", handler);diff --git a/products/desktop/apps/code/src/renderer/platform-adapters/updates.ts b/products/desktop/apps/code/src/renderer/platform-adapters/updates.tsindex 360ea74fad23..d3aee30baafc 100644--- a/products/desktop/apps/code/src/renderer/platform-adapters/updates.ts+++ b/products/desktop/apps/code/src/renderer/platform-adapters/updates.ts@@ -6,6 +6,7 @@ import {updateStore,} from "@posthog/core/updates/updateStore";import { resolveService } from "@posthog/di/container";+import { STAGED_UPDATES_FLAG } from "@posthog/shared";import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";import {UPDATES_CLIENT,@@ -14,6 +15,7 @@ import {import { useWhatsNewStore } from "@posthog/ui/features/updates/whatsNewStore";import { toast } from "@posthog/ui/primitives/toast";import { logger } from "@posthog/ui/shell/logger";+import { posthogFeatureFlags } from "@posthog/ui/shell/posthogAnalyticsImpl";import { hostTrpcClient } from "@renderer/trpc/client";const log = logger.scope("updates-host");@@ -129,6 +131,25 @@ function syncAutoDownload(enabled: boolean): void {);}+// Bridge the staged-updates rollout flag to the core updater; the service+// defaults to off until posthog flags load and this sync lands.+let lastSyncedStagedUpdates: boolean | null = null;+function syncStagedUpdates(): void {+ const enabled = posthogFeatureFlags.isEnabled(STAGED_UPDATES_FLAG);+ if (enabled === lastSyncedStagedUpdates) return;+ lastSyncedStagedUpdates = enabled;+ void hostTrpcClient.updates.setStagedUpdates+ .mutate({ enabled })+ .catch((error: unknown) => {+ // Forget the failed sync so the next flags-loaded callback retries it.+ if (lastSyncedStagedUpdates === enabled) {+ lastSyncedStagedUpdates = null;+ }+ log.error("Failed to sync staged-updates flag", { error });+ });+}+posthogFeatureFlags.onFlagsLoaded(syncStagedUpdates);+// Auto-show "What's New" once on the first launch after the version changes.function maybeShowWhatsNew(): void {void hostTrpcClient.os.getAppVersiondiff --git a/products/desktop/apps/code/tests/e2e/fixtures/update.ts b/products/desktop/apps/code/tests/e2e/fixtures/update.tsindex 6f149c670e08..0493e2b8b906 100644--- a/products/desktop/apps/code/tests/e2e/fixtures/update.ts+++ b/products/desktop/apps/code/tests/e2e/fixtures/update.ts@@ -1,5 +1,6 @@import { type ChildProcess, execFileSync, spawn } from "node:child_process";import {+ cpSync,mkdirSync,readdirSync,readFileSync,@@ -13,6 +14,8 @@ const OUT_DIR = path.join(__dirname, "../../../out");export const PRISTINE_APP = path.join(OUT_DIR, "mac-arm64/PostHog.app");export const FEED_DIR = path.join(OUT_DIR, "dev-update-feed");+export const CHAIN_FEED_DIR = path.join(OUT_DIR, "dev-update-feed-chain");+export const CHAIN_RUN_FEED_DIR = path.join(OUT_DIR, "e2e-chain-feed");export const RUN_DIR = path.join(OUT_DIR, "e2e-update-run");export const RUN_APP = path.join(RUN_DIR, "PostHog.app");export const RUN_APP_BIN = path.join(RUN_APP, "Contents/MacOS/PostHog");@@ -53,6 +56,9 @@ const PROOF_FILE = path.join(PROOF_DIR, "proof.json");export const FORGE_PROOF_DIR = path.join(OUT_DIR, "update-proof-forge");const FORGE_PROOF_FILE = path.join(FORGE_PROOF_DIR, "proof.json");+export const CHAIN_PROOF_DIR = path.join(OUT_DIR, "update-proof-chain");+const CHAIN_PROOF_FILE = path.join(CHAIN_PROOF_DIR, "proof.json");+const SERVE_SCRIPT = path.join(__dirname,"../../../scripts/dev-update/serve.mjs",@@ -66,6 +72,8 @@ export type UpdateProof = {newVersion: string;bootedOn?: string;feedAvailableVersion?: string;+ intermediateVersion?: string;+ restagedVersion?: string;downloaded?: boolean;bundleVersionAfterSwap?: string;autoRelaunchedExecutable?: string;@@ -87,6 +95,26 @@ export function writeForgeProof(proof: UpdateProof): void {writeFileSync(FORGE_PROOF_FILE, `${JSON.stringify(proof, null, 2)}\n`);}+export function writeChainProof(proof: UpdateProof): void {+ mkdirSync(CHAIN_PROOF_DIR, { recursive: true });+ writeFileSync(CHAIN_PROOF_FILE, `${JSON.stringify(proof, null, 2)}\n`);+}++// The chain leg serves a disposable copy of the feed so bumping it mid-test+// never mutates dev-update-feed, which the other legs and the CI feed artifact+// rely on staying at the intermediate version.+export function prepareChainFeed(): void {+ rmSync(CHAIN_RUN_FEED_DIR, { recursive: true, force: true });+ cpSync(FEED_DIR, CHAIN_RUN_FEED_DIR, { recursive: true });+}++// Overlay the newer feed onto the served dir mid-test. serve.mjs re-reads+// latest-mac.yml on every request, so no server restart is needed; the old zip+// stays behind harmlessly while the yml now points at the newer one.+export function bumpChainFeed(): void {+ cpSync(CHAIN_FEED_DIR, CHAIN_RUN_FEED_DIR, { recursive: true });+}+// Copy the pristine built app into a disposable run dir so the in-place update// swap never mutates the build output, which lets a retry start from 1.0.0// again. ditto preserves the code signature that Squirrel.Mac verifies.@@ -102,8 +130,11 @@ export function prepareForgeRunApp(): void {execFileSync("ditto", [FORGE_PRISTINE_APP, FORGE_RUN_APP]);}-export function startFeedServer(port: number): ChildProcess {- return spawn("node", [SERVE_SCRIPT, FEED_DIR, String(port)], {+export function startFeedServer(+ port: number,+ dir: string = FEED_DIR,+): ChildProcess {+ return spawn("node", [SERVE_SCRIPT, dir, String(port)], {stdio: "inherit",});}diff --git a/products/desktop/apps/code/tests/e2e/playwright.update-chain.config.ts b/products/desktop/apps/code/tests/e2e/playwright.update-chain.config.tsnew file mode 100644index 000000000000..a2b89c3b0fb4--- /dev/null+++ b/products/desktop/apps/code/tests/e2e/playwright.update-chain.config.ts@@ -0,0 +1,20 @@+import { defineConfig } from "@playwright/test";++// Dedicated config for the macOS chained auto-update E2E (a newer update+// re-staged over an already staged one). The general suite excludes update+// specs by path, so this only runs here and cannot silently skip. retries are+// 0 so a broken re-stage surfaces immediately. In CI the JSON reporter lets+// the workflow assert exactly one test actually ran.+export default defineConfig({+ testDir: "./tests",+ testMatch: "**/update-chain.spec.ts",+ timeout: 60000,+ retries: 0,+ workers: 1,+ reporter: process.env.CI ? [["list"], ["json"]] : [["list"]],+ outputDir: "../playwright-results",+ use: {+ trace: "retain-on-failure",+ screenshot: "only-on-failure",+ },+});diff --git a/products/desktop/apps/code/tests/e2e/tests/update-chain.spec.ts b/products/desktop/apps/code/tests/e2e/tests/update-chain.spec.tsnew file mode 100644index 000000000000..d86e9427c696--- /dev/null+++ b/products/desktop/apps/code/tests/e2e/tests/update-chain.spec.ts@@ -0,0 +1,302 @@+import { existsSync } from "node:fs";+import {+ type ElectronApplication,+ _electron as electron,+ expect,+ test,+} from "@playwright/test";+import {+ bumpChainFeed,+ CHAIN_FEED_DIR,+ CHAIN_RUN_FEED_DIR,+ FEED_DIR,+ isAppRunning,+ killApp,+ PRISTINE_APP,+ prepareChainFeed,+ prepareRunApp,+ RUN_APP,+ RUN_APP_BIN,+ RUN_DIR,+ readBundleVersion,+ readMainLog,+ resetShipItCache,+ runningAppExecutables,+ SHIPIT_DIR,+ shipItEvidence,+ startFeedServer,+ type UpdateProof,+ waitUntil,+ writeChainProof,+} from "../fixtures/update";++type UpdateStatus = {+ checking?: boolean;+ available?: boolean;+ availableVersion?: string;+ downloading?: boolean;+ downloadPercent?: number;+ updateReady?: boolean;+ version?: string;+};++// Installed on globalThis by main/index.ts when POSTHOG_E2E_UPDATE_FEED is set.+// The cast is erased at compile time, so the evaluate closures serialize to plain+// globalThis access in the main process.+type E2eHook = {+ check: () => void;+ periodicCheck: () => void;+ download: () => void;+ install: () => Promise<unknown>;+ status: () => UpdateStatus;+};+type Hooked = typeof globalThis & { __e2eUpdates: E2eHook };++const FEED_PORT = 8790;+const FEED_URL = `http://127.0.0.1:${FEED_PORT}`;+const OLD_VERSION = "1.0.0";+const MID_VERSION = "2.0.0";+// Must match CHAIN_VERSION in code-update-e2e.yml (feeds build-pair.sh).+const FINAL_VERSION = "3.0.0";++test.describe("macOS chained auto-update", () => {+ // Runs only via playwright.update-chain.config.ts; the general e2e suite+ // excludes update specs by path, so there is no env gate that could skip it.+ test.skip(process.platform !== "darwin", "macOS-only update flow");++ // The re-staging safety proof: with 2.0.0 already downloaded and staged by+ // Squirrel.Mac, a background check finds 3.0.0, downloads it, re-stages it+ // over the pending update and the restart lands directly on 3.0.0.+ test("re-stages a newer update over a staged one and relaunches into it", async () => {+ test.setTimeout(5 * 60_000);++ const proof: UpdateProof = {+ result: "FAIL",+ oldVersion: OLD_VERSION,+ newVersion: FINAL_VERSION,+ intermediateVersion: MID_VERSION,+ };+ let feed: ReturnType<typeof startFeedServer> | undefined;+ let app: ElectronApplication | undefined;+ let updated: ElectronApplication | undefined;++ try {+ proof.failedStep = "preconditions";+ expect(+ existsSync(PRISTINE_APP),+ `missing built app at ${PRISTINE_APP}; run scripts/dev-update/build-pair.sh`,+ ).toBe(true);+ expect(+ existsSync(FEED_DIR),+ `missing feed at ${FEED_DIR}; run scripts/dev-update/build-pair.sh`,+ ).toBe(true);+ expect(+ existsSync(CHAIN_FEED_DIR),+ `missing chain feed at ${CHAIN_FEED_DIR}; run scripts/dev-update/build-pair.sh with CHAIN_VERSION=${FINAL_VERSION}`,+ ).toBe(true);++ prepareRunApp();+ prepareChainFeed();+ resetShipItCache();+ feed = startFeedServer(FEED_PORT, CHAIN_RUN_FEED_DIR);++ // Phase 1: stage the intermediate update on the old build.+ proof.failedStep = "launch";+ const launched = await electron.launch({+ executablePath: RUN_APP_BIN,+ args: [],+ env: {+ ...process.env,+ ELECTRON_DISABLE_GPU: "1",+ POSTHOG_E2E_UPDATE_FEED: FEED_URL,+ },+ });+ app = launched;++ await expect+ .poll(+ () =>+ launched.evaluate(() => typeof (globalThis as Hooked).__e2eUpdates),+ {+ timeout: 30_000,+ message: "update hook was never installed",+ },+ )+ .toBe("object");++ proof.failedStep = "start-version";+ const startVersion = await app.evaluate(({ app: a }) => a.getVersion());+ proof.bootedOn = startVersion;+ expect(startVersion, "run app should start on the old version").toBe(+ OLD_VERSION,+ );++ // The renderer syncs the "download updates automatically" setting (on by+ // default) shortly after boot, so each phase accepts both paths: manual+ // (available, then an explicit download) and auto (straight to+ // downloading/ready).+ proof.failedStep = "first-update-available";+ await app.evaluate(() => (globalThis as Hooked).__e2eUpdates.check());+ await pollStatus(+ app,+ (s) => offersVersion(s, MID_VERSION),+ "intermediate update never became available",+ );+ proof.feedAvailableVersion = MID_VERSION;++ proof.failedStep = "first-download";+ await downloadIfAvailable(app);+ await pollStatus(+ app,+ (s) => s.updateReady === true && s.version === MID_VERSION,+ "intermediate update never finished downloading",+ );+ proof.downloaded = true;++ // Wait for Squirrel to finish staging the intermediate update before+ // offering the next one. This mirrors real release cadence and keeps+ // the native updater idle when the replacement staging kicks off.+ proof.failedStep = "first-stage";+ await waitUntil(+ () => shipItEvidence().exists,+ 120_000,+ "Squirrel never staged the intermediate update",+ );++ // Phase 2: bump the feed and prove the staged update is replaced.+ proof.failedStep = "feed-bump";+ bumpChainFeed();++ proof.failedStep = "second-update-available";+ await app.evaluate(() =>+ (globalThis as Hooked).__e2eUpdates.periodicCheck(),+ );+ await pollStatus(+ app,+ (s) => offersVersion(s, FINAL_VERSION),+ "newer update was never surfaced while one was staged",+ );++ proof.failedStep = "re-download";+ await downloadIfAvailable(app);+ await pollStatus(+ app,+ (s) => s.updateReady === true && s.version === FINAL_VERSION,+ "newer update never replaced the staged one",+ );+ proof.restagedVersion = FINAL_VERSION;++ // Phase 3: install and prove the swap lands on the final version, not+ // the intermediate one.+ proof.failedStep = "install-and-swap";+ const closed = app.waitForEvent("close");+ void app+ .evaluate(() => {+ void (globalThis as Hooked).__e2eUpdates.install();+ })+ .catch(() => undefined);+ await closed;++ await waitUntil(+ () => readBundleVersion(RUN_APP) === FINAL_VERSION,+ 120_000,+ "bundle was not swapped to the final version",+ );+ proof.bundleVersionAfterSwap = readBundleVersion(RUN_APP);++ proof.failedStep = "auto-relaunch";+ await waitUntil(+ () => runningAppExecutables().some((exe) => exe.includes(RUN_DIR)),+ 60_000,+ "Squirrel did not auto-relaunch the updated app",+ );+ proof.autoRelaunchedExecutable = runningAppExecutables().find((exe) =>+ exe.includes(RUN_DIR),+ );++ killApp();+ await waitUntil(+ () => !isAppRunning(),+ 30_000,+ "relaunched instance did not exit",+ );++ proof.failedStep = "fresh-launch";+ updated = await electron.launch({+ executablePath: RUN_APP_BIN,+ args: [],+ env: { ...process.env, ELECTRON_DISABLE_GPU: "1" },+ });+ const version = await updated.evaluate(({ app: a }) => a.getVersion());+ proof.freshLaunchVersion = version;+ expect(version).toBe(FINAL_VERSION);+ await updated.close();++ // Mechanism evidence: the second update was found by a background check+ // while one was staged, and Squirrel.Mac's ShipIt performed the swap.+ proof.failedStep = "evidence";+ const mainLog = readMainLog();+ expect(+ mainLog,+ "main.log missing the background-check-while-staged marker",+ ).toContain("background check while an update is available or staged");+ const shipIt = shipItEvidence();+ proof.shipItExists = shipIt.exists;+ proof.shipItEntries = shipIt.entries;+ expect(+ shipIt.exists,+ `no Squirrel ShipIt cache at ${SHIPIT_DIR}; the swap was not performed by Squirrel`,+ ).toBe(true);++ proof.failedStep = undefined;+ proof.result = "PASS";+ } catch (err) {+ proof.error = err instanceof Error ? err.message : String(err);+ throw err;+ } finally {+ await app?.close().catch(() => {});+ await updated?.close().catch(() => {});+ feed?.kill();+ killApp();+ proof.finishedAt = new Date().toISOString();+ writeChainProof(proof);+ }+ });+});++function offersVersion(status: UpdateStatus, version: string): boolean {+ if (status.updateReady === true) {+ return status.version === version;+ }+ return (+ (status.available === true || status.downloading === true) &&+ status.availableVersion === version+ );+}++async function downloadIfAvailable(app: ElectronApplication): Promise<void> {+ await app.evaluate(() => {+ const hook = (globalThis as Hooked).__e2eUpdates;+ if (hook.status().available === true) {+ hook.download();+ }+ });+}++async function pollStatus(+ app: ElectronApplication,+ predicate: (status: UpdateStatus) => boolean,+ message: string,+): Promise<void> {+ await expect+ .poll(+ async () =>+ predicate(+ await app.evaluate(() =>+ (globalThis as Hooked).__e2eUpdates.status(),+ ),+ ),+ { timeout: 120_000, message },+ )+ .toBe(true);+}diff --git a/products/desktop/packages/core/src/updates/updateStore.test.ts b/products/desktop/packages/core/src/updates/updateStore.test.tsindex 82fe8f5ed6fb..2f7d20eb9acf 100644--- a/products/desktop/packages/core/src/updates/updateStore.test.ts+++ b/products/desktop/packages/core/src/updates/updateStore.test.ts@@ -29,6 +29,7 @@ describe("deriveUpdateUiStatus", () => {deriveUpdateUiStatus({ checking: true, downloading: true }, "idle"),).toEqual({status: "downloading",+ version: null,availableVersion: null,releaseNotes: null,releaseDate: null,@@ -53,6 +54,7 @@ describe("deriveUpdateUiStatus", () => {),).toEqual({status: "available",+ version: null,availableVersion: "v2",releaseNotes: "notes",releaseDate: "2026-01-01",@@ -60,11 +62,21 @@ describe("deriveUpdateUiStatus", () => {});});+ it("clears the staged version when a newer update becomes available", () => {+ expect(+ deriveUpdateUiStatus(+ { checking: false, available: true, availableVersion: "v3" },+ "ready",+ ),+ ).toMatchObject({ status: "available", version: null });+ });+it("defaults available fields to null when absent", () => {expect(deriveUpdateUiStatus({ checking: false, available: true }, "idle"),).toEqual({status: "available",+ version: null,availableVersion: null,releaseNotes: null,releaseDate: null,diff --git a/products/desktop/packages/core/src/updates/updateStore.ts b/products/desktop/packages/core/src/updates/updateStore.tsindex 742f082034d3..9711a1c68333 100644--- a/products/desktop/packages/core/src/updates/updateStore.ts+++ b/products/desktop/packages/core/src/updates/updateStore.ts@@ -108,6 +108,7 @@ export function deriveUpdateUiStatus(if (payload.checking && payload.downloading) {return {status: "downloading",+ version: null,availableVersion: payload.availableVersion ?? null,releaseNotes: payload.releaseNotes ?? null,releaseDate: payload.releaseDate ?? null,@@ -120,6 +121,7 @@ export function deriveUpdateUiStatus(if (payload.available) {return {status: "available",+ version: null,availableVersion: payload.availableVersion ?? null,releaseNotes: payload.releaseNotes ?? null,releaseDate: payload.releaseDate ?? null,diff --git a/products/desktop/packages/core/src/updates/updates.test.ts b/products/desktop/packages/core/src/updates/updates.test.tsindex 34fd9f21b6ac..f4e942d57fee 100644--- a/products/desktop/packages/core/src/updates/updates.test.ts+++ b/products/desktop/packages/core/src/updates/updates.test.ts@@ -53,8 +53,7 @@ const {return () => {};},),- download: vi.fn(),- setAutoDownload: vi.fn(),+ download: vi.fn(() => Promise.resolve()),onNoUpdate: vi.fn((h: () => void) => {updaterHandlers.noUpdate = h;return () => {};@@ -106,7 +105,7 @@ const {};});-import { UpdatesService } from "./updates";+import { isVersionNewer, UpdatesService } from "./updates";function injectPorts(service: UpdatesService): void {const s = service as unknown as Record<string, unknown>;@@ -485,6 +484,28 @@ describe("UpdatesService", () => {expect.anything(),);});++ it("rejects install while a newer update is re-downloading", async () => {+ await initializeService(service);+ service.setStagedUpdatesEnabled(true);+ service.setAutoDownloadEnabled(true);++ updaterHandlers.updateDownloaded?.("v2.0.0");+ service.checkForUpdates("periodic");+ updaterHandlers.updateAvailable?.({+ version: "v3.0.0",+ releaseNotes: null,+ });+ expect(service.getStatus()).toMatchObject({ downloading: true });++ const result = await service.installUpdate();++ expect(result).toEqual({ installed: false });+ expect(mockUpdater.quitAndInstall).not.toHaveBeenCalled();++ updaterHandlers.updateDownloaded?.("v3.0.0");+ expect(service.hasUpdateReady).toBe(true);+ });});describe("triggerMenuCheck", () => {@@ -533,7 +554,8 @@ describe("UpdatesService", () => {});});- it("ignores later update events once an update is already downloaded", () => {+ it("ignores update-not-available once an update is already downloaded", () => {+ service.setStagedUpdatesEnabled(true);// Simulate update already downloadedconst downloadedHandler = updaterHandlers.updateDownloaded;if (downloadedHandler) {@@ -547,9 +569,9 @@ describe("UpdatesService", () => {mockUpdater.check.mockClear();- // Periodic checks should be suppressed once an update is staged.+ // Periodic checks keep running in the background once an update is staged.service.checkForUpdates("periodic");- expect(mockUpdater.check).not.toHaveBeenCalled();+ expect(mockUpdater.check).toHaveBeenCalled();const notAvailableHandler = updaterHandlers.noUpdate;if (notAvailableHandler) {@@ -723,7 +745,11 @@ describe("UpdatesService", () => {});describe("available update guards", () => {- it("does not re-check or clear the banner on periodic checks while available", async () => {+ beforeEach(() => {+ service.setStagedUpdatesEnabled(true);+ });++ it("background-checks without clearing the banner on periodic checks while available", async () => {await initializeService(service);updaterHandlers.updateAvailable?.({@@ -742,7 +768,7 @@ describe("UpdatesService", () => {const result = service.checkForUpdates("periodic");expect(result).toEqual({ success: true });- expect(mockUpdater.check).not.toHaveBeenCalled();+ expect(mockUpdater.check).toHaveBeenCalled();expect(statusHandler).not.toHaveBeenCalled();expect(service.getStatus()).toMatchObject({available: true,@@ -750,6 +776,171 @@ describe("UpdatesService", () => {});});+ it("refreshes the banner when a background check finds a newer version", async () => {+ await initializeService(service);++ updaterHandlers.updateAvailable?.({+ version: "v2.0.0",+ releaseNotes: "Notes",+ });++ const statusHandler = vi.fn();+ service.on(UpdatesEvent.Status, statusHandler);+ service.checkForUpdates("periodic");++ updaterHandlers.updateAvailable?.({+ version: "v3.0.0",+ releaseNotes: "Newer notes",+ });++ expect(statusHandler).not.toHaveBeenCalledWith(+ expect.objectContaining({ checking: true }),+ );+ expect(service.getStatus()).toMatchObject({+ available: true,+ availableVersion: "v3.0.0",+ releaseNotes: "Newer notes",+ });+ });++ it("re-emits the available status without a transition when the same version is found again", async () => {+ await initializeService(service);++ updaterHandlers.updateAvailable?.({+ version: "v2.0.0",+ releaseNotes: "Notes",+ });++ const statusHandler = vi.fn();+ service.on(UpdatesEvent.Status, statusHandler);+ mockLog.info.mockClear();+ service.checkForUpdates("periodic");++ updaterHandlers.updateAvailable?.({+ version: "v2.0.0",+ releaseNotes: "Notes",+ });++ expect(statusHandler).toHaveBeenCalledWith(+ expect.objectContaining({+ available: true,+ availableVersion: "v2.0.0",+ }),+ );+ expect(mockUpdater.download).not.toHaveBeenCalled();+ expect(mockLog.info).not.toHaveBeenCalledWith(+ "Update state transition",+ expect.objectContaining({ reason: "update available" }),+ );+ });++ it("runs a foreground check when the user re-checks while available", async () => {+ await initializeService(service);++ updaterHandlers.updateAvailable?.({+ version: "v2.0.0",+ releaseNotes: null,+ });++ const statusHandler = vi.fn();+ service.on(UpdatesEvent.Status, statusHandler);+ mockUpdater.check.mockClear();++ const result = service.checkForUpdates("user");++ expect(result).toEqual({ success: true });+ expect(mockUpdater.check).toHaveBeenCalled();+ expect(statusHandler).toHaveBeenCalledWith({ checking: true });+ });++ it("re-emits the available status when a background check errors", async () => {+ await initializeService(service);++ updaterHandlers.updateAvailable?.({+ version: "v2.0.0",+ releaseNotes: "Notes",+ });++ const statusHandler = vi.fn();+ service.on(UpdatesEvent.Status, statusHandler);+ service.checkForUpdates("periodic");++ updaterHandlers.error?.(new Error("Network error"));++ expect(statusHandler).toHaveBeenCalledWith(+ expect.objectContaining({+ checking: false,+ available: true,+ availableVersion: "v2.0.0",+ }),+ );+ expect(service.getStatus()).toMatchObject({+ available: true,+ availableVersion: "v2.0.0",+ });+ });++ it("re-emits the available status when a background check times out", async () => {+ await initializeService(service);++ updaterHandlers.updateAvailable?.({+ version: "v2.0.0",+ releaseNotes: null,+ });++ const statusHandler = vi.fn();+ service.on(UpdatesEvent.Status, statusHandler);+ service.checkForUpdates("periodic");++ await vi.advanceTimersByTimeAsync(60 * 1000);++ expect(statusHandler).toHaveBeenCalledWith(+ expect.objectContaining({+ available: true,+ availableVersion: "v2.0.0",+ }),+ );+ expect(service.getStatus()).toMatchObject({ available: true });+ });++ it.each([+ ["no staged update falls back to idle", false],+ ["a staged update falls back to ready", true],+ ])(+ "clears the banner when the feed stops offering an update and %s",+ async (_name, hasStagedUpdate) => {+ await initializeService(service);++ if (hasStagedUpdate) {+ updaterHandlers.updateDownloaded?.("v2.0.0");+ }+ updaterHandlers.updateAvailable?.({+ version: "v3.0.0",+ releaseNotes: null,+ });+ expect(service.getStatus()).toMatchObject({+ available: true,+ availableVersion: "v3.0.0",+ });++ service.checkForUpdates("periodic");+ updaterHandlers.noUpdate?.();++ if (hasStagedUpdate) {+ expect(service.hasUpdateReady).toBe(true);+ expect(service.getStatus()).toEqual({+ checking: false,+ updateReady: true,+ installing: false,+ version: "v2.0.0",+ });+ } else {+ expect(service.hasUpdateReady).toBe(false);+ expect(service.getStatus()).toEqual({ checking: false });+ }+ },+ );+it("starts the download when auto-download is enabled while available", async () => {await initializeService(service);@@ -871,6 +1062,10 @@ describe("UpdatesService", () => {});describe("periodic update checks", () => {+ beforeEach(() => {+ service.setStagedUpdatesEnabled(true);+ });+it("performs initial check on setup", async () => {await initializeService(service);@@ -893,23 +1088,71 @@ describe("UpdatesService", () => {expect(mockUpdater.check.mock.calls.length).toBe(initialCallCount + 2);});- it("stops the periodic interval once an update is staged", async () => {+ it("keeps polling after an update is staged", async () => {await initializeService(service);updaterHandlers.updateDownloaded?.("v2.0.0");const baselineCallCount = mockUpdater.check.mock.calls.length;- // The interval would normally fire every hour; with the update staged it- // should be cleared so no further wake-ups occur.+ // The staged build must not go stale: the hourly interval keeps+ // background-checking so a newer release can replace it before restart.await vi.advanceTimersByTimeAsync(60 * 60 * 1000 * 3);- expect(mockUpdater.check.mock.calls.length).toBe(baselineCallCount);+ expect(mockUpdater.check.mock.calls.length).toBe(baselineCallCount + 3);+ expect(service.hasUpdateReady).toBe(true);+ });++ it("background check timeouts do not wedge later periodic checks", async () => {+ await initializeService(service);++ updaterHandlers.updateDownloaded?.("v2.0.0");++ const statusHandler = vi.fn();+ service.on(UpdatesEvent.Status, statusHandler);+ mockUpdater.check.mockClear();++ service.checkForUpdates("periodic");+ expect(mockUpdater.check).toHaveBeenCalledTimes(1);++ // The 60s watchdog fires with no updater response; a background check+ // must swallow it silently instead of surfacing an error state.+ await vi.advanceTimersByTimeAsync(60 * 1000);+ expect(statusHandler).not.toHaveBeenCalled();+ expect(service.hasUpdateReady).toBe(true);++ await vi.advanceTimersByTimeAsync(60 * 60 * 1000);+ expect(mockUpdater.check).toHaveBeenCalledTimes(2);+ });++ it("does not start a second check while a background check is in flight", async () => {+ await initializeService(service);++ updaterHandlers.updateAvailable?.({+ version: "v2.0.0",+ releaseNotes: null,+ });+ mockUpdater.check.mockClear();++ service.checkForUpdates("periodic");+ expect(mockUpdater.check).toHaveBeenCalledTimes(1);++ expect(service.checkForUpdates("periodic")).toMatchObject({+ errorCode: "already_checking",+ });+ expect(service.checkForUpdates("user")).toMatchObject({+ errorCode: "already_checking",+ });+ expect(mockUpdater.check).toHaveBeenCalledTimes(1);});});describe("staged update guards", () => {- it("does not re-check on periodic checks when update is ready", async () => {+ beforeEach(() => {+ service.setStagedUpdatesEnabled(true);+ });++ it("background-checks on periodic checks without disturbing the staged update", async () => {await initializeService(service);// Simulate update downloaded@@ -920,12 +1163,14 @@ describe("UpdatesService", () => {// Clear the checkForUpdates calls from initializationmockUpdater.check.mockClear();+ const statusHandler = vi.fn();+ service.on(UpdatesEvent.Status, statusHandler);- // Periodic check should not overwrite or refresh the staged update.+ // Periodic check runs silently and must not reset the staged state.const result = service.checkForUpdates("periodic");expect(result).toEqual({ success: true });- expect(mockUpdater.check).not.toHaveBeenCalled();- // Update should still be ready (state not reset)+ expect(mockUpdater.check).toHaveBeenCalled();+ expect(statusHandler).not.toHaveBeenCalled();expect(service.hasUpdateReady).toBe(true);});@@ -960,9 +1205,9 @@ describe("UpdatesService", () => {mockUpdater.check.mockClear();service.checkForUpdates("periodic");- expect(mockUpdater.check).not.toHaveBeenCalled();+ expect(mockUpdater.check).toHaveBeenCalled();- // Simulate a stale updater error after staging.+ // Simulate a background check error after staging.const errorHandler = updaterHandlers.error;if (errorHandler) {errorHandler(new Error("Network error"));@@ -995,7 +1240,7 @@ describe("UpdatesService", () => {expect(readyHandler).not.toHaveBeenCalled();});- it("does not overwrite staged version when a later download event arrives", async () => {+ it("re-stages when a newer download finishes while one is staged", async () => {await initializeService(service);const readyHandler = vi.fn();@@ -1014,11 +1259,411 @@ describe("UpdatesService", () => {downloadedHandler("v3.0.0");}- // User checks should still surface the originally staged update.+ // The newer build replaces the staged one and re-notifies.+ expect(readyHandler).toHaveBeenCalledWith({ version: "v3.0.0" });+ expect(service.hasUpdateReady).toBe(true);+ expect(service.getStatus()).toEqual({+ checking: false,+ updateReady: true,+ installing: false,+ version: "v3.0.0",+ });+ });++ it.each([+ ["auto-download on downloads the newer build", true],+ ["auto-download off surfaces the newer build as available", false],+ ])(+ "background check finding a newer version while staged with %s",+ async (_name, autoDownload) => {+ await initializeService(service);+ service.setAutoDownloadEnabled(autoDownload);++ updaterHandlers.updateDownloaded?.("v2.0.0");++ mockUpdater.download.mockClear();+ service.checkForUpdates("periodic");+ updaterHandlers.updateAvailable?.({+ version: "v3.0.0",+ releaseNotes: null,+ });++ if (autoDownload) {+ expect(mockUpdater.download).toHaveBeenCalled();+ expect(service.getStatus()).toMatchObject({+ checking: true,+ downloading: true,+ availableVersion: "v3.0.0",+ });+ } else {+ expect(mockUpdater.download).not.toHaveBeenCalled();+ expect(service.hasUpdateReady).toBe(false);+ expect(service.getStatus()).toMatchObject({+ available: true,+ availableVersion: "v3.0.0",+ });+ }+ },+ );++ it("ignores a background check that finds the already staged version", async () => {+ await initializeService(service);+ service.setAutoDownloadEnabled(true);++ updaterHandlers.updateDownloaded?.("v2.0.0");++ const statusHandler = vi.fn();+ service.on(UpdatesEvent.Status, statusHandler);+ mockUpdater.download.mockClear();++ service.checkForUpdates("periodic");+ updaterHandlers.updateAvailable?.({+ version: "v2.0.0",+ releaseNotes: null,+ });++ expect(mockUpdater.download).not.toHaveBeenCalled();+ expect(statusHandler).not.toHaveBeenCalled();+ expect(service.getStatus()).toEqual({+ checking: false,+ updateReady: true,+ installing: false,+ version: "v2.0.0",+ });+ });++ it("falls back to the staged update when a re-download errors", async () => {+ await initializeService(service);+ service.setAutoDownloadEnabled(true);++ updaterHandlers.updateDownloaded?.("v2.0.0");++ service.checkForUpdates("periodic");+ updaterHandlers.updateAvailable?.({+ version: "v3.0.0",+ releaseNotes: null,+ });+ expect(service.getStatus()).toMatchObject({ downloading: true });++ updaterHandlers.error?.(new Error("Download failed"));++ expect(service.hasUpdateReady).toBe(true);+ expect(service.getStatus()).toEqual({+ checking: false,+ updateReady: true,+ installing: false,+ version: "v2.0.0",+ });+ });++ it("queues a re-download behind an in-flight download", async () => {+ await initializeService(service);++ let resolveFirstDownload = () => {};+ mockUpdater.download.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ resolveFirstDownload = resolve;+ }),+ );++ updaterHandlers.updateAvailable?.({+ version: "v2.0.0",+ releaseNotes: null,+ });+ service.requestDownload();+ expect(mockUpdater.download).toHaveBeenCalledTimes(1);++ // electron-updater dispatches update-downloaded while its download+ // promise is still pending on the native staging.+ updaterHandlers.updateDownloaded?.("v2.0.0");+ service.setAutoDownloadEnabled(true);++ service.checkForUpdates("periodic");+ updaterHandlers.updateAvailable?.({+ version: "v3.0.0",+ releaseNotes: null,+ });++ expect(mockUpdater.download).toHaveBeenCalledTimes(1);++ resolveFirstDownload();+ await vi.advanceTimersByTimeAsync(0);++ expect(mockUpdater.download).toHaveBeenCalledTimes(2);+ });++ it("ignores a feed rollback below the staged version", async () => {+ await initializeService(service);+ service.setAutoDownloadEnabled(true);++ updaterHandlers.updateDownloaded?.("v3.0.0");++ const statusHandler = vi.fn();+ service.on(UpdatesEvent.Status, statusHandler);+ mockUpdater.download.mockClear();++ service.checkForUpdates("periodic");+ updaterHandlers.updateAvailable?.({+ version: "v2.0.0",+ releaseNotes: null,+ });++ expect(mockUpdater.download).not.toHaveBeenCalled();+ expect(statusHandler).not.toHaveBeenCalled();+ expect(service.getStatus()).toEqual({+ checking: false,+ updateReady: true,+ installing: false,+ version: "v3.0.0",+ });+ });++ it("ignores a feed rollback while a newer offer is pending", async () => {+ await initializeService(service);++ updaterHandlers.updateDownloaded?.("v2.0.0");++ service.checkForUpdates("periodic");+ updaterHandlers.updateAvailable?.({+ version: "v3.0.0",+ releaseNotes: null,+ });+ expect(service.getStatus()).toMatchObject({+ available: true,+ availableVersion: "v3.0.0",+ });++ mockUpdater.download.mockClear();+ service.checkForUpdates("periodic");+ updaterHandlers.updateAvailable?.({+ version: "v1.5.0",+ releaseNotes: null,+ });++ expect(mockUpdater.download).not.toHaveBeenCalled();+ expect(service.getStatus()).toMatchObject({+ available: true,+ availableVersion: "v3.0.0",+ });+ });++ it("falls back to the staged update when a user re-check errors while a newer version is available", async () => {+ await initializeService(service);++ updaterHandlers.updateDownloaded?.("v2.0.0");+ service.checkForUpdates("periodic");+ updaterHandlers.updateAvailable?.({+ version: "v3.0.0",+ releaseNotes: null,+ });+ expect(service.getStatus()).toMatchObject({+ available: true,+ availableVersion: "v3.0.0",+ });+service.checkForUpdates("user");- expect(readyHandler).toHaveBeenCalledWith({ version: "v2.0.0" });+ updaterHandlers.error?.(new Error("Network error"));++ expect(service.hasUpdateReady).toBe(true);+ expect(service.getStatus()).toEqual({+ checking: false,+ updateReady: true,+ installing: false,+ version: "v2.0.0",+ });+ });++ it("falls back to the staged update when the feed empties mid-redownload", async () => {+ await initializeService(service);+ service.setAutoDownloadEnabled(true);++ updaterHandlers.updateDownloaded?.("v2.0.0");+ service.checkForUpdates("periodic");+ updaterHandlers.updateAvailable?.({+ version: "v3.0.0",+ releaseNotes: null,+ });+ expect(service.getStatus()).toMatchObject({ downloading: true });++ updaterHandlers.noUpdate?.();++ expect(service.hasUpdateReady).toBe(true);+ expect(service.getStatus()).toEqual({+ checking: false,+ updateReady: true,+ installing: false,+ version: "v2.0.0",+ });+ });++ it.each([+ { source: "user" as const, emitsStatus: true },+ { source: "periodic" as const, emitsStatus: false },+ ])(+ "$source checks while installing do not restart the state machine",+ async ({ source, emitsStatus }) => {+ await initializeService(service);+ updaterHandlers.updateDownloaded?.("v2.0.0");+ mockLifecycleService.shutdownWithoutContainer.mockReturnValue(+ new Promise(() => {}),+ );+ void service.installUpdate();+ await Promise.resolve();++ const statusHandler = vi.fn();+ service.on(UpdatesEvent.Status, statusHandler);+ mockUpdater.check.mockClear();++ const result = service.checkForUpdates(source);++ expect(result).toEqual({ success: true });+ expect(mockUpdater.check).not.toHaveBeenCalled();+ if (emitsStatus) {+ expect(statusHandler).toHaveBeenCalledWith(+ expect.objectContaining({ updateReady: true, installing: true }),+ );+ } else {+ expect(statusHandler).not.toHaveBeenCalled();+ }+ },+ );++ it.each([+ [+ "update-available",+ () =>+ updaterHandlers.updateAvailable?.({+ version: "v3.0.0",+ releaseNotes: null,+ }),+ ],+ ["update-downloaded", () => updaterHandlers.updateDownloaded?.("v3.0.0")],+ ])("ignores %s while an install is in progress", async (_event, fire) => {+ await initializeService(service);+ updaterHandlers.updateDownloaded?.("v2.0.0");+ mockLifecycleService.shutdownWithoutContainer.mockReturnValue(+ new Promise(() => {}),+ );+ void service.installUpdate();+ await Promise.resolve();++ const statusHandler = vi.fn();+ const readyHandler = vi.fn();+ service.on(UpdatesEvent.Status, statusHandler);+ service.on(UpdatesEvent.Ready, readyHandler);++ fire();++ expect(statusHandler).not.toHaveBeenCalled();+ expect(readyHandler).not.toHaveBeenCalled();+ expect(service.getStatus()).toEqual({+ checking: false,+ updateReady: true,+ installing: true,+ version: "v2.0.0",+ });+ });+ });++ describe("staged updates rollout flag", () => {+ it("stops the periodic interval once an update is staged while off", async () => {+ await initializeService(service);++ updaterHandlers.updateDownloaded?.("v2.0.0");+ mockUpdater.check.mockClear();- // Update should still be ready (state not corrupted)+ await vi.advanceTimersByTimeAsync(60 * 60 * 1000 * 3);++ expect(mockUpdater.check).not.toHaveBeenCalled();+ expect(service.hasUpdateReady).toBe(true);+ });++ it.each([+ [+ "ready",+ () => updaterHandlers.updateDownloaded?.("v2.0.0"),+ "check skipped because update is already staged",+ ],+ [+ "available",+ () =>+ updaterHandlers.updateAvailable?.({+ version: "v2.0.0",+ releaseNotes: null,+ }),+ "periodic check skipped because an update is already available",+ ],+ ])(+ "skips periodic checks while %s without checking while off",+ async (_state, arrange, reason) => {+ await initializeService(service);+ arrange();++ mockUpdater.check.mockClear();+ mockLog.info.mockClear();++ const result = service.checkForUpdates("periodic");++ expect(result).toEqual({ success: true });+ expect(mockUpdater.check).not.toHaveBeenCalled();+ expect(mockLog.info).toHaveBeenCalledWith(+ "Update state transition",+ expect.objectContaining({ reason }),+ );+ },+ );++ it("ignores update-available while an update is staged while off", async () => {+ await initializeService(service);+ service.setAutoDownloadEnabled(true);++ updaterHandlers.updateDownloaded?.("v2.0.0");++ mockUpdater.download.mockClear();+ updaterHandlers.updateAvailable?.({+ version: "v3.0.0",+ releaseNotes: null,+ });++ expect(mockUpdater.download).not.toHaveBeenCalled();+ expect(service.getStatus()).toEqual({+ checking: false,+ updateReady: true,+ installing: false,+ version: "v2.0.0",+ });+ });++ it("keeps the staged version when a later download event arrives while off", async () => {+ await initializeService(service);++ const readyHandler = vi.fn();+ service.on(UpdatesEvent.Ready, readyHandler);+ updaterHandlers.updateDownloaded?.("v2.0.0");+ readyHandler.mockClear();++ updaterHandlers.updateDownloaded?.("v3.0.0");++ expect(readyHandler).not.toHaveBeenCalled();+ expect(service.getStatus()).toEqual({+ checking: false,+ updateReady: true,+ installing: false,+ version: "v2.0.0",+ });+ });++ it("resumes polling when the flag turns on after an update is staged", async () => {+ await initializeService(service);++ updaterHandlers.updateDownloaded?.("v2.0.0");+ mockUpdater.check.mockClear();++ service.setStagedUpdatesEnabled(true);+ await vi.advanceTimersByTimeAsync(60 * 60 * 1000);++ expect(mockUpdater.check).toHaveBeenCalledTimes(1);expect(service.hasUpdateReady).toBe(true);});});@@ -1039,8 +1684,9 @@ describe("UpdatesService", () => {);});- it("logs skipped checks after an update is staged", async () => {+ it("logs background checks after an update is staged", async () => {await initializeService(service);+ service.setStagedUpdatesEnabled(true);updaterHandlers.updateDownloaded?.("v2.0.0");mockLog.info.mockClear();@@ -1053,12 +1699,47 @@ describe("UpdatesService", () => {fromState: "ready",toState: "ready",downloadedVersion: "v2.0.0",+ skippedBecauseUpdateStaged: false,+ reason: "background check while an update is available or staged",+ }),+ );+ });++ it("logs skipped user checks after an update is staged", async () => {+ await initializeService(service);+ updaterHandlers.updateDownloaded?.("v2.0.0");++ mockLog.info.mockClear();+ service.checkForUpdates("user");++ expect(mockLog.info).toHaveBeenCalledWith(+ "Update state transition",+ expect.objectContaining({+ source: "user",+ fromState: "ready",+ toState: "ready",+ downloadedVersion: "v2.0.0",skippedBecauseUpdateStaged: true,}),);});});+ describe("isVersionNewer", () => {+ it.each([+ ["3.0.0", "2.0.0", true],+ ["2.1.0", "2.0.9", true],+ ["2.0.10", "2.0.9", true],+ ["2.0.0", "2.0.0", false],+ ["2.0.0", "3.0.0", false],+ ["2.9.0", "2.10.0", false],+ ["v3.0.0", "v2.0.0", true],+ ["v2.0.0", "3.0.0", false],+ ])("isVersionNewer(%s, %s) is %s", (candidate, current, expected) => {+ expect(isVersionNewer(candidate, current)).toBe(expected);+ });+ });+describe("error handling", () => {it("catches errors during checkForUpdates", async () => {await initializeService(service);@@ -1070,5 +1751,45 @@ describe("UpdatesService", () => {// Should not throwexpect(() => service.checkForUpdates()).not.toThrow();});++ it("keeps the staged state when a background check throws synchronously", async () => {+ await initializeService(service);+ service.setStagedUpdatesEnabled(true);+ updaterHandlers.updateDownloaded?.("v2.0.0");++ const statusHandler = vi.fn();+ service.on(UpdatesEvent.Status, statusHandler);+ mockUpdater.check.mockImplementationOnce(() => {+ throw new Error("boom");+ });++ service.checkForUpdates("periodic");++ expect(statusHandler).not.toHaveBeenCalled();+ expect(service.hasUpdateReady).toBe(true);+ expect(service.getStatus()).toMatchObject({+ updateReady: true,+ version: "v2.0.0",+ });+ });++ it("surfaces an error when a download fails with nothing staged", async () => {+ await initializeService(service);++ updaterHandlers.updateAvailable?.({+ version: "v2.0.0",+ releaseNotes: null,+ });+ service.requestDownload();+ expect(service.getStatus()).toMatchObject({ downloading: true });++ updaterHandlers.error?.(new Error("Download failed"));++ expect(service.hasUpdateReady).toBe(false);+ expect(service.getStatus()).toEqual({+ checking: false,+ error: "Download failed",+ });+ });});});diff --git a/products/desktop/packages/core/src/updates/updates.ts b/products/desktop/packages/core/src/updates/updates.tsindex 10ea50f090c5..d7c7c4d5dbde 100644--- a/products/desktop/packages/core/src/updates/updates.ts+++ b/products/desktop/packages/core/src/updates/updates.ts@@ -30,6 +30,24 @@ import {} from "./schemas";type CheckSource = "user" | "periodic";++function versionTriple(version: string): number[] {+ return version+ .replace(/^v/, "")+ .split(".", 3)+ .map((segment) => Number.parseInt(segment, 10) || 0);+}++export function isVersionNewer(candidate: string, current: string): boolean {+ const a = versionTriple(candidate);+ const b = versionTriple(current);+ for (let i = 0; i < 3; i++) {+ if ((a[i] ?? 0) !== (b[i] ?? 0)) {+ return (a[i] ?? 0) > (b[i] ?? 0);+ }+ }+ return false;+}type UpdateState =| "idle"| "checking"@@ -95,7 +113,9 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {private availableInfo: UpdateAvailableInfo | null = null;private downloadProgress: UpdateDownloadProgress | null = null;private autoDownloadEnabled = false;+ private stagedUpdatesEnabled = false;private lastProgressEmit = 0;+ private activeDownload: Promise<void> | null = null;get hasUpdateReady(): boolean {return this.isUpdateStaged();@@ -128,9 +148,6 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {setAutoDownloadEnabled(enabled: boolean): void {this.autoDownloadEnabled = enabled;- if (this.isEnabled) {- this.updater.setAutoDownload(enabled);- }this.log.info("Auto-download preference updated", { enabled });if (enabled && this.state === "available") {@@ -138,6 +155,25 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {}}+ // Synced from the posthog-desktop-staged-updates rollout flag; off keeps+ // the legacy flow where polling stops once an update is staged.+ setStagedUpdatesEnabled(enabled: boolean): void {+ if (enabled === this.stagedUpdatesEnabled) {+ return;+ }+ this.stagedUpdatesEnabled = enabled;+ this.log.info("Staged-updates rollout flag updated", { enabled });++ // The flag arrives async after boot; if a staged download already stopped+ // the legacy interval, restart it so background checks resume.+ if (enabled && this.initialized && this.checkIntervalId === null) {+ this.checkIntervalId = setInterval(+ () => this.checkForUpdates("periodic"),+ UpdatesService.CHECK_INTERVAL_MS,+ );+ }+ }+requestDownload(): void {if (this.state !== "available") {this.log.warn("requestDownload called but no update is available", {@@ -152,10 +188,18 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {this.log.info("Downloading update...", {version: this.availableInfo?.version,});- this.updater.download();+ this.queueDownload();this.emitStatus(this.downloadingStatusPayload());}+ // electron-updater silently returns the in-flight promise while a previous+ // download is still fetching or staging, so a re-download must wait its turn.+ private queueDownload(): void {+ const start = () => Promise.resolve(this.updater.download());+ this.activeDownload =+ this.activeDownload === null ? start() : this.activeDownload.then(start);+ }+getStatus(): UpdatesStatusPayload {if (this.state === "checking") {return { checking: true };@@ -191,31 +235,55 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {return { success: false, errorMessage: reason, errorCode: "disabled" };}- if (this.isUpdateStaged()) {+ if (this.state === "installing") {this.logStateTransition(this.state, {source,skippedBecauseUpdateStaged: true,- reason: "check skipped because update is already staged",+ reason: "check skipped because install is in progress",});-if (source === "user") {this.pendingNotification = true;this.flushPendingNotification();this.emitStatus(this.stagedStatusPayload());}-return { success: true };}- if (source === "periodic" && this.state === "available") {+ if (this.state === "ready" && source === "user") {this.logStateTransition(this.state, {source,- reason: "periodic check skipped because an update is already available",+ skippedBecauseUpdateStaged: true,+ reason: "check skipped because update is already staged",});+ this.pendingNotification = true;+ this.flushPendingNotification();+ this.emitStatus(this.stagedStatusPayload());return { success: true };}- if (this.state === "checking" || this.state === "downloading") {+ if (+ source === "periodic" &&+ (this.state === "ready" || this.state === "available")+ ) {+ if (!this.stagedUpdatesEnabled) {+ this.logStateTransition(this.state, {+ source,+ skippedBecauseUpdateStaged: this.state === "ready",+ reason:+ this.state === "ready"+ ? "check skipped because update is already staged"+ : "periodic check skipped because an update is already available",+ });+ return { success: true };+ }+ return this.performBackgroundCheck(source);+ }++ if (+ this.state === "checking" ||+ this.state === "downloading" ||+ this.checkTimeoutId !== null+ ) {return {success: false,errorMessage: "Already checking for updates",@@ -364,7 +432,22 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {return;}+ // Re-emit so a menu check that deferred to this background check resolves.+ if (this.state === "available") {+ this.emitStatus(this.availableStatusPayload());+ return;+ }+if (this.state === "checking" || this.state === "downloading") {+ if (this.downloadedVersion !== null) {+ this.availableInfo = null;+ this.transitionTo("ready", {+ reason: "updater error, falling back to staged update",+ error: error.message,+ });+ this.emitStatus(this.stagedStatusPayload());+ return;+ }this.lastError = error.message;this.transitionTo("error", { error: error.message });this.emitStatus({@@ -375,7 +458,19 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {}private handleUpdateAvailable(info: UpdateAvailableInfo): void {- if (this.isUpdateStaged()) {+ this.clearCheckTimeout();++ if (this.state === "installing") {+ this.log.info(+ "Ignoring update-available because install is in progress",+ {+ downloadedVersion: this.downloadedVersion,+ },+ );+ return;+ }++ if (this.state === "ready" && !this.stagedUpdatesEnabled) {this.log.info("Ignoring update-available because an update is already staged",{@@ -385,7 +480,34 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {return;}- this.clearCheckTimeout();+ // Strictly newer only: a manifest rollback must not downgrade what is+ // already staged, regardless of state — an offer accepted while+ // "available" or "downloading" would still re-stage over the download.+ // A pulled release is recovered by fix-forward or the no-update+ // fallback, never by re-staging an older signed build.+ if (+ this.downloadedVersion !== null &&+ !isVersionNewer(info.version, this.downloadedVersion)+ ) {+ this.log.info(+ "Ignoring update-available because it is not newer than the staged version",+ {+ downloadedVersion: this.downloadedVersion,+ incomingVersion: info.version,+ },+ );+ return;+ }++ if (+ this.state === "available" &&+ info.version === this.availableInfo?.version+ ) {+ this.availableInfo = info;+ this.emitStatus(this.availableStatusPayload());+ return;+ }+this.availableInfo = info;this.downloadProgress = null;@@ -397,7 +519,7 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {this.log.info("Update available, auto-downloading...", {version: info.version,});- this.updater.download();+ this.queueDownload();this.emitStatus(this.downloadingStatusPayload());return;}@@ -437,7 +559,19 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {this.log.info("No updates available", {currentVersion: this.appMeta.version,});- if (this.state === "checking" || this.state === "downloading") {+ if (+ this.state === "checking" ||+ this.state === "downloading" ||+ this.state === "available"+ ) {+ this.availableInfo = null;+ if (this.downloadedVersion !== null) {+ this.transitionTo("ready", {+ reason: "feed no longer offers an update, keeping staged update",+ });+ this.emitStatus(this.stagedStatusPayload());+ return;+ }this.transitionTo("idle", { reason: "no update available" });this.emitStatus({checking: false,@@ -450,7 +584,12 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {private handleUpdateDownloaded(version?: string): void {this.clearCheckTimeout();- if (this.isUpdateStaged()) {+ if (+ this.state === "installing" ||+ (this.state === "ready" &&+ (!this.stagedUpdatesEnabled ||+ (version ?? null) === this.downloadedVersion))+ ) {this.log.info("Ignoring duplicate update-downloaded event", {existingVersion: this.downloadedVersion,incomingVersion: version,@@ -463,7 +602,9 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {reason: "update downloaded",incomingVersion: version ?? null,});- this.clearCheckInterval();+ if (!this.stagedUpdatesEnabled) {+ this.clearCheckInterval();+ }this.emitStatus(this.stagedStatusPayload());this.log.info("Update downloaded, awaiting user confirmation", {@@ -496,10 +637,28 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {this.emit(UpdatesEvent.Status, status);}+ private performBackgroundCheck(source: CheckSource): CheckForUpdatesOutput {+ if (this.checkTimeoutId !== null) {+ return {+ success: false,+ errorMessage: "Already checking for updates",+ errorCode: "already_checking",+ };+ }++ this.logStateTransition(this.state, {+ source,+ reason: "background check while an update is available or staged",+ });+ this.performCheck();+ return { success: true };+ }+private performCheck(): void {this.clearCheckTimeout();this.checkTimeoutId = setTimeout(() => {+ this.checkTimeoutId = null;if (this.state === "checking" || this.state === "downloading") {const timeoutSeconds = UpdatesService.CHECK_TIMEOUT_MS / 1000;const message = "Update check timed out. Please try again.";@@ -507,7 +666,12 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {this.lastError = message;this.transitionTo("error", { error: message });this.emitStatus({ checking: false, error: message });+ return;}+ if (this.state === "available") {+ this.emitStatus(this.availableStatusPayload());+ }+ this.log.warn("Background update check timed out", { state: this.state });}, UpdatesService.CHECK_TIMEOUT_MS);try {@@ -515,6 +679,9 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {} catch (error) {this.clearCheckTimeout();this.log.error("Failed to check for updates", { error });+ if (this.state !== "checking" && this.state !== "downloading") {+ return;+ }this.lastError = "Failed to check for updates. Please try again.";this.transitionTo("error", {error: error instanceof Error ? error.message : String(error),diff --git a/products/desktop/packages/host-router/src/routers/updates.router.ts b/products/desktop/packages/host-router/src/routers/updates.router.tsindex cb17491c2508..0e17fd330c6e 100644--- a/products/desktop/packages/host-router/src/routers/updates.router.ts+++ b/products/desktop/packages/host-router/src/routers/updates.router.ts@@ -54,6 +54,14 @@ export const updatesRouter = router({.setAutoDownloadEnabled(input.enabled);}),+ setStagedUpdates: publicProcedure+ .input(z.object({ enabled: z.boolean() }))+ .mutation(({ ctx, input }) => {+ ctx.container+ .get<UpdatesService>(UPDATES_SERVICE)+ .setStagedUpdatesEnabled(input.enabled);+ }),+onReady: subscribe(UpdatesEvent.Ready),onStatus: subscribe(UpdatesEvent.Status),onCheckFromMenu: subscribe(UpdatesEvent.CheckFromMenu),diff --git a/products/desktop/packages/platform/src/updater.ts b/products/desktop/packages/platform/src/updater.tsindex 07fe5e2f4ff7..90501b45149b 100644--- a/products/desktop/packages/platform/src/updater.ts+++ b/products/desktop/packages/platform/src/updater.ts@@ -16,9 +16,8 @@ export interface UpdateDownloadProgress {export interface IUpdater {isSupported(): boolean;check(): void;- download(): void;+ download(): Promise<void>;quitAndInstall(): void;- setAutoDownload(enabled: boolean): void;onCheckStart(handler: () => void): () => void;onUpdateAvailable(handler: (info: UpdateAvailableInfo) => void): () => void;onDownloadProgress(diff --git a/products/desktop/packages/shared/src/flags.ts b/products/desktop/packages/shared/src/flags.tsindex fe5834a13d10..b5c4e43e1b19 100644--- a/products/desktop/packages/shared/src/flags.ts+++ b/products/desktop/packages/shared/src/flags.ts@@ -39,3 +39,9 @@ export const LOCAL_MCP_IMPORT_FLAG = "posthog-code-local-mcp-import";export const MCP_GATEWAY_FLAG = "mcp-gateway";/** Per-task estimated cost readout in the context usage indicator. */export const TASK_COST_FLAG = "posthog-code-task-cost";+/**+ * Rollout gate for re-staging desktop updates: keep polling after an update+ * is staged and replace it when the feed offers a newer version. Off keeps+ * the legacy stop-polling-once-staged behavior.+ */+export const STAGED_UPDATES_FLAG = "posthog-desktop-staged-updates";