Files
client/test/audio-engine.test.mjs
T
omar e6464bc4ed feat: checkpoint account-free client workflows and source-matched UI
Preserve accumulated client implementation since v0.1.4, including local identities, multi-server state, chat, administration, audio and streaming controls. Refine official-source layout, original artwork, responsive composer overflow, settings navigation and chat scroll anchoring.

Current verification: Node suite passes; isolated packaged chat and responsive control smokes pass without device capture. Native core is reused, not rebuilt in this pass. Strict whole-screen visual parity remains incomplete; no 1:1 or cross-platform acceptance claim. Local checkpoint only; no release or push.
2026-11-01 19:43:18 +03:00

417 lines
17 KiB
JavaScript

// Capture lifecycle of the AudioEngine with stubbed Web Audio / getUserMedia: a stop or a newer start
// while the microphone request is pending must never leave a microphone open.
import test from 'node:test';
import assert from 'node:assert/strict';
import { AudioEngine } from '../app/renderer/js/audio/engine.js';
function fakeStream(name) {
const track = {
listeners: new Map(),
label: name,
muted: false,
stopped: false,
stop() { this.stopped = true; },
addEventListener(type, fn) { this.listeners.set(type, fn); },
removeEventListener(type, fn) { if (this.listeners.get(type) === fn) this.listeners.delete(type); },
getSettings: () => ({ sampleRate: 48000, channelCount: 1 }),
};
return { name, track, getTracks: () => [track], getAudioTracks: () => [track] };
}
const node = () => ({
handlers: new Map(),
addEventListener(type, handler) { this.handlers.set(type, handler); },
removeEventListener(type, handler) { if (this.handlers.get(type) === handler) this.handlers.delete(type); },
dispatchEvent(event) { this.handlers.get(event.type)?.(event); },
connect(next) { return next ?? this; },
disconnect() { this.disconnected = true; },
port: { messages: [], postMessage(data) { this.messages.push(data); if (data.type === 'stop') this.onmessage?.({ data: { type: 'stopped' } }); }, close() { this.closed = true; } },
gain: { value: 1 },
});
/** Engine whose getUserMedia calls stay pending until the test resolves them in order. */
function setup() {
const pending = [];
Object.defineProperty(globalThis, 'navigator', {
configurable: true,
value: { mediaDevices: { getUserMedia: () => new Promise((resolve, reject) => pending.push({ resolve, reject })) } },
});
globalThis.AudioWorkletNode = class { constructor() { Object.assign(this, node()); } };
const engine = new AudioEngine({ onFrame() {}, log() {} });
engine.init = async () => {};
engine.ctx = { createMediaStreamSource: () => node(), createGain: node, destination: {} };
const contexts = [];
globalThis.AudioContext = class {
constructor() { this.state = 'running'; this.audioWorklet = { addModule: async () => {} }; contexts.push(this); }
createMediaStreamSource(stream) { return engine.ctx.createMediaStreamSource(stream); }
createGain() { return engine.ctx.createGain(); }
async close() { this.state = 'closed'; }
};
return { engine, pending, contexts, flush: () => new Promise((r) => setTimeout(r, 0)) };
}
test('capture drops renderer-backlogged frames using its own sample clock, not playback or wall time', async () => {
const { engine, pending, flush } = setup();
const received = [];
engine.onFrame = pcm => received.push(pcm);
const started = engine.startCapture({});
await flush(); pending[0].resolve(fakeStream('synthetic')); await started;
engine.ctx.currentTime = 9000;
engine.capture.ctx.currentTime = 10;
const deliver = capturedAt => engine.capture.node.port.onmessage({ data: { type: 'frame', pcm: capturedAt, capturedAt } });
deliver(9.4); deliver(9.79); deliver(9.81); deliver(10);
assert.deepEqual(received, [9.81, 10]);
assert.equal(engine.stats.staleCaptureFrames, 2);
engine.stopCapture(); await engine.captureClosing;
});
test('stop while the microphone request is pending closes the late stream', async () => {
const { engine, pending, flush } = setup();
const started = engine.startCapture({});
await flush();
assert.equal(engine.captureStarting, true);
engine.stopCapture();
assert.equal(engine.captureStarting, false);
const stream = fakeStream('late');
pending[0].resolve(stream);
assert.equal(await started, null);
assert.equal(stream.track.stopped, true);
assert.equal(engine.capturing, false);
});
test('a newer start supersedes a pending one; only the newest stream stays open', async () => {
const { engine, pending, flush } = setup();
const first = engine.startCapture({});
await flush();
const second = engine.startCapture({});
await flush();
const a = fakeStream('first');
const b = fakeStream('second');
pending[1].resolve(b);
assert.equal(await second, 'second');
pending[0].resolve(a);
assert.equal(await first, null);
assert.equal(a.track.stopped, true);
assert.equal(b.track.stopped, false);
assert.equal(engine.capture.stream, b);
engine.stopCapture();
assert.equal(b.track.stopped, true);
assert.equal(engine.capturing, false);
});
test('a failure of a superseded start is ignored; a current failure is reported', async () => {
const { engine, pending, flush } = setup();
const stale = engine.startCapture({});
await flush();
engine.stopCapture();
pending[0].reject(Object.assign(new Error('denied'), { name: 'NotAllowedError' }));
assert.equal(await stale, null);
const current = engine.startCapture({});
await flush();
pending[1].reject(Object.assign(new Error('denied'), { name: 'NotAllowedError' }));
await assert.rejects(current, { name: 'NotAllowedError' });
assert.equal(engine.captureStarting, false);
});
test('a missing explicit device is an error with no second request for another microphone', async () => {
const { engine, pending, flush } = setup();
const start = engine.startCapture({ deviceId: 'gone' });
await flush();
pending[0].reject(Object.assign(new Error('not found'), { name: 'OverconstrainedError' }));
await assert.rejects(start, { code: 'device_unavailable' });
await flush();
assert.equal(pending.length, 1);
assert.equal(engine.capturing, false);
});
test('a failure while building the capture graph releases the opened microphone', async () => {
const { engine, pending, flush } = setup();
const disconnected = [];
engine.ctx.createMediaStreamSource = () => ({ connect: (n) => n, disconnect: () => disconnected.push('source') });
globalThis.AudioWorkletNode = class {
constructor() {
throw new Error('worklet not registered');
}
};
const start = engine.startCapture({});
await flush();
const stream = fakeStream('mic');
pending[0].resolve(stream);
await assert.rejects(start, /worklet not registered/);
assert.equal(stream.track.stopped, true);
assert.deepEqual(disconnected, ['source']);
assert.equal(engine.capturing, false);
assert.equal(engine.captureStarting, false);
});
test('capture stop releases ports, graph and track handlers without closing playback', async () => {
const { engine, pending, flush } = setup();
const started = engine.startCapture({});
await flush();
const stream = fakeStream('mic');
pending[0].resolve(stream);
await started;
const capture = engine.capture;
const context = engine.ctx;
assert.equal(stream.track.listeners.size, 3);
engine.stopCapture();
engine.stopCapture();
await engine.captureClosing;
assert.deepEqual(capture.node.port.messages, [{ type: 'typing', enabled: false }, { type: 'stop' }]);
assert.equal(capture.node.port.closed, true);
assert.equal(capture.node.port.onmessage, null);
assert.equal(stream.track.listeners.size, 0);
assert.equal(stream.track.stopped, true);
for (const part of [capture.source, capture.node, capture.sink]) assert.equal(part.disconnected, true);
assert.equal(engine.ctx, context);
assert.notEqual(capture.ctx, context);
assert.equal(capture.ctx.state, 'closed');
});
test('failed audio initialization closes partial resources and allows a later retry', async () => {
const contexts = [];
globalThis.AudioContext = class {
constructor() {
contexts.push(this);
this.state = 'running';
this.audioWorklet = { addModule: async () => { if (contexts.length === 1) throw new Error('module failed'); } };
}
async close() { this.state = 'closed'; }
createGain() { return node(); }
};
globalThis.AudioWorkletNode = class { constructor() { Object.assign(this, node()); } };
const engine = new AudioEngine({ onFrame() {} });
const first = engine.init();
assert.equal(engine.init(), first);
await assert.rejects(first, /module failed/);
assert.equal(contexts[0].state, 'closed');
assert.equal(engine.ctx, null);
assert.equal(engine.ready, null);
await engine.init();
assert.equal(contexts.length, 2);
assert.equal(engine.ctx.state, 'running');
assert.ok(engine.playback);
});
test('capture graph connection failure stops the partially created processor', async () => {
const { engine, pending, flush } = setup();
let worklet;
globalThis.AudioWorkletNode = class {
constructor() { Object.assign(this, node()); worklet = this; }
};
engine.ctx.createMediaStreamSource = () => ({ disconnect() {}, connect(next) { next.connect = () => { throw new Error('connect failed'); }; return next; } });
const started = engine.startCapture({});
await flush();
const stream = fakeStream('mic');
pending[0].resolve(stream);
await assert.rejects(started, /connect failed/);
assert.deepEqual(worklet.port.messages, [{ type: 'typing', enabled: false }, { type: 'stop' }]);
assert.equal(worklet.port.closed, true);
assert.equal(stream.track.stopped, true);
});
test('stop during capture module load closes its context; stale completion cannot replace a newer capture', async () => {
const { engine, pending, flush } = setup();
const contexts = [];
const loads = [];
globalThis.AudioContext = class {
constructor() {
this.state = 'running';
this.audioWorklet = { addModule: () => new Promise(resolve => loads.push(resolve)) };
contexts.push(this);
}
createMediaStreamSource() { return node(); }
createGain() { return node(); }
async close() { this.state = 'closed'; }
};
const first = engine.startCapture({});
await flush();
const old = fakeStream('old');
pending[0].resolve(old);
await flush();
engine.stopCapture();
assert.equal(contexts[0].state, 'closed');
assert.equal(old.track.stopped, true);
const second = engine.startCapture({});
await flush();
const current = fakeStream('current');
pending[1].resolve(current);
await flush();
loads[1]();
assert.equal(await second, 'current');
loads[0]();
assert.equal(await first, null);
assert.equal(engine.capture.ctx, contexts[1]);
assert.equal(contexts[1].state, 'running');
assert.equal(current.track.stopped, false);
engine.stopCapture();
await engine.captureClosing;
assert.equal(contexts[1].state, 'closed');
});
test('stop during capture resume closes only the pending capture context', async () => {
const { engine, pending, flush } = setup();
let captureContext;
let resume;
globalThis.AudioContext = class {
constructor() { captureContext = this; this.state = 'suspended'; this.audioWorklet = { addModule: async () => {} }; }
resume() { return new Promise(resolve => { resume = resolve; }); }
async close() { this.state = 'closed'; }
};
const playback = engine.ctx;
const start = engine.startCapture({});
await flush();
const stream = fakeStream('pending');
pending[0].resolve(stream);
await flush();
engine.stopCapture();
assert.equal(captureContext.state, 'closed');
assert.equal(stream.track.stopped, true);
resume();
assert.equal(await start, null);
assert.equal(engine.ctx, playback);
});
test('unresponsive capture worklet cannot hold the microphone or block restart past shutdown deadline', async () => {
const { engine, pending, flush } = setup();
const first = engine.startCapture({});
await flush();
const stream = fakeStream('unresponsive');
pending[0].resolve(stream);
await first;
const capture = engine.capture;
capture.node.port.postMessage = () => {}; // suspended/failed processor never acknowledges
engine.stopCapture();
assert.equal(stream.track.stopped, true);
assert.equal(engine.capturing, false);
assert.equal(stream.track.listeners.size, 0);
const second = engine.startCapture({});
await flush();
assert.equal(pending.length, 1, 'new capture waits for old context closure');
await engine.captureClosing;
await flush();
assert.equal(capture.ctx.state, 'closed');
assert.equal(capture.node.port.closed, true);
assert.equal(pending.length, 2);
pending[1].resolve(fakeStream('recovered'));
assert.equal(await second, 'recovered');
engine.stopCapture();
await engine.captureClosing;
});
test('capture processor failure stops the microphone and reports an actionable error', async () => {
const { engine, pending, flush } = setup();
const errors = [];
engine.onError = error => errors.push(error);
const started = engine.startCapture({});
await flush();
const stream = fakeStream('failed processor');
pending[0].resolve(stream);
await started;
const capture = engine.capture;
capture.node.dispatchEvent(new Event('processorerror'));
assert.equal(stream.track.stopped, true, 'silent failed processor must not retain an open microphone');
assert.equal(engine.capturing, false);
assert.equal(errors[0]?.code, 'capture');
await engine.captureClosing;
assert.equal(capture.ctx.state, 'closed');
});
test('explicit init recovers a closed playback context without reusing a dead worklet', async () => {
const contexts = [];
globalThis.AudioContext = class {
constructor() { contexts.push(this); this.state = 'running'; this.audioWorklet = { addModule: async () => {} }; }
async close() { this.state = 'closed'; }
createGain() { return node(); }
};
globalThis.AudioWorkletNode = class { constructor() { Object.assign(this, node()); } };
const engine = new AudioEngine({ onFrame() {} });
await engine.init();
const previous = engine.playback;
await engine.ctx.close();
await engine.init();
assert.equal(engine.ctx.state, 'running', 'a successful init means usable playback');
assert.notEqual(engine.playback, previous);
assert.equal(contexts.length, 2);
});
test('capture close failure blocks a new microphone until an explicit close retry succeeds', async () => {
const { engine, pending, flush } = setup();
const errors = [];
engine.onError = error => errors.push(error);
const start = engine.startCapture({});
await flush();
const stream = fakeStream('closing failure');
pending[0].resolve(stream);
await start;
const capture = engine.capture;
const close = capture.ctx.close.bind(capture.ctx);
capture.ctx.close = async () => { throw new Error('close refused'); };
engine.stopCapture();
await engine.captureClosing;
const retry = engine.startCapture({});
const outcome = await Promise.race([retry.then(() => 'opened', error => error.message), flush().then(() => 'pending')]);
if (pending[1]) { pending[1].resolve(fakeStream('unexpected overlap')); await retry; engine.stopCapture(); await engine.captureClosing; }
assert.equal(outcome, 'close refused');
assert.equal(pending.length, 1, 'must not acquire another mic while failed context is still live');
assert.equal(stream.track.stopped, true);
assert.equal(errors[0]?.code, 'capture');
capture.ctx.close = close;
const recovered = engine.startCapture({});
await flush();
pending[1].resolve(fakeStream('recovered'));
assert.equal(await recovered, 'recovered');
assert.equal(capture.ctx.state, 'closed');
engine.stopCapture();
await engine.captureClosing;
});
test('playback recovery preserves applied gain and sink even through output selection', async () => {
globalThis.AudioContext = class {
constructor() { this.state = 'running'; this.sinkId = ''; this.audioWorklet = { addModule: async () => {} }; }
async close() { this.state = 'closed'; }
async setSinkId(id) { this.sinkId = id; }
createGain() { const n = node(); n.gain.setTargetAtTime = function(value) { this.value = value; }; return n; }
};
globalThis.AudioWorkletNode = class { constructor() { Object.assign(this, node()); } };
const engine = new AudioEngine({ onFrame() {} });
await engine.init();
engine.setOutputLevelDb(-15.5);
await engine.setOutputDevice('selected-output');
const old = engine.ctx;
const pendingStats = engine.playbackStats();
engine.playback.dispatchEvent(new Event('processorerror'));
assert.equal(await pendingStats, null);
await engine.init();
assert.notEqual(engine.ctx, old);
assert.equal(engine.voiceGain.gain.value, 10 ** (-15.5 / 20), 'output selection recovery must not reset voice volume');
assert.equal(engine.ctx.sinkId, 'selected-output');
await engine.setOutputDevice('new-output');
assert.equal(engine.ctx.sinkId, 'new-output');
assert.equal(engine.voiceGain.gain.value, 10 ** (-15.5 / 20));
});
test('playback close rejection retains context ownership and prevents replacement overlap', async () => {
const contexts = [];
globalThis.AudioContext = class {
constructor() { contexts.push(this); this.state = 'running'; this.audioWorklet = { addModule: async () => {} }; }
async close() { this.state = 'closed'; }
createGain() { return node(); }
};
globalThis.AudioWorkletNode = class { constructor() { Object.assign(this, node()); } };
const engine = new AudioEngine({ onFrame() {} });
await engine.init();
const original = engine.ctx;
const close = original.close.bind(original);
original.close = async () => { throw new Error('playback close refused'); };
engine.playback.dispatchEvent(new Event('processorerror'));
await assert.rejects(engine.init(), /playback close refused/);
assert.equal(contexts.length, 1);
assert.equal(engine.ctx, original);
original.close = close;
await engine.init();
assert.equal(original.state, 'closed');
assert.equal(engine.ctx.state, 'running');
assert.equal(contexts.length, 2);
});