Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(editor): the update check answers, and says which answer it is

yhh2f60403f4b29
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 77de16860..d6d867016 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,35 @@ published separately; it ships inside the editor.
## [Unreleased]
+### Fixed
+
+- **Checking for updates showed nothing, and could show nothing forever.** The toast was
+ posted only once the network had answered, so Help ▸ Check for Updates was a click with
+ no visible effect for as long as the request took — and the requests had no timeout at
+ all. `catch` catches a connection that fails, not one that is accepted and then never
+ speaks, which is exactly what a filtered network does: the promise never settled, the
+ command waited on it forever, and nothing was ever shown. Each source now gets six
+ seconds, including the one electron-updater asks (which exposes no timeout of its own,
+ so it is raced against a deadline).
+
+ With that fixed, the answer can be honest. "No update" and "nobody answered" used to be
+ the same `null`, reported the same way — a machine that had reached neither the mirror
+ nor GitHub was told, in green, that it was up to date. The check now reports three
+ outcomes, and the unreachable one offers the download page instead of a reassurance it
+ has not earned.
+
+- **A download that reported nothing looked like a download that had stopped.** Progress
+ was a percentage inside a line of text, which sat at "0%" through connect, redirect and
+ the whole of a differential download's first phase. Toasts can carry a progress bar now:
+ indeterminate while there is nothing to be a percentage of, then the real figure with the
+ download's size next to it. The line is also pinned while the download runs and re-posts
+ itself if it was closed — the download outlives its toast, and "Restart" was the only way
+ to install what it had just fetched.
+
+- **One release, announced once.** The startup check and the menu item both raise the same
+ notification, so clicking Check for Updates in the first seconds after launch answered
+ with two identical lines.
+
### Added
- **A UI node can say that it arrived on screen, or left it.** Everything a panel does when it
diff --git a/desktop/electron/autoUpdate.ts b/desktop/electron/autoUpdate.ts
index 6ae9b16bf..153e6c58f 100644
--- a/desktop/electron/autoUpdate.ts
+++ b/desktop/electron/autoUpdate.ts
@@ -26,7 +26,7 @@ import path from 'node:path';
import { readFileSync } from 'node:fs';
import { spawnSync } from 'node:child_process';
import { app } from 'electron';
-import { checkForUpdate, updateFeeds, type LatestRelease } from './updateCheck';
+import { describeUpdate, updateFeeds, PROBE_TIMEOUT_MS, type LatestRelease } from './updateCheck';
import { publisherNameIn, signatureSatisfies, type AuthenticodeProbe } from './updateSignature';
/** Where a self-installing update sends anyone who would rather read about it first. */
@@ -156,12 +156,39 @@ export function canSelfInstall(): boolean {
/** Reached a feed and got an answer, or reached none at all. */
type CheckOutcome = { reached: true; update: AvailableUpdate | null } | { reached: false };
+/**
+ * Give a promise a deadline it cannot outlive.
+ *
+ * electron-updater exposes no request timeout, and its http executor inherits the
+ * same hazard the plain fetches had: a source that accepts the connection and then
+ * says nothing keeps the check pending for as long as the editor runs. Losing the
+ * race only abandons the ANSWER — the request finishes into nothing — which is the
+ * right trade for a check whose worst honest outcome is "ask again later".
+ */
+async function withDeadline<T>(work: Promise<T>, ms: number, what: string): Promise<T> {
+ let timer: NodeJS.Timeout | undefined;
+ try {
+ return await Promise.race([
+ work,
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error(`${what} did not answer within ${ms}ms`)), ms);
+ }),
+ ]);
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
async function checkWithUpdater(): Promise<CheckOutcome> {
const autoUpdater = await updater();
for (const feed of updateFeeds()) {
try {
autoUpdater.setFeedURL(feed as Parameters<typeof autoUpdater.setFeedURL>[0]);
- const result = await autoUpdater.checkForUpdates();
+ const result = await withDeadline(
+ autoUpdater.checkForUpdates(),
+ PROBE_TIMEOUT_MS,
+ String(feed.url ?? feed.provider),
+ );
if (!result) continue;
// The feed that answered stays selected, so the download comes from the
// source that was fast enough to be asked.
@@ -177,12 +204,20 @@ async function checkWithUpdater(): Promise<CheckOutcome> {
return { reached: false };
}
+/** What a check found, in the shape the renderer has to tell the user about. */
+export type UpdateStatus =
+ | { status: 'update'; update: AvailableUpdate }
+ | { status: 'current' }
+ | { status: 'unreachable' };
+
/**
- * The newest release if it is newer than this build, else null.
+ * What the newest published release means for this build.
*
- * Never throws: an update check must not be able to break editor startup.
+ * Never throws: an update check must not be able to break editor startup. It can,
+ * however, come back saying nobody answered — which is a different thing from "you
+ * are up to date" and must not be reported as one.
*/
-export async function findUpdate(currentVersion: string = app.getVersion()): Promise<AvailableUpdate | null> {
+export async function findUpdate(currentVersion: string = app.getVersion()): Promise<UpdateStatus> {
if (canSelfInstall()) {
// Catches what the per-feed handler cannot: loading the updater at all.
const outcome = await checkWithUpdater().catch((err): CheckOutcome => {
@@ -191,10 +226,14 @@ export async function findUpdate(currentVersion: string = app.getVersion()): Pro
});
// Only a feed that ANSWERED settles the question. "No feed could be reached" is
// not "no update", so it falls through to the check that speaks GitHub's API.
- if (outcome.reached) return outcome.update;
+ if (outcome.reached) {
+ return outcome.update ? { status: 'update', update: outcome.update } : { status: 'current' };
+ }
}
- const release = await checkForUpdate(currentVersion);
- return release ? { ...release, selfInstall: false } : null;
+ const outcome = await describeUpdate(currentVersion);
+ return outcome.status === 'update'
+ ? { status: 'update', update: { ...outcome.release, selfInstall: false } }
+ : outcome;
}
let downloaded = false;
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index a2587d74b..b20283ab7 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -1505,9 +1505,11 @@ app.whenReady().then(async () => {
// Skipped in automation/dev so screenshots and local runs stay deterministic.
if (!VITE_DEV_SERVER_URL && !process.env.ESTELLA_SHOT) {
setTimeout(() => {
- void findUpdate().then((release) => {
- if (release && win && !win.isDestroyed()) {
- win.webContents.send('app:updateAvailable', release);
+ // Startup stays silent unless there IS one: a machine that could not reach a
+ // source has not asked for this check and should not be told about the weather.
+ void findUpdate().then((result) => {
+ if (result.status === 'update' && win && !win.isDestroyed()) {
+ win.webContents.send('app:updateAvailable', result.update);
}
});
}, 5000);
diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts
index 363f7c0ca..7cfae23ed 100644
--- a/desktop/electron/preload.ts
+++ b/desktop/electron/preload.ts
@@ -12,7 +12,7 @@ import type {
PlatformStatus, CreatePlatformResult, PlayableNetworkOption, ProjectPlatformKind,
} from './platformCatalog';
import type { PlayRealmResult } from './buildPlayRealm';
-import type { AvailableUpdate, DownloadProgress } from './autoUpdate';
+import type { AvailableUpdate, DownloadProgress, UpdateStatus } from './autoUpdate';
import type { LaunchError } from './externalProgram';
import type { DetectedEditor } from './editorCatalog';
import type { DiscoveredPlugin, CompiledPlugin } from './pluginHost';
@@ -66,8 +66,9 @@ const api = {
void Promise.resolve(cb()).finally(() => ipcRenderer.send('app:quitConfirmed'));
});
},
- /** Manual update check (Help menu); null = up to date / offline. */
- checkUpdates: (): Promise<AvailableUpdate | null> => ipcRenderer.invoke('app:checkUpdates'),
+ /** Manual update check (Help menu). Says which of the three things happened —
+ * found one, already current, or nobody answered. */
+ checkUpdates: (): Promise<UpdateStatus> => ipcRenderer.invoke('app:checkUpdates'),
/** Startup update notification (main checks once after launch); returns an unsubscribe. */
onUpdateAvailable: (cb: (release: AvailableUpdate) => void): (() => void) => {
const h = (_e: unknown, release: AvailableUpdate) => cb(release);
diff --git a/desktop/electron/updateCheck.ts b/desktop/electron/updateCheck.ts
index 4f8d8a051..60d904e58 100644
--- a/desktop/electron/updateCheck.ts
+++ b/desktop/electron/updateCheck.ts
@@ -53,6 +53,40 @@ export interface LatestRelease {
url: string;
}
+/**
+ * What the check found — three answers, not two.
+ *
+ * "No update" and "nobody answered" used to be the same `null`, and the editor
+ * reported both as "you are up to date": a machine that cannot reach either source
+ * was told, in green, that it had the newest build. `unreachable` is the difference,
+ * and it is the only outcome that should offer the download page instead.
+ */
+export type UpdateOutcome =
+ | { status: 'update'; release: LatestRelease }
+ | { status: 'current' }
+ | { status: 'unreachable' };
+
+/**
+ * How long one source gets to answer.
+ *
+ * There was no limit at all, and `catch` only catches a connection that FAILS.
+ * A blackholed one — dropped rather than refused, which is what a filtered network
+ * usually does — leaves `fetch` pending forever, and with it the menu command that
+ * is waiting on it. That is not a slow check; it is a check that never ends, and no
+ * amount of spinner makes it finish. Per source, so a dead first mirror costs this
+ * much and not the whole budget.
+ */
+export const PROBE_TIMEOUT_MS = 6000;
+
+export interface ProbeOptions {
+ fetch?: typeof fetch;
+ env?: NodeJS.ProcessEnv;
+ platform?: string;
+ arch?: string;
+ /** Per-source deadline; tests shorten it. */
+ timeoutMs?: number;
+}
+
/**
* The same question this file answers, in electron-updater's vocabulary: which
* sources to ask, fastest-first. Mirrors publish the channel files under `latest/`
@@ -99,6 +133,9 @@ export function isNewerVersion(candidate: string, current: string): boolean {
* Latest published release if it is newer than `currentVersion`, else null.
* Never throws: offline / rate-limited / malformed all resolve to null — an
* update check must not be able to break editor startup.
+ *
+ * Keeps the two-valued answer for callers that only want the release; anything
+ * that has to TELL the user what happened wants {@link describeUpdate} instead.
*/
export async function checkForUpdate(
currentVersion: string,
@@ -107,11 +144,46 @@ export async function checkForUpdate(
platform: string = process.platform,
arch: string = process.arch,
): Promise<LatestRelease | null> {
- for (const mirror of releaseMirrors(env)) {
- const found = await checkMirror(mirror, currentVersion, fetchImpl, platform, arch);
- if (found) return found;
+ const outcome = await describeUpdate(currentVersion, { fetch: fetchImpl, env, platform, arch });
+ return outcome.status === 'update' ? outcome.release : null;
+}
+
+/**
+ * Ask every source in order and say which of the three things happened.
+ *
+ * A mirror that is merely CURRENT does not end the search — it may be lagging the
+ * origin, which is the whole reason the origin is asked second (see the file
+ * header). But it does mean something answered, so a later source going dark
+ * downgrades the answer to "current" rather than "nobody answered".
+ */
+export async function describeUpdate(
+ currentVersion: string,
+ opts: ProbeOptions = {},
+): Promise<UpdateOutcome> {
+ const fetchImpl = opts.fetch ?? fetch;
+ const timeoutMs = opts.timeoutMs ?? PROBE_TIMEOUT_MS;
+ const platform = opts.platform ?? process.platform;
+ const arch = opts.arch ?? process.arch;
+
+ let answered = false;
+ for (const mirror of releaseMirrors(opts.env ?? process.env)) {
+ const found = await checkMirror(mirror, currentVersion, fetchImpl, platform, arch, timeoutMs);
+ if (found.status === 'update') return found;
+ if (found.status === 'current') answered = true;
}
- return checkOrigin(currentVersion, fetchImpl);
+ const origin = await checkOrigin(currentVersion, fetchImpl, timeoutMs);
+ if (origin.status === 'unreachable' && answered) return { status: 'current' };
+ return origin;
+}
+
+/**
+ * A source's deadline, as an init a caller cannot forget to pass on.
+ *
+ * `AbortSignal.timeout` aborts the body read too, not just the connect — a source
+ * that answers a header and then stalls is the same hang with extra steps.
+ */
+function deadline(ms: number): Pick<RequestInit, 'signal'> {
+ return { signal: AbortSignal.timeout(ms) };
}
/** A mirror's `latest.json`. Anything unreadable is "no answer", not an error. */
@@ -121,14 +193,20 @@ async function checkMirror(
fetchImpl: typeof fetch,
platform: string,
arch: string,
-): Promise<LatestRelease | null> {
+ timeoutMs: number,
+): Promise<UpdateOutcome> {
try {
- const res = await fetchImpl(`${mirror}/latest.json`, { headers: { accept: 'application/json' } });
- if (!res.ok) return null;
+ const res = await fetchImpl(`${mirror}/latest.json`, {
+ headers: { accept: 'application/json' },
+ ...deadline(timeoutMs),
+ });
+ if (!res.ok) return { status: 'unreachable' };
const body = (await res.json()) as MirrorLatest;
- if (!body.version) return null;
+ if (!body.version) return { status: 'unreachable' };
const parsed = parseVersion(body.version);
- if (!parsed || !isNewerVersion(body.version, currentVersion)) return null;
+ // It answered, and what it published is not newer: current, not silence.
+ if (!parsed) return { status: 'unreachable' };
+ if (!isNewerVersion(body.version, currentVersion)) return { status: 'current' };
const version = parsed.parts.join('.') + (parsed.pre ? `-${parsed.pre}` : '');
// This machine's installer if the mirror publishes one, else whatever page it
@@ -139,27 +217,39 @@ async function checkMirror(
// no answer and the origin (whose release page is real) gets asked instead.
const key = downloadKeyFor(platform, arch);
const url = (key ? body.downloads?.[key]?.url : undefined) ?? body.url;
- return url ? { version, url } : null;
+ return url ? { status: 'update', release: { version, url } } : { status: 'unreachable' };
} catch {
- return null;
+ return { status: 'unreachable' };
}
}
async function checkOrigin(
currentVersion: string,
fetchImpl: typeof fetch,
-): Promise<LatestRelease | null> {
+ timeoutMs: number,
+): Promise<UpdateOutcome> {
try {
const res = await fetchImpl(RELEASES_LATEST, {
headers: { accept: 'application/vnd.github+json', 'user-agent': 'estella-editor' },
+ ...deadline(timeoutMs),
});
- if (!res.ok) return null;
+ if (!res.ok) return { status: 'unreachable' };
const body = (await res.json()) as { tag_name?: string; html_url?: string; draft?: boolean };
- if (!body.tag_name || !body.html_url || body.draft) return null;
+ // A draft is the origin answering — there is simply nothing published past this
+ // build yet, which is "current" and not "the network ate it".
+ if (!body.tag_name || !body.html_url) return { status: 'unreachable' };
+ if (body.draft) return { status: 'current' };
const parsed = parseVersion(body.tag_name);
- if (!parsed || !isNewerVersion(body.tag_name, currentVersion)) return null;
- return { version: parsed.parts.join('.') + (parsed.pre ? `-${parsed.pre}` : ''), url: body.html_url };
+ if (!parsed) return { status: 'unreachable' };
+ if (!isNewerVersion(body.tag_name, currentVersion)) return { status: 'current' };
+ return {
+ status: 'update',
+ release: {
+ version: parsed.parts.join('.') + (parsed.pre ? `-${parsed.pre}` : ''),
+ url: body.html_url,
+ },
+ };
} catch {
- return null;
+ return { status: 'unreachable' };
}
}
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.ts
index 0208766c4..29f51a69d 100644
--- a/desktop/src/commands/editorCommands.ts
+++ b/desktop/src/commands/editorCommands.ts
@@ -34,7 +34,7 @@ import { Toasts } from '@/store/Toasts';
import { confirm } from '@/components/confirm';
import { requestPluginPanelAction } from '@/plugins/panelActions';
import { t } from '@/i18n';
-import { notifyUpdate } from '@/update/updateToast';
+import { checkForUpdatesInteractive } from '@/update/updateToast';
import type { ToolMode } from '@/types';
const editor = () => useEditorStore.getState();
@@ -623,10 +623,7 @@ commands.register({
id: 'help.checkUpdates',
label: t('menu.checkUpdates'),
category: t('cat.help'),
- run: () => void window.estella?.app?.checkUpdates?.().then((release) => {
- if (release) notifyUpdate(release);
- else Toasts.push(t('toast.upToDate'), 'success');
- }),
+ run: () => void checkForUpdatesInteractive(),
});
commands.register({
id: 'help.openLogs',
diff --git a/desktop/src/components/Toaster.tsx b/desktop/src/components/Toaster.tsx
index c8d443ef1..84c226a39 100644
--- a/desktop/src/components/Toaster.tsx
+++ b/desktop/src/components/Toaster.tsx
@@ -26,14 +26,30 @@ export function Toaster() {
{toast.action.label}
</button>
)}
- <button
- type="button"
- className="toast__close"
- aria-label={t('ui.dismiss')}
- onClick={() => Toasts.dismiss(toast.id)}
- >
- <X size={12} strokeWidth={2.2} />
- </button>
+ {!toast.pinned && (
+ <button
+ type="button"
+ className="toast__close"
+ aria-label={t('ui.dismiss')}
+ onClick={() => Toasts.dismiss(toast.id)}
+ >
+ <X size={12} strokeWidth={2.2} />
+ </button>
+ )}
+ {toast.progress !== undefined && (
+ <div
+ className={`toast__bar${toast.progress === 'indeterminate' ? ' toast__bar--waiting' : ''}`}
+ role="progressbar"
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={toast.progress === 'indeterminate' ? undefined : toast.progress}
+ >
+ <span
+ className="toast__bar-fill"
+ style={toast.progress === 'indeterminate' ? undefined : { width: `${toast.progress}%` }}
+ />
+ </div>
+ )}
</div>
))}
</div>
diff --git a/desktop/src/i18n/messages/menu.ts b/desktop/src/i18n/messages/menu.ts
index ff074283e..88abcd175 100644
--- a/desktop/src/i18n/messages/menu.ts
+++ b/desktop/src/i18n/messages/menu.ts
@@ -33,10 +33,23 @@ export const menuMessages = defineMessages({
'toast.extractedSchemas': { en: 'Extracted component schemas', zh: '组件 Schema 已提取' },
'toast.extractFailed': { en: 'Extract failed', zh: '提取失败' },
'toast.updateAvailable': { en: 'Estella {version} is available', zh: '新版本 Estella {version} 可用' },
+ 'toast.updateChecking': { en: 'Checking for updates…', zh: '正在检查更新…' },
+ 'toast.updateUnreachable': {
+ en: 'Could not reach the update server',
+ zh: '连不上更新服务器',
+ },
+ 'toast.updateConnecting': {
+ en: 'Starting the Estella {version} download…',
+ zh: '正在开始下载 Estella {version}…',
+ },
'toast.updateDownloading': {
en: 'Downloading Estella {version}… {percent}%',
zh: '正在下载 Estella {version}… {percent}%',
},
+ 'toast.updateDownloadingOf': {
+ en: 'Downloading Estella {version}… {percent}% of {size}',
+ zh: '正在下载 Estella {version}… {percent}% / {size}',
+ },
'toast.updateReady': {
en: 'Estella {version} is ready — restart to install',
zh: 'Estella {version} 已下载完成,重启即可安装',
diff --git a/desktop/src/store/Toasts.ts b/desktop/src/store/Toasts.ts
index 65c134ece..84faa5b36 100644
--- a/desktop/src/store/Toasts.ts
+++ b/desktop/src/store/Toasts.ts
@@ -20,6 +20,15 @@ export interface Toast {
kind: ToastKind;
message: string;
action?: ToastAction;
+ /**
+ * How far along the work behind this toast is: 0–100, or `'indeterminate'` for
+ * "started, no measurable progress yet". A number that has not moved and a bar
+ * that says nothing yet read very differently — a download stuck at "0%" looks
+ * broken, while the same moment shown as indeterminate looks like connecting.
+ */
+ progress?: number | 'indeterminate';
+ /** Hide the close button: work the user cannot get back to if they lose it. */
+ pinned?: boolean;
}
class ToastsImpl {
@@ -30,12 +39,22 @@ class ToastsImpl {
getSnapshot = (): Toast[] => this.store.getState().list;
/** Post a toast; it auto-dismisses after `ttl` ms (0 = sticky until clicked). */
- push(message: string, kind: ToastKind = 'info', ttl = 3200, action?: ToastAction): number {
+ push(
+ message: string,
+ kind: ToastKind = 'info',
+ ttl = 3200,
+ action?: ToastAction,
+ extra?: Pick<Toast, 'progress' | 'pinned'>,
+ ): number {
const id = ++this.seq;
- this.store.setState((s) => ({ list: [...s.list, { id, kind, message, action }] }));
+ this.store.setState((s) => ({ list: [...s.list, { id, kind, message, action, ...extra }] }));
if (ttl > 0) setTimeout(() => this.dismiss(id), ttl);
return id;
}
+ /** Is this toast still on screen? For work that has to re-post if it was closed. */
+ has(id: number): boolean {
+ return this.store.getState().list.some((t) => t.id === id);
+ }
/**
* Rewrite a live toast in place. For a task that reports as it runs — a download's
* percentage — where a toast per tick would be a column of stale numbers. No-op
diff --git a/desktop/src/theme/app.css b/desktop/src/theme/app.css
index 52ab57815..d500a3790 100644
--- a/desktop/src/theme/app.css
+++ b/desktop/src/theme/app.css
@@ -878,6 +878,8 @@ body.thumb-capture .viewport > :not(.viewport__stage):not(.viewport__play) {
pointer-events: none;
}
.toast {
+ position: relative;
+ overflow: hidden;
display: flex;
align-items: center;
gap: 10px;
@@ -923,6 +925,37 @@ body.thumb-capture .viewport > :not(.viewport__stage):not(.viewport__play) {
color: var(--text-hi);
background: var(--hover);
}
+/* Progress rides the toast's bottom edge: it belongs to the whole line, and a
+ download's own words (percent, size) are already in the message. */
+.toast__bar {
+ position: absolute;
+ right: 0;
+ bottom: 0;
+ left: 0;
+ height: 2px;
+ background: var(--line-strong);
+}
+.toast__bar-fill {
+ display: block;
+ height: 100%;
+ background: var(--star);
+ transition: width var(--t) linear;
+}
+/* Nothing measurable yet — a slice sweeping across says "working", where a bar
+ parked at zero says "stuck". */
+.toast__bar--waiting .toast__bar-fill {
+ width: 30%;
+ transition: none;
+ animation: toast-bar-sweep 1.1s ease-in-out infinite;
+}
+@keyframes toast-bar-sweep {
+ from {
+ transform: translateX(-100%);
+ }
+ to {
+ transform: translateX(333%);
+ }
+}
@keyframes toast-in {
from {
opacity: 0;
diff --git a/desktop/src/update/updateToast.ts b/desktop/src/update/updateToast.ts
index a748b290e..7b0f5a309 100644
--- a/desktop/src/update/updateToast.ts
+++ b/desktop/src/update/updateToast.ts
@@ -2,15 +2,20 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file updateToast.ts
- * @brief What the editor shows when a newer release exists. One place, because
- * two surfaces raise it — the startup check and Help ▸ Check for Updates —
- * and an update that behaves differently depending on which one found it
- * would be a bug nobody would think to look for.
+ * @brief What the editor shows for an update, from the click to the restart. One
+ * place, because two surfaces raise it — the startup check and Help ▸ Check
+ * for Updates — and an update that behaves differently depending on which
+ * one found it would be a bug nobody would think to look for.
*
- * A build that can install the update downloads it here, in the toast:
- * progress rewrites the same line, and the button becomes Restart. A build
- * that cannot (see electron/autoUpdate.ts) keeps the older, honest
- * behaviour of handing the user a link.
+ * Every phase has a visible state, because the check crosses a network and
+ * the download crosses it again: the click posts a toast immediately and
+ * that same toast is rewritten in place — checking → the outcome →
+ * downloading → restart. The one thing it must never do is answer a
+ * question it does not have the answer to: a source that never replied is
+ * reported as exactly that, not as "you are up to date".
+ *
+ * A build that cannot install the update (see electron/autoUpdate.ts) keeps
+ * the older, honest behaviour of handing the user a link.
*/
import { Toasts } from '@/store/Toasts';
import { t } from '@/i18n';
@@ -21,14 +26,93 @@ interface AvailableUpdate {
selfInstall: boolean;
}
+type UpdateStatus =
+ | { status: 'update'; update: AvailableUpdate }
+ | { status: 'current' }
+ | { status: 'unreachable' };
+
+const RELEASES = 'https://github.com/esengine/estella/releases/latest';
+
const pct = (n: number): number => Math.max(0, Math.min(100, Math.round(n)));
+/** Bytes as the size a human would quote — one decimal, MB up to a gigabyte. */
+function size(bytes: number): string {
+ if (!Number.isFinite(bytes) || bytes <= 0) return '';
+ const mb = bytes / 1024 / 1024;
+ return mb >= 1024 ? `${(mb / 1024).toFixed(1)} GB` : `${mb.toFixed(1)} MB`;
+}
+
+/** A check is one at a time: the second click should join the first, not race it. */
+let checking: Promise<void> | null = null;
+
+/**
+ * Run a manual check and report all three outcomes. The toast exists BEFORE the
+ * request does — the whole complaint was that clicking the menu item did nothing
+ * for as long as the network took, which on a filtered one was forever.
+ */
+export function checkForUpdatesInteractive(): Promise<void> {
+ if (checking) return checking;
+ const id = Toasts.push(t('toast.updateChecking'), 'info', 0, undefined, {
+ progress: 'indeterminate',
+ pinned: true,
+ });
+
+ checking = (async () => {
+ let result: UpdateStatus;
+ try {
+ result = (await window.estella?.app?.checkUpdates?.()) ?? { status: 'unreachable' };
+ } catch (err) {
+ console.error('[update] check failed', err);
+ result = { status: 'unreachable' };
+ }
+
+ if (result.status === 'update') {
+ Toasts.dismiss(id);
+ notifyUpdate(result.update);
+ return;
+ }
+ if (result.status === 'current') {
+ Toasts.revise(id, {
+ message: t('toast.upToDate'),
+ kind: 'success',
+ progress: undefined,
+ pinned: false,
+ });
+ setTimeout(() => Toasts.dismiss(id), 3200);
+ return;
+ }
+ // Nobody answered. Say so, and leave the door the user can walk through anyway.
+ Toasts.revise(id, {
+ message: t('toast.updateUnreachable'),
+ kind: 'warn',
+ progress: undefined,
+ pinned: false,
+ action: { label: t('ui.download'), run: () => window.open(RELEASES) },
+ });
+ })().finally(() => {
+ checking = null;
+ });
+
+ return checking;
+}
+
+/**
+ * The version a toast is already about, so the two surfaces that raise this — the
+ * startup check and the menu — announce one release once. Clicking Check for
+ * Updates a few seconds after launch used to answer with two identical lines.
+ */
+let announced: { version: string; id: number } | null = null;
+
/** Post the "there is a newer Estella" toast, wired to whatever this build can do. */
export function notifyUpdate(release: AvailableUpdate): void {
+ if (announced?.version === release.version && Toasts.has(announced.id)) return;
const openInBrowser = { label: t('ui.download'), run: () => window.open(release.url) };
if (!release.selfInstall) {
- Toasts.push(t('toast.updateAvailable', { version: release.version }), 'info', 0, openInBrowser);
+ const linked = Toasts.push(
+ t('toast.updateAvailable', { version: release.version }), 'info', 0, openInBrowser,
+ );
+ announced = { version: release.version, id: linked };
return;
}
@@ -37,34 +121,70 @@ export function notifyUpdate(release: AvailableUpdate): void {
label: t('ui.download'),
run: () => void download(id, release),
});
+ announced = { version: release.version, id };
}
async function download(id: number, release: AvailableUpdate): Promise<void> {
const bridge = window.estella?.app;
if (!bridge?.downloadUpdate) return;
- const show = (percent: number) =>
- Toasts.revise(id, {
- message: t('toast.updateDownloading', { version: release.version, percent }),
+ // The download outlives its toast if the user closes it — and then there is no
+ // way back to "Restart", so the line re-posts itself rather than disappearing.
+ let live = id;
+ const write = (patch: Parameters<typeof Toasts.revise>[1]): void => {
+ if (!Toasts.has(live)) {
+ live = Toasts.push(patch.message ?? '', patch.kind ?? 'info', 0, patch.action, {
+ progress: patch.progress,
+ pinned: patch.pinned,
+ });
+ // The line this release owns moved; keep the "announce once" guard pointing
+ // at the toast that is actually on screen.
+ if (announced?.version === release.version) announced.id = live;
+ return;
+ }
+ Toasts.revise(live, patch);
+ };
+
+ // Until the first byte report there is nothing to be a percentage OF: connecting,
+ // resolving, and (on a mirror) a redirect all land here, and "0%" reads as stuck.
+ write({
+ message: t('toast.updateConnecting', { version: release.version }),
+ action: undefined,
+ progress: 'indeterminate',
+ pinned: true,
+ });
+
+ const stop = bridge.onUpdateProgress?.((p) => {
+ const percent = pct(p.percent);
+ const total = size(p.total);
+ write({
+ message: total
+ ? t('toast.updateDownloadingOf', { version: release.version, percent, size: total })
+ : t('toast.updateDownloading', { version: release.version, percent }),
action: undefined,
+ progress: percent,
+ pinned: true,
});
- show(0);
- const stop = bridge.onUpdateProgress?.((p) => show(pct(p.percent)));
+ });
try {
await bridge.downloadUpdate();
- Toasts.revise(id, {
+ write({
message: t('toast.updateReady', { version: release.version }),
kind: 'success',
+ progress: undefined,
+ pinned: false,
action: { label: t('ui.restart'), run: () => void bridge.installUpdate?.() },
});
} catch (err) {
console.error('[update] download failed', err);
// The link still works when the download did not — a failed update should cost
// the user a click, not the update.
- Toasts.revise(id, {
+ write({
message: t('toast.updateFailed'),
kind: 'error',
+ progress: undefined,
+ pinned: false,
action: { label: t('ui.download'), run: () => window.open(release.url) },
});
} finally {
diff --git a/desktop/tests/update-check.test.ts b/desktop/tests/update-check.test.ts
index 9a16792b8..de137dd4f 100644
--- a/desktop/tests/update-check.test.ts
+++ b/desktop/tests/update-check.test.ts
@@ -1,7 +1,9 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect } from 'vitest';
-import { parseVersion, isNewerVersion, checkForUpdate, downloadKeyFor, updateFeeds } from '../electron/updateCheck';
+import {
+ parseVersion, isNewerVersion, checkForUpdate, describeUpdate, downloadKeyFor, updateFeeds,
+} from '../electron/updateCheck';
import { DEFAULT_RELEASE_MIRROR } from '../../build-tools/utils/nativeTemplate.js';
describe('parseVersion', () => {
@@ -188,3 +190,77 @@ describe('updateFeeds', () => {
}
});
});
+
+// — Three answers, and a deadline ————————————————————————————————————————————————
+//
+// "No update" and "nobody answered" were the same null, and the editor reported
+// both as "up to date" — in green, to a machine that had reached nothing. And the
+// probes had no timeout at all: `catch` catches a connection that FAILS, not one
+// that is accepted and then never speaks, which is what a filtered network does.
+
+describe('describeUpdate', () => {
+ it('separates a source that says no from a source that says nothing', async () => {
+ const current = fetchRouting({ [MIRROR]: { ...LATEST, version: '0.35.0' } });
+ expect(await describeUpdate('0.35.0', { fetch: current, env, platform: 'win32', arch: 'x64' }))
+ .toEqual({ status: 'current' });
+
+ const silent = fetchRouting({});
+ expect(await describeUpdate('0.35.0', { fetch: silent, env, platform: 'win32', arch: 'x64' }))
+ .toEqual({ status: 'unreachable' });
+ });
+
+ it('reports the release when one is published', async () => {
+ const f = fetchRouting({ [MIRROR]: LATEST });
+ expect(await describeUpdate('0.34.1', { fetch: f, env, platform: 'win32', arch: 'x64' })).toEqual({
+ status: 'update',
+ release: { version: '0.35.0', url: 'https://m.test/latest/Estella-Editor-Setup.exe' },
+ });
+ });
+
+ it('a mirror that is merely current still lets the origin be asked', async () => {
+ // The mirror can lag the origin, which is why the origin is asked second at all.
+ const f = fetchRouting({
+ [MIRROR]: { ...LATEST, version: '0.35.0' },
+ 'https://api.github.com': { tag_name: 'v0.36.0', html_url: 'https://github.com/x/releases/v0.36.0' },
+ });
+ expect(await describeUpdate('0.35.0', { fetch: f, env, platform: 'win32', arch: 'x64' })).toEqual({
+ status: 'update',
+ release: { version: '0.36.0', url: 'https://github.com/x/releases/v0.36.0' },
+ });
+ });
+
+ it('a mirror that answered outranks an origin that did not', async () => {
+ // Reaching one source and losing the other is "current", not "unreachable":
+ // something DID tell us where this build stands.
+ const f = fetchRouting({ [MIRROR]: { ...LATEST, version: '0.35.0' } });
+ expect(await describeUpdate('0.35.0', { fetch: f, env, platform: 'win32', arch: 'x64' }))
+ .toEqual({ status: 'current' });
+ });
+
+ it('gives up on a source that accepts the connection and then says nothing', async () => {
+ // The bug this exists for: no timeout meant the promise never settled, so the
+ // menu command waited forever and the user saw a click that did nothing.
+ const blackhole = ((_url: string, init?: RequestInit) =>
+ new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener('abort', () => reject(new Error('aborted')));
+ })) as unknown as typeof fetch;
+
+ const started = Date.now();
+ expect(await describeUpdate('0.35.0', { fetch: blackhole, env, timeoutMs: 30 }))
+ .toEqual({ status: 'unreachable' });
+ // Two sources, one deadline each — and it RESOLVED, which is the whole point.
+ expect(Date.now() - started).toBeLessThan(2000);
+ });
+
+ it('passes a deadline to every request it makes', async () => {
+ const seen: Array<AbortSignal | null | undefined> = [];
+ const f = ((_url: string, init?: RequestInit) => {
+ seen.push(init?.signal);
+ return Promise.resolve({ ok: false, status: 404, json: async () => ({}) });
+ }) as unknown as typeof fetch;
+
+ await describeUpdate('0.35.0', { fetch: f, env, timeoutMs: 50 });
+ expect(seen.length).toBe(2); // the mirror and the origin
+ for (const signal of seen) expect(signal).toBeInstanceOf(AbortSignal);
+ });
+});
diff --git a/desktop/tests/update-toast.test.ts b/desktop/tests/update-toast.test.ts
new file mode 100644
index 000000000..ef7305a3c
--- /dev/null
+++ b/desktop/tests/update-toast.test.ts
@@ -0,0 +1,228 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What the user sees for an update, from the click to the restart.
+ *
+ * The complaint this answers was "clicking Check for Updates does nothing":
+ * the toast used to be posted only once the network had answered, and on a
+ * network that never answers, never. So the assertions here are mostly about
+ * WHEN a toast exists, not just what it says — and about the one outcome the
+ * old code could not express, a source that said nothing being reported as
+ * "up to date" in green.
+ *
+ * The download half is driven through a stand-in bridge because the real one
+ * (electron-updater) only exists in a packaged, signed build; what is covered
+ * here is every state the renderer puts on screen in between.
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import { Toasts, type Toast } from '@/store/Toasts';
+import { checkForUpdatesInteractive, notifyUpdate } from '@/update/updateToast';
+
+interface AppBridge {
+ checkUpdates?: () => Promise<unknown>;
+ downloadUpdate?: () => Promise<void>;
+ installUpdate?: () => Promise<boolean>;
+ onUpdateProgress?: (cb: (p: { percent: number; transferred: number; total: number; bytesPerSecond: number }) => void) => () => void;
+}
+
+const opened: string[] = [];
+
+function bridge(app: AppBridge | undefined): void {
+ (globalThis as unknown as { window: unknown }).window = {
+ estella: app ? { app } : undefined,
+ open: (url: string) => { opened.push(url); return null; },
+ };
+}
+
+const toasts = (): Toast[] => Toasts.getSnapshot();
+const only = (): Toast => {
+ const list = toasts();
+ expect(list).toHaveLength(1);
+ return list[0];
+};
+const settle = (): Promise<void> => new Promise((r) => setTimeout(r, 0));
+
+beforeEach(() => {
+ for (const toast of toasts()) Toasts.dismiss(toast.id);
+ opened.length = 0;
+ bridge({});
+});
+
+describe('checkForUpdatesInteractive', () => {
+ it('shows that it is checking BEFORE the network answers', async () => {
+ let answer: (v: unknown) => void = () => {};
+ bridge({ checkUpdates: () => new Promise((r) => { answer = r; }) });
+
+ const done = checkForUpdatesInteractive();
+ // The whole bug: this instant used to be empty, for as long as the request took.
+ const checking = only();
+ expect(checking.message).toBe('Checking for updates…');
+ expect(checking.progress).toBe('indeterminate');
+ expect(checking.pinned).toBe(true); // nothing to close: it is not an outcome yet
+
+ answer({ status: 'current' });
+ await done;
+ expect(only().message).toBe('Estella is up to date');
+ });
+
+ it('rewrites the same line rather than stacking a second toast', async () => {
+ bridge({ checkUpdates: async () => ({ status: 'current' }) });
+ await checkForUpdatesInteractive();
+ const settled = only();
+ expect(settled.kind).toBe('success');
+ expect(settled.progress).toBeUndefined();
+ expect(settled.pinned).toBe(false); // an outcome can be dismissed
+ });
+
+ it('says nobody answered instead of claiming you are up to date', async () => {
+ bridge({ checkUpdates: async () => ({ status: 'unreachable' }) });
+ await checkForUpdatesInteractive();
+
+ const toast = only();
+ expect(toast.message).toBe('Could not reach the update server');
+ expect(toast.kind).toBe('warn');
+ // And it still leaves a way through: the release page is reachable by hand.
+ expect(toast.action?.label).toBe('Download');
+ toast.action?.run();
+ expect(opened).toEqual(['https://github.com/esengine/estella/releases/latest']);
+ });
+
+ it('treats a check that threw, and a bridge that is not there, as unreachable', async () => {
+ bridge({ checkUpdates: async () => { throw new Error('EAI_AGAIN'); } });
+ await checkForUpdatesInteractive();
+ expect(only().message).toBe('Could not reach the update server');
+
+ for (const toast of toasts()) Toasts.dismiss(toast.id);
+ bridge(undefined); // no preload at all — a browser tab, or a bridge that failed
+ await checkForUpdatesInteractive();
+ expect(only().message).toBe('Could not reach the update server');
+ });
+
+ it('hands an update to the notification instead of leaving the checking line up', async () => {
+ bridge({
+ checkUpdates: async () => ({
+ status: 'update',
+ update: { version: '9.9.9', url: 'https://example.test', selfInstall: false },
+ }),
+ });
+ await checkForUpdatesInteractive();
+
+ const toast = only(); // one line, not "checking" plus "available"
+ expect(toast.message).toBe('Estella 9.9.9 is available');
+ expect(toast.progress).toBeUndefined();
+ });
+
+ it('announces one release once, however many surfaces found it', async () => {
+ // Startup checks ~5s after launch; a user who clicks the menu item in that
+ // window used to get the same line twice.
+ const release = { version: '9.9.9', url: 'https://example.test', selfInstall: false };
+ notifyUpdate(release);
+ notifyUpdate(release);
+ expect(toasts()).toHaveLength(1);
+
+ // A different version is different news, and a dismissed one may be re-raised.
+ notifyUpdate({ ...release, version: '9.9.10' });
+ expect(toasts()).toHaveLength(2);
+ for (const toast of toasts()) Toasts.dismiss(toast.id);
+ notifyUpdate(release);
+ expect(toasts()).toHaveLength(1);
+ });
+
+ it('a second click joins the check in flight instead of starting another', async () => {
+ let calls = 0;
+ let answer: (v: unknown) => void = () => {};
+ bridge({ checkUpdates: () => { calls++; return new Promise((r) => { answer = r; }); } });
+
+ const first = checkForUpdatesInteractive();
+ const second = checkForUpdatesInteractive();
+ expect(calls).toBe(1);
+ expect(toasts()).toHaveLength(1);
+
+ answer({ status: 'current' });
+ await Promise.all([first, second]);
+ expect(calls).toBe(1);
+ });
+});
+
+describe('the download', () => {
+ /** A bridge whose download is driven by the test, byte report by byte report. */
+ function downloadBridge() {
+ let emit: ((p: { percent: number; transferred: number; total: number; bytesPerSecond: number }) => void) | null = null;
+ let finish: () => void = () => {};
+ let fail: (e: Error) => void = () => {};
+ let installed = false;
+ bridge({
+ onUpdateProgress: (cb) => { emit = cb; return () => { emit = null; }; },
+ downloadUpdate: () => new Promise<void>((resolve, reject) => { finish = resolve; fail = reject; }),
+ installUpdate: async () => { installed = true; return true; },
+ });
+ return {
+ report: (percent: number, total = 214_000_000) =>
+ emit?.({ percent, transferred: (total * percent) / 100, total, bytesPerSecond: 5e6 }),
+ finish: () => { finish(); return settle(); },
+ fail: () => { fail(new Error('ECONNRESET')); return settle(); },
+ installed: () => installed,
+ };
+ }
+
+ const startDownload = async (): Promise<void> => {
+ notifyUpdate({ version: '9.9.9', url: 'https://example.test', selfInstall: true });
+ only().action?.run();
+ await settle();
+ };
+
+ it('says it is starting rather than showing a 0% that has not moved', async () => {
+ downloadBridge();
+ await startDownload();
+
+ const toast = only();
+ expect(toast.message).toBe('Starting the Estella 9.9.9 download…');
+ expect(toast.progress).toBe('indeterminate');
+ expect(toast.pinned).toBe(true);
+ });
+
+ it('reports percentage and size once bytes are actually arriving', async () => {
+ const dl = downloadBridge();
+ await startDownload();
+
+ dl.report(37.4);
+ const toast = only();
+ expect(toast.progress).toBe(37);
+ expect(toast.message).toBe('Downloading Estella 9.9.9… 37% of 204.1 MB');
+ });
+
+ it('comes back if the user closes it, so Restart stays reachable', async () => {
+ const dl = downloadBridge();
+ await startDownload();
+ dl.report(20);
+
+ Toasts.dismiss(only().id); // the download keeps running with nothing on screen
+ expect(toasts()).toHaveLength(0);
+
+ dl.report(60);
+ expect(only().progress).toBe(60);
+
+ await dl.finish();
+ const ready = only();
+ expect(ready.message).toBe('Estella 9.9.9 is ready — restart to install');
+ expect(ready.kind).toBe('success');
+ expect(ready.progress).toBeUndefined();
+ expect(ready.pinned).toBe(false);
+
+ ready.action?.run();
+ expect(dl.installed()).toBe(true);
+ });
+
+ it('falls back to the link when the download itself fails', async () => {
+ const dl = downloadBridge();
+ await startDownload();
+ dl.report(12);
+ await dl.fail();
+
+ const toast = only();
+ expect(toast.kind).toBe('error');
+ expect(toast.progress).toBeUndefined();
+ toast.action?.run();
+ expect(opened).toEqual(['https://example.test']);
+ });
+});