822 lines
60 KiB
JavaScript
822 lines
60 KiB
JavaScript
import assert from "node:assert/strict";
|
|
import { spawn } from "node:child_process";
|
|
import { once } from "node:events";
|
|
import { mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import { basename, join, relative, resolve } from "node:path";
|
|
import { DatabaseSync } from "node:sqlite";
|
|
import { createHash, randomUUID } from "node:crypto";
|
|
import { createServer } from "node:net";
|
|
import { tsImport } from "tsx/esm/api";
|
|
import { acceptanceServerExecutable } from "./acceptance-server-executable.mjs";
|
|
import { freeUdpPort } from "./acceptance-udp-port.mjs";
|
|
import { nativePreviews } from "./browser-preview-acceptance.mjs";
|
|
|
|
const { PRODUCT_VERSION } = await tsImport("../../src/client/channel/product-version.ts", import.meta.url);
|
|
|
|
// App hosting and Browser participation share a user, not an endpoint or lifetime.
|
|
export async function appRoom({ initial, serverRoom, browser, action, view, evaluate, until, sample,
|
|
capturedScreen, playing, progressing, audioProgressing, hook, output }) {
|
|
const directory = await mkdtemp(join(tmpdir(), "piik-app-room-check-"));
|
|
const origin = process.env.CHANNEL_UI_ORIGIN;
|
|
const freePort = async () => {
|
|
const probe = createServer();
|
|
await new Promise(resolve => probe.listen(0, "127.0.0.1", resolve));
|
|
const port = probe.address().port;
|
|
await new Promise(resolve => probe.close(resolve));
|
|
return port;
|
|
};
|
|
const port = await freePort();
|
|
const local = `http://127.0.0.1:${port}`;
|
|
const assets = resolve(process.env.PIIK_CHANNEL_APP_WEB_DIR ?? "build/channel-web");
|
|
const executable = resolve(process.env.CHANNEL_APP_EXECUTABLE ??
|
|
`prototype/channel-server/target/debug/piik-channel-app${process.platform === "win32" ? ".exe" : ""}`);
|
|
const url = `${origin}/?piik-client-port=${port}#piik-client=1`;
|
|
let app, otherServer, otherWeb, approvalTab, personalTab, log = "";
|
|
const sourceLayers = [];
|
|
const start = () => {
|
|
log = "";
|
|
app = spawn(executable, [], { env: { ...process.env,
|
|
PIIK_CHANNEL_APP_PORT: String(port), PIIK_CHANNEL_APP_DATA_DIR: directory,
|
|
PIIK_CHANNEL_APP_WEB_DIR: assets, PIIK_CHANNEL_APP_NO_BROWSER: "1",
|
|
}, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
|
|
const collect = chunk => { log = (log + chunk).slice(-64000); };
|
|
app.stdout.on("data", collect); app.stderr.on("data", collect);
|
|
app.on("error", error => collect(String(error)));
|
|
};
|
|
const ready = () => until("App local socket starts", () => {
|
|
if (app.exitCode !== null) throw new Error(log);
|
|
return log;
|
|
}, value => value.includes("App room socket listening"));
|
|
const stop = async () => {
|
|
if (app?.exitCode === null && app.signalCode === null) {
|
|
const exited = once(app, "exit"); app.kill(); await exited;
|
|
}
|
|
};
|
|
const health = site => fetch(`${local}/health`, { headers: { Origin: site } });
|
|
const appReady = index => until("Browser verifies its current App connection", () => evaluate(index, `${hook}?.snapshot().appConnected ?? false`), Boolean);
|
|
const approve = async site => {
|
|
const destination = `${local}/client?site=${encodeURIComponent(site)}`;
|
|
if (!approvalTab) {
|
|
personalTab = (await browser(1, "tab")).tabs.find(tab => tab.active).targetId;
|
|
approvalTab = (await browser(1, "tab", "new", destination)).targetId;
|
|
} else {
|
|
await browser(1, "tab", approvalTab);
|
|
await browser(1, "open", destination);
|
|
}
|
|
await browser(1, "wait", "#site-approval-title");
|
|
await evaluate(1, "localStorage.setItem('piik:ui-lang', 'en')");
|
|
await browser(1, "reload");
|
|
if (site === origin) {
|
|
const viewport = await evaluate(1, "({ width: innerWidth, height: innerHeight })");
|
|
await browser(1, "screenshot", join(output, "app-approval-desktop.png"));
|
|
await browser(1, "set", "viewport", "390", "844");
|
|
await browser(1, "screenshot", join(output, "app-approval-mobile.png"));
|
|
await browser(1, "set", "viewport", String(viewport.width), String(viewport.height));
|
|
}
|
|
await browser(1, "wait", ".lr-client-approval-actions button.is-primary");
|
|
await browser(1, "click", ".lr-client-approval-actions button.is-primary");
|
|
await until("real approval page grants the exact Site", async () => (await health(site)).status, value => value === 200);
|
|
await browser(1, "tab", personalTab);
|
|
};
|
|
try {
|
|
const browserRoom = await action(1, "createRoom({name:'Browser-owned room',icon:'couch',access:'public',hidden:false})");
|
|
start(); await ready();
|
|
const discovery = await fetch(`${local}/connect-discovery`).then(response => response.json());
|
|
assert.deepEqual(discovery, { service: "piik-channel-app", ...PRODUCT_VERSION, port, windowNavigation: false, connectURL: `${local}/client` });
|
|
assert.equal((await health(origin)).status, 403, "discovery does not approve its caller");
|
|
await approve(origin);
|
|
const token = (await (await health(origin)).json()).token;
|
|
const participants = await evaluate(0, `${hook}.snapshot().state.sessions.filter(session => session.online).length`);
|
|
await browser(1, "open", url);
|
|
await browser(1, "reload");
|
|
await until("linked Browser restores its admitted identity", () => view(1), value => value.connection === "connected"
|
|
&& value.self.id === initial[1].self.id);
|
|
await appReady(1);
|
|
const room = await action(1, process.argv.includes("--previews")
|
|
? "createRoom({name:'Preview room',icon:'couch',access:'public',hidden:false})"
|
|
: "createRoom({name:'App-owned room',icon:'couch',access:'private',hidden:true,password:'app-room-password'})");
|
|
await action(1, `browse(${JSON.stringify(room)})`);
|
|
if (process.argv.includes("--previews")) {
|
|
await nativePreviews({ room, browser, action, view, evaluate, until, playing, progressing, hook, output, directory });
|
|
return;
|
|
}
|
|
const invite = await action(1, `createRoomInvite(${JSON.stringify(room)})`);
|
|
assert(!invite.includes(token), "room invitations never carry the local App token");
|
|
await browser(2, "open", invite);
|
|
await until("invited reader enters App-owned room", () => view(2), value => value.connection === "connected"
|
|
&& value.state.channel.rooms.some(entry => entry.id === room && entry.authorized));
|
|
await action(2, `sendMessage(${JSON.stringify(room)}, 'Saved by the linked Rust App')`);
|
|
await until("App room confirmation reaches its owner", () => evaluate(1,
|
|
`${hook}.snapshot().messagesByRoom[${JSON.stringify(room)}]`), messages => messages?.some(message => message.text === "Saved by the linked Rust App"));
|
|
const hosted = (await view(1)).state.channel.rooms.find(entry => entry.id === room);
|
|
const nativeEndpoint = hosted.delivery.hostSessionId;
|
|
assert.notEqual(nativeEndpoint, (await view(1)).sessionId, "App hosting uses its own endpoint");
|
|
assert.equal(await evaluate(1, `${hook}.snapshot().state.sessions.find(session => session.id === ${JSON.stringify(nativeEndpoint)}).userId`), initial[1].self.id);
|
|
assert.equal(await evaluate(1, `${hook}.snapshot().state.sessions.filter(session => session.online).length`), participants + 1,
|
|
"one Native endpoint hosts the App rooms");
|
|
assert.equal((await view(1)).state.channel.rooms.find(entry => entry.id === browserRoom).delivery.hostSessionId,
|
|
(await view(1)).sessionId, "connecting App does not migrate an existing Browser room");
|
|
const nextRoom = await action(1, "createRoom({name:'Another App room',icon:'couch',access:'public',hidden:false})");
|
|
await until("both rooms use the same Native operator", () => view(1), value =>
|
|
value.state.channel.rooms.find(entry => entry.id === nextRoom)?.delivery?.hostSessionId === nativeEndpoint);
|
|
const beforeSwitch = await view(2);
|
|
assert.equal(beforeSwitch.state.pairs.length, 0, "reading and confirmed conversation require no peer connection");
|
|
const peerCount = await evaluate(2, "window.__channelProbe.peers.length");
|
|
for (const destination of [nextRoom, room]) {
|
|
await action(2, `browse(${JSON.stringify(destination)})`);
|
|
await until("new reading commits before the former room leaves", () => view(2), value =>
|
|
value.state.channel.rooms.some(entry => entry.id === destination && entry.reading) &&
|
|
!value.state.channel.rooms.some(entry => entry.id !== destination && entry.reading));
|
|
assert.equal((await view(2)).state.pairs.length, 0,
|
|
"switching chat-only rooms keeps conversation on domain WebSocket carriage");
|
|
assert.equal(await evaluate(2, "window.__channelProbe.peers.length"), peerCount,
|
|
"a chat-only room switch must not create another PeerConnection");
|
|
if (destination === nextRoom) {
|
|
await action(2, `sendMessage(${JSON.stringify(nextRoom)}, 'Same connection, another room')`);
|
|
await action(1, `browse(${JSON.stringify(nextRoom)})`);
|
|
await until("the new room receives its own confirmed message", () => evaluate(1,
|
|
`${hook}.snapshot().messagesByRoom[${JSON.stringify(nextRoom)}]`), messages =>
|
|
messages?.some(message => message.text === "Same connection, another room"));
|
|
assert(!(await evaluate(2, `${hook}.snapshot().messagesByRoom[${JSON.stringify(nextRoom)}]`))
|
|
.some(message => message.text === "Saved by the linked Rust App"), "room histories stay separate");
|
|
}
|
|
}
|
|
await action(1, `browse(${JSON.stringify(room)})`);
|
|
const [siteData] = await readdir(join(directory, "rooms"));
|
|
const storedPath = join(directory, "rooms", siteData, initial[1].state.channel.id, initial[1].self.id, `${room}.sqlite`);
|
|
const stored = new DatabaseSync(storedPath, { readOnly: true });
|
|
const domain = new DatabaseSync(process.env.CHANNEL_DATA_FILE, { readOnly: true });
|
|
try {
|
|
assert.equal(stored.prepare("SELECT count(*) AS count FROM message WHERE room_id=?").get(room).count, 1);
|
|
assert.equal(domain.prepare("SELECT count(*) AS count FROM sqlite_schema WHERE type='table' AND name='message'").get().count, 0);
|
|
} finally { stored.close(); domain.close(); }
|
|
assert.equal(await evaluate(1, `(async () => {
|
|
for (const database of await indexedDB.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'); const request = tx.objectStore('rooms').get(${JSON.stringify(room)});
|
|
await new Promise((resolve, reject) => { tx.oncomplete = resolve; tx.onabort = () => reject(tx.error); });
|
|
if (request.result) return true;
|
|
} finally { db.close(); }
|
|
}
|
|
return false;
|
|
})()`), false,
|
|
"App room has no second Browser storage writer");
|
|
const first = (await view(1)).state.channel.rooms.find(entry => entry.id === room).delivery.bindingId;
|
|
const personalEndpoint = (await view(1)).sessionId;
|
|
await action(1, `joinVoice(${JSON.stringify(room)})`);
|
|
await action(2, `joinVoice(${JSON.stringify(room)})`);
|
|
await until("linked room voice uses Browser media", () => sample(2), value => value.inbound.some(row => row.kind === "audio" && row.samples > 0));
|
|
const picture = await capturedScreen(1, room);
|
|
await action(2, `watch(${JSON.stringify(picture)})`); await playing(2, picture);
|
|
const unrelated = await capturedScreen(0, serverRoom);
|
|
await action(2, `watch(${JSON.stringify(unrelated)})`); await playing(2, unrelated);
|
|
await browser(1, "network", "route", local + "/health*", "--abort");
|
|
await evaluate(1, "window.__channelProbe.sockets.filter(socket => new URL(socket.url).pathname === '/rooms').forEach(socket => socket.close())");
|
|
await until("local control disconnect is visible", () => evaluate(1, `${hook}.snapshot().appConnected`), value => value === false);
|
|
await progressing(2, picture);
|
|
|
|
// The Browser host remains the room owner while its App assists reception.
|
|
await action(1, `browse(${JSON.stringify(browserRoom)})`);
|
|
for (const index of [0, 2, 3]) {
|
|
await action(index, `browse(${JSON.stringify(browserRoom)})`);
|
|
// This helper scenario needs two root branches before adding its filler.
|
|
// Admit those listeners as leaves, then restore normal forwarding.
|
|
if (index !== 3) await action(index, `setForwardingLimit(0)`);
|
|
else for (const child of [0, 2]) await action(child, `setForwardingLimit(-1)`);
|
|
// Conversation alone has no peer demand. Listening creates the ordinary
|
|
// base this media-routing scenario needs without another microphone.
|
|
await action(index, `joinVoice(${JSON.stringify(browserRoom)}, true)`);
|
|
await until("Browser host installs its ordinary room base", () => view(index), value =>
|
|
value.state.pairs.some(pair => (index === 3 || pair.peerId === personalEndpoint) && pair.rooms.includes(browserRoom)));
|
|
await until("ordinary room base opens before the next admission", () => sample(index), value =>
|
|
value.channels.some(channel => channel.label === "piik-room" && channel.state === "open"));
|
|
}
|
|
await action(3, `setForwardingLimit(0)`);
|
|
const fillerBase = (await view(3)).state.pairs.filter(pair => pair.rooms.includes(browserRoom));
|
|
assert.equal(fillerBase.length, 1, "fourth Browser has one ordinary base parent");
|
|
const sourceIndex = [0, 2].find(index => initial[index].sessionId === fillerBase[0].peerId);
|
|
assert.notEqual(sourceIndex, undefined, "fourth Browser is attached below one original base child");
|
|
const downstreamIndex = sourceIndex === 0 ? 2 : 0;
|
|
const viewers = [1, downstreamIndex];
|
|
await writeFile(join(output, "app-helper-roles.json"), JSON.stringify({ sourceIndex, assistedIndex: 1, downstreamIndex, fillerIndex: 3 }, null, 2));
|
|
const browserBindingBeforeHelper = (await view(1)).state.channel.rooms.find(entry => entry.id === browserRoom).delivery.bindingId;
|
|
const concurrentPicture = sourceIndex === 0 ? unrelated : await capturedScreen(sourceIndex, serverRoom);
|
|
const concurrentViewer = sourceIndex === 0 ? 2 : 0;
|
|
if (sourceIndex !== 0) await action(concurrentViewer, `watch(${JSON.stringify(concurrentPicture)})`);
|
|
const concurrentObservations = [];
|
|
const observeConcurrent = async phase => {
|
|
const pages = await Promise.allSettled([0, 1, 2, 3].map(index => evaluate(index, `(async () => ({ index: ${index},
|
|
screen: window.__channelProbe.screen(${JSON.stringify(concurrentPicture)}),
|
|
stats: await window.__channelProbe.sourceStats(${JSON.stringify(concurrentPicture)}) }))()`)));
|
|
concurrentObservations.push({ phase, time: Date.now(), sourceIndex, viewerIndex: concurrentViewer,
|
|
publicationId: concurrentPicture, roomId: serverRoom,
|
|
pages: pages.map((result, index) => result.status === 'fulfilled' ? result.value : { index, error: String(result.reason) }) });
|
|
await writeFile(join(output, "app-helper-concurrent-observations.json"), JSON.stringify(concurrentObservations, null, 2));
|
|
};
|
|
await observeConcurrent("watch-start");
|
|
let concurrentBefore;
|
|
try { concurrentBefore = await progressing(concurrentViewer, concurrentPicture); }
|
|
finally { await observeConcurrent(concurrentBefore ? "playing" : "failed-before-helper"); }
|
|
await action(sourceIndex, "setVideoCodecMode('h264')");
|
|
await evaluate(sourceIndex, "window.__channelProbe.captureAudio(true)");
|
|
await evaluate(sourceIndex, "window.__channelProbe.captureFramerate(30)");
|
|
const helperPicture = await capturedScreen(sourceIndex, browserRoom);
|
|
const globalSources = await Promise.all([0, 1, 2, 3].map(index => evaluate(index, `(() => {
|
|
const value = ${hook}.snapshot(); return { index: ${index}, sessionId: value.sessionId,
|
|
quality: value.quality, codecMode: value.videoCodecMode,
|
|
localScreens: value.state.publications.filter(publication => publication.sessionId === value.sessionId && publication.kind === 'screen').map(({ id, roomId }) => ({ id, roomId })),
|
|
liveVideoCaptures: window.__channelProbe.captures.flatMap(stream => stream.getVideoTracks()).filter(track => track.readyState === 'live').length };
|
|
})()`)));
|
|
const sourceLoad = globalSources[sourceIndex];
|
|
assert.equal(sourceLoad.sessionId, initial[sourceIndex].sessionId);
|
|
assert(sourceLoad.liveVideoCaptures >= 2 && [concurrentPicture, helperPicture].every(id => sourceLoad.localScreens.some(screen => screen.id === id)),
|
|
"the actual helper source retains two live local captures");
|
|
assert.deepEqual(sourceLoad.quality.resolution, { width: 1920, height: 1080 });
|
|
assert.equal(sourceLoad.quality.maxFramerate, 30); assert.equal(sourceLoad.quality.maxBitrate, 5_000_000);
|
|
const concurrentAfter = await progressing(concurrentViewer, concurrentPicture);
|
|
await writeFile(join(output, "app-helper-source-load.json"), JSON.stringify({ sourceIndex,
|
|
quality: sourceLoad.quality, codecMode: sourceLoad.codecMode,
|
|
existingLocalScreens: sourceLoad.localScreens.filter(screen => screen.id !== helperPicture), globalSources,
|
|
concurrent: { publicationId: concurrentPicture, viewerIndex: concurrentViewer,
|
|
createdForRole: sourceIndex !== 0, reason: sourceIndex === 0 ? "retained original living source" : "same living load for the selected source role",
|
|
before: concurrentBefore, after: concurrentAfter } }, null, 2));
|
|
await browser(sourceIndex, "screenshot", join(output, "app-helper-actual-source.png"));
|
|
await browser(concurrentViewer, "screenshot", join(output, "app-helper-concurrent-viewer.png"));
|
|
const carries = (pair, direction) => pair[direction].some(flow => flow.publicationId === helperPicture && flow.selected);
|
|
for (const index of [1, 3, downstreamIndex]) {
|
|
await action(index, `watch(${JSON.stringify(helperPicture)})`); await playing(index, helperPicture);
|
|
if (index === 3) await until("fourth viewer occupies the source's second branch before D watches", () => view(sourceIndex), value =>
|
|
value.state.pairs.some(pair => pair.peerId === initial[3].sessionId && carries(pair, "outgoing")), 35_000);
|
|
}
|
|
const beforeHelper = await view(1);
|
|
assert(beforeHelper.state.pairs.some(pair => pair.peerId === initial[sourceIndex].sessionId && carries(pair, "incoming")),
|
|
"ordinary Browser receives the remote source before App assistance");
|
|
assert(beforeHelper.state.pairs.some(pair => pair.peerId === initial[downstreamIndex].sessionId && carries(pair, "outgoing")),
|
|
"App assistance starts with a real Browser downstream, not two direct viewers");
|
|
assert((await view(sourceIndex)).state.pairs.some(pair => pair.peerId === initial[3].sessionId && carries(pair, "outgoing")),
|
|
"a real fourth viewer occupies the source's other branch");
|
|
const codecs = index => evaluate(index, `(async () => {
|
|
const stream = ${hook}.snapshot().streams.get(${JSON.stringify(helperPicture)});
|
|
if (!stream) return [];
|
|
const rows = [];
|
|
for (const track of stream.getTracks()) {
|
|
const pc = window.__channelProbe.peers.find(pc => pc.connectionState === 'connected'
|
|
&& pc.getReceivers().some(receiver => receiver.track === track));
|
|
if (!pc) continue;
|
|
const stats = await pc.getStats();
|
|
for (const report of stats.values()) if (report.type === 'inbound-rtp' && report.trackIdentifier === track.id) rows.push({
|
|
direction: 'received', kind: report.kind, codec: stats.get(report.codecId)?.mimeType,
|
|
frames: report.framesDecoded ?? 0, samples: report.totalSamplesReceived ?? 0 });
|
|
for (const output of window.__channelProbe.peers.filter(pc => pc.connectionState === 'connected')) {
|
|
for (const sender of output.getSenders().filter(sender => sender.track === track)) {
|
|
const all = await output.getStats();
|
|
for (const report of (await sender.getStats()).values()) if (report.type === 'outbound-rtp') rows.push({
|
|
direction: 'sent', kind: report.kind, codec: all.get(report.codecId)?.mimeType,
|
|
frames: report.framesEncoded ?? 0, bytes: report.bytesSent ?? 0 });
|
|
}
|
|
}
|
|
}
|
|
return rows;
|
|
})()`);
|
|
const mediaBefore = await Promise.all(viewers.map(codecs));
|
|
await writeFile(join(output, "app-helper-media-before.json"), JSON.stringify(mediaBefore, null, 2));
|
|
assert(mediaBefore[0].some(row => row.direction === "received" && row.codec?.toLowerCase() === "video/h264" && row.frames > 0),
|
|
"Source sends actual H264 into the ordinary Browser relay");
|
|
for (const rows of mediaBefore) {
|
|
assert(rows.some(row => row.direction === "received" && row.kind === "video" && row.frames > 0));
|
|
assert(rows.some(row => row.direction === "received" && row.codec?.toLowerCase() === "audio/opus" && row.samples > 0));
|
|
}
|
|
for (const index of [0, 1, 2, 3]) await evaluate(index, "window.__channelProbe.clearProtocol()");
|
|
for (const index of viewers) await evaluate(index, "window.__channelProbe.observeQuality()");
|
|
await browser(1, "network", "unroute", local + "/health*");
|
|
await action(1, "activateApp()"); await appReady(1);
|
|
const lastQualityTimes = new Map();
|
|
await until("Native assists both viewers without Browser WAN forwarding", async () => {
|
|
const [source, assisted, downstream] = await Promise.all([sourceIndex, ...viewers].map(view));
|
|
const qualitySamples = [];
|
|
for (const index of viewers) {
|
|
const screen = await evaluate(index, `window.__channelProbe.screen(${JSON.stringify(helperPicture)})`);
|
|
for (const sample of screen.qualitySamples.filter(sample => sample.time > (lastQualityTimes.get(index) ?? 0))) {
|
|
qualitySamples.push({ index, ...sample });
|
|
lastQualityTimes.set(index, sample.time);
|
|
}
|
|
assert(screen.inputs.some(input => input.selected && input.frames > 0), "handover retains a decoded selected picture");
|
|
}
|
|
if (qualitySamples.length) sourceLayers.push({ qualitySamples,
|
|
...await evaluate(sourceIndex, `window.__channelProbe.sourceStats(${JSON.stringify(helperPicture)})`) });
|
|
return { source, assisted, downstream };
|
|
}, ({ source, assisted, downstream }) => source.state.pairs.some(pair => pair.peerId === nativeEndpoint && carries(pair, "outgoing"))
|
|
&& [assisted, downstream].every(value => value.state.pairs.some(pair => pair.peerId === nativeEndpoint && carries(pair, "incoming")))
|
|
&& !assisted.state.pairs.some(pair => carries(pair, "outgoing")), 35_000);
|
|
const helperProofs = await Promise.all(viewers.map(async index => ({ index,
|
|
...await evaluate(index, `window.__channelProbe.sample().then(({ protocol, qualitySamples }) => ({ protocol, qualitySamples }))`) })));
|
|
await writeFile(join(output, "app-helper-proofs.json"), JSON.stringify(helperProofs, null, 2));
|
|
for (const index of viewers) { await progressing(index, helperPicture); await audioProgressing(index, helperPicture); }
|
|
const mediaAfter = await Promise.all(viewers.map(codecs));
|
|
await writeFile(join(output, "app-helper-media-after.json"), JSON.stringify(mediaAfter, null, 2));
|
|
for (const rows of mediaAfter) {
|
|
assert(rows.some(row => row.codec?.toLowerCase() === "video/h264" && row.frames > 0));
|
|
assert(rows.some(row => row.codec?.toLowerCase() === "audio/opus" && row.samples > 0));
|
|
}
|
|
const viewerSessions = (await Promise.all(viewers.map(view))).map(value => value.sessionId);
|
|
const helperMetrics = () => evaluate(1,
|
|
`${hook}.session.appConnectionMetrics(${JSON.stringify(browserRoom)}, ${JSON.stringify(helperPicture)})`);
|
|
const measuredOutputs = report => report.connections.flatMap(connection => connection.streams
|
|
.filter(stream => stream.publicationId === helperPicture && stream.direction === "send" && stream.selected && stream.bytes > 0)
|
|
.map(stream => ({ peerId: connection.peerId, ...stream })));
|
|
const readyMetrics = () => until("Native metrics validate actual ingress and both viewer outputs", helperMetrics, report => {
|
|
assert.equal(report.sessionId, nativeEndpoint);
|
|
for (const connection of report.connections) for (const stream of connection.streams) {
|
|
if (stream.direction === "receive") assert.equal(stream.outputId, null);
|
|
else assert.equal(typeof stream.outputId, "string", "each Native sender identifies its current Output owner");
|
|
}
|
|
return report.connections.some(connection => connection.streams.some(stream =>
|
|
stream.publicationId === helperPicture && stream.direction === "receive" && stream.media === "video" && stream.bytes > 0))
|
|
&& viewerSessions.every(peerId => ["video", "audio"].every(media => measuredOutputs(report)
|
|
.some(stream => stream.peerId === peerId && stream.media === media && stream.packets > 0)));
|
|
});
|
|
const metricsBefore = await readyMetrics();
|
|
await writeFile(join(output, "app-helper-metrics-result.json"), JSON.stringify({ metricsBefore }, null, 2));
|
|
const profileBefore = await evaluate(sourceIndex, `${hook}.session.screenQuality(${JSON.stringify(helperPicture)}).applied`);
|
|
const profileAfter = { ...profileBefore, degradationPreference: "maintain-framerate" };
|
|
await evaluate(sourceIndex, `(async () => {
|
|
await ${hook}.session.setScreenQuality(${JSON.stringify(helperPicture)}, ${JSON.stringify(profileAfter)});
|
|
return true;
|
|
})()`);
|
|
const preferenceViews = await until("source preference reaches both Native-assisted viewers", async () =>
|
|
Promise.all([sourceIndex, ...viewers].map(view)), values => values.every(value =>
|
|
value.state.publications.find(publication => publication.id === helperPicture)?.videoSettings?.degradationPreference === "maintain-framerate"));
|
|
for (const index of viewers) { await progressing(index, helperPicture); await audioProgressing(index, helperPicture); }
|
|
await progressing(concurrentViewer, concurrentPicture);
|
|
assert(preferenceViews.slice(1).every(value => value.state.pairs.some(pair => pair.peerId === nativeEndpoint && carries(pair, "incoming"))),
|
|
"preference-only edit retains the actual Native helper path");
|
|
await writeFile(join(output, "app-helper-preference-result.json"), JSON.stringify({ passed: true,
|
|
publicationId: helperPicture, profileBefore, profileAfter, nativeEndpoint,
|
|
viewers: viewers.map((index, position) => ({ index, settings: preferenceViews[position + 1].state.publications.find(publication => publication.id === helperPicture).videoSettings })),
|
|
siblingPublication: concurrentPicture, decodedPictureAndAudioContinued: true }, null, 2));
|
|
await action(1, `unwatch(${JSON.stringify(helperPicture)})`);
|
|
await progressing(downstreamIndex, helperPicture); await audioProgressing(downstreamIndex, helperPicture);
|
|
assert((await view(downstreamIndex)).state.pairs.some(pair => pair.peerId === nativeEndpoint && carries(pair, "incoming")),
|
|
"Native transit survives the assisted Browser's unwatch");
|
|
const transitBefore = measuredOutputs(metricsBefore).filter(stream => stream.peerId === viewerSessions[1]);
|
|
const metricsUnwatched = await until("unwatch retires only its own Native outputs", helperMetrics, report =>
|
|
!measuredOutputs(report).some(stream => stream.peerId === viewerSessions[0])
|
|
&& transitBefore.every(before => measuredOutputs(report).some(after =>
|
|
after.peerId === before.peerId && after.media === before.media
|
|
&& after.flowId === before.flowId && after.outputId === before.outputId
|
|
&& after.bytes >= before.bytes && after.packets >= before.packets)));
|
|
await writeFile(join(output, "app-helper-metrics-result.json"), JSON.stringify({ metricsBefore, metricsUnwatched }, null, 2));
|
|
await action(1, `watch(${JSON.stringify(helperPicture)})`);
|
|
await until("assisted watching returns through the same Native endpoint", () => view(1), value =>
|
|
value.state.pairs.some(pair => pair.peerId === nativeEndpoint && carries(pair, "incoming")));
|
|
const metricsAfter = await readyMetrics();
|
|
await writeFile(join(output, "app-helper-metrics-result.json"), JSON.stringify({ metricsBefore, metricsUnwatched, metricsAfter }, null, 2));
|
|
const currentViewers = await Promise.all(viewers.map(view));
|
|
for (const [position, peerId] of viewerSessions.entries()) {
|
|
const currentFlows = currentViewers[position].state.pairs.filter(pair => pair.peerId === nativeEndpoint)
|
|
.flatMap(pair => pair.incoming.filter(flow => flow.publicationId === helperPicture && flow.selected).map(flow => flow.id));
|
|
for (const before of measuredOutputs(metricsBefore).filter(stream => stream.peerId === peerId)) {
|
|
const after = measuredOutputs(metricsAfter).find(stream => stream.peerId === peerId && stream.media === before.media);
|
|
assert(after && currentFlows.includes(after.flowId), "Native metrics name the viewer's current selected flow");
|
|
if (position === 0) assert.notEqual(after.flowId, before.flowId, "rewatching receives a new flow");
|
|
if (after.flowId === before.flowId) {
|
|
assert.equal(after.outputId, before.outputId, "the retained flow preserves its Output counter owner");
|
|
} else {
|
|
assert.notEqual(after.outputId, before.outputId, "a replacement flow has a fresh Output counter owner");
|
|
assert(!measuredOutputs(metricsAfter).some(stream => stream.outputId === before.outputId),
|
|
"metrics do not retain the retired flow's Output counter owner");
|
|
}
|
|
}
|
|
}
|
|
await writeFile(join(output, "app-helper-metrics-result.json"), JSON.stringify({ passed: true, metricsBefore, metricsUnwatched, metricsAfter }, null, 2));
|
|
await browser(1, "network", "route", local + "/health*", "--abort");
|
|
await evaluate(1, "window.__channelProbe.sockets.filter(socket => new URL(socket.url).pathname === '/rooms').forEach(socket => socket.close())");
|
|
await browser(1, "tab", personalTab);
|
|
await until("helper control disconnect is visible", () => evaluate(1, `${hook}.snapshot().appConnected`), value => value === false);
|
|
assert((await view(1)).state.subscriptions.includes(helperPicture), "control loss retains the existing watch intent");
|
|
await progressing(1, helperPicture); await audioProgressing(1, helperPicture);
|
|
const browserHostAfterHelper = (await view(1)).state.channel.rooms.find(entry => entry.id === browserRoom);
|
|
assert.equal(browserHostAfterHelper.delivery.hostSessionId, personalEndpoint);
|
|
assert.equal(browserHostAfterHelper.delivery.bindingId, browserBindingBeforeHelper);
|
|
await writeFile(join(output, "app-helper-result.json"), JSON.stringify({ passed: true, mediaBefore, mediaAfter,
|
|
scenarios: ["Browser-owned base Source to A to D", "H264 and Opus through live Native helper",
|
|
"Native replaces Browser WAN forwarding", "unwatch retains downstream transit", "control loss preserves ordinary watching and hosting"] }, null, 2));
|
|
await action(sourceIndex, `stopScreen(${JSON.stringify(helperPicture)})`);
|
|
await evaluate(sourceIndex, "window.__channelProbe.captureAudio(false)");
|
|
if (sourceIndex !== 0) await action(sourceIndex, `stopScreen(${JSON.stringify(concurrentPicture)})`);
|
|
await action(1, "close()");
|
|
await browser(1, "open", "about:blank");
|
|
await browser(1, "network", "unroute", local + "/health*");
|
|
await until("page close ends personal activity and Browser hosting only", () => view(2), value =>
|
|
value.state.channel.rooms.some(entry => entry.id === room && entry.available && entry.delivery.hostSessionId === nativeEndpoint)
|
|
&& value.state.channel.rooms.some(entry => entry.id === browserRoom && !entry.available)
|
|
&& !value.state.publications.some(publication => publication.id === picture));
|
|
await action(2, `sendMessage(${JSON.stringify(room)}, 'Still here after the owner closes the page')`);
|
|
await until("App confirms chat without its owner's page", () => evaluate(2,
|
|
`${hook}.snapshot().messagesByRoom[${JSON.stringify(room)}]`), messages => messages?.some(message => message.text === "Still here after the owner closes the page"));
|
|
await progressing(2, unrelated);
|
|
await browser(1, "open", url);
|
|
await until("owner returns to the same Native hosting endpoint", () => view(1), value => value.connection === "connected"
|
|
&& value.state.channel.rooms.some(entry => entry.id === room && entry.available && entry.delivery.bindingId === first)
|
|
&& value.state.channel.rooms.some(entry => entry.id === browserRoom && entry.available && entry.delivery.hostSessionId === value.sessionId));
|
|
await appReady(1);
|
|
assert(!(await view(1)).state.voice.some(member => member.sessionId === personalEndpoint || member.sessionId === nativeEndpoint),
|
|
"personal voice stops with its page and never becomes a hosting activity");
|
|
await action(1, `browse(${JSON.stringify(room)})`);
|
|
await until("returning owner's history includes the conversation during absence", () => evaluate(1,
|
|
`${hook}.snapshot().messagesByRoom[${JSON.stringify(room)}]`), messages =>
|
|
messages?.some(message => message.text === "Still here after the owner closes the page"));
|
|
const endpoint = (await view(1)).sessionId;
|
|
const browserBinding = (await view(1)).state.channel.rooms.find(entry => entry.id === browserRoom).delivery.bindingId;
|
|
const domainSockets = await evaluate(1, `(() => {
|
|
const sockets = window.__channelProbe.sockets.filter(socket => new URL(socket.url).pathname === '/prototype/channel');
|
|
window.__appRestartWelcomes = 0;
|
|
for (const socket of sockets) socket.addEventListener('message', event => {
|
|
if (JSON.parse(event.data).type === 'welcome') window.__appRestartWelcomes++;
|
|
});
|
|
return { count: sockets.length, open: sockets.filter(socket => socket.readyState === WebSocket.OPEN).length };
|
|
})()`);
|
|
await stop();
|
|
await until("App loss pauses only its room", () => view(2), value =>
|
|
value.state.channel.rooms.some(entry => entry.id === room && !entry.available)
|
|
&& !value.state.publications.some(publication => publication.roomId === room), 30_000);
|
|
assert.equal((await view(1)).sessionId, endpoint, "local App loss retains the Browser endpoint");
|
|
assert((await view(1)).state.channel.rooms.some(entry => entry.id === browserRoom && entry.available),
|
|
"App shutdown preserves Browser hosting");
|
|
await progressing(2, unrelated);
|
|
start(); await ready();
|
|
assert.equal((await health(origin)).status, 200, "approved Site survives App restart");
|
|
// A failed automatic probe leaves the App button available for an explicit retry.
|
|
await browser(1, "click", ".lr-app-connect");
|
|
await appReady(1);
|
|
assert.equal((await view(1)).sessionId, endpoint, "App re-entry retains the Browser endpoint");
|
|
assert.equal((await view(1)).state.channel.rooms.find(entry => entry.id === browserRoom).delivery.bindingId,
|
|
browserBinding, "App re-entry retains the Browser room binding");
|
|
assert.deepEqual(await evaluate(1, `(() => {
|
|
const sockets = window.__channelProbe.sockets.filter(socket => new URL(socket.url).pathname === '/prototype/channel');
|
|
return { count: sockets.length, open: sockets.filter(socket => socket.readyState === WebSocket.OPEN).length };
|
|
})()`), domainSockets, "App re-entry preserves the open Domain socket without reconnecting");
|
|
assert.equal(await evaluate(1, "window.__appRestartWelcomes"), 0, "App re-entry receives no new Domain Welcome");
|
|
await until("App reconnect restores data with a fresh binding", () => view(1), value => value.state?.channel.rooms.some(entry =>
|
|
entry.id === room && entry.available && entry.delivery.bindingId !== first));
|
|
await action(1, `browse(${JSON.stringify(room)})`);
|
|
await until("App restart restores saved history", () => evaluate(1,
|
|
`${hook}.snapshot().messagesByRoom[${JSON.stringify(room)}]`), messages =>
|
|
messages?.some(message => message.text === "Saved by the linked Rust App"));
|
|
assert(!(await view(1)).state.voice.some(member => member.roomId === room));
|
|
assert(!(await view(1)).state.publications.some(publication => publication.roomId === room));
|
|
await progressing(2, unrelated);
|
|
const restoredBinding = (await view(1)).state.channel.rooms.find(entry => entry.id === room).delivery.bindingId;
|
|
|
|
// A second ordinary domain exercises approval isolation with its own real
|
|
// identity, room runtime and peer confirmation, not another claimed UUID.
|
|
const otherPort = await freePort(), otherCorePort = await freePort();
|
|
const otherOrigin = `http://127.0.0.1:${otherPort}`;
|
|
const otherOwner = randomUUID();
|
|
otherServer = spawn(await acceptanceServerExecutable(directory), [], {
|
|
env: { ...process.env, PIIK_CHANNEL_PORT: String(otherCorePort), PIIK_CHANNEL_UDP_PORT: String(await freeUdpPort()),
|
|
PIIK_CHANNEL_WEB_ORIGIN: otherOrigin,
|
|
PIIK_CHANNEL_WEB_DIR: assets, PIIK_CHANNEL_DATA_DIR: join(directory, "other-domain"),
|
|
PIIK_CHANNEL_OWNER_KEY: otherOwner },
|
|
windowsHide: true, stdio: ["ignore", "pipe", "pipe"],
|
|
});
|
|
const collectOther = chunk => { log = (log + String(chunk).replaceAll(otherOwner, "[other owner key]")).slice(-64000); };
|
|
otherServer.stdout.on("data", collectOther); otherServer.stderr.on("data", collectOther);
|
|
otherServer.on("error", error => collectOther(String(error)));
|
|
otherWeb = spawn(process.execPath, ["node_modules/vite/bin/vite.js", "--config", "prototype/channel-server/vite.config.ts"], {
|
|
env: { ...process.env, PIIK_CHANNEL_PORT: String(otherCorePort), PIIK_CHANNEL_UI_PORT: String(otherPort),
|
|
PIIK_CHANNEL_VITE_CACHE_DIR: join(directory, "other-vite-cache") },
|
|
windowsHide: true, stdio: ["ignore", "pipe", "pipe"],
|
|
});
|
|
otherWeb.stdout.on("data", collectOther); otherWeb.stderr.on("data", collectOther);
|
|
otherWeb.on("error", error => collectOther(String(error)));
|
|
await until("second ordinary Domain starts", () => fetch(`http://127.0.0.1:${otherCorePort}/healthz`).then(response => response.ok).catch(() => false), Boolean);
|
|
await until("second Site's normal frontend starts", () => fetch(otherOrigin).then(response => response.ok).catch(() => false), Boolean);
|
|
assert.equal((await health(otherOrigin)).status, 403, "one approved Site grants no authority to another");
|
|
await approve(otherOrigin);
|
|
const firstDomainTab = (await browser(0, "tab")).tabs.find(tab => tab.active).targetId;
|
|
await browser(0, "tab", "new",
|
|
`${otherOrigin}/?piik-client-port=${port}#owner=${otherOwner}&piik-client=1`);
|
|
await until("second Site admits its own Browser user", () => view(0), value => value.connection === "connected");
|
|
await appReady(0);
|
|
const otherIdentity = (await view(0)).self.id;
|
|
const otherRoom = await action(0, "createRoom({name:'Other Site App room',icon:'couch',access:'public',hidden:false})");
|
|
const otherBinding = (await view(0)).state.channel.rooms.find(entry => entry.id === otherRoom).delivery.bindingId;
|
|
await action(0, `sendMessage(${JSON.stringify(otherRoom)}, 'Other Site before revocation')`);
|
|
await browser(1, "tab", approvalTab);
|
|
await browser(1, "open", `${local}/client?bookmarks`);
|
|
await browser(1, "wait", ".lr-site-list");
|
|
const launcherTab = (await browser(1, "tab", "new", `${local}/client`)).targetId;
|
|
await browser(1, "wait", ".lr-launcher-empty");
|
|
await browser(1, "fill", ".lr-site-bookmark-open input", "https://draft.example");
|
|
await browser(1, "tab", approvalTab);
|
|
await browser(1, "find", "role", "button", "click", "--name", "Manage " + origin, "--exact");
|
|
await browser(1, "fill", ".lr-site-form input[maxlength]", "Friends");
|
|
await browser(1, "fill", ".lr-site-form input[inputmode=url]", `http://127.0.0.1:${otherCorePort}`);
|
|
await browser(1, "click", ".lr-site-form button[type=submit]");
|
|
await browser(1, "wait", ".lr-site-list");
|
|
await browser(1, "tab", launcherTab);
|
|
await until("returning launcher shows the saved site", () => evaluate(1,
|
|
"document.querySelector('.lr-launcher-site strong')?.textContent"), value => value === "Friends");
|
|
await browser(1, "tab", approvalTab);
|
|
await browser(1, "find", "role", "button", "click", "--name", "Manage Friends", "--exact");
|
|
await browser(1, "fill", ".lr-site-form input[maxlength]", "Renamed");
|
|
await browser(1, "click", ".lr-site-form button[type=submit]");
|
|
await browser(1, "wait", ".lr-site-list");
|
|
await browser(1, "tab", launcherTab);
|
|
await until("returning launcher uses the updated bookmark name", () => evaluate(1,
|
|
"document.querySelector('.lr-launcher-site strong')?.textContent"), value => value === "Renamed");
|
|
await browser(1, "tab", approvalTab);
|
|
await browser(1, "find", "role", "button", "click", "--name", "Manage Renamed", "--exact");
|
|
await browser(1, "click", ".lr-site-form-actions button[type=button]");
|
|
await browser(1, "wait", ".lr-site-list");
|
|
await browser(1, "tab", launcherTab);
|
|
await until("returning launcher removes the deleted destination", () => evaluate(1,
|
|
"document.querySelectorAll('.lr-launcher-site').length"), count => count === 0);
|
|
assert.equal(await evaluate(1, "document.querySelector('.lr-site-bookmark-open input').value"), "https://draft.example");
|
|
await browser(1, "tab", "close");
|
|
await browser(1, "tab", approvalTab);
|
|
await browser(1, "find", "role", "button", "click", "--name", "Manage " + origin, "--exact");
|
|
await browser(1, "find", "role", "button", "click", "--name", "Revoke App access", "--exact");
|
|
await until("revocation removes only this Site's health authority", async () => (await health(origin)).status, value => value === 403);
|
|
await until("revoked Site's Native rooms stop", () => view(2), value => value.state.channel.rooms.some(entry => entry.id === room && !entry.available));
|
|
assert.equal((await health(otherOrigin)).status, 200);
|
|
assert.equal((await view(0)).self.id, otherIdentity);
|
|
assert.equal((await view(0)).state.channel.rooms.find(entry => entry.id === otherRoom).delivery.bindingId, otherBinding);
|
|
await action(0, `sendMessage(${JSON.stringify(otherRoom)}, 'Other Site still confirms after revocation')`);
|
|
await until("another Site's actual room keeps confirming", () => evaluate(0,
|
|
`${hook}.snapshot().messagesByRoom[${JSON.stringify(otherRoom)}]`), messages => messages?.some(message => message.text === "Other Site still confirms after revocation"));
|
|
await browser(1, "open", `${local}/client?site=${encodeURIComponent(origin)}`);
|
|
await browser(1, "wait", "#site-approval-title");
|
|
await browser(1, "wait", ".lr-client-approval-actions button.is-primary");
|
|
await browser(1, "click", ".lr-client-approval-actions button.is-primary");
|
|
await until("reapproval restores the Site's existing local permission", async () => (await health(origin)).status, value => value === 200);
|
|
await browser(1, "tab", personalTab);
|
|
await action(1, "activateApp()");
|
|
await until("reapproved Site restores its retained room", () => view(1), value => value.state.channel.rooms.some(entry =>
|
|
entry.id === room && entry.available && entry.delivery.bindingId !== restoredBinding));
|
|
const retained = new DatabaseSync(storedPath, { readOnly: true });
|
|
try { assert(retained.prepare("SELECT count(*) AS count FROM message WHERE room_id=?").get(room).count >= 2); }
|
|
finally { retained.close(); }
|
|
assert.equal((await readdir(join(directory, "rooms"))).length, 2, "reapproval reuses the same Site data directory");
|
|
await browser(0, "tab", firstDomainTab);
|
|
await writeFile(join(output, "app-result.json"), JSON.stringify({ passed: true,
|
|
scenarios: ["real Site approval", "unapproved Origin rejected", "saved approval reused", "cross-Site hosting isolation", "reapproval retains Site data",
|
|
"separate hosting and personal endpoints", "Native SQLite ownership", "Browser rooms do not migrate", "domain-carried chat confirmation",
|
|
"chat-only room switches retain zero peer connections and separate histories",
|
|
"Browser screen and voice", "control loss preserves media", "page close preserves App hosting and chat",
|
|
"returning page reuses Native hosting", "App loss isolates its rooms", "fresh binding restores saved history"] }, null, 2));
|
|
} catch (error) { console.error(log); throw error; }
|
|
finally {
|
|
await stop();
|
|
for (const child of [otherWeb, otherServer]) if (child?.exitCode === null && child.signalCode === null) {
|
|
const exited = once(child, "exit"); child.kill(); await exited;
|
|
}
|
|
for (const key of [process.env.PIIK_CHANNEL_OWNER_KEY]) {
|
|
if (key) log = log.replaceAll(key, "[test key]");
|
|
}
|
|
await writeFile(join(output, "app-runtime.log"), log);
|
|
await writeFile(join(output, "app-helper-source-layers.json"), JSON.stringify(sourceLayers, null, 2));
|
|
if (relative(tmpdir(), directory).startsWith("..") || !basename(directory).startsWith("piik-app-room-check-")) throw new Error("Unexpected App acceptance directory");
|
|
await rm(directory, { recursive: true, force: true });
|
|
}
|
|
}
|
|
|
|
// Exercise the normal interface against an actual Native room operator. The
|
|
// Browser harness replaces only capture, retaining real Opus and WebRTC peers.
|
|
export async function nativeRoom({ initial, serverRoom, browser, action, view, evaluate, until, sample, audioProgressing,
|
|
capturedScreen, playing, progressing, assertNoError, hook, output }) {
|
|
const directory = await mkdtemp(join(tmpdir(), "piik-native-room-check-"));
|
|
const database = join(directory, "room.sqlite");
|
|
let room;
|
|
const name = "Native room";
|
|
const executable = resolve(process.env.CHANNEL_NATIVE_EXECUTABLE ??
|
|
`prototype/channel-native/target/debug/piik-channel-native${process.platform === "win32" ? ".exe" : ""}`);
|
|
let native, log = "";
|
|
const start = () => {
|
|
native = spawn(executable, ["--room", database, name], {
|
|
env: { ...process.env, PIIK_CHANNEL_NATIVE_OWNER_KEY: process.env.PIIK_CHANNEL_OWNER_KEY,
|
|
PIIK_CHANNEL_NATIVE_NAME: "Native operator" },
|
|
windowsHide: true, stdio: ["ignore", "pipe", "pipe"],
|
|
});
|
|
const collect = chunk => { log = (log + chunk).slice(-64_000); };
|
|
native.stdout.on("data", collect); native.stderr.on("data", collect);
|
|
native.on("error", error => collect(String(error)));
|
|
};
|
|
const stop = async () => {
|
|
if (native?.exitCode === null && native.signalCode === null) {
|
|
const exited = once(native, "exit"); native.kill(); await exited;
|
|
}
|
|
};
|
|
const energy = value => value.inbound.filter(row => row.kind === "audio")
|
|
.reduce((total, row) => total + (row.energy ?? 0), 0);
|
|
const audible = index => until(`Browser ${index} receives Native-forwarded voice`, () => sample(index),
|
|
value => value.inbound.some(row => row.kind === "audio" && row.samples > 0 && row.energy > 0));
|
|
const advancing = async index => {
|
|
const before = energy(await sample(index));
|
|
return until(`Browser ${index} voice keeps advancing`, () => sample(index), value => energy(value) > before);
|
|
};
|
|
try {
|
|
// Keep this Native forwarding scenario on its own carrier before either Browser can form a direct route.
|
|
for (const [index, peer] of [[1, 2], [2, 1]]) {
|
|
await evaluate(index, `window.__channelProbe.blockPeer(${JSON.stringify(initial[peer].sessionId)})`);
|
|
}
|
|
start();
|
|
await until("Native room becomes available", async () => {
|
|
if (native.exitCode !== null) throw new Error(`Native host exited: ${log}`);
|
|
return view(0);
|
|
}, value => value.state.channel.rooms.some(entry => entry.name === name && entry.available));
|
|
const hosted = (await view(0)).state.channel.rooms.find(entry => entry.name === name && entry.available);
|
|
room = hosted.id;
|
|
const nativeEndpoint = hosted.delivery.hostSessionId;
|
|
assert(!initial.some(value => value.sessionId === nativeEndpoint), "the room uses the standalone Native endpoint");
|
|
for (const index of [1, 2]) await browser(index, "click", `.c3-room-link[aria-label="${name}"]`);
|
|
for (const index of [1, 2]) await action(index, `joinVoice('${room}', true)`);
|
|
const nativePair = index => evaluate(index, `(() => {
|
|
const peer = [...${hook}.session.media.peers.values()].find(peer => peer.plan.peerId === ${JSON.stringify(nativeEndpoint)});
|
|
return peer && { plan: peer.plan, connected: peer.transport.pc.connectionState === 'connected',
|
|
input: peer.transport.input?.readyState, control: peer.transport.channel?.readyState, bulk: peer.transport.bulk?.readyState };
|
|
})()`);
|
|
const standby = await until("roomless Native probes connect on both Browsers", () => Promise.all([1, 2].map(nativePair)),
|
|
values => values.every(value => value?.connected && value.input === "open"));
|
|
for (const value of standby) {
|
|
assert.deepEqual(value.plan.rooms, []);
|
|
assert.deepEqual(value.plan.incoming, []);
|
|
assert.deepEqual(value.plan.outgoing, []);
|
|
assert(value.control === undefined && value.bulk === undefined, "idle room does not open byte payload channels");
|
|
}
|
|
const pairs = standby.map(value => value.plan);
|
|
|
|
await action(1, `sendMessage('${room}', 'Confirmed by Native room')`);
|
|
await until("Native-confirmed history arrives", () => evaluate(2,
|
|
`${hook}.snapshot().messagesByRoom['${room}']`), messages => messages?.some(message => message.text === "Confirmed by Native room"));
|
|
const stored = new DatabaseSync(database, { readOnly: true });
|
|
const domain = new DatabaseSync(process.env.CHANNEL_DATA_FILE, { readOnly: true });
|
|
try {
|
|
assert.equal(stored.prepare("SELECT count(*) AS count FROM message WHERE room_id=?").get(room).count, 1);
|
|
assert.equal(domain.prepare("SELECT count(*) AS count FROM sqlite_schema WHERE type='table' AND name='message'").get().count, 0);
|
|
} finally { stored.close(); domain.close(); }
|
|
|
|
await evaluate(2, `window.__channelProbe.blockPeer(${JSON.stringify(pairs[1].peerId)})`);
|
|
await action(1, `setMuted('${room}', false)`);
|
|
await until("Native media renegotiation offer is actually withheld", () => sample(2), value => value.protocol.some(event =>
|
|
event.pair === pairs[1].id && event.negotiation?.description === "offer" && event.negotiation.withheld
|
|
&& event.negotiation.flows?.length));
|
|
await evaluate(2, `window.__channelProbe.unblockPeer(${JSON.stringify(pairs[1].peerId)})`);
|
|
await action(2, "reconnect()");
|
|
await audible(2);
|
|
assert.equal((await nativePair(2)).plan.id, pairs[1].id,
|
|
"signaling recovery must complete pending negotiation on the existing pair");
|
|
await action(2, `setMuted('${room}', false)`);
|
|
await audible(1);
|
|
const voices = (await view(1)).state.publications.filter(publication => publication.roomId === room);
|
|
const voiceIds = voices.map(publication => publication.id);
|
|
const sourceVoice = voices.find(publication => publication.sessionId === initial[1].sessionId).id;
|
|
assert((await view(2)).state.pairs.some(pair => pair.id === pairs[1].id &&
|
|
pair.incoming.some(flow => flow.publicationId === sourceVoice)), "the resumed source voice still traverses the Native carrier");
|
|
|
|
await evaluate(1, "window.__channelProbe.captureAudio(true)");
|
|
const nativePicture = await capturedScreen(1, room);
|
|
await evaluate(1, "window.__channelProbe.captureAudio(false)");
|
|
await action(2, `watch(${JSON.stringify(nativePicture)})`);
|
|
await playing(2, nativePicture);
|
|
await audioProgressing(2, nativePicture);
|
|
const audioSeparationDb = await evaluate(2,
|
|
`window.__channelProbe.screenAudioSeparation(${JSON.stringify(nativePicture)})`);
|
|
assert(audioSeparationDb.every(db => db > 20),
|
|
`Native screen sound lost stereo separation: ${JSON.stringify(audioSeparationDb)}`);
|
|
assert((await view(2)).state.pairs.some(pair => pair.id === pairs[1].id && pair.incoming.some(flow => flow.publicationId === nativePicture)),
|
|
"picture startup must reuse the connected Native peer");
|
|
|
|
const carrier = () => evaluate(2, `(() => {
|
|
const peer = ${hook}.session.media.peers.get(${JSON.stringify(pairs[1].id)});
|
|
const flow = peer?.plan.incoming.find(flow => flow.publicationId === ${JSON.stringify(nativePicture)});
|
|
const input = flow && peer.inputs.get(flow.id);
|
|
return { stable: peer?.transport.pc.signalingState === 'stable', flow: flow?.id,
|
|
mapped: [...peer.transport.remoteIds.values()],
|
|
stream: input?.stream.id, track: input?.video?.id,
|
|
sections: peer?.transport.pc.remoteDescription?.sdp.split('\\r\\n').filter(line => line.startsWith('m=')).length };
|
|
})()`);
|
|
const originalCarrier = await carrier();
|
|
let previousFlow = originalCarrier.flow;
|
|
for (let attempt = 0; attempt < 4; attempt++) {
|
|
await action(2, `unwatch(${JSON.stringify(nativePicture)})`);
|
|
await until("Native screen lease is retired on the retained pair", carrier,
|
|
value => value.stable && !value.flow && !value.mapped.includes(previousFlow));
|
|
await action(2, `watch(${JSON.stringify(nativePicture)})`);
|
|
await progressing(2, nativePicture);
|
|
await audioProgressing(2, nativePicture);
|
|
const current = await carrier();
|
|
assert.notEqual(current.flow, previousFlow, "rewatching owns fresh flow proof");
|
|
assert.equal(current.stream, originalCarrier.stream, "Native reuses the idle AV group's MSID");
|
|
assert.equal(current.track, originalCarrier.track, "Native reuses the video carrier");
|
|
assert.equal(current.sections, originalCarrier.sections, "Native media history does not grow per watch");
|
|
await audioProgressing(2, sourceVoice);
|
|
previousFlow = current.flow;
|
|
}
|
|
const fileSize = 1024 * 1024 + 17;
|
|
const expected = createHash("sha256").update(Buffer.from(Array.from({ length: fileSize }, (_, index) => index % 251))).digest("hex");
|
|
await evaluate(1, `(async () => {
|
|
const bytes = Uint8Array.from({length:${fileSize}}, (_, index) => index % 251);
|
|
await ${hook}.session.sendMessage('${room}', 'Peer file through Native', [{id:crypto.randomUUID(),file:new File([bytes], 'peer-proof.bin')}]);
|
|
return true;
|
|
})()`);
|
|
const fileMessage = await until("confirmed peer file description", () => evaluate(2,
|
|
`${hook}.snapshot().messagesByRoom['${room}']?.find(message => message.text === 'Peer file through Native')`), Boolean);
|
|
assert.equal(fileMessage.attachments[0].sha256, expected);
|
|
await evaluate(2, `(() => {
|
|
const key = {roomId:'${room}',messageSeq:${fileMessage.seq},attachmentId:${JSON.stringify(fileMessage.attachments[0].id)}};
|
|
const create = FileSystemFileHandle.prototype.createWritable;
|
|
FileSystemFileHandle.prototype.createWritable = async function(...args) {
|
|
const stream = await create.apply(this,args), write = stream.write.bind(stream);
|
|
stream.write = async value => { await new Promise(resolve => setTimeout(resolve,40)); return write(value); };
|
|
return stream;
|
|
};
|
|
window.__fileCheck = {busy:true};
|
|
void ${hook}.session.attachments.content(key,${JSON.stringify(fileMessage.attachments[0])},new AbortController().signal).then(async file => {
|
|
const digest = await crypto.subtle.digest('SHA-256',await file.arrayBuffer());
|
|
window.__fileCheck = {busy:false,size:file.size,sha256:[...new Uint8Array(digest)].map(byte=>byte.toString(16).padStart(2,'0')).join('')};
|
|
},error => {window.__fileCheck = {busy:false,error:String(error)}}).finally(() => {FileSystemFileHandle.prototype.createWritable=create});
|
|
return true;
|
|
})()`);
|
|
await until("file has its own route through the Native peer", () => view(2), value => value.state.files.some(file =>
|
|
file.attachment.id === fileMessage.attachments[0].id && file.upstream === pairs[0].peerId));
|
|
await until("file demand opens the byte lane on the existing peer", () => nativePair(2), value =>
|
|
value?.plan.id === pairs[1].id && value.plan.rooms.includes(room) && value.bulk === "open");
|
|
assert.equal((await evaluate(2, "window.__fileCheck")).busy, true, "the file must still be in flight");
|
|
await action(1, "reconnect()");
|
|
await browser(2, "click", '.c3-room-link[aria-label="Living room"]');
|
|
const receivedFile = await until("peer bytes finish after switching the room view", () => evaluate(2, "window.__fileCheck"), value => !value.busy);
|
|
assert.equal(receivedFile.error, undefined, receivedFile.error);
|
|
assert.equal(receivedFile.size, fileSize); assert.equal(receivedFile.sha256, expected);
|
|
await advancing(2);
|
|
const fileStore = new DatabaseSync(database, { readOnly: true });
|
|
const fileDomain = new DatabaseSync(process.env.CHANNEL_DATA_FILE, { readOnly: true });
|
|
try {
|
|
assert.equal(fileStore.prepare("SELECT count(*) AS count FROM sqlite_master WHERE type='table' AND name='attachment'").get().count, 0);
|
|
assert.equal(fileDomain.prepare("SELECT count(*) AS count FROM sqlite_schema WHERE type='table' AND name='message'").get().count, 0);
|
|
} finally { fileStore.close(); fileDomain.close(); }
|
|
|
|
await browser(2, "click", `.c3-room-link[aria-label="${name}"]`);
|
|
await progressing(2, nativePicture);
|
|
await action(1, `stopScreen(${JSON.stringify(nativePicture)})`);
|
|
await until("stopping Native-forwarded picture retains the voice pair", () => view(2), value =>
|
|
!value.state.publications.some(publication => publication.id === nativePicture)
|
|
&& value.state.pairs.some(pair => pair.id === pairs[1].id && pair.incoming.some(flow => voiceIds.includes(flow.publicationId))));
|
|
await advancing(2);
|
|
await browser(2, "click", '.c3-room-link[aria-label="Living room"]');
|
|
|
|
const picture = await capturedScreen(0, serverRoom);
|
|
await action(2, `watch(${JSON.stringify(picture)})`);
|
|
await playing(2, picture);
|
|
await browser(1, "click", '.c3-room-link[aria-label="Living room"]');
|
|
await advancing(2);
|
|
await action(1, `leaveVoice('${room}')`);
|
|
await action(1, `joinVoice('${room}')`);
|
|
await advancing(2);
|
|
assert.equal((await nativePair(2)).plan.id, pairs[1].id,
|
|
"replacing voice capture must retain the physical connection");
|
|
await progressing(2, picture);
|
|
for (const index of [0, 1, 2]) await assertNoError(index, "Native voice and room lifecycle");
|
|
|
|
// Kill the actual host, allowing the existing authority deadline to expire.
|
|
// Restart uses its saved room data, never a test-made policy or route model.
|
|
await stop();
|
|
await until("Native host expiry pauses the room", () => view(2), value =>
|
|
value.state.channel.rooms.some(entry => entry.id === room && !entry.available)
|
|
&& !value.state.voice.some(member => member.roomId === room), 30_000);
|
|
assert((await sample(1)).captures.filter(track => track.kind === "audio").every(track => track.state === "ended"));
|
|
await progressing(2, picture);
|
|
start();
|
|
await until("Native room reopens", () => view(2), value =>
|
|
value.state.channel.rooms.some(entry => entry.id === room && entry.available));
|
|
await evaluate(2, `window.__channelProbe.historyBeforeNativeReentry = ${hook}.snapshot().historyByRoom['${room}']`);
|
|
await browser(2, "click", `.c3-room-link[aria-label="${name}"]`);
|
|
// Browse approval starts the automatic load; an idle flag alone can precede it.
|
|
await until("Native room history finishes on re-entry", () => evaluate(2,
|
|
`(() => { const state = ${hook}.snapshot(); return state.historyByRoom['${room}'] !== window.__channelProbe.historyBeforeNativeReentry
|
|
&& !state.pending.has('history:${room}'); })()`), Boolean);
|
|
await evaluate(2, "delete window.__channelProbe.historyBeforeNativeReentry");
|
|
assert((await evaluate(2, `${hook}.snapshot().messagesByRoom['${room}']`))
|
|
.some(message => message.text === "Confirmed by Native room"));
|
|
assert(!(await view(2)).state.voice.some(member => member.roomId === room), "saved data must not revive a call");
|
|
await progressing(2, picture);
|
|
await browser(2, "screenshot", join(output, "native-room.png"), "--full");
|
|
await writeFile(join(output, "native-result.json"), JSON.stringify({ passed: true, audioSeparationDb,
|
|
scenarios: ["Native room authority", "standby probes connect before any room payload", "room SQLite owns confirmed history", "lost offer recovery on an existing pair", "bidirectional encoded Opus forwarding",
|
|
"picture startup reuses an established Native peer", "repeated Native AV carrier reuse with fresh flow proof", "simultaneous picture voice and file forwarding", "picture stop preserves voice",
|
|
"peer file through Native with final digest", "signaling reconnect and view switch preserve file and voice", "no domain or Native file-byte store",
|
|
"view changes retain voice", "capture replacement keeps the physical pair", "other-room picture survives",
|
|
"Native process expiry", "history restore without activity revival"] }, null, 2));
|
|
} finally {
|
|
await stop();
|
|
await writeFile(join(output, "native.log"), log);
|
|
assert(!relative(tmpdir(), directory).startsWith("..") && basename(directory).startsWith("piik-native-room-check-"));
|
|
await rm(directory, { recursive: true, force: true });
|
|
}
|
|
}
|