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
fix(editor): Play always runs current code, closing loses no document, gestures undo in one step
esenginefec47e4182e4
diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 55ec8badd..cbbb47d7a 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -430,36 +430,37 @@ function createWindow() {if (shotOut) void runScreenshot(win, shotOut);if (mcpMode()) void startMcpEndpoint(() => win);- // Unsaved-changes quit guard: prompt before closing a window with a dirty scene.- // `sceneDirty` is pushed from the renderer (app:dirty); `quitting` lets the chosen- // action close past this handler.+ // Unsaved-changes quit guard: prompt before closing a window with dirty+ // 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 || !sceneDirty || !win) return;+ if (process.env.ESTELLA_SHOT || quitting || !editorDirty || !win) return;e.preventDefault();const choice = dialog.showMessageBoxSync(win, {type: 'warning',- buttons: ['Save', "Don't Save", 'Cancel'],+ buttons: ['Save All', "Don't Save", 'Cancel'],defaultId: 0,cancelId: 2,message: 'Save changes before closing?',- detail: 'Your scene has unsaved changes that will be lost otherwise.',+ detail: 'The scene or an open asset editor has unsaved changes that will be lost otherwise.',});if (choice === 2) return; // Cancel → keep the window openif (choice === 1) { quitting = true; win.destroy(); return; } // Don't Save- // Save → ask the renderer to write the scene, then close when it confirms.+ // 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');});}-// The renderer's current unsaved-changes state, mirrored for the close guard above.-let sceneDirty = false;+// The renderer's current unsaved-changes state (the DirtyRegistry aggregate:+// scene + asset editors), mirrored for the close guard above.+let editorDirty = false;// Set once the user has chosen to close (Save/Don't Save), so win.destroy() is allowed through.let quitting = false;-ipcMain.on('app:dirty', (_e, dirty: boolean) => { sceneDirty = !!dirty; });+ipcMain.on('app:dirty', (_e, dirty: boolean) => { editorDirty = !!dirty; });// — Minimal IPC surface (expanded as the editor grows) —ipcMain.handle('app:version', () => app.getVersion());diff --git a/desktop/src/App.tsx b/desktop/src/App.tsxindex f7d7006a4..470e998b1 100644--- a/desktop/src/App.tsx+++ b/desktop/src/App.tsx@@ -8,6 +8,7 @@ import { DockLayout } from '@/layout/DockLayout';import { ActivityBar } from '@/layout/ActivityBar';import { ContentDrawer } from '@/layout/ContentDrawer';import '@/engine/EditorSession'; // side effect: constructs defaultSession → wires the editor engine+import '@/document/dirtyDocs'; // side effect: registers scene + asset docs on the DirtyRegistryimport { Launcher } from '@/launcher/Launcher';import { Toaster } from '@/components/Toaster';import { ConfirmHost } from '@/components/ConfirmHost';@@ -34,7 +35,7 @@ import { FlipbookViewportPreview } from '@/engine/FlipbookViewportPreview';import { TimelineRecorder } from '@/timeline/TimelineRecorder';import { ControllerRecorder } from '@/controller/ControllerRecorder';import { ProjectStore } from '@/project/ProjectStore';-import { EditorHistory } from '@/engine/EditorHistory';+import { DirtyRegistry } from '@/document/DirtyRegistry';import { dockApi } from '@/layout/dockApi';import { forEachEditorWindow } from '@/layout/editorWindows';import { Toasts } from '@/store/Toasts';@@ -123,20 +124,16 @@ export function App() {}, []);// Mirror unsaved-changes state to main for the window-close quit guard, and run- // the save when main requests a save-before-quit.+ // the save when main requests a save-before-quit. Both speak the DirtyRegistry+ // aggregate, so a dirty tileset/flipbook/graph editor prompts and saves like a+ // dirty scene (not just EditorHistory).useEffect(() => {const bridge = window.estella?.app;if (!bridge) return;- const push = () => bridge.setDirty(EditorHistory.isDirty());+ const push = () => bridge.setDirty(DirtyRegistry.isDirty());push();- const unsub = EditorHistory.subscribe(push);- bridge.onSaveBeforeQuit(async () => {- try {- await ProjectStore.save();- } catch {- await ProjectStore.saveAsViaDialog();- }- });+ const unsub = DirtyRegistry.subscribe(push);+ bridge.onSaveBeforeQuit(() => DirtyRegistry.saveAll());return unsub;}, []);@@ -200,7 +197,12 @@ export function App() {// the editor and the FIRST Play are both smooth. Everything heavy is warmed up// front; the overlay clears when every task is done.useEffect(() => {- if (showLauncher) return;+ 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).+ PlayRealms.resetPrimary();+ return;+ }LoadGate.begin([{ key: 'engine', label: t('load.engine') },{ key: 'playRealm', label: t('load.playRealm') },diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.tsindex a941d6d59..d273e57fd 100644--- a/desktop/src/commands/editorCommands.ts+++ b/desktop/src/commands/editorCommands.ts@@ -48,7 +48,10 @@ commands.register({label: t('cmd.project.open'),category: t('cat.file'),keybinding: 'mod+o',- run: () => void ProjectStore.openViaDialog().then((ok) => ok && sel().select(null)),+ run: async () => {+ if (!(await confirmDiscard(t('discard.openProject')))) return;+ void ProjectStore.openViaDialog().then((ok) => ok && sel().select(null));+ },});commands.register({id: 'project.save',@@ -140,12 +143,10 @@ commands.register({label: t('cmd.entity.duplicate'),category: t('cat.entity'),keybinding: 'mod+d',- isEnabled: () => sel().selectedId != null,+ isEnabled: () => sel().selectedIds.size > 0,run: () => {- const id = sel().selectedId;- if (id == null) return;- const dup = SceneCommands.duplicateEntity(id);- if (dup != null) sel().select(dup);+ const dups = SceneCommands.duplicateEntities([...sel().selectedIds]);+ if (dups.length > 0) sel().selectMany(dups, dups[dups.length - 1]);},});commands.register({@@ -155,7 +156,7 @@ commands.register({keybinding: ['delete', 'backspace'],isEnabled: () => sel().selectedIds.size > 0,// Despawn self-heals the selection (SelectionStore) — no manual deselect.- run: () => [...sel().selectedIds].forEach((id) => SceneCommands.deleteEntity(id)),+ run: () => SceneCommands.deleteEntities([...sel().selectedIds]),});commands.register({id: 'entity.copy',diff --git a/desktop/src/document/DirtyRegistry.ts b/desktop/src/document/DirtyRegistry.tsnew file mode 100644index 000000000..26fcf28cb--- /dev/null+++ b/desktop/src/document/DirtyRegistry.ts@@ -0,0 +1,80 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file DirtyRegistry.ts+ * @brief Aggregate unsaved-changes surface over every open editor document.+ *+ * The scene tracks dirty via EditorHistory; each AssetDocument editor (tileset,+ * flipbook, FSM, BT, material graph, …) tracks its own private `_dirty`. The+ * quit guard, the discard guard, and quit-save must see ALL of them, so each+ * document registers a {isDirty, save} pair here and the guards ask the+ * registry instead of one document. Built-in documents register in+ * `dirtyDocs.ts`; transient editors (the .meta importer inspector) register+ * while mounted.+ */++export interface DirtyDocument {+ /** Stable id; re-registering the same id replaces the previous entry. */+ id: string;+ isDirty(): boolean;+ /** Persist the document. Called on quit-save only when {@link isDirty}. */+ save(): Promise<void>;+ /** Change feed, so the aggregate dirty state can push to the quit guard. */+ subscribe?(fn: () => void): () => void;+}++class DirtyRegistryImpl {+ private readonly docs = new Map<string, { doc: DirtyDocument; unsub: (() => void) | null }>();+ private readonly listeners = new Set<() => void>();++ /** Register a document; returns its unregister. */+ register(doc: DirtyDocument): () => void {+ this.docs.get(doc.id)?.unsub?.();+ const unsub = doc.subscribe?.(() => this.bump()) ?? null;+ this.docs.set(doc.id, { doc, unsub });+ this.bump();+ return () => {+ const cur = this.docs.get(doc.id);+ if (cur?.doc !== doc) return; // replaced meanwhile — the newer entry owns the id+ cur.unsub?.();+ this.docs.delete(doc.id);+ this.bump();+ };+ }++ /** True when ANY registered document has unsaved changes. */+ isDirty(): boolean {+ for (const { doc } of this.docs.values()) if (doc.isDirty()) return true;+ return false;+ }++ /** Save every dirty document (sequentially; a failure aborts and rethrows so+ * the caller never reports a clean quit over lost edits). */+ async saveAll(): Promise<void> {+ for (const { doc } of [...this.docs.values()]) {+ if (doc.isDirty()) await doc.save();+ }+ }++ /** Notify subscribers that some document's dirty state may have changed —+ * for documents without their own subscribe feed. */+ bump(): void {+ for (const fn of [...this.listeners]) fn();+ }++ subscribe(fn: () => void): () => void {+ this.listeners.add(fn);+ return () => {+ this.listeners.delete(fn);+ };+ }++ /** @internal Test hook — drop every registration. */+ clearAll(): void {+ for (const { unsub } of this.docs.values()) unsub?.();+ this.docs.clear();+ this.bump();+ }+}++export const DirtyRegistry = new DirtyRegistryImpl();diff --git a/desktop/src/document/dirtyDocs.ts b/desktop/src/document/dirtyDocs.tsnew file mode 100644index 000000000..920665c43--- /dev/null+++ b/desktop/src/document/dirtyDocs.ts@@ -0,0 +1,91 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file dirtyDocs.ts+ * @brief Registers the built-in documents on the DirtyRegistry (side effect+ * on import, like EditorSession): the scene plus every AssetDocument+ * editor. Quit-save and the discard/close guards then see one+ * aggregate dirty state instead of only the scene's.+ */+import { DirtyRegistry } from './DirtyRegistry';+import { EditorHistory } from '@/engine/EditorHistory';+import { ProjectStore } from '@/project/ProjectStore';+import { TilesetDocument } from '@/tileset/TilesetDocument';+import { TilesetCommands } from '@/tileset/TilesetCommands';+import { AnimClipDocument } from '@/flipbook/AnimClipDocument';+import { AnimClipCommands } from '@/flipbook/AnimClipCommands';+import { TimelineDocument } from '@/timeline/TimelineDocument';+import { TimelineCommands } from '@/timeline/TimelineCommands';+import { FsmGraphDocument } from '@/fsm/FsmGraphDocument';+import { BtDocument } from '@/bt/BtDocument';+import { MaterialDocument } from '@/material/MaterialDocument';+import { MaterialGraphDocument } from '@/material/MaterialGraphDocument';+import { saveMaterialGraph } from '@/material/openMaterialGraph';+import type { AssetDocument } from './AssetDocument';++// The scene: EditorHistory-tracked (asset-doc edits record there too, so this can+// over-report — a redundant scene save is harmless; a missed one is not).+DirtyRegistry.register({+ id: 'scene',+ isDirty: () => EditorHistory.isDirty(),+ save: async () => {+ try {+ await ProjectStore.save();+ } catch {+ await ProjectStore.saveAsViaDialog();+ }+ },+ subscribe: EditorHistory.subscribe,+});++// A JSON-file document whose panel save is a plain pretty-printed write (BT/FSM/+// material — mirrors the panels' own save buttons).+function jsonDoc<T>(id: string, doc: AssetDocument<T>): void {+ DirtyRegistry.register({+ id,+ isDirty: () => doc.dirty,+ save: async () => {+ const asset = doc.asset;+ const path = doc.filePath;+ if (asset == null || !path) return;+ await window.estella.fs.write(path, JSON.stringify(asset, null, 2) + '\n');+ doc.markSaved();+ },+ subscribe: doc.subscribe,+ });+}++jsonDoc('bt', BtDocument);+jsonDoc('fsm', FsmGraphDocument);+jsonDoc('material', MaterialDocument);++// Documents with a richer save (custom serializer / compiled sibling output)+// reuse the same save path their panels call.+DirtyRegistry.register({+ id: 'tileset',+ isDirty: () => TilesetDocument.dirty,+ save: () => TilesetCommands.save(),+ subscribe: TilesetDocument.subscribe,+});+DirtyRegistry.register({+ id: 'flipbook',+ isDirty: () => AnimClipDocument.dirty,+ save: () => AnimClipCommands.save(),+ subscribe: AnimClipDocument.subscribe,+});+DirtyRegistry.register({+ id: 'timeline',+ isDirty: () => TimelineDocument.dirty && TimelineDocument.filePath != null,+ save: () => TimelineCommands.save(),+ subscribe: TimelineDocument.subscribe,+});+DirtyRegistry.register({+ id: 'materialgraph',+ isDirty: () => MaterialGraphDocument.dirty,+ save: async () => {+ const graph = MaterialGraphDocument.asset;+ const path = MaterialGraphDocument.filePath;+ if (graph && path) await saveMaterialGraph(path, graph);+ },+ subscribe: MaterialGraphDocument.subscribe,+});diff --git a/desktop/src/engine/EditorHistory.ts b/desktop/src/engine/EditorHistory.tsindex f017a7270..ed7316007 100644--- a/desktop/src/engine/EditorHistory.ts+++ b/desktop/src/engine/EditorHistory.ts@@ -38,8 +38,16 @@ export class EditorHistoryImpl {this.redoIds.length = 0;}+ // While a group is open, record/run/batch append here instead of committing —+ // the whole gesture lands as ONE transaction when the group closes.+ private groupOps: Array<{ forward: () => void; reverse: () => void }> | null = null;+/** Register an already-applied mutation as one undo step (forward NOT run). */record(label: string, forward: () => void, reverse: () => void) {+ if (this.groupOps) {+ this.groupOps.push({ forward, reverse });+ return;+ }const tx = this.tm.begin(label);tx.addDeferred({ forward, reverse });this.tm.commit(tx);@@ -49,6 +57,11 @@ export class EditorHistoryImpl {/** Apply a not-yet-applied mutation and record it (forward runs now). */run(label: string, forward: () => void, reverse: () => void) {+ if (this.groupOps) {+ forward();+ this.groupOps.push({ forward, reverse });+ return;+ }const tx = this.tm.begin(label);tx.add({ forward, reverse });this.tm.commit(tx);@@ -59,6 +72,10 @@ export class EditorHistoryImpl {/** Register several already-applied mutations as ONE undo step (e.g. a* multi-selection add/remove). No-op on an empty op list. */batch(label: string, ops: ReadonlyArray<{ forward: () => void; reverse: () => void }>) {+ if (this.groupOps) {+ this.groupOps.push(...ops);+ return;+ }if (ops.length === 0) return;const tx = this.tm.begin(label);for (const op of ops) tx.addDeferred(op);@@ -67,6 +84,24 @@ export class EditorHistoryImpl {this.bump();}+ /**+ * Run `fn` and collapse every step it records into ONE undo step labeled+ * `label` — the door for multi-selection gestures (delete/duplicate/reparent+ * the whole selection) built from per-entity commands that each record.+ * A nested group folds into the outer one (the outer gesture owns the step).+ */+ group<T>(label: string, fn: () => T): T {+ if (this.groupOps) return fn();+ const ops: Array<{ forward: () => void; reverse: () => void }> = [];+ this.groupOps = ops;+ try {+ return fn();+ } finally {+ this.groupOps = null;+ this.batch(label, ops);+ }+ }+undo() {if (this.tm.undo()) {const id = this.undoIds.pop();diff --git a/desktop/src/engine/PlayInspect.ts b/desktop/src/engine/PlayInspect.tsindex 06fd8a994..d0aeeb8c9 100644--- a/desktop/src/engine/PlayInspect.ts+++ b/desktop/src/engine/PlayInspect.ts@@ -8,11 +8,12 @@* from this snapshot (reusing buildSceneTree/buildInspector) when in Game* mode; field edits route to PlayRealm.setField (live, reverts on Stop).*- * Sampling is a COALESCED loop, not a fixed-interval poll: one request is in- * flight at a time and the next is armed only after the reply, with a small- * floor between starts. So the Details tracks live values smoothly on a- * small scene (request returns fast → ~floor rate) and a large one self-- * throttles to its serialize cost instead of backing up requests.+ * Sampling is a COALESCED loop, not a fixed-interval poll: one request is+ * in flight at a time and the next is armed only after the reply. It runs+ * ONLY while a game-mode panel is actually subscribed (the GameTree /+ * GameDetails views mount only in Game mode), and at split rates: the+ * O(entities) tree at ~7Hz, the selected entity's full data at ~30Hz+ * (detail-only samples skip the realm's tree walk entirely).** Selection here is a REALM runtime id — distinct from the editor's* source-id selection (selectionStore), never mixed.@@ -30,10 +31,12 @@ interface PlayInspectState {selection: EntityId | null;}-/** Minimum gap between sample starts (ms) — a ~60fps cap (no point sampling faster- * than the realm renders). The realm sample is cheap (it decodes data only for the- * selected entity), and coalescing still self-throttles if a sample ever runs long. */-const MIN_GAP_MS = 16;+/** Minimum gap between STRUCTURAL tree samples (ms) — the Outliner doesn't need+ * more than ~7Hz, and the tree serialize is the O(entities) part. */+const TREE_GAP_MS = 150;+/** Minimum gap between selected-entity samples (ms, ~30Hz) — the Details tracks+ * live values smoothly; the realm decodes data only for that one entity. */+const DETAIL_GAP_MS = 33;/** A cheap structural signature of the shallow tree (ids / parent / name / component* types) — drives keeping the tree reference stable when only values changed. */@@ -45,8 +48,27 @@ class PlayInspectImpl {private readonly store = createStore<PlayInspectState>(() => ({ snapshot: null, selectedEntity: null, selection: null }));private active = false;private timer: ReturnType<typeof setTimeout> | null = null;+ // Consumers of the live snapshot (the game-mode Outliner/Details views). Zero+ // subscribers = nobody is looking = don't sample the realm at all.+ private subscribers = 0;+ // One loop at a time: `scheduled` covers a queued-or-in-flight tick; `epoch`+ // invalidates an in-flight tick across stop()/start() so it can't double-arm.+ private scheduled = false;+ private loopEpoch = 0;+ private lastTreeAt = 0;+ // Signature of the CURRENT tree snapshot — computed once when a tree arrives,+ // cached so a new sample hashes only itself (not the old tree again).+ private curTreeSig = '';- subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);+ subscribe = (fn: () => void): (() => void) => {+ const unsub = this.store.subscribe(fn);+ this.subscribers++;+ this.arm();+ return () => {+ this.subscribers--;+ unsub();+ };+ };getSnapshot = (): PlayInspectState => this.store.getState();/** Identity-stable slices so Details-only ticks don't re-render the Outliner. */getTree = (): SceneData | null => this.store.getState().snapshot;@@ -54,55 +76,83 @@ class PlayInspectImpl {select(selection: EntityId | null): void {this.store.setState({ ...this.store.getState(), selection });- void this.poll(); // fetch the newly-selected entity's full data immediately+ void this.poll(false); // fetch the newly-selected entity's full data immediately}- /** Begin the coalesced sampling loop (call on Play). Idempotent. */+ /** Begin sampling (call on Play). Idempotent; idles until a consumer subscribes. */start(): void {if (this.active) return;this.active = true;- void this.tick();+ this.arm();}/** Stop sampling + clear (call on Stop) — live state is discarded with the realm. */stop(): void {this.active = false;+ this.loopEpoch++;+ this.scheduled = false;if (this.timer) clearTimeout(this.timer);this.timer = null;+ this.lastTreeAt = 0;+ this.curTreeSig = '';this.store.setState({ snapshot: null, selectedEntity: null, selection: null });}/** Live-edit a field of the running game; refresh immediately for snappy feedback. */setField(id: EntityId, comp: string, key: string, value: unknown): void {PlayRealm.setField(id, comp, key, value);- void this.poll();+ void this.poll(false);}- // Sample, then re-arm after the reply with at least MIN_GAP_MS between starts.- private async tick(): Promise<void> {- if (!this.active) return;+ // Start the loop if it should run and isn't already (called on start + on the+ // first subscriber appearing while playing).+ private arm(): void {+ if (!this.active || this.subscribers === 0 || this.scheduled) return;+ this.scheduled = true;+ void this.tick(this.loopEpoch);+ }++ // Sample, then re-arm after the reply — the detail rate when an entity is+ // selected, the tree rate otherwise; each tick includes the tree only when the+ // tree interval elapsed.+ private async tick(epoch: number): Promise<void> {+ if (epoch !== this.loopEpoch || !this.active || this.subscribers === 0) {+ this.scheduled = false;+ return;+ }const t0 = performance.now();- await this.poll();- if (!this.active) return;- const wait = Math.max(0, MIN_GAP_MS - (performance.now() - t0));- this.timer = setTimeout(() => void this.tick(), wait);+ const withTree = this.store.getState().snapshot == null || t0 - this.lastTreeAt >= TREE_GAP_MS;+ await this.poll(withTree);+ if (epoch !== this.loopEpoch || !this.active || this.subscribers === 0) {+ this.scheduled = false;+ return;+ }+ const gap = this.store.getState().selection != null ? DETAIL_GAP_MS : TREE_GAP_MS;+ const wait = Math.max(0, gap - (performance.now() - t0));+ this.timer = setTimeout(() => void this.tick(epoch), wait);}- private async poll(): Promise<void> {+ private async poll(withTree: boolean): Promise<void> {const sel = this.store.getState().selection;- const res = await PlayRealm.snapshot(sel);+ const res = await PlayRealm.snapshot(sel, { tree: withTree });if (!res) return;const cur = this.store.getState();// Keep the tree reference stable unless the structure changed, so the Outliner's// memoized tree build is skipped between samples; only the selected entity (the- // Details payload) refreshes each tick.- const sameTree = cur.snapshot != null && treeSig(cur.snapshot) === treeSig(res.tree);+ // Details payload) refreshes each tick. A detail-only sample has no tree.+ let snapshot = cur.snapshot;+ if (res.tree) {+ this.lastTreeAt = performance.now();+ const sig = treeSig(res.tree);+ if (cur.snapshot == null || sig !== this.curTreeSig) snapshot = res.tree;+ this.curTreeSig = sig;+ }const sameSelected = cur.selectedEntity === res.selected|| (cur.selectedEntity != null && res.selected != null&& JSON.stringify(cur.selectedEntity) === JSON.stringify(res.selected));- if (sameTree && sameSelected) return;+ if (snapshot === cur.snapshot && sameSelected) return;this.store.setState({- snapshot: sameTree ? cur.snapshot : res.tree,+ snapshot,selectedEntity: sameSelected ? cur.selectedEntity : res.selected,selection: cur.selection,});diff --git a/desktop/src/engine/PlayRealm.ts b/desktop/src/engine/PlayRealm.tsindex 17b43551b..319742e2e 100644--- a/desktop/src/engine/PlayRealm.ts+++ b/desktop/src/engine/PlayRealm.ts@@ -138,7 +138,16 @@ export class PlayRealmInstance {// scene directly (the host does a warm rebuild: no second wasm instantiate, no// iframe/bundle reload). Single-player primary only; anything else cold-boots.if (this.warm && this.id === 0 && !this.netPorts) {- bootProfiler.mark('warm re-Play (engine kept alive)');+ // The bundle on disk is only rebuilt by preparePlayRealm (cold path) and by+ // fsWatch WHILE playing — so code edited between Stop and re-Play would replay+ // stale. Rebuild first (incremental esbuild, ~100ms); the host re-imports the+ // bundle cache-busted. Best-effort: a build failure keeps the last-good bundle.+ try {+ await window.estella?.project?.buildScripts?.();+ } catch {+ /* keep the last-good bundle — builtin-only projects have none to rebuild */+ }+ bootProfiler.mark('warm re-Play (rebuild scripts + engine kept alive)');this.postInit();return;}@@ -188,6 +197,15 @@ export class PlayRealmInstance {this.set({ playing: false, ready: false, error: null });}+ /** Drop the staged realm but keep the iframe + listener (reusable): cold+ * teardown so the NEXT prewarm/Play stages the current project. Call when the+ * open project changes — a warm realm still holds the previous project's+ * bundle + wasm + assets and would silently play the wrong project. */+ reset(): void {+ this.warm = false;+ this.stop();+ }+/** Full teardown for a session-scoped (client) realm: stop + drop the iframe* and the window listener. The instance is not reusable afterwards. */destroy(): void {@@ -239,14 +257,16 @@ export class PlayRealmInstance {/** A live inspect snapshot: a SHALLOW tree of the running World (cheap to ship* even for thousands of entities) plus the FULL data of `selectedId` for the- * Details panel. Null if not ready. */- snapshot(selectedId: number | null): Promise<PlaySnapshot | null> {+ * Details panel. `opts.tree: false` samples the selected entity only (the+ * realm skips its O(entities) tree walk; `tree` comes back null). Null if not+ * ready. */+ snapshot(selectedId: number | null, opts?: { tree?: boolean }): Promise<PlaySnapshot | null> {if (!this.iframe?.contentWindow || !this.store.getState().ready) return Promise.resolve(null);const reqId = ++this.reqSeq;return new Promise((resolve) => {const done = (data: unknown) => resolve((data as PlaySnapshot) ?? null);this.pending.set(reqId, done);- this.post({ type: 'estella:play:query', kind: 'snapshot', reqId, selectedId });+ this.post({ type: 'estella:play:query', kind: 'snapshot', reqId, selectedId, withTree: opts?.tree !== false });setTimeout(() => {if (this.pending.delete(reqId)) resolve(null);}, 2000);@@ -401,6 +421,12 @@ class PlayRealmsManager {return this.primary.prewarm();}+ /** Cold-reset the primary realm on a project switch / return to launcher, so a+ * realm warmed for project A never serves project B (see {@link PlayRealmInstance.reset}). */+ resetPrimary(): void {+ this.primary.reset();+ }+async startSession(payload: PlayPayload, players = 1): Promise<void> {this.lastPayload_ = payload;this.lastPlayers_ = players;diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex 4d3b8bad2..9532c8ed0 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -606,6 +606,42 @@ export class SceneCommandsImpl {);}+ /** Delete a whole selection as ONE undo step (one gesture, however many roots). */+ deleteEntities(ids: readonly EntityId[]): void {+ if (ids.length === 0) return;+ if (ids.length === 1) return this.deleteEntity(ids[0]);+ this.history.group(`Delete ${ids.length} Entities`, () => {+ for (const id of ids) this.deleteEntity(id);+ });+ }++ /** Duplicate a whole selection as ONE undo step. Returns the new source ids. */+ duplicateEntities(ids: readonly EntityId[]): EntityId[] {+ if (ids.length === 0) return [];+ if (ids.length === 1) {+ const d = this.duplicateEntity(ids[0]);+ return d != null ? [d] : [];+ }+ const out: EntityId[] = [];+ this.history.group(`Duplicate ${ids.length} Entities`, () => {+ for (const id of ids) {+ const d = this.duplicateEntity(id);+ if (d != null) out.push(d);+ }+ });+ return out;+ }++ /** Re-parent a whole drag selection as ONE undo step (per-id rules of {@link setParent}). */+ reparentEntities(ids: readonly EntityId[], parent: EntityId | null): void {+ const movable = ids.filter((id) => id !== parent);+ if (movable.length === 0) return;+ if (movable.length === 1) return this.setParent(movable[0], parent);+ this.history.group(`Reparent ${movable.length} Entities`, () => {+ for (const id of movable) this.setParent(id, parent);+ });+ }+/** Duplicate an entity (offset slightly, as a sibling). Returns the new source id. */duplicateEntity(sourceId: EntityId): EntityId | null {const src = this.model.entityBySource(sourceId);@@ -654,10 +690,10 @@ export class SceneCommandsImpl {return payload.length;}- /** Copy the entities, then delete them (one delete step per selected root). */+ /** Copy the entities, then delete them (the delete is one undo step). */cutEntities(ids: readonly EntityId[]): number {const n = this.copyEntities(ids);- if (n > 0) for (const id of ids) this.deleteEntity(id);+ if (n > 0) this.deleteEntities(ids);return n;}diff --git a/desktop/src/engine/playProtocol.ts b/desktop/src/engine/playProtocol.tsindex 133b008f5..fd099ac3c 100644--- a/desktop/src/engine/playProtocol.ts+++ b/desktop/src/engine/playProtocol.ts@@ -81,9 +81,11 @@ export interface PlayPayload {}/** A live inspect snapshot: a shallow entity tree (Outliner) + the selected entity's- * full data (Details). The reply payload of a `query { kind: 'snapshot' }`. */+ * full data (Details). The reply payload of a `query { kind: 'snapshot' }`.+ * `tree` is null for a detail-only sample (`withTree: false`) — the editor polls+ * the selected entity faster than the O(entities) tree. */export interface PlaySnapshot {- tree: SceneData;+ tree: SceneData | null;selected: SceneData['entities'][number] | null;}@@ -116,7 +118,8 @@ export type PlayOutbound =| { type: 'estella:play:warm' }| { type: 'estella:play:setPaused'; paused: boolean }| { type: 'estella:play:reload' }- | { type: 'estella:play:query'; kind: PlayQueryKind; reqId: number; selectedId?: number | null }+ // `withTree: false` = detail-only snapshot (skip the O(entities) tree walk).+ | { type: 'estella:play:query'; kind: PlayQueryKind; reqId: number; selectedId?: number | null; withTree?: boolean }| { type: 'estella:play:setField'; entityId: number; comp: string; key: string; value: unknown };/** realm → editor. Discriminated by `type`. */diff --git a/desktop/src/i18n/messages/common.ts b/desktop/src/i18n/messages/common.tsindex 7d2f67ea9..446aaefc9 100644--- a/desktop/src/i18n/messages/common.ts+++ b/desktop/src/i18n/messages/common.ts@@ -35,6 +35,7 @@ export const commonMessages = defineMessages({'discard.default': { en: 'They will be lost', zh: '它们将会丢失' },'discard.newScene': { en: 'Creating a new scene will discard them', zh: '新建场景将丢弃这些更改' },'discard.closeProject': { en: 'Closing the project will discard them', zh: '关闭项目将丢弃这些更改' },+ 'discard.openProject': { en: 'Opening another project will discard them', zh: '打开其他项目将丢弃这些更改' },'discard.openScene': { en: 'Opening {name} will discard them', zh: '打开 {name} 将丢弃这些更改' },'discard.reloadChanged': {en: '“{name}” changed on disk. Reloading discards your unsaved edits',diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex dfaa13fed..14d1abad8 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -63,6 +63,7 @@ import { ProjectStore } from '@/project/ProjectStore';import { confirmDiscard } from '@/project/discardGuard';import { t } from '@/i18n';import { MaterialDocument } from '@/material/MaterialDocument';+import { DirtyRegistry } from '@/document/DirtyRegistry';import {isMaterialAsset,resolveMaterialContext,@@ -2464,14 +2465,16 @@ function GenericAssetInspector({ path }: { path: string }) {const write: FieldWrite = (key, _t, value) => {setImporter((cur) => (cur ? applyImporterEdit(cur, key, value as InspectorFieldValue) : cur));setDirty(true);+ DirtyRegistry.bump();};const save = async () => {try {const meta = JSON.parse(await window.estella.fs.read(path + '.meta'));- meta.importer = importer;+ meta.importer = importerRef.current;await window.estella.fs.write(path + '.meta', JSON.stringify(meta, null, 2) + '\n');setDirty(false);+ DirtyRegistry.bump();await ProjectStore.refreshAssets();// Push filter/wrap to the live gl handle so the edit viewport updates now// (no scene reload); a no-op for types/assets without a live texture.@@ -2482,6 +2485,25 @@ function GenericAssetInspector({ path }: { path: string }) {}};+ // Unsaved import-settings edits join the aggregate dirty state while this+ // inspector is mounted (quit-save writes them; deselecting still discards, as+ // before). Latest-refs so the registered closures never go stale.+ const dirtyRef = useRef(dirty);+ dirtyRef.current = dirty;+ const importerRef = useRef(importer);+ importerRef.current = importer;+ const saveRef = useRef(save);+ saveRef.current = save;+ useEffect(+ () =>+ DirtyRegistry.register({+ id: `importer:${path}`,+ isDirty: () => dirtyRef.current,+ save: () => saveRef.current(),+ }),+ [path],+ );+return (<div className="insp"><div className="ent-head">diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsxindex 06a13c78d..86a816cbb 100644--- a/desktop/src/panels/Outliner.tsx+++ b/desktop/src/panels/Outliner.tsx@@ -266,7 +266,7 @@ export function Outliner() {const sel = [...useSelection.getState().selectedIds];if (sel.length) {e.preventDefault();- sel.forEach((i) => SceneCommands.deleteEntity(i));+ SceneCommands.deleteEntities(sel);select(null);}break;@@ -435,7 +435,7 @@ export function Outliner() {dragIds.current = null;setDrop(null);if (!ids) return;- for (const child of ids) if (child !== target) SceneCommands.setParent(child, target);+ SceneCommands.reparentEntities(ids, target);};const moveToFolder = (path: string | null) => {const ids = dragIds.current;@@ -537,8 +537,8 @@ export function Outliner() {label: t('out.duplicate'),shortcut: formatKeybinding('mod+d'),onClick: () => {- const d = SceneCommands.duplicateEntity(id);- if (d != null) select(d);+ const dups = SceneCommands.duplicateEntities(selectionOrTarget(id));+ if (dups.length > 0) useSelection.getState().selectMany(dups, dups[dups.length - 1]);},},{ label: t('out.createPrefab'), onClick: () => void ProjectStore.createPrefabFromEntity(id) },@@ -546,7 +546,7 @@ export function Outliner() {label: t('ui.delete'),shortcut: formatKeybinding('delete'),onClick: () => {- selectionOrTarget(id).forEach((i) => SceneCommands.deleteEntity(i));+ SceneCommands.deleteEntities(selectionOrTarget(id));select(null);},},@@ -556,7 +556,7 @@ export function Outliner() {{ sep: true },{ label: t('out.newFolderFromSelection'), onClick: () => newFolder('', selectionOrTarget(id)) },{ label: t('out.moveToRoot'), onClick: () => SceneCommands.moveToFolder(selectionOrTarget(id), null) },- { label: t('out.unparent'), onClick: () => selectionOrTarget(id).forEach((i) => SceneCommands.setParent(i, null)) },+ { label: t('out.unparent'), onClick: () => SceneCommands.reparentEntities(selectionOrTarget(id), null) },{ sep: true },{ label: t('out.addEntity'), onClick: addEntity },{ label: t('out.createTemplate'), onClick: () => setCreateFor({ parent: id }) },diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.tsindex 4721a6ff2..dbee08c87 100644--- a/desktop/src/playHost.ts+++ b/desktop/src/playHost.ts@@ -36,7 +36,7 @@ function inspectableTypes(world: App['world'], entity: number): string[] {});}-function liveSnapshot(world: App['world'], selectedId: number | null): { tree: SceneData; selected: LiveEntity | null } {+function liveSnapshot(world: App['world'], selectedId: number | null, withTree: boolean): { tree: SceneData | null; selected: LiveEntity | null } {const nameDef = getComponent('Name');const parentDef = getComponent('Parent');const all = world.getAllEntities();@@ -54,15 +54,19 @@ function liveSnapshot(world: App['world'], selectedId: number | null): { tree: Sconst nameOf = (e: number): string =>(nameDef ? (world.tryGet(e as never, nameDef) as { value?: string } | null)?.value : undefined) ?? `Entity_${e}`;- const tree = {- version: '1.0',- name: 'live',- entities: all.map((e): LiveEntity => {- const id = e as never as number;- // Component TYPES only — no data decode (the Outliner reads kind from types).- return { id, name: nameOf(id), parent: parentOf.get(id) ?? null, children: childrenOf.get(id) ?? [], components: inspectableTypes(world, id).map((type) => ({ type, data: {} })) } as LiveEntity;- }),- } as unknown as SceneData;+ // The tree walk is O(entities) — a detail-only sample (withTree false) skips it+ // so the editor can poll the selected entity faster than the tree.+ const tree = withTree+ ? ({+ version: '1.0',+ name: 'live',+ entities: all.map((e): LiveEntity => {+ const id = e as never as number;+ // Component TYPES only — no data decode (the Outliner reads kind from types).+ return { id, name: nameOf(id), parent: parentOf.get(id) ?? null, children: childrenOf.get(id) ?? [], components: inspectableTypes(world, id).map((type) => ({ type, data: {} })) } as LiveEntity;+ }),+ } as unknown as SceneData)+ : null;let selected: LiveEntity | null = null;if (selectedId != null) {@@ -469,7 +473,7 @@ window.addEventListener('message', (e: MessageEvent) => {case 'estella:play:query':// Live introspection for the editor's "Game" inspect mode (the Details panel).if (data.kind === 'snapshot') {- const reply = app ? liveSnapshot(app.world, data.selectedId ?? null) : null;+ const reply = app ? liveSnapshot(app.world, data.selectedId ?? null, data.withTree !== false) : null;post({ type: 'estella:play:reply', reqId: data.reqId, data: reply });} else if (data.kind === 'stats') {// Per-phase + per-system timing + render counters — the running game'sdiff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 55e6c6550..382a2aa2a 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -28,6 +28,7 @@ import { assetTypeOf } from '@/project/assetMeta';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';/** Pad/truncate collision-layer names to the 16 Box2D filter bits (layer 0 = Default). */function normalizeLayers(layers?: string[]): string[] {@@ -346,6 +347,9 @@ class ProjectStoreImpl {}private adopt(opened: OpenedProject) {+ // A play realm warmed for the PREVIOUS project holds its bundle + assets;+ // cold-reset so the next prewarm/Play stages this project.+ PlayRealms.resetPrimary();this.store.setState({project: {root: opened.root,diff --git a/desktop/src/project/discardGuard.ts b/desktop/src/project/discardGuard.tsindex 0ebf11ddc..094d5b6f3 100644--- a/desktop/src/project/discardGuard.ts+++ b/desktop/src/project/discardGuard.ts@@ -2,13 +2,13 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file discardGuard.ts- * @brief The single unsaved-changes gate. Any action that would discard the- * current scene (new / open / close / switch) calls this first, so the- * prompt logic lives in one place and reflects the REAL dirty state- * (EditorHistory.isDirty), not the old `canUndo` proxy that stayed true- * after a save and false-warned.+ * @brief The single unsaved-changes gate. Any action that would discard open+ * documents (new / open / close / switch) calls this first, so the+ * prompt logic lives in one place and reflects the REAL dirty state —+ * the DirtyRegistry aggregate (scene + every open asset editor), not+ * just the scene's EditorHistory.*/-import { EditorHistory } from '@/engine/EditorHistory';+import { DirtyRegistry } from '@/document/DirtyRegistry';import { confirm } from '@/components/confirm';import { t } from '@/i18n';@@ -21,7 +21,7 @@ import { t } from '@/i18n';* `if (!(await confirmDiscard(...))) return;`.*/export async function confirmDiscard(what = t('discard.default')): Promise<boolean> {- if (!EditorHistory.isDirty()) return true;+ if (!DirtyRegistry.isDirty()) return true;return confirm({title: t('discard.title'),body: t('discard.body', { what }),diff --git a/desktop/tests/dirty-docs.test.ts b/desktop/tests/dirty-docs.test.tsnew file mode 100644index 000000000..9e0568665--- /dev/null+++ b/desktop/tests/dirty-docs.test.ts@@ -0,0 +1,70 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file dirtyDocs — the built-in DirtyRegistry registrations: an edited+ * AssetDocument (here the BT editor) makes the aggregate dirty and+ * quit-save (saveAll) writes it to disk + clears its dirty flag.+ * Pure TS with a stubbed window.estella.fs.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { DirtyRegistry } from '@/document/DirtyRegistry';+import { BtDocument } from '@/bt/BtDocument';+import { FsmGraphDocument } from '@/fsm/FsmGraphDocument';+import type { BtDefinition } from 'esengine';+import '@/document/dirtyDocs';++const write = vi.fn(async (_path: string, _text: string) => {});++beforeEach(() => {+ write.mockClear();+ (globalThis as { window?: unknown }).window = { estella: { fs: { write } } };+});++afterEach(() => {+ BtDocument.close();+ FsmGraphDocument.close();+ delete (globalThis as { window?: unknown }).window;+});++const btDef = (): BtDefinition =>+ ({ root: { id: 'root', type: 'selector', children: [] } }) as unknown as BtDefinition;++describe('built-in dirty documents', () => {+ it('an edited asset document makes the aggregate dirty (scene history aside)', () => {+ BtDocument.open(btDef(), 'assets/ai/x.esbt');+ expect(DirtyRegistry.isDirty()).toBe(false);+ BtDocument.edit('Add node', (d) => {+ (d as { root: { children: unknown[] } }).root.children.push({ id: 'n1', type: 'action' });+ });+ expect(BtDocument.dirty).toBe(true);+ expect(DirtyRegistry.isDirty()).toBe(true);+ });++ it('saveAll writes every dirty document and clears its flag', async () => {+ BtDocument.open(btDef(), 'assets/ai/x.esbt');+ BtDocument.edit('Add node', (d) => {+ (d as { root: { children: unknown[] } }).root.children.push({ id: 'n1', type: 'action' });+ });+ FsmGraphDocument.open({ initial: 'idle', states: {} } as never, 'assets/ai/y.esfsm');+ FsmGraphDocument.edit('Rename', (d) => {+ (d as { initial: string }).initial = 'run';+ });++ await DirtyRegistry.saveAll();++ const paths = write.mock.calls.map((c) => c[0]);+ expect(paths).toContain('assets/ai/x.esbt');+ expect(paths).toContain('assets/ai/y.esfsm');+ expect(BtDocument.dirty).toBe(false);+ expect(FsmGraphDocument.dirty).toBe(false);+ expect(JSON.parse(write.mock.calls.find((c) => c[0] === 'assets/ai/y.esfsm')![1] as string)).toEqual({+ initial: 'run',+ states: {},+ });+ });++ it('a clean (or closed) document is not written', async () => {+ await DirtyRegistry.saveAll();+ expect(write).not.toHaveBeenCalled();+ });+});diff --git a/desktop/tests/dirty-registry.test.ts b/desktop/tests/dirty-registry.test.tsnew file mode 100644index 000000000..b8968cd56--- /dev/null+++ b/desktop/tests/dirty-registry.test.ts@@ -0,0 +1,138 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file DirtyRegistry — the aggregate unsaved-changes surface: registration,+ * aggregation, quit-save (saveAll saves only the dirty documents), and+ * the discard guard consulting it (incl. the Ctrl+O project.open gate).+ * Pure TS.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { DirtyRegistry, type DirtyDocument } from '@/document/DirtyRegistry';+import { confirmDiscard } from '@/project/discardGuard';+import { ConfirmService } from '@/components/confirm';+import { ProjectStore } from '@/project/ProjectStore';+import { commands } from '@/commands';++const doc = (id: string, dirty: boolean, save = vi.fn(async () => {})): DirtyDocument & { save: ReturnType<typeof vi.fn> } => {+ let d = dirty;+ return {+ id,+ isDirty: () => d,+ save: save.mockImplementation(async () => {+ d = false;+ }),+ };+};++beforeEach(() => DirtyRegistry.clearAll());+afterEach(() => {+ DirtyRegistry.clearAll();+ vi.restoreAllMocks();+});++describe('DirtyRegistry', () => {+ it('aggregates dirty over all registered documents', () => {+ expect(DirtyRegistry.isDirty()).toBe(false);+ DirtyRegistry.register(doc('a', false));+ expect(DirtyRegistry.isDirty()).toBe(false);+ const un = DirtyRegistry.register(doc('b', true));+ expect(DirtyRegistry.isDirty()).toBe(true);+ un();+ expect(DirtyRegistry.isDirty()).toBe(false);+ });++ it('saveAll saves only the dirty documents', async () => {+ const clean = doc('clean', false);+ const dirty = doc('dirty', true);+ DirtyRegistry.register(clean);+ DirtyRegistry.register(dirty);+ await DirtyRegistry.saveAll();+ expect(clean.save).not.toHaveBeenCalled();+ expect(dirty.save).toHaveBeenCalledTimes(1);+ expect(DirtyRegistry.isDirty()).toBe(false);+ });++ it('re-registering an id replaces the previous entry', () => {+ DirtyRegistry.register(doc('x', true));+ DirtyRegistry.register(doc('x', false));+ expect(DirtyRegistry.isDirty()).toBe(false);+ });++ it("a replaced entry's stale unregister does not remove the newer one", () => {+ const un = DirtyRegistry.register(doc('x', false));+ DirtyRegistry.register(doc('x', true));+ un(); // stale — must not delete the second registration+ expect(DirtyRegistry.isDirty()).toBe(true);+ });++ it('notifies subscribers on register/unregister, bump, and a participant feed', () => {+ const fn = vi.fn();+ const unsub = DirtyRegistry.subscribe(fn);+ let feed: (() => void) | null = null;+ const un = DirtyRegistry.register({+ id: 'a',+ isDirty: () => false,+ save: async () => {},+ subscribe: (f) => {+ feed = f;+ return () => { feed = null; };+ },+ });+ expect(fn).toHaveBeenCalledTimes(1); // register+ feed!();+ expect(fn).toHaveBeenCalledTimes(2); // participant change feed+ DirtyRegistry.bump();+ expect(fn).toHaveBeenCalledTimes(3);+ un();+ expect(fn).toHaveBeenCalledTimes(4); // unregister+ expect(feed).toBeNull(); // participant feed released+ unsub();+ });+});++describe('confirmDiscard over the registry', () => {+ it('resolves true without prompting when nothing is dirty', async () => {+ await expect(confirmDiscard()).resolves.toBe(true);+ expect(ConfirmService.getSnapshot()).toHaveLength(0);+ });++ it('prompts when any document is dirty and honors the answer', async () => {+ DirtyRegistry.register(doc('a', true));+ const p = confirmDiscard();+ const pending = ConfirmService.getSnapshot();+ expect(pending).toHaveLength(1);+ ConfirmService.settle(pending[0].id, false);+ await expect(p).resolves.toBe(false);+ });+});++describe('project.open guard (Ctrl+O)', () => {+ it('does not open while dirty until the user confirms the discard', async () => {+ const open = vi.spyOn(ProjectStore, 'openViaDialog').mockResolvedValue(false);+ DirtyRegistry.register(doc('a', true));++ const run = commands.get('project.open')!.run() as Promise<void>;+ await Promise.resolve(); // let confirmDiscard queue the dialog+ const pending = ConfirmService.getSnapshot();+ expect(pending).toHaveLength(1);+ expect(open).not.toHaveBeenCalled(); // gated behind the prompt++ ConfirmService.settle(pending[0].id, false); // Cancel+ await run;+ expect(open).not.toHaveBeenCalled();+ });++ it('opens when clean (no prompt) and after a confirmed discard', async () => {+ const open = vi.spyOn(ProjectStore, 'openViaDialog').mockResolvedValue(false);++ await commands.get('project.open')!.run();+ expect(open).toHaveBeenCalledTimes(1); // clean → straight through++ DirtyRegistry.register(doc('a', true));+ const run = commands.get('project.open')!.run() as Promise<void>;+ await Promise.resolve();+ ConfirmService.settle(ConfirmService.getSnapshot()[0].id, true); // Discard+ await run;+ expect(open).toHaveBeenCalledTimes(2);+ });+});diff --git a/desktop/tests/editor-history-group.test.ts b/desktop/tests/editor-history-group.test.tsnew file mode 100644index 000000000..b0b925cd1--- /dev/null+++ b/desktop/tests/editor-history-group.test.ts@@ -0,0 +1,91 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file EditorHistory.group — every step recorded inside the callback collapses+ * into ONE undo step (the multi-selection gesture door). Pure TS.+ */+import { describe, it, expect, beforeEach } from 'vitest';+import { EditorHistoryImpl } from '@/engine/EditorHistory';++describe('EditorHistory group', () => {+ let h: EditorHistoryImpl;+ let value: number;+ beforeEach(() => {+ h = new EditorHistoryImpl();+ value = 0;+ });++ const add = (n: number) => {+ value += n;+ h.record(`Add ${n}`, () => { value += n; }, () => { value -= n; });+ };++ it('collapses several record() calls into one undo step', () => {+ h.group('Batch', () => { add(1); add(2); add(4); });+ expect(value).toBe(7);+ expect(h.undoLabel()).toBe('Batch');+ h.undo();+ expect(value).toBe(0); // all three reversed by ONE undo+ expect(h.canUndo()).toBe(false);+ h.redo();+ expect(value).toBe(7);+ });++ it('run() inside a group applies forward immediately and joins the step', () => {+ h.group('Batch', () => {+ h.run('Set', () => { value = 5; }, () => { value = 0; });+ });+ expect(value).toBe(5);+ h.undo();+ expect(value).toBe(0);+ });++ it('an empty group records no step', () => {+ h.group('Nothing', () => {});+ expect(h.canUndo()).toBe(false);+ expect(h.isDirty()).toBe(false);+ });++ it('a nested group folds into the outer one (one step, outer label)', () => {+ h.group('Outer', () => {+ add(1);+ h.group('Inner', () => add(2));+ });+ expect(h.undoLabel()).toBe('Outer');+ h.undo();+ expect(value).toBe(0);+ expect(h.canUndo()).toBe(false);+ });++ it('reverses ops LIFO within the step', () => {+ const order: string[] = [];+ h.group('Batch', () => {+ h.record('a', () => {}, () => order.push('a'));+ h.record('b', () => {}, () => order.push('b'));+ });+ h.undo();+ expect(order).toEqual(['b', 'a']);+ });++ it('recording after the group is a separate step again', () => {+ h.group('Batch', () => add(1));+ add(2);+ expect(h.undoLabel()).toBe('Add 2');+ h.undo();+ expect(value).toBe(1);+ h.undo();+ expect(value).toBe(0);+ });++ it('a throwing callback still commits what it recorded (and rethrows)', () => {+ expect(() =>+ h.group('Boom', () => {+ add(1);+ throw new Error('boom');+ }),+ ).toThrow('boom');+ expect(value).toBe(1);+ h.undo();+ expect(value).toBe(0);+ });+});diff --git a/desktop/tests/multi-select-batch.test.ts b/desktop/tests/multi-select-batch.test.tsnew file mode 100644index 000000000..4844bba21--- /dev/null+++ b/desktop/tests/multi-select-batch.test.ts@@ -0,0 +1,112 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Multi-selection commands batch into ONE undo step per gesture:+ * deleteEntities / duplicateEntities / reparentEntities / cutEntities.+ * Pure TS (real model + history, no WASM).+ */+import { describe, it, expect, beforeEach } from 'vitest';+import type { SceneData } from 'esengine';+import { SceneModelImpl } from '@/engine/SceneModel';+import { EditorHistoryImpl } from '@/engine/EditorHistory';+import { SceneCommandsImpl } from '@/engine/SceneCommands';++const ent = (id: number, parent: number | null = null, children: number[] = []) => ({+ id,+ name: `E${id}`,+ parent,+ children,+ visible: true,+ components: [+ { type: 'Transform', data: { position: { x: 0, y: 0, z: 0 }, rotation: { w: 1, x: 0, y: 0, z: 0 }, scale: { x: 1, y: 1, z: 1 } } },+ ],+});++function scene(): SceneData {+ // 1, 2, 3 roots; 4 is a child of 3.+ return {+ version: '1.0',+ name: 't',+ entities: [ent(1), ent(2), ent(3, null, [4]), ent(4, 3)],+ } as unknown as SceneData;+}++const undoDepth = (h: EditorHistoryImpl): number => {+ let n = 0;+ while (h.canUndo()) {+ h.undo();+ n++;+ }+ for (let i = 0; i < n; i++) h.redo();+ return n;+};++describe('multi-selection batching', () => {+ let model: SceneModelImpl;+ let history: EditorHistoryImpl;+ let cmds: SceneCommandsImpl;++ beforeEach(() => {+ model = new SceneModelImpl();+ history = new EditorHistoryImpl();+ cmds = new SceneCommandsImpl(model, history);+ model.adopt(scene(), new Map([[1, 101], [2, 102], [3, 103], [4, 104]]));+ });++ it('deleteEntities removes all roots (with subtrees) as one undo step', () => {+ cmds.deleteEntities([1, 3]);+ expect(model.entityBySource(1)).toBeUndefined();+ expect(model.entityBySource(3)).toBeUndefined();+ expect(model.entityBySource(4)).toBeUndefined(); // subtree went with 3+ expect(undoDepth(history)).toBe(1);+ expect(history.undoLabel()).toBe('Delete 2 Entities');+ history.undo();+ expect(model.entityBySource(1)).toBeDefined();+ expect(model.entityBySource(3)).toBeDefined();+ expect(model.entityBySource(4)).toBeDefined();+ });++ it('deleteEntities of a single id keeps the named single-delete step', () => {+ cmds.deleteEntities([2]);+ expect(history.undoLabel()).toBe('Delete E2');+ expect(undoDepth(history)).toBe(1);+ });++ it('duplicateEntities clones every selected entity as one undo step', () => {+ const dups = cmds.duplicateEntities([1, 2]);+ expect(dups).toHaveLength(2);+ for (const d of dups) expect(model.entityBySource(d)).toBeDefined();+ expect(undoDepth(history)).toBe(1);+ history.undo();+ for (const d of dups) expect(model.entityBySource(d)).toBeUndefined();+ history.redo();+ for (const d of dups) expect(model.entityBySource(d)).toBeDefined();+ });++ it('reparentEntities moves the whole drag as one undo step', () => {+ cmds.reparentEntities([1, 2], 3);+ expect(model.entityBySource(1)?.parent).toBe(3);+ expect(model.entityBySource(2)?.parent).toBe(3);+ expect(undoDepth(history)).toBe(1);+ history.undo();+ expect(model.entityBySource(1)?.parent ?? null).toBeNull();+ expect(model.entityBySource(2)?.parent ?? null).toBeNull();+ });++ it('reparentEntities keeps per-id rules (skips the target + cycles)', () => {+ cmds.reparentEntities([3, 4, 1], 4); // 3→4 is a cycle, 4→4 is self; only 1 moves+ expect(model.entityBySource(3)?.parent ?? null).toBeNull();+ expect(model.entityBySource(1)?.parent).toBe(4);+ });++ it('cutEntities copies then deletes as one undo step', () => {+ const n = cmds.cutEntities([1, 2]);+ expect(n).toBe(2);+ expect(model.entityBySource(1)).toBeUndefined();+ expect(model.entityBySource(2)).toBeUndefined();+ expect(undoDepth(history)).toBe(1);+ history.undo();+ expect(model.entityBySource(1)).toBeDefined();+ expect(model.entityBySource(2)).toBeDefined();+ });+});diff --git a/desktop/tests/play-inspect-gating.test.ts b/desktop/tests/play-inspect-gating.test.tsnew file mode 100644index 000000000..ba495bdb1--- /dev/null+++ b/desktop/tests/play-inspect-gating.test.ts@@ -0,0 +1,138 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file PlayInspect sampling gates + rates: no realm polling without a+ * subscribed game-mode consumer; tree samples at the slow structural+ * rate, selected-entity detail at the fast rate (detail-only samples+ * skip the realm tree walk); the tree reference stays stable when only+ * values change. PlayRealm is mocked; timers + performance are faked.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import type { SceneData } from 'esengine';++vi.mock('@/engine/PlayRealm', () => ({+ PlayRealm: {+ snapshot: vi.fn(),+ setField: vi.fn(),+ },+}));++import { PlayInspect } from '@/engine/PlayInspect';+import { PlayRealm } from '@/engine/PlayRealm';++const snapshotMock = vi.mocked(PlayRealm.snapshot);++const tree = (ids: number[]): SceneData =>+ ({+ version: '1.0',+ name: 'live',+ entities: ids.map((id) => ({ id, name: `E${id}`, parent: null, children: [], components: [{ type: 'Transform', data: {} }] })),+ }) as unknown as SceneData;++let now = 0;++beforeEach(() => {+ vi.useFakeTimers();+ now = 0;+ vi.spyOn(performance, 'now').mockImplementation(() => now);+ snapshotMock.mockImplementation((sel, opts) =>+ Promise.resolve({+ tree: opts?.tree === false ? null : tree([1, 2]),+ selected: sel != null ? (tree([sel as number]).entities[0] ?? null) : null,+ }),+ );+});++afterEach(() => {+ PlayInspect.stop();+ vi.useRealTimers();+ vi.restoreAllMocks();+ snapshotMock.mockReset();+});++/** Advance fake time and the mocked performance clock together. */+const advance = async (ms: number): Promise<void> => {+ now += ms;+ await vi.advanceTimersByTimeAsync(ms);+};++describe('PlayInspect gating', () => {+ it('does not poll while nobody subscribes', async () => {+ PlayInspect.start();+ await advance(1000);+ expect(snapshotMock).not.toHaveBeenCalled();+ });++ it('polls once a consumer subscribes and stops when the last one leaves', async () => {+ PlayInspect.start();+ const unsub = PlayInspect.subscribe(() => {});+ await advance(500);+ expect(snapshotMock.mock.calls.length).toBeGreaterThan(0);+ const calls = snapshotMock.mock.calls.length;+ unsub();+ await advance(1000);+ expect(snapshotMock.mock.calls.length).toBeLessThanOrEqual(calls + 1); // at most the in-flight one+ });++ it('samples the tree at the slow rate and skips it in between', async () => {+ PlayInspect.start();+ const unsub = PlayInspect.subscribe(() => {});+ await advance(0);+ expect(snapshotMock).toHaveBeenCalledTimes(1);+ expect(snapshotMock.mock.calls[0][1]).toEqual({ tree: true }); // first sample seeds the tree++ PlayInspect.select(7); // detail polling engages+ await advance(500);+ const withTree = snapshotMock.mock.calls.filter((c) => c[1]?.tree !== false).length;+ const detailOnly = snapshotMock.mock.calls.filter((c) => c[1]?.tree === false).length;+ // ~30Hz detail vs ~7Hz tree over 500ms: detail-only samples dominate.+ expect(detailOnly).toBeGreaterThan(withTree);+ expect(withTree).toBeGreaterThanOrEqual(2); // the tree still refreshes periodically+ unsub();+ });++ it('polls at the slow rate while nothing is selected', async () => {+ PlayInspect.start();+ const unsub = PlayInspect.subscribe(() => {});+ await advance(1500);+ // one sample per TREE_GAP (150ms) ≈ 10 + the seed — nowhere near 60Hz (90+).+ expect(snapshotMock.mock.calls.length).toBeLessThanOrEqual(15);+ unsub();+ });++ it('keeps the tree reference stable when only values change', async () => {+ PlayInspect.start();+ const unsub = PlayInspect.subscribe(() => {});+ await advance(200);+ const first = PlayInspect.getTree();+ expect(first).not.toBeNull();+ await advance(300); // more tree samples arrive, same structure (fresh objects)+ expect(PlayInspect.getTree()).toBe(first);+ unsub();+ });++ it('a structural change replaces the tree', async () => {+ PlayInspect.start();+ const unsub = PlayInspect.subscribe(() => {});+ await advance(200);+ const first = PlayInspect.getTree();+ snapshotMock.mockImplementation((sel, opts) =>+ Promise.resolve({ tree: opts?.tree === false ? null : tree([1, 2, 3]), selected: null }),+ );+ await advance(300);+ expect(PlayInspect.getTree()).not.toBe(first);+ expect(PlayInspect.getTree()?.entities).toHaveLength(3);+ unsub();+ });++ it('stop() clears the live state', async () => {+ PlayInspect.start();+ const unsub = PlayInspect.subscribe(() => {});+ await advance(200);+ expect(PlayInspect.getTree()).not.toBeNull();+ PlayInspect.stop();+ expect(PlayInspect.getTree()).toBeNull();+ expect(PlayInspect.getSelection()).toBeNull();+ unsub();+ });+});diff --git a/desktop/tests/play-realm-warm.test.ts b/desktop/tests/play-realm-warm.test.tsnew file mode 100644index 000000000..34e17a9fd--- /dev/null+++ b/desktop/tests/play-realm-warm.test.ts@@ -0,0 +1,128 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file PlayRealm warm re-Play + project-switch reset: a warm re-Play rebuilds+ * the project scripts BEFORE handing the realm the new scene (fsWatch+ * only rebuilds while playing, so Stop→edit→Play replayed stale code),+ * and reset() forces the next Play down the cold restage path so a realm+ * warmed for project A never serves project B. DOM is stubbed (node env).+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { PlayRealmInstance } from '@/engine/PlayRealm';+import { PLAY_PROTOCOL_VERSION } from '@/engine/playProtocol';+import type { PlayPayload, PlayInbound } from '@/engine/playProtocol';++interface FakeIframe {+ title: string;+ style: Record<string, string>;+ src: string;+ isConnected: boolean;+ parentElement: null;+ contentWindow: { postMessage: ReturnType<typeof vi.fn>; focus: () => void };+ focus: () => void;+}++const makeIframe = (): FakeIframe => ({+ title: '',+ style: {},+ src: '',+ isConnected: true,+ parentElement: null,+ contentWindow: { postMessage: vi.fn(), focus: () => {} },+ focus: () => {},+});++const payload = (): PlayPayload =>+ ({ sceneData: { version: '1.0', name: 's', entities: [] }, assetManifest: {} }) as unknown as PlayPayload;++let iframe: FakeIframe;+let preparePlayRealm: ReturnType<typeof vi.fn>;+let buildScripts: ReturnType<typeof vi.fn>;+// Ordered log of the interesting effects, to assert rebuild-before-init.+let events: string[];++beforeEach(() => {+ iframe = makeIframe();+ events = [];+ preparePlayRealm = vi.fn(async () => {+ events.push('prepare');+ return { ok: true, hostPath: '.esengine/play/play.html', errors: [] };+ });+ buildScripts = vi.fn(async () => {+ events.push('buildScripts');+ return { ok: true, outputPath: 'x', errors: [], warnings: [] };+ });+ iframe.contentWindow.postMessage.mockImplementation((msg: { type?: string }) => {+ events.push(msg?.type ?? '?');+ });+ (globalThis as { document?: unknown }).document = { createElement: () => iframe };+ (globalThis as { window?: unknown }).window = {+ estella: { project: { preparePlayRealm, buildScripts } },+ addEventListener: () => {},+ removeEventListener: () => {},+ };+});++afterEach(() => {+ delete (globalThis as { document?: unknown }).document;+ delete (globalThis as { window?: unknown }).window;+});++const deliver = (realm: PlayRealmInstance, data: PlayInbound): void => {+ (realm as unknown as { onMessage: (e: { source: unknown; data: PlayInbound }) => void }).onMessage({+ source: iframe.contentWindow,+ data,+ });+};++/** Cold-boot a realm to ready (→ warm) via the normal hello/ready handshake. */+async function playToReady(realm: PlayRealmInstance): Promise<void> {+ await realm.start(payload());+ deliver(realm, { type: 'estella:play:hello', protocolVersion: PLAY_PROTOCOL_VERSION });+ deliver(realm, { type: 'estella:play:ready' });+}++describe('PlayRealm warm re-Play', () => {+ it('cold Play stages the realm (which builds scripts); warm path is not taken', async () => {+ const realm = new PlayRealmInstance(0);+ await playToReady(realm);+ expect(preparePlayRealm).toHaveBeenCalledTimes(1);+ expect(buildScripts).not.toHaveBeenCalled(); // cold path builds inside preparePlayRealm+ expect(realm.getSnapshot().ready).toBe(true);+ });++ it('re-Play after Stop rebuilds project scripts BEFORE posting init', async () => {+ const realm = new PlayRealmInstance(0);+ await playToReady(realm);+ realm.stop();+ events.length = 0;++ await realm.start(payload()); // warm: engine kept alive, no hello round-trip+ expect(preparePlayRealm).toHaveBeenCalledTimes(1); // no restage+ expect(buildScripts).toHaveBeenCalledTimes(1); // fresh bundle for the edited code+ const initAt = events.indexOf('estella:play:init');+ expect(initAt).toBeGreaterThan(events.indexOf('buildScripts')); // rebuild first+ });++ it('a failing rebuild still plays (last-good bundle)', async () => {+ const realm = new PlayRealmInstance(0);+ await playToReady(realm);+ realm.stop();+ buildScripts.mockRejectedValueOnce(new Error('esbuild wedged'));++ await realm.start(payload());+ expect(iframe.contentWindow.postMessage.mock.calls.some((c) => c[0]?.type === 'estella:play:init')).toBe(true);+ expect(realm.getSnapshot().error).toBeNull();+ });++ it('reset() drops warmth: the next Play cold-restages for the (new) project', async () => {+ const realm = new PlayRealmInstance(0);+ await playToReady(realm);+ realm.stop();+ realm.reset();+ expect(iframe.src).toBe('about:blank'); // the old project realm is released++ await realm.start(payload());+ expect(preparePlayRealm).toHaveBeenCalledTimes(2); // restaged, not the warm handover+ });+});