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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(updates): pure update gate, error policy, retry backoff and install readiness
review487925f414ed
diff --git a/src/shared/update-gate.test.ts b/src/shared/update-gate.test.tsnew file mode 100644index 000000000..1953d60ab--- /dev/null+++ b/src/shared/update-gate.test.ts@@ -0,0 +1,122 @@+import { describe, expect, it } from 'vitest'+import {+ classifyUpdaterError,+ createUpdateGate,+ friendlyUpdateErrorMessage,+ isNewerVersion,+ nextDownloadRetryMs+} from './update-gate'++describe('isNewerVersion', () => {+ it.each([+ ['0.3.8', '0.3.7', true],+ ['0.3.7', '0.3.7', false],+ ['0.3.7', '0.3.8', false],+ ['1.0.0', '0.99.99', true],+ ['0.10.0', '0.9.0', true],+ ['v1.2', '1.1.9', true],+ ['1.0.0', '1.0.0-beta.2', true],+ ['1.0.0-beta.2', '1.0.0', false],+ ['1.0.0-beta.10', '1.0.0-beta.2', true],+ ['1.0.0-rc.1', '1.0.0-beta.9', true],+ ['garbage', '0.1.0', false],+ ['0.1.0', 'garbage', false]+ ])('%s newer than %s → %s', (a, b, want) => {+ expect(isNewerVersion(a, b)).toBe(want)+ })+})++describe('createUpdateGate', () => {+ it('a staged version repeating from the 6h re-check is swallowed: forwarded once, notified once', () => {+ const g = createUpdateGate()+ expect(g.onAvailable('1.1.0', { userInitiated: false })).toEqual({ forward: true, download: false })+ expect(g.onDownloaded('1.1.0')).toEqual({ forward: true, notify: true })+ expect(g.onAvailable('1.1.0', { userInitiated: false })).toEqual({ forward: false, download: false })+ expect(g.onDownloaded('1.1.0')).toEqual({ forward: false, notify: false })+ // Even a user check does not re-download the staged version.+ expect(g.onAvailable('1.1.0', { userInitiated: true })).toEqual({ forward: false, download: false })+ })++ it('a strictly newer release after staging is forwarded, downloaded on purpose and notified', () => {+ const g = createUpdateGate()+ g.onDownloaded('1.1.0')+ expect(g.onAvailable('1.2.0', { userInitiated: false })).toEqual({ forward: true, download: true })+ expect(g.onDownloaded('1.2.0')).toEqual({ forward: true, notify: true })+ expect(g.stagedVersion()).toBe('1.2.0')+ // An older straggler never replaces the staged one.+ expect(g.onDownloaded('1.1.0')).toEqual({ forward: false, notify: false })+ })++ it('a manual check while staged echoes the staged version', () => {+ const g = createUpdateGate()+ expect(g.onManualCheck()).toEqual({ echoDownloaded: null })+ g.onDownloaded('1.1.0')+ expect(g.onManualCheck()).toEqual({ echoDownloaded: '1.1.0' })+ })++ it('check-only builds (never staged) forward the first availability and swallow background repeats', () => {+ const g = createUpdateGate()+ expect(g.onAvailable('1.1.0', { userInitiated: false }).forward).toBe(true)+ expect(g.onAvailable('1.1.0', { userInitiated: false }).forward).toBe(false)+ // …but the user asking always gets the answer.+ expect(g.onAvailable('1.1.0', { userInitiated: true }).forward).toBe(true)+ expect(g.onAvailable('1.2.0', { userInitiated: false }).forward).toBe(true)+ })+})++describe('classifyUpdaterError', () => {+ it.each([+ ['auto-check', 'log'],+ ['auto-download', 'log'],+ ['manual-check', 'surface'],+ ['manual-download', 'surface'],+ ['install', 'surface']+ ] as const)('%s → %s', (origin, want) => {+ expect(classifyUpdaterError(origin)).toBe(want)+ })+})++describe('friendlyUpdateErrorMessage', () => {+ it('maps connectivity failures to a connection sentence', () => {+ for (const raw of [+ 'net::ERR_INTERNET_DISCONNECTED',+ 'Error: net::ERR_NAME_NOT_RESOLVED',+ 'net::ERR_NETWORK_CHANGED',+ 'connect ETIMEDOUT 1.2.3.4:443',+ 'read ECONNRESET'+ ])+ expect(friendlyUpdateErrorMessage(raw)).toMatch(/Couldn't reach the update server/)+ })++ it('maps feed 5xx / missing latest.yml to a server sentence', () => {+ expect(friendlyUpdateErrorMessage('HttpError: 503 Service Unavailable\n"method: GET url: …"')).toMatch(+ /temporarily unavailable/+ )+ expect(friendlyUpdateErrorMessage('HttpError: 404 \nCannot find latest-mac.yml')).toMatch(/temporarily unavailable/)+ })++ it('falls back to a trimmed first line', () => {+ expect(friendlyUpdateErrorMessage('Code signature did not pass validation\n at x')).toBe(+ 'Code signature did not pass validation'+ )+ expect(friendlyUpdateErrorMessage('')).toBe('The update could not be completed.')+ expect(friendlyUpdateErrorMessage('y'.repeat(500)).length).toBe(198)+ })+})++describe('nextDownloadRetryMs', () => {+ const MIN = 60 * 1000+ it('backs off 15/30/60/120 minutes, then hands back to the 6h tick', () => {+ expect([1, 2, 3, 4, 5].map(nextDownloadRetryMs)).toEqual([15 * MIN, 30 * MIN, 60 * MIN, 120 * MIN, null])+ })++ it('every step is below six hours', () => {+ for (let i = 1; i <= 4; i++) expect(nextDownloadRetryMs(i)!).toBeLessThan(6 * 60 * MIN)+ })++ it('garbage counts schedule nothing', () => {+ expect(nextDownloadRetryMs(0)).toBeNull()+ expect(nextDownloadRetryMs(-1)).toBeNull()+ expect(nextDownloadRetryMs(1.5)).toBeNull()+ })+})diff --git a/src/shared/update-gate.ts b/src/shared/update-gate.tsnew file mode 100644index 000000000..c1d0ff991--- /dev/null+++ b/src/shared/update-gate.ts@@ -0,0 +1,159 @@+/**+ * The updater's event policy — pure, so every rule below unit-tests on Linux with no Electron.+ *+ * electron-updater keeps polling after an update is STAGED: the running binary is still the old+ * version, so every 6h re-check emits `update-available` again, re-downloads (a cached file+ * resolves at once) and emits `update-downloaded` again — which used to re-open a card the user had+ * minimized or dismissed and re-send the "Update ready" OS notification, every six hours. The gate+ * remembers what was already said and lets only NEWS through.+ *+ * It also owns the two other decisions main has to make about an updater event: whether an error+ * is worth a card (a background check failing offline is not), and how soon a failed background+ * download is retried (sooner than the next 6h tick, a bounded number of times).+ */++/**+ * Compare two version strings: true when `a` is strictly newer than `b`. Numeric `major.minor.patch`+ * (missing parts are 0); on equal cores a release beats a prerelease, and two prereleases compare by+ * their dot-separated identifiers (numeric ones numerically). Anything unparsable is never "newer" —+ * a garbled feed must not be able to talk the gate into forwarding.+ */+export function isNewerVersion(a: string, b: string): boolean {+ const pa = parseVersion(a)+ const pb = parseVersion(b)+ if (!pa || !pb) return false+ for (let i = 0; i < 3; i++) {+ if (pa.core[i] !== pb.core[i]) return pa.core[i] > pb.core[i]+ }+ if (pa.pre.length === 0) return pb.pre.length > 0+ if (pb.pre.length === 0) return false+ const n = Math.max(pa.pre.length, pb.pre.length)+ for (let i = 0; i < n; i++) {+ const x = pa.pre[i]+ const y = pb.pre[i]+ if (x === undefined) return false+ if (y === undefined) return true+ if (x === y) continue+ const xn = /^\d+$/.test(x)+ const yn = /^\d+$/.test(y)+ if (xn && yn) return Number(x) > Number(y)+ if (xn !== yn) return !xn // numeric identifiers sort below alphanumeric ones+ return x > y+ }+ return false+}++function parseVersion(v: string): { core: number[]; pre: string[] } | null {+ const m = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/.exec(String(v).trim())+ if (!m) return null+ return {+ core: [Number(m[1]), Number(m[2] ?? 0), Number(m[3] ?? 0)],+ pre: m[4] ? m[4].split('.') : []+ }+}++export interface AvailableDecision {+ /** Send `update-available` to the renderer. */+ forward: boolean+ /**+ * Start the download explicitly. Only for a version NEWER than the one already staged: once+ * something is staged main turns `autoDownload` off (a re-check must not re-download and re-stage+ * the same zip), so a newer release is fetched on purpose instead.+ */+ download: boolean+}++export interface DownloadedDecision {+ /** Send `update-downloaded` to the renderer. */+ forward: boolean+ /** Show the OS "Update ready" notification (still subject to the window being unfocused). */+ notify: boolean+}++export interface UpdateGate {+ onAvailable(version: string, opts: { userInitiated: boolean }): AvailableDecision+ onDownloaded(version: string): DownloadedDecision+ /** A user-initiated check: the staged version to echo as `update-downloaded`, if any. Without+ * the echo a user who dismissed the ready card and asks again would be left on "Checking…". */+ onManualCheck(): { echoDownloaded: string | null }+ stagedVersion(): string | null+}++export function createUpdateGate(): UpdateGate {+ let staged: string | null = null+ let lastAvailable: string | null = null+ const notified = new Set<string>()+ return {+ onAvailable(version, { userInitiated }) {+ if (staged !== null) {+ if (!isNewerVersion(version, staged)) return { forward: false, download: false }+ lastAvailable = version+ return { forward: true, download: true }+ }+ // A repeat of the version the renderer already heard about is noise for a background check+ // (the 6h tick, a download retry); a user asking deserves the answer again.+ const forward = userInitiated || lastAvailable !== version+ lastAvailable = version+ return { forward, download: false }+ },+ onDownloaded(version) {+ if (staged !== null && !isNewerVersion(version, staged)) return { forward: false, notify: false }+ staged = version+ const notify = !notified.has(version)+ notified.add(version)+ return { forward: true, notify }+ },+ onManualCheck() {+ return { echoDownloaded: staged }+ },+ stagedVersion: () => staged+ }+}++/**+ * Where an updater error came from. Main tracks the flow it is in (who started the check, whether a+ * download began, whether an install was requested) and names it here.+ */+export type UpdateErrorOrigin =+ | 'auto-check' // the silent launch / 6h check+ | 'manual-check' // Settings → Check for updates, the required card's "Update now"+ | 'auto-download' // a download a background check started+ | 'manual-download' // a download a user-initiated check started+ | 'install' // restart-to-update was requested and preparing/installing failed++/**+ * `surface` = put it on the card; `log` = console only. A background failure — offline at launch, a+ * captive portal, a feed 5xx, a background download dropping — is not something the user asked+ * about and has nothing to do about, so it never becomes an "Update failed" card (a background+ * download is retried instead, see `nextDownloadRetryMs`). Anything the user started is answered.+ */+export function classifyUpdaterError(origin: UpdateErrorOrigin): 'surface' | 'log' {+ return origin === 'auto-check' || origin === 'auto-download' ? 'log' : 'surface'+}++const NETWORK_ERROR = /net::ERR_(INTERNET_DISCONNECTED|NAME_NOT_RESOLVED|NETWORK_CHANGED|NETWORK_IO_SUSPENDED|CONNECTION_(REFUSED|RESET|CLOSED|TIMED_OUT|ABORTED)|ADDRESS_UNREACHABLE|TIMED_OUT|PROXY_CONNECTION_FAILED)|ETIMEDOUT|ECONNRESET|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ENETUNREACH/++/**+ * The sentence the card shows for an updater error. The raw text (`net::ERR_INTERNET_DISCONNECTED`,+ * an HttpError with the feed's headers) stays in the log; the user gets what it means.+ */+export function friendlyUpdateErrorMessage(raw: string): string {+ const text = String(raw ?? '')+ if (NETWORK_ERROR.test(text)) return "Couldn't reach the update server. Check your connection and try again."+ if (/HttpError:\s*(5\d\d|404)\b|status(?:Code)?[:= ]+(5\d\d|404)\b|\b(5\d\d|404)\b.*latest[^\s]*\.yml/i.test(text))+ return 'The update server is temporarily unavailable. Try again later.'+ const first = text.split('\n')[0].trim()+ if (!first) return 'The update could not be completed.'+ return first.length > 200 ? `${first.slice(0, 197)}…` : first+}++/** Retry schedule after a failed BACKGROUND download: 15, 30, 60, 120 minutes, then back to the+ * ordinary 6h tick (null). Every step stays below six hours, so a retry always comes first. */+export const DOWNLOAD_RETRY_MINUTES = [15, 30, 60, 120] as const++/** Delay before retry number `failures` (1-based), or null once the schedule is exhausted. */+export function nextDownloadRetryMs(failures: number): number | null {+ if (!Number.isInteger(failures) || failures < 1) return null+ const m = DOWNLOAD_RETRY_MINUTES[failures - 1]+ return m === undefined ? null : m * 60 * 1000+}diff --git a/src/shared/update-platform.test.ts b/src/shared/update-platform.test.tsindex e1ceceed2..75d30f4ed 100644--- a/src/shared/update-platform.test.ts+++ b/src/shared/update-platform.test.ts@@ -4,8 +4,10 @@ import path from 'path'import {MANUAL_UPDATE_MODE,isManualUpdatePlatform,+ installReadiness,mayQuitAndInstall,noSelfInstallCopy,+ releaseNotesText,shouldEnableUpdater,toUpdateAvailablePayload,updateDelivery@@ -103,9 +105,37 @@ describe('toUpdateAvailablePayload', () => {notes: '',manual: false})+ expect(toUpdateAvailablePayload({ version: '1.2.0', releaseNotes: 42 }, false).notes).toBe('')+ })++ it('flattens the fullChangelog array form instead of dropping it', () => {expect(- toUpdateAvailablePayload({ version: '1.2.0', releaseNotes: [{ note: 'x' }] }, false).notes- ).toBe('')+ toUpdateAvailablePayload(+ { version: '1.2.0', releaseNotes: [{ version: '1.2.0', note: '- a' }, { note: null }, { version: '1.1.0', note: '- b' }] },+ false+ ).notes+ ).toBe('- a\n- b')+ })++ it('caps very long notes', () => {+ expect(releaseNotesText('x'.repeat(100_000)).length).toBe(16 * 1024)+ })+})++describe('installReadiness', () => {+ it('nothing downloaded is never installable, on any platform', () => {+ for (const p of ['darwin', 'linux', 'win32'])+ expect(installReadiness(p, { downloaded: false, nativeReady: true })).toBe('none')+ })++ it('macOS waits for Squirrel.Mac to stage the download', () => {+ expect(installReadiness('darwin', { downloaded: true, nativeReady: false })).toBe('preparing')+ expect(installReadiness('darwin', { downloaded: true, nativeReady: true })).toBe('ready')+ })++ it('AppImage / NSIS install from the downloaded file: ready at once', () => {+ expect(installReadiness('linux', { downloaded: true, nativeReady: false })).toBe('ready')+ expect(installReadiness('win32', { downloaded: true, nativeReady: false })).toBe('ready')})})diff --git a/src/shared/update-platform.ts b/src/shared/update-platform.tsindex 612306723..d32621bc0 100644--- a/src/shared/update-platform.ts+++ b/src/shared/update-platform.ts@@ -33,6 +33,26 @@ export function shouldEnableUpdater(isPackaged: boolean, updateMode: unknown): breturn isPackaged && updateMode !== 'disabled'}+/** Cap on release-notes text forwarded to the renderer: the card shows a few highlights, and a+ * feed is not a channel for megabytes of IPC. */+const NOTES_MAX = 16 * 1024++/**+ * electron-updater's `releaseNotes` is a string, or — with `fullChangelog` — an array of+ * `{version, note}`. Both become one string; anything else is no notes.+ */+export function releaseNotesText(notes: unknown): string {+ let text = ''+ if (typeof notes === 'string') text = notes+ else if (Array.isArray(notes)) {+ text = notes+ .map((n) => (n && typeof n === 'object' && typeof (n as { note?: unknown }).note === 'string' ? (n as { note: string }).note : ''))+ .filter(Boolean)+ .join('\n')+ }+ return text.length > NOTES_MAX ? text.slice(0, NOTES_MAX) : text+}+/** Reduce an electron-updater update-available info to the renderer's UpdateInfo payload. */export function toUpdateAvailablePayload(info: { version: string; releaseNotes?: unknown },@@ -40,11 +60,32 @@ export function toUpdateAvailablePayload(): UpdateInfo {return {version: info.version,- notes: typeof info.releaseNotes === 'string' ? info.releaseNotes : '',+ notes: releaseNotesText(info.releaseNotes),manual}}+/**+ * Whether a staged update can be installed RIGHT NOW.+ *+ * On macOS electron-updater reports `update-downloaded` BEFORE Squirrel.Mac has the update: it+ * dispatches the event and only then asks the native updater to fetch the zip through its localhost+ * proxy, unpack it and verify the signature. Until Electron's own autoUpdater emits+ * `update-downloaded`, `quitAndInstall()` merely queues a listener and returns — so a click there+ * did nothing visible. That window is `preparing`. Every other platform (AppImage, NSIS) installs+ * from the downloaded file itself, so a download is ready.+ */+export type InstallReadiness = 'none' | 'preparing' | 'ready'++export function installReadiness(+ platform: string,+ s: { downloaded: boolean; nativeReady: boolean }+): InstallReadiness {+ if (!s.downloaded) return 'none'+ if (platform === 'darwin' && !s.nativeReady) return 'preparing'+ return 'ready'+}+/*** How this build can receive an update. Three delivery paths plus dev, because the REMEDY the* user needs differs and the card must not blur them: