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(prefab): stop apply/flatten leaking dangling & external entity refs

esenginec7332025f256
diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.ts
index a5556c57f..7d8fb68e9 100644
--- a/desktop/src/i18n/messages/project.ts
+++ b/desktop/src/i18n/messages/project.ts
@@ -103,6 +103,7 @@ export const projectMessages = defineMessages({
'proj.sdkTypesFailed': { en: 'SDK types staging failed — the IDE cannot resolve "esengine": {message}', zh: 'SDK 类型入驻失败——IDE 将无法解析 "esengine":{message}' },
'proj.prefabLoadFailed': { en: 'Could not load prefab: {name}', zh: '无法加载预制体:{name}' },
'proj.saveAsInPrefabMode': { en: 'Save As isn’t available while editing a prefab — use Save Prefab, or go Back to the scene first.', zh: '编辑预制体时无法使用"另存为"——请用"保存预制体",或先返回场景。' },
+ 'proj.returnSceneGone': { en: 'The scene “{name}” is no longer available — opened a blank scene instead.', zh: '场景"{name}"已不存在——已改为打开空白场景。' },
'proj.noOverrides': { en: 'No overrides to apply', zh: '没有可应用的覆盖' },
'proj.applyWriteFailed': { en: 'Apply failed: could not write {name}', zh: '应用失败:无法写入 {name}' },
'proj.appliedOverride': { en: 'Applied {count} override to {name}', zh: '已将 {count} 项覆盖应用到 {name}' },
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index fcc240712..1b99b34c3 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -1929,6 +1929,13 @@ class ProjectStoreImpl {
* an untitled scene (no `currentScene` path to recover into).
*/
async snapshotScene(): Promise<DocSnapshot | null> {
+ // Prefab Mode holds a prefab tree, not a scene (currentScene is null) — snapshot
+ // the prefab to its own path so a crash mid-edit is recoverable, not silently lost.
+ if (this.prefabSession) {
+ const built = this.buildSessionPrefab(this.prefabSession);
+ if (!built) return null;
+ return { path: this.prefabSession.path, contents: JSON.stringify(built.prefab, null, 2) + '\n' };
+ }
const st = this.state;
if (!st?.currentScene) return null;
return { path: st.currentScene, contents: JSON.stringify(await this.serializeCurrent(), null, 2) + '\n' };
@@ -2067,15 +2074,18 @@ class ProjectStoreImpl {
* instead collapses the edited tree against its base into a variant delta
* (keeping basePrefab), so editing a variant stays base-tracked.
*/
- async savePrefab(): Promise<void> {
- const pe = this.prefabSession;
- if (!pe) return;
+ /** Serialize the live Prefab-Mode tree to a {@link PrefabData} without touching
+ * UI or store state — shared by {@link savePrefab} and the crash snapshot.
+ * `removedCount` is the number of base entities a variant edit dropped (a
+ * variant cannot delete a base entity), for the caller to surface. */
+ private buildSessionPrefab(
+ pe: NonNullable<typeof this.prefabSession>,
+ ): { prefab: PrefabData; idBySource: Map<number, string>; removedCount: number } | null {
const model = SceneModel.serialize();
- if (!model) return;
+ if (!model) return null;
const idBySource = new Map(pe.idBySource);
for (const e of model.entities) if (!idBySource.has(e.id)) idBySource.set(e.id, crypto.randomUUID());
- let prefab: PrefabData;
if (pe.base && pe.baseRef) {
// VARIANT: diff the edited tree against the flat base → the variant's own
// overrides + additions, then rebuild the variant (basePrefab preserved).
@@ -2090,16 +2100,25 @@ class ProjectStoreImpl {
}));
const delta = collapseInstance(pe.base, pe.baseRef, processed, this.prefabResolverSync);
const overrides = delta.overrides.filter((o) => o.type !== 'metadata_set' && o.type !== 'metadata_removed');
- if (delta.removed.length > 0) Toasts.push(t('proj.variantNoRemove', { count: delta.removed.length }), 'warn');
- prefab = buildVariant(pe.base, pe.baseRef, pe.name, { overrides, added: delta.added });
- } else {
- prefab = extractPrefab(
- model.entities as unknown as ExtractEntity[],
- pe.rootSource,
- pe.name,
- (srcId) => idBySource.get(srcId) ?? crypto.randomUUID(),
- );
- }
+ const prefab = buildVariant(pe.base, pe.baseRef, pe.name, { overrides, added: delta.added });
+ return { prefab, idBySource, removedCount: delta.removed.length };
+ }
+ const prefab = extractPrefab(
+ model.entities as unknown as ExtractEntity[],
+ pe.rootSource,
+ pe.name,
+ (srcId) => idBySource.get(srcId) ?? crypto.randomUUID(),
+ );
+ return { prefab, idBySource, removedCount: 0 };
+ }
+
+ async savePrefab(): Promise<void> {
+ const pe = this.prefabSession;
+ if (!pe) return;
+ const built = this.buildSessionPrefab(pe);
+ if (!built) return;
+ const { prefab, idBySource, removedCount } = built;
+ if (removedCount > 0) Toasts.push(t('proj.variantNoRemove', { count: removedCount }), 'warn');
try {
await window.estella.fs.write(pe.path, JSON.stringify(prefab, null, 2) + '\n');
} catch {
@@ -2122,11 +2141,19 @@ class ProjectStoreImpl {
const st = this.state;
if (st) this.store.setState({ project: { ...st, prefabEdit: null } });
if (back) {
- await this.openScene(back, { quiet: true });
- // Reframe to where the user was before entering (openScene reseeds the view
- // from the scene camera; this puts their pan/zoom back).
- if (returnView) EngineHost.setEditorView(returnView);
- Toasts.push(t('proj.returnedScene', { name: back.split('/').pop() ?? back }), 'info', 1600);
+ try {
+ // The return scene may have been deleted or renamed while we edited the
+ // prefab; an unguarded load would reject and strand the editor showing the
+ // prefab tree with prefabSession already cleared. Fall back to a blank scene.
+ await this.openScene(back, { quiet: true });
+ // Reframe to where the user was before entering (openScene reseeds the view
+ // from the scene camera; this puts their pan/zoom back).
+ if (returnView) EngineHost.setEditorView(returnView);
+ Toasts.push(t('proj.returnedScene', { name: back.split('/').pop() ?? back }), 'info', 1600);
+ } catch {
+ await this.newScene();
+ Toasts.push(t('proj.returnSceneGone', { name: back.split('/').pop() ?? back }), 'warn');
+ }
} else {
await this.newScene();
}
diff --git a/sdk/src/prefab/entityRef.ts b/sdk/src/prefab/entityRef.ts
index 576f8c860..9990e8c12 100644
--- a/sdk/src/prefab/entityRef.ts
+++ b/sdk/src/prefab/entityRef.ts
@@ -24,9 +24,12 @@ export function remapComponentEntityRefs(
const value = comp.data[field];
if (typeof value === 'string') {
const mapped = idMapping.get(value);
- if (mapped !== undefined) {
- comp.data[field] = mapped;
- }
+ // An unresolved string is a DANGLING prefab-local ref (its target
+ // was deleted, or a stale Apply left it behind). Clear it to
+ // INVALID_ENTITY rather than leaking a string into a field the
+ // runtime/World reads as a numeric entity id (an ABI/type fault on
+ // spawn). Mirrors captureEntityRefs, which clears external refs.
+ comp.data[field] = mapped !== undefined ? mapped : INVALID_ENTITY;
} else if (typeof value === 'number' && value !== INVALID_ENTITY) {
// Already a numeric id; if a caller authored components with
// numeric refs, fall back to numeric→numeric mapping for
diff --git a/sdk/src/prefab/sceneInstance.ts b/sdk/src/prefab/sceneInstance.ts
index 47056543e..9b47880d6 100644
--- a/sdk/src/prefab/sceneInstance.ts
+++ b/sdk/src/prefab/sceneInstance.ts
@@ -338,14 +338,22 @@ export interface SourceDelta {
* targets the top-level asset.
*/
export function applyDeltaToSource(source: PrefabData, delta: SourceDelta): PrefabData {
+ // An entity-ref field bound to something OUTSIDE the instance (an ExposeRef
+ // slot bound to a scene entity) collapses to a `property` override whose value
+ // is a raw runtime id — the diff leaves cross-instance refs numeric, while an
+ // intra-prefab ref normalises to a stable string id. That binding is per-INSTANCE
+ // state; baking it would hard-code one instance's scene id into the SHARED
+ // prefab. Drop those overrides here so Apply never leaks a scene id into the asset.
+ const overrides = delta.overrides.filter((o) => !isExternalEntityRefOverride(o));
+
// 1. Property / component / name / visibility / metadata overrides.
- let next = applyOverridesToSource(source, delta.overrides);
+ let next = applyOverridesToSource(source, overrides);
// 2. Re-parent overrides, BEFORE the removed-closure so an entity moved out
// of a doomed subtree survives (mirrors expandInstance). Targets among the
// source entities are re-linked; a target that is only an `added` entity is
// left in place (added is appended below and is a niche Apply case).
- const parentOverrides = delta.overrides.filter((o) => o.type === 'parent');
+ const parentOverrides = overrides.filter((o) => o.type === 'parent');
if (parentOverrides.length > 0) {
const entities = next.entities.map((e) => ({ ...e, children: [...e.children] }));
const byId = new Map<PrefabEntityId, PrefabEntityData>();
@@ -421,6 +429,16 @@ export function applyDeltaToSource(source: PrefabData, delta: SourceDelta): Pref
return next;
}
+/** True for a `property` override on an entity-ref field whose value is a raw
+ * runtime id — an ExposeRef binding to something outside the instance. Such a
+ * binding is per-instance and must not be baked into the shared prefab source. */
+function isExternalEntityRefOverride(o: PrefabOverride): boolean {
+ if (o.type !== 'property' || !o.componentType || o.propertyName === undefined) return false;
+ const def = getComponent(o.componentType);
+ if (!def || !def.entityFields.includes(o.propertyName)) return false;
+ return typeof o.value === 'number' && o.value !== INVALID_ENTITY;
+}
+
/** Walk `node`'s parent chain in a stable-id entity map; true if `ancestor` is on
* it (so re-parenting `ancestor` under `node` would create a cycle). */
function isAncestor(
diff --git a/sdk/tests/prefab-rigor.test.ts b/sdk/tests/prefab-rigor.test.ts
index 45fc8be61..45c4b9b85 100644
--- a/sdk/tests/prefab-rigor.test.ts
+++ b/sdk/tests/prefab-rigor.test.ts
@@ -772,6 +772,59 @@ describe('diffAgainstSource — entity-ref fields', () => {
});
});
+// ─── entity-ref integrity (dangling clear, external-binding no-bake) ───────
+
+describe('entity-ref integrity', () => {
+ const REF_META = { entityFields: ['target'] };
+
+ it('a dangling string entity-ref clears to INVALID_ENTITY on flatten (not a raw string)', () => {
+ defineComponent('RefHolder', { target: 0 }, REF_META);
+ const prefab: PrefabData = {
+ version: PREFAB_FORMAT_VERSION, name: 'R', rootEntityId: 'root',
+ entities: [
+ // `target: 'ghost'` references an id that isn't in the prefab.
+ { prefabEntityId: 'root', name: 'Root', parent: null, children: [], visible: true,
+ components: [{ type: 'RefHolder', data: { target: 'ghost' } }] },
+ ],
+ };
+ let n = 0;
+ const { entities } = flattenPrefab(prefab, [], { allocateId: () => n++, loadPrefab: () => null });
+ const val = (entities[0].components[0].data as { target: unknown }).target;
+ expect(val).toBe(0); // INVALID_ENTITY — never a leaked string
+ });
+
+ it('applyDeltaToSource bakes an intra-prefab ref (string) but drops an external binding (number)', () => {
+ defineComponent('RefHolder', { target: 0 }, REF_META);
+ const source: PrefabData = {
+ version: PREFAB_FORMAT_VERSION, name: 'R', rootEntityId: 'root',
+ entities: [
+ { prefabEntityId: 'root', name: 'Root', parent: null, children: ['child'], visible: true, components: [] },
+ { prefabEntityId: 'child', name: 'Child', parent: 'root', children: [], visible: true,
+ components: [{ type: 'RefHolder', data: { target: 0 } }] },
+ ],
+ };
+ const baked = applyDeltaToSource(source, {
+ overrides: [
+ // Intra-prefab ref → stable string id → SHOULD bake into the asset.
+ { prefabEntityId: 'child', type: 'property', componentType: 'RefHolder', propertyName: 'target', value: 'root' },
+ ],
+ added: [], removed: [],
+ });
+ const childData = (id: string, p: PrefabData) =>
+ (p.entities.find((e) => e.prefabEntityId === id)!.components[0].data as { target: unknown }).target;
+ expect(childData('child', baked)).toBe('root'); // intra-prefab ref baked
+
+ const bakedExternal = applyDeltaToSource(source, {
+ overrides: [
+ // External binding (a raw scene id) → per-instance → MUST NOT bake.
+ { prefabEntityId: 'child', type: 'property', componentType: 'RefHolder', propertyName: 'target', value: 4242 },
+ ],
+ added: [], removed: [],
+ });
+ expect(childData('child', bakedExternal)).toBe(0); // unchanged — scene id not leaked into the asset
+ });
+});
+
// ─── Hierarchical addressing (nested identity, sibling repeats) ────────────
describe('hierarchical addressing', () => {