Files
client/scripts/smoke-stream-view.mjs
T
omar f618d8bce9
ci / linux-arm64-cross (push) Successful in 3m22s
ci / linux-x64 (push) Successful in 3m32s
chat: add safe hybrid Markdown editing with strict CSP
2026-11-02 11:32:31 +03:00

736 lines
45 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Real Electron smoke of channel selection, the stream area above the chat and the player's full screen,
// on a disposable profile that never connects to a server. Two inputs, reported separately in result.json:
//
// - UI fixture: a synthetic snapshot and stream notifications are delivered through the real main → renderer
// `core:event` IPC, exactly where the core's events arrive, so the production tree, header, stream list and
// buttons are clicked. The core itself is running but not connected: commands the UI issues reach it and
// fail with `not_connected`, which the UI must report. Issued commands are read back from the core's debug
// log (TEAMSPEACH_LOG=debug), so "a click did not join" is checked at the bridge, not in the page.
// - Loopback media: a throwaway RTCPeerConnection sends canvas video and a generated 440 Hz tone.
// After the real-core error checks, a test-only IPC handler routes production Watch clicks to that
// sender's SDP/ICE transport. This proves real Chromium media and production UI, not TS6 signaling.
//
// Neither input proves server discovery or TeamSpeak interoperability. No server connection or capture
// device is opened: getUserMedia is explicitly denied and counted in the disposable renderer.
//
// node scripts/smoke-stream-view.mjs --isolated-desktop --out <dir> [--exe <packaged executable>]
// Requires a dedicated Windows test login separate from the active user console. Offscreen rendering
// cannot prove native PiP always-on-top behavior and is deliberately not substituted for this test.
import { closeSettings, launchApp } from './lib/electron-app.mjs';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const argv = process.argv.slice(2);
const opt = (name) => (argv.indexOf(`--${name}`) >= 0 ? argv[argv.indexOf(`--${name}`) + 1] : undefined);
const out = path.resolve(root, opt('out') ?? 'smoke-out/stream-view');
const exe = opt('exe');
if (!argv.includes('--isolated-desktop') || process.env.TEAMSPEACH_ISOLATED_DESKTOP !== '1') {
throw new Error('Desktop safety: native stream smoke is disabled. Use --isolated-desktop and TEAMSPEACH_ISOLATED_DESKTOP=1 only in a verified dedicated Windows test session, never the user desktop.');
}
if (process.platform !== 'win32') throw new Error('This native OS PiP evidence harness requires isolated Windows; headless results cannot establish always-on-top behavior.');
execFileSync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', path.join(root, 'scripts/lib/stream-windows.ps1'), '-RootProcessId', String(process.pid)], { encoding: 'utf8', windowsHide: true });
mkdirSync(out, { recursive: true });
const profile = mkdtempSync(path.join(tmpdir(), 'teamspeach-stream-view-'));
const result = { startedAt: new Date().toISOString(), exe: exe ?? null, steps: [], pageErrors: [] };
const step = (name, data = {}) => {
result.steps.push({ name, ...data });
console.log(`[stream-view] ${name}`, JSON.stringify(data));
};
// ---------- UI fixture (synthetic server state, delivered over the real core:event IPC) ----------
const channel = (id, name, order, topic = '') => ({
id, parent_id: 0, order, name, topic, has_password: false, is_default: id === 10, max_clients: null,
needed_talk_power: 0, codec: 'opus_voice', codec_quality: 6, icon_id: null, banner_url: null, banner_mode: null, depth: 0,
});
const client = (id, nickname, channelId, isStreaming, extra = {}) => ({
id, uid: null, nickname, channel_id: channelId, is_self: false, client_type: 'normal', input_muted: false,
output_muted: false, input_hardware: true, output_hardware: true, away: false, away_message: null, talk_power: 0,
is_talker: false, is_channel_commander: false, is_priority_speaker: false, is_recording: false,
is_streaming: isStreaming, description: null, country: null, server_groups: [], channel_group_id: null,
channel_group_inherited_from: null, avatar_hash: null, has_myts: false, myts_avatars: [], myts_avatar_unparsed: null,
icon_id: null, badges: null, ...extra,
});
let rev = 0;
const snapshot = (flags = {}) => ({
event: 'snapshot',
rev: ++rev,
server: { name: 'UI fixture (no server)', version: null, welcome_message: '', hostbanner_gfx_url: null, hostbanner_url: null },
own_client_id: 1,
own_channel_id: 10,
server_groups: [],
channel_groups: [],
channels: [channel(10, 'Lobby', 0), channel(20, 'Screens', 1, 'Design and games'), channel(30, 'Quiet', 2)],
clients: [
client(1, 'StreamSmoke', 10, false, { is_self: true }),
client(2, 'Ana', 10, false),
client(11, 'Mira', 20, flags.mira ?? true),
client(12, 'Oleg', 20, flags.oleg ?? true),
client(13, 'Pavel', 20, true),
client(14, 'Rita', 30, false),
],
});
const streamInfo = (id, clid, name, audio) => ({ event: 'stream', name: 'notifystreaminfo', items: [{ id, clid: String(clid), name, type: '2', mode: '1', accessibility: '1', audio, bitrate: '0', viewer: '0', viewer_limit: '0', return_code: '' }] });
let app;
let page;
const send = (evt) => app.evaluate(({ BrowserWindow }, e) => BrowserWindow.getAllWindows()[0].webContents.send('core:event', { ...e, connectionId: 'c1' }), evt);
const resize = (width, height) => app.evaluate(({ BrowserWindow }, [w, h]) => BrowserWindow.getAllWindows()[0].setContentSize(w, h), [width, height]);
const windowFullScreen = () => app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isFullScreen());
const diag = () => page.evaluate(() => window.teamspeachDiagnostics.snapshot());
const coreCommands = () => {
let text = '';
try {
text = readFileSync(path.join(profile, 'logs', 'core.log'), 'utf8');
} catch {
return [];
}
return [...text.matchAll(/cmd="?([a-z_]+)"?\s+request|request.*?cmd="?([a-z_]+)/g)].map((m) => m[1] ?? m[2]);
};
const count = (cmd) => coreCommands().filter((c) => c === cmd).length;
const toasts = () => page.$$eval('.toast', (els) => els.map((e) => ({ kind: e.dataset.kind ?? '', text: e.textContent.trim() })));
const dismissToasts = () => page.evaluate(() => document.querySelectorAll('.toast .icon-btn').forEach((b) => b.click()));
const offers = () => page.$$eval('#stream-offers > li', (els) => els.map((e) => e.dataset.key));
const shot = async (name) => {
await page.waitForTimeout(150);
await page.screenshot({ path: path.join(out, `${name}.png`) });
};
const noOverflow = () => page.evaluate(() => document.documentElement.scrollWidth <= innerWidth && document.body.scrollWidth <= innerWidth);
const waitFor = (fn, arg, timeout = 15000) => page.waitForFunction(fn, arg, { timeout });
// PiP lives in the player's overflow (<details> "more" panel); open it the way a user does, then activate PiP.
const openPip = async (pipSelector) => {
const selector = pipSelector || '[data-role="stream-pip"]';
await page.$eval(selector, (pip) => { const details = pip.closest('details'); if (details && !details.open) details.querySelector('summary').click(); });
await page.click(selector);
};
// ---------- loopback streamer (real WebRTC inside the page) ----------
const installStreamer = () => {
const NativePC = window.RTCPeerConnection;
window.RTCPeerConnection = function () { return new NativePC(); }; // Host-only fixture; no public STUN.
window.RTCPeerConnection.prototype = NativePC.prototype;
window.__loop = {
joins: 0,
transports: new Map(),
sources: new Map(),
async start(id, clientId) {
const watch = await import('./js/watch.js');
const ctx = new AudioContext();
const osc = ctx.createOscillator();
osc.frequency.value = 440;
const dest = ctx.createMediaStreamDestination();
const quiet = ctx.createGain();
quiet.gain.value = 0;
osc.connect(quiet);
quiet.connect(dest);
osc.start();
const canvas = document.createElement('canvas');
canvas.width = 640;
canvas.height = 360;
const g = canvas.getContext('2d');
let n = 0;
const timer = setInterval(() => {
g.fillStyle = `hsl(${(n += 7) % 360} 55% 45%)`;
g.fillRect(0, 0, 640, 360);
g.fillStyle = '#fff';
g.font = '28px sans-serif';
g.fillText(`loopback frame ${n / 7}`, 24, 52);
}, 33);
const ms = new MediaStream([canvas.captureStream(30).getVideoTracks()[0], dest.stream.getAudioTracks()[0]]);
const pc = new RTCPeerConnection();
for (const t of ms.getTracks()) pc.addTrack(t, ms);
const emit = (name, item) => watch.onStreamEvent({ event: 'stream', name, items: [{ id, clid: String(clientId), ...item }] });
pc.onicecandidate = (e) => {
if (e.candidate) emit('notifystreamsignaling', { json: JSON.stringify({ cmd: 'iceCandidate', args: { mLine: e.candidate.sdpMLineIndex, mid: e.candidate.sdpMid, sdp: e.candidate.candidate } }) });
};
const loop = this;
const transport = {
async join() {
loop.joins += 1;
await pc.setLocalDescription(await pc.createOffer());
setTimeout(() => emit('notifyrespondjoinstreamrequest', { decision: '1', offer: pc.localDescription.sdp, msg: '' }), 50);
},
async send(_id, _clid, json) {
if (json.cmd === 'answer') await pc.setRemoteDescription({ type: 'answer', sdp: json.args.answer });
else if (json.cmd === 'iceCandidate') await pc.addIceCandidate({ candidate: json.args.sdp, sdpMid: json.args.mid, sdpMLineIndex: json.args.mLine });
},
async leave() {
clearInterval(timer);
for (const track of ms.getTracks()) track.stop();
pc.close();
await ctx.close();
},
};
this.transports.set(id, transport);
this.sources.set(id, { pc, media: ms });
transport.end = async () => {
emit('notifystreamstopped', {});
await transport.leave();
};
},
};
};
const media = () => page.evaluate(() => {
const v = document.querySelector('[data-role="stream-video"]');
const d = window.teamspeachDiagnostics.snapshot();
return {
sameElementMedia: v === window.__video && v.srcObject !== null && v.srcObject === window.__src,
paused: v.paused,
tracks: v.srcObject ? v.srcObject.getTracks().map((t) => `${t.kind}:${t.readyState}`) : [],
joins: window.__loop.joins,
state: d.watches[0].state,
watchingIds: d.watchingIds,
framesDecoded: d.watches[0].framesDecoded,
inboundAudioPackets: d.watches[0].inboundAudioPackets,
fullscreen: d.fullscreen,
videoWidth: Math.round(v.getBoundingClientRect().width),
videoHeight: Math.round(v.getBoundingClientRect().height),
viewportHeight: innerHeight,
viewport: innerWidth,
button: document.querySelector('[data-role="stream-fullscreen"]').getAttribute('aria-label'),
};
});
const progressed = async (before, label) => {
await page.waitForTimeout(2000);
const after = await media();
assert.ok(after.framesDecoded > before.framesDecoded, `${label}: video frames keep decoding`);
assert.ok(after.inboundAudioPackets > before.inboundAudioPackets, `${label}: audio packets keep arriving`);
assert.equal(after.sameElementMedia, true, `${label}: same MediaStream on the same <video>`);
assert.equal(after.joins, 1, `${label}: no new join (re-subscription)`);
assert.equal(after.state, 'live', `${label}: session still live`);
assert.equal(after.paused, false, `${label}: element still playing`);
return after;
};
let failed = null;
try {
app = await launchApp({ exe, profile, env: { TEAMSPEACH_LOG: 'debug' } });
page = await app.firstWindow();
page.on('pageerror', (e) => result.pageErrors.push(e.message));
await page.waitForSelector('#view-onboarding', { state: 'visible', timeout: 30000 });
await page.evaluate(() => {
window.__captureRequests = 0;
for (const method of ['getUserMedia', 'getDisplayMedia']) {
navigator.mediaDevices[method] = async () => {
window.__captureRequests += 1;
throw new DOMException('Capture disabled by isolated QA', 'NotAllowedError');
};
}
window.__qaKeys = [];
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') window.__qaKeys.push({ key: event.key, trusted: event.isTrusted, focused: document.hasFocus() });
});
});
await page.fill('#onboarding-nick', 'StreamSmoke');
await page.click('#onboarding-submit');
await page.waitForSelector('#view-app', { state: 'visible', timeout: 20000 });
await waitFor(() => window.teamspeachDiagnostics.snapshot().core === 'ready');
await resize(1280, 800);
await page.evaluate(installStreamer);
// 1. Fixture "connected": own channel Lobby is shown, nothing streams there.
await send(snapshot());
await send(streamInfo('fx-mira', 11, 'Design review', '1'));
await send(streamInfo('fx-oleg', 12, 'Ranked match', '0'));
await waitFor(() => window.teamspeachDiagnostics.snapshot().streams.length === 2);
await page.waitForTimeout(800); // own-channel stream_list (300 ms debounce) reaches the core and fails
await dismissToasts();
let d = await diag();
assert.equal(d.selectedChannel, 'Lobby');
assert.equal(await page.isHidden('#stream-offers'), true);
assert.equal(await page.isHidden('#channel-browse'), true);
step('own channel shown, no streams there', { selected: d.selectedChannel, own: d.ownChannel, streams: d.streams.length, tree: await page.$$eval('#tree .member-flags .flag-live', (e) => e.length) });
await shot('01-own-channel-dark-1280');
// 2. Click another channel: it is shown, voice stays, its streams appear with Watch; nothing is joined.
const joinsBefore = count('join_channel');
await page.click('#tree [data-key="c:20"] .row-btn');
await waitFor(() => document.querySelector('#stream-offers [data-key="error:13"]'));
d = await diag();
assert.equal(d.selectedChannel, 'Screens');
assert.equal(d.ownChannel, 'Lobby');
assert.equal(count('join_channel'), joinsBefore, 'selecting must not join');
assert.deepEqual(await offers(), ['s:fx-mira', 's:fx-oleg', 'error:13']);
assert.equal(await page.isVisible('#stream-offers [data-key="s:fx-mira"]'), true, 'non-own channel Info must keep its stream discovery visible');
// Selecting a channel that is not the own channel shows its channel info; Chat mode is offered only for
// the own channel, so the composer can never suggest a different target than the one it sends to.
const browse = {
title: await page.textContent('#channel-title'),
note: await page.textContent('#channel-browse'),
joinVisible: await page.isVisible('#btn-join-channel'),
chatModeVisible: await page.isVisible('#btn-channel-chat'),
composerVisible: await page.isVisible('#chat-form'),
pavel: await page.textContent('#stream-offers [data-key="error:13"] .offer-sub'),
streamListCommands: count('stream_list'),
joinChannelCommands: count('join_channel'),
streamJoinCommands: count('stream_join'),
};
assert.equal(browse.joinVisible, true);
assert.match(browse.title, /Screens/);
assert.equal(browse.chatModeVisible, false, 'Chat mode is hidden for a channel that is not the own channel');
assert.equal(browse.composerVisible, false, 'no composer for a channel the user is not in');
assert.equal(browse.streamJoinCommands, 0, 'browsing must not request a stream');
step('click shows channel info without joining voice or stream; own voice channel unchanged', browse);
await shot('02-browse-streams-dark-1280');
await resize(880, 560);
assert.equal(await noOverflow(), true, 'no horizontal overflow at 880×560');
await shot('02-browse-streams-dark-880');
await resize(1280, 800);
// 3. Keyboard: Enter on a channel row selects it; streams of the previous channel are cleared.
await page.focus('#tree [data-key="c:30"] .row-btn');
await page.keyboard.press('Enter');
await waitFor(() => window.teamspeachDiagnostics.snapshot().selectedChannel === 'Quiet');
assert.equal(await page.isHidden('#stream-offers'), true);
const removedChannel = snapshot();
removedChannel.channels = removedChannel.channels.filter((ch) => ch.id !== 30);
removedChannel.clients = removedChannel.clients.filter((cl) => cl.channel_id !== 30);
await send(removedChannel);
await waitFor(() => window.teamspeachDiagnostics.snapshot().selectedChannel === 'Lobby');
step('removed selected channel falls back to own channel', { selected: (await diag()).selectedChannel });
await send(snapshot());
await page.focus('#tree [data-key="c:20"] .row-btn');
await page.keyboard.press('Enter');
await waitFor(() => document.querySelectorAll('#stream-offers > li').length === 3);
step('keyboard selection replaces the stream list', { joinChannelCommands: count('join_channel') });
assert.equal(count('join_channel'), joinsBefore);
await send(streamInfo('fx-mira-second', 11, 'Second screen', '0'));
await waitFor(() => document.querySelectorAll('#stream-offers [data-clid="11"]').length === 2);
step('two shares from one member are separate watch actions', { offers: await offers() });
await send({ event: 'stream', name: 'notifystreamstopped', items: [{ id: 'fx-mira-second', clid: '11' }] });
await waitFor(() => !document.querySelector('#stream-offers [data-key="s:fx-mira-second"]'));
// 4. Production Watch click: stream_join reaches the real (unconnected) core; its error is shown.
await page.click('#stream-offers [data-key="s:fx-mira"] .offer-watch');
await waitFor(() => window.teamspeachDiagnostics.snapshot().watches[0].state === 'failed');
const failedView = {
streamJoinCommands: count('stream_join'),
overlay: await page.textContent('[data-role="stream-overlay"]'),
stopLabel: await page.textContent('[data-role="stream-stop"]'),
toasts: await toasts(),
offersAfterFailure: await offers(),
};
assert.equal(failedView.streamJoinCommands, 1);
assert.ok(failedView.toasts.some((x) => x.kind === 'error'));
step('watch click issues stream_join; core error shown in player', failedView);
await shot('03-watch-error-dark-1280');
await page.click('[data-role="stream-stop"]');
assert.equal(await page.locator('.stream-view').count(), 0);
await dismissToasts();
// 5. Explicit joins: double-click and the header button each issue join_channel (the core refuses).
await page.dblclick('#tree [data-key="c:30"] .row-btn');
await waitFor((n) => document.querySelectorAll('.toast[data-kind="error"]').length >= 1, null);
const afterDbl = count('join_channel');
await dismissToasts();
await page.click('#tree [data-key="c:20"] .row-btn');
await page.click('#btn-join-channel');
await waitFor(() => document.querySelectorAll('.toast[data-kind="error"]').length >= 1, null);
step('double-click and Join channel are the only join paths', { afterDoubleClick: afterDbl - joinsBefore, afterJoinButton: count('join_channel') - joinsBefore, ownChannel: (await diag()).ownChannel });
assert.equal(afterDbl - joinsBefore, 1);
assert.equal(count('join_channel') - joinsBefore, 2);
await dismissToasts();
// 6. Stream end notifications and server flag changes remove entries.
await send({ event: 'stream', name: 'notifystreamstopped', items: [{ id: 'fx-oleg', clid: '12' }] });
await waitFor(() => !document.querySelector('#stream-offers [data-key="s:fx-oleg"]'));
await send(snapshot({ mira: false }));
await waitFor(() => !document.querySelector('#stream-offers [data-key="s:fx-mira"]'));
step('stopped stream and cleared is_streaming flag remove their entries', { offers: await offers(), treeLive: await page.$$eval('#tree .member-flags .flag-live', (e) => e.length) });
await send(snapshot({ mira: true }));
// Only this disposable instance changes its IPC boundary. All signaling below is synthetic local
// transport, while UI handlers, receiver peer connection and decoded media are production paths.
await app.evaluate(({ ipcMain, BrowserWindow }) => {
ipcMain.removeHandler('core:request');
globalThis.__qaStreamCommands = [];
ipcMain.handle('core:request', async (_event, connectionId, cmd, args) => {
globalThis.__qaStreamCommands.push(cmd);
if (!['stream_join', 'stream_signal', 'stream_leave'].includes(cmd)) {
return { ok: false, error: { code: 'not_connected', message: 'Disconnected QA fixture' } };
}
try {
await BrowserWindow.getAllWindows()[0].webContents.executeJavaScript(`(async () => {
const args = ${JSON.stringify(args)};
const transport = window.__loop.transports.get(args.stream_id);
if (!transport) throw new Error('Unknown QA stream');
const method = ${JSON.stringify(cmd)};
if (method === 'stream_join') await transport.join();
else if (method === 'stream_signal') await transport.send(args.stream_id, args.client_id, args.json);
else await transport.leave();
})()`);
return { ok: true, result: {} };
} catch (error) {
return { ok: false, error: { code: 'qa_transport', message: error.message } };
}
});
});
// 7. Loopback media: full screen by click, Escape, keyboard; same session and element throughout.
// The fixture announces the loopback stream like a server would, plus a second stream to offer.
await send(streamInfo('loop-1', 11, 'Loopback canvas', '1'));
await send(streamInfo('fx-oleg', 12, 'Ranked match', '0'));
await page.evaluate(() => window.__loop.start('loop-1', 11));
await page.click('#stream-offers [data-key="s:loop-1"] .offer-watch');
await waitFor(() => window.teamspeachDiagnostics.snapshot().watches[0].framesDecoded > 30 && window.teamspeachDiagnostics.snapshot().watches[0].inboundAudioPackets > 20, null, 30000);
await page.evaluate(() => { window.__video = document.querySelector('[data-role="stream-video"]'); window.__src = window.__video.srcObject; });
let m = await media();
const inlineWidth = m.videoWidth;
step('loopback live in the player', m);
await shot('04-player-live-dark-1280');
await resize(880, 560);
assert.equal(await noOverflow(), true);
await shot('04-player-live-dark-880');
await resize(1280, 800);
// Fault injection at the browser API boundary, not an Electron permission policy override.
// Electron callback(false) can leave the native promise pending; the production app-origin policy
// grants fullscreen. That engine limitation is not claimed as a handled promise rejection.
await page.evaluate(() => {
const view = document.querySelector('.stream-view');
window.__requestFullscreen = view.requestFullscreen;
view.requestFullscreen = () => Promise.reject(new DOMException('QA request rejection', 'NotAllowedError'));
});
await page.click('[data-role="stream-fullscreen"]');
await waitFor(() => document.querySelector('.toast[data-kind="error"]'));
const rejected = { fullscreen: await page.evaluate(() => document.fullscreenElement?.dataset.streamId ?? null), button: await page.getAttribute('[data-role="stream-fullscreen"]', 'aria-label'), toasts: await toasts(), state: (await diag()).watches[0].state };
assert.equal(rejected.fullscreen, null);
assert.ok(rejected.toasts.some((x) => x.kind === 'error' && x.text.includes('Full screen unavailable')), 'rejection is reported');
assert.equal(rejected.state, 'live', 'a rejected request does not touch the session');
step('injected requestFullscreen rejection reported without stopping playback', rejected);
await page.evaluate(() => { document.querySelector('.stream-view').requestFullscreen = window.__requestFullscreen; });
await dismissToasts();
await page.click('[data-role="stream-fullscreen"]');
await waitFor(() => document.fullscreenElement?.dataset.streamId !== undefined);
await page.waitForTimeout(600);
m = await progressed(m, 'enter by click');
assert.equal(await windowFullScreen(), true);
assert.equal(m.videoWidth, m.viewport, 'player fills the actual fullscreen viewport');
assert.ok(m.videoHeight > m.viewportHeight * 0.8, 'video stage fills fullscreen height');
assert.equal(m.button, 'Exit full screen');
step('full screen by click', { ...m, windowFullScreen: true });
await shot('05-fullscreen-dark');
await page.focus('[data-role="stream-fullscreen"]');
await app.evaluate(({ BrowserWindow }) => {
const win = BrowserWindow.getAllWindows()[0];
win.focus();
win.webContents.focus();
});
await waitFor(() => document.hasFocus());
await app.evaluate(({ BrowserWindow }) => {
const wc = BrowserWindow.getAllWindows()[0].webContents;
wc.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
wc.sendInputEvent({ type: 'keyUp', keyCode: 'Escape' });
});
await waitFor(() => document.fullscreenElement === null);
await page.waitForTimeout(600);
m = await progressed(m, 'exit by Escape');
assert.equal(await windowFullScreen(), false);
assert.equal(m.videoWidth, inlineWidth, 'Escape restores the original player geometry');
assert.equal(m.button, 'Full screen');
step('Escape leaves full screen', { ...m, windowFullScreen: false, focus: await page.evaluate(() => document.activeElement?.id ?? '') });
const keys = await page.evaluate(() => window.__qaKeys);
step('native Escape input', { route: 'Electron webContents.sendInputEvent', documentFocusedBeforeInput: true, domEvents: keys, note: 'Chromium consumes native Escape before DOM keydown when leaving HTML fullscreen.' });
await page.focus('[data-role="stream-fullscreen"]');
await page.keyboard.press('Enter');
await waitFor(() => document.fullscreenElement?.dataset.streamId !== undefined);
m = await progressed(m, 'enter by keyboard');
await page.keyboard.press('Enter');
await waitFor(() => document.fullscreenElement === null);
m = await progressed(m, 'exit by keyboard on the button');
step('keyboard toggles full screen on the focused button', m);
// Fault injection only: exercise the otherwise uncommon exit rejection and its recovery UI.
await page.click('[data-role="stream-fullscreen"]');
await waitFor(() => document.fullscreenElement?.dataset.streamId !== undefined);
await page.evaluate(() => {
window.__exitFullscreen = document.exitFullscreen;
document.exitFullscreen = () => Promise.reject(new DOMException('QA exit rejection', 'NotAllowedError'));
});
await page.click('[data-role="stream-fullscreen"]');
await waitFor(() => document.querySelector('.toast[data-kind="error"]'));
assert.equal((await media()).fullscreen, 'loop-1');
step('injected exit rejection is reported and leaves an enabled exit control', { toasts: await toasts(), disabled: await page.isDisabled('[data-role="stream-fullscreen"]') });
assert.equal(await page.isDisabled('[data-role="stream-fullscreen"]'), false);
assert.equal(await page.isVisible('[data-role="stream-fullscreen-error"]'), true, 'exit rejection is visible inside the fullscreen top layer');
await shot('05-fullscreen-exit-error-injected');
await page.evaluate(() => { document.exitFullscreen = window.__exitFullscreen; });
await page.click('[data-role="stream-fullscreen"]');
await waitFor(() => document.fullscreenElement === null);
m = await progressed(m, 'recover from injected exit rejection');
await dismissToasts();
// 8. The stream ends while in full screen: full screen is left and the end is explained.
await page.click('[data-role="stream-fullscreen"]');
await waitFor(() => document.fullscreenElement?.dataset.streamId !== undefined);
await page.evaluate(() => window.__loop.transports.get('loop-1').end());
await waitFor(() => window.teamspeachDiagnostics.snapshot().watches[0].state === 'ended');
await waitFor(() => document.fullscreenElement === null);
await page.waitForTimeout(500);
const ended = { overlay: await page.textContent('[data-role="stream-overlay"]'), stop: await page.textContent('[data-role="stream-stop"]'), windowFullScreen: await windowFullScreen(), button: await page.getAttribute('[data-role="stream-fullscreen"]', 'aria-label'), toasts: await toasts() };
assert.equal(ended.windowFullScreen, false);
assert.equal(ended.button, 'Full screen');
step('stream ended in full screen: left full screen, ended state shown', ended);
await shot('06-ended-after-fullscreen-dark-1280');
await page.click('[data-role="stream-stop"]');
await dismissToasts();
// 9. Restart through the production Watch button for locale/theme and disconnect checks.
await send(streamInfo('loop-2', 11, 'Loopback canvas', '1'));
await page.evaluate(() => window.__loop.start('loop-2', 11));
await page.click('#stream-offers [data-key="s:loop-2"] .offer-watch');
await waitFor(() => window.teamspeachDiagnostics.snapshot().watches[0].framesDecoded > 10, null, 30000);
// 10. Light theme and Russian, with the player and the stream list.
await page.evaluate(() => window.teamspeach.setPrefs({ theme: 'light' }));
await page.waitForTimeout(400);
await shot('07-player-and-streams-light-1280');
await resize(880, 560);
await shot('07-player-and-streams-light-880');
await resize(1280, 800);
await page.evaluate(() => window.teamspeach.setPrefs({ theme: 'dark' }));
await page.click('#btn-settings');
await page.click('#settings-nav [data-panel="appearance"]');
await page.selectOption('#language-select', 'ru');
await waitFor(() => document.documentElement.lang === 'ru');
await closeSettings(page);
await page.click('#tree [data-key="c:20"] .row-btn');
await page.waitForTimeout(300);
const ru = { browse: await page.textContent('#channel-browse'), join: await page.textContent('#btn-join-channel'), fullscreen: await page.getAttribute('[data-role="stream-fullscreen"]', 'aria-label'), offers: await page.$$eval('#stream-offers > li', (els) => els.map((e) => e.textContent.trim())) };
step('Russian labels', ru);
await shot('08-player-and-streams-ru-dark-1280');
await resize(880, 560);
assert.equal(await noOverflow(), true);
await shot('08-player-and-streams-ru-dark-880');
await resize(1280, 800);
// Stop the live player through its real button while fullscreen, then test a declined pending join.
await page.click('[data-role="stream-fullscreen"]');
await waitFor(() => document.fullscreenElement?.dataset.streamId !== undefined);
await page.click('[data-role="stream-stop"]');
await waitFor(() => document.fullscreenElement === null);
assert.equal(await page.locator('.stream-view').count(), 0);
assert.deepEqual((await diag()).watches, []);
assert.equal(await page.locator('[data-role="stream-video"]').count(), 0);
step('Stop watching clears live media and exits fullscreen');
for (const reason of ['stop', 'ended']) {
const id = `loop-pip-${reason}`;
await send(streamInfo(id, 11, 'PiP lifecycle fixture', '1'));
await page.evaluate(id => window.__loop.start(id, 11), id);
await page.click(`#stream-offers [data-key="s:${id}"] .offer-watch`);
await waitFor(() => window.teamspeachDiagnostics.snapshot().watches[0].framesDecoded > 10, null, 30000);
await page.evaluate(() => { window.__terminalTracks = document.querySelector('[data-role="stream-video"]').srcObject.getTracks(); });
if (reason === 'stop') await page.evaluate(() => {
const video = document.querySelector('[data-role="stream-video"]');
const request = video.requestPictureInPicture.bind(video);
// Real native window; only the application's promise continuation is deliberately held.
video.requestPictureInPicture = () => request().then(window => new Promise(resolve => { globalThis.__releasePip = () => resolve(window); }));
});
await openPip('');
await waitFor(() => document.pictureInPictureElement !== null);
if (reason === 'stop') await waitFor(() => typeof window.__releasePip === 'function');
if (reason === 'stop') await page.click('[data-role="stream-stop"]');
else await page.evaluate(id => window.__loop.transports.get(id).end(), id);
await waitFor(() => document.pictureInPictureElement === null);
if (reason === 'stop') await page.evaluate(() => window.__releasePip());
assert.ok(await page.evaluate(() => window.__terminalTracks.every(track => track.readyState === 'ended')));
if (reason === 'ended') {
assert.equal((await diag()).watches[0].state, 'ended');
await page.click('[data-role="stream-stop"]');
}
step(`native PiP cleanup on ${reason}`);
await dismissToasts();
}
await send(streamInfo('denied-join', 12, 'Pending join fixture', '0'));
await page.evaluate(() => window.__loop.transports.set('denied-join', {
join: async () => {}, send: async () => {}, leave: async () => {},
}));
await page.click('#stream-offers [data-key="s:denied-join"] .offer-watch');
await waitFor(() => window.teamspeachDiagnostics.snapshot().watches[0].state === 'requesting');
await page.click('[data-role="stream-fullscreen"]');
await waitFor(() => document.fullscreenElement?.dataset.streamId !== undefined);
await send({ event: 'stream', name: 'notifyrespondjoinstreamrequest', items: [{ id: 'denied-join', clid: '12', decision: '0', msg: 'QA synthetic decline' }] });
await waitFor(() => window.teamspeachDiagnostics.snapshot().watches[0].state === 'declined' && document.fullscreenElement === null);
assert.equal(await windowFullScreen(), false);
step('synthetic declined join exits fullscreen', { overlay: await page.textContent('[data-role="stream-overlay"]') });
await page.click('[data-role="stream-stop"]');
await dismissToasts();
await send(streamInfo('loop-3', 11, 'Loopback canvas', '1'));
await page.evaluate(() => window.__loop.start('loop-3', 11));
await page.click('#stream-offers [data-key="s:loop-3"] .offer-watch');
await waitFor(() => window.teamspeachDiagnostics.snapshot().watches[0].framesDecoded > 10, null, 30000);
// 11. Two actual, independently subscribed generated sources above a usable chat.
await send(streamInfo('loop-4', 12, 'Second loopback canvas', '1'));
await page.evaluate(() => window.__loop.start('loop-4', 12));
const joinsBeforeSecond = await page.evaluate(() => window.__loop.joins);
await page.click('#stream-offers [data-key="s:loop-4"] .offer-watch');
await waitFor(() => window.teamspeachDiagnostics.snapshot().watches.filter((w) => w.state === 'live' && w.framesDecoded > 10).length === 2, null, 30000);
assert.equal(await page.evaluate(() => window.__loop.joins), joinsBeforeSecond + 1);
const tile = (id, role) => `.stream-view[data-stream-id="${id}"] [data-role="${role}"]`;
await page.evaluate(() => {
window.__multiMedia = Array.from(document.querySelectorAll('.stream-view'), view => ({
id: view.dataset.streamId, video: view.querySelector('video'), source: view.querySelector('video').srcObject,
tracks: view.querySelector('video').srcObject.getTracks(),
}));
});
const multiState = () => page.evaluate(() => ({
joins: window.__loop.joins,
watches: window.teamspeachDiagnostics.snapshot().watches,
elements: window.__multiMedia.map(({ id, video, source, tracks }) => ({ id, attached: video.isConnected, sameMedia: video.srcObject === source, tracks: tracks.map(t => t.readyState), muted: video.muted, volume: video.volume })),
}));
const initialMulti = await multiState();
assert.deepEqual(initialMulti.elements.map(e => e.sameMedia), [true, true]);
const boundary = () => page.evaluate(() => {
const stage = document.querySelector('#stream-area').getBoundingClientRect();
const chat = document.querySelector('.chat').getBoundingClientRect();
const input = document.querySelector('#chat-input').getBoundingClientRect();
return { stage: stage.toJSON(), chat: chat.toJSON(), input: input.toJSON(), videos: Array.from(document.querySelectorAll('.stream-view video'), v => ({ rect: v.getBoundingClientRect().toJSON(), fit: getComputedStyle(v).objectFit })) };
});
let layout = await boundary();
assert.ok(layout.stage.bottom <= layout.chat.top);
assert.ok(layout.chat.height >= 180 && layout.input.bottom <= 800);
assert.equal(layout.videos.length, 2);
assert.ok(layout.videos.every(v => v.fit === 'contain' && v.rect.width > 100 && v.rect.height > 60));
await shot('09-two-real-streams-ru-dark-1280');
const split = await page.locator('#stream-splitter').boundingBox();
await page.mouse.move(split.x + split.width / 2, split.y + split.height / 2);
await page.mouse.down();
await page.mouse.move(split.x + split.width / 2, split.y + split.height / 2 + 80, { steps: 5 });
await page.mouse.up();
const resized = await boundary();
assert.ok(resized.stage.height > layout.stage.height + 30);
assert.ok(resized.chat.height >= 180 && resized.stage.bottom <= resized.chat.top);
await page.focus('#stream-splitter');
await page.keyboard.press('ArrowUp');
assert.ok((await boundary()).stage.height < resized.stage.height);
await page.keyboard.press('Enter');
await waitFor(async () => (await import('./js/state.js')).S.prefs.streamStageRatio === 0.55);
const restoredRatio = await page.evaluate(() => {
const stage = document.querySelector('#stream-area');
return Number.parseFloat(stage.style.getPropertyValue('--stream-stage-height')) / stage.parentElement.clientHeight;
});
assert.ok(Math.abs(restoredRatio - 0.55) < 0.01, 'divider reset restores the persisted default ratio');
await page.click('#stream-collapse');
assert.equal(await page.isHidden('#stream-grid'), true);
assert.ok((await boundary()).chat.height > resized.chat.height);
await page.fill('#chat-input', 'Unsent local composer fixture');
await page.click('#stream-collapse');
assert.equal(await page.evaluate(async () => (await import('./js/chat.js')).composerEditor().value), 'Unsent local composer fixture');
await page.fill('#chat-input', '');
assert.equal((await multiState()).joins, initialMulti.joins, 'collapse/resize must not resubscribe');
await resize(880, 560);
assert.equal(await noOverflow(), true);
layout = await boundary();
assert.ok(layout.stage.bottom <= layout.chat.top && layout.chat.height >= 180);
await shot('09-two-real-streams-ru-dark-880');
await resize(1280, 800);
await page.evaluate(() => window.teamspeach.setPrefs({ theme: 'light' }));
await shot('09-two-real-streams-ru-light-1280');
await page.evaluate(() => window.teamspeach.setPrefs({ theme: 'dark' }));
// Per-stream mute/gain stays on each existing element even when PiP owns its display.
await page.$eval(tile('loop-3', 'stream-volume'), el => { el.value = '23'; el.dispatchEvent(new Event('input', { bubbles: true })); });
await page.$eval(tile('loop-4', 'stream-volume'), el => { el.value = '71'; el.dispatchEvent(new Event('input', { bubbles: true })); });
await page.click(tile('loop-3', 'stream-mute'));
let levels = (await multiState()).elements;
assert.deepEqual(levels.map(e => [e.muted, e.volume]), [[true, 0.23], [false, 0.71]]);
await page.$eval(tile('loop-3', 'stream-video'), video => {
window.__nativePip = video.requestPictureInPicture;
video.requestPictureInPicture = () => Promise.reject(new DOMException('QA PiP rejection', 'NotAllowedError'));
});
await openPip(tile('loop-3', 'stream-pip'));
await waitFor(() => document.querySelector('#toasts').textContent.includes('QA PiP rejection'));
assert.ok((await diag()).watches.every(w => w.state === 'live'));
assert.equal((await multiState()).joins, initialMulti.joins);
await page.$eval(tile('loop-3', 'stream-video'), video => { video.requestPictureInPicture = window.__nativePip; });
await dismissToasts();
// Windows native HWND evidence: the extra floating window must belong to this disposable process
// tree, be visible, have nonzero bounds, and carry WS_EX_TOPMOST. API presence is not enough.
assert.equal(process.platform, 'win32', 'this OS evidence path requires Windows; no unsupported platform claim');
const windows = (closeHandle = '') => JSON.parse(execFileSync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', path.join(root, 'scripts/lib/stream-windows.ps1'), '-RootProcessId', String(app.process().pid), ...(closeHandle ? ['-CloseHandle', closeHandle] : [])], { encoding: 'utf8', windowsHide: true }));
const nativeBefore = windows();
assert.ok(nativeBefore.every(w => !w.topmost), 'prior stop/end PiP windows must not survive');
await openPip(tile('loop-3', 'stream-pip'));
await waitFor(() => document.pictureInPictureElement?.closest('.stream-view').dataset.streamId === 'loop-3');
const nativeWithPip = windows();
const pipWindow = nativeWithPip.find(w => !nativeBefore.some(b => b.handle === w.handle) && w.topmost && w.width > 0 && w.height > 0);
assert.ok(pipWindow, 'native PiP must create an actual always-on-top OS window');
step('native PiP window plus two independent live sessions', { nativeBefore, nativeWithPip, pipWindow, state: await multiState() });
await page.waitForTimeout(1800);
let runningMulti = await multiState();
assert.ok(runningMulti.watches.every((w, i) => w.framesDecoded > initialMulti.watches[i].framesDecoded));
assert.deepEqual(runningMulti.elements.map(e => [e.sameMedia, e.muted, e.volume]), [[true, true, 0.23], [true, false, 0.71]]);
assert.equal(runningMulti.joins, initialMulti.joins);
await page.click(tile('loop-3', 'stream-mute'));
assert.equal((await multiState()).elements[0].muted, false);
// Native close returns the same playing video to its tile, not a replacement subscription.
windows(pipWindow.handle);
await waitFor(() => document.pictureInPictureElement === null);
assert.ok(!windows().some(w => w.handle === pipWindow.handle));
assert.equal((await multiState()).joins, initialMulti.joins);
await openPip(tile('loop-3', 'stream-pip'));
await waitFor(() => document.pictureInPictureElement !== null);
await page.click(tile('loop-3', 'stream-fullscreen'));
await waitFor(() => document.fullscreenElement?.dataset.streamId === 'loop-3' && document.pictureInPictureElement === null);
assert.equal(await windowFullScreen(), true);
await openPip(tile('loop-3', 'stream-pip'));
await waitFor(() => document.pictureInPictureElement?.closest('.stream-view').dataset.streamId === 'loop-3' && document.fullscreenElement === null);
assert.equal(await windowFullScreen(), false);
runningMulti = await multiState();
assert.ok(runningMulti.elements.every(e => e.sameMedia));
assert.equal(runningMulti.joins, initialMulti.joins);
await openPip(tile('loop-4', 'stream-pip'));
await waitFor(() => document.pictureInPictureElement?.closest('.stream-view').dataset.streamId === 'loop-4');
assert.equal((await multiState()).joins, initialMulti.joins, 'PiP switching does not subscribe');
// Ending a different view cannot close the active PiP window or affect its peer.
await page.evaluate(() => window.__loop.transports.get('loop-3').end());
await waitFor(() => window.teamspeachDiagnostics.snapshot().watches.find(w => w.id === 'loop-3').state === 'ended');
assert.equal(await page.evaluate(() => document.pictureInPictureElement?.closest('.stream-view').dataset.streamId), 'loop-4');
assert.equal((await diag()).watches.find(w => w.id === 'loop-4').state, 'live');
assert.deepEqual((await multiState()).elements[0].tracks, ['ended', 'ended']);
await page.click(tile('loop-3', 'stream-stop'));
assert.equal((await diag()).watches.length, 1);
// Disconnect closes the remaining PiP and all receiver resources. Generated sender cleanup is
// explicit fixture work, not a production leave on an already-disconnected server.
await send({ event: 'state', state: 'disconnected', reason: null });
await waitFor(() => document.pictureInPictureElement === null && document.fullscreenElement === null);
await page.evaluate(() => window.__loop.transports.get('loop-4').leave());
d = await diag();
assert.equal(d.streams.length, 0);
assert.ok(d.watches.every(w => w.state === 'ended'));
const disconnectedMulti = await multiState();
assert.ok(disconnectedMulti.elements.every(e => e.tracks.every(t => t === 'ended')));
const nativeAfter = windows();
assert.ok(!nativeAfter.some(w => !nativeBefore.some(b => b.handle === w.handle) && w.topmost));
step('disconnect closes PiP and all receiver tracks', { state: disconnectedMulti, nativeAfter });
const captureRequests = await page.evaluate(() => window.__captureRequests);
assert.equal(captureRequests, 0, 'no microphone capture requested');
step('capture safety and synthetic IPC commands', { captureRequests, commands: await app.evaluate(() => globalThis.__qaStreamCommands) });
assert.deepEqual(result.pageErrors, []);
} catch (err) {
failed = err;
step('FAILED', { error: String(err.stack || err) });
if (page) await page.screenshot({ path: path.join(out, 'failure.png') }).catch(() => {});
} finally {
result.commands = coreCommands();
if (app) await app.close().catch(() => {});
rmSync(profile, { recursive: true, force: true });
}
result.ok = !failed;
result.note = 'UI-only synthetic snapshot/stream notifications via core:event with disconnected real-core error checks. Positive Watch clicks use test-only IPC signaling to real in-page WebRTC canvas/tone media. No server discovery or TS6 interoperability proof; no microphone capture.';
writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2));
console.log(`[stream-view] ${result.ok ? 'OK' : 'FAILED'} → ${out}`);
process.exit(result.ok ? 0 : 1);