BlueGit

ict rusty-teams

Files

rusty-teams / scripts / call-e2e.mjs

call-e2e.mjs

call-e2e.mjs 12.9 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
74const INBOUND_AUDIO = `(async () => {
75 let energy = 0, duration = 0, packets = 0;
76 for (const peer of window.__pcs || []) {
77 if (peer.connectionState === 'closed') continue;
78 (await peer.getStats()).forEach((entry) => {
79 if (entry.type !== 'inbound-rtp' || entry.kind !== 'audio') return;
80 energy += entry.totalAudioEnergy || 0; duration += entry.totalSamplesDuration || 0; packets += entry.packetsReceived || 0;
81 });
82 }
83 return { energy, duration, packets };
84})()`;
85
86const GUEST_SENDING = `(async () => {
87 let energy = 0, duration = 0, packets = 0;
88 for (const peer of window.__pcs || []) {
89 if (peer.connectionState === 'closed') continue;
90 (await peer.getStats()).forEach((entry) => {
91 if (entry.type === 'media-source' && entry.kind === 'audio') { energy += entry.totalAudioEnergy || 0; duration += entry.totalSamplesDuration || 0; }
92 if (entry.type === 'outbound-rtp' && entry.kind === 'audio') packets += entry.packetsSent || 0;
93 });
94 }
95 return { level: duration > 0 ? Math.sqrt(energy / duration) : 0, packets };
96})()`;
97const LOCATE = (step) => `(() => {
98 const onlyExact = ${JSON.stringify(step.startsWith('='))};
99 const wanted = ${JSON.stringify(step.replace(/^=/, ''))}.toLowerCase();
100 const nodes = [...document.querySelectorAll('button, [role=button], [role=menuitem], a')];
101 const label = (node) => ((node.getAttribute('aria-label') || '') + ' ' + (node.innerText || '') + ' ' + (node.getAttribute('title') || '')).trim().toLowerCase();
102 const visible = nodes.filter((node) => node.getClientRects().length && !node.disabled && node.getAttribute('aria-disabled') !== 'true');
103 const exact = visible.find((node) => (node.innerText || '').trim().toLowerCase() === wanted || (node.getAttribute('aria-label') || '').trim().toLowerCase() === wanted);
104 const target = exact || (onlyExact ? null : visible.find((node) => label(node).includes(wanted)));
105 if (!target) return null;
106 target.scrollIntoView({ block: 'center' });
107 target.click();
108 return label(target).slice(0, 80);
109})()`;
110const CONNECTED = `(window.__pcs || []).some((peer) => peer.connectionState === 'connected')`;
111const TEAMS_ORIGINS = ['https://teams.cloud.microsoft', 'https://teams.microsoft.com'];
112
113class GuestTab {
114 constructor(browser) { this.browser = browser; }
115 async open(link) {
116 this.contextId = (await this.browser.send('Target.createBrowserContext', { disposeOnDetach: false })).browserContextId;
117 const context = this.contextId ? { browserContextId: this.contextId } : {};
118 const { targetId } = await this.browser.send('Target.createTarget', { url: 'about:blank', ...context });
119 this.targetId = targetId;
120 const { sessionId } = await this.browser.send('Target.attachToTarget', { targetId, flatten: true });
121 this.sessionId = sessionId;
122 await this.browser.send('Page.enable', {}, sessionId);
123 await this.browser.send('Runtime.enable', {}, sessionId);
124 await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: PEER_HOOK }, sessionId);
125 await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: FAKE_MEDIA(speechDataUrl()) }, sessionId);
126 for (const origin of TEAMS_ORIGINS) {
127 await this.browser.send('Browser.grantPermissions', { permissions: ['audioCapture', 'videoCapture'], origin, ...context }).catch(() => {});
128 }
129 await this.browser.send('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId).catch(() => {});
130 await this.browser.send('Page.navigate', { url: link }, sessionId);
131 }
132 async evaluate(expression) {
133 const result = await this.browser.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, this.sessionId);
134 if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description ?? 'evaluate failed');
135 return result.result.value;
136 }
137 async join() {
138 const deadline = Date.now() + WEB_JOIN_TIMEOUT_MS;
139 const clickedAt = new Map();
140 while (Date.now() < deadline) {
141 const inLobby = await this.evaluate(`${JSON.stringify(LOBBY_TEXTS)}.some((text) => document.body.innerText.includes(text))`).catch(() => false);
142 if (!inLobby && (await this.evaluate(CONNECTED).catch(() => false))) return true;
143 await this.activate();
144 await this.typeName();
145 for (const step of WEB_JOIN_STEPS) {
146 if (Date.now() - (clickedAt.get(step) ?? 0) < STEP_REPEAT_MS) continue;
147 if (await this.click(step)) {
148 clickedAt.set(step, Date.now());
149 log(`web: clicked "${step}"`);
150 }
151 }
152 await delay(2000);
153 }
154 return false;
155 }
156 async click(step) {
157 return this.evaluate(LOCATE(step)).catch(() => null);
158 }
159 async activate() {
160 for (const type of ['mousePressed', 'mouseReleased']) {
161 await this.browser.send('Input.dispatchMouseEvent', { type, x: 5, y: 5, button: 'left', clickCount: 1 }, this.sessionId).catch(() => {});
162 }
163 }
164 async typeName() {
165 const focused = await this.evaluate(`(() => {
166 const input = document.querySelector('input[placeholder*="name" i]');
167 if (!input || input.value) return false;
168 input.focus(); return true;
169 })()`).catch(() => false);
170 if (focused) await this.browser.send('Input.insertText', { text: GUEST_NAME }, this.sessionId);
171 }
172 async shot(path) {
173 const { data } = await this.browser.send('Page.captureScreenshot', { format: 'png' }, this.sessionId);
174 writeFileSync(path, Buffer.from(data, 'base64'));
175 }
176 async close() {
177 if (this.targetId) await this.browser.send('Target.closeTarget', { targetId: this.targetId }).catch(() => {});
178 if (this.contextId) await this.browser.send('Target.disposeBrowserContext', { browserContextId: this.contextId }).catch(() => {});
179 }
180}
181
182async function sampleWeb(tab, seconds) {
183 const levels = [];
184 let previous = await tab.evaluate(INBOUND_AUDIO);
185 const end = Date.now() + seconds * 1000;
186 while (Date.now() < end) {
187 await delay(WINDOW_MS);
188 const current = await tab.evaluate(INBOUND_AUDIO);
189 const duration = current.duration - previous.duration;
190 levels.push(duration > 0 ? Math.sqrt(Math.max(0, current.energy - previous.energy) / duration) : 0);
191 previous = current;
192 }
193 return levels;
194}
195
196function judge(levels, threshold) {
197 const sorted = [...levels].sort((left, right) => left - right);
198 const percentile = (share) => sorted[Math.min(sorted.length - 1, Math.floor(share * sorted.length))] ?? 0;
199 const [p10, p90] = [percentile(0.1), percentile(0.9)];
200 const speech = p90 >= threshold.speech;
201 const pauses = p90 >= SPEECH_TO_PAUSE * Math.max(p10, threshold.floor);
202 return { pass: speech && pauses, p10, p90, windows: levels.length };
203}
204
205const report = { started: new Date().toISOString() };
206const savedCapture = defaultAudio('get', 'capture');
207const restoreCapture = () => defaultAudio('set', 'capture', savedCapture);
208for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { restoreCapture(); process.exit(130); });
209const browser = await new Browser(OWN_ENDPOINT).connect();
210const tab = new GuestTab(browser);
211try {
212 if (!teamsProcessId()) {
213 log(`starting the app, waiting ${APP_START_WAIT_MS / 1000}s`);
214 runTeams();
215 await delay(APP_START_WAIT_MS);
216 }
217 const link = givenLink ?? createMeeting();
218 report.link = link;
219 log('meeting ready');
220 defaultAudio('set', 'capture', 'CABLE Output');
221 log('default mic: CABLE Output');
222 const playSeconds = Math.ceil((APP_JOIN_WAIT_MS + WEB_JOIN_TIMEOUT_MS) / 1000) + MEASURE_SECONDS + 10;
223 const playing = runProbe('play', 'CABLE Input', windowsPath(PROBE_DIR + '/app.wav'), String(playSeconds));
224 runTeams('--join', link);
225 log(`app joining, waiting ${APP_JOIN_WAIT_MS / 1000}s`);
226 await delay(APP_JOIN_WAIT_MS);
227 await tab.open(link);
228 const admitting = setInterval(() => runTeams('--admit-all'), ADMIT_INTERVAL_MS);
229 report.webJoined = await tab.join().finally(() => clearInterval(admitting));
230 log(`web guest joined: ${report.webJoined}`);
231 if (!report.webJoined) {
232 await tab.shot(workDir + '/web-join.png');
233 throw new Error('Teams web guest did not join, see web-join.png');
234 }
235 await tab.activate();
236 const processId = teamsProcessId();
237 if (!processId) throw new Error('teams.exe is not running');
238 log(`measuring ${MEASURE_SECONDS}s (teams.exe pid ${processId})`);
239 const [recorded, webLevels] = await Promise.all([
240 runProbe('record-process', String(processId), String(MEASURE_SECONDS), windowsPath(workDir + '/app-heard.wav')),
241 sampleWeb(tab, MEASURE_SECONDS),
242 ]);
243 report.guestSending = await tab.evaluate(GUEST_SENDING).catch((error) => error.message);
244 report.appToWeb = judge(webLevels, WEB_THRESHOLD);
245 report.webToApp = judge(JSON.parse(recorded).rms, APP_THRESHOLD);
246 report.webLevels = webLevels.map((level) => Number(level.toFixed(4)));
247 report.appLevels = JSON.parse(recorded).rms;
248 await tab.shot(workDir + '/web-in-call.png');
249 await playing.catch((error) => (report.playError = error.message));
250} catch (error) {
251 report.error = error.message;
252} finally {
253 if (teamsProcessId()) runTeams('--hang-up');
254 await tab.close();
255 restoreCapture();
256 log('default mic restored');
257 browser.socket.close();
258}
259report.pass = Boolean(report.appToWeb?.pass && report.webToApp?.pass);
260writeFileSync(workDir + '/report.json', JSON.stringify(report, null, 2));
261console.log(JSON.stringify({ pass: report.pass, appToWeb: report.appToWeb, webToApp: report.webToApp, guestSending: report.guestSending, error: report.error }));
262process.exit(report.pass ? 0 : 1);