Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(desktop): guard updater events after window destroy (#3871)

Naiyuan Qing3f98ada5470d
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index c5dc326a96..e75b424834 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -165,10 +165,15 @@ function createWindow(): void {
additionalArguments: [`--multica-locale=${systemLocale}`],
},
});
+ const window = mainWindow;
+
+ window.on("closed", () => {
+ if (mainWindow === window) mainWindow = null;
+ });
// Strip Origin header from WebSocket upgrade requests so the server's
// origin whitelist doesn't reject connections from localhost dev origins.
- mainWindow.webContents.session.webRequest.onBeforeSendHeaders(
+ window.webContents.session.webRequest.onBeforeSendHeaders(
{ urls: ["wss://*/*", "ws://*/*"] },
(details, callback) => {
delete details.requestHeaders["Origin"];
@@ -176,8 +181,8 @@ function createWindow(): void {
},
);
- mainWindow.on("ready-to-show", () => {
- mainWindow?.show();
+ window.on("ready-to-show", () => {
+ window.show();
});
// Detect OS language changes while the app is running. Electron has no
@@ -185,14 +190,14 @@ function createWindow(): void {
// catches the common case where users switch System Settings → Language
// and bring the app back. The renderer decides whether to act (it ignores
// the signal when the user has an explicit Settings choice).
- mainWindow.on("focus", () => {
+ window.on("focus", () => {
const current = getSystemLocale();
if (current === lastKnownSystemLocale) return;
lastKnownSystemLocale = current;
- mainWindow?.webContents.send("locale:system-changed", current);
+ window.webContents.send("locale:system-changed", current);
});
- mainWindow.webContents.setWindowOpenHandler((details) => {
+ window.webContents.setWindowOpenHandler((details) => {
openExternalSafely(details.url);
return { action: "deny" };
});
@@ -201,8 +206,8 @@ function createWindow(): void {
// both the renderer keydown AND the application menu accelerator, so
// anything we own here (reload-block, zoom) is the sole handler for
// that combination — no double-fire with the macOS default View menu.
- mainWindow.webContents.on("before-input-event", (event, input) => {
- if (handleAppShortcut(input, mainWindow!.webContents)) {
+ window.webContents.on("before-input-event", (event, input) => {
+ if (handleAppShortcut(input, window.webContents)) {
event.preventDefault();
}
});
@@ -224,7 +229,7 @@ function createWindow(): void {
// Forward every renderer-side console.* call. The detail object also
// carries source URL + line — included so a thrown stack trace from
// window.onerror is traceable back to a file.
- mainWindow.webContents.on("console-message", (details) => {
+ window.webContents.on("console-message", (details) => {
const { level, message, sourceId, lineNumber } = details;
log(level, `${message} (${sourceId}:${lineNumber})`);
});
@@ -232,7 +237,7 @@ function createWindow(): void {
// Fires when loadURL / loadFile can't reach its target (dev server
// not up yet, network blip, file missing). errorCode is a Chromium
// net error number; -3 = ABORTED is normal during HMR and skipped.
- mainWindow.webContents.on(
+ window.webContents.on(
"did-fail-load",
(_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
if (errorCode === -3) return;
@@ -245,20 +250,20 @@ function createWindow(): void {
}
- installRendererRecoveryHandlers(mainWindow as unknown as RendererRecoveryWindow, {
+ installRendererRecoveryHandlers(window as unknown as RendererRecoveryWindow, {
isDev: is.dev,
showReloadPrompt: createElectronReloadPrompt((options) =>
- dialog.showMessageBox(mainWindow!, options),
+ dialog.showMessageBox(window, options),
),
});
- installContextMenu(mainWindow.webContents);
- installNavigationGestures(mainWindow);
+ installContextMenu(window.webContents);
+ installNavigationGestures(window);
if (is.dev && process.env["ELECTRON_RENDERER_URL"]) {
- mainWindow.loadURL(process.env["ELECTRON_RENDERER_URL"]);
+ window.loadURL(process.env["ELECTRON_RENDERER_URL"]);
} else {
- mainWindow.loadFile(join(__dirname, "../renderer/index.html"));
+ window.loadFile(join(__dirname, "../renderer/index.html"));
}
}
diff --git a/apps/desktop/src/main/updater.test.ts b/apps/desktop/src/main/updater.test.ts
new file mode 100644
index 0000000000..314e5b5cf5
--- /dev/null
+++ b/apps/desktop/src/main/updater.test.ts
@@ -0,0 +1,170 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { BrowserWindow, WebContents } from "electron";
+
+type Handler = (...args: unknown[]) => void;
+
+const ctx = vi.hoisted(() => ({
+ handlers: new Map<string, Handler[]>(),
+ ipcHandle: vi.fn(),
+ checkForUpdates: vi.fn(async () => ({
+ updateInfo: { version: "0.3.18" },
+ isUpdateAvailable: false,
+ })),
+ downloadUpdate: vi.fn(),
+ quitAndInstall: vi.fn(),
+ getVersion: vi.fn(() => "0.3.17"),
+}));
+
+vi.mock("electron-updater", () => {
+ const autoUpdater = {
+ autoDownload: false,
+ autoInstallOnAppQuit: false,
+ channel: undefined as string | undefined,
+ on: vi.fn((event: string, handler: Handler) => {
+ const handlers = ctx.handlers.get(event) ?? [];
+ handlers.push(handler);
+ ctx.handlers.set(event, handlers);
+ return autoUpdater;
+ }),
+ checkForUpdates: ctx.checkForUpdates,
+ downloadUpdate: ctx.downloadUpdate,
+ quitAndInstall: ctx.quitAndInstall,
+ };
+ return { autoUpdater };
+});
+
+vi.mock("electron", () => ({
+ app: {
+ getVersion: ctx.getVersion,
+ },
+ BrowserWindow: class BrowserWindow {},
+ ipcMain: {
+ handle: ctx.ipcHandle,
+ },
+}));
+
+import { setupAutoUpdater } from "./updater";
+
+function emitUpdater(event: string, ...args: unknown[]) {
+ for (const handler of ctx.handlers.get(event) ?? []) {
+ handler(...args);
+ }
+}
+
+function makeWindow() {
+ const send = vi.fn();
+ return {
+ win: {
+ isDestroyed: () => false,
+ webContents: {
+ isDestroyed: () => false,
+ send,
+ },
+ } as unknown as BrowserWindow,
+ send,
+ };
+}
+
+function makeDestroyedWindow() {
+ return {
+ isDestroyed: () => true,
+ get webContents(): WebContents {
+ throw new TypeError("Object has been destroyed");
+ },
+ } as unknown as BrowserWindow;
+}
+
+function makeWindowWithDestroyedWebContents() {
+ const send = vi.fn(() => {
+ throw new TypeError("Object has been destroyed");
+ });
+ return {
+ win: {
+ isDestroyed: () => false,
+ webContents: {
+ isDestroyed: () => true,
+ send,
+ },
+ } as unknown as BrowserWindow,
+ send,
+ };
+}
+
+function makeWindowWithThrowingSend(error: Error) {
+ const send = vi.fn(() => {
+ throw error;
+ });
+ return {
+ win: {
+ isDestroyed: () => false,
+ webContents: {
+ isDestroyed: () => false,
+ send,
+ },
+ } as unknown as BrowserWindow,
+ send,
+ };
+}
+
+describe("setupAutoUpdater", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ ctx.handlers.clear();
+ ctx.ipcHandle.mockClear();
+ ctx.checkForUpdates.mockClear();
+ ctx.downloadUpdate.mockClear();
+ ctx.quitAndInstall.mockClear();
+ ctx.getVersion.mockClear();
+ });
+
+ afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ });
+
+ it("forwards update progress to a live renderer", () => {
+ const { win, send } = makeWindow();
+ setupAutoUpdater(() => win);
+
+ emitUpdater("download-progress", { percent: 42 });
+
+ expect(send).toHaveBeenCalledWith("updater:download-progress", {
+ percent: 42,
+ });
+ });
+
+ it("skips update progress when the BrowserWindow has already been destroyed", () => {
+ setupAutoUpdater(() => makeDestroyedWindow());
+
+ expect(() => emitUpdater("download-progress", { percent: 42 })).not.toThrow();
+ });
+
+ it("skips update progress when the BrowserWindow webContents has already been destroyed", () => {
+ const { win, send } = makeWindowWithDestroyedWebContents();
+ setupAutoUpdater(() => win);
+
+ expect(() => emitUpdater("download-progress", { percent: 42 })).not.toThrow();
+ expect(send).not.toHaveBeenCalled();
+ });
+
+ it("skips update progress when webContents.send loses a destroy race", () => {
+ const { win, send } = makeWindowWithThrowingSend(
+ new TypeError("Object has been destroyed"),
+ );
+ setupAutoUpdater(() => win);
+
+ expect(() => emitUpdater("download-progress", { percent: 42 })).not.toThrow();
+ expect(send).toHaveBeenCalledWith("updater:download-progress", {
+ percent: 42,
+ });
+ });
+
+ it("rethrows non-destroy errors from webContents.send", () => {
+ const { win } = makeWindowWithThrowingSend(new Error("boom"));
+ setupAutoUpdater(() => win);
+
+ expect(() => emitUpdater("download-progress", { percent: 42 })).toThrow(
+ "boom",
+ );
+ });
+});
diff --git a/apps/desktop/src/main/updater.ts b/apps/desktop/src/main/updater.ts
index 0f3657022d..d622a6af3a 100644
--- a/apps/desktop/src/main/updater.ts
+++ b/apps/desktop/src/main/updater.ts
@@ -1,5 +1,5 @@
-import { autoUpdater, UpdateDownloadedEvent } from "electron-updater";
-import { app, BrowserWindow, ipcMain } from "electron";
+import { autoUpdater, type UpdateDownloadedEvent } from "electron-updater";
+import { app, type BrowserWindow, ipcMain } from "electron";
// Silent background updates: electron-updater downloads on its own as soon
// as `update-available` fires; we only surface UI when the package is fully
@@ -29,6 +29,32 @@ export type ManualUpdateCheckResult =
}
| { ok: false; error: string };
+type RendererChannel =
+ | "updater:update-available"
+ | "updater:download-progress"
+ | "updater:update-downloaded";
+
+function isDestroyedObjectError(err: unknown): boolean {
+ return err instanceof Error && err.message.includes("Object has been destroyed");
+}
+
+function sendToLiveRenderer(
+ win: BrowserWindow | null,
+ channel: RendererChannel,
+ payload: unknown,
+): void {
+ if (!win || win.isDestroyed()) return;
+
+ try {
+ const { webContents } = win;
+ if (webContents.isDestroyed()) return;
+ webContents.send(channel, payload);
+ } catch (err) {
+ if (isDestroyedObjectError(err)) return;
+ throw err;
+ }
+}
+
// Single-flight guard around checkForUpdates(). With autoDownload=true the
// startup, periodic, and manual triggers can all kick off downloads, and
// overlapping calls have caused duplicate download warnings in the past
@@ -62,23 +88,20 @@ export function setupAutoUpdater(getMainWindow: () => BrowserWindow | null): voi
autoUpdater.on("update-available", (info) => {
// Forwarded for renderer-side state tracking only; the notification UI
// does not render an "available" affordance with autoDownload=true.
- const win = getMainWindow();
- win?.webContents.send("updater:update-available", {
+ sendToLiveRenderer(getMainWindow(), "updater:update-available", {
version: info.version,
releaseNotes: info.releaseNotes,
});
});
autoUpdater.on("download-progress", (progress) => {
- const win = getMainWindow();
- win?.webContents.send("updater:download-progress", {
+ sendToLiveRenderer(getMainWindow(), "updater:download-progress", {
percent: progress.percent,
});
});
autoUpdater.on("update-downloaded", (info: UpdateDownloadedEvent) => {
- const win = getMainWindow();
- win?.webContents.send("updater:update-downloaded", {
+ sendToLiveRenderer(getMainWindow(), "updater:update-downloaded", {
version: info.version,
releaseNotes: info.releaseNotes,
});