Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

fix(updater): repair the native auto-update path + make the version a live update control

Chaitanya Giri295c5b773e93
diff --git a/package.json b/package.json
index 7e450445..853ea356 100644
--- a/package.json
+++ b/package.json
@@ -19,7 +19,7 @@
"typecheck:node": "tsc --noEmit -p tsconfig.node.json",
"typecheck:web": "tsc --noEmit -p tsconfig.web.json",
"typecheck": "npm run typecheck:node && npm run typecheck:web",
- "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs test/node-install.test.cjs test/office-gl-recovery.test.cjs",
+ "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs test/node-install.test.cjs test/office-gl-recovery.test.cjs test/update-state.test.cjs",
"dist": "npm run build && electron-builder",
"dist:mac": "npm run build && electron-builder --mac",
"dist:win": "npm run build && electron-builder --win",
diff --git a/src/main/updater.ts b/src/main/updater.ts
index e1eb1437..e79daf91 100644
--- a/src/main/updater.ts
+++ b/src/main/updater.ts
@@ -1,71 +1,122 @@
import { app, ipcMain, shell } from 'electron';
import type { WebContents } from 'electron';
import { request as httpsRequest } from 'node:https';
+import { appendFileSync, mkdirSync } from 'node:fs';
+import { join } from 'node:path';
import { readConfig } from './config';
+import { reduceStatus, clampPercent, isNewer, type UpdateStatus } from '../shared/updateState';
/**
- * Auto-update from GitHub releases (v0.3.4).
+ * Auto-update from GitHub releases.
*
* Primary path: electron-updater against the `publish` block in
* electron-builder.yml — the release workflow uploads latest*.yml + zip +
- * blockmaps, macOS builds are Developer ID signed + notarized, so Squirrel.Mac
- * (zip), NSIS, and AppImage all update natively. Downloads happen in the
- * background; installation is ALWAYS user-initiated ("Restart to update" toast
+ * blockmaps, macOS builds are Developer ID signed + notarized + stapled, so
+ * Squirrel.Mac (zip), NSIS, and AppImage all update natively. Downloads happen
+ * in the background; installation is ALWAYS user-initiated ("restart to update"
* → `update:restartAndInstall`). The app never restarts on its own.
*
- * Fallback path (win-portable exe, unsigned/dev-ish builds, or any updater
- * error): a plain `releases/latest` poll — semver-compare against the running
- * version and show a notify-only toast linking the release page. Same pattern
- * as the landing page's REL upgrade fetch, with the same modest cache so we
- * stay far from the unauthenticated 60/hr rate limit.
+ * Fallback path (win-portable exe, or a genuine updater error): a plain
+ * `releases/latest` poll — semver-compare against the running version and show a
+ * notify-only state linking the release page.
*
* Everything is gated on the `autoUpdate` HarnessConfig flag (default ON,
* Settings → General) and on `app.isPackaged` — dev runs never poll.
+ *
+ * ─── v0.3.7: why native updating never actually ran ──────────────────────────
+ * electron-updater is CommonJS and exposes `autoUpdater` through a lazy
+ * `Object.defineProperty` getter. Node's cjs-module-lexer cannot see through
+ * that, so the ESM namespace produced by `await import('electron-updater')` has
+ * NO `autoUpdater` named export — only `.default.autoUpdater`. The old code did
+ * `const { autoUpdater } = await import('electron-updater')`, got `undefined`,
+ * and threw `TypeError: Cannot set properties of undefined (setting
+ * 'autoDownload')` on the very first line of setup. That threw into a catch that
+ * silently latched notify-only mode, so from v0.3.4 through v0.3.6 EVERY
+ * packaged build only ever offered "open the releases page". It never showed up
+ * in dev because the whole block is behind `app.isPackaged`.
+ *
+ * Two rules came out of that and both are load-bearing here:
+ * 1. resolve the module through `loadAutoUpdater()` below, which handles the
+ * namespace/default interop and throws a NAMED error if the export is gone;
+ * 2. never swallow an updater error — every failure is surfaced to the
+ * renderer AND appended to `updater.log` in userData, and the notify-only
+ * downgrade is per-check, not a permanent latch.
*/
const REPO = 'chaitanyagiri/munder-difflin';
const CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000; // 6h
const FALLBACK_CACHE_MS = 60 * 60 * 1000; // 1h between releases/latest polls
-export type UpdateStatus =
- | { state: 'downloaded'; version: string; notes?: string }
- | { state: 'available-manual'; version: string; url: string };
+export type { UpdateStatus };
let sendTo: (() => WebContents | null) | null = null;
let started = false;
-let fallbackActive = false;
let lastFallbackCheck = 0;
-/** Remembered so a toast dismissed by a reload can be re-served on checkNow. */
+/** Remembered so a status survives a renderer reload and can be re-served. */
let lastStatus: UpdateStatus | null = null;
+/** Append-only breadcrumb trail in userData. The whole point of this file's
+ * existence is that the last failure left no trace anywhere. */
+function logLine(msg: string): void {
+ const line = `[${new Date().toISOString()}] ${msg}\n`;
+ console.log('[updater]', msg);
+ try {
+ const dir = app.getPath('userData');
+ mkdirSync(dir, { recursive: true });
+ appendFileSync(join(dir, 'updater.log'), line);
+ } catch { /* logging must never take the app down */ }
+}
+
function emit(status: UpdateStatus): void {
- lastStatus = status;
- try { sendTo?.()?.send('update:status', status); } catch { /* window tore down */ }
+ lastStatus = reduceStatus(lastStatus, status);
+ try { sendTo?.()?.send('update:status', lastStatus); } catch { /* window tore down */ }
}
function autoUpdateEnabled(): boolean {
- const cfg = readConfig();
- return cfg.autoUpdate !== false; // default ON
+ try {
+ return readConfig().autoUpdate !== false; // default ON
+ } catch {
+ return true;
+ }
}
-/** `1.2.3` -> [1,2,3]; returns null for anything that doesn't look like semver. */
-function parseVersion(v: string): number[] | null {
- const m = v.trim().replace(/^v/, '').match(/^(\d+)\.(\d+)\.(\d+)/);
- return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
-}
+type AutoUpdater = import('electron-updater').AppUpdater;
+
+let autoUpdaterPromise: Promise<AutoUpdater> | null = null;
-function isNewer(candidate: string, current: string): boolean {
- const a = parseVersion(candidate);
- const b = parseVersion(current);
- if (!a || !b) return false;
- for (let i = 0; i < 3; i++) {
- if (a[i] !== b[i]) return a[i] > b[i];
+/**
+ * Resolve electron-updater's `autoUpdater` across the CJS/ESM interop seam.
+ *
+ * See the header note: the named export is invisible to the ESM lexer, so the
+ * namespace object only carries it on `.default`. Both shapes are checked so
+ * this keeps working if a future electron-updater ships real named exports, and
+ * a missing export throws something we can actually read in a log.
+ */
+async function loadAutoUpdater(): Promise<AutoUpdater> {
+ autoUpdaterPromise ??= (async () => {
+ const ns = (await import('electron-updater')) as unknown as {
+ autoUpdater?: AutoUpdater;
+ default?: { autoUpdater?: AutoUpdater };
+ };
+ const found = ns.autoUpdater ?? ns.default?.autoUpdater;
+ if (!found) throw new Error('electron-updater loaded but exposes no `autoUpdater` export');
+ return found;
+ })();
+ try {
+ return await autoUpdaterPromise;
+ } catch (e) {
+ autoUpdaterPromise = null; // let a later attempt retry rather than latch
+ throw e;
}
- return false;
+}
+
+function errText(e: unknown): string {
+ const m = e instanceof Error ? e.message : String(e);
+ return m.length > 300 ? `${m.slice(0, 300)}…` : m;
}
/** Notify-only check against releases/latest (no download). Never throws. */
-function fallbackCheck(force = false): void {
+function fallbackCheck(reason: string | undefined, force = false): void {
const now = Date.now();
if (!force && now - lastFallbackCheck < FALLBACK_CACHE_MS) return;
lastFallbackCheck = now;
@@ -90,7 +141,8 @@ function fallbackCheck(force = false): void {
emit({
state: 'available-manual',
version: tag.replace(/^v/, ''),
- url: rel.html_url ?? `https://github.com/${REPO}/releases/latest`
+ url: rel.html_url ?? `https://github.com/${REPO}/releases/latest`,
+ reason
});
}
} catch { /* malformed body — try again next interval */ }
@@ -103,20 +155,49 @@ function fallbackCheck(force = false): void {
} catch { /* never let the fallback take the app down */ }
}
-async function nativeCheck(): Promise<void> {
- if (fallbackActive) { fallbackCheck(); return; }
+/**
+ * One check. Native first; on failure, report the real error AND degrade to the
+ * notify-only poll for THIS check only — the next tick tries native again, so a
+ * single blip no longer costs the session its ability to self-update.
+ */
+async function runCheck(): Promise<{ ok: boolean; error?: string }> {
+ emit({ state: 'checking' });
try {
- const { autoUpdater } = await import('electron-updater');
- await autoUpdater.checkForUpdates();
- } catch {
- fallbackActive = true;
- fallbackCheck();
+ const autoUpdater = await loadAutoUpdater();
+ const result = await autoUpdater.checkForUpdates();
+ if (!result || !isNewer(result.updateInfo.version, app.getVersion())) {
+ emit({ state: 'not-available' });
+ }
+ // `update-available` / `download-progress` / `update-downloaded` handlers
+ // (wired in initAutoUpdater) carry it from here.
+ return { ok: true };
+ } catch (e) {
+ const message = errText(e);
+ logLine(`native check failed: ${message}`);
+ emit({ state: 'error', message });
+ fallbackCheck(message);
+ return { ok: false, error: message };
+ }
+}
+
+/** Explicitly start (or restart) the download. Safe to call twice. */
+async function runDownload(): Promise<{ ok: boolean; error?: string }> {
+ try {
+ const autoUpdater = await loadAutoUpdater();
+ await autoUpdater.downloadUpdate();
+ return { ok: true };
+ } catch (e) {
+ const message = errText(e);
+ logLine(`download failed: ${message}`);
+ emit({ state: 'error', message });
+ fallbackCheck(message);
+ return { ok: false, error: message };
}
}
/**
* Start the updater. Call once from app.whenReady with an accessor for the
- * primary window's webContents. Safe to call in dev (no-ops).
+ * primary window's webContents. Safe to call in dev (registers IPC, no polling).
*/
export function initAutoUpdater(getWebContents: () => WebContents | null): void {
sendTo = getWebContents;
@@ -124,19 +205,27 @@ export function initAutoUpdater(getWebContents: () => WebContents | null): void
// IPC surface is registered unconditionally so the renderer can always call it.
ipcMain.handle('update:restartAndInstall', async () => {
try {
- const { autoUpdater } = await import('electron-updater');
+ const autoUpdater = await loadAutoUpdater();
+ logLine('quitAndInstall requested by the user');
autoUpdater.quitAndInstall();
return { ok: true };
} catch (e) {
- return { ok: false, error: e instanceof Error ? e.message : String(e) };
+ const error = errText(e);
+ logLine(`quitAndInstall failed: ${error}`);
+ emit({ state: 'error', message: error });
+ return { ok: false, error };
}
});
ipcMain.handle('update:checkNow', async () => {
- if (!app.isPackaged) return { ok: false, error: 'dev build' };
- if (lastStatus) emit(lastStatus); // re-serve a pending status to a fresh window
- await nativeCheck();
- return { ok: true };
+ if (!app.isPackaged) return { ok: false, error: 'dev build — updates are only checked in packaged apps' };
+ return runCheck();
});
+ ipcMain.handle('update:download', async () => {
+ if (!app.isPackaged) return { ok: false, error: 'dev build — updates are only downloaded in packaged apps' };
+ return runDownload();
+ });
+ /** Re-serve the last known status to a freshly loaded window. */
+ ipcMain.handle('update:current', () => lastStatus ?? { state: 'idle' });
ipcMain.handle('update:openRelease', (_evt, url: unknown) => {
const href = typeof url === 'string' ? url : `https://github.com/${REPO}/releases/latest`;
// Only ever open the project's releases page — this is not a generic opener.
@@ -151,24 +240,38 @@ export function initAutoUpdater(getWebContents: () => WebContents | null): void
void (async () => {
try {
- const { autoUpdater } = await import('electron-updater');
+ const autoUpdater = await loadAutoUpdater();
autoUpdater.autoDownload = true;
autoUpdater.autoInstallOnAppQuit = false; // install ONLY on explicit restart
+ autoUpdater.on('update-available', (info) => {
+ logLine(`update available: ${info.version}`);
+ emit({ state: 'available', version: info.version, notes: typeof info.releaseNotes === 'string' ? info.releaseNotes : undefined });
+ });
+ autoUpdater.on('download-progress', (p) => {
+ const version = lastStatus && 'version' in lastStatus ? lastStatus.version : app.getVersion();
+ emit({ state: 'downloading', version, percent: clampPercent(p.percent) });
+ });
autoUpdater.on('update-downloaded', (info) => {
+ logLine(`update downloaded: ${info.version} — waiting for the user to restart`);
emit({ state: 'downloaded', version: info.version, notes: typeof info.releaseNotes === 'string' ? info.releaseNotes : undefined });
});
autoUpdater.on('error', (err) => {
- // Portable exe / missing metadata / offline: degrade to notify-only.
- console.warn('[updater] native update failed; falling back to notify-only:', err?.message ?? err);
- fallbackActive = true;
- fallbackCheck();
+ const message = errText(err);
+ logLine(`native updater error: ${message}`);
+ emit({ state: 'error', message });
+ // Notify-only for THIS failure; the next tick still tries native.
+ fallbackCheck(message);
});
+ logLine(`native updater ready (current v${app.getVersion()})`);
} catch (e) {
- console.warn('[updater] electron-updater unavailable; notify-only mode:', e);
- fallbackActive = true;
+ // Reaching here means the module itself is unusable — the exact class of
+ // bug that hid from v0.3.4 to v0.3.6. Say so loudly, in the log and the UI.
+ const message = errText(e);
+ logLine(`electron-updater unavailable; notify-only mode: ${message}`);
+ emit({ state: 'error', message });
}
- const tick = (): void => { if (autoUpdateEnabled()) void nativeCheck(); };
+ const tick = (): void => { if (autoUpdateEnabled()) void runCheck(); };
// First check shortly after boot (don't compete with spawn/startup I/O),
// then every CHECK_INTERVAL_MS.
setTimeout(tick, 30_000);
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 4377567f..d90bd95e 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -4,6 +4,8 @@ import type { HireManifest } from '../shared/hire';
export type { HireManifest } from '../shared/hire';
import type { IntegrationRecord, IntegrationTemplate } from '../shared/integrations';
export type { IntegrationRecord, IntegrationTemplate } from '../shared/integrations';
+import type { UpdateStatus } from '../shared/updateState';
+export type { UpdateStatus } from '../shared/updateState';
/** Renderer-visible integration record: the secretRef handle is redacted to a
* presence boolean. Matches main `integrations.listRecordsRedacted()` — the
@@ -1182,25 +1184,29 @@ const api = {
rosterWrite: (snap: RosterSnapshot): Promise<{ ok: boolean; skipped?: string; error?: string }> =>
ipcRenderer.invoke('roster:write', snap),
- // ─── Auto-update (v0.3.4) ───────────────────────────────────────────────────
- /** Push channel from main's updater: either a downloaded update waiting for a
- * restart, or (fallback/notify-only installs) a newer release to link to. */
- onUpdateStatus: (
- cb: (status:
- | { state: 'downloaded'; version: string; notes?: string }
- | { state: 'available-manual'; version: string; url: string }) => void
- ): (() => void) => {
- const listener = (_e: IpcRendererEvent, payload: Parameters<typeof cb>[0]) => cb(payload);
+ // ─── Auto-update (v0.3.4; full state model v0.3.7) ──────────────────────────
+ /** Push channel from main's updater — every stage of the pipeline, so the
+ * toolbar badge can show "checking", download progress, and the staged
+ * "restart to update" rather than only the terminal states. */
+ onUpdateStatus: (cb: (status: UpdateStatus) => void): (() => void) => {
+ const listener = (_e: IpcRendererEvent, payload: UpdateStatus) => cb(payload);
ipcRenderer.on('update:status', listener);
return () => ipcRenderer.removeListener('update:status', listener);
},
- /** Quit and install the downloaded update — only ever called from the toast's
- * explicit "restart to update" button. */
+ /** The last known status — a reloaded window subscribes AFTER main may have
+ * already emitted, so it pulls the current state instead of waiting 6h. */
+ updateCurrent: (): Promise<UpdateStatus> => ipcRenderer.invoke('update:current'),
+ /** Quit and install the downloaded update — only ever called from an explicit
+ * "restart to update" click. */
updateRestartAndInstall: (): Promise<{ ok: boolean; error?: string }> =>
ipcRenderer.invoke('update:restartAndInstall'),
- /** Manual re-check (also re-serves a pending status to a fresh window). */
+ /** Manual re-check. */
updateCheckNow: (): Promise<{ ok: boolean; error?: string }> =>
ipcRenderer.invoke('update:checkNow'),
+ /** Start the download for an already-detected update (autoDownload normally
+ * beats the user to it; this is the explicit one-click path). */
+ updateDownload: (): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('update:download'),
/** Open the project's releases page for a notify-only update. */
updateOpenRelease: (url?: string): Promise<{ ok: boolean }> =>
ipcRenderer.invoke('update:openRelease', url)
diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx
index 64c6169e..5d7aa1b5 100644
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@ -14,6 +14,7 @@ import { HivePicker } from '@/components/HivePicker';
import { QuitWarningModal, type ClosingTimeState } from '@/components/QuitWarningModal';
import { CompletionToast } from '@/realtime/CompletionToast';
import { UpdateToast } from '@/components/UpdateToast';
+import { UpdateBadge } from '@/components/UpdateBadge';
import { useAppTheme, toggleAppTheme } from '@/design/theme';
import { SettingsModal } from '@/components/SettingsModal';
import { PixelPanel } from '@/components/PixelPanel';
@@ -238,12 +239,15 @@ export function App() {
alt="Munder Difflin"
style={{ height: 20, width: 'auto', display: 'block' }}
/>
+ {/* v0.3.7: the version is no longer inert text — it doubles as the
+ update control (check / download / restart to update). */}
+ <UpdateBadge />
<span style={{
fontFamily: 'var(--cth-font-ui)',
fontSize: 13,
color: 'var(--cth-ink-500)'
}}>
- v{__APP_VERSION__} · {config.autoMode ? 'auto mode on' : 'auto mode off'}
+ {config.autoMode ? 'auto mode on' : 'auto mode off'}
</span>
{/* v0.3.4: theme + fullscreen live HERE (top right), not buried in the
terminal header — and the theme darkens the whole app, terminals
diff --git a/src/renderer/src/components/UpdateBadge.tsx b/src/renderer/src/components/UpdateBadge.tsx
new file mode 100644
index 00000000..f7ee3260
--- /dev/null
+++ b/src/renderer/src/components/UpdateBadge.tsx
@@ -0,0 +1,91 @@
+/**
+ * Toolbar version + update control — top-left, right next to the logo.
+ *
+ * Always shows the running version. When main's updater reports anything
+ * interesting it grows a chip that IS the button: "v0.3.7 ready to install"
+ * (click → download), "downloading 42%", "restart to update to v0.3.7"
+ * (click → quitAndInstall). With nothing pending, clicking the version itself
+ * runs a manual check — the old build only ever checked 30s after boot and then
+ * every 6h, so there was no way to ask.
+ *
+ * All of the "what does this state say and do" logic lives in
+ * src/shared/updateState.ts so it can be unit-tested without Electron; this file
+ * is wiring and pixels.
+ */
+import { useCallback, useEffect, useState } from 'react';
+import { describeUpdate, reduceStatus, type UpdateStatus } from '@shared/updateState';
+
+declare const __APP_VERSION__: string;
+
+export function UpdateBadge() {
+ const [status, setStatus] = useState<UpdateStatus | null>(null);
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ // Subscribe first, then pull — main may have emitted before this window
+ // finished loading (or before a reload), and `update:current` re-serves it.
+ const off = window.cth.onUpdateStatus?.((next) => setStatus((prev) => reduceStatus(prev, next)));
+ void window.cth.updateCurrent?.().then((cur) => {
+ if (cur) setStatus((prev) => reduceStatus(prev, cur));
+ }).catch(() => { /* older main without the handler — the push channel still works */ });
+ return off;
+ }, []);
+
+ const view = describeUpdate(status, __APP_VERSION__);
+
+ const onClick = useCallback(async () => {
+ if (view.action === 'none' || busy) return;
+ setBusy(true);
+ try {
+ if (view.action === 'restart') await window.cth.updateRestartAndInstall();
+ else if (view.action === 'download') await window.cth.updateDownload();
+ else if (view.action === 'check') await window.cth.updateCheckNow();
+ else if (view.action === 'open-release') {
+ await window.cth.updateOpenRelease(status?.state === 'available-manual' ? status.url : undefined);
+ }
+ } catch { /* the emitted status carries the failure — nothing to do here */ }
+ setBusy(false);
+ }, [view.action, busy, status]);
+
+ const interactive = view.action !== 'none' && !view.busy;
+ // The chip only earns colour when it wants something: ready = mint (act on
+ // me), warn = amber (something went wrong), busy/idle stay in the titlebar's
+ // own greys so a quiet app looks exactly like it did before.
+ const chipBg =
+ view.tone === 'ready' ? 'var(--cth-mint-light, #d0f0e0)'
+ : view.tone === 'warn' ? 'var(--cth-amber-light, #f6e2b3)'
+ : 'transparent';
+
+ return (
+ <button
+ className="cth-titlebar-nodrag"
+ onClick={() => { void onClick(); }}
+ disabled={!interactive}
+ title={view.title}
+ aria-label={view.label ? `${view.title}` : `Version ${__APP_VERSION__} — check for updates`}
+ aria-busy={view.busy || busy}
+ style={{
+ display: 'inline-flex', alignItems: 'center', gap: 6,
+ padding: view.label ? '2px 8px' : '2px 4px',
+ margin: 0,
+ background: chipBg,
+ border: 'none',
+ borderRadius: 2,
+ boxShadow: view.label ? 'inset 0 0 0 1px var(--cth-ink-300)' : 'none',
+ fontFamily: 'var(--cth-font-ui)',
+ fontSize: 13,
+ lineHeight: '18px',
+ color: view.tone === 'idle' ? 'var(--cth-ink-500)' : 'var(--cth-ink-900)',
+ cursor: interactive ? 'pointer' : 'default'
+ }}
+ >
+ <span>v{__APP_VERSION__}</span>
+ {view.label && (
+ <>
+ <span aria-hidden style={{ color: 'var(--cth-ink-500)' }}>·</span>
+ <span style={{ fontWeight: 600 }}>{view.label}</span>
+ </>
+ )}
+ </button>
+ );
+}
diff --git a/src/renderer/src/components/UpdateToast.tsx b/src/renderer/src/components/UpdateToast.tsx
index c5471a20..f00863b3 100644
--- a/src/renderer/src/components/UpdateToast.tsx
+++ b/src/renderer/src/components/UpdateToast.tsx
@@ -13,16 +13,27 @@
*/
import { useEffect, useState } from 'react';
import { Icon } from '@/components/Icon';
+import type { UpdateStatus } from '@shared/updateState';
-type UpdateStatus =
- | { state: 'downloaded'; version: string; notes?: string }
- | { state: 'available-manual'; version: string; url: string };
+/** The toast is the LOUD half — it only interrupts for the two states a user has
+ * to act on. Everything else (checking, available, download progress, errors)
+ * lives quietly in the toolbar badge next to the logo. */
+type ToastStatus = Extract<UpdateStatus, { state: 'downloaded' | 'available-manual' }>;
+
+function toastable(s: UpdateStatus): ToastStatus | null {
+ return s.state === 'downloaded' || s.state === 'available-manual' ? s : null;
+}
export function UpdateToast() {
- const [status, setStatus] = useState<UpdateStatus | null>(null);
+ const [status, setStatus] = useState<ToastStatus | null>(null);
const [busy, setBusy] = useState(false);
- useEffect(() => window.cth.onUpdateStatus?.(setStatus), []);
+ useEffect(() => window.cth.onUpdateStatus?.((next) => {
+ const t = toastable(next);
+ // A non-toastable state (a re-check, say) must not erase a toast the user
+ // hasn't answered yet — only a new actionable state replaces it.
+ if (t) setStatus(t);
+ }), []);
if (!status) return null;
diff --git a/src/shared/updateState.ts b/src/shared/updateState.ts
new file mode 100644
index 00000000..f1d8e7eb
--- /dev/null
+++ b/src/shared/updateState.ts
@@ -0,0 +1,142 @@
+/**
+ * Auto-update status model + presentation mapping.
+ *
+ * Deliberately electron-free: main (src/main/updater.ts) produces these states
+ * from electron-updater events, the toolbar badge
+ * (src/renderer/src/components/UpdateBadge.tsx) renders them, and the rules that
+ * matter — which state wins when two arrive out of order, what the button says
+ * and does — live here where they can be unit-tested without booting Electron.
+ */
+
+export type UpdateStatus =
+ /** Nothing known yet (fresh window, or dev build where we never check). */
+ | { state: 'idle' }
+ | { state: 'checking' }
+ | { state: 'not-available' }
+ | { state: 'available'; version: string; notes?: string }
+ | { state: 'downloading'; version: string; percent: number }
+ | { state: 'downloaded'; version: string; notes?: string }
+ /** This install can't self-update (win-portable, or the native path failed):
+ * notify-only, link to the release page. `reason` is the underlying error. */
+ | { state: 'available-manual'; version: string; url: string; reason?: string }
+ | { state: 'error'; message: string };
+
+export type UpdateAction = 'none' | 'check' | 'download' | 'restart' | 'open-release';
+
+export interface UpdateBadgeView {
+ /** Extra text beside the version, or null to show the version alone. */
+ label: string | null;
+ /** What a click does. 'none' renders the badge non-interactive. */
+ action: UpdateAction;
+ tone: 'idle' | 'busy' | 'ready' | 'warn';
+ /** Tooltip — the only place the underlying error is ever surfaced verbatim. */
+ title: string;
+ busy: boolean;
+}
+
+/** `1.2.3` / `v1.2.3` -> [1,2,3]; null for anything that isn't semver-ish. */
+export function parseVersion(v: string): [number, number, number] | null {
+ const m = String(v ?? '').trim().replace(/^v/, '').match(/^(\d+)\.(\d+)\.(\d+)/);
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
+}
+
+export function isNewer(candidate: string, current: string): boolean {
+ const a = parseVersion(candidate);
+ const b = parseVersion(current);
+ if (!a || !b) return false;
+ for (let i = 0; i < 3; i++) {
+ if (a[i] !== b[i]) return a[i] > b[i];
+ }
+ return false;
+}
+
+/** Download percentages arrive as floats and, on a resumed/differential
+ * download, occasionally out of range. Clamp so the UI can't render `-0%`
+ * or `104%`. */
+export function clampPercent(n: number): number {
+ if (!Number.isFinite(n)) return 0;
+ return Math.max(0, Math.min(100, Math.round(n)));
+}
+
+/** How far along the update pipeline a state is. A later stage is never
+ * replaced by an earlier one for the SAME version — see `reduceStatus`. */
+function rank(s: UpdateStatus): number {
+ switch (s.state) {
+ case 'idle': return 0;
+ case 'checking': return 1;
+ case 'not-available': return 1;
+ case 'error': return 1;
+ case 'available-manual': return 2;
+ case 'available': return 3;
+ case 'downloading': return 4;
+ case 'downloaded': return 5;
+ }
+}
+
+function versionOf(s: UpdateStatus): string | null {
+ return 'version' in s ? s.version : null;
+}
+
+/**
+ * Fold a new status into the current one.
+ *
+ * The rule that matters: once an update is staged, the 6-hourly re-check (or a
+ * manual "check now") must NOT wipe the "restart to update" affordance out from
+ * under the user — `checking` / `not-available` / a transient `error` are all
+ * lower-rank and lose. A genuinely NEWER version always wins, so a long-running
+ * app that sees 0.3.7 while 0.3.6 is staged moves forward rather than sticking.
+ */
+export function reduceStatus(prev: UpdateStatus | null, next: UpdateStatus): UpdateStatus {
+ if (!prev) return next;
+ const pv = versionOf(prev);
+ const nv = versionOf(next);
+ if (pv && nv && isNewer(nv, pv)) return next; // a newer release supersedes
+ if (pv && nv && pv !== nv) return next; // different (e.g. rolled back) release
+ return rank(next) >= rank(prev) ? next : prev;
+}
+
+/**
+ * What the toolbar badge shows and does for a given status.
+ *
+ * `currentVersion` is the running app's version — it is always rendered next to
+ * the logo, so every one of these views is "v0.3.6" plus at most one extra chip.
+ */
+export function describeUpdate(status: UpdateStatus | null, currentVersion: string): UpdateBadgeView {
+ const v = currentVersion;
+ switch (status?.state) {
+ case 'checking':
+ return { label: 'checking…', action: 'none', tone: 'busy', busy: true, title: `Checking for updates (you're on v${v})` };
+ case 'available':
+ return {
+ label: `v${status.version} ready to install`, action: 'download', tone: 'ready', busy: false,
+ title: `Version ${status.version} is available — click to download it`
+ };
+ case 'downloading':
+ return {
+ label: `downloading ${clampPercent(status.percent)}%`, action: 'none', tone: 'busy', busy: true,
+ title: `Downloading v${status.version}… ${clampPercent(status.percent)}%`
+ };
+ case 'downloaded':
+ return {
+ label: `restart to update to v${status.version}`, action: 'restart', tone: 'ready', busy: false,
+ title: `v${status.version} is downloaded and ready — click to restart and apply it`
+ };
+ case 'available-manual':
+ return {
+ label: `v${status.version} — get it manually`, action: 'open-release', tone: 'warn', busy: false,
+ title: status.reason
+ ? `This install couldn't update itself (${status.reason}) — click to open the release page`
+ : `This install can't update itself — click to open the release page`
+ };
+ case 'error':
+ return {
+ label: 'update check failed', action: 'check', tone: 'warn', busy: false,
+ title: `${status.message} — click to try again`
+ };
+ case 'not-available':
+ return { label: null, action: 'check', tone: 'idle', busy: false, title: `v${v} is the latest version — click to check again` };
+ case 'idle':
+ default:
+ return { label: null, action: 'check', tone: 'idle', busy: false, title: `v${v} — click to check for updates` };
+ }
+}
diff --git a/test/update-state.test.cjs b/test/update-state.test.cjs
new file mode 100644
index 00000000..59c3a9d0
--- /dev/null
+++ b/test/update-state.test.cjs
@@ -0,0 +1,114 @@
+'use strict';
+
+/**
+ * Auto-update state model.
+ *
+ * These cover the two rules that actually broke in the field:
+ * 1. a re-check must never wipe out a staged "restart to update" (the 6h tick
+ * and the manual check both emit `checking` → `not-available`);
+ * 2. every state maps to a button that says what it does — the v0.3.4-0.3.6
+ * builds could only ever say "open the releases page", which is what the
+ * founder hit when 0.3.6 shipped.
+ */
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const loadTs = require('./load-ts.cjs');
+
+const { parseVersion, isNewer, clampPercent, reduceStatus, describeUpdate } =
+ loadTs('src/shared/updateState.ts');
+
+test('parseVersion accepts v-prefixed and bare semver, rejects junk', () => {
+ assert.deepEqual(parseVersion('0.3.6'), [0, 3, 6]);
+ assert.deepEqual(parseVersion('v0.3.6'), [0, 3, 6]);
+ assert.deepEqual(parseVersion('1.10.2-beta.1'), [1, 10, 2]);
+ assert.equal(parseVersion('nightly'), null);
+ assert.equal(parseVersion(''), null);
+});
+
+test('isNewer compares numerically, not lexically', () => {
+ assert.equal(isNewer('0.3.6', '0.3.5'), true);
+ assert.equal(isNewer('v0.3.6', '0.3.5'), true);
+ // The one a string compare gets wrong: '0.3.10' < '0.3.9' lexically.
+ assert.equal(isNewer('0.3.10', '0.3.9'), true);
+ assert.equal(isNewer('0.3.5', '0.3.6'), false);
+ assert.equal(isNewer('0.3.6', '0.3.6'), false);
+ assert.equal(isNewer('garbage', '0.3.6'), false);
+});
+
+test('clampPercent keeps progress renderable', () => {
+ assert.equal(clampPercent(42.6), 43);
+ assert.equal(clampPercent(-3), 0);
+ assert.equal(clampPercent(104), 100);
+ assert.equal(clampPercent(NaN), 0);
+ assert.equal(clampPercent(undefined), 0);
+});
+
+test('a re-check never clobbers a staged update', () => {
+ const staged = { state: 'downloaded', version: '0.3.7' };
+ // The 6h tick: checking → not-available, both must lose to the staged update.
+ assert.deepEqual(reduceStatus(staged, { state: 'checking' }), staged);
+ assert.deepEqual(reduceStatus(staged, { state: 'not-available' }), staged);
+ // A transient network error mid-session must not drop the restart button.
+ assert.deepEqual(reduceStatus(staged, { state: 'error', message: 'ETIMEDOUT' }), staged);
+});
+
+test('the pipeline moves forward for the same version', () => {
+ let s = reduceStatus(null, { state: 'checking' });
+ s = reduceStatus(s, { state: 'available', version: '0.3.7' });
+ assert.equal(s.state, 'available');
+ s = reduceStatus(s, { state: 'downloading', version: '0.3.7', percent: 12 });
+ assert.equal(s.state, 'downloading');
+ s = reduceStatus(s, { state: 'downloaded', version: '0.3.7' });
+ assert.equal(s.state, 'downloaded');
+ // Late progress events must not walk it back off "downloaded".
+ s = reduceStatus(s, { state: 'downloading', version: '0.3.7', percent: 99 });
+ assert.equal(s.state, 'downloaded');
+});
+
+test('a genuinely newer release supersedes a staged one', () => {
+ const staged = { state: 'downloaded', version: '0.3.7' };
+ const next = reduceStatus(staged, { state: 'available', version: '0.3.8' });
+ assert.deepEqual(next, { state: 'available', version: '0.3.8' });
+});
+
+test('every actionable state offers the action its label promises', () => {
+ const check = (status, expected) => {
+ const v = describeUpdate(status, '0.3.6');
+ assert.equal(v.action, expected.action, `action for ${status ? status.state : 'null'}`);
+ if ('label' in expected) assert.equal(v.label, expected.label);
+ if ('busy' in expected) assert.equal(v.busy, expected.busy);
+ };
+
+ // Idle / up-to-date: version only, but still clickable to check on demand —
+ // the whole point of the founder's "tell me and let me trigger it" ask.
+ check(null, { action: 'check', label: null, busy: false });
+ check({ state: 'idle' }, { action: 'check', label: null });
+ check({ state: 'not-available' }, { action: 'check', label: null });
+
+ check({ state: 'checking' }, { action: 'none', busy: true });
+ check({ state: 'available', version: '0.3.7' }, { action: 'download', busy: false });
+ check({ state: 'downloading', version: '0.3.7', percent: 42 }, { action: 'none', busy: true });
+ check({ state: 'downloaded', version: '0.3.7' }, { action: 'restart', busy: false });
+ check({ state: 'available-manual', version: '0.3.7', url: 'https://x' }, { action: 'open-release' });
+ check({ state: 'error', message: 'boom' }, { action: 'check' });
+});
+
+test('labels name the version so the badge is self-explanatory', () => {
+ assert.match(describeUpdate({ state: 'available', version: '0.3.7' }, '0.3.6').label, /0\.3\.7/);
+ assert.match(describeUpdate({ state: 'downloaded', version: '0.3.7' }, '0.3.6').label, /restart/i);
+ assert.match(describeUpdate({ state: 'downloading', version: '0.3.7', percent: 42.4 }, '0.3.6').label, /42%/);
+});
+
+test('the underlying failure reaches the tooltip instead of being swallowed', () => {
+ // This is the regression guard for the v0.3.4-0.3.6 bug: the real error was
+ // caught and dropped, leaving "open the releases page" with no explanation.
+ const err = describeUpdate({ state: 'error', message: 'Cannot set properties of undefined' }, '0.3.6');
+ assert.match(err.title, /Cannot set properties of undefined/);
+
+ const manual = describeUpdate(
+ { state: 'available-manual', version: '0.3.7', url: 'https://x', reason: 'ENOTFOUND github.com' },
+ '0.3.6'
+ );
+ assert.match(manual.title, /ENOTFOUND github\.com/);
+});