Files
piik/tests/viewer-peer-generation.test.ts
T
AAAandAkazaAkalin 3707e48225 feat!: expand media controls and simplify App connections
## Problem and outcome / 问题与结果

Piik's media settings were coupled to a small preset list, and using native App capture on a Site required a separate launcher mode. This release separates numeric media requests from presets and bounded runtime admission, remembers successfully applied settings, and lets a running App serve an explicitly approved Site independently of Local/public room startup.

The same phase repairs confirmed capture-retirement, ICE discovery, media-recovery and storage failures. P2P-first routing, one room authority and the existing Browser/Native media owners remain. This phase targets **v2.0.0** with incompatible Web/App contracts. The owner authorized publication after final acceptance; the verified package and deployment records own delivery completion.

## Release notes

### 中文

Piik 2.0 扩展了画质设置,简化了 App 与站点的连接,并集中修复采集和断线恢复问题。**本次升级调整了通信协议,App 与所用站点需要一起升级。**

#### 新功能与改进

- **自定义画面设置:** 保留三档推荐预设,支持填写分辨率上限、1–240 帧的帧率上限和 0.1–240 Mbps 的视频码率上限。滑动条沿用常用范围,更高数值可直接填写并显示为“自定义”。帧率范围随画幅变化,可请求 1080p240、1440p144、4K60 和超宽画面;输出保留来源比例。
- **自定义音频质量:** 在原有三档音频预设之外,可填写 6–320 kbps 的来源音频码率上限。
- **双端 App 协同连接:** 启用增强 NAT 穿透后,适用的重试可协调双方 App 准备 UDP 连接;首次连接仍走普通 ICE,不适用时继续现有流程。已通过受控网络验证,实际连通性仍取决于双方网络。
- **记住分享设置:** 下次打开时恢复已应用的画面与音频质量。仅用浏览器时按站点保存;通过新版 App 使用时,更换临时公网邀请网址也能保留设置。
- **更直接地连接 App:** 启动页提供本地房间和公网邀请,首次默认选择公网邀请。使用已有站点时,保持 App 运行,在站点点击 **App** 并确认授权即可。App 打开的本地房主页自动获得授权,站点按钮会显示 App 就绪状态。启动页可查看或取消授权;从另一个站点连接并批准,会替换原授权。
- **置顶聊天窗口:** 支持的桌面浏览器可将聊天移入独立置顶窗口,保留当前消息、草稿和阅读位置;关闭窗口后回到原页面。

#### 修复

- **连接与恢复:** 完善备用 STUN 与 NAT 采样信息的处理;重新收集 ICE 候选时刷新网卡地址。修正观众重连的机会计数、本机媒体连接恢复,以及恢复后遗留的发送队列和带宽统计问题。保留视频编码对应的标准重传能力,改善网络地址变化后的画面恢复。
- **采集稳定性:** 修正 Windows 停止采集或预览时的异步资源释放问题,保留采集边框偏好,更快跳过无法正常输出的编码器。采集与应用音频能力按实际接口探测,不再按 Windows 版本号排除;修正 Linux Portal 来源识别和早期采集失败通知,改善摄像头与原生采集的画面比例处理。
- **状态与清理:** 房间失效时及时释放 App 连接和待完成的选源请求;本地或公网房间启动失败时,App 保持待机并保留其他已授权站点的连接;公网邀请启动失败保留底层错误。修正启动页旧查询覆盖新设置的问题,并限制原生连接准备的待完成任务。SFU 诊断区分房主发布和观众接收状态。
- **其他维护:** 收到尚不支持的表情时跳过该效果;修正 SQLite 写入失败后的事务恢复。Gitee 镜像可独立重试,官网交互、指南和依赖同步更新。App 连接失败时提供重试与下载入口;统一选源设置与自定义数值的反馈。减少重复的随机短语,仅在持续等待时定时轮换。

#### 升级须知

**2.0 与 1.x 不能混用。** 自建站点请更新 Server 和连接该站点的 App,并刷新所有分享与观看页面。本地房间或公网邀请用户请停止分享、关闭旧 App,完整解压新版程序包后重新发送邀请链接。

本次不变更房间数据库结构。重启会中断正在进行的分享;麦克风、采集权限和设备选择不会自动恢复。4K60 等设置是输出上限,实际清晰度与帧率取决于来源、设备和网络。macOS/Linux 采集及部分移动设备仍需更多实机反馈。

### English

Piik 2.0 adds more control over sharing quality, simplifies connecting the App to a Site, and fixes capture and connection-recovery failures. **The communication contracts change in this release: update the App and its Site together.**

#### Highlights

- **Custom picture settings:** Keep the three recommended presets or enter a resolution ceiling, a 1–240 fps limit and a 0.1–240 Mbps video bitrate limit. Sliders retain their familiar ranges; higher entered values are clearly marked as custom. Frame-rate limits depend on picture size, admitting requests such as 1080p240, 1440p144, 4K60 and ultrawide pictures while preserving source proportions.
- **Custom audio quality:** Enter a 6–320 kbps source-audio bitrate limit alongside the three existing audio presets.
- **Coordinated App connections:** With enhanced NAT traversal enabled, eligible retries can coordinate UDP preparation between two Apps. The first attempt remains ordinary ICE, and ineligible preparation continues through the existing path. Controlled network checks pass; real-world connectivity still depends on both networks.
- **Remember sharing settings:** Restore successfully applied picture and audio quality next time. Browser-only use saves settings per site; an updated App can retain them across changing temporary public-invitation addresses.
- **Connect the App from a Site:** The launcher offers Local room and Public invite, with Public invite selected on first use. For an existing Site, keep the App running, click **App** on the Site and confirm its authorization. Host pages opened locally by App are authorized automatically, and the Site button reflects verified App readiness. View or revoke approval in the launcher. Connecting and approving another Site replaces the previous approval.
- **Always-on-top chat:** Supported desktop browsers can move chat into a separate always-on-top window while retaining messages, drafts and reading position. Closing the window returns chat to the page.

#### Fixes

