BlueGit

ict rusty-teams

Files

rusty-teams / scripts / call-e2e.mjs

call-e2e.mjs

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