Files
piik/tests/native-capture-selection.test.ts
T
AAA 42588f3a8b fix(media): stabilize reconnects and quality recovery
This maintenance phase corrects connection and media recovery after startup deadlines, congestion and packet loss. Route selection remains a bounded operation; Pion and LiveKit continue to own congestion control, adaptation and retransmission.

Changes stay within existing owners:

- Preserve an untried SFU fallback when a connected P2P candidate produces no first frame before its deadline. Retire expired native preparations using the current edge identity.
- Correct paced output, probe accounting and partial-recovery demand. Negotiate RTX consistently for native forwarding and SFU publication, including repaired stream identifiers for simulcast.
- Return working IPv4 mappings without waiting for optional IPv6 work, and separate NAT observations by the local socket/address that produced them.
- Keep optional App availability separate from basic source selection; stabilize nickname/chat layouts and restore volume from zero correctly.
- Retry complete Gitee reads, including response bodies and hash verification. Ambiguous uploads remain single attempts and are reconciled against the remote inventory before rerunning.

Related: #468, #464, #471. The repairs affect paths discussed in these reports; incomplete field diagnostics do not establish that each report has the same cause, so this PR does not automatically close them.

## Validation

- Web type checks, production build and 1,624 tests passed. Go core, formatting, vet and local target builds passed.
- Delayed RTX recovery reproduced the defect before the fix; the repaired-SSRC mutation also fails the focused regression. Real Windows H.264 and VP8 capture passed the SFU gates, including settings, reload recovery and retirement.
- The media lifecycle gate passed all 14 trials across Browser/App pairings and P2P/SFU handoffs. Native connectivity, paced forwarding and negative-control checks passed.
- Responsive UI and current website architecture links were checked; Gitee's current release was independently downloaded and matched against the GitHub originals.
- [Platform candidate](https://github.com/TNTcraftHIM/Piik/actions/runs/38669095115): all five Apps, both Server architectures and container checks passed at `c534573b`. Subsequent tracked changes only update documentation, the complete-matrix CI budget and race-test coverage.
- [Full network comparison](https://github.com/TNTcraftHIM/Piik/actions/runs/38667624364) completed 70 trials before the batch's 45-minute limit. The [remaining scenario](https://github.com/TNTcraftHIM/Piik/actions/runs/38672805155) passed three paired repetitions; all 71 scenario/setting variants are covered, with 58 media and 13 expected/observed unavailable outcomes. Six negative controls passed, and owned resources were cleaned up. These are controlled observations, not a public success rate.
- The final validation also includes the shared forwarder under the Go race detector. The separate sole-active-output publication experiment still shows inconsistent recovery: two of four current-code repeats did not pass its recovery observation, so the limitation below remains open.

The native SFU allocator still has a measured recovery limitation when only its lowest rate-controlled encoding is active. Fixing that requires a supported upstream demand input; no second controller or allocator fork is introduced. Unmatched capture-failure reports and physical-platform coverage retain their documented evidence limits.

## Release notes

### 中文

这是一次连接与播放稳定性更新,重点改善重连、弱网后的画质恢复和下载镜像可靠性。与 Piik 2.0.0 保持兼容。

- 修复连接等待超时后过早跳过备用线路的问题,保留尚未尝试的媒体服务器兜底机会。
- 改善原生分享在网络拥塞后的画质恢复,并修复转发和媒体服务器发布链路上的视频重传协商遗漏。
- 修复原生观看准备超时后的清理与重试,以及音量从零恢复时的异常。
- 避免可选的 IPv6 端口映射拖慢 IPv4 准备,并修正多网卡环境下的 NAT 预测观测归属。
- 修复昵称编辑、聊天字数变化引起的布局移动;保持 App 提示简洁,并为更新提示补充官网备用下载入口。
- 修复 Gitee 镜像同步在传输中途断开时未重试的问题,校验通过后才完成镜像发布。

仍在跟进:部分原生媒体服务器链路的弱网后恢复仍可能偏慢;尚缺匹配诊断的采集失败反馈不能确认已解决。

### English

This maintenance update improves connection and playback recovery after interruptions and congestion, along with download-mirror reliability. It remains compatible with Piik 2.0.0.

- Preserve untried media-server fallback routes when a connection reaches its waiting deadline.
- Improve native sharing quality recovery after congestion and fix missing video retransmission negotiation in forwarding and media-server publication paths.
- Correct cleanup and retry after native viewing preparation expires, and restore playback volume correctly from zero.
- Prevent optional IPv6 port mapping from delaying IPv4 preparation, and associate NAT-prediction observations with the correct local interface.
- Stabilize nickname editing and chat counters, keep App guidance unobtrusive, and add the website's alternate downloads to update notices.
- Retry interrupted Gitee mirror transfers and complete publication only after verification succeeds.

Still under investigation: recovery after congestion can remain slow on some native media-server paths. Capture-failure reports without matching diagnostics are not claimed as resolved.
2026-10-14 22:57:17 -04:00

262 lines
12 KiB
TypeScript

import { afterEach, describe, expect, it } from "vitest";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { CaptureSourcePicker } from "../src/client/components/living/CaptureSourcePicker";
import { AudioExclusionSelect } from "../src/client/components/living/AudioExclusionSelect";
import { CameraSources } from "../src/client/components/living/CameraSources";
import { setCopy, t } from "../src/client/ui/copy";
import {
defaultNativeCapturePath,
nativeCaptureTargetKey,
} from "../src/client/native/capture-selection";
import type {
NativeAdapter,
NativeCaptureTarget,
} from "../src/client/native/wire";
function target(
title: string,
sourceId: string,
): Extract<NativeCaptureTarget, { kind: "window" }> {
return {
kind: "window",
title,
sourceId,
pid: 10,
creationTime: "123456",
};
}
describe("native capture source selection", () => {
const game = target("My Game", "1");
afterEach(() => setCopy({ lang: "en", vis: true }));
it("keeps enumerated cameras selectable while optional thumbnails load", () => {
const props = {
sources: [{ id: "front", label: "Front camera", preview: null }],
busy: true, error: null, selected: "", onSelect: () => {},
};
const html = renderToStaticMarkup(createElement(CameraSources, { ...props, disabled: false }));
expect(html).toContain('data-camera-source="front"');
expect(html).not.toContain('disabled=""');
expect(renderToStaticMarkup(createElement(CameraSources, { ...props, disabled: true })))
.toContain('disabled=""');
});
it.each(["en", "zh", "vis"] as const)("keeps Browser capture reachable with an actionable App mismatch in %s", (mode) => {
const lang = mode === "zh" ? "zh" : "en";
setCopy({ lang, vis: mode === "vis" });
const props = {
nativeSources: { kind: "incompatible" },
onBrowser: () => {}, onNative: () => {}, onPreview: async () => null,
onRefresh: () => {}, onCancel: () => {},
} as const;
const html = renderToStaticMarkup(createElement(CaptureSourcePicker, { ...props, initialTab: "browser" }));
expect(html).not.toContain(t(lang, "native.incompatible"));
expect(html).toContain(`aria-label="${t(lang, "host.sourcePicker.browser")}"`);
expect(html).not.toMatch(/data-source-tab="browser"[^>]*disabled=""/);
expect(html).not.toContain(t(lang, "host.sourcePicker.empty"));
expect(html).not.toContain('role="status"');
const nativeTab = renderToStaticMarkup(createElement(CaptureSourcePicker, { ...props, initialTab: "window" }));
expect(nativeTab).toContain(t(lang, "native.incompatible"));
expect(nativeTab).toContain('role="status"');
});
it("uses the complete window identity as the UI key", () => {
expect(nativeCaptureTargetKey(game)).toBe("window:1:10:123456");
expect(
nativeCaptureTargetKey({ ...game, creationTime: "654321" }),
).not.toBe(nativeCaptureTargetKey(game));
expect(
nativeCaptureTargetKey({
kind: "display",
sourceId: "2",
title: "Display 1",
}),
).toBe("display:2");
});
it("keeps a missing exclusion selected and distinguishes a restarted process", () => {
setCopy({ lang: "en", vis: false });
const restarted = { ...game, creationTime: "654321" };
const html = renderToStaticMarkup(createElement(AudioExclusionSelect, {
sources: [restarted, { ...restarted, sourceId: "2" }],
value: game, onChange: () => {},
}));
expect(html).toMatch(/<option value="10:123456" disabled="" selected="">/);
expect(html.match(/<option value="10:654321"/g)).toHaveLength(1);
expect(html).not.toMatch(/<option value="" selected="">/);
});
it.each(["unavailable", "unsupported", "failed"] as const)("does not describe %s as an empty list or block Browser capture", (kind) => {
for (const mode of ["en", "zh", "vis"] as const) {
const lang = mode === "zh" ? "zh" : "en";
setCopy({ lang, vis: mode === "vis" });
const props = {
nativeSources: { kind }, onBrowser: () => {}, onNative: () => {},
onPreview: async () => null, onRefresh: () => {}, onCancel: () => {},
};
const nativeTab = renderToStaticMarkup(createElement(CaptureSourcePicker, props));
if (kind === "unavailable") {
expect(nativeTab).not.toContain('data-source-tab="window"');
expect(nativeTab).not.toContain('data-source-tab="display"');
expect(nativeTab).toMatch(/data-source-tab="browser"[^>]*aria-selected="true"/);
}
if (kind === "unavailable") expect(nativeTab).not.toContain('role="status"');
else expect(nativeTab.replaceAll("&#x27;", "'")).toContain(t(lang, `host.sourcePicker.${kind}`));
expect(nativeTab).not.toContain(t(lang, "host.sourcePicker.empty"));
expect(nativeTab).not.toMatch(/class="lr-source-picker-refresh"[^>]*disabled=""/);
const browserTab = renderToStaticMarkup(createElement(CaptureSourcePicker, { ...props, initialTab: "browser" }));
expect(browserTab).toContain(`aria-label="${t(lang, "host.sourcePicker.browser")}"`);
const browserCopy = browserTab.replaceAll("&#x27;", "'");
expect(browserCopy).not.toContain('role="status"');
expect(browserTab).not.toMatch(/class="lr-source-option is-browser"[^>]*disabled=""/);
}
});
it.each(["browser", "window"] as const)("keeps Browser and Camera reachable during discovery with initial %s preference", initialTab => {
setCopy({ lang: "en", vis: false });
const html = renderToStaticMarkup(createElement(CaptureSourcePicker, {
nativeSources: { kind: "loading" }, initialTab,
onBrowser: () => {}, onNative: () => {}, onPreview: async () => null,
onRefresh: () => {}, onCancel: () => {},
}));
expect(html).toMatch(/data-source-tab="browser"[^>]*aria-selected="true"/);
expect(html).not.toContain('data-source-tab="window"');
expect(html).not.toContain("lr-brand-loader");
expect(html).not.toMatch(/class="lr-source-picker-close"[^>]*disabled=""/);
});
it("separates windows from displays and locks Browser switching during native sharing", () => {
const html = renderToStaticMarkup(createElement(CaptureSourcePicker, {
nativeSources: {
kind: "ready",
sources: [game, { kind: "display", sourceId: "2", title: "Display 1" }],
processAudio: false,
systemAudio: true,
},
browserAvailable: false,
audioLocked: true,
onBrowser: () => {},
onNative: () => {},
onPreview: async () => null,
onRefresh: () => {},
onCancel: () => {},
}));
expect(html).toContain('data-source-tab="browser"');
expect(html).toMatch(/data-source-tab="browser"[^>]*disabled=""/);
expect(html).toMatch(/data-native-source="window:1:10:123456"[^>]*disabled=""/);
expect(html).not.toContain('data-native-source="display:2"');
expect(html.match(/role="tab"/g)).toHaveLength(4);
expect([...html.matchAll(/data-source-tab="([^"]+)"/g)].map((match) => match[1]))
.toEqual(["browser", "camera", "window", "display"]);
expect(html).toMatch(/data-source-tab="window"[^>]*aria-selected="true"/);
});
it("offers only Browser and Camera without an App, defaulting to Browser", () => {
setCopy({ lang: "en", vis: false });
const html = renderToStaticMarkup(createElement(CaptureSourcePicker, {
nativeSources: { kind: "browser" }, onBrowser: () => {}, onCamera: () => {},
onNative: () => {}, onPreview: async () => null, onRefresh: () => {}, onCancel: () => {},
}));
expect([...html.matchAll(/data-source-tab="([^"]+)"/g)].map((match) => match[1]))
.toEqual(["browser", "camera"]);
expect(html).toMatch(/data-source-tab="browser"[^>]*aria-selected="true"/);
expect(html).not.toMatch(/data-source-tab="camera"[^>]*disabled=""/);
expect(html).not.toContain('role="status"');
});
it("selects a focusable Camera tab when Browser sharing is unavailable", () => {
const html = renderToStaticMarkup(createElement(CaptureSourcePicker, {
nativeSources: { kind: "browser" }, browserAvailable: false,
onBrowser: () => {}, onCamera: () => {}, onNative: () => {},
onPreview: async () => null, onRefresh: () => {}, onCancel: () => {},
}));
expect(html).toMatch(/data-source-tab="camera"[^>]*aria-selected="true"[^>]*tabindex="0"/);
expect(html).toMatch(/data-source-tab="browser"[^>]*tabindex="-1"[^>]*disabled=""/);
});
it("retains the platform-owned combined source picker", () => {
const html = renderToStaticMarkup(createElement(CaptureSourcePicker, {
nativeSources: {
kind: "ready",
sources: [{ kind: "picker", sourceId: "1", title: "System picker" }],
processAudio: false,
systemAudio: true,
},
onBrowser: () => {},
onNative: () => {},
onPreview: async () => null,
onRefresh: () => {},
onCancel: () => {},
}));
expect(html).toContain('data-native-source="picker:1"');
expect(html).toContain('aria-checked="true"');
});
it.each(["browser", "window"] as const)("blocks %s confirmation during owning page work while retaining cancel", (initialTab) => {
setCopy({ lang: "en", vis: false });
const html = renderToStaticMarkup(createElement(CaptureSourcePicker, {
nativeSources: { kind: "ready", sources: [game], processAudio: false, systemAudio: false },
initialTab, selectionDisabled: true,
onBrowser: () => {}, onNative: () => {}, onPreview: async () => null,
onRefresh: () => {}, onCancel: () => {},
}));
expect(html).toMatch(/class="lr-source-option(?: is-browser)?"[^>]*disabled=""/);
expect(html).not.toMatch(/class="lr-source-picker-close"[^>]*disabled=""/);
});
it.each(["en", "zh", "vis"] as const)("offers the requested border preference only for supported native capture in %s", (mode) => {
const lang = mode === "zh" ? "zh" : "en";
setCopy({ lang, vis: mode === "vis" });
const render = (supported: boolean | undefined, initialTab: "window" | "display" | "browser", initialShowCaptureBorder?: boolean) =>
renderToStaticMarkup(createElement(CaptureSourcePicker, {
nativeSources: { kind: "ready", sources: [game], processAudio: true, systemAudio: true, captureBorderControl: supported },
initialTab, initialShowCaptureBorder,
onBrowser: () => {}, onNative: () => {}, onPreview: async () => null,
onRefresh: () => {}, onCancel: () => {},
}));
const label = t(lang, "host.sourcePicker.showCaptureBorder");
for (const tab of ["window", "display"] as const) {
expect(render(true, tab)).toContain(`aria-checked="false" aria-label="${label}"`);
expect(render(true, tab, true)).toContain(`aria-checked="true" aria-label="${label}"`);
expect(render(true, tab)).toContain(`aria-description="${t(lang, "host.sourcePicker.showCaptureBorderHint")}"`);
expect(render(false, tab, true)).not.toContain(label);
expect(render(undefined, tab, true)).not.toContain(label);
}
expect(render(true, "browser", true)).not.toContain(label);
});
});
describe("native adapter selection", () => {
const adapters: NativeAdapter[] = [
{ index: 0, name: "GPU A", identity: "a", hardwareH264: [] },
{
index: 1,
name: "GPU B",
identity: "b",
hardwareH264: [{ index: 0, name: "H264", identity: "encoder" }],
},
];
it("selects the first complete hardware path for UI capture", () => {
expect(defaultNativeCapturePath(adapters)).toEqual({
adapterIndex: 1,
encoderIndex: 0,
});
expect(defaultNativeCapturePath([adapters[0]!])).toBeNull();
});
it("uses software VP8 only when that capture capability exists", () => {
expect(defaultNativeCapturePath(adapters, "vp8", true)).toEqual({
adapterIndex: 0, encoderIndex: 0,
});
expect(defaultNativeCapturePath(adapters, "vp8", false)).toBeNull();
expect(defaultNativeCapturePath(adapters, "auto", true)?.adapterIndex).toBe(1);
expect(defaultNativeCapturePath([adapters[0]!], "auto", true)?.adapterIndex).toBe(0);
expect(defaultNativeCapturePath([adapters[0]!], "h264", true)).toBeNull();
});
});