- **Connections and recovery:** Improve fallback STUN discovery and NAT survey handling, and refresh interface addresses during ICE gathering. Fix Viewer recovery-opportunity accounting, local media-connection recovery, stale send queues and bandwidth accounting after recovery. Preserve standard video retransmission when selecting a codec to improve picture recovery after network-address changes.
- **Capture stability:** Fix asynchronous Windows resource retirement after capture or preview ends, retain the capture-border preference, and reject non-performing encoder candidates earlier. Detect capture and process-audio support through actual APIs rather than Windows-version gates. Correct Linux Portal target identification and early capture-failure delivery; improve source-aspect handling for camera and native capture.
- **State and cleanup:** Release App connections and pending source selection when room authority ends. Keep the App on standby and preserve other authorized Site connections when interactive Local/public room startup fails. Retain underlying public-invitation startup errors. Prevent stale launcher reads from replacing newer settings, bound pending native connection-preparation work, and distinguish Host publication from Viewer reception in SFU diagnostics.
- **Maintenance:** Skip unsupported incoming reaction effects, recover SQLite transactions after write failures, and retry Gitee mirroring independently. Update website interactions, guides and dependencies; clarify App connection recovery, source-selection settings and custom-value feedback. Reduce repeated playful captions, with timed rotation reserved for ongoing waits.

#### Upgrading

**2.0 and 1.x cannot be mixed.** For a hosted Site, update its Server and connected Apps, then refresh every Host and Viewer page. For Local rooms or Public invites, stop sharing, close the old App, extract the complete new package and send a fresh invitation.

The room database schema is unchanged. Restarting interrupts active shares; microphone activation, capture permission and device selection are not restored automatically. Settings such as 4K60 are output ceilings: actual resolution and frame rate depend on the source, device and network. macOS/Linux capture and some mobile devices still need more physical-device feedback.

## Verification / 验证

