BlueGit

ict rusty-teams

Files

rusty-teams / scripts / call-e2e.mjs

call-e2e.mjs

call-e2e.mjs 20.6 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})()`;
140const CONNECTED = `(window.__pcs || []).some((peer) => peer.connectionState === 'connected')`;
141const TEAMS_ORIGINS = ['https://teams.cloud.microsoft', 'https://teams.microsoft.com'];
142
143class GuestTab {
144 constructor(browser) { this.browser = browser; }
145 async open(link) {
146 this.contextId = (await this.browser.send('Target.createBrowserContext', { disposeOnDetach: false })).browserContextId;
147 const context = this.contextId ? { browserContextId: this.contextId } : {};
148 const { targetId } = await this.browser.send('Target.createTarget', { url: 'about:blank', ...context });
149 this.targetId = targetId;
150 const { sessionId } = await this.browser.send('Target.attachToTarget', { targetId, flatten: true });
151 this.sessionId = sessionId;
152 await this.browser.send('Page.enable', {}, sessionId);
153 await this.browser.send('Runtime.enable', {}, sessionId);
154 await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: PEER_HOOK }, sessionId);
155 await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: REMOTE_AUDIO_TAP }, sessionId);
156 await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: FAKE_MEDIA(speechDataUrl()) }, sessionId);
157 for (const origin of TEAMS_ORIGINS) {
158 await this.browser.send('Browser.grantPermissions', { permissions: ['audioCapture', 'videoCapture'], origin, ...context }).catch(() => {});
159 }
160 await this.browser.send('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId).catch(() => {});
161 await this.browser.send('Page.navigate', { url: link }, sessionId);
162 }
163 async evaluate(expression) {
164 const result = await this.browser.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, this.sessionId);
165 if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description ?? 'evaluate failed');
166 return result.result.value;
167 }
168 async join() {
169 const deadline = Date.now() + WEB_JOIN_TIMEOUT_MS;
170 const clickedAt = new Map();
171 while (Date.now() < deadline) {
172 const inLobby = await this.evaluate(`${JSON.stringify(LOBBY_TEXTS)}.some((text) => document.body.innerText.includes(text))`).catch(() => false);
173 if (!inLobby && (await this.evaluate(CONNECTED).catch(() => false))) return true;
174 await this.activate();
175 await this.typeName();
176 for (const step of WEB_JOIN_STEPS) {
177 if (Date.now() - (clickedAt.get(step) ?? 0) < STEP_REPEAT_MS) continue;
178 if (await this.click(step)) {
179 clickedAt.set(step, Date.now());
180 log(`web: clicked "${step}"`);
181 }
182 }
183 await delay(2000);
184 }
185 return false;
186 }
187 async click(step) {
188 return this.evaluate(LOCATE(step)).catch(() => null);
189 }
190 async activate() {
191 for (const type of ['mousePressed', 'mouseReleased']) {
192 await this.browser.send('Input.dispatchMouseEvent', { type, x: 5, y: 5, button: 'left', clickCount: 1 }, this.sessionId).catch(() => {});
193 }
194 }
195 async playbackState() {
196 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);
197 }
198 async typeName() {
199 const focused = await this.evaluate(`(() => {
200 const input = document.querySelector('input[placeholder*="name" i]');
201 if (!input || input.value) return false;
202 input.focus(); return true;
203 })()`).catch(() => false);
204 if (focused) await this.browser.send('Input.insertText', { text: GUEST_NAME }, this.sessionId);
205 }
206 async shot(path) {
207 const { data } = await this.browser.send('Page.captureScreenshot', { format: 'png' }, this.sessionId);
208 writeFileSync(path, Buffer.from(data, 'base64'));
209 }
210 async close() {
211 if (this.targetId) await this.browser.send('Target.closeTarget', { targetId: this.targetId }).catch(() => {});
212 if (this.contextId) await this.browser.send('Target.disposeBrowserContext', { browserContextId: this.contextId }).catch(() => {});
213 }
214}
215
216async function sampleWeb(tab, seconds) {
217 const levels = [];
218 let previous = await tab.evaluate(INBOUND_AUDIO);
219 const end = Date.now() + seconds * 1000;
220 while (Date.now() < end) {
221 await delay(WINDOW_MS);
222 const current = await tab.evaluate(INBOUND_AUDIO);
223 const count = current.count - previous.count;
224 const duration = current.duration - previous.duration;
225 if (count > 0) levels.push(Math.sqrt((current.sum - previous.sum) / count));
226 else levels.push(duration > 0 ? Math.sqrt((current.energy - previous.energy) / duration) : 0);
227 previous = current;
228 }
229 return levels;
230}
231
232function judge(levels, threshold) {
233 const sorted = [...levels].sort((left, right) => left - right);
234 const percentile = (share) => sorted[Math.min(sorted.length - 1, Math.floor(share * sorted.length))] ?? 0;
235 const [p10, p90] = [percentile(0.1), percentile(0.9)];
236 const speech = p90 >= threshold.speech;
237 const pauses = p90 >= SPEECH_TO_PAUSE * Math.max(p10, threshold.floor);
238 return { pass: speech && pauses, p10, p90, windows: levels.length };
239}
240
241
242async function appStats(workDir) {
243 const path = workDir + '/app-stats.json';
244 writeFileSync(path, '');
245 runTeams('--call', `stats ${windowsPath(path)}`);
246 const deadline = Date.now() + 10_000;
247 while (Date.now() < deadline) {
248 await delay(STATS_WAIT_MS);
249 const text = readFileSync(path, 'utf8');
250 if (text) return JSON.parse(text);
251 }
252 throw new Error('the app wrote no stats');
253}
254
255const sum = (entries, key) => entries.reduce((total, entry) => total + (entry[key] || 0), 0);
256
257async function guestVideo(tab) {
258 const stats = await tab.evaluate(PEER_STATS);
259 return {
260 decoded: sum(stats.videoIn, 'decoded'),
261 widest: Math.max(0, ...stats.videoIn.map((entry) => entry.width || 0)),
262 sentFrames: sum(stats.videoOut, 'frames'),
263 };
264}
265
266async function measure(tab, workDir) {
267 const [appBefore, guestBefore] = [await appStats(workDir), await guestVideo(tab)];
268 await delay(SCENARIO_MEASURE_MS);
269 const [appAfter, guestAfter] = [await appStats(workDir), await guestVideo(tab)];
270 const grew = (after, before, key) => (after[key] || 0) - (before[key] || 0);
271 return {
272 app: appAfter,
273 appVideoOut: grew(appAfter, appBefore, 'videoOutFramesEncoded'),
274 appVideoIn: grew(appAfter, appBefore, 'videoInFramesDecoded'),
275 appVideoShown: grew(appAfter, appBefore, 'videoFramesPublished'),
276 appShareOut: grew(appAfter, appBefore, 'shareOutPackets'),
277 appShareIn: grew(appAfter, appBefore, 'shareInPackets'),
278 guestVideoIn: guestAfter.decoded - guestBefore.decoded,
279 guestWidest: guestAfter.widest,
280 guestVideoOut: guestAfter.sentFrames - guestBefore.sentFrames,
281 };
282}
283
284const ONLY = process.env.SCENARIOS?.split(',');
285
286async function scenario(name, report, tab, workDir, act, check) {
287 if (ONLY && !ONLY.includes(name)) return;
288 log(`scenario: ${name}`);
289 try {
290 await act();
291 await delay(SCENARIO_SETTLE_MS);
292 const measured = await measure(tab, workDir);
293 const pass = Boolean(check(measured));
294 report.scenarios[name] = { pass, ...measured, app: undefined, appState: measured.app };
295 log(`scenario ${name}: ${pass ? 'PASS' : 'FAIL'}`);
296 if (!pass) {
297 await tab.shot(`${workDir}/${name}.png`).catch(() => {});
298 report.scenarios[name].guestVideoStreams = (await tab.evaluate(PEER_STATS).catch(() => ({}))).videoIn;
299 }
300 } catch (error) {
301 report.scenarios[name] = { pass: false, error: error.message };
302 log(`scenario ${name}: ERROR ${error.message}`);
303 }
304}
305
306async function guestClick(tab, labels) {
307 for (const label of labels) {
308 if (await tab.click(label)) return label;
309 }
310 throw new Error(`guest found none of ${labels.join(', ')}`);
311}
312
313async function guestCamera(tab, on) {
314 const sending = (await guestVideo(tab)).sentFrames;
315 await delay(2_000);
316 const isOn = (await guestVideo(tab)).sentFrames > sending;
317 if (isOn !== on) await guestClick(tab, [on ? '=Turn camera on' : '=Turn camera off', '=Camera']);
318}
319
320async function runScenarios(report, tab, workDir) {
321 report.scenarios = {};
322 await scenario('app-camera-on', report, tab, workDir, () => runTeams('--call', 'camera on'),
323 (m) => m.app.cameraOn && m.appVideoOut >= MIN_FRAMES && m.guestVideoIn >= MIN_FRAMES);
324 await scenario('guest-camera-on', report, tab, workDir, () => guestCamera(tab, true),
325 (m) => m.guestVideoOut >= MIN_FRAMES && m.appVideoIn >= MIN_FRAMES && m.appVideoShown >= MIN_FRAMES);
326 await scenario('app-camera-off', report, tab, workDir, () => runTeams('--call', 'camera off'),
327 (m) => !m.app.cameraOn && m.appVideoOut < MIN_FRAMES && m.appVideoIn >= MIN_FRAMES);
328 await scenario('guest-camera-off', report, tab, workDir, () => guestCamera(tab, false),
329 (m) => m.appVideoIn < MIN_FRAMES);
330 await scenario('app-share', report, tab, workDir, async () => {
331 runTeams('--call', 'share-sources');
332 await delay(3_000);
333 runTeams('--call', 'share');
334 }, (m) => m.app.localShare && m.appShareOut > 50 && m.guestVideoIn >= MIN_FRAMES);
335 await scenario('app-stop-share', report, tab, workDir, () => runTeams('--call', 'stop-share'),
336 (m) => !m.app.localShare && m.appShareOut < 20);
337 await scenario('guest-share', report, tab, workDir, async () => {
338 await guestClick(tab, ['=Share', 'Share content', 'Share']);
339 await delay(2_000);
340 await guestClick(tab, ['=Screen', 'Share screen', 'Screen', 'Entire screen']).catch(() => null);
341 }, (m) => m.app.screenSharer && m.appShareIn > 50);
342 await scenario('guest-stop-share', report, tab, workDir, () => guestClick(tab, ['=Stop sharing', 'Stop sharing', 'Stop presenting']),
343 (m) => !m.app.screenSharer && m.appShareIn < 20);
344 await scenario('app-mute', report, tab, workDir, () => runTeams('--call', 'mute'), (m) => m.app.muted);
345 const muted = await sampleWeb(tab, 6);
346 report.scenarios['app-mute'].guestHeardWhileMuted = judge(muted, WEB_THRESHOLD);
347 if (report.scenarios['app-mute'].guestHeardWhileMuted.p90 >= WEB_THRESHOLD.speech) report.scenarios['app-mute'].pass = false;
348 await scenario('app-unmute', report, tab, workDir, () => runTeams('--call', 'unmute'), (m) => !m.app.muted);
349 const unmuted = await sampleWeb(tab, 8);
350 report.scenarios['app-unmute'].guestHears = judge(unmuted, WEB_THRESHOLD);
351 if (!report.scenarios['app-unmute'].guestHears.pass) report.scenarios['app-unmute'].pass = false;
352}
353
354const report = { started: new Date().toISOString() };
355const savedCapture = defaultAudio('get', 'capture');
356const restoreCapture = () => defaultAudio('set', 'capture', savedCapture);
357for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { restoreCapture(); process.exit(130); });
358const browser = await new Browser(OWN_ENDPOINT).connect();
359const tab = new GuestTab(browser);
360try {
361 if (!teamsProcessId()) {
362 log(`starting the app, waiting ${APP_START_WAIT_MS / 1000}s`);
363 runTeams();
364 await delay(APP_START_WAIT_MS);
365 }
366 const link = givenLink ?? createMeeting();
367 report.link = link;
368 log('meeting ready');
369 defaultAudio('set', 'capture', 'CABLE Output');
370 log('default mic: CABLE Output');
371 const playSeconds = Math.ceil((APP_JOIN_WAIT_MS + WEB_JOIN_TIMEOUT_MS) / 1000) + MEASURE_SECONDS + 10 + (process.env.AUDIO_ONLY ? 0 : 240);
372 const playing = runProbe('play', 'CABLE Input', windowsPath(PROBE_DIR + '/app.wav'), String(playSeconds));
373 runTeams('--join', link);
374 log(`app joining, waiting ${APP_JOIN_WAIT_MS / 1000}s`);
375 await delay(APP_JOIN_WAIT_MS);
376 await tab.open(link);
377 const admitting = setInterval(() => runTeams('--admit-all'), ADMIT_INTERVAL_MS);
378 report.webJoined = await tab.join().finally(() => clearInterval(admitting));
379 log(`web guest joined: ${report.webJoined}`);
380 if (!report.webJoined) {
381 await tab.shot(workDir + '/web-join.png');
382 throw new Error('Teams web guest did not join, see web-join.png');
383 }
384 await tab.activate();
385 runTeams('--unmute');
386 const processId = teamsProcessId();
387 if (!processId) throw new Error('teams.exe is not running');
388 log(`measuring ${MEASURE_SECONDS}s (teams.exe pid ${processId})`);
389 const [recorded, webLevels] = await Promise.all([
390 runProbe('record-process', String(processId), String(MEASURE_SECONDS), windowsPath(workDir + '/app-heard.wav')),
391 sampleWeb(tab, MEASURE_SECONDS),
392 ]);
393 report.guestSending = await tab.evaluate(GUEST_SENDING).catch((error) => error.message);
394 report.guestPlayback = await tab.playbackState();
395 report.guestReceiving = await tab.evaluate(PEER_STATS).then((stats) => ({ peers: stats.peers, audioIn: stats.audioIn })).catch((error) => error.message);
396 report.appToWeb = judge(webLevels, WEB_THRESHOLD);
397 report.webToApp = judge(JSON.parse(recorded).rms, APP_THRESHOLD);
398 report.webLevels = webLevels.map((level) => Number(level.toFixed(4)));
399 report.appLevels = JSON.parse(recorded).rms;
400 await tab.shot(workDir + '/web-in-call.png');
401 if (!process.env.AUDIO_ONLY) await runScenarios(report, tab, workDir);
402 await playing.catch((error) => (report.playError = error.message));
403} catch (error) {
404 report.error = error.message;
405} finally {
406 if (teamsProcessId()) runTeams('--hang-up');
407 await tab.close();
408 restoreCapture();
409 log('default mic restored');
410 browser.socket.close();
411}
412const scenariosPass = Object.values(report.scenarios ?? {}).every((entry) => entry.pass);
413report.pass = Boolean(report.appToWeb?.pass && report.webToApp?.pass && scenariosPass);
414writeFileSync(workDir + '/report.json', JSON.stringify(report, null, 2));
415const scenarioSummary = Object.fromEntries(Object.entries(report.scenarios ?? {}).map(([name, entry]) => [name, entry.pass ? 'pass' : `FAIL ${entry.error ?? ''}`.trim()]));
416console.log(JSON.stringify({ pass: report.pass, guestPlayback: report.guestPlayback, guestReceiving: report.guestReceiving, appToWeb: report.appToWeb, webToApp: report.webToApp, scenarios: scenarioSummary, guestSending: report.guestSending, error: report.error }));
417process.exit(report.pass ? 0 : 1);