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): undo entries know their document — cross-document corruption closed
esengine62e8f8855bb6
diff --git a/desktop/src/bt/BtDocument.ts b/desktop/src/bt/BtDocument.tsindex 1bb5c29ab..50b869a56 100644--- a/desktop/src/bt/BtDocument.ts+++ b/desktop/src/bt/BtDocument.ts@@ -22,4 +22,4 @@ class BtDocumentImpl extends AssetDocument<BtDefinition> {}}-export const BtDocument = new BtDocumentImpl();+export const BtDocument = new BtDocumentImpl('bt');diff --git a/desktop/src/bt/openBehaviorTree.ts b/desktop/src/bt/openBehaviorTree.tsindex 08dc6c6fd..05b086a1f 100644--- a/desktop/src/bt/openBehaviorTree.ts+++ b/desktop/src/bt/openBehaviorTree.ts@@ -8,12 +8,19 @@import { emptyBt, ensureBtIds, type BtDefinition } from 'esengine';import { BtDocument } from './BtDocument';import { ProjectStore } from '@/project/ProjectStore';+import { confirmDiscardDoc } from '@/project/discardGuard';import { dockApi } from '@/layout/dockApi';import { baseName } from '@/project/assetMeta';import { Toasts } from '@/store/Toasts';import { t } from '@/i18n';export async function openBehaviorTree(path: string): Promise<void> {+ // Already-open file: just front the panel — a reload would clobber unsaved edits.+ if (BtDocument.isOpen && BtDocument.filePath === path) {+ dockApi.openDocument('behaviortree', 'behaviortree', t('bt.tabTitle'));+ return;+ }+ if (!(await confirmDiscardDoc(BtDocument.dirty, t('discard.openAsset', { name: baseName(path) })))) return;try {const text = await window.estella.fs.read(path);// Hand-written trees may lack editor ids; assign before editing.diff --git a/desktop/src/document/AssetDocument.ts b/desktop/src/document/AssetDocument.tsindex 3c633f8ee..0e05a2055 100644--- a/desktop/src/document/AssetDocument.ts+++ b/desktop/src/document/AssetDocument.ts@@ -20,16 +20,31 @@import { createStore } from 'zustand/vanilla';import { EditorHistory } from '@/engine/EditorHistory';+import { remapAssetPath } from '@/project/pathRemap';const clone = <T>(v: T): T =>typeof structuredClone === 'function' ? structuredClone(v) : (JSON.parse(JSON.stringify(v)) as T);export class AssetDocument<T> {+ /** Every constructed document (editor documents are singletons), so a project-+ * wide event — an asset rename — can reach all open documents at once. */+ private static readonly instances = new Set<AssetDocument<unknown>>();++ static openDocuments(): AssetDocument<unknown>[] {+ return [...AssetDocument.instances].filter((d) => d.isOpen);+ }+protected _asset: T | null = null;protected _filePath: string | null = null;protected _dirty = false;private readonly store = createStore<{ revision: number }>(() => ({ revision: 0 }));+ /** `docId` tags this document's EditorHistory entries so open/close can purge+ * ONLY its own stale steps off the shared stack (see EditorHistory.purgeDoc). */+ constructor(readonly docId: string) {+ AssetDocument.instances.add(this as AssetDocument<unknown>);+ }+subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);getRevision = (): number => this.store.getState().revision;protected bump(): void {@@ -51,6 +66,9 @@ export class AssetDocument<T> {/** @internal Subclasses call this from their typed `open()`. */protected openAsset(asset: T, filePath: string | null): void {+ // A (re)opened file is a fresh document: earlier steps' snapshots belong to+ // the previous content, and replaying them here would clobber the new file.+ EditorHistory.purgeDoc(this.docId);this._asset = asset;this._filePath = filePath;this._dirty = false;@@ -64,6 +82,21 @@ export class AssetDocument<T> {this.bump();}+ /**+ * Follow an asset rename/move (`from` → `to`, file or containing folder):+ * without this a later save would write to the OLD path, resurrecting a stale+ * file. Content, dirty state, and undo history are untouched — same document,+ * new file binding. Returns whether this document was affected.+ */+ rebindPath(from: string, to: string): boolean {+ if (this._filePath == null) return false;+ const next = remapAssetPath(this._filePath, from, to);+ if (next == null) return false;+ this._filePath = next;+ this.bump();+ return true;+ }+/** Clear the dirty flag after a successful save. */markSaved(): void {if (this._dirty) {@@ -74,6 +107,8 @@ export class AssetDocument<T> {/** @internal Subclasses call this from their typed `close()`. */protected closeAsset(): void {+ // Undoing a snapshot step after close would silently resurrect the document.+ EditorHistory.purgeDoc(this.docId);this._asset = null;this._filePath = null;this._dirty = false;@@ -91,6 +126,18 @@ export class AssetDocument<T> {label,() => this.replaceAsset(after),() => this.replaceAsset(before),+ this.docId,+ );+ }++ /** Register an externally-applied whole-asset change (a live drag's+ * before/after) as ONE doc-tagged undo step. */+ recordEdit(label: string, before: T, after: T): void {+ EditorHistory.record(+ label,+ () => this.replaceAsset(after),+ () => this.replaceAsset(before),+ this.docId,);}}diff --git a/desktop/src/document/dirtyDocs.ts b/desktop/src/document/dirtyDocs.tsindex 920665c43..d4e4ee998 100644--- a/desktop/src/document/dirtyDocs.ts+++ b/desktop/src/document/dirtyDocs.ts@@ -23,8 +23,8 @@ 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).+// The scene: EditorHistory-tracked (scene-scoped — doc-tagged asset entries on+// the shared stack don't count; each asset document reports itself below).DirtyRegistry.register({id: 'scene',isDirty: () => EditorHistory.isDirty(),diff --git a/desktop/src/engine/EditorHistory.ts b/desktop/src/engine/EditorHistory.tsindex ed7316007..f5ac19f5c 100644--- a/desktop/src/engine/EditorHistory.ts+++ b/desktop/src/engine/EditorHistory.ts@@ -1,87 +1,96 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { createStore } from 'zustand/vanilla';-import { TransactionManager } from 'esengine';/**- * Editor undo/redo, built on the engine's {@link TransactionManager}.+ * Editor undo/redo. One user gesture (a field edit, a drag, a future add/delete)+ * = one entry. Mutations are applied live through `EngineHost`; the gesture's+ * owner captures before/after and calls {@link record} so the pair becomes+ * undoable without re-running the forward closure. Panels subscribe for+ * undo/redo availability.*- * One user gesture (a field edit, a drag, a future add/delete) = one entry.- * Mutations are applied live through `EngineHost`; the gesture's owner captures- * before/after and calls {@link record} so the pair becomes undoable without- * re-running the forward closure. Panels subscribe for undo/redo availability.+ * The scene AND every AssetDocument editor share one history (one Ctrl+Z), so+ * entries carry a document identity: `doc` is null for scene entries and the+ * owning AssetDocument's docId otherwise. That identity is what lets a document+ * purge ONLY its own stale steps when its file is replaced or closed+ * ({@link purgeDoc}), and lets a scene switch keep asset-doc steps alive+ * ({@link clearScene}) — asset snapshots reference no scene entities.*/const HISTORY_LIMIT = 200;+interface HistoryOp {+ forward(): void;+ reverse(): void;+}++interface HistoryEntry {+ /** Unique per edit — drives saved-point dirty tracking (see isDirty). */+ id: number;+ label: string;+ /** Owning document: null = the scene, else an AssetDocument docId. */+ doc: string | null;+ ops: HistoryOp[];+}+export class EditorHistoryImpl {- private readonly tm = new TransactionManager({ historyLimit: HISTORY_LIMIT });+ private readonly undoStack: HistoryEntry[] = [];+ private readonly redoStack: HistoryEntry[] = [];+ private seq = 0;private readonly store = createStore<{ version: number }>(() => ({ version: 0 }));- // Dirty tracking. `version` bumps on every op (drives subscriptions) but is- // monotonic, so it can't tell "back at the saved state". Instead each committed- // edit gets a unique id pushed onto a mirror of the undo stack; `savedHead` is the- // head id at the last save. dirty ⇔ head id ≠ savedHead — so undoing back to the- // saved point clears the star (UE semantics), and a fresh edit at the same depth- // does NOT (its id is new). Capped to the TM history limit so it can't grow- // unbounded; an evicted saved point just stays dirty (you can't reach it anyway).- private undoIds: number[] = [];- private redoIds: number[] = [];- private seq = 0;+ // Dirty is scene-scoped: dirty ⇔ newest SCENE entry id ≠ the id at the last+ // save. Ids (not depth) make undo-back-to-save clean while a fresh edit at+ // the same depth stays dirty (UE semantics). Asset-doc entries don't count —+ // each AssetDocument tracks its own `_dirty` for the DirtyRegistry.private savedHead: number | null = null;- private head(): number | null {- return this.undoIds.length ? this.undoIds[this.undoIds.length - 1] : null;- }- private pushEdit() {- this.undoIds.push(++this.seq);- if (this.undoIds.length > HISTORY_LIMIT) this.undoIds.shift();- this.redoIds.length = 0;+ private sceneHead(): number | null {+ for (let i = this.undoStack.length - 1; i >= 0; i--) {+ if (this.undoStack[i].doc === null) return this.undoStack[i].id;+ }+ return null;}// 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;+ // the whole gesture lands as ONE entry when the group closes.+ private groupOps: HistoryOp[] | null = null;++ private commit(label: string, ops: HistoryOp[], doc: string | null): void {+ if (ops.length === 0) return;+ this.undoStack.push({ id: ++this.seq, label, doc, ops });+ if (this.undoStack.length > HISTORY_LIMIT) this.undoStack.shift();+ this.redoStack.length = 0;+ this.bump();+ }/** Register an already-applied mutation as one undo step (forward NOT run). */- record(label: string, forward: () => void, reverse: () => void) {+ record(label: string, forward: () => void, reverse: () => void, doc: string | null = null) {if (this.groupOps) {this.groupOps.push({ forward, reverse });return;}- const tx = this.tm.begin(label);- tx.addDeferred({ forward, reverse });- this.tm.commit(tx);- this.pushEdit();- this.bump();+ this.commit(label, [{ forward, reverse }], doc);}/** Apply a not-yet-applied mutation and record it (forward runs now). */- run(label: string, forward: () => void, reverse: () => void) {+ run(label: string, forward: () => void, reverse: () => void, doc: string | null = null) {if (this.groupOps) {forward();this.groupOps.push({ forward, reverse });return;}- const tx = this.tm.begin(label);- tx.add({ forward, reverse });- this.tm.commit(tx);- this.pushEdit();- this.bump();+ forward();+ this.commit(label, [{ forward, reverse }], doc);}/** 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 }>) {+ batch(label: string, ops: ReadonlyArray<HistoryOp>, doc: string | null = null) {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);- this.tm.commit(tx);- this.pushEdit();- this.bump();+ this.commit(label, [...ops], doc);}/**@@ -92,7 +101,7 @@ export class EditorHistoryImpl {*/group<T>(label: string, fn: () => T): T {if (this.groupOps) return fn();- const ops: Array<{ forward: () => void; reverse: () => void }> = [];+ const ops: HistoryOp[] = [];this.groupOps = ops;try {return fn();@@ -102,48 +111,103 @@ export class EditorHistoryImpl {}}- undo() {- if (this.tm.undo()) {- const id = this.undoIds.pop();- if (id !== undefined) this.redoIds.push(id);- this.bump();+ // Ops run per-direction under try/catch — one broken closure must not wedge+ // the rest of the entry (matches the engine TransactionManager this replaced).+ private static apply(entry: HistoryEntry, dir: 'undo' | 'redo'): void {+ if (dir === 'undo') {+ // LIFO so ops can depend on the state left by earlier ops in the entry.+ for (let i = entry.ops.length - 1; i >= 0; i--) {+ try {+ entry.ops[i].reverse();+ } catch (e) {+ console.warn(`[history] undo op ${i} of "${entry.label}" threw`, e);+ }+ }+ } else {+ for (let i = 0; i < entry.ops.length; i++) {+ try {+ entry.ops[i].forward();+ } catch (e) {+ console.warn(`[history] redo op ${i} of "${entry.label}" threw`, e);+ }+ }}}++ undo() {+ const entry = this.undoStack.pop();+ if (!entry) return;+ EditorHistoryImpl.apply(entry, 'undo');+ this.redoStack.push(entry);+ this.bump();+ }redo() {- if (this.tm.redo()) {- const id = this.redoIds.pop();- if (id !== undefined) this.undoIds.push(id);- this.bump();- }+ const entry = this.redoStack.pop();+ if (!entry) return;+ EditorHistoryImpl.apply(entry, 'redo');+ this.undoStack.push(entry);+ this.bump();}canUndo() {- return this.tm.canUndo();+ return this.undoStack.length > 0;}canRedo() {- return this.tm.canRedo();+ return this.redoStack.length > 0;}undoLabel(): string | null {- return this.tm.peekUndo()?.label ?? null;+ return this.undoStack.length ? this.undoStack[this.undoStack.length - 1].label : null;}redoLabel(): string | null {- return this.tm.peekRedo()?.label ?? null;+ return this.redoStack.length ? this.redoStack[this.redoStack.length - 1].label : null;}++ /** Drop every entry (all documents) — project switch / hard reset. */clear() {- this.tm.clear();- // A cleared history is the new clean baseline (scene load / new scene).- this.undoIds.length = 0;- this.redoIds.length = 0;+ this.undoStack.length = 0;+ this.redoStack.length = 0;+ this.savedHead = null;+ this.bump();+ }++ /**+ * Drop the SCENE's entries and reset its clean baseline (scene load / new+ * scene). Asset-doc entries survive: their snapshot closures reference only+ * their document, and wiping them would orphan those documents' unsaved edits.+ */+ clearScene() {+ this.purge(null);this.savedHead = null;this.bump();}+ /**+ * Drop one document's entries from both stacks — called when that document+ * opens another file or closes, so a later Ctrl+Z can't replay its stale+ * snapshots into whatever the document shows next.+ */+ purgeDoc(doc: string) {+ if (this.purge(doc)) this.bump();+ }++ private purge(doc: string | null): boolean {+ const keep = (e: HistoryEntry) => e.doc !== doc;+ const nextUndo = this.undoStack.filter(keep);+ const nextRedo = this.redoStack.filter(keep);+ const changed = nextUndo.length !== this.undoStack.length || nextRedo.length !== this.redoStack.length;+ this.undoStack.length = 0;+ this.undoStack.push(...nextUndo);+ this.redoStack.length = 0;+ this.redoStack.push(...nextRedo);+ return changed;+ }+/** Mark the current state as saved — the dirty star clears until the next edit. */markSaved() {- this.savedHead = this.head();+ this.savedHead = this.sceneHead();this.bump();}- /** True when the document has unsaved edits relative to the last save / load. */- isDirty = (): boolean => this.head() !== this.savedHead;+ /** True when the SCENE has unsaved edits relative to the last save / load. */+ isDirty = (): boolean => this.sceneHead() !== this.savedHead;private bump() {this.store.setState((s) => ({ version: s.version + 1 }));diff --git a/desktop/src/engine/SceneLoader.ts b/desktop/src/engine/SceneLoader.tsindex 929236039..b632df95f 100644--- a/desktop/src/engine/SceneLoader.ts+++ b/desktop/src/engine/SceneLoader.ts@@ -57,7 +57,7 @@ export const SceneLoader = {await loadEditorSpine(app, raw, map as Map<number, number>, (ref) =>ref.startsWith(UUID_PREFIX) ? (uuidToUrl.get(ref.slice(UUID_PREFIX.length)) ?? ref) : ref,);- EditorHistory.clear();+ EditorHistory.clearScene();SceneModel.adopt(raw, map as Map<number, number>);return map.size;},diff --git a/desktop/src/flipbook/AnimClipDocument.ts b/desktop/src/flipbook/AnimClipDocument.tsindex be5c24c6e..ebda5f4ed 100644--- a/desktop/src/flipbook/AnimClipDocument.ts+++ b/desktop/src/flipbook/AnimClipDocument.ts@@ -36,4 +36,4 @@ export class AnimClipDocumentImpl extends AssetDocument<AnimClipAssetData> {}/** The app's default flipbook document (the one the Flipbook editor panel drives). */-export const AnimClipDocument = new AnimClipDocumentImpl();+export const AnimClipDocument = new AnimClipDocumentImpl('flipbook');diff --git a/desktop/src/flipbook/openFlipbook.ts b/desktop/src/flipbook/openFlipbook.tsindex f93751986..412679648 100644--- a/desktop/src/flipbook/openFlipbook.ts+++ b/desktop/src/flipbook/openFlipbook.ts@@ -9,6 +9,7 @@import { createAnimClip, serializeAnimClip } from 'esengine';import { AnimClipDocument } from './AnimClipDocument';import { ProjectStore } from '@/project/ProjectStore';+import { confirmDiscardDoc } from '@/project/discardGuard';import { dockApi } from '@/layout/dockApi';import { baseName } from '@/project/assetMeta';import { Toasts } from '@/store/Toasts';@@ -16,6 +17,12 @@ import { t } from '@/i18n';/** Open an existing .esanim into the Flipbook editor and reveal the panel. */export async function openFlipbook(path: string): Promise<void> {+ // Already-open file: just front the panel — a reload would clobber unsaved edits.+ if (AnimClipDocument.isOpen && AnimClipDocument.filePath === path) {+ dockApi.openDocument('flipbook', 'flipbook', t('fb.panelTitle'));+ return;+ }+ if (!(await confirmDiscardDoc(AnimClipDocument.dirty, t('discard.openAsset', { name: baseName(path) })))) return;try {const text = await window.estella.fs.read(path);AnimClipDocument.openJson(JSON.parse(text), path);diff --git a/desktop/src/fsm/FsmGraphDocument.ts b/desktop/src/fsm/FsmGraphDocument.tsindex e0f72d712..c0d3c5fc2 100644--- a/desktop/src/fsm/FsmGraphDocument.ts+++ b/desktop/src/fsm/FsmGraphDocument.ts@@ -23,4 +23,4 @@ class FsmGraphDocumentImpl extends AssetDocument<FsmDefinition> {}}-export const FsmGraphDocument = new FsmGraphDocumentImpl();+export const FsmGraphDocument = new FsmGraphDocumentImpl('fsm');diff --git a/desktop/src/fsm/openStateMachine.ts b/desktop/src/fsm/openStateMachine.tsindex 48e000ff4..fea14ca31 100644--- a/desktop/src/fsm/openStateMachine.ts+++ b/desktop/src/fsm/openStateMachine.ts@@ -10,6 +10,7 @@import { emptyFsm } from 'esengine';import { FsmGraphDocument } from './FsmGraphDocument';import { ProjectStore } from '@/project/ProjectStore';+import { confirmDiscardDoc } from '@/project/discardGuard';import { dockApi } from '@/layout/dockApi';import { baseName } from '@/project/assetMeta';import { Toasts } from '@/store/Toasts';@@ -17,6 +18,12 @@ import { t } from '@/i18n';/** Open an existing `.esfsm` into the state-machine editor and reveal the panel. */export async function openStateMachine(path: string): Promise<void> {+ // Already-open file: just front the panel — a reload would clobber unsaved edits.+ if (FsmGraphDocument.isOpen && FsmGraphDocument.filePath === path) {+ dockApi.openDocument('statemachine', 'statemachine', t('fsm.tabTitle'));+ return;+ }+ if (!(await confirmDiscardDoc(FsmGraphDocument.dirty, t('discard.openAsset', { name: baseName(path) })))) return;try {const text = await window.estella.fs.read(path);FsmGraphDocument.openJson(JSON.parse(text), path);diff --git a/desktop/src/i18n/messages/common.ts b/desktop/src/i18n/messages/common.tsindex 446aaefc9..7425ff241 100644--- a/desktop/src/i18n/messages/common.ts+++ b/desktop/src/i18n/messages/common.ts@@ -37,6 +37,8 @@ export const commonMessages = defineMessages({'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.openAsset': { en: 'Opening {name} will discard them', zh: '打开 {name} 将丢弃这些更改' },+ 'discard.closeTab': { en: 'Closing {title} will discard them', zh: '关闭 {title} 将丢弃这些更改' },'discard.reloadChanged': {en: '“{name}” changed on disk. Reloading discards your unsaved edits',zh: '“{name}”在磁盘上已被修改。重新加载将丢弃未保存的编辑',diff --git a/desktop/src/layout/DockLayout.tsx b/desktop/src/layout/DockLayout.tsxindex 41a438258..bc494c910 100644--- a/desktop/src/layout/DockLayout.tsx+++ b/desktop/src/layout/DockLayout.tsx@@ -12,6 +12,7 @@ import {import { ChevronDown, X, SquareArrowOutUpRight } from 'lucide-react';import { DirtyDot } from '@/components/DirtyDot';import { panelDirtySource } from '@/layout/panelDirty';+import { confirmDiscardDoc } from '@/project/discardGuard';import { Outliner } from '@/panels/Outliner';import { Viewport } from '@/panels/Viewport';import { Details } from '@/panels/Details';@@ -220,7 +221,13 @@ function EstellaTab(props: IDockviewPanelHeaderProps) {onPointerDown={(e) => e.stopPropagation()}onClick={(e) => {e.stopPropagation();- props.api.close();+ void (async () => {+ if (source.isDirty()) {+ if (!(await confirmDiscardDoc(true, t('discard.closeTab', { title })))) return;+ source.discard?.();+ }+ props.api.close();+ })();}}><X size={12} strokeWidth={2} />diff --git a/desktop/src/layout/panelDirty.ts b/desktop/src/layout/panelDirty.tsindex 7ffde5b52..04d7cdb84 100644--- a/desktop/src/layout/panelDirty.ts+++ b/desktop/src/layout/panelDirty.ts@@ -16,15 +16,19 @@ import { TimelineDocument } from '@/timeline/TimelineDocument';export interface DirtySource {subscribe(cb: () => void): () => void;isDirty(): boolean;+ /** Close the underlying document, dropping its unsaved edits — the dock tab X+ * calls this after the user confirms the discard, so the dirty state (and the+ * document's undo steps) don't linger invisibly behind a closed tab. */+ discard?(): void;}const SOURCES: Record<string, DirtySource> = {- statemachine: { subscribe: FsmGraphDocument.subscribe, isDirty: () => FsmGraphDocument.dirty },- behaviortree: { subscribe: BtDocument.subscribe, isDirty: () => BtDocument.dirty },- materialgraph: { subscribe: MaterialGraphDocument.subscribe, isDirty: () => MaterialGraphDocument.dirty },- tileset: { subscribe: TilesetDocument.subscribe, isDirty: () => TilesetDocument.dirty },- flipbook: { subscribe: AnimClipDocument.subscribe, isDirty: () => AnimClipDocument.dirty },- sequencer: { subscribe: TimelineDocument.subscribe, isDirty: () => TimelineDocument.dirty },+ statemachine: { subscribe: FsmGraphDocument.subscribe, isDirty: () => FsmGraphDocument.dirty, discard: () => FsmGraphDocument.close() },+ behaviortree: { subscribe: BtDocument.subscribe, isDirty: () => BtDocument.dirty, discard: () => BtDocument.close() },+ materialgraph: { subscribe: MaterialGraphDocument.subscribe, isDirty: () => MaterialGraphDocument.dirty, discard: () => MaterialGraphDocument.close() },+ tileset: { subscribe: TilesetDocument.subscribe, isDirty: () => TilesetDocument.dirty, discard: () => TilesetDocument.close() },+ flipbook: { subscribe: AnimClipDocument.subscribe, isDirty: () => AnimClipDocument.dirty, discard: () => AnimClipDocument.close() },+ sequencer: { subscribe: TimelineDocument.subscribe, isDirty: () => TimelineDocument.dirty, discard: () => TimelineDocument.close() },};const NONE: DirtySource = { subscribe: () => () => {}, isDirty: () => false };diff --git a/desktop/src/material/MaterialDocument.ts b/desktop/src/material/MaterialDocument.tsindex 615207144..0e7473634 100644--- a/desktop/src/material/MaterialDocument.ts+++ b/desktop/src/material/MaterialDocument.ts@@ -53,4 +53,4 @@ class MaterialDocumentImpl extends AssetDocument<MaterialAssetData> {}}-export const MaterialDocument = new MaterialDocumentImpl();+export const MaterialDocument = new MaterialDocumentImpl('material');diff --git a/desktop/src/material/MaterialGraphDocument.ts b/desktop/src/material/MaterialGraphDocument.tsindex b59efaeb5..2f2554338 100644--- a/desktop/src/material/MaterialGraphDocument.ts+++ b/desktop/src/material/MaterialGraphDocument.ts@@ -22,4 +22,4 @@ class MaterialGraphDocumentImpl extends AssetDocument<MaterialGraph> {}}-export const MaterialGraphDocument = new MaterialGraphDocumentImpl();+export const MaterialGraphDocument = new MaterialGraphDocumentImpl('materialgraph');diff --git a/desktop/src/material/openMaterialGraph.ts b/desktop/src/material/openMaterialGraph.tsindex 9c2446af0..ece899e6c 100644--- a/desktop/src/material/openMaterialGraph.ts+++ b/desktop/src/material/openMaterialGraph.ts@@ -11,6 +11,7 @@import { compileMaterialGraph, newMaterialGraph, type MaterialGraph } from 'esengine';import { MaterialGraphDocument } from './MaterialGraphDocument';import { ProjectStore } from '@/project/ProjectStore';+import { confirmDiscardDoc } from '@/project/discardGuard';import { dockApi } from '@/layout/dockApi';import { baseName } from '@/project/assetMeta';import { Toasts } from '@/store/Toasts';@@ -20,6 +21,12 @@ const shaderPathOf = (graphPath: string) => graphPath.replace(/\.esmatgraph$/, '/** Open an existing `.esmatgraph` into the Material Graph editor and reveal the panel. */export async function openMaterialGraph(path: string): Promise<void> {+ // Already-open file: just front the panel — a reload would clobber unsaved edits.+ if (MaterialGraphDocument.isOpen && MaterialGraphDocument.filePath === path) {+ dockApi.openDocument('materialgraph', 'materialgraph', t('mat.panelTitle'));+ return;+ }+ if (!(await confirmDiscardDoc(MaterialGraphDocument.dirty, t('discard.openAsset', { name: baseName(path) })))) return;try {const text = await window.estella.fs.read(path);MaterialGraphDocument.openJson(JSON.parse(text), path);diff --git a/desktop/src/panels/BtTreeEditor.tsx b/desktop/src/panels/BtTreeEditor.tsxindex fc146907b..a26d8c740 100644--- a/desktop/src/panels/BtTreeEditor.tsx+++ b/desktop/src/panels/BtTreeEditor.tsx@@ -19,7 +19,6 @@ import {} from 'esengine';import { BtDocument } from '@/bt/BtDocument';import { t } from '@/i18n';-import { EditorHistory } from '@/engine/EditorHistory';import { NodeGraphCanvas, type CanvasNode, type MenuItem } from '@/components/NodeGraphCanvas';import { Select } from '@/components/Select';import { DirtyDot } from '@/components/DirtyDot';@@ -119,7 +118,7 @@ export function BtTreeEditor() {onMoveNodeEnd={() => {const after = BtDocument.asset;const before = dragBefore.current;- if (after && before) EditorHistory.record('Move node', () => BtDocument.replaceAsset(after), () => BtDocument.replaceAsset(before));+ if (after && before) BtDocument.recordEdit('Move node', before, after);}}onConnect={(from, to) => BtDocument.edit('Reparent', d => Object.assign(d, reparentBtNode(d, to, from)))}onDeleteNode={id => { if (def.root.id !== id) { BtDocument.edit('Delete node', d => Object.assign(d, removeBtNode(d, id))); setSelected(null); } }}diff --git a/desktop/src/panels/MaterialGraphEditor.tsx b/desktop/src/panels/MaterialGraphEditor.tsxindex 19be26579..55843b6ec 100644--- a/desktop/src/panels/MaterialGraphEditor.tsx+++ b/desktop/src/panels/MaterialGraphEditor.tsx@@ -29,7 +29,6 @@ import {import { t } from '@/i18n';import { MaterialGraphDocument } from '@/material/MaterialGraphDocument';import { saveMaterialGraph } from '@/material/openMaterialGraph';-import { EditorHistory } from '@/engine/EditorHistory';import { ColorControl } from '@/components/ColorControl';import { DirtyDot } from '@/components/DirtyDot';import { NumField } from '@/components/NumField';@@ -170,7 +169,7 @@ export function MaterialGraphEditor() {onMoveNodeEnd={() => {const after = MaterialGraphDocument.asset;const before = dragBefore.current;- if (after && before) EditorHistory.record('Move node', () => MaterialGraphDocument.replaceAsset(after), () => MaterialGraphDocument.replaceAsset(before));+ if (after && before) MaterialGraphDocument.recordEdit('Move node', before, after);}}onConnect={(from, to, _fromPort, toPort) =>MaterialGraphDocument.edit('Connect', (d) => Object.assign(d, connect(d, from, to, toPort)))}diff --git a/desktop/src/panels/StateMachineEditor.tsx b/desktop/src/panels/StateMachineEditor.tsxindex 47c12821b..97d5b669e 100644--- a/desktop/src/panels/StateMachineEditor.tsx+++ b/desktop/src/panels/StateMachineEditor.tsx@@ -22,7 +22,6 @@ import {} from 'esengine';import { FsmGraphDocument } from '@/fsm/FsmGraphDocument';import { t } from '@/i18n';-import { EditorHistory } from '@/engine/EditorHistory';import { NodeGraphCanvas, type CanvasNode } from '@/components/NodeGraphCanvas';import { Select } from '@/components/Select';import { DirtyDot } from '@/components/DirtyDot';@@ -111,7 +110,7 @@ export function StateMachineEditor() {onMoveNodeEnd={() => {const after = FsmGraphDocument.asset;const before = dragBefore.current;- if (after && before) EditorHistory.record('Move state', () => FsmGraphDocument.replaceAsset(after), () => FsmGraphDocument.replaceAsset(before));+ if (after && before) FsmGraphDocument.recordEdit('Move state', before, after);}}onConnect={(from, to) => FsmGraphDocument.edit('Add transition', d => Object.assign(d, addTransition(d, from, to)))}onDeleteNode={id => { FsmGraphDocument.edit('Delete state', d => Object.assign(d, removeState(d, id))); setSelState(null); }}diff --git a/desktop/src/panels/TilemapPainter.tsx b/desktop/src/panels/TilemapPainter.tsxindex 3d8cc0bb2..fa319d337 100644--- a/desktop/src/panels/TilemapPainter.tsx+++ b/desktop/src/panels/TilemapPainter.tsx@@ -9,7 +9,7 @@* the Viewport (this panel drives the active tool + stamp via the paint store).*/-import { useEffect, useRef, useState } from 'react';+import { useEffect, useRef, useState, useSyncExternalStore } from 'react';import {Brush, Eraser, Square, Circle, Slash, PaintBucket, BoxSelect, Pipette,FlipHorizontal, FlipVertical, RotateCw, Mountain, Plus, X, MousePointer2, Dices,@@ -26,8 +26,9 @@ import { MOD_LABEL } from '@/commands/keybinding';import { usePanelWindow } from '@/components/PanelWindow';import { buildStampGhost } from '@/tools/tileStampGhost';import { colsFor, rowsFor, TERRAIN_COLORS } from '@/tools/tileMath';-import { loadTilesetAsset } from '@/tileset/loadTileset';+import { loadTilesetForPalette } from '@/tileset/loadTileset';import { openTileset } from '@/tileset/openTileset';+import { TilesetDocument } from '@/tileset/TilesetDocument';import { useTilesetView } from '@/tileset/tilesetView';import { createTilemapFromTileset } from '@/tilemap/createTilemap';import { layerTilesetRefs } from '@/tilemap/layerTilesetModel';@@ -118,6 +119,11 @@ export function TilemapPainter() {if (typeof localStorage !== 'undefined') localStorage.setItem(stampLibraryKey(projectRoot), serializeStampLibrary(next));};+ // Tileset-editor edits (collision/terrain/animation, possibly unsaved) must reach+ // the palette: reload whenever the shared TilesetDocument bumps, and read through+ // loadTilesetForPalette so the open file resolves to the LIVE document.+ const tilesetDocRev = useSyncExternalStore(TilesetDocument.subscribe, TilesetDocument.getRevision);+// Selecting a TilemapLayer loads ALL its referenced .estileset(s) into the palette,// each assigned its firstId (matching resolveTilesetModel's running sum), so the tab// bar can switch between them and painted cells encode to the right global gid.@@ -131,7 +137,7 @@ export function TilemapPainter() {let firstId = 1;for (const path of paths) {try {- const a = await loadTilesetAsset(path);+ const a = await loadTilesetForPalette(path);entries.push({ path, asset: a, firstId });let count = a.tileCount ?? 0;if (count <= 0) {@@ -145,7 +151,7 @@ export function TilemapPainter() {if (alive) setTilesets(entries);})();return () => { alive = false; };- }, [selectedId, setTilesets, reloadKey]);+ }, [selectedId, setTilesets, reloadKey, tilesetDocRev]);// A tile selection (the select-tool marquee) is layer-scoped: drop it when the active// layer changes so a stale marquee can't drive copy/cut/delete on the wrong layer.@@ -157,12 +163,12 @@ export function TilemapPainter() {if (!tilesetPath) { setAsset(null); setTilesetAsset(null); return; }void (async () => {try {- const a = await loadTilesetAsset(tilesetPath);+ const a = await loadTilesetForPalette(tilesetPath);if (alive) { setAsset(a); setTilesetAsset(a); }} catch { if (alive) { setAsset(null); setTilesetAsset(null); } }})();return () => { alive = false; };- }, [tilesetPath, setTilesetAsset]);+ }, [tilesetPath, setTilesetAsset, tilesetDocRev]);const texUrl = asset ? `estella://project/${ProjectStore.assetInfo(asset.texture)?.path ?? ''}` : null;const [natural, setNatural] = useState<{ w: number; h: number } | null>(null);diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 382a2aa2a..7c9654424 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -424,13 +424,14 @@ class ProjectStoreImpl {this.lastAssetResult = result; // narrowed to the handle maps the resolver reads}- // A scene is a session document: replacing it clears the editor history +- // selection so undo closures can't reference the previous scene's entities- // selection. The Reconciler bulk path then builds the World+ // A scene is a session document: replacing it clears the SCENE's history+ // entries + selection so undo closures can't reference the previous scene's+ // entities (open asset editors keep theirs — their snapshots reference no+ // scene state). The Reconciler bulk path then builds the World// from the resolved scene and adopts the raw scene (with @uuid: refs + any// components/fields/invisible entities the World drops) as the source of// truth. The World is a lossy projection; the model is what save() serializes.- EditorHistory.clear();+ EditorHistory.clearScene();useSelection.getState().select(null);// Incremental recreate (duplicate / undo / play-stop) re-resolves @uuid:→handle// from the same preload result — for all types, not just textures. Spine@@ -489,7 +490,7 @@ class ProjectStoreImpl {if (!st) return;const blank = this.blankScene();await this.buildAssetRegistry(); // keep the uuid→path registry current for new refs- EditorHistory.clear();+ EditorHistory.clearScene();useSelection.getState().select(null);Reconciler.setAssetResolver((ref) => this.handleForRef(ref));Reconciler.setRefPathResolver((ref) => this.resolveRef(ref));diff --git a/desktop/src/project/discardGuard.ts b/desktop/src/project/discardGuard.tsindex 094d5b6f3..69b9ef670 100644--- a/desktop/src/project/discardGuard.ts+++ b/desktop/src/project/discardGuard.ts@@ -22,6 +22,21 @@ import { t } from '@/i18n';*/export async function confirmDiscard(what = t('discard.default')): Promise<boolean> {if (!DirtyRegistry.isDirty()) return true;+ return ask(what);+}++/**+ * Per-document variant: guards ONE editor document (an asset editor about to+ * load another file, a dock tab about to close) — the aggregate registry would+ * wrongly trip on OTHER dirty documents the action doesn't touch. The caller+ * passes that document's dirty state.+ */+export async function confirmDiscardDoc(dirty: boolean, what = t('discard.default')): Promise<boolean> {+ if (!dirty) return true;+ return ask(what);+}++function ask(what: string): Promise<boolean> {return confirm({title: t('discard.title'),body: t('discard.body', { what }),diff --git a/desktop/src/tileset/TilesetDocument.ts b/desktop/src/tileset/TilesetDocument.tsindex 86492480b..de4402fb0 100644--- a/desktop/src/tileset/TilesetDocument.ts+++ b/desktop/src/tileset/TilesetDocument.ts@@ -40,4 +40,4 @@ export class TilesetDocumentImpl extends AssetDocument<TilesetAsset> {}/** The app's default tileset document (the one the Tileset editor panel drives). */-export const TilesetDocument = new TilesetDocumentImpl();+export const TilesetDocument = new TilesetDocumentImpl('tileset');diff --git a/desktop/src/tileset/loadTileset.ts b/desktop/src/tileset/loadTileset.tsindex 7acb612c3..fc49105fe 100644--- a/desktop/src/tileset/loadTileset.ts+++ b/desktop/src/tileset/loadTileset.ts@@ -7,8 +7,20 @@* painter's palette loader isn't a second, drifting copy of it.*/import { parseTileset, type TilesetAsset } from 'esengine';+import { TilesetDocument } from './TilesetDocument';/** Load and parse an `.estileset` at `path` (throws on unreadable/invalid JSON). */export async function loadTilesetAsset(path: string): Promise<TilesetAsset> {return parseTileset(JSON.parse(await window.estella.fs.read(path)));}++/**+ * The palette's view of a tileset: the LIVE TilesetDocument when the Tileset+ * editor has this file open — so unsaved collision/terrain/animation edits show+ * up in the painter immediately — else the on-disk copy.+ */+export async function loadTilesetForPalette(path: string): Promise<TilesetAsset> {+ const live = TilesetDocument.asset;+ if (live && TilesetDocument.filePath === path) return live;+ return loadTilesetAsset(path);+}diff --git a/desktop/src/tileset/openTileset.ts b/desktop/src/tileset/openTileset.tsindex 7171f1d78..5dcc55fa1 100644--- a/desktop/src/tileset/openTileset.ts+++ b/desktop/src/tileset/openTileset.ts@@ -10,6 +10,7 @@import { createTileset as createTilesetAsset, serializeTileset } from 'esengine';import { TilesetDocument } from './TilesetDocument';import { ProjectStore } from '@/project/ProjectStore';+import { confirmDiscardDoc } from '@/project/discardGuard';import { dockApi } from '@/layout/dockApi';import { baseName } from '@/project/assetMeta';import { Toasts } from '@/store/Toasts';@@ -17,6 +18,12 @@ import { t } from '@/i18n';/** Open an existing .estileset into the Tileset editor and reveal the panel. */export async function openTileset(path: string): Promise<void> {+ // Already-open file: just front the panel — a reload would clobber unsaved edits.+ if (TilesetDocument.isOpen && TilesetDocument.filePath === path) {+ dockApi.openDocument('tileset', 'tileset', t('tile.panelTileset'));+ return;+ }+ if (!(await confirmDiscardDoc(TilesetDocument.dirty, t('discard.openAsset', { name: baseName(path) })))) return;try {const text = await window.estella.fs.read(path);TilesetDocument.openJson(JSON.parse(text), path);diff --git a/desktop/src/timeline/TimelineDocument.ts b/desktop/src/timeline/TimelineDocument.tsindex c939472af..b98e93d1e 100644--- a/desktop/src/timeline/TimelineDocument.ts+++ b/desktop/src/timeline/TimelineDocument.ts@@ -77,4 +77,4 @@ export class TimelineDocumentImpl extends AssetDocument<TimelineAsset> {}/** The app's default timeline document (the one the Sequencer panel drives). */-export const TimelineDocument = new TimelineDocumentImpl();+export const TimelineDocument = new TimelineDocumentImpl('timeline');diff --git a/desktop/src/timeline/TimelineRecorder.ts b/desktop/src/timeline/TimelineRecorder.tsindex 4cc8e134a..b2a8dc330 100644--- a/desktop/src/timeline/TimelineRecorder.ts+++ b/desktop/src/timeline/TimelineRecorder.ts@@ -25,7 +25,6 @@ import { TimelineDocument } from './TimelineDocument';import { upsertKeyframe } from './timelineView';import { useSequencerStore } from '@/store/sequencerStore';import { SceneCommands } from '@/engine/SceneCommands';-import { EditorHistory } from '@/engine/EditorHistory';import type { EntityId, InspectorFieldType, InspectorFieldValue } from '@/types';const clone = <T>(v: T): T =>@@ -121,11 +120,7 @@ class TimelineRecorderImpl {this.burstBefore = null;const after = TimelineDocument.asset;if (!before || !after) return;- EditorHistory.record(- 'Record Keyframes',- () => TimelineDocument.replaceAsset(after),- () => TimelineDocument.replaceAsset(before),- );+ TimelineDocument.recordEdit('Record Keyframes', before, after);}}diff --git a/desktop/src/timeline/openClip.ts b/desktop/src/timeline/openClip.tsindex e7be62d4e..24bff683b 100644--- a/desktop/src/timeline/openClip.ts+++ b/desktop/src/timeline/openClip.ts@@ -18,9 +18,18 @@ import { useSelection } from '@/store/selectionStore';import { dockApi } from '@/layout/dockApi';import { Toasts } from '@/store/Toasts';import { ProjectStore } from '@/project/ProjectStore';+import { confirmDiscardDoc } from '@/project/discardGuard';import { baseName } from '@/project/assetMeta';export async function openAnimationClip(path: string): Promise<void> {+ // Already-open file: front the Sequencer and rebind the preview root — a+ // reload would clobber unsaved edits.+ if (TimelineDocument.isOpen && TimelineDocument.filePath === path) {+ TimelineDocument.setRootEntity(useSelection.getState().selectedId);+ dockApi.revealAndExpand('sequencer');+ return;+ }+ if (!(await confirmDiscardDoc(TimelineDocument.dirty, t('discard.openAsset', { name: baseName(path) })))) return;try {const text = await window.estella.fs.read(path);const asset = parseAnimationClip(JSON.parse(text));diff --git a/desktop/tests/asset-doc-undo-isolation.test.ts b/desktop/tests/asset-doc-undo-isolation.test.tsnew file mode 100644index 000000000..c7ae1577e--- /dev/null+++ b/desktop/tests/asset-doc-undo-isolation.test.ts@@ -0,0 +1,90 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Cross-document undo isolation — the corruption cluster: an AssetDocument+ * shares the app EditorHistory with the scene, so opening file B over+ * dirty file A (or closing the document) must purge A's stale snapshot+ * steps instead of letting Ctrl+Z replay them into B. Pure TS.+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import type { BtDefinition } from 'esengine';+import { EditorHistory } from '@/engine/EditorHistory';+import { BtDocument } from '@/bt/BtDocument';+import { FsmGraphDocument } from '@/fsm/FsmGraphDocument';++const btDef = (rootId: string): BtDefinition =>+ ({ root: { id: rootId, type: 'selector', children: [] } }) as unknown as BtDefinition;+const rootId = () => (BtDocument.asset as unknown as { root: { id: string } } | null)?.root.id;+const pushChild = (id: string) =>+ BtDocument.edit('Add node', (d) => {+ (d as unknown as { root: { children: unknown[] } }).root.children.push({ id, type: 'action' });+ });++beforeEach(() => {+ EditorHistory.clear();+});+afterEach(() => {+ BtDocument.close();+ FsmGraphDocument.close();+ EditorHistory.clear();+});++describe('cross-document undo isolation', () => {+ it('dirty A → open B → undo does NOT clobber B with A stale snapshot', () => {+ BtDocument.open(btDef('a'), 'assets/a.esbt');+ pushChild('a1');+ expect(BtDocument.dirty).toBe(true);++ BtDocument.openJson(btDef('b'), 'assets/b.esbt');+ EditorHistory.undo(); // must be a no-op for this document++ expect(BtDocument.filePath).toBe('assets/b.esbt');+ expect(rootId()).toBe('b');+ expect(BtDocument.dirty).toBe(false);+ expect(EditorHistory.canUndo()).toBe(false);+ });++ it('undo cannot resurrect a closed document', () => {+ BtDocument.open(btDef('a'), 'assets/a.esbt');+ pushChild('a1');+ BtDocument.close();+ EditorHistory.undo();+ expect(BtDocument.isOpen).toBe(false);+ expect(BtDocument.asset).toBeNull();+ });++ it("closing one document keeps another document's undo intact", () => {+ BtDocument.open(btDef('a'), 'assets/a.esbt');+ pushChild('a1');+ FsmGraphDocument.open({ initial: 'idle', states: {} } as never, 'assets/x.esfsm');+ FsmGraphDocument.edit('Rename', (d) => {+ (d as { initial: string }).initial = 'run';+ });++ BtDocument.close();+ EditorHistory.undo();+ expect((FsmGraphDocument.asset as { initial: string }).initial).toBe('idle');+ expect(EditorHistory.canUndo()).toBe(false);+ });++ it('scene switch (clearScene) keeps asset-doc undo steps and dirty state', () => {+ EditorHistory.record('Move entity', () => {}, () => {}); // a scene step+ BtDocument.open(btDef('a'), 'assets/a.esbt');+ pushChild('a1');++ EditorHistory.clearScene();+ expect(EditorHistory.isDirty()).toBe(false); // scene baseline reset+ expect(BtDocument.dirty).toBe(true); // asset edits survive, still guarded+ expect(EditorHistory.canUndo()).toBe(true);++ EditorHistory.undo();+ expect((BtDocument.asset as unknown as { root: { children: unknown[] } }).root.children).toHaveLength(0);+ });++ it('an asset edit alone does not mark the scene history dirty', () => {+ BtDocument.open(btDef('a'), 'assets/a.esbt');+ pushChild('a1');+ expect(EditorHistory.isDirty()).toBe(false);+ expect(BtDocument.dirty).toBe(true);+ });+});diff --git a/desktop/tests/asset-document.test.ts b/desktop/tests/asset-document.test.tsindex 2f6562d66..55f4c155d 100644--- a/desktop/tests/asset-document.test.ts+++ b/desktop/tests/asset-document.test.ts@@ -16,7 +16,7 @@ describe('AssetDocument (generic reactive + undoable base)', () => {let doc: TestDoc;beforeEach(() => {EditorHistory.clear();- doc = new TestDoc();+ doc = new TestDoc('test');});it('opens clean and tracks dirty on edit', () => {diff --git a/desktop/tests/history-doc-identity.test.ts b/desktop/tests/history-doc-identity.test.tsnew file mode 100644index 000000000..9af1da584--- /dev/null+++ b/desktop/tests/history-doc-identity.test.ts@@ -0,0 +1,99 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file EditorHistory document identity — entries carry a docId so an asset+ * editor reopening/closing its file can purge ONLY its own stale steps,+ * and a scene switch (clearScene) keeps asset-doc steps alive. Pure TS.+ */+import { describe, it, expect, beforeEach } from 'vitest';+import { EditorHistoryImpl } from '@/engine/EditorHistory';++describe('EditorHistory document identity', () => {+ let h: EditorHistoryImpl;+ let log: string[];+ beforeEach(() => {+ h = new EditorHistoryImpl();+ log = [];+ });+ const rec = (label: string, doc?: string) =>+ h.record(label, () => log.push(`fwd:${label}`), () => log.push(`rev:${label}`), doc);++ it('purgeDoc drops only that document entries from the undo stack', () => {+ rec('scene1');+ rec('tsA', 'tileset');+ rec('scene2');+ rec('tsB', 'tileset');+ h.purgeDoc('tileset');+ h.undo();+ h.undo();+ expect(log).toEqual(['rev:scene2', 'rev:scene1']);+ expect(h.canUndo()).toBe(false);+ });++ it('purgeDoc also drops that document entries from the redo stack', () => {+ rec('tsA', 'tileset');+ rec('scene1');+ h.undo();+ h.undo(); // both on the redo stack now+ h.purgeDoc('tileset');+ h.redo();+ expect(log).toEqual(['rev:scene1', 'rev:tsA', 'fwd:scene1']);+ expect(h.canRedo()).toBe(false);+ });++ it('purgeDoc leaves other documents entries untouched', () => {+ rec('bt1', 'bt');+ rec('fsm1', 'fsm');+ h.purgeDoc('bt');+ expect(h.undoLabel()).toBe('fsm1');+ h.undo();+ expect(log).toEqual(['rev:fsm1']);+ expect(h.canUndo()).toBe(false);+ });++ it('clearScene purges scene entries but keeps asset-doc entries undoable', () => {+ rec('scene1');+ rec('bt1', 'bt');+ rec('scene2');+ h.clearScene();+ expect(h.undoLabel()).toBe('bt1');+ h.undo();+ expect(log).toEqual(['rev:bt1']);+ expect(h.canUndo()).toBe(false);+ });++ it('doc-tagged edits do not dirty the scene; scene edits do', () => {+ rec('bt1', 'bt');+ expect(h.isDirty()).toBe(false);+ rec('scene1');+ expect(h.isDirty()).toBe(true);+ });++ it('scene dirty tracks the scene head across interleaved asset edits', () => {+ rec('scene1');+ h.markSaved();+ rec('bt1', 'bt');+ expect(h.isDirty()).toBe(false); // asset edit on top of the saved scene head+ rec('scene2');+ expect(h.isDirty()).toBe(true);+ h.undo(); // scene2+ expect(h.isDirty()).toBe(false); // back at the saved scene head (bt1 on top)+ });++ it('clearScene resets the scene clean baseline', () => {+ rec('scene1');+ expect(h.isDirty()).toBe(true);+ h.clearScene();+ expect(h.isDirty()).toBe(false);+ });++ it('run/batch accept a docId and purge with it', () => {+ let v = 0;+ h.run('set', () => { v = 1; }, () => { v = 0; }, 'material');+ h.batch('pair', [{ forward: () => { v = 2; }, reverse: () => { v = 1; } }], 'material');+ expect(v).toBe(1); // batch registers already-applied ops; forward not re-run+ h.purgeDoc('material');+ expect(h.canUndo()).toBe(false);+ expect(h.isDirty()).toBe(false);+ });+});diff --git a/desktop/tests/open-asset-guard.test.ts b/desktop/tests/open-asset-guard.test.tsnew file mode 100644index 000000000..5f7cea4b3--- /dev/null+++ b/desktop/tests/open-asset-guard.test.ts@@ -0,0 +1,82 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Open-asset discard guard — opening a different file into a dirty+ * AssetDocument editor must prompt (confirmDiscardDoc); re-opening the+ * SAME file fronts the panel without a disk reload that would clobber+ * unsaved edits. Exercised through openTileset (the twins share the shape).+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { createTileset, serializeTileset } from 'esengine';+import { EditorHistory } from '@/engine/EditorHistory';++vi.mock('@/components/confirm', () => ({ confirm: vi.fn() }));+import { confirm } from '@/components/confirm';+import { openTileset } from '@/tileset/openTileset';+import { TilesetDocument } from '@/tileset/TilesetDocument';++const confirmMock = vi.mocked(confirm);++const read = vi.fn(async (path: string) => {+ if (path === 'assets/b.estileset') {+ return JSON.stringify(serializeTileset(createTileset('@uuid:tex-b', 32, 32, 4)));+ }+ throw new Error(`unexpected read: ${path}`);+});++beforeEach(() => {+ confirmMock.mockReset();+ read.mockClear();+ (globalThis as { window?: unknown }).window = { estella: { fs: { read } } };+ EditorHistory.clear();+ TilesetDocument.open(createTileset('@uuid:tex-a', 16, 16, 2), 'assets/a.estileset');+ TilesetDocument.edit('Resize tiles', (d) => {+ d.tileWidth = 24;+ });+});++afterEach(() => {+ TilesetDocument.close();+ EditorHistory.clear();+ delete (globalThis as { window?: unknown }).window;+});++describe('open-asset discard guard (openTileset)', () => {+ it('declining the prompt keeps the dirty document untouched', async () => {+ confirmMock.mockResolvedValue(false);+ await openTileset('assets/b.estileset');+ expect(confirmMock).toHaveBeenCalledTimes(1);+ expect(read).not.toHaveBeenCalled();+ expect(TilesetDocument.filePath).toBe('assets/a.estileset');+ expect(TilesetDocument.dirty).toBe(true);+ expect(TilesetDocument.asset?.tileWidth).toBe(24);+ });++ it("confirming opens the new file and purges the old file's undo steps", async () => {+ confirmMock.mockResolvedValue(true);+ await openTileset('assets/b.estileset');+ expect(TilesetDocument.filePath).toBe('assets/b.estileset');+ expect(TilesetDocument.dirty).toBe(false);+ expect(TilesetDocument.asset?.tileWidth).toBe(32);++ EditorHistory.undo(); // must not replay A's stale snapshot into B+ expect(TilesetDocument.asset?.tileWidth).toBe(32);+ expect(TilesetDocument.filePath).toBe('assets/b.estileset');+ });++ it('re-opening the same dirty file fronts the panel without a reload or prompt', async () => {+ await openTileset('assets/a.estileset');+ expect(confirmMock).not.toHaveBeenCalled();+ expect(read).not.toHaveBeenCalled();+ expect(TilesetDocument.dirty).toBe(true);+ expect(TilesetDocument.asset?.tileWidth).toBe(24);+ });++ it('opening over a CLEAN document needs no prompt', async () => {+ TilesetDocument.open(createTileset('@uuid:tex-a', 16, 16, 2), 'assets/a.estileset'); // reset clean+ confirmMock.mockResolvedValue(false); // would block if asked+ await openTileset('assets/b.estileset');+ expect(confirmMock).not.toHaveBeenCalled();+ expect(TilesetDocument.filePath).toBe('assets/b.estileset');+ });+});diff --git a/desktop/tests/panel-dirty-discard.test.ts b/desktop/tests/panel-dirty-discard.test.tsnew file mode 100644index 000000000..4156571e3--- /dev/null+++ b/desktop/tests/panel-dirty-discard.test.ts@@ -0,0 +1,38 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file panelDirty discard — the dock tab X routes a confirmed discard here so+ * the underlying AssetDocument actually closes (dropping its dirty state+ * and purging its undo steps) instead of lingering invisibly.+ */+import { describe, it, expect, afterEach } from 'vitest';+import type { BtDefinition } from 'esengine';+import { panelDirtySource } from '@/layout/panelDirty';+import { BtDocument } from '@/bt/BtDocument';+import { EditorHistory } from '@/engine/EditorHistory';++afterEach(() => {+ BtDocument.close();+ EditorHistory.clear();+});++describe('panelDirtySource discard', () => {+ it('discard closes the panel document and drops its undo steps', () => {+ BtDocument.open({ root: { id: 'r', type: 'selector', children: [] } } as unknown as BtDefinition, 'assets/a.esbt');+ BtDocument.edit('Add node', (d) => {+ (d as unknown as { root: { children: unknown[] } }).root.children.push({ id: 'n', type: 'action' });+ });+ const src = panelDirtySource('behaviortree');+ expect(src.isDirty()).toBe(true);++ src.discard?.();+ expect(BtDocument.isOpen).toBe(false);+ expect(src.isDirty()).toBe(false);+ EditorHistory.undo();+ expect(BtDocument.isOpen).toBe(false); // no resurrection+ });++ it('panels without a document expose no discard', () => {+ expect(panelDirtySource('viewport').discard).toBeUndefined();+ });+});diff --git a/desktop/tests/tileset-palette-live.test.ts b/desktop/tests/tileset-palette-live.test.tsnew file mode 100644index 000000000..ef8d691ca--- /dev/null+++ b/desktop/tests/tileset-palette-live.test.ts@@ -0,0 +1,56 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Tilemap palette ↔ Tileset editor bridge — the painter must see the LIVE+ * TilesetDocument (unsaved collision/terrain edits included) when the+ * Tileset editor has the same file open, and fall back to disk otherwise.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { createTileset, serializeTileset } from 'esengine';+import { loadTilesetForPalette } from '@/tileset/loadTileset';+import { TilesetDocument } from '@/tileset/TilesetDocument';+import { EditorHistory } from '@/engine/EditorHistory';++const read = vi.fn(async (path: string) => {+ if (path === 'assets/disk.estileset') {+ return JSON.stringify(serializeTileset(createTileset('@uuid:disk', 8, 8, 2)));+ }+ throw new Error(`unexpected read: ${path}`);+});++beforeEach(() => {+ read.mockClear();+ (globalThis as { window?: unknown }).window = { estella: { fs: { read } } };+});++afterEach(() => {+ TilesetDocument.close();+ EditorHistory.clear();+ delete (globalThis as { window?: unknown }).window;+});++describe('loadTilesetForPalette', () => {+ it('returns the live document asset (unsaved edits included) for the open file', async () => {+ TilesetDocument.open(createTileset('@uuid:live', 16, 16, 2), 'assets/live.estileset');+ TilesetDocument.edit('Mark solid', (d) => {+ d.tiles[3] = { collision: 'full' } as never;+ });++ const asset = await loadTilesetForPalette('assets/live.estileset');+ expect(asset).toBe(TilesetDocument.asset);+ expect(asset.tiles[3]).toBeDefined();+ expect(read).not.toHaveBeenCalled();+ });++ it('falls back to disk for a file the editor does not have open', async () => {+ TilesetDocument.open(createTileset('@uuid:live', 16, 16, 2), 'assets/live.estileset');+ const asset = await loadTilesetForPalette('assets/disk.estileset');+ expect(asset.texture).toBe('@uuid:disk');+ expect(read).toHaveBeenCalledWith('assets/disk.estileset');+ });++ it('falls back to disk when no document is open', async () => {+ const asset = await loadTilesetForPalette('assets/disk.estileset');+ expect(asset.tileWidth).toBe(8);+ });+});