Skip to content

armgit / Piik

Public Imported from GitHub
0

Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。

fix(media): recover active SFU from viewer control (#162)

AAAa0e901bee908
diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.md
index bcb76144..679f665d 100644
--- a/docs/adr/0005-automatic-hybrid-media-routing.md
+++ b/docs/adr/0005-automatic-hybrid-media-routing.md
@@ -280,6 +280,12 @@ ID allowlist.
STUN-only throughout these attempts. When admission has no eligible peer path,
or recovery is exhausted, select the SFU root plan. Stock LiveKit participant
ICE remains a distinct domain.
+ The Viewer recovery control follows the authoritative active route: a peer
+ edge requests the existing peer recovery, while an SFU assignment restarts
+ Screener signaling so reauthentication reasserts the same route and the
+ existing authoritative resync rebuilds the subscriber from fresh config. It
+ neither reports a connection as healthy nor directly requests SFU-to-peer
+ migration.
3. The server computes revision `R+1` without mutating the active topology. It
sends a prepare plan only to the host and required fallback roots.
4. When fallback is configured, host and viewer clients have already made one
diff --git a/docs/project-memory.md b/docs/project-memory.md
index c7dc7a24..956da3d8 100644
--- a/docs/project-memory.md
+++ b/docs/project-memory.md
@@ -27,7 +27,7 @@ Last updated: 2026-08-22
- Web defaults to browser/LiveKit codec negotiation; advanced settings offer Automatic, H.264, or VP8 for the next share while retaining fallback codecs and `backupCodec=false`. A codec choice neither proves hardware encoding nor shared encode. ADR-0006's browser bridge remains no-go.
- Mobile endpoints are Web Viewer-only. Current Android/iOS browsers do not expose Web Host capture; AirPlay/system mirroring is Viewer-local output.
- ADR-0005: direct/peer UDP -> bounded SFU roots -> selected-edge TURN. The deployed controller caps pending/answered `peer-selected` at one per room; Host ingress is independent. A pre-`ecc794d` exact-source/production-media canary proves active Host ingress only. Ordinary peers stay STUN-only.
-- `PEER_ASSISTED_MEDIA=true` enables all-room controllers; room `1` is historical. One-root healthy-SFU MBB is deployed with retained parent, media proof, Host2/browser1 overlap and cooldown. A cooldown-time ready is retained; expiry needs two fresh windows. It excludes `peer-selected`; active-SFU loss uses normal recovery. Capacity `0 -> 1`, multi-root and browser gates remain open.
+- `PEER_ASSISTED_MEDIA=true` covers all rooms. One-root healthy-SFU MBB is deployed with retained parent, media proof, Host2/browser1 overlap, cooldown and fresh two-window proof; it excludes `peer-selected`. Active-SFU loss uses normal recovery; the manual control keeps its route: peer restarts its edge, SFU reauthenticates signaling and rebuilds that subscriber. Capacity `0 -> 1`, multi-root/browser gates remain open.
- C+B reparenting stays edge-local: severe uses fallback; relative relay FPS uses fresh parent evidence and peers only. No scoring or global penalty.
- Flagship media is UDP; HTTPS/WSS stays TLS/TCP; the old release remains rollback-only.
- Treat settings as ceilings and degradation as unclassified. Use correlated Host A+B/Viewer C and one-variable evidence; never force AV1, infer by UA, or create a composite score.
diff --git a/docs/status.md b/docs/status.md
index a147f732..6be56883 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -51,7 +51,7 @@ Parallel flagship work; use minimum relevant checks and rollback proof. Target-d
## Next Milestone
Next: representative production-room UDP/frame/cap/stop canary; room `1` is history. TURN performance follows later.
-Recovery uses one ICE restart, one same-parent rebuild, one alternate peer, then SFU. Next gate exactly-two/Dynacast-off BWE on a zero-child SFU leaf, then root evacuation.
+Recovery: ICE restart -> same parent -> alternate peer -> SFU. Source-only manual recovery keeps the route: peer restarts; SFU reauth rebuilds its subscriber. Next: exactly-two/Dynacast-off zero-child SFU BWE, then evacuation.
Native WGC/MF passed one-Viewer hardware; package download, Viewer2/FIFO and game A/V remain. Use representative target-device or production evidence for performance, not an ordinary-PC synthetic gate.
Ordinary peers stay STUN-only; initial ingress, `peer-selected`, and healthy-reselection browser gates remain open.
ADR-0004 still needs its resource/quality matrix; the 20-viewer gate precedes a default change. Mobile uses the same capacity and is a compatibility observation.
diff --git a/src/client/lib/signaling.ts b/src/client/lib/signaling.ts
index d64d7e27..a86c84a2 100644
--- a/src/client/lib/signaling.ts
+++ b/src/client/lib/signaling.ts
@@ -32,6 +32,7 @@ const FATAL_SIGNAL_ERRORS = new Set([
"HOST_ALREADY_CONNECTED",
]);
const SESSION_REPLACED_CLOSE_CODE = 4001;
+const CLIENT_RECONNECT_CLOSE_CODE = 4002;
const INVALID_MESSAGE_CLOSE_CODE = 1008;
const VIEWER_ACCESS_REVOKED_CLOSE_CODE = 4004;
const PROTOCOL_REFRESH_MESSAGE = "页面版本已更新,请刷新后重试";
@@ -87,6 +88,20 @@ export class SignalingClient {
this.events.onStatus("offline");
}
+ reconnect(): boolean {
+ const socket = this.socket;
+ if (
+ this.stopped ||
+ !this.authenticated ||
+ !socket ||
+ socket.readyState >= WebSocket.CLOSING
+ ) {
+ return false;
+ }
+ socket.close(CLIENT_RECONNECT_CLOSE_CODE, "client reconnect");
+ return true;
+ }
+
send(message: ClientMessage): boolean {
if (
!this.authenticated ||
diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsx
index d738f251..b537d55d 100644
--- a/src/client/pages/ViewerPage.tsx
+++ b/src/client/pages/ViewerPage.tsx
@@ -114,6 +114,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
const [sfuUpstream, setSfuUpstream] = useState<SfuUpstreamState | null>(null);
const [assignedRoute, setAssignedRoute] = useState<{
revision: number;
+ phase: "prepare" | "active";
upstream: ParticipantRouteAssignment["upstream"];
} | null>(null);
const [relaySnapshot, setRelaySnapshot] = useState<PeerSnapshot | null>(null);
@@ -195,11 +196,12 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
function acceptAssignedRoute(
revision: number,
upstream: ParticipantRouteAssignment["upstream"],
+ phase: "prepare" | "active" = "active",
): void {
setAssignedRoute((current) =>
current && revision < current.revision
? current
- : { revision, upstream },
+ : { revision, phase, upstream },
);
}
@@ -825,6 +827,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
nextPeerAssisted && "routeAssignment" in message
? {
revision: message.routeRevision,
+ phase: "active",
upstream: message.routeAssignment.upstream,
}
: null,
@@ -949,7 +952,11 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
}
const result = ensureViewerSfuRoute().accept(message);
if (result !== "stale") {
- acceptAssignedRoute(message.revision, message.assignment.upstream);
+ acceptAssignedRoute(
+ message.revision,
+ message.assignment.upstream,
+ message.phase,
+ );
}
}
return;
@@ -1219,7 +1226,12 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
}
function retryConnection(): void {
- if (!peerRef.current?.requestRecovery()) {
+ const requested =
+ assignedRoute?.phase === "active" &&
+ assignedRoute.upstream.kind === "sfu"
+ ? signalRef.current?.reconnect() === true
+ : peerRef.current?.requestRecovery() === true;
+ if (!requested) {
setStatusText(hostOnline ? "正在连接" : "等待开始分享");
} else {
setStatusText("正在恢复连接");
@@ -1484,7 +1496,13 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
className="icon-button"
title="恢复连接"
aria-label="恢复连接"
- disabled={!peerSnapshot}
+ disabled={
+ !peerSnapshot &&
+ !(
+ assignedRoute?.phase === "active" &&
+ assignedRoute.upstream.kind === "sfu"
+ )
+ }
onClick={retryConnection}
>
<RefreshCw size={19} />
diff --git a/tests/client-state.test.ts b/tests/client-state.test.ts
index bc42ed5d..34e8dc3f 100644
--- a/tests/client-state.test.ts
+++ b/tests/client-state.test.ts
@@ -587,9 +587,74 @@ describe("client signaling recovery policy", () => {
expect(shouldReconnectSignaling(4001)).toBe(false);
expect(shouldReconnectSignaling(4004)).toBe(false);
expect(shouldReconnectSignaling(1008)).toBe(false);
+ expect(shouldReconnectSignaling(4002)).toBe(true);
expect(shouldReconnectSignaling(1006)).toBe(true);
});
+ it("restarts only an authenticated active signaling session on request", () => {
+ const sockets: FakeWebSocket[] = [];
+ class FakeWebSocket extends EventTarget {
+ static readonly CLOSING = 2;
+ readyState = 1;
+ readonly send = vi.fn();
+ readonly close = vi.fn((code?: number, reason?: string) => {
+ void code;
+ void reason;
+ this.readyState = FakeWebSocket.CLOSING;
+ });
+
+ constructor(readonly url: string) {
+ super();
+ sockets.push(this);
+ }
+ }
+ vi.stubGlobal("WebSocket", FakeWebSocket);
+ vi.stubGlobal("window", {
+ location: new URL("https://share.test/r/123456789012"),
+ setTimeout,
+ clearTimeout,
+ });
+ const signal = new SignalingClient(
+ {
+ roomId: "123456789012",
+ role: "viewer",
+ clientId: "viewer-client",
+ },
+ {
+ onMessage: () => undefined,
+ onStatus: () => undefined,
+ onTerminated: () => undefined,
+ onAccessRequired: () => undefined,
+ },
+ );
+
+ signal.start();
+ expect(signal.reconnect()).toBe(false);
+ sockets[0]!.dispatchEvent(new Event("open"));
+ const authenticated = new Event("message");
+ Object.defineProperty(authenticated, "data", {
+ value: JSON.stringify({
+ type: "authenticated",
+ protocol: "screener-v4",
+ role: "viewer",
+ peerId: "viewer_12345678",
+ roomExpiresAt: null,
+ maxViewers: 8,
+ hostOnline: true,
+ connectionId: null,
+ viewerPeerIds: [],
+ iceConfig: { iceServers: [] },
+ viewerPolicy: "private-link",
+ viewerAuthorizationGeneration: "viewer_generation_12345678",
+ }),
+ });
+ sockets[0]!.dispatchEvent(authenticated);
+
+ expect(signal.reconnect()).toBe(true);
+ expect(sockets[0]!.close).toHaveBeenCalledWith(4002, "client reconnect");
+ expect(signal.reconnect()).toBe(false);
+ });
+
it.each([
JSON.stringify({
type: "error",