Files
piik/src/client/components/living/AppConnectionButton.tsx
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

173 lines
9.1 KiB
TypeScript

import { useEffect, useId, useRef, useState } from "react";
import { activateClient, isClientActivated, watchClientActivation } from "../../lib/session";
import { useCopy } from "../../ui/copy";
import { Glyph } from "../../ui/icons";
import { Tooltip } from "./Tooltip";
import { Comic } from "./Comic";
export function AppConnectionButton({ sourcePicker = false, onConnected }: {
sourcePicker?: boolean;
onConnected?: () => void;
} = {}) {
const { t, vis } = useCopy();
const [state, setState] = useState<"idle" | "busy" | "ready" | "unavailable" | "incompatible">("idle");
const [helpOpen, setHelpOpen] = useState(false);
const helpId = useId();
const trigger = useRef<HTMLButtonElement>(null);
const help = useRef<HTMLDivElement>(null);
const pending = useRef<{ controller: AbortController; popup: Window | null } | null>(null);
const healthCheck = useRef<AbortController | null>(null);
useEffect(() => {
if (sourcePicker) return;
const refresh = async () => {
if (pending.current || help.current?.matches(":popover-open") || !isClientActivated()) return;
healthCheck.current?.abort();
const current = healthCheck.current = new AbortController();
const native = await import("../../native/client");
if (current.signal.aborted) return;
try {
const health = await native.discoverNativeHealth({ signal: current.signal, waitForPermission: false });
if (!current.signal.aborted && !pending.current) setState(health ? "ready" : "idle");
} catch (error) {
if (!current.signal.aborted && !pending.current) {
setState(error instanceof native.NativeCompatibilityError ? "incompatible" : "idle");
}
}
};
// Launch/remembered activation is intent, not proof of current permission.
// Recheck on return without keeping a media session or a polling timer alive.
const onFocus = () => { void refresh().catch(() => undefined); };
onFocus();
window.addEventListener("focus", onFocus);
const unwatch = watchClientActivation(onFocus);
return () => { healthCheck.current?.abort(); window.removeEventListener("focus", onFocus); unwatch(); };
}, [sourcePicker]);
useEffect(() => () => { pending.current?.controller.abort(); pending.current?.popup?.close(); }, []);
useEffect(() => {
// A one-shot disclosure follows its trigger again on the next opening.
const close = () => help.current?.hidePopover();
window.addEventListener("resize", close);
window.addEventListener("scroll", close);
return () => { window.removeEventListener("resize", close); window.removeEventListener("scroll", close); };
}, []);
function showHelp(): void {
if (trigger.current) help.current?.showPopover({ source: trigger.current });
}
async function connect(): Promise<void> {
if (pending.current) return;
help.current?.hidePopover();
healthCheck.current?.abort();
// Reserve the window during the click, before local-network discovery waits.
const attempt = { controller: new AbortController(), popup: window.open("about:blank", "_blank") };
if (!attempt.popup) { setState("unavailable"); showHelp(); return; }
pending.current = attempt;
setState("busy");
const signal = attempt.controller.signal;
let native: typeof import("../../native/client") | undefined;
let approving = false;
const onMessage = async (event: MessageEvent) => {
if (approving || event.source !== attempt.popup || !approvalOrigin || event.origin !== approvalOrigin ||
event.data?.type !== "piik-app-approved" || event.data.site !== window.location.origin) return;
approving = true;
// The approval message only asks us to recheck the App-owned permission.
const health = await native?.discoverNativeHealth({ signal }).catch(() => null);
if (signal.aborted) return;
finish(health ? "ready" : "unavailable");
if (health) {
activateClient();
onConnected?.();
}
};
let approvalOrigin = "";
const finish = (result: typeof state) => {
window.removeEventListener("message", onMessage);
window.removeEventListener("focus", onFocus);
attempt.controller.abort();
attempt.popup?.close();
if (pending.current === attempt) {
pending.current = null;
setState(result);
if (result === "unavailable" || result === "incompatible") showHelp();
}
};
const onFocus = () => {
if (attempt.popup?.closed && !approving) finish("idle");
};
window.addEventListener("message", onMessage);
window.addEventListener("focus", onFocus);
signal.addEventListener("abort", () => {
window.removeEventListener("message", onMessage);
window.removeEventListener("focus", onFocus);
}, { once: true });
try {
native = await import("../../native/client");
if (signal.aborted) return;
const url = await native.discoverNativeConnect(signal);
if (signal.aborted) return;
if (!url) { finish("unavailable"); return; }
approvalOrigin = new URL(url).origin;
attempt.popup.location.replace(url);
} catch (error) {
if (!signal.aborted) finish(native && error instanceof native.NativeCompatibilityError ? "incompatible" : "unavailable");
}
}
const label = t(state === "ready" ? "client.connect.standby" : state === "incompatible" ? "native.incompatible" :
state === "unavailable" ? "client.connect.unavailable" : "client.connect.action");
const failed = state === "unavailable" || state === "incompatible";
return <><Tooltip kind={state === "ready" ? "hint-app-ready" : state === "unavailable" ? "signal-failed" : state === "incompatible" ? "warning" : "hint-client-site"}
text={vis ? undefined : label} toggleOnClick={state === "ready"} disabled={helpOpen}
place={sourcePicker ? "above" : "below"} align="end">
<button ref={trigger} type="button" className={`${sourcePicker ? "lr-source-picker-refresh lr-source-app-connect" : "lr-btn lr-app-connect"}${state === "ready" ? " is-ready" : ""}`}
aria-label={sourcePicker ? t("client.connect.action") : label} aria-busy={state === "busy" || undefined}
popoverTarget={failed ? helpId : undefined} aria-haspopup={failed ? "dialog" : undefined}
onClick={state === "ready" || failed ? undefined : event => {
// Failure may attach popoverTarget during this click; do not toggle the
// recovery card closed immediately after opening it.
event.preventDefault();
void connect();
}} disabled={state === "busy"}>
<Glyph name={state === "ready" ? "check" : state === "busy" ? "loader" : state === "unavailable" || state === "incompatible" ? "alert" : "window"}
size={16} className={state === "busy" ? "lr-spin" : undefined} />
{vis ? null : <span className="lr-cap">App</span>}
</button>
</Tooltip>
<div ref={help} id={helpId} popover="auto" role="dialog" aria-label={t("client.connect.action")} aria-describedby={`${helpId}-message`}
className="lr-app-connect-help" onToggle={event => {
setHelpOpen(event.newState === "open");
if (event.newState !== "open" || !trigger.current) return;
const panel = event.currentTarget;
const rect = trigger.current.getBoundingClientRect();
if (rect.bottom <= 0 || rect.top >= window.innerHeight) { panel.hidePopover(); return; }
const below = window.innerHeight - rect.bottom - 16;
const above = rect.top - 16;
const openAbove = below < panel.scrollHeight && above > below;
panel.classList.toggle("is-above", openAbove);
panel.style.maxHeight = `${Math.max(0, openAbove ? above : below)}px`;
panel.style.left = `${Math.max(8, Math.min(rect.right - panel.offsetWidth, window.innerWidth - panel.offsetWidth - 8))}px`;
panel.style.top = `${Math.max(8, openAbove ? rect.top - panel.offsetHeight - 8 : rect.bottom + 8)}px`;
panel.querySelector<HTMLButtonElement>("button")?.focus();
}}>
<div className="lr-app-connect-head">
<div className="lr-app-connect-scene" aria-hidden="true">{helpOpen && <Comic kind={state === "incompatible" ? "warning" : "signal-failed"} theme="paper" />}</div>
<button type="button" className="lr-btn lr-app-connect-close" aria-label={t("common.close")}
popoverTarget={helpId} popoverTargetAction="hide">
<Glyph name="x" size={16} />
</button>
</div>
<p id={`${helpId}-message`} className={vis ? "visually-hidden" : undefined}>{label}</p>
<div className="lr-app-connect-actions">
<button type="button" className="lr-btn" aria-label={t("common.retry")} onClick={() => void connect()}>
<Glyph name="refresh" size={16} /><span className={vis ? "visually-hidden" : undefined}>{t("common.retry")}</span>
</button>
<a className="lr-btn" href="https://piik.tv/#download" target="_blank" rel="noopener noreferrer" aria-label={t("client.connect.download")}>
<Glyph name="arrowDown" size={16} /><span className={vis ? "visually-hidden" : undefined}>{t("client.connect.download")}</span>
</a>
</div>
<p className={vis ? "visually-hidden" : "lr-app-connect-optional"}>{t("client.connect.browserHint")}</p>
</div>
</>;
}