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): a prefab changed on disk while open is reloaded, not overwritten

yhh6d4fcf968cef
diff --git a/desktop/scripts/editor-checks/prefab-disk-reload.mjs b/desktop/scripts/editor-checks/prefab-disk-reload.mjs
new file mode 100644
index 000000000..f6bca5d8f
--- /dev/null
+++ b/desktop/scripts/editor-checks/prefab-disk-reload.mjs
@@ -0,0 +1,110 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file prefab-disk-reload — the OPEN DOCUMENT reconciles with disk, both kinds.
+ *
+ * A scene changed on disk while open (an external editor, a git checkout, a build
+ * step) is reloaded: seamless when clean, discard-guarded when not. Prefab Mode
+ * had none of that, and the reason was one line — the watcher asked
+ * `isOpenScenePath`, which reads `currentScene`, which is null while a prefab is
+ * open. So the editor kept the tree it had flattened at open, and the next Save
+ * wrote it over whatever had arrived, without a word.
+ *
+ * Same shape as the guard that only saw the scene's dirt: the machinery existed,
+ * and the code deciding whether to run it was written per document KIND.
+ *
+ * This drives it end to end: enter Prefab Mode, rewrite the `.esprefab` from
+ * outside, and require the editor's tree to show what the file now says.
+ */
+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 = JSON.stringify({
+ version: '1.0', name: 'Main',
+ 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 } },
+ ],
+ },
+ {
+ id: 1, name: 'Turret', parent: null, children: [], visible: true,
+ components: [
+ { type: 'Transform', data: { position: { x: 0, y: 0, z: 0 } } },
+ { type: 'Sprite', data: { size: { x: 32, y: 32 }, color: { r: 1, g: 0, b: 0, a: 1 } } },
+ ],
+ },
+ ],
+}, null, 1);
+
+export const name = 'prefab-disk-reload';
+export const describes = 'a prefab rewritten on disk while open in Prefab Mode is reloaded, not overwritten';
+
+/** Poll until `read` reports true, or give up. The reload is watcher-driven —
+ * a debounce, an incremental rescan and a re-flatten — so it is not immediate. */
+async function until(ed, read, ms = 12000) {
+ const t0 = Date.now();
+ for (;;) {
+ if (await read()) return true;
+ if (Date.now() - t0 > ms) return false;
+ await ed.sleep(250);
+ }
+}
+
+export async function run(ed) {
+ const root = await makeProject({ 'assets/scenes/main.esscene': SCENE });
+ 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');
+ await ed.call('create_prefab_from_entity', { entity: 1 }, 60000);
+
+ const prefabPath = 'assets/prefabs/Turret.esprefab';
+ const before = await ed.json('read_project_file', { path: prefabPath });
+ if (!check(typeof before === 'string' && before.includes('Turret'), `no prefab at ${prefabPath}`)) {
+ return check.failures;
+ }
+
+ await ed.call('open_asset', { path: prefabPath }, 60000);
+ const doc = await ed.json('get_document', {});
+ if (!check(doc?.kind === 'prefab', `open_asset left the document as ${doc?.kind}`)) return check.failures;
+ // Entering Prefab Mode adopts a fresh document, so nothing is unsaved yet. That
+ // matters: a dirty document would put up a discard prompt with nobody to answer.
+ check(doc?.dirty === false, `Prefab Mode opened dirty (${doc?.dirty}) — the reload would prompt`);
+
+ const named = async (want) => {
+ const tree = await ed.json('get_scene_tree', {});
+ const walk = (ns) => (ns ?? []).some((n) => n.name === want || walk(n.children));
+ return walk(tree);
+ };
+ check(await named('Turret'), 'the prefab did not open showing its own entity');
+
+ // The external edit: same file, one name changed, written by someone who is not
+ // the editor's own Save.
+ await ed.call('write_project_file', {
+ path: prefabPath,
+ content: before.replace(/"Turret"/g, '"TurretReloaded"'),
+ }, 60000);
+
+ const reloaded = await until(ed, () => named('TurretReloaded'));
+ check(reloaded, 'the prefab changed on disk and Prefab Mode kept showing the stale tree');
+
+ // And the way out still works — a reload re-enters Prefab Mode, which must carry
+ // the return scene forward rather than stranding the editor on a blank one.
+ if (reloaded) {
+ const after = await ed.json('get_document', {});
+ check(after?.kind === 'prefab' && after?.path === prefabPath,
+ `after the reload the document is ${JSON.stringify({ kind: after?.kind, path: after?.path })}`);
+ await ed.call('exit_prefab_mode', { discardChanges: true }, 60000);
+ const back = await ed.json('get_document', {});
+ check(back?.kind === 'scene' && !!back?.path, `leaving Prefab Mode landed on ${JSON.stringify(back)}`);
+ }
+
+ return check.failures;
+}
diff --git a/desktop/src/project/PrefabCache.ts b/desktop/src/project/PrefabCache.ts
index f0a0c9be5..6ab61c3dc 100644
--- a/desktop/src/project/PrefabCache.ts
+++ b/desktop/src/project/PrefabCache.ts
@@ -89,6 +89,13 @@ class PrefabCacheImpl {
this.byRef.clear();
}
+ /** Drop ONE prefab, so the next {@link load} re-reads it. For a caller that
+ * knows the file changed and must not wait for the rescan that would also
+ * notice — a reload racing an eviction reads the copy it is replacing. */
+ forget(ref: string): void {
+ this.byRef.delete(ref);
+ }
+
/**
* Evict only the prefabs whose FILE changed or went away, given the paths a
* rescan reported and the set it still knows about.
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index 3d4149808..bd83dc945 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -178,8 +178,14 @@ class ProjectStoreImpl {
/** The latest scene preload result; the Reconciler resolver reads handles from
* it for entities recreated incrementally (duplicate / undo / play-stop). */
private lastAssetResult: PreloadResult | null = null;
- private knownSceneText: string | null = null;
- private knownScenePath: string | null = null;
+ /** What the OPEN DOCUMENT looked like on disk the last time we read or wrote it —
+ * a scene, or the `.esprefab` being edited in Prefab Mode. It answers one
+ * question, "was that change ours", and it is per-document rather than
+ * per-scene because both kinds are edited in the same world and overwritten by
+ * the same Save. While it tracked only the scene, an external edit to a prefab
+ * open in Prefab Mode was invisible and Save silently overwrote it. */
+ private diskText: string | null = null;
+ private diskPath: string | null = null;
/** A disk-change discard prompt is showing — don't stack another. */
private reloadPromptOpen = false;
constructor() {
@@ -567,8 +573,8 @@ class ProjectStoreImpl {
// Loading a scene always leaves Prefab Mode (if it was active).
this.prefabSession = null;
this.store.setState({ project: { ...st, currentScene: rel, prefabEdit: null } });
- this.knownSceneText = text;
- this.knownScenePath = rel;
+ this.diskText = text;
+ this.diskPath = rel;
}
/** A fresh, untitled scene document: a single orthographic Camera at the origin. */
@@ -2082,8 +2088,8 @@ class ProjectStoreImpl {
private async writeScene(relPath: string, data: SceneData): Promise<void> {
const body = JSON.stringify(data, null, 2) + '\n';
await window.estella.fs.write(relPath, body);
- this.knownSceneText = body;
- this.knownScenePath = relPath;
+ this.diskText = body;
+ this.diskPath = relPath;
}
/**
@@ -2189,6 +2195,11 @@ class ProjectStoreImpl {
ViewportController.frameSelection(content);
};
requestAnimationFrame(() => requestAnimationFrame(frameContent));
+ // Seed the disk baseline from the file we just opened, so the first external
+ // change to it is recognised as one — and a watcher event that carries no
+ // actual change (a touch, a `.meta` write beside it) is not mistaken for one.
+ this.diskText = await window.estella.fs.read(path).catch(() => null);
+ this.diskPath = path;
const returnLeaf = returnScene ? (returnScene.split('/').pop() ?? returnScene) : null;
const baseRef = prefab.basePrefab ?? null;
this.prefabSession = { ref, path, name: prefab.name, rootSource: rootId, idBySource, returnScene, returnView, returnSelection, base, baseRef };
@@ -2296,12 +2307,18 @@ class ProjectStoreImpl {
if (!built) return;
const { prefab, idBySource, removedCount } = built;
if (removedCount > 0) Toasts.push(t('proj.variantNoRemove', { count: removedCount }), 'warn');
+ const body = JSON.stringify(prefab, null, 2) + '\n';
try {
- await window.estella.fs.write(pe.path, JSON.stringify(prefab, null, 2) + '\n');
+ await window.estella.fs.write(pe.path, body);
} catch {
Toasts.push(t('proj.applyWriteFailed', { name: pe.path.split('/').pop() ?? pe.path }), 'error');
return;
}
+ // Our own write is not an external change — record it, or the watcher fires
+ // and offers to reload the file we just produced. `writeScene` does the same
+ // for a scene; this is the prefab half of the same rule.
+ this.diskText = body;
+ this.diskPath = pe.path;
PrefabCache.put(pe.ref, prefab);
this.prefabSession = { ...pe, idBySource };
EditorHistory.markSaved();
@@ -2341,27 +2358,43 @@ class ProjectStoreImpl {
}
}
- /** True if the changed paths include the open scene document. */
- isOpenScenePath(paths: readonly string[]): boolean {
- const cur = this.state?.currentScene;
+ /** The file the editor currently has open as its document: the prefab in Prefab
+ * Mode, else the scene. One accessor, so nothing has to remember that
+ * `currentScene` is null while a prefab is open. */
+ private openDocumentPath(): string | null {
+ return this.prefabSession?.path ?? this.state?.currentScene ?? null;
+ }
+
+ /** True if the changed paths include the open document — scene or prefab. */
+ isOpenDocumentPath(paths: readonly string[]): boolean {
+ const cur = this.openDocumentPath();
if (!cur) return false;
const norm = cur.replace(/\\/g, '/');
return paths.some((p) => p.replace(/\\/g, '/') === norm);
}
/**
- * Reconcile the open scene with an on-disk change made outside the editor —
+ * Reconcile the open DOCUMENT with an on-disk change made outside the editor —
* seamless when clean, discard-guarded when there are unsaved edits. A change
- * matching our own last write (or save) is a no-op.
+ * matching our own last write (or read) is a no-op.
+ *
+ * Both kinds, because both are edited in the same world and overwritten by the
+ * same Save. This asked about the scene alone, and `currentScene` is null in
+ * Prefab Mode — so a prefab changed on disk while open was invisible, and the
+ * next Save wrote the stale tree over it without a word. Reloading a prefab is
+ * re-entering Prefab Mode on it, which re-reads and re-flattens; the session
+ * carries its own return scene and view forward, so the way out is unchanged.
*/
- async reloadOpenSceneFromDisk(): Promise<void> {
- const st = this.state;
- if (!st || !st.currentScene) return;
+ async reloadOpenDocumentFromDisk(): Promise<void> {
+ const target = this.openDocumentPath();
+ if (!this.state || !target) return;
let text: string;
- try { text = await window.estella.fs.read(st.currentScene); }
+ try { text = await window.estella.fs.read(target); }
catch { return; }
- if (text === this.knownSceneText && st.currentScene === this.knownScenePath) return;
- const name = st.currentScene.split('/').pop() ?? st.currentScene;
+ if (text === this.diskText && target === this.diskPath) return;
+ const name = target.split('/').pop() ?? target;
+ // The document's OWN history, not the aggregate: reloading this file discards
+ // this file's edits and leaves every other open editor alone.
if (EditorHistory.isDirty()) {
// The confirm is async — further disk-change events while it's open must
// not stack more dialogs for the same question.
@@ -2370,12 +2403,21 @@ class ProjectStoreImpl {
const ok = await confirmDiscard(t('discard.reloadChanged', { name }));
this.reloadPromptOpen = false;
if (!ok) {
- this.knownSceneText = text;
- this.knownScenePath = st.currentScene;
+ // Declined: adopt the new bytes as the baseline so the same change is not
+ // asked about again, and the editor keeps the edits it was told to keep.
+ this.diskText = text;
+ this.diskPath = target;
return;
}
}
- await this.loadCurrentScene();
+ if (this.prefabSession) {
+ // Re-read, don't re-use: the rescan that evicts a changed prefab runs on its
+ // own debounce, and losing that race would reload the copy being replaced.
+ PrefabCache.forget(this.prefabSession.ref);
+ await this.openPrefab(target, { discardChanges: true });
+ } else {
+ await this.loadCurrentScene();
+ }
Toasts.push(t('toast.reloadedFromDisk', { name }), 'info', 1600);
}
diff --git a/desktop/src/project/fsWatch.ts b/desktop/src/project/fsWatch.ts
index ada614641..4f33a3f55 100644
--- a/desktop/src/project/fsWatch.ts
+++ b/desktop/src/project/fsWatch.ts
@@ -81,10 +81,11 @@ export function initFsWatch(): void {
fsRefresh.bump();
}, 60);
- // The open scene changed on disk (external edit, git, build output) → reload it.
- if (ProjectStore.isOpenScenePath(paths)) {
+ // The open document — a scene, or the prefab being edited in Prefab Mode —
+ // changed on disk (external edit, git, build output) → reload it.
+ if (ProjectStore.isOpenDocumentPath(paths)) {
if (sceneDebounce) clearTimeout(sceneDebounce);
- sceneDebounce = setTimeout(() => void ProjectStore.reloadOpenSceneFromDisk(), 120);
+ sceneDebounce = setTimeout(() => void ProjectStore.reloadOpenDocumentFromDisk(), 120);
}
// An editor-plugin source edit → recompile + re-activate that plugin. Its own