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

1198 lines
92 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 inviteKey = process.env.PIIK_CHANNEL_INVITE_KEY;
const backupOnly = process.argv.includes("--backup");
assert(inviteKey && (backupOnly || ownerKey), "Set the local server's invitation key and, for owner scenarios, owner key");
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] : lifecycleOnly || roomsOnly || hostsOnly || nativeOnly || appOnly ? [0, 1, 2] : [0, 1, 2, 3, 4];
async function browser(index, ...args) {
// 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 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 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 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();
left.setOutgoing(new Map([['voice', voice], ['failed-screen', { kind: 'screen', stream: new MediaStream([video, audio]) }]]));
check(errors.length === 1 && errors[0] === 'InvalidAccessError', 'Chrome must reject the duplicate audio track itself');
check(failures.length === 1 && failures[0] === 'failed-screen', 'only the failed flow reports allocation failure');
check(left.pc.getSenders().filter(sender => sender.track).length === 1 && left.pc.getSenders().some(sender => sender.track === audio), 'partial video sender was not rolled back');
check([audio, video, secondVideo].every(track => track.readyState === 'live'), 'allocation failure stopped a source track');
const failed = { kind: 'screen', stream: new MediaStream([video]) };
for (let repeat = 0; repeat < 3; repeat++) left.setOutgoing(new Map([['voice', voice], ['failed-screen', failed]]));
check(errors.length === 1 && left.pc.getSenders().filter(sender => sender.track).length === 1, '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 = left.pc.getSenders().filter(sender => sender.track);
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);
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(stableSenders.every(sender => left.pc.getSenders().includes(sender) && sender.track?.readyState === 'live'), 'an established sender was retired with the candidate');
check(!left.pc.getSenders().some(sender => sender.track === candidateVideo) && candidateVideo.readyState === 'live', 'failed candidate resource was retained or its source stopped');
for (let repeat = 0; repeat < 3; repeat++) left.setOutgoing(offered);
check(!left.pc.getSenders().some(sender => sender.track === candidateVideo), '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');
return { passed: true, error: errors[0], 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 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 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, `joinVoice(${JSON.stringify(room)})`);
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 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)));
// Set a real lower-quality incumbent before releasing its first SDP.
// The capture and shadow senders remain unconstrained at 640x360/10fps.
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, 'sender limits do not constrain the capture');
assert.deepEqual(frameLimit.after.others, frameLimit.before.others, 'other video senders keep their own encoding parameters');
assert(frameLimit.after.encodings.length && frameLimit.after.encodings.every(encoding => encoding.maxFramerate === 5 && encoding.scaleResolutionDownBy === 4));
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 faults = await until('only the two shadow video senders stop actual RTP', () => Promise.all([source, relay].map(sample)), values =>
values.every((value, offset) => value.videoStall?.flowId === branches[offset].candidate.id && value.videoStall.connected));
for (const value of faults) assert.equal(value.videoStall.bytes, 0, 'the candidate fault emits no RTP while the incumbent shares a live PC');
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 held = await Promise.all(watchers.map(index => inspect(index, publication)));
held.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'));
});
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') {
await evaluate(source, 'window.__channelProbe.restoreVideo()');
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, firstSwitchReadyAt: readyAt, expiredAfterReadyMs: Date.now() - readyAt,
elapsedMs: Date.now() - faults[0].videoStall.startedAt });
await Promise.all((mode === 'unwatch' ? [relay] : watchers).map(index => progressing(index, publication)));
} else {
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 browser(viewer, 'dblclick', `video[data-flow-id="${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));
await Promise.all([source, relay].map(index => evaluate(index, '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, 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');
assert.deepEqual(selected[0].outputs.find(output => output.flowId === downstream.candidate.id), warmOutput,
'commit preserves the shadow output flow, wrapper and sender identities');
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 browser(viewer, 'dblclick', `video[data-flow-id="${downstream.candidate.id}"]`);
records.push({ mode, branches, frameLimit, baseline, 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]) 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})");
const source = await capturedScreen(1, pictureRoom);
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"]');
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)})`);
await browser(3, "click", '.c3-room-link[aria-label="Connected room"]');
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(1, `joinVoice(${JSON.stringify(room)}, true)`);
await action(3, `joinVoice(${JSON.stringify(room)})`);
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");
assert(await evaluate(2, "[...document.querySelectorAll('audio')].filter(audio => audio.srcObject).every(audio => audio.hidden && audio.muted)"),
"transit decoder consumers must remain silent and absent from local playback");
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));
const voicePairIds = (await view(1)).state.pairs.map(pair => pair.id).sort();
await action(1, `setDeafened(${JSON.stringify(room)}, true)`);
await until("deafen only mutes local voice", () => evaluate(1,
"[...document.querySelectorAll('audio')].filter(audio => audio.srcObject).map(audio => audio.muted)"), value => value.length > 0 && value.every(Boolean));
assert.deepEqual((await view(1)).state.pairs.map(pair => pair.id).sort(), voicePairIds);
await action(1, `setDeafened(${JSON.stringify(room)}, false)`);
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 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;
// 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("last voice stops without closing base connections", () => view(3), value =>
!value.state.voice.some(member => member.roomId === room) && value.state.pairs.some(pair => pair.rooms.includes(room)));
for (const index of [0, 3]) await browser(index, "click", '.c3-room-link[aria-label="Living room"]');
await until("last room 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)));
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: ["room entry 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", "voice stop keeps base", "last lease 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) {
await action(0, `sendMessage(${JSON.stringify(serverRoom)}, 'Server room through its native peer')`);
await action(0, `loadLatestHistory(${JSON.stringify(serverRoom)})`);
const serverWS = (await sample(0)).conversationWS[serverRoom];
assert.equal(serverWS, undefined, "Server room conversation uses the same peer carrier as a Browser room");
await until("another reader receives the Server's peer confirmation", () => evaluate(2,
`${hook}.snapshot().messagesByRoom[${JSON.stringify(serverRoom)}]`), messages => messages?.some(message => message.text === "Server room through its native peer"));
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, `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.deepEqual(initialHostedWS, [null, null], "Browser room chat and history never traverse 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 { runtime, signer } = await session.conversation.identity;
if (value.sessionId === entry.delivery.hostSessionId) throw new Error('Expected ordinary participant');
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: crypto.randomUUID(),
record: { type: 'live_message', message: { id: crypto.randomUUID(), seq: 2,
userId: entry.creatorId, text: ${JSON.stringify(forgedText)}, time: Date.now(), attachments: [] } }
})));
await session.conversation.deliver(packet, runtime);
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;
})()`);
}
await action(2, `loadLatestHistory(${JSON.stringify(room)})`);
const page = await evaluate(2, `${hook}.snapshot().messagesByRoom[${JSON.stringify(room)}].map(message => message.text.length)`);
assert.deepEqual(page, Array(100).fill(2000), "a full valid history page arrives as individual signed DataChannel records and one end marker");
const hostedWS = await Promise.all([0, 1, 2].map(async index => (await sample(index)).conversationWS[room] ?? null));
assert.deepEqual(hostedWS, [null, null, null], "hosted chat and history stay off WebSocket throughout 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: { messages: 100, charactersPerMessage: 2000, transport: "signed DataChannel 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(initial, 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)})`);
const revokedScreen = await capturedScreen(1, roomId);
await action(0, `setRoles(${JSON.stringify(initial[1].self.id)}, [])`);
await until("role revocation releases the local screen", () => sample(1), value => value.captures.every(track => track.state === "ended"));
assert(!(await view(1)).streams.includes(revokedScreen));
await action(0, `setRoles(${JSON.stringify(initial[1].self.id)}, ['member'])`);
console.log("Authority role revocation retires local capture");
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 sameSession = (await view(1)).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 evaluate(1, "[...document.querySelectorAll('audio')].filter(audio => audio.srcObject && !audio.paused && !audio.muted).length") }), value =>
value.capture.captures.every(track => track.state === "ended") && value.audio === 0 &&
!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", "role revoke 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 openDomain = () => browser(0, "find", "role", "button", "click", "--name", "Domain appearance", "--exact");
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 openDomain(); 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 openDomain();
assert.equal(await evaluate(0, "!!document.querySelector('.c3-identity-upload img')"), false);
await upload(png); await preview();
await browser(0, "click", ".c3-identity-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("domain rail renders the saved image", () => evaluate(1,
"[...document.querySelectorAll('.c3-domain-icon img')].some(image => image.naturalWidth > 0)"), Boolean);
await browser(0, "find", "role", "button", "click", "--name", "Room settings", "--exact");
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 browser(0, "find", "role", "button", "click", "--name", "Room settings", "--exact");
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 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 browser(0, "find", "role", "button", "click", "--name", "Room settings", "--exact");
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 browser(0, "click", 'button[aria-controls="c3-room-settings"]');
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 browser(0, "click", 'button[aria-controls="c3-room-settings"]');
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 = () => browser(index, "find", "role", "button", "click", "--name", "Room settings", "--exact");
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('#c3-room-settings .c3-room-form').length"), 1);
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 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.querySelector('.c3-composer')"), 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 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");
await browser(1, "click", '.c3-room-link[aria-label="Movie night"]');
for (let start = 0; start < 1020; start += 40) {
await evaluate(1, `(async () => {
for (let index = ${start}; index < ${Math.min(start + 40, 1020)}; index++) await ${hook}.session.sendMessage(${JSON.stringify(room.id)}, 'history-' + index);
return true;
})()`);
}
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)}]?.length`), count => count === 100);
for (let page = 0; page < 10; page++) {
const anchor = page === 9 ? 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");
await until("older page advances the reading window", () => evaluate(0,
`${hook}.snapshot().messagesByRoom[${JSON.stringify(room.id)}]?.[0]?.seq`), seq => seq === Math.max(1, 922 - (page + 1) * 100));
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`), 1000);
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 browser(0, "find", "role", "button", "click", "--name", "Room settings", "--exact");
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 browser(0, "find", "role", "button", "click", "--name", "Room settings", "--exact");
await browser(0, "find", "role", "button", "click", "--name", "Create room invitation", "--exact");
const invite = await until("room invitation is ready", () => evaluate(0, "document.querySelector('.c3-invite-copy input')?.value"), value => !!value);
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, "reload");
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 browser(0, "press", "Escape");
await capturedScreen(1, room.id);
const member = (await view(1)).self.id;
await action(0, `revokeRoomAccess(${JSON.stringify(room.id)}, ${JSON.stringify(member)})`);
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, "set", "viewport", "390", "844");
await browser(0, "find", "role", "button", "click", "--name", "Room settings", "--exact");
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" : "invite"}=${encodeURIComponent(index === 0 ? ownerKey : inviteKey)}`);
}
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, `renameSelf(${JSON.stringify(String.fromCharCode(65 + index))})`);
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, 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(initial, 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 voicePairs = (await view(4)).state.pairs.map(pair => pair.id).sort();
await action(4, `setDeafened(${JSON.stringify(roomId)}, true)`);
await until("deafen mutes local voice sinks", () => evaluate(4,
"[...document.querySelectorAll('audio')].filter(audio => audio.srcObject).map(audio => audio.muted)"), values => values.length > 0 && values.every(Boolean));
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)`);
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)));
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;
const sourceBaseDegree = routed[2].state.pairs.filter(pair => pair.rooms.includes(roomId)).length;
assert(sourceCopies <= Math.max(2, sourceBaseDegree), `source fanout exceeded its existing base paths: ${sourceCopies}`);
if (relay !== secondPublisher) {
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 downstream = relayView.state.pairs.find(pair => pair.outgoing.some(flow => flow.publicationId === primaryPublication)).peerId;
const downstreamIndex = routed.findIndex(value => value.sessionId === downstream);
assert(downstreamIndex >= 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 progressing(downstreamIndex, primaryPublication);
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 browser(layoutIndex, "click", "#c3-people-trigger");
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-sidebar .c3-pane-back button");
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);
}