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(sdk): hot reload survives contact with a real project
esenginef3abda390aff
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 013002180..ffd67f975 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -180,6 +180,28 @@ to.(`GLDebug.enable()`), the on-demand probes still force a check, and the browseralready reports WebGL errors to the console on its own.+- **Editor automation no longer times out when a call lands during a subframe+ load.** Driving the editor (MCP tools, the agent, the e2e) goes through a guard+ that waited for `did-finish-load` whenever the window reported loading — but+ the play realm prewarms in an IFRAME seconds after a project opens, the loading+ flag covers subframes, and that event only fires for the main frame. A call+ that drew the short straw awaited an event that had already fired for the last+ time. The guard polls now, bounded, and cannot be stranded.++- **Hot reload now actually keeps the World — in projects that exist.** Two+ gates rejected every real project while passing every unit test. Startup+ systems are consumed when they run, so a re-imported bundle always has ones+ the live side doesn't — structural mismatch, full restart, for anyone using+ `addStartupSystem`. And "no owning subsystem" was read as "user system", which+ swept up engine systems that register lazily outside a plugin build (the+ physics event bridge among them) — phantom structure, full restart, for any+ project with physics. User systems are now classified by the one boundary that+ defines them — they came through the project bundle's drain — startup is+ exempt in both directions, and every reload logs which path it took and why,+ so a fallback is a stated fact instead of a mystery about lost state. Proven+ live by the editor e2e: a logic edit mid-play swaps with state preserved, a+ schema edit forces the clean restart it must.+- **Saves no longer live in a directory the platform may delete.** Key/valuestorage went to the host's cache directory, whose stated purpose was theregenerable bytecode cache. On iOS that is `NSCachesDirectory`, which the systemdiff --git a/desktop/scripts/editor-mcp-editor-e2e.mjs b/desktop/scripts/editor-mcp-editor-e2e.mjsindex 959b13c32..9f30de1e1 100644--- a/desktop/scripts/editor-mcp-editor-e2e.mjs+++ b/desktop/scripts/editor-mcp-editor-e2e.mjs@@ -323,6 +323,11 @@ try {await writeFile(path.join(project, COUNTER_REL), counterSource(1000000, 2));const s2 = await until('the swapped logic to arrive', (s) => s.lv === 2);if (s2.v % 1000000 === 0) {+ const logs = JSON.parse((await call('get_logs', { tail: 30 })).text);+ for (const l of logs) {+ const line = typeof l === 'string' ? l : JSON.stringify(l);+ if (/reload|play|swap/i.test(line)) console.log(' log:', line.slice(0, 520));+ }await fail(`logic edit lost the World: counter restarted at ${s2.v} — hot swap fell back to a full reload (or swapped a rebooted realm)`);}if (s2.v % 1000000 < s1.v) await fail(`counter went backwards across the swap (${s1.v} -> ${s2.v})`);diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.tsindex db295a479..7e669d7d6 100644--- a/desktop/src/playHost.ts+++ b/desktop/src/playHost.ts@@ -415,15 +415,27 @@ async function boot(msg: InitMessage): Promise<void> {*/async function tryHotSwapReload(): Promise<boolean> {if (!app) return false;+ // Each outcome says why: "the editor kept my state" vs "it restarted" is+ // invisible from the outside, and a swap that silently falls back reads as a+ // hot reload that lost the World.try {const liveFingerprint = getUserComponentFingerprint();const { fingerprint, pending } = await probeRegistrations(() =>import(/* @vite-ignore */ `${bundleUrl}?v=${++reloadSeq}`).then(() => undefined),);- if (fingerprint !== liveFingerprint) return false; // a component's fields changed- return app.hotSwapSystems(pending as Parameters<App['hotSwapSystems']>[0]);- } catch {- return false; // probe/import failure → safe full reload+ if (fingerprint !== liveFingerprint) {+ console.info('[play] reload: full restart — a component schema changed');+ return false;+ }+ if (!app.hotSwapSystems(pending as Parameters<App['hotSwapSystems']>[0])) {+ console.info('[play] reload: full restart — the system structure changed');+ return false;+ }+ console.info('[play] reload: hot-swapped system bodies in place (World kept)');+ return true;+ } catch (e) {+ console.info(`[play] reload: full restart — probe failed: ${(e as Error)?.message ?? e}`);+ return false;}}diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex c9105a5d2..cb85af928 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -444,6 +444,7 @@ ComponentDef<any> | BuiltinComponentDef<any>## App — class```+addBundleSystems: (entries: ReadonlyArray<{ schedule: number; system: SystemDef; }>) => AppaddEvent: <T>(event: EventDef<T>) => AppaddPlugin: (plugin: Plugin) => AppaddPlugins: (plugins: Plugin[]) => Appdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 74f90d41e..b82c6b9d7 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -444,6 +444,7 @@ ComponentDef<any> | BuiltinComponentDef<any>## App — class```+addBundleSystems: (entries: ReadonlyArray<{ schedule: number; system: SystemDef; }>) => AppaddEvent: <T>(event: EventDef<T>) => AppaddPlugin: (plugin: Plugin) => AppaddPlugins: (plugins: Plugin[]) => Appdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex e47607f3d..4f82eaf4b 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -439,6 +439,7 @@ ComponentDef<any> | BuiltinComponentDef<any>## App — class```+addBundleSystems: (entries: ReadonlyArray<{ schedule: number; system: SystemDef; }>) => AppaddEvent: <T>(event: EventDef<T>) => AppaddPlugin: (plugin: Plugin) => AppaddPlugins: (plugins: Plugin[]) => Appdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 018a04793..6d7ab5b69 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -439,6 +439,7 @@ ComponentDef<any> | BuiltinComponentDef<any>## App — class```+addBundleSystems: (entries: ReadonlyArray<{ schedule: number; system: SystemDef; }>) => AppaddEvent: <T>(event: EventDef<T>) => AppaddPlugin: (plugin: Plugin) => AppaddPlugins: (plugins: Plugin[]) => Appdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 2ef717ae2..f227de07c 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -439,6 +439,7 @@ ComponentDef<any> | BuiltinComponentDef<any>## App — class```+addBundleSystems: (entries: ReadonlyArray<{ schedule: number; system: SystemDef; }>) => AppaddEvent: <T>(event: EventDef<T>) => AppaddPlugin: (plugin: Plugin) => AppaddPlugins: (plugins: Plugin[]) => Appdiff --git a/sdk/src/app/app.ts b/sdk/src/app/app.tsindex c1e8bc0fc..43fa2572f 100644--- a/sdk/src/app/app.ts+++ b/sdk/src/app/app.ts@@ -62,6 +62,12 @@ interface SystemEntry {/** The subsystem (owning plugin name) this system belongs to — pets that* subsystem's liveness watchdog when it runs (observability). */subsystem?: string;+ /** Came through the project bundle's pending-systems drain — the set hot+ * reload may swap. "No owning subsystem" is NOT that set: engine systems+ * registered lazily outside a plugin build (the physics event bridge, the+ * hot-update rebind) carry no subsystem either, and mistaking them for+ * user systems vetoed every hot swap in any project that had physics. */+ fromBundle?: boolean;}// =============================================================================@@ -102,6 +108,7 @@ export class App {/** The plugin currently in build(), so systems it adds inherit its name for* liveness reporting. Null outside a build. */private buildingPlugin_: string | null = null;+ private addingBundleSystems_ = false;// The realm's acquirer for optional native modules (physics, spine). Set once// at app creation; physics/spine self-gate off it. Null in headless/test apps.private sideModules_: SideModuleHost | null = null;@@ -261,6 +268,7 @@ export class App {runAfter: mergeOrderingEdges(system._runAfter, options?.runAfter),runIf: options?.runIf,subsystem: this.buildingPlugin_ ?? undefined,+ fromBundle: this.addingBundleSystems_ || undefined,});this.sortedSystemsCache_.delete(schedule);return this;@@ -270,6 +278,24 @@ export class App {return this.addSystemToSchedule(Schedule.Update, system);}+ /**+ * Register systems drained from the PROJECT BUNDLE, marking them as the set+ * hot reload may swap. The bundle drain is the one boundary that separates+ * user-authored systems from everything the engine registers — plugin+ * builds tag themselves, but lazily-added engine systems are told apart+ * from user code only by which door they came through.+ * @internal+ */+ addBundleSystems(entries: ReadonlyArray<{ schedule: number; system: SystemDef }>): this {+ this.addingBundleSystems_ = true;+ try {+ for (const e of entries) this.addSystemToSchedule(e.schedule as Schedule, e.system);+ } finally {+ this.addingBundleSystems_ = false;+ }+ return this;+ }+addStartupSystem(system: SystemDef): this {return this.addSystemToSchedule(Schedule.Startup, system);}@@ -295,21 +321,42 @@ export class App {else bySchedule.set(e.schedule as Schedule, [e.system]);}const userEntries = (s: Schedule): SystemEntry[] =>- (this.systems_.get(s) ?? []).filter((entry) => entry.subsystem === undefined);-+ (this.systems_.get(s) ?? []).filter((entry) => entry.fromBundle === true);++ // Startup is exempt from matching in both directions: its entries are+ // CONSUMED when they run (flushStartupSystems truncates the list), so the+ // live side is always empty while a re-imported bundle always queues them+ // again — requiring a match would veto hot swap for every project that+ // uses addStartupSystem. There is nothing to swap either way: a startup+ // body can only run on a cold start, so an edited one takes effect on the+ // next full reload, which is the only time it could.+ // Each rejection names the mismatch: "the structure changed" alone reads+ // as a hot reload that arbitrarily lost the World.for (const [schedule, defs] of bySchedule) {+ if (schedule === Schedule.Startup) continue;const live = userEntries(schedule);- if (live.length !== defs.length) return false;+ if (live.length !== defs.length) {+ log.info('hotReload', `structure: schedule ${Schedule[schedule]} has ${live.length} live user system(s) [${live.map((e) => e.system._name).join(', ')}] vs ${defs.length} incoming [${defs.map((d) => d._name || '(unnamed)').join(', ')}]`);+ return false;+ }for (let i = 0; i < live.length; i++) {- if (!App.systemNamesCompatible(live[i].system._name, defs[i]._name)) return false;+ if (!App.systemNamesCompatible(live[i].system._name, defs[i]._name)) {+ log.info('hotReload', `structure: schedule ${Schedule[schedule]} system #${i} renamed "${live[i].system._name}" -> "${defs[i]._name || '(unnamed)'}"`);+ return false;+ }}}// A schedule that had user systems the new bundle didn't re-add is structural.for (const [schedule, entries] of this.systems_) {- if (!bySchedule.has(schedule) && entries.some((e) => e.subsystem === undefined)) return false;+ if (schedule === Schedule.Startup) continue;+ if (!bySchedule.has(schedule) && entries.some((e) => e.fromBundle === true)) {+ log.info('hotReload', `structure: schedule ${Schedule[schedule]} lost its user systems in the new bundle`);+ return false;+ }}for (const [schedule, defs] of bySchedule) {+ if (schedule === Schedule.Startup) continue;const live = userEntries(schedule);for (let i = 0; i < live.length; i++) {const cur = live[i].system;@@ -1156,7 +1203,5 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): Aexport function flushPendingSystems(app: App): void {const drained = getDefaultContext().drainPendingSystems();- for (const entry of drained) {- app.addSystemToSchedule(entry.schedule as Schedule, entry.system as SystemDef);- }+ app.addBundleSystems(drained as ReadonlyArray<{ schedule: number; system: SystemDef }>);}diff --git a/sdk/tests/hot-swap-systems.test.ts b/sdk/tests/hot-swap-systems.test.tsindex f79c99a4b..4bcdd838d 100644--- a/sdk/tests/hot-swap-systems.test.ts+++ b/sdk/tests/hot-swap-systems.test.ts@@ -22,7 +22,7 @@ describe('App.hotSwapSystems', () => {}it('swaps a named system body in place, keeping it scheduled', async () => {- app.addSystemToSchedule(Schedule.Update, defineSystem([], () => log.push('old'), { name: 'S' }));+ app.addBundleSystems([{ schedule: Schedule.Update, system: defineSystem([], () => log.push('old'), { name: 'S' }) }]);await runUpdate();expect(log).toEqual(['old']);@@ -36,8 +36,46 @@ describe('App.hotSwapSystems', () => {expect(log).toEqual(['new']);});+ it('ignores startup systems: consumed on run, always re-queued by a re-import', async () => {+ // The live side truncates Schedule.Startup after flushing it, so a+ // re-imported bundle's startup defs have no live counterpart. That must+ // not veto the swap — it did, which made hot reload silently dead for+ // every project using addStartupSystem (the e2e's first complete run+ // caught it as "counter restarted at a clean multiple").+ app.addSystemToSchedule(Schedule.Startup, defineSystem([], () => log.push('boot'), { name: 'Boot' }));+ app.addBundleSystems([{ schedule: Schedule.Update, system: defineSystem([], () => log.push('old'), { name: 'S' }) }]);+ (app as unknown as { systems_: Map<Schedule, unknown[]> }).systems_.get(Schedule.Startup)!.length = 0;++ const ok = app.hotSwapSystems([+ { schedule: Schedule.Startup, system: defineSystem([], () => log.push('boot2'), { name: 'Boot' }) },+ { schedule: Schedule.Update, system: defineSystem([], () => log.push('new'), { name: 'S' }) },+ ]);+ expect(ok).toBe(true);++ await runUpdate();+ expect(log).toEqual(['new']);+ });++ it('ignores engine systems registered lazily outside a plugin build', async () => {+ // PhysicsEventBridgeSystem / HotUpdateRebindSystem register via+ // app.addSystemToSchedule after boot — no owning subsystem, but not user+ // code either. Classifying "no subsystem" as "user" made them phantom+ // structure: every project with physics full-reloaded on every edit.+ // The bundle door is the classifier now.+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => log.push('engine'), { name: 'PhysicsEventBridgeSystem' }));+ app.addBundleSystems([{ schedule: Schedule.Update, system: defineSystem([], () => log.push('old'), { name: 'S' }) }]);++ const ok = app.hotSwapSystems([+ { schedule: Schedule.Update, system: defineSystem([], () => log.push('new'), { name: 'S' }) },+ ]);+ expect(ok).toBe(true);++ await runUpdate();+ expect(log.sort()).toEqual(['engine', 'new']);+ });+it('rejects an added system (count change) → caller full-reloads', () => {- app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {}, { name: 'S' }));+ app.addBundleSystems([{ schedule: Schedule.Update, system: defineSystem([], () => {}, { name: 'S' }) }]);expect(app.hotSwapSystems([{ schedule: Schedule.Update, system: defineSystem([], () => {}, { name: 'S' }) },{ schedule: Schedule.Update, system: defineSystem([], () => {}, { name: 'T' }) },@@ -45,15 +83,17 @@ describe('App.hotSwapSystems', () => {});it('rejects a rename → full-reload', () => {- app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {}, { name: 'S' }));+ app.addBundleSystems([{ schedule: Schedule.Update, system: defineSystem([], () => {}, { name: 'S' }) }]);expect(app.hotSwapSystems([{ schedule: Schedule.Update, system: defineSystem([], () => {}, { name: 'Renamed' }) },])).toBe(false);});it('matches unnamed systems positionally (System_N ⇔ unnamed)', async () => {- app.addSystemToSchedule(Schedule.Update, defineSystem([], () => log.push('a-old')));- app.addSystemToSchedule(Schedule.Update, defineSystem([], () => log.push('b-old')));+ app.addBundleSystems([+ { schedule: Schedule.Update, system: defineSystem([], () => log.push('a-old')) },+ { schedule: Schedule.Update, system: defineSystem([], () => log.push('b-old')) },+ ]);expect(app.hotSwapSystems([{ schedule: Schedule.Update, system: defineSystem([], () => log.push('a-new')) },{ schedule: Schedule.Update, system: defineSystem([], () => log.push('b-new')) },