Files
piik/prototype/channel-server/browser-acceptance.mjs
T

1564 lines
119 KiB
JavaScript

// Local prototype acceptance: agent-browser drives real UI/session and WebRTC.
// Media scenarios substitute only OS capture with moving canvas and oscillator tracks.
import assert from "node:assert/strict";
import { fixture } from "./browser-fixture.mjs";
import { spawn } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
import { mkdir, mkdtemp, readFile, rm, rmdir, unlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { appRoom, nativeRoom } from "./browser-native-acceptance.mjs";
// On Windows the daemon can inherit a CLI pipe. Wait for the command's exit,
// rather than execFile's close event, which would also wait for that daemon.
function run(executable, args, options = {}) {
return new Promise((resolve, reject) => {
const child = spawn(executable, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
let stdout = "", stderr = "";
child.stdout.on("data", bytes => { stdout += bytes; });
child.stderr.on("data", bytes => { stderr += bytes; });
const timer = setTimeout(() => { child.kill(); reject(new Error("agent-browser command timed out")); }, options.timeout ?? 35_000);
child.once("error", error => { clearTimeout(timer); reject(error); });
child.once("exit", code => {
clearTimeout(timer);
child.stdout.destroy(); child.stderr.destroy();
if (code === 0) resolve({ stdout, stderr });
else reject(new Error(stderr || stdout || `agent-browser exited ${code}`));
});
});
}
const executable = process.env.AGENT_BROWSER_BIN ?? (process.platform === "win32"
? join(process.env.APPDATA, "npm/node_modules/agent-browser/bin/agent-browser-win32-x64.exe")
: "agent-browser");
const origin = process.env.CHANNEL_UI_ORIGIN ?? "http://127.0.0.1:8790";
assert(["127.0.0.1", "localhost"].includes(new URL(origin).hostname), "Acceptance only targets loopback");
const output = resolve(process.env.CHANNEL_ACCEPTANCE_OUTPUT ?? "build/channel-acceptance");
const ownerKey = process.env.PIIK_CHANNEL_OWNER_KEY;
const backupOnly = process.argv.includes("--backup");
assert(backupOnly || ownerKey, "Set the local server's owner bootstrap key for owner scenarios");
const sessionPrefix = `channel-acceptance-${randomUUID()}`;
const sessions = ["a", "b", "c", "d", "e"].map(name => `${sessionPrefix}-${name}`);
const lifecycleOnly = process.argv.includes("--lifecycle");
const roomsOnly = process.argv.includes("--rooms");
const identityOnly = process.argv.includes("--identity");
const hostsOnly = process.argv.includes("--hosts");
const baseOnly = process.argv.includes("--base");
const nativeOnly = process.argv.includes("--native");
const appOnly = process.argv.includes("--app") || process.argv.includes("--previews");
const active = backupOnly ? [1] : identityOnly ? [0, 1] : process.argv.includes("--app") ? [0, 1, 2, 3]
: lifecycleOnly || roomsOnly || hostsOnly || nativeOnly || appOnly ? [0, 1, 2] : [0, 1, 2, 3, 4];
async function browser(index, ...args) {
if (["click", "dblclick", "hover"].includes(args[0])) await browser(index, "scrollintoview", args[1]);
// Omitting launch options on later commands selects a different Browser context.
const { stdout } = await run(executable, ["--session", sessions[index], "--json",
...(backupOnly ? ["--download-path", output] : ["--args", "--no-sandbox,--autoplay-policy=no-user-gesture-required",
"--init-script", join(temporary, `${index}.js`)]), ...args], {
timeout: 35_000, maxBuffer: 4 * 1024 * 1024, windowsHide: true,
});
const result = JSON.parse(stdout);
assert(result.success, result.error ?? `agent-browser ${args[0]} failed`);
return result.data;
}
const { evaluate, until, captureProbe, hook, action, view, picture, playing, progressing, publishScreen, capturedScreen, sample, audioProgressing, assertNoError } = fixture(browser);
const voicePlayback = (index, publications, retain = false) => evaluate(index,
`${JSON.stringify(publications)}.map(id => window.__channelProbe.voicePlayback(id, ${retain}))`);
const nativeVoicePlaying = values => values.length > 0 && values.every(value =>
value.current.some(player => !player.hidden && !player.paused && !player.muted && player.volume === 1));
const voicePlayersRetired = values => values.length > 0 && values.every(value =>
value.retained.length > 0 && value.retained.every(player => player.paused && !player.bound && !player.connected)
&& value.current.every(player => player.paused || player.muted || player.volume === 0));
const dropSignaling = index => evaluate(index,
"window.__channelProbe.sockets.filter(socket => socket.readyState === WebSocket.OPEN && new URL(socket.url).pathname === '/prototype/channel').forEach(socket => socket.close())");
async function showRoomList(index) {
if (!await evaluate(index, "document.querySelector('#c3-room-list')?.checkVisibility() ?? false")) {
await browser(index, "click", "#c3-rooms-trigger");
}
}
async function settingsTask(index, task) {
await browser(index, "click", `dialog.c3-settings-dialog[open] [role="tab"][aria-controls$="-${task}"]`);
}
async function roomSettings(index, roomId, task = "room") {
await showRoomList(index);
await browser(index, "click", `button[data-room-settings=${JSON.stringify(roomId)}]`);
await browser(index, "wait", "dialog.c3-settings-dialog[open]");
await settingsTask(index, task);
}
async function roomInvitation(index, roomId) {
const room = (await view(index)).state.channel.rooms.find(room => room.id === roomId);
assert(room, "the invitation belongs to a visible room");
await showRoomList(index);
await browser(index, "click", `.c3-room-link[aria-label=${JSON.stringify(room.name)}]`);
await browser(index, "find", "role", "button", "click", "--name", `Invite to ${room.name}`, "--exact");
await browser(index, "wait", ".c3-room-invitation:popover-open");
}
async function senderAllocationFailure() {
const result = await evaluate(0, `(async () => {
const { ChannelTransport } = await import('/src/client/channel/transport.ts');
const deadline = Date.now() + 25000;
const check = (condition, message) => { if (!condition) throw new Error(message); };
const wait = async (label, sample) => {
while (Date.now() < deadline) { if (await sample()) return; await new Promise(resolve => setTimeout(resolve, 50)); }
throw new Error(label);
};
const context = new AudioContext(), oscillator = context.createOscillator();
const destination = context.createMediaStreamDestination(); oscillator.connect(destination); oscillator.start(); await context.resume();
const audio = destination.stream.getAudioTracks()[0];
const canvas = document.createElement('canvas'); canvas.width = 160; canvas.height = 90;
const paint = canvas.getContext('2d'); let frame = 0;
const timer = setInterval(() => { paint.fillStyle = 'hsl(' + (++frame * 13 % 360) + ' 80% 50%)'; paint.fillRect(0, 0, 160, 90); }, 50);
const video = canvas.captureStream(20).getVideoTracks()[0], secondVideo = video.clone(), candidateVideo = video.clone();
const failures = [], errors = [], received = [], consumers = [], inputs = new Map();
const warn = console.warn;
console.warn = (...args) => { if (args[0] === 'Channel media sender attach failed') errors.push(args[2]?.name); warn(...args); };
let left, right;
const options = (polite, send) => ({ polite, iceServers: [], send, connected() {}, base() {},
failed() { failures.push('pair'); }, outgoingFailed(id) { failures.push(id); },
receive(id, stream) {
inputs.set(id, stream);
const element = document.createElement(stream.getVideoTracks().length ? 'video' : 'audio');
element.muted = true; element.autoplay = true; element.srcObject = stream;
element.style.cssText = 'position:fixed;width:1px;height:1px;opacity:0'; document.body.append(element);
consumers.push(element); void element.play().catch(() => {});
}, data(kind, data) { received.push(data); },
});
const stats = async () => {
const values = [];
for (const [side, pc] of [['sender', left.pc], ['receiver', right.pc]]) {
for (const report of (await pc.getStats()).values()) {
if (report.type === (side === 'sender' ? 'outbound-rtp' : 'inbound-rtp') && (report.kind ?? report.mediaType) === 'audio') {
values.push({ side, id: report.id, packets: report.packetsSent ?? report.packetsReceived ?? 0 });
}
}
}
return values;
};
const advancing = (before, after) => ['sender', 'receiver'].every(side => before.some(old => old.side === side &&
after.some(next => next.side === side && next.id === old.id && next.packets > old.packets)));
const videoSample = async id => {
const track = inputs.get(id)?.getVideoTracks()[0];
const receiver = right.pc.getReceivers().find(receiver => receiver.track === track);
if (!receiver) return null;
const report = [...(await receiver.getStats()).values()].find(report => report.type === 'inbound-rtp' && report.kind === 'video');
return report ? { id: report.id, frames: report.framesDecoded ?? 0 } : null;
};
const senderSnapshot = () => new Map(left.pc.getSenders().filter(sender => sender.track)
.map(sender => [sender, sender.track]));
const retainsOnly = expected => {
const actual = senderSnapshot();
return actual.size === expected.size && [...expected].every(([sender, track]) =>
actual.get(sender) === track && track.readyState === 'live');
};
const voice = { kind: 'voice', stream: new MediaStream([audio]) };
try {
left = new ChannelTransport(options(false, signal => right.signal(signal)));
right = new ChannelTransport(options(true, signal => left.signal(signal)));
left.setRooms(['allocation-check']); right.setRooms(['allocation-check']);
left.setOutgoing(new Map([['voice', voice]]));
await wait('voice and base channels did not establish', async () => inputs.has('voice') && left.isBaseReady() && right.isBaseReady() && (await stats()).every(value => value.packets > 0) && (await stats()).length >= 2);
const before = await stats();
const voiceSenders = senderSnapshot(), allocated = [];
check(voiceSenders.size === 1, 'the existing voice owns one live sender');
const allocate = left.pc.addTransceiver.bind(left.pc);
let rejectedAllocations = 0;
left.pc.addTransceiver = (track, options) => {
if (allocated.length === 1) {
left.pc.addTransceiver = allocate;
rejectedAllocations += 1;
throw new DOMException('Controlled second screen sender allocation failure', 'OperationError');
}
const transceiver = allocate(track, options);
allocated.push({ sender: transceiver.sender, track: transceiver.sender.track });
return transceiver;
};
try {
left.setOutgoing(new Map([['voice', voice], ['failed-screen', { kind: 'screen', stream: new MediaStream([video, audio]) }]]));
} finally { left.pc.addTransceiver = allocate; }
check(rejectedAllocations === 1 && errors.length === 1 && errors[0] === 'OperationError', 'the second screen allocation fails once at the current platform boundary');
check(allocated.length === 1, 'one screen sender was allocated before the failure');
check(failures.length === 1 && failures[0] === 'failed-screen', 'only the failed flow reports allocation failure');
check(retainsOnly(voiceSenders) && allocated.every(({ sender, track }) => !sender.track
&& track.readyState === (track.kind === 'video' ? 'ended' : 'live')),
'the partial sender was not rolled back or its track ownership was violated');
check([audio, video, secondVideo, candidateVideo].every(track => track.readyState === 'live'), 'allocation failure stopped a source track');
const failed = { kind: 'screen', stream: new MediaStream([video]) };
const afterAllocation = left.pc.getSenders();
for (let repeat = 0; repeat < 3; repeat++) left.setOutgoing(new Map([['voice', voice], ['failed-screen', failed]]));
check(errors.length === 1 && retainsOnly(voiceSenders) && left.pc.getSenders().length === afterAllocation.length,
'same failed lease was allocated again');
const good = { kind: 'screen', stream: new MediaStream([secondVideo]) };
left.setOutgoing(new Map([['voice', voice], ['failed-screen', failed], ['good-screen', good]]));
await wait('a later legal screen did not receive media', async () => (await videoSample('good-screen'))?.frames > 1);
left.setOutgoing(new Map([['voice', voice], ['good-screen', good]]));
left.setOutgoing(new Map([['voice', voice], ['good-screen', good], ['new-screen', failed]]));
await wait('a new lease could not allocate the retired flow source', async () => (await videoSample('new-screen'))?.frames > 0);
const pictureBefore = await videoSample('new-screen');
await wait('new lease picture did not advance on its own receiver', async () => {
const next = await videoSample('new-screen'); return next?.id === pictureBefore.id && next.frames > pictureBefore.frames;
});
await left.sendData('control', 'after-allocation-failure');
await wait('voice or base stopped after a flow allocation failure', async () => received.includes('after-allocation-failure') && advancing(before, await stats()));
check(failures.length === 1 && left.pc.connectionState === 'connected' && right.pc.connectionState === 'connected', 'flow allocation failed the shared pair');
await wait('pair did not finish its existing negotiation', () => left.pc.signalingState === 'stable' && right.pc.signalingState === 'stable');
const liveVideo = await videoSample('new-screen'), liveAudio = await stats();
const stableSenders = senderSnapshot();
const install = left.pc.setLocalDescription.bind(left.pc);
let rejectedOffers = 0;
left.pc.setLocalDescription = async (...args) => {
left.pc.setLocalDescription = install;
rejectedOffers += 1;
throw new DOMException('Controlled local offer allocation failure', 'OperationError');
};
const candidate = { kind: 'screen', stream: new MediaStream([candidateVideo]) };
const offered = new Map([['voice', voice], ['good-screen', good], ['new-screen', failed], ['failed-offer', candidate]]);
left.setOutgoing(offered);
const candidateSenders = [...senderSnapshot()].filter(([sender, track]) => stableSenders.get(sender) !== track);
check(candidateSenders.length === 1 && candidateSenders[0][1].kind === 'video', 'the candidate owns a distinct allocated video sender before its offer');
await wait('the unnegotiated candidate did not report its own failure', () => failures.includes('failed-offer'));
check(rejectedOffers === 1 && !failures.includes('pair'), 'a local offer failure retired the established pair');
check(retainsOnly(stableSenders), 'an established sender was retired with the candidate');
check(candidateSenders.every(([sender, track]) => !sender.track && track.readyState === 'ended')
&& candidateVideo.readyState === 'live', 'failed candidate sender or its clone was retained, or its source stopped');
const afterOffer = left.pc.getSenders();
for (let repeat = 0; repeat < 3; repeat++) left.setOutgoing(offered);
check(retainsOnly(stableSenders) && left.pc.getSenders().length === afterOffer.length,
'unchanged rejected demand was allocated again');
await left.sendData('control', 'after-offer-failure');
await wait('existing picture, voice or base stopped after the rejected offer', async () => {
const next = await videoSample('new-screen');
return next?.id === liveVideo.id && next.frames > liveVideo.frames
&& advancing(liveAudio, await stats()) && received.includes('after-offer-failure');
});
offered.delete('failed-offer'); offered.set('recovered-screen', candidate);
left.setOutgoing(offered);
await wait('a later real media request could not negotiate', async () => (await videoSample('recovered-screen'))?.frames > 1);
check(failures.length === 2 && left.pc.connectionState === 'connected' && right.pc.connectionState === 'connected', 'retry damaged the established pair');
check([audio, video, secondVideo, candidateVideo].every(track => track.readyState === 'live'), 'recovery stopped an original source track');
return { passed: true, error: errors[0], rejectedAllocations, rolledBackSenders: allocated.length,
failures, before, after: await stats(), baseMessage: true,
retiredLeaseReallocated: true, localOffer: { rejectedOffers, oldPicture: liveVideo, resumed: await videoSample('recovered-screen') } };
} finally {
left?.close(); right?.close(); console.warn = warn; clearInterval(timer);
for (const element of consumers) { element.pause(); element.srcObject = null; element.remove(); }
for (const track of [audio, video, secondVideo, candidateVideo]) track.stop(); oscillator.stop(); oscillator.disconnect(); await context.close();
}
})()`);
await writeFile(join(output, 'sender-allocation-result.json'), JSON.stringify(result, null, 2));
return result;
}
async function branchShortcut(initial) {
const host = 1, relay = 2, source = 3, viewer = 4, watchers = [relay, viewer];
await Promise.all(watchers.map(index => evaluate(index, 'window.__channelProbe.observeQuality()')));
const room = await action(host, "createRoom({name:'Branch shortcut',icon:'couch',access:'public',hidden:false})");
await browser(host, 'click', '.c3-room-link[aria-label="Branch shortcut"]');
// Fill the host's two base branches before admitting the downstream viewer.
for (const index of [source, relay]) {
await browser(index, 'click', '.c3-room-link[aria-label="Branch shortcut"]');
await action(index, `joinVoice(${JSON.stringify(room)}, true)`);
await until('host installs its initial base branch', () => view(index), value =>
value.state.pairs.some(pair => pair.peerId === initial[host].sessionId && pair.rooms.includes(room)));
await until('base branch opens before the next admission', () => sample(index), value =>
value.channels.some(channel => channel.label === 'piik-room' && channel.state === 'open'));
}
for (const [first, second] of [[source, viewer], [viewer, source]]) {
await evaluate(first, `window.__channelProbe.blockPeer(${JSON.stringify(initial[second].sessionId)})`);
}
await browser(viewer, 'click', '.c3-room-link[aria-label="Branch shortcut"]');
await action(viewer, `joinVoice(${JSON.stringify(room)}, true)`);
await until('viewer reaches the room through its internal relay', () => view(viewer), value =>
value.state.pairs.some(pair => pair.peerId === initial[relay].sessionId && pair.rooms.includes(room)), 35_000);
for (const index of [viewer, source]) await action(index, `setMuted(${JSON.stringify(room)}, false)`);
const viewerVoice = (await view(viewer)).state.publications.find(publication => publication.sessionId === initial[viewer].sessionId && publication.kind === 'voice' && publication.roomId === room).id;
const sourceVoice = (await view(source)).state.publications.find(publication => publication.sessionId === initial[source].sessionId && publication.kind === 'voice' && publication.roomId === room).id;
await audioProgressing(viewer, sourceVoice); await audioProgressing(source, viewerVoice);
const base = await Promise.all([host, relay, source, viewer].map(async index => ({ index,
pairs: (await view(index)).state.pairs.filter(pair => pair.rooms.includes(room)).map(pair => pair.id).sort() })));
const inspect = (index, publication) => evaluate(index, `window.__channelProbe.screen(${JSON.stringify(publication)})`);
const clickFullscreen = async (publication, flowId) => {
const video = `video[data-flow-id="${flowId}"]`;
await browser(viewer, 'hover', video);
await until('the current player exposes its playback controls', () => evaluate(viewer, `(() => {
const controls = document.querySelector(${JSON.stringify(video)})?.parentElement?.querySelector('.c3-mini-controls');
if (!controls) return false;
const style = getComputedStyle(controls);
return Number(style.opacity) > 0 && style.pointerEvents !== 'none';
})()`), value => value === true);
const input = (await inspect(viewer, publication)).inputs.find(input => input.flowId === flowId);
assert(input?.fullscreenControl && !input.fullscreenControl.disabled, 'the current player exposes its fullscreen action');
await browser(viewer, 'click', `.c3-video:has(> video[data-flow-id="${flowId}"]) .c3-mini-controls button[aria-label=${JSON.stringify(input.fullscreenControl.label)}]`);
};
const records = [];
await evaluate(source, 'window.__channelProbe.captureAudio(true)');
try {
for (const mode of ['timeout', 'unwatch', 'commit']) {
// Keep the host as a real viewer too: the source's other admitted output
// stays occupied after internal commit, rather than starting a later leaf shortcut.
await evaluate(source, `window.__channelProbe.blockPeer(${JSON.stringify(initial[host].sessionId)})`);
const publication = await capturedScreen(source, room);
await evaluate(source, `window.__channelProbe.stallVideo(${JSON.stringify(publication)}, ${JSON.stringify(initial[relay].sessionId)}, true)`);
await evaluate(relay, `window.__channelProbe.stallVideo(${JSON.stringify(publication)}, ${JSON.stringify(initial[viewer].sessionId)}, true)`);
try {
await Promise.all([host, ...watchers].map(index => action(index, `watch(${JSON.stringify(publication)})`)));
await until('host and both branch watchers are authoritative before media starts', () => Promise.all([host, ...watchers].map(view)), values =>
values.every(value => value.state.subscriptions.includes(publication)));
// Limit the incumbent's actual encoding profile before releasing its first SDP.
// Capture and other output profiles remain at the original ceiling.
const frameLimit = await until('source installs the controlled incumbent sender', () => evaluate(source,
`window.__channelProbe.limitVideo(${JSON.stringify(publication)}, ${JSON.stringify(initial[host].sessionId)}, 5, 4)`), value => !!value);
assert.deepEqual(frameLimit.after.settings, frameLimit.before.settings, 'output limits do not constrain the capture');
assert.deepEqual(frameLimit.after.others, frameLimit.before.others, 'other video outputs keep their own profiles');
assert.deepEqual(frameLimit.after.profile, { ...frameLimit.before.profile, resolution: { width: 160, height: 90 }, maxFramerate: 5 });
await evaluate(source, `window.__channelProbe.unblockPeer(${JSON.stringify(initial[host].sessionId)})`);
await action(source, 'reconnect()'); // Replay the original blocked exchange through the production owner.
await until('source resumes its authenticated session', () => view(source), value => value.connection === 'connected');
await Promise.all([host, ...watchers].map(index => playing(index, publication)));
const hostInput = (await view(host)).state.pairs.flatMap(pair => pair.incoming.filter(flow => flow.publicationId === publication)
.map(flow => ({ flowId: flow.id, pairId: pair.id, peerId: pair.peerId })))[0];
assert.equal(hostInput.peerId, initial[source].sessionId);
assert.equal(frameLimit.flowId, hostInput.flowId);
const pending = await until('internal relay and downstream viewer both install shadow inputs', () => Promise.all(watchers.map(view)), values =>
values.every(value => value.state.pairs.some(pair => pair.incoming.some(flow => flow.publicationId === publication && !flow.selected))));
const branches = pending.map((value, offset) => {
const inputs = value.state.pairs.flatMap(pair => pair.incoming.filter(flow => flow.publicationId === publication).map(flow => ({ ...flow, pairId: pair.id, peerId: pair.peerId })));
return { index: watchers[offset], incumbent: inputs.find(flow => flow.selected), candidate: inputs.find(flow => !flow.selected) };
});
const [internal, downstream] = branches;
assert.equal(internal.incumbent.peerId, initial[host].sessionId);
assert.equal(internal.candidate.peerId, initial[source].sessionId);
assert.equal(downstream.incumbent.peerId, initial[relay].sessionId);
assert.equal(downstream.candidate.pairId, downstream.incumbent.pairId, 'two lineages share the existing relay-viewer physical pair');
assert.equal(downstream.incumbent.inputFlowId, internal.incumbent.id);
assert.equal(downstream.candidate.inputFlowId, internal.candidate.id);
const sourceFault = await until('the source shadow video sender stops actual RTP', () => sample(source), value =>
value.videoStall?.flowId === internal.candidate.id && value.videoStall.connected);
assert.equal(sourceFault.videoStall.bytes, 0, 'the source candidate emits no RTP while the incumbent stays live');
const decoded = () => Promise.all(branches.map(branch => evaluate(branch.index,
`window.__channelProbe.decodedVideo(${JSON.stringify(publication)}, ${JSON.stringify(branch.incumbent.id)})`)));
const baseline = { before: await until('both incumbents decode the controlled dimensions', decoded, values =>
values.every(value => value?.frames > 0 && value.width > 0 && value.width <= 160 && value.height > 0 && value.height <= 90)) };
await new Promise(resolve => setTimeout(resolve, 2_000));
baseline.after = await decoded();
baseline.after.forEach((value, offset) => {
const before = baseline.before[offset];
assert.equal(value?.id, before.id, 'the baseline samples the same incumbent receiver');
assert.equal(value.width, before.width); assert.equal(value.height, before.height);
assert(value.frames > before.frames && Math.round((value.frames - before.frames) * 1000 / (value.timestamp - before.timestamp)) <= 5,
'the real decoded incumbent advances at the controlled frame rate before the candidate starts');
});
await Promise.all(watchers.map(index => progressing(index, publication)));
const beforeRelease = await Promise.all(watchers.map(index => inspect(index, publication)));
beforeRelease.forEach((value, offset) => {
assert.equal(value.inputs.find(input => input.selected)?.flowId, branches[offset].incumbent.id);
assert(!value.flowStates.some(proof => proof.flowId === branches[offset].candidate.id && proof.state === 'switch_ready'));
});
if (mode === 'commit') {
await Promise.all(branches.map(branch => evaluate(branch.index, `(() => {
const video = document.querySelector('video[data-flow-id="${branch.incumbent.id}"]');
const slider = video.closest('.c3-video').querySelector('input.c3-mini-volume');
if (!slider) throw new Error('screen volume control unavailable');
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(slider, '0.35');
slider.dispatchEvent(new Event('input', { bubbles: true })); slider.dispatchEvent(new Event('change', { bubbles: true }));
})()`)));
await clickFullscreen(publication, downstream.incumbent.id);
await until('downstream incumbent enters container fullscreen', () => inspect(viewer, publication), value => value.inputs.some(input => input.flowId === downstream.incumbent.id && input.fullscreen));
await browser(viewer, 'click', '.c3-video:fullscreen .c3-mini-controls button:first-child');
await until('downstream incumbent pauses before selection', () => inspect(viewer, publication), value => value.inputs.some(input => input.flowId === downstream.incumbent.id && input.paused));
}
// A relay needs actual decoded input before it can select its output codec.
await evaluate(source, 'window.__channelProbe.restoreVideo()');
const downstreamFault = await until('the relay shadow video sender stops actual RTP', () => sample(relay), value =>
value.videoStall?.flowId === downstream.candidate.id && value.videoStall.connected);
assert.equal(downstreamFault.videoStall.bytes, 0, 'the downstream candidate emits no RTP while the incumbent shares its live PC');
const held = await until('both candidate consumers exist before they are selected', () => Promise.all(watchers.map(index => inspect(index, publication))), values =>
values.every((value, offset) => value.inputs.some(input => input.flowId === branches[offset].candidate.id && input.elementId)));
held.forEach((value, offset) => assert.equal(value.inputs.find(input => input.selected)?.flowId, branches[offset].incumbent.id));
const warm = held.map((value, offset) => value.inputs.find(input => input.flowId === branches[offset].candidate.id));
assert(warm.every(input => input?.elementId), 'both candidate consumers exist before they are selected');
const warmOutput = held[0].outputs.find(output => output.flowId === downstream.candidate.id);
assert.equal(warmOutput.inputFlowId, internal.candidate.id);
assert.equal(warmOutput.senders.length, 2, 'the shadow output forwards its own video and source audio');
if (mode !== 'commit') {
const firstReady = await until('relay proves its candidate but cannot commit for the stalled downstream viewer', () => inspect(relay, publication), value =>
value.flowStates.some(proof => proof.flowId === internal.candidate.id && proof.state === 'switch_ready'));
const readyAt = firstReady.flowStates.find(proof => proof.flowId === internal.candidate.id && proof.state === 'switch_ready').time;
assert.equal(firstReady.inputs.find(input => input.selected)?.flowId, internal.incumbent.id);
const blocked = await inspect(viewer, publication);
assert.equal(blocked.inputs.find(input => input.selected)?.flowId, downstream.incumbent.id);
assert(!blocked.flowStates.some(proof => proof.flowId === downstream.candidate.id && proof.state === 'switch_ready'));
if (mode === 'unwatch') await action(viewer, `unwatch(${JSON.stringify(publication)})`);
await until('expiry or a changed watcher cohort cancels the entire shadow branch', () => Promise.all(watchers.map(view)), values =>
values.every((value, offset) => !value.state.pairs.some(pair => pair.incoming.some(flow => flow.id === branches[offset].candidate.id))
&& (mode === 'unwatch' && offset === 1 ? !value.state.subscriptions.includes(publication)
: value.state.pairs.some(pair => pair.incoming.some(flow => flow.id === branches[offset].incumbent.id && flow.selected)))), 8_000);
records.push({ mode, branches, frameLimit, baseline, sourceFault, downstreamFault, firstSwitchReadyAt: readyAt, expiredAfterReadyMs: Date.now() - readyAt,
elapsedMs: Date.now() - sourceFault.videoStall.startedAt });
await Promise.all((mode === 'unwatch' ? [relay] : watchers).map(index => progressing(index, publication)));
} else {
await evaluate(relay, 'window.__channelProbe.restoreVideo()');
const selected = await until('both watchers adopt the prepared shadow cohort', () => Promise.all(watchers.map(index => inspect(index, publication))), values =>
values.every((value, offset) => value.inputs.some(input => input.flowId === branches[offset].candidate.id && input.selected && input.displayed === 'true' && input.composited === 'true')), 25_000);
await writeFile(join(output, 'base-branch-commit-observed.json'), JSON.stringify({ branches, frameLimit, baseline, sourceFault, downstreamFault, beforeRelease, held, selected }, null, 2));
const adopted = selected.map((value, offset) => value.inputs.find(input => input.flowId === branches[offset].candidate.id));
adopted.forEach((input, offset) => {
assert.equal(input.elementId, warm[offset].elementId, 'commit adopts the prewarmed DOM element');
assert.equal(input.streamId, warm[offset].streamId, 'commit retains the exact candidate srcObject');
assert(Math.abs(input.volume - .35) < .01, 'both viewers retain volume');
const proofs = selected[offset].flowStates.filter(proof => proof.flowId === branches[offset].candidate.id);
assert(proofs.some(proof => proof.state === 'decoded') && proofs.some(proof => proof.state === 'switch_ready'));
const incumbent = held[offset].inputs.find(input => input.selected);
const approved = selected[offset].qualitySamples.findLast(sample => sample.result === 'approved'
&& sample.current?.trackIdentifier === incumbent.video[0] && sample.candidate?.trackIdentifier === input.video[0]);
assert(approved && approved.current.frameWidth === incumbent.width && approved.current.frameHeight === incumbent.height,
'the positive comparison retains the incumbent decoded dimensions');
assert(input.audioObjects.length === 1 && selected[offset].audioOwners.includes(input.audioObjects[0]));
assert(incumbent.audioObjects.every(id => !selected[offset].audioOwners.includes(id)), 'the old source audio graph is retired');
});
assert(adopted[1].paused && adopted[1].fullscreen, 'commit preserves pause and the fullscreen container');
assert(!adopted[0].paused, 'the relay viewer continues playing');
const adoptedOutput = selected[0].outputs.find(output => output.flowId === downstream.candidate.id);
const outputIdentity = output => ({ flowId: output.flowId, inputFlowId: output.inputFlowId, pairId: output.pairId,
peerId: output.peerId, streamId: output.streamId, wrapperId: output.wrapperId,
senders: output.senders.map(sender => ({ id: sender.id, pcIndex: sender.pcIndex, mid: sender.mid,
source: { id: sender.source?.id, objectId: sender.source?.objectId, kind: sender.source?.kind } })) });
assert(warmOutput.senders.every(sender => sender.source), 'the prepared senders expose their actual logical sources');
assert.deepEqual(outputIdentity(adoptedOutput), outputIdentity(warmOutput),
'commit preserves the shadow flow, wrapper, sender objects and logical sources');
assert.equal(warmOutput.selected, false);
assert.equal(adoptedOutput.selected, true);
assert(adoptedOutput.senders.every(sender => sender.connectionState === 'connected'
&& sender.source?.readyState === 'live' && sender.track.readyState === 'live'), 'the committed senders and logical sources remain live');
await until('commit retires only the old media branch', () => Promise.all(watchers.map(view)), values =>
values.every((value, offset) => !value.state.pairs.some(pair => pair.incoming.some(flow => flow.id === branches[offset].incumbent.id))));
await browser(viewer, 'screenshot', join(output, 'base-shortcut-fullscreen.png'));
await browser(viewer, 'click', '.c3-video:fullscreen .c3-mini-controls button:first-child');
await Promise.all(watchers.map(index => progressing(index, publication)));
await clickFullscreen(publication, downstream.candidate.id);
await until('downstream candidate leaves container fullscreen', () => inspect(viewer, publication), value =>
value.inputs.some(input => input.flowId === downstream.candidate.id && !input.fullscreen));
records.push({ mode, branches, frameLimit, baseline, sourceFault, downstreamFault, warm, warmOutput, adopted,
quality: selected.map(value => value.qualitySamples), proofs: selected.map(value => value.flowStates) });
}
for (const before of base) assert.deepEqual((await view(before.index)).state.pairs.filter(pair => pair.rooms.includes(room)).map(pair => pair.id).sort(), before.pairs,
'media convergence preserves every existing base pair');
assert((await view(host)).state.pairs.some(pair => pair.id === hostInput.pairId
&& pair.incoming.some(flow => flow.id === hostInput.flowId && flow.selected)), 'the host keeps its original source input');
await progressing(host, publication);
await audioProgressing(viewer, sourceVoice); await audioProgressing(source, viewerVoice);
await writeFile(join(output, 'base-branch-shortcut.json'), JSON.stringify({ passed: true, records }, null, 2));
} finally {
await Promise.all([source, relay].map(index => evaluate(index, 'window.__channelProbe.restoreVideo()')));
await evaluate(source, `window.__channelProbe.unblockPeer(${JSON.stringify(initial[host].sessionId)})`);
await evaluate(viewer, 'document.fullscreenElement ? document.exitFullscreen() : undefined');
await action(source, `stopScreen(${JSON.stringify(publication)})`);
}
}
} finally {
await evaluate(source, 'window.__channelProbe.captureAudio(false)');
for (const index of [viewer, source, relay]) await action(index, `leaveVoice(${JSON.stringify(room)})`);
for (const [first, second] of [[source, viewer], [viewer, source]]) {
await evaluate(first, `window.__channelProbe.unblockPeer(${JSON.stringify(initial[second].sessionId)})`);
}
for (const index of [host, relay, source, viewer]) await browser(index, 'click', '.c3-room-link[aria-label="Living room"]');
}
for (const index of [host, relay, source, viewer]) await assertNoError(index, 'internal branch handover');
return records;
}
async function roomBase(initial) {
const branchShortcuts = await branchShortcut(initial);
// Host this fixture at its source so its two viewers have a known base path;
// cross-room lease reuse must not depend on an optional quality-based shortcut.
const pictureRoom = await action(1, "createRoom({name:'Picture room',icon:'couch',access:'public',hidden:false})");
await evaluate(1, 'window.__channelProbe.captureAudio(true)');
let source;
try { source = await capturedScreen(1, pictureRoom); }
finally { await evaluate(1, 'window.__channelProbe.captureAudio(false)'); }
await action(2, `watch(${JSON.stringify(source)})`);
await playing(2, source);
const originalPair = (await view(2)).state.pairs.find(pair => pair.incoming.some(flow => flow.publicationId === source)).id;
const room = await action(1, "createRoom({name:'Connected room',icon:'couch',access:'public',hidden:false})");
for (const index of [1, 2]) await browser(index, "click", '.c3-room-link[aria-label="Connected room"]');
for (const index of [1, 2]) await action(index, `joinVoice(${JSON.stringify(room)}, true)`);
await until("base reuses the existing screen connection", () => view(2), value =>
value.state.pairs.some(pair => pair.id === originalPair && pair.rooms.includes(room)));
await until("room DataChannel opens", () => sample(2), value => value.channels.some(channel => channel.state === "open"));
// Prevent this pair's real SDP/ICE exchange. Other peer negotiations still run.
// This is a controlled unreachable edge, not a model of a particular NAT.
await evaluate(1, `window.__channelProbe.blockPeer(${JSON.stringify(initial[3].sessionId)})`);
await evaluate(3, `window.__channelProbe.blockPeer(${JSON.stringify(initial[1].sessionId)})`);
// Blocking signaling cannot break a carrier retained from an earlier room.
const retiredPairs = await evaluate(1, `(() => {
const peers = [...window.__channelGate.session.media.peers.values()].filter(peer => peer.plan.peerId === ${JSON.stringify(initial[3].sessionId)});
for (const peer of peers) { peer.transport.pc.close(); peer.transport.fail(); }
return peers.map(peer => peer.plan.id);
})()`);
await until("the old direct carriers retire before the unreachable-edge trial", () => Promise.all([1, 3].map(view)), values =>
values.every(value => value.state.pairs.every(pair => !retiredPairs.includes(pair.id))));
await browser(3, "click", '.c3-room-link[aria-label="Connected room"]');
await action(3, `joinVoice(${JSON.stringify(room)}, true)`);
await until("D reaches its room through C after B-D fails", () => view(3), value =>
value.state.pairs.some(pair => pair.peerId === initial[2].sessionId && pair.rooms.includes(room)), 35_000);
await action(2, `leaveVoice(${JSON.stringify(room)})`);
await action(3, `setMuted(${JSON.stringify(room)}, false)`);
await until("voice crosses the base transit", () => sample(1), value =>
value.inbound.some(report => report.kind === "audio" && report.samples > 0 && report.energy > 0));
const dVoice = (await view(3)).state.publications.find(value => value.sessionId === initial[3].sessionId && value.kind === "voice").id;
const cTransit = await view(2);
assert(cTransit.state.pairs.some(pair => pair.incoming.some(flow => flow.publicationId === dVoice)));
assert(cTransit.state.pairs.some(pair => pair.outgoing.some(flow => flow.publicationId === dVoice)));
assert(!cTransit.state.subscriptions.includes(dVoice), "transit does not join voice or play it locally");
await until("transit voice decoder remains silent without a local listener", () => voicePlayback(2, [dVoice]), values =>
values[0].current.length > 0 && values[0].current.every(player => player.hidden && player.muted));
await progressing(2, source);
const basePicture = await capturedScreen(3, room);
await action(1, `watch(${JSON.stringify(basePicture)})`);
await playing(1, basePicture);
assert((await view(1)).state.pairs.some(pair => pair.peerId === initial[2].sessionId && pair.incoming.some(flow => flow.publicationId === basePicture)),
"picture startup uses the reachable base transit despite a blocked direct path");
assert(!(await view(2)).state.subscriptions.includes(basePicture), "picture transit does not require local viewing");
await action(1, `setMuted(${JSON.stringify(room)}, false)`);
await until("reverse voice crosses the same base edges", () => sample(3), value =>
value.inbound.some(report => report.kind === "audio" && report.samples > 0 && report.energy > 0));
await browser(2, "click", '.c3-room-link[aria-label="Living room"]');
assert((await view(2)).state.pairs.some(pair => pair.rooms.includes(room)), "leaving the view preserves necessary transit");
await progressing(2, source);
await browser(0, "click", '.c3-room-link[aria-label="Connected room"]');
await action(0, `joinVoice(${JSON.stringify(room)}, true)`);
await until("A becomes an available base branch", () => view(0), value => value.state.pairs.some(pair => pair.rooms.includes(room)));
await action(0, `watch(${JSON.stringify(source)})`);
await playing(0, source);
const survivingPair = (await view(0)).state.pairs.find(pair => pair.incoming.some(flow => flow.publicationId === source)).id;
const localVoice = (await view(1)).state.publications.find(publication => publication.roomId === room
&& publication.kind === 'voice' && publication.sessionId === initial[1].sessionId).id;
const listenedVoices = [dVoice, localVoice];
await until("listener has actual native voice playback before deafen", () => voicePlayback(0, listenedVoices), nativeVoicePlaying);
await voicePlayback(0, listenedVoices, true);
const screenSound = async () => (await evaluate(0, `window.__channelProbe.screen(${JSON.stringify(source)})`)).inputs
.find(input => input.selected);
const soundingPicture = await until("another room's picture sound is playing", screenSound,
input => input?.audio.length > 0 && !input.paused && !input.muted && input.volume === 1);
const voicePairIds = (await view(0)).state.pairs.map(pair => pair.id).sort();
await action(0, `setDeafened(${JSON.stringify(room)}, true)`);
await until("deafen retires the retained local voice players", () => voicePlayback(0, listenedVoices), voicePlayersRetired);
await Promise.all([audioProgressing(0, dVoice), audioProgressing(0, localVoice), audioProgressing(1, dVoice), audioProgressing(3, localVoice)]);
const deafenedPicture = await screenSound();
assert.equal(deafenedPicture.elementId, soundingPicture.elementId, "deafen keeps the other room's actual picture player");
assert.deepEqual(deafenedPicture.audioObjects, soundingPicture.audioObjects, "deafen keeps the other room's sound track");
assert(!deafenedPicture.paused && !deafenedPicture.muted && deafenedPicture.volume === 1,
"deafen does not silence another room's picture sound");
await audioProgressing(0, source); await progressing(0, source);
assert.deepEqual((await view(0)).state.pairs.map(pair => pair.id).sort(), voicePairIds, "local deafen retains media routing transports");
await action(0, `setDeafened(${JSON.stringify(room)}, false)`);
await until("undeafen installs live native voice players again", () => voicePlayback(0, listenedVoices), nativeVoicePlaying);
// The media edge must time out independently of its connected room/voice transport.
const stalledPicture = await capturedScreen(1, room);
let mediaPrepare;
try {
await action(0, `watch(${JSON.stringify(stalledPicture)})`);
await playing(0, stalledPicture); // A is a real, already-supplied alternative parent.
await evaluate(1, `window.__channelProbe.unblockPeer(${JSON.stringify(initial[3].sessionId)})`);
await evaluate(3, `window.__channelProbe.unblockPeer(${JSON.stringify(initial[1].sessionId)})`);
await evaluate(2, `window.__channelProbe.stallVideo(${JSON.stringify(stalledPicture)}, ${JSON.stringify(initial[3].sessionId)})`);
await action(3, `watch(${JSON.stringify(stalledPicture)})`);
const blocked = await until("C disables only the new picture sender to D", () => sample(2), value =>
value.videoStall?.flowId || value.videoStall?.error);
const fault = blocked.videoStall;
assert.equal(fault.error, undefined);
assert(fault.connected && fault.roomOpen && fault.active.length > 0 && fault.active.every(active => active === false),
"the stalled video shares an already-connected PC and open room DataChannel");
assert.equal(fault.bytes, 0, "the disabled video sender emitted no RTP before its first proof");
const waiting = await view(3);
assert(waiting.state.pairs.some(pair => pair.id === fault.pairId && pair.rooms.includes(room)
&& pair.incoming.some(flow => flow.id === fault.flowId && flow.publicationId === stalledPicture)),
"the unproved picture starts on the existing C-D base pair");
assert.equal((await picture(3, stalledPicture)).frames, 0);
const voiceIds = waiting.state.publications.filter(publication => publication.kind === "voice" && publication.roomId === room).map(publication => publication.id);
const bVoice = waiting.state.publications.find(publication => publication.kind === "voice" && publication.roomId === room
&& publication.sessionId === initial[1].sessionId).id;
const voiceFlows = pair => [...pair.incoming, ...pair.outgoing].filter(flow => voiceIds.includes(flow.publicationId)).map(flow => flow.id).sort();
const originalBase = waiting.state.pairs.find(pair => pair.id === fault.pairId);
const repaired = await until("unproved video retires its flow and uses another supplied parent", () => view(3), value =>
!value.state.pairs.some(pair => pair.incoming.some(flow => flow.id === fault.flowId))
&& value.state.pairs.some(pair => pair.peerId !== initial[2].sessionId
&& pair.incoming.some(flow => flow.publicationId === stalledPicture)), 35_000);
const elapsedMs = Date.now() - fault.startedAt;
await progressing(3, stalledPicture);
const retainedBase = repaired.state.pairs.find(pair => pair.id === fault.pairId && pair.rooms.includes(room));
assert(retainedBase,
"a media prepare timeout preserves the original room/voice pair");
assert.deepEqual(voiceFlows(retainedBase), voiceFlows(originalBase), "video timeout does not replace the shared pair's voice flows");
await audioProgressing(1, dVoice);
await audioProgressing(3, bVoice);
const replacement = repaired.state.pairs.flatMap(pair => pair.incoming.filter(flow => flow.publicationId === stalledPicture)
.map(flow => ({ pairId: pair.id, peerId: pair.peerId, flowId: flow.id })));
mediaPrepare = { retiredFlow: fault.flowId, retainedBasePair: fault.pairId, replacement,
elapsedMs, blockedVideoBytes: fault.bytes, bidirectionalVoice: true };
await writeFile(join(output, "base-media-prepare.json"), JSON.stringify({ passed: true, ...mediaPrepare }, null, 2));
} finally {
try { await evaluate(2, "window.__channelProbe.restoreVideo()"); }
finally {
await action(1, `stopScreen(${JSON.stringify(stalledPicture)})`);
await evaluate(1, `window.__channelProbe.blockPeer(${JSON.stringify(initial[3].sessionId)})`);
await evaluate(3, `window.__channelProbe.blockPeer(${JSON.stringify(initial[1].sessionId)})`);
}
}
await evaluate(2, "window.__channelProbe.closeDataChannels()");
await until("D repairs through A after its transit DataChannel closes", () => view(3), value =>
value.state.pairs.some(pair => pair.rooms.includes(room) && pair.peerId === initial[0].sessionId), 30_000);
await audioProgressing(1, dVoice);
await progressing(0, source);
await progressing(2, source);
assert((await view(2)).state.pairs.some(pair => pair.id === originalPair && pair.incoming.some(flow => flow.publicationId === source)), "a failed DataChannel must not close the same pair's healthy picture");
assert((await view(0)).state.pairs.some(pair => pair.id === survivingPair && pair.incoming.some(flow => flow.publicationId === source)), "base repair preserves unrelated screen transport");
await progressing(1, basePicture);
await browser(2, "close");
await until("picture repairs through the surviving base branch", () => view(1), value =>
value.state.pairs.some(pair => pair.peerId === initial[0].sessionId && pair.incoming.some(flow => flow.publicationId === basePicture)), 30_000);
await progressing(1, basePicture);
await action(3, `stopScreen(${JSON.stringify(basePicture)})`);
for (const index of [1, 3]) await action(index, `leaveVoice(${JSON.stringify(room)})`);
await until("remaining listener retains the base after the speakers leave", () => view(0), value =>
value.state.voice.some(member => member.roomId === room && member.sessionId === value.sessionId)
&& value.state.pairs.some(pair => pair.rooms.includes(room)));
await action(0, `leaveVoice(${JSON.stringify(room)})`);
await until("last media demand releases only base leases", () => view(0), value =>
!value.state.pairs.some(pair => pair.rooms.includes(room)) && value.state.pairs.some(pair => pair.id === survivingPair && pair.incoming.some(flow => flow.publicationId === source)));
for (const index of [0, 3]) await browser(index, "click", '.c3-room-link[aria-label="Living room"]');
await progressing(0, source);
for (const index of [0, 1, 3, 4]) await action(index, 'browse("")');
await action(1, `stopScreen(${JSON.stringify(source)})`);
await until("last physical lease closes the pair", () => view(0), value => !value.state.pairs.some(pair => pair.id === survivingPair));
for (const index of [0, 1, 3]) await assertNoError(index, "room base lifecycle");
await writeFile(join(output, "base-result.json"), JSON.stringify({ passed: true, mediaPrepare, branchShortcuts,
scenarios: ["listen-only demand without capture", "media/base transport reuse", "unreachable direct edge",
"picture startup through non-viewing base transit", "picture recovery after transit departure",
"bidirectional voice through a non-listener", "deafen keeps routes", "view change preserves transit",
"connected video without RTP times out without retiring base or voice", "failed DataChannel repairs voice without closing healthy RTP", "retired transit leaves independently",
"repair preserves another room's picture", "listener retains base after speakers leave", "last demand retirement",
"internal relay shadow lineage on a shared pair", "all watcher proofs required within their finite validity",
"watcher change cancels the shadow cohort", "warm branch commit preserves playback and forwarding resources"] }, null, 2));
console.log("Room DataChannels, bidirectional voice transit and shared media leases passed real Browser acceptance");
}
async function roomOwner(initial, serverRoom) {
for (const index of [0, 2]) await action(index, `browse(${JSON.stringify(serverRoom)})`);
await until("both Server conversation readers are installed", () => Promise.all([0, 2].map(view)), values =>
values.every(value => value.state.channel.rooms.some(room => room.id === serverRoom && room.reading)));
await action(0, `sendMessage(${JSON.stringify(serverRoom)}, 'Server room through the domain WebSocket')`);
await action(0, `loadLatestHistory(${JSON.stringify(serverRoom)})`);
const serverWS = (await sample(0)).conversationWS[serverRoom];
assert(serverWS?.sent.chat > 0 && serverWS.received.chat > 0 && serverWS.sent.history > 0 && serverWS.received.history > 0,
"Server room chat and signed history use the domain WebSocket");
await until("another current reader receives the Server's signed confirmation", () => evaluate(2,
`${hook}.snapshot().messagesByRoom[${JSON.stringify(serverRoom)}]`), messages => messages?.some(message => message.text === "Server room through the domain WebSocket"));
assert.equal((await view(0)).state.pairs.length, 0, "confirmed conversation needs no peer transport");
const room = await action(1, "createRoom({name:'Browser-owned room',icon:'couch',access:'private',hidden:true,password:'browser-room-password'})");
const invite = await action(1, `createRoomInvite(${JSON.stringify(room)})`);
await action(2, "close()");
await evaluate(2, "localStorage.removeItem('piik.channel.prototype.credential')");
await browser(2, "open", invite);
await browser(2, "reload");
await until("fresh user joins the Browser-owned private room", () => view(2), value => value.connection === "connected" &&
value.state.channel.rooms.some(entry => entry.id === room && entry.authorized));
await action(1, `browse(${JSON.stringify(room)})`);
await action(2, `browse(${JSON.stringify(room)})`);
await until("both Browser conversation readers are installed", () => Promise.all([1, 2].map(view)), values =>
values.every(value => value.state.channel.rooms.some(entry => entry.id === room && entry.reading)));
await action(2, `sendMessage(${JSON.stringify(room)}, 'Confirmed on B')`);
await until("owner receives confirmed room history", () => evaluate(1,
`${hook}.snapshot().messagesByRoom[${JSON.stringify(room)}]`), value => value?.some(message => message.text === "Confirmed on B"));
await action(2, `loadLatestHistory(${JSON.stringify(room)})`);
const initialHostedWS = await Promise.all([1, 2].map(async index => (await sample(index)).conversationWS[room] ?? null));
assert(initialHostedWS[0]?.received.chat > 0 && initialHostedWS[0].sent.chat > 0
&& initialHostedWS[1]?.sent.chat > 0 && initialHostedWS[1].received.chat > 0
&& initialHostedWS[1].sent.history > 0 && initialHostedWS[1].received.history > 0,
"Browser owner and participant exchange signed conversation through the domain WebSocket");
await evaluate(1, `(() => {
const conversation = ${hook}.session.conversation, receive = conversation.receive;
conversation.receive = async function(...args) {
try { return await receive.apply(this, args); }
catch (error) { window.__channelProbe.conversationRejected = String(error); throw error; }
};
window.__channelProbe.restoreConversation = () => { conversation.receive = receive; };
return true;
})()`);
const forgedText = "Ordinary-user fake live reply must be rejected";
let rejectedReply;
try {
await evaluate(2, `(async () => {
const session = ${hook}.session, value = ${hook}.snapshot();
const entry = value.state.channel.rooms.find(room => room.id === ${JSON.stringify(room)});
const { signer } = await session.conversation.identity;
if (value.sessionId === entry.delivery.hostSessionId) throw new Error('Expected ordinary participant');
const requestId = crypto.randomUUID();
const packet = JSON.parse(signer.sign(value.sessionId, JSON.stringify({
roomId: entry.id, bindingId: entry.delivery.bindingId, sender: value.sessionId,
recipient: entry.delivery.hostSessionId, requestId,
record: { type: 'live_message', message: { id: crypto.randomUUID(), seq: 2,
userId: entry.creatorId, text: ${JSON.stringify(forgedText)}, time: Date.now(), attachments: [] } }
})));
session.write({ type: 'conversation', packet, requestId });
return true;
})()`);
rejectedReply = await until("room owner rejects a participant-signed fake reply", () => evaluate(1,
"window.__channelProbe.conversationRejected"), value => value?.includes("invalid_conversation_sender"));
assert.equal(await evaluate(1, `${hook}.snapshot().messagesByRoom[${JSON.stringify(room)}].some(message => message.text === ${JSON.stringify(forgedText)})`), false);
await action(2, `sendMessage(${JSON.stringify(room)}, 'Chat after rejected fake reply')`);
await until("normal chat continues after rejecting the fake reply", () => evaluate(1,
`${hook}.snapshot().messagesByRoom[${JSON.stringify(room)}]`), value => value?.some(message => message.text === "Chat after rejected fake reply"));
} finally { await evaluate(1, "window.__channelProbe.restoreConversation()"); }
const stored = await evaluate(1, `(async () => {
const databases = await indexedDB.databases();
for (const database of databases) {
if (!database.name?.startsWith('piik.channel.rooms.')) continue;
const db = await new Promise((resolve, reject) => { const request = indexedDB.open(database.name);
request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); });
try {
const tx = db.transaction(['rooms','messages']);
const policy = tx.objectStore('rooms').get(${JSON.stringify(room)});
const messages = tx.objectStore('messages').getAll(IDBKeyRange.bound([${JSON.stringify(room)}], [${JSON.stringify(room)}, Infinity]));
await new Promise((resolve, reject) => { tx.oncomplete = resolve; tx.onabort = () => reject(tx.error); });
if (policy.result) return { policy: JSON.parse(policy.result.policy), messages: messages.result };
} finally { db.close(); }
}
return null;
})()`);
assert(stored?.messages.some(message => message.text === "Confirmed on B"));
assert.equal(stored.policy.creatorId, initial[1].self.id);
const db = new DatabaseSync(process.env.CHANNEL_DATA_FILE, { readOnly: true });
try {
assert.equal(db.prepare("SELECT count(*) AS count FROM message WHERE room_id=?").get(room).count, 0);
const checkpoint = db.prepare("SELECT body FROM checkpoint WHERE id=1").get().body;
assert(!checkpoint.includes(stored.policy.passwordHash), "domain must not retain Browser room password hashes");
assert(!checkpoint.includes("Confirmed on B"), "domain must not checkpoint Browser room history");
} finally { db.close(); }
const serverPicture = await capturedScreen(0, serverRoom);
await browser(2, "click", '.c3-room-link[aria-label="Living room"]');
await action(2, `watch(${JSON.stringify(serverPicture)})`);
await playing(2, serverPicture);
const viewerSession = (await view(2)).sessionId;
const sharedPair = (await view(0)).state.pairs.find(pair => pair.peerId === viewerSession).id;
const roomPicture = await capturedScreen(2, room);
for (const index of [0, 1]) {
await browser(index, "click", '.c3-room-link[aria-label="Browser-owned room"]');
await action(index, `watch(${JSON.stringify(roomPicture)})`);
await playing(index, roomPicture);
}
assert.equal((await view(0)).state.pairs.find(pair => pair.peerId === viewerSession).id, sharedPair);
await action(1, `joinVoice(${JSON.stringify(room)})`);
await action(2, `joinVoice(${JSON.stringify(room)})`);
await until("Browser room voice reaches a remote participant", () => sample(2), value => value.inbound.some(row => row.kind === "audio" && row.samples > 0));
const ownerSession = (await view(1)).sessionId;
await dropSignaling(1);
await action(1, "reconnect()");
await until("same Browser room owner resumes", () => view(1), value => value.connection === "connected" && value.sessionId === ownerSession &&
value.state.publications.some(publication => publication.id === roomPicture));
await progressing(0, roomPicture);
await action(1, "close()");
await until("stopped owner pauses its room", () => view(2), value => !value.state.publications.some(publication => publication.roomId === room), 25_000);
assert((await view(2)).state.channel.rooms.some(entry => entry.id === room && entry.authorized && !entry.available),
"a paused private room remains visible to an already admitted participant");
assert((await sample(0)).captures.some(track => track.kind === "video" && track.state === "live"));
assert.equal((await view(0)).state.pairs.find(pair => pair.peerId === viewerSession).id, sharedPair);
await progressing(2, serverPicture);
await browser(1, "open", `${origin}/__channel-preview`);
await until("reopened owner restores the saved room", () => view(1), value => value.connection === "connected" &&
value.state.channel.rooms.some(entry => entry.id === room && entry.authorized && entry.available !== false));
await action(1, `browse(${JSON.stringify(room)})`);
await until("reopened owner reads its own retained history", () => evaluate(1,
`${hook}.snapshot().messagesByRoom[${JSON.stringify(room)}]`), value => value?.some(message => message.text === "Confirmed on B"));
assert(!(await view(1)).state.publications.some(publication => publication.roomId === room));
assert(!(await view(1)).state.voice.some(member => member.roomId === room));
await progressing(2, serverPicture);
await browser(2, "click", '.c3-room-link[aria-label="Browser-owned room"]');
for (let start = 0; start < 100; start += 20) {
await evaluate(2, `(async () => {
for (let index = ${start}; index < ${start + 20}; index++) {
await ${hook}.session.sendMessage(${JSON.stringify(room)}, String.fromCharCode(1).repeat(2000));
}
return true;
})()`);
}
// The host pages 50 retained messages at a time, independently of the larger
// reading window. Keep the 100-message payload trial and read both pages.
const historyPages = [];
for (const method of ['loadLatestHistory', 'loadHistory']) {
await evaluate(2, 'window.__channelProbe.clearProtocol()');
await action(2, `${method}(${JSON.stringify(room)})`);
const records = (await sample(2)).protocol.filter(event => event.direction === 'received'
&& event.type === 'conversation' && event.room === room);
const end = records.findLast(event => event.result === 'history_end');
assert(end, 'a signed history request completes with its own END record');
const pageRecords = records.filter(event => event.request === end.request);
assert.equal(pageRecords.filter(event => event.result === 'history_message').length, 50,
'each maximum history page delivers all 50 signed message records');
assert.equal(pageRecords.filter(event => event.result === 'message_reactions').length, 50,
'each history message retains its signed reaction snapshot');
assert.equal(pageRecords.filter(event => event.result === 'history_end').length, 1);
assert.equal(end.historyCount, 50, 'END confirms the complete page count');
historyPages.push({ requestId: end.request, messages: end.historyCount, reactionSnapshots: 50, endMarkers: 1 });
}
const page = await evaluate(2, `${hook}.snapshot().messagesByRoom[${JSON.stringify(room)}].map(message => ({ seq: message.seq, characters: message.text.length }))`);
assert.deepEqual(page.map(message => message.characters), Array(100).fill(2000),
'two complete signed pages retain all 100 maximum-size test messages');
assert(page.every((message, index) => index === 0 || message.seq === page[index - 1].seq + 1),
'history pagination preserves every confirmed sequence without gaps or duplicates');
const hostedWS = await Promise.all([0, 1, 2].map(async index => (await sample(index)).conversationWS[room] ?? null));
assert(hostedWS.every(counts => counts && counts.sent.chat + counts.received.chat > 0
&& counts.sent.history + counts.received.history > 0),
"current readers retain domain-carried conversation through owner recovery and paging");
await browser(1, "click", '.c3-room-link[aria-label="Browser-owned room"]');
for (const index of [0, 1, 2]) await assertNoError(index, "normal Browser room lifecycle");
await browser(1, "screenshot", join(output, "browser-owned-room.png"), "--full");
await writeFile(join(output, "room-owner-result.json"), JSON.stringify({ passed: true,
scenarios: ["private invitation initial admission", "owner IndexedDB history", "no room data in domain SQLite",
"cross-room shared transport", "room voice", "owner signaling resume", "scoped shutdown", "retained paused directory",
"owner reopen without capture revival", "maximum valid history page", "participant-signed fake reply rejected", "normal chat after rejected reply"],
conversationTransport: { serverRoomWS: serverWS, hostedRoomWS: hostedWS, rejectedReply },
domainMessageCopies: 0, maximumHistoryPage: { messagesPerPage: 50, retainedMessages: 100, charactersPerMessage: 2000,
pages: historyPages, transport: "signed WebSocket records" } }, null, 2));
console.log("Browser owns policy/history and room activities; domain only retains its directory; unrelated media survives owner shutdown");
}
async function lifecycle(roomId) {
await action(1, `joinVoice(${JSON.stringify(roomId)}, true)`);
assert.equal((await sample(1)).captures.filter(track => track.kind === "audio" && track.state === "live").length, 0);
await action(1, `setMuted(${JSON.stringify(roomId)}, false)`);
assert((await sample(1)).captures.some(track => track.kind === "audio" && track.state === "live"));
await action(1, `leaveVoice(${JSON.stringify(roomId)})`);
await until("leave releases microphone capture", () => sample(1), value => value.captures.every(track => track.state === "ended"));
console.log("Listen-only takes no microphone; unmute captures; leave releases it");
const otherScreen = await capturedScreen(2, roomId);
await action(2, `joinVoice(${JSON.stringify(roomId)})`);
await action(1, `joinVoice(${JSON.stringify(roomId)})`);
await action(1, `watch(${JSON.stringify(otherScreen)})`);
await playing(1, otherScreen);
await until("voice receives actual samples", () => sample(1), value => value.inbound.some(row => row.kind === "audio" && row.samples > 0));
const voiceBeforeOffline = await view(1);
const offlineVoices = voiceBeforeOffline.state.publications.filter(publication => publication.kind === 'voice'
&& publication.roomId === roomId && publication.sessionId !== voiceBeforeOffline.sessionId).map(publication => publication.id);
await until("local voice is actually playing before the offline stop", () => voicePlayback(1, offlineVoices), nativeVoicePlaying);
await voicePlayback(1, offlineVoices, true);
const sameSession = voiceBeforeOffline.sessionId;
await browser(1, "set", "offline", "on");
await dropSignaling(1);
await until("signaling is offline", () => view(1), value => value.connection === "reconnecting");
await action(1, `unwatch(${JSON.stringify(otherScreen)})`);
await action(1, `leaveVoice(${JSON.stringify(roomId)})`);
await until("offline stop releases microphone and playback", async () => ({ state: await view(1),
capture: await sample(1), audio: await voicePlayback(1, offlineVoices) }), value =>
value.capture.captures.every(track => track.state === "ended") && voicePlayersRetired(value.audio) &&
!value.state.state.subscriptions.includes(otherScreen) && !value.state.state.voice.some(member => member.sessionId === sameSession));
await until("offline unwatch removes the local player", () => picture(1, otherScreen), value => value.frames === 0 && value.time === 0);
await browser(1, "set", "offline", "off");
await action(1, "reconnect()");
await until("offline intent survives authoritative reconciliation", () => view(1), value => value.connection === "connected" &&
value.sessionId === sameSession && !value.state.subscriptions.includes(otherScreen) &&
!value.state.voice.some(member => member.sessionId === sameSession));
assert((await sample(1)).captures.every(track => track.state === "ended"));
console.log("Offline unwatch/leave immediately stop consumption and do not revive on resume");
const expiringScreen = await capturedScreen(1, roomId);
await action(0, `watch(${JSON.stringify(expiringScreen)})`);
await playing(0, expiringScreen);
const previousSession = (await view(1)).sessionId;
await browser(1, "set", "offline", "on");
const disconnectedAt = Date.now();
await dropSignaling(1);
await until("20-second authority deadline retires media", async () => ({ state: await view(1), media: await sample(1) }), value =>
value.state.sessionId === null && value.media.captures.every(track => track.state === "ended") &&
value.media.connections.every(connection => connection === "closed"), 28_000);
assert(Date.now() - disconnectedAt >= 19_000, "capture must survive the bounded recovery window before expiry");
await browser(1, "set", "offline", "off");
await action(1, "reconnect()");
await until("expiry admits a fresh endpoint without old capture", () => view(1), value => value.connection === "connected" &&
value.sessionId !== previousSession && !value.state.publications.some(publication => publication.id === expiringScreen));
assert((await sample(1)).captures.every(track => track.state === "ended"));
console.log("Signaling deadline releases all captures/transports; a fresh session does not resurrect them");
await browser(0, "set", "viewport", "390", "844");
await evaluate(0, `(async () => {
(await import('/src/client/ui/copy.ts')).setCopy({lang:'zh',vis:false});
(await import('/src/client/ui/theme.ts')).applyTheme('light');
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
})()`);
assert.equal((await sample(0)).overflow, false);
await browser(0, "screenshot", join(output, "lifecycle-zh-light-390.png"), "--full");
await writeFile(join(output, "lifecycle-result.json"), JSON.stringify({ passed: true,
scenarios: ["listen-only", "unmute capture", "leave capture retirement",
"offline unwatch/leave", "same-session intent reconciliation", "20s media expiry", "new-session no resurrection"],
recoveryMs: Date.now() - disconnectedAt }, null, 2));
}
async function identityControls(serverRoom) {
const png = join(temporary, "picture.png"), invalid = join(temporary, "notes.txt");
const data = await evaluate(0, `(() => {
const canvas = document.createElement('canvas'); canvas.width = canvas.height = 256;
const context = canvas.getContext('2d'); context.fillStyle = '#ef9463'; context.fillRect(0,0,256,256);
context.fillStyle = '#fff4d6'; context.beginPath(); context.arc(128,128,84,0,Math.PI*2); context.fill();
context.fillStyle = '#35322f'; context.fillRect(88,100,18,30); context.fillRect(150,100,18,30);
context.fillRect(106,162,44,10); return canvas.toDataURL('image/png');
})()`);
await writeFile(png, Buffer.from(data.split(',')[1], "base64"));
await writeFile(invalid, "This is not a picture.");
const openSite = async () => {
await showRoomList(0);
await browser(0, "find", "role", "button", "click", "--name", "Site settings", "--exact");
await settingsTask(0, "site");
await browser(0, "click", ".c3-identity-appearance > summary");
};
const upload = async path => {
await browser(0, "upload", '.c3-identity-picker input[type="file"]', path);
};
const preview = () => until("chosen identity decodes", () => evaluate(0,
"!!document.querySelector('.c3-identity-upload img')?.naturalWidth"), Boolean);
await openSite(); await upload(invalid);
await until("invalid picture leaves an actionable error", () => evaluate(0,
"document.querySelector('.c3-identity-error')?.textContent"), value => value?.includes("Try another"));
await upload(png); await preview();
await browser(0, "find", "role", "button", "click", "--name", "Cancel", "--exact");
assert.equal((await view(0)).state.channel.icon, "couch", "cancel never writes the draft image");
await openSite();
assert.equal(await evaluate(0, "!!document.querySelector('.c3-identity-upload img')"), false);
await upload(png); await preview();
await browser(0, "click", ".c3-room-form button[type=submit]");
const domainIcon = await until("domain image reaches the other user", () => evaluate(1,
`${hook}.snapshot().state.channel.icon`), value => value.startsWith("data:image/"));
await until("site header renders the saved image", () => evaluate(1,
"[...document.querySelectorAll('.c3-site-name img')].some(image => image.naturalWidth > 0)"), Boolean);
await roomSettings(0, serverRoom);
await browser(0, "click", ".c3-identity-appearance > summary");
await upload(png); await preview();
await browser(0, "click", ".c3-room-form button[type=submit]");
await until("Native room projects its saved image", () => view(1), value =>
value.state.channel.rooms.find(room => room.id === serverRoom)?.icon.startsWith("data:image/"));
await roomSettings(0, serverRoom);
await browser(0, "click", ".c3-identity-appearance > summary");
await browser(0, "find", "role", "button", "click", "--name", "Star", "--exact");
await browser(0, "click", ".c3-room-form button[type=submit]");
await until("preset replaces Native room image", () => view(1), value => value.state.channel.rooms.find(room => room.id === serverRoom)?.icon === "star");
await browser(0, "find", "role", "button", "click", "--name", "Create room", "--exact");
await browser(0, "fill", ".c3-room-form input[type=text], .c3-room-form input:not([type])", "Identity room");
await browser(0, "click", ".c3-identity-appearance > summary");
await upload(png); await preview();
await browser(0, "click", ".c3-room-form button[type=submit]");
const created = await until("Browser room is created with its image", () => view(1), value =>
value.state.channel.rooms.some(room => room.name === "Identity room" && room.icon.startsWith("data:image/")));
const room = created.state.channel.rooms.find(room => room.name === "Identity room");
await browser(0, "reload");
await until("Browser reload restores hosting and both identities", () => view(0), value =>
value.connection === "connected" && value.state.channel.icon === domainIcon &&
value.state.channel.rooms.some(item => item.id === room.id && item.available && item.icon === room.icon));
await browser(0, "click", '.c3-room-link[aria-label="Identity room"]');
await until("conversation welcome renders its room image", () => evaluate(0,
"!!document.querySelector('.c3-room-start-mark img')?.naturalWidth"), Boolean);
await roomSettings(0, room.id);
await browser(0, "click", ".c3-identity-appearance > summary");
await until("identity editor opens", () => evaluate(0, "!!document.querySelector('.c3-room-form')"), Boolean);
await browser(0, "screenshot", join(output, "identity-desktop.png"));
await browser(0, "press", "Escape");
await browser(0, "set", "viewport", "390", "844");
for (const [lang, theme, vis] of [["en", "light", false], ["zh", "dark", false], ["en", "dark", true]]) {
await evaluate(0, `(async () => {
(await import('/src/client/ui/copy.ts')).setCopy({lang:${JSON.stringify(lang)},vis:${vis}});
(await import('/src/client/ui/theme.ts')).applyTheme(${JSON.stringify(theme)});
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); return true;
})()`);
await roomSettings(0, room.id);
await browser(0, "click", ".c3-identity-appearance > summary");
await until("translated identity editor opens", () => evaluate(0, "!!document.querySelector('.c3-room-form')"), Boolean);
const bounds = await evaluate(0, `(() => { const form = document.querySelector('.c3-room-form').getBoundingClientRect();
return {left:form.left, right:form.right, width:innerWidth, scroll:document.documentElement.scrollWidth}; })()`);
assert(bounds.left >= 0 && bounds.right <= bounds.width && bounds.scroll <= bounds.width, JSON.stringify(bounds));
await browser(0, "screenshot", join(output, `identity-${lang}-${theme}-${vis ? "visual" : "text"}.png`));
await browser(0, "press", "Escape");
}
await evaluate(0, `(async () => { (await import('/src/client/ui/copy.ts')).setCopy({lang:'en',vis:false}); return true; })()`);
await roomSettings(0, room.id);
await browser(0, "click", ".c3-identity-appearance > summary");
await browser(0, "find", "role", "button", "click", "--name", "Remove", "--exact");
await browser(0, "click", ".c3-room-form button[type=submit]");
await until("removing Browser image restores a preset", () => view(1), value => value.state.channel.rooms.find(item => item.id === room.id)?.icon === "couch");
for (const index of active) await assertNoError(index, "identity image editing");
await writeFile(join(output, "identity-result.json"), JSON.stringify({ passed: true, domain: true, nativeRoom: true,
browserRoom: true, reload: true, cancel: true, invalidImage: true, presetReplacement: true, narrowThemesAndLanguages: true }, null, 2));
}
async function roomBackupControls() {
const index = 1, name = "Browser backup room", first = "Room backup A", newer = "Room backup B";
const admitted = await view(index);
assert.notEqual(admitted.self.id, admitted.state.channel.ownerId, "backup uses an ordinary member");
assert.equal(await evaluate(index, `${hook}.snapshot().appConnected`), false);
assert.equal(await evaluate(index, "typeof window.__channelProbe"), "undefined", "no media fixture is installed");
await browser(index, "find", "role", "button", "click", "--name", "English", "--exact");
await browser(index, "find", "role", "button", "click", "--name", "Create room", "--exact");
await browser(index, "find", "label", "Room name", "fill", name);
await browser(index, "click", ".c3-room-form button[type=submit]");
const created = await until("member creates its Browser room", () => view(index), value =>
value.state.channel.rooms.some(room => room.name === name && room.available && room.delivery?.hostSessionId === value.sessionId));
const roomId = created.state.channel.rooms.find(room => room.name === name).id;
const current = () => evaluate(index, `(() => {
const value = ${hook}.snapshot(), room = value.state.channel.rooms.find(room => room.id === ${JSON.stringify(roomId)});
return { sessionId: value.sessionId, userId: value.self.id, domainId: value.state.channel.id, room,
messages: value.messagesByRoom[${JSON.stringify(roomId)}] ?? [], history: value.historyByRoom[${JSON.stringify(roomId)}],
pending: [...value.pending], error: value.error, text: document.querySelector('.c3-message-log')?.textContent };
})()`);
const send = async text => {
await browser(index, "fill", ".c3-composer textarea", text);
await browser(index, "click", ".c3-composer button[type=submit]");
};
const settings = async () => {
await roomSettings(index, roomId, "data");
};
await send(first);
const before = await until("A is authoritative and visible", current, value => value.messages.length === 1 && value.messages[0].text === first && value.text.includes(first));
await settings();
const archive = join(output, "piik-room-backup.zip");
await rm(archive, { force: true });
await browser(index, "click", '.c3-backup-actions button[aria-label="Export backup"]');
const bytes = await until("normal export finishes its Browser download", () => readFile(archive).catch(() => undefined), value => value?.length > 0);
assert.equal(bytes.subarray(0, 2).toString(), "PK", "normal export downloads a ZIP");
await browser(index, "press", "Escape");
await send(newer);
const changed = await until("B is visible in the newer reading", current, value => value.messages.length === 2 && value.messages[1].text === newer && value.text.includes(newer));
await settings();
await browser(index, "click", '.c3-backup-actions button[aria-label="Restore backup"]');
await browser(index, "upload", '.c3-backup-controls input[type="file"]', archive);
assert((await browser(index, "get", "text", ".c3-backup-confirm")).text.includes("Restoring replaces this room"));
await browser(index, "screenshot", join(output, "room-backup-confirm.png"));
await browser(index, "click", '.c3-backup-confirm button[aria-label="Confirm"]');
const readingReady = value => value.messages.length === 1 && value.messages[0].text === first
&& value.history?.atLatest && !value.pending.includes(`history:${roomId}`) && !value.pending.includes("room-backup")
&& value.text.includes(first) && !value.text.includes(newer);
const restored = await until("fresh authority replaces B with the archived A reading", current, value =>
value.room?.delivery && value.room.delivery.bindingId !== changed.room.delivery.bindingId
&& value.room.delivery.hostSessionId === changed.room.delivery.hostSessionId && readingReady(value));
assert.equal(restored.sessionId, changed.sessionId);
assert.equal(restored.messages[0].id, before.messages[0].id);
assert.equal(await evaluate(index, "document.querySelectorAll('dialog.c3-settings-dialog[open]').length"), 1);
assert.equal(await evaluate(index, "document.querySelector('dialog.c3-settings-dialog[open] [role=tab][aria-controls$=\"-data\"]')?.getAttribute('aria-selected')"), "true");
assert.deepEqual((await browser(index, "console")).messages.filter(message => message.type === "error"), []);
await browser(index, "screenshot", join(output, "room-backup-restored.png"));
await browser(index, "reload");
await until("ordinary member reconnects after reload", () => view(index), value => value.connection === "connected"
&& value.state.channel.rooms.some(room => room.id === roomId && room.available));
await browser(index, "click", `.c3-room-link[aria-label="${name}"]`);
const reloaded = await until("real IndexedDB reopens the restored A history", current, readingReady);
assert.equal(reloaded.userId, before.userId); assert.equal(reloaded.domainId, before.domainId);
assert.equal(reloaded.room.delivery.hostSessionId, reloaded.sessionId);
assert.equal(reloaded.messages[0].id, before.messages[0].id);
assert.equal(reloaded.error, null);
assert.deepEqual((await browser(index, "errors")).errors, []);
await writeFile(join(output, "room-backup-result.json"), JSON.stringify({ passed: true, ordinaryMember: true,
mediaFixture: false, sessionMutations: false, indexedDbWritesByTest: false,
archive: { bytes: bytes.length, sha256: createHash("sha256").update(bytes).digest("hex") },
before, changed, restored, reloaded }, null, 2));
}
async function countedRoomReactions(roomId) {
const room = (await view(0)).state.channel.rooms.find(room => room.id === roomId);
const message = await until("both readers receive the message reaction target", () => evaluate(1,
`${hook}.snapshot().messagesByRoom[${JSON.stringify(roomId)}]?.[0]`), Boolean);
const messageSelector = `[data-message-id=${JSON.stringify(message.id)}]`;
const messageCount = index => evaluate(index,
`${hook}.snapshot().messagesByRoom[${JSON.stringify(roomId)}]?.find(message => message.id === ${JSON.stringify(message.id)})?.reactions?.counts.tomato ?? 0`);
await browser(1, "hover", messageSelector);
await browser(1, "click", `${messageSelector} .c3-add-reaction`);
for (let count = 1; count <= 2; count++) {
await until("the shared room reaction cooldown permits another confirmed click", () => evaluate(1,
`${hook}.snapshot().interactionsByRoom.get(${JSON.stringify(roomId)})?.getSnapshot().coolingDown === false`), Boolean);
await browser(1, "click", '.c3-message-reaction-menu:popover-open button[aria-label="Toss tomato"]');
await until("both readers receive the confirmed message count", () => Promise.all([0, 1].map(messageCount)),
values => values.every(value => value === count));
}
assert.equal(await evaluate(1, `document.querySelector(${JSON.stringify(messageSelector)})?.querySelectorAll('.c3-message-reaction[aria-pressed]').length`), 0,
"counted reactions are actions, not selected toggles");
await browser(1, "press", "Escape");
const publication = await capturedScreen(0, roomId);
try {
await browser(1, "click", `.c3-monitor-offer[data-source-id=${JSON.stringify(publication)}] button[aria-label="Watch"]`);
await playing(1, publication);
await browser(1, "click", `[data-publication-id=${JSON.stringify(publication)}] .c3-add-reaction`);
await until("source reaction uses the same available cooldown", () => evaluate(1,
`${hook}.snapshot().interactionsByRoom.get(${JSON.stringify(roomId)})?.getSnapshot().coolingDown === false`), Boolean);
await browser(1, "click", '.c3-message-reaction-menu:popover-open button[aria-label="Toss poop"]');
const sourceCount = index => evaluate(index, `${hook}.snapshot().publicationReactions.get(${JSON.stringify(publication)})?.counts.poop ?? 0`);
await until("owner and Viewer receive the same confirmed publication count", () => Promise.all([0, 1].map(sourceCount)),
values => values.every(value => value === 1));
await browser(1, "press", "Escape");
await browser(1, "reload");
await until("the ordinary member reconnects with the current room", () => view(1), value => value.connection === "connected"
&& value.state.channel.rooms.some(value => value.id === roomId && value.authorized && value.available));
await showRoomList(1);
await browser(1, "click", `.c3-room-link[aria-label=${JSON.stringify(room.name)}]`);
await until("history and live-source snapshots restore their counts", async () => ({ message: await messageCount(1), source: await sourceCount(1),
ready: await evaluate(1, `${hook}.snapshot().interactionsByRoom.get(${JSON.stringify(roomId)})?.getSnapshot().ready`) }),
value => value.message === 2 && value.source === 1 && value.ready);
assert.equal(await evaluate(1, "document.querySelectorAll('.lr-reaction-content').length"), 0,
"history and readiness snapshots do not replay live reaction effects");
await writeFile(join(output, "counted-room-reactions.json"), JSON.stringify({ passed: true, messageCount: 2, sourceCount: 1,
confirmedAcrossReaders: true, ordinaryMemberReload: true, snapshotAnimationReplayed: false }, null, 2));
} finally { await action(0, `stopScreen(${JSON.stringify(publication)})`); }
console.log("Message and publication reactions count confirmed clicks across readers; reload restores counts without replay");
}
async function profileControls(roomId, messageId) {
const member = (await view(1)).self, owner = (await view(0)).self;
const name = "Profile member";
const memberProfile = index => evaluate(index,
`${hook}.snapshot().profiles.get(${JSON.stringify(member.id)})`);
const messageAvatar = () => evaluate(0, `(() => {
const row = document.querySelector('[data-message-id=' + CSS.escape(${JSON.stringify(messageId)}) + ']');
const image = row?.querySelector(':scope > .lr-person image');
return { name: row?.querySelector('.c3-message-meta strong')?.textContent, avatar: image?.getAttribute('href') ?? null };
})()`);
const openProfile = async () => {
await browser(1, "find", "role", "button", "click", "--name", "Edit profile", "--exact");
await browser(1, "wait", ".c3-name-popover:popover-open .c3-profile-picture");
};
const reenter = async () => {
await until("member reconnects with the saved private-room grant", () => view(1), value => value.connection === "connected"
&& value.self.id === member.id && value.state.channel.rooms.some(room => room.id === roomId && room.authorized && room.available));
const room = (await view(1)).state.channel.rooms.find(room => room.id === roomId);
await showRoomList(1);
await browser(1, "click", `.c3-room-link[aria-label=${JSON.stringify(room.name)}]`);
};
await openProfile();
await browser(1, "upload", '.c3-name-popover:popover-open input[type="file"]', resolve("public/favicon.png"));
const avatar = await until("the selected profile image finishes normal preparation", () => evaluate(1,
"document.querySelector('.c3-name-popover:popover-open .c3-profile-picture image')?.getAttribute('href')"), value => value?.startsWith("data:image/"));
await browser(1, "fill", '.c3-name-popover:popover-open input[autocomplete="nickname"]', name);
await browser(1, "click", '.c3-name-popover:popover-open button[type="submit"]');
await until("saved profile reaches both readers and the retained message author", async () => ({
profiles: await Promise.all([0, 1].map(memberProfile)), message: await messageAvatar(),
}), value => value.profiles.every(user => user?.name === name && user.avatar === avatar)
&& value.message.name === name && value.message.avatar === avatar);
await browser(0, "screenshot", join(output, "member-profile-message.png"));
await browser(1, "reload");
await reenter();
assert.deepEqual((({ id, name, avatar }) => ({ id, name, avatar }))((await view(1)).self), { id: member.id, name, avatar },
"ordinary reload restores the saved name and avatar");
await browser(1, "open", "about:blank");
await until("offline author retains the image on confirmed history", async () => ({
sessions: await evaluate(0, `${hook}.snapshot().state.sessions`), profile: await memberProfile(0), message: await messageAvatar(),
}), value => !value.sessions.some(session => session.userId === member.id && session.online)
&& value.profile?.name === name && value.profile.avatar === avatar
&& value.message.name === name && value.message.avatar === avatar);
await browser(1, "open", `${origin}/__channel-preview#room=${encodeURIComponent(roomId)}`);
await reenter();
if (!await evaluate(0, "document.querySelector('#c3-people')?.checkVisibility() ?? false"))
await browser(0, "click", "#c3-companion-trigger");
const previewButton = `#c3-people [data-user-id=${JSON.stringify(member.id)}] .c3-avatar-preview`;
await browser(0, "click", previewButton);
await browser(0, "wait", ".c3-image-dialog[open]");
await openProfile();
await browser(1, "find", "role", "button", "click", "--name", "Remove picture", "--exact");
await browser(1, "click", '.c3-name-popover:popover-open button[type="submit"]');
await until("removing a profile image updates the other reader without changing its own identity", async () => ({
profiles: await Promise.all([0, 1].map(memberProfile)), message: await messageAvatar(), owner: (await view(0)).self,
}), value => value.profiles.every(user => user?.name === name && user.avatar === null)
&& value.message.name === name && value.message.avatar === null
&& value.owner.id === owner.id && value.owner.name === owner.name && value.owner.avatar === owner.avatar);
await until("removing the viewed avatar retires its preview", () => evaluate(0,
"document.querySelectorAll('.c3-image-dialog[open]').length"), count => count === 0);
await openProfile();
await browser(1, "upload", '.c3-name-popover:popover-open input[type="file"]', resolve("public/favicon.png"));
await until("the same avatar is prepared again", () => evaluate(1,
"document.querySelector('.c3-name-popover:popover-open .c3-profile-picture image')?.getAttribute('href')"), value => value === avatar);
await browser(1, "click", '.c3-name-popover:popover-open button[type="submit"]');
await until("the restored avatar reaches both readers", () => Promise.all([0, 1].map(memberProfile)),
values => values.every(user => user?.avatar === avatar));
assert.equal(await evaluate(0, "document.querySelectorAll('.c3-image-dialog[open]').length"), 0,
"restoring an avatar does not restore an old preview intent");
await browser(0, "click", previewButton);
await browser(0, "wait", ".c3-image-dialog[open]");
await browser(0, "press", "Escape");
await until("the explicitly reopened preview closes normally", () => evaluate(0,
"document.querySelectorAll('.c3-image-dialog[open]').length"), count => count === 0);
await writeFile(join(output, "member-profile-result.json"), JSON.stringify({ passed: true, userId: member.id,
messageId, name, avatarSha256: createHash("sha256").update(avatar).digest("hex"),
realImagePreparation: true, bothReaders: true, reload: true, offlineAuthor: true, removal: true,
removedPreviewRetired: true, explicitPreviewReopen: true, ownerUnchanged: true }, null, 2));
console.log("Profile UI saves name and avatar across readers/reload, retains the offline author and removes the image live");
}
async function roomsAndFiles() {
await browser(0, "find", "role", "button", "click", "--name", "Create room", "--exact");
await browser(0, "fill", ".c3-room-form input:not([type])", "Movie night");
await browser(0, "check", ".c3-room-form input[value=private]");
await browser(0, "fill", ".c3-room-form input[type=password]", "movie-night-test");
await browser(0, "click", ".c3-room-form button[type=submit]");
const created = await until("new private room is selected", () => view(0), value => value.state.channel.rooms.some(room => room.name === "Movie night"));
const room = created.state.channel.rooms.find(room => room.name === "Movie night");
await browser(1, "click", '.c3-room-link[aria-label="Movie night"]');
await until("unadmitted user sees password entry", () => evaluate(1, "!!document.querySelector('.c3-locked-room input')"), Boolean);
assert.equal(await evaluate(1, "[...document.querySelectorAll('.c3-composer')].some(form => !form.closest('[hidden]') && !form.querySelector('textarea').disabled)"), false);
await browser(1, "fill", ".c3-locked-room input", "movie-night-test");
await browser(1, "click", ".c3-locked-room button[type=submit]");
await until("room grant opens the conversation", () => evaluate(1, "!!document.querySelector('.c3-composer textarea')"), Boolean);
await browser(1, "fill", ".c3-composer textarea", "Hello from the private room");
assert.equal(await evaluate(1, "!!document.querySelector('.c3-composer input[type=file]')"), true,
"Browser rooms use their real peer endpoint for files");
const png = join(temporary, "picture.png"), text = join(temporary, "notes.txt");
await writeFile(png, Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a1XcAAAAASUVORK5CYII=", "base64"));
await writeFile(text, "A file shared through the actual composer.");
await browser(1, "upload", '.c3-composer input[type="file"]', png, text);
await until("two draft files", () => evaluate(1, "document.querySelectorAll('.c3-draft-files > div').length"), count => count === 2);
await browser(1, "click", ".c3-composer button[type=submit]");
await until("attachment metadata arrives in chat", () => evaluate(0, "document.querySelector('.c3-message-log').textContent"), text => text.includes("picture.png") && text.includes("notes.txt"));
await browser(0, "find", "role", "button", "click", "--name", "View image", "--exact");
await until("PNG preview decodes", () => evaluate(0, "[...document.querySelectorAll('.c3-attachment img')].some(image => image.complete && image.naturalWidth > 0)"), Boolean);
for (const index of [0, 1]) await assertNoError(index, "normal room entry, chat and file flow");
await countedRoomReactions(room.id);
const authored = await until("the profile target is the member's confirmed image message", () => evaluate(0,
`${hook}.snapshot().messagesByRoom[${JSON.stringify(room.id)}]?.find(message => message.text === 'Hello from the private room')`), Boolean);
assert.equal(authored.userId, (await view(1)).self.id);
await profileControls(room.id, authored.id);
await browser(0, "screenshot", join(output, "peer-room-files-desktop.png"), "--full");
for (const index of [0, 1]) await browser(index, "click", '.c3-room-link[aria-label="Living room"]');
assert.equal(await evaluate(1, "!!document.querySelector('.c3-composer input[type=file]')"), true,
"the Server room's real peer endpoint supports the same file delivery");
console.log("Private Browser room owns chat and sends file bytes over its actual peer path");
const historyWindow = created.state.channel.historyWindow;
const pageSize = await evaluate(0, `(async () => {
const { history_page_size } = await import('/prototype/channel-browser/pkg/piik_channel_browser.js');
return history_page_size();
})()`);
// Prepare retained history independently of the normal sends above/below.
// One transaction copies the confirmed row's storage shape without rendering
// a thousand intermediate conversations just to reach the reading boundary.
await evaluate(0, `(async () => {
const host = ${hook}.session.hostedRooms.get(${JSON.stringify(room.id)}).host;
const tx = host.db.transaction('messages', 'readwrite');
const messages = tx.objectStore('messages');
const first = messages.get([${JSON.stringify(room.id)}, 1]);
first.onsuccess = () => {
for (let seq = 2; seq <= ${historyWindow}; seq++) messages.add({ ...first.result,
seq, id: crypto.randomUUID(), nonce: 'history-fixture-' + seq, text: 'history-' + seq,
attachments: [], reactions: { revision: 0, counts: {} } });
};
await new Promise((resolve, reject) => { tx.oncomplete = resolve; tx.onabort = () => reject(tx.error); });
return true;
})()`);
await browser(1, "click", '.c3-room-link[aria-label="Movie night"]');
await action(1, `sendMessage(${JSON.stringify(room.id)}, 'History preparation complete')`);
const latestSeq = historyWindow + 1;
await browser(0, "click", '.c3-room-link[aria-label="Movie night"]');
await until("returning loads the latest contiguous history page", () => evaluate(0,
`${hook}.snapshot().messagesByRoom[${JSON.stringify(room.id)}]?.map(message => message.seq)`),
seqs => seqs?.length === pageSize && seqs[0] === latestSeq - pageSize + 1 && seqs.at(-1) === latestSeq);
let firstSeq = latestSeq - pageSize + 1, loaded = pageSize;
while (firstSeq > 1) {
const olderCount = Math.min(pageSize, firstSeq - 1);
const anchor = loaded + olderCount > historyWindow ? await evaluate(0, `(() => {
const log = document.querySelector('.c3-message-log'); log.scrollTop = 0;
const message = log.querySelector('[data-message-id]');
return { id: message.dataset.messageId, offset: message.getBoundingClientRect().top - log.getBoundingClientRect().top };
})()`) : null;
await browser(0, "find", "role", "button", "click", "--name", "Earlier messages", "--exact");
firstSeq -= olderCount;
loaded = Math.min(historyWindow, loaded + olderCount);
await until("older page advances the reading window", () => evaluate(0,
`${hook}.snapshot().messagesByRoom[${JSON.stringify(room.id)}]?.map(message => message.seq)`),
seqs => seqs?.length === loaded && seqs[0] === firstSeq && seqs.every((seq, index) => seq === firstSeq + index));
if (anchor) {
await until("full-window pagination preserves the visible message", () => evaluate(0, `(() => {
const log = document.querySelector('.c3-message-log');
const message = [...log.querySelectorAll('[data-message-id]')].find(element => element.dataset.messageId === ${JSON.stringify(anchor.id)});
return message.getBoundingClientRect().top - log.getBoundingClientRect().top;
})()`), offset => Math.abs(offset - anchor.offset) <= 2);
}
}
assert.equal(await evaluate(0, `${hook}.snapshot().messagesByRoom[${JSON.stringify(room.id)}].length`), historyWindow);
assert.equal(await evaluate(0, `${hook}.snapshot().historyByRoom[${JSON.stringify(room.id)}].atLatest`), false);
await browser(0, "screenshot", join(output, "room-history-desktop.png"), "--full");
await browser(0, "set", "viewport", "390", "844");
assert.equal((await sample(0)).overflow, false);
await browser(0, "screenshot", join(output, "room-history-mobile.png"), "--full");
await browser(0, "set", "viewport", "1280", "900");
await action(1, `sendMessage(${JSON.stringify(room.id)}, 'Latest response')`);
assert.equal(await evaluate(0, `${hook}.snapshot().messagesByRoom[${JSON.stringify(room.id)}][0].seq`), 1);
await browser(0, "find", "role", "button", "click", "--name", "Latest messages", "--exact");
await until("reader can return to current conversation", () => evaluate(0,
`${hook}.snapshot().messagesByRoom[${JSON.stringify(room.id)}]?.at(-1)?.text`), text => text === "Latest response");
console.log("Room history retains old messages, advances a bounded reading window and returns to latest without live interruptions");
await roomSettings(0, room.id);
await browser(0, "find", "label", "Hide from users without access", "check");
await browser(0, "click", ".c3-room-form button[type=submit]");
await until("unadmitted user loses hidden directory entry", () => view(2), value => !value.state.channel.rooms.some(value => value.id === room.id));
await roomInvitation(0, room.id);
const invitationState = await until("room invitation controls finish loading", () => evaluate(0, `(() => {
const panel = document.querySelector('.c3-room-invitation:popover-open');
const generate = panel?.querySelector('button[aria-label="Generate password-free invitation"]');
return { url: panel?.querySelector('.c3-invitation-link input')?.value,
canGenerate: !!generate?.checkVisibility() && !generate.disabled && generate.getAttribute('aria-disabled') !== 'true' };
})()`), value => value.url || value.canGenerate);
if (!invitationState.url) {
await browser(0, "find", "role", "button", "click", "--name", "Generate password-free invitation", "--exact");
}
const previousInvite = await until("current room invitation is loaded", () => evaluate(0,
"document.querySelector('.c3-room-invitation:popover-open .c3-invitation-link input')?.value"), Boolean);
await browser(0, "click", ".c3-room-invitation:popover-open > details.c3-settings-details > summary");
await browser(0, "find", "role", "button", "click", "--name", "Confirm invitation reset", "--exact");
const invite = await until("replacement room invitation is ready", () => evaluate(0,
"document.querySelector('.c3-room-invitation:popover-open .c3-invitation-link input')?.value"), value => !!value && value !== previousInvite);
await browser(0, "click", ".c3-room-invitation:popover-open .c3-invite-qr-details > summary");
await until("the replacement invitation has its actual QR image", () => evaluate(0,
"!!document.querySelector('.c3-room-invitation:popover-open .c3-invite-qr-details[open] svg[data-invitation-code]')"), Boolean);
await browser(0, "screenshot", join(output, "room-invitation-qr.png"));
await browser(0, "press", "Escape");
await until("Escape closes the invitation and its inline QR together", () => evaluate(0,
"!document.querySelector('.c3-room-invitation:popover-open')"), Boolean);
const invitedSession = (await view(2)).sessionId;
await browser(2, "open", invite);
await until("open page enters hidden room from room invitation", () => view(2), value => value.connection === "connected" && value.state.channel.rooms.some(value => value.id === room.id && value.authorized));
assert.equal((await view(2)).sessionId, invitedSession, "invitation navigation must retain the live endpoint");
await evaluate(2, "localStorage.removeItem('piik.channel.prototype.credential')");
await browser(2, "open", "about:blank");
await browser(2, "open", invite);
await until("fresh user enters hidden room from room invitation", () => view(2), value => value.connection === "connected" && value.state.channel.rooms.some(value => value.id === room.id && value.authorized));
await capturedScreen(1, room.id);
const memberName = (await view(1)).self.name;
await roomSettings(0, room.id, "room");
await browser(0, "click", "dialog.c3-settings-dialog[open] .c3-room-members > summary");
const memberRows = await evaluate(0, "[...document.querySelectorAll('dialog.c3-settings-dialog[open] .c3-room-members > div')].map(row => row.querySelector(':scope > span')?.textContent)");
const memberRow = memberRows.indexOf(memberName);
assert(memberRow >= 0, "the admitted member has a real access-management row");
await browser(0, "click", `dialog.c3-settings-dialog[open] .c3-room-members > div:nth-of-type(${memberRow + 1}) button[aria-label="Remove room access"]`);
await until("revocation retires capture and history", async () => ({ view: await view(1), probe: await sample(1),
history: await evaluate(1, `${hook}.snapshot().messagesByRoom[${JSON.stringify(room.id)}]`) }),
value => !value.view.state.channel.rooms.some(value => value.id === room.id) && !value.history && value.probe.captures.every(track => track.state === "ended"));
console.log("Hidden-room invitation admits a new user; revocation clears private history and capture");
await browser(0, "press", "Escape");
await browser(0, "set", "viewport", "390", "844");
await roomSettings(0, room.id);
assert.equal((await sample(0)).overflow, false);
await browser(0, "screenshot", join(output, "private-room-settings-mobile.png"), "--full");
await browser(0, "press", "Escape");
}
// The scenario below is bound to the prototype's real session API, never a
// parallel test implementation of room state, routing or signaling.
await mkdir(output, { recursive: true });
const temporary = await mkdtemp(join(tmpdir(), "piik-channel-acceptance-"));
try {
for (const index of active) {
const script = join(temporary, `${index}.js`);
if (!backupOnly) await writeFile(script, captureProbe(String.fromCharCode(65 + index)));
await browser(index, "open", `${origin}/__channel-preview${index === 0 ? `#owner=${encodeURIComponent(ownerKey)}` : ""}`);
}
const initial = [];
for (const index of active) {
await until(`browser ${index} authenticates`, () => evaluate(index,
`${hook} ? ${hook}.snapshot().connection : 'no hook'`), value => value === "connected");
if (!backupOnly) await action(index, `updateProfile({name:${JSON.stringify(String.fromCharCode(65 + index))},avatar:null})`);
initial.push(await view(index));
}
const roomId = backupOnly ? undefined : initial[0].state.channel.rooms[0].id;
if (!backupOnly) assert.equal(initial[0].self.id, initial[0].state.channel.ownerId);
if (backupOnly) {
await roomBackupControls();
console.log(`Browser room backup UI acceptance passed; evidence: ${output}`);
} else if (identityOnly) {
await identityControls(roomId);
console.log(`Identity image acceptance passed; evidence: ${output}`);
} else if (appOnly) {
await appRoom({ initial, serverRoom: roomId, browser, action, view, evaluate, until, sample,
capturedScreen, playing, progressing, audioProgressing, hook, output });
console.log(`Linked App room acceptance passed; evidence: ${output}`);
} else if (nativeOnly) {
await nativeRoom({ initial, serverRoom: roomId, browser, action, view, evaluate, until, sample, audioProgressing,
capturedScreen, playing, progressing, assertNoError, hook, output });
console.log(`Native room acceptance passed; evidence: ${output}`);
} else if (baseOnly) {
await senderAllocationFailure();
await roomBase(initial);
console.log(`Room base acceptance passed; evidence: ${output}`);
} else if (hostsOnly) {
await roomOwner(initial, roomId);
console.log(`Browser room-owner acceptance passed; evidence: ${output}`);
} else if (roomsOnly) {
await roomsAndFiles();
console.log(`Room and file Browser acceptance passed; evidence: ${output}`);
} else if (lifecycleOnly) {
await lifecycle(roomId);
console.log(`Focused lifecycle acceptance passed; evidence: ${output}`);
} else {
console.log("Five independent Browser sessions authenticated");
// The continuing publisher hosts this room so a separate relay can leave.
// Native acceptance separately checks Server-hosted paths.
const roomId = await action(2, "createRoom({name:'Shared viewing',icon:'couch',access:'public',hidden:false})");
for (const index of active) await browser(index, "click", '.c3-room-link[aria-label="Shared viewing"]');
let secondPublisher = 1;
let secondPublication = await publishScreen(1, roomId);
const primaryPublication = await publishScreen(2, roomId);
for (const index of [0, 3, 4]) await action(index, `watch(${JSON.stringify(secondPublication)})`);
await action(4, `watch(${JSON.stringify(primaryPublication)})`);
await Promise.all([playing(3, secondPublication), playing(4, secondPublication), playing(4, primaryPublication)]);
assert(!(await view(3)).state.subscriptions.includes(primaryPublication), "D watches only B, even when it forwards C to E");
assert.equal((await picture(3, primaryPublication)).frames, 0, "transit must not create an unrequested local player");
await browser(4, "screenshot", join(output, "desktop-two-sources.png"), "--full");
await evaluate(4, "(() => { window.__focusPlayers = [...document.querySelectorAll('video')]; return true; })()");
const subscriptionsBeforeFocus = (await view(4)).state.subscriptions;
await browser(4, "click", `[data-publication-id="${primaryPublication}"] button[aria-label^="Focus"]`);
assert.equal(await evaluate(4, "document.querySelectorAll('.c3-monitor-grid.is-focused').length"), 1);
assert.equal(await evaluate(4, "window.__focusPlayers.every(video => video.isConnected)"), true);
assert.deepEqual((await view(4)).state.subscriptions, subscriptionsBeforeFocus);
await browser(4, "find", "role", "button", "click", "--name", "Grid view", "--exact");
await progressing(4, primaryPublication);
console.log("Two simultaneous sources; D receives only B; E decodes both");
const initialRoutes = await Promise.all([0, 3, 4].map(index => view(index)));
const leaf = [0, 3, 4][initialRoutes.findIndex(value => !value.state.pairs.some(pair => pair.outgoing.some(flow => flow.publicationId === secondPublication)))];
assert(leaf !== undefined, "distribution must have a leaf viewer");
await action(leaf, `unwatch(${JSON.stringify(secondPublication)})`);
await until("leaf stops watching", () => view(leaf), value => !value.state.subscriptions.includes(secondPublication));
await action(leaf, `watch(${JSON.stringify(secondPublication)})`);
await progressing(leaf, secondPublication);
for (const index of [0, 1, 4]) await action(index,
`joinVoice(${JSON.stringify(roomId)}, false, await navigator.mediaDevices.getUserMedia({audio:true}))`);
await until("real voice audio energy", () => evaluate(4, "window.__channelProbe.sample()"),
sample => sample.inbound.some(row => row.kind === "audio" && row.samples > 0 && row.energy > 0));
const voiceView = await view(4);
const playedVoices = voiceView.state.publications.filter(publication => publication.kind === 'voice'
&& publication.roomId === roomId && publication.sessionId !== voiceView.sessionId).map(publication => publication.id);
await until("actual native voice players are audible before deafen", () => voicePlayback(4, playedVoices), nativeVoicePlaying);
await voicePlayback(4, playedVoices, true);
const voicePairs = (await view(4)).state.pairs.map(pair => pair.id).sort();
await action(4, `setDeafened(${JSON.stringify(roomId)}, true)`);
await until("deafen retires the actual local voice players", () => voicePlayback(4, playedVoices), voicePlayersRetired);
await Promise.all(playedVoices.map(publication => audioProgressing(4, publication)));
assert.deepEqual((await view(4)).state.pairs.map(pair => pair.id).sort(), voicePairs, "local deafen must retain routing transports");
await action(4, `setDeafened(${JSON.stringify(roomId)}, false)`);
await until("undeafen restores actual native voice playback", () => voicePlayback(4, playedVoices), nativeVoicePlaying);
console.log("Real voice samples arrive alongside picture sharing");
for (const index of [1, 0, 3]) await action(index, `watch(${JSON.stringify(primaryPublication)})`);
await Promise.all([0, 1, 3, 4].map(index => playing(index, primaryPublication)));
const routed = await Promise.all(sessions.map((_, index) => view(index)));
const relay = routed.findIndex((state, index) => index !== 2 && state.state.pairs.some(pair => pair.outgoing.some(flow => flow.publicationId === primaryPublication && flow.selected)));
assert(relay >= 0, "bounded source fanout must produce an actual peer relay for four viewers");
const sourceCopies = routed[2].state.pairs.filter(pair => pair.outgoing.some(flow => flow.publicationId === primaryPublication)).length;
await action(secondPublisher, `stopScreen(${JSON.stringify(secondPublication)})`);
secondPublisher = relay;
secondPublication = await publishScreen(relay, roomId);
const watcher = relay === 4 ? 0 : 4;
await action(watcher, `watch(${JSON.stringify(secondPublication)})`);
await playing(watcher, secondPublication);
await action(secondPublisher, `stopScreen(${JSON.stringify(secondPublication)})`);
await progressing(relay, primaryPublication);
const relayView = await view(relay);
assert(relayView.state.pairs.some(pair => pair.outgoing.some(flow => flow.publicationId === primaryPublication)), "own source retirement must retain another source's forwarding");
console.log(`Browser ${relay} stopped its own source and keeps receiving/forwarding C`);
const downstreamIndices = relayView.state.pairs.filter(pair => pair.outgoing.some(flow => flow.publicationId === primaryPublication && flow.selected))
.map(pair => routed.findIndex(value => value.sessionId === pair.peerId));
assert(downstreamIndices.length > 0 && downstreamIndices.every(index => index >= 0));
const downstreamIndex = downstreamIndices[0];
const transitPairs = relayView.state.pairs.filter(pair => pair.incoming.some(flow => flow.publicationId === primaryPublication) || pair.outgoing.some(flow => flow.publicationId === primaryPublication)).map(pair => pair.id).sort();
await action(relay, `unwatch(${JSON.stringify(primaryPublication)})`);
const transit = await until("relay stops local consumption", () => view(relay), value => !value.state.subscriptions.includes(primaryPublication));
assert.deepEqual(transit.state.pairs.filter(pair => pair.incoming.some(flow => flow.publicationId === primaryPublication) || pair.outgoing.some(flow => flow.publicationId === primaryPublication)).map(pair => pair.id).sort(), transitPairs);
await until("transit has no local player", () => picture(relay, primaryPublication), value => value.frames === 0);
await Promise.all(downstreamIndices.map(index => progressing(index, primaryPublication, undefined, 30)));
await action(relay, `watch(${JSON.stringify(primaryPublication)})`);
await progressing(relay, primaryPublication);
console.log("Unwatch stops the relay's local player and preserves its downstream frames and pair IDs");
await browser(4, "click", `.c3-room-link[aria-label=${JSON.stringify(initial[0].state.channel.rooms[1].name)}]`);
await progressing(4, primaryPublication);
assert((await view(4)).state.subscriptions.includes(primaryPublication));
await action(4, `browse(${JSON.stringify(roomId)})`);
const beforeReconnect = (await view(4)).sessionId;
await evaluate(4, "window.__channelProbe.sockets.filter(socket => socket.readyState === WebSocket.OPEN && new URL(socket.url).pathname === '/prototype/channel').forEach(socket => socket.close())");
await action(4, "reconnect()");
await until("same endpoint reconnects", () => view(4), value => value.connection === "connected" && value.sessionId === beforeReconnect);
await progressing(4, primaryPublication);
console.log("Room browsing and signaling reconnect preserve current media");
await browser(relay, "close");
await progressing(downstreamIndex, primaryPublication);
const repaired = await until("relay exit is removed from recovered route", () => view(downstreamIndex), value =>
value.state.pairs.some(pair => pair.incoming.some(flow => flow.publicationId === primaryPublication) && pair.peerId !== routed[relay].sessionId));
assert(repaired.streams.includes(primaryPublication));
console.log("Relay exit recovers its downstream subscription");
const layoutIndex = relay === 4 ? 0 : 4;
assert.equal(await evaluate(layoutIndex, "document.querySelector('#c3-people').checkVisibility()"), true,
"the desktop roster is always available");
await evaluate(layoutIndex, "(() => { window.__panePlayers = [...document.querySelectorAll('video')]; return true; })()");
await browser(layoutIndex, "set", "viewport", "390", "844");
for (const lang of ["zh", "en"]) for (const theme of ["light", "dark"]) {
await evaluate(layoutIndex, `(async () => {
(await import('/src/client/ui/copy.ts')).setCopy({lang:${JSON.stringify(lang)},vis:false});
(await import('/src/client/ui/theme.ts')).applyTheme(${JSON.stringify(theme)});
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
return true;
})()`);
const layout = await evaluate(layoutIndex, `({ width: innerWidth, scroll: document.documentElement.scrollWidth,
lang: document.documentElement.lang, theme: document.documentElement.dataset.theme })`);
assert(layout.lang.startsWith(lang), `language did not update: ${JSON.stringify(layout)}`);
assert.equal(layout.theme, theme);
assert(layout.scroll <= layout.width, `${lang}/${theme} page overflows at 390px: ${JSON.stringify(layout)}`);
await browser(layoutIndex, "screenshot", join(output, `${lang}-${theme}-390.png`), "--full");
}
await browser(layoutIndex, "fill", ".c3-composer textarea", "A draft while checking the room");
const beforePanes = await view(layoutIndex);
await showRoomList(layoutIndex);
await browser(layoutIndex, "click", ".c3-domain-name button");
await browser(layoutIndex, "click", ".c3-domain-menu-actions > button");
assert.equal(await evaluate(layoutIndex, "document.activeElement.id"), "c3-people-heading");
await browser(layoutIndex, "screenshot", join(output, "people-mobile.png"), "--full");
await browser(layoutIndex, "click", "#c3-people .c3-pane-back button");
await browser(layoutIndex, "click", "#c3-rooms-trigger");
assert.equal(await evaluate(layoutIndex, "document.activeElement.id"), "c3-room-list-heading");
await browser(layoutIndex, "screenshot", join(output, "rooms-mobile.png"), "--full");
await browser(layoutIndex, "click", ".c3-room-list-actions button[aria-controls=\"c3-room-list\"]");
assert.equal(await evaluate(layoutIndex, "document.querySelector('.c3-composer textarea').value"), "A draft while checking the room");
assert.equal(await evaluate(layoutIndex, "window.__panePlayers.every(video => video.isConnected)"), true);
const afterPanes = await view(layoutIndex);
assert.equal(afterPanes.sessionId, beforePanes.sessionId);
assert(afterPanes.state.subscriptions.includes(primaryPublication), "pane navigation retains the watched screen");
await progressing(layoutIndex, primaryPublication);
await writeFile(join(output, "result.json"), JSON.stringify({ scenarios: ["two sources", "selective watching", "voice", "fanout relay",
"independent source stop", "transit without local watching", "room browsing", "signaling reconnect", "relay recovery", "bilingual themes at 390px", "room/people panes retain drafts and playback"],
sourceCopies, relay, downstreamIndex }, null, 2));
console.log(`Browser acceptance passed; evidence: ${output}`);
}
} catch (error) {
const evidence = await Promise.all(active.map(async index => ({
url: await browser(index, "get", "url").catch(failure => ({ error: String(failure) })),
errors: await browser(index, "errors").catch(failure => ({ error: String(failure) })),
console: await browser(index, "console").catch(failure => ({ error: String(failure) })),
view: await view(index).catch(failure => ({ error: String(failure) })),
probe: await evaluate(index, "window.__channelProbe?.sample() ?? { text: document.body.innerText.slice(-1800) }")
.catch(failure => ({ error: String(failure) })),
})));
await writeFile(join(output, "failure.json"), JSON.stringify({ error: String(error), evidence }, null, 2));
throw error;
} finally {
await Promise.allSettled(active.map(index => browser(index, "close")));
await Promise.allSettled([...active.map(index => `${index}.js`), "picture.png", "notes.txt"].map(name => unlink(join(temporary, name))));
await rmdir(temporary);
}