Files
piik/tests/native-viewer-peer.test.ts
T
AAA e3ada873fd feat(app): improve sharing controls, recovery and troubleshooting
Sharing failures were often reduced to a generic message, and changing Windows audio exclusion required reopening source selection. This phase keeps actionable failure context at the TV status indicator, adds live source-audio controls, and integrates independent capture, codec and ICE-lifetime repairs against the published contract.

The audio controls reuse source replacement and the existing mixer; audio-only changes preserve video capture, encoded sources and connections. Source enumeration is bounded by the serialized control response. Codec preflight and H.264 decoder input enforce the existing native format. Gateway mappings are revalidated only for actual ICE gatherings. Website scripts and styles now share content-addressed build output.

Browser/server v23, Native control v9, capture v7 and the 1440p ceiling stay unchanged. The held 4K/capability candidate and Magicsock transport are excluded. Documentation changes belong to the existing guides, standards and evidence owners.

## Validation

- `npm run check`: type checking, 81 test files / 1,370 tests and the production Web build passed.
- `npm run check:go`: Go tests, formatting, vet, cross-builds and Windows native capture regressions passed. A first run hit Windows temporary-directory cleanup after an unchanged SQLite test; five focused repetitions and the full rerun passed.
- Native Host gates passed separately with H.264 and VP8: live/paused quality changes, minimized-window recovery, source replacement, Viewer decoding and complete process/port cleanup. The App Local entry/authentication/invitation gate passed.
- Website/documentation build, documentation links and repository hygiene passed. Browser review covered Chinese/English, dark/light controls, 320px/360px and desktop layouts, audio selection/off state, troubleshooting dialog/ESC focus return, matching GitHub/Gitee architecture links and the embedded film.
- macOS/Linux physical capture, Windows 10 exclusion and representative network/device coverage remain explicit evidence limits. CI must pass Linux race checks and native packaging before publication.

## Release notes

### 中文

这是一次分享体验与兼容性更新。Windows App 支持在开播后调整排除的应用声音;遇到分享失败时,也有更清楚的提示和排查入口。

#### 使用改进

- 在「分享设置 → 声音」中调整系统声音和排除的应用,无需停止分享。支持的 Windows 10 系统也会按实际能力显示排除选项。
- 分享失败提示保留具体原因。点击电视下方状态,可查看处理建议、诊断入口及对应的故障排查文档。
- 补全中英文常见问题说明,涵盖 App 连接、选源与编码、站点地址配置、严格网络和浏览器 HDR 限制。

#### 修复

- 修复窗口较多或名称较长时选源列表可能加载失败,以及部分独立窗口未列出的情况。
- 改善 Windows 窗口最小化、恢复后的采集衔接。
- 修复部分 Firefox 编码属性影响连接的问题,并使原生接收的格式预判与实际支持范围一致。
- 重连时刷新网关端口映射,避免沿用已失效的映射结果;加强原生 H.264 输入校验。
- 官网下载架构切换增加统一动效,脚本与样式使用带内容标识的地址,减少更新后的缓存混用。

更新 App 并刷新页面即可使用相应改进,无需迁移配置或房间数据。Windows 10 音频排除是否可用取决于系统能力。

### English

This update improves sharing controls and compatibility. Windows App users can change audio exclusion during a share, and sharing failures now provide clearer guidance and a direct troubleshooting entry.

#### Improvements

- Change system sound and the excluded application under **Sharing settings → Sound** without stopping the share. Supported Windows 10 installations can also expose exclusion after the capability check.
- Sharing failures retain their specific cause. Select the status below the TV for recovery suggestions, diagnostics and the relevant troubleshooting guide.
- Updated English and Chinese guides cover App connectivity, source selection and encoding, site-address configuration, restricted networks and Browser HDR limitations.

#### Fixes

- Fixed source lists failing with many windows or long titles, and certain independent application windows being omitted.
- Improved Windows capture transitions when a window is minimized and restored.
- Fixed stale Firefox codec attributes disrupting connections and aligned native receiver preflight with its supported formats.
- Refresh gateway port mappings for new ICE gatherings instead of reusing stale results, and validate H.264 input before native decoding.
- Added consistent motion to website architecture selection and content-hashed script/style URLs to prevent mixed cached versions.

