BlueGit

ict rusty-teams

Files

rusty-teams / scripts / call-e2e.mjs

call-e2e.mjs

call-e2e.mjs 13.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// Usage: node scripts/call-e2e.mjs <work dir> [meeting link]
6import { spawn, execFileSync } from 'node:child_process';
7import { readFileSync, writeFileSync } from 'node:fs';
8import { Browser, FAKE_MEDIA, PEER_HOOK } from './teams-web-cdp.mjs';
9
10const [workDir, givenLink] = process.argv.slice(2);
11const OWN_ENDPOINT = process.env.OWN_CDP ?? 'http://127.0.0.1:9222';
12const PROBE_DIR = process.env.PROBE_DIR ?? '/mnt/c/Users/dd/AppData/Local/Temp/call-e2e';
13const TEAMS_EXE = process.env.TEAMS_EXE ?? '/mnt/c/Users/dd/AppData/Local/Programs/ms-teams-linux/teams.exe';
14const POWERSHELL = '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe';
15const TASKLIST = '/mnt/c/Windows/System32/tasklist.exe';
16const SCRIPT_DIR = new URL('.', import.meta.url).pathname;
17const REPO_DIR = new URL('..', import.meta.url).pathname;
18const APP_START_WAIT_MS = 40_000;
19const WEB_JOIN_TIMEOUT_MS = 90_000;
20const APP_JOIN_WAIT_MS = 25_000;
21const MEASURE_SECONDS = 30;
22const WINDOW_MS = 250;
23const STEP_REPEAT_MS = 15_000;
24const ADMIT_INTERVAL_MS = 5_000;
25const WEB_JOIN_STEPS = ['Continue on this browser', 'Not now', '=Join now', '=Join'];
26const GUEST_NAME = 'Call e2e guest';
27const LOBBY_TEXTS = ['let you in shortly', 'should let you in soon'];
28const WEB_THRESHOLD = { speech: 0.005, floor: 0.0005 };
29const APP_THRESHOLD = { speech: 200, floor: 20 };
30const SPEECH_TO_PAUSE = 4;
31
32const windowsPath = (path) => execFileSync('wslpath', ['-w', path]).toString().trim();
33const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
34const log = (message) => console.error(`[${new Date().toISOString().slice(11, 19)}] ${message}`);
35
36function defaultAudio(...args) {
37 const script = windowsPath(SCRIPT_DIR + 'default-audio.ps1');
38 return execFileSync(POWERSHELL, ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script, ...args]).toString().trim();
39}
40
41function createMeeting() {
42 return execFileSync('cargo', ['run', '-q', '-p', 'chatsvc', '--example', 'create_test_meeting'], { cwd: REPO_DIR, stdio: ['ignore', 'pipe', 'inherit'] })
43 .toString()
44 .trim();
45}
46
47function teamsProcessId() {
48 const rows = execFileSync(TASKLIST, ['/FI', 'IMAGENAME eq teams.exe', '/FO', 'CSV', '/NH']).toString().trim().split(/\r?\n/);
49 const processes = rows
50 .map((row) => row.split('","').map((cell) => cell.replace(/"/g, '')))
51 .filter((cells) => cells[0]?.toLowerCase() === 'teams.exe')
52 .map((cells) => ({ id: Number(cells[1]), memory: Number(cells[4].replace(/\D/g, '')) }));
53 processes.sort((left, right) => right.memory - left.memory);
54 return processes[0]?.id;
55}
56
57function runTeams(...args) {
58 spawn(TEAMS_EXE, args, { detached: true, stdio: 'ignore' }).unref();
59}
60
61function runProbe(...args) {
62 return new Promise((resolve, reject) => {
63 const child = spawn(PROBE_DIR + '/audio_probe.exe', args, { stdio: ['ignore', 'pipe', 'pipe'] });
64 let output = '';
65 let errors = '';
66 child.stdout.on('data', (chunk) => (output += chunk));
67 child.stderr.on('data', (chunk) => (errors += chunk));
68 child.on('exit', (code) => (code === 0 ? resolve(output) : reject(new Error(`audio_probe ${args[0]}: ${errors.trim()}`))));
69 });
70}
71
72const speechDataUrl = () => `data:audio/wav;base64,${readFileSync(PROBE_DIR + '/web.wav').toString('base64')}`;
73
74// Taps every received audio track, so the level does not depend on headless Chrome playing it out.
75const REMOTE_AUDIO_TAP = `(() => {
76 window.__remoteAudio = { sum: 0, count: 0, packets: 0 };
77 const tapped = new WeakSet();
78 const tap = async (track) => {
79 tapped.add(track);
80 const reader = new MediaStreamTrackProcessor({ track }).readable.getReader();
81 for (;;) {
82 const { value, done } = await reader.read();
83 if (done) return;
84 const samples = new Float32Array(value.numberOfFrames);
85 value.copyTo(samples, { planeIndex: 0, format: 'f32-planar' });
86 value.close();
87 for (const sample of samples) window.__remoteAudio.sum += sample * sample;
88 window.__remoteAudio.count += samples.length;
89 }
90 };
91 setInterval(() => {
92 for (const peer of window.__pcs || []) {
93 for (const receiver of peer.getReceivers()) {
94 if (receiver.track && receiver.track.kind === 'audio' && !tapped.has(receiver.track)) tap(receiver.track).catch(() => {});
95 }
96 }
97 }, 500);
98})();`;
99
100const INBOUND_AUDIO = `({ ...window.__remoteAudio })`;
101
102const GUEST_SENDING = `(async () => {
103 let energy = 0, duration = 0, packets = 0;
104 for (const peer of window.__pcs || []) {
105 if (peer.connectionState === 'closed') continue;
106 (await peer.getStats()).forEach((entry) => {
107 if (entry.type === 'media-source' && entry.kind === 'audio') { energy += entry.totalAudioEnergy || 0; duration += entry.totalSamplesDuration || 0; }
108 if (entry.type === 'outbound-rtp' && entry.kind === 'audio') packets += entry.packetsSent || 0;
109 });
110 }
111 return { level: duration > 0 ? Math.sqrt(energy / duration) : 0, packets };
112})()`;
113const LOCATE = (step) => `(() => {
114 const onlyExact = ${JSON.stringify(step.startsWith('='))};
115 const wanted = ${JSON.stringify(step.replace(/^=/, ''))}.toLowerCase();
116 const nodes = [...document.querySelectorAll('button, [role=button], [role=menuitem], a')];
117 const label = (node) => ((node.getAttribute('aria-label') || '') + ' ' + (node.innerText || '') + ' ' + (node.getAttribute('title') || '')).trim().toLowerCase();
118 const visible = nodes.filter((node) => node.getClientRects().length && !node.disabled && node.getAttribute('aria-disabled') !== 'true');
119 const exact = visible.find((node) => (node.innerText || '').trim().toLowerCase() === wanted || (node.getAttribute('aria-label') || '').trim().toLowerCase() === wanted);
120 const target = exact || (onlyExact ? null : visible.find((node) => label(node).includes(wanted)));
121 if (!target) return null;
122 target.scrollIntoView({ block: 'center' });
123 target.click();
124 return label(target).slice(0, 80);
125})()`;
126const CONNECTED = `(window.__pcs || []).some((peer) => peer.connectionState === 'connected')`;
127const TEAMS_ORIGINS = ['https://teams.cloud.microsoft', 'https://teams.microsoft.com'];
128
129class GuestTab {
130 constructor(browser) { this.browser = browser; }
131 async open(link) {
132 this.contextId = (await this.browser.send('Target.createBrowserContext', { disposeOnDetach: false })).browserContextId;
133 const context = this.contextId ? { browserContextId: this.contextId } : {};
134 const { targetId } = await this.browser.send('Target.createTarget', { url: 'about:blank', ...context });
135 this.targetId = targetId;
136 const { sessionId } = await this.browser.send('Target.attachToTarget', { targetId, flatten: true });
137 this.sessionId = sessionId;
138 await this.browser.send('Page.enable', {}, sessionId);
139 await this.browser.send('Runtime.enable', {}, sessionId);
140 await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: PEER_HOOK }, sessionId);
141 await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: REMOTE_AUDIO_TAP }, sessionId);
142 await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: FAKE_MEDIA(speechDataUrl()) }, sessionId);
143 for (const origin of TEAMS_ORIGINS) {
144 await this.browser.send('Browser.grantPermissions', { permissions: ['audioCapture', 'videoCapture'], origin, ...context }).catch(() => {});
145 }
146 await this.browser.send('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId).catch(() => {});
147 await this.browser.send('Page.navigate', { url: link }, sessionId);
148 }
149 async evaluate(expression) {
150 const result = await this.browser.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, this.sessionId);
151 if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description ?? 'evaluate failed');
152 return result.result.value;
153 }
154 async join() {
155 const deadline = Date.now() + WEB_JOIN_TIMEOUT_MS;
156 const clickedAt = new Map();
157 while (Date.now() < deadline) {
158 const inLobby = await this.evaluate(`${JSON.stringify(LOBBY_TEXTS)}.some((text) => document.body.innerText.includes(text))`).catch(() => false);
159 if (!inLobby && (await this.evaluate(CONNECTED).catch(() => false))) return true;
160 await this.activate();
161 await this.typeName();
162 for (const step of WEB_JOIN_STEPS) {
163 if (Date.now() - (clickedAt.get(step) ?? 0) < STEP_REPEAT_MS) continue;
164 if (await this.click(step)) {
165 clickedAt.set(step, Date.now());
166 log(`web: clicked "${step}"`);
167 }
168 }
169 await delay(2000);
170 }
171 return false;
172 }
173 async click(step) {
174 return this.evaluate(LOCATE(step)).catch(() => null);
175 }
176 async activate() {
177 for (const type of ['mousePressed', 'mouseReleased']) {
178 await this.browser.send('Input.dispatchMouseEvent', { type, x: 5, y: 5, button: 'left', clickCount: 1 }, this.sessionId).catch(() => {});
179 }
180 }
181 async typeName() {
182 const focused = await this.evaluate(`(() => {
183 const input = document.querySelector('input[placeholder*="name" i]');
184 if (!input || input.value) return false;
185 input.focus(); return true;
186 })()`).catch(() => false);
187 if (focused) await this.browser.send('Input.insertText', { text: GUEST_NAME }, this.sessionId);
188 }
189 async shot(path) {
190 const { data } = await this.browser.send('Page.captureScreenshot', { format: 'png' }, this.sessionId);
191 writeFileSync(path, Buffer.from(data, 'base64'));
192 }
193 async close() {
194 if (this.targetId) await this.browser.send('Target.closeTarget', { targetId: this.targetId }).catch(() => {});
195 if (this.contextId) await this.browser.send('Target.disposeBrowserContext', { browserContextId: this.contextId }).catch(() => {});
196 }
197}
198
199async function sampleWeb(tab, seconds) {
200 const levels = [];
201 let previous = await tab.evaluate(INBOUND_AUDIO);
202 const end = Date.now() + seconds * 1000;
203 while (Date.now() < end) {
204 await delay(WINDOW_MS);
205 const current = await tab.evaluate(INBOUND_AUDIO);
206 const count = current.count - previous.count;
207 levels.push(count > 0 ? Math.sqrt((current.sum - previous.sum) / count) : 0);
208 previous = current;
209 }
210 return levels;
211}
212
213function judge(levels, threshold) {
214 const sorted = [...levels].sort((left, right) => left - right);
215 const percentile = (share) => sorted[Math.min(sorted.length - 1, Math.floor(share * sorted.length))] ?? 0;
216 const [p10, p90] = [percentile(0.1), percentile(0.9)];
217 const speech = p90 >= threshold.speech;
218 const pauses = p90 >= SPEECH_TO_PAUSE * Math.max(p10, threshold.floor);
219 return { pass: speech && pauses, p10, p90, windows: levels.length };
220}
221
222const report = { started: new Date().toISOString() };
223const savedCapture = defaultAudio('get', 'capture');
224const restoreCapture = () => defaultAudio('set', 'capture', savedCapture);
225for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { restoreCapture(); process.exit(130); });
226const browser = await new Browser(OWN_ENDPOINT).connect();
227const tab = new GuestTab(browser);
228try {
229 if (!teamsProcessId()) {
230 log(`starting the app, waiting ${APP_START_WAIT_MS / 1000}s`);
231 runTeams();
232 await delay(APP_START_WAIT_MS);
233 }
234 const link = givenLink ?? createMeeting();
235 report.link = link;
236 log('meeting ready');
237 defaultAudio('set', 'capture', 'CABLE Output');
238 log('default mic: CABLE Output');
239 const playSeconds = Math.ceil((APP_JOIN_WAIT_MS + WEB_JOIN_TIMEOUT_MS) / 1000) + MEASURE_SECONDS + 10;
240 const playing = runProbe('play', 'CABLE Input', windowsPath(PROBE_DIR + '/app.wav'), String(playSeconds));
241 runTeams('--join', link);
242 log(`app joining, waiting ${APP_JOIN_WAIT_MS / 1000}s`);
243 await delay(APP_JOIN_WAIT_MS);
244 await tab.open(link);
245 const admitting = setInterval(() => runTeams('--admit-all'), ADMIT_INTERVAL_MS);
246 report.webJoined = await tab.join().finally(() => clearInterval(admitting));
247 log(`web guest joined: ${report.webJoined}`);
248 if (!report.webJoined) {
249 await tab.shot(workDir + '/web-join.png');
250 throw new Error('Teams web guest did not join, see web-join.png');
251 }
252 await tab.activate();
253 runTeams('--unmute');
254 const processId = teamsProcessId();
255 if (!processId) throw new Error('teams.exe is not running');
256 log(`measuring ${MEASURE_SECONDS}s (teams.exe pid ${processId})`);
257 const [recorded, webLevels] = await Promise.all([
258 runProbe('record-process', String(processId), String(MEASURE_SECONDS), windowsPath(workDir + '/app-heard.wav')),
259 sampleWeb(tab, MEASURE_SECONDS),
260 ]);
261 report.guestSending = await tab.evaluate(GUEST_SENDING).catch((error) => error.message);
262 report.appToWeb = judge(webLevels, WEB_THRESHOLD);
263 report.webToApp = judge(JSON.parse(recorded).rms, APP_THRESHOLD);
264 report.webLevels = webLevels.map((level) => Number(level.toFixed(4)));
265 report.appLevels = JSON.parse(recorded).rms;
266 await tab.shot(workDir + '/web-in-call.png');
267 await playing.catch((error) => (report.playError = error.message));
268} catch (error) {
269 report.error = error.message;
270} finally {
271 if (teamsProcessId()) runTeams('--hang-up');
272 await tab.close();
273 restoreCapture();
274 log('default mic restored');
275 browser.socket.close();
276}
277report.pass = Boolean(report.appToWeb?.pass && report.webToApp?.pass);
278writeFileSync(workDir + '/report.json', JSON.stringify(report, null, 2));
279console.log(JSON.stringify({ pass: report.pass, appToWeb: report.appToWeb, webToApp: report.webToApp, guestSending: report.guestSending, error: report.error }));
280process.exit(report.pass ? 0 : 1);