: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): install the latest available update on restart (#82437)
Alessandro Pogliaghia8e7c7591526
diff --git a/products/desktop/packages/core/src/updates/updates.test.ts b/products/desktop/packages/core/src/updates/updates.test.tsindex 9409799d6fec..692fca7aea34 100644--- a/products/desktop/packages/core/src/updates/updates.test.ts+++ b/products/desktop/packages/core/src/updates/updates.test.ts@@ -125,6 +125,13 @@ async function initializeService(service: UpdatesService): Promise<void> {await vi.advanceTimersByTimeAsync(0);}+const PRE_INSTALL_CHECK_TIMEOUT_MS = 5_000;+const DOWNLOAD_STALL_TIMEOUT_MS = 60_000;++async function flushPreInstallCheck(): Promise<void> {+ await vi.advanceTimersByTimeAsync(PRE_INSTALL_CHECK_TIMEOUT_MS);+}+describe("UpdatesService", () => {let service: UpdatesService;let originalPlatform: PropertyDescriptor | undefined;@@ -389,6 +396,7 @@ describe("UpdatesService", () => {);const resultPromise = service.installUpdate();+ await flushPreInstallCheck();await vi.advanceTimersByTimeAsync(20_000);await expect(resultPromise).resolves.toEqual({ installed: true });@@ -430,7 +438,9 @@ describe("UpdatesService", () => {throw new Error("Failed to install");});- await service.installUpdate();+ const pending = service.installUpdate();+ await flushPreInstallCheck();+ await pending;expect(mockLifecycleService.clearQuittingForUpdate).toHaveBeenCalled();const setOrder =@@ -451,7 +461,9 @@ describe("UpdatesService", () => {const statusHandler = vi.fn();service.on(UpdatesEvent.Status, statusHandler);- const first = await service.installUpdate();+ const firstPending = service.installUpdate();+ await flushPreInstallCheck();+ const first = await firstPending;expect(first).toEqual({ installed: false });expect(service.hasUpdateReady).toBe(true);expect(statusHandler).toHaveBeenLastCalledWith({@@ -462,8 +474,9 @@ describe("UpdatesService", () => {});mockUpdater.quitAndInstall.mockImplementationOnce(() => undefined);- const second = await service.installUpdate();- expect(second).toEqual({ installed: true });+ const secondPending = service.installUpdate();+ await flushPreInstallCheck();+ await expect(secondPending).resolves.toEqual({ installed: true });});it("is idempotent when install is already in progress", async () => {@@ -471,9 +484,9 @@ describe("UpdatesService", () => {updaterHandlers.updateDownloaded?.("v2.0.0");- await expect(service.installUpdate()).resolves.toEqual({- installed: true,- });+ const firstPending = service.installUpdate();+ await flushPreInstallCheck();+ await expect(firstPending).resolves.toEqual({ installed: true });expect(mockUpdater.quitAndInstall).toHaveBeenCalledTimes(1);await expect(service.installUpdate()).resolves.toEqual({@@ -486,6 +499,140 @@ describe("UpdatesService", () => {);});+ it("installs the newer build when one shipped after the staged one", async () => {+ await initializeService(service);+ updaterHandlers.updateDownloaded?.("v2.0.0");+ mockUpdater.check.mockClear();+ mockUpdater.download.mockClear();++ const pending = service.installUpdate();+ await Promise.resolve();+ expect(mockUpdater.check).toHaveBeenCalled();++ updaterHandlers.updateAvailable?.({+ version: "v3.0.0",+ releaseNotes: null,+ });+ expect(mockUpdater.download).toHaveBeenCalled();+ expect(mockUpdater.quitAndInstall).not.toHaveBeenCalled();++ updaterHandlers.updateDownloaded?.("v3.0.0");+ await expect(pending).resolves.toEqual({ installed: true });+ expect(mockUpdater.quitAndInstall).toHaveBeenCalled();+ expect(service.getStatus()).toMatchObject({ version: "v3.0.0" });+ });++ it.each([+ ["the feed reports no update", () => updaterHandlers.noUpdate?.()],+ [+ "the feed offers nothing newer",+ () =>+ updaterHandlers.updateAvailable?.({+ version: "v2.0.0",+ releaseNotes: null,+ }),+ ],+ [+ "the check errors",+ () => updaterHandlers.error?.(new Error("Network error")),+ ],+ ["the check times out", () => undefined],+ ])("installs the staged build when %s", async (_case, fire) => {+ await initializeService(service);+ updaterHandlers.updateDownloaded?.("v2.0.0");+ mockUpdater.download.mockClear();++ const pending = service.installUpdate();+ await Promise.resolve();+ fire();+ await flushPreInstallCheck();++ await expect(pending).resolves.toEqual({ installed: true });+ expect(mockUpdater.download).not.toHaveBeenCalled();+ expect(mockUpdater.quitAndInstall).toHaveBeenCalled();+ });++ it("gives up when the pre-install download stalls", async () => {+ await initializeService(service);+ updaterHandlers.updateDownloaded?.("v2.0.0");++ const pending = service.installUpdate();+ await Promise.resolve();+ updaterHandlers.updateAvailable?.({+ version: "v3.0.0",+ releaseNotes: null,+ });+ expect(mockUpdater.download).toHaveBeenCalled();++ await flushPreInstallCheck();+ await vi.advanceTimersByTimeAsync(DOWNLOAD_STALL_TIMEOUT_MS);++ await expect(pending).resolves.toEqual({ installed: false });+ expect(mockUpdater.quitAndInstall).not.toHaveBeenCalled();+ expect(service.getStatus()).toMatchObject({ downloading: true });+ });++ it("waits out a slow download while progress keeps arriving", async () => {+ await initializeService(service);+ updaterHandlers.updateDownloaded?.("v2.0.0");++ let settled = false;+ const pending = service.installUpdate().then((result) => {+ settled = true;+ return result;+ });+ await Promise.resolve();+ updaterHandlers.updateAvailable?.({+ version: "v3.0.0",+ releaseNotes: null,+ });+ await flushPreInstallCheck();++ for (let i = 0; i < 3; i++) {+ await vi.advanceTimersByTimeAsync(DOWNLOAD_STALL_TIMEOUT_MS - 1_000);+ updaterHandlers.downloadProgress?.({+ percent: 25 * (i + 1),+ bytesPerSecond: 1_000,+ transferred: 25 * (i + 1),+ total: 100,+ });+ }+ expect(settled).toBe(false);+ expect(mockUpdater.quitAndInstall).not.toHaveBeenCalled();++ updaterHandlers.updateDownloaded?.("v3.0.0");++ await expect(pending).resolves.toEqual({ installed: true });+ expect(mockUpdater.quitAndInstall).toHaveBeenCalled();+ expect(service.getStatus()).toMatchObject({ version: "v3.0.0" });+ });++ it("abandons a pending install when the service shuts down", async () => {+ await initializeService(service);+ updaterHandlers.updateDownloaded?.("v2.0.0");++ const pending = service.installUpdate();+ await Promise.resolve();+ service.shutdown();++ await expect(pending).resolves.toEqual({ installed: false });+ expect(mockUpdater.quitAndInstall).not.toHaveBeenCalled();+ expect(mockLifecycleService.setQuittingForUpdate).not.toHaveBeenCalled();+ });++ it("joins a second install request while the pre-install check is open", async () => {+ await initializeService(service);+ updaterHandlers.updateDownloaded?.("v2.0.0");++ const first = service.installUpdate();+ const second = service.installUpdate();+ await flushPreInstallCheck();++ await expect(first).resolves.toEqual({ installed: true });+ await expect(second).resolves.toEqual({ installed: true });+ expect(mockUpdater.quitAndInstall).toHaveBeenCalledTimes(1);+ });+it("rejects install while a newer update is re-downloading", async () => {await initializeService(service);service.setAutoDownloadEnabled(true);@@ -680,8 +827,7 @@ describe("UpdatesService", () => {);void service.installUpdate();- // Allow the synchronous part of installUpdate to run.- await Promise.resolve();+ await flushPreInstallCheck();expect(service.getStatus()).toEqual({checking: false,@@ -691,6 +837,21 @@ describe("UpdatesService", () => {});});+ it("keeps the staged update installable while the pre-install check runs", async () => {+ await initializeService(service);++ updaterHandlers.updateDownloaded?.("v2.0.0");+ void service.installUpdate();+ await Promise.resolve();++ expect(service.getStatus()).toEqual({+ checking: false,+ updateReady: true,+ installing: false,+ version: "v2.0.0",+ });+ });+it("returns available status when an update is found", async () => {await initializeService(service);@@ -1161,24 +1322,21 @@ describe("UpdatesService", () => {expect(service.hasUpdateReady).toBe(true);});- it("user check still shows existing notification when update is ready", async () => {+ it("user check re-notifies and still hits the feed when an update is staged", async () => {await initializeService(service);- // Simulate update downloaded- const downloadedHandler = updaterHandlers.updateDownloaded;- if (downloadedHandler) {- downloadedHandler("v2.0.0");- }+ updaterHandlers.updateDownloaded?.("v2.0.0");const readyHandler = vi.fn();service.on(UpdatesEvent.Ready, readyHandler);- // User check should show existing notification, not re-checkmockUpdater.check.mockClear();const result = service.checkForUpdates("user");+expect(result).toEqual({ success: true });- expect(mockUpdater.check).not.toHaveBeenCalled();expect(readyHandler).toHaveBeenCalledWith({ version: "v2.0.0" });+ expect(mockUpdater.check).toHaveBeenCalled();+ expect(service.hasUpdateReady).toBe(true);});it("preserves downloaded update when later updater errors fire", async () => {@@ -1496,7 +1654,7 @@ describe("UpdatesService", () => {new Promise(() => {}),);void service.installUpdate();- await Promise.resolve();+ await flushPreInstallCheck();const statusHandler = vi.fn();service.on(UpdatesEvent.Status, statusHandler);@@ -1533,7 +1691,7 @@ describe("UpdatesService", () => {new Promise(() => {}),);void service.installUpdate();- await Promise.resolve();+ await flushPreInstallCheck();const statusHandler = vi.fn();const readyHandler = vi.fn();@@ -1588,25 +1746,6 @@ describe("UpdatesService", () => {}),);});-- 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", () => {diff --git a/products/desktop/packages/core/src/updates/updates.ts b/products/desktop/packages/core/src/updates/updates.tsindex fea8be6abb18..746071bace82 100644--- a/products/desktop/packages/core/src/updates/updates.ts+++ b/products/desktop/packages/core/src/updates/updates.ts@@ -57,6 +57,8 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {// inside partial shutdown get cut off and quitAndInstall proceeds without// any teardown at all.private static readonly INSTALL_SHUTDOWN_TIMEOUT_MS = 20_000;+ private static readonly PRE_INSTALL_CHECK_TIMEOUT_MS = 5_000;+ private static readonly DOWNLOAD_STALL_TIMEOUT_MS = 60_000;@inject(UPDATE_LIFECYCLE_SERVICE)private lifecycle!: IUpdateLifecycle;@@ -99,6 +101,12 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {private autoDownloadEnabled = false;private lastProgressEmit = 0;private activeDownload: Promise<void> | null = null;+ private pendingInstall: Promise<InstallUpdateOutput> | null = null;+ private installIntent = false;+ private installGate: (() => void) | null = null;+ private installGateTimeoutId: ReturnType<typeof setTimeout> | null = null;+ private downloadStallTimeoutId: ReturnType<typeof setTimeout> | null = null;+ private isShuttingDown = false;get hasUpdateReady(): boolean {return this.isUpdateStaged();@@ -214,15 +222,10 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {}if (this.state === "ready" && source === "user") {- this.logStateTransition(this.state, {- source,- skippedBecauseUpdateStaged: true,- reason: "check skipped because update is already staged",- });this.pendingNotification = true;this.flushPendingNotification();this.emitStatus(this.stagedStatusPayload());- return { success: true };+ return this.performBackgroundCheck(source);}if (@@ -260,6 +263,11 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {return { installed: true };}+ if (this.pendingInstall !== null) {+ this.log.info("Install already requested, joining the in-flight request");+ return this.pendingInstall;+ }+if (this.state !== "ready") {this.log.warn("installUpdate called but no update is ready", {state: this.state,@@ -267,6 +275,107 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {return { installed: false };}+ const pending = this.runInstall();+ this.pendingInstall = pending;+ try {+ return await pending;+ } finally {+ this.pendingInstall = null;+ }+ }++ private async runInstall(): Promise<InstallUpdateOutput> {+ await this.waitForFreshestUpdate();++ if (this.isShuttingDown) {+ this.log.warn("Abandoning install because the service is shutting down", {+ stagedVersion: this.downloadedVersion,+ });+ return { installed: false };+ }++ if (this.state !== "ready") {+ this.log.warn("No update staged after the pre-install check", {+ state: this.state,+ });+ return { installed: false };+ }++ return this.performInstall();+ }++ private waitForFreshestUpdate(): Promise<void> {+ this.installIntent = true;+ this.log.info("Checking for a newer release before installing", {+ stagedVersion: this.downloadedVersion,+ });++ return new Promise<void>((resolve) => {+ this.installGate = resolve;+ this.installGateTimeoutId = setTimeout(() => {+ this.installGateTimeoutId = null;+ if (this.state === "downloading") {+ this.armDownloadStallWatchdog();+ return;+ }+ this.log.warn(+ "Pre-install update check timed out, installing the staged build",+ { stagedVersion: this.downloadedVersion },+ );+ this.settleInstallGate("pre-install check timed out");+ }, UpdatesService.PRE_INSTALL_CHECK_TIMEOUT_MS);++ if (this.checkTimeoutId === null) {+ this.performCheck();+ }+ });+ }++ // Settle only: the partial build must not be installed.+ private armDownloadStallWatchdog(): void {+ this.clearDownloadStallWatchdog();+ this.downloadStallTimeoutId = setTimeout(() => {+ this.downloadStallTimeoutId = null;+ this.log.warn("Pre-install download stalled, abandoning the install", {+ stalledForMs: UpdatesService.DOWNLOAD_STALL_TIMEOUT_MS,+ stagedVersion: this.downloadedVersion,+ incomingVersion: this.availableInfo?.version ?? null,+ });+ this.settleInstallGate("pre-install download stalled");+ }, UpdatesService.DOWNLOAD_STALL_TIMEOUT_MS);+ }++ private clearDownloadStallWatchdog(): void {+ if (this.downloadStallTimeoutId !== null) {+ clearTimeout(this.downloadStallTimeoutId);+ this.downloadStallTimeoutId = null;+ }+ }++ private settleInstallGate(reason: string): void {+ this.clearDownloadStallWatchdog();++ if (this.installGate === null) {+ return;+ }++ this.log.info("Pre-install check settled", {+ reason,+ stagedVersion: this.downloadedVersion,+ state: this.state,+ });++ if (this.installGateTimeoutId !== null) {+ clearTimeout(this.installGateTimeoutId);+ this.installGateTimeoutId = null;+ }+ const resolve = this.installGate;+ this.installGate = null;+ this.installIntent = false;+ resolve();+ }++ private async performInstall(): Promise<InstallUpdateOutput> {this.log.info("Installing update and restarting...", {downloadedVersion: this.downloadedVersion,});@@ -382,6 +491,7 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {reason: "updater error ignored because update is staged",error: error.message,});+ this.settleInstallGate("updater error while staged");return;}@@ -399,6 +509,7 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {error: error.message,});this.emitStatus(this.stagedStatusPayload());+ this.settleInstallGate("updater error, staged build still installable");return;}this.lastError = error.message;@@ -407,6 +518,7 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {checking: false,error: error.message,});+ this.settleInstallGate("updater error with nothing staged");}}@@ -439,6 +551,7 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {incomingVersion: info.version,},);+ this.settleInstallGate("staged build is already the newest on the feed");return;}@@ -454,13 +567,16 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {this.availableInfo = info;this.downloadProgress = null;- if (this.autoDownloadEnabled) {+ if (this.autoDownloadEnabled || this.installIntent) {this.transitionTo("downloading", {- reason: "update available (auto-download)",+ reason: this.installIntent+ ? "newer build found during pre-install check"+ : "update available (auto-download)",incomingVersion: info.version,});- this.log.info("Update available, auto-downloading...", {+ this.log.info("Update available, downloading...", {version: info.version,+ forInstall: this.installIntent,});this.queueDownload();this.emitStatus(this.downloadingStatusPayload());@@ -482,6 +598,9 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {return;}this.downloadProgress = progress;+ if (this.downloadStallTimeoutId !== null) {+ this.armDownloadStallWatchdog();+ }const now = Date.now();if (now - this.lastProgressEmit >= 400 || progress.percent >= 100) {this.lastProgressEmit = now;@@ -496,6 +615,7 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {this.log.info("Ignoring update-not-available because update is staged", {downloadedVersion: this.downloadedVersion,});+ this.settleInstallGate("feed reports no update beyond the staged build");return;}@@ -513,6 +633,9 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {reason: "feed no longer offers an update, keeping staged update",});this.emitStatus(this.stagedStatusPayload());+ this.settleInstallGate(+ "feed pulled the newer build, staged one stands",+ );return;}this.transitionTo("idle", { reason: "no update available" });@@ -521,6 +644,7 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {upToDate: true,version: this.appMeta.version,});+ this.settleInstallGate("nothing left to install");}}@@ -535,6 +659,7 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {existingVersion: this.downloadedVersion,incomingVersion: version,});+ this.settleInstallGate("duplicate update-downloaded event");return;}@@ -558,6 +683,8 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {version: this.downloadedVersion,});}++ this.settleInstallGate("newer build downloaded and staged");}private flushPendingNotification(): void {@@ -604,6 +731,7 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {this.lastError = message;this.transitionTo("error", { error: message });this.emitStatus({ checking: false, error: message });+ this.settleInstallGate("update check timed out");return;}if (this.state === "available") {@@ -674,8 +802,10 @@ export class UpdatesService extends TypedEventEmitter<UpdatesEvents> {@preDestroy()shutdown(): void {+ this.isShuttingDown = true;this.clearCheckTimeout();this.clearCheckInterval();+ this.settleInstallGate("service shutting down");for (const unsub of this.unsubscribes) unsub();this.unsubscribes = [];}