Update the App and reload the page to use the relevant improvements. No configuration or room-data migration is required. Windows 10 audio exclusion depends on actual system capability.
2026-10-06 02:24:15 +08:00

586 lines
24 KiB
TypeScript

import { afterEach, expect, it, vi } from "vitest";
import type { SignalPayload } from "../src/shared/protocol";
import type { NativeClient } from "../src/client/native/client";
import { NativeMediaBridge } from "../src/client/native/media-bridge";
import { VIEWER_AUTOMATIC_RECOVERY_TIMEOUT_MS, ViewerPeer } from "../src/client/webrtc/viewer-peer";
import { EMPTY_METRICS, type PeerSnapshot } from "../src/client/types";
import type { NativeClientEvent } from "../src/client/native/wire";
import {
NativeCapableViewerPeer,
offerHasNativeVideoCodec,
} from "../src/client/native/native-viewer-peer";
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
it("retires queued candidates when disposed during their delivery", async () => {
vi.stubGlobal("window", globalThis);
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
let finishCandidate!: () => void;
const accept = vi.spyOn(ViewerPeer.prototype, "acceptSignal").mockImplementation(
async (_parent, payload) => {
if (payload.kind === "candidate") {
await new Promise<void>(resolve => { finishCandidate = resolve; });
}
},
);
const peer = new NativeCapableViewerPeer(
{ iceServers: [] },
{
sendSignal: () => true, sendRestartRequest: () => true,
onStream: () => undefined, onUpdate: () => undefined,
},
{}, async () => null, () => undefined, "session", 2,
);
try {
for (const port of [5000, 5001]) {
await peer.acceptSignal("parent", {
kind: "candidate", connectionId: "current",
candidate: { candidate: `candidate:1 1 UDP 2122260223 192.0.2.1 ${port} typ host` },
});
}
const accepting = peer.acceptSignal("parent", {
kind: "description", connectionId: "current",
description: { type: "offer", sdp: "v=0\r\n" },
});
await vi.waitFor(() => expect(accept).toHaveBeenCalledTimes(2));
peer.dispose();
finishCandidate();
await expect(accepting).resolves.toBeUndefined();
expect(accept).toHaveBeenCalledTimes(2);
} finally {
peer.dispose();
}
});
it.each(["viewer", "route"] as const)("retires a connected Native receiver on control loss (%s)", async (recoveryOwner) => {
vi.useFakeTimers();
vi.stubGlobal("window", globalThis);
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
vi.stubGlobal("RTCPeerConnection", class { close() {} });
vi.spyOn(NativeMediaBridge.prototype, "start").mockResolvedValue({} as MediaStream);
vi.spyOn(NativeMediaBridge.prototype, "collectMetrics").mockResolvedValue({ ...EMPTY_METRICS });
vi.spyOn(NativeMediaBridge.prototype, "decodedVideoFrames").mockResolvedValue(null);
let onEvent!: (event: NativeClientEvent) => void;
let onClose!: () => void;
const client = {
receiveOffer: async () => ({
answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8",
}),
onEvent: (handler: typeof onEvent) => { onEvent = handler; return () => undefined; },
onClose: (handler: typeof onClose) => { onClose = handler; return () => undefined; },
closeReceiver: vi.fn(async () => undefined),
closeEdge: vi.fn(async () => undefined),
} as unknown as NativeClient;
const unavailable = vi.fn();
const restart = vi.fn(() => true);
const exhausted = vi.fn(() => true);
const updates: PeerSnapshot[] = [];
const peer = new NativeCapableViewerPeer(
{ iceServers: [] },
{
sendSignal: () => true, sendRestartRequest: restart,
onStream: () => undefined, onUpdate: (value) => updates.push(value),
onRecoveryExhausted: exhausted,
},
{ recoveryOwner }, async () => client, unavailable, "session", 2,
);
try {
await peer.acceptSignal("parent", {
kind: "description", connectionId: "current",
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
});
const connected = {
version: 9, shareId: "session", connectionId: "current", type: "edge-state", state: "connected",
} as const;
onEvent(connected);
expect(peer.isConnected()).toBe(true);
expect(peer.nativeSource).not.toBeNull();
onClose();
expect(peer.isConnected()).toBe(false);
expect(peer.nativeSource).toBeNull();
expect(updates.at(-1)?.connectionState).toBe("failed");
// A queued event cannot revive the receiver that owns the dead bridge.
onEvent(connected);
onClose();
expect(peer.isConnected()).toBe(false);
expect(unavailable).toHaveBeenCalledOnce();
if (recoveryOwner === "viewer") {
expect(restart).toHaveBeenCalledExactlyOnceWith("parent", "current", true);
expect(exhausted).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(VIEWER_AUTOMATIC_RECOVERY_TIMEOUT_MS);
} else {
expect(restart).not.toHaveBeenCalled();
}
expect(exhausted).toHaveBeenCalledExactlyOnceWith("parent", "current");
} finally {
peer.dispose();
}
});
it.each([false, true])("ignores a late Native offer after control loss (disposed=%s)", async (disposeOnFailure) => {
vi.useFakeTimers();
vi.stubGlobal("window", globalThis);
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
vi.stubGlobal("RTCPeerConnection", class { close() {} });
const bridgeStart = vi.spyOn(NativeMediaBridge.prototype, "start").mockResolvedValue({} as MediaStream);
let resolveOffer!: (value: Awaited<ReturnType<NativeClient["receiveOffer"]>>) => void;
const receiveOffer = vi.fn(() => new Promise<Awaited<ReturnType<NativeClient["receiveOffer"]>>>((resolve) => {
resolveOffer = resolve;
}));
let onClose!: () => void;
const closeReceiver = vi.fn(async () => undefined);
const client = {
receiveOffer,
onEvent: () => () => undefined,
onClose: (handler: typeof onClose) => { onClose = handler; return () => undefined; },
closeReceiver, closeEdge: vi.fn(async () => undefined),
} as unknown as NativeClient;
const sendSignal = vi.fn(() => true);
const onStream = vi.fn();
const restart = vi.fn(() => true);
const unavailable = vi.fn();
const updates: PeerSnapshot[] = [];
let peer!: NativeCapableViewerPeer;
peer = new NativeCapableViewerPeer(
{ iceServers: [] },
{
sendSignal, sendRestartRequest: restart, onStream,
onUpdate: (value) => {
updates.push(value);
if (disposeOnFailure && value.connectionState === "failed") peer.dispose();
},
},
{}, async () => client, unavailable, "session", 2,
);
try {
const accepting = peer.acceptSignal("parent", {
kind: "description", connectionId: "current",
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
});
await vi.waitFor(() => expect(receiveOffer).toHaveBeenCalledOnce());
onClose();
resolveOffer({ answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8", reused: false });
await accepting;
expect(updates.at(-1)?.connectionState).toBe("failed");
expect(peer.isConnected()).toBe(false);
expect(peer.nativeSource).toBeNull();
expect(closeReceiver).toHaveBeenCalledWith("session", "current");
expect(sendSignal).not.toHaveBeenCalled();
expect(onStream).not.toHaveBeenCalled();
expect(bridgeStart).not.toHaveBeenCalled();
expect(unavailable).toHaveBeenCalledOnce();
expect(restart).toHaveBeenCalledTimes(disposeOnFailure ? 0 : 1);
} finally {
peer.dispose();
}
});
it.each(["reused", "replaced", "answer-lost", "control-lost"])("keeps Native receiver lifetimes coherent through renegotiation (%s)", async (outcome) => {
vi.useFakeTimers();
vi.stubGlobal("window", globalThis);
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
vi.stubGlobal("RTCPeerConnection", class { close() {} });
const bridges: NativeMediaBridge[] = [];
const bridgeStart = vi.spyOn(NativeMediaBridge.prototype, "start").mockImplementation(async function (this: NativeMediaBridge) {
bridges.push(this);
return {} as MediaStream;
});
let closeControl!: () => void;
let event!: (event: NativeClientEvent) => void;
const receiveOffer = vi.fn(async () => ({
answer: { type: "answer" as const, sdp: "answer-sdp" }, audio: false, codec: "vp8" as const, reused: false,
}));
const closeReceiver = vi.fn(async () => undefined);
const closeEdge = vi.fn(async () => undefined);
const client = {
health: { nativeMedia: { receiverReuse: true } }, receiveOffer, closeReceiver, closeEdge,
onEvent: (listener: typeof event) => { event = listener; return () => {}; },
onClose: (listener: typeof closeControl) => { closeControl = listener; return () => {}; },
} as unknown as NativeClient;
const sendSignal = vi.fn(() => true);
const onStream = vi.fn();
const unavailable = vi.fn();
const peer = new NativeCapableViewerPeer({ iceServers: [] }, {
sendSignal, sendRestartRequest: () => true, onStream, onUpdate: () => {},
}, {}, async () => client, unavailable, "session", 2);
const offer = (ice: string): SignalPayload => ({
kind: "description", connectionId: "current", description: { type: "offer",
sdp: `v=0\r\na=ice-ufrag:${ice}\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n` },
});
try {
await peer.acceptSignal("parent", offer("first"));
event({ version: 9, type: "edge-state", shareId: "session", connectionId: "current", state: "connected" });
const source = peer.nativeSource;
receiveOffer.mockImplementationOnce(async () => {
if (outcome === "replaced") {
// Replacement closes the old local edge before its answer reaches JS.
(bridges[0] as unknown as { onFailed(): void }).onFailed();
}
if (outcome === "control-lost") closeControl();
return { answer: { type: "answer", sdp: "new-answer-sdp" }, audio: false, codec: "vp8", reused: outcome !== "replaced" };
});
if (outcome === "answer-lost") sendSignal.mockReturnValue(false);
await peer.acceptSignal("parent", offer("restarted"));
expect(receiveOffer).toHaveBeenCalledTimes(2);
if (outcome === "control-lost") {
expect(peer.nativeSource).toBeNull();
expect(unavailable).toHaveBeenCalledOnce();
} else {
expect(closeReceiver).not.toHaveBeenCalled();
expect(unavailable).not.toHaveBeenCalled();
expect(bridgeStart).toHaveBeenCalledTimes(outcome === "replaced" ? 2 : 1);
expect(onStream).toHaveBeenCalledTimes(outcome === "replaced" ? 2 : 1);
expect(peer.nativeSource?.generation).toBe(source!.generation + (outcome === "replaced" ? 1 : 0));
if (outcome !== "replaced") {
expect(closeEdge).not.toHaveBeenCalled();
expect(peer.isConnected()).toBe(true);
}
}
} finally { peer.dispose(); }
});
it("admits one active sending H264 or VP8 video section, not unrelated SDP codec text", () => {
const video = (codec: string, direction = "sendonly", port = 9, payload = 96) => [
`m=video ${port} UDP/TLS/RTP/SAVPF ${payload}`,
`a=${direction}`,
`a=rtpmap:96 ${codec}/90000`,
"a=fmtp:96 profile-level-id=42e01f;packetization-mode=1",
"",
].join("\r\n");
expect(offerHasNativeVideoCodec(video("H264"))).toBe(true);
expect(offerHasNativeVideoCodec(video("VP8"))).toBe(true);
expect(offerHasNativeVideoCodec(video("VP8", "sendrecv"))).toBe(true);
expect(offerHasNativeVideoCodec("a=group:BUNDLE 0\r\n" +
video("VP8", "sendonly", 0) + "a=bundle-only\r\na=mid:0\r\n")).toBe(true);
expect(offerHasNativeVideoCodec("m=video 9 UDP/TLS/RTP/SAVPF 96 97\r\n" +
"a=sendonly\r\na=rtpmap:96 H264/90000\r\na=rtpmap:97 VP8/90000\r\n")).toBe(true);
for (const offer of [
video("VP8", "recvonly"), video("VP8", "inactive"),
video("VP8", "sendonly", 0), video("VP8", "sendonly", 9, 97),
video("VP8", "sendonly", 0) + "a=bundle-only\r\na=mid:0\r\n",
video("VP9"), video("H264") + video("VP8"),
"m=audio 9 UDP/TLS/RTP/SAVPF 96\r\na=rtpmap:96 VP8/90000\r\n",
]) expect(offerHasNativeVideoCodec(offer)).toBe(false);
});
it.each([
["42e01f", "1", true], ["42c01f", "1", true],
["4de01f", "1", true], ["58c01f", "1", true],
["42e00b", "1", true], ["42e033", "1", true], ["42e034", "1", false],
["4d001f", "1", false], ["64001f", "1", false], ["42001f", "1", false],
["42e11f", "1", false], ["42e035", "1", false], ["42e03c", "1", false],
["42e01f=invalid", "1", false],
["", "1", false], ["42e01f", "0", false], ["42e01f", "", false],
])("matches Native H264 forwarding admission: profile=%s, packetization=%s", (profile, mode, supported) => {
const offer = "m=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\n" +
"a=rtpmap:96 H264/90000\r\n" +
`a=fmtp:96 profile-level-id=${profile};packetization-mode=${mode}\r\n`;
expect(offerHasNativeVideoCodec(offer)).toBe(supported);
});
it("sends an unsupported Native format straight to the Browser without failing the App", async () => {
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
const browserSignal = vi.spyOn(ViewerPeer.prototype, "acceptSignal").mockResolvedValue();
const acquire = vi.fn(async () => null);
const unavailable = vi.fn();
const restart = vi.fn(() => true);
const peer = new NativeCapableViewerPeer({ iceServers: [] }, {
sendSignal: () => true, sendRestartRequest: restart,
onStream: () => undefined, onUpdate: () => undefined,
}, {}, acquire, unavailable, "session", 2);
const offer: SignalPayload = { kind: "description", connectionId: "current", description: {
type: "offer", sdp: "m=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\n" +
"a=rtpmap:96 H264/90000\r\na=fmtp:96 profile-level-id=64001f;packetization-mode=1\r\n",
}};
try {
await peer.acceptSignal("parent", offer);
expect(browserSignal).toHaveBeenCalledExactlyOnceWith("parent", offer);
expect(acquire).not.toHaveBeenCalled();
expect(unavailable).not.toHaveBeenCalled();
expect(restart).not.toHaveBeenCalled();
} finally { peer.dispose(); }
});
it("does not create a browser backend after deferred native discovery is disposed", async () => {
let resolveClient: (value: null) => void = () => undefined;
const nativeClient = new Promise<null>((resolve) => {
resolveClient = resolve;
});
const peer = new NativeCapableViewerPeer(
{ iceServers: [] },
{
sendSignal: () => true,
sendRestartRequest: () => true,
onStream: () => undefined,
onUpdate: () => undefined,
},
{},
() => nativeClient,
() => undefined,
"session",
2,
);
const accepted = peer.acceptSignal("parent", {
kind: "description",
connectionId: "connection",
description: {
type: "offer",
sdp: [
"v=0",
"m=video 9 UDP/TLS/RTP/SAVPF 96",
"a=sendonly",
"a=rtpmap:96 H264/90000",
"",
].join("\r\n"),
},
});
peer.dispose();
resolveClient(null);
await accepted;
expect(peer.getConnectionIdentity()).toBeNull();
});
it.each(["route", "viewer"] as const)("recovers an answer signaling failure without disabling native (%s)", async (recoveryOwner) => {
vi.stubGlobal("window", globalThis);
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
vi.stubGlobal("RTCPeerConnection", class { close() {} });
const receiveOffer = vi.fn(async () => ({
answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8",
}));
const closeReceiver = vi.fn(async () => undefined);
const client = {
receiveOffer,
onEvent: () => () => undefined,
onClose: () => () => undefined,
closeReceiver,
closeEdge: vi.fn(async () => undefined),
} as unknown as NativeClient;
let available = true;
const acquire = vi.fn(async () => available ? client : null);
const unavailable = vi.fn(() => { available = false; });
const restart = vi.fn(() => true);
const exhausted = vi.fn(() => true);
let signalOnline = false;
const peer = new NativeCapableViewerPeer(
{ iceServers: [] },
{
sendSignal: () => signalOnline,
sendRestartRequest: restart,
onStream: () => undefined,
onUpdate: () => undefined,
onRecoveryExhausted: exhausted,
},
{ recoveryOwner },
acquire,
unavailable,
"session",
2,
);
const offer = (connectionId: string): SignalPayload => ({
kind: "description", connectionId,
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
});
try {
// A transient room-signaling outage at the answer must not disable
// Native reception for the session: close only this receiver and run
// the ordinary recovery path.
await peer.acceptSignal("parent", offer("first"));
expect(unavailable).not.toHaveBeenCalled();
expect(peer.nativeSource).toBeNull();
expect(closeReceiver).toHaveBeenCalledWith("session", "first");
if (recoveryOwner === "viewer") {
expect(restart).toHaveBeenCalledWith("parent", "first", true);
expect(exhausted).not.toHaveBeenCalled();
} else {
expect(exhausted).toHaveBeenCalledWith("parent", "first");
expect(restart).not.toHaveBeenCalled();
}
// With signaling back online, the next offer re-acquires the native path.
signalOnline = true;
vi.spyOn(NativeMediaBridge.prototype, "start").mockResolvedValue(
new (class {})() as never,
);
await peer.acceptSignal("parent", offer("second"));
expect(acquire).toHaveBeenCalledTimes(2);
expect(receiveOffer).toHaveBeenCalledTimes(2);
expect(unavailable).not.toHaveBeenCalled();
} finally {
peer.dispose();
}
});
it("still disables native on a genuine failure after a signaling failure", async () => {
vi.stubGlobal("window", globalThis);
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
vi.stubGlobal("RTCPeerConnection", class { close() {} });
let eventHandler: ((event: unknown) => void) | null = null;
const receiveOffer = vi.fn(async () => ({
answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8",
}));
const client = {
receiveOffer,
onEvent: (handler: (event: unknown) => void) => {
eventHandler = handler;
return () => undefined;
},
onClose: () => () => undefined,
closeReceiver: vi.fn(async () => undefined),
closeEdge: vi.fn(async () => undefined),
} as unknown as NativeClient;
const unavailable = vi.fn();
const peer = new NativeCapableViewerPeer(
{ iceServers: [] },
{
sendSignal: () => false,
sendRestartRequest: () => true,
onStream: () => undefined,
onUpdate: () => undefined,
onRecoveryExhausted: () => true,
},
{},
async () => client,
unavailable,
"session",
2,
);
try {
await peer.acceptSignal("parent", {
kind: "description",
connectionId: "first",
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
});
expect(unavailable).not.toHaveBeenCalled();
// A genuine native failure on the same connection must still disable
// Native for the session: the signaling path must not have latched the
// failure state.
eventHandler!({ shareId: "session", type: "share-ended", failed: true });
expect(unavailable).toHaveBeenCalledOnce();
} finally {
peer.dispose();
}
});
it.each([
["route", "initialize"], ["route", "start"],
["viewer", "initialize"], ["viewer", "start"],
] as const)("keeps %s bridge %s failure unavailable across replacement peers", async (recoveryOwner, failureStage) => {
vi.stubGlobal("window", globalThis);
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
vi.stubGlobal("RTCPeerConnection", class {
constructor() { if (failureStage === "initialize") throw new DOMException("Peer unavailable", "NotSupportedError"); }
close() {}
});
const browserSignal = vi.spyOn(ViewerPeer.prototype, "acceptSignal").mockResolvedValue();
const bridgeStart = vi.spyOn(NativeMediaBridge.prototype, "start").mockRejectedValue(new Error("bridge failed"));
const receiveOffer = vi.fn(async () => ({
answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8",
}));
const client = {
receiveOffer,
onEvent: () => () => undefined,
onClose: () => () => undefined,
closeReceiver: vi.fn(async () => undefined),
closeEdge: vi.fn(async () => undefined),
} as unknown as NativeClient;
let available = true;
const acquire = vi.fn(async () => available ? client : null);
const unavailable = vi.fn(() => { available = false; });
const recover = vi.fn(() => {
expect(available).toBe(false);
return true;
});
const create = () => new NativeCapableViewerPeer(
{ iceServers: [] },
{
sendSignal: () => true,
sendRestartRequest: recover,
onStream: () => undefined,
onUpdate: () => undefined,
onRecoveryExhausted: recover,
},
{ recoveryOwner },
acquire,
unavailable,
"session",
2,
);
const offer = (connectionId: string): SignalPayload => ({
kind: "description", connectionId,
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
});
const first = create();
const queued = create();
try {
await first.acceptSignal("parent", offer("first"));
await vi.waitFor(() => expect(unavailable).toHaveBeenCalledOnce());
expect(recover).toHaveBeenCalledOnce();
first.dispose();
await queued.acceptSignal("parent", offer("queued"));
expect(browserSignal).toHaveBeenCalledOnce();
const replacement = create();
try {
await replacement.acceptSignal("parent", offer("replacement"));
expect(browserSignal).toHaveBeenCalledTimes(2);
expect(receiveOffer).toHaveBeenCalledOnce();
expect(bridgeStart).toHaveBeenCalledTimes(failureStage === "initialize" ? 0 : 1);
expect(acquire).toHaveBeenCalledTimes(3);
} finally {
replacement.dispose();
}
} finally {
first.dispose();
queued.dispose();
}
});
it.each([false, true])("keeps committed route recovery across backend replacement (replaced=%s)", async (replaced) => {
vi.useFakeTimers();
vi.stubGlobal("window", globalThis);
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
vi.stubGlobal("RTCPeerConnection", class { close() {} });
vi.spyOn(NativeMediaBridge.prototype, "start").mockResolvedValue({} as MediaStream);
vi.spyOn(NativeMediaBridge.prototype, "collectMetrics").mockResolvedValue({ ...EMPTY_METRICS });
vi.spyOn(NativeMediaBridge.prototype, "decodedVideoFrames").mockResolvedValue(null);
let onEvent!: (event: NativeClientEvent) => void;
const client = {
receiveOffer: async () => ({ answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8" }),
onEvent: (fn: typeof onEvent) => { onEvent = fn; return () => undefined; },
onClose: () => () => undefined,
closeReceiver: vi.fn(async () => undefined), closeEdge: vi.fn(async () => undefined),
} as unknown as NativeClient;
const restart = vi.fn(() => true);
const exhausted = vi.fn(() => true);
const options = { recoveryOwner: "route" as const };
const peer = new NativeCapableViewerPeer({ iceServers: [] }, {
sendSignal: () => true, sendRestartRequest: restart,
onStream: () => undefined, onUpdate: () => undefined, onRecoveryExhausted: exhausted,
}, options, async () => client, () => undefined, "session", 2);
const offer = (connectionId: string) => ({ kind: "description" as const, connectionId,
description: { type: "offer" as const, sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" }});
const state = (connectionId: string, value: "connected" | "failed") => onEvent({
version: 9, shareId: "session", connectionId, type: "edge-state", state: value,
});
try {
await peer.acceptSignal("parent", offer("first"));
state("first", "connected");
peer.activatePreparedRoute();
expect(options.recoveryOwner).toBe("route"); // Caller options are not mutable route state.
const connectionId = replaced ? "replacement" : "first";
if (replaced) {
await peer.acceptSignal("parent", offer(connectionId));
state(connectionId, "connected");
}
state(connectionId, "failed");
expect(restart).toHaveBeenCalledExactlyOnceWith("parent", connectionId, false);
expect(exhausted).not.toHaveBeenCalled();
} finally { peer.dispose(); }
});