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.

feat(editor): surface stale prefab-instance overrides + one-click clean-up (P2 UX)

yhh12431be2621e
diff --git a/desktop/src/i18n/messages/details.ts b/desktop/src/i18n/messages/details.ts
index 5dce02563..ab2bbb4af 100644
--- a/desktop/src/i18n/messages/details.ts
+++ b/desktop/src/i18n/messages/details.ts
@@ -202,6 +202,15 @@ export const detailsMessages = defineMessages({
'det.id': { en: 'ID', zh: 'ID' },
'det.prefabEdit': { en: 'Edit', zh: '编辑' },
'det.prefabEditTip': { en: 'Open this prefab in Prefab Mode', zh: '在预制体模式中打开此预制体' },
+ 'det.staleOverrides': {
+ en: '{count} override(s) no longer match the prefab — dropped',
+ zh: '{count} 处覆盖已与预制体不符,已被丢弃',
+ },
+ 'det.staleRepair': { en: 'Repair', zh: '修复' },
+ 'det.staleRepairTip': {
+ en: 'Save the scene to remove these stale overrides from the file',
+ zh: '保存场景以从文件中移除这些失效覆盖',
+ },
'det.prefabSelect': { en: 'Select', zh: '选择' },
'det.prefabSelectTip': { en: 'Select the prefab asset in the Content Browser', zh: '在内容浏览器中选中该预制体资产' },
'det.prefabApply': { en: 'Apply', zh: '应用' },
diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.ts
index 6c96ccdd8..607c929d0 100644
--- a/desktop/src/i18n/messages/project.ts
+++ b/desktop/src/i18n/messages/project.ts
@@ -133,6 +133,10 @@ export const projectMessages = defineMessages({
'proj.prefabCreated': { en: 'Created prefab: {name}', zh: '已创建预制体:{name}' },
'proj.variantCreated': { en: 'Created variant {name}', zh: '已创建变体 {name}' },
'proj.variantNoRemove': { en: "Variant can't remove base entities — {count} removal(s) dropped", zh: '变体无法删除基础实体——已忽略 {count} 处删除' },
+ 'proj.staleOverrides': {
+ en: '{overrides} override(s) on {instances} prefab instance(s) no longer match the prefab and were dropped',
+ zh: '{instances} 个预制体实例上的 {overrides} 处覆盖已与预制体不符,已被丢弃',
+ },
'proj.saveSortingLayersFailed': { en: 'Failed to save sorting layers', zh: '保存排序层失败' },
'proj.saveDesignResolutionFailed': { en: 'Failed to save design resolution', zh: '保存设计分辨率失败' },
'proj.savePackagingFailed': { en: 'Failed to save packaging settings', zh: '保存打包设置失败' },
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsx
index 56362c143..083628d12 100644
--- a/desktop/src/panels/Details.tsx
+++ b/desktop/src/panels/Details.tsx
@@ -3,6 +3,7 @@
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import type { KeyboardEvent as ReactKeyboardEvent, MouseEvent as ReactMouseEvent, ReactNode } from 'react';
import {
+ AlertTriangle,
Box,
Camera,
Check,
@@ -40,6 +41,7 @@ import { Toasts } from '@/store/Toasts';
import { baseName, assetTypeOf, IMAGE_RE } from '@/project/assetMeta';
import { revealAsset } from '@/project/assetReveal';
import { useSelection } from '@/store/selectionStore';
+import { usePrefabConflicts } from '@/store/prefabConflicts';
import { useEditorStore } from '@/store/editorStore';
import { useControllerStore } from '@/store/controllerStore';
import { isGeared, controllerCurrentPage, readModelField, readGearBindings } from '@/controller/controllerModel';
@@ -2787,6 +2789,7 @@ function EditorDetails() {
const selectedAsset = useSelection((s) => s.selectedAsset);
const inspectSource = useSelection((s) => s.inspectSource);
const selectedFolder = useOutliner((s) => s.selectedFolder);
+ const conflictsByInstance = usePrefabConflicts((s) => s.byInstance);
const ready = engine.status === 'ready' && selectedId != null;
// Selection targets, primary (the active id) first. Edits fan out across all.
@@ -2878,6 +2881,10 @@ function EditorDetails() {
? prefabTag.prefab ?? SceneModel.prefabTag(prefabTag.instanceRoot)?.prefab
: undefined;
const prefabName = prefabRef ? ProjectStore.assetInfo(prefabRef)?.name ?? null : null;
+ // Stale overrides the loader dropped from THIS instance on load (keyed by root).
+ const staleOverrides = prefabTag
+ ? conflictsByInstance.get(prefabTag.instanceRoot) ?? []
+ : [];
return (
<div className="insp">
@@ -2968,6 +2975,15 @@ function EditorDetails() {
</span>
</div>
)}
+ {staleOverrides.length > 0 && !multi && (
+ <div className="prefab-conflicts" title={staleOverrides.map((s) => s.reason).join('\n')}>
+ <span className="pc-icon"><AlertTriangle size={13} strokeWidth={1.9} /></span>
+ <span className="pc-text">{t('det.staleOverrides', { count: staleOverrides.length })}</span>
+ <button type="button" className="pc-fix" title={t('det.staleRepairTip')} onClick={() => void ProjectStore.save()}>
+ {t('det.staleRepair')}
+ </button>
+ </div>
+ )}
</div>
<div className="insp-addrow">
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index aace906b4..02b94cb70 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -1,9 +1,9 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { createStore } from 'zustand/vanilla';
-import { getComponent, getEditorType, Assets, migratePrefabData, extractPrefab, flattenPrefab, collectExternalEntityRefs, collapseInstance, applyDeltaToSource, buildVariant, setTextureParams, TextureFilter, TextureWrap, Renderer, RETIRED_COMPONENT_TYPES, parseThemeOverrides } from 'esengine';
+import { getComponent, getEditorType, Assets, migratePrefabData, extractPrefab, flattenPrefab, collectExternalEntityRefs, collapseInstance, applyDeltaToSource, buildVariant, validateOverrides, setTextureParams, TextureFilter, TextureWrap, Renderer, RETIRED_COMPONENT_TYPES, parseThemeOverrides } from 'esengine';
import { readTextureImportSettings } from './assetImporter';
-import type { SceneData, PrefabData, ExtractEntity, ProcessedEntity, PhysicsPluginConfig, AudioProjectConfig, AssetsData, ThemeOverrides } from 'esengine';
+import type { SceneData, PrefabData, ExtractEntity, ProcessedEntity, PhysicsPluginConfig, AudioProjectConfig, AssetsData, ThemeOverrides, StaleOverride, PrefabOverride } from 'esengine';
import { EngineHost } from '@/engine/EngineHost';
import { applyWidgetTheme } from '@/engine/widgetTheme';
import { bootProfiler } from '@/engine/bootProfiler';
@@ -22,6 +22,7 @@ import { setAssetRefProblemResolver } from '@/engine/EditorControlSurface';
import { installSpineSync, type SpineTransport } from '@/engine/spineSync';
import { SceneStore } from '@/engine/SceneStore';
import { useSelection } from '@/store/selectionStore';
+import { usePrefabConflicts } from '@/store/prefabConflicts';
import { Toasts } from '@/store/Toasts';
import { confirmDiscard } from './discardGuard';
import { confirm } from '@/components/confirm';
@@ -510,6 +511,9 @@ class ProjectStoreImpl {
// Edit-world live theme: re-resolve ThemeStyle-tagged widgets against the
// project's effective theme, matching what a shipped runtime boots with.
applyWidgetTheme(this.uiTheme(), this.uiThemeOverrides());
+ // Surface any instance overrides the loader just dropped (they point at prefab
+ // structure that no longer exists) — otherwise the customization loss is silent.
+ this.detectPrefabConflicts(raw);
// Loading a scene always leaves Prefab Mode (if it was active).
this.prefabSession = null;
this.store.setState({ project: { ...st, currentScene: rel, prefabEdit: null } });
@@ -557,6 +561,7 @@ class ProjectStoreImpl {
installSpineSync(this.spineTransport());
Reconciler.adopt(blank, blank); // no @uuid: refs → resolved === raw
EngineHost.syncEditorViewToScene();
+ usePrefabConflicts.getState().clear();
this.prefabSession = null;
this.store.setState({ project: { ...st, currentScene: null, prefabEdit: null } });
}
@@ -952,6 +957,37 @@ class ProjectStoreImpl {
* instance resolves its base the same way in both. */
private prefabResolverSync = (ref: string): PrefabData | null => this.prefabCache.get(ref) ?? null;
+ /**
+ * Scan a raw scene's prefab-instance entries for STALE overrides — ones that
+ * target an entity / component the prefab no longer has. The loader silently
+ * drops them (the customization vanishes with no trace), so record them per
+ * instance root ({@link usePrefabConflicts}) for the Inspector to surface. Only
+ * FLAT bases are checked: validateOverrides is structural, so a variant / nested
+ * base (whose inherited entities live in ITS base) would false-positive.
+ */
+ private detectPrefabConflicts(raw: SceneData): void {
+ const byInstance = new Map<number, StaleOverride[]>();
+ for (const e of raw.entities as unknown[]) {
+ const entry = e as { id?: number; prefab?: string; overrides?: PrefabOverride[] };
+ if (typeof entry.prefab !== 'string' || !entry.overrides?.length || typeof entry.id !== 'number') continue;
+ const base = this.prefabCache.get(entry.prefab);
+ if (!base || base.basePrefab || base.entities.some((be) => be.nestedPrefab)) continue;
+ const { stale } = validateOverrides(base, { instanceOverrides: entry.overrides });
+ if (stale.length > 0) byInstance.set(entry.id, stale);
+ }
+ usePrefabConflicts.getState().setAll(byInstance);
+ const total = usePrefabConflicts.getState().total;
+ if (total > 0) {
+ console.warn(
+ `[prefab] ${total} stale override(s) on ${byInstance.size} instance(s) reference prefab ` +
+ `structure that no longer exists — dropped on load. Select an affected instance to review, ` +
+ `or save to persist the cleanup.`,
+ );
+ Toasts.push(t('proj.staleOverrides', { overrides: total, instances: byInstance.size }), 'warn', 4500);
+ }
+ }
+
+
/**
* Instantiate a `.esprefab` (by project-relative path) into the open scene
* under `parent`, optionally placed at `position` (world coords). Selects the
@@ -2012,6 +2048,7 @@ class ProjectStoreImpl {
}
EditorHistory.clearScene();
useSelection.getState().select(null);
+ usePrefabConflicts.getState().clear(); // a prefab document has no scene instances
Reconciler.setAssetResolver((ref) => this.handleForRef(ref));
Reconciler.setRefPathResolver((ref) => this.resolveRef(ref));
Reconciler.setAssetTouchListener((ref, slot) => this.hotLoadAsset(ref, slot));
@@ -2151,6 +2188,9 @@ class ProjectStoreImpl {
await this.writeScene(st.currentScene, await this.serializeCurrent());
await this.persistLastScene(st.currentScene);
EditorHistory.markSaved();
+ // The written scene is collapsed from the clean model — the stale overrides
+ // the loader dropped are gone from the file now, so the warnings can clear.
+ usePrefabConflicts.getState().clear();
Toasts.push(t('proj.savedScene', { name: st.currentScene.split('/').pop() ?? st.currentScene }), 'success');
void this.captureThumbnail();
}
@@ -2161,6 +2201,7 @@ class ProjectStoreImpl {
await this.writeScene(relPath, await this.serializeCurrent());
await this.persistLastScene(relPath);
EditorHistory.markSaved();
+ usePrefabConflicts.getState().clear();
Toasts.push(t('proj.savedScene', { name: relPath.split('/').pop() ?? relPath }), 'success');
void this.captureThumbnail();
}
diff --git a/desktop/src/store/prefabConflicts.ts b/desktop/src/store/prefabConflicts.ts
new file mode 100644
index 000000000..ee3bccda0
--- /dev/null
+++ b/desktop/src/store/prefabConflicts.ts
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file prefabConflicts.ts — stale prefab-instance overrides detected on scene
+ * load (via the SDK `validateOverrides`). An instance override that points
+ * at an entity / component the prefab no longer has can't be applied — the
+ * loader silently drops it, so a customization vanishes with no trace. This
+ * store records what was dropped, keyed by the instance root's source id,
+ * so the Inspector can surface it and offer a one-click clean-up (a save
+ * persists the already-dropped state).
+ */
+import { create } from 'zustand';
+import type { StaleOverride } from 'esengine';
+
+interface PrefabConflictState {
+ /** Instance root source id → the stale overrides dropped on load. Empty = none. */
+ byInstance: Map<number, StaleOverride[]>;
+ /** Total dropped overrides across all instances (toast / summary count). */
+ total: number;
+ setAll: (byInstance: Map<number, StaleOverride[]>) => void;
+ /** Forget one instance's conflicts (after it's repaired / its subtree removed). */
+ clearInstance: (rootId: number) => void;
+ clear: () => void;
+}
+
+const countAll = (m: Map<number, StaleOverride[]>): number => {
+ let n = 0;
+ for (const v of m.values()) n += v.length;
+ return n;
+};
+
+export const usePrefabConflicts = create<PrefabConflictState>((set) => ({
+ byInstance: new Map(),
+ total: 0,
+ setAll: (byInstance) => set({ byInstance, total: countAll(byInstance) }),
+ clearInstance: (rootId) =>
+ set((s) => {
+ if (!s.byInstance.has(rootId)) return s;
+ const byInstance = new Map(s.byInstance);
+ byInstance.delete(rootId);
+ return { byInstance, total: countAll(byInstance) };
+ }),
+ clear: () => set({ byInstance: new Map(), total: 0 }),
+}));
diff --git a/desktop/src/theme/inspector.css b/desktop/src/theme/inspector.css
index 240f8ebb6..fee48d3d8 100644
--- a/desktop/src/theme/inspector.css
+++ b/desktop/src/theme/inspector.css
@@ -48,6 +48,15 @@
.prefab-bar button { display: inline-flex; align-items: center; gap: 3px; font-size: var(--fs-2xs); color: var(--acc-hi); padding: 2px 6px; border-radius: var(--r-xs); transition: background var(--t-fast); }
.prefab-bar button:hover { background: var(--acc-soft-2); }
+/* Stale-override warning: instance overrides the loader dropped because they no
+ longer match the prefab. Amber, sits just under the prefab bar; the button
+ saves (persisting the already-dropped state so the file is clean). */
+.prefab-conflicts { display: flex; align-items: center; gap: 7px; margin-top: 5px; padding: 5px 8px; background: color-mix(in srgb, var(--warn) 12%, transparent); border: 1px solid color-mix(in srgb, var(--warn) 40%, transparent); border-radius: var(--r-sm); font-size: var(--fs-xs); }
+.prefab-conflicts .pc-icon { color: var(--warn); flex-shrink: 0; display: grid; place-items: center; }
+.prefab-conflicts .pc-text { color: var(--text); flex: 1; }
+.prefab-conflicts .pc-fix { flex-shrink: 0; font-size: var(--fs-2xs); font-weight: 600; color: var(--warn); padding: 2px 8px; border-radius: var(--r-xs); border: 1px solid color-mix(in srgb, var(--warn) 45%, transparent); transition: background var(--t-fast); }
+.prefab-conflicts .pc-fix:hover { background: color-mix(in srgb, var(--warn) 18%, transparent); }
+
/* component / category */
.comp { border-bottom: 1px solid var(--border); }
.comp-head { display: flex; align-items: center; gap: 7px; height: 30px; padding: 0 8px 0 0; background: var(--srf-3); cursor: pointer; position: relative; user-select: none; transition: background var(--t-fast); }