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.

feat(editor): the editor downloads its own update, instead of opening a browser

esengine0d6ae418262e
diff --git a/.github/workflows/mirror-release.yml b/.github/workflows/mirror-release.yml
index db909af94..cb1a8d856 100644
--- a/.github/workflows/mirror-release.yml
+++ b/.github/workflows/mirror-release.yml
@@ -146,6 +146,18 @@ jobs:
'$d + {"mac-arm64": {url: $url, name: $name, size: $size}}')
fi
+ # The updater's feed. electron-updater reads latest.yml / latest-mac.yml
+ # and then fetches the file each one NAMES, resolved against the same
+ # directory — so the channel files are copied beside the very files they
+ # name, under their real versioned basenames. Nothing is rewritten: the
+ # channel file the release published is the channel file served, sha512s
+ # and all, and a mirror that cannot restate a fact cannot get it wrong.
+ for f in mirror/latest*.yml mirror/*.exe mirror/*.dmg mirror/*.zip mirror/*.blockmap; do
+ aws s3 cp "s3://$BUCKET/v$version/$(basename "$f")" "s3://$BUCKET/latest/$(basename "$f")" \
+ --endpoint-url "$ENDPOINT" --no-progress \
+ --metadata-directive REPLACE --cache-control "max-age=300"
+ done
+
# Written last, and only for the newest release: an editor that reads
# latest.json must never be pointed at a version whose assets are still
# uploading, nor at an older one somebody re-mirrored. `version` and
@@ -162,6 +174,46 @@ jobs:
aws s3 cp latest.json "s3://$BUCKET/latest.json" \
--endpoint-url "$ENDPOINT" --cache-control "max-age=300"
+ # A feed that names a file nobody can fetch is an update that dies at the
+ # download — the failure the versioned-directory url already taught this
+ # project, one layer down. So every file the channel files name is asked for
+ # over the public base, and a miss fails the job.
+ #
+ # The names come from the copies on disk, not from re-reading the published
+ # channel file: that one is overwritten every release behind a 300s cache, and
+ # a stale body would name the PREVIOUS release's files and fail for a reason
+ # that has nothing to do with what was just uploaded.
+ - name: Prove the updater feed resolves
+ if: steps.cfg.outputs.configured == 'true' && steps.latest.outputs.is_latest == 'true'
+ env:
+ PUBLIC_BASE: ${{ secrets.R2_PUBLIC_BASE }}
+ run: |
+ base="${PUBLIC_BASE%/}"
+ shopt -s nullglob
+ channels=(mirror/latest*.yml)
+ if [ ${#channels[@]} -eq 0 ]; then
+ echo "::error::the release published no channel file — nothing can auto-update"
+ exit 1
+ fi
+ reachable() {
+ code=$(curl -sS -o /dev/null -w '%{http_code}' -I "$1") || code=000
+ [ "$code" = "200" ] || { echo "::error::$1 answers $code"; return 1; }
+ }
+ checked=0
+ for channel in "${channels[@]}"; do
+ reachable "$base/latest/$(basename "$channel")" || exit 1
+ names=$(sed -nE 's/^[[:space:]]*-?[[:space:]]*(url|path):[[:space:]]*"?([^"]+)"?[[:space:]]*$/\2/p' "$channel" | sort -u)
+ if [ -z "$names" ]; then
+ echo "::error::$(basename "$channel") names no file to download"
+ exit 1
+ fi
+ for name in $names; do
+ reachable "$base/latest/$name" || exit 1
+ checked=$((checked + 1))
+ done
+ done
+ echo "updater feed OK — ${#channels[@]} channel file(s), $checked payload url(s) reachable"
+
# The website reads latest.json from a different origin than the bucket, so
# without this its version and size labels are blocked — the download links
# themselves are plain navigations and never were. Re-applied every run
diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml
index 3b6bc9c88..00be49405 100644
--- a/.github/workflows/release-desktop.yml
+++ b/.github/workflows/release-desktop.yml
@@ -10,6 +10,15 @@ on:
# burning a tag.
workflow_dispatch:
+# Signing the macOS build is optional, and everything degrades when it is absent:
+# five secrets — MAC_CSC_LINK (base64 of the Developer ID Application .p12),
+# MAC_CSC_KEY_PASSWORD, APPLE_ID, APPLE_APP_SPECIFIC_PASSWORD, APPLE_TEAM_ID.
+# Unset, electron-builder logs that it skipped signing and notarization and still
+# produces installers, and the editor keeps handing macOS users a download link
+# instead of updating in place (electron/autoUpdate.ts settles that by reading the
+# running bundle's own signature). Windows needs no certificate to auto-update; one
+# would buy a quiet SmartScreen, not the capability.
+
# Read by default; the two jobs that touch the release raise it to contents:write.
permissions:
contents: read
@@ -255,6 +264,12 @@ jobs:
shell: bash
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ CSC_LINK: ${{ secrets.MAC_CSC_LINK }}
+ CSC_KEY_PASSWORD: ${{ secrets.MAC_CSC_KEY_PASSWORD }}
+ # An app-specific password, NOT the Apple ID's own.
+ APPLE_ID: ${{ secrets.APPLE_ID }}
+ APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
# electron-builder's GitHub publisher dedups assets on re-upload, so the
# whole command is idempotent — retry it to ride out GitHub API 5xx
# blips (a 503 on GET /releases has failed an otherwise-finished build
@@ -282,6 +297,7 @@ jobs:
path: |
desktop/release/*.exe
desktop/release/*.dmg
+ desktop/release/*.zip
retention-days: 3
# Publishing is the last step, and the one that has to be sure. A release missing
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1a7afebcf..f4d5dc26f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,30 @@ published separately; it ships inside the editor.
## [Unreleased]
+### Added
+
+- **The editor updates itself.** Until now an update notification could only hand
+ over a link: the build is unsigned, and silent auto-update needs a signature it
+ did not have. The check, the download and the install are now the editor's own —
+ progress reports into the toast that announced the update, and the button becomes
+ Restart when the download lands. The download comes from whichever source
+ answered the check, mirror before origin, so it is as fast as the check was.
+- **The macOS build ships a zip alongside the dmg.** Not a second thing to
+ download — it is what an in-place update installs from. Squirrel.Mac swaps in a
+ whole signed `.app`, which a dmg is not.
+- **Releases can be signed and notarized.** `release-desktop.yml` reads five
+ optional secrets (`MAC_CSC_LINK`, `MAC_CSC_KEY_PASSWORD`, `APPLE_ID`,
+ `APPLE_APP_SPECIFIC_PASSWORD`, `APPLE_TEAM_ID`). Unset — on a fork, or before a
+ certificate exists — the build still produces installers, and the editor keeps
+ handing macOS users a link, because it checks its own signature before offering
+ to update in place rather than discovering the problem after a 200 MB download.
+- **The mirror publishes the updater's feed, and proves it.** `latest.yml` and
+ `latest-mac.yml` are copied beside the very files they name, under their real
+ names, so nothing has to be rewritten and no url is composed. Every file the
+ channel files name is then fetched over the public base, and the mirror job fails
+ on a miss — a feed naming a file nobody can fetch is an update that dies at the
+ download.
+
## [0.34.1] - 2026-07-27
0.34.0 made a game packageable for Android. This one makes the package
diff --git a/desktop/electron-builder.yml b/desktop/electron-builder.yml
index 313a27e01..d0a1407ca 100644
--- a/desktop/electron-builder.yml
+++ b/desktop/electron-builder.yml
@@ -98,9 +98,21 @@ mac:
# the host-arch esbuild native binary, so the x64 slice would ship a broken esbuild
# (and electron-builder rejects the identical-across-arch binary). Intel-mac support
# would need the darwin-x64 esbuild binary installed for a separate x64 dmg.
+ #
+ # The zip is not a second thing to download — it is what Squirrel.Mac installs
+ # from. An in-place update swaps in a whole signed .app, which a dmg is not, so a
+ # release carrying only the dmg leaves latest-mac.yml naming a file nobody shipped
+ # and every macOS auto-update fails at the last step.
+ #
+ # Everything else macOS signing needs is already the default: a hardened runtime,
+ # entitlements granting the JIT the engine's wasm runs on, and notarization
+ # whenever APPLE_ID and friends are in the environment (skipped with a warning
+ # when they are not, which is what a local `pnpm dist` wants).
target:
- target: dmg
arch: arm64
+ - target: zip
+ arch: arm64
category: public.app-category.developer-tools
linux:
target: AppImage
diff --git a/desktop/electron/autoUpdate.ts b/desktop/electron/autoUpdate.ts
new file mode 100644
index 000000000..8b8179417
--- /dev/null
+++ b/desktop/electron/autoUpdate.ts
@@ -0,0 +1,167 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file autoUpdate.ts
+ * @brief The editor installs its own update where it can, and links to a
+ * download where it cannot. electron-updater does the check, the download
+ * and the handover to the installer; updateCheck.ts remains the fallback.
+ * The two never both decide — `findUpdate` picks one and reports which.
+ *
+ * Two builds cannot install an update. An unpackaged one has no
+ * app-update.yml to read. An UNSIGNED macOS bundle reads one, downloads
+ * the entire update, and only then does Squirrel.Mac refuse it for want of
+ * a signature — so the signature is settled up front, and a build that
+ * would fail at the end never starts.
+ *
+ * The feed is the mirror before the origin, for the reason the update
+ * check and the runtime templates already ask a mirror first: the origin
+ * is slow where most of the users are. A mirror publishes the channel
+ * files under `latest/` beside the files they name (mirror-release.yml),
+ * so pointing at one is a base swap and nothing else.
+ */
+import path from 'node:path';
+import { spawnSync } from 'node:child_process';
+import { app } from 'electron';
+import { checkForUpdate, updateFeeds, type LatestRelease } from './updateCheck';
+
+/** Where a self-installing update sends anyone who would rather read about it first. */
+const RELEASE_PAGE = 'https://github.com/esengine/estella/releases/latest';
+
+export interface AvailableUpdate extends LatestRelease {
+ /** The editor can download and install this one; `url` is then only a fallback. */
+ selfInstall: boolean;
+}
+
+export interface DownloadProgress {
+ percent: number;
+ transferred: number;
+ total: number;
+ bytesPerSecond: number;
+}
+
+type Updater = (typeof import('electron-updater'))['autoUpdater'];
+
+let updaterPromise: Promise<Updater> | null = null;
+
+/**
+ * The updater, loaded on first use.
+ *
+ * Lazily, like esbuild (see esbuildRuntime.ts): constructing it reads
+ * app-update.yml and picks a platform implementation, which is work no build that
+ * links to a download should pay for at startup.
+ *
+ * `default ?? namespace` because electron-updater is CommonJS and publishes
+ * `autoUpdater` through `Object.defineProperty` — a getter that cjs-module-lexer
+ * cannot see, so Node's ESM interop may expose it only under `default`.
+ */
+async function updater(): Promise<Updater> {
+ if (!updaterPromise) {
+ updaterPromise = import('electron-updater').then((mod) => {
+ const autoUpdater = (mod.default ?? mod).autoUpdater;
+ // A 200 MB download is the user's call, not a background surprise. Installing
+ // on quit IS left on: someone who took the download and then never restarted
+ // still gets the update, at the moment it costs them nothing.
+ autoUpdater.autoDownload = false;
+ autoUpdater.autoInstallOnAppQuit = true;
+ autoUpdater.logger = console;
+ return autoUpdater;
+ });
+ }
+ return updaterPromise;
+}
+
+let macSignature: boolean | null = null;
+
+/**
+ * Whether the running macOS bundle carries a signature Squirrel.Mac will accept.
+ *
+ * An ad-hoc signature passes `codesign`'s exit code but not Squirrel, which matches
+ * the update's identity against the running app's — so it is rejected here too.
+ */
+function macBundleIsSigned(): boolean {
+ if (macSignature === null) {
+ try {
+ // …/Estella Editor.app/Contents/MacOS/Estella Editor → the .app itself.
+ const bundle = path.resolve(path.dirname(app.getPath('exe')), '..', '..');
+ const probe = spawnSync('/usr/bin/codesign', ['-dv', bundle], { encoding: 'utf8' });
+ macSignature = probe.status === 0 && !/Signature=adhoc/.test(probe.stderr ?? '');
+ } catch {
+ macSignature = false;
+ }
+ }
+ return macSignature;
+}
+
+/** Whether this build can download and install an update in place. */
+export function canSelfInstall(): boolean {
+ if (!app.isPackaged) return false;
+ if (process.platform === 'darwin') return macBundleIsSigned();
+ return process.platform === 'win32';
+}
+
+/** Reached a feed and got an answer, or reached none at all. */
+type CheckOutcome = { reached: true; update: AvailableUpdate | null } | { reached: false };
+
+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();
+ if (!result) continue;
+ // The feed that answered stays selected, so the download comes from the
+ // source that was fast enough to be asked.
+ if (!result.isUpdateAvailable) return { reached: true, update: null };
+ return {
+ reached: true,
+ update: { version: result.updateInfo.version, url: RELEASE_PAGE, selfInstall: true },
+ };
+ } catch (err) {
+ console.warn('[update] feed unusable, trying the next', err);
+ }
+ }
+ return { reached: false };
+}
+
+/**
+ * The newest release if it is newer than this build, else null.
+ *
+ * Never throws: an update check must not be able to break editor startup.
+ */
+export async function findUpdate(currentVersion: string = app.getVersion()): Promise<AvailableUpdate | null> {
+ if (canSelfInstall()) {
+ // Catches what the per-feed handler cannot: loading the updater at all.
+ const outcome = await checkWithUpdater().catch((err): CheckOutcome => {
+ console.warn('[update] updater unavailable, falling back to the link', err);
+ return { reached: false };
+ });
+ // 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;
+ }
+ const release = await checkForUpdate(currentVersion);
+ return release ? { ...release, selfInstall: false } : null;
+}
+
+let downloaded = false;
+
+/** Download the update found by the last `findUpdate`, reporting progress. */
+export async function downloadUpdate(onProgress: (p: DownloadProgress) => void): Promise<void> {
+ const autoUpdater = await updater();
+ const relay = (p: DownloadProgress) => onProgress(p);
+ autoUpdater.on('download-progress', relay);
+ try {
+ await autoUpdater.downloadUpdate();
+ downloaded = true;
+ } finally {
+ autoUpdater.removeListener('download-progress', relay);
+ }
+}
+
+/** Quit and hand the app to the installer. No-op until a download has finished. */
+export async function installUpdate(): Promise<boolean> {
+ if (!downloaded) return false;
+ const autoUpdater = await updater();
+ autoUpdater.quitAndInstall();
+ return true;
+}
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 6e177e1c2..a60beb538 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -54,7 +54,7 @@ import {
packPlugin, packageFileName, inspectPluginPackage, installPluginPackage, writePackage,
PLUGIN_PACKAGE_EXT,
} from './pluginPackage';
-import { checkForUpdate } from './updateCheck';
+import { findUpdate, downloadUpdate, installUpdate } from './autoUpdate';
import {
listPlatforms, loadProjectPlatform, createProjectPlatform, setPlatformTrustGate,
listPlayableNetworks, loadPlayableProfile,
@@ -543,24 +543,13 @@ function createWindow() {
// documents (scene or asset editors — the renderer pushes the aggregate via
// app:dirty); `quitting` lets the chosen action close past this handler.
win.on('close', (e) => {
- // Screenshot / automation mode discards unsaved changes silently — a shot run
- // dirties the scene (it creates/edits entities), and a blocking save prompt on
- // app.quit() would hang the headless run waiting for a click.
if (process.env.ESTELLA_SHOT || quitting || !editorDirty || !win) return;
e.preventDefault();
- const choice = dialog.showMessageBoxSync(win, {
- type: 'warning',
- buttons: ['Save All', "Don't Save", 'Cancel'],
- defaultId: 0,
- cancelId: 2,
- message: 'Save changes before closing?',
- detail: 'The scene or an open asset editor has unsaved changes that will be lost otherwise.',
+ void settleUnsavedChanges().then((proceed) => {
+ if (!proceed) return; // Cancel → keep the window open
+ quitting = true;
+ win?.destroy();
});
- if (choice === 2) return; // Cancel → keep the window open
- if (choice === 1) { quitting = true; win.destroy(); return; } // Don't Save
- // Save All → ask the renderer to save every dirty document, then close when it confirms.
- ipcMain.once('app:quitConfirmed', () => { quitting = true; win?.destroy(); });
- win.webContents.send('app:saveBeforeQuit');
});
}
@@ -571,10 +560,52 @@ let editorDirty = false;
let quitting = false;
ipcMain.on('app:dirty', (_e, dirty: boolean) => { editorDirty = !!dirty; });
+/**
+ * Settle unsaved work before something that ends this session. Resolves true when
+ * it may go ahead, false when the user chose Cancel.
+ *
+ * Shared by the window's close guard and the update installer, which BOTH end the
+ * session — and the installer is the one that cannot be allowed to skip it, since
+ * quitAndInstall launches the installer and only then quits. Prompting after that
+ * would let a Cancel leave the editor running while its own files are replaced.
+ *
+ * Screenshot / automation mode saves nothing and asks nothing: a shot run dirties
+ * the scene by creating entities, and a modal prompt on quit would hang it waiting
+ * for a click nobody is there to give.
+ */
+function settleUnsavedChanges(): Promise<boolean> {
+ if (process.env.ESTELLA_SHOT || !editorDirty || !win) return Promise.resolve(true);
+ const choice = dialog.showMessageBoxSync(win, {
+ type: 'warning',
+ buttons: ['Save All', "Don't Save", 'Cancel'],
+ defaultId: 0,
+ cancelId: 2,
+ message: 'Save changes before closing?',
+ detail: 'The scene or an open asset editor has unsaved changes that will be lost otherwise.',
+ });
+ if (choice === 2) return Promise.resolve(false);
+ if (choice === 1) return Promise.resolve(true);
+ // Save All → the renderer saves every dirty document and confirms when done.
+ return new Promise((resolve) => {
+ ipcMain.once('app:quitConfirmed', () => resolve(true));
+ win?.webContents.send('app:saveBeforeQuit');
+ });
+}
+
// — Minimal IPC surface (expanded as the editor grows) —
ipcMain.handle('app:version', () => app.getVersion());
ipcMain.handle('app:platform', () => process.platform);
-ipcMain.handle('app:checkUpdates', () => checkForUpdate(app.getVersion()));
+ipcMain.handle('app:checkUpdates', () => findUpdate());
+ipcMain.handle('app:downloadUpdate', (e) =>
+ downloadUpdate((progress) => e.sender.send('app:updateProgress', progress)),
+);
+ipcMain.handle('app:installUpdate', async () => {
+ if (!(await settleUnsavedChanges())) return false;
+ // Past the prompt the session is over, so the close guard must not ask again —
+ // it would run against a window the installer is already replacing.
+ quitting = true;
+ return installUpdate();
+});
ipcMain.handle('diagnostics:openLogs', () => shell.openPath(logsDir()));
ipcMain.on('engine:status', (_e, status: string) => console.log('[engine]', status));
@@ -1263,7 +1294,7 @@ 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 checkForUpdate(app.getVersion()).then((release) => {
+ void findUpdate().then((release) => {
if (release && win && !win.isDestroyed()) {
win.webContents.send('app:updateAvailable', release);
}
diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts
index a3806f463..d9c09fee1 100644
--- a/desktop/electron/preload.ts
+++ b/desktop/electron/preload.ts
@@ -11,7 +11,7 @@ import type {
PlatformStatus, CreatePlatformResult, PlayableNetworkOption, ProjectPlatformKind,
} from './platformCatalog';
import type { PlayRealmResult } from './buildPlayRealm';
-import type { LatestRelease } from './updateCheck';
+import type { AvailableUpdate, DownloadProgress } from './autoUpdate';
import type { DiscoveredPlugin, CompiledPlugin } from './pluginHost';
import type { ScaffoldPluginOptions, ScaffoldPluginResult } from './pluginScaffold';
import type { PluginPackageInfo, InstallPluginResult } from './pluginPackage';
@@ -57,13 +57,23 @@ const api = {
});
},
/** Manual update check (Help menu); null = up to date / offline. */
- checkUpdates: (): Promise<LatestRelease | null> => ipcRenderer.invoke('app:checkUpdates'),
+ checkUpdates: (): Promise<AvailableUpdate | null> => ipcRenderer.invoke('app:checkUpdates'),
/** Startup update notification (main checks once after launch); returns an unsubscribe. */
- onUpdateAvailable: (cb: (release: LatestRelease) => void): (() => void) => {
- const h = (_e: unknown, release: LatestRelease) => cb(release);
+ onUpdateAvailable: (cb: (release: AvailableUpdate) => void): (() => void) => {
+ const h = (_e: unknown, release: AvailableUpdate) => cb(release);
ipcRenderer.on('app:updateAvailable', h);
return () => ipcRenderer.removeListener('app:updateAvailable', h);
},
+ /** Download the update the last check found. Only for `selfInstall` updates. */
+ downloadUpdate: (): Promise<void> => ipcRenderer.invoke('app:downloadUpdate'),
+ /** Quit and let the installer take over; false if no download has finished. */
+ installUpdate: (): Promise<boolean> => ipcRenderer.invoke('app:installUpdate'),
+ /** Bytes-so-far for the running download; returns an unsubscribe. */
+ onUpdateProgress: (cb: (p: DownloadProgress) => void): (() => void) => {
+ const h = (_e: unknown, p: DownloadProgress) => cb(p);
+ ipcRenderer.on('app:updateProgress', h);
+ return () => ipcRenderer.removeListener('app:updateProgress', h);
+ },
/** Open the local diagnostics log folder (main-process errors, crash dumps). */
openLogs: (): Promise<void> => ipcRenderer.invoke('diagnostics:openLogs'),
},
diff --git a/desktop/electron/updateCheck.ts b/desktop/electron/updateCheck.ts
index fab1a603b..4f8d8a051 100644
--- a/desktop/electron/updateCheck.ts
+++ b/desktop/electron/updateCheck.ts
@@ -53,6 +53,27 @@ export interface LatestRelease {
url: string;
}
+/**
+ * The same question this file answers, in electron-updater's vocabulary: which
+ * sources to ask, fastest-first. Mirrors publish the channel files under `latest/`
+ * beside the files they name (mirror-release.yml), so a feed is a base and nothing
+ * more — see autoUpdate.ts for who consumes these.
+ *
+ * Differential download is off for mirrors: it asks for several byte ranges in one
+ * request, which object storage behind a CDN answers with the whole file, and
+ * electron-updater fails the block map rather than falling back.
+ */
+export function updateFeeds(env: NodeJS.ProcessEnv = process.env): Array<Record<string, unknown>> {
+ return [
+ ...releaseMirrors(env).map((base) => ({
+ provider: 'generic',
+ url: `${base}/latest`,
+ useMultipleRangeRequest: false,
+ })),
+ { provider: 'github', owner: 'esengine', repo: 'estella' },
+ ];
+}
+
/** Parse "v1.2.3" / "1.2.3" / "v1.2.3-rc.1" → parts + prerelease flag. Null if not a version. */
export function parseVersion(tag: string): { parts: [number, number, number]; pre: string | null } | null {
const m = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(tag.trim());
diff --git a/desktop/package.json b/desktop/package.json
index a50514a1b..c6f7c4d1f 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -68,6 +68,7 @@
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"dockview": "^6.6.1",
+ "electron-updater": "^6.8.9",
"esbuild": "^0.27.0",
"esengine": "workspace:*",
"ffmpeg-static": "^5.3.0",
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx
index 3b5e22226..3fcb252a3 100644
--- a/desktop/src/App.tsx
+++ b/desktop/src/App.tsx
@@ -46,6 +46,7 @@ import { dockApi } from '@/layout/dockApi';
import { forEachEditorWindow } from '@/layout/editorWindows';
import { Toasts } from '@/store/Toasts';
import { t } from '@/i18n';
+import { notifyUpdate } from '@/update/updateToast';
// Commands that fire even while a text field is focused — Save must work mid-edit;
// everything else (typing, native Cmd+Z/backspace) stays with the field.
@@ -163,12 +164,7 @@ export function App() {
useEffect(() => {
const bridge = window.estella?.app;
if (!bridge?.onUpdateAvailable) return;
- return bridge.onUpdateAvailable((release) => {
- Toasts.push(t('toast.updateAvailable', { version: release.version }), 'info', 0, {
- label: t('ui.download'),
- run: () => window.open(release.url),
- });
- });
+ return bridge.onUpdateAvailable(notifyUpdate);
}, []);
const idle = (fn: () => void) =>
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.ts
index bc0d6eeb9..2a61effd0 100644
--- a/desktop/src/commands/editorCommands.ts
+++ b/desktop/src/commands/editorCommands.ts
@@ -33,6 +33,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 type { ToolMode } from '@/types';
const editor = () => useEditorStore.getState();
@@ -582,14 +583,8 @@ commands.register({
label: t('menu.checkUpdates'),
category: t('cat.help'),
run: () => void window.estella?.app?.checkUpdates?.().then((release) => {
- if (release) {
- Toasts.push(t('toast.updateAvailable', { version: release.version }), 'info', 0, {
- label: t('ui.download'),
- run: () => window.open(release.url),
- });
- } else {
- Toasts.push(t('toast.upToDate'), 'success');
- }
+ if (release) notifyUpdate(release);
+ else Toasts.push(t('toast.upToDate'), 'success');
}),
});
commands.register({
diff --git a/desktop/src/i18n/messages/common.ts b/desktop/src/i18n/messages/common.ts
index f7ae29058..d11cd8d8f 100644
--- a/desktop/src/i18n/messages/common.ts
+++ b/desktop/src/i18n/messages/common.ts
@@ -18,6 +18,7 @@ export const commonMessages = defineMessages({
'ui.save': { en: 'Save', zh: '保存' },
'ui.untitled': { en: 'untitled', zh: '未命名' },
'ui.download': { en: 'Download', zh: '下载' },
+ 'ui.restart': { en: 'Restart', zh: '重启' },
'ui.reloadNow': { en: 'Reload now', zh: '立即重新加载' },
'ui.dismiss': { en: 'Dismiss', zh: '关闭' },
'ui.zoomIn': { en: 'Zoom in', zh: '放大' },
diff --git a/desktop/src/i18n/messages/menu.ts b/desktop/src/i18n/messages/menu.ts
index ebb5b0bdd..ff074283e 100644
--- a/desktop/src/i18n/messages/menu.ts
+++ b/desktop/src/i18n/messages/menu.ts
@@ -33,5 +33,14 @@ 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.updateDownloading': {
+ en: 'Downloading Estella {version}… {percent}%',
+ zh: '正在下载 Estella {version}… {percent}%',
+ },
+ 'toast.updateReady': {
+ en: 'Estella {version} is ready — restart to install',
+ zh: 'Estella {version} 已下载完成,重启即可安装',
+ },
+ 'toast.updateFailed': { en: 'Update download failed', zh: '更新下载失败' },
'toast.upToDate': { en: 'Estella is up to date', zh: 'Estella 已是最新版本' },
});
diff --git a/desktop/src/store/Toasts.ts b/desktop/src/store/Toasts.ts
index 722073924..65c134ece 100644
--- a/desktop/src/store/Toasts.ts
+++ b/desktop/src/store/Toasts.ts
@@ -36,6 +36,16 @@ class ToastsImpl {
if (ttl > 0) setTimeout(() => this.dismiss(id), ttl);
return 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
+ * once the toast is gone, so a late report cannot resurrect it.
+ */
+ revise(id: number, patch: Partial<Omit<Toast, 'id'>>): void {
+ const cur = this.store.getState().list;
+ if (!cur.some((t) => t.id === id)) return;
+ this.store.setState({ list: cur.map((t) => (t.id === id ? { ...t, ...patch } : t)) });
+ }
dismiss(id: number): void {
const cur = this.store.getState().list;
const next = cur.filter((t) => t.id !== id);
diff --git a/desktop/src/update/updateToast.ts b/desktop/src/update/updateToast.ts
new file mode 100644
index 000000000..a748b290e
--- /dev/null
+++ b/desktop/src/update/updateToast.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: Apache-2.0
+// 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.
+ *
+ * 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.
+ */
+import { Toasts } from '@/store/Toasts';
+import { t } from '@/i18n';
+
+interface AvailableUpdate {
+ version: string;
+ url: string;
+ selfInstall: boolean;
+}
+
+const pct = (n: number): number => Math.max(0, Math.min(100, Math.round(n)));
+
+/** Post the "there is a newer Estella" toast, wired to whatever this build can do. */
+export function notifyUpdate(release: AvailableUpdate): void {
+ 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);
+ return;
+ }
+
+ let id = 0;
+ id = Toasts.push(t('toast.updateAvailable', { version: release.version }), 'info', 0, {
+ label: t('ui.download'),
+ run: () => void download(id, release),
+ });
+}
+
+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 }),
+ action: undefined,
+ });
+ show(0);
+ const stop = bridge.onUpdateProgress?.((p) => show(pct(p.percent)));
+
+ try {
+ await bridge.downloadUpdate();
+ Toasts.revise(id, {
+ message: t('toast.updateReady', { version: release.version }),
+ kind: 'success',
+ 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, {
+ message: t('toast.updateFailed'),
+ kind: 'error',
+ action: { label: t('ui.download'), run: () => window.open(release.url) },
+ });
+ } finally {
+ stop?.();
+ }
+}
diff --git a/desktop/tests/update-check.test.ts b/desktop/tests/update-check.test.ts
index 413577289..9a16792b8 100644
--- a/desktop/tests/update-check.test.ts
+++ b/desktop/tests/update-check.test.ts
@@ -1,7 +1,8 @@
// 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 } from '../electron/updateCheck';
+import { parseVersion, isNewerVersion, checkForUpdate, downloadKeyFor, updateFeeds } from '../electron/updateCheck';
+import { DEFAULT_RELEASE_MIRROR } from '../../build-tools/utils/nativeTemplate.js';
describe('parseVersion', () => {
it('parses plain and v-prefixed versions', () => {
@@ -149,3 +150,41 @@ describe('checkForUpdate — mirror', () => {
.toBe('https://github.com/x/releases/v0.35.0');
});
});
+
+// — The updater's feed ——————————————————————————————————————————————————————————
+//
+// electron-updater downloads from whichever feed answered the check, so the order
+// here IS the download speed. `latest/` is where mirror-release.yml puts the channel
+// files, beside the files they name.
+
+describe('updateFeeds', () => {
+ it('asks the mirror before the origin', () => {
+ expect(updateFeeds({})).toEqual([
+ { provider: 'generic', url: `${DEFAULT_RELEASE_MIRROR}/latest`, useMultipleRangeRequest: false },
+ { provider: 'github', owner: 'esengine', repo: 'estella' },
+ ]);
+ });
+
+ it('follows the mirror override, in the order it is given', () => {
+ const feeds = updateFeeds({ ESTELLA_RELEASE_MIRROR: 'https://a.test, https://b.test/' });
+ expect(feeds.map((f) => f.url)).toEqual([
+ 'https://a.test/latest',
+ 'https://b.test/latest',
+ undefined, // GitHub is named by owner/repo, not a url
+ ]);
+ });
+
+ it('leaves the origin alone when the mirror is turned off', () => {
+ expect(updateFeeds({ ESTELLA_RELEASE_MIRROR: '' }))
+ .toEqual([{ provider: 'github', owner: 'esengine', repo: 'estella' }]);
+ });
+
+ it('never asks a mirror for several byte ranges at once', () => {
+ // Object storage behind a CDN answers a multi-range request with the whole
+ // file, and electron-updater fails the block map instead of falling back — so
+ // differential download is off wherever the response is a CDN's to shape.
+ for (const feed of updateFeeds({ ESTELLA_RELEASE_MIRROR: 'https://a.test' })) {
+ if (feed.provider === 'generic') expect(feed.useMultipleRangeRequest).toBe(false);
+ }
+ });
+});
diff --git a/desktop/vite.config.ts b/desktop/vite.config.ts
index d338b4dfb..0b99fe36a 100644
--- a/desktop/vite.config.ts
+++ b/desktop/vite.config.ts
@@ -91,7 +91,16 @@ export default defineConfig({
// sibling binaries at runtime (native exe / wasm via import.meta.url /
// module __dirname), so bundling them breaks that — keep them external,
// loaded from disk by the cook.
- vite: { build: { rolldownOptions: { external: ['esbuild', 'ffmpeg-static', /[\\/]build-tools[\\/]basis[\\/]/] } } },
+ // electron-updater is external for a different reason: it resolves its own
+ // package.json and requires its providers by path, and it must stay the
+ // CommonJS package Node's interop knows how to load (see autoUpdate.ts).
+ vite: {
+ build: {
+ rolldownOptions: {
+ external: ['esbuild', 'ffmpeg-static', 'electron-updater', /[\\/]build-tools[\\/]basis[\\/]/],
+ },
+ },
+ },
},
preload: {
input: 'electron/preload.ts',
diff --git a/docs/astro/src/content/docs/getting-started/installation.mdx b/docs/astro/src/content/docs/getting-started/installation.mdx
index 0d34a8d00..bc72d448c 100644
--- a/docs/astro/src/content/docs/getting-started/installation.mdx
+++ b/docs/astro/src/content/docs/getting-started/installation.mdx
@@ -25,9 +25,11 @@ import { Tabs, TabItem, Steps, Aside } from '@astrojs/starlight/components';
</Steps>
<Aside type="tip">
- **Help → Check for Updates…** reads the same mirror (`dl.estella.games`) and
- hands back a download from it, falling back to GitHub when the mirror has no
- answer or a staler one — the origin stays the authority on what exists.
+ **Help → Check for Updates…** downloads the update inside the editor and
+ installs it on restart, from the same mirror (`dl.estella.games`) the
+ installer above comes from, falling back to GitHub when the mirror has no
+ answer or a staler one — the origin stays the authority on what exists. A
+ build that cannot install its own update hands you a link instead.
</Aside>
<Aside type="note">
diff --git a/docs/astro/src/content/docs/zh-cn/getting-started/installation.mdx b/docs/astro/src/content/docs/zh-cn/getting-started/installation.mdx
index 85b772f58..c4d119c72 100644
--- a/docs/astro/src/content/docs/zh-cn/getting-started/installation.mdx
+++ b/docs/astro/src/content/docs/zh-cn/getting-started/installation.mdx
@@ -22,8 +22,9 @@ import { Tabs, TabItem, Steps, Aside } from '@astrojs/starlight/components';
</Steps>
<Aside type="tip">
- **帮助 → 检查更新…** 读的是同一个镜像(`dl.estella.games`),给出的下载链接也
- 指向它;镜像没答案或答案更旧时回落 GitHub —— 「有没有新版本」始终以源站为准。
+ **帮助 → 检查更新…** 会在编辑器内下载更新,并在重启时安装;下载源与上面的安装包
+ 同为镜像(`dl.estella.games`),镜像没答案或答案更旧时回落 GitHub —— 「有没有
+ 新版本」始终以源站为准。无法自行安装更新的版本,则仍旧只给出下载链接。
</Aside>
<Aside type="note">
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 871bb8119..d62ee5fc0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -29,6 +29,9 @@ importers:
dockview:
specifier: ^6.6.1
version: 6.6.1([email protected])
+ electron-updater:
+ specifier: ^6.8.9
+ version: 6.8.9
esbuild:
specifier: ^0.27.0
version: 0.27.7
@@ -1457,6 +1460,9 @@ packages:
resolution: {integrity: sha512-g/2bn8YTavY4cuS5F+jOS7zmZbXXBV8KZ8yHKfJjFPoKtzBqrpCdNPxBd3tqdBwP7BVd0lGzf7Bk2s0KesWZ4Q==}
+ resolution: {integrity: sha512-ZhVxM9iGONUpZGI1FxdMRgJjUFXi7AYGVa5PwKlO1tV1/4zDxQmfKpXOHVztKrd6L9rLcFjERvi1Mf2vxyTkig==}
+
resolution: {integrity: sha512-bO3y10YikuUwUuDUQRM4KfwNkKhnpVO7IPdbsrejwN9/AABJzzTQ4GeHwyzNSrVO+tEH3/Np255a3sVZpZDjvg==}
engines: {node: '>=8.0.0'}
@@ -2026,6 +2032,13 @@ packages:
resolution: {integrity: sha512-++gUqRDEvcnN6Zhqrr+y/CkVEHhlrR96vZn3nZZPYzMcBUyBtTKzB9NadClFIsIVSsu+3i9tfk/erqy9kAmt7Q==}
engines: {node: '>=14'}
+ resolution: {integrity: sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==}
+
+ resolution: {integrity: sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==}
+ deprecated: This package is deprecated. Use require('node:util').isDeepStrictEqual instead.
+
resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==}
@@ -2681,6 +2694,9 @@ packages:
resolution: {integrity: sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA==}
+ resolution: {integrity: sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA==}
+
resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
@@ -4270,6 +4286,19 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ builder-util-runtime: 9.7.0
+ fs-extra: 10.1.0
+ js-yaml: 4.3.0
+ lazy-val: 1.0.5
+ lodash.escaperegexp: 4.1.2
+ lodash.isequal: 4.5.0
+ semver: 7.7.4
+ tiny-typed-emitter: 2.1.0
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@electron/asar': 3.4.1
@@ -4932,6 +4961,10 @@ snapshots:
pkg-types: 2.3.1
quansync: 0.2.11
+
+
@@ -5637,6 +5670,8 @@ snapshots:
dependencies:
semver: 5.7.2
+