Skip to content

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

fix(editor): unsaved work in ANY document blocks a document swap

yhhbf8ef09af6cf
diff --git a/desktop/scripts/editor-checks/dirty-document-guard.mjs b/desktop/scripts/editor-checks/dirty-document-guard.mjs
new file mode 100644
index 000000000..40f1ffcb1
--- /dev/null
+++ b/desktop/scripts/editor-checks/dirty-document-guard.mjs
@@ -0,0 +1,104 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file dirty-document-guard — unsaved work in ANY document blocks a swap.
+ *
+ * The editor holds several documents at once: the scene, and every open asset
+ * editor. DirtyRegistry aggregates them and discardGuard states the rule — a
+ * guard reads the aggregate, "NOT just the scene's EditorHistory".
+ *
+ * Four doors in the automation surface restated that rule by hand and one
+ * drifted: `open_scene` asked EditorHistory alone. So with an unsaved material
+ * graph open and a clean scene, `open_asset` on a scene refused and `open_scene`
+ * went through — the same operation, opposite answers, and nothing failed to say
+ * so. Whether the graph then survived was luck, not design.
+ *
+ * A static check keeps the surface off single-document state; this is the half a
+ * static check cannot do — that the refusal actually happens, and that saving
+ * lifts it.
+ */
+import path from 'node:path';
+import { cp } from 'node:fs/promises';
+import { makeProject, checker, DESKTOP } from '../lib/editorDriver.mjs';
+
+const EXAMPLE = path.resolve(DESKTOP, '..', 'examples', 'sprite-rendering');
+
+const scene = (name) => JSON.stringify({
+ version: '1.0', name,
+ entities: [
+ {
+ id: 0, name: 'Camera', parent: null, children: [], visible: true,
+ components: [
+ { type: 'Transform', data: { position: { x: 0, y: 0, z: 10 } } },
+ { type: 'Camera', data: { projectionType: 1, orthoSize: 300, isActive: true, priority: 0 } },
+ ],
+ },
+ ],
+}, null, 1);
+
+const GRAPH = JSON.stringify({
+ name: 'Fire',
+ output: 'out',
+ nodes: [
+ { id: 'tint', type: 'constColor', x: 60, y: 60, params: { name: 'u_tint', value: [1, 0, 0, 1] } },
+ { id: 'out', type: 'output', x: 260, y: 60, inputs: { color: 'tint' } },
+ ],
+}, null, 2);
+
+export const name = 'dirty-document-guard';
+export const describes = 'an unsaved ASSET editor blocks a scene swap, and saving it lifts the block';
+
+/** True when a call was refused (the driver throws on an error reply). */
+async function refused(fn) {
+ try {
+ await fn();
+ return null;
+ } catch (e) {
+ return String(e?.message ?? e);
+ }
+}
+
+export async function run(ed) {
+ const root = await makeProject({
+ 'assets/scenes/main.esscene': scene('Main'),
+ 'assets/scenes/other.esscene': scene('Other'),
+ });
+ await cp(path.join(EXAMPLE, 'project.esproject'), path.join(root, 'project.esproject'));
+ await cp(path.join(EXAMPLE, 'src'), path.join(root, 'src'), { recursive: true });
+ const check = checker();
+
+ await ed.open(root, 'assets/scenes/main.esscene');
+
+ const graphPath = await ed.json('create_asset', {
+ destDir: 'assets/fx', baseName: 'Fire', content: GRAPH, type: 'materialgraph',
+ }, 60000);
+ if (!check(typeof graphPath === 'string', `create_asset returned ${JSON.stringify(graphPath)}`)) return check.failures;
+
+ // The SCENE stays clean throughout — that is the whole point. Only the asset
+ // document is dirty, which is exactly what the drifted door could not see.
+ await ed.call('open_asset', { path: graphPath }, 60000);
+ await ed.call('edit_asset_document', {
+ changes: [{ path: 'nodes.0.params.name', value: 'u_flame' }],
+ label: 'Rename param',
+ });
+
+ const doc = await ed.json('get_document', {});
+ check(doc?.dirty === true, `with an edited graph open the document reports dirty=${doc?.dirty}`);
+
+ const why = await refused(() => ed.call('open_scene', { path: 'assets/scenes/other.esscene' }, 60000));
+ check(why !== null, 'open_scene went through with an unsaved material graph open');
+ if (why) check(/unsaved/i.test(why), `it refused, but not about unsaved work: ${why}`);
+
+ // Same state, the other door: it always refused, and must keep refusing.
+ const why2 = await refused(() => ed.call('open_asset', { path: 'assets/scenes/other.esscene' }, 60000));
+ check(why2 !== null, 'open_asset went through with an unsaved material graph open');
+
+ // Saying it out loud is still allowed — the refusal is not a wall.
+ const forced = await refused(() =>
+ ed.call('open_scene', { path: 'assets/scenes/other.esscene', discardChanges: true }, 60000));
+ check(forced === null, `open_scene refused even with discardChanges: ${forced}`);
+ const after = await ed.json('get_document', {});
+ check(after?.path === 'assets/scenes/other.esscene', `the forced open landed on ${after?.path}`);
+
+ return check.failures;
+}
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index dffb1d2eb..7c274eb4d 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -48,7 +48,6 @@ import { PlayRealm } from './engine/PlayRealm';
import { dockApi } from './layout/dockApi';
import { EditorControlSurface } from './engine/EditorSession';
import { runContributedTool } from './plugins/agentTools';
-import { EditorHistory } from './engine/EditorHistory';
import { SceneModel } from './engine/SceneModel';
import { EngineHost } from './engine/EngineHost';
import { Particle, getComponent } from 'esengine';
@@ -118,6 +117,27 @@ function documentState(): { kind: 'scene' | 'prefab'; path: string | null; name:
return { kind: 'scene', path: st?.currentScene ?? null, name: st?.name ?? null, dirty };
}
+/**
+ * Refuse a document swap that would throw away unsaved work, unless the caller
+ * says to throw it away.
+ *
+ * Every door that replaces the open document asks this ONE question, and the
+ * answer comes from the registry — the scene AND every open asset editor — never
+ * from one document. discardGuard states that rule for the UI prompts ("not just
+ * the scene's EditorHistory"), and four doors here each restated it by hand until
+ * one of them drifted: `openScene` asked EditorHistory alone, so opening a scene
+ * over an unsaved tileset or material graph was refused through open_asset and
+ * waved through here.
+ *
+ * A person gets a prompt for this. A driver gets a refusal, because a modal with
+ * nobody to answer it never resolves — so discarding is something the caller says
+ * out loud instead.
+ */
+function requireDiscardable(discardChanges: boolean, what: string): void {
+ if (discardChanges || !DirtyRegistry.isDirty()) return;
+ throw new Error(`${what} would discard unsaved changes — save first, or pass discardChanges to throw them away`);
+}
+
/**
* What the editor is set up as, for the agent's per-turn context.
*
@@ -206,15 +226,9 @@ function buildEditorAutomation(): unknown {
* their own get_scene_tree polling): waits out the model-version bump the
* adopt performs, racing the engine boot on a freshly opened project. */
openScene: async (rel: string, discardChanges = false) => {
- // A person gets a "save your work?" prompt here. A driver got silence and
- // lost whatever it had built — opening the scene it had just authored into
- // reloads it from disk, and the hundred entities never written are gone.
- // Refuse instead, and make discarding something the caller says out loud.
- if (!discardChanges && EditorHistory.isDirty()) {
- throw new Error(
- 'the open scene has unsaved changes — save_scene first, or pass discardChanges to throw them away',
- );
- }
+ // Opening a scene reloads from disk, so anything just authored and never
+ // written is gone. A driver used to get silence and lose it.
+ requireDiscardable(discardChanges, `opening ${rel}`);
await openSceneAwaited(rel);
// Say so when nothing opened. The open path can leave the document empty —
// an editor whose project fell out from under it answers every read with
@@ -481,17 +495,18 @@ function buildEditorAutomation(): unknown {
+ 'external program. Read or write it as text instead (read_project_file / write_project_file).',
);
}
- // A scene or prefab REPLACES the document, and both take `discardChanges` all the
- // way down. An asset editor prompts about ITS OWN document, which nothing here can
- // answer for — so it opens only from a clean state.
+ // A scene or prefab REPLACES the document, and both take `discardChanges` all
+ // the way down. An asset editor prompts about ITS OWN document, which nothing
+ // here can answer for — so it opens only from a clean state, and no
+ // `discardChanges` will buy its way past that.
const swapsDocument = type === 'scene' || type === 'prefab';
- if (DirtyRegistry.isDirty() && !(swapsDocument && discardChanges)) {
- throw new Error(swapsDocument
- ? `opening ${path} would discard unsaved changes — save first, or pass discardChanges to throw them away`
- : `save the open documents before opening ${path} — an asset editor asks about its own unsaved changes, `
- + 'and that prompt has nobody to answer it here',
+ if (!swapsDocument && DirtyRegistry.isDirty()) {
+ throw new Error(
+ `save the open documents before opening ${path} — an asset editor asks about its own unsaved changes, `
+ + 'and that prompt has nobody to answer it here',
);
}
+ requireDiscardable(discardChanges, `opening ${path}`);
if (type === 'prefab') {
await ProjectStore.openPrefab(path, { discardChanges: true });
const doc = documentState();
@@ -560,9 +575,7 @@ function buildEditorAutomation(): unknown {
if (!ProjectStore.getSnapshot()?.prefabEdit) {
throw new Error('not editing a prefab — nothing to leave (see get_document)');
}
- if (!discardChanges && DirtyRegistry.isDirty()) {
- throw new Error('the prefab has unsaved changes — save first, or pass discardChanges to throw them away');
- }
+ requireDiscardable(discardChanges, 'leaving Prefab Mode');
await ProjectStore.exitPrefabMode({ discardChanges: true });
return documentState();
},
@@ -570,9 +583,7 @@ function buildEditorAutomation(): unknown {
* Prefab") — the door that needs no ref→path lookup by the caller. */
editPrefab: async (entity: number, discardChanges = false) => {
requireInstance(entity);
- if (!discardChanges && DirtyRegistry.isDirty()) {
- throw new Error('editing the prefab would discard unsaved changes — save first, or pass discardChanges');
- }
+ requireDiscardable(discardChanges, 'editing the prefab');
await ProjectStore.editPrefabOfInstance(entity, { discardChanges: true });
const doc = documentState();
if (doc.kind !== 'prefab') {
diff --git a/package.json b/package.json
index 81d821cb3..2d62fc228 100644
--- a/package.json
+++ b/package.json
@@ -17,7 +17,7 @@
"emsdk:setup": "node build-tools/toolchain/setup-emsdk.js",
"asset-meta": "node tools/asset-meta.js",
"migrate-asset-refs": "node tools/migrate-asset-refs.js",
- "verify": "pnpm --filter ./sdk exec tsc --noEmit && node tools/api-surface.mjs --check && node tools/check-cycles.mjs && node tools/check-layers.mjs && node tools/check-project-settings.mjs && node tools/check-workflows.mjs && node tools/check-tool-calls.mjs && node tools/check-inspector-door.mjs && node tools/component-reference.mjs --check",
+ "verify": "pnpm --filter ./sdk exec tsc --noEmit && node tools/api-surface.mjs --check && node tools/check-cycles.mjs && node tools/check-layers.mjs && node tools/check-project-settings.mjs && node tools/check-workflows.mjs && node tools/check-tool-calls.mjs && node tools/check-inspector-door.mjs && node tools/check-dirty-source.mjs && node tools/component-reference.mjs --check",
"perf": "node tools/perf-guard.mjs --check",
"prepare": "git config core.hooksPath .githooks || true"
},
diff --git a/tools/check-dirty-source.mjs b/tools/check-dirty-source.mjs
new file mode 100644
index 000000000..32891a447
--- /dev/null
+++ b/tools/check-dirty-source.mjs
@@ -0,0 +1,75 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file check-dirty-source.mjs — "is there unsaved work" has one answer.
+ *
+ * The editor holds several documents at once: the scene, and every open asset
+ * editor (tileset, flipbook, FSM, behaviour tree, material graph, timeline).
+ * Each tracks its own dirt; DirtyRegistry aggregates them, and discardGuard says
+ * the rule outright — a guard reads "the DirtyRegistry aggregate (scene + every
+ * open asset editor), NOT just the scene's EditorHistory".
+ *
+ * Four doors in the automation surface each restated that rule by hand, and one
+ * drifted: `open_scene` asked EditorHistory alone, so opening a scene over an
+ * unsaved material graph was refused through `open_asset` and waved through here
+ * — same operation, opposite answers, and no failure anywhere to notice. They go
+ * through one `requireDiscardable` now, and this keeps it that way.
+ *
+ * The rule: the AUTOMATION SURFACE may not read a single document's dirty state.
+ * It is the surface with no human to prompt, so a wrong answer there is silent
+ * data loss rather than a dialog someone can cancel.
+ *
+ * NARROW, on the evidence of check-layers. It does not police EditorHistory
+ * everywhere — asking one document about itself is legitimate and common: the
+ * scene registers into the aggregate with it (dirtyDocs), reloading the scene
+ * from disk discards only the scene's edits (ProjectStore), and the Save command
+ * asks the panel it is about (editorCommands). Those are per-document questions
+ * with a person present. This checks the one file where neither is true.
+ */
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join, resolve, relative } from 'node:path';
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+
+/** The automation surface: what MCP and the built-in agent drive the editor through. */
+const SURFACE = join(ROOT, 'desktop', 'src', 'main.tsx');
+/** Where the aggregate is defined, and where the rule is written down. */
+const REGISTRY = join(ROOT, 'desktop', 'src', 'document', 'DirtyRegistry.ts');
+const GUARD = join(ROOT, 'desktop', 'src', 'project', 'discardGuard.ts');
+
+for (const f of [SURFACE, REGISTRY, GUARD]) {
+ try {
+ readFileSync(f, 'utf8');
+ } catch {
+ console.error(`check-dirty-source: STALE — ${relative(ROOT, f)} does not exist.`);
+ console.error(' Update SURFACE/REGISTRY/GUARD to name the files that hold the rule.');
+ process.exit(1);
+ }
+}
+
+const stripComments = (s) => s.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^[ \t]*\/\/.*$/gm, '');
+
+// The aggregate must still BE an aggregate: a registry that stopped reading the
+// scene would make every guard below it pass while seeing nothing.
+if (!/EditorHistory/.test(readFileSync(join(ROOT, 'desktop', 'src', 'document', 'dirtyDocs.ts'), 'utf8'))) {
+ console.error('check-dirty-source: STALE — dirtyDocs no longer registers the scene into DirtyRegistry.');
+ process.exit(1);
+}
+
+const src = stripComments(readFileSync(SURFACE, 'utf8'));
+const violations = [];
+src.split(/\r?\n/).forEach((line, i) => {
+ if (/\bEditorHistory\b/.test(line)) violations.push({ line: i + 1, text: line.trim() });
+});
+
+if (violations.length) {
+ console.error(`check-dirty-source: the automation surface reads one document's dirty state (${violations.length})`);
+ for (const v of violations) console.error(` ${relative(ROOT, SURFACE)}:${v.line} ${v.text.slice(0, 100)}`);
+ console.error('\n A door that swaps the open document calls requireDiscardable, which asks');
+ console.error(' DirtyRegistry — the scene AND every open asset editor. One document\'s');
+ console.error(' history is not that answer; see discardGuard.ts.');
+ process.exit(1);
+}
+
+console.log('check-dirty-source: the automation surface asks the registry, not one document.');