oficina / meet Public

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

Plain git — no account needed to clone.

Download

Download this file

File too large to show in full — download it above (showing a truncated preview below).

1// call.mjs — a real call, in a real browser.
2//
3// Driven by TestCallInARealBrowser, which starts the app on a real
4// port, signs the two members in through the magic-link flow, creates
5// the meeting, and hands this script the origin, the meeting id and the
6// scenario to run.
7//
8// node test/browser/call.mjs <origin> <sqid> <scenario>
9//
10// The secrets do not travel on argv, where every process on the box can
11// read them off /proc: the session cookies and the meeting's join-link
12// token arrive in the environment, as CALLS_COOKIE_NAME, CALLS_COOKIE_A,
13// CALLS_COOKIE_B and CALLS_JOIN_TOKEN.
14//
15// One scenario per process. Every assertion prints one line; the exit
16// code is the gate.
17//
18// Two things this script cannot do for itself, and asks Go for over its
19// own stdin and stdout: read the mail recorder (a guest signs itself in
20// from the browser, and only Go can see the link that was mailed), and
21// restart the app. Both go out as a line beginning "CONTROL " and come
22// back as one line.
23//
24// Chromium's flags are not decoration. --use-fake-device-for-media-stream
25// gives every context a camera and a microphone that always work;
26// --use-fake-ui-for-media-stream answers the permission prompt;
27// --autoplay-policy=no-user-gesture-required lets a remote <video> play
28// without a click; --disable-features=WebRtcHideLocalIpsWithMdns
29// turns off mDNS candidate obfuscation, which in a container resolves to
30// nothing at all — with no ICE servers in this slice (spec §5.5), host
31// candidates are the only ones there are, and an obfuscated one connects
32// to nobody; and --auto-accept-this-tab-capture answers getDisplayMedia
33// with no picker, which the fake-ui flag does not cover (§5.4).
34import { syntheticMedia } from './synthetic-media.mjs';
35import { portraitCamera } from './portrait-camera.mjs';
36import { writeSync, mkdirSync, writeFileSync } from 'node:fs';
37import { inflateSync } from 'node:zlib';
38import { createInterface } from 'node:readline';
39import { chromium, webkit } from 'playwright';
40
41const [origin, sqid, scenario] = process.argv.slice(2);
42const cookieName = process.env.CALLS_COOKIE_NAME;
43const cookieA = process.env.CALLS_COOKIE_A;
44const cookieB = process.env.CALLS_COOKIE_B;
45const token = process.env.CALLS_JOIN_TOKEN;
46
47if (!origin || !sqid || !scenario || !cookieName || !cookieA || !cookieB) {
48 console.error('usage: call.mjs <origin> <sqid> <scenario>');
49 console.error(' with CALLS_COOKIE_NAME, CALLS_COOKIE_A, CALLS_COOKIE_B and CALLS_JOIN_TOKEN in the environment');
50 process.exit(2);
51}
52
53const GUEST = 'guest@example.com';
54// A second outsider, whose only job is to be knocking while somebody
55// else is let in: the guest-isolation filters (§4.3, ruling 9) leak
56// nothing when the guest under test is the only guest in the room, so
57// whole-branch review W-1 found this scenario passing with the filter
58// deleted. Same link, so it costs one of the five sign-ins that link
59// allows in fifteen minutes.
60const WAITER = 'waiter@example.com';
61
62// The Go driver gives up at three minutes. This gives up first, so a
63// stuck scenario prints why instead of being killed silently. unref'd:
64// it must not be the reason the process stays alive.
65const HARNESS_DEADLINE = 165000;
66
67const LAUNCH_ARGS = [
68 '--use-fake-device-for-media-stream',
69 '--use-fake-ui-for-media-stream',
70 '--autoplay-policy=no-user-gesture-required',
71 '--disable-features=WebRtcHideLocalIpsWithMdns',
72 // §5.4's half of the permission story. --use-fake-ui-for-media-stream
73 // answers getUserMedia and nothing else; getDisplayMedia has its own
74 // picker, and in headless Chromium this is what accepts it without
75 // one. It picks a fake 1280x720 monitor that really produces frames —
76 // watched here at ~20/s over a loopback peer connection — so the
77 // share scenario asserts on pixels and not only on a message. The
78 // older --auto-select-desktop-capture-source needs a real display and
79 // is not reached for.
80 '--auto-accept-this-tab-capture',
81 // The relay host in the ICE scenarios' contract does not exist, and
82 // this is what makes it not exist *here*, rather than out on the
83 // internet: the name never leaves the machine, and Chromium fails it
84 // at once instead of waiting on a resolver. Both halves matter. §13's
85 // last sentence says no test touches a relay, and a DNS lookup of the
86 // platform's own relay host is touching one; and a resolution that
87 // hangs takes Chromium's network thread with it — two runs of the ICE
88 // scenario were watched failing exactly that way, with an answer that
89 // was posted and 200'd never applied by the browser that had offered.
90 // Every other scenario runs with no ICE servers at all, so this maps
91 // a name none of them ever look up.
92 '--host-resolver-rules=MAP relay.eu-west-1.oncarlos.com ~NOTFOUND',
93];
94
95// ── the scoreboard ───────────────────────────────────────────────────
96
97const failures = [];
98
99function line(s) {
100 // Written synchronously to fd 1: an assertion is evidence, and
101 // evidence that is still in a pipe buffer when the process ends is
102 // evidence nobody has. Never a line Go would read as a control
103 // request, and never a newline inside one.
104 writeSync(1, String(s).replace(/\r?\n/g, ' | ') + '\n');
105}
106
107function check(cond, what) {
108 if (cond) {
109 line('ok ' + what);
110 return true;
111 }
112 failures.push(what);
113 line('FAIL ' + what);
114 return false;
115}
116
117// where names a page without quoting a secret. A join link and a magic
118// link both live in a URL, and these lines are written to a log that
119// outlives the run: only the first path segment goes in.
120function where(page) {
121 try {
122 return '/' + (new URL(page.url()).pathname.split('/')[1] || '');
123 } catch {
124 return '(no url)';
125 }
126}
127
128// ── the control channel back to Go ───────────────────────────────────
129
130let rl = null;
131const inbox = [];
132const waiters = [];
133
134function control(verb) {
135 if (!rl) {
136 rl = createInterface({ input: process.stdin });
137 rl.on('line', (l) => {
138 const w = waiters.shift();
139 if (w) w(l);
140 else inbox.push(l);
141 });
142 }
143 line('CONTROL ' + verb);
144 return new Promise((resolve) => {
145 if (inbox.length) resolve(inbox.shift());
146 else waiters.push(resolve);
147 });
148}
149
150// ── waiting ──────────────────────────────────────────────────────────
151
152const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
153
154// until polls rather than reading once: every state this gate asserts on
155// arrives over a network and a peer connection, and a single read is a
156// race dressed up as an assertion.
157async function until(fn, ms) {
158 const deadline = Date.now() + ms;
159 for (;;) {
160 try {
161 const got = await fn();
162 if (got) return got;
163 } catch {
164 // A page mid-navigation: try again until the deadline.
165 }
166 if (Date.now() > deadline) return null;
167 await sleep(250);
168 }
169}
170
171// stayed is until's opposite, for the assertions that are about nothing
172// happening: it polls for the whole window and returns null if the
173// predicate held throughout, or the first state that broke it. A single
174// read cannot tell "did not happen" from "has not happened yet".
175async function stayed(page, ms, pred) {
176 const deadline = Date.now() + ms;
177 for (;;) {
178 const s = await state(page);
179 if (!pred(s)) return s;
180 if (Date.now() > deadline) return null;
181 await sleep(250);
182 }
183}
184
185// bothStable is `stayed` for a pair of connections rather than one
186// page's state: it watches both for the whole window and returns the
187// first side that was not settled, or null if neither ever wobbled. A
188// renegotiation still in flight leaves signalingState somewhere other
189// than `stable`, and the shape worth catching is a rollback that never
190// comes back — which a single read taken too early and one taken too
191// late would both miss, in opposite directions.
192async function bothStable(watch, ms) {
193 const deadline = Date.now() + ms;
194 for (;;) {
195 for (const w of watch) {
196 const s = await state(w.page);
197 if (s.signaling[w.other] !== 'stable') {
198 return { label: w.label, signaling: s.signaling, connection: s.connection };
199 }
200 }
201 if (Date.now() > deadline) return null;
202 await sleep(250);
203 }
204}
205
206// frameGrowth is the only honest way to ask "is this media arriving
207// *now*" (Codex S4-6). It reads the counter, and only then starts
208// waiting for it to rise, so nothing delivered before the question was
209// asked can answer it.
210//
211// Two ways the gate got this wrong. `frames[key] > 0` reads a counter
212// `dropShare` deliberately leaves behind, so a second round of sharing
213// could pass on the first round's frames with no media at all. And a
214// baseline taken *before* a gesture is answered by the frames that
215// arrived between the snapshot and the stall the gesture caused —
216// which is exactly the shape of the camera failure this slice spent two
217// fix rounds on.
218//
219// The answer carries both numbers, because a failure message that says
220// only "no frames" cannot tell a stall from a screen that never
221// started.
222async function frameGrowth(page, key, ms) {
223 const base = (await state(page)).frames[key] || 0;
224 const grown = await until(async () => {
225 const now = (await state(page)).frames[key] || 0;
226 return now > base ? now : false;
227 }, ms);
228 return { ok: grown !== null, base, now: grown === null ? (await state(page)).frames[key] || 0 : grown };
229}
230
231// growth is frameGrowth's answer as a sentence, for the check that
232// reads it.
233function growth(g) {
234 return g.base + ' -> ' + g.now;
235}
236
237// MEDIA_WINDOWS and MEDIA_WINDOW_MS are the shape of an observation:
238// three subwindows of a second and a half, and growth required in every
239// one of them. Four and a half seconds of watching, not four and a half
240// seconds of deadline.
241const MEDIA_WINDOWS = 3;
242const MEDIA_WINDOW_MS = 1500;
243
244// observe watches a set of counters over a fixed duration and requires
245// each of them to move in *every* subwindow (Codex S4-14).
246//
247// The helper it replaces was two early-return waits in a row, which is
248// a deadline and not an observation: counters reading 0, 1, 2, 3 and
249// then frozen for ever satisfied it, because it stopped looking the
250// moment it saw an increase. The failure this whole slice is about is a
251// tile that runs for a moment after a renegotiation and then stops, so
252// "it moved once" is precisely the answer that must not count.
253//
254// `read` returns every counter at once, so streams and peers are
255// watched together rather than one after another — a check that walks
256// them in turn gives each one a different window, and the last one gets
257// its window after the others have had theirs. Lifted by name in
258// test/browser/media.test.mjs, with a burst-then-freeze control.
259async function observe(read, keys, opts) {
260 const o = opts || {};
261 const windows = o.windows === undefined ? MEDIA_WINDOWS : o.windows;
262 const windowMs = o.windowMs === undefined ? MEDIA_WINDOW_MS : o.windowMs;
263 const wait = o.sleep || sleep;
264 if (!keys.length) return { ok: false, stalled: [['(nothing was expected)', 0]], series: [] };
265 const seen = [await read()];
266 const stalled = new Map();
267 for (let w = 1; w <= windows; w++) {
268 await wait(windowMs);
269 const now = await read();
270 const before = seen[seen.length - 1];
271 for (const key of keys) {
272 if ((now[key] || 0) > (before[key] || 0)) continue;
273 if (!stalled.has(key)) stalled.set(key, w);
274 }
275 seen.push(now);
276 }
277 return {
278 ok: stalled.size === 0,
279 stalled: Array.from(stalled.entries()),
280 series: keys.map((k) => k + ' ' + seen.map((s) => s[k] || 0).join('->')),
281 };
282}
283
284// watchMedia is `observe` over what a set of sides should be receiving,
285// named explicitly by the caller rather than read back off the page:
286// a check that asks the page which screens it is showing and then
287// requires those to move cannot fail for a screen that never arrived.
288//
289// Each side is {page, label, keys} — every frame key that side should
290// be receiving, the other peer's camera included.
291async function watchMedia(sides, at, opts) {
292 for (const side of sides) {
293 const correct = await side.page.evaluate(() => [...document.querySelectorAll('.calls-tile')].every(tile => {
294 const video = tile.querySelector('video');
295 if (!video) return true;
296 const transform = new DOMMatrix(getComputedStyle(video).transform);
297 const expected = tile.classList.contains('calls-tile-self') && !tile.classList.contains('calls-tile-share') ? -1 : 1;
298 return transform.a === expected;
299 }));
300 check(correct, side.label + ': only the local camera display is mirrored');
301 }
302 const keys = [];
303 for (const side of sides) {
304 for (const key of side.keys) keys.push(side.label + ' | ' + key);
305 }
306 const read = async () => {
307 const snaps = await Promise.all(sides.map((side) => state(side.page)));
308 const out = {};
309 sides.forEach((side, i) => {
310 for (const key of side.keys) out[side.label + ' | ' + key] = snaps[i].frames[key] || 0;
311 });
312 return out;
313 };
314 const seen = await observe(read, keys, opts);
315 const ok = check(seen.ok, at + 'every stream kept arriving through ' +
316 ((opts && opts.windows) || MEDIA_WINDOWS) + ' windows of ' +
317 (((opts && opts.windowMs) || MEDIA_WINDOW_MS) / 1000) + ' s (' + seen.series.join('; ') + ')');
318 if (!ok) {
319 for (const [key, window] of seen.stalled) line(' ' + key + ' stopped in window ' + window);
320 for (const side of sides) line(' ' + (await diagnose(side.page, side.label)));
321 }
322 return ok;
323}
324
325// ── the browser ──────────────────────────────────────────────────────
326
327const browser = await chromium.launch({ args: LAUNCH_ARGS });
328
329const consoleErrors = new Map(); // label -> string[]
330// Every Content-Security-Policy refusal any page reported, in any
331// context. The rig serves the app through rastrillo's production stack
332// (calls.ServeOptions), so this is the policy a deployed instance sends,
333// and a style attribute or script it blocks is a failure of the scenario
334// even when the check that would have noticed the damage is not written.
335const cspViolations = [];
336// Every console line, not only the errors: §5.2 promises that nothing
337// about the servers is logged, and a promise about logging cannot be
338// measured against the error channel alone.
339const consoleLines = new Map(); // label -> string[]
340
341// `via` is the browser to open the context in, for the one scenario
342// (autoplay) that needs a Chromium launched under a different policy.
343// downlinkCap is §15.30's thin link, for the lowbandwidth scenario: every
344// video frame arriving in this page passes a token bucket of `kbit/s` (2 s
345// of burst) or is dropped before the decoder — and after a drop, every
346// frame until a keyframe fits, which is what a decoder downstream of a
347// lossy link has to work with, and what makes it freeze and ask for one.
348// window.__capDownlink(kbps) sets the cap (0 lifts it) and answers how many
349// video receivers are behind it; window.__capCounts is what passed and what
350// was dropped. On the main thread, through insertable streams: every sender
351// and receiver of a connection made with them must be piped, so the
352// others pass straight through. The gate's, never the page's.
353function downlinkCap() {
354 const Native = window.RTCPeerConnection;
355 if (!Native || typeof RTCRtpSender === 'undefined' || !('createEncodedStreams' in RTCRtpSender.prototype)) return;
356 const bucket = { cap: 0, tokens: 0, last: 0, lost: false, passed: 0, dropped: 0 };
357 let receivers = 0;
358 const piped = new WeakSet();
359 window.__capCounts = bucket;
360 window.__capDownlink = (kbps) => {
361 bucket.cap = Number(kbps) || 0;
362 bucket.tokens = bucket.cap * 125 * 2;
363 bucket.last = performance.now();
364 bucket.lost = false;
365 return receivers;
366 };
367 const pass = (end) => {
368 if (!end || piped.has(end)) return;
369 piped.add(end);
370 const { readable, writable } = end.createEncodedStreams();
371 readable.pipeTo(writable).catch(() => {});
372 };
373 const capped = (receiver) => {
374 if (piped.has(receiver)) return;
375 piped.add(receiver);
376 const { readable, writable } = receiver.createEncodedStreams();
377 readable.pipeThrough(new TransformStream({
378 transform(f, c) {
379 const b = bucket;
380 if (!b.cap) {
381 b.passed += 1;
382 c.enqueue(f);
383 return;
384 }
385 const now = performance.now();
386 b.tokens = Math.min(b.cap * 125 * 2, b.tokens + ((now - b.last) / 1000) * b.cap * 125);
387 b.last = now;
388 if (b.lost && f.type !== 'key') {
389 b.dropped += 1;
390 return;
391 }
392 if (b.tokens >= f.data.byteLength) {
393 b.tokens -= f.data.byteLength;
394 b.lost = false;
395 b.passed += 1;
396 c.enqueue(f);
397 } else {
398 b.lost = true;
399 b.dropped += 1;
400 }
401 },
402 })).pipeTo(writable).catch(() => {});
403 receivers += 1;
404 };
405 const insertable = (config) => Object.assign({}, config || {}, { encodedInsertableStreams: true });
406 window.RTCPeerConnection = class extends Native {
407 constructor(config, ...rest) {
408 super(insertable(config), ...rest);
409 this.addEventListener('track', (ev) => {
410 try {
411 if (ev.track.kind === 'video') capped(ev.receiver);
412 else pass(ev.receiver);
413 if (ev.transceiver) pass(ev.transceiver.sender);
414 } catch {
415 // Piped already, or a connection closing.
416 }
417 });
418 }
419 setConfiguration(config) { return super.setConfiguration(insertable(config)); }
420 addTrack(...args) {
421 const sender = super.addTrack(...args);
422 try { pass(sender); } catch {}
423 return sender;
424 }
425 addTransceiver(...args) {
426 const tx = super.addTransceiver(...args);
427 try { pass(tx.sender); } catch {}
428 return tx;
429 }
430 };
431}
432
433async function newContext(label, { cookie = null, javaScriptEnabled = true, via = browser, options = {} } = {}) {
434 const ctx = await via.newContext({ javaScriptEnabled, ...options });
435 if (cookie) {
436 await ctx.addCookies([{ name: cookieName, value: cookie, url: origin }]);
437 }
438 consoleErrors.set(label, []);
439 consoleLines.set(label, []);
440 ctx.on('page', (p) => watch(p, label));
441 // Diagnostic only, and on every context rather than the one scenario
442 // that walks getStats by hand: when a pair does not come up, what the
443 // browser thinks of its own connections is the evidence, and it
444 // cannot be collected after the fact. The trap only records what is
445 // constructed — no page behaviour changes, and nothing reads it
446 // except diagnose() and the renewal scenario's own ufrag walk.
447 if (javaScriptEnabled) await ctx.addInitScript(pcTap);
448 if (javaScriptEnabled && process.env.CALLS_SYNTHETIC_MEDIA) await ctx.addInitScript(syntheticMedia);
449 return ctx;
450}
451
452
453function watch(page, label) {
454 const errs = consoleErrors.get(label);
455 const all = consoleLines.get(label);
456 page.on('console', (m) => {
457 const text = m.text();
458 all.push(m.type() + ': ' + text);
459 if (/Content Security Policy/i.test(text)) cspViolations.push(label + ': ' + text);
460 if (m.type() === 'error') errs.push(text);
461 });
462 page.on('pageerror', (e) => {
463 const text = String(e && e.message ? e.message : e);
464 all.push('pageerror: ' + text);
465 errs.push(text);
466 });
467}
468
469function errorsFor(label) {
470 return (consoleErrors.get(label) || []).join('; ');
471}
472
473function linesFor(label) {
474 return (consoleLines.get(label) || []).join('\n');
475}
476
477// state reads window.meet.state(). frames, signaling and connection are
478// Maps in the page, so they are flattened here rather than trusting a
479// serializer to carry them.
480function state(page) {
481 return page.evaluate(() => {
482 const s = window.meet.state();
483 return {
484 peer: s.peer,
485 boot: s.boot,
486 admitted: s.admitted,
487 terminal: s.terminal,
488 rosters: s.rosters,
489 stale: s.stale,
490 peers: s.peers,
491 frames: Object.fromEntries(s.frames),
492 signaling: Object.fromEntries(s.signaling),
493 connection: Object.fromEntries(s.connection),
494 candidates: s.candidates,
495 // §5.2 and §5.3. Both are plain objects in the page — `ice`
496 // carries counts and three clocks in milliseconds since the
497 // epoch, `renewals` is keyed by peer id — so they survive
498 // page.evaluate as they are and are handed straight out.
499 ice: s.ice,
500 renewals: s.renewals,
501 // §6 and §5.4. `chat` is two counts, `shares` a list of peer ids
502 // and `sharing` a boolean, so all three survive page.evaluate as
503 // they are. `frames` above is keyed by TILE rather than by peer
504 // now, so a peer sharing a screen has a second entry under
505 // `<peer>#share`.
506 chat: s.chat,
507 sharing: s.sharing,
508 shares: s.shares,
509 // §15.30: what this tab asks of each sender, and sends each.
510 videoAsks: s.videoAsks,
511 adapt: s.adapt ? Object.fromEntries(Object.entries(s.adapt).map(([id, a]) =>
512 [id, { level: a.level, sent: a.sent, last: a.last }])) : null,
513 // §15.20. `hearing` is keyed by tile ('self' for this tab's own):
514 // what each tile says about its audio, its levels between 0 and
515 // 1, its lit bars and any notice. All plain values.
516 hearing: s.hearing,
517 audioBlocked: s.audioBlocked,
518 soundBanner: s.soundBanner,
519 noSoundFrom: s.noSoundFrom,
520 remoteMedia: s.remoteMedia,
521 // Speaker view: who has the floor, by peer id ('' before anyone).
522 speaker: s.speaker,
523 // §15.24: who this tab says it hears, and per peer whether they
524 // are still in their first moments and the words are showing.
525 hearingList: s.hearingList,
526 connecting: s.connecting,
527 // §15.28: each connection's recovery, the totals, the gate's own
528 // block, the peers' clients and every tile's note, word for word;
529 // and §15.23's words.
530 recovery: s.recovery,
531 autoRestarts: s.autoRestarts,
532 autoRebuilds: s.autoRebuilds,
533 iceBlockMangled: s.iceBlockMangled,
534 clients: s.clients,
535 notes: s.notes,
536 reconnect: s.reconnect,
537 };
538 });
539}
540
541function statusText(page) {
542 return page.evaluate(() => (document.getElementById('status') || {}).textContent || '');
543}
544
545// diagnose is what a failure prints. It is deliberately more than the
546// assertion needed: this output is a fix round's evidence, and the
547// difference between "frames stayed 0" and "frames stayed 0 while the
548// connection said connected, the video element had a stream, 640px of
549// width and was not paused" is the whole diagnosis. Only the first path
550// segment of the URL goes in — see where().
551async function diagnose(page, label) {
552 try {
553 const d = await page.evaluate(async () => {
554 const s = window.meet ? window.meet.state() : null;
555 const tiles = Array.from(document.querySelectorAll('#tiles figure')).map((f) => {
556 const v = f.querySelector('video');
557 return {
558 name: (f.querySelector('figcaption span') || {}).textContent || '',
559 note: (f.querySelector('.calls-tile-note') || {}).textContent || '',
560 // §5.4: a screen and a face are the same <figure> with
561 // different content, and only the class says which.
562 share: f.classList.contains('calls-tile-share'),
563 hasStream: !!(v && v.srcObject),
564 readyState: v ? v.readyState : null,
565 videoWidth: v ? v.videoWidth : null,
566 paused: v ? v.paused : null,
567 currentTime: v ? Number(v.currentTime.toFixed(2)) : null,
568 };
569 });
570 // Every connection this page still holds, as the browser sees it
571 // rather than as room.js reports it. `local` is the decisive one
572 // when a pair does not come up: a null localDescription with a
573 // signalingState of `stable` means this connection never
574 // negotiated at all — nothing was offered, so nothing gathered —
575 // which is a different fault from one that negotiated and could
576 // not find a pair. The rest says whether there was anything to
577 // offer: a transceiver per direction and kind, and the state of
578 // the tracks behind them.
579 //
580 // And, under each connection, what the receiver actually got. A
581 // connected transport carrying no pixels is the failure this gate
582 // meets most often, and `frames: {}` alone cannot tell its three
583 // causes apart: framesReceived at zero means nothing arrived;
584 // framesReceived climbing while framesDecoded stays flat means the
585 // decoder is the problem; freezeCount and pliCount rising mean the
586 // pixels arrived and then stopped. The receiving track's own
587 // `muted` sits beside them because a muted track decodes nothing
588 // and looks, from the tile, exactly like a dead one.
589 const pcState = [];
590 for (const pc of window.__pcs || []) {
591 try {
592 if (pc.connectionState === 'closed') continue;
593 const muted = new Map();
594 for (const r of pc.getReceivers()) {
595 if (r.track) muted.set(r.track.id, r.track.muted);
596 }
597 const inbound = [];
598 const outbound = [];
599 try {
600 const report = await pc.getStats();
601 report.forEach((v) => {
602 if (v.kind !== 'video') return;
603 if (v.type === 'inbound-rtp') {
604 inbound.push({
605 ssrc: v.ssrc,
606 framesReceived: v.framesReceived,
607 framesDecoded: v.framesDecoded,
608 framesDropped: v.framesDropped,
609 pliCount: v.pliCount,
610 freezeCount: v.freezeCount,
611 muted: muted.has(v.trackIdentifier) ? muted.get(v.trackIdentifier) : null,
612 });
613 } else if (v.type === 'outbound-rtp') {
614 // The other half of the same question. Inbound alone
615 // cannot tell "this browser stopped sending" from "this
616 // browser stopped receiving", and with two video streams
617 // per connection that is the first thing to know.
618 outbound.push({
619 ssrc: v.ssrc,
620 framesSent: v.framesSent,
621 framesEncoded: v.framesEncoded,
622 active: v.active,
623 limited: v.qualityLimitationReason,
624 });
625 }
626 });
627 } catch {
628 // getStats on a connection that is closing: nothing to add.
629 }
630 pcState.push({
631 signaling: pc.signalingState,
632 connection: pc.connectionState,
633 ice: pc.iceConnectionState,
634 gathering: pc.iceGatheringState,
635 local: pc.localDescription && pc.localDescription.type,
636 remote: pc.remoteDescription && pc.remoteDescription.type,
637 senders: pc.getSenders().length,
638 // mid/wanted/negotiated:kind. `currentDirection` is the
639 // one that decides whether media flows — `direction` is
640 // only what this side asked for — and the mid says which
641 // m-line each transceiver ended up on, which is the whole
642 // question when two peers renegotiate at once.
643 transceivers: pc.getTransceivers().map((t) => (t.mid == null ? '-' : t.mid) + ' ' +
644 t.direction + '/' + (t.currentDirection || '-') + ':' +
645 ((t.receiver && t.receiver.track && t.receiver.track.kind) ||
646 (t.sender && t.sender.track && t.sender.track.kind) || '?')),
647 tracks: pc.getSenders().filter((sn) => sn.track)
648 .map((sn) => sn.track.kind + ':' + sn.track.readyState),
649 inbound,
650 outbound,
651 });
652 } catch {
653 // A connection that went away under the walk.
654 }
655 }
656
657 // §5.4: what this tab is capturing, when it is capturing at all.
658 // Read off the sender that carries it, because room.js does not
659 // put its capture on `window` and should not; `displaySurface` is
660 // the one settings key only getDisplayMedia produces, so it is
661 // also how a display track is told from a camera. Null on every
662 // page that is not sharing.
663 let displaySurface = null;
664 for (const pc of window.__pcs || []) {
665 try {
666 if (pc.connectionState === 'closed') continue;
667 for (const sn of pc.getSenders()) {
668 if (!sn.track || sn.track.kind !== 'video' || !sn.track.getSettings) continue;
669 const settings = sn.track.getSettings();
670 if (settings && settings.displaySurface) displaySurface = settings.displaySurface;
671 }
672 } catch {
673 // Same connection, same reason.
674 }
675 }
676
677 return {
678 at: '/' + (location.pathname.split('/')[1] || ''),
679 status: (document.getElementById('status') || {}).textContent || '',
680 roomHidden: (document.getElementById('room') || {}).hidden,
681 displaySurface,
682 pcState,
683 state: s
684 ? {
685 peer: s.peer,
686 admitted: s.admitted,
687 terminal: s.terminal,
688 peers: s.peers,
689 stale: s.stale,
690 rosters: s.rosters,
691 frames: Object.fromEntries(s.frames),
692 signaling: Object.fromEntries(s.signaling),
693 connection: Object.fromEntries(s.connection),
694 ice: s.ice,
695 renewals: s.renewals,
696 // Where ICE got to, per peer. The pcState above says
697 // negotiation finished; these say whether anything was
698 // ever gathered, delivered to the hub, received or added
699 // afterwards, which is the next question and the one
700 // nothing else answers.
701 candidates: s.candidates,
702 // §6 and §5.4: lines in and out, and whose screens this
703 // page is showing. A share tile that never arrived and one
704 // that arrived and stopped read the same in `tiles` below;
705 // these two say which it was.
706 chat: s.chat,
707 sharing: s.sharing,
708 shares: s.shares,
709 // §15.30: what this page asks of each sender, and sends each.
710 videoAsks: s.videoAsks,
711 adapt: s.adapt ? Object.fromEntries(Object.entries(s.adapt).map(([id, a]) =>
712 [id, { level: a.level, sent: a.sent, cameraPaused: a.cameraPaused, why: a.why, last: a.last }])) : null,
713 }
714 : null,
715 tiles,
716 queue: Array.from(document.querySelectorAll('#knocks li')).map((li) => li.textContent),
717 };
718 });
719 return label + ' ' + JSON.stringify(d) + ' console=[' + errorsFor(label) + ']';
720 } catch (e) {
721 return label + ' could not be diagnosed: ' + e.message + ' console=[' + errorsFor(label) + ']';
722 }
723}
724
725// ── the room ─────────────────────────────────────────────────────────
726
727async function openRoom(ctx) {
728 const page = await ctx.newPage();
729 await page.goto(origin + '/m/' + sqid, { waitUntil: 'domcontentloaded' });
730 // window.meet exists only once #room is in the document and the
731 // script has run to its end.
732 await page.waitForFunction(() => !!window.meet, null, { timeout: 20000 });
733 return page;
734}
735
736// connected is admitted, with at least one live peer connection. It is
737// never asserted tighter than a couple of seconds: a pair negotiates,
738// and glare runs on nearly every one of them.
739async function waitConnected(page, ms = 25000) {
740 return until(async () => {
741 const s = await state(page);
742 return s.admitted && s.peers.length >= 1 ? s : false;
743 }, ms);
744}
745
746async function waitFrames(page, peer, ms = 25000) {
747 return until(async () => {
748 const s = await state(page);
749 return (s.frames[peer] || 0) > 0 ? s : false;
750 }, ms);
751}
752
753async function waitStatus(page, text, ms = 20000) {
754 return until(async () => ((await statusText(page)).includes(text) ? true : false), ms);
755}
756
757// A pair is asserted from both ends: a call where only one side sees
758// video is not a call.
759async function assertPair(pageA, pageB, labelA, labelB, ms = 25000) {
760 const a = await waitConnected(pageA, ms);
761 if (!check(a, labelA + ' is admitted and has a peer connection — ' + (await diagnose(pageA, labelA)))) return null;
762 const b = await waitConnected(pageB, ms);
763 if (!check(b, labelB + ' is admitted and has a peer connection — ' + (await diagnose(pageB, labelB)))) return null;
764
765 check(a.peers.includes(b.peer), labelA + ' knows ' + labelB + "'s peer id (" + a.peers + ' vs ' + b.peer + ')');
766 check(b.peers.includes(a.peer), labelB + ' knows ' + labelA + "'s peer id (" + b.peers + ' vs ' + a.peer + ')');
767
768 // Negotiation settled and the transport came up, read straight off the
769 // RTCPeerConnection. Glare runs on nearly every pair here, so a
770 // signalingState still at have-local-offer is the shape a collision
771 // that never resolved would leave behind.
772 for (const [page, label, other, otherLabel] of [
773 [pageA, labelA, b.peer, labelB],
774 [pageB, labelB, a.peer, labelA],
775 ]) {
776 const settled = await until(async () => {
777 const s = await state(page);
778 return s.signaling[other] === 'stable' && s.connection[other] === 'connected' ? s : false;
779 }, ms);
780 check(settled, label + ' settled negotiation and connected to ' + otherLabel +
781 ' — ' + (await diagnose(page, label)));
782 }
783
784 const fa = await waitFrames(pageA, b.peer, ms);
785 check(fa, labelA + ' decoded a video frame from ' + labelB + ' — ' + (await diagnose(pageA, labelA)));
786 const fb = await waitFrames(pageB, a.peer, ms);
787 check(fb, labelB + ' decoded a video frame from ' + labelA + ' — ' + (await diagnose(pageB, labelB)));
788
789 return { a, b };
790}
791
792// leave is preferred over closing the context: `leave` is posted with
793// keepalive on pagehide, and a closing context may never flush it —
794// which would leave this session's one peer slot held into whatever runs
795// next.
796async function leaveRoom(page) {
797 try {
798 await page.click('#leave', { timeout: 5000 });
799 await page.waitForURL('**/m/' + sqid + '/join', { timeout: 10000 });
800 } catch {
801 // A terminal page has its controls disabled; there is nothing to
802 // leave, and the participation is already gone.
803 }
804}
805
806// The call window (2026-09-28) keeps chat, the layout and the devices
807// behind the bar's buttons, so a scenario opens them the way a person
808// does. chatMounted is whether room.js has made the panel usable — the
809// hidden attribute it owns — which is not whether the sidebar is open.
810function chatMounted(page) {
811 return page.evaluate(() => {
812 const c = document.getElementById('chat');
813 return !!c && !c.hidden;
814 });
815}
816
817async function openChat(page) {
818 await until(() => chatMounted(page), 10000);
819 if ((await page.locator('#toggle-chat').getAttribute('aria-expanded')) !== 'true') {
820 await page.locator('#toggle-chat').click();
821 }
822 await page.locator('#chat-text').waitFor({ state: 'visible', timeout: 5000 });
823}
824
825// openTileMenu opens a tile's ⋯ menu (2026-09-29): Pin, the moves and,
826// for a member, Remove live there rather than on the tile.
827async function openTileMenu(page, key) {
828 const more = page.locator('#tiles > figure[data-tile="' + key + '"] .calls-tool-more');
829 if ((await more.getAttribute('aria-expanded')) !== 'true') {
830 await page.locator('#tiles > figure[data-tile="' + key + '"]').hover();
831 await more.click();
832 }
833 await page.locator('#tile-menu').waitFor({ state: 'visible', timeout: 3000 });
834}
835
836// chooseLayout picks Speaker or Grid from the bar's layout popover, and
837// closes it again.
838async function chooseLayout(page, mode) {
839 // On a phone the layout button is in the controls sheet.
840 if (!(await page.locator('#layout-toggle').isVisible()) && await page.locator('#more-controls').isVisible()) {
841 await page.locator('#more-controls').click();
842 }
843 if (await page.locator('#layout-panel').isHidden()) await page.locator('#layout-toggle').click();
844 await page.locator('#layout-' + mode).click();
845 if (!(await page.locator('#layout-panel').isHidden())) await page.keyboard.press('Escape');
846}
847
848// cuttableStream is the instrument the three resume gates share: A's
849// *attaching* stream GET is aborted while `cut.on` is true, and only
850// that one. The probe forms go through untouched, because the whole
851// ladder §4.5 asks the client to walk — probe, read the status, then
852// attach — depends on the probe still answering; abort that too and the
853// scenario would be testing a dead network rather than a dead stream.
854//
855// The TTL header rides along for the same reason the renewal scenario
856// sends it: a stream that has already attached is not routed again, so
857// without a short life a cut would take effect five minutes from now.
858// Two seconds here rather than the renewal scenario's production-shaped
859// six, because these scenarios cut and restore within a few seconds and
860// want the cut to bite promptly.
861async function cuttableStream(ctx, ttl = '2s') {
862 const cut = { on: false, aborted: 0, attaches: 0, probeFail: false, probesFailed: 0 };
863 await ctx.route('**/stream*', async (route) => {
864 if (route.request().url().includes('probe=1')) {
865 // probeFail is the other half of the instrument: a probe that
866 // answers 503 proves nothing about anybody's participation, and a
867 // client must not act on it (§4.5's ladder, Codex S2-12).
868 if (cut.probeFail) {
869 cut.probesFailed += 1;
870 await route.fulfill({ status: 503, contentType: 'application/json', body: '{"error":"full"}' });
871 return;
872 }
873 await route.continue();
874 return;
875 }
876 if (cut.on) {
877 cut.aborted += 1;
878 await route.abort();
879 return;
880 }
881 cut.attaches += 1;
882 await route.continue({ headers: { ...route.request().headers(), 'x-calls-test-ttl': ttl } });
883 });
884 return cut;
885}
886
887// biteCut waits until the cut has actually taken an attaching GET away.
888// Setting the flag is not the cut: the stream that is already open runs
889// to its own TTL first.
890async function biteCut(cut, ms = 20000) {
891 return until(() => (cut.aborted > 0 ? cut.aborted : false), ms);
892}
893
894// ── the relay list (spec §5.2, §5.3) ─────────────────────────────────
895
896// The two sentences §5.3 puts on a screen, quoted whole rather than
897// matched loosely: a gate that grepped for "relay" would pass on either
898// of them, and they mean different things — one says this browser cannot
899// reach the relay at all, the other that one connection's credential ran
900// out before a new one landed.
901const ICE_WARNING = 'Calls could not reach the relay. Calls may not connect until it can.';
902const ICE_EXPIRED = 'The relay credential expired for this connection.';
903const ICE_STUCK = 'Could not renew this connection through the relay.';
904
905// iceRoute is the instrument the three ICE scenarios share. Every
906// GET /m/{sqid}/ice from this context goes through it, which buys three
907// things the page cannot give: the response body (the credential never
908// reaches state(), and rightly), the header that shortens the server's
909// schedule from hours to seconds, and the ability to take the relay away
910// from the second fetch on.
911//
912// The header is added to the request rather than faked into a response,
913// because /ice rides room.js's own plain `probe` fetch and what these
914// scenarios assert on is the list the real endpoint minted. Nothing here
915// bursts /ice: it spends /signal's per-session, per-room bucket, and a
916// gate that hammered it would be measuring the rate limiter.
917//
918// The TTL is always a multiple of six seconds. The server names
919// `renewAt` at five sixths of the life and `expiresAt` at the whole of
920// it, both truncated to whole seconds, and the client schedules from the
921// difference — so a life that is not a multiple of six loses the margin
922// to the truncation.
923async function iceRoute(ctx, { ttl = null, failFrom = 0 } = {}) {
924 const seen = { requests: 0, served: 0, refused: 0, servers: [], turn: [], credentials: [] };
925 await ctx.route('**/ice*', async (route) => {
926 seen.requests += 1;
927 if (failFrom && seen.requests >= failFrom) {
928 seen.refused += 1;
929 await route.fulfill({ status: 503, contentType: 'application/json', body: '{"error":"relay"}' });
930 return;
931 }
932 const headers = { ...route.request().headers() };
933 if (ttl) headers['x-calls-test-ice-ttl'] = ttl;
934 let res;
935 try {
936 res = await route.fetch({ headers });
937 } catch {
938 // The context closing under a fetch in flight: aborting is the
939 // truthful answer, and `served` shows it never landed.
940 try { await route.abort(); } catch { /* already gone */ }
941 return;
942 }
943 const body = await res.text();
944 try {
945 const list = JSON.parse(body).iceServers || [];
946 seen.served += 1;
947 seen.servers.push(list.length);
948 for (const s of list) {
949 if (s.username) seen.turn.push(s.username);
950 if (s.credential) seen.credentials.push(s.credential);
951 }
952 } catch {
953 // Not JSON at all: `served` stays where it is, and the assertions
954 // that count it say so.
955 }
956 await route.fulfill({ response: res, body });
957 });
958 return seen;
959}
960
961// pcTap keeps a reference to every RTCPeerConnection the page builds, so
962// the gate can walk getStats itself rather than taking room.js's word
963// for the generation it is on. room.js exposes state() and not
964// connections, and rightly — a peer connection handed out on `window` is
965// one anything can close. A construct trap rather than a wrapper
966// function, so the prototype and every static stay the browser's own.
967const pcTap = () => {
968 const Real = window.RTCPeerConnection;
969 if (!Real) return;
970 // Idempotent: it is installed on every context for diagnose()'s sake,
971 // and once more by hand where a scenario walks the connections itself.
972 // Wrapping the proxy in another proxy would work and reads like a bug.
973 if (window.__pcs) return;
974 window.__pcs = [];
975 // And every ICE configuration the page actually installs, which is a
976 // different fact from the list room.js says it holds: state().ice
977 // would read the same if the constructor were handed an empty array
978 // and setConfiguration were deleted (Codex S3-5). Recorded by shape
979 // and by digest — a 32-bit FNV-1a of the usernames and credentials —
980 // so the gate can say "a different credential is installed" without
981 // anything anywhere printing one.
982 window.__iceConfigs = [];
983 const digest = (servers) => {
984 const text = servers.map((v) => (v.username || '') + '|' + (v.credential || '')).join('\n');
985 let h = 2166136261;
986 for (let i = 0; i < text.length; i++) {
987 h ^= text.charCodeAt(i);
988 h = Math.imul(h, 16777619);
989 }
990 return (h >>> 0).toString(16);
991 };
992 // `pc` is the connection's index in __pcs, so a configuration can be
993 // attributed to the connection that took it: without that, repeated
994 // updates to one connection could stand in for another left on the
995 // empty list (Codex S3-10).
996 const note = (at, pc, config) => {
997 const servers = (config && config.iceServers) || [];
998 window.__iceConfigs.push({
999 at,
1000 pc,
1001 servers: servers.length,
1002 credentialed: servers.filter((v) => v.credential).length,
1003 digest: digest(servers),
1004 });
1005 };
1006 window.RTCPeerConnection = new Proxy(Real, {
1007 construct(target, args) {
1008 const pc = Reflect.construct(target, args);
1009 const index = window.__pcs.length;
1010 window.__pcs.push(pc);
1011 note('construct', index, args[0]);
1012 const real = pc.setConfiguration && pc.setConfiguration.bind(pc);
1013 if (real) {
1014 pc.setConfiguration = (config) => {
1015 // After the real call returns, never before: a
1016 // setConfiguration that throws installs nothing, and
1017 // recording it first counted an attempt as an installation.
1018 const out = real(config);
1019 note('setConfiguration', index, config);
1020 return out;
1021 };
1022 }
1023 // Every remote description this connection applies, and the
1024 // state it was in when it applied it. That is what a rollback
1025 // looks like from outside: perfect negotiation's polite side
1026 // applies a remote *offer* while it is in `have-local-offer`, and
1027 // setRemoteDescription rolls its own offer back to do it. Nothing
1028 // in room.js records that, and a scenario about a late collision
1029 // has to be able to prove the collision happened rather than
1030 // assume a delay caused one (Codex round 2).
1031 window.__rollbacks = window.__rollbacks || [];
1032 const setRemote = pc.setRemoteDescription && pc.setRemoteDescription.bind(pc);
1033 if (setRemote) {
1034 pc.setRemoteDescription = (desc) => {
1035 const before = pc.signalingState;
1036 const out = setRemote(desc);
1037 const type = (desc && desc.type) || '';
1038 if (type === 'offer' && before === 'have-local-offer') {
1039 window.__rollbacks.push({ pc: index, at: Date.now() });
1040 }
1041 return out;
1042 };
1043 }
1044 return pc;
1045 },
1046 });
1047};
1048
1049// rollbacks is what that trap saw: one entry per remote offer applied
1050// over this side's own outstanding offer.
1051function rollbacks(page) {
1052 return page.evaluate(() => (window.__rollbacks || []).length);
1053}
1054
1055// mediaIdentity is room.js's own answer to "what is this tile bound
1056// to": the track each tile holds, the tracks its element is holding,
1057// and what the connection's receivers say. The comparison is made in
1058// the page, because object identity does not survive an evaluate().
1059function mediaIdentity(page) {
1060 return page.evaluate(() => (window.meet && window.meet.media && window.meet.media()) || {});
1061}
1062
1063// installedPerConnection folds the trap's log into "what each live
1064// connection is actually configured with": the last configuration it
1065// took, keyed by the connection's own index.
1066function installedPerConnection(configs, live) {
1067 const out = new Map();
1068 for (const c of configs) {
1069 if (live && !live.includes(c.pc)) continue;
1070 out.set(c.pc, c);
1071 }
1072 return Array.from(out.entries()).map(([pc, c]) => ({ pc, ...c }));
1073}
1074
1075// iceConfigs is what the trap recorded: one entry per configuration the
1076// page installed, in order, with a digest standing in for the
1077// credentials it carried.
1078function iceConfigs(page) {
1079 return page.evaluate(() => window.__iceConfigs || []);
1080}
1081
1082// livePcs is the indices of the connections the page still holds open,
1083// so a configuration belonging to one that has since been closed and
1084// rebuilt is not read as the current state of anything.
1085function livePcs(page) {
1086 return page.evaluate(() => (window.__pcs || [])
1087 .map((pc, i) => (pc.connectionState === 'closed' ? -1 : i))
1088 .filter((i) => i >= 0));
1089}
1090
1091// selectedUfrags is §5.3 step 2's reading taken independently of the
1092// client's: the transport names the selected pair, the pair names its
1093// local candidate, and the candidate carries the ICE generation's
1094// username fragment. A generation name, not a credential — and the same
1095// walk room.js's own proof does, so the two can be compared.
1096function selectedUfrags(page) {
1097 return page.evaluate(async () => {
1098 const out = [];
1099 for (const pc of window.__pcs || []) {
1100 if (pc.connectionState === 'closed') continue;
1101 let report = null;
1102 try {
1103 report = await pc.getStats();
1104 } catch {
1105 continue;
1106 }
1107 let pairId = null;
1108 report.forEach((r) => {
1109 if (r.type === 'transport' && r.selectedCandidatePairId) pairId = r.selectedCandidatePairId;
1110 });
1111 if (!pairId) continue;
1112 const pair = report.get(pairId);
1113 if (!pair || pair.state !== 'succeeded') continue;
1114 const local = report.get(pair.localCandidateId);
1115 out.push((local && local.usernameFragment) || '');
1116 }
1117 return out;
1118 });
1119}
1120
1121// warningRegion is §5.3 step 1's live region: whether it is there, what
1122// it says, and whether a reader would be told at all — a <p> that is
1123// hidden says nothing however much text is in it.
1124function warningRegion(page) {
1125 return page.evaluate(() => {
1126 const el = document.getElementById('ice-warning');
1127 if (!el) return null;
1128 return { text: (el.textContent || '').trim(), hidden: !!el.hidden, role: el.getAttribute('role') };
1129 });
1130}
1131
1132// tileNotes is every sentence currently under a tile. There are only
1133// four it can ever be — the expired credential, the renewal that would
1134// not land, and the two failure sentences — so the whole list goes into
1135// the assertion's message.
1136function tileNotes(page) {
1137 return page.evaluate(() =>
1138 Array.from(document.querySelectorAll('#tiles figure .calls-tile-note'))
1139 .map((n) => (n.textContent || '').trim())
1140 .filter(Boolean));
1141}
1142
1143// leakedCredential answers which minted credential, if any, turned up in
1144// a console line — by index, never by value: a gate that printed the
1145// credential it caught would be the leak it was written to catch.
1146function leakedCredential(credentials, lines) {
1147 for (let i = 0; i < credentials.length; i++) {
1148 if (credentials[i] && lines.includes(credentials[i])) return i;
1149 }
1150 return -1;
1151}
1152
1153// ── the guest ────────────────────────────────────────────────────────
1154
1155// signInAsGuest is the whole outsider path from spec §3.2, driven in the
1156// browser: follow the emailed link signed out, ask for a sign-in link,
1157// and click the one that was actually mailed.
1158async function signInAsGuest(ctx, address = GUEST) {
1159 const member = await newContext('configure waiting room', { cookie: cookieA });
1160 await member.request.post(origin + '/meetings/' + sqid + '/settings', {
1161 headers: { Origin: origin }, form: { waiting_room: 'on' },
1162 });
1163 await member.close();
1164 const page = await ctx.newPage();
1165 await page.goto(origin + '/j/' + token, { waitUntil: 'domcontentloaded' });
1166 // The invitation page's way to sign in is the bar's corner (shared
1167 // chrome R2: guests get the same "Sign in" as anyone signed out).
1168 if (page.url().includes('/j/')) await page.locator('[estilo-bar-signin]').click();
1169 check(page.url().startsWith(origin + '/signin'),
1170 'the link sends a signed-out outsider to sign in (at ' + where(page) + ')');
1171
1172 // The smart door's email way (rastrillo's screen in estilo's door):
1173 // while the join cookie is live the door opens on the email field, with
1174 // Oficina ID only under Other ways (Paul's ruling, 2026-11-22).
1175 check(await page.locator('a[href^="/signin/oficina"]').count() === 0,
1176 'the join cookie\'s door opens on email, not Oficina ID (at ' + where(page) + ')');
1177 await page.fill('input[name="address"]', address);
1178 // Sent is /signin?sent=1&attempt=<id>: the attempt names the address on
1179 // the page and differs every time, the same shape for anybody.
1180 const sent = (u) => u.pathname === '/signin' && u.searchParams.get('sent') === '1' && u.searchParams.has('attempt');
1181 await Promise.all([
1182 page.waitForURL(sent, { timeout: 15000 }),
1183 page.click('form[rst-signin-form] button[type="submit"]'),
1184 ]);
1185 const at = new URL(page.url());
1186 check(sent(at) && [...at.searchParams.keys()].sort().join(',') === 'attempt,sent',
1187 'asking for a sign-in link gives the same answer every time (at ' + where(page) + ')');
1188
1189 const link = await control('guest-link ' + address);
1190 // The emailed link opens the confirm door, which spends nothing (a
1191 // mail scanner's fetch must not); its one Sign in button POSTs the
1192 // link back, and that is what signs in.
1193 await page.goto(link, { waitUntil: 'domcontentloaded' });
1194 check(await page.locator('input[name="address"]').count() === 0 &&
1195 await page.locator('form[action="/auth/verify"] button[type="submit"]').count() === 1,
1196 'the emailed link opens the confirm door: one Sign in button, no address field (at ' + where(page) + ')');
1197 await Promise.all([
1198 page.waitForURL((u) => !u.pathname.startsWith('/auth/verify'), { timeout: 15000, waitUntil: 'domcontentloaded' }),
1199 page.click('form[action="/auth/verify"] button[type="submit"]'),
1200 ]);
1201 check(page.url() === origin + '/m/' + sqid + '/join',
1202 'the emailed link lands the guest on this meeting (at ' + where(page) + ')');
1203 await page.close();
1204}
1205
1206// admitKnock clicks the Admit button on the queue entry with this
1207// display name. The queue holds more than one entry in the guest
1208// scenario, and clicking the first one would admit whoever happened to
1209// knock first.
1210async function admitKnock(page, name) {
1211 const lis = page.locator('#knocks li');
1212 const n = await lis.count();
1213 for (let i = 0; i < n; i++) {
1214 const who = ((await lis.nth(i).locator('span').first().textContent()) || '').trim();
1215 if (who === name) {
1216 await lis.nth(i).locator('button').click();
1217 return true;
1218 }
1219 }
1220 return false;
1221}
1222
1223// previewState is the holding screen's own <video>: whether it has a
1224// stream, and whether that stream is actually being decoded and played.
1225function previewState(page) {
1226 return page.evaluate(() => {
1227 const v = document.getElementById('preview');
1228 if (!v) return null;
1229 return { hasStream: !!v.srcObject, width: v.videoWidth, time: v.currentTime, paused: v.paused };
1230 });
1231}
1232
1233// remoteTile reads the first remote tile's <video> the same way, for the
1234// scenarios about a tile that is playing or not.
1235function remoteTile(page) {
1236 return page.evaluate(() => {
1237 const v = document.querySelector('#tiles figure:not(.calls-tile-self) video');
1238 if (!v) return null;
1239 return { hasStream: !!v.srcObject, width: v.videoWidth, time: v.currentTime, paused: v.paused };
1240 });
1241}
1242
1243// queueNames is the admission queue as this page has it, which is
1244// exactly what the server decided this page may know: room.js fills it
1245// from knock, knock-gone and roster.waiting and from nothing else.
1246async function queueNames(page) {
1247 return page.evaluate(() =>
1248 Array.from(document.querySelectorAll('#knocks li span')).map((s) => s.textContent.trim()));
1249}
1250
1251// ── the chat panel and the share tile ────────────────────────────────
1252
1253// chatLog is the panel's log as a reader has it: who each line is from,
1254// what it says, and whether the panel drew it as this tab's own. Read
1255// through the class names chat.js builds rather than through the ids, so
1256// the panel keeps the freedom its own report claims — a host may rename
1257// every `chat-*` id, and the classes are what the stylesheet and this
1258// gate both hang on.
1259function chatLog(page) {
1260 return page.evaluate(() =>
1261 Array.from(document.querySelectorAll('[data-chat-log] li')).map((li) => ({
1262 name: ((li.querySelector('.chat-name') || {}).textContent || '').trim(),
1263 text: ((li.querySelector('.chat-text') || {}).textContent || '').trim(),
1264 self: li.classList.contains('chat-line-self'),
1265 })));
1266}
1267
1268// selfName is the server's word for the person in this tab, read off
1269// the room element the page was rendered with. Not off their own tile:
1270// that caption is this name with " (you)" appended, and what the other
1271// contexts see — the name on an arriving chat line, the name in
1272// "<name>’s screen" — is the name without it. Reading the dataset is
1273// reading exactly what room.js reads.
1274function selfName(page) {
1275 return page.evaluate(() => {
1276 const root = document.getElementById('room');
1277 return root ? (root.dataset.selfName || '') : '';
1278 });
1279}
1280
1281// shareTiles is every screen currently on this page: its caption and
1282// whether the <video> under it has anything to play. A tile with a
1283// caption and no stream is exactly what `share {on:true}` draws before
1284// the media arrives, so the two are read together and never conflated.
1285function shareTiles(page) {
1286 return page.evaluate(() =>
1287 Array.from(document.querySelectorAll('#tiles figure.calls-tile-share')).map((f) => {
1288 const v = f.querySelector('video');
1289 return {
1290 name: ((f.querySelector('figcaption span') || {}).textContent || '').trim(),
1291 hasStream: !!(v && v.srcObject),
1292 width: v ? v.videoWidth : null,
1293 paused: v ? v.paused : null,
1294 };
1295 }));
1296}
1297
1298// capturedSurface is what this tab is actually sending as a screen:
1299// `displaySurface` off the settings of a video track it has out, which
1300// is the one key only getDisplayMedia produces. A tab sharing its
1301// camera down the share m-line would answer null here, and every other
1302// assertion about sharing would still hold — which is what makes this
1303// worth reading. Null on a page that is not sharing.
1304function capturedSurface(page) {
1305 return page.evaluate(() => {
1306 for (const pc of window.__pcs || []) {
1307 try {
1308 if (pc.connectionState === 'closed') continue;
1309 for (const sn of pc.getSenders()) {
1310 if (!sn.track || sn.track.kind !== 'video' || !sn.track.getSettings) continue;
1311 const settings = sn.track.getSettings();
1312 if (settings && settings.displaySurface) return settings.displaySurface;
1313 }
1314 } catch {
1315 // A connection that went away under the walk.
1316 }
1317 }
1318 return null;
1319 });
1320}
1321
1322// shareControl is the Share button's three cues at once. Colour is not
1323// one of them (AGENTS.md), so what is read here is the word and the
1324// attribute a screen reader announces — never the outline.
1325function shareControl(page) {
1326 return page.evaluate(() => {
1327 const b = document.getElementById('share');
1328 if (!b) return null;
1329 const s = document.getElementById('share-state');
1330 return {
1331 pressed: b.getAttribute('aria-pressed'),
1332 state: s ? (s.textContent || '').trim() : null,
1333 disabled: !!b.disabled,
1334 };
1335 });
1336}
1337
1338// tileMarks is what spec §15.19 draws on one peer's tile, read the way a
1339// person reads it: whether the muted badge and the camera-off cover are
1340// showing, and the words each carries — the words, not the colour or
1341// the icon, being the part AGENTS.md makes the contract.
1342function tileMarks(page, key) {
1343 return page.evaluate((k) => {
1344 const f = document.querySelector('#tiles figure[data-tile="' + k + '"]');
1345 if (!f) return null;
1346 const muted = f.querySelector('.calls-tile-muted');
1347 const off = f.querySelector('.calls-tile-off');
1348 const shown = (el) => !!(el && !el.hidden && el.getClientRects().length);
1349 return {
1350 muted: shown(muted),
1351 mutedText: muted ? (muted.textContent || '').trim() : '',
1352 cameraOff: shown(off),
1353 offText: off ? (off.textContent || '').trim() : '',
1354 caption: ((f.querySelector('figcaption') || {}).textContent || '').trim(),
1355 };
1356 }, key);
1357}
1358
1359// refuseFirstPlay is an init script: the first unmuted play() on the
1360// page is refused the way a blocking autoplay policy refuses it, and the
1361// element held paused until a later play() — which only a gesture
1362// should be asking for.
1363const refuseFirstPlay = () => {
1364 const real = HTMLMediaElement.prototype.play;
1365 let refused = 0;
1366 let blocked = null;
1367 // A rejected promise on its own is not what a blocking autoplay
1368 // policy does: the element also stays paused. Rejecting and
1369 // letting the element play anyway (its own `autoplay` attribute
1370 // does that, and the launch flag permits it) left every "the
1371 // gesture started the video" assertion true before the gesture
1372 // as well, which is the hole Codex S2-9 is about. So the refusal
1373 // pauses the element and keeps it paused until the gesture.
1374 const holdPaused = (e) => {
1375 if (blocked === e.target) e.target.pause();
1376 };
1377 HTMLMediaElement.prototype.play = function play() {
1378 if (!this.muted && refused < 1) {
1379 refused += 1;
1380 blocked = this;
1381 this.autoplay = false;
1382 this.pause();
1383 this.addEventListener('play', holdPaused);
1384 return Promise.reject(new DOMException('autoplay refused', 'NotAllowedError'));
1385 }
1386 if (blocked === this) {
1387 blocked = null;
1388 this.removeEventListener('play', holdPaused);
1389 }
1390 return real.apply(this, arguments);
1391 };
1392};
1393
1394// ── the self view (2026-10-21) ───────────────────────────────────────
1395//
1396// selfTile reads this tab's own tile: whether its <video> has the local
1397// stream, whether that stream's camera is live, and whether the element
1398// is actually playing it — its clock, its paused flag, its size — plus
1399// what the tile says when it is not, and where the tile is (the floating
1400// picture-in-picture, the stage or the filmstrip).
1401function selfTile(page) {
1402 return page.evaluate(() => {
1403 const f = document.querySelector('#tiles figure.calls-tile-self');
1404 if (!f) return null;
1405 const v = f.querySelector('video');
1406 const s = v && v.srcObject;
1407 const track = s && s.getVideoTracks ? s.getVideoTracks()[0] : null;
1408 const cover = f.querySelector('.calls-tile-paused');
1409 return {
1410 pip: f.classList.contains('calls-tile-pip'),
1411 stage: f.hasAttribute('data-stage'),
1412 hasStream: !!s,
1413 track: track ? track.readyState + (track.enabled ? '' : '/disabled') : 'none',
1414 paused: v.paused,
1415 time: Math.round(v.currentTime * 100) / 100,
1416 width: v.videoWidth,
1417 ready: v.readyState,
1418 cover: cover && !cover.hidden ? cover.textContent : '',
1419 };
1420 });
1421}
1422
1423// selfAdvancing waits for the self view to be playing a live camera:
1424// not paused, a picture with a size, and its clock moving between two
1425// reads. Paused and a still clock is the black tile of 2026-10-21.
1426async function selfAdvancing(page, ms = 12000) {
1427 return until(async () => {
1428 const one = await selfTile(page);
1429 if (!one || one.paused || !one.width || !one.track.startsWith('live')) return false;
1430 await sleep(600);
1431 const two = await selfTile(page);
1432 return two && !two.paused && two.time > one.time ? two : false;
1433 }, ms);
1434}
1435
1436// selfPainted is whether the self view is a picture on screen and not a
1437// black box: a screenshot of the middle of its <video>, and how much of
1438// it is neither black nor the tile's own #212121. This is the half the
1439// element's clock cannot answer — a compositor that draws a playing
1440// video as black (WebKit and a backdrop-filter or a transform, say).
1441async function selfPainted(page, which = '#tiles figure.calls-tile-self video') {
1442 const box = await page.locator(which).boundingBox();
1443 if (!box || box.width < 20 || box.height < 20) return { lit: 0, box };
1444 const clip = { x: box.x + box.width * 0.2, y: box.y + box.height * 0.15, width: box.width * 0.6, height: box.height * 0.5 };
1445 const img = decodePNG(await shoot(page, { clip }));
1446 let lit = 0;
1447 for (let j = 0; j < img.height; j++) {
1448 for (let i = 0; i < img.width; i++) {
1449 const c = img.rgb(i, j);
1450 const far = (v) => Math.max(Math.abs(c[0] - v), Math.abs(c[1] - v), Math.abs(c[2] - v)) > 24;
1451 if (far(0) && far(33)) lit++;
1452 }
1453 }
1454 return { lit: Math.round((lit / (img.width * img.height)) * 100) / 100 };
1455}
1456
1457// shoot is page.screenshot for a page whose CSP the gate is watching. In
1458// WebKit, Playwright's screenshot puts a stylesheet of its own into the
1459// page, and WebKit holds that to the page's CSP and reports it — a
1460// violation by the instrument, not by the page. Only those reports, and
1461// only the ones that arrive while the screenshot is being taken, are
1462// taken back off the books.
1463const PLAYWRIGHT_STYLE = /^Refused to apply a stylesheet because its hash, its nonce, or 'unsafe-inline' does not appear in the style-src directive/;
1464async function shoot(page, opts) {
1465 const csp = cspViolations.length;
1466 const errs = new Map(Array.from(consoleErrors, ([label, list]) => [label, list.length]));
1467 const img = await page.screenshot({ caret: 'initial', ...opts });
1468 await sleep(200);
1469 const keep = (list, from, text) => {
1470 const tail = list.splice(from);
1471 list.push(...tail.filter((line) => !PLAYWRIGHT_STYLE.test(text(line))));
1472 };
1473 keep(cspViolations, csp, (line) => line.replace(/^[^:]*: /, ''));
1474 for (const [label, from] of errs) keep(consoleErrors.get(label), from, (line) => line);
1475 return img;
1476}
1477
1478// gumTap keeps every stream the room opened, so a scenario can end its
1479// tracks as the system would.
1480const gumTap = () => {
1481 window.__gum = [];
1482 const md = navigator.mediaDevices;
1483 if (!md || !md.getUserMedia) return;
1484 const gum = md.getUserMedia.bind(md);
1485 md.getUserMedia = async (c) => {
1486 if (window.__noCamera && c && c.video) throw new DOMException('camera busy', 'NotReadableError');
1487 const s = await gum(c);
1488 window.__gum.push(s);
1489 return s;
1490 };
1491 window.__noCamera = !!sessionStorage.getItem('calls.test.noCamera');
1492};
1493
1494// hideAndShow is the tab going to the background and coming back, the
1495// way native-webkit.mjs plays it: visibilityState is the page's to
1496// believe, and the event is what room.js listens for. `during` is what
1497// the system does meanwhile.
1498async function hideAndShow(page, during) {
1499 await page.evaluate((what) => {
1500 if (what.pauseAll) for (const v of document.querySelectorAll('video')) v.pause();
1501 if (what.endTracks) for (const s of window.__gum) for (const t of s.getTracks()) t.stop();
1502 let shown = 'hidden';
1503 Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => shown });
1504 Object.defineProperty(document, 'hidden', { configurable: true, get: () => shown === 'hidden' });
1505 document.dispatchEvent(new Event('visibilitychange'));
1506 window.__show = () => {
1507 shown = 'visible';
1508 document.dispatchEvent(new Event('visibilitychange'));
1509 };
1510 }, during);
1511 await sleep(1000);
1512 await page.evaluate(() => window.__show());
1513}
1514
1515// glowOf is the warm rim on a tile's name label as it is drawn (0.4.3):
1516// whether it is lit, its --lvl and --on, the shadow the browser computed
1517// for the label's ::after from them, and the most opaque of that shadow's
1518// layers — plus whether anything of the ring or the meter it replaced is
1519// left on the tile.
1520function glowOf(page, key) {
1521 return page.evaluate((k) => {
1522 const figure = document.querySelector('#tiles figure[data-tile="' + k + '"]');
1523 const label = figure && figure.querySelector('.calls-tile-name');
1524 if (!label) return null;
1525 const style = getComputedStyle(label);
1526 const shadow = getComputedStyle(label, '::after').boxShadow;
1527 let alpha = 0;
1528 for (const m of shadow.matchAll(/rgba?\(([^)]*)\)/g)) {
1529 const parts = m[1].split(',').map(Number);
1530 alpha = Math.max(alpha, parts.length === 4 ? parts[3] : 1);
1531 }
1532 return {
1533 lit: label.dataset.glow === 'on',
1534 glow: Number(style.getPropertyValue('--lvl')) || 0,
1535 on: Number(style.getPropertyValue('--on')) || 0,
1536 shadow,
1537 alpha,
1538 // The old ring was an inset shadow on the figure (a floating self
1539 // view's own drop shadow is not one).
1540 ring: figure.classList.contains('calls-tile-speaking') || /inset/.test(getComputedStyle(figure).boxShadow),
1541 meter: !!figure.querySelector('.calls-meter'),
1542 };
1543 }, key);
1544}
1545
1546// speakInto replaces a page's microphone on every connection with a
1547// steady tone, loud enough to be speech to the glow's gate. Chromium's
1548// fake microphone only beeps, and a beep is exactly the brief noise the
1549// glow is built to ignore. stopSpeaking puts the microphone back.
1550function speakInto(page) {
1551 return page.evaluate(async () => {
1552 const ctx = new AudioContext();
1553 const osc = ctx.createOscillator();
1554 const gain = ctx.createGain();
1555 gain.gain.value = 0.3;
1556 osc.frequency.value = 220;
1557 const dest = ctx.createMediaStreamDestination();
1558 osc.connect(gain).connect(dest);
1559 osc.start();
1560 await ctx.resume();
1561 const tone = dest.stream.getAudioTracks()[0];
1562 window.__toneRestore = [];
1563 for (const pc of window.__pcs || []) {
1564 for (const sn of pc.getSenders()) {
1565 if (sn.track && sn.track.kind === 'audio') {
1566 window.__toneRestore.push([sn, sn.track]);
1567 await sn.replaceTrack(tone);
1568 }
1569 }
1570 }
1571 window.__toneCtx = ctx;
1572 return window.__toneRestore.length;
1573 });
1574}
1575function stopSpeaking(page) {
1576 return page.evaluate(async () => {
1577 for (const [sn, track] of window.__toneRestore || []) await sn.replaceTrack(track);
1578 if (window.__toneCtx) await window.__toneCtx.close();
1579 window.__toneRestore = [];
1580 });
1581}
1582
1583function mediaLive(page) {
1584 return page.evaluate(() => ((document.getElementById('media-live') || {}).textContent || '').trim());
1585}
1586
1587// ── ink ───────────────────────────────────────────────────────────────
1588//
1589// Where a glyph's ink is, read off a screenshot the way Paul read the
1590// Mac bar's (0.4.1): the centroid of the pixels brighter than the pane
1591// under them, weighted by how much brighter. The PNG is Chromium's own
1592// (8-bit, RGB or RGBA, not interlaced), so a decoder this small reads it.
1593
1594function decodePNG(buf) {
1595 let at = 8;
1596 let width = 0, height = 0, type = 0;
1597 const idat = [];
1598 while (at < buf.length) {
1599 const len = buf.readUInt32BE(at);
1600 const kind = buf.toString('latin1', at + 4, at + 8);
1601 const body = buf.subarray(at + 8, at + 8 + len);
1602 if (kind === 'IHDR') {
1603 width = body.readUInt32BE(0);
1604 height = body.readUInt32BE(4);
1605 if (body[8] !== 8 || body[12] !== 0) throw new Error('decodePNG: not 8-bit non-interlaced');
1606 type = body[9];
1607 } else if (kind === 'IDAT') idat.push(body);
1608 at += 12 + len;
1609 }
1610 const bpp = type === 6 ? 4 : type === 2 ? 3 : 0;
1611 if (!bpp) throw new Error('decodePNG: colour type ' + type);
1612 const raw = inflateSync(Buffer.concat(idat));
1613 const stride = width * bpp;
1614 const px = Buffer.alloc(height * stride);
1615 for (let y = 0; y < height; y++) {
1616 const f = raw[y * (stride + 1)];
1617 const row = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1));
1618 for (let x = 0; x < stride; x++) {
1619 const a = x >= bpp ? px[y * stride + x - bpp] : 0;
1620 const b = y > 0 ? px[(y - 1) * stride + x] : 0;
1621 const c = x >= bpp && y > 0 ? px[(y - 1) * stride + x - bpp] : 0;
1622 let v = row[x];
1623 if (f === 1) v += a;
1624 else if (f === 2) v += b;
1625 else if (f === 3) v += (a + b) >> 1;
1626 else if (f === 4) {
1627 const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c);
1628 v += pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
1629 }
1630 px[y * stride + x] = v & 255;
1631 }
1632 }
1633 const lum = (x, y) => {
1634 const i = y * stride + x * bpp;
1635 return 0.2126 * px[i] + 0.7152 * px[i + 1] + 0.0722 * px[i + 2];
1636 };
1637 const rgb = (x, y) => {
1638 const i = y * stride + x * bpp;
1639 return [px[i], px[i + 1], px[i + 2]];
1640 };
1641 return { width, height, lum, rgb };
1642}
1643
1644// contrastOnWhite is WCAG's contrast ratio of white text on a colour.
1645function contrastOnWhite([r, g, b]) {
1646 const lin = (c) => {
1647 const v = c / 255;
1648 return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
1649 };
1650 const L = 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
1651 return 1.05 / (L + 0.05);
1652}
1653
1654// sampleColour is the average colour of a small square of the page as
1655// drawn, in page CSS pixels.
1656async function sampleColour(page, x, y, size = 4) {
1657 const img = decodePNG(await page.screenshot({ clip: { x: x - size / 2, y: y - size / 2, width: size, height: size } }));
1658 const sum = [0, 0, 0];
1659 for (let j = 0; j < img.height; j++) {
1660 for (let i = 0; i < img.width; i++) {
1661 const c = img.rgb(i, j);
1662 sum[0] += c[0]; sum[1] += c[1]; sum[2] += c[2];
1663 }
1664 }
1665 const n = img.width * img.height;
1666 return sum.map((v) => Math.round(v / n));
1667}
1668
1669// inkCentroid screenshots `box` (page CSS pixels, at the page's own
1670// device scale) and returns the ink's vertical centroid in page CSS
1671// pixels, or null if there was no ink.
1672async function inkCentroid(page, box, scale = 1) {
1673 const pad = 2;
1674 const clip = { x: box.x - pad, y: box.y - pad, width: box.width + 2 * pad, height: box.height + 2 * pad };
1675 const img = decodePNG(await page.screenshot({ clip }));
1676 let floor = 255;
1677 for (let y = 0; y < img.height; y++) for (let x = 0; x < img.width; x++) floor = Math.min(floor, img.lum(x, y));
1678 let total = 0, moment = 0;
1679 for (let y = 0; y < img.height; y++) {
1680 for (let x = 0; x < img.width; x++) {
1681 const w = Math.max(0, img.lum(x, y) - floor - 8);
1682 total += w;
1683 moment += w * (y + 0.5);
1684 }
1685 }
1686 if (!total) return null;
1687 return clip.y + moment / total / scale;
1688}
1689
1690// ── the scenarios ────────────────────────────────────────────────────
1691
1692const run = {
1693 async guestdirect() {
1694 const member = await newContext('settings owner', { cookie: cookieA, javaScriptEnabled: false });
1695 const settings = await member.newPage();
1696 await settings.goto(origin + '/settings');
1697 check(!(await settings.getByLabel('Require sign-in to join').isChecked()), 'new meeting defaults permit guests');
1698 check(!(await settings.getByLabel('Enable waiting room').isChecked()), 'waiting room defaults off');
1699 await settings.screenshot({ path: '/tmp/calls-settings.png', fullPage: true });
1700 await member.close();
1701 const guest = await newContext('anonymous guest');
1702 const page = await guest.newPage();
1703 await page.goto(origin + '/j/' + token);
1704 check((await page.getByRole('link', { name: 'Join in the app' }).getAttribute('href')).startsWith('oficina-calls://join?'), 'invitation offers the native app');
1705 await page.getByLabel('Your name').fill('Visitor');
1706 await Promise.all([
1707 page.waitForURL('**/m/' + sqid + '/join'),
1708 page.getByRole('button', { name: 'Continue in browser' }).click(),
1709 ]);
1710 check(await page.getByRole('link', { name: 'Join in the app' }).count() === 1, 'holding screen offers the native app');
1711 await page.locator('#join').click();
1712 check(await until(async () => (await state(page)).admitted, 20000), 'anonymous guest joins directly without sign-in or admission');
1713 await guest.close();
1714 },
1715 // The holding screen reaches real hardware: it enumerates devices,
1716 // previews one, and lets the person in.
1717 async devices() {
1718 const ctx = await newContext('member A', { cookie: cookieA });
1719 const page = await ctx.newPage();
1720 await page.goto(origin + '/m/' + sqid + '/join', { waitUntil: 'domcontentloaded' });
1721
1722 const revealed = await until(async () => !(await page.locator('#devices').isHidden()), 10000);
1723 check(revealed, 'the holding screen reveals its devices block');
1724
1725 const options = await until(async () => {
1726 const n = await page.locator('#pick-camera option').count();
1727 return n > 0 ? n : false;
1728 }, 10000);
1729 check(options, 'the camera picker lists at least one camera (got ' + options + ')');
1730
1731 const enabled = await until(async () => await page.locator('#join').isEnabled(), 10000);
1732 check(enabled, 'the Join button is enabled within ten seconds — status: ' + (await page.locator('#status').textContent()));
1733
1734 // A truthy srcObject was all this used to ask (Codex S2-9), and a
1735 // preview that never decoded a pixel satisfies that. Real dimensions
1736 // and a clock that moves are what "previewing" means.
1737 const preview = await until(async () => {
1738 const p = await previewState(page);
1739 return p && p.hasStream && p.width > 0 ? p : false;
1740 }, 15000);
1741 check(preview, 'the preview is decoding real frames (' + JSON.stringify(preview || (await previewState(page))) + ')');
1742 check(await page.locator('#preview').evaluate(video => new DOMMatrix(getComputedStyle(video).transform).a === -1), 'the holding camera preview is mirrored');
1743 if (preview) {
1744 const rising = await until(async () => {
1745 const p = await previewState(page);
1746 return p && p.time > preview.time ? p : false;
1747 }, 10000);
1748 check(rising, 'the preview is playing rather than holding one frame (' +
1749 JSON.stringify(rising || (await previewState(page))) + ')');
1750 }
1751
1752 check(errorsFor('member A') === '', 'no console errors on the holding screen (' + errorsFor('member A') + ')');
1753 await ctx.close();
1754 },
1755
1756 // Spec §15.20: the holding screen's audio test. The fake microphone
1757 // beeps, so the microphone test says it works; the test sound plays;
1758 // and the playback test records, plays back and throws the recording
1759 // away — with no request leaving the page while it does, which is the
1760 // promise the section makes in words.
1761 async audiotest() {
1762 const ctx = await newContext('member A', { cookie: cookieA });
1763 const page = await ctx.newPage();
1764 const requests = [];
1765 page.on('request', (r) => {
1766 const body = r.postDataBuffer();
1767 requests.push({ method: r.method(), path: where({ url: () => r.url() }), body: body ? body.length : 0 });
1768 });
1769 await page.goto(origin + '/m/' + sqid + '/join', { waitUntil: 'domcontentloaded' });
1770 const ready = await until(async () => await page.locator('#join').isEnabled(), 15000);
1771 check(ready, 'the holding screen is ready — status: ' + (await page.locator('#status').textContent()));
1772 check(await page.locator('#audio-test').isVisible(), 'the audio test is offered');
1773 await page.click('#audio-test summary');
1774 const test = () => page.evaluate(() => window.meetDevices.audioTest());
1775 const sent = requests.length;
1776
1777 await page.click('#test-mic');
1778 const working = await until(async () => {
1779 const t = await test();
1780 return t.mic.verdict === 'working' ? t : false;
1781 }, 10000);
1782 check(working, 'the microphone test hears the microphone (' + JSON.stringify(working || (await test())) + ')');
1783 const micText = ((await page.locator('#mic-result').textContent()) || '').trim();
1784 check(micText === 'Your microphone is working.', 'and says so in words (' + micText + ')');
1785 const micMeter = await until(async () => {
1786 const v = await page.locator('#mic-level').evaluate((m) => m.value);
1787 return v > 0 ? v : false;
1788 }, 5000);
1789 check(micMeter, 'its meter moves (' + micMeter + ')');
1790
1791 await page.click('#test-speaker');
1792 const played = await until(async () => {
1793 const t = await test();
1794 return t.speaker.played && t.speaker.peak > 0 ? t : false;
1795 }, 10000);
1796 check(played, 'the test sound plays, and its meter moves (' + JSON.stringify(played || (await test())) + ')');
1797 const speakerText = await until(async () => {
1798 const t = ((await page.locator('#speaker-result').textContent()) || '').trim();
1799 return t.startsWith('Played a test sound through') ? t : false;
1800 }, 5000);
1801 check(speakerText, 'and says where it played (' + speakerText + ')');
1802 check(await test().then((t) => t.running === '' && t.mic.verdict === 'working'),
1803 'starting one test stopped the other');
1804
1805 await page.click('#test-loopback');
1806 const recording = await until(async () => ((await test()).loopback.phase === 'recording' ? true : false), 5000);
1807 check(recording, 'the playback test records');
1808 const back = await until(async () => {
1809 const t = await test();
1810 return t.loopback.phase === 'played' || t.loopback.phase === 'failed' ? t : false;
1811 }, 20000);
1812 check(back && back.loopback.phase === 'played' && back.loopback.bytes > 0 && back.loopback.peak > 0,
1813 'records, and plays it back (' + JSON.stringify(back || (await test())) + ')');
1814 const loopText = ((await page.locator('#loopback-result').textContent()) || '').trim();
1815 check(loopText === 'That is how you sound to the others. The recording has been thrown away.',
1816 'and says so (' + loopText + ')');
1817 const released = await page.evaluate(() => {
1818 const a = document.getElementById('test-audio');
1819 return !a.srcObject;
1820 });
1821 check(released, 'the player lets go of the recording');
1822
1823 const during = requests.slice(sent);
1824 const carried = during.filter((r) => r.method !== 'GET' || r.body > 0);
1825 check(carried.length === 0, 'nothing left the page while the tests ran (' + JSON.stringify(carried) + ')');
1826
1827 // And Join still works afterwards.
1828 await page.click('#join');
1829 const joined = await until(async () => page.url().endsWith('/m/' + sqid), 10000);
1830 check(joined, 'Join still goes to the room (' + where(page) + ')');
1831 await page.waitForFunction(() => !!window.meet, null, { timeout: 20000 }).catch(() => {});
1832 await leaveRoom(page);
1833
1834 check(errorsFor('member A') === '', 'no console errors (' + errorsFor('member A') + ')');
1835 await ctx.close();
1836 },
1837
1838 // The whole media path in one assertion each way: getUserMedia, join,
1839 // roster, perfect negotiation, trickle ICE, a decoded frame.
1840 async call() {
1841 const ctxA = await newContext('member A', { cookie: cookieA });
1842 const ctxB = await newContext('member B', { cookie: cookieB });
1843 const pageA = await openRoom(ctxA);
1844 const pageB = await openRoom(ctxB);
1845
1846 await assertPair(pageA, pageB, 'member A', 'member B');
1847
1848 check(errorsFor('member A') === '', 'no console errors in A (' + errorsFor('member A') + ')');
1849 check(errorsFor('member B') === '', 'no console errors in B (' + errorsFor('member B') + ')');
1850
1851 await leaveRoom(pageA);
1852 await leaveRoom(pageB);
1853 await ctxA.close();
1854 await ctxB.close();
1855 },
1856
1857 // Spec §15.19: one peer mutes and turns the camera off, and the other
1858 // sees both on that peer's tile — in words, not only an icon — and
1859 // hears about it through the polite live region. Then the watcher
1860 // leaves and comes back, and the state is on the tile from the roster
1861 // alone, with no event to carry it: that is the late-joiner and resume
1862 // path, which is the reason the state lives in the roster at all.
1863 async mute() {
1864 const ctxA = await newContext('member A', { cookie: cookieA });
1865 const ctxB = await newContext('member B', { cookie: cookieB });
1866 const pageA = await openRoom(ctxA);
1867 let pageB = await openRoom(ctxB);
1868
1869 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
1870 if (!pair) return;
1871 const a = pair.a.peer;
1872 const nameA = await selfName(pageA);
1873
1874 // Both report on admission, so each knows the other is on — known,
1875 // not merely unknown — before anybody touches anything.
1876 const known = await until(async () => {
1877 const s = await pageB.evaluate(() => window.meet.state().remoteMedia);
1878 return s[a] && s[a].muted === false && s[a].cameraOff === false ? s : false;
1879 }, 10000);
1880 check(known, 'B has A’s first report: on, not unknown (' + JSON.stringify(known) + ')');
1881 const before = await tileMarks(pageB, a);
1882 check(before && !before.muted && !before.cameraOff, 'A’s tile starts with neither mark (' + JSON.stringify(before) + ')');
1883
1884 await pageA.click('#mute');
1885 const muted = await until(async () => {
1886 const m = await tileMarks(pageB, a);
1887 return m && m.muted ? m : false;
1888 }, 10000);
1889 check(muted, 'B sees A’s muted badge after A mutes (' + JSON.stringify(muted || (await tileMarks(pageB, a))) + ')');
1890 check(muted && /muted/i.test(muted.mutedText), 'the badge says Muted in words (' + (muted && muted.mutedText) + ')');
1891 check(muted && !muted.cameraOff, 'muting alone does not cover the video');
1892 const said = await until(async () => {
1893 const t = await mediaLive(pageB);
1894 return t.includes('muted their microphone') ? t : false;
1895 }, 5000);
1896 check(said && said.startsWith(nameA), 'B’s live region says so, politely, by name (' + (said || (await mediaLive(pageB))) + ')');
1897 const selfMark = await tileMarks(pageA, 'self');
1898 check(selfMark && selfMark.muted, 'A’s own tile carries the badge too (' + JSON.stringify(selfMark) + ')');
1899
1900 await pageA.click('#camera');
1901 const off = await until(async () => {
1902 const m = await tileMarks(pageB, a);
1903 return m && m.cameraOff ? m : false;
1904 }, 10000);
1905 check(off, 'B sees A’s camera-off cover (' + JSON.stringify(off || (await tileMarks(pageB, a))) + ')');
1906 check(off && off.offText === 'Camera off', 'the cover says Camera off in words (' + (off && off.offText) + ')');
1907 check(off && off.muted, 'and A is still muted');
1908 // For a person to look at, as guestdirect keeps the settings page.
1909 await pageB.screenshot({ path: '/tmp/calls-mute.png', fullPage: true });
1910
1911 // The watcher comes back: the roster alone must carry both.
1912 await leaveRoom(pageB);
1913 await pageB.close();
1914 pageB = await openRoom(ctxB);
1915 const again = await until(async () => {
1916 const s = await state(pageB);
1917 if (!s.admitted || !s.peers.includes(a)) return false;
1918 const m = await tileMarks(pageB, a);
1919 return m && m.muted && m.cameraOff ? m : false;
1920 }, 25000);
1921 check(again, 'B, rejoining, reads both marks from the roster (' + JSON.stringify(again || (await tileMarks(pageB, a))) + ')');
1922 check((await mediaLive(pageB)) === '', 'a state learned from the roster is not announced as news');
1923
1924 // And back on: both marks go.
1925 await pageA.click('#mute');
1926 await pageA.click('#camera');
1927 const clear = await until(async () => {
1928 const m = await tileMarks(pageB, a);
1929 return m && !m.muted && !m.cameraOff ? m : false;
1930 }, 10000);
1931 check(clear, 'unmuting and turning the camera on clears both marks (' + JSON.stringify(clear || (await tileMarks(pageB, a))) + ')');
1932 const fb = await waitFrames(pageB, a);
1933 check(fb, 'B is still decoding A’s video afterwards');
1934
1935 check(errorsFor('member A') === '', 'no console errors in A (' + errorsFor('member A') + ')');
1936 check(errorsFor('member B') === '', 'no console errors in B (' + errorsFor('member B') + ')');
1937 await leaveRoom(pageA);
1938 await leaveRoom(pageB);
1939 await ctxA.close();
1940 await ctxB.close();
1941 },
1942
1943 // Spec §15.20: the meters and the five-second rule, in a real call.
1944 // Chromium's fake microphone beeps about once a second, so a working
1945 // call is one where every meter moves and nobody is ever called
1946 // silent. Then the far side mutes, which is the Muted badge and not a
1947 // silence; and then it goes silent *without* muting — its microphone
1948 // track disabled under it, the shape of a microphone that hears
1949 // nothing — which is "No sound from …" here and "… isn't getting any
1950 // sound from you" there, over the report.
1951 async meters() {
1952 const ctxA = await newContext('member A', { cookie: cookieA });
1953 const ctxB = await newContext('member B', { cookie: cookieB });
1954 const pageA = await openRoom(ctxA);
1955 const pageB = await openRoom(ctxB);
1956
1957 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
1958 if (!pair) return;
1959 const a = pair.a.peer;
1960 const b = pair.b.peer;
1961 const nameA = await selfName(pageA);
1962 const nameB = await selfName(pageB);
1963 const hearingOf = async (page, key) => ((await state(page)).hearing || {})[key] || null;
1964
1965 const heard = await until(async () => {
1966 const h = await hearingOf(pageB, a);
1967 return h && h.peak > 0 && h.shown === 'meter' ? h : false;
1968 }, 15000);
1969 check(heard, 'B reads a level above zero for A (' + JSON.stringify(heard || (await hearingOf(pageB, a))) + ')');
1970 // The glow replaced the ring and the meter (0.3.7): neither is drawn.
1971 const plain = await glowOf(pageB, a);
1972 check(plain && !plain.ring && !plain.meter,
1973 'no ring round A’s tile and no meter beside the name on B (' + JSON.stringify(plain) + ')');
1974 const self = await until(async () => {
1975 const h = await hearingOf(pageA, 'self');
1976 return h && h.peak > 0 ? h : false;
1977 }, 15000);
1978 check(self, 'A’s own tile reads its microphone (' + JSON.stringify(self || (await hearingOf(pageA, 'self'))) + ')');
1979 // A speaks — a steady tone rather than the fake microphone's beep —
1980 // and A's name glows on B, and on A's own tile.
1981 const toned = await speakInto(pageA);
1982 check(toned > 0, 'A’s microphone is replaced by a tone (' + toned + ' senders)');
1983 const lit = await until(async () => {
1984 const g = await glowOf(pageB, a);
1985 const h = await hearingOf(pageB, a);
1986 return g && g.lit && g.glow > 0 && g.on === 1 && g.alpha > 0.1 && h && h.speaking && h.glow > 0 ? { g, h } : false;
1987 }, 10000);
1988 check(lit, 'A’s name glows on B while A speaks (' + JSON.stringify(lit || (await glowOf(pageB, a))) + ')');
1989 const selfLit = await until(async () => {
1990 const g = await glowOf(pageA, 'self');
1991 return g && g.lit && g.glow > 0 ? g : false;
1992 }, 10000);
1993 check(selfLit, 'and on A’s own tile (' + JSON.stringify(selfLit || (await glowOf(pageA, 'self'))) + ')');
1994 // For a look at it: CALLS_GLOW_SNAPSHOTS=<dir> keeps B's room, glowing.
1995 if (process.env.CALLS_GLOW_SNAPSHOTS) {
1996 await pageB.screenshot({ path: process.env.CALLS_GLOW_SNAPSHOTS + '/web-room-glowing.png', fullPage: true });
1997 }
1998 const ringless = await glowOf(pageB, a);
1999 check(ringless && !ringless.ring, 'speaking draws no ring round the tile (' + JSON.stringify(ringless) + ')');
2000 // Silence — the track disabled, so packets carry nothing — puts it
2001 // out, over the release rather than at once: --on waits for --lvl to
2002 // fall, then every layer of the rim is transparent. (The fake
2003 // microphone's beep, back, would light it again: Chromium's audioLevel
2004 // lingers.)
2005 await pageA.evaluate(() => {
2006 for (const [sn] of window.__toneRestore || []) if (sn.track) sn.track.enabled = false;
2007 });
2008 const out = await until(async () => {
2009 const g = await glowOf(pageB, a);
2010 return g && !g.lit && g.glow === 0 && g.on === 0 && g.shadow !== 'none' && g.alpha === 0 ? g : false;
2011 }, 10000);
2012 await stopSpeaking(pageA);
2013 check(out, 'and it goes out when A stops (' + JSON.stringify(out || (await glowOf(pageB, a))) + ')');
2014
2015 // A beeping microphone is not a silent one, on either side, for
2016 // longer than the rule's five seconds.
2017 const falseAlarm = await stayed(pageB, 7000, (s) =>
2018 s.hearing[a] && s.hearing[a].shown === 'meter' && !s.noSoundFrom.length && !s.hearing.self.text);
2019 check(!falseAlarm, 'a working microphone is never called silent (' +
2020 JSON.stringify(falseAlarm && { hearing: falseAlarm.hearing, noSoundFrom: falseAlarm.noSoundFrom }) + ')');
2021
2022 // Muted is the badge, not a meter and not a silence.
2023 await pageA.click('#mute');
2024 const muted = await until(async () => {
2025 const h = await hearingOf(pageB, a);
2026 const m = await tileMarks(pageB, a);
2027 return h && h.shown === 'muted' && m && m.muted ? { h, m } : false;
2028 }, 10000);
2029 check(muted, 'B shows A as Muted once A mutes (' + JSON.stringify(muted || (await hearingOf(pageB, a))) + ')');
2030 const glowGone = await until(async () => {
2031 const g = await glowOf(pageB, a);
2032 return g && !g.lit && g.glow === 0 ? g : false;
2033 }, 3000);
2034 check(glowGone, 'muted, nothing glows (' + JSON.stringify(glowGone || (await glowOf(pageB, a))) + ')');
2035 const mutedQuiet = await stayed(pageB, 6500, (s) =>
2036 s.hearing[a] && s.hearing[a].shown === 'muted' && s.hearing[a].text === '' && !s.noSoundFrom.length);
2037 check(!mutedQuiet, 'a muted peer is never "No sound from" (' + JSON.stringify(mutedQuiet && mutedQuiet.hearing[a]) + ')');
2038 const selfMuted = await hearingOf(pageA, 'self');
2039 check(selfMuted && selfMuted.shown === 'muted' && selfMuted.text === '',
2040 'and muted, A’s own tile warns of nothing (' + JSON.stringify(selfMuted) + ')');
2041 await pageA.click('#mute');
2042 const back = await until(async () => {
2043 const h = await hearingOf(pageB, a);
2044 return h && h.shown === 'meter' ? h : false;
2045 }, 10000);
2046 check(back, 'unmuting brings live sound back (' + JSON.stringify(back || (await hearingOf(pageB, a))) + ')');
2047
2048 // Silence without muting: the microphone track is disabled under the
2049 // call, so packets keep flowing and carry nothing, and A's report
2050 // still says unmuted — which is exactly a microphone that hears
2051 // nothing, as far as anybody listening can tell.
2052 await pageA.evaluate(() => {
2053 for (const pc of window.__pcs || []) {
2054 for (const sn of pc.getSenders()) if (sn.track && sn.track.kind === 'audio') sn.track.enabled = false;
2055 }
2056 });
2057 const silent = await until(async () => {
2058 const s = await state(pageB);
2059 const h = s.hearing[a];
2060 return h && h.shown === 'silent' && s.noSoundFrom.includes(a) ? { h, noSoundFrom: s.noSoundFrom } : false;
2061 }, 15000);
2062 check(silent, 'B calls A silent after five flat seconds (' + JSON.stringify(silent || (await hearingOf(pageB, a))) + ')');
2063 check(silent && silent.h.text === 'No sound from ' + nameA,
2064 'in words, by name (' + (silent && silent.h.text) + ')');
2065 const told = await until(async () => {
2066 const h = await hearingOf(pageA, b);
2067 return h && /isn.t getting any sound from you\./.test(h.notice) ? h : false;
2068 }, 10000);
2069 check(told, 'A’s tile for B says B is getting no sound from A (' + JSON.stringify(told || (await hearingOf(pageA, b))) + ')');
2070 check(told && told.notice === nameB + ' isn\u2019t getting any sound from you.',
2071 'naming B (' + (told && told.notice) + ')');
2072 const saidA = await mediaLive(pageA);
2073 check(/isn.t getting any sound from you/.test(saidA), 'and A’s live region says so once (' + saidA + ')');
2074
2075 // Sound again ends it on both sides.
2076 await pageA.evaluate(() => {
2077 for (const pc of window.__pcs || []) {
2078 for (const sn of pc.getSenders()) if (sn.track && sn.track.kind === 'audio') sn.track.enabled = true;
2079 }
2080 });
2081 const cleared = await until(async () => {
2082 const s = await state(pageB);
2083 return s.hearing[a] && s.hearing[a].shown === 'meter' && !s.noSoundFrom.length ? s.hearing[a] : false;
2084 }, 10000);
2085 check(cleared, 'sound again clears "No sound" on B (' + JSON.stringify(cleared || (await hearingOf(pageB, a))) + ')');
2086 const untold = await until(async () => {
2087 const h = await hearingOf(pageA, b);
2088 return h && h.notice === '' ? h : false;
2089 }, 10000);
2090 check(untold, 'and the notice on A (' + JSON.stringify(untold || (await hearingOf(pageA, b))) + ')');
2091
2092 check(errorsFor('member A') === '', 'no console errors in A (' + errorsFor('member A') + ')');
2093 check(errorsFor('member B') === '', 'no console errors in B (' + errorsFor('member B') + ')');
2094 await leaveRoom(pageA);
2095 await leaveRoom(pageB);
2096 await ctxA.close();
2097 await ctxB.close();
2098 },
2099
2100 // Space toggles mute (the keyboard path to the same toggle as the
2101 // button, so the peer's badge follows over the same `media` report).
2102 // Held Space is one toggle, not a flicker; Space on the focused Mute
2103 // button is the button's own press, once; and Space in the chat
2104 // composer is a space in the message, with the microphone left alone.
2105 async spacemute() {
2106 const ctxA = await newContext('member A', { cookie: cookieA });
2107 const ctxB = await newContext('member B', { cookie: cookieB });
2108 const pageA = await openRoom(ctxA);
2109 const pageB = await openRoom(ctxB);
2110
2111 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
2112 if (!pair) return;
2113 const a = pair.a.peer;
2114 const pressed = () => pageA.evaluate(() => document.getElementById('mute').getAttribute('aria-pressed'));
2115 const known = await until(async () => {
2116 const s = await pageB.evaluate(() => window.meet.state().remoteMedia);
2117 return s[a] && s[a].muted === false ? s : false;
2118 }, 10000);
2119 check(known, 'B has A’s first report, unmuted (' + JSON.stringify(known) + ')');
2120 // Whether the page kept the key: read after room.js's own listener.
2121 await pageA.evaluate(() => {
2122 window.__spacePrevented = [];
2123 window.addEventListener('keydown', (ev) => {
2124 if (ev.key === ' ') window.__spacePrevented.push(ev.defaultPrevented);
2125 });
2126 });
2127
2128 await pageA.evaluate(() => document.activeElement && document.activeElement.blur());
2129 await pageA.keyboard.press('Space');
2130 const muted = await until(async () => {
2131 const m = await tileMarks(pageB, a);
2132 return m && m.muted ? m : false;
2133 }, 10000);
2134 check(muted, 'Space mutes A, and B sees the badge (' + JSON.stringify(muted || (await tileMarks(pageB, a))) + ')');
2135 check((await pressed()) === 'true', 'A’s Mute button says pressed');
2136 const said = await until(async () => {
2137 const t = await mediaLive(pageA);
2138 return t === 'Microphone muted.' ? t : false;
2139 }, 5000);
2140 check(said, 'A’s live region says so (' + (await mediaLive(pageA)) + ')');
2141 check((await pageA.evaluate(() => window.__spacePrevented.slice(-1)[0])) === true,
2142 'a handled Space is prevented, so the page does not scroll');
2143
2144 // Held: the first press toggles, the repeat is swallowed.
2145 await pageA.keyboard.down('Space');
2146 await pageA.keyboard.down('Space');
2147 await pageA.keyboard.up('Space');
2148 check((await pressed()) === 'false', 'a held Space unmutes once and does not flicker back');
2149 const unmuted = await until(async () => {
2150 const m = await tileMarks(pageB, a);
2151 return m && !m.muted ? m : false;
2152 }, 10000);
2153 check(unmuted, 'B sees A unmuted (' + JSON.stringify(unmuted || (await tileMarks(pageB, a))) + ')');
2154
2155 // Space on the focused button: the button's own press, exactly once.
2156 await pageA.focus('#mute');
2157 await pageA.keyboard.press('Space');
2158 check(await until(async () => (await pressed()) === 'true', 3000),
2159 'Space on the focused Mute button presses it once — twice would leave it unmuted');
2160
2161 // Space in the chat composer is typing.
2162 check(await until(() => chatMounted(pageA), 10000), 'A’s chat panel is up');
2163 await openChat(pageA);
2164 await pageA.click('#chat-text');
2165 await pageA.keyboard.type('two words');
2166 const typed = await pageA.inputValue('#chat-text');
2167 check(typed === 'two words', 'Space in the chat box types a space (' + JSON.stringify(typed) + ')');
2168 check((await pressed()) === 'true', 'and leaves the microphone as it was');
2169 check((await pageA.evaluate(() => window.__spacePrevented.slice(-1)[0])) === false,
2170 'a Space that is typing is not prevented');
2171 const stillMuted = await tileMarks(pageB, a);
2172 check(stillMuted && stillMuted.muted, 'B still sees A muted');
2173
2174 check(errorsFor('member A') === '', 'no console errors in A (' + errorsFor('member A') + ')');
2175 check(errorsFor('member B') === '', 'no console errors in B (' + errorsFor('member B') + ')');
2176 await leaveRoom(pageA);
2177 await leaveRoom(pageB);
2178 await ctxA.close();
2179 await ctxB.close();
2180 },
2181
2182 // Changing a device without leaving the call. The panel opens, the
2183 // microphone and then the camera are chosen again from the list, and
2184 // the far side's media is watched across both.
2185 //
2186 // Picking the same device again is the point rather than a weakness
2187 // of the test. What is under test is the swap — getUserMedia, a
2188 // replaceTrack on every connection's sender, the local stream rebuilt
2189 // under the self tile — and none of that cares whether the id it is
2190 // handed differs from the one already in use. Chromium's fake capture
2191 // offers one camera and one microphone, so a "different" device here
2192 // would be a second fake and not a second assertion.
2193 //
2194 // The assertion that matters is the negative one: a swap must not
2195 // cost the call anything. replaceTrack does not renegotiate, so a
2196 // regression that reached for addTrack, or that stopped the old track
2197 // before the new one was on the senders, shows up here as the far
2198 // side's frames stopping.
2199 async switching() {
2200 const ctxA = await newContext('member A', { cookie: cookieA });
2201 const ctxB = await newContext('member B', { cookie: cookieB });
2202 const pageA = await openRoom(ctxA);
2203 const pageB = await openRoom(ctxB);
2204
2205 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
2206 if (!pair) {
2207 await ctxA.close();
2208 await ctxB.close();
2209 return;
2210 }
2211
2212 // room.js reveals the button only where there is an enumeration
2213 // behind it, so its being visible is itself the feature detection
2214 // working.
2215 const shown = await until(async () => await pageA.locator('#devices-toggle').isVisible(), 10000);
2216 check(shown, 'the Devices button is revealed in the room');
2217 await pageA.click('#devices-toggle');
2218 check(await pageA.locator('#room-devices').isVisible(), 'the device panel opens');
2219 check(await pageA.locator('#devices-toggle').getAttribute('aria-expanded') === 'true',
2220 'the Devices button reports itself expanded');
2221
2222 const mics = await until(async () => {
2223 const n = await pageA.locator('#pick-mic option').count();
2224 return n > 0 ? n : false;
2225 }, 10000);
2226 check(mics, 'the room lists at least one microphone (got ' + mics + ')');
2227 const cameras = await pageA.locator('#pick-camera option').count();
2228 check(cameras > 0, 'the room lists at least one camera (got ' + cameras + ')');
2229
2230 const sides = [
2231 { page: pageB, label: 'member B', keys: [pair.a.peer] },
2232 { page: pageA, label: 'member A', keys: [pair.b.peer] },
2233 ];
2234 for (const [selector, what] of [['#pick-mic', 'microphone'], ['#pick-camera', 'camera']]) {
2235 const value = await pageA.locator(selector + ' option').first().getAttribute('value');
2236 await pageA.selectOption(selector, value);
2237 // The swap is asynchronous behind the change event: one
2238 // getUserMedia and a replaceTrack per connection. Nothing in the
2239 // page announces it finishing, so what is waited for is the thing
2240 // that must be true afterwards — a live local track of that kind
2241 // — and then the media is watched over a duration.
2242 const live = await until(async () => await pageA.evaluate((kind) => {
2243 const tracks = (window.meet && window.meet.local && window.meet.local()) || [];
2244 const of = tracks.filter((t) => t.kind === kind);
2245 return of.length === 1 && of[0].state === 'live' && of[0].chosen;
2246 }, what === 'microphone' ? 'audio' : 'video'), 15000);
2247 check(live, 'member A holds exactly one live ' + what + ' track after the switch');
2248
2249 check((await pageA.locator('#device-note').textContent() || '').trim() === '',
2250 'switching the ' + what + ' reported no trouble (' +
2251 (await pageA.locator('#device-note').textContent()) + ')');
2252
2253 await watchMedia(sides, 'after the ' + what + ' was switched: ');
2254 }
2255
2256 // Three changes with nothing awaited between them, which is one
2257 // person clicking through a list rather than choosing from it. Each
2258 // is a getUserMedia and a replaceTrack across the mesh, and run at
2259 // once they would be two loops writing to the same senders — what
2260 // every peer then receives decided by whichever device opened
2261 // fastest. Serialised, the last click wins and the media never
2262 // stops; the failure this catches is the middle run stopping a
2263 // track the senders were still holding, which reads at the far end
2264 // as the call simply ending.
2265 const camera = await pageA.locator('#pick-camera option').first().getAttribute('value');
2266 await Promise.all([
2267 pageA.selectOption('#pick-camera', camera),
2268 pageA.selectOption('#pick-camera', camera),
2269 pageA.selectOption('#pick-camera', camera),
2270 ]);
2271 const settled = await until(async () => await pageA.evaluate(() => {
2272 const tracks = (window.meet && window.meet.local && window.meet.local()) || [];
2273 const video = tracks.filter((t) => t.kind === 'video');
2274 return video.length === 1 && video[0].state === 'live';
2275 }), 20000);
2276 check(settled, 'member A holds exactly one live camera after three switches at once — ' +
2277 JSON.stringify(await pageA.evaluate(() => window.meet.local())));
2278 await watchMedia(sides, 'after three switches at once: ');
2279
2280 check(errorsFor('member A') === '', 'no console errors in A (' + errorsFor('member A') + ')');
2281 check(errorsFor('member B') === '', 'no console errors in B (' + errorsFor('member B') + ')');
2282
2283 await leaveRoom(pageA);
2284 await leaveRoom(pageB);
2285 await ctxA.close();
2286 await ctxB.close();
2287 },
2288
2289 // §5.4 and §13's slice-4 sentence: "the higher-id context shares its
2290 // screen and the lower receives a second video track, then stops, the
2291 // received track ends, the share tile is removed and the camera track
2292 // keeps flowing."
2293 //
2294 // Every clause of that is an assertion here, and the camera is watched
2295 // across both halves rather than only at the end: a share that
2296 // renegotiated the call into silence and then gave it back would pass
2297 // a check made once, at rest.
2298 async share() {
2299 const ctxA = await newContext('member A', { cookie: cookieA });
2300 const ctxB = await newContext('member B', { cookie: cookieB });
2301 const pageA = await openRoom(ctxA);
2302 const pageB = await openRoom(ctxB);
2303 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
2304 if (!pair) {
2305 await ctxA.close();
2306 await ctxB.close();
2307 return;
2308 }
2309
2310 // §5.1's own tie-break, read the same way room.js reads it. §13
2311 // names the higher id as the one that shares, and it is the
2312 // interesting half: the higher id is the impolite peer, so the
2313 // offer its new transceiver causes is the one that does not roll
2314 // back on a collision.
2315 const aHigher = String(pair.a.peer) > String(pair.b.peer);
2316 const sharer = aHigher
2317 ? { page: pageA, label: 'member A', peer: pair.a.peer }
2318 : { page: pageB, label: 'member B', peer: pair.b.peer };
2319 const viewer = aHigher
2320 ? { page: pageB, label: 'member B', peer: pair.b.peer }
2321 : { page: pageA, label: 'member A', peer: pair.a.peer };
2322 line('the higher-id context is ' + sharer.label);
2323
2324 // The caption is built from the roster's name and the typographic
2325 // apostrophe room.js writes, not from a name typed here: the whole
2326 // point of the `share` message is that no label crosses the wire.
2327 const name = await selfName(sharer.page);
2328 check(name !== '', 'the sharer has a name for its screen to be captioned with (' + name + ')');
2329 const caption = name + '’s screen';
2330 const key = sharer.peer + '#share';
2331
2332 const resting = await shareControl(sharer.page);
2333 check(resting && resting.pressed === 'false' && resting.state === 'Off' && !resting.disabled,
2334 'the Share button rests off, in a word and in aria-pressed (' + JSON.stringify(resting) + ')');
2335 check((await shareTiles(viewer.page)).length === 0,
2336 'nobody is showing a screen before anybody shares one');
2337
2338 await sharer.page.click('#share');
2339
2340 // The message first: `shares` follows the tile, and the tile follows
2341 // the `share {on:true}` — which is what lets a name appear before
2342 // the media and is why these are three assertions and not one.
2343 const announced = await until(async () => {
2344 const s = await state(viewer.page);
2345 return s.shares.includes(sharer.peer) ? s : false;
2346 }, 5000);
2347 check(announced, 'the other context is told whose screen is coming within five seconds — ' +
2348 (await diagnose(viewer.page, viewer.label)));
2349
2350 const captioned = await until(async () => {
2351 const tiles = await shareTiles(viewer.page);
2352 return tiles.length === 1 && tiles[0].name === caption ? tiles : false;
2353 }, 5000);
2354 check(captioned, 'a second tile says whose screen it is (' +
2355 JSON.stringify(await shareTiles(viewer.page)) + ', want ' + JSON.stringify(caption) + ')');
2356
2357 const pixels = await frameGrowth(viewer.page, key, 10000);
2358 check(pixels.ok, 'the screen is decoding real frames and not only labelled (' +
2359 growth(pixels) + ') — ' + (await diagnose(viewer.page, viewer.label)));
2360
2361 // From a baseline taken now that the transition has settled, not
2362 // from one taken before the gesture: frames delivered between a
2363 // pre-gesture snapshot and a rollback stall would satisfy a
2364 // pre-gesture baseline while the camera was already dead (Codex
2365 // S4-6).
2366 const cameraOn = await frameGrowth(viewer.page, sharer.peer, 10000);
2367 check(cameraOn.ok, 'the camera kept flowing across the renegotiation (' +
2368 growth(cameraOn) + ')');
2369
2370 // And still flowing through a window rather than at an instant, in
2371 // both directions: the failure this slice is about is a tile that
2372 // runs for a moment after a renegotiation and then stops, which a
2373 // check that returns on the first new frame cannot tell from
2374 // health (Codex's S4-6 gap). Both sides, because the sharer's own
2375 // view of the viewer's camera is renegotiated just as hard and was
2376 // never looked at.
2377 await watchMedia([
2378 { page: viewer.page, label: viewer.label, keys: [sharer.peer, key] },
2379 { page: sharer.page, label: sharer.label, keys: [viewer.peer] },
2380 ], 'after the share started: ');
2381
2382 const pressed = await shareControl(sharer.page);
2383 check(pressed && pressed.pressed === 'true' && pressed.state === 'On',
2384 'the Share button says it is on, in both cues (' + JSON.stringify(pressed) + ')');
2385 check((await state(sharer.page)).sharing === true, 'the sharing tab says it is sharing');
2386 check((await shareTiles(sharer.page)).length === 0,
2387 'the sharer is not shown its own screen back (' + JSON.stringify(await shareTiles(sharer.page)) + ')');
2388
2389 // The received track's own ending, armed before anything stops.
2390 // `ended` fires once and never again, so a listener installed after
2391 // the click would be an assertion about a moment already gone — and
2392 // the track object is kept on the page too, because the tile that
2393 // was holding it is about to be removed and the failure message
2394 // wants its readyState.
2395 const armed = await viewer.page.evaluate(() => {
2396 const v = document.querySelector('#tiles figure.calls-tile-share video');
2397 const track = v && v.srcObject ? v.srcObject.getVideoTracks()[0] : null;
2398 if (!track) return null;
2399 window.__shareEnded = [];
2400 window.__shareTrack = track;
2401 track.addEventListener('ended', () => window.__shareEnded.push(track.id));
2402 return { id: track.id, readyState: track.readyState };
2403 });
2404 check(armed && armed.readyState === 'live',
2405 'the received screen track is live, and watched for its ending (' + JSON.stringify(armed) + ')');
2406
2407 // Paul, 2026-09-28: the sharing notice carries its own Stop
2408 // sharing button, named for a screen reader, reachable from the
2409 // keyboard — and this stop goes through it, so the button is
2410 // proved to do exactly what the bar's toggle does.
2411 const notice = await sharer.page.evaluate(() => {
2412 const n = document.getElementById('share-notice');
2413 const b = document.getElementById('share-stop');
2414 return n && b ? {
2415 shown: !n.hidden && n.getClientRects().length > 0,
2416 text: (n.querySelector('.calls-share-notice-row span') || {}).textContent || '',
2417 label: b.getAttribute('aria-label'),
2418 words: (b.textContent || '').trim(),
2419 focusable: b.tabIndex >= 0 && !b.disabled,
2420 } : null;
2421 });
2422 check(notice && notice.shown && notice.text === 'You are sharing your screen' &&
2423 notice.label === 'Stop sharing your screen' && notice.words === 'Stop sharing' && notice.focusable,
2424 'the sharing notice shows, with its own Stop sharing button (' + JSON.stringify(notice) + ')');
2425 await sharer.page.focus('#share-stop');
2426 await sharer.page.keyboard.press('Enter');
2427
2428 const removed = await until(async () => {
2429 const s = await state(viewer.page);
2430 if (s.shares.length !== 0) return false;
2431 return (await shareTiles(viewer.page)).length === 0 ? s : false;
2432 }, 5000);
2433 check(removed, 'the screen tile and the shared state are gone within five seconds — ' +
2434 (await diagnose(viewer.page, viewer.label)));
2435
2436 const ended = await until(() =>
2437 viewer.page.evaluate(() => ((window.__shareEnded || []).length > 0)), 5000);
2438 check(ended, 'the received track ended rather than merely stopping being drawn (readyState ' +
2439 (await viewer.page.evaluate(() => (window.__shareTrack || {}).readyState || '(no track)')) + ')');
2440
2441 // Again from a fresh baseline, taken now that the stop has settled,
2442 // and again across a window rather than at an instant.
2443 // The screen is gone by now and is not expected; the two cameras
2444 // are, and they are the half a stopped share can take with it.
2445 await watchMedia([
2446 { page: viewer.page, label: viewer.label, keys: [sharer.peer] },
2447 { page: sharer.page, label: sharer.label, keys: [viewer.peer] },
2448 ], 'after the share stopped: ');
2449
2450 const off = await until(async () => {
2451 const b = await shareControl(sharer.page);
2452 return b && b.pressed === 'false' && b.state === 'Off' ? b : false;
2453 }, 5000);
2454 check(off, 'the Share button is back off, in both cues (' +
2455 JSON.stringify(await shareControl(sharer.page)) + ')');
2456 check((await state(sharer.page)).sharing === false, 'the sharing tab says it has stopped');
2457 check(await sharer.page.evaluate(() => document.getElementById('share-notice').hidden),
2458 'the sharing notice goes with the share');
2459
2460 check(errorsFor('member A') === '', 'no console errors in A (' + errorsFor('member A') + ')');
2461 check(errorsFor('member B') === '', 'no console errors in B (' + errorsFor('member B') + ')');
2462
2463 await leaveRoom(pageA);
2464 await leaveRoom(pageB);
2465 await ctxA.close();
2466 await ctxB.close();
2467 },
2468
2469 // Both of them at once, three times over. §5.4 gives each connection
2470 // one sendonly transceiver for a screen, and a simultaneous share is
2471 // where that goes wrong: two peers renegotiating the same connection
2472 // in the same moment, the polite one rolling its own offer back — and
2473 // taking its share m-line with it. Either each screen ends up on its
2474 // own m-line, or one of them silently takes the other's and the
2475 // second screen arrives on a transceiver nothing is sending down.
2476 //
2477 // Nothing is staggered on purpose, because the stagger is the bug's
2478 // hiding place. Both clicks go out together, both directions are
2479 // asserted separately, and the frames half of each is what catches an
2480 // inactive m-line: `shares` and the caption move on the `share`
2481 // message alone, so a screen that was announced and never arrived
2482 // looks exactly like one that works until the pixels are counted.
2483 //
2484 // Three rounds, because a rollback that is recovered from once may
2485 // not be recovered from twice: the transceiver a round leaves behind
2486 // is the one the next round has to reuse or replace.
2487 async mutualshare() {
2488 const ctxA = await newContext('member A', { cookie: cookieA });
2489 const ctxB = await newContext('member B', { cookie: cookieB });
2490 const pageA = await openRoom(ctxA);
2491 const pageB = await openRoom(ctxB);
2492 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
2493 if (!pair) {
2494 await ctxA.close();
2495 await ctxB.close();
2496 return;
2497 }
2498
2499 const nameA = await selfName(pageA);
2500 const nameB = await selfName(pageB);
2501 check(nameA !== '' && nameB !== '' && nameA !== nameB,
2502 'the two contexts have different names, so a caption can name the wrong one (' +
2503 JSON.stringify([nameA, nameB]) + ')');
2504
2505 // `other` is the peer id on the far side of this page's one
2506 // connection, so every assertion below reads as "this page, about
2507 // the other one" and the two directions never get crossed.
2508 const sides = [
2509 { page: pageA, label: 'member A', other: pair.b.peer, otherName: nameB },
2510 { page: pageB, label: 'member B', other: pair.a.peer, otherName: nameA },
2511 ];
2512
2513 // Both buttons hovered first, so Playwright's actionability checks
2514 // are already satisfied and the two clicks are two CDP messages and
2515 // nothing else. Trusted input rather than a scripted
2516 // element.click(): getDisplayMedia needs transient activation and a
2517 // synthesised click does not grant it. This is as near the same tick
2518 // as two browser contexts get.
2519 const bothClick = async () => {
2520 await Promise.all([pageA.hover('#share'), pageB.hover('#share')]);
2521 await Promise.all([pageA.click('#share'), pageB.click('#share')]);
2522 };
2523
2524 for (let round = 1; round <= 3; round++) {
2525 const at = 'round ' + round + ': ';
2526 await bothClick();
2527
2528 for (const side of sides) {
2529 const key = side.other + '#share';
2530
2531 const announced = await until(async () => {
2532 const s = await state(side.page);
2533 return s.shares.includes(side.other) ? s : false;
2534 }, 10000);
2535 check(announced, at + side.label + " was told about the other's screen — " +
2536 (await diagnose(side.page, side.label)));
2537
2538 const tiles = await shareTiles(side.page);
2539 check(tiles.length === 1 && tiles[0].name === side.otherName + '’s screen',
2540 at + side.label + ' shows one screen, captioned with the other name (' +
2541 JSON.stringify(tiles) + ', want ' + JSON.stringify(side.otherName + '’s screen') + ')');
2542
2543 // The half a message cannot fake. A share m-line the far side
2544 // took for its own, or one left inactive by a rollback, is
2545 // announced exactly like a working one and carries nothing.
2546 //
2547 // From a baseline taken now, in every round: `frames[key] > 0`
2548 // reads a counter `dropShare` deliberately leaves behind, so
2549 // rounds two and three used to pass on round one's frames even
2550 // if the new screen delivered none at all (Codex S4-6).
2551 const pixels = await frameGrowth(side.page, key, 15000);
2552 check(pixels.ok, at + side.label + ' is decoding the other screen, not just showing its name (' +
2553 growth(pixels) + ') — ' + (await diagnose(side.page, side.label)));
2554
2555 // The camera, from a baseline taken after this round's
2556 // transition settled rather than before the gesture that caused
2557 // it: frames delivered between a pre-gesture snapshot and a
2558 // rollback stall satisfy a pre-gesture baseline while the camera
2559 // is already dead, which is the exact failure this scenario was
2560 // written to catch.
2561 const camera = await frameGrowth(side.page, side.other, 15000);
2562 check(camera.ok, at + side.label + " is still receiving the other's camera (" +
2563 growth(camera) + ') — ' + (await diagnose(side.page, side.label)));
2564 }
2565
2566 check((await state(pageA)).sharing === true && (await state(pageB)).sharing === true,
2567 at + 'both tabs say they are sharing');
2568
2569 // Five seconds of not wobbling. Glare's worst outcome is not a
2570 // screen that never arrives but a connection left mid-offer: it
2571 // goes on carrying the media it already had, so every count above
2572 // keeps rising while nothing further can ever be negotiated.
2573 const wobbled = await bothStable(sides, 5000);
2574 check(wobbled === null, at + 'negotiation settled and stayed settled — ' + JSON.stringify(wobbled));
2575
2576 // And the media through that same window. The five seconds above
2577 // watch signalling, which a connection whose camera has stopped
2578 // encoding passes perfectly: `connected`, `stable`, sendrecv, a
2579 // live track, and nothing coming out (Codex S4-6). Two successive
2580 // intervals per stream, both screens and both cameras, so a
2581 // stream that delivers a frame and stops cannot answer for one
2582 // that is running.
2583 // Both cameras and both screens, named rather than read back off
2584 // the page, and all four watched through the same windows.
2585 await watchMedia(sides.map((side) => ({
2586 page: side.page,
2587 label: side.label,
2588 keys: [side.other, side.other + '#share'],
2589 })), at + 'after the wait: ');
2590
2591 if (round === 1) {
2592 for (const side of sides) {
2593 const surface = await capturedSurface(side.page);
2594 check(surface !== null,
2595 side.label + ' is sending a display capture and not a second camera (displaySurface ' +
2596 JSON.stringify(surface) + ')');
2597 }
2598 }
2599
2600 if (round === 3) break;
2601
2602 await bothClick();
2603 for (const side of sides) {
2604 const gone = await until(async () => {
2605 const s = await state(side.page);
2606 if (s.shares.length !== 0) return false;
2607 return (await shareTiles(side.page)).length === 0 ? s : false;
2608 }, 10000);
2609 check(gone, at + side.label + ' lost the screen tile before the next round — ' +
2610 (await diagnose(side.page, side.label)));
2611 }
2612 check((await state(pageA)).sharing === false && (await state(pageB)).sharing === false,
2613 at + 'both tabs say they have stopped');
2614
2615 // The stop is a renegotiation too, and the round that follows
2616 // would happily start on a camera this one had already killed.
2617 await watchMedia(sides.map((side) => ({
2618 page: side.page,
2619 label: side.label,
2620 keys: [side.other],
2621 })), at + 'after both stopped: ');
2622 }
2623
2624 // And the asymmetric ending, which is the one a symmetrical
2625 // scenario would never reach: one of them stops and the other does
2626 // not. The m-line that goes has to be the one that was stopped.
2627 const [stopper, keeper] = sides;
2628 const keptKey = stopper.other + '#share';
2629
2630 await stopper.page.click('#share');
2631
2632 const dropped = await until(async () => {
2633 const s = await state(keeper.page);
2634 if (s.shares.length !== 0) return false;
2635 return (await shareTiles(keeper.page)).length === 0 ? s : false;
2636 }, 10000);
2637 check(dropped, keeper.label + ' lost only the screen that stopped — ' +
2638 (await diagnose(keeper.page, keeper.label)));
2639
2640 // Fresh baselines again, taken after the one-sided stop settled:
2641 // the screen that was kept, and both cameras.
2642 check((await state(stopper.page)).shares.includes(stopper.other),
2643 stopper.label + ' still holds the other screen through its own stop');
2644 const kept = await frameGrowth(stopper.page, keptKey, 10000);
2645 check(kept.ok, stopper.label + ' still has the other screen, and it is still arriving (' +
2646 growth(kept) + ') — ' + (await diagnose(stopper.page, stopper.label)));
2647
2648 const stillCamera = await frameGrowth(keeper.page, keeper.other, 10000);
2649 check(stillCamera.ok, keeper.label + ' still has the camera through the one-sided stop (' +
2650 growth(stillCamera) + ') — ' + (await diagnose(keeper.page, keeper.label)));
2651 const stopperCamera = await frameGrowth(stopper.page, stopper.other, 10000);
2652 check(stopperCamera.ok, stopper.label + ' still has the camera through its own stop (' +
2653 growth(stopperCamera) + ') — ' + (await diagnose(stopper.page, stopper.label)));
2654
2655 check((await state(stopper.page)).sharing === false,
2656 stopper.label + ' says it has stopped');
2657 check((await state(keeper.page)).sharing === true,
2658 keeper.label + ' says it is still sharing');
2659
2660 const settledAfter = await bothStable(sides, 5000);
2661 check(settledAfter === null,
2662 'the one-sided stop left both connections settled — ' + JSON.stringify(settledAfter));
2663
2664 // Last of all, and after that wait rather than before it: the media
2665 // checks above all ran before those five seconds, so a camera that
2666 // froze during them left every one of them green (Codex's S4-6
2667 // gap). Both sides, and the screen that is still being shared.
2668 // The stopper still holds the keeper's screen; the keeper holds
2669 // none. Both cameras, either way.
2670 await watchMedia([
2671 { page: stopper.page, label: stopper.label, keys: [stopper.other, keptKey] },
2672 { page: keeper.page, label: keeper.label, keys: [keeper.other] },
2673 ], 'after the one-sided stop settled: ');
2674
2675 check(errorsFor('member A') === '', 'no console errors in A (' + errorsFor('member A') + ')');
2676 check(errorsFor('member B') === '', 'no console errors in B (' + errorsFor('member B') + ')');
2677
2678 await keeper.page.click('#share');
2679 await leaveRoom(pageA);
2680 await leaveRoom(pageB);
2681 await ctxA.close();
2682 await ctxB.close();
2683 },
2684
2685 // The residual spec §15.16 names, forced rather than waited for.
2686 //
2687 // POLITE_YIELD is 300 ms, and a pair whose signalling round trip
2688 // exceeds it still collides: the polite side gives way, offers
2689 // anyway, and the remote offer lands afterwards — so it rolls back,
2690 // and Chromium rebuilds every send stream on the connection. The
2691 // camera's comes back having encoded nothing and never encodes again,
2692 // on an m-line that goes on reading sendrecv with a live track. A
2693 // slow network is only one way to get there: a 429 retry and a slow
2694 // offer arrive just as late.
2695 //
2696 // The lateness here is real rather than simulated. One context's own
2697 // `offer` POSTs are held for four times the yield before they reach
2698 // the hub, so the other side's offer really does arrive after the
2699 // yield has ended, on a connection that has already offered.
2700 //
2701 // What this asserts is the recovery, not the failure: a Chromium that
2702 // no longer rebuilds the streams passes it exactly as a repaired one
2703 // does, which is the right way round for a gate — the assertion is
2704 // "the camera is encoding again", never "the camera broke first".
2705 // Whether it stalled on the way is recorded as a line rather than a
2706 // check, because that half is the browser's behaviour and not this
2707 // app's promise.
2708 async laterolls() {
2709 const HOLD = 1200; // four times POLITE_YIELD
2710 const ctxA = await newContext('member A', { cookie: cookieA });
2711 const ctxB = await newContext('member B', { cookie: cookieB });
2712 const pageA = await openRoom(ctxA);
2713 const pageB = await openRoom(ctxB);
2714 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
2715 if (!pair) {
2716 await ctxA.close();
2717 await ctxB.close();
2718 return;
2719 }
2720
2721 // §5.1's tie-break, read the way room.js reads it: the lower id is
2722 // the polite one, and the polite one is the side that rolls back.
2723 const aPolite = String(pair.a.peer) < String(pair.b.peer);
2724 const polite = aPolite
2725 ? { page: pageA, ctx: ctxA, label: 'member A', peer: pair.a.peer, other: pair.b.peer }
2726 : { page: pageB, ctx: ctxB, label: 'member B', peer: pair.b.peer, other: pair.a.peer };
2727 const impolite = aPolite
2728 ? { page: pageB, ctx: ctxB, label: 'member B', peer: pair.b.peer, other: pair.a.peer }
2729 : { page: pageA, ctx: ctxA, label: 'member A', peer: pair.a.peer, other: pair.b.peer };
2730 line('the polite side is ' + polite.label + ', and its offers are the ones that roll back');
2731
2732 // Only the impolite side's offers, and only the offers: everything
2733 // else — candidates, the share announcement, the leave — goes at
2734 // its own speed, so what is delayed is exactly the thing that makes
2735 // the collision late.
2736 const held = [];
2737 await impolite.ctx.route('**/signal', async (route) => {
2738 const body = route.request().postData() || '';
2739 if (body.includes('"type":"offer"')) {
2740 held.push(Date.now());
2741 await sleep(HOLD);
2742 }
2743 await route.continue();
2744 });
2745
2746 await Promise.all([polite.page.hover('#share'), impolite.page.hover('#share')]);
2747 await Promise.all([polite.page.click('#share'), impolite.page.click('#share')]);
2748
2749 check(await until(() => held.length > 0, 15000) !== null,
2750 'the impolite side had an offer to hold back (' + held.length + ' held)');
2751
2752 for (const side of [polite, impolite]) {
2753 const announced = await until(async () => {
2754 const s = await state(side.page);
2755 return s.shares.includes(side.other) ? s : false;
2756 }, 20000);
2757 check(announced, side.label + " was told about the other's screen through the delay — " +
2758 (await diagnose(side.page, side.label)));
2759 }
2760
2761 // The collision, asserted rather than assumed. Holding an offer
2762 // back is a delay; what this scenario is about is what the delay
2763 // causes, and that is a remote offer arriving over this side's own
2764 // outstanding one — which is precisely when perfect negotiation
2765 // rolls the polite side back. The trap counts exactly that.
2766 const rolled = await until(async () => (await rollbacks(polite.page)) > 0, 15000);
2767 check(rolled, 'the delay produced a rollback on the polite side (' +
2768 (await rollbacks(polite.page)) + ' seen; without one this scenario proves nothing)');
2769
2770 // The stall itself, watched but not required, and watched as a
2771 // series rather than as two numbers five seconds apart: a total
2772 // that grew across the window cannot tell a steady stream from one
2773 // that ran for a moment and stopped.
2774 const series = [];
2775 for (let i = 0; i < 6; i++) {
2776 series.push((await state(impolite.page)).frames[polite.peer] || 0);
2777 await sleep(500);
2778 }
2779 const moving = series[series.length - 1] > series[series.length - 2];
2780 line('the polite side\'s camera, rendered frames every 500 ms: ' + JSON.stringify(series) +
2781 (moving ? ' — still moving' : ' — stopped'));
2782
2783 // And what the tiles are actually bound to, on both sides, whatever
2784 // happens next: three answers that ought to be one object.
2785 for (const side of [polite, impolite]) {
2786 line(side.label + ' identity: ' + JSON.stringify(await mediaIdentity(side.page)));
2787 }
2788
2789 // The recovery, which is the promise: whatever the rollback did,
2790 // both cameras and both screens are delivering frames across two
2791 // successive intervals inside the repair budget — two polls to
2792 // notice, a replaceTrack cycle, two more polls, and a reset behind
2793 // that.
2794 // Recovery has to *arrive* before it can be required to last, and
2795 // arriving takes real time: three polls for the watch to notice,
2796 // two replays, and behind those a reset that rebuilds the pair. So
2797 // a deadline for the arrival — growth from a baseline taken now,
2798 // never "the counter is above zero", which a counter left over from
2799 // before the collision answers on its own — and then, separately,
2800 // an observation for the lasting.
2801 for (const side of [polite, impolite]) {
2802 for (const key of [side.other, side.other + '#share']) {
2803 const back = await frameGrowth(side.page, key, 40000);
2804 if (!check(back.ok, side.label + ' has ' + key + ' arriving again after the collision (' +
2805 growth(back) + ')')) {
2806 line(' ' + (await diagnose(side.page, side.label)));
2807 line(' identity: ' + JSON.stringify(await mediaIdentity(side.page)));
2808 }
2809 }
2810 }
2811
2812 // Settled *after* the recovery, because a reset is one of the ways
2813 // this scenario is allowed to recover and a pair mid-rebuild is not
2814 // a pair that failed to settle.
2815 const settled = await bothStable(
2816 [{ page: polite.page, label: polite.label, other: polite.other },
2817 { page: impolite.page, label: impolite.label, other: impolite.other }], 15000);
2818 check(settled === null, 'the late collision left both connections settled — ' + JSON.stringify(settled));
2819
2820 // And then the windows: every stream, both pages, growth in each
2821 // one. A recovery that lasts as long as a check and stops
2822 // afterwards is the shape this scenario exists to refuse.
2823 await watchMedia([
2824 { page: polite.page, label: polite.label, keys: [polite.other, polite.other + '#share'] },
2825 { page: impolite.page, label: impolite.label, keys: [impolite.other, impolite.other + '#share'] },
2826 ], 'and kept arriving once it had settled: ');
2827
2828 check(errorsFor('member A') === '', 'no console errors in A (' + errorsFor('member A') + ')');
2829 check(errorsFor('member B') === '', 'no console errors in B (' + errorsFor('member B') + ')');
2830
2831 await impolite.ctx.unroute('**/signal');
2832 await polite.page.click('#share');
2833 await impolite.page.click('#share');
2834 await leaveRoom(pageA);
2835 await leaveRoom(pageB);
2836 await ctxA.close();
2837 await ctxB.close();
2838 },
2839
2840 // A stream lives five minutes and is then renewed by a resume. Six
2841 // seconds here, through a header only development honours, so the
2842 // renewal happens several times while the call is watched — and six
2843 // rather than two because a stream shorter than the client's own
2844 // "this one was healthy" mark never clears its backoff, so the
2845 // renewals would slow down and this scenario would be measuring the
2846 // backoff ladder rather than the renewal. The client's mark stays
2847 // where it is; the header moves.
2848 async renewal() {
2849 const ctxA = await newContext('member A', { cookie: cookieA });
2850 const ctxB = await newContext('member B', { cookie: cookieB });
2851 // Counting the attaching GETs is what stops this scenario passing
2852 // vacuously: a header the server ignored would leave the call up
2853 // for the whole watch on one five-minute stream, and every other
2854 // assertion here would still be true.
2855 let attaches = 0;
2856 for (const ctx of [ctxA, ctxB]) {
2857 await ctx.route('**/stream*', async (route) => {
2858 const url = route.request().url();
2859 if (!url.includes('probe=1')) attaches += 1;
2860 await route.continue({ headers: { ...route.request().headers(), 'x-calls-test-ttl': '6s' } });
2861 });
2862 }
2863 const pageA = await openRoom(ctxA);
2864 const pageB = await openRoom(ctxB);
2865
2866 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
2867 if (!pair) {
2868 await ctxA.close();
2869 await ctxB.close();
2870 return;
2871 }
2872
2873 const before = { a: await state(pageA), b: await state(pageB) };
2874 // Long enough for at least one renewal each at a six-second life,
2875 // and in practice two. Watched four times a second the whole way:
2876 // a renewal is a stream ended on purpose and resumed, and §15.23 says
2877 // nobody sees it — not "Reconnecting…" over the call, not on a tile,
2878 // not in the title (Paul, 2026-09-30: "I saw 'Reconnecting' appear
2879 // occasionally over the video, but only for a second").
2880 const said = [];
2881 let streamDowns = 0;
2882 for (const until = Date.now() + 16000; Date.now() < until;) {
2883 for (const [page, who] of [[pageA, 'A'], [pageB, 'B']]) {
2884 const r = await page.evaluate(() => ({
2885 reconnect: window.meet.state().reconnect,
2886 status: (document.getElementById('status') || {}).textContent || '',
2887 title: (document.getElementById('call-top') || {}).textContent || '',
2888 tiles: Array.from(document.querySelectorAll('.calls-tile-notice, [data-hear-notice]')).map((n) => n.textContent),
2889 }));
2890 if (r.reconnect.streamDown) streamDowns += 1;
2891 const text = [r.status, r.title, ...r.tiles].join(' | ');
2892 if (r.reconnect.call || r.reconnect.peers.length || /Reconnecting/.test(text)) said.push(who + ': ' + text);
2893 }
2894 await sleep(250);
2895 }
2896 const after = { a: await state(pageA), b: await state(pageB) };
2897 check(said.length === 0, 'no renewal was said as "Reconnecting" (' + said.slice(0, 3).join('; ') + ')');
2898 console.log('renewal: a stream was seen down (between its end and its resume) at ' + streamDowns + ' of the looks');
2899
2900 check(after.a.peer === before.a.peer,
2901 'A kept its participation across the renewals (' + before.a.peer + ' -> ' + after.a.peer + ')');
2902 check(after.b.peer === before.b.peer,
2903 'B kept its participation across the renewals (' + before.b.peer + ' -> ' + after.b.peer + ')');
2904 check(after.a.admitted && after.a.peers.includes(before.b.peer),
2905 'A is still in the call after the renewals — ' + (await diagnose(pageA, 'member A')));
2906 check(after.b.admitted && after.b.peers.includes(before.a.peer),
2907 'B is still in the call after the renewals — ' + (await diagnose(pageB, 'member B')));
2908 check((after.a.frames[before.b.peer] || 0) > (before.a.frames[before.b.peer] || 0),
2909 'A is still receiving video after the renewals (' +
2910 (before.a.frames[before.b.peer] || 0) + ' -> ' + (after.a.frames[before.b.peer] || 0) + ')');
2911 // Two browsers, a six-second life, sixteen seconds of watching: the
2912 // first two attaches are the two fresh streams, and everything past
2913 // that is a renewal that actually happened. The floor is four — one
2914 // renewal each — rather than the number a stopwatch would predict,
2915 // because what this counts is that the header was honoured at all: a
2916 // server that ignored it would leave both calls up on one
2917 // five-minute stream and stop at two.
2918 check(attaches >= 4, 'the streams really were renewed (' + attaches + ' attaching GETs, want at least 4)');
2919
2920 await leaveRoom(pageA);
2921 await leaveRoom(pageB);
2922 await ctxA.close();
2923 await ctxB.close();
2924 },
2925
2926 // §5.2 in a real browser: the app has a relay, both members fetch the
2927 // list before they build anything, and the pair connects anyway — the
2928 // contract names a host that does not exist, so a call that connects
2929 // at all connected on host candidates. The credential in that list is
2930 // the one thing that must never turn up anywhere else.
2931 async ice() {
2932 const ctxA = await newContext('member A', { cookie: cookieA });
2933 const ctxB = await newContext('member B', { cookie: cookieB });
2934 const iceA = await iceRoute(ctxA);
2935 const iceB = await iceRoute(ctxB);
2936 const pageA = await openRoom(ctxA);
2937 const pageB = await openRoom(ctxB);
2938
2939 // assertPair is the assertion that matters most here: signalling
2940 // settled, the transport up, and a decoded frame each way, with two
2941 // unreachable servers in every connection's configuration.
2942 await assertPair(pageA, pageB, 'member A', 'member B');
2943
2944 for (const [page, label, seen] of [[pageA, 'member A', iceA], [pageB, 'member B', iceB]]) {
2945 const s = await state(page);
2946 check(s.ice.servers === 2,
2947 label + ' holds the two servers /ice minted (servers=' + s.ice.servers + ')');
2948 // And the connections were actually built with them. The line
2949 // above is the client's own cached count and would read the same
2950 // if every RTCPeerConnection were constructed with an empty list;
2951 // this is what the constructor received (Codex S3-5).
2952 const configs = await iceConfigs(page);
2953 const live = await livePcs(page);
2954 const now = installedPerConnection(configs, live);
2955 // Per connection, and the *last* configuration each one took: a
2956 // connection built with the list and one that adopted it at its
2957 // first quiet moment are both §5.2, and neither may be left on
2958 // the empty one. Counted globally, one connection's second update
2959 // could stand in for another's first (Codex S3-10).
2960 check(now.length > 0 && now.every((c) => c.servers === 2 && c.credentialed === 1),
2961 label + ' has every live connection configured with the two-entry list, one credentialed (' +
2962 JSON.stringify(now) + ' of ' + JSON.stringify(configs) + ')');
2963 check(s.ice.fetches === 1,
2964 label + ' fetched the list once for the call, not once per connection (fetches=' + s.ice.fetches + ')');
2965 check(s.ice.expiresAt > Date.now() && s.ice.renewAt > Date.now() && s.ice.renewAt < s.ice.expiresAt,
2966 label + ' was given a renewal time before an expiry, both ahead of now (' + JSON.stringify(s.ice) + ')');
2967 check(s.ice.warning === false, label + ' shows no relay warning (' + JSON.stringify(s.ice) + ')');
2968
2969 const w = await warningRegion(page);
2970 check(w && w.role === 'status' && w.hidden && w.text === '',
2971 label + "'s warning region is in the page, empty and hidden (" + JSON.stringify(w) + ')');
2972 check((await tileNotes(page)).length === 0,
2973 label + ' has no sentence under any tile (' + JSON.stringify(await tileNotes(page)) + ')');
2974
2975 check(seen.served >= 1 && seen.servers.every((n) => n === 2),
2976 label + ' was served a two-entry list every time (' + JSON.stringify(seen.servers) + ')');
2977 check(seen.turn.length === seen.served,
2978 label + ' got exactly one credentialed entry per fetch (' + seen.turn.length + ' of ' + seen.served + ')');
2979 // The five fields are the platform's own username shape: the
2980 // expiry the credential is minted against, then the account, the
2981 // app, the incarnation and the key id the suffix names.
2982 const fields = seen.turn.length ? seen.turn[0].split(':') : [];
2983 check(fields.length === 5,
2984 label + "'s turn username has five colon-separated fields (" + fields.length + ')');
2985 check(fields[1] === 'abc' && fields[2] === 'meet' && fields[3] === '0123456789abcdef' && fields[4] === 'k1',
2986 label + "'s turn username carries the contract's suffix (" + fields.slice(1).join(':') + ')');
2987 check(Number(fields[0]) > Math.floor(Date.now() / 1000),
2988 label + "'s turn username is minted against an expiry in the future (" + fields[0] + ')');
2989 }
2990
2991 // §5.2's promise, measured: room.js prints an error object and never
2992 // a response, so no credential is in any console line — of either
2993 // browser, since one page's list must not reach the other's log
2994 // either.
2995 const creds = [...iceA.credentials, ...iceB.credentials];
2996 check(creds.length === 2, 'both members were minted a credential (' + creds.length + ')');
2997 const allLines = linesFor('member A') + '\n' + linesFor('member B');
2998 const leaked = leakedCredential(creds, allLines);
2999 check(leaked === -1,
3000 'no credential reaches the console (credential ' + leaked + ' of ' + creds.length +
3001 ' was found in ' + allLines.split('\n').filter(Boolean).length + ' console line(s))');
3002
3003 check(errorsFor('member A') === '', 'no console errors in A (' + errorsFor('member A') + ')');
3004 check(errorsFor('member B') === '', 'no console errors in B (' + errorsFor('member B') + ')');
3005
3006 await leaveRoom(pageA);
3007 await leaveRoom(pageB);
3008 await ctxA.close();
3009 await ctxB.close();
3010 },
3011
3012 // §5.3 steps 2 and 4: the credential's life shortened to eighteen
3013 // seconds, so the schedule the server named comes round while the call
3014 // is being watched. A is renewed; B is the control — no header, so its
3015 // credential lasts the production three hours and it never renews. One
3016 // browser's ICE restart is what step 2 is about, and two of them at
3017 // once would be a glare test wearing a renewal's clothes.
3018 //
3019 // Eighteen rather than twelve: the server renews at five sixths of the
3020 // life and expires at the whole of it, so twelve leaves two seconds
3021 // between the renewal starting and the deadline that prints the
3022 // expired sentence — and this scenario asserts that sentence stays
3023 // away. Eighteen leaves three, and still renews inside the window.
3024 async icerenewal() {
3025 const ctxA = await newContext('member A', { cookie: cookieA });
3026 const ctxB = await newContext('member B', { cookie: cookieB });
3027 await ctxA.addInitScript(pcTap);
3028 const iceA = await iceRoute(ctxA, { ttl: '18s' });
3029 const iceB = await iceRoute(ctxB);
3030 const pageA = await openRoom(ctxA);
3031 const pageB = await openRoom(ctxB);
3032
3033 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
3034 if (!pair) {
3035 await ctxA.close();
3036 await ctxB.close();
3037 return;
3038 }
3039 const peerA = pair.a.peer;
3040 const peerB = pair.b.peer;
3041
3042 const first = await state(pageA);
3043 check(first.ice.fetches === 1, 'A is on its first list before the renewal (' + first.ice.fetches + ')');
3044 check(first.ice.expiresAt - first.ice.renewAt === 3000,
3045 'the shortened life left the three-second margin the schedule is measured from (' +
3046 (first.ice.expiresAt - first.ice.renewAt) + ' ms)');
3047
3048 // The generation the call is on now, read the same way room.js's own
3049 // proof reads it. Without this the "changed" half of the assertion
3050 // below would have nothing to change from.
3051 const before = await selectedUfrags(pageA);
3052 check(before.length === 1 && before[0],
3053 'A is on a named ICE generation before the renewal (' + JSON.stringify(before) + ')');
3054
3055 const second = await until(async () => {
3056 const s = await state(pageA);
3057 return s.ice.fetches >= 2 ? s : false;
3058 }, 25000);
3059 check(second, 'A fetched a second list on the schedule the server named — ' + (await diagnose(pageA, 'member A')));
3060 if (!second) {
3061 await ctxA.close();
3062 await ctxB.close();
3063 return;
3064 }
3065 check(second.ice.lastFetchAt > first.ice.lastFetchAt,
3066 'the second list is a fetch and not a re-read (' + (second.ice.lastFetchAt - first.ice.lastFetchAt) + ' ms later)');
3067 check(second.ice.renewAt > Date.now(),
3068 'the second fetch put the next renewal ahead of now (' + (second.ice.renewAt - Date.now()) + ' ms)');
3069 check(iceA.served >= 2, 'the route saw both of A\'s fetches (' + iceA.served + ')');
3070
3071 // §5.3 step 2's proof: the exchange completed, the connection is
3072 // stable, and the selected pair is on a *new* generation.
3073 const record = await until(async () => {
3074 const s = await state(pageA);
3075 const r = s.renewals[peerB];
3076 return r && r.renewed ? r : false;
3077 }, 25000);
3078 check(record, 'A proved the ICE restart landed on the new list — ' + (await diagnose(pageA, 'member A')));
3079 if (record) {
3080 check(record.attempts === 1, 'one restart was enough (' + record.attempts + ' of 3)');
3081 check(record.ufrag && record.ufrag !== before[0],
3082 'the proof is a new ICE generation (' + before[0] + ' -> ' + record.ufrag + ')');
3083 const after = await selectedUfrags(pageA);
3084 check(after.length === 1 && after[0] && after[0] !== before[0],
3085 "the gate's own walk of the selected pair agrees (" + JSON.stringify(before) + ' -> ' + JSON.stringify(after) + ')');
3086
3087 // And the renewal installed the *replacement* credential, rather
3088 // than restarting on the one it already had: a fresh generation
3089 // and flowing media would look exactly the same if renewal's
3090 // setConfiguration call were deleted, because host candidates
3091 // carry this call either way (Codex S3-5). Digests, never
3092 // credentials.
3093 const configs = await iceConfigs(pageA);
3094 const live = await livePcs(pageA);
3095 const mine = configs.filter((c) => live.includes(c.pc));
3096 const credentialed = mine.filter((c) => c.servers === 2 && c.credentialed === 1);
3097 const digests = Array.from(new Set(credentialed.map((c) => c.digest)));
3098 // Two credentialed configurations with *different* digests: the
3099 // first list this connection was given, and the replacement the
3100 // renewal installed. Which of them arrived through the
3101 // constructor and which through setConfiguration is not the
3102 // claim — a connection built during the first fetch takes its
3103 // first list through adopt — and the digests never leave the
3104 // page as anything but digests.
3105 check(credentialed.length >= 2 && digests.length >= 2,
3106 'the renewal installed a credential different from the one this connection had (' +
3107 JSON.stringify(mine.map((c) => c.at + ':' + c.pc + ':' + c.servers + ':' + c.digest)) + ')');
3108 const last = installedPerConnection(mine, live);
3109 check(last.length > 0 && last.every((c) => c.digest === digests[digests.length - 1]),
3110 'and it is the newer credential each live connection is left on (' +
3111 JSON.stringify(last) + ')');
3112 }
3113
3114 // The call is what matters, not the restart: frames rising on both
3115 // sides two seconds after the renewal was proven.
3116 const framesA = (await state(pageA)).frames[peerB] || 0;
3117 const framesB = (await state(pageB)).frames[peerA] || 0;
3118 await sleep(2000);
3119 const risingA = await until(async () => {
3120 const s = await state(pageA);
3121 return (s.frames[peerB] || 0) > framesA ? s.frames[peerB] : false;
3122 }, 15000);
3123 check(risingA, 'A is still receiving video after the renewal (' + framesA + ' -> ' + risingA + ') — ' +
3124 (await diagnose(pageA, 'member A')));
3125 const risingB = await until(async () => {
3126 const s = await state(pageB);
3127 return (s.frames[peerA] || 0) > framesB ? s.frames[peerA] : false;
3128 }, 15000);
3129 check(risingB, 'B is still receiving video after A renewed (' + framesB + ' -> ' + risingB + ') — ' +
3130 (await diagnose(pageB, 'member B')));
3131
3132 // Nothing expired: a renewal that lands inside the old credential's
3133 // life is the whole point of the schedule, and §5.3 step 3's
3134 // sentence belongs to the case where it does not.
3135 const end = await state(pageA);
3136 check(end.renewals[peerB] && end.renewals[peerB].expired === false,
3137 'no connection was marked expired (' + JSON.stringify(end.renewals) + ')');
3138 check(end.ice.warning === false, 'no relay warning was shown (' + JSON.stringify(end.ice) + ')');
3139 for (const [page, label] of [[pageA, 'member A'], [pageB, 'member B']]) {
3140 const notes = await tileNotes(page);
3141 check(!notes.includes(ICE_EXPIRED),
3142 label + ' shows no tile the credential expired on (' + JSON.stringify(notes) + ')');
3143 const w = await warningRegion(page);
3144 check(w && w.hidden && w.text === '', label + "'s warning region stayed empty (" + JSON.stringify(w) + ')');
3145 }
3146 check((await state(pageB)).ice.fetches === 1 && iceB.served === 1,
3147 'B, on the production schedule, never renewed (' + (await state(pageB)).ice.fetches + ' fetch(es))');
3148
3149 await leaveRoom(pageA);
3150 await leaveRoom(pageB);
3151 await ctxA.close();
3152 await ctxB.close();
3153 },
3154
3155 // §5.3 steps 1 and 3, the unhappy half: the list is fetched once and
3156 // every fetch after that is refused. A is told, in a sentence, that
3157 // Calls cannot reach the relay; when the old credential's own deadline
3158 // passes with nothing renewed, the connection that was built on it
3159 // says so too — and through all of it the call stays up, because on
3160 // this network the relay was never load-bearing.
3161 //
3162 // Twelve seconds here rather than the renewal scenario's eighteen:
3163 // this one wants the deadline to arrive, and it arrives two seconds
3164 // after the warning.
3165 //
3166 // What is NOT asserted: the recovery. The client's retry is a fixed
3167 // minute (§5.3 step 1) and shortening it from the gate would be
3168 // testing a knob rather than the client, so proving the warning clears
3169 // would cost this scenario seventy seconds of waiting. The plan's own
3170 // ruling says the same; the recovery timing stays unproved here.
3171 // §13's other renewal ending, and the one no scenario reached: the
3172 // fetch works, the restart does not. room.js must spend all three
3173 // attempts and then say the connection is stuck — never that the
3174 // credential expired, which it plainly has not, and which is what the
3175 // client used to say after one attempt when the old deadline happened
3176 // to fall inside the window (Codex S3-4, S3-5).
3177 //
3178 // The instrument is a page-side stub: A's restartIce does nothing at
3179 // all. Everything else is real — the fetch is served normally, the
3180 // list is installed, the exchange is untouched — so what is being
3181 // tested is the state machine's own verdict on a restart that will
3182 // not land.
3183 async icestuck() {
3184 const ctxA = await newContext('member A', { cookie: cookieA });
3185 const ctxB = await newContext('member B', { cookie: cookieB });
3186 await ctxA.addInitScript(() => {
3187 const proto = window.RTCPeerConnection && window.RTCPeerConnection.prototype;
3188 if (proto) proto.restartIce = function noRestart() {};
3189 });
3190 const iceA = await iceRoute(ctxA, { ttl: '12s' });
3191 const pageA = await openRoom(ctxA);
3192 const pageB = await openRoom(ctxB);
3193
3194 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
3195 if (!pair) {
3196 await ctxA.close();
3197 await ctxB.close();
3198 return;
3199 }
3200 const peerB = pair.b.peer;
3201 const framesBefore = (await state(pageA)).frames[peerB] || 0;
3202
3203 // The renewal itself works: a second list arrives.
3204 const renewing = await until(async () => {
3205 const s = await state(pageA);
3206 return s.ice.fetches >= 2 ? s : false;
3207 }, 25000);
3208 check(renewing, 'A fetched a replacement list (' + iceA.served + ' served) — ' +
3209 (await diagnose(pageA, 'member A')));
3210 check(!(await state(pageA)).ice.warning,
3211 'and nothing claims the relay is unreachable: it answered (' +
3212 JSON.stringify((await state(pageA)).ice) + ')');
3213
3214 // Three restarts, thirty seconds each, and none of them lands.
3215 // That is 90 seconds before the verdict, so the wait is generous.
3216 const verdict = await until(async () => {
3217 const r = (await state(pageA)).renewals[peerB];
3218 return r && r.trouble ? r : false;
3219 }, 120000);
3220 check(verdict, 'A reached a verdict on the connection it could not renew — ' +
3221 (await diagnose(pageA, 'member A')));
3222 if (verdict) {
3223 check(verdict.trouble === 'stuck',
3224 'the verdict is that the connection is stuck, not that the credential expired (' +
3225 JSON.stringify(verdict) + ')');
3226 check(verdict.expired === false,
3227 'and it is not marked expired: a replacement credential was in hand throughout (' +
3228 JSON.stringify(verdict) + ')');
3229 // The run that reached this verdict, not the connection's whole
3230 // life: `attempts` keeps counting as later runs take later lists,
3231 // so it cannot say how many restarts *this* verdict followed
3232 // (Codex S3-14). `lastRun` is captured with the verdict itself.
3233 check(verdict.lastRun && verdict.lastRun.attempts === 3 &&
3234 verdict.lastRun.verdict === 'stuck',
3235 'the run that gave up spent the whole three-restart budget (' +
3236 JSON.stringify(verdict.lastRun) + ')');
3237 check(verdict.attempts >= 3,
3238 'and the lifetime count is at least that (' + verdict.attempts + ')');
3239 check(verdict.renewed === false, 'and nothing was proven (' + JSON.stringify(verdict) + ')');
3240 const notes = await tileNotes(pageA);
3241 check(notes.includes(ICE_STUCK) && !notes.includes(ICE_EXPIRED),
3242 "A's tile says it could not renew this connection, and does not say expired (" +
3243 JSON.stringify(notes) + ')');
3244 }
3245
3246 // And the call itself is untouched: a restart that never happened
3247 // costs nothing on a network where the media was already flowing.
3248 const rising = await until(async () => {
3249 const s = await state(pageA);
3250 return (s.frames[peerB] || 0) > framesBefore && s.connection[peerB] === 'connected' ? s : false;
3251 }, 15000);
3252 check(rising, 'the call is still connected and still receiving video (' + framesBefore + ' -> ' +
3253 (rising ? rising.frames[peerB] : 'stuck') + ') — ' + (await diagnose(pageA, 'member A')));
3254
3255 await leaveRoom(pageA);
3256 await leaveRoom(pageB);
3257 await ctxA.close();
3258 await ctxB.close();
3259 },
3260
3261 // §15.28, the incident of 2026-10-21 in browsers: A and B in a call, B
3262 // leaves, A's ICE is blocked (every candidate it sends or receives
3263 // pointed at nothing) and C — the same person as B — comes back. Nothing
3264 // exchanged during the block is any use afterwards, so the pair is
3265 // mended only by fresh candidates. Nobody presses Retry; A has to decode
3266 // C again on its own. ICE_RECOVER_OFF=c switches C's recovery off (a
3267 // client from before §15.28, which A must mend alone); =both switches off
3268 // both, the 0.4.10 baseline, and expects the pair to stay down.
3269 //
3270 // Both cameras are off unless ICE_RECOVER_CAMERA=on. With a camera
3271 // sending, §15.16's encoder watch already resets a pair whose camera has
3272 // stopped encoding, and in 0.4.10 that reset was what mended a blocked
3273 // pair in a browser, three seconds after the block, by accident; a
3274 // person with their camera off, or no camera, had nothing. Off, the
3275 // recovery is the only thing that can, and "mended" is A hearing C.
3276 async icerecover() {
3277 const off = process.env.ICE_RECOVER_OFF || '';
3278 const blockMs = Number(process.env.ICE_BLOCK_MS || 25000);
3279 const cameras = process.env.ICE_RECOVER_CAMERA === 'on';
3280 const ctxA = await newContext('member A', { cookie: cookieA });
3281 const ctxB = await newContext('member B', { cookie: cookieB });
3282 const pageA = await openRoom(ctxA);
3283 const pageB = await openRoom(ctxB);
3284 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
3285 if (!pair) {
3286 await ctxA.close();
3287 await ctxB.close();
3288 return;
3289 }
3290 await leaveRoom(pageB);
3291 await ctxB.close();
3292 if (!cameras) await pageA.click('#camera');
3293 check(await until(async () => (await state(pageA)).peers.length === 0, 15000),
3294 'A sees B go — ' + (await diagnose(pageA, 'member A')));
3295 if (off === 'both') await pageA.evaluate(() => window.meet.recoveryForTest(false));
3296
3297 // Every reset either side asks the hub for, whoever asks: the
3298 // recovery's rebuilds, and §15.16's camera watch, which resets a pair
3299 // whose camera has stopped encoding.
3300 const resets = { a: 0, c: 0 };
3301 const countResets = (who) => (req) => {
3302 if (req.method() === 'POST' && /\/signal$/.test(req.url()) && /"type":"reset"/.test(req.postData() || '')) resets[who] += 1;
3303 };
3304 pageA.on('request', countResets('a'));
3305 await pageA.evaluate((ms) => window.meet.blockIceForTest(ms), blockMs);
3306 const blockedAt = Date.now();
3307 const ctxC = await newContext('member B again', { cookie: cookieB });
3308 ctxC.on('request', countResets('c'));
3309 const pageC = await openRoom(ctxC);
3310 if (!cameras) await pageC.click('#camera');
3311 if (off) await pageC.evaluate(() => window.meet.recoveryForTest(false));
3312 const joined = await until(async () => {
3313 const s = await state(pageA);
3314 return s.peers.length === 1 ? s : false;
3315 }, 20000);
3316 if (!check(joined, 'C is in the call with A — ' + (await diagnose(pageA, 'member A')))) {
3317 await ctxA.close();
3318 await ctxC.close();
3319 return;
3320 }
3321 const peerC = joined.peers[0];
3322
3323 // While the block lasts the pair does not come up, A's tile says
3324 // "Reconnecting to …" once C's first moments are over, and the failure
3325 // sentence waits for its minute.
3326 let sawReconnecting = false;
3327 let sawFailure = false;
3328 let early = '';
3329 while (Date.now() - blockedAt < blockMs) {
3330 const s = await state(pageA);
3331 if (s.connection[peerC] === 'connected') {
3332 check(false, 'A connected to C through the block — ' + JSON.stringify(s.candidates));
3333 break;
3334 }
3335 // Someone in their first moments is "connecting and can't hear you
3336 // yet" (§15.24) before they are "Reconnecting to …" (§15.23).
3337 if (s.reconnect.peers.includes(peerC) || (s.connecting[peerC] && s.connecting[peerC].shown)) sawReconnecting = true;
3338 if (s.notes[peerC] && Date.now() - blockedAt < 50000) early = s.notes[peerC];
3339 if (/^Could not connect/.test(s.notes[peerC] || '')) sawFailure = true;
3340 await sleep(250);
3341 }
3342 const blocked = await state(pageA);
3343 line('block over: A ' + JSON.stringify({ connection: blocked.connection[peerC], recovery: blocked.recovery[peerC],
3344 mangled: blocked.iceBlockMangled, reconnect: blocked.reconnect }));
3345 if (off !== 'both') {
3346 check(sawReconnecting, "A's tile for C said it was connecting, or Reconnecting to …, while the block lasted");
3347 check(!early, 'no failure sentence before its minute (' + early + ')');
3348 if (blockMs >= 75000) check(sawFailure, 'the failure sentence came once the minute had passed');
3349 }
3350
3351 // Nobody does anything.
3352 const before = (await state(pageA)).frames[peerC] || 0;
3353 const within = Number(process.env.ICE_RECOVER_WITHIN || 90000);
3354 const mended = await until(async () => {
3355 const s = await state(pageA);
3356 if (s.connection[peerC] !== 'connected') return false;
3357 return (cameras ? (s.frames[peerC] || 0) > before + 15 : s.hearingList.includes(peerC)) ? s : false;
3358 }, within);
3359 const a = await state(pageA);
3360 const c = await state(pageC);
3361 line('A: ' + JSON.stringify({ connection: a.connection[peerC], recovery: a.recovery[peerC],
3362 autoRestarts: a.autoRestarts, autoRebuilds: a.autoRebuilds, notes: a.notes, clients: a.clients }));
3363 line('C: ' + JSON.stringify({ recovery: c.recovery, autoRestarts: c.autoRestarts, autoRebuilds: c.autoRebuilds }));
3364 line('resets asked for: ' + JSON.stringify(resets));
3365 if (off === 'both') {
3366 // The baseline: with no recovery anywhere, the pair stays down.
3367 check(!mended, 'with no recovery on either side the pair stayed down for ' + within / 1000 + ' s after the block');
3368 line(mended ? 'BASELINE recovered on its own' : 'BASELINE STUCK ' + within / 1000 + ' s after the block lifted');
3369 } else {
3370 check(mended, 'A decodes C again, with nobody pressing Retry, within ' + within / 1000 + ' s of the block lifting — ' +
3371 (await diagnose(pageA, 'member A')));
3372 if (mended) line('recovered ' + Math.round((Date.now() - blockedAt - blockMs) / 1000) + ' s after the block lifted');
3373 // With cameras on, §15.16's watch may get there first, and the
3374 // recovery then has nothing to do: either is a mended pair.
3375 if (!cameras) check(a.autoRestarts + c.autoRestarts > 0, 'a restart was made on its own (A ' + a.autoRestarts + ', C ' + c.autoRestarts + ')');
3376 if (off === 'c' && !cameras) check(c.autoRestarts === 0 && c.autoRebuilds === 0 && a.autoRestarts > 0,
3377 'A mended it alone (A ' + a.autoRestarts + '/' + a.autoRebuilds + ', C ' + c.autoRestarts + '/' + c.autoRebuilds + ')');
3378 const quiet = await until(async () => {
3379 const s = await state(pageA);
3380 return !s.notes[peerC] && !s.reconnect.peers.includes(peerC) ? s : false;
3381 }, 5000);
3382 check(quiet, 'the words go with the trouble (' + JSON.stringify((await state(pageA)).notes) + ')');
3383 // A browser is never "on an old version".
3384 check(!(a.clients[peerC] || ''), 'a browser has no client in the roster (' + JSON.stringify(a.clients) + ')');
3385 }
3386
3387 await leaveRoom(pageA);
3388 await leaveRoom(pageC);
3389 await ctxA.close();
3390 await ctxC.close();
3391 },
3392
3393 async icefail() {
3394 const ctxA = await newContext('member A', { cookie: cookieA });
3395 const ctxB = await newContext('member B', { cookie: cookieB });
3396 const iceA = await iceRoute(ctxA, { ttl: '12s', failFrom: 2 });
3397 const pageA = await openRoom(ctxA);
3398 const pageB = await openRoom(ctxB);
3399
3400 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
3401 if (!pair) {
3402 await ctxA.close();
3403 await ctxB.close();
3404 return;
3405 }
3406 const peerA = pair.a.peer;
3407 const peerB = pair.b.peer;
3408
3409 const first = await state(pageA);
3410 check(first.ice.fetches === 1 && first.ice.warning === false,
3411 'A is on a good list with no warning before the relay goes (' + JSON.stringify(first.ice) + ')');
3412 check(first.ice.expiresAt - first.ice.renewAt === 2000,
3413 'the shortened life left the two-second margin (' + (first.ice.expiresAt - first.ice.renewAt) + ' ms)');
3414 const framesBefore = (await state(pageA)).frames[peerB] || 0;
3415
3416 const warned = await until(async () => {
3417 const s = await state(pageA);
3418 return s.ice.warning ? s : false;
3419 }, 25000);
3420 check(warned, 'A says it cannot reach the relay — ' + (await diagnose(pageA, 'member A')));
3421 const warnedAt = Date.now();
3422 check(warnedAt - first.ice.renewAt < 15000,
3423 'the sentence arrives within fifteen seconds of the renewal time the server named (' +
3424 (warnedAt - first.ice.renewAt) + ' ms)');
3425 check(iceA.refused >= 1, 'the relay really was refused (' + iceA.refused + ' refusal(s))');
3426 check((await state(pageA)).ice.fetches === 1,
3427 'a refused fetch is not counted as a list (' + (await state(pageA)).ice.fetches + ')');
3428
3429 const w = await warningRegion(pageA);
3430 check(w && w.text === ICE_WARNING && !w.hidden && w.role === 'status',
3431 'the warning is the sentence itself, in a live region a reader is told about (' + JSON.stringify(w) + ')');
3432
3433 // §5.3 step 3: the old credential's expiry is the must-succeed-by,
3434 // and the connection built on it is marked when it passes.
3435 const expired = await until(async () => {
3436 const s = await state(pageA);
3437 const r = s.renewals[peerB];
3438 return r && r.expired ? s : false;
3439 }, 25000);
3440 check(expired, 'the connection that credential was about is marked expired — ' + (await diagnose(pageA, 'member A')));
3441 if (expired) {
3442 check(Date.now() >= first.ice.expiresAt,
3443 'nothing was called expired before the credential it belonged to ran out (' +
3444 (Date.now() - first.ice.expiresAt) + ' ms after)');
3445 check(Date.now() >= warnedAt,
3446 'the warning came first and the sentence second (' + (Date.now() - warnedAt) + ' ms apart)');
3447 const notes = await tileNotes(pageA);
3448 check(notes.includes(ICE_EXPIRED), "A's tile says the credential expired (" + JSON.stringify(notes) + ')');
3449 }
3450
3451 // And through all of it: a call that never needed the relay.
3452 const rising = await until(async () => {
3453 const s = await state(pageA);
3454 return (s.frames[peerB] || 0) > framesBefore &&
3455 s.signaling[peerB] === 'stable' && s.connection[peerB] === 'connected' ? s : false;
3456 }, 15000);
3457 check(rising, 'the call is still connected and still receiving video (' + framesBefore + ' -> ' +
3458 (rising ? rising.frames[peerB] : 'stuck') + ') — ' + (await diagnose(pageA, 'member A')));
3459
3460 // B is the control: nothing was taken away from it, so neither
3461 // sentence belongs on its screen.
3462 const b = await state(pageB);
3463 check(b.ice.warning === false && b.ice.fetches === 1,
3464 'B, whose relay was never taken away, shows no warning (' + JSON.stringify(b.ice) + ')');
3465 check(!(await tileNotes(pageB)).includes(ICE_EXPIRED),
3466 'B shows no expired sentence (' + JSON.stringify(await tileNotes(pageB)) + ')');
3467 check((b.frames[peerA] || 0) > 0, 'B is still receiving A (' + (b.frames[peerA] || 0) + ' frames)');
3468
3469 line('note: the one-minute retry recovering is not asserted here — see the comment above icefail');
3470
3471 await leaveRoom(pageA);
3472 await leaveRoom(pageB);
3473 await ctxA.close();
3474 await ctxB.close();
3475 },
3476
3477 // §4.3's admission queue: a guest knocks, sees nothing of the room,
3478 // and is let in by a member.
3479 //
3480 // Two guests knock, and only one is admitted. That is what makes the
3481 // isolation half of this scenario load-bearing (W-1): with a single
3482 // guest, the queue is empty at the moment it is admitted and no
3483 // admission ever happens while anyone is waiting, so every one of
3484 // §4.3's audience filters can be deleted and the scenario still
3485 // passes. It was, and it did.
3486 async guest() {
3487 const ctxA = await newContext('member A', { cookie: cookieA });
3488 const ctxW = await newContext('waiting guest');
3489 const ctxG = await newContext('guest');
3490 const pageA = await openRoom(ctxA);
3491 check(await until(async () => (await state(pageA)).admitted, 20000),
3492 'the member is in the room — ' + (await diagnose(pageA, 'member A')));
3493
3494 // The guest that stays in the queue for the whole scenario.
3495 await signInAsGuest(ctxW, WAITER);
3496 const pageW = await openRoom(ctxW);
3497 check(await until(async () => ((await state(pageW)).peer ? true : false), 20000),
3498 'the first guest knocked — ' + (await diagnose(pageW, 'waiting guest')));
3499 check(await until(async () => (await pageA.locator('#knocks li').count()) === 1, 20000),
3500 "the member's queue shows the first knock — " + (await diagnose(pageA, 'member A')));
3501
3502 await signInAsGuest(ctxG, GUEST);
3503 const pageG = await openRoom(ctxG);
3504
3505 const knocked = await until(async () => ((await state(pageG)).peer ? true : false), 20000);
3506 check(knocked, 'the guest got a peer id and knocked — ' + (await diagnose(pageG, 'guest')));
3507 check(await waitStatus(pageG, 'Waiting for someone to let you in.', 10000),
3508 'the guest is told it is waiting — status: ' + (await statusText(pageG)));
3509
3510 const waitingState = await state(pageG);
3511 check(waitingState.admitted === false, 'the guest is not admitted before anyone admits it');
3512 check(waitingState.peers.length === 0,
3513 'the guest has no peer connections before admission (' + JSON.stringify(waitingState.peers) + ')');
3514 check((await queueNames(pageG)).length === 0,
3515 'a guest that has only knocked is told nothing about the queue (' + JSON.stringify(await queueNames(pageG)) + ')');
3516
3517 const queued = await until(async () => (await pageA.locator('#knocks li').count()) === 2, 20000);
3518 check(queued, "the member's queue shows both knocks — " + (await diagnose(pageA, 'member A')));
3519 if (queued) {
3520 check(await admitKnock(pageA, 'guest'),
3521 'the queue names the guest to admit (' + JSON.stringify(await queueNames(pageA)) + ')');
3522 }
3523
3524 await assertPair(pageA, pageG, 'member A', 'guest');
3525
3526 // W-1, as a browser can see it. The guest was admitted while
3527 // somebody else was knocking, so roster.waiting had a name in it to
3528 // leak, and an admission happened while the other guest waited.
3529 check((await queueNames(pageG)).length === 0,
3530 'the admitted guest was never handed the waiting queue (' + JSON.stringify(await queueNames(pageG)) + ')');
3531 check(await pageG.locator('#queue').isHidden(),
3532 "the admitted guest's queue stays hidden");
3533 // `terminal === null` and a peer id are load-bearing, not decoration:
3534 // a `peer` event sent to a waiting guest makes it open a connection
3535 // and start signalling, which is refused, which sends it round the
3536 // fresh-stream ladder into `replaced` — and a terminal page has an
3537 // empty peer list too. Without these two the assertion would pass on
3538 // the very leak it is written to catch.
3539 const stillWaiting = await stayed(pageW, 3000,
3540 (s) => s.terminal === null && !!s.peer && s.admitted === false && s.peers.length === 0);
3541 check(stillWaiting === null,
3542 'the guest still waiting is still just waiting, told nothing of the admission — ' +
3543 JSON.stringify(stillWaiting));
3544 check((await queueNames(pageW)).length === 0,
3545 'the guest still waiting knows nothing of the queue it is in (' + JSON.stringify(await queueNames(pageW)) + ')');
3546
3547 // The member does see the queue, so the three checks above are an
3548 // audience and not an empty room.
3549 check(JSON.stringify(await queueNames(pageA)) === JSON.stringify(['waiter']),
3550 "the member's queue still holds the guest that was not admitted (" + JSON.stringify(await queueNames(pageA)) + ')');
3551
3552 // And a knock that arrives *while* the guest is admitted: the same
3553 // audience rule, and the one slice 4's chat fan-out extends. The
3554 // waiter leaves and comes back so the knock happens now rather than
3555 // before the admission.
3556 await leaveRoom(pageW);
3557 const pageW2 = await openRoom(ctxW);
3558 check(await until(async () => ((await state(pageW2)).peer ? true : false), 20000),
3559 'the guest knocked again — ' + (await diagnose(pageW2, 'waiting guest')));
3560 check(await until(async () => (await pageA.locator('#knocks li').count()) === 1, 20000),
3561 "the member is told about the second knock — " + (await diagnose(pageA, 'member A')));
3562 check((await queueNames(pageG)).length === 0,
3563 'the admitted guest is not told who is knocking (' + JSON.stringify(await queueNames(pageG)) + ')');
3564
3565 await leaveRoom(pageG);
3566 await leaveRoom(pageW2);
3567 await leaveRoom(pageA);
3568 await ctxA.close();
3569 await ctxW.close();
3570 await ctxG.close();
3571 },
3572
3573 // §6 and §13's other slice-4 sentence: "chat arrives at the admitted
3574 // context and not at a waiting one."
3575 //
3576 // The guest is what makes that a claim rather than a description. It
3577 // is signed in, it has a participation, it is knocking — everything
3578 // except admitted — so a fan-out that reached everybody with a stream
3579 // would reach it. The window it is watched for is opened only after
3580 // the *member* has the line, so "silence" here means a message that
3581 // demonstrably arrived somewhere and demonstrably did not arrive here.
3582 // Then it is let in, and the very next line has to reach it.
3583 async chat() {
3584 const ctxA = await newContext('member A', { cookie: cookieA });
3585 const ctxB = await newContext('member B', { cookie: cookieB });
3586 const ctxG = await newContext('guest');
3587
3588 // Every chat POST A makes, kept whole. §4.3's wire shape is a
3589 // negative claim — no `to`, no `seq`, no `gen` — and the body A
3590 // actually sent is the only place a browser can prove it. The count
3591 // matters as much as the shape: one line typed is one POST however
3592 // many people hear it, which is the whole difference between a
3593 // broadcast and a loop over the roster.
3594 const chatPosts = [];
3595 await ctxA.route('**/signal', async (route) => {
3596 try {
3597 const msg = JSON.parse(route.request().postData() || '');
3598 if (msg && msg.type === 'chat') chatPosts.push(msg);
3599 } catch {
3600 // No body, or not JSON: not a chat.
3601 }
3602 await route.continue();
3603 });
3604
3605 const pageA = await openRoom(ctxA);
3606 const pageB = await openRoom(ctxB);
3607 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
3608 if (!pair) {
3609 await ctxA.close();
3610 await ctxB.close();
3611 await ctxG.close();
3612 return;
3613 }
3614
3615 check(await until(() => chatMounted(pageA), 10000),
3616 "an admitted member's chat panel is on the page — " + (await diagnose(pageA, 'member A')));
3617 check(await pageA.locator('#chat-overlay').isHidden(), 'and closed until asked for, as on the Mac');
3618 await openChat(pageA);
3619 await openChat(pageB);
3620 check(await pageA.locator('#chat-text').isEditable(), "A's composer is live");
3621 check(await pageB.locator('#chat-send').isEnabled(), "B's Send button is live");
3622
3623 // The third context: signed in through the emailed link, knocking,
3624 // not admitted.
3625 await signInAsGuest(ctxG);
3626 const pageG = await openRoom(ctxG);
3627 check(await until(async () => ((await state(pageG)).peer ? true : false), 20000),
3628 'the guest got a peer id and knocked — ' + (await diagnose(pageG, 'guest')));
3629 check(await waitStatus(pageG, 'Waiting for someone to let you in.', 10000),
3630 'the guest is told it is waiting — status: ' + (await statusText(pageG)));
3631 check((await state(pageG)).admitted === false, 'the guest is waiting, not admitted');
3632 check(!(await chatMounted(pageG)) && await pageG.locator('#chat').isHidden(),
3633 'a guest that has only knocked is shown no chat panel');
3634
3635 const nameA = await selfName(pageA);
3636 check(nameA !== '', "A's own tile names it (" + nameA + ')');
3637
3638 const HELLO = 'hello from A';
3639 await pageA.fill('#chat-text', HELLO);
3640 await pageA.press('#chat-text', 'Enter');
3641
3642 const heard = await until(async () => {
3643 const log = await chatLog(pageB);
3644 return log.find((l) => l.text === HELLO) || false;
3645 }, 2000);
3646 check(heard, "B's log gained the line within two seconds (" +
3647 JSON.stringify(await chatLog(pageB)) + ')');
3648 if (heard) {
3649 // Not "the envelope's name": what a browser can see is that the
3650 // line B was given is attributed to A and not to B, and with two
3651 // distinct local parts on the two addresses (browser_test.go says
3652 // why) that is a claim this check can fail.
3653 check(heard.name === nameA,
3654 "the line B sees is attributed to A, not to B (" + JSON.stringify(heard.name) +
3655 ' vs ' + JSON.stringify(nameA) + ')');
3656 check(heard.self === false, "the line B sees is not drawn as B's own");
3657 }
3658
3659 // A's echo is appended when A's own POST is answered, and B's line
3660 // when the hub's broadcast reaches B's stream: two different events
3661 // with no order between them. Reading A's log the instant B had the
3662 // line raced that, and lost about one run in six on main f5a1254 as
3663 // on this branch (#24). The claim is unchanged — A's log shows what A
3664 // said — and it gets the same two seconds B's does.
3665 const echo = await until(async () => (await chatLog(pageA)).find((l) => l.text === HELLO) || false, 2000);
3666 check(echo, "A's own log shows what A said (" + JSON.stringify(await chatLog(pageA)) + ')');
3667 if (echo) check(echo.self === true, "A's echo is drawn as A's own line");
3668
3669 // §4.3: the hub never sends a chat back to the tab that sent it, and
3670 // the line in A's log is the panel's own echo. Those two facts are
3671 // one line each and they are what stop a double-drawn message
3672 // passing every check above.
3673 check((await state(pageA)).chat.received === 0,
3674 'A was not sent its own line back (' + JSON.stringify((await state(pageA)).chat) + ')');
3675 check((await chatLog(pageA)).filter((l) => l.text === HELLO).length === 1,
3676 "A's log holds the line once, not twice (" + JSON.stringify(await chatLog(pageA)) + ')');
3677 check((await chatLog(pageB)).filter((l) => l.text === HELLO).length === 1,
3678 "B's log holds the line once, not twice (" + JSON.stringify(await chatLog(pageB)) + ')');
3679
3680 // The member side is polled first, deliberately: the guest's
3681 // two-second window has to be a window in which the message
3682 // demonstrably existed, or it is a test of nothing having happened
3683 // yet. Every guest check below is guarded on it for the same reason
3684 // — an unsent message is silent everywhere, and this scenario would
3685 // be reporting that as a pass.
3686 const counted = await until(async () => {
3687 const s = await state(pageB);
3688 return s.chat.received >= 1 ? s : false;
3689 }, 5000);
3690 check(counted, 'B counted the line it put in its log (' +
3691 JSON.stringify((await state(pageB)).chat) + ')');
3692 check(counted && counted.chat.received === 1,
3693 'and counted it once (' + JSON.stringify(counted && counted.chat) + ')');
3694 check((await state(pageA)).chat.sent === 1,
3695 'A counted exactly the one line the hub accepted (' +
3696 JSON.stringify((await state(pageA)).chat) + ')');
3697
3698 if (counted) {
3699 const silent = await stayed(pageG, 2000, (s) => s.chat.received === 0 && s.admitted === false);
3700 check(silent === null,
3701 'the waiting guest was sent no chat at all — ' + JSON.stringify(silent));
3702 check(!(await chatMounted(pageG)) && await pageG.locator('#chat').isHidden(),
3703 "the waiting guest's chat panel is still not there to put anything in");
3704 check((await chatLog(pageG)).length === 0,
3705 "the waiting guest's log is empty (" + JSON.stringify(await chatLog(pageG)) + ')');
3706 } else {
3707 check(false, 'the guest was not watched for silence: nothing was proven to have been said');
3708 }
3709
3710 check(chatPosts.length === 1,
3711 'one line typed is one POST, however many people hear it (' + chatPosts.length + ')');
3712 const sent = chatPosts[0] || {};
3713 check(sent.type === 'chat' && sent.peer === pair.a.peer &&
3714 sent.payload && sent.payload.text === HELLO,
3715 'the POST carries this tab\'s own peer and the text (' + JSON.stringify(Object.keys(sent)) + ')');
3716 check(!('to' in sent) && !('seq' in sent) && !('gen' in sent),
3717 'a broadcast names no target and no ordering (' + JSON.stringify(Object.keys(sent)) + ')');
3718
3719 // And now the other half of the sentence.
3720 const queued = await until(async () => (await pageA.locator('#knocks li').count()) === 1, 20000);
3721 check(queued, "the member's queue shows the knock — " + (await diagnose(pageA, 'member A')));
3722 if (queued) {
3723 check(await admitKnock(pageA, 'guest'),
3724 'the queue names the guest to admit (' + JSON.stringify(await queueNames(pageA)) + ')');
3725 }
3726
3727 const admitted = await until(async () => {
3728 const s = await state(pageG);
3729 return s.admitted && s.rosters >= 1 ? s : false;
3730 }, 25000);
3731 check(admitted, 'the guest was admitted and has its roster — ' + (await diagnose(pageG, 'guest')));
3732 check(await until(() => chatMounted(pageG), 10000),
3733 "the admitted guest's chat panel is on the page — " + (await diagnose(pageG, 'guest')));
3734
3735 const AGAIN = 'and now the guest is here';
3736 await pageA.fill('#chat-text', AGAIN);
3737 await pageA.press('#chat-text', 'Enter');
3738
3739 const guestHeard = await until(async () => {
3740 const log = await chatLog(pageG);
3741 return log.find((l) => l.text === AGAIN) || false;
3742 }, 5000);
3743 check(guestHeard, 'the admitted guest receives the next line (' +
3744 JSON.stringify(await chatLog(pageG)) + ')');
3745 if (guestHeard) {
3746 check(guestHeard.name === nameA,
3747 "the guest's line is attributed to A too (" + JSON.stringify(guestHeard.name) + ')');
3748 }
3749 // §6 has no replay and no history: what was said before this guest
3750 // was let in is not caught up with, and nothing offers to.
3751 check((await chatLog(pageG)).every((l) => l.text !== HELLO),
3752 'and is handed nothing that was said before it was let in (' +
3753 JSON.stringify(await chatLog(pageG)) + ')');
3754 check(chatPosts.length === 2,
3755 'the second line is one POST as well (' + chatPosts.length + ')');
3756 // Exactly two, not at least two: §6 has no replay and no gap, so a
3757 // count that climbed past what was said would mean something was
3758 // delivered twice, and a count short of it would mean a line went
3759 // missing. Both are the same assertion.
3760 const both = await until(async () => {
3761 const s = await state(pageB);
3762 return s.chat.received >= 2 ? s : false;
3763 }, 5000);
3764 check(both && both.chat.received === 2,
3765 'B heard both lines, each once (' + JSON.stringify((await state(pageB)).chat) + ')');
3766 check((await chatLog(pageB)).filter((l) => l.text === AGAIN).length === 1,
3767 "and drew the second one once (" + JSON.stringify(await chatLog(pageB)) + ')');
3768 check((await state(pageA)).chat.received === 0,
3769 'A was sent neither of its own lines back (' +
3770 JSON.stringify((await state(pageA)).chat) + ')');
3771
3772 // §6 and §5.2's promise together: what people say is not logged.
3773 for (const label of ['member A', 'member B', 'guest']) {
3774 const lines = linesFor(label);
3775 check(!lines.includes(HELLO) && !lines.includes(AGAIN),
3776 'nothing anybody typed reached the console on ' + label);
3777 }
3778 check(errorsFor('member A') === '', 'no console errors in A (' + errorsFor('member A') + ')');
3779 check(errorsFor('member B') === '', 'no console errors in B (' + errorsFor('member B') + ')');
3780
3781 await leaveRoom(pageG);
3782 await leaveRoom(pageA);
3783 await leaveRoom(pageB);
3784 await ctxA.close();
3785 await ctxB.close();
3786 await ctxG.close();
3787 },
3788
3789 // §3.5: removal is a member's own confirm page, in its own tab, and
3790 // the person removed is told so in a sentence.
3791 async removed() {
3792 const ctxA = await newContext('member A', { cookie: cookieA });
3793 const ctxG = await newContext('guest');
3794 const pageA = await openRoom(ctxA);
3795 await until(async () => (await state(pageA)).admitted, 20000);
3796
3797 await signInAsGuest(ctxG);
3798 const pageG = await openRoom(ctxG);
3799
3800 const queued = await until(async () => (await pageA.locator('#knocks li').count()) === 1, 20000);
3801 check(queued, 'the guest reached the queue — ' + (await diagnose(pageA, 'member A')));
3802 if (queued) await pageA.click('#knocks li button');
3803
3804 const pair = await assertPair(pageA, pageG, 'member A', 'guest');
3805 if (!pair) {
3806 await ctxA.close();
3807 await ctxG.close();
3808 return;
3809 }
3810
3811 check(await pageA.locator('#tiles figcaption .calls-tile-remove, #tiles figcaption a').count() === 0,
3812 'the name label carries no Remove: it is in the tile menu');
3813 await openTileMenu(pageA, pair.b.peer);
3814 const href = await pageA.locator('.calls-tile-remove').first().getAttribute('href');
3815 check(href === '/m/' + sqid + '/remove/' + pair.b.peer,
3816 "the Remove control names the guest's peer (" + href + ')');
3817
3818 // target="_blank": the call is holding this tab, so the confirm page
3819 // arrives as a second page in the same context.
3820 const [confirm] = await Promise.all([
3821 ctxA.waitForEvent('page', { timeout: 15000 }),
3822 pageA.click('.calls-tile-remove'),
3823 ]);
3824 await confirm.waitForLoadState('domcontentloaded');
3825 const heading = await confirm.locator('h1').first().textContent();
3826 check(/^Remove .* from the call\?$/.test((heading || '').trim()),
3827 'the confirm page asks about this person (' + heading + ')');
3828
3829 await Promise.all([
3830 confirm.waitForURL('**/m/' + sqid + '/join', { timeout: 15000 }),
3831 confirm.click('form[rst-form-actions] button[type="submit"]'),
3832 ]);
3833 check(confirm.url() === origin + '/m/' + sqid + '/join',
3834 'the confirmed removal lands on the holding screen, which opens no stream (at ' + where(confirm) + ')');
3835
3836 check(await waitStatus(pageG, 'Someone removed you from this meeting.', 20000),
3837 'the guest is told it was removed — status: ' + (await statusText(pageG)));
3838 const ended = await until(async () => {
3839 const s = await state(pageG);
3840 return s.terminal === 'removed' && s.admitted === false && s.peers.length === 0 ? s : false;
3841 }, 10000);
3842 check(ended, 'the removed guest is terminal on `removed`, not admitted, and holds no peer connections — ' +
3843 (await diagnose(pageG, 'guest')));
3844
3845 await leaveRoom(pageA);
3846 await ctxA.close();
3847 await ctxG.close();
3848 },
3849
3850 // §2.4 and §13: a member dropped from the team mid-call is dropped on
3851 // the next tick, and the other context sees them go. Only Go can move
3852 // the allowlist and run the tick, so the browser asks for both.
3853 async allowlist() {
3854 const ctxA = await newContext('member A', { cookie: cookieA });
3855 const ctxB = await newContext('member B', { cookie: cookieB });
3856 const pageA = await openRoom(ctxA);
3857 const pageB = await openRoom(ctxB);
3858 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
3859 if (!pair) {
3860 await ctxA.close();
3861 await ctxB.close();
3862 return;
3863 }
3864
3865 const answer = await control('drop-member-b');
3866 check(answer === 'ok', 'B was taken off the team and the tick was run (' + answer + ')');
3867
3868 const dropped = await until(async () => {
3869 const s = await state(pageB);
3870 return s.terminal === 'standing' && s.admitted === false && s.peers.length === 0 ? s : false;
3871 }, 25000);
3872 check(dropped, 'the dropped member is terminal on `standing`, not admitted, and holds no connections — ' +
3873 (await diagnose(pageB, 'member B')));
3874 check(await waitStatus(pageB, 'You no longer have access to this meeting.', 10000),
3875 'the dropped member is told why in plain words — status: ' + (await statusText(pageB)));
3876
3877 const gone = await until(async () => {
3878 const s = await state(pageA);
3879 return !s.peers.includes(pair.b.peer) ? s : false;
3880 }, 25000);
3881 check(gone, 'the other context lost the dropped member from its peers — ' + (await diagnose(pageA, 'member A')));
3882 const tiles = await until(async () => (await pageA.locator('#tiles figure').count()) === 1, 15000);
3883 check(tiles, "the dropped member's tile is gone — " + (await diagnose(pageA, 'member A')));
3884 check(!(await state(pageA)).terminal, 'the member still on the team is still in the call');
3885
3886 await leaveRoom(pageA);
3887 await ctxA.close();
3888 await ctxB.close();
3889 },
3890
3891 // §4.5 and §13: a context whose stream is cut while a peer leaves
3892 // resumes, receives the roster, and has closed the connection to the
3893 // peer that left. The `gone` event never reached it; the roster is
3894 // what tells it.
3895 async departure() {
3896 const ctxA = await newContext('member A', { cookie: cookieA });
3897 const ctxB = await newContext('member B', { cookie: cookieB });
3898 const cut = await cuttableStream(ctxA);
3899 const pageA = await openRoom(ctxA);
3900 const pageB = await openRoom(ctxB);
3901 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
3902 if (!pair) {
3903 await ctxA.close();
3904 await ctxB.close();
3905 return;
3906 }
3907
3908 cut.on = true;
3909 check(await biteCut(cut), "A's attaching stream is cut (" + cut.aborted + ' aborted)');
3910
3911 await leaveRoom(pageB);
3912 cut.on = false;
3913
3914 const back = await until(async () => {
3915 const s = await state(pageA);
3916 return s.peer === pair.a.peer && !s.peers.includes(pair.b.peer) && !s.terminal ? s : false;
3917 }, 45000);
3918 check(back, 'A resumed its own participation and closed the connection to the peer that left — ' +
3919 (await diagnose(pageA, 'member A')));
3920 const tiles = await until(async () => (await pageA.locator('#tiles figure').count()) === 1, 15000);
3921 check(tiles, 'A is left with its own tile only — ' + (await diagnose(pageA, 'member A')));
3922
3923 await leaveRoom(pageA);
3924 await ctxA.close();
3925 await ctxB.close();
3926 },
3927
3928 // §4.5 and §13: signalling whose SSE delivery is cut after the POST's
3929 // 2xx is replayed on resume, and the pair connects. B forces an ICE
3930 // restart while A cannot hear it; the offer sits in A's ring; A's
3931 // resume replays it. B's own signalingState is the proof — it stays at
3932 // have-local-offer until A answers, so B returning to `stable` means
3933 // the replayed offer arrived and was answered.
3934 async replay() {
3935 const ctxA = await newContext('member A', { cookie: cookieA });
3936 const ctxB = await newContext('member B', { cookie: cookieB });
3937 const cut = await cuttableStream(ctxA);
3938 const pageA = await openRoom(ctxA);
3939 const pageB = await openRoom(ctxB);
3940 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
3941 if (!pair) {
3942 await ctxA.close();
3943 await ctxB.close();
3944 return;
3945 }
3946
3947 cut.on = true;
3948 check(await biteCut(cut), "A's attaching stream is cut (" + cut.aborted + ' aborted)');
3949
3950 // The Retry control on B's tile for A is restartIce. The page only
3951 // reveals it on a failed connection, so it is dispatched rather than
3952 // clicked: this scenario is about the signalling, not the control.
3953 await pageB.locator('#tiles figure:not(.calls-tile-self) figcaption button').first().dispatchEvent('click');
3954
3955 // Asserted while A is still cut, and this is the assertion that
3956 // makes the scenario mean anything: B has an offer out that A cannot
3957 // answer, so its signalingState leaves `stable`. Without this, the
3958 // ending state below is the starting state — B stable and connected,
3959 // A's frames still rising because the cut is on the SSE stream and
3960 // not on the media — and a dispatch that never reached restartIce
3961 // would pass.
3962 const offered = await until(async () => {
3963 const b = await state(pageB);
3964 return b.signaling[pair.a.peer] === 'have-local-offer' ? b : false;
3965 }, 5000);
3966 check(offered, 'B has signalling out that A cannot answer while it is cut — ' +
3967 (await diagnose(pageB, 'member B')));
3968
3969 await sleep(5000);
3970 cut.on = false;
3971
3972 const settled = await until(async () => {
3973 const b = await state(pageB);
3974 const a = await state(pageA);
3975 return b.signaling[pair.a.peer] === 'stable' && b.connection[pair.a.peer] === 'connected' &&
3976 a.peer === pair.a.peer && a.connection[pair.b.peer] === 'connected' ? { a, b } : false;
3977 }, 45000);
3978 check(settled, 'the offer B sent while A was cut was replayed on A’s resume and answered — ' +
3979 (await diagnose(pageB, 'member B')) + ' ' + (await diagnose(pageA, 'member A')));
3980
3981 const before = (await state(pageA)).frames[pair.b.peer] || 0;
3982 const rising = await until(async () => ((await state(pageA)).frames[pair.b.peer] || 0) > before, 25000);
3983 check(rising, 'A is decoding video again after the replay (' + before + ' -> ' +
3984 ((await state(pageA)).frames[pair.b.peer] || 0) + ')');
3985
3986 await leaveRoom(pageA);
3987 await leaveRoom(pageB);
3988 await ctxA.close();
3989 await ctxB.close();
3990 },
3991
3992 // §4.5, §4.6 and §13: more targeted messages than the ring holds
3993 // arrive while A is cut, so the replay cannot fill the hole. The hub
3994 // answers `gap`, A asks for a reset, the hub bumps the generation and
3995 // both sides rebuild.
3996 async gap() {
3997 const ctxA = await newContext('member A', { cookie: cookieA });
3998 const ctxB = await newContext('member B', { cookie: cookieB });
3999 const cut = await cuttableStream(ctxA);
4000 // A's own POSTs are counted, not touched: a `reset` from A is the
4001 // observable proof that it received `gap` — nothing else in the room
4002 // makes A ask for one.
4003 let resets = 0;
4004 await ctxA.route('**/signal', async (route) => {
4005 const body = route.request().postData() || '';
4006 if (body.includes('"type":"reset"')) resets += 1;
4007 await route.continue();
4008 });
4009 const pageA = await openRoom(ctxA);
4010 const pageB = await openRoom(ctxB);
4011 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
4012 if (!pair) {
4013 await ctxA.close();
4014 await ctxB.close();
4015 return;
4016 }
4017 check(resets === 0, 'nothing had reset this pair before the gap (' + resets + ')');
4018
4019 cut.on = true;
4020 check(await biteCut(cut), "A's attaching stream is cut (" + cut.aborted + ' aborted)');
4021
4022 // Forty targeted messages, from B's own page so they carry B's
4023 // session and peer, aimed at A. The ring holds thirty-two, and `seq`
4024 // starts far above anything room.js has sent, so every one of them
4025 // is above the cursor A resumes with and the eviction is a real
4026 // hole rather than an already-delivered prefix. `gen` is 1 because
4027 // nothing has reset this pair — the check above is what says so.
4028 const posted = await pageB.evaluate(async ({ room, to, n }) => {
4029 const me = window.meet.state().peer;
4030 let ok = 0;
4031 for (let i = 0; i < n; i++) {
4032 const res = await fetch('/m/' + room + '/signal', {
4033 method: 'POST',
4034 credentials: 'same-origin',
4035 headers: { 'Content-Type': 'application/json' },
4036 body: JSON.stringify({ peer: me, type: 'candidate', to, seq: 100000 + i, gen: 1, payload: {} }),
4037 });
4038 if (res.status === 200) ok += 1;
4039 }
4040 return ok;
4041 }, { room: sqid, to: pair.a.peer, n: 40 });
4042 check(posted === 40, 'B pushed forty targeted messages past A while it was cut (' + posted + ' accepted)');
4043
4044 cut.on = false;
4045
4046 const asked = await until(() => (resets > 0 ? resets : false), 45000);
4047 check(asked, 'A received `gap` and asked for a reset (' + resets + ' resets posted)');
4048
4049 const rebuilt = await until(async () => {
4050 const a = await state(pageA);
4051 const b = await state(pageB);
4052 return a.peer === pair.a.peer && !a.terminal &&
4053 a.peers.includes(pair.b.peer) && b.peers.includes(pair.a.peer) &&
4054 a.signaling[pair.b.peer] === 'stable' && a.connection[pair.b.peer] === 'connected' &&
4055 b.signaling[pair.a.peer] === 'stable' && b.connection[pair.a.peer] === 'connected' ? { a, b } : false;
4056 }, 45000);
4057 check(rebuilt, 'both sides rebuilt the pair at the new generation and connected — ' +
4058 (await diagnose(pageA, 'member A')) + ' ' + (await diagnose(pageB, 'member B')));
4059
4060 await leaveRoom(pageA);
4061 await leaveRoom(pageB);
4062 await ctxA.close();
4063 await ctxB.close();
4064 },
4065
4066 // The rest of §13's gap clause: "including when one side's `pair` was
4067 // cut and it learns the generation from the roster on its own resume".
4068 //
4069 // The reset comes from B, and A is cut across the whole of it, so A's
4070 // `pair` is never delivered. It is not replayed either: a `pair` is
4071 // only replayed when it carries a generation *above* the roster's, and
4072 // the roster carries the current one — so the roster is the only place
4073 // A can learn it (hub/relay.go's own note on that branch). A's
4074 // reconcile path is what has to notice: `ensurePC` with a generation
4075 // above the local one rebuilds.
4076 //
4077 // That A never asked is the assertion that separates this from the gap
4078 // scenario: its own `reset` count stays at zero throughout.
4079 async rosterpair() {
4080 const ctxA = await newContext('member A', { cookie: cookieA });
4081 const ctxB = await newContext('member B', { cookie: cookieB });
4082 const cut = await cuttableStream(ctxA);
4083 let resets = 0;
4084 await ctxA.route('**/signal', async (route) => {
4085 if ((route.request().postData() || '').includes('"type":"reset"')) resets += 1;
4086 await route.continue();
4087 });
4088 const pageA = await openRoom(ctxA);
4089 const pageB = await openRoom(ctxB);
4090 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
4091 if (!pair) {
4092 await ctxA.close();
4093 await ctxB.close();
4094 return;
4095 }
4096
4097 cut.on = true;
4098 check(await biteCut(cut), "A's attaching stream is cut (" + cut.aborted + ' aborted)');
4099
4100 // B resets the pair from its own page, so the request carries B's
4101 // session and peer and nothing on A's side is involved.
4102 const reset = await pageB.evaluate(async ({ room, to }) => {
4103 const res = await fetch('/m/' + room + '/signal', {
4104 method: 'POST',
4105 credentials: 'same-origin',
4106 headers: { 'Content-Type': 'application/json' },
4107 body: JSON.stringify({ peer: window.meet.state().peer, type: 'reset', to }),
4108 });
4109 return res.status;
4110 }, { room: sqid, to: pair.a.peer });
4111 check(reset === 200, 'B reset the pair while A was cut (' + reset + ')');
4112
4113 // B rebuilt on its own `pair`, which it did receive: its connection
4114 // to A leaves `connected` while A knows nothing about it.
4115 const bRebuilt = await until(async () => {
4116 const b = await state(pageB);
4117 return b.connection[pair.a.peer] !== 'connected' || b.signaling[pair.a.peer] !== 'stable' ? b : false;
4118 }, 15000);
4119 check(bRebuilt, 'B rebuilt its side at the new generation — ' + (await diagnose(pageB, 'member B')));
4120
4121 cut.on = false;
4122
4123 const rebuilt = await until(async () => {
4124 const a = await state(pageA);
4125 const b = await state(pageB);
4126 return a.peer === pair.a.peer && !a.terminal &&
4127 a.peers.includes(pair.b.peer) && b.peers.includes(pair.a.peer) &&
4128 a.signaling[pair.b.peer] === 'stable' && a.connection[pair.b.peer] === 'connected' &&
4129 b.signaling[pair.a.peer] === 'stable' && b.connection[pair.a.peer] === 'connected' ? { a, b } : false;
4130 }, 45000);
4131 // Connecting at all is the proof that A converged on B's generation:
4132 // the hub refuses signalling at any other one with 409, so a side
4133 // still at the old generation never gets an offer through.
4134 check(rebuilt, 'A learned the new generation from the roster alone and the pair connected again — ' +
4135 (await diagnose(pageA, 'member A')) + ' ' + (await diagnose(pageB, 'member B')));
4136 check(resets === 0, 'A never asked for a reset of its own (' + resets + ')');
4137
4138 const before = (await state(pageA)).frames[pair.b.peer] || 0;
4139 const rising = await until(async () => ((await state(pageA)).frames[pair.b.peer] || 0) > before, 25000);
4140 check(rising, 'A is decoding video over the rebuilt connection (' + before + ' -> ' +
4141 ((await state(pageA)).frames[pair.b.peer] || 0) + ')');
4142
4143 await leaveRoom(pageA);
4144 await leaveRoom(pageB);
4145 await ctxA.close();
4146 await ctxB.close();
4147 },
4148
4149 // A signal 404 that is about the *target*, not about us (Codex S2-3).
4150 // A's stream is cut, B leaves, and A — which cannot have heard `gone`
4151 // — sends B an offer. The hub answers 404 because B is not there any
4152 // more. That says nothing about A's own participation, and A must
4153 // stay in the call: the old client closed everything, opened a fresh
4154 // stream, met a 409 from its own still-live participation and put up
4155 // the takeover screen for a tab that does not exist.
4156 async staletarget() {
4157 const ctxA = await newContext('member A', { cookie: cookieA });
4158 const ctxB = await newContext('member B', { cookie: cookieB });
4159 const cut = await cuttableStream(ctxA);
4160 // A's own 404s are counted, to prove the scenario actually produced
4161 // the answer it is about rather than passing on a quiet call — and
4162 // so is everything A posts once the roster is known to be stale,
4163 // because "A is still here" was true of the twelve-round reset cycle
4164 // Codex S2-11 found as well.
4165 let notFound = 0;
4166 let posts = 0;
4167 let counting = false;
4168 await ctxA.route('**/signal', async (route) => {
4169 if (counting) posts += 1;
4170 const res = await route.fetch();
4171 if (res.status() === 404) notFound += 1;
4172 await route.fulfill({ response: res });
4173 });
4174 const pageA = await openRoom(ctxA);
4175 const pageB = await openRoom(ctxB);
4176 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
4177 if (!pair) {
4178 await ctxA.close();
4179 await ctxB.close();
4180 return;
4181 }
4182
4183 cut.on = true;
4184 check(await biteCut(cut), "A's attaching stream is cut (" + cut.aborted + ' aborted)');
4185
4186 await leaveRoom(pageB);
4187 counting = true;
4188 // The recovery's own probe is refused 503 to begin with. That says
4189 // nothing about anyone's participation, and acting on it recreated
4190 // the very failure this scenario is about (Codex S2-12).
4191 cut.probeFail = true;
4192
4193 // The Retry control on A's tile for B is restartIce, which fires
4194 // negotiationneeded and puts an offer on the wire for a peer that
4195 // is no longer in the room. Dispatched rather than clicked: the
4196 // scenario is about the answer, not about the control.
4197 await pageA.locator('#tiles figure:not(.calls-tile-self) figcaption button').first().dispatchEvent('click');
4198 const answered = await until(() => (notFound > 0 ? notFound : false), 20000);
4199 check(answered, 'A was answered 404 for a peer that had left (' + notFound + ')');
4200 const refusedProbe = await until(() => (cut.probesFailed > 0 ? cut.probesFailed : false), 20000);
4201 check(refusedProbe, 'a probe was answered 503 while A was diagnosing (' + cut.probesFailed + ')');
4202
4203 // Nothing about either answer is A's own ending, and A is still cut,
4204 // so the whole window is asserted rather than read once.
4205 const broke = await stayed(pageA, 8000, (s) => s.peer === pair.a.peer && !s.terminal);
4206 check(broke === null, 'A stayed in the call with its own peer id after the 404 and the 503 — ' +
4207 (broke ? JSON.stringify(broke) : 'held for eight seconds') + ' — ' + (await diagnose(pageA, 'member A')));
4208 const status = await statusText(pageA);
4209 check(!status.includes('another tab'), 'A was never shown the takeover screen (status: ' + status + ')');
4210
4211 // Now the probe answers, A learns its own participation is fine, and
4212 // whatever it does about the departed peer it does once: the roster
4213 // is what settles a stale target, not a reset cycle with a fresh
4214 // budget each round.
4215 cut.probeFail = false;
4216 await sleep(5000);
4217 check(posts <= 3, 'A posted at most three times while its roster was stale (' + posts + ')');
4218
4219 // What "reconciled" has to mean: not that A's own `pcs` no longer
4220 // has B — `staleTarget` closes that connection locally, while the
4221 // stream is still cut, so that was already true — but that A's
4222 // stream came back and the server told it who is here (Codex
4223 // S2-16). Both are counted from here.
4224 const attachesBefore = cut.attaches;
4225 const rostersBefore = (await state(pageA)).rosters;
4226 cut.on = false;
4227
4228 // And the departure reaches A the way §4.5 says it does: from the
4229 // roster on its own resume, not from the 404.
4230 const reconciled = await until(async () => {
4231 const s = await state(pageA);
4232 return cut.attaches > attachesBefore && s.rosters > rostersBefore &&
4233 s.peer === pair.a.peer && !s.terminal && !s.peers.includes(pair.b.peer) ? s : false;
4234 }, 45000);
4235 check(reconciled, 'A resumed its stream, was sent a fresh roster, and has let the departed peer go — ' +
4236 'attaches ' + attachesBefore + '→' + cut.attaches + ', rosters ' + rostersBefore + '→' +
4237 ((await state(pageA)).rosters) + ' — ' + (await diagnose(pageA, 'member A')));
4238 // Counted across the whole recovery, not only the first five
4239 // seconds of it: a cycle that started late would still be a cycle.
4240 // The round-1 client posted four hundred and fifty times here.
4241 check(posts <= 6, 'the whole recovery cost a handful of requests, not a cycle (' + posts + ')');
4242
4243 await leaveRoom(pageA);
4244 await ctxA.close();
4245 await ctxB.close();
4246 },
4247
4248 // §4.6's thirty seconds again, this time over the *diagnosis* rather
4249 // than the message (Codex S2-15). A signal 404 sends the client to
4250 // probe its own participation; that probe never settles. Two things
4251 // have to hold: the probe is aborted rather than awaited for ever, and
4252 // the clock it is aborted on is the one the message started — the 404
4253 // here is deliberately answered twenty seconds late, so a recovery
4254 // that took a fresh thirty seconds would land at fifty and fail the
4255 // measurement rather than merely being slower.
4256 async probehang() {
4257 const ctxA = await newContext('member A', { cookie: cookieA });
4258 const ctxB = await newContext('member B', { cookie: cookieB });
4259 const pageA = await openRoom(ctxA);
4260 const pageB = await openRoom(ctxB);
4261 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
4262 if (!pair) {
4263 await ctxA.close();
4264 await ctxB.close();
4265 return;
4266 }
4267
4268 // §15.24: A reports who it hears once the pair is up; let that report
4269 // go before everything A posts is held, or it is counted below as a
4270 // second message the recovery sent.
4271 const settled = await until(async () => ((await state(pageA)).hearingList || []).includes(pair.b.peer), 10000);
4272 check(settled, 'A reports that it hears B before the cut');
4273 await sleep(500);
4274
4275 let firstAt = 0;
4276 let signals = 0;
4277 const posted = [];
4278 let hungProbes = 0;
4279 // Everything A posts from here is answered 404, twenty seconds
4280 // after it was sent: "that peer is not here", arriving with a third
4281 // of the message's budget left.
4282 await ctxA.route('**/signal', async (route) => {
4283 const m = (route.request().postData() || '').match(/"type":"([a-z-]+)"/);
4284 posted.push(m ? m[1] : '?');
4285 // A media report is state on the broadcast lane, not part of the
4286 // recovery under test: §15.30's asks change when the picture from B
4287 // stops, and again when B is let go. It is answered like the rest
4288 // and not counted.
4289 if (m && m[1] === 'media') {
4290 await route.fulfill({ status: 404, contentType: 'application/json', body: '{"error":"not-found"}' });
4291 return;
4292 }
4293 if (!firstAt) firstAt = Date.now();
4294 signals += 1;
4295 await sleep(20000);
4296 await route.fulfill({ status: 404, contentType: 'application/json', body: '{"error":"not-found"}' });
4297 });
4298 // And the probe that follows never answers at all. Only the probe
4299 // forms: A's own stream stays up, so nothing else is being tested.
4300 await ctxA.route('**/stream*', async (route) => {
4301 if (!route.request().url().includes('probe=1')) {
4302 await route.continue();
4303 return;
4304 }
4305 hungProbes += 1;
4306 await new Promise(() => {});
4307 });
4308
4309 await pageA.locator('#tiles figure:not(.calls-tile-self) figcaption button').first().dispatchEvent('click');
4310
4311 const dropped = await until(async () => {
4312 const s = await state(pageA);
4313 return !s.peers.includes(pair.b.peer) ? s : false;
4314 }, 70000);
4315 check(dropped, 'A let the target go rather than waiting on a probe that never answers (' + signals +
4316 ' signals, ' + hungProbes + ' hung probes) — ' + (await diagnose(pageA, 'member A')));
4317 check(hungProbes > 0, 'the scenario actually hung the probe it meant to (' + hungProbes + ')');
4318 const took = Date.now() - firstAt;
4319 check(took >= 25000 && took <= 35000,
4320 'and it did so on the message’s own clock, not a fresh one (' + took + ' ms; a restarted clock lands near 50000)');
4321
4322 // Dropping the target on time is not the claim. The claim is that
4323 // the recovery ended there — and a client that let the queue restart
4324 // would look identical at this instant while a reset ran on a fresh
4325 // thirty seconds behind it (Codex S2-17). So: the one message this
4326 // scenario sent is the only thing A ever posted, and it is still the
4327 // only thing ten seconds later.
4328 const atDrop = signals;
4329 check(atDrop === 1, 'the offer was the only message A posted (' + atDrop + ': ' + posted.join(', ') + ')');
4330 check(dropped && dropped.stale && dropped.stale.includes(pair.b.peer),
4331 'and A holds the target marked stale, waiting for a roster rather than asking again (' +
4332 JSON.stringify(dropped && dropped.stale) + ')');
4333 await sleep(10000);
4334 check(signals === atDrop, 'nothing followed it, ten seconds on (' + atDrop + ' → ' + signals + ')');
4335
4336 const after = await state(pageA);
4337 check(after.peer === pair.a.peer && !after.terminal,
4338 'A is still in the call with its own peer id — ' + (await diagnose(pageA, 'member A')));
4339
4340 await ctxA.close();
4341 await ctxB.close();
4342 },
4343
4344 // §4.6 and Codex S2-5: a `reset` refused with 429 used to be dropped
4345 // on the floor, and after an outbound deadline that reset is the only
4346 // thing left that can rebuild the pair — the queue has been thrown
4347 // away and the connection closed, the hub's generation has not moved,
4348 // and no `pair` is coming. So this scenario walks A into exactly that
4349 // corner: everything it posts is refused until the deadline fires,
4350 // and then the reset the deadline asks for is refused once more.
4351 async resetretry() {
4352 const ctxA = await newContext('member A', { cookie: cookieA });
4353 const ctxB = await newContext('member B', { cookie: cookieB });
4354 let failing = false;
4355 let resets = 0;
4356 await ctxA.route('**/signal', async (route) => {
4357 const isReset = (route.request().postData() || '').includes('"type":"reset"');
4358 if (isReset) {
4359 resets += 1;
4360 // The deadline has done its work; the room is reachable again
4361 // and only the reset itself is in question.
4362 failing = false;
4363 if (resets === 1) {
4364 await route.fulfill({
4365 status: 429,
4366 headers: { 'retry-after': '1' },
4367 contentType: 'application/json',
4368 body: '{"error":"rate"}',
4369 });
4370 return;
4371 }
4372 await route.continue();
4373 return;
4374 }
4375 if (failing) {
4376 await route.fulfill({ status: 503, contentType: 'application/json', body: '{"error":"full"}' });
4377 return;
4378 }
4379 await route.continue();
4380 });
4381 const pageA = await openRoom(ctxA);
4382 const pageB = await openRoom(ctxB);
4383 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
4384 if (!pair) {
4385 await ctxA.close();
4386 await ctxB.close();
4387 return;
4388 }
4389 check(resets === 0, 'nothing had reset this pair before this (' + resets + ')');
4390
4391 failing = true;
4392 await pageA.locator('#tiles figure:not(.calls-tile-self) figcaption button').first().dispatchEvent('click');
4393
4394 const asked = await until(() => (resets > 0 ? resets : false), 60000);
4395 check(asked, 'A hit its outbound deadline and asked for a reset (' + resets + ')');
4396 const askedTwice = await until(() => (resets > 1 ? resets : false), 30000);
4397 check(askedTwice, 'A asked again after the 429 rather than losing the reset (' + resets + ' asks)');
4398
4399 const rebuilt = await until(async () => {
4400 const a = await state(pageA);
4401 const b = await state(pageB);
4402 return a.peer === pair.a.peer && !a.terminal &&
4403 a.signaling[pair.b.peer] === 'stable' && a.connection[pair.b.peer] === 'connected' &&
4404 b.signaling[pair.a.peer] === 'stable' && b.connection[pair.a.peer] === 'connected' ? { a, b } : false;
4405 }, 45000);
4406 check(rebuilt, 'the pair came back, on a reset that was refused the first time — ' +
4407 (await diagnose(pageA, 'member A')) + ' ' + (await diagnose(pageB, 'member B')));
4408
4409 const before = (await state(pageA)).frames[pair.b.peer] || 0;
4410 const rising = await until(async () => ((await state(pageA)).frames[pair.b.peer] || 0) > before, 25000);
4411 check(rising, 'A is decoding video over the rebuilt connection (' + before + ' -> ' +
4412 ((await state(pageA)).frames[pair.b.peer] || 0) + ')');
4413
4414 await leaveRoom(pageA);
4415 await leaveRoom(pageB);
4416 await ctxA.close();
4417 await ctxB.close();
4418 },
4419
4420 // §4.6's thirty seconds, under continuous 429s (Codex S2-6). Every
4421 // retry used to skip the deadline check, so a rate-limited target was
4422 // retried for ever and the connection to it was never rebuilt. What
4423 // is asserted is the verdict — A closes the connection to B — not how
4424 // long it took to reach it.
4425 async senddeadline() {
4426 const ctxA = await newContext('member A', { cookie: cookieA });
4427 const ctxB = await newContext('member B', { cookie: cookieB });
4428 const pageA = await openRoom(ctxA);
4429 const pageB = await openRoom(ctxB);
4430 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
4431 if (!pair) {
4432 await ctxA.close();
4433 await ctxB.close();
4434 return;
4435 }
4436
4437 // Only from here: the join and the whole negotiation above went
4438 // through untouched, so what is being timed is one message.
4439 let limited = 0;
4440 let firstAt = 0;
4441 await ctxA.route('**/signal', async (route) => {
4442 if (!firstAt) firstAt = Date.now();
4443 limited += 1;
4444 await route.fulfill({
4445 status: 429,
4446 headers: { 'retry-after': '1' },
4447 contentType: 'application/json',
4448 body: '{"error":"rate"}',
4449 });
4450 });
4451 await pageA.locator('#tiles figure:not(.calls-tile-self) figcaption button').first().dispatchEvent('click');
4452
4453 const gaveUp = await until(async () => {
4454 const s = await state(pageA);
4455 return !s.peers.includes(pair.b.peer) ? s : false;
4456 }, 60000);
4457 check(gaveUp, 'A gave up on an endlessly rate-limited target (' + limited +
4458 ' refusals) — ' + (await diagnose(pageA, 'member A')));
4459 // §4.6's number, not merely "eventually": measured from the first
4460 // message this route saw, which is the one whose deadline is
4461 // running. Five seconds of tolerance for the polling and the
4462 // scheduler at either end (Codex S2-13).
4463 const took = Date.now() - firstAt;
4464 check(took >= 25000 && took <= 35000,
4465 'and it gave up on §4.6’s thirty seconds, not on its own clock (' + took + ' ms)');
4466 check(limited > 1, 'and it did retry rather than giving up on the first refusal (' + limited + ')');
4467 check(!(await state(pageA)).terminal, 'giving up on one target is not the end of the call');
4468
4469 await ctxA.close();
4470 await ctxB.close();
4471 },
4472
4473 // The other half of the same deadline: a request that never settles at
4474 // all. Without an abort on the fetch the pump simply waits for ever,
4475 // and the deadline check is never even reached (Codex S2-6).
4476 async sendhang() {
4477 const ctxA = await newContext('member A', { cookie: cookieA });
4478 const ctxB = await newContext('member B', { cookie: cookieB });
4479 const pageA = await openRoom(ctxA);
4480 const pageB = await openRoom(ctxB);
4481 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
4482 if (!pair) {
4483 await ctxA.close();
4484 await ctxB.close();
4485 return;
4486 }
4487
4488 let hung = 0;
4489 let firstAt = 0;
4490 // The abort itself, watched from outside the page: a fetch the page
4491 // gives up on fails, and that is the only direct evidence that the
4492 // AbortController fired rather than the request having settled some
4493 // other way (Codex S2-13).
4494 let cancelled = 0;
4495 pageA.on('requestfailed', (req) => {
4496 if (req.url().includes('/signal')) cancelled += 1;
4497 });
4498 await ctxA.route('**/signal', async () => {
4499 if (!firstAt) firstAt = Date.now();
4500 hung += 1;
4501 // Never fulfilled, never continued, never aborted: the request
4502 // stays pending until the page itself gives up on it.
4503 await new Promise(() => {});
4504 });
4505 await pageA.locator('#tiles figure:not(.calls-tile-self) figcaption button').first().dispatchEvent('click');
4506
4507 const gaveUp = await until(async () => {
4508 const s = await state(pageA);
4509 return !s.peers.includes(pair.b.peer) ? s : false;
4510 }, 60000);
4511 check(gaveUp, 'A gave up on a target whose requests never settle (' + hung +
4512 ' hung requests) — ' + (await diagnose(pageA, 'member A')));
4513 check(hung > 0, 'the scenario actually hung the request it meant to (' + hung + ')');
4514 check(cancelled > 0, 'and the page aborted it rather than waiting for it (' + cancelled + ' cancelled)');
4515 const took = Date.now() - firstAt;
4516 check(took >= 25000 && took <= 35000,
4517 'the abort came at §4.6’s thirty seconds (' + took + ' ms)');
4518 check(!(await state(pageA)).terminal, 'a hanging endpoint is not the end of the call either');
4519
4520 await ctxA.close();
4521 await ctxB.close();
4522 },
4523
4524 // The process goes away and comes back. Both browsers see the stream
4525 // die, find a boot they do not know, and rejoin (§4.5).
4526 async restart() {
4527 const ctxA = await newContext('member A', { cookie: cookieA });
4528 const ctxB = await newContext('member B', { cookie: cookieB });
4529 const pageA = await openRoom(ctxA);
4530 const pageB = await openRoom(ctxB);
4531
4532 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
4533 if (!pair) {
4534 await ctxA.close();
4535 await ctxB.close();
4536 return;
4537 }
4538 const bootBefore = (await state(pageA)).boot;
4539 check(!!bootBefore, 'the browser knows which process it is talking to (boot ' + bootBefore + ')');
4540
4541 // §13 asks that both contexts have closed their old connections
4542 // *before* rejoining, and that is a moment rather than a state: the
4543 // gap between closeAllPCs and the roster of the new participation is
4544 // one round trip wide. A poll from out here would step over it, so
4545 // each page watches itself, five milliseconds at a time, from before
4546 // the restart until after the new peer ids arrive.
4547 for (const page of [pageA, pageB]) {
4548 await page.evaluate(() => {
4549 window.__sawEmpty = false;
4550 window.__samples = 0;
4551 window.__watch = setInterval(() => {
4552 window.__samples += 1;
4553 if (window.meet.state().peers.length === 0) window.__sawEmpty = true;
4554 }, 5);
4555 });
4556 }
4557
4558 const answer = await control('restart');
4559 check(answer === 'ok', 'the app restarted on the same port (' + answer + ')');
4560
4561 const back = await until(async () => {
4562 const a = await state(pageA);
4563 const b = await state(pageB);
4564 return a.peer && b.peer && a.peer !== pair.a.peer && b.peer !== pair.b.peer ? { a, b } : false;
4565 }, 60000);
4566 check(back, 'both browsers took a new participation after the restart — ' +
4567 (await diagnose(pageA, 'member A')) + ' ' + (await diagnose(pageB, 'member B')));
4568
4569 // §13: "a different-boot 404 after restart" (W-3). New peer ids are
4570 // not that: a hub whose boot came from something stable would issue
4571 // new ids too, and `recoverFromNotFound` would lose the one thing
4572 // that tells a restart from a lapsed resume window (§4.5).
4573 const bootAfter = back ? back.a.boot : (await state(pageA)).boot;
4574 check(!!bootAfter && bootAfter !== bootBefore,
4575 'the restarted process announced a different boot id (' + bootBefore + ' then ' + bootAfter + ')');
4576
4577 for (const [page, label] of [[pageA, 'member A'], [pageB, 'member B']]) {
4578 const watched = await page.evaluate(() => {
4579 clearInterval(window.__watch);
4580 return { sawEmpty: window.__sawEmpty, samples: window.__samples };
4581 });
4582 check(watched.sawEmpty, label + ' held no peer connections at all between the old participation and the new one (' +
4583 watched.samples + ' samples)');
4584 }
4585
4586 if (back) await assertPair(pageA, pageB, 'member A', 'member B', 40000);
4587
4588 await leaveRoom(pageA);
4589 await leaveRoom(pageB);
4590 await ctxA.close();
4591 await ctxB.close();
4592 },
4593
4594 // §4.2: one peer per session per room, and nothing displaces a tab
4595 // automatically. The second tab is refused and offers the confirm
4596 // page; confirming it is what ends the first.
4597 async takeover() {
4598 const ctxA = await newContext('member A', { cookie: cookieA });
4599 const first = await openRoom(ctxA);
4600 check(await until(async () => (await state(first)).peer, 20000),
4601 'the first tab is in the room — ' + (await diagnose(first, 'member A')));
4602
4603 const second = await openRoom(ctxA);
4604 check(await waitStatus(second, 'This meeting is open in another tab.', 20000),
4605 'the second tab is told the meeting is open elsewhere — status: ' + (await statusText(second)));
4606 const secondState = await state(second);
4607 check(secondState.peer === null,
4608 'the second tab took no participation (' + secondState.peer + ')');
4609
4610 // Not a single read: "was not displaced" is a claim about a window
4611 // of time, and the displacement it is denying would arrive over a
4612 // stream a moment later if it were going to arrive at all.
4613 await sleep(1000);
4614 const displaced = await stayed(first, 3000, (s) => s.peer !== null && !s.terminal);
4615 check(displaced === null,
4616 'the first tab was not displaced by the second opening (' + JSON.stringify(displaced) + ')');
4617
4618 // Located by the href, not by "the link in #status": a terminal
4619 // screen may carry more than one way out, and this scenario is about
4620 // the one that takes the call over.
4621 const takeover = second.locator('#status a[href$="/takeover"]');
4622 const takeoverHref = await takeover.getAttribute('href');
4623 check(takeoverHref === '/m/' + sqid + '/takeover',
4624 'the second tab offers the takeover page (' + takeoverHref + ')');
4625
4626 await Promise.all([
4627 second.waitForURL('**/m/' + sqid + '/takeover', { timeout: 15000 }),
4628 takeover.click(),
4629 ]);
4630 await Promise.all([
4631 second.waitForURL(origin + '/m/' + sqid, { timeout: 15000 }),
4632 second.click('form[rst-form-actions] button[type="submit"]'),
4633 ]);
4634 check(second.url() === origin + '/m/' + sqid,
4635 'the confirmed takeover lands the second tab in the room (at ' + where(second) + ')');
4636
4637 check(await waitStatus(first, 'This meeting is open in another tab.', 20000),
4638 'the first tab is told it lost the call — status: ' + (await statusText(first)));
4639 const lost = await state(first);
4640 check(lost.terminal === 'replaced' && lost.admitted === false,
4641 'the displaced tab is terminal on `replaced` and no longer admitted (' + JSON.stringify(lost) + ')');
4642
4643 // Terminal means terminal: nothing reconnects on its own.
4644 const reconnected = await stayed(first, 5000, (s) => s.peers.length === 0 && s.terminal === 'replaced');
4645 check(reconnected === null,
4646 'the displaced tab did not reconnect (' + JSON.stringify(reconnected) + ')');
4647
4648 await ctxA.close();
4649 },
4650
4651 // A GET from somewhere else on the web ends nothing: the takeover is
4652 // a POST behind its own confirm page (§4.2), and a top-level
4653 // navigation does not even reach the stream (ruling 15).
4654 async crosssite() {
4655 const ctxA = await newContext('member A', { cookie: cookieA });
4656 const page = await openRoom(ctxA);
4657 check(await until(async () => (await state(page)).peer, 20000),
4658 'the call is up before the cross-site visit — ' + (await diagnose(page, 'member A')));
4659 const before = await state(page);
4660
4661 await ctxA.route('http://elsewhere.test/**', (route) =>
4662 route.fulfill({
4663 status: 200,
4664 contentType: 'text/html',
4665 body: '<!doctype html><a id="go" href="' + origin + '/m/' + sqid + '/takeover">go</a>' +
4666 '<a id="stream" href="' + origin + '/m/' + sqid + '/stream">stream</a>',
4667 }));
4668
4669 const other = await ctxA.newPage();
4670 await other.goto('http://elsewhere.test/', { waitUntil: 'domcontentloaded' });
4671 check(new URL(other.url()).origin !== origin, 'the other page really is another origin (' + other.url() + ')');
4672
4673 await Promise.all([
4674 other.waitForURL('**/m/' + sqid + '/takeover', { timeout: 15000 }),
4675 other.click('#go'),
4676 ]);
4677 check(other.url() === origin + '/m/' + sqid + '/takeover',
4678 'the cross-site GET reached the takeover URL (at ' + where(other) + ')');
4679
4680 // And the navigation to the stream itself, which must not take this
4681 // session's peer slot either.
4682 await other.goto('http://elsewhere.test/', { waitUntil: 'domcontentloaded' });
4683 await Promise.all([
4684 other.waitForURL('**/m/' + sqid + '/stream', { timeout: 15000 }),
4685 other.click('#stream'),
4686 ]);
4687 check(other.url() === origin + '/m/' + sqid + '/stream',
4688 'the cross-site GET reached the stream URL (at ' + where(other) + ')');
4689 // Ruling 15, seen from a browser: a top-level navigation asks for
4690 // HTML, so it is refused before anything is looked up and cannot
4691 // occupy this session's one peer slot for the resume window. The
4692 // exact bytes, because the whole point of that refusal is that it
4693 // is identical for every meeting and every person.
4694 const refusal = (await other.locator('body').innerText()).trim();
4695 check(refusal === '{"error":"accept"}',
4696 'the navigation was refused with exactly the accept error (' + refusal + ')');
4697
4698 const disturbed = await stayed(page, 3000,
4699 (s) => s.peer === before.peer && !s.terminal);
4700 check(disturbed === null,
4701 'the call kept its participation through the cross-site GETs (' + JSON.stringify(disturbed) + ')');
4702 check(!(await statusText(page)).includes('This meeting is open in another tab.'),
4703 'the call was not displaced by a GET — status: ' + (await statusText(page)));
4704
4705 await leaveRoom(page);
4706 await ctxA.close();
4707 },
4708
4709 // A refusal the probe cannot name: the room is full, which the
4710 // peerless probe answers 204 to because this session holds no peer
4711 // here. Without a ceiling the client would retry that for ever behind
4712 // "Connecting to the call."; with one it stops and says something
4713 // true, with both ways out.
4714 async stall() {
4715 const ctx = await newContext('member A', { cookie: cookieA });
4716 await ctx.route('**/stream*', async (route) => {
4717 if (route.request().url().includes('probe=1')) {
4718 await route.continue();
4719 return;
4720 }
4721 await route.fulfill({ status: 503, contentType: 'application/json', body: '{"error":"full"}' });
4722 });
4723 const page = await openRoom(ctx);
4724
4725 // Deliberately generous: the ceiling is a count of rounds and a
4726 // stretch of time, and the backoff between rounds is the client's
4727 // own. What is asserted is where it ends up, never how long it took.
4728 const ended = await until(async () => ((await state(page)).terminal === 'unreachable' ? true : false), 130000);
4729 check(ended, 'a refusal the probe cannot name stops rather than retrying for ever — ' +
4730 (await diagnose(page, 'member A')));
4731 check(await waitStatus(page, 'Calls cannot reach the call.', 10000),
4732 'the stalled room says something true — status: ' + (await statusText(page)));
4733 const hrefs = await page.locator('#status a').evaluateAll((as) => as.map((a) => a.getAttribute('href')));
4734 check(hrefs.includes('/m/' + sqid) && hrefs.includes('/m/' + sqid + '/join'),
4735 'the stalled room offers both ways out (' + JSON.stringify(hrefs) + ')');
4736
4737 await ctx.close();
4738 },
4739
4740 // An expired session answers the signal endpoint 403. That is not
4741 // transient and never becomes true by waiting, so the room says so and
4742 // offers the one thing that fixes it.
4743 async signedout() {
4744 const ctx = await newContext('member A', { cookie: cookieA });
4745 await ctx.route('**/signal', (route) =>
4746 route.fulfill({ status: 403, contentType: 'text/plain', body: 'forbidden' }));
4747 const page = await openRoom(ctx);
4748
4749 const out = await until(async () => ((await state(page)).terminal === 'signedout' ? true : false), 30000);
4750 check(out, 'a 403 from the signal endpoint ends the call as signed out — ' + (await diagnose(page, 'member A')));
4751 check(await waitStatus(page, 'You have been signed out.', 10000),
4752 'the signed-out room says so — status: ' + (await statusText(page)));
4753 const href = await page.locator('#status a').first().getAttribute('href');
4754 // Back in, and back to this meeting's holding screen (spec §9.4).
4755 check(href === '/signin?return_to=' + encodeURIComponent('/m/' + sqid + '/join'), 'the signed-out room offers the way back in, to this meeting (' + href + ')');
4756
4757 await ctx.close();
4758
4759 // The other half of the same rule, and the one the client explicitly
4760 // implements the compatibility for: a session that has expired can
4761 // answer a POST with a redirect to sign-in instead of a 403. fetch
4762 // follows it, so what comes back is a 200 carrying the sign-in page
4763 // — which read as a status alone is success, and was being taken as
4764 // success (Codex S2-8). Member B, because A's participation from the
4765 // phase above is still inside its resume window.
4766 const ctxB = await newContext('member B', { cookie: cookieB });
4767 await ctxB.route('**/signal', (route) =>
4768 route.fulfill({ status: 303, headers: { location: origin + '/signin' } }));
4769 const pageB = await openRoom(ctxB);
4770
4771 const redirected = await until(async () => ((await state(pageB)).terminal === 'signedout' ? true : false), 30000);
4772 check(redirected, 'a POST redirected to sign-in ends the call as signed out, not as a success — ' +
4773 (await diagnose(pageB, 'member B')));
4774 check(await waitStatus(pageB, 'You have been signed out.', 10000),
4775 'the redirected room says the same thing — status: ' + (await statusText(pageB)));
4776
4777 await ctxB.close();
4778 },
4779
4780 // A browser with no WebRTC at all. The room needs another peer before
4781 // it tries to build a connection, so B is in the call first.
4782 async nowebrtc() {
4783 const ctxB = await newContext('member B', { cookie: cookieB });
4784 const pageB = await openRoom(ctxB);
4785 check(await until(async () => (await state(pageB)).admitted, 20000),
4786 'the other member is in the room — ' + (await diagnose(pageB, 'member B')));
4787
4788 const ctxA = await newContext('member A', { cookie: cookieA });
4789 await ctxA.addInitScript(() => {
4790 delete window.RTCPeerConnection;
4791 });
4792 const pageA = await openRoom(ctxA);
4793
4794 const ended = await until(async () => ((await state(pageA)).terminal === 'nowebrtc' ? true : false), 30000);
4795 check(ended, 'a browser that cannot make calls is told so rather than sitting on an empty grid — ' +
4796 (await diagnose(pageA, 'member A')));
4797 check(await waitStatus(pageA, 'This browser cannot make calls.', 10000),
4798 'the sentence says what is wrong — status: ' + (await statusText(pageA)));
4799 const href = await pageA.locator('#status a').first().getAttribute('href');
4800 check(href === '/m/' + sqid + '/join', 'even this is not a dead end (' + href + ')');
4801
4802 await leaveRoom(pageB);
4803 await ctxA.close();
4804 await ctxB.close();
4805 },
4806
4807 // An autoplay policy that refuses a remote video: the tile offers the
4808 // gesture rather than leaving a still frame nobody can explain. The
4809 // refusal is applied to unmuted elements only, which is every remote
4810 // tile and no local one, and it lasts one call so the control can be
4811 // seen to work.
4812 async playfallback() {
4813 const ctxA = await newContext('member A', { cookie: cookieA });
4814 await ctxA.addInitScript(refuseFirstPlay);
4815 const ctxB = await newContext('member B', { cookie: cookieB });
4816 const pageA = await openRoom(ctxA);
4817 const pageB = await openRoom(ctxB);
4818
4819 const a = await waitConnected(pageA);
4820 check(a, 'A is in the call with a peer — ' + (await diagnose(pageA, 'member A')));
4821 const b = await waitConnected(pageB);
4822 check(b, 'B is in the call with a peer — ' + (await diagnose(pageB, 'member B')));
4823
4824 // The two buttons in a remote tile's caption are Retry and Play, in
4825 // that order.
4826 const play = pageA.locator('#tiles figure:not(.calls-tile-self) figcaption button').nth(1);
4827 const offered = await until(async () => await play.isVisible(), 25000);
4828 check(offered, 'the refused remote video offers a Play control — ' + (await diagnose(pageA, 'member A')));
4829 if (offered) {
4830 // What the control has to actually do. The click handler hides the
4831 // button before it attempts playback, so "the button went" was
4832 // satisfied by a handler that never called play() at all (Codex
4833 // S2-9): the assertion is frames arriving and the element's own
4834 // clock moving, both of which stop while it is paused.
4835 const before = (await state(pageA)).frames[b.peer] || 0;
4836 const still = await remoteTile(pageA);
4837 check(still && still.paused, 'the refused video is paused before the gesture (' + JSON.stringify(still) + ')');
4838
4839 await play.click();
4840 const taken = await until(async () => !(await play.isVisible()), 20000);
4841 check(taken, 'the gesture starts the video and the control goes — ' + (await diagnose(pageA, 'member A')));
4842
4843 const advancing = await until(async () => {
4844 const s = await state(pageA);
4845 const t = await remoteTile(pageA);
4846 return (s.frames[b.peer] || 0) > before && t && !t.paused && t.time > (still ? still.time : 0)
4847 ? { frames: s.frames[b.peer], tile: t }
4848 : false;
4849 }, 25000);
4850 check(advancing, 'the gesture starts the frames as well as hiding the control (from ' + before +
4851 ' frames; ' + JSON.stringify(advancing || (await remoteTile(pageA))) + ') — ' +
4852 (await diagnose(pageA, 'member A')));
4853 }
4854
4855 await leaveRoom(pageA);
4856 await leaveRoom(pageB);
4857 await ctxA.close();
4858 await ctxB.close();
4859 },
4860
4861 // Spec §15.20, the autoplay half, in a Chromium launched under its
4862 // real desktop policy rather than the gate's permissive one, and never
4863 // given a gesture. First what the incident of 2026-09-25 settled:
4864 // Chromium plays a MediaStream without a gesture whatever its policy,
4865 // so the call just plays and no banner appears — if that ever changes,
4866 // this is where it shows. Then a refusal, forced the way playfallback
4867 // forces one: the banner, the report reaching the other side as a
4868 // notice on this tab's tile, and a click anywhere putting it all back.
4869 async autoplay() {
4870 const strict = await chromium.launch({
4871 args: LAUNCH_ARGS.filter((a) => !a.startsWith('--autoplay-policy=')).concat(
4872 '--autoplay-policy=document-user-activation-required'),
4873 });
4874 try {
4875 const ctxA = await newContext('member A', { cookie: cookieA, via: strict });
4876 const ctxB = await newContext('member B', { cookie: cookieB, via: strict });
4877 // No evaluate may touch A's page until its remote tile has played:
4878 // Playwright runs page.evaluate as a user gesture, so the gate's
4879 // own polling would be the activation this is proving is not
4880 // needed. So A's page reports for itself, through the console, the
4881 // moment an unmuted element starts playing and whether it had been
4882 // activated by then — and A is opened with a bare goto, not
4883 // openRoom, whose waitForFunction is an evaluate too.
4884 await ctxA.addInitScript(() => {
4885 document.addEventListener('playing', (e) => {
4886 const el = e.target;
4887 if (!el || el.muted || el.dataset.reported) return;
4888 el.dataset.reported = '1';
4889 const active = navigator.userActivation ? navigator.userActivation.hasBeenActive : 'unknown';
4890 console.log('calls-autoplay: playing active=' + active);
4891 }, true);
4892 });
4893 let pageA = await ctxA.newPage();
4894 const firstPlay = new Promise((resolve) => {
4895 pageA.on('console', (m) => {
4896 if (m.text().startsWith('calls-autoplay:')) resolve(m.text());
4897 });
4898 });
4899 await pageA.goto(origin + '/m/' + sqid, { waitUntil: 'domcontentloaded' });
4900 const pageB = await openRoom(ctxB);
4901 const played = await Promise.race([firstPlay, sleep(30000).then(() => null)]);
4902 check(played, 'with no gesture, A’s remote tile starts playing under the real policy (' + played + ')');
4903 check(played === 'calls-autoplay: playing active=false',
4904 'and A’s page had really had no gesture when it did (' + played + ')');
4905 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
4906 if (!pair) return;
4907 const nameA = await selfName(pageA);
4908
4909 const plays = await until(async () => {
4910 const t = await remoteTile(pageA);
4911 return t && t.hasStream && !t.paused && t.time > 0.5 ? t : false;
4912 }, 15000);
4913 check(plays, 'and it goes on playing (' + JSON.stringify(plays || (await remoteTile(pageA))) + ')');
4914 const calm = await stayed(pageA, 3000, (s) => !s.soundBanner && !s.audioBlocked);
4915 check(!calm, 'no banner and nothing blocked (' + JSON.stringify(calm && { banner: calm.soundBanner, blocked: calm.audioBlocked }) + ')');
4916 check(!(await pageA.locator('#sound-banner').isVisible()), 'the banner is not on the page');
4917
4918 // Now a browser that refuses. A comes back in a fresh page whose
4919 // first unmuted play() is refused.
4920 await leaveRoom(pageA);
4921 await pageA.close();
4922 await ctxA.addInitScript(refuseFirstPlay);
4923 pageA = await openRoom(ctxA);
4924 const again = await waitConnected(pageA);
4925 check(again, 'A is back in the call — ' + (await diagnose(pageA, 'member A')));
4926 if (!again) return;
4927 const a = again.peer;
4928 const b = pair.b.peer;
4929
4930 const banner = await until(async () => {
4931 const s = await state(pageA);
4932 return s.soundBanner && s.audioBlocked ? s : false;
4933 }, 20000);
4934 check(banner, 'the refusal puts the banner up and marks A blocked — ' + (await diagnose(pageA, 'member A')));
4935 const bannerText = ((await pageA.locator('#sound-banner').textContent()) || '').trim();
4936 check(await pageA.locator('#sound-banner').isVisible() && bannerText.startsWith('Click anywhere to turn on sound'),
4937 'the banner says what to do, in words (' + bannerText + ')');
4938 check(await pageA.locator('#sound-banner button').isVisible(), 'with a button a keyboard can reach');
4939 check(await pageA.evaluate(() => !!document.querySelector('.calls-window #notices > #sound-banner')),
4940 'in the call window\'s notices, which stay whatever the controls do');
4941 const winOut = process.env.CALLS_WINDOW_SNAPSHOTS;
4942 if (winOut) {
4943 mkdirSync(winOut, { recursive: true });
4944 await pageA.screenshot({ path: winOut + '/web-autoplay-banner.png' });
4945 }
4946 const refusedTile = await until(async () => {
4947 const s = await state(pageA);
4948 return s.hearing[b] && s.hearing[b].shown === 'blocked' ? s.hearing[b] : false;
4949 }, 10000);
4950 check(refusedTile && refusedTile.text === 'Sound blocked — click to hear',
4951 'B’s tile on A says the sound is blocked (' + JSON.stringify(refusedTile) + ')');
4952 const still = await remoteTile(pageA);
4953 check(still && still.paused, 'and the refused video is paused (' + JSON.stringify(still) + ')');
4954
4955 const notice = await until(async () => {
4956 const s = await state(pageB);
4957 const h = s.hearing[a];
4958 return h && /blocking sound/.test(h.notice) && s.remoteMedia[a] && s.remoteMedia[a].audioBlocked ? h : false;
4959 }, 15000);
4960 check(notice, 'B hears about it: A’s tile on B carries the notice (' +
4961 JSON.stringify(notice || ((await state(pageB)).hearing || {})[a]) + ')');
4962 check(notice && notice.notice === nameA + '’s browser is blocking sound — they need to click to hear you.',
4963 'naming A (' + (notice && notice.notice) + ')');
4964 // §15.24: A is new to B and cannot hear B yet, but its own report
4965 // is more specific than "connecting", and replaces it.
4966 const first = (await state(pageB)).connecting[a];
4967 check(notice && notice.noticeKind === 'report' && first && first.joining,
4968 'in place of "' + nameA + ' is connecting and can’t hear you yet" (' + JSON.stringify({ notice, first }) + ')');
4969
4970 // A click on nothing in particular: the page's own heading.
4971 const heading = await pageA.locator('h1').first().boundingBox();
4972 await pageA.mouse.click(heading.x + 4, heading.y + heading.height / 2);
4973 const resumed = await until(async () => {
4974 const s = await state(pageA);
4975 const t = await remoteTile(pageA);
4976 return !s.soundBanner && !s.audioBlocked && t && !t.paused ? { t, banner: s.soundBanner } : false;
4977 }, 15000);
4978 check(resumed, 'a click anywhere plays the tile and takes the banner down — ' + (await diagnose(pageA, 'member A')));
4979 if (resumed) {
4980 const moving = await until(async () => {
4981 const t = await remoteTile(pageA);
4982 return t && !t.paused && t.time > resumed.t.time ? t : false;
4983 }, 10000);
4984 check(moving, 'and the video is really playing (' + JSON.stringify(moving || (await remoteTile(pageA))) + ')');
4985 }
4986 const cleared = await until(async () => {
4987 const s = await state(pageB);
4988 return s.hearing[a] && s.hearing[a].notice === '' && !(s.remoteMedia[a] || {}).audioBlocked ? s.hearing[a] : false;
4989 }, 15000);
4990 check(cleared, 'and B’s notice clears (' + JSON.stringify(cleared || ((await state(pageB)).hearing || {})[a]) + ')');
4991
4992 check(errorsFor('member A') === '', 'no console errors in A (' + errorsFor('member A') + ')');
4993 check(errorsFor('member B') === '', 'no console errors in B (' + errorsFor('member B') + ')');
4994 await leaveRoom(pageA);
4995 await leaveRoom(pageB);
4996 await ctxA.close();
4997 await ctxB.close();
4998 } finally {
4999 await strict.close();
5000 }
5001 },
5002
5003 // Spec §15.24 (2026-10-01): "<name> is connecting and can't hear you
5004 // yet". A fast join says nothing; a join whose connection is held back
5005 // says it on the joiner's tile, with dots a screen reader never hears,
5006 // and clears with "… can hear you now" the moment the joiner's own
5007 // report lists us in `hearing`; and a joiner that does not send
5008 // `hearing` (a client from before it, played by stripping the key off
5009 // its reports) is let go on its first report once the connection is up.
5010 // CALLS_CONNECTING_SNAPSHOTS=<dir> keeps pictures of the notice.
5011 async connecting() {
5012 const out = process.env.CALLS_CONNECTING_SNAPSHOTS;
5013 if (out) mkdirSync(out, { recursive: true });
5014 const ctxA = await newContext('member A', { cookie: cookieA });
5015 const ctxB = await newContext('member B', { cookie: cookieB });
5016 const pageA = await openRoom(ctxA);
5017 const admitted = await until(async () => ((await state(pageA)).admitted ? true : false), 20000);
5018 check(admitted, 'A is in the call on its own — ' + (await diagnose(pageA, 'member A')));
5019 const a = (await state(pageA)).peer;
5020 // A watches itself, ten times a second, from inside the page: whether
5021 // the words ever showed for anyone, when each person appeared, and
5022 // when their first moments ended; and everything its live region said.
5023 const watchA = () => pageA.evaluate(() => {
5024 window.__joins = {};
5025 window.__said = [];
5026 const live = document.getElementById('media-live');
5027 if (live) new MutationObserver(() => window.__said.push(live.textContent)).observe(live, { childList: true, characterData: true, subtree: true });
5028 setInterval(() => {
5029 const s = window.meet.state();
5030 for (const [id, c] of Object.entries(s.connecting || {})) {
5031 const j = window.__joins[id] || (window.__joins[id] = { from: Date.now(), done: 0, shown: false });
5032 if (c.shown) j.shown = true;
5033 if (!c.joining && !j.done) j.done = Date.now();
5034 }
5035 }, 100);
5036 });
5037 await watchA();
5038 const joins = () => pageA.evaluate(() => window.__joins);
5039 const said = () => pageA.evaluate(() => window.__said);
5040
5041 // 1. A fast join says nothing.
5042 let pageB = await openRoom(ctxB);
5043 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
5044 if (!pair) return;
5045 let b = pair.b.peer;
5046 const nameB = await selfName(pageB);
5047 const heardA = await until(async () => ((await state(pageB)).hearingList || []).includes(a), 15000);
5048 check(heardA, 'B reports that it hears A (' + JSON.stringify((await state(pageB)).hearingList) + ')');
5049 const fast = await until(async () => {
5050 const j = (await joins())[b];
5051 return j && j.done ? j : false;
5052 }, 15000);
5053 check(fast && !fast.shown, 'a fast join never says "can’t hear you yet" (' + JSON.stringify(fast) + ', ' +
5054 (fast ? fast.done - fast.from : '?') + ' ms from appearing to being heard)');
5055 check(!(await said()).some((t) => /hear you/.test(t)), 'and nothing about it is announced (' + JSON.stringify(await said()) + ')');
5056 await leaveRoom(pageB);
5057 await pageB.close();
5058
5059 // 2. B again, with everything that would connect it held back for a
5060 // few seconds: its offers, answers and candidates.
5061 const HOLD = 6000;
5062 let releaseAt = 0;
5063 const holdSignals = async (route) => {
5064 const body = route.request().postData() || '';
5065 if (/"type":"(offer|answer|candidate)"/.test(body)) {
5066 if (!releaseAt) releaseAt = Date.now() + HOLD;
5067 await sleep(Math.max(0, releaseAt - Date.now()));
5068 }
5069 await route.continue();
5070 };
5071 await ctxB.route('**/signal', holdSignals);
5072 await pageA.evaluate(() => { window.__said = []; });
5073 pageB = await openRoom(ctxB);
5074 const joined = await until(async () => {
5075 const s = await state(pageB);
5076 return s.admitted && s.peer ? s.peer : false;
5077 }, 20000);
5078 check(joined, 'B is back, connection held — ' + (await diagnose(pageB, 'member B')));
5079 b = joined;
5080 const words = nameB + ' is connecting and can’t hear you yet';
5081 const showing = await until(async () => {
5082 const s = await state(pageA);
5083 const h = s.hearing[b];
5084 return h && h.noticeKind === 'connecting' ? h : false;
5085 }, 10000);
5086 check(showing && showing.notice === words, 'A says it on B’s tile (' + JSON.stringify(showing) + ')');
5087 const drawn = await pageA.evaluate((id) => {
5088 const n = document.querySelector('figure[data-tile="' + id + '"] .calls-tile-notice');
5089 const dots = n && n.querySelector('.calls-ellipsis');
5090 return n && { visible: !n.hidden && n.offsetWidth > 0, dots: !!dots, hidden: dots && dots.getAttribute('aria-hidden') };
5091 }, b);
5092 check(drawn && drawn.visible && drawn.dots && drawn.hidden === 'true',
5093 'on screen, with the dots hidden from screen readers (' + JSON.stringify(drawn) + ')');
5094 check((await said()).includes(words), 'and it is announced once, without the dots (' + JSON.stringify(await said()) + ')');
5095 if (out) await pageA.screenshot({ path: out + '/web-connecting.png' });
5096 await pageA.emulateMedia({ reducedMotion: 'reduce' });
5097 const still = await pageA.evaluate((id) => {
5098 const dot = document.querySelector('figure[data-tile="' + id + '"] .calls-ellipsis > span');
5099 return dot ? getComputedStyle(dot).animationName : null;
5100 }, b);
5101 check(still === 'none', 'under reduced motion the dots keep still (' + still + ')');
5102 if (out) await pageA.screenshot({ path: out + '/web-connecting-reduced-motion.png' });
5103 await pageA.emulateMedia({ reducedMotion: 'no-preference' });
5104
5105 const clear = await until(async () => {
5106 const s = await state(pageA);
5107 const h = s.hearing[b];
5108 return h && h.notice === '' && s.connecting[b] && !s.connecting[b].joining ? s : false;
5109 }, 30000);
5110 check(clear, 'once B hears A, the words go — ' + (await diagnose(pageA, 'member A')));
5111 check(clear && ((clear.remoteMedia[b] || {}).hearing || []).includes(a), 'because B’s own report says so (' +
5112 JSON.stringify(clear && clear.remoteMedia[b]) + ')');
5113 check(releaseAt > 0 && Date.now() >= releaseAt, 'and not before the hold let go');
5114 check((await said()).includes(nameB + ' can hear you now'), 'and A hears that B can hear it now (' + JSON.stringify(await said()) + ')');
5115 await ctxB.unroute('**/signal', holdSignals);
5116 await leaveRoom(pageB);
5117 await pageB.close();
5118
5119 // 3. B as a client that does not say who it hears: the key stripped
5120 // off every report, and the connection held back as before.
5121 releaseAt = 0;
5122 const oldClient = async (route) => {
5123 let body = route.request().postData() || '';
5124 if (body.includes('"type":"media"')) {
5125 const sig = JSON.parse(body);
5126 delete sig.payload.hearing;
5127 body = JSON.stringify(sig);
5128 return route.continue({ postData: body });
5129 }
5130 return holdSignals(route);
5131 };
5132 await ctxB.route('**/signal', oldClient);
5133 pageB = await openRoom(ctxB);
5134 const back = await until(async () => {
5135 const s = await state(pageB);
5136 return s.admitted && s.peer ? s.peer : false;
5137 }, 20000);
5138 check(back, 'B is back as an old client — ' + (await diagnose(pageB, 'member B')));
5139 b = back;
5140 const oldShowing = await until(async () => {
5141 const h = (await state(pageA)).hearing[b];
5142 return h && h.noticeKind === 'connecting' ? h : false;
5143 }, 10000);
5144 check(oldShowing, 'the words show for an old client too (' + JSON.stringify(oldShowing) + ')');
5145 const oldClear = await until(async () => {
5146 const s = await state(pageA);
5147 return s.connecting[b] && !s.connecting[b].joining && s.hearing[b] && s.hearing[b].notice === '' ? s : false;
5148 }, 30000);
5149 check(oldClear && oldClear.remoteMedia[b] && !('hearing' in oldClear.remoteMedia[b]) &&
5150 oldClear.connection[b] === 'connected',
5151 'and go once its connection is up, without any `hearing` from it (' + JSON.stringify(oldClear && oldClear.remoteMedia[b]) + ')');
5152 check(Date.now() - (releaseAt || Date.now()) < 20000, 'well before the twenty-second cap');
5153 await ctxB.unroute('**/signal', oldClient);
5154
5155 check(errorsFor('member A') === '', 'no console errors in A (' + errorsFor('member A') + ')');
5156 // A signal held back for seconds can land after the pair has moved to
5157 // a new generation, and the hub refuses it 409 (§15.9) — which is the
5158 // hold's doing, and what the client recovers from. Nothing else.
5159 const errorsB = (consoleErrors.get('member B') || []).filter((e) => !/status of 409/.test(e)).join('; ');
5160 check(errorsB === '', 'no console errors in B but the held signals’ 409s (' + errorsB + ')');
5161 await leaveRoom(pageA);
5162 await leaveRoom(pageB);
5163 await ctxA.close();
5164 await ctxB.close();
5165 },
5166
5167 // Speaker view and the viewer's order (0.4.0), in a call of four: two
5168 // members and two guests. Everyone's microphone is silenced but one,
5169 // which speaks a tone; the stage goes to that person only once they
5170 // have held the floor for the dominance delay, and stays put through a
5171 // short interjection. A pin holds the stage against the speaker; the
5172 // tile buttons and a mouse drag change the tiles' order in the DOM,
5173 // and the order survives a reload of the tab (sessionStorage).
5174 // CALLS_SPEAKER_SNAPSHOTS=<dir> keeps pictures of each state.
5175 async speaker() {
5176 const out = process.env.CALLS_SPEAKER_SNAPSHOTS;
5177 if (out) mkdirSync(out, { recursive: true });
5178 const shot = async (page, name) => { if (out) await page.screenshot({ path: out + '/web-' + name + '.png' }); };
5179 const ctxA = await newContext('member A', { cookie: cookieA });
5180 const ctxB = await newContext('member B', { cookie: cookieB });
5181 const ctxG = await newContext('guest');
5182 const ctxW = await newContext('waiter');
5183 const pageA = await openRoom(ctxA);
5184 await pageA.setViewportSize({ width: 1280, height: 900 });
5185 await pageA.evaluate(() => { localStorage.removeItem('calls.videoLayout'); });
5186 const pageB = await openRoom(ctxB);
5187 const pair = await assertPair(pageA, pageB, 'member A', 'member B');
5188 if (!pair) return;
5189 for (const [ctx, address, name] of [[ctxG, GUEST, 'guest'], [ctxW, WAITER, 'waiter']]) {
5190 await signInAsGuest(ctx, address);
5191 await openRoom(ctx);
5192 check(await until(async () => (await pageA.locator('#knocks li').count()) >= 1 && await admitKnock(pageA, name), 20000),
5193 'A lets ' + name + ' in (' + JSON.stringify(await queueNames(pageA)) + ')');
5194 }
5195 const pageG = ctxG.pages().find((p) => p.url().endsWith('/m/' + sqid));
5196 const pageW = ctxW.pages().find((p) => p.url().endsWith('/m/' + sqid));
5197 const four = await until(async () => {
5198 const s = await state(pageA);
5199 return s.peers.length === 3 && Object.values(s.frames).filter((n) => n > 0).length >= 3 ? s : false;
5200 }, 40000);
5201 check(four, 'A is in a call of four, with video from all three (' + JSON.stringify(await state(pageA).catch(() => null)) + ')');
5202 if (!four) return;
5203 const b = pair.b.peer;
5204 const g = (await state(pageG)).peer;
5205 const w = (await state(pageW)).peer;
5206 check(await pageA.locator('#layout-speaker').getAttribute('aria-pressed') === 'true', 'Speaker is the layout by default');
5207
5208 // Silence: every microphone's track disabled under the call, so the
5209 // packets carry nothing and nobody is speaking.
5210 const hush = (page) => page.evaluate(() => {
5211 for (const pc of window.__pcs || []) {
5212 for (const sn of pc.getSenders()) if (sn.track && sn.track.kind === 'audio') sn.track.enabled = false;
5213 }
5214 });
5215 for (const page of [pageA, pageB, pageG, pageW]) await hush(page);
5216 await sleep(2500);
5217 const layoutOf = (page) => page.evaluate(() => ({
5218 ...window.callsLayout.state(),
5219 stage: (document.querySelector('#tiles > [data-stage]') || {}).dataset?.tile || '',
5220 pinned: (document.querySelector('#tiles > [data-pinned]') || {}).dataset?.tile || '',
5221 tiles: Array.from(document.querySelectorAll('#tiles > figure')).map((f) => f.dataset.tile),
5222 strip: Array.from(document.querySelectorAll('#tiles > figure:not([data-stage])')).map((f) => f.dataset.tile),
5223 }));
5224 const quiet = await layoutOf(pageA);
5225 check(quiet.strip.length === 3 && quiet.strip.includes('self'),
5226 'the filmstrip holds the three not on the stage, A included (' + JSON.stringify(quiet) + ')');
5227
5228 // Before anyone speaks the stage is the first other person in A's
5229 // order. G, who is not, speaks: the stage goes to G, and not before
5230 // G has held the floor for the dominance delay.
5231 check(quiet.stage !== g, 'G is not on the stage before speaking (' + quiet.stage + ')');
5232 await speakInto(pageG);
5233 const started = Date.now();
5234 const toG = await until(async () => ((await layoutOf(pageA)).stage === g ? Date.now() : false), 15000);
5235 check(toG, 'the stage goes to G while G speaks (' + JSON.stringify(await layoutOf(pageA)) + ')');
5236 check(toG && toG - started >= 1200, 'and only after G has held the floor for the delay (' + (toG - started) + ' ms)');
5237 await shot(pageA, 'speaker-filmstrip');
5238
5239 // B interjects for about half a second while G carries on: the stage
5240 // stays with G throughout.
5241 await speakInto(pageB);
5242 await sleep(500);
5243 await stopSpeaking(pageB);
5244 await hush(pageB);
5245 const flapped = await stayed(pageA, 4000, (s) => s.speaker === g);
5246 check(!flapped, 'an interjection does not take the stage (' + JSON.stringify(flapped && flapped.speaker) + ')');
5247 // G stops; W speaks on. W takes it, and over the next seconds the
5248 // stage changes exactly once.
5249 await stopSpeaking(pageG);
5250 await hush(pageG);
5251 await speakInto(pageW);
5252 const seen = [];
5253 const deadline = Date.now() + 9000;
5254 while (Date.now() < deadline) {
5255 const s = await layoutOf(pageA);
5256 if (seen[seen.length - 1] !== s.stage) seen.push(s.stage);
5257 await sleep(150);
5258 }
5259 check(seen.join(',') === [g, w].join(','), 'the stage moves once, from G to W, and does not flap (' + seen.join(' -> ') + ')');
5260
5261 // A pin holds the stage against the speaker: B's tile, clicked in the
5262 // filmstrip.
5263 await pageA.locator('#tiles > figure[data-tile="' + b + '"]').click({ position: { x: 20, y: 40 } });
5264 const pinned = await until(async () => {
5265 const l = await layoutOf(pageA);
5266 return l.stage === b && l.pinned === b ? l : false;
5267 }, 3000);
5268 check(pinned, 'clicking B in the filmstrip pins B to the stage (' + JSON.stringify(await layoutOf(pageA)) + ')');
5269 check(/Pinned .* to the stage/.test(await pageA.locator('#layout-live').textContent()), 'and says so, politely');
5270 check(await pageA.locator('#tiles > figure[data-tile="' + b + '"] .calls-tool-pin').isVisible(),
5271 'a pinned stage shows its pin');
5272 await sleep(2500);
5273 check((await layoutOf(pageA)).stage === b, 'W speaking does not take a pinned stage');
5274 await shot(pageA, 'speaker-pinned');
5275 await pageA.locator('#tiles > figure[data-tile="' + b + '"] .calls-tool-pin').click();
5276 check(await until(async () => (await layoutOf(pageA)).stage === w, 3000), 'unpinning gives the stage back to the speaker');
5277 await stopSpeaking(pageW);
5278
5279 // The viewer's order: "Move to first" on the last person changes the
5280 // DOM order, and the keyboard stays on a move button.
5281 await chooseLayout(pageA, 'grid');
5282 const before = (await layoutOf(pageA)).tiles;
5283 const last = before[before.length - 1];
5284 await openTileMenu(pageA, last);
5285 const first = pageA.locator('#tile-menu [data-move="first"]');
5286 await first.focus();
5287 await pageA.keyboard.press('Enter');
5288 const moved = await until(async () => {
5289 const l = await layoutOf(pageA);
5290 return l.tiles[0] === last ? l : false;
5291 }, 3000);
5292 check(moved, 'Move to first puts ' + last + ' first in the DOM (' + JSON.stringify(await layoutOf(pageA)) + ')');
5293 check(/moved to position 1 of 4/.test(await pageA.locator('#layout-live').textContent()), 'and says where it went');
5294 check(await pageA.evaluate(() => !!document.activeElement.closest('#tile-menu')), 'the keyboard stays in the tile\'s menu');
5295 // Move later, by keyboard: one place on.
5296 const later = pageA.locator('#tile-menu [data-move="later"]');
5297 await later.focus();
5298 await pageA.keyboard.press('Enter');
5299 check(await until(async () => (await layoutOf(pageA)).tiles[1] === last, 3000), 'Move later moves it one place');
5300 await pageA.keyboard.press('Escape');
5301 check(await pageA.locator('#tile-menu').isHidden() &&
5302 await pageA.evaluate(() => document.activeElement && document.activeElement.classList.contains('calls-tool-more')),
5303 'Escape closes the menu and puts the keyboard back on its ⋯');
5304
5305 // A mouse drag: the first tile dropped on the third's place.
5306 const order1 = (await layoutOf(pageA)).tiles;
5307 const from = await pageA.locator('#tiles > figure[data-tile="' + order1[0] + '"]').boundingBox();
5308 const to = await pageA.locator('#tiles > figure[data-tile="' + order1[2] + '"]').boundingBox();
5309 await pageA.mouse.move(from.x + from.width / 2, from.y + from.height / 2);
5310 await pageA.mouse.down();
5311 for (let i = 1; i <= 10; i++) {
5312 await pageA.mouse.move(from.x + from.width / 2 + (to.x - from.x) * i / 10, from.y + from.height / 2 + (to.y - from.y) * i / 10);
5313 await sleep(30);
5314 }
5315 check(await pageA.locator('.calls-tile-lifted').count() === 1, 'the dragged tile is lifted');
5316 await shot(pageA, 'grid-drag');
5317 await pageA.mouse.up();
5318 const dragged = await until(async () => {
5319 const l = await layoutOf(pageA);
5320 return l.tiles[2] === order1[0] ? l : false;
5321 }, 3000);
5322 check(dragged, 'dragging the first tile onto the third puts it third in the DOM (' +
5323 JSON.stringify({ before: order1, after: (await layoutOf(pageA)).tiles }) + ')');
5324 await shot(pageA, 'grid-reordered');
5325 const kept = (await layoutOf(pageA)).tiles;
5326 const stored = await pageA.evaluate((k) => sessionStorage.getItem(k), 'calls.order.' + sqid);
5327 check(stored && JSON.parse(stored).length === 4, 'the order is kept in sessionStorage for the meeting (' + stored + ')');
5328
5329 // A reload of the tab puts the order back (the peer ids are new).
5330 await pageA.reload({ waitUntil: 'domcontentloaded' });
5331 await pageA.waitForFunction(() => !!window.meet, null, { timeout: 20000 });
5332 const back = await until(async () => {
5333 const l = await pageA.evaluate(() => Array.from(document.querySelectorAll('#tiles > figure')).map((f) =>
5334 f.classList.contains('calls-tile-self') ? 'self' : f.dataset.name));
5335 return l.length === 4 ? l : false;
5336 }, 40000);
5337 check(back, 'A is back in the call of four after a reload');
5338 // Compared with what was kept before the reload, not after it: a
5339 // leave that wiped the order and a rejoin that rebuilt it in roster
5340 // order would agree with themselves.
5341 const want = JSON.parse(stored || '[]');
5342 check(back && back.map((n) => n === 'self' ? 'self' : 'name:' + n).join(',') === want.join(','),
5343 'and the tiles come back in the kept order (' + JSON.stringify({ back, want, kept,
5344 now: await pageA.evaluate(() => window.callsLayout && window.callsLayout.state()) }) + ')');
5345
5346 for (const label of ['member A', 'member B', 'guest', 'waiter']) {
5347 check(errorsFor(label) === '', 'no console errors in ' + label + ' (' + errorsFor(label) + ')');
5348 }
5349 for (const page of [pageA, pageB, pageG, pageW]) await leaveRoom(page);
5350 for (const ctx of [ctxA, ctxB, ctxG, ctxW]) await ctx.close();
5351 },
5352
5353 // The fl