Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(updates): announce once per version, wait for Squirrel.Mac, quiet background failures

review6e6b124a174a
diff --git a/src/main/index.ts b/src/main/index.ts
index bb2b04583..142680015 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -163,7 +163,7 @@ import {
generateGroupName,
generateTerminalName
} from '../core/commit-message'
-import { initUpdater } from './updater'
+import { initUpdater, type UpdaterHandle } from './updater'
import { requestRendererFlush } from './renderer-flush'
import { fetchCheck } from '../core/check'
import {
@@ -822,7 +822,9 @@ function confirmQuit(parentWin: BrowserWindow | null): Promise<boolean> {
// down in before-quit. Its state is fed from facts main already holds — the unread count the
// renderer sends for the badge, and the phone-access setting — never from the hook-event stream.
let backgroundTray: BackgroundTray | undefined
-const trayState: TrayState = { unread: 0, phoneAccess: false }
+const trayState: TrayState = { unread: 0, phoneAccess: false, updateReady: null }
+// The updater's guarded restart path, for the tray's "Restart to update" item (set in whenReady).
+let updater: UpdaterHandle | undefined
/** Hide-on-close is in force off macOS only while the tray actually exists: a tray that failed to
* construct must not turn the window's × into a hide with no way back. */
@@ -865,7 +867,12 @@ function syncBackgroundTray(): void {
initial: { ...trayState },
// Quit is the ordinary app.quit(): before-quit (and its confirm dialog) runs exactly as for
// Ctrl+Q. `quitting` is NOT set here — a cancelled confirm must leave the × hiding again.
- onAction: (action) => (action === 'open' ? showMainWindowFromBackground() : app.quit())
+ onAction: (action) =>
+ action === 'open'
+ ? showMainWindowFromBackground()
+ : action === 'restart-update'
+ ? updater?.restartToUpdate()
+ : app.quit()
})
} catch (e) {
console.warn('[tray] could not create the notification-area icon; window close will quit', e)
@@ -2369,9 +2376,21 @@ app.whenReady().then(async () => {
// quitAndInstall closes all windows then calls app.quit(), which our hide-on-close would block.
// Also skip the confirm dialog — this is a restart-to-update the user already asked for via the
// "Restart to update" card, not an exit, and a modal here would just block the install.
- initUpdater(() => {
- quitting = true
- skipQuitConfirmation = true
+ // Both flags flip only when the install REALLY starts (on macOS: after Squirrel.Mac staged the
+ // update — updater.ts `restartToUpdate`), and are put back if it then fails.
+ updater = initUpdater({
+ onBeforeRestart: () => {
+ quitting = true
+ skipQuitConfirmation = true
+ },
+ onRestartAborted: () => {
+ quitting = false
+ skipQuitConfirmation = false
+ },
+ onUpdateReady: (version) => {
+ trayState.updateReady = version
+ backgroundTray?.update({ ...trayState })
+ }
})
// Prepare-for-update (Windows session host, issue #829). The user confirmed the whole flow in
// its own dialog, so the quit at its end skips the ordinary quit confirmation, like the
diff --git a/src/main/tray-model.test.ts b/src/main/tray-model.test.ts
index 7e3cb6f79..b32285427 100644
--- a/src/main/tray-model.test.ts
+++ b/src/main/tray-model.test.ts
@@ -56,3 +56,20 @@ describe('trayIconPath', () => {
expect(trayIconPath({ ...base, isPackaged: false })).toBe(join('/b', 'icon.png'))
})
})
+
+describe('the restart-to-update item', () => {
+ it('appears only while an update is ready, above Quit, with its version', () => {
+ expect(trayMenuModel({ unread: 0, phoneAccess: false }).some((i) => i.type === 'normal' && i.action === 'restart-update')).toBe(false)
+ expect(trayMenuModel({ unread: 0, phoneAccess: false, updateReady: null }).some((i) => i.type === 'normal' && i.action === 'restart-update')).toBe(false)
+ const items = trayMenuModel({ unread: 0, phoneAccess: false, updateReady: '0.5.0' })
+ const idx = items.findIndex((i) => i.type === 'normal' && i.action === 'restart-update')
+ expect(items[idx]).toEqual({ type: 'normal', label: 'Restart to update v0.5.0', enabled: true, action: 'restart-update' })
+ expect(items.findIndex((i) => i.type === 'normal' && i.action === 'quit')).toBeGreaterThan(idx)
+ })
+
+ it('changes the rebuild key, so the menu picks it up', () => {
+ expect(trayStateKey({ unread: 0, phoneAccess: false, updateReady: '0.5.0' })).not.toBe(
+ trayStateKey({ unread: 0, phoneAccess: false })
+ )
+ })
+})
diff --git a/src/main/tray-model.ts b/src/main/tray-model.ts
index b1d9c9a50..8bb3c2816 100644
--- a/src/main/tray-model.ts
+++ b/src/main/tray-model.ts
@@ -7,9 +7,12 @@
export interface TrayState {
unread: number
phoneAccess: boolean
+ /** A downloaded update installable by a restart (its version), fed by the updater. A background-
+ * mode app is rarely quit, so install-on-quit alone could leave it waiting for days. */
+ updateReady?: string | null
}
-export type TrayAction = 'open' | 'quit'
+export type TrayAction = 'open' | 'quit' | 'restart-update'
export type TrayMenuItem =
| { type: 'separator' }
@@ -33,6 +36,9 @@ export function trayMenuModel(state: TrayState): TrayMenuItem[] {
if (unread > 0) items.push({ type: 'normal', label: unreadLabel(unread), enabled: false })
items.push({ type: 'normal', label: `Phone access: ${state.phoneAccess ? 'on' : 'off'}`, enabled: false })
items.push({ type: 'separator' })
+ // The same guarded restart the update card's button takes (updater.ts `restartToUpdate`).
+ if (state.updateReady)
+ items.push({ type: 'normal', label: `Restart to update v${state.updateReady}`, enabled: true, action: 'restart-update' })
// Quit goes through the ordinary app.quit() → before-quit path (confirm dialog included), so a
// tray quit tears down exactly what the menu Quit (Ctrl+Q on Linux, File → Exit on Windows) does.
items.push({ type: 'normal', label: 'Quit nodeterm', enabled: true, action: 'quit' })
@@ -46,7 +52,7 @@ export function trayTooltip(state: TrayState): string {
/** Identity of a state for rebuild de-duplication: the menu is rebuilt only when this changes. */
export function trayStateKey(state: TrayState): string {
- return `${normalizeUnread(state.unread)}|${state.phoneAccess ? 1 : 0}`
+ return `${normalizeUnread(state.unread)}|${state.phoneAccess ? 1 : 0}|${state.updateReady ?? ''}`
}
/**
diff --git a/src/main/updater.no-channel.test.ts b/src/main/updater.no-channel.test.ts
index de5b715c1..ad3eede12 100644
--- a/src/main/updater.no-channel.test.ts
+++ b/src/main/updater.no-channel.test.ts
@@ -34,7 +34,10 @@ vi.mock('electron', () => ({
ipcHandle[ch] = fn
}
},
- Notification: Object.assign(function () {}, { isSupported: () => false })
+ Notification: Object.assign(function () {}, { isSupported: () => false }),
+ // Electron's own (Squirrel) autoUpdater — only wired on darwin; the restart flow is pinned in
+ // updater.restart.test.ts.
+ autoUpdater: { on: () => {} }
}))
// `vi.mock` factories are hoisted above every const, so the double the factory returns has to be
@@ -47,6 +50,7 @@ const { updaterEvents, autoUpdater } = vi.hoisted(() => {
autoDownload: true,
autoInstallOnAppQuit: true,
checkForUpdates: vi.fn(() => Promise.resolve(null)),
+ downloadUpdate: vi.fn(() => Promise.resolve([])),
quitAndInstall: vi.fn(),
on: (ev: string, fn: (...a: unknown[]) => void) => {
events[ev] = fn
@@ -224,7 +228,7 @@ describe('the unsigned Windows beta (manual marker)', () => {
onBeforeRestart.mockClear()
setPlatform('win32')
packageWith('manual')
- initUpdater(onBeforeRestart)
+ initUpdater({ onBeforeRestart })
})
it('checks the feed on launch and every six hours', () => {
@@ -253,11 +257,16 @@ describe('the unsigned Windows beta (manual marker)', () => {
// that does not serve latest.yml yet) — that must not put an error card up on every launch.
updaterEvents['error']?.(new Error('HttpError: 404 latest.yml'))
expect(channels()).not.toContain(IPC.appUpdateError)
- autoUpdater.checkForUpdates.mockImplementationOnce(() => Promise.reject(new Error('offline')))
+ // electron-updater emits 'error' for the rejected manual check too; that listener is the one
+ // owner of the report (the catch only logs), so exactly one card comes up.
+ autoUpdater.checkForUpdates.mockImplementationOnce(() => {
+ updaterEvents['error']?.(new Error('offline'))
+ return Promise.reject(new Error('offline'))
+ })
check()
await Promise.resolve()
await Promise.resolve()
- expect(channels()).toContain(IPC.appUpdateError)
+ expect(channels().filter((c) => c === IPC.appUpdateError)).toHaveLength(1)
})
it('refuses restart-to-update in main: quitAndInstall never runs', () => {
@@ -269,22 +278,31 @@ describe('the unsigned Windows beta (manual marker)', () => {
})
describe('restart-to-update elsewhere', () => {
- it('a self-installing release still restarts into the update', () => {
+ it('a self-installing release still restarts into a downloaded update', async () => {
+ // (macOS's wait for Squirrel.Mac is pinned in updater.restart.test.ts; AppImage installs from
+ // the downloaded file, so it is the immediate case.)
const onBeforeRestart = vi.fn()
- setPlatform('darwin')
+ setPlatform('linux')
+ process.env.APPIMAGE = '/tmp/nodeterm.AppImage'
packageWith(undefined)
- initUpdater(onBeforeRestart)
+ initUpdater({ onBeforeRestart, flushRenderer: () => Promise.resolve() })
+ updaterEvents['update-downloaded']?.({ version: '9.9.9' })
restart()
+ await vi.waitFor(() => expect(autoUpdater.quitAndInstall).toHaveBeenCalledTimes(1))
expect(onBeforeRestart).toHaveBeenCalledTimes(1)
- expect(autoUpdater.quitAndInstall).toHaveBeenCalledTimes(1)
})
- it('a Linux .deb still surfaces an update error event, as before', () => {
+ it('a Linux .deb: a BACKGROUND check failure is logged, not carded; a user check still reports', () => {
setPlatform('linux')
packageWith(undefined)
initUpdater()
updaterEvents['error']?.(new Error('boom'))
- expect(channels()).toContain(IPC.appUpdateError)
+ expect(channels()).not.toContain(IPC.appUpdateError)
+ check()
+ updaterEvents['error']?.(new Error('boom'))
+ expect(sent.filter((s) => s.channel === IPC.appUpdateError)).toEqual([
+ { channel: IPC.appUpdateError, payload: 'boom' }
+ ])
})
it('a Linux .deb (manual-install) refuses it too', () => {
diff --git a/src/main/updater.restart.test.ts b/src/main/updater.restart.test.ts
new file mode 100644
index 000000000..1369b986a
--- /dev/null
+++ b/src/main/updater.restart.test.ts
@@ -0,0 +1,358 @@
+// The updater's event policy and restart flow, wired (the pure rules live in
+// src/shared/update-gate.test.ts and update-platform.test.ts). Platform is injected through
+// process.platform + the packaged marker, so every branch runs on Linux CI.
+//
+// - macOS: "Restart to update" must not flag the app as quitting until Squirrel.Mac has staged the
+// update, must say it is preparing meanwhile, and must install exactly once.
+// - a staged update is announced (and notified) once per version, not every six hours.
+// - background failures log; a failed background download retries on a backoff.
+import { EventEmitter } from 'events'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import fs from 'fs'
+import path from 'path'
+import { IPC } from '../shared/ipc'
+
+const { ipcOn, sent, appMock, notifications, nativeUpdater } = vi.hoisted(() => {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const { EventEmitter: EE } = require('events') as typeof import('events')
+ return {
+ ipcOn: {} as Record<string, (...a: unknown[]) => void>,
+ sent: [] as Array<{ channel: string; payload?: unknown }>,
+ appMock: { isPackaged: true, appPath: '' },
+ notifications: [] as string[],
+ nativeUpdater: new EE()
+ }
+})
+
+vi.mock('electron', () => ({
+ app: {
+ get isPackaged() {
+ return appMock.isPackaged
+ },
+ getAppPath: () => appMock.appPath,
+ getVersion: () => '0.3.7'
+ },
+ ipcMain: {
+ on: (ch: string, fn: (...a: unknown[]) => void) => {
+ ipcOn[ch] = fn
+ },
+ handle: () => {},
+ removeListener: () => {}
+ },
+ Notification: Object.assign(
+ function (this: { on: () => void; show: () => void }, opts: { body: string }) {
+ notifications.push(opts.body)
+ this.on = () => {}
+ this.show = () => {}
+ },
+ { isSupported: () => true }
+ ),
+ autoUpdater: nativeUpdater
+}))
+
+const { autoUpdater } = vi.hoisted(() => {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const { EventEmitter: EE } = require('events') as typeof import('events')
+ const em = new EE()
+ return {
+ autoUpdater: Object.assign(em, {
+ autoDownload: true,
+ autoInstallOnAppQuit: true,
+ checkForUpdates: vi.fn(() => Promise.resolve(null)),
+ downloadUpdate: vi.fn(() => Promise.resolve([])),
+ quitAndInstall: vi.fn()
+ })
+ }
+})
+vi.mock('electron-updater', () => ({ autoUpdater }))
+vi.mock('./main-window', () => ({
+ getMainWindow: () => null,
+ sendToMain: (channel: string, payload?: unknown) => sent.push({ channel, payload })
+}))
+vi.mock('./notifications', () => ({ retainUntilDismissed: () => {} }))
+
+import { initUpdater, PREPARE_TIMEOUT_MS } from './updater'
+
+const realReadFileSync = fs.readFileSync
+const realPlatform = process.platform
+const realAppImage = process.env.APPIMAGE
+
+function release(platform: string): void {
+ Object.defineProperty(process, 'platform', { value: platform, configurable: true })
+ appMock.appPath = path.join(path.sep, 'fake-app-path')
+ const target = path.join(appMock.appPath, 'package.json')
+ vi.spyOn(fs, 'readFileSync').mockImplementation(((file: unknown, ...rest: unknown[]) =>
+ file === target ? JSON.stringify({ name: 'x' }) : realReadFileSync(file as never, ...(rest as []))) as typeof fs.readFileSync)
+}
+
+const hooks = () => ({
+ onBeforeRestart: vi.fn(),
+ onRestartAborted: vi.fn(),
+ onUpdateReady: vi.fn(),
+ flushRenderer: vi.fn(() => Promise.resolve('flushed'))
+})
+
+const of = (ch: string) => sent.filter((s) => s.channel === ch)
+const restart = (): void => ipcOn[IPC.appRestartToUpdate]?.()
+const check = (): void => ipcOn[IPC.appCheckForUpdates]?.()
+const flushMicrotasks = async (): Promise<void> => {
+ for (let i = 0; i < 5; i++) await Promise.resolve()
+}
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ for (const k of Object.keys(ipcOn)) delete ipcOn[k]
+ sent.length = 0
+ notifications.length = 0
+ ;(autoUpdater as EventEmitter).removeAllListeners()
+ nativeUpdater.removeAllListeners()
+ autoUpdater.checkForUpdates.mockClear()
+ autoUpdater.downloadUpdate.mockClear()
+ autoUpdater.quitAndInstall.mockClear()
+ autoUpdater.autoDownload = true
+ autoUpdater.autoInstallOnAppQuit = true
+ appMock.isPackaged = true
+ delete process.env.APPIMAGE
+})
+
+afterEach(() => {
+ vi.restoreAllMocks()
+ vi.useRealTimers()
+ Object.defineProperty(process, 'platform', { value: realPlatform, configurable: true })
+ if (realAppImage === undefined) delete process.env.APPIMAGE
+ else process.env.APPIMAGE = realAppImage
+})
+
+describe('macOS restart waits for Squirrel.Mac', () => {
+ let h: ReturnType<typeof hooks>
+ beforeEach(() => {
+ release('darwin')
+ h = hooks()
+ initUpdater(h)
+ autoUpdater.emit('update-downloaded', { version: '1.1.0' })
+ })
+
+ it('before native staging: says preparing, flags nothing, installs nothing', async () => {
+ restart()
+ await flushMicrotasks()
+ expect(of(IPC.appUpdateInstalling)).toEqual([
+ { channel: IPC.appUpdateInstalling, payload: { phase: 'preparing', version: '1.1.0' } }
+ ])
+ expect(h.onBeforeRestart).not.toHaveBeenCalled()
+ expect(autoUpdater.quitAndInstall).not.toHaveBeenCalled()
+ })
+
+ it('once staged: restarting → flush → flags → quitAndInstall, exactly once despite double clicks', async () => {
+ restart()
+ restart()
+ nativeUpdater.emit('update-downloaded')
+ await flushMicrotasks()
+ restart()
+ await flushMicrotasks()
+ expect(of(IPC.appUpdateInstalling).map((s) => (s.payload as { phase: string }).phase)).toEqual([
+ 'preparing',
+ 'restarting'
+ ])
+ expect(h.flushRenderer).toHaveBeenCalledTimes(1)
+ expect(h.onBeforeRestart).toHaveBeenCalledTimes(1)
+ expect(autoUpdater.quitAndInstall).toHaveBeenCalledTimes(1)
+ expect(h.flushRenderer.mock.invocationCallOrder[0]).toBeLessThan(h.onBeforeRestart.mock.invocationCallOrder[0])
+ })
+
+ it('already staged before the click: installs at once', async () => {
+ nativeUpdater.emit('update-downloaded')
+ restart()
+ await flushMicrotasks()
+ expect(of(IPC.appUpdateInstalling).map((s) => (s.payload as { phase: string }).phase)).toEqual(['restarting'])
+ expect(autoUpdater.quitAndInstall).toHaveBeenCalledTimes(1)
+ })
+
+ it('a native error while preparing aborts with a card, and a later click may try again', async () => {
+ restart()
+ nativeUpdater.emit('error', new Error('Code signature did not pass validation'))
+ await flushMicrotasks()
+ expect(of(IPC.appUpdateError)).toEqual([
+ { channel: IPC.appUpdateError, payload: 'Code signature did not pass validation' }
+ ])
+ expect(h.onBeforeRestart).not.toHaveBeenCalled()
+ expect(h.onRestartAborted).not.toHaveBeenCalled() // nothing was flagged, nothing to undo
+ nativeUpdater.emit('update-downloaded')
+ restart()
+ await flushMicrotasks()
+ expect(autoUpdater.quitAndInstall).toHaveBeenCalledTimes(1)
+ })
+
+ it('a staging failure BEFORE the click is reported on the click instead of hanging in preparing', async () => {
+ nativeUpdater.emit('error', new Error('staging failed'))
+ restart()
+ await flushMicrotasks()
+ expect(of(IPC.appUpdateInstalling)).toEqual([])
+ expect(of(IPC.appUpdateError).map((s) => s.payload)).toEqual(['staging failed'])
+ })
+
+ it('an error after quitAndInstall undoes the quitting flags', async () => {
+ nativeUpdater.emit('update-downloaded')
+ restart()
+ await flushMicrotasks()
+ nativeUpdater.emit('error', new Error('install failed'))
+ expect(h.onRestartAborted).toHaveBeenCalledTimes(1)
+ expect(of(IPC.appUpdateError).map((s) => s.payload)).toEqual(['install failed'])
+ })
+
+ it('a background check failing while preparing does not cancel the restart', async () => {
+ restart()
+ autoUpdater.emit('error', new Error('net::ERR_INTERNET_DISCONNECTED'))
+ nativeUpdater.emit('update-downloaded')
+ await flushMicrotasks()
+ expect(of(IPC.appUpdateError)).toEqual([])
+ expect(autoUpdater.quitAndInstall).toHaveBeenCalledTimes(1)
+ })
+
+ it('gives up on a click that waits too long, without cancelling the update', async () => {
+ restart()
+ vi.advanceTimersByTime(PREPARE_TIMEOUT_MS)
+ await flushMicrotasks()
+ expect(of(IPC.appUpdateError)).toHaveLength(1)
+ expect(autoUpdater.quitAndInstall).not.toHaveBeenCalled()
+ })
+
+ it('a flush that times out still installs', async () => {
+ h.flushRenderer.mockImplementation(() => Promise.resolve('timeout'))
+ nativeUpdater.emit('update-downloaded')
+ restart()
+ await flushMicrotasks()
+ expect(autoUpdater.quitAndInstall).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('other self-install platforms install from the download', () => {
+ it('Linux AppImage: restarting → quitAndInstall immediately, no native wait', async () => {
+ release('linux')
+ process.env.APPIMAGE = '/tmp/nodeterm.AppImage'
+ const h = hooks()
+ initUpdater(h)
+ autoUpdater.emit('update-downloaded', { version: '1.1.0' })
+ restart()
+ await flushMicrotasks()
+ expect(of(IPC.appUpdateInstalling).map((s) => (s.payload as { phase: string }).phase)).toEqual(['restarting'])
+ expect(autoUpdater.quitAndInstall).toHaveBeenCalledTimes(1)
+ expect(nativeUpdater.listenerCount('update-downloaded')).toBe(0)
+ })
+
+ it('nothing downloaded yet: the click is ignored and nothing is flagged', async () => {
+ release('linux')
+ process.env.APPIMAGE = '/tmp/nodeterm.AppImage'
+ const h = hooks()
+ initUpdater(h)
+ restart()
+ await flushMicrotasks()
+ expect(h.onBeforeRestart).not.toHaveBeenCalled()
+ expect(autoUpdater.quitAndInstall).not.toHaveBeenCalled()
+ })
+})
+
+describe('a staged update is announced once per version', () => {
+ let h: ReturnType<typeof hooks>
+ beforeEach(() => {
+ release('darwin')
+ h = hooks()
+ initUpdater(h)
+ })
+
+ it('a repeat downloaded/available (the 6h re-check) sends nothing and notifies once', () => {
+ autoUpdater.emit('update-available', { version: '1.1.0' })
+ autoUpdater.emit('update-downloaded', { version: '1.1.0' })
+ autoUpdater.emit('update-available', { version: '1.1.0' })
+ autoUpdater.emit('update-downloaded', { version: '1.1.0' })
+ expect(of(IPC.appUpdateAvailable)).toHaveLength(1)
+ expect(of(IPC.appUpdateDownloaded)).toHaveLength(1)
+ expect(notifications).toEqual(['nodeterm 1.1.0 is ready to install.'])
+ expect(h.onUpdateReady).toHaveBeenCalledTimes(1)
+ expect(h.onUpdateReady).toHaveBeenCalledWith('1.1.0')
+ })
+
+ it('once staged it stops auto-downloading, and fetches a NEWER release on purpose', () => {
+ autoUpdater.emit('update-downloaded', { version: '1.1.0' })
+ expect(autoUpdater.autoDownload).toBe(false)
+ expect(autoUpdater.autoInstallOnAppQuit).toBe(true)
+ autoUpdater.emit('update-available', { version: '1.1.0' })
+ expect(autoUpdater.downloadUpdate).not.toHaveBeenCalled()
+ autoUpdater.emit('update-available', { version: '1.2.0' })
+ expect(autoUpdater.downloadUpdate).toHaveBeenCalledTimes(1)
+ autoUpdater.emit('update-downloaded', { version: '1.2.0' })
+ expect(notifications).toHaveLength(2)
+ })
+
+ it('a manual check while staged echoes the staged version (no notification) and still looks', () => {
+ autoUpdater.emit('update-downloaded', { version: '1.1.0' })
+ sent.length = 0
+ autoUpdater.checkForUpdates.mockClear()
+ check()
+ expect(of(IPC.appUpdateDownloaded)).toEqual([{ channel: IPC.appUpdateDownloaded, payload: { version: '1.1.0' } }])
+ expect(notifications).toHaveLength(1)
+ expect(autoUpdater.checkForUpdates).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('errors and retries', () => {
+ beforeEach(() => {
+ release('darwin')
+ initUpdater(hooks())
+ })
+
+ it('a background check failure is logged, never carded', () => {
+ autoUpdater.emit('error', new Error('net::ERR_INTERNET_DISCONNECTED'))
+ expect(of(IPC.appUpdateError)).toEqual([])
+ })
+
+ it('a manual check failure is carded once, in plain words', () => {
+ check()
+ autoUpdater.emit('error', new Error('net::ERR_INTERNET_DISCONNECTED'))
+ expect(of(IPC.appUpdateError)).toEqual([
+ { channel: IPC.appUpdateError, payload: "Couldn't reach the update server. Check your connection and try again." }
+ ])
+ })
+
+ it('a manual check that started a download still reports that download failing', () => {
+ check()
+ autoUpdater.emit('update-available', { version: '1.1.0' })
+ autoUpdater.emit('error', new Error('ECONNRESET'))
+ expect(of(IPC.appUpdateError)).toHaveLength(1)
+ })
+
+ it('a failed BACKGROUND download is silent and retried at 15, then 30 minutes', () => {
+ const MIN = 60 * 1000
+ autoUpdater.checkForUpdates.mockClear()
+ autoUpdater.emit('update-available', { version: '1.1.0' })
+ autoUpdater.emit('error', new Error('ECONNRESET'))
+ expect(of(IPC.appUpdateError)).toEqual([])
+ vi.advanceTimersByTime(15 * MIN - 1)
+ expect(autoUpdater.checkForUpdates).not.toHaveBeenCalled()
+ vi.advanceTimersByTime(1)
+ expect(autoUpdater.checkForUpdates).toHaveBeenCalledTimes(1)
+ autoUpdater.emit('update-available', { version: '1.1.0' })
+ autoUpdater.emit('error', new Error('ECONNRESET'))
+ vi.advanceTimersByTime(30 * MIN)
+ expect(autoUpdater.checkForUpdates).toHaveBeenCalledTimes(2)
+ })
+
+ it('a background CHECK failure schedules no early retry', () => {
+ autoUpdater.checkForUpdates.mockClear()
+ autoUpdater.emit('error', new Error('offline'))
+ vi.advanceTimersByTime(5 * 60 * 60 * 1000)
+ expect(autoUpdater.checkForUpdates).not.toHaveBeenCalled()
+ })
+})
+
+describe('manual-install builds keep their cadence', () => {
+ it('a Linux .deb schedules no download retry (it downloads nothing)', () => {
+ release('linux')
+ initUpdater(hooks())
+ autoUpdater.checkForUpdates.mockClear()
+ autoUpdater.emit('update-available', { version: '1.1.0' })
+ autoUpdater.emit('error', new Error('ECONNRESET'))
+ vi.advanceTimersByTime(5 * 60 * 60 * 1000)
+ expect(autoUpdater.checkForUpdates).not.toHaveBeenCalled()
+ expect(autoUpdater.autoInstallOnAppQuit).toBe(false)
+ })
+})
diff --git a/src/main/updater.ts b/src/main/updater.ts
index 264a958b9..9644ff42c 100644
--- a/src/main/updater.ts
+++ b/src/main/updater.ts
@@ -1,10 +1,11 @@
// Auto-update client (electron-updater). The packaged app downloads updates automatically
-// and forwards the full lifecycle (available → progress → downloaded → error/not-available)
-// to the renderer's UpdateCard. Version lookup, manual check, and restart work in dev too;
+// and forwards the lifecycle (available → progress → downloaded → error/not-available) to the
+// renderer's UpdateCard — filtered by the pure gate in shared/update-gate.ts, so a staged update
+// is announced once per version and a background failure never becomes an error card. Version lookup, manual check, and restart work in dev too;
// the automatic feed checks and event wiring are packaged-only. On macOS, silent self-install
// requires a signed + notarized build; unsigned builds still surface the card for a manual
// download.
-import { app, ipcMain, Notification } from 'electron'
+import { app, autoUpdater as nativeUpdater, ipcMain, Notification } from 'electron'
import fs from 'fs'
import path from 'path'
// Named import — the default-import + destructure pattern returns undefined under
@@ -12,16 +13,33 @@ import path from 'path'
import { autoUpdater } from 'electron-updater'
import { IPC } from '../shared/ipc'
import {
- MANUAL_UPDATE_MODE,
+ installReadiness,
mayQuitAndInstall,
+ releaseNotesText,
toUpdateAvailablePayload,
updateDelivery
} from '../shared/update-platform'
+import {
+ classifyUpdaterError,
+ createUpdateGate,
+ friendlyUpdateErrorMessage,
+ nextDownloadRetryMs,
+ type UpdateErrorOrigin
+} from '../shared/update-gate'
+import type { UpdateInstalling } from '../shared/types'
import { getMainWindow, sendToMain } from './main-window'
import { retainUntilDismissed } from './notifications'
+import { requestRendererFlush } from './renderer-flush'
const SIX_HOURS = 6 * 60 * 60 * 1000
+/**
+ * How long a restart-to-update may sit in `preparing` (macOS: Squirrel.Mac re-reading the zip and
+ * verifying its signature) before we give up on THIS click. The update is not cancelled — Squirrel
+ * keeps going and a later click (or the next quit) still installs it.
+ */
+export const PREPARE_TIMEOUT_MS = 5 * 60 * 1000
+
/**
* The `nodeTermUpdates` marker a LOCAL package carries in its packaged package.json, injected by
* the `dist*` scripts via electron-builder's `extraMetadata`. `release` does not set it, so a
@@ -55,32 +73,100 @@ function packagedUpdateMode(): unknown {
}
}
+export interface UpdaterHooks {
+ /**
+ * Run right before `quitAndInstall()` — and ONLY once the install can actually start (on macOS:
+ * after Squirrel.Mac staged it). Required so the caller can flip its "quitting" flag:
+ * `quitAndInstall()` closes all windows and only then calls `app.quit()`, but our
+ * `win.on('close')` hides the window (keeps the app alive) unless we're already quitting — so
+ * without this the window just hides, `app.quit()` never fires, and the update never installs.
+ */
+ onBeforeRestart?: () => void
+ /** The install failed AFTER `onBeforeRestart` ran: undo what it set (quitting flags). */
+ onRestartAborted?: () => void
+ /** A version is staged and installable on restart (`null` = none). Feeds the tray item. */
+ onUpdateReady?: (version: string | null) => void
+ /** Write the renderer's pending canvas edits; must never reject or hang (defaults to
+ * `requestRendererFlush`, capped at ~1 s). */
+ flushRenderer?: () => Promise<unknown>
+}
+
+export interface UpdaterHandle {
+ /** The one guarded restart-to-update path, shared by the card (IPC) and the tray item. */
+ restartToUpdate(): void
+}
+
/**
* The window is resolved AT EVENT TIME (getMainWindow/sendToMain) — never captured in a closure.
* On macOS the window can be closed (the app lives on) and recreated from the dock, so a captured
* reference is a DESTROYED window: touching it throws `TypeError: Object has been destroyed`. That
* shipped — an update finishing downloading after a close→dock-reopen crashed the main process on
* `win.isFocused()`.
- *
- * @param onBeforeRestart Run right before `quitAndInstall()`. Required so the caller can flip its
- * "quitting" flag: `quitAndInstall()` closes all windows and only then calls `app.quit()`, but
- * our `win.on('close')` hides the window (keeps the app alive) unless we're already quitting — so
- * without this the window just hides, `app.quit()` never fires, and the update never installs.
*/
-export function initUpdater(onBeforeRestart?: () => void): void {
+export function initUpdater(hooks: UpdaterHooks = {}): UpdaterHandle {
const send = (channel: string, payload?: unknown) => sendToMain(channel, payload)
+ const flushRenderer =
+ hooks.flushRenderer ?? (() => requestRendererFlush(getMainWindow()?.webContents, ipcMain))
+ const platform = process.platform
const updateMode = packagedUpdateMode()
const delivery = updateDelivery({
isPackaged: app.isPackaged,
updateMode,
- platform: process.platform,
+ platform,
hasAppImage: !!process.env.APPIMAGE
})
- // Always available, even in dev: current version, manual check, restart.
- ipcMain.handle(IPC.appGetVersion, () => app.getVersion())
- ipcMain.on(IPC.appRestartToUpdate, () => {
+ const gate = createUpdateGate()
+ // What is staged and whether the OS updater can install it yet (installReadiness).
+ let stagedVersion: string | null = null
+ let nativeReady = false
+ let nativeFailed: string | null = null
+ // One restart at a time: a double click (or card + tray) must not queue a second install.
+ const restart = {
+ requested: false,
+ waitingForNative: false,
+ beforeRestartRan: false,
+ timer: undefined as ReturnType<typeof setTimeout> | undefined
+ }
+
+ const installing = (phase: UpdateInstalling['phase']): void =>
+ send(IPC.appUpdateInstalling, { phase, version: stagedVersion } satisfies UpdateInstalling)
+
+ const abortRestart = (raw: string): void => {
+ if (!restart.requested) return
+ if (restart.timer) clearTimeout(restart.timer)
+ const ranBefore = restart.beforeRestartRan
+ restart.requested = false
+ restart.waitingForNative = false
+ restart.beforeRestartRan = false
+ restart.timer = undefined
+ // The app was flagged as quitting for a quit that is not coming: without the reset a later
+ // window close actually closes (instead of hiding) and the next ⌘Q skips its confirm.
+ if (ranBefore) hooks.onRestartAborted?.()
+ send(IPC.appUpdateError, friendlyUpdateErrorMessage(raw))
+ }
+
+ const proceed = async (): Promise<void> => {
+ restart.waitingForNative = false
+ if (restart.timer) clearTimeout(restart.timer)
+ restart.timer = undefined
+ installing('restarting')
+ // The last canvas edits, BEFORE quitAndInstall: on macOS it closes every window first, so a
+ // flush in before-quit would find no renderer. Capped and never throws.
+ await flushRenderer().catch(() => undefined)
+ if (!restart.requested) return // aborted while flushing
+ restart.beforeRestartRan = true
+ hooks.onBeforeRestart?.()
+ try {
+ autoUpdater.quitAndInstall()
+ } catch (err) {
+ console.error('[updater] quitAndInstall failed:', err)
+ abortRestart(err instanceof Error ? err.message : String(err))
+ }
+ }
+
+ const restartToUpdate = (): void => {
// A build that must not self-install refuses here, in main — not only by the card never
// offering the button. The unsigned Windows beta (`nodeTermUpdates=manual`) is the reason:
// quitAndInstall must never run there, whatever the renderer sends. It also skips
@@ -89,9 +175,44 @@ export function initUpdater(onBeforeRestart?: () => void): void {
console.warn(`[updater] restart-to-update ignored: this build does not self-install (${delivery})`)
return
}
- onBeforeRestart?.()
- autoUpdater.quitAndInstall()
- })
+ if (delivery === 'dev') {
+ // Historical dev behaviour: nothing is ever staged, the call is a logged no-op.
+ hooks.onBeforeRestart?.()
+ autoUpdater.quitAndInstall()
+ return
+ }
+ if (restart.requested) return
+ const readiness = installReadiness(platform, { downloaded: stagedVersion !== null, nativeReady })
+ if (readiness === 'none') {
+ console.warn('[updater] restart-to-update ignored: no update has been downloaded yet')
+ return
+ }
+ restart.requested = true
+ if (readiness === 'ready') {
+ void proceed()
+ return
+ }
+ // macOS, Squirrel.Mac still staging. Do NOT flag the app as quitting yet — just say so and
+ // wait for the native 'update-downloaded' (the listener below calls proceed()).
+ if (nativeFailed) {
+ abortRestart(nativeFailed)
+ return
+ }
+ restart.waitingForNative = true
+ installing('preparing')
+ restart.timer = setTimeout(
+ () =>
+ abortRestart(
+ 'Preparing the update is taking longer than expected. It will still install the next time you quit.'
+ ),
+ PREPARE_TIMEOUT_MS
+ )
+ }
+
+ // Always available, even in dev: current version, manual check, restart.
+ ipcMain.handle(IPC.appGetVersion, () => app.getVersion())
+ ipcMain.on(IPC.appRestartToUpdate, () => restartToUpdate())
+ const handle: UpdaterHandle = { restartToUpdate }
if (delivery === 'dev' || delivery === 'no-channel') {
// Neither can reach a feed, so automatic networking and updater event wiring stay off — but
@@ -105,7 +226,7 @@ export function initUpdater(onBeforeRestart?: () => void): void {
ipcMain.on(IPC.appCheckForUpdates, () =>
send(delivery === 'no-channel' ? IPC.appUpdateNoChannel : IPC.appUpdateNotAvailable)
)
- return
+ return handle
}
// A Linux .deb/.rpm install (no APPIMAGE env) cannot self-install and would re-download the
@@ -118,8 +239,24 @@ export function initUpdater(onBeforeRestart?: () => void): void {
autoUpdater.autoDownload = !manualUpdates
autoUpdater.autoInstallOnAppQuit = !manualUpdates
+ // The flow an error belongs to (classifyUpdaterError): who started the check, and whether a
+ // download is running.
+ let userFlow = false
+ let downloading = false
+ let downloadFailures = 0
+ let retryTimer: ReturnType<typeof setTimeout> | undefined
+
autoUpdater.on('update-available', (info) => {
- send(IPC.appUpdateAvailable, toUpdateAvailablePayload(info, manualUpdates))
+ const d = gate.onAvailable(info.version, { userInitiated: userFlow })
+ if (d.download) {
+ // Newer than what is staged. autoDownload is off once something is staged (a re-check must
+ // not re-download and re-stage the same zip), so this one is fetched on purpose.
+ downloading = true
+ void autoUpdater.downloadUpdate().catch(() => undefined) // failures arrive as 'error'
+ } else if (!manualUpdates && autoUpdater.autoDownload) {
+ downloading = true
+ }
+ if (d.forward) send(IPC.appUpdateAvailable, toUpdateAvailablePayload(info, manualUpdates))
})
autoUpdater.on('download-progress', (p) => {
@@ -132,11 +269,25 @@ export function initUpdater(onBeforeRestart?: () => void): void {
})
autoUpdater.on('update-downloaded', (info) => {
- send(IPC.appUpdateDownloaded, { version: info.version })
+ downloading = false
+ userFlow = false
+ downloadFailures = 0
+ const d = gate.onDownloaded(info.version)
+ if (!d.forward) return
+ stagedVersion = info.version
+ // A new staging run starts now (MacUpdater hands the zip to Squirrel.Mac right after this
+ // event); the native 'update-downloaded' marks it installable.
+ nativeReady = false
+ nativeFailed = null
+ // Staged: from here on a re-check must not re-download the same version (see the gate).
+ autoUpdater.autoDownload = false
+ hooks.onUpdateReady?.(info.version)
+ send(IPC.appUpdateDownloaded, { version: info.version, notes: releaseNotesText(info.releaseNotes) })
// OS notification only when the window is in the background; the card covers the foreground.
+ // Once per version (the gate) — a staged update used to re-notify every six hours.
// Resolve the window HERE, not at init: a download can finish long after a close→dock-reopen.
// No live window (closed on macOS) reads as "not focused", which is exactly when we notify.
- if (!getMainWindow()?.isFocused() && Notification.isSupported()) {
+ if (d.notify && !getMainWindow()?.isFocused() && Notification.isSupported()) {
const n = new Notification({
title: 'Update ready',
body: `nodeterm ${info.version} is ready to install.`
@@ -155,35 +306,80 @@ export function initUpdater(onBeforeRestart?: () => void): void {
}
})
- autoUpdater.on('update-not-available', () => send(IPC.appUpdateNotAvailable))
+ autoUpdater.on('update-not-available', () => {
+ downloading = false
+ userFlow = false
+ send(IPC.appUpdateNotAvailable)
+ })
+
+ // Squirrel.Mac (Electron's own autoUpdater — the singleton MacUpdater drives) reports when the
+ // staged update is actually installable, and when staging failed. Elsewhere electron-updater
+ // installs from the downloaded file itself and the native updater is not involved.
+ if (platform === 'darwin' && nativeUpdater) {
+ nativeUpdater.on('update-downloaded', () => {
+ nativeReady = true
+ nativeFailed = null
+ if (restart.requested && restart.waitingForNative) void proceed()
+ })
+ nativeUpdater.on('error', (err: Error) => {
+ const message = err?.message ?? String(err)
+ console.error('[updater] native updater:', message)
+ if (restart.requested) abortRestart(message)
+ else if (stagedVersion !== null && !nativeReady) nativeFailed = message
+ })
+ }
- // A check-only build (`nodeTermUpdates=manual`, the unsigned Windows beta) downloads nothing, so
- // every 'error' event it can emit is a CHECK failure — and electron-updater emits one for the
- // silent launch/6h checks too. The beta previously showed nothing at all; an error card on every
- // launch (offline, or a feed mirror that does not serve latest.yml yet) would be a regression
- // for exactly the users this notice exists for. So there the event is logged only; a
- // user-initiated check still surfaces its failure through the catch below. Every other build
- // keeps its historical behaviour.
- const checkOnly = delivery === 'manual-install' && updateMode === MANUAL_UPDATE_MODE
+ // One owner for error reporting: this listener. electron-updater emits 'error' for every failed
+ // check (manual and automatic alike) and download, so the manual handler below only logs its
+ // rejection — answering there too used to put the same error up twice.
autoUpdater.on('error', (err) => {
- const message = err?.message ?? String(err)
- console.error('[updater]', message)
- if (!checkOnly) send(IPC.appUpdateError, message)
+ const raw = err?.message ?? String(err)
+ console.error('[updater]', raw)
+ // Once quitAndInstall ran, an error is the install failing. While still waiting on Squirrel
+ // the native 'error' above is the authority — an unrelated background check failing in that
+ // window must not cancel the user's restart.
+ if (restart.requested && restart.beforeRestartRan) {
+ abortRestart(raw)
+ return
+ }
+ const origin: UpdateErrorOrigin = downloading
+ ? userFlow
+ ? 'manual-download'
+ : 'auto-download'
+ : userFlow
+ ? 'manual-check'
+ : 'auto-check'
+ const wasDownloading = downloading
+ downloading = false
+ userFlow = false
+ if (classifyUpdaterError(origin) === 'surface') send(IPC.appUpdateError, friendlyUpdateErrorMessage(raw))
+ // A failed background download is retried sooner than the next 6h tick (bounded backoff).
+ // Check failures (offline at launch) keep the ordinary cadence, so we never hammer the feed.
+ if (wasDownloading && origin === 'auto-download' && delivery === 'self-install') {
+ const delay = nextDownloadRetryMs(++downloadFailures)
+ if (retryTimer) clearTimeout(retryTimer)
+ retryTimer = delay === null ? undefined : setTimeout(check, delay)
+ }
})
- // Manual check from Settings; surfaces failures to the card.
+ // Manual check from Settings / the required card; its outcome reaches the card through the
+ // events above.
ipcMain.on(IPC.appCheckForUpdates, () => {
- autoUpdater.checkForUpdates().catch((err) => {
- const message = err?.message ?? String(err)
- console.error('[updater]', message)
- send(IPC.appUpdateError, message)
- })
+ userFlow = true
+ // Already staged: say so at once (a dismissed ready card comes back), and still look for a
+ // newer release.
+ const { echoDownloaded } = gate.onManualCheck()
+ if (echoDownloaded) send(IPC.appUpdateDownloaded, { version: echoDownloaded })
+ autoUpdater.checkForUpdates().catch(() => undefined) // reported by the 'error' listener
})
// Automatic checks: on launch and every six hours.
- const check = () => {
- autoUpdater.checkForUpdates().catch((err) => console.error('[updater]', err?.message ?? err))
+ function check(): void {
+ if (retryTimer) clearTimeout(retryTimer)
+ retryTimer = undefined
+ autoUpdater.checkForUpdates().catch(() => undefined) // logged by the 'error' listener
}
check()
setInterval(check, SIX_HOURS)
+ return handle
}