Files
client/test/stream-session.test.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

353 lines
15 KiB
JavaScript

// Behaviour of the TS6 viewer session against a scripted peer connection: ordering of answers and
// candidates, realign offers, stale ICE generations, filters and cancellation during negotiation.
// This exercises session logic only; TS6 interoperability is proven by scripts/probe-stream.mjs.
import test from 'node:test';
import assert from 'node:assert/strict';
import { StreamViewerSession, candidateUfrag, remoteUfrags } from '../app/renderer/js/stream/session.js';
const OFFER = (ufrag) => `v=0\r\na=group:BUNDLE 0 1\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=mid:0\r\na=ice-ufrag:${ufrag}\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:1\r\na=ice-ufrag:${ufrag}\r\n`;
const CAND = (ufrag, n = 1) => `candidate:${n} 1 udp 2122260223 10.10.10.5 5${n}000 typ host generation 0 ufrag ${ufrag} network-id 1`;
class FakePC {
constructor() {
this.signalingState = 'stable';
this.remoteDescription = null;
this.localDescription = null;
this.added = [];
this.closed = false;
this.gates = {};
this.rejectNextCandidate = null;
}
async setRemoteDescription(d) {
if (d.type === 'rollback') {
this.signalingState = 'stable';
return;
}
if (this.gates.setRemote) await this.gates.setRemote;
this.remoteDescription = d;
this.signalingState = 'have-remote-offer';
}
async createAnswer() {
return { type: 'answer', sdp: `answer-for-${this.remoteDescription.sdp.length}` };
}
async setLocalDescription(d) {
if (this.gates.setLocal) await this.gates.setLocal;
this.localDescription = d;
this.signalingState = 'stable';
}
async addIceCandidate(c) {
if (this.rejectNextCandidate) {
const err = this.rejectNextCandidate;
this.rejectNextCandidate = null;
throw err;
}
this.added.push(c);
}
emitLocalCandidate(candidate, mLine = 0, mid = '0') {
this.onicecandidate?.({ candidate: { candidate, sdpMLineIndex: mLine, sdpMid: mid } });
}
close() {
this.closed = true;
}
}
function harness(extra = {}) {
const wire = [];
const states = [];
const timers = [];
let pc = null;
const session = new StreamViewerSession({
streamId: 'S1',
clientId: 16,
ownClientId: 28,
message: 'Probe',
signal: {
join: async (id, clid, msg) => wire.push({ op: 'join', id, clid, msg }),
send: async (id, clid, json) => wire.push({ op: 'send', id, clid, json }),
leave: async (id, clid) => wire.push({ op: 'leave', id, clid }),
},
createPeerConnection: () => {
pc = new FakePC();
return pc;
},
onState: (s, d) => states.push(d ? `${s}:${d}` : s),
setTimer: (fn, ms) => {
timers.push({ fn, ms });
return timers.length;
},
clearTimer: () => {},
...extra,
});
return { session, wire, states, timers, pc: () => pc };
}
const settle = () => new Promise((r) => setTimeout(r, 0));
const signal = (json, id = 'S1', clid = '16') => ({ id, clid, json: JSON.stringify(json) });
test('candidates that arrive before the offer is applied are buffered, then added', async () => {
const h = harness();
await h.session.start();
h.session.handle('notifystreamsignaling', signal({ cmd: 'iceCandidate', args: { mLine: 0, mid: '0', sdp: CAND('u1', 1) } }));
h.session.handle('notifyrespondjoinstreamrequest', { id: 'S1', clid: '16', decision: '1', offer: OFFER('u1'), msg: '' });
h.session.handle('notifystreamsignaling', signal({ cmd: 'iceCandidate', args: { mLine: 1, mid: '1', sdp: CAND('u1', 2) } }));
await settle();
await h.session.queue;
assert.equal(h.pc().added.length, 2);
assert.deepEqual(h.pc().added.map((c) => c.sdpMid), ['0', '1']);
const answers = h.wire.filter((w) => w.op === 'send' && w.json.cmd === 'answer');
assert.equal(answers.length, 1);
assert.equal(typeof answers[0].json.args.answer, 'string');
assert.equal(h.session.state, 'connecting');
});
test('local candidates gathered before the answer is sent follow it, in order', async () => {
const h = harness();
await h.session.start();
let release;
h.session.handle('notifyrespondjoinstreamrequest', { id: 'S1', clid: '16', decision: '1', offer: OFFER('u1') });
await settle();
h.pc().gates.setLocal = new Promise((r) => {
release = r;
});
h.pc().emitLocalCandidate('candidate:9 1 udp 1 192.168.1.2 4000 typ host');
release();
await h.session.queue;
const sends = h.wire.filter((w) => w.op === 'send').map((w) => w.json.cmd);
assert.deepEqual(sends, ['answer', 'iceCandidate']);
const cand = h.wire.find((w) => w.op === 'send' && w.json.cmd === 'iceCandidate').json.args;
assert.deepEqual(Object.keys(cand).sort(), ['mLine', 'mid', 'sdp']);
});
test('a realign offer after the first answer is answered again', async () => {
const h = harness();
await h.session.start();
h.session.handle('notifyrespondjoinstreamrequest', { id: 'S1', clid: '16', decision: '1', offer: OFFER('u1') });
h.session.handle('notifystreamsignaling', signal({ cmd: 'offer', args: { offer: `${OFFER('u1')}a=x-realign\r\n` } }));
await settle();
await h.session.queue;
assert.equal(h.session.offersApplied, 2);
assert.equal(h.wire.filter((w) => w.op === 'send' && w.json.cmd === 'answer').length, 2);
});
test('candidates of a replaced ICE generation are skipped; current-generation failures are counted', async () => {
const h = harness();
await h.session.start();
h.session.handle('notifyrespondjoinstreamrequest', { id: 'S1', clid: '16', decision: '1', offer: OFFER('old') });
h.session.handle('notifystreamsignaling', signal({ cmd: 'reconnectOffer', args: { offer: OFFER('new') } }));
h.session.handle('notifystreamsignaling', signal({ cmd: 'iceCandidate', args: { mLine: 0, mid: '0', sdp: CAND('old', 1) } }));
await settle();
await h.session.queue;
assert.equal(h.session.staleCandidates, 1);
assert.equal(h.pc().added.length, 0);
h.pc().rejectNextCandidate = new Error('malformed');
h.session.handle('notifystreamsignaling', signal({ cmd: 'iceCandidate', args: { mLine: 0, mid: '0', sdp: CAND('new', 2) } }));
await settle();
await h.session.queue;
assert.equal(h.session.candidateErrors, 1);
assert.equal(h.session.state, 'connecting');
});
test('stop during negotiation: leave is sent once and nothing follows it', async () => {
const h = harness();
await h.session.start();
let release;
h.session.handle('notifyrespondjoinstreamrequest', { id: 'S1', clid: '16', decision: '1', offer: OFFER('u1') });
await settle();
h.pc().gates.setLocal = new Promise((r) => {
release = r;
});
h.session.handle('notifystreamsignaling', signal({ cmd: 'offer', args: { offer: OFFER('u1') } }));
await settle();
h.session.stop();
h.pc().emitLocalCandidate('candidate:9 1 udp 1 192.168.1.2 4000 typ host');
release();
await h.session.queue;
await settle();
const leaveAt = h.wire.findIndex((w) => w.op === 'leave');
assert.ok(leaveAt >= 0, 'leave sent');
assert.equal(h.wire.filter((w) => w.op === 'leave').length, 1);
assert.deepEqual(h.wire.slice(leaveAt + 1), [], 'no signaling after leave');
assert.equal(h.session.state, 'stopped');
assert.equal(h.pc().closed, true);
});
test('notifications for other streams or other clients are ignored', async () => {
const h = harness();
await h.session.start();
assert.equal(h.session.handle('notifyrespondjoinstreamrequest', { id: 'OTHER', clid: '16', decision: '1', offer: OFFER('x') }), false);
assert.equal(h.session.handle('notifystreamsignaling', signal({ cmd: 'offer', args: { offer: OFFER('x') } }, 'S1', '99')), false);
assert.equal(h.session.handle('notifystreamstopped', { id: 'OTHER' }), false);
await settle();
assert.equal(h.pc(), null);
assert.equal(h.session.state, 'requesting');
});
test('declined join ends without a leave; stopped stream ends without a leave', async () => {
const a = harness();
await a.session.start();
a.session.handle('notifyrespondjoinstreamrequest', { id: 'S1', clid: '16', decision: '0', msg: 'nope' });
assert.equal(a.session.state, 'declined');
assert.equal(a.wire.some((w) => w.op === 'leave'), false);
const b = harness();
await b.session.start();
b.session.handle('notifyrespondjoinstreamrequest', { id: 'S1', clid: '16', decision: '1', offer: OFFER('u1') });
await settle();
b.session.handle('notifystreamstopped', { id: 'S1', clid: '16' });
assert.equal(b.session.state, 'ended');
assert.equal(b.wire.some((w) => w.op === 'leave'), false);
});
test('client-wide stop ends its viewer but a different explicit stream id does not', async () => {
const h = harness();
await h.session.start();
assert.equal(h.session.handle('notifystreamstopped', { id: 'OTHER', clid: '16' }), false);
assert.equal(h.session.handle('notifystreamstopped', { clid: '99' }), false);
assert.equal(h.session.handle('notifystreamstopped', {}), false);
assert.equal(h.session.state, 'requesting');
assert.equal(h.session.handle('notifystreamstopped', { clid: '16' }), true);
assert.equal(h.session.state, 'ended');
assert.equal(h.session.closed, true);
assert.equal(h.wire.some((w) => w.op === 'leave'), false);
});
test('SFU access info ends only its identified stream, not other pending viewers', async () => {
const h = harness();
await h.session.start();
assert.equal(h.session.handle('notifysfuaccessinfo', { sfu_endpoint: 'x' }), false);
assert.equal(h.session.handle('notifysfuaccessinfo', { id: 'OTHER', clid: '16', sfu_endpoint: 'x' }), false);
assert.equal(h.session.state, 'requesting');
h.session.handle('notifysfuaccessinfo', { id: 'S1', clid: '16', sfu_endpoint: 'x' });
assert.equal(h.session.state, 'unsupported');
assert.equal(h.wire.filter((w) => w.op === 'leave').length, 1);
});
test('two viewers keep signaling, peer lifetimes and leave actions independent', async () => {
const first = harness();
const second = harness({ streamId: 'S2', clientId: 17 });
const all = [first, second];
await Promise.all(all.map((h) => h.session.start()));
for (const h of all) {
h.session.handle('notifyrespondjoinstreamrequest', { id: 'S1', clid: '16', decision: '1', offer: OFFER('first') });
h.session.handle('notifyrespondjoinstreamrequest', { id: 'S2', clid: '17', decision: '1', offer: OFFER('second') });
}
await Promise.all(all.map((h) => h.session.queue));
assert.notEqual(first.pc(), second.pc());
assert.deepEqual(all.map((h) => h.session.answersSent), [1, 1]);
for (const h of all) h.session.handle('notifystreamsignaling', signal({ cmd: 'iceCandidate', args: { mLine: 0, mid: '0', sdp: CAND('second') } }, 'S2', '17'));
await Promise.all(all.map((h) => h.session.queue));
assert.equal(first.pc().added.length, 0);
assert.equal(second.pc().added.length, 1);
first.session.stop();
assert.equal(first.session.pc, null);
assert.equal(second.pc().closed, false);
assert.equal(second.wire.filter((w) => w.op === 'leave').length, 0);
assert.equal(first.wire.filter((w) => w.op === 'leave').length, 1);
for (const h of all) h.session.handle('notifystreamstopped', { id: 'S1', clid: '16' });
assert.equal(second.session.closed, false);
second.session.terminate('disconnected');
assert.equal(second.session.pc, null);
assert.equal(second.wire.filter((w) => w.op === 'leave').length, 0);
});
test('no answer to the join request times out and leaves', async () => {
const h = harness();
await h.session.start();
assert.equal(h.timers.length, 1);
h.timers[0].fn();
assert.equal(h.session.state, 'failed');
assert.equal(h.session.detail, 'no_response');
assert.equal(h.wire.filter((w) => w.op === 'leave').length, 1);
});
test('ufrag helpers', () => {
assert.equal(candidateUfrag(CAND('abc')), 'abc');
assert.equal(candidateUfrag('candidate:1 1 udp 1 1.2.3.4 5 typ host'), null);
assert.deepEqual([...remoteUfrags(OFFER('zz'))], ['zz']);
});
test('terminal session releases its closed peer and detaches peer event callbacks', async () => {
const h = harness();
await h.session.start();
h.session.handle('notifyrespondjoinstreamrequest', { id: 'S1', clid: '16', decision: '1', offer: OFFER('u1') });
await h.session.queue;
const pc = h.pc();
h.session.terminate('stream_stopped');
assert.equal(pc.closed, true);
assert.equal(pc.onicecandidate, null);
assert.equal(pc.ontrack, null);
assert.equal(pc.onconnectionstatechange, null);
assert.equal(h.session.pc, null);
});
test('stop while draining buffered ICE never applies more candidates or creates an answer', async () => {
const h = harness();
await h.session.start();
let release;
const gate = new Promise((resolve) => { release = resolve; });
let attempted = 0;
let answers = 0;
h.session.createPeerConnection = () => {
const pc = new FakePC();
pc.addIceCandidate = async () => { attempted++; await gate; };
pc.createAnswer = async () => { answers++; return { type: 'answer', sdp: 'answer' }; };
return pc;
};
for (const n of [1, 2]) h.session.handle('notifystreamsignaling', signal({ cmd: 'iceCandidate', args: { mLine: 0, mid: '0', sdp: CAND('u1', n) } }));
h.session.handle('notifyrespondjoinstreamrequest', { id: 'S1', clid: '16', decision: '1', offer: OFFER('u1') });
await settle();
assert.equal(attempted, 1);
h.session.stop();
release();
await h.session.queue;
assert.equal(attempted, 1);
assert.equal(answers, 0);
assert.equal(h.session.remoteCandidatesAdded, 0);
});
test('stop during rollback does not apply a replacement offer', async () => {
const h = harness();
await h.session.start();
const pc = h.session._ensurePc();
pc.signalingState = 'have-remote-offer';
let release;
const gate = new Promise((resolve) => { release = resolve; });
const descriptions = [];
pc.setRemoteDescription = async (description) => {
descriptions.push(description.type);
if (description.type === 'rollback') await gate;
};
h.session.handle('notifystreamsignaling', signal({ cmd: 'offer', args: { offer: OFFER('new') } }));
await settle();
h.session.stop();
release();
await h.session.queue;
assert.deepEqual(descriptions, ['rollback']);
assert.equal(h.session.pc, null);
});
test('cancelling with queued reconnect offers never recreates a peer or answers the queue', async () => {
let release;
const gate = new Promise(resolve => { release = resolve; });
let peers = 0;
const applied = [];
const h = harness({ createPeerConnection: () => {
peers++;
const pc = new FakePC();
pc.setRemoteDescription = async description => { applied.push(description.sdp); await gate; };
return pc;
} });
await h.session.start();
h.session.handle('notifyrespondjoinstreamrequest', { id: 'S1', clid: '16', decision: '1', offer: OFFER('first') });
await settle();
for (const name of ['second', 'third']) h.session.handle('notifystreamsignaling', signal({ cmd: 'reconnectOffer', args: { offer: OFFER(name) } }));
h.session.stop();
release();
await h.session.queue;
assert.equal(peers, 1);
assert.deepEqual(applied, [OFFER('first')]);
assert.deepEqual(h.wire.map(item => item.op), ['join', 'leave']);
assert.equal(h.session.pc, null);
assert.equal(h.session.state, 'stopped');
});