Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(audio): reject loads from retired context generations

yhhc0703c6cf21e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fc0c102e4..9372d0d68 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@ published separately; it ships inside the editor.
### Fixed
+- **Web audio loads cannot cross disposed or replaced contexts.** Async reads and decodes capture their context generation and validate it before decoding or publishing a buffer. Late work rejects without borrowing a new session's cached handle, replacing its source entry or repopulating disposed storage; current-session loads and same-session source revisions retain their existing behavior.
+
- **Web audio source records follow live buffer ownership.** URL cache entries and invalidation identities retire after their current buffer and pending loads are released, instead of retaining every historical scene path. Distinct source records preserve overlapping invalidated loads, and unloading an older result leaves the replacement cached; failed loads release their records too.
- **Web UI getters can reach their generated pointer accessors.** The optional UINode pointer export avoids full component object marshaling for pre-resolved readers, with existing generated layout assertions and fresh pointer resolution after pool growth. Live focus queries use compact per-query visibility flags and pre-resolved parent reads to reduce transient work; older cores retain the getter fallback.
diff --git a/sdk/src/audio/WebAudioBackend.ts b/sdk/src/audio/WebAudioBackend.ts
index 61f801ae7..91e3428fb 100644
--- a/sdk/src/audio/WebAudioBackend.ts
+++ b/sdk/src/audio/WebAudioBackend.ts
@@ -293,9 +293,11 @@ export class WebAudioBackend implements PlatformAudioBackend {
}
private async loadSource_(url: string, read: () => Promise<ArrayBuffer>): Promise<AudioBufferHandle> {
- if (!this.context_) {
+ const context = this.context_;
+ if (!context) {
throw new Error('AudioContext not initialized');
}
+ const generation = this.contextGeneration_;
const cached = this.cachedBuffer_(url);
if (cached) return cached;
let source = this.sources_.get(url);
@@ -305,7 +307,9 @@ export class WebAudioBackend implements PlatformAudioBackend {
}
source.pending++;
try {
- return await this.decodeBuffer_(url, await read(), source);
+ const data = await read();
+ this.assertLoadContext_(context, generation);
+ return await this.decodeBuffer_(url, data, source, context, generation);
} finally {
source.pending--;
if (this.sources_.get(url) === source && source.pending === 0 && source.bufferId === undefined) {
@@ -314,10 +318,16 @@ export class WebAudioBackend implements PlatformAudioBackend {
}
}
- private async decodeBuffer_(url: string, data: ArrayBuffer, source: SourceRecord): Promise<AudioBufferHandle> {
- if (!this.context_) {
- throw new Error('AudioContext not initialized');
+ private assertLoadContext_(context: AudioContext, generation: number): void {
+ if (this.context_ !== context || this.contextGeneration_ !== generation) {
+ throw new Error('AudioContext changed while loading audio');
}
+ }
+
+ private async decodeBuffer_(
+ url: string, data: ArrayBuffer, source: SourceRecord,
+ context: AudioContext, generation: number,
+ ): Promise<AudioBufferHandle> {
if (this.sources_.get(url) === source) {
const cached = this.cachedBuffer_(url);
if (cached) return cached;
@@ -325,10 +335,12 @@ export class WebAudioBackend implements PlatformAudioBackend {
let audioBuffer: AudioBuffer;
try {
- audioBuffer = await this.context_.decodeAudioData(data);
+ audioBuffer = await context.decodeAudioData(data);
} catch (err) {
+ this.assertLoadContext_(context, generation);
throw new Error(`Failed to decode audio ${url}: ${(err as Error).message}`);
}
+ this.assertLoadContext_(context, generation);
const id = ++this.nextBufferId_;
this.buffers_.set(id, { buffer: audioBuffer, url });
diff --git a/sdk/tests/web-audio-backend.test.ts b/sdk/tests/web-audio-backend.test.ts
index 361a47507..3c3230af1 100644
--- a/sdk/tests/web-audio-backend.test.ts
+++ b/sdk/tests/web-audio-backend.test.ts
@@ -211,6 +211,51 @@ describe('WebAudioBackend', () => {
});
describe('loadBuffer', () => {
+ it.each(['read', 'decode'] as const)('rejects an old %s after the AudioContext is replaced', async stage => {
+ await backend.initialize();
+ const ctx = (globalThis as any).__mockAudioContext;
+ const platform = (globalThis as any).__mockPlatform;
+ let finish!: (value: unknown) => void;
+ if (stage === 'read') platform.readFile.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ else ctx.decodeAudioData.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ const pending = stage === 'read'
+ ? backend.loadBuffer('restart.wav')
+ : backend.loadBufferFromData('restart.wav', new ArrayBuffer(8));
+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'));
+ backend.dispose();
+ // This mock deliberately reuses the context object. A session
+ // generation, rather than object identity alone, must reject it.
+ await backend.initialize();
+ ctx.decodeAudioData.mockResolvedValue({ duration: 2, length: 16, numberOfChannels: 1 });
+ const current = await backend.loadBufferFromData('restart.wav', new ArrayBuffer(16));
+ const calls = ctx.decodeAudioData.mock.calls.length;
+ const rejection = expect(pending).rejects.toThrow('AudioContext changed');
+ finish(stage === 'read' ? new ArrayBuffer(8) : { duration: 1, length: 8, numberOfChannels: 1 });
+ await rejection;
+ expect(ctx.decodeAudioData).toHaveBeenCalledTimes(calls);
+ expect((await backend.loadBuffer('restart.wav')).id).toBe(current.id);
+ backend.unloadBuffer(current);
+ const retained = Object.values(backend).filter(value => value instanceof Map)
+ .reduce((count, map) => count + map.size, 0);
+ expect(retained).toBe(0);
+ });
+
+ it('does not republish a decoded buffer after disposal without reinitialization', async () => {
+ await backend.initialize();
+ const ctx = (globalThis as any).__mockAudioContext;
+ let finish!: (value: unknown) => void;
+ ctx.decodeAudioData.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ const pending = backend.loadBufferFromData('disposed.wav', new ArrayBuffer(8));
+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'));
+ backend.dispose();
+ const rejection = expect(pending).rejects.toThrow('AudioContext changed');
+ finish({ duration: 1, length: 8, numberOfChannels: 1 });
+ await rejection;
+ const retained = Object.values(backend).filter(value => value instanceof Map)
+ .reduce((count, map) => count + map.size, 0);
+ expect(retained).toBe(0);
+ });
+
it.each([false, true])('retires source metadata after buffer release (invalidate=%s)', async invalidate => {
await backend.initialize();
const ctx = (globalThis as any).__mockAudioContext;
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 13682b248..829e006d3 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'fix(audio): reject loads from retired context generations':
+ { note: 'Web audio loads cannot cross disposed or replaced contexts.' },
'fix(audio): retire source records with owned buffers':
{ note: 'Web audio source records follow live buffer ownership.' },
'perf(ui): use generated web pointers for live focus checks':