BlueGit

ict rusty-teams

Files

rusty-teams / scripts / call-e2e.mjs

call-e2e.mjs

call-e2e.mjs 9.8 KiB Download Raw
1// Call end-to-end test with Daniel's real account and the deployed Windows app, no second person needed.
2// Teams web (own Chrome, CDP 9222) joins a fresh Meet now with a looped speech file as its mic.
3// The Windows app joins through `teams.exe --join`; its mic is VB-CABLE fed with a second speech file,
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 { createServer } from 'node:http';
8import { readFileSync, writeFileSync } from 'node:fs';
9import { Browser, CLICK, FAKE_MEDIA, PEER_HOOK } 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 PORT = Number(process.env.E2E_PORT ?? 9475);
14const PROBE_DIR = process.env.PROBE_DIR ?? '/mnt/c/Users/dd/AppData/Local/Temp/call-e2e';
15const TEAMS_EXE = process.env.TEAMS_EXE ?? '/mnt/c/Users/dd/AppData/Local/Programs/ms-teams-linux/teams.exe';
16const POWERSHELL = '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe';
17const TASKLIST = '/mnt/c/Windows/System32/tasklist.exe';
18const SCRIPT_DIR = new URL('.', import.meta.url).pathname;
19const REPO_DIR = new URL('..', import.meta.url).pathname;
20const APP_START_WAIT_MS = 40_000;
21const WEB_JOIN_TIMEOUT_MS = 90_000;
22const APP_JOIN_WAIT_MS = 25_000;
23const MEASURE_SECONDS = 30;
24const WINDOW_MS = 250;
25const WEB_JOIN_STEPS = ['Continue on this browser', 'Join now'];
26const WEB_THRESHOLD = { speech: 0.005, floor: 0.0005 };
27const APP_THRESHOLD = { speech: 200, floor: 20 };
28const SPEECH_TO_PAUSE = 4;
29
30const windowsPath = (path) => execFileSync('wslpath', ['-w', path]).toString().trim();
31const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
32const log = (message) => console.error(`[${new Date().toISOString().slice(11, 19)}] ${message}`);
33
34function defaultAudio(...args) {
35 const script = windowsPath(SCRIPT_DIR + 'default-audio.ps1');
36 return execFileSync(POWERSHELL, ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script, ...args]).toString().trim();
37}
38
39function createMeeting() {
40 return execFileSync('cargo', ['run', '-q', '-p', 'calling', '--example', 'create_test_meeting'], { cwd: REPO_DIR, stdio: ['ignore', 'pipe', 'inherit'] })
41 .toString()
42 .trim();
43}
44
45function teamsProcessId() {
46 const rows = execFileSync(TASKLIST, ['/FI', 'IMAGENAME eq teams.exe', '/FO', 'CSV', '/NH']).toString().trim().split(/\r?\n/);
47 const processes = rows
48 .map((row) => row.split('","').map((cell) => cell.replace(/"/g, '')))
49 .filter((cells) => cells[0]?.toLowerCase() === 'teams.exe')
50 .map((cells) => ({ id: Number(cells[1]), memory: Number(cells[4].replace(/\D/g, '')) }));
51 processes.sort((left, right) => right.memory - left.memory);
52 return processes[0]?.id;
53}
54
55function runTeams(...args) {
56 spawn(TEAMS_EXE, args, { detached: true, stdio: 'ignore' }).unref();
57}
58
59function runProbe(...args) {
60 return new Promise((resolve, reject) => {
61 const child = spawn(PROBE_DIR + '/audio_probe.exe', args, { stdio: ['ignore', 'pipe', 'pipe'] });
62 let output = '';
63 let errors = '';
64 child.stdout.on('data', (chunk) => (output += chunk));
65 child.stderr.on('data', (chunk) => (errors += chunk));
66 child.on('exit', (code) => (code === 0 ? resolve(output) : reject(new Error(`audio_probe ${args[0]}: ${errors.trim()}`))));
67 });
68}
69
70function serveSpeech() {
71 const speech = readFileSync(PROBE_DIR + '/web.wav');
72 const server = createServer((_, response) => {
73 response.writeHead(200, { 'content-type': 'audio/wav', 'access-control-allow-origin': '*', 'access-control-allow-private-network': 'true' }).end(speech);
74 });
75 server.listen(PORT, '127.0.0.1');
76 return server;
77}
78
79const INBOUND_AUDIO = `(async () => {
80 let energy = 0, duration = 0, packets = 0;
81 for (const peer of window.__pcs || []) {
82 if (peer.connectionState === 'closed') continue;
83 (await peer.getStats()).forEach((entry) => {
84 if (entry.type !== 'inbound-rtp' || entry.kind !== 'audio') return;
85 energy += entry.totalAudioEnergy || 0; duration += entry.totalSamplesDuration || 0; packets += entry.packetsReceived || 0;
86 });
87 }
88 return { energy, duration, packets };
89})()`;
90
91class WebTab {
92 constructor(browser) { this.browser = browser; }
93 async open(link) {
94 const { targetId } = await this.browser.send('Target.createTarget', { url: 'about:blank' });
95 this.targetId = targetId;
96 const { sessionId } = await this.browser.send('Target.attachToTarget', { targetId, flatten: true });
97 this.sessionId = sessionId;
98 await this.browser.send('Page.enable', {}, sessionId);
99 await this.browser.send('Runtime.enable', {}, sessionId);
100 await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: PEER_HOOK }, sessionId);
101 await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: FAKE_MEDIA(`http://127.0.0.1:${PORT}/speech.wav`) }, sessionId);
102 await this.browser.send('Browser.grantPermissions', { permissions: ['audioCapture', 'videoCapture'], origin: 'https://teams.cloud.microsoft' }).catch(() => {});
103 await this.browser.send('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId).catch(() => {});
104 await this.browser.send('Page.navigate', { url: link }, sessionId);
105 }
106 async evaluate(expression) {
107 const result = await this.browser.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, this.sessionId);
108 if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description ?? 'evaluate failed');
109 return result.result.value;
110 }
111 async join() {
112 const deadline = Date.now() + WEB_JOIN_TIMEOUT_MS;
113 while (Date.now() < deadline) {
114 const audio = await this.evaluate(INBOUND_AUDIO).catch(() => null);
115 if (audio && audio.packets > 0) return true;
116 for (const step of WEB_JOIN_STEPS) {
117 const click = await this.evaluate(CLICK(step)).catch(() => null);
118 if (click?.clicked) log(`web: clicked "${step}"`);
119 }
120 await delay(2000);
121 }
122 return false;
123 }
124 async shot(path) {
125 const { data } = await this.browser.send('Page.captureScreenshot', { format: 'png' }, this.sessionId);
126 writeFileSync(path, Buffer.from(data, 'base64'));
127 }
128 async close() {
129 if (this.targetId) await this.browser.send('Target.closeTarget', { targetId: this.targetId }).catch(() => {});
130 }
131}
132
133async function sampleWeb(tab, seconds) {
134 const levels = [];
135 let previous = await tab.evaluate(INBOUND_AUDIO);
136 const end = Date.now() + seconds * 1000;
137 while (Date.now() < end) {
138 await delay(WINDOW_MS);
139 const current = await tab.evaluate(INBOUND_AUDIO);
140 const duration = current.duration - previous.duration;
141 levels.push(duration > 0 ? Math.sqrt(Math.max(0, current.energy - previous.energy) / duration) : 0);
142 previous = current;
143 }
144 return levels;
145}
146
147function judge(levels, threshold) {
148 const sorted = [...levels].sort((left, right) => left - right);
149 const percentile = (share) => sorted[Math.min(sorted.length - 1, Math.floor(share * sorted.length))] ?? 0;
150 const [p10, p90] = [percentile(0.1), percentile(0.9)];
151 const speech = p90 >= threshold.speech;
152 const pauses = p90 >= SPEECH_TO_PAUSE * Math.max(p10, threshold.floor);
153 return { pass: speech && pauses, p10, p90, windows: levels.length };
154}
155
156const report = { started: new Date().toISOString() };
157const savedCapture = defaultAudio('get', 'capture');
158const restoreCapture = () => defaultAudio('set', 'capture', savedCapture);
159for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { restoreCapture(); process.exit(130); });
160const server = serveSpeech();
161const browser = await new Browser(OWN_ENDPOINT).connect();
162const tab = new WebTab(browser);
163try {
164 if (!teamsProcessId()) {
165 log(`starting the app, waiting ${APP_START_WAIT_MS / 1000}s`);
166 runTeams();
167 await delay(APP_START_WAIT_MS);
168 }
169 const link = givenLink ?? createMeeting();
170 report.link = link;
171 log('meeting ready');
172 await tab.open(link);
173 report.webJoined = await tab.join();
174 log(`web joined: ${report.webJoined}`);
175 if (!report.webJoined) {
176 await tab.shot(workDir + '/web-join.png');
177 throw new Error('Teams web did not join, see web-join.png');
178 }
179 defaultAudio('set', 'capture', 'CABLE Output');
180 log('default mic: CABLE Output');
181 const playSeconds = Math.ceil(APP_JOIN_WAIT_MS / 1000) + MEASURE_SECONDS + 10;
182 const playing = runProbe('play', 'CABLE Input', windowsPath(PROBE_DIR + '/app.wav'), String(playSeconds));
183 runTeams('--join', link);
184 log(`app joining, waiting ${APP_JOIN_WAIT_MS / 1000}s`);
185 await delay(APP_JOIN_WAIT_MS);
186 const processId = teamsProcessId();
187 if (!processId) throw new Error('teams.exe is not running');
188 log(`measuring ${MEASURE_SECONDS}s (teams.exe pid ${processId})`);
189 const [recorded, webLevels] = await Promise.all([
190 runProbe('record-process', String(processId), String(MEASURE_SECONDS), windowsPath(workDir + '/app-heard.wav')),
191 sampleWeb(tab, MEASURE_SECONDS),
192 ]);
193 report.appToWeb = judge(webLevels, WEB_THRESHOLD);
194 report.webToApp = judge(JSON.parse(recorded).rms, APP_THRESHOLD);
195 report.webLevels = webLevels.map((level) => Number(level.toFixed(4)));
196 report.appLevels = JSON.parse(recorded).rms;
197 await tab.shot(workDir + '/web-in-call.png');
198 await playing.catch((error) => (report.playError = error.message));
199} catch (error) {
200 report.error = error.message;
201} finally {
202 if (teamsProcessId()) runTeams('--hang-up');
203 await tab.close();
204 restoreCapture();
205 log('default mic restored');
206 server.close();
207 browser.socket.close();
208}
209report.pass = Boolean(report.appToWeb?.pass && report.webToApp?.pass);
210writeFileSync(workDir + '/report.json', JSON.stringify(report, null, 2));
211console.log(JSON.stringify({ pass: report.pass, appToWeb: report.appToWeb, webToApp: report.webToApp, error: report.error }));
212process.exit(report.pass ? 0 : 1);