Files
client/scripts/smoke-voice-vad.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

236 lines
11 KiB
JavaScript

// Voice activation through the real program: two TeamsPeach instances (disposable profiles) on a live server.
// A's capture device is Chromium's fake device fed from a WAV file built from the public-domain speech
// fixture (core/tests/fixtures/speech-librivox-48k.wav): 2 s silence, 4 s speech, 3 s silence, looped.
// Everything after getUserMedia is the real path (capture processing, worklet, IPC, core voice detector,
// Opus, server, B's decoder). B listens at zero playback gain and never transmits.
//
// node scripts/smoke-voice-vad.mjs --server 10.10.10.160:9987 --out docs/evidence/runtime/<name> [--exe packaged.exe]
//
// Refuses to run if anyone else is in the channel. Not an official-client interoperability test.
import { closeSettings, launchApp } from './lib/electron-app.mjs';
import { mkdirSync, writeFileSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const argv = process.argv.slice(2);
const opt = (name, fallback) => (argv.indexOf(`--${name}`) >= 0 ? argv[argv.indexOf(`--${name}`) + 1] : fallback);
const server = opt('server');
if (!server) {
console.error('--server is required');
process.exit(2);
}
const out = path.resolve(root, opt('out', 'smoke-vad-out'));
const exe = opt('exe');
mkdirSync(out, { recursive: true });
const result = { startedAt: new Date().toISOString(), server, steps: [], console: [] };
const step = (name, data = {}) => {
result.steps.push({ name, at: new Date().toISOString(), ...data });
console.log(`[vad] ${name}`, JSON.stringify(data));
};
/** 48 kHz mono s16 WAV: silence, the speech fixture, silence. */
function buildInput(file) {
const wav = readFileSync(path.join(root, 'core', 'tests', 'fixtures', 'speech-librivox-48k.wav'));
const dataAt = wav.indexOf('data') + 8;
const speech = wav.subarray(dataAt, dataAt + wav.readUInt32LE(dataAt - 4));
const pcm = Buffer.concat([Buffer.alloc(2 * 48000 * 2), speech, Buffer.alloc(3 * 48000 * 2)]);
const header = Buffer.alloc(44);
header.write('RIFF', 0);
header.writeUInt32LE(36 + pcm.length, 4);
header.write('WAVEfmt ', 8);
header.writeUInt32LE(16, 16);
header.writeUInt16LE(1, 20);
header.writeUInt16LE(1, 22);
header.writeUInt32LE(48000, 24);
header.writeUInt32LE(96000, 28);
header.writeUInt16LE(2, 32);
header.writeUInt16LE(16, 34);
header.write('data', 36);
header.writeUInt32LE(pcm.length, 40);
writeFileSync(file, Buffer.concat([header, pcm]));
return { seconds: pcm.length / 96000 };
}
const work = mkdtempSync(path.join(tmpdir(), 'teamspeach-vad-'));
const inputWav = path.join(work, 'speech-loop.wav');
const input = buildInput(inputWav);
async function launch(label, nickname, args, profile = mkdtempSync(path.join(tmpdir(), `teamspeach-${label}-`))) {
const app = await launchApp({ exe, profile, args: ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', ...args] });
const page = await app.firstWindow();
page.on('console', (m) => result.console.push(`${label} ${m.type()}: ${m.text()}`));
page.on('pageerror', (e) => result.console.push(`${label} pageerror: ${e.message}`));
if (nickname) {
await page.waitForSelector('#view-onboarding', { state: 'visible', timeout: 20000 });
await page.fill('#onboarding-nick', nickname);
await page.click('#onboarding-submit');
}
await page.waitForSelector('#view-app', { state: 'visible', timeout: 20000 });
return { app, page, profile };
}
const diag = (page) => page.evaluate(() => window.teamspeachDiagnostics.snapshot());
const waitDiag = (page, fn, arg, timeout = 20000) => page.waitForFunction(fn, arg, { timeout });
async function openAudioSettings(page) {
await page.click('#btn-settings');
await page.click('#settings-nav .nav-item[data-panel="audio"]');
}
async function setTransmit(page, mode) {
await openAudioSettings(page);
await page.check(`input[name="transmit"][value="${mode}"]`);
await closeSettings(page);
}
async function connect(page) {
await page.fill('#connect-address', server);
await page.click('#connect-submit');
await waitDiag(page, () => window.teamspeachDiagnostics.snapshot().conn === 'connected', null, 60000);
}
/** Samples A's core transmit state and B's received frames every 50 ms. */
async function observe(a, b, aClid, ms) {
const samples = [];
const end = Date.now() + ms;
while (Date.now() < end) {
const [sa, sb] = await Promise.all([diag(a.page), diag(b.page)]);
samples.push({ t: Date.now(), tx: sa.audio.transmitting, heard: sb.talking.includes(aClid), rx: sb.voice.framesPlayed });
await a.page.waitForTimeout(50);
}
return samples;
}
/** Contiguous on/off segments of `key` with their durations in ms. */
function segments(samples, key) {
const segs = [];
for (const s of samples) {
const last = segs.at(-1);
if (last && last.on === s[key]) last.end = s.t;
else segs.push({ on: s[key], start: s.t, end: s.t });
}
return segs.map((s) => ({ on: s.on, ms: s.end - s.start, start: s.start, end: s.end }));
}
function quiet(samples, label) {
const transmitted = samples.some((s) => s.tx);
const rxDelta = samples.at(-1).rx - samples[0].rx;
step(label, { transmitted, bReceivedFrames: rxDelta });
if (transmitted || rxDelta > 0) throw new Error(`${label}: audio was sent`);
}
let a;
let b;
let failed = null;
try {
step('build', { exe: exe ? path.basename(exe) : 'dev tree' });
step('input', { file: 'silence 2 s + speech-librivox-48k.wav (4 s) + silence 3 s, looped', seconds: input.seconds });
a = await launch('A', 'PeachVadA', [`--use-file-for-fake-audio-capture=${inputWav}`]);
b = await launch('B', 'PeachVadB', []);
await openAudioSettings(b.page);
await b.page.$eval('#voice-volume', (el) => {
el.value = '0';
el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new Event('change', { bubbles: true }));
});
await closeSettings(b.page);
// A chooses voice activation before connecting; the core must confirm it.
await setTransmit(a.page, 'vad');
await waitDiag(a.page, () => window.teamspeachDiagnostics.snapshot().voice.coreMode?.mode === 'vad', null, 10000);
step('A voice activation confirmed by the core', { coreMode: (await diag(a.page)).voice.coreMode });
await openAudioSettings(a.page);
await a.page.screenshot({ path: path.join(out, '80-audio-settings-voice-activation.png') });
await closeSettings(a.page);
await connect(b.page);
await connect(a.page);
await a.page.waitForTimeout(1000);
const da = await diag(a.page);
const db = await diag(b.page);
const ownCid = (s) => s.clients.find((c) => c.id === s.ownClientId)?.channel;
const others = db.clients.filter((c) => c.type !== 'query' && c.channel === ownCid(db) && c.id !== da.ownClientId && c.id !== db.ownClientId);
if (da.ownChannel !== db.ownChannel) throw new Error('clients landed in different channels');
if (others.length > 0) throw new Error(`refusing to transmit: channel occupied by ${others.length} other client(s)`);
step('both connected, channel empty otherwise', { channel: da.ownChannel });
const aClid = da.ownClientId;
// Speech opens the gate, silence closes it after the hangover; B hears A only while A transmits.
const samples = await observe(a, b, aClid, 2 * input.seconds * 1000 + 500);
const tx = segments(samples, 'tx');
const on = tx.filter((s) => s.on);
const off = tx.filter((s) => !s.on);
const onMs = on.reduce((n, s) => n + s.ms, 0);
const total = samples.at(-1).t - samples[0].t;
// B's received frames in the middle of each long silence (skip 600 ms after the gate closed).
const rxInSilence = off.filter((s) => s.ms > 1500).map((s) => {
const inside = samples.filter((x) => x.t >= s.start + 600 && x.t <= s.end);
return inside.length ? inside.at(-1).rx - inside[0].rx : 0;
});
const heardWhileOn = samples.filter((s) => s.tx).some((s) => s.heard);
step('speech and silence', {
spurts: on.length,
onMs: on.map((s) => s.ms),
offMs: off.map((s) => s.ms),
onFraction: Number((onMs / total).toFixed(2)),
bHeardA: heardWhileOn,
bFramesDuringSilence: rxInSilence,
});
if (on.length < 1) throw new Error('speech never opened the gate');
if (!off.some((s) => s.ms >= 2500)) throw new Error('silence did not keep the gate closed');
if (!heardWhileOn) throw new Error('B never heard A');
if (rxInSilence.some((n) => n > 0)) throw new Error('B received audio during silence');
await b.page.screenshot({ path: path.join(out, '81-b-hears-a.png') });
// Mute, deafen, push-to-talk (not held): nothing is sent.
await a.page.click('#btn-mute');
await waitDiag(a.page, () => window.teamspeachDiagnostics.snapshot().audio.input_muted === true);
quiet(await observe(a, b, aClid, input.seconds * 1000), 'muted: nothing sent');
await a.page.click('#btn-mute');
await a.page.click('#btn-deafen');
await waitDiag(a.page, () => window.teamspeachDiagnostics.snapshot().audio.output_muted === true);
quiet(await observe(a, b, aClid, input.seconds * 1000), 'deafened: nothing sent');
await a.page.click('#btn-deafen');
await setTransmit(a.page, 'ptt');
await waitDiag(a.page, () => window.teamspeachDiagnostics.snapshot().voice.coreMode?.mode === 'direct', null, 10000);
quiet(await observe(a, b, aClid, input.seconds * 1000), 'push to talk not held: nothing sent');
// Back to voice activation: speech opens it again.
await setTransmit(a.page, 'vad');
await waitDiag(a.page, () => window.teamspeachDiagnostics.snapshot().audio.transmitting === true, null, 2 * input.seconds * 1000);
step('voice activation again: speech sent');
// Disconnected: nothing is sent.
await a.page.hover('#connection-list .connection-row').then(() => a.page.click('#connection-list .connection-close'));
await waitDiag(a.page, () => window.teamspeachDiagnostics.snapshot().conn === 'disconnected', null, 20000);
const afterDisconnect = await observe(a, b, aClid, 3000);
step('disconnected', { transmitted: afterDisconnect.some((s) => s.tx) });
if (afterDisconnect.some((s) => s.tx)) throw new Error('transmitting while disconnected');
// The choice persists across a restart and is confirmed by the new core.
await a.app.close();
a = await launch('A2', null, [`--use-file-for-fake-audio-capture=${inputWav}`], a.profile);
await waitDiag(a.page, () => window.teamspeachDiagnostics.snapshot().voice.coreMode?.mode === 'vad', null, 20000);
const prefs = JSON.parse(readFileSync(path.join(a.profile, 'prefs.json'), 'utf8'));
step('restart: voice activation persisted and confirmed', { pttEnabled: prefs.pttEnabled, inputDsp: prefs.inputDsp, coreMode: (await diag(a.page)).voice.coreMode });
const inputDsp = prefs.inputDsp.devices[prefs.inputDeviceId] ?? prefs.inputDsp.template;
if (prefs.pttEnabled || !inputDsp.vad) throw new Error('voice activation mode not persisted');
} catch (err) {
failed = err;
step('FAILED', { error: String(err.stack || err) });
} finally {
for (const x of [a, b]) {
if (x) await x.app.close().catch(() => {});
}
for (const x of [a, b]) {
if (x) rmSync(x.profile, { recursive: true, force: true });
}
rmSync(work, { recursive: true, force: true });
}
result.ok = !failed;
result.pageErrors = result.console.filter((l) => l.includes('pageerror')).length;
writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2));
console.log(`[vad] ${result.ok ? 'OK' : 'FAILED'} → ${out}`);
process.exit(result.ok ? 0 : 1);