Files
client/scripts/audit-stream-callbacks.mjs
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

126 lines
9.3 KiB
JavaScript

// Real local generated WebRTC; deliberately gated callback results are fault injection, not TS6 evidence.
import { launchApp } from './lib/electron-app.mjs';
import { mkdirSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import assert from 'node:assert/strict';
const arg = key => { const i = process.argv.indexOf(`--${key}`); return i < 0 ? undefined : process.argv[i + 1]; };
const out = path.resolve(arg('out'));
mkdirSync(out, { recursive: true });
const profile = mkdtempSync(path.join(tmpdir(), 'teamspeach-callbacks-'));
const result = { generatedWebRTC: true, injectedCallbackDelays: true, cases: {}, errors: [] };
let app;
try {
app = await launchApp({ profile, exe: arg('exe') });
const page = await app.firstWindow();
page.on('pageerror', e => result.errors.push(e.message));
await page.waitForSelector('#view-onboarding', { state: 'visible' });
await page.evaluate(() => {
window.__captureRequests = 0;
for (const method of ['getUserMedia', 'getDisplayMedia']) navigator.mediaDevices[method] = async () => { window.__captureRequests++; throw new Error('Capture forbidden'); };
});
await page.fill('#onboarding-nick', 'CallbackAudit');
await page.click('#onboarding-submit');
await page.waitForSelector('#view-app', { state: 'visible' });
await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].webContents.send('core:event', { ...{
event: 'snapshot', own_client_id: 1, own_channel_id: 1,
server: { name: 'Generated', version: '', welcome_message: '' },
channels: [{ id: 1, parent_id: 0, depth: 0, name: 'Generated', codec: 'opus_voice' }],
clients: [{ id: 1, uid: 'self', nickname: 'Self', channel_id: 1, is_self: true }, { id: 2, uid: 'peer', nickname: 'Peer', channel_id: 1 }], server_groups: [], channel_groups: [],
}, connectionId: 'c1' }));
await page.waitForSelector('#session-view', { state: 'visible' });
await page.evaluate(async () => {
const watch = await import('./js/watch.js');
const { S } = await import('./js/state.js');
const { StreamViewerSession } = await import('./js/stream/session.js');
const nativePC = RTCPeerConnection;
window.RTCPeerConnection = function () { return new nativePC(); };
window.RTCPeerConnection.prototype = nativePC.prototype;
const start = StreamViewerSession.prototype.start;
const A = window.__callbacks = { watch, S, sequence: 0, releases: {}, sessions: [], sources: [], video: null, firstPlay: true };
StreamViewerSession.prototype.start = function () { A.sessions.push(this); return start.call(this); };
S.audio.output_muted = true;
A.start = async () => {
watch.stopWatching(); // Explicit fixture replacement, not automatic production switching.
const id = `callback-${++A.sequence}`;
const canvas = document.createElement('canvas'); canvas.width = 320; canvas.height = 180;
const context = canvas.getContext('2d'); let frame = 0;
const timer = setInterval(() => { context.fillStyle = ++frame % 2 ? '#445566' : '#667788'; context.fillRect(0, 0, 320, 180); }, 33);
const stream = canvas.captureStream(30);
const pc = new nativePC(); pc.addTrack(stream.getTracks()[0], stream);
const emit = (name, data) => watch.onStreamEvent({ name, items: [{ id, clid: '2', ...data }] });
const source = { pc, stream, stop() { clearInterval(timer); stream.getTracks().forEach(t => t.stop()); pc.onicecandidate = null; pc.close(); } };
A.sources.push(source);
pc.onicecandidate = e => { if (e.candidate) emit('notifystreamsignaling', { json: JSON.stringify({ cmd: 'iceCandidate', args: { sdp: e.candidate.candidate, mid: e.candidate.sdpMid, mLine: e.candidate.sdpMLineIndex } }) }); };
watch.startWatching({ id, clientId: 2, name: 'Generated callback fixture' }, {
join: async () => { await pc.setLocalDescription(await pc.createOffer()); emit('notifyrespondjoinstreamrequest', { decision: '1', offer: pc.localDescription.sdp }); },
send: async (_id, _clid, json) => { if (pc.signalingState === 'closed') return; 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 }); },
leave: async () => source.stop(),
});
A.video = document.querySelector(`[data-stream-id="${id}"] video`);
A.nativePlay = A.video.play.bind(A.video);
if (A.firstPlay) {
A.firstPlay = false;
const nativePlay = A.nativePlay;
A.video.play = () => { nativePlay().catch(() => {}); return new Promise((_resolve, reject) => { A.releases.play = () => reject(new DOMException('Old play cancelled', 'AbortError')); }); };
}
A.video.setSinkId = () => new Promise((_resolve, reject) => { A.releases.sink = () => reject(new DOMException('Old sink failed', 'NotFoundError')); });
};
});
const live = async () => page.waitForFunction(() => __callbacks.video.videoWidth > 0 && !__callbacks.video.paused && __callbacks.watch.watchSnapshots()[0].state === 'live');
await page.evaluate(() => __callbacks.start()); await live();
result.visible = await page.evaluate(() => ({ visible: __callbacks.video.checkVisibility(), width: __callbacks.video.videoWidth, height: __callbacks.video.videoHeight }));
// Hold actual old-session stats, native play result and sink failure until the replacement is playing.
await page.evaluate(async () => {
const A = __callbacks, old = A.sessions.at(-1);
A.oldTrack = A.video.srcObject.getVideoTracks()[0];
const report = await old.pc.getStats();
old.pc.getStats = () => { A.statsPending = true; return new Promise(resolve => { A.releases.stats = () => resolve(report); }); };
A.video.play = A.nativePlay;
A.video.setSinkId = () => new Promise((_resolve, reject) => { A.releases.sink = () => reject(new DOMException('Old sink failed', 'NotFoundError')); });
A.S.prefs.outputDeviceId = 'injected-output'; A.watch.applySink();
});
await page.waitForFunction(() => __callbacks.statsPending && __callbacks.releases.sink);
await page.evaluate(() => { __callbacks.S.prefs.outputDeviceId = ''; return __callbacks.start(); }); await live();
result.cases.switch = await page.evaluate(async () => {
const A = __callbacks;
const current = A.video.srcObject;
A.S.prefs.outputDeviceId = '';
A.releases.stats(); A.releases.sink(); A.releases.play();
A.oldTrack.dispatchEvent(new Event('ended'));
await new Promise(resolve => setTimeout(resolve, 50));
return { sameMedia: A.video.srcObject === current, tracks: current.getTracks().length, state: A.watch.watchSnapshots()[0].state, sinkError: A.watch.watchSnapshots()[0].sinkError, oldTrackState: A.oldTrack.readyState };
});
// A sink failure after terminal end must not report an error for an already-closed player.
await page.evaluate(async () => {
const A = __callbacks; A.S.prefs.outputDeviceId = 'injected-output'; A.watch.applySink();
await new Promise(resolve => setTimeout(resolve, 20));
A.sessions.at(-1).terminate('stream_stopped');
A.releases.sink();
await new Promise(resolve => setTimeout(resolve, 50));
});
result.cases.terminalSink = await page.evaluate(() => ({ state: __callbacks.watch.watchSnapshots()[0].state, sinkError: __callbacks.watch.watchSnapshots()[0].sinkError, staleErrorVisible: document.querySelector('#toasts').innerText.includes('NotFoundError') }));
await page.evaluate(() => { __callbacks.S.prefs.outputDeviceId = ''; return __callbacks.start(); }); await live();
// Hold a rejected fullscreen completion across a switch; native fullscreen behavior has a separate smoke.
await page.evaluate(() => {
document.querySelector('.stream-view').requestFullscreen = () => new Promise((_resolve, reject) => { __callbacks.releases.fullscreen = () => reject(new Error('Old fullscreen failed')); });
});
await page.click('[data-role="stream-fullscreen"]');
await page.evaluate(() => __callbacks.start()); await live();
await page.evaluate(() => __callbacks.releases.fullscreen());
await page.waitForTimeout(60);
result.cases.fullscreenSwitch = await page.evaluate(() => ({ state: __callbacks.watch.watchSnapshots()[0].state, staleErrorVisible: document.body.innerText.includes('Old fullscreen failed') }));
await page.screenshot({ path: path.join(out, 'callbacks.png') });
result.captureRequests = await page.evaluate(() => window.__captureRequests);
await page.evaluate(() => { __callbacks.watch.stopWatching(); __callbacks.sources.forEach(s => s.stop()); });
if (process.argv.includes('--verify')) {
assert.equal(result.visible.visible, true);
assert.deepEqual(result.cases.switch, { sameMedia: true, tracks: 1, state: 'live', sinkError: '', oldTrackState: 'ended' });
assert.equal(result.cases.terminalSink.sinkError, '');
assert.equal(result.cases.terminalSink.staleErrorVisible, false);
assert.equal(result.cases.fullscreenSwitch.staleErrorVisible, false);
assert.equal(result.captureRequests, 0); assert.deepEqual(result.errors, []);
}
} catch (e) { result.errors.push(e.stack); process.exitCode = 1; }
finally { if (app) await app.close(); rmSync(profile, { recursive: true, force: true }); writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2)); console.log(JSON.stringify(result, null, 2)); }