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(app): hold execution across frames input and media

yhh3059c8d2ebf1
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index d3f25dbf0..afd2f2622 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -74,6 +74,10 @@ jobs:
node tools/tests/crazygames-training.e2e.mjs --dir output/crazygames-training-ci-export --out output/crazygames-training-ci-check
node tools/tests/export-crazygames-score-fixture.mjs --wasm build/wasm/web --out output/crazygames-training-ci-score-export
node tools/tests/crazygames-training.e2e.mjs --dir output/crazygames-training-ci-score-export --expect-scores --out output/crazygames-training-ci-score-check
+ - name: Check execution holds in an authored game and real browser media
+ run: |
+ node tools/tests/export-execution-hold-fixture.mjs --wasm build/wasm/web --out output/execution-hold-ci-export
+ node tools/tests/execution-hold.e2e.mjs --dir output/execution-hold-ci-export --out output/execution-hold-ci-check
- name: Upload hash-bound local observations and screenshots
if: always()
uses: actions/upload-artifact@v7
@@ -95,6 +99,13 @@ jobs:
name: crazygames-training-local-mock-checks
path: output/crazygames-training-ci-*
retention-days: 3
+ - name: Upload execution hold observations and screenshot
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: execution-hold-headless-checks
+ path: output/execution-hold-ci-*
+ retention-days: 3
# The engine binaries, and nothing else: every gate below waits on this job, so
# a step here that no downstream job reads is a delay on all of them.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5dde4802f..6e3cbd23d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@ published separately; it ships inside the editor.
### Added
+- **App execution holds stop owned frames, input and media.** Hosts can hold execution independently of user pause, with nested owners and idempotent releases. Interrupted startup retains systems that had not begun, and resumed frames wait for pending startup. Native gesture input is discarded while held; audio and video preserve player preferences. Game-owned timers and asynchronous work can cooperate through execution notifications.
+
- **Storage exposes asynchronous write acknowledgment.** Games can await Storage.flush or SaveManager.saveAsync without changing synchronous save slots. The host bridge loads before writing, serializes cloud requests, preserves newer progress during pending saves and keeps failed writes retryable; an unsupported load is never replaced with an empty save. A synchronous adapter's flush does not imply cloud backup.
- **CrazyGames scores and saved training credits follow platform contracts.** Optional Scores submission encrypts finite scores in the official HTML5 format; the editor exposes the client encryption key only for CrazyGames. The example saves earned credits through SDK Data, restores them on reload and preserves unreadable or externally changed progress. A sent score does not certify leaderboard acceptance, and SDK saving does not certify cloud backup.
diff --git a/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx b/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx
index c1e3805df..ad3cff566 100644
--- a/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx
+++ b/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx
@@ -225,6 +225,8 @@ from there; if you are writing a game, you should never need to name them.
| `app.setMaxDeltaTime(s)` | Clamp on a single frame's delta. Default `0.25`. |
| `app.setMaxFixedSteps(n)` | Cap on fixed-step catch-up per frame. Default `8`. A time budget additionally caps catch-up so a too-heavy sim degrades to slow motion instead of freezing. |
| `app.setPaused(v)` / `app.isPaused()` | User pause. While paused only `Schedule.Last` runs. |
+| `app.holdExecution()` | Returns an idempotent release function. While any owner holds execution, automatic frames, tick, stepping and native game input are held. Audio and video plugins cooperate. |
+| `app.isExecutionHeld()` / `app.onExecutionChange(fn)` | Query the hold, or observe it with an initial notification and disposer. Observers are withdrawn on quit. |
| `app.stepFrame()` | Queue exactly one full frame while paused (editor "step"). |
| `app.setPlaySpeed(x)` / `app.getPlaySpeed()` | Time scale, clamped to `0.1`–`4.0`. Default `1.0`. |
| `app.setTargetFrameRate(fps)` / `app.getTargetFrameRate()` | Frame cap; `0` (default) = uncapped (vsync). |
@@ -234,6 +236,29 @@ Within one frame the schedules run: `First` → the fixed trio
the accumulator) → `PreUpdate` → `Update` → `PostUpdate` → `Last`. `Startup`
systems are flushed before the first frame.
+### Execution holds
+
+Use an execution hold when a host requires the game to stop rendering and interacting:
+
+```typescript
+const release = app.holdExecution();
+// Other host owners may acquire their own holds.
+release(); // the last release resumes automatic execution, preserving user pause
+```
+
+The input funnel discards held keys and press edges; UI gesture captures are
+cancelled rather than clicked after resuming. Audio resume and video play cannot
+override the hold. Paused, stopped or completed videos remain so after release.
+Startup systems that had not begun are retained, and resuming waits for an
+interrupted asynchronous startup before the first new frame. The frame clock
+is rebased so host pause time does not become a simulation catch-up interval.
+
+Already-started asynchronous systems can still settle. The engine prevents
+later systems and completed-frame observers from running for that interrupted
+frame; arbitrary JavaScript promises, timers and external network requests are
+owned by the game. Use `onExecutionChange` to abort or suspend those tasks and
+restart them after release. Quit invalidates outstanding release functions.
+
### Errors, physics, stats
| Member | Meaning |
diff --git a/docs/astro/src/content/docs/zh-cn/core-concepts/app-lifecycle.mdx b/docs/astro/src/content/docs/zh-cn/core-concepts/app-lifecycle.mdx
index 165e0f4a2..ac52eeb86 100644
--- a/docs/astro/src/content/docs/zh-cn/core-concepts/app-lifecycle.mdx
+++ b/docs/astro/src/content/docs/zh-cn/core-concepts/app-lifecycle.mdx
@@ -209,6 +209,8 @@ export const scorePlugin: Plugin = {
| `app.setMaxDeltaTime(s)` | 单帧 delta 的钳制上限。默认 `0.25`。 |
| `app.setMaxFixedSteps(n)` | 每帧固定步追赶的上限。默认 `8`。此外还有时间预算封顶追赶,过重的模拟会退化为慢动作而不是卡死。 |
| `app.setPaused(v)` / `app.isPaused()` | 用户暂停。暂停期间只有 `Schedule.Last` 运行。 |
+| `app.holdExecution()` | 返回幂等的释放函数。任一持有者挂起时,自动帧、tick、步进及原生游戏输入均停止,音频与视频插件配合挂起。 |
+| `app.isExecutionHeld()` / `app.onExecutionChange(fn)` | 查询挂起状态,或订阅状态变化(含初始通知,返回取消订阅函数)。退出时移除订阅。 |
| `app.stepFrame()` | 在暂停时排入恰好一整帧(编辑器"步进")。 |
| `app.setPlaySpeed(x)` / `app.getPlaySpeed()` | 时间缩放,钳制在 `0.1`–`4.0`。默认 `1.0`。 |
| `app.setTargetFrameRate(fps)` / `app.getTargetFrameRate()` | 帧率上限;`0`(默认)= 不封顶(vsync)。 |
@@ -217,6 +219,24 @@ export const scorePlugin: Plugin = {
`FixedUpdate` / `FixedPostUpdate`,由累加器决定跑零到多次)→ `PreUpdate` →
`Update` → `PostUpdate` → `Last`。`Startup` 系统在首帧之前冲刷。
+### 执行挂起
+
+当宿主要求游戏停止渲染和交互时,可以取得执行挂起:
+
+```typescript
+const release = app.holdExecution();
+// 其他宿主控制器可以取得独立的挂起。
+release(); // 最后一个持有者释放后恢复自动执行,保留玩家自己的暂停状态
+```
+
+输入入口清除按键和按下边沿,取消 UI 手势捕获,恢复后不补发旧点击。音频 resume 和视频 play
+不能覆盖挂起;玩家暂停、停止或已播完的视频不会被恢复操作重新启动。未开始的 Startup 系统会
+保留,恢复时先等待被打断的异步启动完成,再运行新帧。帧时钟重新校准,不把宿主暂停时长用于追帧。
+
+已经开始的异步系统仍可能完成;引擎阻止该帧后续系统与完整帧观察者执行。任意 JavaScript Promise、
+定时器与外部网络请求仍由游戏管理,应通过 `onExecutionChange` 中止或挂起这些任务,并在释放后
+恢复。退出会让尚未调用的释放函数失效。
+
### 错误、物理、统计
| 成员 | 含义 |
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index e1638087b..b6015e1da 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -762,13 +762,16 @@ getResourceEntries: () => Array<[string, unknown]>
getSystemTimings: () => ReadonlyMap<string, number> | null
getTargetFrameRate: () => number
hasResource: <T>(resource: ResourceDef<T>) => boolean
+holdExecution: () => () => void
hotSwapSystems: (incoming: ReadonlyArray<{ schedule: number; system: SystemDef; }>) => boolean
insertResource: <T>(resource: ResourceDef<T>, value: T) => App
installCompiledSystems: (source: string | BufferSource, manifest: AotManifest) => Promise<number>
+isExecutionHeld: () => boolean
isPaused: () => boolean
isPhysicsReady: boolean
measureFrameScope: <T>(name: string, fn: () => T, options?: { remainder?: ScopeRemainder; }) => T
onError: (handler: (error: unknown, systemName: string) => void) => App
+onExecutionChange: (callback: (held: boolean) => void) => () => void
onFrameEnd: (fn: (dtMs: number) => void) => () => void
onSystemError: (handler: (error: Error, systemName?: string) => "continue" | "pause") => App
onWasmError: (handler: (error: unknown, context: string) => void) => App
@@ -4409,7 +4412,7 @@ version: number
## InputPlugin — class @experimental
```
build: (app: App) => void
-cleanup: () => void
+cleanup: (app?: App) => void
name: string
static new (target?: unknown): InputPlugin
static prototype: InputPlugin
@@ -4428,6 +4431,7 @@ dispatchTouchEnd: (id: number) => boolean
dispatchTouchMove: (id: number, x: number, y: number) => boolean
dispatchTouchStart: (id: number, x: number, y: number) => boolean
dispatchWheel: (deltaX: number, deltaY: number) => boolean
+resetModifiers: () => void
setEditorHandler: (handler: InputHandler | null) => () => void
setUIHandler: (handler: InputHandler | null) => () => void
static new (): InputRouter
@@ -9760,7 +9764,7 @@ setRefResolver: (resolver: ((ref: string) => string) | null) => void
stop: (handle: VideoStreamHandle) => void
stopAll: () => void
update: (module: ESEngineModule | null) => void
-static new (backend: PlatformVideoBackend): VideoAPI
+static new (backend: PlatformVideoBackend, observeExecution?: (callback: (held: boolean) => void) => () => void): VideoAPI
static prototype: VideoAPI
```
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index f4c8c04da..c1f9a0bb6 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -762,13 +762,16 @@ getResourceEntries: () => Array<[string, unknown]>
getSystemTimings: () => ReadonlyMap<string, number> | null
getTargetFrameRate: () => number
hasResource: <T>(resource: ResourceDef<T>) => boolean
+holdExecution: () => () => void
hotSwapSystems: (incoming: ReadonlyArray<{ schedule: number; system: SystemDef; }>) => boolean
insertResource: <T>(resource: ResourceDef<T>, value: T) => App
installCompiledSystems: (source: string | BufferSource, manifest: AotManifest) => Promise<number>
+isExecutionHeld: () => boolean
isPaused: () => boolean
isPhysicsReady: boolean
measureFrameScope: <T>(name: string, fn: () => T, options?: { remainder?: ScopeRemainder; }) => T
onError: (handler: (error: unknown, systemName: string) => void) => App
+onExecutionChange: (callback: (held: boolean) => void) => () => void
onFrameEnd: (fn: (dtMs: number) => void) => () => void
onSystemError: (handler: (error: Error, systemName?: string) => "continue" | "pause") => App
onWasmError: (handler: (error: unknown, context: string) => void) => App
@@ -4417,7 +4420,7 @@ version: number
## InputPlugin — class @experimental
```
build: (app: App) => void
-cleanup: () => void
+cleanup: (app?: App) => void
name: string
static new (target?: unknown): InputPlugin
static prototype: InputPlugin
@@ -4436,6 +4439,7 @@ dispatchTouchEnd: (id: number) => boolean
dispatchTouchMove: (id: number, x: number, y: number) => boolean
dispatchTouchStart: (id: number, x: number, y: number) => boolean
dispatchWheel: (deltaX: number, deltaY: number) => boolean
+resetModifiers: () => void
setEditorHandler: (handler: InputHandler | null) => () => void
setUIHandler: (handler: InputHandler | null) => () => void
static new (): InputRouter
@@ -9973,7 +9977,7 @@ setRefResolver: (resolver: ((ref: string) => string) | null) => void
stop: (handle: VideoStreamHandle) => void
stopAll: () => void
update: (module: ESEngineModule | null) => void
-static new (backend: PlatformVideoBackend): VideoAPI
+static new (backend: PlatformVideoBackend, observeExecution?: (callback: (held: boolean) => void) => () => void): VideoAPI
static prototype: VideoAPI
```
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index b55e60f01..e1eb9970d 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -757,13 +757,16 @@ getResourceEntries: () => Array<[string, unknown]>
getSystemTimings: () => ReadonlyMap<string, number> | null
getTargetFrameRate: () => number
hasResource: <T>(resource: ResourceDef<T>) => boolean
+holdExecution: () => () => void
hotSwapSystems: (incoming: ReadonlyArray<{ schedule: number; system: SystemDef; }>) => boolean
insertResource: <T>(resource: ResourceDef<T>, value: T) => App
installCompiledSystems: (source: string | BufferSource, manifest: AotManifest) => Promise<number>
+isExecutionHeld: () => boolean
isPaused: () => boolean
isPhysicsReady: boolean
measureFrameScope: <T>(name: string, fn: () => T, options?: { remainder?: ScopeRemainder; }) => T
onError: (handler: (error: unknown, systemName: string) => void) => App
+onExecutionChange: (callback: (held: boolean) => void) => () => void
onFrameEnd: (fn: (dtMs: number) => void) => () => void
onSystemError: (handler: (error: Error, systemName?: string) => "continue" | "pause") => App
onWasmError: (handler: (error: unknown, context: string) => void) => App
@@ -4404,7 +4407,7 @@ version: number
## InputPlugin — class @experimental
```
build: (app: App) => void
-cleanup: () => void
+cleanup: (app?: App) => void
name: string
static new (target?: unknown): InputPlugin
static prototype: InputPlugin
@@ -4423,6 +4426,7 @@ dispatchTouchEnd: (id: number) => boolean
dispatchTouchMove: (id: number, x: number, y: number) => boolean
dispatchTouchStart: (id: number, x: number, y: number) => boolean
dispatchWheel: (deltaX: number, deltaY: number) => boolean
+resetModifiers: () => void
setEditorHandler: (handler: InputHandler | null) => () => void
setUIHandler: (handler: InputHandler | null) => () => void
static new (): InputRouter
@@ -9755,7 +9759,7 @@ setRefResolver: (resolver: ((ref: string) => string) | null) => void
stop: (handle: VideoStreamHandle) => void
stopAll: () => void
update: (module: ESEngineModule | null) => void
-static new (backend: PlatformVideoBackend): VideoAPI
+static new (backend: PlatformVideoBackend, observeExecution?: (callback: (held: boolean) => void) => () => void): VideoAPI
static prototype: VideoAPI
```
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index d07cf562e..f7e423be5 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -757,13 +757,16 @@ getResourceEntries: () => Array<[string, unknown]>
getSystemTimings: () => ReadonlyMap<string, number> | null
getTargetFrameRate: () => number
hasResource: <T>(resource: ResourceDef<T>) => boolean
+holdExecution: () => () => void
hotSwapSystems: (incoming: ReadonlyArray<{ schedule: number; system: SystemDef; }>) => boolean
insertResource: <T>(resource: ResourceDef<T>, value: T) => App
installCompiledSystems: (source: string | BufferSource, manifest: AotManifest) => Promise<number>
+isExecutionHeld: () => boolean
isPaused: () => boolean
isPhysicsReady: boolean
measureFrameScope: <T>(name: string, fn: () => T, options?: { remainder?: ScopeRemainder; }) => T
onError: (handler: (error: unknown, systemName: string) => void) => App
+onExecutionChange: (callback: (held: boolean) => void) => () => void
onFrameEnd: (fn: (dtMs: number) => void) => () => void
onSystemError: (handler: (error: Error, systemName?: string) => "continue" | "pause") => App
onWasmError: (handler: (error: unknown, context: string) => void) => App
@@ -4404,7 +4407,7 @@ version: number
## InputPlugin — class @experimental
```
build: (app: App) => void
-cleanup: () => void
+cleanup: (app?: App) => void
name: string
static new (target?: unknown): InputPlugin
static prototype: InputPlugin
@@ -4423,6 +4426,7 @@ dispatchTouchEnd: (id: number) => boolean
dispatchTouchMove: (id: number, x: number, y: number) => boolean
dispatchTouchStart: (id: number, x: number, y: number) => boolean
dispatchWheel: (deltaX: number, deltaY: number) => boolean
+resetModifiers: () => void
setEditorHandler: (handler: InputHandler | null) => () => void
setUIHandler: (handler: InputHandler | null) => () => void
static new (): InputRouter
@@ -10048,7 +10052,7 @@ setRefResolver: (resolver: ((ref: string) => string) | null) => void
stop: (handle: VideoStreamHandle) => void
stopAll: () => void
update: (module: ESEngineModule | null) => void
-static new (backend: PlatformVideoBackend): VideoAPI
+static new (backend: PlatformVideoBackend, observeExecution?: (callback: (held: boolean) => void) => () => void): VideoAPI
static prototype: VideoAPI
```
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 7f1408680..6ebbdf2f2 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -757,13 +757,16 @@ getResourceEntries: () => Array<[string, unknown]>
getSystemTimings: () => ReadonlyMap<string, number> | null
getTargetFrameRate: () => number
hasResource: <T>(resource: ResourceDef<T>) => boolean
+holdExecution: () => () => void
hotSwapSystems: (incoming: ReadonlyArray<{ schedule: number; system: SystemDef; }>) => boolean
insertResource: <T>(resource: ResourceDef<T>, value: T) => App
installCompiledSystems: (source: string | BufferSource, manifest: AotManifest) => Promise<number>
+isExecutionHeld: () => boolean
isPaused: () => boolean
isPhysicsReady: boolean
measureFrameScope: <T>(name: string, fn: () => T, options?: { remainder?: ScopeRemainder; }) => T
onError: (handler: (error: unknown, systemName: string) => void) => App
+onExecutionChange: (callback: (held: boolean) => void) => () => void
onFrameEnd: (fn: (dtMs: number) => void) => () => void
onSystemError: (handler: (error: Error, systemName?: string) => "continue" | "pause") => App
onWasmError: (handler: (error: unknown, context: string) => void) => App
@@ -4411,7 +4414,7 @@ version: number
## InputPlugin — class @experimental
```
build: (app: App) => void
-cleanup: () => void
+cleanup: (app?: App) => void
name: string
static new (target?: unknown): InputPlugin
static prototype: InputPlugin
@@ -4430,6 +4433,7 @@ dispatchTouchEnd: (id: number) => boolean
dispatchTouchMove: (id: number, x: number, y: number) => boolean
dispatchTouchStart: (id: number, x: number, y: number) => boolean
dispatchWheel: (deltaX: number, deltaY: number) => boolean
+resetModifiers: () => void
setEditorHandler: (handler: InputHandler | null) => () => void
setUIHandler: (handler: InputHandler | null) => () => void
static new (): InputRouter
@@ -9762,7 +9766,7 @@ setRefResolver: (resolver: ((ref: string) => string) | null) => void
stop: (handle: VideoStreamHandle) => void
stopAll: () => void
update: (module: ESEngineModule | null) => void
-static new (backend: PlatformVideoBackend): VideoAPI
+static new (backend: PlatformVideoBackend, observeExecution?: (callback: (held: boolean) => void) => () => void): VideoAPI
static prototype: VideoAPI
```
diff --git a/sdk/src/app/app.ts b/sdk/src/app/app.ts
index 76a0969fc..d848ced00 100644
--- a/sdk/src/app/app.ts
+++ b/sdk/src/app/app.ts
@@ -24,7 +24,7 @@ import type { BridgeConnectOptions } from '../ecs/bridge/BuiltinBridge';
import { UICameraInfo } from '../ui/core/ui-camera-info';
import { ScreenLayout } from '../ui/core/screen-layout';
import { ScreenOverlay, defaultScreenOverlay } from '../ui/core/screen-overlay';
-import { inputPlugin, Input } from '../input/input';
+import { inputPlugin, Input, setInputExecutionHeld } from '../input/input';
import { assetPlugin } from '../asset';
import { prefabsPlugin } from '../prefab/prefabServer';
import { setWasmErrorHandler } from '../wasm/wasmError';
@@ -113,6 +113,7 @@ interface InflightSystem {
}
interface SystemEntry {
+ startupInvoked?: boolean;
system: SystemDef;
runBefore?: string[];
runAfter?: string[];
@@ -169,6 +170,9 @@ export class App {
private readonly setMembership_ = new Map<string, string[]>();
private running_ = false;
+ private readonly executionHolds_ = new Set<object>();
+ private executionEpoch_ = 0;
+ private readonly executionObservers_: Array<(held: boolean) => void> = [];
private loopVersion_ = 0;
private queuedFrame_: number | null = null;
private frameInFlight_: Promise<void> | null = null;
@@ -867,6 +871,7 @@ export class App {
}
stepFrame(): void {
+ if (this.isExecutionHeld()) return;
this.step_pending_ = true;
}
@@ -1167,12 +1172,69 @@ export class App {
// =========================================================================
async tick(delta: number): Promise<void> {
+ if (this.isExecutionHeld()) return;
+ const epoch = this.executionEpoch_;
+ this.frame_paused_ = false;
this.boot_();
await this.flushStartupSystems_();
+ if (epoch !== this.executionEpoch_ || this.isExecutionHeld()) return;
await this.runFrame_(delta);
}
+ /** Hold frame execution without changing the game's own pause state. */
+ holdExecution(): () => void {
+ const owner = {}, quitEpoch = this.quitEpoch_;
+ const first = this.executionHolds_.size === 0;
+ this.executionHolds_.add(owner);
+ if (first) {
+ this.executionEpoch_++;
+ this.frame_paused_ = true;
+ this.invalidateLoop_();
+ if (this.hasResource(Input)) setInputExecutionHeld(this.getResource(Input), this, true);
+ this.notifyExecution_();
+ }
+ return () => {
+ if (quitEpoch !== this.quitEpoch_ || !this.executionHolds_.delete(owner) || this.executionHolds_.size) return;
+ if (this.hasResource(Input)) setInputExecutionHeld(this.getResource(Input), this, false);
+ this.notifyExecution_();
+ if (this.isExecutionHeld()) return;
+ const version = this.loopVersion_;
+ // An interrupted asynchronous frame settles before another frame starts.
+ void (this.frameInFlight_ ?? Promise.resolve()).then(() => {
+ if (!this.running_ || this.isExecutionHeld() || version !== this.loopVersion_) return;
+ this.lastTime_ = platformNow();
+ if (typeof requestAnimationFrame === 'function') this.queueLoopFrame_();
+ else void this.mainLoop();
+ });
+ };
+ }
+
+ isExecutionHeld(): boolean { return this.executionHolds_.size > 0; }
+
+ /** Observe execution holds, including the initial state. Media/timer owners can cooperate here. */
+ onExecutionChange(callback: (held: boolean) => void): () => void {
+ this.executionObservers_.push(callback);
+ this.callExecutionObserver_(callback);
+ return () => {
+ const index = this.executionObservers_.indexOf(callback);
+ if (index >= 0) this.executionObservers_.splice(index, 1);
+ };
+ }
+
+ private notifyExecution_(): void {
+ for (const callback of [...this.executionObservers_]) {
+ this.callExecutionObserver_(callback);
+ }
+ }
+
+ private callExecutionObserver_(callback: (held: boolean) => void): void {
+ try {
+ const result: unknown = callback(this.isExecutionHeld());
+ if (result instanceof Promise) void result.catch(error => log.error('app', 'Execution observer error', error));
+ } catch (error) { log.error('app', 'Execution observer error', error); }
+ }
+
/**
* Advance exactly `frames` frames of exactly `dt` seconds, with the rAF loop held
* off for the duration — "let the game run a bit", made reproducible.
@@ -1190,6 +1252,9 @@ export class App {
* its delta.
*/
async stepFrames(frames = 1, dt = 1 / 60): Promise<void> {
+ if (this.isExecutionHeld()) return;
+ const executionEpoch = this.executionEpoch_, quitEpoch = this.quitEpoch_;
+ const previousStep = this.step_pending_;
const wasRunning = this.running_;
const wasPaused = this.user_paused_;
this.invalidateLoop_();
@@ -1198,17 +1263,26 @@ export class App {
try {
await this.frameInFlight_;
this.user_paused_ = false;
- for (let i = 0; i < frames; i++) { this.step_pending_ = true; await this.tick(dt); }
+ for (let i = 0; i < frames; i++) {
+ if (this.isExecutionHeld() || executionEpoch !== this.executionEpoch_) break;
+ this.step_pending_ = true; await this.tick(dt);
+ }
} finally {
- this.user_paused_ = wasPaused;
- if (wasRunning && version === this.loopVersion_) {
+ if (quitEpoch === this.quitEpoch_) {
+ this.user_paused_ = wasPaused;
+ if (executionEpoch !== this.executionEpoch_ || this.isExecutionHeld()) this.step_pending_ = previousStep;
+ }
+ if (wasRunning && quitEpoch === this.quitEpoch_
+ && (version === this.loopVersion_ || executionEpoch !== this.executionEpoch_)) {
this.lastTime_ = platformNow();
this.running_ = true;
// Resumed on the next animation frame, not by starting one here:
// a frame begun inside this call's own microtask drain swallows
// the input edge a caller injects the moment it returns.
- if (typeof requestAnimationFrame === 'function') this.queueLoopFrame_();
- else void this.mainLoop();
+ if (!this.isExecutionHeld()) {
+ if (typeof requestAnimationFrame === 'function') this.queueLoopFrame_();
+ else void this.mainLoop();
+ }
}
}
}
@@ -1219,9 +1293,14 @@ export class App {
}
this.running_ = true;
+ if (this.isExecutionHeld()) return;
+ const version = this.loopVersion_;
+ this.frame_paused_ = false;
this.boot_();
await this.flushStartupSystems_();
+ if (!this.running_ || this.isExecutionHeld() || version !== this.loopVersion_) return;
+
this.lastTime_ = platformNow();
this.mainLoop();
}
@@ -1235,6 +1314,7 @@ export class App {
}
private queueLoopFrame_(): void {
+ if (this.isExecutionHeld() || this.queuedFrame_ !== null) return;
if (typeof requestAnimationFrame !== 'function') return;
const version = this.loopVersion_;
this.queuedFrame_ = requestAnimationFrame((time) => {
@@ -1245,7 +1325,7 @@ export class App {
}
private mainLoop = async (rafTime?: number, version = this.loopVersion_): Promise<void> => {
- if (!this.running_ || version !== this.loopVersion_) {
+ if (!this.running_ || this.isExecutionHeld() || version !== this.loopVersion_) {
return;
}
@@ -1276,8 +1356,10 @@ export class App {
const rawDelta = Math.max(0, Math.min(deltaMs / 1000, this.maxDeltaTime_));
const delta = rawDelta * this.play_speed_;
+ this.frame_paused_ = false;
+ this.boot_();
await this.flushStartupSystems_();
- if (!this.running_ || version !== this.loopVersion_) return;
+ if (!this.running_ || this.isExecutionHeld() || version !== this.loopVersion_) return;
const frame = this.runFrame_(delta, Math.max(0, deltaMs));
this.frameInFlight_ = frame;
try { await frame; }
@@ -1298,6 +1380,9 @@ export class App {
}
private quit_(options?: { keepRenderer?: boolean }): void {
+ this.executionEpoch_++;
+ this.executionHolds_.clear();
+ if (this.hasResource(Input)) setInputExecutionHeld(this.getResource(Input), this, false);
this.invalidateLoop_();
this.running_ = false;
@@ -1307,6 +1392,7 @@ export class App {
}
}
this.installed_plugins_.length = 0;
+ this.executionObservers_.length = 0;
this.installedPluginSet_.clear();
this.installedPluginNames_.clear();
@@ -1405,6 +1491,9 @@ export class App {
}
private async runFrame_(delta: number, frameMs = delta * 1000): Promise<void> {
+ if (this.isExecutionHeld()) return;
+ const executionEpoch = this.executionEpoch_;
+ const current = () => !this.isExecutionHeld() && executionEpoch === this.executionEpoch_;
this.runner_?.clearTimings();
this.phaseTimings_?.clear();
this.frameScopes_?.clear();
@@ -1415,9 +1504,10 @@ export class App {
this.frame_paused_ = false;
if (this.isPaused() && !this.step_pending_) {
- await this.runSchedule(Schedule.Last);
+ await this.runSchedule(Schedule.Last, executionEpoch);
} else {
- await this.runSchedule(Schedule.First);
+ await this.runSchedule(Schedule.First, executionEpoch);
+ if (!current()) return;
// The SCALED delta, so Time.scale = 0 stops the fixed steps too —
// otherwise physics would keep stepping through a paused world.
@@ -1439,10 +1529,11 @@ export class App {
// (1-based) — the simulation time axis netcode stamps packets with.
this.resources_.get(Time).fixedTick++;
input?.beginFixedStep();
- await this.runSchedule(Schedule.FixedPreUpdate);
- await this.runSchedule(Schedule.FixedUpdate);
- await this.runSchedule(Schedule.FixedPostUpdate);
+ await this.runSchedule(Schedule.FixedPreUpdate, executionEpoch);
+ await this.runSchedule(Schedule.FixedUpdate, executionEpoch);
+ await this.runSchedule(Schedule.FixedPostUpdate, executionEpoch);
input?.endFixedStep();
+ if (!current()) return;
fixedSteps++;
// Stop catching up once this frame's fixed steps blow the time
// budget — drop the backlog below so we don't spiral.
@@ -1459,16 +1550,17 @@ export class App {
this.resources_.get(Time).fixedAlpha =
this.fixedTimestep_ > 0 ? this.fixedAccumulator_ / this.fixedTimestep_ : 0;
- await this.runSchedule(Schedule.PreUpdate);
- await this.runSchedule(Schedule.Update);
- await this.runSchedule(Schedule.PostUpdate);
- await this.runSchedule(Schedule.Last);
+ await this.runSchedule(Schedule.PreUpdate, executionEpoch);
+ await this.runSchedule(Schedule.Update, executionEpoch);
+ await this.runSchedule(Schedule.PostUpdate, executionEpoch);
+ await this.runSchedule(Schedule.Last, executionEpoch);
if (this.step_pending_) {
this.step_pending_ = false;
}
}
+ if (!current()) return;
this.frameTiming_ = { seq: (this.frameTiming_?.seq ?? 0) + 1, frameMs };
for (const observe of this.frameObservers_) {
try { observe(frameMs); } catch (e) {
@@ -1653,26 +1745,29 @@ export class App {
return sorted;
}
- private flushing_startup_ = false;
+ private startupInFlight_: Promise<void> | null = null;
private async flushStartupSystems_(): Promise<void> {
- if (this.flushing_startup_) return;
const startup = this.systems_.get(Schedule.Startup)!;
- if (startup.length === 0) return;
- this.flushing_startup_ = true;
- try {
- await this.runSchedule(Schedule.Startup);
- startup.length = 0;
- this.sortedSystemsCache_.delete(Schedule.Startup);
- this.dependencyCache_.delete(Schedule.Startup);
- } finally {
- this.flushing_startup_ = false;
+ const executionEpoch = this.executionEpoch_;
+ while (startup.length && !this.isExecutionHeld() && !this.frame_paused_ && executionEpoch === this.executionEpoch_) {
+ if (!this.startupInFlight_) {
+ this.startupInFlight_ = Promise.resolve().then(async () => {
+ await this.runSchedule(Schedule.Startup, executionEpoch);
+ for (let index = startup.length - 1; index >= 0; index--) {
+ if (startup[index].startupInvoked) startup.splice(index, 1);
+ }
+ this.sortedSystemsCache_.delete(Schedule.Startup);
+ this.dependencyCache_.delete(Schedule.Startup);
+ }).finally(() => { this.startupInFlight_ = null; });
+ }
+ await this.startupInFlight_;
}
}
- private async runSchedule(schedule: Schedule): Promise<void> {
+ private async runSchedule(schedule: Schedule, executionEpoch = this.executionEpoch_): Promise<void> {
const rawSystems = this.systems_.get(schedule);
- if (!rawSystems || !this.runner_ || this.frame_paused_) {
+ if (!rawSystems || !this.runner_ || this.frame_paused_ || this.isExecutionHeld() || executionEpoch !== this.executionEpoch_) {
return;
}
@@ -1700,8 +1795,9 @@ export class App {
for (let i = 0; i < systems.length; i++) {
const entry = systems[i];
- if (this.frame_paused_) break;
- if (entry.runIf && !entry.runIf()) continue;
+ if (this.frame_paused_ || this.isExecutionHeld() || executionEpoch !== this.executionEpoch_) break;
+ if (schedule === Schedule.Startup && entry.startupInvoked) continue;
+ if (entry.runIf && !entry.runIf()) { if (schedule === Schedule.Startup) entry.startupInvoked = true; continue; }
// Where the declarations are spent rather than reported: a system
// starts beside an unfinished one only when it neither depends on it
@@ -1715,6 +1811,9 @@ export class App {
if (blocked) await settle();
}
+ if (this.frame_paused_ || this.isExecutionHeld() || executionEpoch !== this.executionEpoch_) break;
+ if (schedule === Schedule.Startup) entry.startupInvoked = true;
+
try {
this.currentSystem_ = entry.system._name;
const result = this.runner_.run(entry.system);
diff --git a/sdk/src/audio/AudioPlugin.ts b/sdk/src/audio/AudioPlugin.ts
index abfdd0601..d5d5291a9 100644
--- a/sdk/src/audio/AudioPlugin.ts
+++ b/sdk/src/audio/AudioPlugin.ts
@@ -46,6 +46,7 @@ interface AudioPluginState {
released: boolean;
offMemoryWarning: () => void;
offAudioMute: () => void;
+ offExecution: () => void;
offDespawn: () => void;
}
@@ -82,6 +83,8 @@ export class AudioPlugin implements Plugin {
const offAudioMute = (isPlatformInitialized()
? getPlatform().onAudioMute?.(muted => setAudioHostSuspended(audio, muteOwner, muted))
: undefined) ?? (() => {});
+ const executionOwner = {};
+ const offExecution = app.onExecutionChange(held => setAudioHostSuspended(audio, executionOwner, held));
// OS memory pressure → drop the decoded-buffer warm cache. Held
// buffers keep playing; re-fetch cost returns only for evicted ones.
@@ -107,7 +110,7 @@ export class AudioPlugin implements Plugin {
}
playedEntities.delete(entity);
});
- const state = { activeSourceHandles, playedEntities, audio, offMemoryWarning, offAudioMute, offDespawn, released: false };
+ const state = { activeSourceHandles, playedEntities, audio, offMemoryWarning, offAudioMute, offExecution, offDespawn, released: false };
this.states_.set(app, state);
this.latestState_ = state;
const stopVoice = (id: number): void => {
@@ -329,6 +332,7 @@ export class AudioPlugin implements Plugin {
if (app) this.states_.delete(app);
if (state === this.latestState_) this.latestState_ = null;
state.offAudioMute();
+ state.offExecution();
state.offMemoryWarning();
state.offDespawn();
this.stopSources_(state);
diff --git a/sdk/src/input/input.ts b/sdk/src/input/input.ts
index e67ebf50a..0495332ac 100644
--- a/sdk/src/input/input.ts
+++ b/sdk/src/input/input.ts
@@ -407,6 +407,21 @@ export class InputState {
*/
export const Input = defineResource<InputState>(new InputState(), 'Input');
+const executionOwners = new WeakMap<InputState, Set<object>>();
+/** Internal, per-owner execution gate for the platform event funnel. */
+export function setInputExecutionHeld(state: InputState, owner: object, held: boolean): void {
+ let owners = executionOwners.get(state);
+ if (held) {
+ if (!owners) { owners = new Set(); executionOwners.set(state, owners); }
+ const wasHeld = owners.size > 0;
+ owners.add(owner);
+ if (!wasHeld) inputEventCallbacks(state).onInputCancel?.();
+ } else {
+ owners?.delete(owner);
+ if (!owners?.size) executionOwners.delete(state);
+ }
+}
+
/**
* The callbacks a platform's raw events arrive through — routed past the UI
* first, then recorded on `state`.
@@ -428,15 +443,18 @@ export function inputEventCallbacks(state: InputState): InputEventCallbacks {
};
return {
onKeyDown(code) {
+ if (executionOwners.has(state)) return claimsKeyDefault(state, code);
if (inputRouter.dispatchKeyDown(code)) return true;
state.noteKeyDown(code);
return claimsKeyDefault(state, code);
},
onKeyUp(code) {
+ if (executionOwners.has(state)) return;
if (inputRouter.dispatchKeyUp(code)) state.keysDown.delete(code);
else if (state.keysDown.has(code)) state.noteKeyUp(code);
},
onPointerMove(x, y) {
+ if (executionOwners.has(state)) return;
// Pointer position tracks the cursor even when consumed so
// gameplay code that reads `getMousePosition()` (e.g. HUD
// cursor rendering) doesn't freeze while the editor is
@@ -446,12 +464,14 @@ export function inputEventCallbacks(state: InputState): InputEventCallbacks {
inputRouter.dispatchPointerMove(x, y);
},
onPointerDown(button, x, y) {
+ if (executionOwners.has(state)) return;
state.mouseX = x;
state.mouseY = y;
if (inputRouter.dispatchPointerDown(button, x, y)) return;
state.noteMouseDown(button);
},
onPointerUp(button) {
+ if (executionOwners.has(state)) return;
if (inputRouter.dispatchPointerUp(button)) {
state.mouseButtons.delete(button);
if (button === 0) cancelPrimaryPointer(state);
@@ -459,17 +479,20 @@ export function inputEventCallbacks(state: InputState): InputEventCallbacks {
else if (state.mouseButtons.has(button)) state.noteMouseUp(button);
},
onWheel(deltaX, deltaY) {
+ if (executionOwners.has(state)) return;
if (inputRouter.dispatchWheel(deltaX, deltaY)) return;
state.scrollDeltaX += deltaX;
state.scrollDeltaY += deltaY;
},
onTouchStart(id, x, y) {
+ if (executionOwners.has(state)) return;
if (inputRouter.dispatchTouchStart(id, x, y)) return;
const point = { id, x, y };
state.touches.set(id, point);
state.touchesStarted.set(id, point);
},
onTouchMove(id, x, y) {
+ if (executionOwners.has(state)) return;
if (inputRouter.dispatchTouchMove(id, x, y)) return;
const existing = state.touches.get(id);
if (existing) {
@@ -478,9 +501,11 @@ export function inputEventCallbacks(state: InputState): InputEventCallbacks {
}
},
onTouchEnd(id) {
+ if (executionOwners.has(state)) return;
finishTouch(id, inputRouter.dispatchTouchEnd(id));
},
onTouchCancel(id, primary) {
+ if (executionOwners.has(state)) return;
inputRouter.dispatchTouchCancel(id);
state.touches.delete(id);
state.touchesStarted.delete(id);
@@ -495,6 +520,7 @@ export function inputEventCallbacks(state: InputState): InputEventCallbacks {
}
},
onInputCancel() {
+ inputRouter.resetModifiers();
state.keysDown.clear();
state.mouseButtons.clear();
state.touches.clear();
@@ -513,6 +539,7 @@ export class InputPlugin implements Plugin {
name = 'input';
private target_: unknown;
private unbind_: (() => void) | null = null;
+ private readonly executionCleanup_ = new WeakMap<App, () => void>();
constructor(target?: unknown) {
this.target_ = target ?? null;
@@ -521,6 +548,8 @@ export class InputPlugin implements Plugin {
build(app: App): void {
const state = new InputState();
app.insertResource(Input, state);
+ const offExecution = app.onExecutionChange(held => setInputExecutionHeld(state, app, held));
+ this.executionCleanup_.set(app, () => { offExecution(); setInputExecutionHeld(state, app, false); });
state.touchAvailable = getPlatform().hasTouch?.() ?? false;
getPlatform().bindInputEvents(inputEventCallbacks(state), this.target_ ?? undefined);
@@ -541,7 +570,8 @@ export class InputPlugin implements Plugin {
}, { name: 'InputClearSystem' }));
}
- cleanup(): void {
+ cleanup(app?: App): void {
+ if (app) { this.executionCleanup_.get(app)?.(); this.executionCleanup_.delete(app); }
platformUnbindInputEvents();
}
}
diff --git a/sdk/src/input/inputRouter.ts b/sdk/src/input/inputRouter.ts
index 76f1d002d..e204497cb 100644
--- a/sdk/src/input/inputRouter.ts
+++ b/sdk/src/input/inputRouter.ts
@@ -82,6 +82,9 @@ export class InputRouter {
return this.mods_;
}
+ /** Clear cancelled key chords without delivering input to handlers. */
+ resetModifiers(): void { this.mods_ = NO_MODS; }
+
// ── Dispatch (called by InputPlugin) ────────────────────────────────
dispatchKeyDown(code: string): boolean {
diff --git a/sdk/src/ui/input/interaction.ts b/sdk/src/ui/input/interaction.ts
index c5811eae3..5ff883e22 100644
--- a/sdk/src/ui/input/interaction.ts
+++ b/sdk/src/ui/input/interaction.ts
@@ -84,6 +84,10 @@ export class UIInteractionPlugin implements Plugin {
app.insertResource(UIControlPointers, { pointers: controlPointers });
/** Where each pointer last hit, so a settled pointer skips the raycast. */
const lastHit = new UiPointerHitCache();
+ const offExecution = app.onExecutionChange(held => {
+ if (!held) return;
+ book.clear(); controlPointers.clear(); lastHit.clear(); expireGestureFired(world);
+ });
let lastLayoutGen = -1;
let lastWorldVersion = -1;
let lastTick = -1;
@@ -94,6 +98,7 @@ export class UIInteractionPlugin implements Plugin {
// During the host's release event, from what the last frame saw: the
// control this pointer pressed, if it is still the one under it.
const releaseInGesture = (pointer: number): void => {
+ if (app.isExecutionHeld()) return;
const held = book.releasing(pointer, lastHit.get(pointer)?.entity ?? null);
if (held === null || !eligible(held)) return;
if (world.has(held, Interactable) && !(world.get(held, Interactable) as InteractableData).enabled) return;
@@ -104,6 +109,7 @@ export class UIInteractionPlugin implements Plugin {
onPointerUp: (button) => { if (button === 0) releaseInGesture(MOUSE_POINTER); },
});
this.releases_.set(app, () => {
+ offExecution();
unregister();
book.clear();
controlPointers.clear();
diff --git a/sdk/src/video/VideoAPI.ts b/sdk/src/video/VideoAPI.ts
index 42fcbac7b..c07ca2e18 100644
--- a/sdk/src/video/VideoAPI.ts
+++ b/sdk/src/video/VideoAPI.ts
@@ -20,9 +20,13 @@ export class VideoAPI {
private readonly muteTargets_ = new Map<VideoStreamHandle, () => void>();
private readonly offHostMute_: () => void;
private readonly hasHostMute_: boolean;
+ private executionHeld_ = false;
+ private readonly playbackTargets_ = new Map<VideoStreamHandle, (held: boolean) => void>();
+ private readonly offExecution_: () => void;
+ private readonly hasExecutionPolicy_: boolean;
baseUrl = '';
- constructor(backend: PlatformVideoBackend) {
+ constructor(backend: PlatformVideoBackend, observeExecution?: (callback: (held: boolean) => void) => () => void) {
this.backend_ = backend;
const subscribe = isPlatformInitialized() ? getPlatform().onAudioMute : undefined;
this.hasHostMute_ = subscribe !== undefined;
@@ -30,6 +34,17 @@ export class VideoAPI {
this.hostMuted_ = muted;
for (const apply of this.muteTargets_.values()) apply();
}) ?? (() => {});
+ this.hasExecutionPolicy_ = observeExecution !== undefined;
+ this.offExecution_ = observeExecution?.(held => {
+ if (held === this.executionHeld_) return;
+ this.executionHeld_ = held;
+ for (const [handle, apply] of this.playbackTargets_) {
+ try { apply(held); } catch (error) {
+ log.error('video', 'Execution policy failed for a stream', error);
+ try { this.stop(handle); } catch { /* broken stream does not block other streams */ }
+ }
+ }
+ }) ?? (() => {});
}
get backendName(): string { return this.backend_.name; }
@@ -48,20 +63,30 @@ export class VideoAPI {
play(source: string, options: VideoPlayOptions = {}): VideoStreamHandle {
let userMuted = options.muted ?? false;
+ let userPlaying = options.autoplay ?? true;
const stream = this.backend_.createStream(this.resolveUrl_(source), {
...options,
...(this.hasHostMute_ ? { muted: userMuted || this.hostMuted_ } : {}),
+ ...(this.executionHeld_ ? { autoplay: false } : {}),
audioTrackUrl: options.audioTrackUrl ?? this.resolveAudioTrack_(source),
});
let handle = stream;
- if (this.hasHostMute_) {
+ if (this.hasHostMute_ || this.hasExecutionPolicy_) {
const setMuted = stream.setMuted.bind(stream);
+ const play = stream.play.bind(stream), pause = stream.pause.bind(stream), stop = stream.stop.bind(stream);
const methods = new Set(['play', 'pause', 'stop', 'seek', 'setVolume', 'setLoop', 'setPlaybackRate', 'pump']);
const bindings = new Map<PropertyKey, { original: unknown; bound: unknown }>();
const overrideMuted = (muted: boolean) => { userMuted = muted; setMuted(userMuted || this.hostMuted_); };
+ const overridePlay = () => { userPlaying = true; if (!this.executionHeld_) play(); };
+ const overridePause = () => { userPlaying = false; pause(); };
+ const overrideStop = () => { userPlaying = false; stop(); };
+ const ownsExecution = this.hasExecutionPolicy_;
handle = new Proxy(stream, {
get(target, key) {
if (key === 'setMuted') return overrideMuted;
+ if (ownsExecution && key === 'play') return overridePlay;
+ if (ownsExecution && key === 'pause') return overridePause;
+ if (ownsExecution && key === 'stop') return overrideStop;
const value = Reflect.get(target, key, target);
if (typeof key === 'string' && methods.has(key) && typeof value === 'function') {
let entry = bindings.get(key);
@@ -73,6 +98,13 @@ export class VideoAPI {
set(target, key, value) { return Reflect.set(target, key, value, target); },
});
this.muteTargets_.set(handle, () => setMuted(userMuted || this.hostMuted_));
+ if (this.hasExecutionPolicy_) this.playbackTargets_.set(handle, held => {
+ if (held) {
+ // A completed or already-paused stream must not restart on release.
+ if (stream.isReady && !stream.isPlaying) userPlaying = false;
+ pause();
+ } else if (userPlaying) play();
+ });
}
this.handles_.add(handle);
return handle;
@@ -102,6 +134,7 @@ export class VideoAPI {
log.error('video', `pump failed for stream #${handle.id} — stopping it`, err);
this.handles_.delete(handle);
this.muteTargets_.delete(handle);
+ this.playbackTargets_.delete(handle);
try { handle.stop(); } catch { /* already broken */ }
handle.onError?.(err);
}
@@ -110,6 +143,7 @@ export class VideoAPI {
stop(handle: VideoStreamHandle): void {
this.muteTargets_.delete(handle);
+ this.playbackTargets_.delete(handle);
if (this.handles_.delete(handle)) handle.stop();
}
@@ -117,12 +151,14 @@ export class VideoAPI {
for (const handle of this.handles_) handle.stop();
this.handles_.clear();
this.muteTargets_.clear();
+ this.playbackTargets_.clear();
}
dispose(): void {
if (this.disposed_) return;
this.disposed_ = true;
this.offHostMute_();
+ this.offExecution_();
this.stopAll();
this.backend_.dispose();
}
diff --git a/sdk/src/video/VideoPlugin.ts b/sdk/src/video/VideoPlugin.ts
index 4455b232e..b997badec 100644
--- a/sdk/src/video/VideoPlugin.ts
+++ b/sdk/src/video/VideoPlugin.ts
@@ -85,7 +85,7 @@ export class VideoPlugin implements Plugin {
try { return app.getResource(Audio); } catch { return null; }
},
}) ?? new NullVideoBackend();
- const video = new VideoAPI(backend);
+ const video = new VideoAPI(backend, app.onExecutionChange.bind(app));
app.insertResource(VideoPlayer, video);
const handles = new Map<number, VideoStreamHandle>();
diff --git a/sdk/tests/audio-plugin-lifecycle.test.ts b/sdk/tests/audio-plugin-lifecycle.test.ts
index 161313a18..c208ffa3c 100644
--- a/sdk/tests/audio-plugin-lifecycle.test.ts
+++ b/sdk/tests/audio-plugin-lifecycle.test.ts
@@ -43,6 +43,13 @@ it('host mute overrides game resume and preserves explicit suspension after host
audio.resume(); expect(backend.resume).toHaveBeenCalledOnce();
app.quit(); expect(muteListeners.size).toBe(0);
});
+it('execution holds keep audio suspended until the final owner releases, preserving user suspension', () => {
+ const app=build(new AudioPlugin()),audio=app.getResource(Audio),backend=backends[0];
+ const first=app.holdExecution(),second=app.holdExecution();audio.resume();
+ expect(backend.suspend).toHaveBeenCalledOnce();expect(backend.resume).not.toHaveBeenCalled();
+ first();expect(backend.resume).not.toHaveBeenCalled();audio.suspend();second();
+ expect(backend.resume).not.toHaveBeenCalled();audio.resume();expect(backend.resume).toHaveBeenCalledOnce();
+});
it('quitting an older app releases its backend and preserves the newer app voice and subscription', async () => {
const plugin=new AudioPlugin(), first=build(plugin), second=build(plugin);
const a=first.getResource(Audio), b=second.getResource(Audio);
diff --git a/sdk/tests/execution-hold.test.ts b/sdk/tests/execution-hold.test.ts
new file mode 100644
index 000000000..502271a0b
--- /dev/null
+++ b/sdk/tests/execution-hold.test.ts
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { App } from '../src/app/app';
+import { Schedule, defineSystem } from '../src/ecs/system';
+import { Time } from '../src/ecs/resource';
+import { Input, InputState, inputEventCallbacks } from '../src/input/input';
+import { inputRouter } from '../src/input/inputRouter';
+import { setPlatform } from '../src/platform/base';
+import { webAdapter } from '../src/platform/web';
+
+const apps: App[] = [], frames=new Map<number,FrameRequestCallback>();let nextFrame=0;
+beforeEach(()=>{
+ setPlatform(webAdapter);
+ vi.stubGlobal('requestAnimationFrame',(callback:FrameRequestCallback)=>{const id=++nextFrame;frames.set(id,callback);return id;});
+ vi.stubGlobal('cancelAnimationFrame',(id:number)=>frames.delete(id));
+ inputRouter.setUIHandler(null);inputRouter.setEditorHandler(null);
+});
+afterEach(()=>{for(const app of apps.splice(0))app.quit();frames.clear();vi.unstubAllGlobals();inputRouter.setUIHandler(null);});
+function build(){const app=App.new();apps.push(app);return app;}
+function deferred(){let resolve!:()=>void;const promise=new Promise<void>(r=>{resolve=r;});return{promise,resolve};}
+it('holds every schedule, frame observers and forced stepping without changing user pause',async()=>{
+ const app=build(), events:string[]=[];
+ for(const schedule of [Schedule.Startup,Schedule.First,Schedule.Update,Schedule.Last])app.addSystemToSchedule(schedule,defineSystem([],()=>{events.push(Schedule[schedule]);}));
+ app.onFrameEnd(()=>events.push('frame'));app.setPaused(true);
+ const first=app.holdExecution(),second=app.holdExecution();
+ app.stepFrame();
+ await app.tick(1/60);await app.stepFrames(3);expect(events).toEqual([]);
+ first();first();await app.tick(1/60);expect(events).toEqual([]);expect(app.isPaused()).toBe(true);
+ second();await app.tick(1/60);expect(events).toEqual(['Startup','Last','frame']);expect(app.isPaused()).toBe(true);
+ app.setPaused(false);await app.tick(1/60);expect(events.slice(-4)).toEqual(['First','Update','Last','frame']);
+});
+it('discards queued keyboard/pointer input and blocks the native gesture router while held',async()=>{
+ const app=build(),input=new InputState();app.insertResource(Input,input);
+ const routed=vi.fn(()=>false);inputRouter.setUIHandler({onPointerUp:routed,onTouchEnd:routed,onKeyDown:routed});
+ const callbacks=inputEventCallbacks(input);callbacks.onKeyDown?.('KeyD');callbacks.onPointerDown?.(0,10,10);
+ const release=app.holdExecution();expect(input.keysDown.size).toBe(0);expect(input.mouseButtons.size).toBe(0);routed.mockClear();
+ callbacks.onPointerUp?.(0);callbacks.onTouchEnd?.(1);expect(callbacks.onKeyDown?.('Space')).toBe(false);
+ expect(routed).not.toHaveBeenCalled();expect(input.keysDown.size).toBe(0);
+ release();callbacks.onKeyDown?.('KeyD');expect(input.keysDown.has('KeyD')).toBe(true);
+});
+it('stops dependent systems after a hold interrupts an asynchronous frame, even when released early',async()=>{
+ const app=build(),waiting=deferred(),started=deferred(), events:string[]=[];
+ app.addSystemToSchedule(Schedule.Update,defineSystem([],async()=>{events.push('first');started.resolve();await waiting.promise;},{name:'AsyncFirst'}));
+ app.addSystemToSchedule(Schedule.Update,defineSystem([],()=>{events.push('second');},{name:'Dependent',runAfter:['AsyncFirst']}));
+ app.addSystemToSchedule(Schedule.Last,defineSystem([],()=>{events.push('render');}));app.onFrameEnd(()=>events.push('observed'));
+ const tick=app.tick(1/60);await started.promise;const release=app.holdExecution();release();waiting.resolve();await tick;
+ expect(events).toEqual(['first']);await app.tick(1/60);expect(events.slice(-4)).toEqual(['first','second','render','observed']);
+});
+it('preserves unstarted startup systems and waits for the interrupted startup before an automatic frame',async()=>{
+ const app=build(),waiting=deferred(),started=deferred(),events:string[]=[];
+ app.addSystemToSchedule(Schedule.Startup,defineSystem([],async()=>{events.push('start-a');started.resolve();await waiting.promise;},{name:'StartA'}));
+ app.addSystemToSchedule(Schedule.Startup,defineSystem([],()=>{events.push('start-b');},{name:'StartB',runAfter:['StartA']}));
+ app.addSystemToSchedule(Schedule.Update,defineSystem([],()=>{events.push('update');}));
+ const running=app.run();await started.promise;const release=app.holdExecution();release();
+ await vi.waitFor(()=>expect(frames.size).toBe(1));const [id,callback]=frames.entries().next().value!;frames.delete(id);callback(performance.now());
+ await Promise.resolve();expect(events).toEqual(['start-a']);waiting.resolve();await running;
+ await vi.waitFor(()=>expect(events).toEqual(['start-a','start-b','update']));
+});
+it('can be held before run and resumes only one RAF loop with a fresh clock',async()=>{
+ const app=build(),observe=vi.fn();app.onFrameEnd(observe);
+ const release=app.holdExecution();await app.run();expect(observe).not.toHaveBeenCalled();expect(frames.size).toBe(0);
+ release();release();await vi.waitFor(()=>expect(frames.size).toBe(1));
+ const [id,callback]=frames.entries().next().value!;frames.delete(id);callback(performance.now());
+ await vi.waitFor(()=>expect(observe).toHaveBeenCalledOnce());expect(app.getResource(Time).delta).toBeLessThan(0.1);
+ expect(frames.size).toBe(1);
+});
+it('ignores stale releases after quit and withdraws execution observers',async()=>{
+ const app=build(),observer=vi.fn();app.onExecutionChange(observer);const release=app.holdExecution();
+ expect(observer.mock.calls.map(args=>args[0])).toEqual([false,true]);app.quit();release();expect(frames.size).toBe(0);
+ app.holdExecution();expect(observer).toHaveBeenCalledTimes(2);
+});
+it('keeps automatic running intent after a forced step is interrupted',async()=>{
+ const app=build(),waiting=deferred(),started=deferred();let block=false;
+ app.addSystemToSchedule(Schedule.Update,defineSystem([],async()=>{if(block){started.resolve();await waiting.promise;}}));
+ await app.run();await vi.waitFor(()=>expect(frames.size).toBe(1));block=true;
+ const stepping=app.stepFrames(3);await started.promise;const release=app.holdExecution();
+ waiting.resolve();await stepping;expect(frames.size).toBe(0);
+ release();await vi.waitFor(()=>expect(frames.size).toBe(1));
+});
+it('preserves input holds owned by another app sharing the state',()=>{
+ const a=build(),b=build(),input=new InputState();a.insertResource(Input,input);b.insertResource(Input,input);
+ const releaseA=a.holdExecution(),releaseB=b.holdExecution(),callbacks=inputEventCallbacks(input);
+ a.quit();releaseA();callbacks.onKeyDown?.('KeyD');expect(input.keysDown.size).toBe(0);
+ releaseB();callbacks.onKeyDown?.('KeyD');expect(input.keysDown.has('KeyD')).toBe(true);
+});
+it('does not leave a forced step queued after interruption of a user-paused app',async()=>{
+ const app=build(),waiting=deferred(),started=deferred();let updates=0;
+ app.setPaused(true);app.addSystemToSchedule(Schedule.Update,defineSystem([],async()=>{updates++;started.resolve();await waiting.promise;}));
+ await app.run();await vi.waitFor(()=>expect(frames.size).toBe(1));
+ const stepping=app.stepFrames(2);await started.promise;const release=app.holdExecution();waiting.resolve();await stepping;
+ release();await vi.waitFor(()=>expect(frames.size).toBe(1));
+ const [id,callback]=frames.entries().next().value!;frames.delete(id);callback(performance.now());
+ await vi.waitFor(()=>expect(frames.size).toBe(1));expect(updates).toBe(1);expect(app.isPaused()).toBe(true);
+});
diff --git a/sdk/tests/video-execution-hold.test.ts b/sdk/tests/video-execution-hold.test.ts
new file mode 100644
index 000000000..bf808959a
--- /dev/null
+++ b/sdk/tests/video-execution-hold.test.ts
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { afterEach, expect, it, vi } from 'vitest';
+import { App } from '../src/app/app';
+import { VideoAPI } from '../src/video/VideoAPI';
+import { NullVideoBackend } from '../src/video/NullVideoBackend';
+const apps:App[]=[],videos:VideoAPI[]=[];
+afterEach(()=>{for(const video of videos.splice(0))video.dispose();for(const app of apps.splice(0))app.quit();});
+function fixture() {
+ const app=App.new();apps.push(app);
+ const backend=new NullVideoBackend(),create=vi.spyOn(backend,'createStream');
+ const video=new VideoAPI(backend,app.onExecutionChange.bind(app));videos.push(video);
+ return {app,video,create};
+}
+it('pauses playing streams, blocks play during holds and restores the player preference',()=>{
+ const {app,video}=fixture(),playing=video.play('playing.mp4'),paused=video.play('paused.mp4');paused.pause();
+ const first=app.holdExecution(),second=app.holdExecution();expect(playing.isPlaying).toBe(false);
+ playing.play();expect(playing.isPlaying).toBe(false);first();expect(playing.isPlaying).toBe(false);
+ second();expect(playing.isPlaying).toBe(true);expect(paused.isPlaying).toBe(false);
+ const next=app.holdExecution();playing.pause();next();expect(playing.isPlaying).toBe(false);
+});
+it('creates non-autoplay streams during a hold and does not revive stopped streams',()=>{
+ const {app,video,create}=fixture(),release=app.holdExecution();
+ const pending=video.play('pending.mp4'),stopped=video.play('stopped.mp4');
+ expect(create.mock.calls[0][1].autoplay).toBe(false);expect(pending.isPlaying).toBe(false);
+ stopped.stop();release();expect(pending.isPlaying).toBe(true);expect(stopped.isPlaying).toBe(false);
+});
+it('does not restart completed streams or retain retired handles after disposal',()=>{
+ const {app,video,create}=fixture(),ended=video.play('ended.mp4');
+ const raw=create.mock.results[0].value;Object.defineProperty(raw,'isReady',{value:true});raw.pause();
+ const release=app.holdExecution();release();expect(ended.isPlaying).toBe(false);
+ const playing=video.play('playing.mp4');video.dispose();
+ const late=app.holdExecution();late();expect(playing.isPlaying).toBe(false);
+});
diff --git a/sdk/tests/video-plugin-lifecycle.test.ts b/sdk/tests/video-plugin-lifecycle.test.ts
index b755bfbdf..0fe2bd2d2 100644
--- a/sdk/tests/video-plugin-lifecycle.test.ts
+++ b/sdk/tests/video-plugin-lifecycle.test.ts
@@ -29,7 +29,9 @@ it('quitting an older app releases its video backend and preserves the newer app
first.quit();
expect(backends[0].dispose).toHaveBeenCalledOnce();
expect(backends[1].dispose).not.toHaveBeenCalled();
- expect(a.stop).toHaveBeenCalledOnce(); expect(b.stop).not.toHaveBeenCalled();
+ expect(vi.mocked(backends[0].createStream).mock.results[0].value.stop).toHaveBeenCalledOnce();
+ expect(vi.mocked(backends[1].createStream).mock.results[0].value.stop).not.toHaveBeenCalled();
+ expect(a.isPlaying).toBe(false); expect(b.isPlaying).toBe(true);
second.quit(); expect(backends[1].dispose).toHaveBeenCalledOnce();
});
@@ -37,10 +39,12 @@ it('releases 100 preview backends without stopping the main app video', () => {
const plugin = new VideoPlugin(), main = build(plugin);
const handle = main.getResource(VideoPlayer).play('main.mp4');
for (let i = 0; i < 100; i++) { const preview = build(plugin); preview.quit(); }
- expect(handle.stop).not.toHaveBeenCalled();
+ expect(vi.mocked(backends[0].createStream).mock.results[0].value.stop).not.toHaveBeenCalled();
+ expect(handle.isPlaying).toBe(true);
expect(backends[0].dispose).not.toHaveBeenCalled();
for (const backend of backends.slice(1)) expect(backend.dispose).toHaveBeenCalledOnce();
- main.quit(); expect(handle.stop).toHaveBeenCalledOnce();
+ main.quit(); expect(vi.mocked(backends[0].createStream).mock.results[0].value.stop).toHaveBeenCalledOnce();
+ expect(handle.isPlaying).toBe(false);
});
it('stopAll retires component handles from the video service, once', async () => {
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 844db23de..fdb337071 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -30,6 +30,8 @@ export const NOTES_FLOOR = 'v0.65.0';
export const NOTED = {
'perf(text): reclaim unused glyph pages at frame boundaries':
{ note: 'Unused text atlas pages retire at frame boundaries.' },
+ 'feat(app): hold execution across frames input and media':
+ { note: 'App execution holds stop owned frames, input and media.' },
'feat(storage): await asynchronous host persistence':
{ note: 'Storage exposes asynchronous write acknowledgment.' },
'fix(text): rasterize enlarged bitmap glyphs within atlas limits':
diff --git a/tools/tests/execution-hold.e2e.mjs b/tools/tests/execution-hold.e2e.mjs
new file mode 100644
index 000000000..4c636e81d
--- /dev/null
+++ b/tools/tests/execution-hold.e2e.mjs
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import fs from 'node:fs';import path from 'node:path';import http from 'node:http';import crypto from 'node:crypto';
+import assert from 'node:assert/strict';import {chromium} from 'playwright';
+const args=process.argv.slice(2),flag=name=>args[args.indexOf(name)+1];
+if(!args.includes('--dir'))throw Error('Expected --dir <fixture export>');
+const root=fs.realpathSync(flag('--dir')),out=path.resolve(args.includes('--out')?flag('--out'):'output/execution-hold-check');fs.mkdirSync(out,{recursive:true});
+const sha=file=>crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
+const files=(under='')=>fs.readdirSync(path.join(root,under),{withFileTypes:true}).flatMap(entry=>{
+ const file=under?`${under}/${entry.name}`:entry.name;if(entry.isDirectory())return files(file);
+ if(!entry.isFile())throw Error('Unsupported export entry');return[file];
+});
+const identities=Object.fromEntries(files().map(file=>[file,sha(path.join(root,file))]));
+const report={headless:true,mode:'authored-fixture',status:'failed',identities,verifierSha256:sha(new URL(import.meta.url)),errors:[],unexpectedRequests:[],observations:[]};
+const mime={'.html':'text/html','.js':'text/javascript','.mjs':'text/javascript','.json':'application/json','.wasm':'application/wasm','.png':'image/png'};
+const server=http.createServer((req,res)=>{try{const name=decodeURIComponent(new URL(req.url,'http://localhost').pathname).slice(1)||'index.html';
+ const file=fs.realpathSync(path.resolve(root,name));if(!file.startsWith(root+path.sep)||!fs.statSync(file).isFile())throw Error('Outside export');
+ res.setHeader('Content-Type',mime[path.extname(file)]??'application/octet-stream');res.end(fs.readFileSync(file));}catch{res.writeHead(404);res.end();}});
+await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));const origin=`http://127.0.0.1:${server.address().port}`;
+const browser=await chromium.launch({headless:true,args:['--enable-unsafe-swiftshader','--use-angle=swiftshader','--mute-audio']});
+let page;
+try {
+ page=await browser.newPage({viewport:{width:800,height:450}});page.on('pageerror',error=>report.errors.push(String(error)));
+ report.console=[];page.on('console',message=>{if(message.type()==='error'||message.type()==='warning')report.console.push(message.text().slice(0,1000));});
+ await page.addInitScript(()=>{window.__audioContexts=[];const Original=window.AudioContext;
+ if(Original)window.AudioContext=class extends Original{constructor(...args){super(...args);window.__audioContexts.push(this);}};});
+ await page.route('**/*',route=>{const url=route.request().url();if(url.startsWith(origin+'/')||url.startsWith('data:'))return route.continue();report.unexpectedRequests.push(url);return route.abort();});
+ await page.goto(origin+'/?headless');await page.waitForFunction(()=>window.__executionFixture?.probe&&window.__estellaCooked?.probe(['ExecutionProbe']).at.ExecutionProbe);
+ await page.waitForFunction(()=>!document.getElementById('es-splash'));
+ const box=await page.evaluate(()=>__estellaCooked.probe(['ExecutionProbe']).at.ExecutionProbe),point={x:400+box.x,y:225-box.y};
+ await page.mouse.click(point.x,point.y);await page.waitForFunction(()=>__executionFixture.clicks===1&&__executionFixture.video?.isReady&&__executionFixture.video?.isPlaying);
+ await page.waitForFunction(()=>__audioContexts.length>0&&__audioContexts.every(context=>context.state==='running'));
+ const facts=()=>page.evaluate(async()=>{const{Time}=await import('esengine');const state=__executionFixture;return{frame:state.app.getResource(Time).frameCount,clicks:state.clicks,
+ playing:state.video.isPlaying,mediaTime:state.video.currentTime,player:__estellaCooked.probe(['Player']).at.Player};});
+ await page.mouse.move(point.x,point.y);await page.mouse.down();await page.waitForTimeout(100);
+ await page.evaluate(()=>{window.__releaseA=__executionFixture.app.holdExecution();window.__releaseB=__executionFixture.app.holdExecution();});
+ await page.waitForFunction(()=>__audioContexts.every(context=>context.state==='suspended'));
+ const held=await facts();assert.equal(held.playing,false);report.observations.push({stage:'held',...held});
+ await page.mouse.up();await page.mouse.click(point.x,point.y);await page.keyboard.press('KeyD');
+ await page.evaluate(async()=>{const{Audio}=await import('esengine');const state=__executionFixture;state.video.play();state.app.getResource(Audio).resume();await state.app.tick(1/60);await state.app.stepFrames(5);});
+ await page.waitForTimeout(200);const after=await facts();assert.deepEqual(after,held);assert.equal(after.clicks,1);
+ assert(await page.evaluate(()=>__audioContexts.every(context=>context.state==='suspended')));
+ await page.evaluate(()=>{__releaseA();__releaseA();});await page.waitForTimeout(80);assert.deepEqual(await facts(),held);
+ await page.evaluate(()=>__releaseB());await page.waitForFunction(()=>__executionFixture.video.isPlaying&&__audioContexts.every(context=>context.state==='running'));
+ await page.waitForTimeout(100);const resumed=await facts();assert(resumed.frame>held.frame);assert(resumed.mediaTime!==held.mediaTime);assert.equal(resumed.clicks,1);
+ await page.mouse.click(point.x,point.y);await page.waitForFunction(()=>__executionFixture.clicks===2);
+ await page.evaluate(()=>{__executionFixture.app.setPaused(true);window.__releaseC=__executionFixture.app.holdExecution();});
+ await page.evaluate(()=>__releaseC());assert(await page.evaluate(()=>__executionFixture.app.isPaused()));
+ const file='resumed.png';await page.screenshot({path:path.join(out,file)});report.screenshot={file,sha256:sha(path.join(out,file))};
+ report.observations.push({stage:'resumed',...resumed});
+ assert.deepEqual(report.errors,[]);assert.deepEqual(report.unexpectedRequests,[]);
+ assert.deepEqual(Object.fromEntries(files().map(file=>[file,sha(path.join(root,file))])),identities);report.status='checks-passed';
+} catch(error) {
+ report.failure=String(error);
+ if(page) {
+ report.failureFacts=await page.evaluate(()=>{const state=window.__executionFixture;return{clicks:state?.clicks,held:state?.app.isExecutionHeld(),
+ video:state?.video?{ready:state.video.isReady,playing:state.video.isPlaying,time:state.video.currentTime,width:state.video.width}:null,
+ box:window.__estellaCooked?.probe(['ExecutionProbe']).at.ExecutionProbe};}).catch(()=>null);
+ await page.screenshot({path:path.join(out,'failure.png')}).catch(()=>{});
+ }
+ throw error;
+} finally {fs.writeFileSync(path.join(out,'runtime-check.json'),JSON.stringify(report,null,2));await browser.close();await new Promise(resolve=>server.close(resolve));}
+console.log('Execution hold: frames, native gestures, real AudioContext and media clock passed headlessly');
diff --git a/tools/tests/export-execution-hold-fixture.mjs b/tools/tests/export-execution-hold-fixture.mjs
new file mode 100644
index 000000000..fe672114a
--- /dev/null
+++ b/tools/tests/export-execution-hold-fixture.mjs
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/** Disposable authored game fixture; no test controls enter the original example. */
+import fs from 'node:fs';import path from 'node:path';import {execFileSync} from 'node:child_process';
+const args=process.argv.slice(2),flag=name=>args[args.indexOf(name)+1];
+if(!args.includes('--wasm')||!args.includes('--out'))throw Error('Expected --wasm <runtime> --out <export>');
+const workspace=process.cwd(),output=path.resolve(workspace,'output');fs.mkdirSync(output,{recursive:true});
+const temporary=fs.mkdtempSync(path.join(output,'execution-hold-source-'));
+try {
+ const source=path.join(workspace,'examples/mobile-controls'),project=path.join(temporary,'game');
+ fs.cpSync(source,project,{recursive:true,filter:file=>!path.relative(source,file).split(path.sep).some(part=>part.startsWith('dist-')||part==='.esengine')});
+ const media='assets/execution-probe.mp4';
+ fs.copyFileSync(path.join(workspace,'fixtures/scenes/video-playback.mp4'),path.join(project,media));
+ fs.copyFileSync(path.join(workspace,'examples/video-playback/assets/video/clip.mp4.meta'),path.join(project,media+'.meta'));
+ const scenePath=path.join(project,'assets/scenes/main.esscene'),scene=JSON.parse(fs.readFileSync(scenePath,'utf8'));
+ scene.entities.push({id:Math.max(...scene.entities.map(entity=>entity.id))+1,name:'ExecutionMediaAsset',parent:null,children:[],visible:false,
+ components:[{type:'Video',data:{source:media,enabled:false,autoplay:false,muted:true}}]});
+ fs.writeFileSync(scenePath,JSON.stringify(scene));
+ fs.appendFileSync(path.join(project,'src/main.ts'),`
+import {addPlugin as fixturePlugin,createButton as fixtureButton,UIEvents as FixtureEvents,Res as FixtureRes,
+ GetWorld as FixtureWorld,defineSystem as fixtureSystem,Schedule as FixtureSchedule,Time as FixtureTime,
+ VideoPlayer as FixtureVideo,type VideoHandle as FixtureVideoHandle} from 'esengine';
+fixturePlugin({name:'ExecutionHoldFixture',build(app){
+ const state={app,clicks:0,probe:0,video:null as FixtureVideoHandle|null};
+ (window as unknown as {__executionFixture:unknown}).__executionFixture=state;
+ app.addSystemToSchedule(FixtureSchedule.Startup,fixtureSystem([FixtureRes(FixtureEvents),FixtureWorld()],(events,world)=>{
+ const parent=world.findEntityByName('Canvas');if(parent===null)throw Error('Fixture canvas missing');
+ const button=fixtureButton({world,events,parent,userGesture:true,text:'PROBE',
+ node:{position:UIPositionType.Absolute,insetLeft:px(360),insetTop:px(346),width:px(90),height:px(36)},
+ onClick:()=>{state.clicks++;if(!state.video)state.video=app.getResource(FixtureVideo).play(${JSON.stringify(media)},{muted:true,loop:true});}});
+ state.probe=button.entity;world.insert(button.entity,Name,{value:'ExecutionProbe'});
+ }));
+}});
+`);
+ execFileSync(process.execPath,['pipeline/bin/estella.mjs','export',project,'--platform','web','--wasm',path.resolve(flag('--wasm')),'--out',path.resolve(flag('--out'))],{cwd:workspace,stdio:'inherit',windowsHide:true});
+} finally {
+ const resolved=path.resolve(temporary);
+ if(path.dirname(resolved)!==output||!path.basename(resolved).startsWith('execution-hold-source-'))throw Error('Unsafe temporary source path');
+ fs.rmSync(resolved,{recursive:true,force:true,maxRetries:10,retryDelay:50});
+}