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(desktop): the editor survives its crashes — local crash capture, main-process failsafes, update notification

esengine9d87cc650f5d
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index ff726cdfb..6a4ee4ebb 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -30,6 +30,8 @@ import { importAssets, createAsset, IMPORT_EXTENSIONS } from './importAssets';
import { exportGame } from './exportGame';
import { buildPlayRealm } from './buildPlayRealm';
import { syncSdkTypes } from './syncSdkTypes';
+import { installCrashCapture, logsDir } from './resilience';
+import { checkForUpdate } from './updateCheck';
import { resolveScripts } from '../src/project/format';
import type { WorkspaceState } from '../src/project/format';
@@ -359,6 +361,8 @@ ipcMain.on('app:dirty', (_e, dirty: boolean) => { sceneDirty = !!dirty; });
// — 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('diagnostics:openLogs', () => shell.openPath(logsDir()));
ipcMain.on('engine:status', (_e, status: string) => console.log('[engine]', status));
// — Custom window controls (frameless Windows/Linux; macOS uses native traffic lights) —
@@ -670,10 +674,24 @@ async function handleApp(request: Request): Promise<Response> {
}
}
+installCrashCapture();
+
app.whenReady().then(() => {
protocol.handle('estella', handleEstella);
protocol.handle('app', handleApp);
createWindow();
+
+ // Startup update check: silent unless a newer release exists (offline = no-op).
+ // 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) => {
+ if (release && win && !win.isDestroyed()) {
+ win.webContents.send('app:updateAvailable', release);
+ }
+ });
+ }, 5000);
+ }
});
app.on('activate', () => {
diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts
index 1c92a1909..4dc523fdb 100644
--- a/desktop/electron/preload.ts
+++ b/desktop/electron/preload.ts
@@ -8,6 +8,7 @@ import type { ScanAssetsResult } from './assetDb';
import type { CookResult } from './cookAssets';
import type { ExportGameResult } from './exportGame';
import type { PlayRealmResult } from './buildPlayRealm';
+import type { LatestRelease } from './updateCheck';
// The privileged bridge the renderer is allowed to touch. Keep this surface small
// and explicit — anything the editor needs from the OS or Node goes through here.
@@ -48,6 +49,16 @@ const api = {
void Promise.resolve(cb()).finally(() => ipcRenderer.send('app:quitConfirmed'));
});
},
+ /** Manual update check (Help menu); null = up to date / offline. */
+ checkUpdates: (): Promise<LatestRelease | 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);
+ ipcRenderer.on('app:updateAvailable', h);
+ return () => ipcRenderer.removeListener('app:updateAvailable', h);
+ },
+ /** Open the local diagnostics log folder (main-process errors, crash dumps). */
+ openLogs: (): Promise<void> => ipcRenderer.invoke('diagnostics:openLogs'),
},
// — Project / workspace (RC12 §E7) —
diff --git a/desktop/electron/resilience.ts b/desktop/electron/resilience.ts
new file mode 100644
index 000000000..bfbbddd1a
--- /dev/null
+++ b/desktop/electron/resilience.ts
@@ -0,0 +1,96 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file resilience.ts
+ * @brief Crash and error capture for the editor. Local-first: native crash
+ * minidumps and a main-process error log land under userData — no
+ * telemetry, nothing leaves the machine. The editor holds unsaved
+ * user scenes, so a main-process exception must never take the app
+ * down silently: log it, tell the user once, keep running so they
+ * can save.
+ */
+import { app, crashReporter, dialog, shell, BrowserWindow } from 'electron';
+import { appendFileSync, mkdirSync, statSync, renameSync, existsSync } from 'node:fs';
+import path from 'node:path';
+
+const LOG_ROTATE_BYTES = 512 * 1024;
+
+export function logsDir(): string {
+ return path.join(app.getPath('userData'), 'logs');
+}
+
+function errorLogPath(): string {
+ return path.join(logsDir(), 'main-errors.log');
+}
+
+/** Append one structured entry; rotate to `.old` past the cap so the log can't grow unbounded. */
+function logError(kind: string, detail: unknown): void {
+ try {
+ mkdirSync(logsDir(), { recursive: true });
+ const file = errorLogPath();
+ if (existsSync(file) && statSync(file).size > LOG_ROTATE_BYTES) {
+ renameSync(file, file + '.old');
+ }
+ const text = detail instanceof Error ? (detail.stack ?? detail.message) : JSON.stringify(detail);
+ appendFileSync(file, `[${new Date().toISOString()}] ${kind}: ${text}\n`);
+ } catch {
+ // Logging must never become a second crash.
+ }
+ console.error(`[resilience] ${kind}:`, detail);
+}
+
+let shownExceptionDialog = false;
+
+/**
+ * Install crash capture. Call once, before `app.whenReady()` resolves, so the
+ * crash reporter covers every renderer from the start.
+ */
+export function installCrashCapture(): void {
+ // Native crash minidumps (main + renderers + GPU) → userData/Crashpad, local only.
+ crashReporter.start({ uploadToServer: false, compress: true });
+
+ process.on('uncaughtException', (err) => {
+ logError('uncaughtException', err);
+ // One dialog per session: inform, don't storm. Later exceptions still log.
+ if (shownExceptionDialog) return;
+ shownExceptionDialog = true;
+ const win = BrowserWindow.getAllWindows()[0];
+ const opts = {
+ type: 'error' as const,
+ buttons: ['Continue', 'Open Log Folder'],
+ defaultId: 0,
+ message: 'An unexpected error occurred in the editor.',
+ detail:
+ 'The editor is still running — save your work. Details were written to the log folder.\n\n' +
+ String(err?.message ?? err),
+ };
+ const choice = win ? dialog.showMessageBoxSync(win, opts) : dialog.showMessageBoxSync(opts);
+ if (choice === 1) void shell.openPath(logsDir());
+ });
+
+ process.on('unhandledRejection', (reason) => {
+ logError('unhandledRejection', reason);
+ });
+
+ // A dead renderer is a dead editor window — offer to reload it in place.
+ app.on('render-process-gone', (_e, contents, details) => {
+ logError('render-process-gone', details);
+ if (details.reason === 'clean-exit' || details.reason === 'killed') return;
+ const win = BrowserWindow.fromWebContents(contents);
+ if (!win) return;
+ const choice = dialog.showMessageBoxSync(win, {
+ type: 'error',
+ buttons: ['Reload Editor', 'Close'],
+ defaultId: 0,
+ message: 'The editor window crashed.',
+ detail: `Reason: ${details.reason} (exit code ${details.exitCode}). A crash dump was saved locally.`,
+ });
+ if (choice === 0) contents.reload();
+ else win.destroy();
+ });
+
+ // GPU / utility process losses are recoverable noise worth a trace, not a dialog.
+ app.on('child-process-gone', (_e, details) => {
+ if (details.reason !== 'clean-exit') logError('child-process-gone', details);
+ });
+}
diff --git a/desktop/electron/updateCheck.ts b/desktop/electron/updateCheck.ts
new file mode 100644
index 000000000..60cdc07b9
--- /dev/null
+++ b/desktop/electron/updateCheck.ts
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file updateCheck.ts
+ * @brief Release update check against GitHub Releases. Unsigned builds rule
+ * out silent auto-update (Squirrel.Mac requires a valid signature),
+ * so the honest architecture is notify + one-click download: compare
+ * the running version to the latest published release and hand the
+ * renderer a link. Pure logic — `fetch` is injected so tests need no
+ * network and main needs no mock.
+ */
+
+const RELEASES_LATEST = 'https://api.github.com/repos/esengine/estella/releases/latest';
+
+export interface LatestRelease {
+ /** Normalized version, no leading `v` (e.g. "0.18.0"). */
+ version: string;
+ /** Release page URL for the download button. */
+ url: string;
+}
+
+/** 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());
+ if (!m) return null;
+ return { parts: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] ?? null };
+}
+
+/** SemVer precedence: is `candidate` strictly newer than `current`? Prerelease < its release. */
+export function isNewerVersion(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.parts[i] !== b.parts[i]) return a.parts[i] > b.parts[i];
+ }
+ if (a.pre === b.pre) return false;
+ if (a.pre === null) return true; // release > any prerelease of the same triplet
+ if (b.pre === null) return false;
+ return a.pre > b.pre; // lexicographic is enough for rc.1 < rc.2 style tags
+}
+
+/**
+ * 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.
+ */
+export async function checkForUpdate(
+ currentVersion: string,
+ fetchImpl: typeof fetch = fetch,
+): Promise<LatestRelease | null> {
+ try {
+ const res = await fetchImpl(RELEASES_LATEST, {
+ headers: { accept: 'application/vnd.github+json', 'user-agent': 'estella-editor' },
+ });
+ if (!res.ok) return null;
+ 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;
+ 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 };
+ } catch {
+ return null;
+ }
+}
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx
index cf44cd772..6ef736c50 100644
--- a/desktop/src/App.tsx
+++ b/desktop/src/App.tsx
@@ -78,6 +78,18 @@ export function App() {
return unsub;
}, []);
+ // Startup update notification (main checks GitHub Releases once after launch).
+ useEffect(() => {
+ const bridge = window.estella?.app;
+ if (!bridge?.onUpdateAvailable) return;
+ return bridge.onUpdateAvailable((release) => {
+ Toasts.push(`Estella ${release.version} is available`, 'info', 0, {
+ label: 'Download',
+ run: () => window.open(release.url),
+ });
+ });
+ }, []);
+
const idle = (fn: () => void) =>
typeof window.requestIdleCallback === 'function' ? window.requestIdleCallback(fn) : setTimeout(fn, 500);
diff --git a/desktop/src/components/Toaster.tsx b/desktop/src/components/Toaster.tsx
index 2d0090c65..afbd45b1a 100644
--- a/desktop/src/components/Toaster.tsx
+++ b/desktop/src/components/Toaster.tsx
@@ -13,6 +13,18 @@ export function Toaster() {
{toasts.map((t) => (
<div key={t.id} className={`toast toast--${t.kind}`} role="status">
<span className="toast__msg">{t.message}</span>
+ {t.action && (
+ <button
+ type="button"
+ className="toast__action"
+ onClick={() => {
+ t.action?.run();
+ Toasts.dismiss(t.id);
+ }}
+ >
+ {t.action.label}
+ </button>
+ )}
<button
type="button"
className="toast__close"
diff --git a/desktop/src/layout/MenuBar.tsx b/desktop/src/layout/MenuBar.tsx
index 8aacbdd7e..760833c07 100644
--- a/desktop/src/layout/MenuBar.tsx
+++ b/desktop/src/layout/MenuBar.tsx
@@ -161,6 +161,24 @@ export function MenuBar() {
.then((v) => window.alert(`Estella Editor${v ? ' · ' + v : ''}\nA modern editor for the Estella 2D engine.`))
.catch(() => window.alert('Estella Editor')),
},
+ {
+ label: 'Check for Updates…',
+ onClick: () => void window.estella?.app?.checkUpdates?.().then((release) => {
+ if (release) {
+ Toasts.push(`Estella ${release.version} is available`, 'info', 0, {
+ label: 'Download',
+ run: () => window.open(release.url),
+ });
+ } else {
+ Toasts.push('Estella is up to date', 'success');
+ }
+ }),
+ },
+ { sep: true },
+ {
+ label: 'Open Log Folder',
+ onClick: () => void window.estella?.app?.openLogs?.(),
+ },
],
},
];
diff --git a/desktop/src/store/Toasts.ts b/desktop/src/store/Toasts.ts
index 4c1b18012..722073924 100644
--- a/desktop/src/store/Toasts.ts
+++ b/desktop/src/store/Toasts.ts
@@ -10,10 +10,16 @@ import { createStore } from 'zustand/vanilla';
export type ToastKind = 'info' | 'success' | 'warn' | 'error';
+export interface ToastAction {
+ label: string;
+ run: () => void;
+}
+
export interface Toast {
id: number;
kind: ToastKind;
message: string;
+ action?: ToastAction;
}
class ToastsImpl {
@@ -24,9 +30,9 @@ 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): number {
+ push(message: string, kind: ToastKind = 'info', ttl = 3200, action?: ToastAction): number {
const id = ++this.seq;
- this.store.setState((s) => ({ list: [...s.list, { id, kind, message }] }));
+ this.store.setState((s) => ({ list: [...s.list, { id, kind, message, action }] }));
if (ttl > 0) setTimeout(() => this.dismiss(id), ttl);
return id;
}
diff --git a/desktop/src/theme/app.css b/desktop/src/theme/app.css
index 82a4a869b..307193331 100644
--- a/desktop/src/theme/app.css
+++ b/desktop/src/theme/app.css
@@ -2204,6 +2204,18 @@ body.thumb-capture .viewport__play-stop {
.toast__msg {
flex: 1;
}
+.toast__action {
+ flex-shrink: 0;
+ padding: 3px 9px;
+ border: 1px solid var(--line-strong);
+ border-radius: var(--r-xs);
+ color: var(--star);
+ font-size: var(--fs-sm);
+ font-weight: 600;
+}
+.toast__action:hover {
+ background: var(--hover);
+}
.toast__close {
flex-shrink: 0;
display: grid;
diff --git a/desktop/tests/update-check.test.ts b/desktop/tests/update-check.test.ts
new file mode 100644
index 000000000..a9cc15a60
--- /dev/null
+++ b/desktop/tests/update-check.test.ts
@@ -0,0 +1,67 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { parseVersion, isNewerVersion, checkForUpdate } from '../electron/updateCheck';
+
+describe('parseVersion', () => {
+ it('parses plain and v-prefixed versions', () => {
+ expect(parseVersion('0.17.0')).toEqual({ parts: [0, 17, 0], pre: null });
+ expect(parseVersion('v1.2.3')).toEqual({ parts: [1, 2, 3], pre: null });
+ expect(parseVersion('v1.0.0-rc.1')).toEqual({ parts: [1, 0, 0], pre: 'rc.1' });
+ });
+
+ it('rejects non-versions', () => {
+ expect(parseVersion('docs-v0.17.0')).toBeNull();
+ expect(parseVersion('latest')).toBeNull();
+ expect(parseVersion('1.2')).toBeNull();
+ });
+});
+
+describe('isNewerVersion', () => {
+ it('compares major/minor/patch', () => {
+ expect(isNewerVersion('0.18.0', '0.17.0')).toBe(true);
+ expect(isNewerVersion('0.17.1', '0.17.0')).toBe(true);
+ expect(isNewerVersion('1.0.0', '0.99.99')).toBe(true);
+ expect(isNewerVersion('0.17.0', '0.17.0')).toBe(false);
+ expect(isNewerVersion('0.16.9', '0.17.0')).toBe(false);
+ });
+
+ it('ranks a release above its own prereleases', () => {
+ expect(isNewerVersion('1.0.0', '1.0.0-rc.1')).toBe(true);
+ expect(isNewerVersion('1.0.0-rc.1', '1.0.0')).toBe(false);
+ expect(isNewerVersion('1.0.0-rc.2', '1.0.0-rc.1')).toBe(true);
+ });
+
+ it('never reports malformed input as newer', () => {
+ expect(isNewerVersion('garbage', '0.17.0')).toBe(false);
+ expect(isNewerVersion('0.18.0', 'garbage')).toBe(false);
+ });
+});
+
+const fetchReturning = (status: number, body: unknown): typeof fetch =>
+ (async () => ({ ok: status >= 200 && status < 300, status, json: async () => body })) as unknown as typeof fetch;
+
+describe('checkForUpdate', () => {
+ it('returns the release when newer', async () => {
+ const f = fetchReturning(200, { tag_name: 'v0.18.0', html_url: 'https://example.com/r/v0.18.0' });
+ expect(await checkForUpdate('0.17.0', f)).toEqual({ version: '0.18.0', url: 'https://example.com/r/v0.18.0' });
+ });
+
+ it('returns null when up to date or older', async () => {
+ const f = fetchReturning(200, { tag_name: 'v0.17.0', html_url: 'https://example.com' });
+ expect(await checkForUpdate('0.17.0', f)).toBeNull();
+ expect(await checkForUpdate('0.18.0', f)).toBeNull();
+ });
+
+ it('resolves null on API failure, network error, and malformed payloads', async () => {
+ expect(await checkForUpdate('0.17.0', fetchReturning(403, {}))).toBeNull();
+ expect(await checkForUpdate('0.17.0', (async () => { throw new Error('offline'); }) as unknown as typeof fetch)).toBeNull();
+ expect(await checkForUpdate('0.17.0', fetchReturning(200, { tag_name: 'latest' }))).toBeNull();
+ expect(await checkForUpdate('0.17.0', fetchReturning(200, {}))).toBeNull();
+ });
+
+ it('ignores drafts', async () => {
+ const f = fetchReturning(200, { tag_name: 'v9.9.9', html_url: 'https://example.com', draft: true });
+ expect(await checkForUpdate('0.17.0', f)).toBeNull();
+ });
+});