Files
client/scripts/smoke-stream-publish.cjs
T
omar e6464bc4ed feat: checkpoint account-free client workflows and source-matched UI
Preserve accumulated client implementation since v0.1.4, including local identities, multi-server state, chat, administration, audio and streaming controls. Refine official-source layout, original artwork, responsive composer overflow, settings navigation and chat scroll anchoring.

Current verification: Node suite passes; isolated packaged chat and responsive control smokes pass without device capture. Native core is reused, not rebuilt in this pass. Strict whole-screen visual parity remains incomplete; no 1:1 or cross-platform acceptance claim. Local checkpoint only; no release or push.
2026-11-01 19:43:18 +03:00

183 lines
14 KiB
JavaScript

'use strict';
// Noninteractive production sender -> production viewer WebRTC proof. NEVER shows a window,
// opens capture devices, connects to TS6, or touches the normal app/profile. Controlled local
// signaling is NOT live server interoperability; real stdio/schema tests are in core/tests.
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { pathToFileURL } = require('node:url');
const { spawn } = require('node:child_process');
const root = path.resolve(__dirname, '..');
const arg = (name) => { const i = process.argv.indexOf(`--${name}`); return i >= 0 ? process.argv[i + 1] : undefined; };
const out = path.resolve(arg('out') || path.join(root, 'smoke-out', 'stream-publish'));
if (!process.versions.electron) {
const electron = require('electron');
const env = { ...process.env }; delete env.ELECTRON_RUN_AS_NODE;
const child = spawn(electron, [__filename, '--out', out], { env, stdio: 'inherit', windowsHide: true });
child.on('error', (error) => { console.error(error); process.exitCode = 1; });
child.on('exit', (code) => { process.exitCode = code ?? 1; });
} else {
const { app, BrowserWindow } = require('electron');
const { validateRequest } = require('../app/main/ipc-validate.js');
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'teamspeach-publisher-offscreen-'));
app.setPath('userData', profile);
app.commandLine.appendSwitch('autoplay-policy', 'no-user-gesture-required');
app.commandLine.appendSwitch('disable-background-timer-throttling');
app.commandLine.appendSwitch('disable-renderer-backgrounding');
let win;
let captureRequests = 0;
const result = { startedAt: new Date().toISOString(), scope: 'Offscreen generated canvas/tone, production publisher and viewer; controlled signaling, not live TS6', errors: [] };
app.whenReady().then(async () => {
fs.mkdirSync(out, { recursive: true });
const pagePath = path.join(profile, 'media.html');
fs.writeFileSync(pagePath, '<!doctype html><meta charset="utf-8"><title>Generated sender media proof (offscreen)</title><body></body>');
win = new BrowserWindow({ show: false, focusable: false, width: 720, height: 500,
webPreferences: { offscreen: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
win.webContents.setAudioMuted(true);
if (win.isVisible() || win.isFocusable() || !win.webContents.isOffscreen()) throw new Error('Generated publisher requires hidden nonfocusable offscreen window');
for (const method of ['show', 'showInactive', 'focus', 'setFullScreen', 'setSimpleFullScreen']) win[method] = () => { throw new Error(`Forbidden window operation: ${method}`); };
win.webContents.session.setPermissionRequestHandler((_wc, _permission, callback) => { captureRequests++; callback(false); });
win.webContents.session.setPermissionCheckHandler(() => false);
win.webContents.on('render-process-gone', (_e, detail) => result.errors.push(detail));
try {
// Test the actual main validation function against all sender adapter shapes, not an echo.
const metadata = { name: 'Disposable generated media', type: 3, accessibility: 3, mode: 1, bitrate: 1200, viewer_limit: 1, audio: true };
for (const [cmd, args] of [['stream_setup', metadata], ['stream_update', { stream_id: 'qa-1', ...metadata }],
['stream_respond', { stream_id: 'qa-1', client_id: 2, decision: true, offer: 'v=0\r\n', message: '' }],
['stream_remove', { stream_id: 'qa-1', client_id: 2 }], ['stream_stop', { stream_id: 'qa-1' }]]) validateRequest(cmd, args);
await win.loadFile(pagePath);
result.media = await win.webContents.executeJavaScript(`(${mediaProof.toString()})(${JSON.stringify({
publisher: pathToFileURL(path.join(root, 'app/renderer/js/stream/publisher.js')).href,
viewer: pathToFileURL(path.join(root, 'app/renderer/js/stream/session.js')).href,
})})`);
result.captureRequests = captureRequests;
if (captureRequests !== 0) throw new Error('Generated media unexpectedly requested capture permission');
fs.writeFileSync(path.join(out, 'generated-media.png'), (await win.webContents.capturePage()).toPNG());
result.passed = true;
} catch (error) {
result.passed = false; result.errors.push(error.stack || String(error)); process.exitCode = 1;
result.diagnostics = await win.webContents.executeJavaScript('window.__publisherProofDiagnostics ?? null').catch(() => null);
} finally {
result.finishedAt = new Date().toISOString();
fs.writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2) + '\n');
console.log(JSON.stringify(result, null, 2));
if (win && !win.isDestroyed()) win.destroy();
app.exit(result.passed ? 0 : 1);
}
}).catch((error) => { console.error(error); app.exit(1); });
process.on('exit', () => { try { fs.rmSync(profile, { recursive: true, force: true }); } catch {} });
}
async function mediaProof(paths) {
const { StreamPublisherSession } = await import(paths.publisher);
const { StreamViewerSession } = await import(paths.viewer);
const assert = (condition, message) => { if (!condition) throw new Error(message); };
const waitFor = async (check, message, timeout = 15000) => {
const deadline = performance.now() + timeout;
while (!await check()) { if (performance.now() > deadline) throw new Error(message); await new Promise((r) => setTimeout(r, 40)); }
};
const wire = [], states = [], allPeers = [];
const canvas = document.createElement('canvas'); canvas.width = 640; canvas.height = 360;
const ctx = canvas.getContext('2d'); let frame = 0;
const draw = () => { ctx.fillStyle = `hsl(${frame++ * 7 % 360} 75% 40%)`; ctx.fillRect(0, 0, 640, 360); ctx.fillStyle = 'white'; ctx.font = '28px sans-serif'; ctx.fillText(`Generated frame ${frame}`, 30, 70); };
draw(); const timer = setInterval(draw, 33);
const audio = new AudioContext(); const tone = audio.createOscillator(); tone.frequency.value = 440;
const dest = audio.createMediaStreamDestination(); const gain = audio.createGain(); gain.gain.value = 0.15;
tone.connect(gain).connect(dest); tone.start(); await audio.resume();
const media = new MediaStream([canvas.captureStream(30).getVideoTracks()[0], dest.stream.getAudioTracks()[0]]);
// Consume and measure decoded remote PCM BEFORE a zero-gain sink, never audible.
// Chromium's inbound totalAudioEnergy can stay zero despite nonzero decoded PCM.
const monitor = new AudioContext(); const analyser = monitor.createAnalyser();
const silent = monitor.createGain(); silent.gain.value = 0;
analyser.connect(silent).connect(monitor.destination); await monitor.resume();
const audioSamples = new Float32Array(analyser.fftSize); let decodedRms = 0; let audioSource;
const received = new MediaStream(); const video = document.createElement('video');
video.muted = true; video.autoplay = true; video.playsInline = true; video.srcObject = received;
video.style.width = '640px'; document.body.append(video);
const caption = document.createElement('p'); caption.textContent = 'Offscreen generated media → production publisher → production viewer'; document.body.append(caption);
let viewer, released = 0;
const clients = new Map([[2, { uid: 'qa-viewer', nickname: 'Generated QA viewer' }]]);
const pcFactory = (config) => { const pc = new RTCPeerConnection(config); allPeers.push(pc); return pc; };
const publisher = new StreamPublisherSession({ ownClientId: 1, resolveClient: (id) => clients.get(id), iceServers: [], createPeerConnection: pcFactory,
onState: (state) => states.push({ state: state.state, detail: state.detail, viewers: state.viewers.length, pending: state.pending.length }),
signal: {
setup: async (args) => { wire.push({ op: 'setup', args }); queueMicrotask(() => publisher.handle('notifystreamstarted', { id: 'qa-1', clid: '1' })); },
update: async (args) => { wire.push({ op: 'update', args }); },
stop: async (id) => { wire.push({ op: 'stop', id }); viewer?.handle('notifystreamstopped', { id, clid: '1' }); },
respond: async (id, clientId, decision, offer, message) => {
wire.push({ op: 'respond', clientId, decision, offerBytes: offer.length });
viewer.handle('notifyrespondjoinstreamrequest', { id, clid: '1', decision: decision ? '1' : '0', offer, msg: message });
},
remove: async (id, clientId) => { wire.push({ op: 'remove', clientId }); viewer.handle('notifystreamclientleft', { id, clid: String(clientId) }); },
send: async (id, _clid, json) => { wire.push({ op: 'send', direction: 'publisher', cmd: json.cmd }); viewer.handle('notifystreamsignaling', { id, clid: '1', json: JSON.stringify(json) }); },
},
});
const createViewer = () => new StreamViewerSession({ streamId: 'qa-1', clientId: 1, ownClientId: 2, iceServers: [], createPeerConnection: pcFactory,
onTrack: (track) => {
received.addTrack(track); video.play().catch(() => {});
if (track.kind === 'audio') { audioSource = monitor.createMediaStreamSource(new MediaStream([track])); audioSource.connect(analyser); }
},
signal: {
join: async (id) => publisher.handle('notifyjoinstreamrequest', { id, clid: '2', is_remove: '0' }),
send: async (id, _clid, json) => { wire.push({ op: 'send', direction: 'viewer', cmd: json.cmd }); publisher.handle('notifystreamsignaling', { id, clid: '2', json: JSON.stringify(json) }); },
leave: async (id) => publisher.handle('notifyjoinstreamrequest', { id, clid: '2', is_remove: '1' }),
},
});
let outcome;
const samples = [];
window.__publisherProofDiagnostics = { wire, states, samples };
try {
await publisher.start({ mediaStream: media, options: { name: 'Disposable generated media', privacy: 'closed', resolution: '720', fps: 30,
videoBitrateKbps: 1200, audioBitrateKbps: 128, viewerLimit: 1 }, release: async () => { released++; clearInterval(timer); tone.stop(); await audio.close(); } });
viewer = createViewer(); await viewer.start();
assert(publisher.snapshot.pending.length === 1 && allPeers.length === 0, 'Closed access created a peer before approval');
await publisher.approveViewer(2);
await waitFor(() => viewer.state === 'live' && video.videoWidth > 0, 'Real sender/viewer media failed to connect: ' + JSON.stringify(states));
await waitFor(async () => {
const rows = [...(await viewer.pc.getStats()).values()].filter((row) => row.type === 'inbound-rtp');
samples.push(rows.map((r) => ({ kind: r.kind, bytesReceived: r.bytesReceived, framesDecoded: r.framesDecoded, totalAudioEnergy: r.totalAudioEnergy })));
if (samples.length > 8) samples.shift();
analyser.getFloatTimeDomainData(audioSamples);
decodedRms = Math.sqrt(audioSamples.reduce((sum, sample) => sum + sample * sample, 0) / audioSamples.length);
const diagnostic = window.__publisherProofDiagnostics;
diagnostic.decodedRms = decodedRms;
diagnostic.source = { frame, audioState: audio.state, audioTime: audio.currentTime, videoTime: video.currentTime,
videoWidth: video.videoWidth, tracks: media.getTracks().map((t) => ({ kind: t.kind, readyState: t.readyState, enabled: t.enabled, muted: t.muted, settings: t.getSettings() })) };
diagnostic.senderStats = [...(await publisher.viewers.get(2).pc.getStats()).values()].filter((r) => ['outbound-rtp', 'media-source', 'codec'].includes(r.type));
return decodedRms > 0.01 && rows.some((r) => r.kind === 'video' && r.framesDecoded >= 15) && rows.some((r) => r.kind === 'audio' && r.bytesReceived > 0);
}, 'Generated audio/video RTP did not arrive');
const first = { width: video.videoWidth, height: video.videoHeight, tracks: received.getTracks().map((t) => t.kind) };
const publisherPeer = publisher.viewers.get(2);
const encodingBefore = publisherPeer.senders.map((s) => ({ kind: s.track.kind, encodings: s.getParameters().encodings }));
await publisher.updateOptions({ fps: 5, videoBitrateKbps: 600, audioBitrateKbps: 64 });
const encodingAfter = publisherPeer.senders.map((s) => ({ kind: s.track.kind, encodings: s.getParameters().encodings }));
assert(encodingAfter.find((s) => s.kind === 'video').encodings[0].maxFramerate === 5, 'Actual video sender ceiling did not change');
assert(encodingAfter.find((s) => s.kind === 'video').encodings[0].maxBitrate === 600000, 'Actual bitrate ceiling did not change');
assert(encodingAfter.find((s) => s.kind === 'audio').encodings[0].maxBitrate === 64000, 'Actual audio ceiling did not change');
publisher.setPaused(true);
assert(media.getTracks().every(track => track.enabled === false && track.readyState === 'live'), 'Pause replaced or ended the source');
publisher.setPaused(false);
assert(media.getTracks().every(track => track.enabled === true), 'Resume did not restore source tracks');
await publisher.kickViewer(2, true);
assert(publisherPeer.pc === null && publisher.viewers.size === 0 && viewer.closed, 'Kick did not close both production sessions');
viewer = createViewer(); await viewer.start();
assert(viewer.state === 'declined' && publisher.viewers.size === 0, 'Kicked UID was re-admitted');
await publisher.stop(); await waitFor(() => released === 1 && audio.state === 'closed', 'Capture release not completed');
assert(media.getTracks().every((t) => t.readyState === 'ended'), 'Source tracks leaked');
assert(allPeers.every((pc) => pc.connectionState === 'closed'), 'Peer connection leaked');
outcome = { first, decodedRms, samples: samples.slice(-2), senderStats: window.__publisherProofDiagnostics.senderStats,
encodingBefore, encodingAfter, wire, states, released,
targetsAreCeilingsNotMeasuredThroughput: true, captureDeviceCalls: 0, liveTS6Interoperability: false };
} finally {
viewer?.terminate('qa_cleanup'); await publisher.stop(); clearInterval(timer);
if (audio.state !== 'closed') { tone.stop(); await audio.close(); }
audioSource?.disconnect(); analyser.disconnect(); silent.disconnect(); await monitor.close();
for (const track of media.getTracks()) track.stop();
for (const track of received.getTracks()) track.stop();
for (const pc of allPeers) pc.close();
video.pause(); video.srcObject = null;
}
return outcome;
}