- Product candidate: `24a28738241b9012c0476386356a515aab21f1a5`, built as `v2.0.0`. [Final full candidate CI](https://github.com/TNTcraftHIM/Piik/actions/runs/38555494851) covers core validation, vulnerabilities, races, five App packages and both Server/container targets without publishing. Later commits extend race coverage, correct the capture test fixture's inherited Go race-exit delay, and update documentation/staged website screenshots; shipped product code is unchanged. [Additional control/loopback race checks](https://github.com/TNTcraftHIM/Piik/actions/runs/38561191343) use that updated collector. Product shutdown deadlines and test assertions are unchanged.
- Local Web acceptance passes **91 files / 1,612 tests**, type checking and production build. Full Go/native checks, Windows capture compilation, five-repeat control regressions, website/documentation build and repository checks pass. Existing documentation-size and bundle-size warnings remain visible.
- The Windows candidate's original descriptor, revision and SHA-256 are checked before extraction and packaged Local/control acceptance. All candidate packages pass the release publisher's read-only identity/checksum verification.
- Serial Windows native H.264 Host acceptance passes live/paused/custom/4K settings, background/source recovery and stop/re-share. VP8 two-room SFU and H.264 SFU-only checks pass live quality/audio changes, subscription/page-reload recovery and retirement; stopping one room preserves the other room's media. Browser-to-App fanout and App-exit fallback also pass. Gates clean their processes, profiles and listeners. These checks do not establish sustained game/4K performance.
- The final network run passes **37 cases and six negative controls**, with **32 actual media outcomes and five unavailable observations**. It covers all Browser/App pairings, IPv6, remapping, STUN backup, outages, quality recovery, healthy siblings and SFU policies. Sequential-NAT App/App preparation delivers media; a mixed sequential case also connects in this run, without a claim of deterministic benefit. Fault controls reject absent faults/frozen video and verify cancellation/cleanup. No public success percentage is inferred.
- Twenty Viewer topology acceptance delivers increasing decoded frames to all Viewers, preserves the two-copy bound and recovers from relay loss. Invitation privacy checks find no grant leakage in requests, cookies, persistent storage or logs. Both are bounded synthetic-source checks, not public-network endurance.
- Current UI checks cover Chinese/English/visual, both themes and 320/360/768/1366-pixel layouts, numeric limits, source selection, App approval/revocation, architecture downloads and reader navigation. Chat/PiP retains draft/history/scroll and returns to the page on close; retirement and refused opening clean up. Real Host/Viewer UI chat continues after capture stops and while the Host is absent. Film controls, mute/seek/end/replay, mobile containment and pointer-close unloading pass. README stills and the staged launcher now use current navigation. Scoped axe checks report no violations; contrast and physical assistive-technology coverage are not certified.
- Physical macOS/Linux capture, limited decoders, mixed HDR displays, mobile permissions and sustained game/4K use retain their [evidence limits](https://github.com/TNTcraftHIM/Piik/blob/ci/gitee-mirror/docs/verification-status.md). Unmatched field reports remain open. Gitee activation and public-domain checks are publication postflight; original v1.9.2 artifact/mirror recovery already passed without remote writes.

## Boundaries and contributor credit / 边界与贡献

The candidate uses Browser/server v24 and Native control v10; capture v7 and SQLite schema 2 are unchanged. Numeric wire values remain separate from codec/allocation admission. H.264/VP8, framework-owned adaptation and automatic P2P-first routing remain; this candidate adds neither codecs, room voice, end-to-end HDR, surround audio nor Magicsock.

Local controls confirm specific repairs, not the causes of unmatched user reports or a measured increase in NAT success rate. The STUN report in #471 remains subject to paired endpoint/network evidence. Gitee's separate workflow activation still needs post-merge verification; its original-artifact and anonymous-download path has passed against v1.9.2.

The Linux Portal fix from @AkazaAkali in #470 is incorporated with original commit authorship and the co-author trailer below. #462 and #469 propose higher audio rates and 4K; neither patch is merged. Their preset-expansion implementation is superseded by the independently established numeric-media contract, so overlapping functionality alone does not warrant merging or co-authorship. #475 identifies the Linux desktop entry’s missing terminal controls; that defect is independently corrected without accepting tray or Browser-owned process-exit additions. The settings request in #460 is implemented; issue/PR closure remains part of release follow-up.

Co-authored-by: AkazaAkalin <478080766@qq.com>
2026-10-14 08:09:45 -04:00

1139 lines
39 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { IceConfig, SignalPayload } from "../src/shared/protocol.ts";
import type { PeerSnapshot } from "../src/client/types.ts";
import { ViewerPeer, type ViewerPeerEvents } from "../src/client/webrtc/viewer-peer.ts";
import { ViewerSfuRoute } from "../src/client/media/viewer-sfu-route";
import { NativeCapableViewerPeer } from "../src/client/native/native-viewer-peer";
interface Deferred<T> {
promise: Promise<T>;
resolve: (value: T) => void;
}
function createDeferred<T>(): Deferred<T> {
let resolve!: (value: T) => void;
const promise = new Promise<T>((resolvePromise) => {
resolve = resolvePromise;
});
return { promise, resolve };
}
const ANSWER_SDP = [
"v=0",
"o=- 1 1 IN IP4 127.0.0.1",
"s=-",
"t=0 0",
"m=audio 9 UDP/TLS/RTP/SAVPF 111",
"c=IN IP4 0.0.0.0",
"a=rtpmap:111 opus/48000/2",
"a=fmtp:111 minptime=10;useinbandfec=1",
"a=recvonly",
"",
].join("\r\n");
interface ConnectionPlan {
constructorError?: Error;
answerError?: Error;
answerSdp?: string;
candidateGates?: Promise<void>[];
localDescriptionGate?: Promise<void>;
statsGate?: Promise<RTCStatsReport>;
}
class FakeMediaStream {
private readonly tracks: MediaStreamTrack[] = [];
getTrackById(id: string): MediaStreamTrack | null {
return this.tracks.find((track) => track.id === id) ?? null;
}
addTrack(track: MediaStreamTrack): void {
this.tracks.push(track);
}
getVideoTracks(): MediaStreamTrack[] {
return this.tracks.filter((track) => track.kind === "video");
}
getAudioTracks(): MediaStreamTrack[] {
return this.tracks.filter((track) => track.kind === "audio");
}
}
class FakePeerConnection extends EventTarget {
static readonly instances: FakePeerConnection[] = [];
static readonly plans: ConnectionPlan[] = [];
readonly configurations: RTCConfiguration[] = [];
connectionState: RTCPeerConnectionState = "new";
iceConnectionState: RTCIceConnectionState = "new";
iceGatheringState: RTCIceGatheringState = "new";
remoteDescription: RTCSessionDescription | null = null;
localDescription: RTCSessionDescription | null = null;
statsGate: Promise<RTCStatsReport> | null = null;
private readonly candidateGates: Promise<void>[];
private readonly localDescriptionGate: Promise<void> | null;
private readonly answerError: Error | null;
private readonly answerSdp: string;
readonly addIceCandidate = vi.fn(async (_candidate: RTCIceCandidateInit | null) => {
const gate = this.candidateGates.shift();
if (gate) {
await gate;
}
});
readonly getStats = vi.fn(async () => {
if (this.statsGate) {
return this.statsGate;
}
return new Map() as unknown as RTCStatsReport;
});
readonly setLocalDescription = vi.fn(
async (description: RTCSessionDescriptionInit) => {
if (this.localDescriptionGate) {
await this.localDescriptionGate;
}
this.localDescription = description as RTCSessionDescription;
},
);
constructor(configuration?: RTCConfiguration) {
super();
if (configuration) {
this.configurations.push(configuration);
}
const plan = FakePeerConnection.plans.shift() ?? {};
if (plan.constructorError) throw plan.constructorError;
this.candidateGates = [...(plan.candidateGates ?? [])];
this.localDescriptionGate = plan.localDescriptionGate ?? null;
this.answerError = plan.answerError ?? null;
this.answerSdp = plan.answerSdp ?? ANSWER_SDP;
this.statsGate = plan.statsGate ?? null;
FakePeerConnection.instances.push(this);
}
readonly setRemoteDescription = vi.fn(
async (description: RTCSessionDescriptionInit): Promise<void> => {
this.remoteDescription = description as RTCSessionDescription;
},
);
async createAnswer(): Promise<RTCSessionDescriptionInit> {
if (this.answerError) {
throw this.answerError;
}
return {
type: "answer",
sdp: this.answerSdp,
};
}
readonly setConfiguration = vi.fn((configuration: RTCConfiguration) => {
this.configurations.push(configuration);
});
close(): void {
this.connectionState = "closed";
}
emitTrack(track: MediaStreamTrack, streams: MediaStream[] = []): void {
this.dispatchEvent(
Object.assign(new Event("track"), { track, streams }),
);
}
}
const intervalCallbacks = new Map<number, () => void>();
let nextIntervalId = 1;
const timeoutCallbacks = new Map<number, () => void>();
const timeoutDelays = new Map<number, number>();
let nextTimeoutId = 1;
function offer(connectionId: string): SignalPayload {
return {
kind: "description",
connectionId,
description: { type: "offer", sdp: `offer-${connectionId}` },
};
}
function candidate(connectionId: string, value: string): SignalPayload {
return {
kind: "candidate",
connectionId,
candidate: {
candidate: value,
sdpMid: "0",
sdpMLineIndex: 0,
},
};
}
function decodedReport(framesDecoded: number): RTCStatsReport {
return new Map([
[
"video-in",
{
id: "video-in",
type: "inbound-rtp",
timestamp: 1_000,
kind: "video",
framesDecoded,
},
],
]) as unknown as RTCStatsReport;
}
function createPeer(
signals: SignalPayload[],
snapshots: PeerSnapshot[],
signalPeers: string[] = [],
iceConfig: IceConfig = { iceServers: [] },
natPrediction = false,
): ViewerPeer {
return new ViewerPeer(
iceConfig,
{
sendSignal: (peerId, payload) => {
signalPeers.push(peerId);
signals.push(payload);
return true;
},
sendRestartRequest: () => true,
onStream: () => undefined,
onUpdate: (snapshot) => snapshots.push(snapshot),
},
{ natPredictionEnabled: natPrediction },
);
}
async function flushAsyncWork(): Promise<void> {
await new Promise<void>((resolve) => setImmediate(resolve));
}
beforeEach(() => {
FakePeerConnection.instances.length = 0;
FakePeerConnection.plans.length = 0;
intervalCallbacks.clear();
nextIntervalId = 1;
timeoutCallbacks.clear();
timeoutDelays.clear();
nextTimeoutId = 1;
vi.stubGlobal("MediaStream", FakeMediaStream);
vi.stubGlobal("RTCPeerConnection", FakePeerConnection);
vi.stubGlobal("window", {
setInterval: (callback: () => void) => {
const id = nextIntervalId++;
intervalCallbacks.set(id, callback);
return id;
},
clearInterval: (id: number) => intervalCallbacks.delete(id),
setTimeout: (callback: () => void, delay: number) => {
const id = nextTimeoutId++;
timeoutCallbacks.set(id, callback);
timeoutDelays.set(id, delay);
return id;
},
clearTimeout: (id: number) => {
timeoutCallbacks.delete(id);
timeoutDelays.delete(id);
},
});
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe("ViewerPeer connection generations", () => {
it.each(["dispose", "replace"])("settles pending answer work on %s without a browser completion", async (retirement) => {
const gate = createDeferred<void>();
FakePeerConnection.plans.push({ localDescriptionGate: gate.promise });
const signals: SignalPayload[] = [];
const peer = createPeer(signals, []);
let settled = false;
const old = peer.acceptSignal("parent", offer("old"));
void old.then(() => { settled = true; });
await flushAsyncWork();
expect(FakePeerConnection.instances[0]!.setLocalDescription).toHaveBeenCalledOnce();
if (retirement === "dispose") peer.dispose();
else await peer.acceptSignal("parent", offer("new"));
await flushAsyncWork();
const settledByRetirement = settled;
gate.resolve();
await old;
peer.dispose();
expect(signals.filter(value => value.connectionId === "old")).toEqual([]);
expect(settledByRetirement).toBe(true);
});
it("releases authoritative route resync when its old browser operation never completes", async () => {
const gate = createDeferred<void>();
FakePeerConnection.plans.push({ localDescriptionGate: gate.promise });
const signals: SignalPayload[] = [];
let peer: ViewerPeer | null = createPeer(signals, []);
let connection = 0;
const route = new ViewerSfuRoute("viewer-old", {
activatePeer: async () => {
peer ??= createPeer(signals, []);
await peer.acceptSignal("parent", offer(`connection-${++connection}`));
},
resetMedia: () => { peer?.dispose(); peer = null; },
onSfuStream: () => undefined,
send: () => true,
});
const assignment = { upstream: { kind: "peer" as const, peerId: "parent" }, childPeerIds: [], sfuPublicationGeneration: null };
route.accept({ revision: 1, phase: "active", assignment });
await flushAsyncWork();
expect(FakePeerConnection.instances[0]!.setLocalDescription).toHaveBeenCalledOnce();
let settled = false;
const resync = route.resyncAuthoritative({ revision: 2, phase: "active", assignment }, "viewer-new");
void resync.then(() => { settled = true; });
await flushAsyncWork();
const resyncedWithoutRetiredWork = settled;
gate.resolve();
await resync;
await route.disconnect();
peer?.dispose();
expect(signals.filter(value => value.connectionId === "connection-1")).toEqual([]);
expect(resyncedWithoutRetiredWork).toBe(true);
});
it.each(["route", "viewer"] as const)("handles construction failure with the %s recovery owner and exact identity", async (recoveryOwner) => {
const sendSignal = vi.fn(() => true);
const sendRestartRequest = vi.fn(() => true);
const exhausted = vi.fn((_parent: string, id: string) => {
expect(peer.hasConnectionId(id)).toBe(true);
return true;
});
const peer = new NativeCapableViewerPeer({ iceServers: [] }, { sendSignal, sendRestartRequest,
onStream: () => undefined, onUpdate: () => undefined, onRecoveryExhausted: exhausted },
{ recoveryOwner }, async () => null, () => undefined, "session", 2);
FakePeerConnection.plans.push({ constructorError: new DOMException("Allocation failed", "UnknownError") });
await expect(peer.acceptSignal("host", offer("first"))).resolves.toBeUndefined();
expect(peer.hasConnection()).toBe(false);
expect(peer.getConnectionIdentity()).toEqual({ parentPeerId: "host", connectionId: "first" });
if (recoveryOwner === "route") {
expect(sendRestartRequest).not.toHaveBeenCalled();
expect(exhausted).toHaveBeenCalledExactlyOnceWith("host", "first");
} else {
expect(sendRestartRequest).toHaveBeenCalledExactlyOnceWith("host", "first", true);
FakePeerConnection.plans.push({ constructorError: new DOMException("Allocation failed", "UnknownError") });
await peer.acceptSignal("host", offer("second"));
expect(sendRestartRequest).toHaveBeenCalledOnce();
expect(exhausted).toHaveBeenCalledExactlyOnceWith("host", "second");
}
expect(timeoutCallbacks.size).toBe(0);
await peer.acceptSignal("host", offer("working"));
expect(sendSignal).toHaveBeenCalledOnce();
expect(peer.hasConnectionId("working")).toBe(true);
expect(peer.hasConnectionId("first")).toBe(false);
peer.dispose();
expect(peer.hasConnectionId("working")).toBe(false);
});
it("returns failed prepared SDP to its route owner without requesting a rebuild", async () => {
const restart = vi.fn(() => true), exhausted = vi.fn(() => true);
const peer = new ViewerPeer({ iceServers: [] }, { sendSignal: () => true, sendRestartRequest: restart,
onStream: () => undefined, onUpdate: () => undefined, onRecoveryExhausted: exhausted },
{ recoveryOwner: "route" });
FakePeerConnection.plans.push({ answerError: new Error("answer failed") });
await peer.acceptSignal("host", offer("prepared"));
expect(restart).not.toHaveBeenCalled();
expect(exhausted).toHaveBeenCalledExactlyOnceWith("host", "prepared");
expect(timeoutCallbacks.size).toBe(0);
peer.dispose();
});
it("returns rejected video to the existing route owner with its receiving cause", async () => {
const restart = vi.fn(() => true), exhausted = vi.fn(() => true), sendSignal = vi.fn(() => true);
const updates: PeerSnapshot[] = [];
const peer = new ViewerPeer({ iceServers: [] }, { sendSignal, sendRestartRequest: restart,
onStream: () => undefined, onUpdate: value => updates.push(value), onRecoveryExhausted: exhausted },
{ recoveryOwner: "route" });
FakePeerConnection.plans.push({ answerSdp: "m=video 0 UDP/TLS/RTP/SAVPF 120\r\n" });
await peer.acceptSignal("host", { kind: "description", connectionId: "rejected",
description: { type: "offer", sdp: "m=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\n" } });
expect(updates.at(-1)?.error).toEqual({ key: "viewer.msg.videoRejected" });
expect(exhausted).toHaveBeenCalledExactlyOnceWith("host", "rejected");
expect(sendSignal).not.toHaveBeenCalled();
expect(restart).not.toHaveBeenCalled();
expect(timeoutCallbacks.size).toBe(0);
peer.dispose();
});
it("answers after a rejected queued candidate and still applies later candidates", async () => {
const signals: SignalPayload[] = [];
const snapshots: PeerSnapshot[] = [];
const peer = createPeer(signals, snapshots);
await peer.acceptSignal("host", candidate("queued", "stale-candidate"));
const current = candidate("queued", "current-candidate");
await peer.acceptSignal("host", current);
const answering = peer.acceptSignal("host", offer("queued"));
const connection = FakePeerConnection.instances[0]!;
connection.addIceCandidate.mockRejectedValueOnce(new DOMException("Unknown ICE username fragment", "OperationError"));
await answering;
expect(connection.addIceCandidate).toHaveBeenCalledTimes(2);
expect(signals).toHaveLength(1);
expect(signals[0]).toMatchObject({ kind: "description", description: { type: "answer" } });
expect(snapshots.at(-1)?.error).toBeNull();
peer.dispose();
});
it("keeps separately delivered audio and video on one remote stream", async () => {
const streams: MediaStream[] = [];
const peer = new ViewerPeer(
{ iceServers: [] },
{
sendSignal: () => true,
sendRestartRequest: () => true,
onStream: (stream) => streams.push(stream),
onUpdate: () => undefined,
},
);
await peer.acceptSignal("host", offer("separate-tracks"));
const connection = FakePeerConnection.instances[0]!;
const video = { id: "remote-video", kind: "video" } as MediaStreamTrack;
const audio = { id: "remote-audio", kind: "audio" } as MediaStreamTrack;
connection.emitTrack(video, [{} as MediaStream]);
connection.emitTrack(audio, [{} as MediaStream]);
expect(streams).toHaveLength(2);
expect(streams[0]).toBe(streams[1]);
expect(streams[1]!.getVideoTracks()).toEqual([video]);
expect(streams[1]!.getAudioTracks()).toEqual([audio]);
peer.dispose();
});
it("proves a fresh exact connection from its first cumulative decoded frame", async () => {
FakePeerConnection.plans.push({
statsGate: Promise.resolve(decodedReport(1)),
});
const decoded = vi.fn(() => true);
const peer = new ViewerPeer(
{ iceServers: [] },
{
sendSignal: () => true,
sendRestartRequest: () => true,
onStream: () => undefined,
onUpdate: () => undefined,
onFirstDecodedFrame: decoded,
},
);
await peer.acceptSignal("host", offer("fresh-exact"));
await flushAsyncWork();
expect(decoded).toHaveBeenCalledOnce();
expect(decoded).toHaveBeenCalledWith("fresh-exact");
peer.dispose();
});
it("does not publish an in-flight decoded proof from a replaced connection", async () => {
const oldStats = createDeferred<RTCStatsReport>();
FakePeerConnection.plans.push(
{ statsGate: oldStats.promise },
{ statsGate: Promise.resolve(new Map() as unknown as RTCStatsReport) },
);
const decoded = vi.fn(() => true);
const peer = new ViewerPeer(
{ iceServers: [] },
{
sendSignal: () => true,
sendRestartRequest: () => true,
onStream: () => undefined,
onUpdate: () => undefined,
onFirstDecodedFrame: decoded,
},
);
await peer.acceptSignal("host-a", offer("old-exact"));
await peer.acceptSignal("host-b", offer("new-exact"));
oldStats.resolve(decodedReport(3));
await flushAsyncWork();
expect(decoded).not.toHaveBeenCalled();
peer.dispose();
});
it("sets and signals stereo audio bitrate for every answer", async () => {
const signals: SignalPayload[] = [];
const peer = createPeer(signals, []);
await peer.acceptSignal("host", offer("screen-audio"));
await peer.acceptSignal("host", offer("screen-audio"));
await peer.acceptSignal("host", offer("screen-audio-rebuild"));
const answers = signals.filter((signal) => signal.kind === "description");
const localDescriptions = FakePeerConnection.instances.flatMap((connection) =>
connection.setLocalDescription.mock.calls.map(([description]) => description),
);
expect(answers).toHaveLength(3);
for (const [index, description] of localDescriptions.entries()) {
expect(description).toEqual(expect.objectContaining({
type: "answer",
sdp: expect.stringContaining(
"a=fmtp:111 minptime=10;useinbandfec=1;stereo=1;maxaveragebitrate=510000",
),
}));
expect(answers[index]?.description.sdp).toBe(description.sdp);
}
});
it("applies STUN-only ICE configuration at creation and update", async () => {
const peer = createPeer([], [], [], {
iceServers: [{ urls: ["stun:stun-a.example.test:3478"] }],
});
await peer.acceptSignal("host", offer("stun-config"));
const connection = FakePeerConnection.instances[0]!;
peer.updateIceConfig({
iceServers: [{ urls: ["stun:stun-b.example.test:3478"] }],
});
expect(connection.configurations).toEqual([
{ iceServers: [{ urls: ["stun:stun-a.example.test:3478"] }] },
{ iceServers: [{ urls: ["stun:stun-b.example.test:3478"] }] },
]);
expect(connection.setConfiguration).toHaveBeenCalledOnce();
for (const configuration of connection.configurations) {
expect(
configuration.iceServers?.every(
(server) =>
!Reflect.has(server, "username") &&
!Reflect.has(server, "credential") &&
(typeof server.urls === "string"
? server.urls.startsWith("stun:")
: server.urls.every((url) => url.startsWith("stun:"))),
),
).toBe(true);
}
});
it("uses the room NAT policy for Viewer-originated ICE candidates", async () => {
const signals: SignalPayload[] = [];
const peer = createPeer(
signals,
[],
[],
{
iceServers: [{ urls: "stun:share.example.test:3478" }],
natPredictionStunUrls: [
"stun:share.example.test:3479",
"stun:share.example.test:3480",
],
},
true,
);
await peer.acceptSignal("host", offer("nat-room-policy"));
const connection = FakePeerConnection.instances[0]!;
expect(connection.configurations[0]?.iceServers).toEqual([
{ urls: "stun:share.example.test:3478" },
{ urls: "stun:share.example.test:3479" },
{ urls: "stun:share.example.test:3480" },
]);
const surveyUrls = [
"stun:share.example.test:3478",
"stun:share.example.test:3479",
"stun:share.example.test:3480",
];
const emitCandidate = (port: number, url: string): void => {
const event = new Event("icecandidate");
Object.defineProperty(event, "candidate", {
value: {
candidate:
`candidate:base 1 udp 2122260223 203.0.113.7 ${port} ` +
"typ srflx raddr 192.0.2.7 rport 50000 generation 0 ufrag test",
sdpMid: "0",
sdpMLineIndex: 0,
usernameFragment: "test",
url,
},
});
connection.dispatchEvent(event);
};
emitCandidate(40_000, surveyUrls[0]!);
emitCandidate(40_003, surveyUrls[1]!);
emitCandidate(40_006, surveyUrls[2]!);
connection.iceGatheringState = "complete";
connection.dispatchEvent(new Event("icegatheringstatechange"));
const candidates = signals.filter(
(signal): signal is Extract<SignalPayload, { kind: "candidate" }> =>
signal.kind === "candidate",
);
expect(
candidates.some((signal) =>
signal.candidate?.candidate.startsWith("candidate:sp"),
),
).toBe(true);
expect(
candidates.filter((signal) =>
signal.candidate?.candidate.startsWith("candidate:base"),
),
).toHaveLength(3);
expect(candidates.filter((signal) => signal.candidate === null)).toHaveLength(1);
peer.dispose();
});
it("restarts ICE when an answered initial connection stays stuck", async () => {
const restartRequests: Array<{
peerId: string;
connectionId: string;
rebuild: boolean;
}> = [];
const peer = new ViewerPeer(
{ iceServers: [] },
{
sendSignal: () => true,
sendRestartRequest: (peerId, connectionId, rebuild) => {
restartRequests.push({ peerId, connectionId, rebuild });
return true;
},
onStream: () => undefined,
onUpdate: () => undefined,
},
);
await peer.acceptSignal("relay-parent", offer("stuck-connection"));
expect(timeoutDelays.get(1)).toBe(15_000);
timeoutCallbacks.get(1)!();
expect(restartRequests).toEqual([
{
peerId: "relay-parent",
connectionId: "stuck-connection",
rebuild: false,
},
]);
expect(timeoutDelays.get(2)).toBe(3_000);
});
it("returns NAT-enabled candidate failure to its route owner without local retries", async () => {
const restartRequests: string[] = [];
const exhausted: string[] = [];
const peer = new ViewerPeer(
{ iceServers: [] },
{
sendSignal: () => true,
sendRestartRequest: (_peerId, connectionId) => {
restartRequests.push(connectionId);
return true;
},
onStream: () => undefined,
onUpdate: () => undefined,
onRecoveryExhausted: (_peerId, connectionId) => {
exhausted.push(connectionId);
return true;
},
},
{ recoveryOwner: "route", natPredictionEnabled: true },
);
await peer.acceptSignal("host", offer("route-candidate"));
const connection = FakePeerConnection.instances[0]!;
connection.connectionState = "disconnected";
connection.dispatchEvent(new Event("connectionstatechange"));
expect(timeoutDelays).toEqual(new Map());
expect(restartRequests).toEqual([]);
expect(exhausted).toEqual([]);
connection.connectionState = "failed";
connection.dispatchEvent(new Event("connectionstatechange"));
expect(restartRequests).toEqual([]);
expect(timeoutDelays).toEqual(new Map());
expect(exhausted).toEqual(["route-candidate"]);
});
it("transfers recovery ownership when a prepared route fails during commit", async () => {
const restartRequests: Array<{
connectionId: string;
rebuild: boolean;
}> = [];
const peer = new ViewerPeer(
{ iceServers: [] },
{
sendSignal: () => true,
sendRestartRequest: (_peerId, connectionId, rebuild) => {
restartRequests.push({ connectionId, rebuild });
return true;
},
onStream: () => undefined,
onUpdate: () => undefined,
},
{ recoveryOwner: "route" },
);
await peer.acceptSignal("host", offer("committed-candidate"));
const connection = FakePeerConnection.instances[0]!;
connection.connectionState = "failed";
peer.activatePreparedRoute();
expect(restartRequests).toEqual([
{ connectionId: "committed-candidate", rebuild: false },
]);
expect([...timeoutDelays.values()]).toEqual([3_000]);
});
it("cancels the initial deadline after connecting", async () => {
const restartRequests: string[] = [];
const peer = new ViewerPeer(
{ iceServers: [] },
{
sendSignal: () => true,
sendRestartRequest: (_peerId, connectionId) => {
restartRequests.push(connectionId);
return true;
},
onStream: () => undefined,
onUpdate: () => undefined,
},
);
await peer.acceptSignal("host", offer("connected-generation"));
const initialDeadline = timeoutCallbacks.get(1)!;
const connection = FakePeerConnection.instances[0]!;
connection.connectionState = "connected";
connection.dispatchEvent(new Event("connectionstatechange"));
expect(timeoutCallbacks.has(1)).toBe(false);
initialDeadline();
expect(restartRequests).toEqual([]);
});
it("ignores an initial deadline from an old connection generation", async () => {
const restartRequests: string[] = [];
const peer = new ViewerPeer(
{ iceServers: [] },
{
sendSignal: () => true,
sendRestartRequest: (_peerId, connectionId) => {
restartRequests.push(connectionId);
return true;
},
onStream: () => undefined,
onUpdate: () => undefined,
},
);
await peer.acceptSignal("host", offer("connection-old"));
const oldDeadline = timeoutCallbacks.get(1)!;
await peer.acceptSignal("host", offer("connection-new"));
expect(timeoutCallbacks.has(1)).toBe(false);
expect(timeoutDelays.get(2)).toBe(15_000);
oldDeadline();
expect(restartRequests).toEqual([]);
const currentConnection = FakePeerConnection.instances[1]!;
currentConnection.connectionState = "connected";
currentConnection.dispatchEvent(new Event("connectionstatechange"));
expect(timeoutCallbacks.has(2)).toBe(false);
});
it("clears the initial deadline when disposed", async () => {
const peer = createPeer([], []);
await peer.acceptSignal("host", offer("disposed-connection"));
peer.dispose();
expect(timeoutCallbacks).toEqual(new Map());
expect(timeoutDelays).toEqual(new Map());
});
it.each([false, true])("bounds recovery across rebuilt Browser connections (native wrapper=%s)", async (wrapped) => {
const restartRequests: Array<{
peerId: string;
connectionId: string;
rebuild: boolean;
}> = [];
const exhausted: Array<{ peerId: string; connectionId: string }> = [];
const events: ViewerPeerEvents = {
sendSignal: () => true,
sendRestartRequest: (peerId, connectionId, rebuild) => {
restartRequests.push({ peerId, connectionId, rebuild });
return true;
},
onStream: () => undefined,
onUpdate: () => undefined,
onRecoveryExhausted: (peerId, connectionId) => {
exhausted.push({ peerId, connectionId });
return true;
},
};
const peer = wrapped
? new NativeCapableViewerPeer({ iceServers: [] }, events, {}, async () => null,
() => undefined, "session", 2)
: new ViewerPeer({ iceServers: [] }, events);
await peer.acceptSignal("relay-parent", offer("failed-connection"));
const connection = FakePeerConnection.instances[0]!;
connection.connectionState = "failed";
connection.dispatchEvent(new Event("connectionstatechange"));
expect(restartRequests).toEqual([
{
peerId: "relay-parent",
connectionId: "failed-connection",
rebuild: false,
},
]);
timeoutCallbacks.get(2)!();
expect(restartRequests.at(-1)).toEqual({
peerId: "relay-parent",
connectionId: "failed-connection",
rebuild: true,
});
await peer.acceptSignal("relay-parent", offer("rebuilt-connection"));
expect(timeoutCallbacks.has(3)).toBe(false);
connection.connectionState = "connected";
connection.dispatchEvent(new Event("connectionstatechange"));
const rebuilt = FakePeerConnection.instances.at(-1)!;
rebuilt.connectionState = "failed";
rebuilt.dispatchEvent(new Event("connectionstatechange"));
expect(exhausted).toEqual([
{ peerId: "relay-parent", connectionId: "rebuilt-connection" },
]);
rebuilt.dispatchEvent(new Event("connectionstatechange"));
expect(restartRequests).toHaveLength(2);
expect(exhausted).toHaveLength(1);
expect(peer.requestRecovery(true)).toBe(true);
[...timeoutCallbacks.values()].at(-1)!();
expect(restartRequests).toHaveLength(3);
expect(exhausted).toHaveLength(2);
peer.dispose();
});
it("retries delivery of an exhausted edge after signaling reconnects", async () => {
let reportAvailable = false;
const exhausted: string[] = [];
const peer = new ViewerPeer(
{ iceServers: [] },
{
sendSignal: () => true,
sendRestartRequest: () => true,
onStream: () => undefined,
onUpdate: () => undefined,
onRecoveryExhausted: (_peerId, connectionId) => {
exhausted.push(connectionId);
return reportAvailable;
},
},
);
await peer.acceptSignal("relay-parent", offer("failed-connection"));
const connection = FakePeerConnection.instances[0]!;
connection.connectionState = "failed";
connection.dispatchEvent(new Event("connectionstatechange"));
timeoutCallbacks.get(2)!();
timeoutCallbacks.get(3)!();
expect(exhausted).toEqual(["failed-connection"]);
reportAvailable = true;
timeoutCallbacks.get(4)!();
expect(exhausted).toEqual(["failed-connection", "failed-connection"]);
connection.dispatchEvent(new Event("connectionstatechange"));
expect(exhausted).toHaveLength(2);
});
it("requests one bounded rebuild when answer negotiation fails", async () => {
FakePeerConnection.plans.push(
{ answerError: new Error("first answer failed") },
{ answerError: new Error("second answer failed") },
);
const restartRequests: Array<{
peerId: string;
connectionId: string;
rebuild: boolean;
}> = [];
const peer = new ViewerPeer(
{ iceServers: [] },
{
sendSignal: () => true,
sendRestartRequest: (peerId, connectionId, rebuild) => {
restartRequests.push({ peerId, connectionId, rebuild });
return true;
},
onStream: () => undefined,
onUpdate: () => undefined,
},
);
await peer.acceptSignal("relay-parent", offer("connection-first"));
await peer.acceptSignal("relay-parent", offer("connection-second"));
expect(restartRequests).toEqual([
{
peerId: "relay-parent",
connectionId: "connection-first",
rebuild: true,
},
]);
});
it("requests a rebuild when the completed answer cannot be signaled", async () => {
const restartRequests: Array<{
peerId: string;
connectionId: string;
rebuild: boolean;
}> = [];
const peer = new ViewerPeer(
{ iceServers: [] },
{
sendSignal: () => false,
sendRestartRequest: (peerId, connectionId, rebuild) => {
restartRequests.push({ peerId, connectionId, rebuild });
return true;
},
onStream: () => undefined,
onUpdate: () => undefined,
},
);
await peer.acceptSignal("relay-parent", offer("unsent-answer"));
expect(restartRequests).toEqual([
{
peerId: "relay-parent",
connectionId: "unsent-answer",
rebuild: true,
},
]);
expect([...timeoutDelays.values()]).toEqual([3_000]);
});
it("serializes recovery requests at the current parent", async () => {
const signals: SignalPayload[] = [];
const signalPeers: string[] = [];
const restartRequests: Array<{
peerId: string;
connectionId: string;
rebuild: boolean;
}> = [];
const peer = new ViewerPeer(
{ iceServers: [] },
{
sendSignal: (peerId, payload) => {
signalPeers.push(peerId);
signals.push(payload);
return true;
},
sendRestartRequest: (peerId, connectionId, rebuild) => {
restartRequests.push({ peerId, connectionId, rebuild });
return true;
},
onStream: () => undefined,
onUpdate: () => undefined,
},
);
await peer.acceptSignal("parent-old", offer("connection-old"));
await peer.acceptSignal("parent-new", offer("connection-new"));
expect(signalPeers).toEqual(["parent-old", "parent-new"]);
expect(peer.requestRecovery(true)).toBe(true);
expect(peer.requestRecovery(true)).toBe(false);
expect(restartRequests).toEqual([
{
peerId: "parent-new",
connectionId: "connection-new",
rebuild: true,
},
]);
const connection = FakePeerConnection.instances.at(-1)!;
connection.connectionState = "connected";
[...timeoutCallbacks.values()].at(-1)!();
expect(peer.requestRecovery(true)).toBe(true);
expect(restartRequests).toHaveLength(2);
peer.dispose();
});
it("retires the recovery deadline when a rebuilt connection is answered", async () => {
const exhausted: string[] = [];
const peer = new ViewerPeer(
{ iceServers: [] },
{
sendSignal: () => true,
sendRestartRequest: () => true,
onStream: () => undefined,
onUpdate: () => undefined,
onRecoveryExhausted: (_peerId, connectionId) => {
exhausted.push(connectionId);
return true;
},
},
);
await peer.acceptSignal("relay-parent", offer("connection-before-rebuild"));
expect(peer.requestRecovery(true)).toBe(true);
await peer.acceptSignal("relay-parent", offer("connection-after-rebuild"));
expect([...timeoutDelays.values()]).toEqual([15_000]);
expect(exhausted).toEqual([]);
peer.dispose();
});
it("does not send an old answer or candidate after replacing the connection", async () => {
const oldLocalDescription = createDeferred<void>();
FakePeerConnection.plans.push({
localDescriptionGate: oldLocalDescription.promise,
});
const signals: SignalPayload[] = [];
const snapshots: PeerSnapshot[] = [];
const peer = createPeer(signals, snapshots);
const oldAccept = peer.acceptSignal("host", offer("connection-old"));
await vi.waitFor(() => {
expect(FakePeerConnection.instances[0]?.setLocalDescription).toHaveBeenCalledOnce();
});
const oldConnection = FakePeerConnection.instances[0]!;
await peer.acceptSignal("host", offer("connection-new"));
const iceEvent = new Event("icecandidate");
Object.defineProperty(iceEvent, "candidate", {
value: {
candidate: "candidate-from-old-connection",
sdpMid: "0",
sdpMLineIndex: 0,
usernameFragment: null,
},
});
oldConnection.dispatchEvent(iceEvent);
oldLocalDescription.resolve();
await oldAccept;
expect(signals).toHaveLength(1);
expect(signals[0]).toMatchObject({
kind: "description",
connectionId: "connection-new",
description: { type: "answer" },
});
expect(snapshots.at(-1)).toMatchObject({
connectionId: "connection-new",
error: null,
});
});
it("serializes ordinary offers for the same connection", async () => {
const firstLocalDescription = createDeferred<void>();
FakePeerConnection.plans.push({
localDescriptionGate: firstLocalDescription.promise,
});
const signals: SignalPayload[] = [];
const peer = createPeer(signals, []);
const first = peer.acceptSignal("host", offer("same-connection"));
await vi.waitFor(() =>
expect(
FakePeerConnection.instances[0]?.setLocalDescription,
).toHaveBeenCalledOnce(),
);
const connection = FakePeerConnection.instances[0]!;
const second = peer.acceptSignal("host", offer("same-connection"));
await Promise.resolve();
expect(connection.setRemoteDescription).toHaveBeenCalledOnce();
firstLocalDescription.resolve();
await Promise.all([first, second]);
expect(connection.setRemoteDescription).toHaveBeenCalledTimes(2);
expect(
signals.filter((signal) => signal.kind === "description"),
).toHaveLength(2);
});
it("stops flushing old candidates when the connection is replaced", async () => {
const firstCandidate = createDeferred<void>();
FakePeerConnection.plans.push({
candidateGates: [firstCandidate.promise],
});
const peer = createPeer([], []);
await peer.acceptSignal("host", candidate("connection-old", "candidate-1"));
await peer.acceptSignal("host", candidate("connection-old", "candidate-2"));
const oldAccept = peer.acceptSignal("host", offer("connection-old"));
await vi.waitFor(() => {
expect(FakePeerConnection.instances[0]?.addIceCandidate).toHaveBeenCalledOnce();
});
const oldConnection = FakePeerConnection.instances[0]!;
await peer.acceptSignal("host", offer("connection-new"));
const newConnection = FakePeerConnection.instances[1]!;
// Retirement must settle the old flush without awaiting the browser gate.
await oldAccept;
firstCandidate.resolve();
expect(oldConnection.addIceCandidate).toHaveBeenCalledTimes(1);
expect(newConnection.addIceCandidate).not.toHaveBeenCalled();
});
it("does not apply stats that resolve after the connection is replaced", async () => {
const signals: SignalPayload[] = [];
const snapshots: PeerSnapshot[] = [];
const peer = createPeer(signals, snapshots);
await peer.acceptSignal("host", offer("connection-old"));
const oldConnection = FakePeerConnection.instances[0]!;
const oldStats = createDeferred<RTCStatsReport>();
oldConnection.statsGate = oldStats.promise;
const oldStatsCallback = intervalCallbacks.get(1)!;
oldStatsCallback();
await vi.waitFor(() => expect(oldConnection.getStats).toHaveBeenCalledOnce());
await peer.acceptSignal("host", offer("connection-new"));
const newSnapshotCount = snapshots.filter(
({ connectionId }) => connectionId === "connection-new",
).length;
oldStats.resolve(
new Map([
[
"inbound-old",
{
id: "inbound-old",
type: "inbound-rtp",
timestamp: 2_000,
kind: "video",
bytesReceived: 1_000,
framesDecoded: 60,
frameWidth: 1_920,
frameHeight: 1_080,
},
],
]) as unknown as RTCStatsReport,
);
await flushAsyncWork();
const newSnapshots = snapshots.filter(
({ connectionId }) => connectionId === "connection-new",
);
expect(newSnapshots).toHaveLength(newSnapshotCount);
expect(newSnapshots.at(-1)?.metrics.resolution).toBeNull();
});
it("skips overlapping stats ticks on the same connection", async () => {
const peer = createPeer([], []);
await peer.acceptSignal("host", offer("connection"));
const connection = FakePeerConnection.instances[0]!;
const stats = createDeferred<RTCStatsReport>();
connection.statsGate = stats.promise;
const statsCallback = intervalCallbacks.get(1)!;
statsCallback();
statsCallback();
await vi.waitFor(() => expect(connection.getStats).toHaveBeenCalledOnce());
stats.resolve(new Map() as unknown as RTCStatsReport);
await flushAsyncWork();
connection.statsGate = null;
statsCallback();
await vi.waitFor(() =>
expect(connection.getStats).toHaveBeenCalledTimes(2),
);
});
});