BlueGit

ict rusty-teams

Files

rusty-teams / scripts / call-e2e.mjs

call-e2e.mjs

call-e2e.mjs 13.1 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 as Daniel hosts a fresh Meet now and admits an anonymous Teams web guest whose mic is a looped speech file.
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', 'Not now', 'Join now'];
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
72function silentWav(seconds) {
73 const dataBytes = seconds * 48000 * 2;
74 const header = Buffer.alloc(44);
75 header.write('RIFF', 0); header.writeUInt32LE(36 + dataBytes, 4); header.write('WAVEfmt ', 8);
76 header.writeUInt32LE(16, 16); header.writeUInt16LE(1, 20); header.writeUInt16LE(1, 22); header.writeUInt32LE(48000, 24);
77 header.writeUInt32LE(96000, 28); header.writeUInt16LE(2, 32); header.writeUInt16LE(16, 34); header.write('data', 36); header.writeUInt32LE(dataBytes, 40);
78 return Buffer.concat([header, Buffer.alloc(dataBytes)]);
79}
80
81function serveSpeech() {
82 const files = { '/speech.wav': readFileSync(PROBE_DIR + '/web.wav'), '/silence.wav': silentWav(1) };
83 const server = createServer((request, response) => {
84 response.writeHead(200, { 'content-type': 'audio/wav', 'access-control-allow-origin': '*', 'access-control-allow-private-network': 'true' }).end(files[request.url] ?? files['/silence.wav']);
85 });
86 server.listen(PORT, '127.0.0.1');
87 return server;
88}
89
90const INBOUND_AUDIO = `(async () => {
91 let energy = 0, duration = 0, packets = 0;
92 for (const peer of window.__pcs || []) {
93 if (peer.connectionState === 'closed') continue;
94 (await peer.getStats()).forEach((entry) => {
95 if (entry.type !== 'inbound-rtp' || entry.kind !== 'audio') return;
96 energy += entry.totalAudioEnergy || 0; duration += entry.totalSamplesDuration || 0; packets += entry.packetsReceived || 0;
97 });
98 }
99 return { energy, duration, packets };
100})()`;
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 CONNECTED = `(window.__pcs || []).some((peer) => peer.connectionState === 'connected')`;
114const TEAMS_ORIGINS = ['https://teams.cloud.microsoft', 'https://teams.microsoft.com'];
115
116class WebTab {
117 constructor(browser, { guest }) { this.browser = browser; this.guest = guest; }
118 async open(link) {
119 if (this.guest) this.contextId = (await this.browser.send('Target.createBrowserContext', { disposeOnDetach: false })).browserContextId;
120 const context = this.contextId ? { browserContextId: this.contextId } : {};
121 const { targetId } = await this.browser.send('Target.createTarget', { url: 'about:blank', ...context });
122 this.targetId = targetId;
123 const { sessionId } = await this.browser.send('Target.attachToTarget', { targetId, flatten: true });
124 this.sessionId = sessionId;
125 await this.browser.send('Page.enable', {}, sessionId);
126 await this.browser.send('Runtime.enable', {}, sessionId);
127 await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: PEER_HOOK }, sessionId);
128 await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: FAKE_MEDIA(`http://127.0.0.1:${PORT}/${this.guest ? 'speech' : 'silence'}.wav`) }, sessionId);
129 for (const origin of TEAMS_ORIGINS) {
130 await this.browser.send('Browser.grantPermissions', { permissions: ['audioCapture', 'videoCapture'], origin, ...context }).catch(() => {});
131 }
132 await this.browser.send('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId).catch(() => {});
133 await this.browser.send('Page.navigate', { url: link }, sessionId);
134 }
135 async evaluate(expression) {
136 const result = await this.browser.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, this.sessionId);
137 if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description ?? 'evaluate failed');
138 return result.result.value;
139 }
140 async join() {
141 const deadline = Date.now() + WEB_JOIN_TIMEOUT_MS;
142 while (Date.now() < deadline) {
143 const inLobby = await this.evaluate(`${JSON.stringify(LOBBY_TEXTS)}.some((text) => document.body.innerText.includes(text))`).catch(() => false);
144 if (!inLobby && (await this.evaluate(CONNECTED).catch(() => false))) return true;
145 if (this.guest) await this.typeName();
146 for (const step of WEB_JOIN_STEPS) {
147 const click = await this.evaluate(CLICK(step)).catch(() => null);
148 if (click?.clicked) log(`web: clicked "${step}"`);
149 }
150 await delay(2000);
151 }
152 return false;
153 }
154 async typeName() {
155 const focused = await this.evaluate(`(() => {
156 const input = document.querySelector('input[placeholder*="name" i]');
157 if (!input || input.value) return false;
158 input.focus(); return true;
159 })()`).catch(() => false);
160 if (focused) await this.browser.send('Input.insertText', { text: GUEST_NAME }, this.sessionId);
161 }
162 async admitGuests() {
163 const click = await this.evaluate(CLICK('Admit')).catch(() => null);
164 if (click?.clicked) log(`web: clicked "${click.label}"`);
165 else if (!this.peopleOpen) this.peopleOpen = (await this.evaluate(CLICK('People')).catch(() => null))?.clicked;
166 }
167 async shot(path) {
168 const { data } = await this.browser.send('Page.captureScreenshot', { format: 'png' }, this.sessionId);
169 writeFileSync(path, Buffer.from(data, 'base64'));
170 }
171 async close() {
172 if (this.targetId) await this.browser.send('Target.closeTarget', { targetId: this.targetId }).catch(() => {});
173 if (this.contextId) await this.browser.send('Target.disposeBrowserContext', { browserContextId: this.contextId }).catch(() => {});
174 }
175}
176
177async function sampleWeb(tab, seconds) {
178 const levels = [];
179 let previous = await tab.evaluate(INBOUND_AUDIO);
180 const end = Date.now() + seconds * 1000;
181 while (Date.now() < end) {
182 await delay(WINDOW_MS);
183 const current = await tab.evaluate(INBOUND_AUDIO);
184 const duration = current.duration - previous.duration;
185 levels.push(duration > 0 ? Math.sqrt(Math.max(0, current.energy - previous.energy) / duration) : 0);
186 previous = current;
187 }
188 return levels;
189}
190
191function judge(levels, threshold) {
192 const sorted = [...levels].sort((left, right) => left - right);
193 const percentile = (share) => sorted[Math.min(sorted.length - 1, Math.floor(share * sorted.length))] ?? 0;
194 const [p10, p90] = [percentile(0.1), percentile(0.9)];
195 const speech = p90 >= threshold.speech;
196 const pauses = p90 >= SPEECH_TO_PAUSE * Math.max(p10, threshold.floor);
197 return { pass: speech && pauses, p10, p90, windows: levels.length };
198}
199
200const report = { started: new Date().toISOString() };
201const savedCapture = defaultAudio('get', 'capture');
202const restoreCapture = () => defaultAudio('set', 'capture', savedCapture);
203for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { restoreCapture(); process.exit(130); });
204const server = serveSpeech();
205const browser = await new Browser(OWN_ENDPOINT).connect();
206const host = new WebTab(browser, { guest: false });
207const tab = new WebTab(browser, { guest: true });
208try {
209 if (!teamsProcessId()) {
210 log(`starting the app, waiting ${APP_START_WAIT_MS / 1000}s`);
211 runTeams();
212 await delay(APP_START_WAIT_MS);
213 }
214 const link = givenLink ?? createMeeting();
215 report.link = link;
216 log('meeting ready');
217 await host.open(link);
218 if (!(await host.join())) {
219 await host.shot(workDir + '/host-join.png');
220 throw new Error('Teams web host did not join, see host-join.png');
221 }
222 log('web host joined');
223 await tab.open(link);
224 const admitting = setInterval(() => host.admitGuests(), 2000);
225 report.webJoined = await tab.join().finally(() => clearInterval(admitting));
226 log(`web guest joined: ${report.webJoined}`);
227 if (!report.webJoined) {
228 await tab.shot(workDir + '/web-join.png');
229 await host.shot(workDir + '/host-admit.png');
230 throw new Error('Teams web guest did not join, see web-join.png and host-admit.png');
231 }
232 defaultAudio('set', 'capture', 'CABLE Output');
233 log('default mic: CABLE Output');
234 const playSeconds = Math.ceil(APP_JOIN_WAIT_MS / 1000) + MEASURE_SECONDS + 10;
235 const playing = runProbe('play', 'CABLE Input', windowsPath(PROBE_DIR + '/app.wav'), String(playSeconds));
236 runTeams('--join', link);
237 log(`app joining, waiting ${APP_JOIN_WAIT_MS / 1000}s`);
238 await delay(APP_JOIN_WAIT_MS);
239 const processId = teamsProcessId();
240 if (!processId) throw new Error('teams.exe is not running');
241 log(`measuring ${MEASURE_SECONDS}s (teams.exe pid ${processId})`);
242 const [recorded, webLevels] = await Promise.all([
243 runProbe('record-process', String(processId), String(MEASURE_SECONDS), windowsPath(workDir + '/app-heard.wav')),
244 sampleWeb(tab, MEASURE_SECONDS),
245 ]);
246 report.guestSending = await tab.evaluate(GUEST_SENDING).catch((error) => error.message);
247 report.appToWeb = judge(webLevels, WEB_THRESHOLD);
248 report.webToApp = judge(JSON.parse(recorded).rms, APP_THRESHOLD);
249 report.webLevels = webLevels.map((level) => Number(level.toFixed(4)));
250 report.appLevels = JSON.parse(recorded).rms;
251 await tab.shot(workDir + '/web-in-call.png');
252 await playing.catch((error) => (report.playError = error.message));
253} catch (error) {
254 report.error = error.message;
255} finally {
256 if (teamsProcessId()) runTeams('--hang-up');
257 await tab.close();
258 await host.close();
259 restoreCapture();
260 log('default mic restored');
261 server.close();
262 browser.socket.close();
263}
264report.pass = Boolean(report.appToWeb?.pass && report.webToApp?.pass);
265writeFileSync(workDir + '/report.json', JSON.stringify(report, null, 2));
266console.log(JSON.stringify({ pass: report.pass, appToWeb: report.appToWeb, webToApp: report.webToApp, guestSending: report.guestSending, error: report.error }));
267process.exit(report.pass ? 0 : 1);