BlueGit

ict rusty-teams

Files

rusty-teams / scripts / call-e2e.mjs

call-e2e.mjs

call-e2e.mjs 25.0 KiB Download Raw
1// Call end-to-end test with Daniel's real account and the deployed Windows app, no second person needed.
2// The Windows app hosts a fresh Meet now without lobby through `teams.exe --join`; its mic is VB-CABLE fed with a speech file.
3// An anonymous Teams web guest (own incognito context) joins with a second speech file as its mic,
4// and process loopback records what the app plays. Both directions must show speech with pauses.
5// After audio it runs the video, screen share, mute and rejoin scenarios and judges each from both sides' stats.
6// Usage: node scripts/call-e2e.mjs <work dir> [meeting link]
7import { spawn, execFileSync } from 'node:child_process';
8import { readFileSync, writeFileSync } from 'node:fs';
9import { Browser, FAKE_MEDIA, PEER_HOOK, PEER_STATS } from './teams-web-cdp.mjs';
10
11const [workDir, givenLink] = process.argv.slice(2);
12const OWN_ENDPOINT = process.env.OWN_CDP ?? 'http://127.0.0.1:9222';
13const PROBE_DIR = process.env.PROBE_DIR ?? '/mnt/c/Users/dd/AppData/Local/Temp/call-e2e';
14const TEAMS_EXE = process.env.TEAMS_EXE ?? '/mnt/c/Users/dd/AppData/Local/Programs/ms-teams-linux/teams.exe';
15const POWERSHELL = '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe';
16const TASKLIST = '/mnt/c/Windows/System32/tasklist.exe';
17const SCRIPT_DIR = new URL('.', import.meta.url).pathname;
18const REPO_DIR = new URL('..', import.meta.url).pathname;
19const APP_START_WAIT_MS = 40_000;
20const WEB_JOIN_TIMEOUT_MS = 90_000;
21const APP_JOIN_WAIT_MS = 25_000;
22const MEASURE_SECONDS = 30;
23const WINDOW_MS = 250;
24const STEP_REPEAT_MS = 15_000;
25const ADMIT_INTERVAL_MS = 5_000;
26const WEB_JOIN_STEPS = ['Continue on this browser', 'Not now', '=Join now', '=Join'];
27const GUEST_NAME = 'Call e2e guest';
28const LOBBY_TEXTS = ['let you in shortly', 'should let you in soon'];
29const WEB_THRESHOLD = { speech: 0.005, floor: 0.0005 };
30const APP_THRESHOLD = { speech: 200, floor: 20 };
31const SPEECH_TO_PAUSE = 4;
32const SCENARIO_SETTLE_MS = 8_000;
33const SCENARIO_MEASURE_MS = 8_000;
34const STATS_WAIT_MS = 1_500;
35const MIN_FRAMES = 30;
36
37const windowsPath = (path) => execFileSync('wslpath', ['-w', path]).toString().trim();
38const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
39const log = (message) => console.error(`[${new Date().toISOString().slice(11, 19)}] ${message}`);
40
41function defaultAudio(...args) {
42 const script = windowsPath(SCRIPT_DIR + 'default-audio.ps1');
43 return execFileSync(POWERSHELL, ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script, ...args]).toString().trim();
44}
45
46function createMeeting() {
47 return execFileSync('cargo', ['run', '-q', '-p', 'chatsvc', '--example', 'create_test_meeting'], { cwd: REPO_DIR, stdio: ['ignore', 'pipe', 'inherit'] })
48 .toString()
49 .trim();
50}
51
52function teamsProcessId() {
53 const rows = execFileSync(TASKLIST, ['/FI', 'IMAGENAME eq teams.exe', '/FO', 'CSV', '/NH']).toString().trim().split(/\r?\n/);
54 const processes = rows
55 .map((row) => row.split('","').map((cell) => cell.replace(/"/g, '')))
56 .filter((cells) => cells[0]?.toLowerCase() === 'teams.exe')
57 .map((cells) => ({ id: Number(cells[1]), memory: Number(cells[4].replace(/\D/g, '')) }));
58 processes.sort((left, right) => right.memory - left.memory);
59 return processes[0]?.id;
60}
61
62function runTeams(...args) {
63 spawn(TEAMS_EXE, args, { detached: true, stdio: 'ignore' }).unref();
64}
65
66function runProbe(...args) {
67 return new Promise((resolve, reject) => {
68 const child = spawn(PROBE_DIR + '/audio_probe.exe', args, { stdio: ['ignore', 'pipe', 'pipe'] });
69 let output = '';
70 let errors = '';
71 child.stdout.on('data', (chunk) => (output += chunk));
72 child.stderr.on('data', (chunk) => (errors += chunk));
73 child.on('exit', (code) => (code === 0 ? resolve(output) : reject(new Error(`audio_probe ${args[0]}: ${errors.trim()}`))));
74 });
75}
76
77const speechDataUrl = () => `data:audio/wav;base64,${readFileSync(PROBE_DIR + '/web.wav').toString('base64')}`;
78
79// Taps every received audio track, so the level does not depend on headless Chrome playing it out.
80const REMOTE_AUDIO_TAP = `(() => {
81 window.__remoteAudio = { sum: 0, count: 0, packets: 0 };
82 const tapped = new WeakSet();
83 const tap = async (track) => {
84 tapped.add(track);
85 const reader = new MediaStreamTrackProcessor({ track }).readable.getReader();
86 for (;;) {
87 const { value, done } = await reader.read();
88 if (done) return;
89 const samples = new Float32Array(value.numberOfFrames);
90 value.copyTo(samples, { planeIndex: 0, format: 'f32-planar' });
91 value.close();
92 for (const sample of samples) window.__remoteAudio.sum += sample * sample;
93 window.__remoteAudio.count += samples.length;
94 }
95 };
96 setInterval(() => {
97 for (const peer of window.__pcs || []) {
98 for (const receiver of peer.getReceivers()) {
99 if (receiver.track && receiver.track.kind === 'audio' && !tapped.has(receiver.track)) tap(receiver.track).catch(() => {});
100 }
101 }
102 }, 500);
103})();`;
104
105const INBOUND_AUDIO = `(async () => {
106 let energy = 0, duration = 0;
107 for (const peer of window.__pcs || []) {
108 if (peer.connectionState === 'closed') continue;
109 (await peer.getStats()).forEach((entry) => {
110 if (entry.type === 'inbound-rtp' && entry.kind === 'audio') { energy += entry.totalAudioEnergy || 0; duration += entry.totalSamplesDuration || 0; }
111 });
112 }
113 return { ...window.__remoteAudio, energy, duration };
114})()`;
115
116const GUEST_SENDING = `(async () => {
117 let energy = 0, duration = 0, packets = 0;
118 for (const peer of window.__pcs || []) {
119 if (peer.connectionState === 'closed') continue;
120 (await peer.getStats()).forEach((entry) => {
121 if (entry.type === 'media-source' && entry.kind === 'audio') { energy += entry.totalAudioEnergy || 0; duration += entry.totalSamplesDuration || 0; }
122 if (entry.type === 'outbound-rtp' && entry.kind === 'audio') packets += entry.packetsSent || 0;
123 });
124 }
125 return { level: duration > 0 ? Math.sqrt(energy / duration) : 0, packets };
126})()`;
127const LOCATE = (step) => `(() => {
128 const onlyExact = ${JSON.stringify(step.startsWith('='))};
129 const wanted = ${JSON.stringify(step.replace(/^=/, ''))}.toLowerCase();
130 const nodes = [...document.querySelectorAll('button, [role=button], [role=menuitem], a')];
131 const label = (node) => ((node.getAttribute('aria-label') || '') + ' ' + (node.innerText || '') + ' ' + (node.getAttribute('title') || '')).trim().toLowerCase();
132 const visible = nodes.filter((node) => node.getClientRects().length && !node.disabled && node.getAttribute('aria-disabled') !== 'true');
133 const exact = visible.find((node) => (node.innerText || '').trim().toLowerCase() === wanted || (node.getAttribute('aria-label') || '').trim().toLowerCase() === wanted);
134 const target = exact || (onlyExact ? null : visible.find((node) => label(node).includes(wanted)));
135 if (!target) return null;
136 target.scrollIntoView({ block: 'center' });
137 target.click();
138 return label(target).slice(0, 80);
139})()`;
140
141// Teams web offers audio/L16 109 first; headless Chrome decodes none of it, so the guest is held to Opus.
142const NO_L16 = `(() => {
143 const strip = (sdp) => {
144 if (!sdp) return sdp;
145 const payload = (sdp.match(/a=rtpmap:(\\d+) L16\\//) || [])[1];
146 if (!payload) return sdp;
147 return sdp.split('\\r\\n').filter((line) => !line.startsWith('a=rtpmap:' + payload + ' ') && !line.startsWith('a=fmtp:' + payload + ' ') && !line.startsWith('a=rtcp-fb:' + payload + ' '))
148 .map((line) => line.startsWith('m=audio') ? line.split(' ').filter((part, index) => index < 3 || part !== payload).join(' ') : line).join('\\r\\n');
149 };
150 const prototype = RTCPeerConnection.prototype;
151 for (const name of ['createOffer', 'createAnswer']) {
152 const original = prototype[name];
153 prototype[name] = async function (...args) { const description = await original.apply(this, args); return { type: description.type, sdp: strip(description.sdp) }; };
154 }
155 const setLocal = prototype.setLocalDescription;
156 prototype.setLocalDescription = function (description) { return description && description.sdp ? setLocal.call(this, { type: description.type, sdp: strip(description.sdp) }) : setLocal.apply(this, arguments); };
157})();`;
158
159const AUDIO_DECODER = `(async () => {
160 const out = [];
161 for (const peer of window.__pcs || []) {
162 const stats = await peer.getStats();
163 stats.forEach((entry) => {
164 if (entry.type !== 'inbound-rtp' || entry.kind !== 'audio') return;
165 const codec = entry.codecId && stats.get(entry.codecId);
166 out.push({ ssrc: entry.ssrc, mid: entry.mid, packets: entry.packetsReceived, discarded: entry.packetsDiscarded, lost: entry.packetsLost, samples: entry.totalSamplesReceived, concealed: entry.concealedSamples, emitted: entry.jitterBufferEmittedCount, decoder: entry.decoderImplementation, codec: codec ? codec.mimeType + '/' + codec.payloadType : null, bytes: entry.bytesReceived });
167 });
168 out.push({ transforms: peer.getReceivers().map((receiver) => receiver.track && receiver.track.kind + ':' + Boolean(receiver.transform)) });
169 }
170 return out;
171 })()`;
172const CONNECTED = `(window.__pcs || []).some((peer) => peer.connectionState === 'connected')`;
173const TEAMS_ORIGINS = ['https://teams.cloud.microsoft', 'https://teams.microsoft.com'];
174
175class GuestTab {
176 constructor(browser) { this.browser = browser; }
177 async open(link) {
178 this.contextId = (await this.browser.send('Target.createBrowserContext', { disposeOnDetach: false })).browserContextId;
179 const context = this.contextId ? { browserContextId: this.contextId } : {};
180 const { targetId } = await this.browser.send('Target.createTarget', { url: 'about:blank', ...context });
181 this.targetId = targetId;
182 const { sessionId } = await this.browser.send('Target.attachToTarget', { targetId, flatten: true });
183 this.sessionId = sessionId;
184 await this.browser.send('Page.enable', {}, sessionId);
185 await this.browser.send('Runtime.enable', {}, sessionId);
186 await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: PEER_HOOK }, sessionId);
187 await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: NO_L16 }, sessionId);
188 await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: REMOTE_AUDIO_TAP }, sessionId);
189 await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: FAKE_MEDIA(speechDataUrl()) }, sessionId);
190 for (const origin of TEAMS_ORIGINS) {
191 await this.browser.send('Browser.grantPermissions', { permissions: ['audioCapture', 'videoCapture'], origin, ...context }).catch(() => {});
192 }
193 await this.browser.send('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId).catch(() => {});
194 await this.browser.send('Page.navigate', { url: link }, sessionId);
195 }
196 async evaluate(expression) {
197 const result = await this.browser.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, this.sessionId);
198 if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description ?? 'evaluate failed');
199 return result.result.value;
200 }
201 async join() {
202 const deadline = Date.now() + WEB_JOIN_TIMEOUT_MS;
203 const clickedAt = new Map();
204 while (Date.now() < deadline) {
205 const inLobby = await this.evaluate(`${JSON.stringify(LOBBY_TEXTS)}.some((text) => document.body.innerText.includes(text))`).catch(() => false);
206 if (!inLobby && (await this.evaluate(CONNECTED).catch(() => false))) return true;
207 await this.activate();
208 await this.typeName();
209 for (const step of WEB_JOIN_STEPS) {
210 if (Date.now() - (clickedAt.get(step) ?? 0) < STEP_REPEAT_MS) continue;
211 if (await this.click(step)) {
212 clickedAt.set(step, Date.now());
213 log(`web: clicked "${step}"`);
214 }
215 }
216 await delay(2000);
217 }
218 return false;
219 }
220 async click(step) {
221 return this.evaluate(LOCATE(step)).catch(() => null);
222 }
223 async activate() {
224 for (const type of ['mousePressed', 'mouseReleased']) {
225 await this.browser.send('Input.dispatchMouseEvent', { type, x: 5, y: 5, button: 'left', clickCount: 1 }, this.sessionId).catch(() => {});
226 }
227 }
228 async playbackState() {
229 return this.evaluate(`[...document.querySelectorAll('audio, video')].map((element) => ({ tag: element.tagName, paused: element.paused, muted: element.muted, volume: element.volume, tracks: element.srcObject ? element.srcObject.getTracks().map((track) => track.kind + ':' + track.readyState + ':' + (track.muted ? 'muted' : 'live')) : [] }))`).catch((error) => error.message);
230 }
231 async typeName() {
232 const focused = await this.evaluate(`(() => {
233 const input = document.querySelector('input[placeholder*="name" i]');
234 if (!input || input.value) return false;
235 input.focus(); return true;
236 })()`).catch(() => false);
237 if (focused) await this.browser.send('Input.insertText', { text: GUEST_NAME }, this.sessionId);
238 }
239 async shot(path) {
240 const { data } = await this.browser.send('Page.captureScreenshot', { format: 'png' }, this.sessionId);
241 writeFileSync(path, Buffer.from(data, 'base64'));
242 }
243 async close() {
244 if (this.targetId) await this.browser.send('Target.closeTarget', { targetId: this.targetId }).catch(() => {});
245 if (this.contextId) await this.browser.send('Target.disposeBrowserContext', { browserContextId: this.contextId }).catch(() => {});
246 }
247}
248
249async function sampleWeb(tab, seconds) {
250 const levels = [];
251 let previous = await tab.evaluate(INBOUND_AUDIO);
252 const end = Date.now() + seconds * 1000;
253 while (Date.now() < end) {
254 await delay(WINDOW_MS);
255 const current = await tab.evaluate(INBOUND_AUDIO);
256 const count = current.count - previous.count;
257 const duration = current.duration - previous.duration;
258 if (count > 0) levels.push(Math.sqrt((current.sum - previous.sum) / count));
259 else levels.push(duration > 0 ? Math.sqrt((current.energy - previous.energy) / duration) : 0);
260 previous = current;
261 }
262 return levels;
263}
264
265function judge(levels, threshold) {
266 const sorted = [...levels].sort((left, right) => left - right);
267 const percentile = (share) => sorted[Math.min(sorted.length - 1, Math.floor(share * sorted.length))] ?? 0;
268 const [p10, p90] = [percentile(0.1), percentile(0.9)];
269 const speech = p90 >= threshold.speech;
270 const pauses = p90 >= SPEECH_TO_PAUSE * Math.max(p10, threshold.floor);
271 return { pass: speech && pauses, p10, p90, windows: levels.length };
272}
273
274
275async function appStats(workDir) {
276 const path = workDir + '/app-stats.json';
277 writeFileSync(path, '');
278 runTeams('--call', `stats ${windowsPath(path)}`);
279 const deadline = Date.now() + 10_000;
280 while (Date.now() < deadline) {
281 await delay(STATS_WAIT_MS);
282 const text = readFileSync(path, 'utf8');
283 if (text) return JSON.parse(text);
284 }
285 throw new Error('the app wrote no stats');
286}
287
288const sum = (entries, key) => entries.reduce((total, entry) => total + (entry[key] || 0), 0);
289
290async function guestVideo(tab) {
291 const stats = await tab.evaluate(PEER_STATS);
292 return {
293 decoded: sum(stats.videoIn, 'decoded'),
294 widest: Math.max(0, ...stats.videoIn.map((entry) => entry.width || 0)),
295 sentFrames: sum(stats.videoOut, 'frames'),
296 };
297}
298
299async function measure(tab, workDir) {
300 const [appBefore, guestBefore] = [await appStats(workDir), await guestVideo(tab)];
301 await delay(SCENARIO_MEASURE_MS);
302 const [appAfter, guestAfter] = [await appStats(workDir), await guestVideo(tab)];
303 const grew = (after, before, key) => (after[key] || 0) - (before[key] || 0);
304 return {
305 app: appAfter,
306 appVideoOut: grew(appAfter, appBefore, 'videoOutFramesEncoded'),
307 appVideoIn: grew(appAfter, appBefore, 'videoInFramesDecoded'),
308 appVideoShown: grew(appAfter, appBefore, 'videoFramesPublished'),
309 appShareOut: grew(appAfter, appBefore, 'shareOutPackets'),
310 appShareIn: grew(appAfter, appBefore, 'shareInPackets'),
311 guestVideoIn: guestAfter.decoded - guestBefore.decoded,
312 guestWidest: guestAfter.widest,
313 guestVideoOut: guestAfter.sentFrames - guestBefore.sentFrames,
314 };
315}
316
317const ONLY = process.env.SCENARIOS?.split(',');
318
319async function scenario(name, report, tab, workDir, act, check) {
320 if (ONLY && !ONLY.includes(name)) return;
321 log(`scenario: ${name}`);
322 try {
323 await act();
324 await delay(SCENARIO_SETTLE_MS);
325 const measured = await measure(tab, workDir);
326 const pass = Boolean(check(measured));
327 report.scenarios[name] = { pass, ...measured, app: undefined, appState: measured.app };
328 log(`scenario ${name}: ${pass ? 'PASS' : 'FAIL'}`);
329 if (!pass) {
330 await tab.shot(`${workDir}/${name}.png`).catch(() => {});
331 report.scenarios[name].guestVideoStreams = (await tab.evaluate(PEER_STATS).catch(() => ({}))).videoIn;
332 }
333 } catch (error) {
334 report.scenarios[name] = { pass: false, error: error.message };
335 log(`scenario ${name}: ERROR ${error.message}`);
336 }
337}
338
339async function guestClick(tab, labels) {
340 for (const label of labels) {
341 if (await tab.click(label)) return label;
342 }
343 throw new Error(`guest found none of ${labels.join(', ')}`);
344}
345
346async function guestCamera(tab, on) {
347 const sending = (await guestVideo(tab)).sentFrames;
348 await delay(2_000);
349 const isOn = (await guestVideo(tab)).sentFrames > sending;
350 if (isOn !== on) await guestClick(tab, [on ? '=Turn camera on' : '=Turn camera off', '=Camera']);
351}
352
353async function runScenarios(report, tab, workDir) {
354 report.scenarios = {};
355 await scenario('app-camera-on', report, tab, workDir, () => runTeams('--call', 'camera on'),
356 (m) => m.app.cameraOn && m.appVideoOut >= MIN_FRAMES && m.guestVideoIn >= MIN_FRAMES);
357 await scenario('guest-camera-on', report, tab, workDir, () => guestCamera(tab, true),
358 (m) => m.guestVideoOut >= MIN_FRAMES && m.appVideoIn >= MIN_FRAMES && m.appVideoShown >= MIN_FRAMES);
359 await scenario('app-camera-off', report, tab, workDir, () => runTeams('--call', 'camera off'),
360 (m) => !m.app.cameraOn && m.appVideoOut < MIN_FRAMES && m.appVideoIn >= MIN_FRAMES);
361 await scenario('guest-camera-off', report, tab, workDir, () => guestCamera(tab, false),
362 (m) => m.appVideoIn < MIN_FRAMES);
363 await scenario('app-share', report, tab, workDir, async () => {
364 runTeams('--call', 'share-sources');
365 await delay(3_000);
366 runTeams('--call', 'share');
367 }, (m) => m.app.localShare && m.appShareOut > 50 && m.guestVideoIn >= MIN_FRAMES);
368 await scenario('app-stop-share', report, tab, workDir, () => runTeams('--call', 'stop-share'),
369 (m) => !m.app.localShare && m.appShareOut < 20);
370 await scenario('guest-share', report, tab, workDir, async () => {
371 await guestClick(tab, ['=Share', 'Share content', 'Share']);
372 await delay(2_000);
373 await guestClick(tab, ['=Screen', 'Share screen', 'Screen', 'Entire screen']).catch(() => null);
374 }, (m) => m.app.screenSharer && m.appShareIn > 50);
375 await scenario('guest-stop-share', report, tab, workDir, () => guestClick(tab, ['=Stop sharing', 'Stop sharing', 'Stop presenting']),
376 (m) => !m.app.screenSharer && m.appShareIn < 20);
377 await scenario('app-mute', report, tab, workDir, () => runTeams('--call', 'mute'), (m) => m.app.muted);
378 const muted = await sampleWeb(tab, 6);
379 report.scenarios['app-mute'].guestHeardWhileMuted = judge(muted, WEB_THRESHOLD);
380 if (report.scenarios['app-mute'].guestHeardWhileMuted.p90 >= WEB_THRESHOLD.speech) report.scenarios['app-mute'].pass = false;
381 await scenario('app-unmute', report, tab, workDir, () => runTeams('--call', 'unmute'), (m) => !m.app.muted);
382 await audioCheck(report, 'app-unmute', tab, true);
383 await scenario('mic-to-other-device', report, tab, workDir, () => runTeams('--call', 'input microphone array'),
384 (m) => m.app.inCall && /Device/.test(m.app.input ?? ''));
385 await scenario('mic-back-to-cable', report, tab, workDir, () => runTeams('--call', 'input cable output'), (m) => m.app.inCall);
386 await audioCheck(report, 'mic-back-to-cable', tab, true);
387 await scenario('leave-and-rejoin', report, tab, workDir, async () => {
388 runTeams('--hang-up');
389 await delay(8_000);
390 runTeams('--join', report.link);
391 await delay(APP_JOIN_WAIT_MS);
392 runTeams('--unmute');
393 }, (m) => m.app.inCall);
394 await audioCheck(report, 'leave-and-rejoin', tab, true);
395}
396
397async function audioCheck(report, name, tab, expectSpeech) {
398 const entry = report.scenarios[name];
399 if (!entry) return;
400 entry.guestHears = judge(await sampleWeb(tab, 8), WEB_THRESHOLD);
401 if (entry.guestHears.pass !== expectSpeech) entry.pass = false;
402}
403
404const report = { started: new Date().toISOString() };
405const savedCapture = defaultAudio('get', 'capture');
406const restoreCapture = () => defaultAudio('set', 'capture', savedCapture);
407for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { restoreCapture(); process.exit(130); });
408const browser = await new Browser(OWN_ENDPOINT).connect();
409const tab = new GuestTab(browser);
410const secondTab = process.env.SECOND_GUEST ? new GuestTab(browser) : null;
411try {
412 if (!teamsProcessId()) {
413 log(`starting the app, waiting ${APP_START_WAIT_MS / 1000}s`);
414 runTeams();
415 await delay(APP_START_WAIT_MS);
416 }
417 const link = givenLink ?? createMeeting();
418 report.link = link;
419 log('meeting ready');
420 defaultAudio('set', 'capture', 'CABLE Output');
421 log('default mic: CABLE Output');
422 const playSeconds = Math.ceil((APP_JOIN_WAIT_MS + WEB_JOIN_TIMEOUT_MS) / 1000) + MEASURE_SECONDS + 10 + (process.env.AUDIO_ONLY ? 0 : 360);
423 const playing = runProbe('play', 'CABLE Input', windowsPath(PROBE_DIR + '/app.wav'), String(playSeconds));
424 runTeams('--join', link);
425 log(`app joining, waiting ${APP_JOIN_WAIT_MS / 1000}s`);
426 await delay(APP_JOIN_WAIT_MS);
427 const joined = await appStats(workDir).catch(() => ({ inCall: false }));
428 if (!joined.inCall) throw new Error('the app is not in the call after --join');
429 await tab.open(link);
430 const admitting = setInterval(() => runTeams('--admit-all'), ADMIT_INTERVAL_MS);
431 report.webJoined = await tab.join().finally(() => clearInterval(admitting));
432 if (secondTab) {
433 await secondTab.open(link);
434 const admittingSecond = setInterval(() => runTeams('--admit-all'), ADMIT_INTERVAL_MS);
435 report.secondJoined = await secondTab.join().finally(() => clearInterval(admittingSecond));
436 log(`second guest joined: ${report.secondJoined}`);
437 runTeams('--call', 'mute');
438 await delay(10_000);
439 report.secondHearsFirstOnly = await secondTab.evaluate(AUDIO_DECODER).catch((error) => error.message);
440 report.firstWhileAppMuted = await tab.evaluate(AUDIO_DECODER).catch((error) => error.message);
441 }
442 log(`web guest joined: ${report.webJoined}`);
443 if (!report.webJoined) {
444 await tab.shot(workDir + '/web-join.png');
445 throw new Error('Teams web guest did not join, see web-join.png');
446 }
447 await tab.activate();
448 runTeams('--unmute');
449 const processId = teamsProcessId();
450 if (!processId) throw new Error('teams.exe is not running');
451 log(`measuring ${MEASURE_SECONDS}s (teams.exe pid ${processId})`);
452 const [recorded, webLevels] = await Promise.all([
453 runProbe('record-process', String(processId), String(MEASURE_SECONDS), windowsPath(workDir + '/app-heard.wav')),
454 sampleWeb(tab, MEASURE_SECONDS),
455 ]);
456 report.guestSending = await tab.evaluate(GUEST_SENDING).catch((error) => error.message);
457 report.guestPlayback = await tab.playbackState();
458 report.guestAudioDecoder = await tab.evaluate(AUDIO_DECODER).catch((error) => error.message);
459 report.guestSourceLevels = [];
460 for (let sample = 0; sample < 10; sample++) {
461 report.guestSourceLevels.push(await tab.evaluate(`(window.__pcs || []).flatMap((peer) => peer.getReceivers().filter((receiver) => receiver.track && receiver.track.kind === 'audio').flatMap((receiver) => receiver.getSynchronizationSources().map((source) => Number((source.audioLevel || 0).toFixed(3)))))`).catch((error) => error.message));
462 await delay(500);
463 }
464 report.guestReceiving = await tab.evaluate(PEER_STATS).then((stats) => ({ peers: stats.peers, audioIn: stats.audioIn })).catch((error) => error.message);
465 report.appToWeb = judge(webLevels, WEB_THRESHOLD);
466 report.webToApp = judge(JSON.parse(recorded).rms, APP_THRESHOLD);
467 report.webLevels = webLevels.map((level) => Number(level.toFixed(4)));
468 report.appLevels = JSON.parse(recorded).rms;
469 await tab.shot(workDir + '/web-in-call.png');
470 if (!process.env.AUDIO_ONLY) await runScenarios(report, tab, workDir);
471 await playing.catch((error) => (report.playError = error.message));
472} catch (error) {
473 report.error = error.message;
474} finally {
475 if (teamsProcessId()) runTeams('--hang-up');
476 await tab.close();
477 if (secondTab) await secondTab.close();
478 restoreCapture();
479 log('default mic restored');
480 browser.socket.close();
481}
482const scenariosPass = Object.values(report.scenarios ?? {}).every((entry) => entry.pass);
483report.pass = Boolean(report.appToWeb?.pass && report.webToApp?.pass && scenariosPass);
484writeFileSync(workDir + '/report.json', JSON.stringify(report, null, 2));
485const scenarioSummary = Object.fromEntries(Object.entries(report.scenarios ?? {}).map(([name, entry]) => [name, entry.pass ? 'pass' : `FAIL ${entry.error ?? ''}`.trim()]));
486console.log(JSON.stringify({ pass: report.pass, secondHearsFirstOnly: report.secondHearsFirstOnly, firstWhileAppMuted: report.firstWhileAppMuted, guestAudioDecoder: report.guestAudioDecoder, guestPlayback: report.guestPlayback, guestReceiving: report.guestReceiving, appToWeb: report.appToWeb, webToApp: report.webToApp, scenarios: scenarioSummary, guestSending: report.guestSending, error: report.error }));
487process.exit(report.pass ? 0 : 1);