oficina / meet Public

Clone
git clone https://amadan.net/oficina/meet

Plain git — no account needed to clone.

Download

Download this file

1import { syntheticMedia } from './synthetic-media.mjs';
2import { chromium } from 'playwright';
3import { spawn } from 'node:child_process';
4import { createInterface } from 'node:readline';
5import assert from 'node:assert/strict';
6import { fileURLToPath } from 'node:url';
7
8const [origin, room, binary, mode] = process.argv.slice(2);
9const browser = await chromium.launch({ headless: true, args: [
10 '--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream',
11 '--autoplay-policy=no-user-gesture-required', '--disable-features=WebRtcHideLocalIpsWithMdns',
12 '--mute-audio',
13 // §5.4: answers getDisplayMedia with a fake monitor that really
14 // produces frames, as call.mjs does for the browser-only share gate.
15 '--auto-accept-this-tab-capture',
16] });
17const context = await browser.newContext({ permissions: ['camera', 'microphone'] });
18if (process.env.CALLS_SYNTHETIC_MEDIA) await context.addInitScript(syntheticMedia);
19await context.addCookies([{ name: process.env.CALLS_COOKIE_NAME, value: process.env.CALLS_COOKIE_A, url: origin }]);
20const page = await context.newPage();
21await page.addInitScript(() => {
22 const Native = window.RTCPeerConnection;
23 window.__nativeInteropPCs = new Set();
24 window.RTCPeerConnection = class extends Native {
25 constructor(...args) { super(...args); window.__nativeInteropPCs.add(this); }
26 };
27});
28let native;
29try {
30 await page.goto(`${origin}/m/${room}`);
31 await page.waitForFunction(() => !!window.meet);
32 console.log('browser before native', await page.evaluate(() => ({status: document.querySelector('#status')?.textContent, tiles: document.querySelectorAll('#tiles video').length})));
33 // Spec §15.24, both ways: the browser's offers, answers and candidates
34 // are held back for the first few seconds, so the app and the browser
35 // each have someone who cannot hear them yet, and each says so.
36 const HOLD = 5000;
37 let releaseAt = 0;
38 const holdSignals = async (route) => {
39 const body = route.request().postData() || '';
40 if (/"type":"(offer|answer|candidate)"/.test(body)) {
41 if (!releaseAt) releaseAt = Date.now() + HOLD;
42 await new Promise(r => setTimeout(r, Math.max(0, releaseAt - Date.now())));
43 }
44 await route.continue();
45 };
46 if (mode !== 'guest') await page.route('**/signal', holdSignals);
47 native = spawn(binary, [], { stdio: ['pipe', 'pipe', 'pipe'] });
48 native.stdin.write(process.env.CALLS_NATIVE_INPUT + '\n');
49 let sample = null;
50 let chatCommandHandled = false;
51 let chatSnapshotSaved = false;
52 let invitationReady = false;
53 let invitationRefused = false;
54 let invitationSnapshotSaved = false;
55 let audioSwitched = null;
56 let camera = null;
57 let cameraRefused = false;
58 let exited = false;
59 native.on('exit', () => { exited = true; });
60 // Native logs must never print credentials, SDP or candidates. Keep only
61 // the gate's explicit numeric observations and suppress library diagnostics.
62 createInterface({ input: native.stdout }).on('line', line => {
63 try {
64 const value = JSON.parse(line);
65 if (value.chatSnapshotSaved) chatSnapshotSaved = true;
66 if (value.chatCommandHandled) chatCommandHandled = true;
67 if (value.invitationReady) invitationReady = true;
68 if (value.invitationRefused) invitationRefused = true;
69 if (value.invitationSnapshotSaved) invitationSnapshotSaved = true;
70 if (value.audioSwitched !== undefined) audioSwitched = value.audioSwitched;
71 if (value.camera !== undefined) { camera = value.camera; cameraRefused = value.cameraRefused; }
72 if (value.stats) { sample = value; console.log(JSON.stringify(value)); }
73 } catch {}
74 });
75 native.stderr.resume();
76 const wait = async (predicate, label, seconds = 35) => {
77 const until = Date.now() + seconds * 1000;
78 while (Date.now() < until) {
79 if (exited) throw new Error('native executable exited');
80 if (await predicate()) return;
81 await new Promise(r => setTimeout(r, 250));
82 }
83 console.log('browser at failure', await page.evaluate(() => ({status: document.querySelector('#status')?.textContent, tiles: document.querySelectorAll('#tiles video').length, body: document.body.innerText})));
84 throw new Error(label + ': ' + JSON.stringify(sample));
85 };
86 if (mode === 'guest') {
87 await page.getByRole('button', { name: 'Admit', exact: true }).waitFor();
88 await wait(() => sample !== null, "native waiting observation");
89 await new Promise(r => setTimeout(r, 1500));
90 assert.equal(sample?.stats.framesDecoded ?? 0, 0, 'waiting guest receives no video');
91 assert.equal(sample?.stats.audioBytesReceived ?? 0, 0, 'waiting guest receives no audio');
92 await page.getByRole('button', { name: 'Admit', exact: true }).click();
93 console.log('PASS guest media waits for member admission');
94 }
95 if (mode !== 'guest') {
96 await wait(() => sample?.peer, 'the app is in the call');
97 const app = sample.peer;
98 const connecting = () => page.evaluate((id) => {
99 const s = window.meet.state();
100 return { c: s.connecting[id] || null, h: s.hearing[id] || null, media: s.remoteMedia[id] || null,
101 me: s.peer, hearingList: s.hearingList };
102 }, app);
103 await wait(async () => { const c = await connecting(); return c.h && c.h.noticeKind === 'connecting'; },
104 'the browser says the app cannot hear it yet', 15);
105 const words = (await connecting()).h.notice;
106 assert.match(words, / is connecting and can’t hear you yet$/);
107 console.log(`PASS the browser says "${words}" while the connection is held`);
108 await wait(() => sample?.stats.connectingShown === 1, 'the app says the browser cannot hear it yet', 15);
109 console.log('PASS the app says the browser cannot hear it yet');
110 await wait(async () => { const c = await connecting(); return c.c && !c.c.joining && c.h.notice === ''; },
111 'the browser stops saying it once the app hears it', 30);
112 const heard = await connecting();
113 assert.ok((heard.media.hearing || []).includes(heard.me), 'because the app reports it hears the browser');
114 assert.ok(Date.now() >= releaseAt, 'and not before the hold let go');
115 console.log('PASS the app reports hearing the browser, and the browser\u2019s notice goes');
116 await wait(() => sample?.stats.connectingShown === 0 && sample?.stats.connectingJoining === 0 && sample?.stats.hearing === 1,
117 'the app stops saying it once the browser hears it', 30);
118 assert.ok(heard.hearingList.includes(app) || (await connecting()).hearingList.includes(app), 'the browser reports it hears the app');
119 console.log('PASS the browser reports hearing the app, and the app\u2019s notice goes');
120 await page.unroute('**/signal', holdSignals);
121 }
122 await wait(() => sample?.stats.framesDecoded > 15 && sample?.stats.audioBytesReceived > 0 && sample?.stats.videoBytesSent > 0 && sample?.stats.audioBytesSent > 0, 'native receives browser audio/video');
123 console.log('PASS native decoded browser video and received audio');
124 // The synthetic microphone runs through WebRTC's capture processing, so
125 // the noise suppressor in its post-processing hook must have seen frames.
126 await wait(() => sample?.stats.noiseFramesProcessed > 100, 'native noise suppressor processes captured audio');
127 console.log(`PASS native noise suppressor ran on captured audio (${sample.stats.noiseSuppressor === 2 ? 'DeepFilterNet 3' : 'RNNoise'})`);
128 // And it runs instead of WebRTC's own suppressor and gain, beside its echo canceller.
129 assert.equal(sample.stats.webrtcNoiseSuppression, 0, "WebRTC's noise suppressor is off");
130 assert.equal(sample.stats.webrtcGainControl, 0, "WebRTC's gain control is off");
131 assert.equal(sample.stats.webrtcEchoCancellation, 1, "echo cancellation stays on");
132 console.log('PASS WebRTC noise suppression and gain off, echo cancellation on');
133 // With audio flowing, the readout reports what is running rather than
134 // "The microphone has not started yet".
135 assert.equal(sample.stats.audioReadoutStarted, 1, 'the audio readout knows the microphone has started');
136 console.log('PASS the audio readout reports a started microphone');
137 // Each remote video has its own decoded frame count; local preview alone
138 // cannot satisfy this check. Read the actual room test observation contract.
139 // Remote videos exclude the muted local preview. getVideoPlaybackQuality
140 // measures decoded frames in the actual browser renderer.
141 const remoteFrames = () => page.evaluate(() => [...document.querySelectorAll('#tiles video')]
142 .filter(v => !v.muted).reduce((n,v) => n + (v.getVideoPlaybackQuality?.().totalVideoFrames ?? 0), 0));
143 await wait(async () => await remoteFrames() > 15, 'browser decodes native video');
144 const browserAudio = () => page.evaluate(async () => {
145 let bytes = 0;
146 for (const pc of window.__nativeInteropPCs) {
147 if (pc.connectionState === 'closed') continue;
148 const stats = await pc.getStats();
149 for (const report of stats.values()) {
150 if (report.type === 'inbound-rtp' && report.kind === 'audio') bytes += report.bytesReceived || 0;
151 }
152 }
153 return bytes;
154 });
155 await wait(async () => await browserAudio() > 0, 'browser receives native audio');
156 console.log('PASS browser decoded native video and received native audio');
157 // Spec §15.20: bytes are not sound. On 2026-09-25 a call carried audio
158 // packets both ways while one side sent silence, and every counter said
159 // all was well. So the browser has to measure *energy* in what the app
160 // sends (inbound-rtp totalAudioEnergy and audioLevel), and the app's own
161 // receive meter has to see the browser's fake microphone.
162 {
163 const browserHearing = () => page.evaluate(async () => {
164 let energy = 0, level = 0;
165 for (const pc of window.__nativeInteropPCs) {
166 if (pc.connectionState === 'closed') continue;
167 for (const report of (await pc.getStats()).values()) {
168 if (report.type === 'inbound-rtp' && report.kind === 'audio') {
169 energy += report.totalAudioEnergy || 0;
170 level = Math.max(level, report.audioLevel || 0);
171 }
172 }
173 }
174 return { energy, level };
175 });
176 const before = await browserHearing();
177 let loudest = 0;
178 await wait(async () => {
179 const now = await browserHearing();
180 loudest = Math.max(loudest, now.level);
181 return now.energy > before.energy + 0.001 && loudest > 0.01;
182 }, 'the browser hears non-silent audio from the app');
183 console.log(`PASS the browser measures sound, not only bytes, from the app (audioLevel up to ${loudest.toFixed(3)})`);
184 await wait(() => sample?.stats.remoteAudioPeakPermille > 10, "the app's receive meter hears the browser");
185 console.log(`PASS the app's receive meter hears the browser (peak ${sample.stats.remoteAudioPeakPermille}\u2030)`);
186 await wait(() => sample?.stats.micPeakPermille > 10, "the app's own meter sees what it sends");
187 assert.equal(sample.stats.micSilent, 0, "a live synthetic microphone is not reported as picking nothing up");
188 console.log(`PASS the app's microphone meter reads what it sends, with no silence warning (noSoundFrom ${sample.stats.noSoundFrom})`);
189 await wait(() => sample?.stats.micGlow === 1, "the app's own name glows while its synthetic voice speaks");
190 console.log('PASS the speaking glow behind the app\'s own name lights for its voice');
191 }
192 // Choose the system default on the audio device module during the live
193 // call, then refuse an unavailable microphone. Both must leave media and
194 // the peer connection intact. (The harness's module is in manual
195 // rendering, so this exercises the routing code, not a device change.)
196 const audioBeforeSwitch = await browserAudio();
197 native.stdin.write('audio-default\n');
198 await wait(() => audioSwitched === true, 'native applies per-call audio selection');
199 await wait(async () => await browserAudio() > audioBeforeSwitch + 1000, 'audio continues after switching');
200 native.stdin.write('audio-missing\n');
201 await wait(() => audioSwitched === false, 'native refuses missing microphone');
202 const audioAfterRefusal = await browserAudio();
203 await wait(async () => await browserAudio() > audioAfterRefusal + 1000, 'audio survives refused selection');
204 assert.equal(sample.stats.peerConnections, 1, 'audio switching keeps the same peer connection');
205 console.log('PASS per-call audio switching and refused selection preserve media');
206 // Changing camera mid-call. The switch rests on the capturer feeding the
207 // same RTCVideoSource, so the RTCVideoTrack every connection is already
208 // sending does not change and nothing renegotiates — the native
209 // counterpart of the browser's replaceTrack. What proves it is the far
210 // side: frames must keep arriving across the switch, on the same
211 // connection, with no new m-line.
212 {
213 const beforeFrames = await remoteFrames();
214 const beforeLines = await page.evaluate(() => window.meet.state().peers.length);
215 native.stdin.write('camera synthetic-480\n');
216 await wait(() => camera === 'synthetic-480', 'native reports the camera it switched to');
217 assert.equal(cameraRefused, false, 'camera switch was refused');
218 await wait(async () => await remoteFrames() > beforeFrames + 15, 'browser keeps decoding across a camera switch');
219 assert.equal(
220 await page.evaluate(() => window.meet.state().peers.length), beforeLines,
221 'a camera switch must not change the roster or rebuild the pair');
222 // Two switches at once are two capture restarts on one device. Queued,
223 // the last one wins; run at once, the survivor is whichever session
224 // opened last, which is not the one a person chose.
225 native.stdin.write('camera synthetic-320\n');
226 native.stdin.write('camera synthetic-480\n');
227 await wait(() => camera === 'synthetic-480', 'the last of two racing switches is the one that holds');
228 const racedFrames = await remoteFrames();
229 await wait(async () => await remoteFrames() > racedFrames + 15, 'media survives racing camera switches');
230 // And a camera that is not there is refused without costing the call
231 // its picture.
232 native.stdin.write('camera no-such-camera\n');
233 await wait(() => cameraRefused === true, 'an unknown camera is refused');
234 const refusedFrames = await remoteFrames();
235 await wait(async () => await remoteFrames() > refusedFrames + 15, 'media survives a refused camera switch');
236 console.log('PASS camera switched mid-call without disturbing the connection');
237 }
238 // A camera that stops sending — an ATEM Mini whose input changed format
239 // — is noticed by the watchdog and restarted, on the same track, and the
240 // far side's picture comes back without anyone touching anything.
241 {
242 await wait(() => sample?.cameraStatus === 'live', 'the camera reports live before the stall');
243 const opensBefore = sample.cameraOpens;
244 native.stdin.write('camera-stall\n');
245 await wait(() => sample?.cameraOpens > opensBefore, 'the watchdog restarts a stalled camera', 20);
246 await wait(() => sample?.cameraStatus === 'live', 'the restarted camera reports live again', 20);
247 const recoveredFrames = await remoteFrames();
248 await wait(async () => await remoteFrames() > recoveredFrames + 15, 'browser decodes again after the camera recovers');
249 assert.equal(sample.stats.peerConnections, 1, 'recovering the camera keeps the same peer connection');
250 console.log('PASS a stalled camera was restarted and the far side kept its picture');
251 }
252 // Spec §15.30, the app as the sender: the browser's own Video quality
253 // asks the app for minimal, and the app's camera to the browser drops to
254 // 180 lines or fewer — measured where it arrives — then Audio only stops
255 // it, and Auto brings it back, all without a new connection.
256 if (mode === 'member') {
257 const arriving = () => page.evaluate(async () => {
258 let height = 0, bytes = 0;
259 for (const pc of window.__nativeInteropPCs) {
260 if (pc.connectionState === 'closed') continue;
261 for (const r of (await pc.getStats()).values()) {
262 if (r.type === 'inbound-rtp' && r.kind === 'video') {
263 height = Math.max(height, r.frameHeight || 0);
264 bytes += r.bytesReceived || 0;
265 }
266 }
267 }
268 return { height, bytes };
269 });
270 const pick = async (value) => {
271 await page.evaluate((v) => {
272 const panel = document.getElementById('room-devices');
273 if (panel && panel.hidden) document.getElementById('devices-toggle').click();
274 const el = document.getElementById('pick-video-quality');
275 el.value = v;
276 el.dispatchEvent(new Event('change', { bubbles: true }));
277 }, value);
278 };
279 // What the app sends when nothing is asked of it, unless its own
280 // watch holds its camera down (a busy gate machine: §15.30's sender
281 // half, which the app reports as ownCameraLevel).
282 const full = (await arriving()).height;
283 console.log(`the app's camera arrives at ${full} lines before anything is asked; its own level ${sample?.stats.ownCameraLevel}`);
284 await pick('low');
285 await wait(async () => (await arriving()).height > 0 && (await arriving()).height <= 180,
286 'the app sends its camera at 180 lines or fewer when the browser asks for minimal', 20);
287 const low = (await arriving()).height;
288 console.log(`PASS the app applies a requested level: its camera arrives at ${low} lines, from ${full}`);
289 await pick('audio');
290 await new Promise(r => setTimeout(r, 3000));
291 const paused = (await arriving()).bytes;
292 await new Promise(r => setTimeout(r, 3000));
293 assert.ok((await arriving()).bytes - paused < 3000, 'the app sends no camera to a browser that asks for audio only');
294 await wait(() => sample?.stats.audioBytesReceived > 0, 'audio still arrives at the app');
295 console.log('PASS the app pauses its camera for a browser on Audio only, and audio carries on');
296 await pick('auto');
297 // Back to what it sent before anything was asked, or more.
298 await wait(async () => (await arriving()).height >= Math.min(full, 181) && (await arriving()).height > 0,
299 'the app sends its camera as before once the browser is back on Auto', 20);
300 assert.equal(sample.stats.peerConnections, 1, 'changing levels keeps the same peer connection');
301 console.log('PASS the app goes back to full video for Auto, on the same connection');
302 }
303 // Chat is not replayed to a recipient whose stream is renewing (§6), and
304 // in this mode the stream renews every ten seconds, so a line that lands
305 // in a renewal's gap is lost by design. Since the camera steps above went
306 // in, chat runs well after the first renewal, and under load the gap is
307 // wide enough to catch it (2026-09-25: both subtests failed here on an
308 // unchanged tree, then passed alone and in a full run). Each direction
309 // gets three tries; a line that never arrives still fails.
310 for (let attempt = 1; ; attempt++) {
311 await openWebChat(page);
312 await page.locator('[data-chat-text]').fill('browser chat probe');
313 await page.locator('[data-chat-send]').click();
314 try {
315 await wait(() => sample?.receivedChatProbe === true, 'native displays browser chat', 8);
316 break;
317 } catch (err) {
318 if (attempt === 3) throw err;
319 console.log('RETRY browser chat probe, attempt', attempt + 1);
320 }
321 }
322 for (let attempt = 1; ; attempt++) {
323 native.stdin.write('chat\n');
324 await wait(() => chatCommandHandled, 'native handles send-chat command');
325 try {
326 await page.locator('[data-chat-log]').getByText('native chat probe', { exact: true }).first()
327 .waitFor({ timeout: 8000 });
328 break;
329 } catch (err) {
330 if (attempt === 3) throw err;
331 console.log('RETRY native chat probe, attempt', attempt + 1);
332 }
333 }
334 await wait(() => sample?.sentChatProbe === true, 'native displays accepted outgoing chat');
335 console.log('PASS chat delivered from browser to native and native to browser');
336 // Spec §15.19 across the two clients: the app's mute reaches the
337 // browser tile as the badge, the browser's reaches the app's snapshot,
338 // and both clear again.
339 {
340 const nativePeer = sample.peer;
341 const nativeMarked = () => page.evaluate((id) => {
342 const m = document.querySelector('#tiles figure[data-tile="' + id + '"] .calls-tile-muted');
343 return !!(m && !m.hidden);
344 }, nativePeer);
345 assert.equal(await nativeMarked(), false, 'the native peer starts unmuted on the browser tile');
346 native.stdin.write('mute\n');
347 await wait(nativeMarked, 'browser shows the native peer muted');
348 await page.click('#mute');
349 await wait(() => sample?.remoteMuted === 1, 'native sees the browser muted');
350 await page.click('#mute');
351 native.stdin.write('mute\n');
352 await wait(async () => !(await nativeMarked()) && sample?.remoteMuted === 0, 'both unmuted again');
353 console.log('PASS mute state crosses between native and browser both ways');
354 }
355 // The screen scenarios run after chat and not before: they take the
356 // better part of a minute, and chat is not replayed to a recipient
357 // whose stream is renewing, which in this mode is every ten seconds.
358 // Screen share does not depend on its message arriving — the m-line
359 // is classified on its own, and a stopped transceiver ends the track —
360 // so it can share the call with renewals where chat cannot.
361 // §5.4, receiving: the browser shares its screen and the app shows it
362 // as a tile of its own, captioned with the sharer's name, while the
363 // browser's camera keeps arriving on the tile it always had. Then the
364 // browser stops, and the tile goes — by the `share {on:false}` or the
365 // stopped transceiver, whichever lands first — with the camera still
366 // arriving afterwards.
367 if (mode === 'member') {
368 const name = await page.evaluate(() => document.getElementById('room')?.dataset.selfName || '');
369 assert.notEqual(name, '', 'the browser has a name for its screen to be captioned with');
370 const caption = name + '\u2019s screen';
371 await page.click('#share');
372 await wait(() => sample?.screenCaptions?.length === 1 && sample.screenCaptions[0] === caption,
373 'native captions the browser\u2019s screen with its name');
374 await wait(() => sample?.stats.remoteScreens === 1, 'the browser\u2019s screen reaches the app as a track');
375 const screenBase = sample.stats.screenFramesDecoded;
376 await wait(() => sample.stats.screenFramesDecoded > screenBase + 15, 'native decodes the browser\u2019s screen');
377 const cameraBase = sample.stats.framesDecoded;
378 await wait(() => sample.stats.framesDecoded > cameraBase + 15, 'the browser\u2019s camera keeps arriving beside its screen');
379 assert.equal(sample.stats.remoteTracks, 1, 'the screen is not taken for a second camera');
380 console.log('PASS native shows the browser\u2019s screen as its own captioned tile');
381 await page.click('#share');
382 await wait(() => sample?.screenCaptions?.length === 0 && sample.stats.remoteScreens === 0 && sample.stats.screens === 0,
383 'native removes the browser\u2019s screen when it stops');
384 const afterStop = sample.stats.framesDecoded;
385 await wait(() => sample.stats.framesDecoded > afterStop + 15, 'the browser\u2019s camera survives its screen stopping');
386 console.log('PASS native removes a stopped screen and keeps the camera');
387 }
388 // §5.4, sending: the app shares a (synthetic) screen and the browser
389 // shows it exactly as it shows another browser's — a tile of its own
390 // under shareKey, captioned with the app's name, decoding real frames
391 // while the app's camera keeps arriving. Stopping must *end* the
392 // browser's received track, which only a stopped transceiver and a
393 // renegotiation do; a message alone would leave a frozen frame behind
394 // on a browser that never got it. Then the capture ending on its own,
395 // the path the system's stop control takes, ends the share the same
396 // way.
397 if (mode === 'member') {
398 const nativePeer = sample.peer;
399 const key = nativePeer + '#share';
400 const browserState = () => page.evaluate(() => {
401 const s = window.meet.state();
402 return { shares: s.shares, frames: Object.fromEntries(s.frames) };
403 });
404 const tiles = () => page.evaluate(() => ({
405 camera: [...document.querySelectorAll('#tiles figure.calls-tile:not(.calls-tile-self):not(.calls-tile-share) figcaption span')]
406 .map(e => e.textContent.trim()).filter(Boolean)[0] || '',
407 screens: [...document.querySelectorAll('#tiles figure.calls-tile-share figcaption span')]
408 .map(e => e.textContent.trim()).filter(Boolean),
409 }));
410 for (const ending of ['screen-off', 'screen-end']) {
411 native.stdin.write('screen-on\n');
412 await wait(() => sample?.sharingScreen === true, 'native says it is sharing');
413 await wait(async () => (await browserState()).shares.includes(nativePeer), 'the browser is told whose screen is coming');
414 const { camera } = await tiles();
415 assert.notEqual(camera, '', 'the browser captions the app\u2019s camera');
416 await wait(async () => { const t = await tiles(); return t.screens.length === 1 && t.screens[0] === camera + '\u2019s screen'; },
417 'the browser captions the app\u2019s screen with its name');
418 const screenBase = (await browserState()).frames[key] || 0;
419 await wait(async () => ((await browserState()).frames[key] || 0) > screenBase + 15, 'the browser decodes the app\u2019s screen');
420 const cameraBase = (await browserState()).frames[nativePeer] || 0;
421 await wait(async () => ((await browserState()).frames[nativePeer] || 0) > cameraBase + 15,
422 'the app\u2019s camera keeps arriving beside its screen');
423 await wait(() => sample.stats.screenBytesSent > 0, 'the app counts its screen apart from its camera');
424 console.log('PASS the browser shows the app\u2019s screen as its own captioned tile');
425 const armed = await page.evaluate(() => {
426 const v = document.querySelector('#tiles figure.calls-tile-share video');
427 const track = v && v.srcObject ? v.srcObject.getVideoTracks()[0] : null;
428 if (!track) return null;
429 window.__nativeShareEnded = false;
430 track.addEventListener('ended', () => { window.__nativeShareEnded = true; });
431 return track.readyState;
432 });
433 assert.equal(armed, 'live', 'the received screen track is live and watched for its ending');
434 native.stdin.write(ending + '\n');
435 await wait(() => sample?.sharingScreen === false, 'native says it has stopped');
436 await wait(async () => (await browserState()).shares.length === 0 && (await tiles()).screens.length === 0,
437 'the browser removes the app\u2019s screen');
438 await wait(() => page.evaluate(() => window.__nativeShareEnded === true),
439 'the browser\u2019s received screen track ended rather than froze');
440 const afterStop = (await browserState()).frames[nativePeer] || 0;
441 await wait(async () => ((await browserState()).frames[nativePeer] || 0) > afterStop + 15,
442 'the app\u2019s camera survives its screen stopping');
443 console.log('PASS the app\u2019s screen ended in the browser (' + ending + ') and its camera continued');
444 }
445 }
446 if (mode === 'chat') {
447 native.stdin.write('share\n');
448 await wait(() => invitationReady, 'native member retrieves the original invitation');
449 const expectedInvitation = JSON.parse(process.env.CALLS_NATIVE_INPUT).invitation;
450 const popupPromise = context.waitForEvent('page');
451 await page.getByRole('button', { name: 'Share meeting link', exact: true }).click();
452 const sharePage = await popupPromise;
453 await sharePage.waitForLoadState();
454 assert.equal(await sharePage.locator('#invitation-link').getAttribute('href'), expectedInvitation);
455 // Exercise Copy without changing the operator's system clipboard.
456 await sharePage.evaluate(() => Object.defineProperty(navigator, 'clipboard', {
457 value: { writeText: async value => { window.copiedInvitation = value; } },
458 }));
459 await sharePage.getByRole('button', { name: 'Copy link', exact: true }).click();
460 assert.equal(await sharePage.evaluate(() => window.copiedInvitation), expectedInvitation);
461 await sharePage.screenshot({ path: fileURLToPath(new URL('../../native/build/share-web.png', import.meta.url)) });
462 await sharePage.close();
463 const plain = await browser.newContext({ javaScriptEnabled: false });
464 await plain.addCookies([{ name: process.env.CALLS_COOKIE_NAME, value: process.env.CALLS_COOKIE_A, url: origin }]);
465 const plainPage = await plain.newPage();
466 await plainPage.goto(`${origin}/m/${room}`);
467 const plainPopup = plain.waitForEvent('page');
468 await plainPage.getByRole('button', { name: 'Share meeting link', exact: true }).click();
469 const plainShare = await plainPopup;
470 await plainShare.waitForLoadState();
471 assert.equal(await plainShare.locator('#invitation-link').getAttribute('href'), expectedInvitation);
472 await plain.close();
473 console.log('PASS native sharing, web Share and Copy, and scriptless sharing preserve the invitation');
474 for (let n = 1; n <= 12; n++) {
475 await openWebChat(page);
476 await page.locator('[data-chat-text]').fill(`Incoming browser message ${n}`);
477 await page.locator('[data-chat-send]').click();
478 await wait(() => sample?.receivedChatCount === n + 1, `native receives browser message ${n}`);
479 }
480 native.stdin.write('snapshot\n');
481 await wait(() => chatSnapshotSaved, 'native chat screenshot saved');
482 native.stdin.write('share-snapshot\n');
483 await wait(() => invitationSnapshotSaved, 'native invitation screenshot saved');
484 console.log('PASS all 12 browser messages reached native chat; rendered screenshot saved');
485 } else {
486 native.stdin.write('share\n');
487 await wait(() => mode === 'guest' ? invitationRefused : invitationReady, 'native sharing follows current membership');
488 const peer = sample.peer;
489 const beforeNative = sample.stats.framesDecoded;
490 const beforeBrowser = await remoteFrames();
491 const beforeAudio = await browserAudio();
492 const beforeNativeAudio = sample.stats.audioBytesReceived;
493 // The test server renews streams every ten seconds. Observe fresh frames
494 // well after two renewals, and require the same native participation.
495 await new Promise(r => setTimeout(r, 22000));
496 await wait(async () => sample.stats.framesDecoded > beforeNative + 20 && await remoteFrames() > beforeBrowser + 20 && await browserAudio() > beforeAudio && sample.stats.audioBytesReceived > beforeNativeAudio, 'media survives stream renewal');
497 assert.equal(sample.peer, peer, 'resume must preserve the native participation');
498 console.log('PASS native/browser media continues across SSE renewals');
499 }
500 const left = new Promise((resolve, reject) => {
501 native.once('exit', code => code === 0 ? resolve() : reject(new Error('native leave failed')));
502 });
503 native.stdin.write('leave\n');
504 await Promise.race([left, new Promise((_,reject) => { setTimeout(() => reject(new Error('native leave timed out')), 5000).unref(); })]);
505 await page.waitForFunction(() => [...document.querySelectorAll('#tiles video')].filter(v => !v.muted).length === 0);
506 console.log('PASS leaving native call removes its browser tile');
507} finally {
508 native?.kill('SIGTERM');
509 await browser.close();
510}
511
512// The web call's chat is a sidebar over the picture that starts closed
513// (the call window, 2026-09-28): open it, as a person would, before
514// typing into it.
515async function openWebChat(page) {
516 await page.locator('#toggle-chat:not([hidden])').waitFor({ timeout: 10000 });
517 if ((await page.locator('#toggle-chat').getAttribute('aria-expanded')) !== 'true') {
518 await page.locator('#toggle-chat').click();
519 }
520 await page.locator('[data-chat-text]').waitFor({ state: 'visible', timeout: 5000 });
521}
522