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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(editor): autosave + crash recovery, global error surfaces, no launcher leak
esengine6b774b370e69
diff --git a/desktop/electron/autosave.ts b/desktop/electron/autosave.tsnew file mode 100644index 000000000..559e1b415--- /dev/null+++ b/desktop/electron/autosave.ts@@ -0,0 +1,135 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file autosave.ts+ * @brief Crash-recovery snapshot store under `<root>/.esengine/autosave/`.+ *+ * The renderer periodically serializes every DIRTY editor document (through the+ * same model its real save uses) and hands the bytes here; we mirror each under+ * the autosave dir at the document's own project-relative path. These are+ * snapshots, NOT saves — the document stays dirty. After a crash + the app's+ * render-gone reload, {@link listAutosave} surfaces the snapshots that are newer+ * than their on-disk file so the open prompt can offer to restore them; a normal+ * save (which post-dates the snapshot) makes them non-recoverable.+ */+import { writeFile, mkdir, rm, stat, readdir, cp } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import path from 'node:path';+import { WORKSPACE_DIR } from '../src/project/format';+import { resolveInRoot } from './projectFs';++const AUTOSAVE_SUBDIR = 'autosave';++/** One dirty document's serialized snapshot: its real project-relative path plus+ * the exact bytes a save would have written. */+export interface AutosaveEntry {+ rel: string;+ contents: string;+}++/** A snapshot whose content is unsaved (newer than, or without, its on-disk+ * file) — a crash-recovery candidate. */+export interface RecoverableEntry {+ rel: string;+ snapshotMtimeMs: number;+ /** The on-disk file's mtime, or null when it no longer exists. */+ fileMtimeMs: number | null;+}++const autosaveRoot = (root: string): string => path.join(root, WORKSPACE_DIR, AUTOSAVE_SUBDIR);++/** Forward-slashed, leading-slash-stripped project-relative path. */+function normRel(rel: string): string {+ return rel.replace(/\\/g, '/').replace(/^\/+/, '');+}++/** Absolute path of a real project-relative path's snapshot (sandboxed to root). */+function snapAbs(root: string, rel: string): string {+ return resolveInRoot(root, path.posix.join(WORKSPACE_DIR, AUTOSAVE_SUBDIR, normRel(rel)));+}++async function* walkFiles(absDir: string): AsyncGenerator<string> {+ let entries;+ try {+ entries = await readdir(absDir, { withFileTypes: true });+ } catch {+ return; // no autosave dir yet+ }+ for (const e of entries) {+ const p = path.join(absDir, e.name);+ if (e.isDirectory()) yield* walkFiles(p);+ else yield p;+ }+}++/**+ * Reconcile the autosave dir with the current dirty set: (re)write each entry's+ * snapshot and delete any leftover snapshot NOT in the set — so a document that+ * was saved (hence no longer dirty, hence absent) has its snapshot dropped on the+ * next sync.+ */+export async function syncAutosave(root: string, entries: AutosaveEntry[]): Promise<void> {+ const keep = new Set<string>();+ for (const e of entries) {+ const rel = normRel(e.rel);+ if (!rel) continue;+ keep.add(rel);+ const abs = snapAbs(root, rel);+ await mkdir(path.dirname(abs), { recursive: true });+ await writeFile(abs, e.contents, 'utf8');+ }+ const base = autosaveRoot(root);+ for await (const abs of walkFiles(base)) {+ const rel = path.relative(base, abs).split(path.sep).join('/');+ if (!keep.has(rel)) await rm(abs, { force: true });+ }+}++/**+ * The recoverable snapshots: those newer than their on-disk file, or whose file+ * is gone. A snapshot older-or-equal to its file was superseded by a real save —+ * not a recovery candidate.+ */+export async function listAutosave(root: string): Promise<RecoverableEntry[]> {+ const base = autosaveRoot(root);+ const out: RecoverableEntry[] = [];+ for await (const abs of walkFiles(base)) {+ const rel = path.relative(base, abs).split(path.sep).join('/');+ let snapshotMtimeMs: number;+ try {+ snapshotMtimeMs = (await stat(abs)).mtimeMs;+ } catch {+ continue;+ }+ let fileMtimeMs: number | null = null;+ try {+ fileMtimeMs = (await stat(resolveInRoot(root, rel))).mtimeMs;+ } catch {+ fileMtimeMs = null;+ }+ if (fileMtimeMs === null || snapshotMtimeMs > fileMtimeMs) {+ out.push({ rel, snapshotMtimeMs, fileMtimeMs });+ }+ }+ return out;+}++/** Copy the named snapshots over their real files (recover the unsaved edits),+ * then clear the whole autosave dir — the recovery is consumed. */+export async function restoreAutosave(root: string, rels: string[]): Promise<void> {+ for (const raw of rels) {+ const rel = normRel(raw);+ if (!rel) continue;+ const from = snapAbs(root, rel);+ if (!existsSync(from)) continue;+ const to = resolveInRoot(root, rel);+ await mkdir(path.dirname(to), { recursive: true });+ await cp(from, to);+ }+ await clearAutosave(root);+}++/** Drop every snapshot (discard the recovery, or after everything is saved). */+export async function clearAutosave(root: string): Promise<void> {+ await rm(autosaveRoot(root), { recursive: true, force: true });+}diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 944d357d1..062f0e0be 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -22,6 +22,7 @@ import {resolveInRoot,META_EXT,} from './projectFs';+import { syncAutosave, listAutosave, restoreAutosave, clearAutosave, type AutosaveEntry } from './autosave';import { listRecents, addRecent, removeRecent, listTemplates, createFromTemplate } from './launcher';import { buildProjectScripts } from './buildScripts';import { extractProjectSchemas } from './extractSchemas';@@ -606,6 +607,11 @@ ipcMain.handle('fs:trash', async (_e, relPath: string) => {ipcMain.handle('fs:restoreTrashed', (_e, relPath: string, token: string) =>restoreTrashed(requireRoot(), relPath, token),);+// Crash-recovery snapshots under `.esengine/autosave/` (see electron/autosave.ts).+ipcMain.handle('autosave:sync', (_e, entries: AutosaveEntry[]) => syncAutosave(requireRoot(), entries));+ipcMain.handle('autosave:list', () => listAutosave(requireRoot()));+ipcMain.handle('autosave:restore', (_e, rels: string[]) => restoreAutosave(requireRoot(), rels));+ipcMain.handle('autosave:clear', () => clearAutosave(requireRoot()));// Reveal a file/folder in the OS file manager (Finder / Explorer).ipcMain.handle('shell:showItem', (_e, relPath: string) => {shell.showItemInFolder(resolveInRoot(requireRoot(), relPath));diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.tsindex 6d40d799e..94116bd08 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -156,6 +156,21 @@ const api = {return () => ipcRenderer.removeListener('project:fsChanged', listener);},},+ // Crash-recovery snapshots under `.esengine/autosave/`. The renderer's autosave+ // loop mirrors dirty documents here; on open, `list` surfaces the ones newer+ // than their saved file so the restore prompt can offer them.+ autosave: {+ /** Mirror the current dirty documents into the autosave dir, dropping stale ones. */+ sync: (entries: { rel: string; contents: string }[]): Promise<void> =>+ ipcRenderer.invoke('autosave:sync', entries),+ /** Snapshots newer than (or without) their on-disk file — recovery candidates. */+ list: (): Promise<{ rel: string; snapshotMtimeMs: number; fileMtimeMs: number | null }[]> =>+ ipcRenderer.invoke('autosave:list'),+ /** Copy the named snapshots over their real files, then clear the autosave dir. */+ restore: (rels: string[]): Promise<void> => ipcRenderer.invoke('autosave:restore', rels),+ /** Discard every snapshot. */+ clear: (): Promise<void> => ipcRenderer.invoke('autosave:clear'),+ },// OS shell integration.shell: {/** Reveal a project-relative file/folder in Finder / Explorer. */diff --git a/desktop/src/App.tsx b/desktop/src/App.tsxindex ea4cd944e..4ab6eb695 100644--- a/desktop/src/App.tsx+++ b/desktop/src/App.tsx@@ -37,6 +37,11 @@ import { TimelineRecorder } from '@/timeline/TimelineRecorder';import { ControllerRecorder } from '@/controller/ControllerRecorder';import { ProjectStore } from '@/project/ProjectStore';import { DirtyRegistry } from '@/document/DirtyRegistry';+import { Autosave } from '@/document/Autosave';+import { StatsStore } from '@/engine/StatsStore';+import { PerfMonitor } from '@/engine/PerfMonitor';+import { installGlobalErrorHandlers } from '@/store/errorSurface';+import { ErrorBoundary } from '@/components/ErrorBoundary';import { dockApi } from '@/layout/dockApi';import { forEachEditorWindow } from '@/layout/editorWindows';import { Toasts } from '@/store/Toasts';@@ -115,6 +120,10 @@ export function App() {return () => { unsubMode(); unsubEngine(); };}, []);+ // Route otherwise-silent renderer faults (rejected promises, uncaught errors)+ // into the Output Log + a rate-limited toast — LogStore only patches console.*.+ useEffect(() => installGlobalErrorHandlers(), []);+// Wire the edit-mode live previews (timeline document → World, selected// flipbook → World) and record-mode auto-key once.useEffect(() => {@@ -200,10 +209,17 @@ export function App() {useEffect(() => {if (showLauncher) {// Back on the launcher there is no project — release the primary play- // realm (a warm one still holds the closed project's bundle + wasm).+ // realm (a warm one still holds the closed project's bundle + wasm) and+ // stop the per-frame telemetry loops that would otherwise poll wasm forever+ // (the Viewport that started them has unmounted).PlayRealms.resetPrimary();+ StatsStore.stop();+ PerfMonitor.stop();+ Autosave.stop();return;}+ // A project just opened: run the crash-recovery snapshotter.+ Autosave.start();LoadGate.begin([{ key: 'engine', label: t('load.engine') },{ key: 'playRealm', label: t('load.playRealm') },@@ -222,6 +238,9 @@ export function App() {// attached, so the realm can boot its engine now (no scene, off-screen)..then(() => (cancelled ? undefined : PlayRealms.prewarm())).then(() => { if (!cancelled) LoadGate.done('playRealm'); })+ // Scene is loaded + overlay clearing: offer to restore any autosave newer+ // than its saved file (a prior session crashed with unsaved edits).+ .then(() => { if (!cancelled) void Autosave.recover(); }).finally(() => clearTimeout(safety));return () => { cancelled = true; clearTimeout(safety); LoadGate.close(); };// eslint-disable-next-line react-hooks/exhaustive-deps@@ -230,18 +249,21 @@ export function App() {const settingsOpen = useEditorStore((s) => s.settingsOpen);const tilemapPickerOpen = useEditorStore((s) => s.tilemapPickerOpen);const paletteOpen = useEditorStore((s) => s.paletteOpen);- if (showLauncher) return <Launcher />;+ if (showLauncher) return <ErrorBoundary label="launcher"><Launcher /></ErrorBoundary>;+ // Each chrome region gets its own ErrorBoundary so one throwing region (e.g.+ // the StatusBar consuming live engine data every 333ms) shows a recoverable+ // card instead of white-screening the whole editor.return (<div className="shell">- <Perf id="menubar"><MenuBar /></Perf>- <Perf id="toolbar"><Toolbar /></Perf>+ <ErrorBoundary label="menubar"><Perf id="menubar"><MenuBar /></Perf></ErrorBoundary>+ <ErrorBoundary label="toolbar"><Perf id="toolbar"><Toolbar /></Perf></ErrorBoundary><main className="shell__workspace">- <Perf id="activitybar"><ActivityBar /></Perf>+ <ErrorBoundary label="activitybar"><Perf id="activitybar"><ActivityBar /></Perf></ErrorBoundary><DockLayout /></main>- <Perf id="statusbar"><StatusBar /></Perf>- <Perf id="contentdrawer"><ContentDrawer /></Perf>+ <ErrorBoundary label="statusbar"><Perf id="statusbar"><StatusBar /></Perf></ErrorBoundary>+ <ErrorBoundary label="contentdrawer"><Perf id="contentdrawer"><ContentDrawer /></Perf></ErrorBoundary><PerfRealmBridge />{buildOpen && <BuildDialog />}{settingsOpen && <SettingsDialog />}diff --git a/desktop/src/document/Autosave.ts b/desktop/src/document/Autosave.tsnew file mode 100644index 000000000..a64bb8c4c--- /dev/null+++ b/desktop/src/document/Autosave.ts@@ -0,0 +1,161 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Autosave.ts+ * @brief Periodic crash-recovery snapshotter for the open project.+ *+ * The editor has no periodic save. It DOES have crash minidump + a render-gone+ * reload — but after either, a session's unsaved edits are gone. This service+ * closes that gap: every {@link AUTOSAVE_INTERVAL_MS} it serializes each dirty+ * document (through the DirtyRegistry's snapshot feed — a snapshot never marks a+ * document saved) into `<project>/.esengine/autosave/`. On project open,+ * {@link Autosave.recover} offers to restore any snapshot newer than its saved+ * file. A real save post-dates its snapshot, so it stops being offered.+ */+import { DirtyRegistry, type DocSnapshot } from './DirtyRegistry';+import { useEditorStore } from '@/store/editorStore';+import { confirm } from '@/components/confirm';+import { Toasts } from '@/store/Toasts';+import { t } from '@/i18n';++export const AUTOSAVE_INTERVAL_MS = 60_000;++/** The service's collaborators, injectable so the scheduler is testable without+ * the fs bridge, real timers, or a live DirtyRegistry. */+export interface AutosaveEnv {+ isDirty(): boolean;+ isPlaying(): boolean;+ snapshotDirty(): Promise<DocSnapshot[]>;+ sync(entries: DocSnapshot[]): Promise<void>;+ clear(): Promise<void>;+}++export class AutosaveService {+ private timer: ReturnType<typeof setInterval> | null = null;+ private busy = false;+ private wasDirty = false;++ constructor(+ protected readonly env: AutosaveEnv,+ private readonly intervalMs: number = AUTOSAVE_INTERVAL_MS,+ ) {}++ /**+ * The snapshot gate: unsaved changes AND no Play session. A Play session runs+ * in an isolated realm that never mutates the edit model, so there is nothing+ * new to snapshot while it's active — and we don't want to compete with it.+ */+ shouldSnapshot(): boolean {+ return this.env.isDirty() && !this.env.isPlaying();+ }++ /** One scheduler cycle: snapshot the dirty documents when the gate allows. */+ async tick(): Promise<void> {+ if (this.busy || !this.shouldSnapshot()) return;+ this.busy = true;+ try {+ await this.env.sync(await this.env.snapshotDirty());+ } catch (e) {+ console.warn('[autosave] snapshot failed', e);+ } finally {+ this.busy = false;+ }+ }++ /**+ * React to an aggregate dirty-state change: when everything just became saved,+ * drop the recovery snapshots at once rather than waiting for the next interval+ * to prune them — "clear a document's snapshot after its next real save".+ */+ noteDirtyChanged(): void {+ const dirty = this.env.isDirty();+ if (this.wasDirty && !dirty) void this.env.clear();+ this.wasDirty = dirty;+ }++ start(): void {+ if (this.timer) return;+ this.wasDirty = this.env.isDirty();+ this.timer = setInterval(() => void this.tick(), this.intervalMs);+ }++ stop(): void {+ if (!this.timer) return;+ clearInterval(this.timer);+ this.timer = null;+ }++ get running(): boolean {+ return this.timer !== null;+ }+}++type AutosaveBridge = NonNullable<Window['estella']>['autosave'];++function autosaveBridge(): AutosaveBridge | undefined {+ return (globalThis as { window?: Window }).window?.estella?.autosave;+}++const realEnv: AutosaveEnv = {+ isDirty: () => DirtyRegistry.isDirty(),+ isPlaying: () => useEditorStore.getState().isPlaying,+ snapshotDirty: () => DirtyRegistry.snapshotAll(),+ sync: async (entries) => {+ await autosaveBridge()?.sync(entries.map((e) => ({ rel: e.path, contents: e.contents })));+ },+ clear: async () => {+ await autosaveBridge()?.clear();+ },+};++/** The wired singleton: real env + DirtyRegistry change feed + the open-time+ * recovery prompt. */+class AutosaveWiring extends AutosaveService {+ private unsub: (() => void) | null = null;++ start(): void {+ super.start();+ this.unsub ??= DirtyRegistry.subscribe(() => this.noteDirtyChanged());+ }++ stop(): void {+ super.stop();+ this.unsub?.();+ this.unsub = null;+ }++ /**+ * Offer to recover any snapshot newer than its saved file (a prior session+ * crashed / was reloaded with unsaved edits). Restore copies the snapshots over+ * their real files and reloads the open scene; discard drops them. Runs once+ * per project open, after the shell (hence the confirm host) is mounted.+ */+ async recover(): Promise<'restored' | 'discarded' | 'none'> {+ const bridge = autosaveBridge();+ if (!bridge) return 'none';+ let entries: Awaited<ReturnType<AutosaveBridge['list']>>;+ try {+ entries = await bridge.list();+ } catch {+ return 'none';+ }+ if (entries.length === 0) return 'none';++ const restore = await confirm({+ title: t('autosave.recoverTitle'),+ body: t('autosave.recoverBody', { count: entries.length }),+ confirmLabel: t('autosave.recoverConfirm'),+ });+ if (restore) {+ await bridge.restore(entries.map((e) => e.rel));+ const { ProjectStore } = await import('@/project/ProjectStore');+ await ProjectStore.loadCurrentScene();+ Toasts.push(t('autosave.recovered', { count: entries.length }), 'success');+ return 'restored';+ }+ await bridge.clear();+ return 'discarded';+ }+}++export const Autosave = new AutosaveWiring(realEnv);diff --git a/desktop/src/document/DirtyRegistry.ts b/desktop/src/document/DirtyRegistry.tsindex 26fcf28cb..9e4b681b6 100644--- a/desktop/src/document/DirtyRegistry.ts+++ b/desktop/src/document/DirtyRegistry.ts@@ -13,6 +13,13 @@* while mounted.*/+/** A dirty document's serialized recovery snapshot: its real on-disk target path+ * (project-relative) plus the exact bytes a save would write. */+export interface DocSnapshot {+ path: string;+ contents: string;+}+export interface DirtyDocument {/** Stable id; re-registering the same id replaces the previous entry. */id: string;@@ -21,6 +28,13 @@ export interface DirtyDocument {save(): Promise<void>;/** Change feed, so the aggregate dirty state can push to the quit guard. */subscribe?(fn: () => void): () => void;+ /**+ * Serialize the current model exactly as {@link save} would, WITHOUT persisting+ * or marking the document clean — the autosave source. Returns null when there+ * is nothing to snapshot (e.g. an untitled document with no target path).+ * Documents that omit this simply don't participate in crash recovery.+ */+ snapshot?(): Promise<DocSnapshot | null>;}class DirtyRegistryImpl {@@ -56,6 +70,25 @@ class DirtyRegistryImpl {}}+ /**+ * Snapshot every dirty document that supports it, WITHOUT saving/marking any+ * clean — the autosave feed. A snapshot() that returns null (or throws — a+ * failing one must not abort the others) is skipped; a snapshot is not a save.+ */+ async snapshotAll(): Promise<DocSnapshot[]> {+ const out: DocSnapshot[] = [];+ for (const { doc } of [...this.docs.values()]) {+ if (!doc.isDirty() || !doc.snapshot) continue;+ try {+ const snap = await doc.snapshot();+ if (snap) out.push(snap);+ } catch (e) {+ console.warn(`[autosave] snapshot of "${doc.id}" failed`, e);+ }+ }+ return out;+ }+/** Notify subscribers that some document's dirty state may have changed —* for documents without their own subscribe feed. */bump(): void {diff --git a/desktop/src/document/dirtyDocs.ts b/desktop/src/document/dirtyDocs.tsindex d4e4ee998..15a77b7aa 100644--- a/desktop/src/document/dirtyDocs.ts+++ b/desktop/src/document/dirtyDocs.ts@@ -21,6 +21,7 @@ import { BtDocument } from '@/bt/BtDocument';import { MaterialDocument } from '@/material/MaterialDocument';import { MaterialGraphDocument } from '@/material/MaterialGraphDocument';import { saveMaterialGraph } from '@/material/openMaterialGraph';+import { serializeTileset, serializeAnimClip, serializeTimelineToJson } from 'esengine';import type { AssetDocument } from './AssetDocument';// The scene: EditorHistory-tracked (scene-scoped — doc-tagged asset entries on@@ -36,6 +37,7 @@ DirtyRegistry.register({}},subscribe: EditorHistory.subscribe,+ snapshot: () => ProjectStore.snapshotScene(),});// A JSON-file document whose panel save is a plain pretty-printed write (BT/FSM/@@ -52,6 +54,11 @@ function jsonDoc<T>(id: string, doc: AssetDocument<T>): void {doc.markSaved();},subscribe: doc.subscribe,+ snapshot: async () => {+ const asset = doc.asset;+ const path = doc.filePath;+ return asset == null || !path ? null : { path, contents: JSON.stringify(asset, null, 2) + '\n' };+ },});}@@ -66,19 +73,36 @@ DirtyRegistry.register({isDirty: () => TilesetDocument.dirty,save: () => TilesetCommands.save(),subscribe: TilesetDocument.subscribe,+ snapshot: async () => {+ const a = TilesetDocument.asset;+ const path = TilesetDocument.filePath;+ return a && path ? { path, contents: JSON.stringify(serializeTileset(a), null, 2) + '\n' } : null;+ },});DirtyRegistry.register({id: 'flipbook',isDirty: () => AnimClipDocument.dirty,save: () => AnimClipCommands.save(),subscribe: AnimClipDocument.subscribe,+ snapshot: async () => {+ const a = AnimClipDocument.asset;+ const path = AnimClipDocument.filePath;+ return a && path ? { path, contents: JSON.stringify(serializeAnimClip(a), null, 2) + '\n' } : null;+ },});DirtyRegistry.register({id: 'timeline',isDirty: () => TimelineDocument.dirty && TimelineDocument.filePath != null,save: () => TimelineCommands.save(),subscribe: TimelineDocument.subscribe,+ snapshot: async () => {+ const a = TimelineDocument.asset;+ const path = TimelineDocument.filePath;+ return a && path ? { path, contents: serializeTimelineToJson(a) + '\n' } : null;+ },});+// The material graph's snapshot recovers the graph document only; the compiled+// shader sibling is regenerated by the next real save (saveMaterialGraph).DirtyRegistry.register({id: 'materialgraph',isDirty: () => MaterialGraphDocument.dirty,@@ -88,4 +112,9 @@ DirtyRegistry.register({if (graph && path) await saveMaterialGraph(path, graph);},subscribe: MaterialGraphDocument.subscribe,+ snapshot: async () => {+ const graph = MaterialGraphDocument.asset;+ const path = MaterialGraphDocument.filePath;+ return graph && path ? { path, contents: JSON.stringify(graph, null, 2) + '\n' } : null;+ },});diff --git a/desktop/src/engine/PerfMonitor.ts b/desktop/src/engine/PerfMonitor.tsindex 88bba495e..1eed79147 100644--- a/desktop/src/engine/PerfMonitor.ts+++ b/desktop/src/engine/PerfMonitor.ts@@ -247,6 +247,7 @@ class PerfMonitorImpl {cancelAnimationFrame(this.raf);this.obs?.disconnect();this.obs = null;+ this.last = 0; // a later restart treats the next frame as the first (no stale dt)}setEnabled(on: boolean): void { this.enabled = on; this.patch({ enabled: on }); }diff --git a/desktop/src/engine/StatsStore.ts b/desktop/src/engine/StatsStore.tsindex a0a91e862..cf8eccc7b 100644--- a/desktop/src/engine/StatsStore.ts+++ b/desktop/src/engine/StatsStore.ts@@ -112,6 +112,17 @@ class StatsStoreImpl {requestAnimationFrame(loop);}+ /**+ * Stop the sampling loop (returning to the launcher — otherwise it polls wasm+ * every 333ms forever). Idempotent; {@link start} resumes with a fresh window+ * (a new Viewport mount restarts it).+ */+ stop() {+ this.running = false;+ this.frames = 0;+ this.windowStart = 0;+ }+/** Report the viewport cursor world position (rounded; ignores no-op moves). */setCursor(x: number, y: number) {const cx = Math.round(x);diff --git a/desktop/src/i18n/messages/common.ts b/desktop/src/i18n/messages/common.tsindex 7425ff241..915d183b5 100644--- a/desktop/src/i18n/messages/common.ts+++ b/desktop/src/i18n/messages/common.ts@@ -44,4 +44,16 @@ export const commonMessages = defineMessages({zh: '“{name}”在磁盘上已被修改。重新加载将丢弃未保存的编辑',},'toast.reloadedFromDisk': { en: 'Reloaded {name} from disk', zh: '已从磁盘重新加载 {name}' },++ // — Global error surface (store/errorSurface.ts) —+ 'err.uncaught': { en: 'Unexpected error: {message}', zh: '意外错误:{message}' },++ // — Crash-recovery prompt (document/Autosave.ts) —+ 'autosave.recoverTitle': { en: 'Recover unsaved changes', zh: '恢复未保存的更改' },+ 'autosave.recoverBody': {+ en: 'Found {count} autosaved document(s) newer than their saved files, from a session that ended unexpectedly. Restore them?',+ zh: '发现 {count} 个自动保存的文档比已保存文件更新,来自一次意外结束的会话。要恢复它们吗?',+ },+ 'autosave.recoverConfirm': { en: 'Restore', zh: '恢复' },+ 'autosave.recovered': { en: 'Recovered {count} unsaved document(s)', zh: '已恢复 {count} 个未保存的文档' },});diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 7c9654424..5cdf16ba4 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -29,6 +29,7 @@ import type { AssetType } from '@/types';import { resolveLayout, orientationFromDesignResolution, resolveOrientation, cameraScaleModeValue, WORKSPACE_DIR, PROJECT_MANIFEST_FILE, type OpenedProject, type ProjectFeatures, type ProjectLayout, type ProjectPackaging, type WorkspaceState, type DesignResolution, type ScreenOrientation, type CameraScaleMode } from './format';import { useEditorMode } from '@/store/editorModeStore';import { PlayRealms } from '@/engine/PlayRealm';+import type { DocSnapshot } from '@/document/DirtyRegistry';/** Pad/truncate collision-layer names to the 16 Box2D filter bits (layer 0 = Default). */function normalizeLayers(layers?: string[]): string[] {@@ -1591,6 +1592,17 @@ class ProjectStoreImpl {return { ...model, name: this.state?.name ?? model.name, entities };}+ /**+ * The open scene as a crash-recovery snapshot: its real target path + the exact+ * bytes {@link save} would write, WITHOUT persisting or marking saved. Null for+ * an untitled scene (no `currentScene` path to recover into).+ */+ async snapshotScene(): Promise<DocSnapshot | null> {+ const st = this.state;+ if (!st?.currentScene) return null;+ return { path: st.currentScene, contents: JSON.stringify(await this.serializeCurrent(), null, 2) + '\n' };+ }+private async writeScene(relPath: string, data: SceneData): Promise<void> {const body = JSON.stringify(data, null, 2) + '\n';await window.estella.fs.write(relPath, body);diff --git a/desktop/src/store/errorSurface.ts b/desktop/src/store/errorSurface.tsnew file mode 100644index 000000000..b6376e7a9--- /dev/null+++ b/desktop/src/store/errorSurface.ts@@ -0,0 +1,76 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file errorSurface.ts+ * @brief Route otherwise-silent renderer faults somewhere visible.+ *+ * LogStore only patches `console.*`, so a rejected promise or an uncaught error+ * surfaces nowhere. This registers the window handlers that push them into the+ * Output Log and raise a rate-limited error toast — rate-limited so one promise+ * that rejects every frame can't spam the toast stack.+ */+import { LogStore } from './LogStore';+import { Toasts } from './Toasts';+import { t } from '@/i18n';++/** Emits at most once per key per window; a repeating fault stays quiet until the+ * window elapses. */+export class ErrorRateLimiter {+ private readonly last = new Map<string, number>();++ constructor(+ private readonly windowMs = 5000,+ private readonly now: () => number = () => Date.now(),+ ) {}++ allow(key: string): boolean {+ const t = this.now();+ const prev = this.last.get(key);+ if (prev !== undefined && t - prev < this.windowMs) return false;+ this.last.set(key, t);+ if (this.last.size > 64) {+ for (const [k, v] of this.last) if (t - v >= this.windowMs) this.last.delete(k);+ }+ return true;+ }+}++function reasonMessage(reason: unknown): string {+ if (reason instanceof Error) return reason.stack || reason.message;+ if (typeof reason === 'string') return reason;+ try {+ return JSON.stringify(reason);+ } catch {+ return String(reason);+ }+}++/**+ * Register the global 'unhandledrejection' + 'error' handlers on `target`. Each+ * fault is logged in full to the Output Log and — deduped by the limiter — raises+ * a short error toast. Returns a disposer.+ */+export function installGlobalErrorHandlers(+ target: Window = window,+ limiter: ErrorRateLimiter = new ErrorRateLimiter(),+): () => void {+ const surface = (source: 'unhandledrejection' | 'error', message: string) => {+ LogStore.push('error', source, message);+ if (limiter.allow(message)) {+ Toasts.push(t('err.uncaught', { message: message.split('\n')[0].slice(0, 200) }), 'error');+ }+ };+ const onRejection = (e: PromiseRejectionEvent) => surface('unhandledrejection', reasonMessage(e.reason));+ const onError = (e: ErrorEvent) => {+ // Resource-load errors (a failed <img>/<script>) carry no Error and no useful+ // message and aren't renderer faults — ignore them.+ if (!e.error && !e.message) return;+ surface('error', e.error instanceof Error ? e.error.stack || e.error.message : e.message);+ };+ target.addEventListener('unhandledrejection', onRejection as EventListener);+ target.addEventListener('error', onError as EventListener);+ return () => {+ target.removeEventListener('unhandledrejection', onRejection as EventListener);+ target.removeEventListener('error', onError as EventListener);+ };+}diff --git a/desktop/tests/autosave.test.ts b/desktop/tests/autosave.test.tsnew file mode 100644index 000000000..cd98c7391--- /dev/null+++ b/desktop/tests/autosave.test.ts@@ -0,0 +1,148 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Autosave crash recovery. Two halves: the main-process snapshot store+ * (sync → list → restore/clear roundtrip against a real temp dir, incl.+ * the newer-than-saved recovery rule and stale-snapshot pruning) and the+ * renderer scheduler's decisions (dirty-gate, play-skip, save-clear).+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, utimesSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { syncAutosave, listAutosave, restoreAutosave, clearAutosave } from '../electron/autosave';+import { AutosaveService, type AutosaveEnv } from '@/document/Autosave';+import type { DocSnapshot } from '@/document/DirtyRegistry';++const SCENE = 'assets/scenes/main.esscene';+const snapPath = (root: string, rel: string) => path.join(root, '.esengine', 'autosave', rel);++describe('autosave snapshot store (main process)', () => {+ let root: string;+ beforeEach(() => {+ root = mkdtempSync(path.join(tmpdir(), 'estella-autosave-'));+ });+ afterEach(() => rmSync(root, { recursive: true, force: true }));++ const writeReal = (rel: string, body: string, mtimeMs?: number) => {+ const abs = path.join(root, rel);+ mkdirSync(path.dirname(abs), { recursive: true });+ writeFileSync(abs, body);+ if (mtimeMs !== undefined) utimesSync(abs, new Date(mtimeMs), new Date(mtimeMs));+ };++ it('mirrors a dirty document under .esengine/autosave at its own path', async () => {+ await syncAutosave(root, [{ rel: SCENE, contents: 'DIRTY' }]);+ expect(readFileSync(snapPath(root, SCENE), 'utf8')).toBe('DIRTY');+ });++ it('lists a snapshot newer than its saved file as recoverable', async () => {+ writeReal(SCENE, 'SAVED', Date.now() - 60_000); // the on-disk file is older+ await syncAutosave(root, [{ rel: SCENE, contents: 'DIRTY' }]);+ const recoverable = await listAutosave(root);+ expect(recoverable.map((r) => r.rel)).toEqual([SCENE]);+ expect(recoverable[0].fileMtimeMs).not.toBeNull();+ });++ it('lists a snapshot whose saved file is gone as recoverable', async () => {+ await syncAutosave(root, [{ rel: SCENE, contents: 'DIRTY' }]);+ const recoverable = await listAutosave(root);+ expect(recoverable[0].rel).toBe(SCENE);+ expect(recoverable[0].fileMtimeMs).toBeNull();+ });++ it('does NOT list a snapshot that a later save superseded', async () => {+ await syncAutosave(root, [{ rel: SCENE, contents: 'DIRTY' }]);+ writeReal(SCENE, 'SAVED', Date.now() + 60_000); // saved after the snapshot+ expect(await listAutosave(root)).toEqual([]);+ });++ it('restore copies the snapshot over its real file, then clears the dir', async () => {+ writeReal(SCENE, 'SAVED', Date.now() - 60_000);+ await syncAutosave(root, [{ rel: SCENE, contents: 'RECOVERED' }]);+ await restoreAutosave(root, [SCENE]);+ expect(readFileSync(path.join(root, SCENE), 'utf8')).toBe('RECOVERED');+ expect(existsSync(path.join(root, '.esengine', 'autosave'))).toBe(false);+ });++ it('sync prunes a snapshot no longer in the dirty set (document saved)', async () => {+ await syncAutosave(root, [+ { rel: 'a.esscene', contents: 'A' },+ { rel: 'b.esscene', contents: 'B' },+ ]);+ expect(existsSync(snapPath(root, 'b.esscene'))).toBe(true);+ await syncAutosave(root, [{ rel: 'a.esscene', contents: 'A' }]); // b saved → absent+ expect(existsSync(snapPath(root, 'a.esscene'))).toBe(true);+ expect(existsSync(snapPath(root, 'b.esscene'))).toBe(false);+ });++ it('clear drops every snapshot and list is empty', async () => {+ await syncAutosave(root, [{ rel: SCENE, contents: 'DIRTY' }]);+ await clearAutosave(root);+ expect(await listAutosave(root)).toEqual([]);+ });+});++describe('AutosaveService scheduler (renderer)', () => {+ const snap: DocSnapshot[] = [{ path: SCENE, contents: 'DIRTY' }];+ const env = (over: Partial<AutosaveEnv>): AutosaveEnv & { sync: ReturnType<typeof vi.fn>; clear: ReturnType<typeof vi.fn> } => ({+ isDirty: () => true,+ isPlaying: () => false,+ snapshotDirty: vi.fn(async () => snap),+ sync: vi.fn(async () => {}),+ clear: vi.fn(async () => {}),+ ...over,+ });++ it('gates snapshotting on dirty AND not playing', () => {+ expect(new AutosaveService(env({})).shouldSnapshot()).toBe(true);+ expect(new AutosaveService(env({ isDirty: () => false })).shouldSnapshot()).toBe(false);+ expect(new AutosaveService(env({ isPlaying: () => true })).shouldSnapshot()).toBe(false);+ });++ it('tick snapshots the dirty documents when the gate is open', async () => {+ const e = env({});+ await new AutosaveService(e).tick();+ expect(e.snapshotDirty).toHaveBeenCalledTimes(1);+ expect(e.sync).toHaveBeenCalledWith(snap);+ });++ it('tick is a no-op while a Play session is active', async () => {+ const e = env({ isPlaying: () => true });+ await new AutosaveService(e).tick();+ expect(e.sync).not.toHaveBeenCalled();+ });++ it('tick is a no-op when nothing is dirty', async () => {+ const e = env({ isDirty: () => false });+ await new AutosaveService(e).tick();+ expect(e.sync).not.toHaveBeenCalled();+ });++ it('clears snapshots when the project just became fully saved', () => {+ let dirty = true;+ const e = env({ isDirty: () => dirty });+ const svc = new AutosaveService(e);+ svc.noteDirtyChanged(); // still dirty+ expect(e.clear).not.toHaveBeenCalled();+ dirty = false;+ svc.noteDirtyChanged(); // dirty → clean transition+ expect(e.clear).toHaveBeenCalledTimes(1);+ });++ it('start runs the interval and stop halts it', async () => {+ vi.useFakeTimers();+ try {+ const e = env({});+ const svc = new AutosaveService(e, 1000);+ svc.start();+ await vi.advanceTimersByTimeAsync(1000);+ expect(e.sync).toHaveBeenCalledTimes(1);+ svc.stop();+ await vi.advanceTimersByTimeAsync(5000);+ expect(e.sync).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/desktop/tests/error-surface.test.ts b/desktop/tests/error-surface.test.tsnew file mode 100644index 000000000..0f97940b8--- /dev/null+++ b/desktop/tests/error-surface.test.ts@@ -0,0 +1,73 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Global error surface: the rate limiter's dedupe window, and that the+ * window handlers route a rejected promise / uncaught error into the+ * Output Log every time while raising at most one toast per window.+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { ErrorRateLimiter, installGlobalErrorHandlers } from '@/store/errorSurface';+import { LogStore } from '@/store/LogStore';+import { Toasts } from '@/store/Toasts';++describe('ErrorRateLimiter', () => {+ it('allows once, then suppresses repeats until the window elapses', () => {+ let now = 0;+ const limiter = new ErrorRateLimiter(5000, () => now);+ expect(limiter.allow('a')).toBe(true);+ expect(limiter.allow('a')).toBe(false);+ expect(limiter.allow('b')).toBe(true); // a different key is independent+ now = 5000;+ expect(limiter.allow('a')).toBe(true); // window elapsed+ });+});++describe('installGlobalErrorHandlers', () => {+ const listeners = new Map<string, EventListener>();+ const target = {+ addEventListener: (type: string, fn: EventListener) => listeners.set(type, fn),+ removeEventListener: (type: string) => listeners.delete(type),+ } as unknown as Window;++ let dispose: () => void;+ let now: number;++ beforeEach(() => {+ now = 0;+ LogStore.clear();+ dispose = installGlobalErrorHandlers(target, new ErrorRateLimiter(5000, () => now));+ });+ afterEach(() => {+ dispose();+ for (const t of Toasts.getSnapshot()) Toasts.dismiss(t.id);+ LogStore.clear();+ });++ it('routes an unhandled rejection into the Output Log and one toast', () => {+ listeners.get('unhandledrejection')!({ reason: 'boom' } as unknown as Event);+ expect(LogStore.getSnapshot().some((e) => e.level === 'error' && e.message.includes('boom'))).toBe(true);+ expect(Toasts.getSnapshot()).toHaveLength(1);+ });++ it('logs every repeat but suppresses the duplicate toast within the window', () => {+ const fire = () => listeners.get('unhandledrejection')!({ reason: 'boom' } as unknown as Event);+ fire();+ fire();+ fire();+ expect(LogStore.getSnapshot().filter((e) => e.message.includes('boom'))).toHaveLength(3);+ expect(Toasts.getSnapshot()).toHaveLength(1); // deduped++ now = 6000; // past the window+ fire();+ expect(Toasts.getSnapshot()).toHaveLength(2);+ });++ it('routes an uncaught error but ignores a resource-load error (no message)', () => {+ listeners.get('error')!({ message: 'render blew up', error: new Error('render blew up') } as unknown as Event);+ expect(LogStore.getSnapshot().some((e) => e.message.includes('render blew up'))).toBe(true);++ const before = LogStore.getSnapshot().length;+ listeners.get('error')!({ message: '', error: null } as unknown as Event); // resource error+ expect(LogStore.getSnapshot().length).toBe(before);+ });+});diff --git a/desktop/tests/telemetry-stop.test.ts b/desktop/tests/telemetry-stop.test.tsnew file mode 100644index 000000000..672027fb8--- /dev/null+++ b/desktop/tests/telemetry-stop.test.ts@@ -0,0 +1,57 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Telemetry loops stop on project close. Returning to the launcher must+ * halt StatsStore's 333ms sampling loop and PerfMonitor's rAF/longtask+ * observers — otherwise they poll wasm forever after the Viewport that+ * started them has unmounted.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { StatsStore } from '@/engine/StatsStore';+import { PerfMonitor } from '@/engine/PerfMonitor';++let rafCbs: FrameRequestCallback[];++beforeEach(() => {+ rafCbs = [];+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => rafCbs.push(cb));+ vi.stubGlobal('cancelAnimationFrame', vi.fn());+});+afterEach(() => {+ StatsStore.stop();+ PerfMonitor.stop();+ vi.unstubAllGlobals();+});++describe('StatsStore.stop', () => {+ it('halts the sampling loop so it stops rescheduling', () => {+ StatsStore.start();+ expect(rafCbs).toHaveLength(1);+ rafCbs[rafCbs.length - 1](1000); // running → reschedules+ expect(rafCbs).toHaveLength(2);++ StatsStore.stop();+ rafCbs[rafCbs.length - 1](1333); // stopped → must not reschedule+ expect(rafCbs).toHaveLength(2);+ });++ it('restarts cleanly after a stop (a new Viewport mount)', () => {+ StatsStore.start();+ StatsStore.stop();+ StatsStore.start();+ expect(rafCbs.length).toBeGreaterThan(0);+ });+});++describe('PerfMonitor.stop', () => {+ it('cancels the rAF loop and stops rescheduling', () => {+ PerfMonitor.start();+ expect(rafCbs).toHaveLength(1);+ PerfMonitor.stop();+ expect(cancelAnimationFrame).toHaveBeenCalled();++ const before = rafCbs.length;+ rafCbs[rafCbs.length - 1](16); // stopped → must not reschedule+ expect(rafCbs).toHaveLength(before);+ });+});