feat(calling): call e2e runs with the app as host and a lobby guest
- teams.exe --admit-all admits lobby guests in the running call - call-e2e: no own Teams web tab any more (several Teams tabs in one profile hung at "Connecting"); the app hosts, an anonymous guest joins and gets admitted - guest fake mic: speech as data URL (incognito blocked the loopback fetch), real click for audio activation - audio_probe record-mic records the default mic through the call capture path Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -5,13 +5,16 @@ use crate::app_state::AppState;
5
5
6
6
pub const JOIN_FLAG: &str = "--join";
7
7
pub const HANG_UP_FLAG: &str = "--hang-up";
8
pub const ADMIT_ALL_FLAG: &str = "--admit-all";
8
9
const JOIN_COMMAND: &str = "join ";
9
10
const HANG_UP_COMMAND: &str = "hang-up";
11
const ADMIT_ALL_COMMAND: &str = "admit-all";
10
12
11
13
#[derive(Debug, Clone, PartialEq, Eq)]
12
14
pub enum RemoteCommand {
13
15
Join(String),
14
16
HangUp,
17
AdmitAll,
15
18
}
16
19
17
20
impl RemoteCommand {
@@ -19,12 +22,15 @@ impl RemoteCommand {
19
22
match self {
20
23
RemoteCommand::Join(link) => format!("{JOIN_COMMAND}{link}"),
21
24
RemoteCommand::HangUp => HANG_UP_COMMAND.to_owned(),
25
RemoteCommand::AdmitAll => ADMIT_ALL_COMMAND.to_owned(),
22
26
}
23
27
}
24
28
25
29
pub fn decode(text: &str) -> Option<RemoteCommand> {
26
if text == HANG_UP_COMMAND {
27
return Some(RemoteCommand::HangUp);
30
match text {
31
HANG_UP_COMMAND => return Some(RemoteCommand::HangUp),
32
ADMIT_ALL_COMMAND => return Some(RemoteCommand::AdmitAll),
33
_ => {}
28
34
}
29
35
let link = text.strip_prefix(JOIN_COMMAND)?.trim();
30
36
(!link.is_empty()).then(|| RemoteCommand::Join(link.to_owned()))
@@ -41,6 +47,7 @@ impl AppState {
41
47
self.own_engine_next_call = false;
42
48
}
43
49
Some(RemoteCommand::HangUp) => self.leave_call(cx),
50
Some(RemoteCommand::AdmitAll) => self.admit_all_call_guests(cx),
44
51
None => {}
45
52
}
46
53
}
@@ -55,6 +62,7 @@ mod tests {
55
62
for command in [
56
63
RemoteCommand::Join("https://teams.microsoft.com/l/meetup-join/x".to_owned()),
57
64
RemoteCommand::HangUp,
65
RemoteCommand::AdmitAll,
58
66
] {
59
67
assert_eq!(RemoteCommand::decode(&command.encode()), Some(command));
60
68
}
@@ -5,13 +5,16 @@ use crate::app_state::AppState;5
5
6
pub const JOIN_FLAG: &str = "--join";6
pub const JOIN_FLAG: &str = "--join";7
pub const HANG_UP_FLAG: &str = "--hang-up";7
pub const HANG_UP_FLAG: &str = "--hang-up";8
pub const ADMIT_ALL_FLAG: &str = "--admit-all";8
const JOIN_COMMAND: &str = "join ";9
const JOIN_COMMAND: &str = "join ";9
const HANG_UP_COMMAND: &str = "hang-up";10
const HANG_UP_COMMAND: &str = "hang-up";11
const ADMIT_ALL_COMMAND: &str = "admit-all";10
12
11
#[derive(Debug, Clone, PartialEq, Eq)]13
#[derive(Debug, Clone, PartialEq, Eq)]12
pub enum RemoteCommand {14
pub enum RemoteCommand {13
Join(String),15
Join(String),14
HangUp,16
HangUp,17
AdmitAll,15
}18
}16
19
17
impl RemoteCommand {20
impl RemoteCommand {@@ -19,12 +22,15 @@ impl RemoteCommand {19
match self {22
match self {20
RemoteCommand::Join(link) => format!("{JOIN_COMMAND}{link}"),23
RemoteCommand::Join(link) => format!("{JOIN_COMMAND}{link}"),21
RemoteCommand::HangUp => HANG_UP_COMMAND.to_owned(),24
RemoteCommand::HangUp => HANG_UP_COMMAND.to_owned(),25
RemoteCommand::AdmitAll => ADMIT_ALL_COMMAND.to_owned(),22
}26
}23
}27
}24
28
25
pub fn decode(text: &str) -> Option<RemoteCommand> {29
pub fn decode(text: &str) -> Option<RemoteCommand> {26
if text == HANG_UP_COMMAND {30
match text {27
return Some(RemoteCommand::HangUp);31
HANG_UP_COMMAND => return Some(RemoteCommand::HangUp),32
ADMIT_ALL_COMMAND => return Some(RemoteCommand::AdmitAll),33
_ => {}28
}34
}29
let link = text.strip_prefix(JOIN_COMMAND)?.trim();35
let link = text.strip_prefix(JOIN_COMMAND)?.trim();30
(!link.is_empty()).then(|| RemoteCommand::Join(link.to_owned()))36
(!link.is_empty()).then(|| RemoteCommand::Join(link.to_owned()))@@ -41,6 +47,7 @@ impl AppState {41
self.own_engine_next_call = false;47
self.own_engine_next_call = false;42
}48
}43
Some(RemoteCommand::HangUp) => self.leave_call(cx),49
Some(RemoteCommand::HangUp) => self.leave_call(cx),50
Some(RemoteCommand::AdmitAll) => self.admit_all_call_guests(cx),44
None => {}51
None => {}45
}52
}46
}53
}@@ -55,6 +62,7 @@ mod tests {55
for command in [62
for command in [56
RemoteCommand::Join("https://teams.microsoft.com/l/meetup-join/x".to_owned()),63
RemoteCommand::Join("https://teams.microsoft.com/l/meetup-join/x".to_owned()),57
RemoteCommand::HangUp,64
RemoteCommand::HangUp,65
RemoteCommand::AdmitAll,58
] {66
] {59
assert_eq!(RemoteCommand::decode(&command.encode()), Some(command));67
assert_eq!(RemoteCommand::decode(&command.encode()), Some(command));60
}68
}@@ -25,7 +25,7 @@ use gpui_kit::*;
25
25
use store::Store;
26
26
27
27
use crate::app_state::{AppState, Mode};
28
use crate::call::remote_command::{HANG_UP_FLAG, JOIN_FLAG, RemoteCommand};
28
use crate::call::remote_command::{ADMIT_ALL_FLAG, HANG_UP_FLAG, JOIN_FLAG, RemoteCommand};
29
29
use views::shell::{AppShell, OpenTarget, Startup, bind_keys};
30
30
31
31
const LINUX_APP_ID: &str = "rusty-teams";
@@ -82,6 +82,7 @@ fn parse_arguments() -> Arguments {
82
82
}
83
83
JOIN_FLAG => arguments.remote_command = input.next().map(RemoteCommand::Join),
84
84
HANG_UP_FLAG => arguments.remote_command = Some(RemoteCommand::HangUp),
85
ADMIT_ALL_FLAG => arguments.remote_command = Some(RemoteCommand::AdmitAll),
85
86
"--database" => arguments.database = input.next().map(PathBuf::from),
86
87
"--endpoint" => arguments.endpoint = input.next(),
87
88
"--open" => {
@@ -25,7 +25,7 @@ use gpui_kit::*;25
use store::Store;25
use store::Store;26
26
27
use crate::app_state::{AppState, Mode};27
use crate::app_state::{AppState, Mode};28
use crate::call::remote_command::{HANG_UP_FLAG, JOIN_FLAG, RemoteCommand};28
use crate::call::remote_command::{ADMIT_ALL_FLAG, HANG_UP_FLAG, JOIN_FLAG, RemoteCommand};29
use views::shell::{AppShell, OpenTarget, Startup, bind_keys};29
use views::shell::{AppShell, OpenTarget, Startup, bind_keys};30
30
31
const LINUX_APP_ID: &str = "rusty-teams";31
const LINUX_APP_ID: &str = "rusty-teams";@@ -82,6 +82,7 @@ fn parse_arguments() -> Arguments {82
}82
}83
JOIN_FLAG => arguments.remote_command = input.next().map(RemoteCommand::Join),83
JOIN_FLAG => arguments.remote_command = input.next().map(RemoteCommand::Join),84
HANG_UP_FLAG => arguments.remote_command = Some(RemoteCommand::HangUp),84
HANG_UP_FLAG => arguments.remote_command = Some(RemoteCommand::HangUp),85
ADMIT_ALL_FLAG => arguments.remote_command = Some(RemoteCommand::AdmitAll),85
"--database" => arguments.database = input.next().map(PathBuf::from),86
"--database" => arguments.database = input.next().map(PathBuf::from),86
"--endpoint" => arguments.endpoint = input.next(),87
"--endpoint" => arguments.endpoint = input.next(),87
"--open" => {88
"--open" => {@@ -1,6 +1,7 @@
1
1
//! Windows tool for the call end-to-end test.
2
2
//! `audio_probe play <render device name part> <mono 16-bit 48 kHz wav> <seconds>` loops the file into that endpoint.
3
3
//! `audio_probe record-process <pid> <seconds> <out.wav>` records only what that process plays and prints loudness per 250 ms as JSON.
4
//! `audio_probe record-mic <seconds> <out.wav>` records the default communications mic the way a call does.
4
5
5
6
#[cfg(windows)]
6
7
fn main() {
@@ -13,7 +14,8 @@ fn main() {
13
14
seconds.parse().expect("seconds"),
14
15
out,
15
16
),
16
_ => Err("usage: play DEVICE WAV SECONDS | record-process PID SECONDS OUT.wav".to_owned()),
17
["record-mic", seconds, out] => probe::record_mic(seconds.parse().expect("seconds"), out),
18
_ => Err("usage: play DEVICE WAV SECONDS | record-process PID SECONDS OUT.wav | record-mic SECONDS OUT.wav".to_owned()),
17
19
};
18
20
if let Err(error) = outcome {
19
21
eprintln!("{error}");
@@ -151,6 +153,18 @@ mod probe {
151
153
pub fn record_process(process_id: u32, seconds: u64, out: &str) -> Result<(), String> {
152
154
let queue = SampleQueue::default();
153
155
let _capture = calling::start_process_capture(queue.clone(), process_id).map_err(|error| failed("capture", error))?;
156
record(&queue, seconds, out)
157
}
158
159
pub fn record_mic(seconds: u64, out: &str) -> Result<(), String> {
160
let queue = SampleQueue::default();
161
let started = calling::sound_capture::start_microphone(&calling::DeviceChoice::SystemDefault, queue.clone())
162
.map_err(|error| failed("microphone", error))?;
163
eprintln!("{}", started.source);
164
record(&queue, seconds, out)
165
}
166
167
fn record(queue: &SampleQueue, seconds: u64, out: &str) -> Result<(), String> {
154
168
let mut dump = WavDump::create(std::path::Path::new(out)).map_err(|error| failed("wav", error))?;
155
169
let frames_per_window = WINDOW_MS * SAMPLE_RATE as usize / 1000 / FRAME_SAMPLES;
156
170
let mut window = Vec::new();
@@ -1,6 +1,7 @@1
//! Windows tool for the call end-to-end test.1
//! Windows tool for the call end-to-end test.2
//! `audio_probe play <render device name part> <mono 16-bit 48 kHz wav> <seconds>` loops the file into that endpoint.2
//! `audio_probe play <render device name part> <mono 16-bit 48 kHz wav> <seconds>` loops the file into that endpoint.3
//! `audio_probe record-process <pid> <seconds> <out.wav>` records only what that process plays and prints loudness per 250 ms as JSON.3
//! `audio_probe record-process <pid> <seconds> <out.wav>` records only what that process plays and prints loudness per 250 ms as JSON.4
//! `audio_probe record-mic <seconds> <out.wav>` records the default communications mic the way a call does.4
5
5
#[cfg(windows)]6
#[cfg(windows)]6
fn main() {7
fn main() {@@ -13,7 +14,8 @@ fn main() {13
seconds.parse().expect("seconds"),14
seconds.parse().expect("seconds"),14
out,15
out,15
),16
),16
_ => Err("usage: play DEVICE WAV SECONDS | record-process PID SECONDS OUT.wav".to_owned()),17
["record-mic", seconds, out] => probe::record_mic(seconds.parse().expect("seconds"), out),18
_ => Err("usage: play DEVICE WAV SECONDS | record-process PID SECONDS OUT.wav | record-mic SECONDS OUT.wav".to_owned()),17
};19
};18
if let Err(error) = outcome {20
if let Err(error) = outcome {19
eprintln!("{error}");21
eprintln!("{error}");@@ -151,6 +153,18 @@ mod probe {151
pub fn record_process(process_id: u32, seconds: u64, out: &str) -> Result<(), String> {153
pub fn record_process(process_id: u32, seconds: u64, out: &str) -> Result<(), String> {152
let queue = SampleQueue::default();154
let queue = SampleQueue::default();153
let _capture = calling::start_process_capture(queue.clone(), process_id).map_err(|error| failed("capture", error))?;155
let _capture = calling::start_process_capture(queue.clone(), process_id).map_err(|error| failed("capture", error))?;156
record(&queue, seconds, out)157
}158
159
pub fn record_mic(seconds: u64, out: &str) -> Result<(), String> {160
let queue = SampleQueue::default();161
let started = calling::sound_capture::start_microphone(&calling::DeviceChoice::SystemDefault, queue.clone())162
.map_err(|error| failed("microphone", error))?;163
eprintln!("{}", started.source);164
record(&queue, seconds, out)165
}166
167
fn record(queue: &SampleQueue, seconds: u64, out: &str) -> Result<(), String> {154
let mut dump = WavDump::create(std::path::Path::new(out)).map_err(|error| failed("wav", error))?;168
let mut dump = WavDump::create(std::path::Path::new(out)).map_err(|error| failed("wav", error))?;155
let frames_per_window = WINDOW_MS * SAMPLE_RATE as usize / 1000 / FRAME_SAMPLES;169
let frames_per_window = WINDOW_MS * SAMPLE_RATE as usize / 1000 / FRAME_SAMPLES;156
let mut window = Vec::new();170
let mut window = Vec::new();@@ -1,16 +1,14 @@
1
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,
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
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]
6
6
import { spawn, execFileSync } from 'node:child_process';
7
import { createServer } from 'node:http';
8
7
import { readFileSync, writeFileSync } from 'node:fs';
9
import { Browser, CLICK, FAKE_MEDIA, PEER_HOOK } from './teams-web-cdp.mjs';
8
import { Browser, FAKE_MEDIA, PEER_HOOK } from './teams-web-cdp.mjs';
10
9
11
10
const [workDir, givenLink] = process.argv.slice(2);
12
11
const OWN_ENDPOINT = process.env.OWN_CDP ?? 'http://127.0.0.1:9222';
13
const PORT = Number(process.env.E2E_PORT ?? 9475);
14
12
const PROBE_DIR = process.env.PROBE_DIR ?? '/mnt/c/Users/dd/AppData/Local/Temp/call-e2e';
15
13
const TEAMS_EXE = process.env.TEAMS_EXE ?? '/mnt/c/Users/dd/AppData/Local/Programs/ms-teams-linux/teams.exe';
16
14
const POWERSHELL = '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe';
@@ -22,7 +20,9 @@ const WEB_JOIN_TIMEOUT_MS = 90_000;
22
20
const APP_JOIN_WAIT_MS = 25_000;
23
21
const MEASURE_SECONDS = 30;
24
22
const WINDOW_MS = 250;
25
const WEB_JOIN_STEPS = ['Continue on this browser', 'Not now', 'Join now'];
23
const STEP_REPEAT_MS = 15_000;
24
const ADMIT_INTERVAL_MS = 5_000;
25
const WEB_JOIN_STEPS = ['Continue on this browser', 'Not now', '=Join now', '=Join'];
26
26
const GUEST_NAME = 'Call e2e guest';
27
27
const LOBBY_TEXTS = ['let you in shortly', 'should let you in soon'];
28
28
const WEB_THRESHOLD = { speech: 0.005, floor: 0.0005 };
@@ -69,23 +69,7 @@ function runProbe(...args) {
69
69
});
70
70
}
71
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
81
function 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
}
72
const speechDataUrl = () => `data:audio/wav;base64,${readFileSync(PROBE_DIR + '/web.wav').toString('base64')}`;
89
73
90
74
const INBOUND_AUDIO = `(async () => {
91
75
let energy = 0, duration = 0, packets = 0;
@@ -110,13 +94,26 @@ const GUEST_SENDING = `(async () => {
110
94
}
111
95
return { level: duration > 0 ? Math.sqrt(energy / duration) : 0, packets };
112
96
})()`;
97
const 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
})()`;
113
110
const CONNECTED = `(window.__pcs || []).some((peer) => peer.connectionState === 'connected')`;
114
111
const TEAMS_ORIGINS = ['https://teams.cloud.microsoft', 'https://teams.microsoft.com'];
115
112
116
class WebTab {
117
constructor(browser, { guest }) { this.browser = browser; this.guest = guest; }
113
class GuestTab {
114
constructor(browser) { this.browser = browser; }
118
115
async open(link) {
119
if (this.guest) this.contextId = (await this.browser.send('Target.createBrowserContext', { disposeOnDetach: false })).browserContextId;
116
this.contextId = (await this.browser.send('Target.createBrowserContext', { disposeOnDetach: false })).browserContextId;
120
117
const context = this.contextId ? { browserContextId: this.contextId } : {};
121
118
const { targetId } = await this.browser.send('Target.createTarget', { url: 'about:blank', ...context });
122
119
this.targetId = targetId;
@@ -125,7 +122,7 @@ class WebTab {
125
122
await this.browser.send('Page.enable', {}, sessionId);
126
123
await this.browser.send('Runtime.enable', {}, sessionId);
127
124
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);
125
await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: FAKE_MEDIA(speechDataUrl()) }, sessionId);
129
126
for (const origin of TEAMS_ORIGINS) {
130
127
await this.browser.send('Browser.grantPermissions', { permissions: ['audioCapture', 'videoCapture'], origin, ...context }).catch(() => {});
131
128
}
@@ -139,18 +136,31 @@ class WebTab {
139
136
}
140
137
async join() {
141
138
const deadline = Date.now() + WEB_JOIN_TIMEOUT_MS;
139
const clickedAt = new Map();
142
140
while (Date.now() < deadline) {
143
141
const inLobby = await this.evaluate(`${JSON.stringify(LOBBY_TEXTS)}.some((text) => document.body.innerText.includes(text))`).catch(() => false);
144
142
if (!inLobby && (await this.evaluate(CONNECTED).catch(() => false))) return true;
145
if (this.guest) await this.typeName();
143
await this.activate();
144
await this.typeName();
146
145
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}"`);
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
}
149
151
}
150
152
await delay(2000);
151
153
}
152
154
return false;
153
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
}
154
164
async typeName() {
155
165
const focused = await this.evaluate(`(() => {
156
166
const input = document.querySelector('input[placeholder*="name" i]');
@@ -159,11 +169,6 @@ class WebTab {
159
169
})()`).catch(() => false);
160
170
if (focused) await this.browser.send('Input.insertText', { text: GUEST_NAME }, this.sessionId);
161
171
}
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
172
async shot(path) {
168
173
const { data } = await this.browser.send('Page.captureScreenshot', { format: 'png' }, this.sessionId);
169
174
writeFileSync(path, Buffer.from(data, 'base64'));
@@ -201,10 +206,8 @@ const report = { started: new Date().toISOString() };
201
206
const savedCapture = defaultAudio('get', 'capture');
202
207
const restoreCapture = () => defaultAudio('set', 'capture', savedCapture);
203
208
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { restoreCapture(); process.exit(130); });
204
const server = serveSpeech();
205
209
const browser = await new Browser(OWN_ENDPOINT).connect();
206
const host = new WebTab(browser, { guest: false });
207
const tab = new WebTab(browser, { guest: true });
210
const tab = new GuestTab(browser);
208
211
try {
209
212
if (!teamsProcessId()) {
210
213
log(`starting the app, waiting ${APP_START_WAIT_MS / 1000}s`);
@@ -214,28 +217,22 @@ try {
214
217
const link = givenLink ?? createMeeting();
215
218
report.link = link;
216
219
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
220
defaultAudio('set', 'capture', 'CABLE Output');
233
221
log('default mic: CABLE Output');
234
const playSeconds = Math.ceil(APP_JOIN_WAIT_MS / 1000) + MEASURE_SECONDS + 10;
222
const playSeconds = Math.ceil((APP_JOIN_WAIT_MS + WEB_JOIN_TIMEOUT_MS) / 1000) + MEASURE_SECONDS + 10;
235
223
const playing = runProbe('play', 'CABLE Input', windowsPath(PROBE_DIR + '/app.wav'), String(playSeconds));
236
224
runTeams('--join', link);
237
225
log(`app joining, waiting ${APP_JOIN_WAIT_MS / 1000}s`);
238
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();
239
236
const processId = teamsProcessId();
240
237
if (!processId) throw new Error('teams.exe is not running');
241
238
log(`measuring ${MEASURE_SECONDS}s (teams.exe pid ${processId})`);
@@ -255,10 +252,8 @@ try {
255
252
} finally {
256
253
if (teamsProcessId()) runTeams('--hang-up');
257
254
await tab.close();
258
await host.close();
259
255
restoreCapture();
260
256
log('default mic restored');
261
server.close();
262
257
browser.socket.close();
263
258
}
264
259
report.pass = Boolean(report.appToWeb?.pass && report.webToApp?.pass);
@@ -1,16 +1,14 @@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 as Daniel hosts a fresh Meet now and admits an anonymous Teams web guest whose mic is a looped speech file.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
// The Windows app joins through `teams.exe --join`; its mic is VB-CABLE fed with a second 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.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]6
import { spawn, execFileSync } from 'node:child_process';6
import { spawn, execFileSync } from 'node:child_process';7
import { createServer } from 'node:http';8
import { readFileSync, writeFileSync } from 'node:fs';7
import { readFileSync, writeFileSync } from 'node:fs';9
import { Browser, CLICK, FAKE_MEDIA, PEER_HOOK } from './teams-web-cdp.mjs';8
import { Browser, FAKE_MEDIA, PEER_HOOK } from './teams-web-cdp.mjs';10
9
11
const [workDir, givenLink] = process.argv.slice(2);10
const [workDir, givenLink] = process.argv.slice(2);12
const OWN_ENDPOINT = process.env.OWN_CDP ?? 'http://127.0.0.1:9222';11
const OWN_ENDPOINT = process.env.OWN_CDP ?? 'http://127.0.0.1:9222';13
const PORT = Number(process.env.E2E_PORT ?? 9475);14
const PROBE_DIR = process.env.PROBE_DIR ?? '/mnt/c/Users/dd/AppData/Local/Temp/call-e2e';12
const PROBE_DIR = process.env.PROBE_DIR ?? '/mnt/c/Users/dd/AppData/Local/Temp/call-e2e';15
const TEAMS_EXE = process.env.TEAMS_EXE ?? '/mnt/c/Users/dd/AppData/Local/Programs/ms-teams-linux/teams.exe';13
const TEAMS_EXE = process.env.TEAMS_EXE ?? '/mnt/c/Users/dd/AppData/Local/Programs/ms-teams-linux/teams.exe';16
const POWERSHELL = '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe';14
const POWERSHELL = '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe';@@ -22,7 +20,9 @@ const WEB_JOIN_TIMEOUT_MS = 90_000;22
const APP_JOIN_WAIT_MS = 25_000;20
const APP_JOIN_WAIT_MS = 25_000;23
const MEASURE_SECONDS = 30;21
const MEASURE_SECONDS = 30;24
const WINDOW_MS = 250;22
const WINDOW_MS = 250;25
const WEB_JOIN_STEPS = ['Continue on this browser', 'Not now', 'Join now'];23
const STEP_REPEAT_MS = 15_000;24
const ADMIT_INTERVAL_MS = 5_000;25
const WEB_JOIN_STEPS = ['Continue on this browser', 'Not now', '=Join now', '=Join'];26
const GUEST_NAME = 'Call e2e guest';26
const GUEST_NAME = 'Call e2e guest';27
const LOBBY_TEXTS = ['let you in shortly', 'should let you in soon'];27
const LOBBY_TEXTS = ['let you in shortly', 'should let you in soon'];28
const WEB_THRESHOLD = { speech: 0.005, floor: 0.0005 };28
const WEB_THRESHOLD = { speech: 0.005, floor: 0.0005 };@@ -69,23 +69,7 @@ function runProbe(...args) {69
});69
});70
}70
}71
71
72
function silentWav(seconds) {72
const speechDataUrl = () => `data:audio/wav;base64,${readFileSync(PROBE_DIR + '/web.wav').toString('base64')}`;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
81
function 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
73
90
const INBOUND_AUDIO = `(async () => {74
const INBOUND_AUDIO = `(async () => {91
let energy = 0, duration = 0, packets = 0;75
let energy = 0, duration = 0, packets = 0;@@ -110,13 +94,26 @@ const GUEST_SENDING = `(async () => {110
}94
}111
return { level: duration > 0 ? Math.sqrt(energy / duration) : 0, packets };95
return { level: duration > 0 ? Math.sqrt(energy / duration) : 0, packets };112
})()`;96
})()`;97
const 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
})()`;113
const CONNECTED = `(window.__pcs || []).some((peer) => peer.connectionState === 'connected')`;110
const CONNECTED = `(window.__pcs || []).some((peer) => peer.connectionState === 'connected')`;114
const TEAMS_ORIGINS = ['https://teams.cloud.microsoft', 'https://teams.microsoft.com'];111
const TEAMS_ORIGINS = ['https://teams.cloud.microsoft', 'https://teams.microsoft.com'];115
112
116
class WebTab {113
class GuestTab {117
constructor(browser, { guest }) { this.browser = browser; this.guest = guest; }114
constructor(browser) { this.browser = browser; }118
async open(link) {115
async open(link) {119
if (this.guest) this.contextId = (await this.browser.send('Target.createBrowserContext', { disposeOnDetach: false })).browserContextId;116
this.contextId = (await this.browser.send('Target.createBrowserContext', { disposeOnDetach: false })).browserContextId;120
const context = this.contextId ? { browserContextId: this.contextId } : {};117
const context = this.contextId ? { browserContextId: this.contextId } : {};121
const { targetId } = await this.browser.send('Target.createTarget', { url: 'about:blank', ...context });118
const { targetId } = await this.browser.send('Target.createTarget', { url: 'about:blank', ...context });122
this.targetId = targetId;119
this.targetId = targetId;@@ -125,7 +122,7 @@ class WebTab {125
await this.browser.send('Page.enable', {}, sessionId);122
await this.browser.send('Page.enable', {}, sessionId);126
await this.browser.send('Runtime.enable', {}, sessionId);123
await this.browser.send('Runtime.enable', {}, sessionId);127
await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: PEER_HOOK }, sessionId);124
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);125
await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: FAKE_MEDIA(speechDataUrl()) }, sessionId);129
for (const origin of TEAMS_ORIGINS) {126
for (const origin of TEAMS_ORIGINS) {130
await this.browser.send('Browser.grantPermissions', { permissions: ['audioCapture', 'videoCapture'], origin, ...context }).catch(() => {});127
await this.browser.send('Browser.grantPermissions', { permissions: ['audioCapture', 'videoCapture'], origin, ...context }).catch(() => {});131
}128
}@@ -139,18 +136,31 @@ class WebTab {139
}136
}140
async join() {137
async join() {141
const deadline = Date.now() + WEB_JOIN_TIMEOUT_MS;138
const deadline = Date.now() + WEB_JOIN_TIMEOUT_MS;139
const clickedAt = new Map();142
while (Date.now() < deadline) {140
while (Date.now() < deadline) {143
const inLobby = await this.evaluate(`${JSON.stringify(LOBBY_TEXTS)}.some((text) => document.body.innerText.includes(text))`).catch(() => false);141
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;142
if (!inLobby && (await this.evaluate(CONNECTED).catch(() => false))) return true;145
if (this.guest) await this.typeName();143
await this.activate();144
await this.typeName();146
for (const step of WEB_JOIN_STEPS) {145
for (const step of WEB_JOIN_STEPS) {147
const click = await this.evaluate(CLICK(step)).catch(() => null);146
if (Date.now() - (clickedAt.get(step) ?? 0) < STEP_REPEAT_MS) continue;148
if (click?.clicked) log(`web: clicked "${step}"`);147
if (await this.click(step)) {148
clickedAt.set(step, Date.now());149
log(`web: clicked "${step}"`);150
}149
}151
}150
await delay(2000);152
await delay(2000);151
}153
}152
return false;154
return false;153
}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
}154
async typeName() {164
async typeName() {155
const focused = await this.evaluate(`(() => {165
const focused = await this.evaluate(`(() => {156
const input = document.querySelector('input[placeholder*="name" i]');166
const input = document.querySelector('input[placeholder*="name" i]');@@ -159,11 +169,6 @@ class WebTab {159
})()`).catch(() => false);169
})()`).catch(() => false);160
if (focused) await this.browser.send('Input.insertText', { text: GUEST_NAME }, this.sessionId);170
if (focused) await this.browser.send('Input.insertText', { text: GUEST_NAME }, this.sessionId);161
}171
}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) {172
async shot(path) {168
const { data } = await this.browser.send('Page.captureScreenshot', { format: 'png' }, this.sessionId);173
const { data } = await this.browser.send('Page.captureScreenshot', { format: 'png' }, this.sessionId);169
writeFileSync(path, Buffer.from(data, 'base64'));174
writeFileSync(path, Buffer.from(data, 'base64'));@@ -201,10 +206,8 @@ const report = { started: new Date().toISOString() };201
const savedCapture = defaultAudio('get', 'capture');206
const savedCapture = defaultAudio('get', 'capture');202
const restoreCapture = () => defaultAudio('set', 'capture', savedCapture);207
const restoreCapture = () => defaultAudio('set', 'capture', savedCapture);203
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { restoreCapture(); process.exit(130); });208
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { restoreCapture(); process.exit(130); });204
const server = serveSpeech();205
const browser = await new Browser(OWN_ENDPOINT).connect();209
const browser = await new Browser(OWN_ENDPOINT).connect();206
const host = new WebTab(browser, { guest: false });210
const tab = new GuestTab(browser);207
const tab = new WebTab(browser, { guest: true });208
try {211
try {209
if (!teamsProcessId()) {212
if (!teamsProcessId()) {210
log(`starting the app, waiting ${APP_START_WAIT_MS / 1000}s`);213
log(`starting the app, waiting ${APP_START_WAIT_MS / 1000}s`);@@ -214,28 +217,22 @@ try {214
const link = givenLink ?? createMeeting();217
const link = givenLink ?? createMeeting();215
report.link = link;218
report.link = link;216
log('meeting ready');219
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');220
defaultAudio('set', 'capture', 'CABLE Output');233
log('default mic: CABLE Output');221
log('default mic: CABLE Output');234
const playSeconds = Math.ceil(APP_JOIN_WAIT_MS / 1000) + MEASURE_SECONDS + 10;222
const playSeconds = Math.ceil((APP_JOIN_WAIT_MS + WEB_JOIN_TIMEOUT_MS) / 1000) + MEASURE_SECONDS + 10;235
const playing = runProbe('play', 'CABLE Input', windowsPath(PROBE_DIR + '/app.wav'), String(playSeconds));223
const playing = runProbe('play', 'CABLE Input', windowsPath(PROBE_DIR + '/app.wav'), String(playSeconds));236
runTeams('--join', link);224
runTeams('--join', link);237
log(`app joining, waiting ${APP_JOIN_WAIT_MS / 1000}s`);225
log(`app joining, waiting ${APP_JOIN_WAIT_MS / 1000}s`);238
await delay(APP_JOIN_WAIT_MS);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();239
const processId = teamsProcessId();236
const processId = teamsProcessId();240
if (!processId) throw new Error('teams.exe is not running');237
if (!processId) throw new Error('teams.exe is not running');241
log(`measuring ${MEASURE_SECONDS}s (teams.exe pid ${processId})`);238
log(`measuring ${MEASURE_SECONDS}s (teams.exe pid ${processId})`);@@ -255,10 +252,8 @@ try {255
} finally {252
} finally {256
if (teamsProcessId()) runTeams('--hang-up');253
if (teamsProcessId()) runTeams('--hang-up');257
await tab.close();254
await tab.close();258
await host.close();259
restoreCapture();255
restoreCapture();260
log('default mic restored');256
log('default mic restored');261
server.close();262
browser.socket.close();257
browser.socket.close();263
}258
}264
report.pass = Boolean(report.appToWeb?.pass && report.webToApp?.pass);259
report.pass = Boolean(report.appToWeb?.pass && report.webToApp?.pass);@@ -24,6 +24,8 @@ export const FAKE_MEDIA = (speechUrl) => `(() => {
24
24
let audioContext;
25
25
const speechTrack = async () => {
26
26
audioContext = audioContext || new AudioContext();
27
addEventListener('pointerdown', () => audioContext.resume(), true);
28
audioContext.resume().catch(() => {});
27
29
const destination = audioContext.createMediaStreamDestination();
28
30
try {
29
31
const data = await (await fetch('${speechUrl}')).arrayBuffer();
@@ -24,6 +24,8 @@ export const FAKE_MEDIA = (speechUrl) => `(() => {24
let audioContext;24
let audioContext;25
const speechTrack = async () => {25
const speechTrack = async () => {26
audioContext = audioContext || new AudioContext();26
audioContext = audioContext || new AudioContext();27
addEventListener('pointerdown', () => audioContext.resume(), true);28
audioContext.resume().catch(() => {});27
const destination = audioContext.createMediaStreamDestination();29
const destination = audioContext.createMediaStreamDestination();28
try {30
try {29
const data = await (await fetch('${speechUrl}')).arrayBuffer();31
const data = await (await fetch('${speechUrl}')).arrayBuffer();