BlueGit

ict rusty-teams

fix(calling): use the default mic when the saved one is not connected

- a saved but unplugged microphone made WASAPI activation fail, the call then sent silence
- now the default communications microphone takes over
- call e2e: anonymous guest as the measuring peer, host admits it, guest send level in the report
- create_test_meeting uses chatsvc::Calendar::create_meet_now for the join link

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-11-08 · 3 weeks ago

Hash
37f8a060a9a2f694bb31c1594d908b829957af38
Parent
a38cddb6
5 files changed +104 −64
crates/calling/examples/create_test_meeting.rs deleted +0 −41
@@ -1,41 +0,0 @@
1 //! Creates a "Native client test" Meet now meeting and prints its join link (call end-to-end test).
2 use serde_json::{Value, json};
3 use session::{DEFAULT_ENDPOINT, Method, SPACES, Scope, Session};
4
5 const CREATE_URL: &str =
6 "https://teams.cloud.microsoft/api/mt/emea/beta/me/calendarEvents/privateMeeting/schedulingService/create";
7 const SUBJECT: &str = "Native client test";
8 const LINK_KEYS: [&str; 4] = ["meetingUrl", "joinUrl", "meetingJoinUrl", "joinWebUrl"];
9
10 fn find_text<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a str> {
11 match value {
12 Value::Object(map) => map.iter().find_map(|(key, inner)| {
13 let direct = keys
14 .iter()
15 .any(|wanted| key.eq_ignore_ascii_case(wanted))
16 .then(|| inner.as_str().filter(|text| !text.is_empty()))
17 .flatten();
18 direct.or_else(|| find_text(inner, keys))
19 }),
20 Value::Array(items) => items.iter().find_map(|item| find_text(item, keys)),
21 _ => None,
22 }
23 }
24
25 #[tokio::main]
26 async fn main() {
27 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
28 let session = Session::connect(&endpoint).await.expect("browser");
29 let body = json!({"meetingType": "MeetNow", "isStreamEnabled": false, "subject": SUBJECT, "unhideChatThread": true});
30 let created = session
31 .request(Method::Post, CREATE_URL, &Scope::new(SPACES, "user_impersonation"), Some(body))
32 .await
33 .expect("create meeting");
34 match find_text(&created.body, &LINK_KEYS) {
35 Some(link) => println!("{link}"),
36 None => {
37 eprintln!("HTTP {} without a join link: {:#}", created.status, created.body);
38 std::process::exit(1);
39 }
40 }
41 }
@@ -1,41 +0,0 @@
1//! Creates a "Native client test" Meet now meeting and prints its join link (call end-to-end test).
2use serde_json::{Value, json};
3use session::{DEFAULT_ENDPOINT, Method, SPACES, Scope, Session};
4
5const CREATE_URL: &str =
6 "https://teams.cloud.microsoft/api/mt/emea/beta/me/calendarEvents/privateMeeting/schedulingService/create";
7const SUBJECT: &str = "Native client test";
8const LINK_KEYS: [&str; 4] = ["meetingUrl", "joinUrl", "meetingJoinUrl", "joinWebUrl"];
9
10fn find_text<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a str> {
11 match value {
12 Value::Object(map) => map.iter().find_map(|(key, inner)| {
13 let direct = keys
14 .iter()
15 .any(|wanted| key.eq_ignore_ascii_case(wanted))
16 .then(|| inner.as_str().filter(|text| !text.is_empty()))
17 .flatten();
18 direct.or_else(|| find_text(inner, keys))
19 }),
20 Value::Array(items) => items.iter().find_map(|item| find_text(item, keys)),
21 _ => None,
22 }
23}
24
25#[tokio::main]
26async fn main() {
27 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
28 let session = Session::connect(&endpoint).await.expect("browser");
29 let body = json!({"meetingType": "MeetNow", "isStreamEnabled": false, "subject": SUBJECT, "unhideChatThread": true});
30 let created = session
31 .request(Method::Post, CREATE_URL, &Scope::new(SPACES, "user_impersonation"), Some(body))
32 .await
33 .expect("create meeting");
34 match find_text(&created.body, &LINK_KEYS) {
35 Some(link) => println!("{link}"),
36 None => {
37 eprintln!("HTTP {} without a join link: {:#}", created.status, created.body);
38 std::process::exit(1);
39 }
40 }
41}
crates/calling/src/mic_windows.rs +11 −6
@@ -7,7 +7,7 @@ use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_OBJECT_0};
7 7 use windows::Win32::Media::Audio::{
8 8 AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
9 9 AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, AUDCLNT_STREAMOPTIONS_NONE, AudioCategory_Communications, AudioClientProperties,
10 AUDIO_EFFECT, AUDIO_EFFECT_STATE_OFF, AUDIO_EFFECT_STATE_ON, IAudioCaptureClient, IAudioClient, IAudioClient2,
10 AUDIO_EFFECT, AUDIO_EFFECT_STATE_OFF, AUDIO_EFFECT_STATE_ON, DEVICE_STATE_ACTIVE, IAudioCaptureClient, IAudioClient, IAudioClient2,
11 11 IAudioEffectsManager, IMMDevice, IMMDeviceEnumerator, MMDeviceEnumerator, WAVEFORMATEX, eCapture, eCommunications,
12 12 };
13 13 use windows::Win32::System::Com::StructuredStorage::{PROPVARIANT, PropVariantClear};
@@ -36,13 +36,18 @@ fn open_device(choice: &DeviceChoice) -> Result<IMMDevice> {
36 36 unsafe {
37 37 let enumerator: IMMDeviceEnumerator =
38 38 CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(|error| audio_error("device enumerator", error))?;
39 match choice {
40 DeviceChoice::SystemDefault => enumerator
41 .GetDefaultAudioEndpoint(eCapture, eCommunications)
42 .map_err(|error| audio_error("default communications microphone", error)),
39 let chosen = match choice {
40 DeviceChoice::SystemDefault => None,
43 41 DeviceChoice::Device(key) => enumerator
44 42 .GetDevice(&HSTRING::from(key.as_str()))
45 .map_err(|error| audio_error("microphone endpoint", error)),
43 .ok()
44 .filter(|device| device.GetState().is_ok_and(|state| state == DEVICE_STATE_ACTIVE)),
45 };
46 match chosen {
47 Some(device) => Ok(device),
48 None => enumerator
49 .GetDefaultAudioEndpoint(eCapture, eCommunications)
50 .map_err(|error| audio_error("default communications microphone", error)),
46 51 }
47 52 }
48 53 }
@@ -7,7 +7,7 @@ use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_OBJECT_0};
7use windows::Win32::Media::Audio::{
7use windows::Win32::Media::Audio::{
8 AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
8 AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
9 AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, AUDCLNT_STREAMOPTIONS_NONE, AudioCategory_Communications, AudioClientProperties,
9 AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, AUDCLNT_STREAMOPTIONS_NONE, AudioCategory_Communications, AudioClientProperties,
10 AUDIO_EFFECT, AUDIO_EFFECT_STATE_OFF, AUDIO_EFFECT_STATE_ON, IAudioCaptureClient, IAudioClient, IAudioClient2,
10 AUDIO_EFFECT, AUDIO_EFFECT_STATE_OFF, AUDIO_EFFECT_STATE_ON, DEVICE_STATE_ACTIVE, IAudioCaptureClient, IAudioClient, IAudioClient2,
11 IAudioEffectsManager, IMMDevice, IMMDeviceEnumerator, MMDeviceEnumerator, WAVEFORMATEX, eCapture, eCommunications,
11 IAudioEffectsManager, IMMDevice, IMMDeviceEnumerator, MMDeviceEnumerator, WAVEFORMATEX, eCapture, eCommunications,
12};
12};
13use windows::Win32::System::Com::StructuredStorage::{PROPVARIANT, PropVariantClear};
13use windows::Win32::System::Com::StructuredStorage::{PROPVARIANT, PropVariantClear};
@@ -36,13 +36,18 @@ fn open_device(choice: &DeviceChoice) -> Result<IMMDevice> {
36 unsafe {
36 unsafe {
37 let enumerator: IMMDeviceEnumerator =
37 let enumerator: IMMDeviceEnumerator =
38 CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(|error| audio_error("device enumerator", error))?;
38 CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(|error| audio_error("device enumerator", error))?;
39 match choice {
39 let chosen = match choice {
40 DeviceChoice::SystemDefault => enumerator
40 DeviceChoice::SystemDefault => None,
41 .GetDefaultAudioEndpoint(eCapture, eCommunications)
42 .map_err(|error| audio_error("default communications microphone", error)),
43 DeviceChoice::Device(key) => enumerator
41 DeviceChoice::Device(key) => enumerator
44 .GetDevice(&HSTRING::from(key.as_str()))
42 .GetDevice(&HSTRING::from(key.as_str()))
45 .map_err(|error| audio_error("microphone endpoint", error)),
43 .ok()
44 .filter(|device| device.GetState().is_ok_and(|state| state == DEVICE_STATE_ACTIVE)),
45 };
46 match chosen {
47 Some(device) => Ok(device),
48 None => enumerator
49 .GetDefaultAudioEndpoint(eCapture, eCommunications)
50 .map_err(|error| audio_error("default communications microphone", error)),
46 }
51 }
47 }
52 }
48}
53}
crates/chatsvc/examples/create_test_meeting.rs added +17 −0
@@ -0,0 +1,17 @@
1 //! Creates a "Native client test" Meet now meeting and prints its join link (call end-to-end test).
2 use session::{DEFAULT_ENDPOINT, Session};
3
4 const SUBJECT: &str = "Native client test";
5
6 #[tokio::main]
7 async fn main() {
8 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
9 let session = Session::connect(&endpoint).await.expect("browser");
10 match chatsvc::Calendar::new(&session).create_meet_now(SUBJECT).await {
11 Ok(link) => println!("{link}"),
12 Err(error) => {
13 eprintln!("{error}");
14 std::process::exit(1);
15 }
16 }
17 }
@@ -0,0 +1,17 @@
1//! Creates a "Native client test" Meet now meeting and prints its join link (call end-to-end test).
2use session::{DEFAULT_ENDPOINT, Session};
3
4const SUBJECT: &str = "Native client test";
5
6#[tokio::main]
7async fn main() {
8 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
9 let session = Session::connect(&endpoint).await.expect("browser");
10 match chatsvc::Calendar::new(&session).create_meet_now(SUBJECT).await {
11 Ok(link) => println!("{link}"),
12 Err(error) => {
13 eprintln!("{error}");
14 std::process::exit(1);
15 }
16 }
17}
scripts/call-e2e.mjs +72 −17
@@ -1,5 +1,5 @@
1 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.
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 3 // The Windows app joins through `teams.exe --join`; its mic is VB-CABLE fed with a second speech file,
4 4 // and process loopback records what the app plays. Both directions must show speech with pauses.
5 5 // Usage: node scripts/call-e2e.mjs <work dir> [meeting link]
@@ -22,7 +22,9 @@ const WEB_JOIN_TIMEOUT_MS = 90_000;
22 22 const APP_JOIN_WAIT_MS = 25_000;
23 23 const MEASURE_SECONDS = 30;
24 24 const WINDOW_MS = 250;
25 const WEB_JOIN_STEPS = ['Continue on this browser', 'Join now'];
25 const WEB_JOIN_STEPS = ['Continue on this browser', 'Not now', 'Join now'];
26 const GUEST_NAME = 'Call e2e guest';
27 const LOBBY_TEXTS = ['let you in shortly', 'should let you in soon'];
26 28 const WEB_THRESHOLD = { speech: 0.005, floor: 0.0005 };
27 29 const APP_THRESHOLD = { speech: 200, floor: 20 };
28 30 const SPEECH_TO_PAUSE = 4;
@@ -37,7 +39,7 @@ function defaultAudio(...args) {
37 39 }
38 40
39 41 function createMeeting() {
40 return execFileSync('cargo', ['run', '-q', '-p', 'calling', '--example', 'create_test_meeting'], { cwd: REPO_DIR, stdio: ['ignore', 'pipe', 'inherit'] })
42 return execFileSync('cargo', ['run', '-q', '-p', 'chatsvc', '--example', 'create_test_meeting'], { cwd: REPO_DIR, stdio: ['ignore', 'pipe', 'inherit'] })
41 43 .toString()
42 44 .trim();
43 45 }
@@ -67,10 +69,19 @@ function runProbe(...args) {
67 69 });
68 70 }
69 71
72 function 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
70 81 function 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);
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']);
74 85 });
75 86 server.listen(PORT, '127.0.0.1');
76 87 return server;
@@ -88,18 +99,36 @@ const INBOUND_AUDIO = `(async () => {
88 99 return { energy, duration, packets };
89 100 })()`;
90 101
102 const 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 })()`;
113 const CONNECTED = `(window.__pcs || []).some((peer) => peer.connectionState === 'connected')`;
114 const TEAMS_ORIGINS = ['https://teams.cloud.microsoft', 'https://teams.microsoft.com'];
115
91 116 class WebTab {
92 constructor(browser) { this.browser = browser; }
117 constructor(browser, { guest }) { this.browser = browser; this.guest = guest; }
93 118 async open(link) {
94 const { targetId } = await this.browser.send('Target.createTarget', { url: 'about:blank' });
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 });
95 122 this.targetId = targetId;
96 123 const { sessionId } = await this.browser.send('Target.attachToTarget', { targetId, flatten: true });
97 124 this.sessionId = sessionId;
98 125 await this.browser.send('Page.enable', {}, sessionId);
99 126 await this.browser.send('Runtime.enable', {}, sessionId);
100 127 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(() => {});
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 }
103 132 await this.browser.send('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId).catch(() => {});
104 133 await this.browser.send('Page.navigate', { url: link }, sessionId);
105 134 }
@@ -111,8 +140,9 @@ class WebTab {
111 140 async join() {
112 141 const deadline = Date.now() + WEB_JOIN_TIMEOUT_MS;
113 142 while (Date.now() < deadline) {
114 const audio = await this.evaluate(INBOUND_AUDIO).catch(() => null);
115 if (audio && audio.packets > 0) return true;
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();
116 146 for (const step of WEB_JOIN_STEPS) {
117 147 const click = await this.evaluate(CLICK(step)).catch(() => null);
118 148 if (click?.clicked) log(`web: clicked "${step}"`);
@@ -121,12 +151,26 @@ class WebTab {
121 151 }
122 152 return false;
123 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 }
124 167 async shot(path) {
125 168 const { data } = await this.browser.send('Page.captureScreenshot', { format: 'png' }, this.sessionId);
126 169 writeFileSync(path, Buffer.from(data, 'base64'));
127 170 }
128 171 async close() {
129 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(() => {});
130 174 }
131 175 }
132 176
@@ -159,7 +203,8 @@ const restoreCapture = () => defaultAudio('set', 'capture', savedCapture);
159 203 for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { restoreCapture(); process.exit(130); });
160 204 const server = serveSpeech();
161 205 const browser = await new Browser(OWN_ENDPOINT).connect();
162 const tab = new WebTab(browser);
206 const host = new WebTab(browser, { guest: false });
207 const tab = new WebTab(browser, { guest: true });
163 208 try {
164 209 if (!teamsProcessId()) {
165 210 log(`starting the app, waiting ${APP_START_WAIT_MS / 1000}s`);
@@ -169,12 +214,20 @@ try {
169 214 const link = givenLink ?? createMeeting();
170 215 report.link = link;
171 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');
172 223 await tab.open(link);
173 report.webJoined = await tab.join();
174 log(`web joined: ${report.webJoined}`);
224 const admitting = setInterval(() => host.admitGuests(), 2000);
225 report.webJoined = await tab.join().finally(() => clearInterval(admitting));
226 log(`web guest joined: ${report.webJoined}`);
175 227 if (!report.webJoined) {
176 228 await tab.shot(workDir + '/web-join.png');
177 throw new Error('Teams web did not join, see 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');
178 231 }
179 232 defaultAudio('set', 'capture', 'CABLE Output');
180 233 log('default mic: CABLE Output');
@@ -190,6 +243,7 @@ try {
190 243 runProbe('record-process', String(processId), String(MEASURE_SECONDS), windowsPath(workDir + '/app-heard.wav')),
191 244 sampleWeb(tab, MEASURE_SECONDS),
192 245 ]);
246 report.guestSending = await tab.evaluate(GUEST_SENDING).catch((error) => error.message);
193 247 report.appToWeb = judge(webLevels, WEB_THRESHOLD);
194 248 report.webToApp = judge(JSON.parse(recorded).rms, APP_THRESHOLD);
195 249 report.webLevels = webLevels.map((level) => Number(level.toFixed(4)));
@@ -201,6 +255,7 @@ try {
201 255 } finally {
202 256 if (teamsProcessId()) runTeams('--hang-up');
203 257 await tab.close();
258 await host.close();
204 259 restoreCapture();
205 260 log('default mic restored');
206 261 server.close();
@@ -208,5 +263,5 @@ try {
208 263 }
209 264 report.pass = Boolean(report.appToWeb?.pass && report.webToApp?.pass);
210 265 writeFileSync(workDir + '/report.json', JSON.stringify(report, null, 2));
211 console.log(JSON.stringify({ pass: report.pass, appToWeb: report.appToWeb, webToApp: report.webToApp, error: report.error }));
266 console.log(JSON.stringify({ pass: report.pass, appToWeb: report.appToWeb, webToApp: report.webToApp, guestSending: report.guestSending, error: report.error }));
212 267 process.exit(report.pass ? 0 : 1);
@@ -1,5 +1,5 @@
1// Call end-to-end test with Daniel's real account and the deployed Windows app, no second person needed.
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.
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,
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.
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]
5// Usage: node scripts/call-e2e.mjs <work dir> [meeting link]
@@ -22,7 +22,9 @@ const WEB_JOIN_TIMEOUT_MS = 90_000;
22const APP_JOIN_WAIT_MS = 25_000;
22const APP_JOIN_WAIT_MS = 25_000;
23const MEASURE_SECONDS = 30;
23const MEASURE_SECONDS = 30;
24const WINDOW_MS = 250;
24const WINDOW_MS = 250;
25const WEB_JOIN_STEPS = ['Continue on this browser', 'Join now'];
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'];
26const WEB_THRESHOLD = { speech: 0.005, floor: 0.0005 };
28const WEB_THRESHOLD = { speech: 0.005, floor: 0.0005 };
27const APP_THRESHOLD = { speech: 200, floor: 20 };
29const APP_THRESHOLD = { speech: 200, floor: 20 };
28const SPEECH_TO_PAUSE = 4;
30const SPEECH_TO_PAUSE = 4;
@@ -37,7 +39,7 @@ function defaultAudio(...args) {
37}
39}
38
40
39function createMeeting() {
41function createMeeting() {
40 return execFileSync('cargo', ['run', '-q', '-p', 'calling', '--example', 'create_test_meeting'], { cwd: REPO_DIR, stdio: ['ignore', 'pipe', 'inherit'] })
42 return execFileSync('cargo', ['run', '-q', '-p', 'chatsvc', '--example', 'create_test_meeting'], { cwd: REPO_DIR, stdio: ['ignore', 'pipe', 'inherit'] })
41 .toString()
43 .toString()
42 .trim();
44 .trim();
43}
45}
@@ -67,10 +69,19 @@ function runProbe(...args) {
67 });
69 });
68}
70}
69
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
70function serveSpeech() {
81function serveSpeech() {
71 const speech = readFileSync(PROBE_DIR + '/web.wav');
82 const files = { '/speech.wav': readFileSync(PROBE_DIR + '/web.wav'), '/silence.wav': silentWav(1) };
72 const server = createServer((_, response) => {
83 const server = createServer((request, response) => {
73 response.writeHead(200, { 'content-type': 'audio/wav', 'access-control-allow-origin': '*', 'access-control-allow-private-network': 'true' }).end(speech);
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']);
74 });
85 });
75 server.listen(PORT, '127.0.0.1');
86 server.listen(PORT, '127.0.0.1');
76 return server;
87 return server;
@@ -88,18 +99,36 @@ const INBOUND_AUDIO = `(async () => {
88 return { energy, duration, packets };
99 return { energy, duration, packets };
89})()`;
100})()`;
90
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
91class WebTab {
116class WebTab {
92 constructor(browser) { this.browser = browser; }
117 constructor(browser, { guest }) { this.browser = browser; this.guest = guest; }
93 async open(link) {
118 async open(link) {
94 const { targetId } = await this.browser.send('Target.createTarget', { url: 'about:blank' });
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 });
95 this.targetId = targetId;
122 this.targetId = targetId;
96 const { sessionId } = await this.browser.send('Target.attachToTarget', { targetId, flatten: true });
123 const { sessionId } = await this.browser.send('Target.attachToTarget', { targetId, flatten: true });
97 this.sessionId = sessionId;
124 this.sessionId = sessionId;
98 await this.browser.send('Page.enable', {}, sessionId);
125 await this.browser.send('Page.enable', {}, sessionId);
99 await this.browser.send('Runtime.enable', {}, sessionId);
126 await this.browser.send('Runtime.enable', {}, sessionId);
100 await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: PEER_HOOK }, sessionId);
127 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);
128 await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: FAKE_MEDIA(`http://127.0.0.1:${PORT}/${this.guest ? 'speech' : 'silence'}.wav`) }, sessionId);
102 await this.browser.send('Browser.grantPermissions', { permissions: ['audioCapture', 'videoCapture'], origin: 'https://teams.cloud.microsoft' }).catch(() => {});
129 for (const origin of TEAMS_ORIGINS) {
130 await this.browser.send('Browser.grantPermissions', { permissions: ['audioCapture', 'videoCapture'], origin, ...context }).catch(() => {});
131 }
103 await this.browser.send('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId).catch(() => {});
132 await this.browser.send('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId).catch(() => {});
104 await this.browser.send('Page.navigate', { url: link }, sessionId);
133 await this.browser.send('Page.navigate', { url: link }, sessionId);
105 }
134 }
@@ -111,8 +140,9 @@ class WebTab {
111 async join() {
140 async join() {
112 const deadline = Date.now() + WEB_JOIN_TIMEOUT_MS;
141 const deadline = Date.now() + WEB_JOIN_TIMEOUT_MS;
113 while (Date.now() < deadline) {
142 while (Date.now() < deadline) {
114 const audio = await this.evaluate(INBOUND_AUDIO).catch(() => null);
143 const inLobby = await this.evaluate(`${JSON.stringify(LOBBY_TEXTS)}.some((text) => document.body.innerText.includes(text))`).catch(() => false);
115 if (audio && audio.packets > 0) return true;
144 if (!inLobby && (await this.evaluate(CONNECTED).catch(() => false))) return true;
145 if (this.guest) await this.typeName();
116 for (const step of WEB_JOIN_STEPS) {
146 for (const step of WEB_JOIN_STEPS) {
117 const click = await this.evaluate(CLICK(step)).catch(() => null);
147 const click = await this.evaluate(CLICK(step)).catch(() => null);
118 if (click?.clicked) log(`web: clicked "${step}"`);
148 if (click?.clicked) log(`web: clicked "${step}"`);
@@ -121,12 +151,26 @@ class WebTab {
121 }
151 }
122 return false;
152 return false;
123 }
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 }
124 async shot(path) {
167 async shot(path) {
125 const { data } = await this.browser.send('Page.captureScreenshot', { format: 'png' }, this.sessionId);
168 const { data } = await this.browser.send('Page.captureScreenshot', { format: 'png' }, this.sessionId);
126 writeFileSync(path, Buffer.from(data, 'base64'));
169 writeFileSync(path, Buffer.from(data, 'base64'));
127 }
170 }
128 async close() {
171 async close() {
129 if (this.targetId) await this.browser.send('Target.closeTarget', { targetId: this.targetId }).catch(() => {});
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(() => {});
130 }
174 }
131}
175}
132
176
@@ -159,7 +203,8 @@ const restoreCapture = () => defaultAudio('set', 'capture', savedCapture);
159for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { restoreCapture(); process.exit(130); });
203for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { restoreCapture(); process.exit(130); });
160const server = serveSpeech();
204const server = serveSpeech();
161const browser = await new Browser(OWN_ENDPOINT).connect();
205const browser = await new Browser(OWN_ENDPOINT).connect();
162const tab = new WebTab(browser);
206const host = new WebTab(browser, { guest: false });
207const tab = new WebTab(browser, { guest: true });
163try {
208try {
164 if (!teamsProcessId()) {
209 if (!teamsProcessId()) {
165 log(`starting the app, waiting ${APP_START_WAIT_MS / 1000}s`);
210 log(`starting the app, waiting ${APP_START_WAIT_MS / 1000}s`);
@@ -169,12 +214,20 @@ try {
169 const link = givenLink ?? createMeeting();
214 const link = givenLink ?? createMeeting();
170 report.link = link;
215 report.link = link;
171 log('meeting ready');
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');
172 await tab.open(link);
223 await tab.open(link);
173 report.webJoined = await tab.join();
224 const admitting = setInterval(() => host.admitGuests(), 2000);
174 log(`web joined: ${report.webJoined}`);
225 report.webJoined = await tab.join().finally(() => clearInterval(admitting));
226 log(`web guest joined: ${report.webJoined}`);
175 if (!report.webJoined) {
227 if (!report.webJoined) {
176 await tab.shot(workDir + '/web-join.png');
228 await tab.shot(workDir + '/web-join.png');
177 throw new Error('Teams web did not join, see 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');
178 }
231 }
179 defaultAudio('set', 'capture', 'CABLE Output');
232 defaultAudio('set', 'capture', 'CABLE Output');
180 log('default mic: CABLE Output');
233 log('default mic: CABLE Output');
@@ -190,6 +243,7 @@ try {
190 runProbe('record-process', String(processId), String(MEASURE_SECONDS), windowsPath(workDir + '/app-heard.wav')),
243 runProbe('record-process', String(processId), String(MEASURE_SECONDS), windowsPath(workDir + '/app-heard.wav')),
191 sampleWeb(tab, MEASURE_SECONDS),
244 sampleWeb(tab, MEASURE_SECONDS),
192 ]);
245 ]);
246 report.guestSending = await tab.evaluate(GUEST_SENDING).catch((error) => error.message);
193 report.appToWeb = judge(webLevels, WEB_THRESHOLD);
247 report.appToWeb = judge(webLevels, WEB_THRESHOLD);
194 report.webToApp = judge(JSON.parse(recorded).rms, APP_THRESHOLD);
248 report.webToApp = judge(JSON.parse(recorded).rms, APP_THRESHOLD);
195 report.webLevels = webLevels.map((level) => Number(level.toFixed(4)));
249 report.webLevels = webLevels.map((level) => Number(level.toFixed(4)));
@@ -201,6 +255,7 @@ try {
201} finally {
255} finally {
202 if (teamsProcessId()) runTeams('--hang-up');
256 if (teamsProcessId()) runTeams('--hang-up');
203 await tab.close();
257 await tab.close();
258 await host.close();
204 restoreCapture();
259 restoreCapture();
205 log('default mic restored');
260 log('default mic restored');
206 server.close();
261 server.close();
@@ -208,5 +263,5 @@ try {
208}
263}
209report.pass = Boolean(report.appToWeb?.pass && report.webToApp?.pass);
264report.pass = Boolean(report.appToWeb?.pass && report.webToApp?.pass);
210writeFileSync(workDir + '/report.json', JSON.stringify(report, null, 2));
265writeFileSync(workDir + '/report.json', JSON.stringify(report, null, 2));
211console.log(JSON.stringify({ pass: report.pass, appToWeb: report.appToWeb, webToApp: report.webToApp, error: report.error }));
266console.log(JSON.stringify({ pass: report.pass, appToWeb: report.appToWeb, webToApp: report.webToApp, guestSending: report.guestSending, error: report.error }));
212process.exit(report.pass ? 0 : 1);
267process.exit(report.pass ? 0 : 1);
scripts/teams-web-cdp.mjs +4 −0
@@ -47,6 +47,10 @@ export const FAKE_MEDIA = (speechUrl) => `(() => {
47 47 return new MediaStream(tracks);
48 48 };
49 49 navigator.mediaDevices.getDisplayMedia = async () => new MediaStream([canvasTrack('screen', 1280, 720)]);
50 const query = navigator.permissions.query.bind(navigator.permissions);
51 navigator.permissions.query = (descriptor) => ['microphone', 'camera'].includes(descriptor && descriptor.name)
52 ? Promise.resolve({ state: 'granted', name: descriptor.name, onchange: null, addEventListener() {}, removeEventListener() {} })
53 : query(descriptor);
50 54 navigator.mediaDevices.__matrix = true;
51 55 })();`;
52 56
@@ -47,6 +47,10 @@ export const FAKE_MEDIA = (speechUrl) => `(() => {
47 return new MediaStream(tracks);
47 return new MediaStream(tracks);
48 };
48 };
49 navigator.mediaDevices.getDisplayMedia = async () => new MediaStream([canvasTrack('screen', 1280, 720)]);
49 navigator.mediaDevices.getDisplayMedia = async () => new MediaStream([canvasTrack('screen', 1280, 720)]);
50 const query = navigator.permissions.query.bind(navigator.permissions);
51 navigator.permissions.query = (descriptor) => ['microphone', 'camera'].includes(descriptor && descriptor.name)
52 ? Promise.resolve({ state: 'granted', name: descriptor.name, onchange: null, addEventListener() {}, removeEventListener() {} })
53 : query(descriptor);
50 navigator.mediaDevices.__matrix = true;
54 navigator.mediaDevices.__matrix = true;
51})();`;
55})();`;
52
56