refactor(browser): retire obsolete native client runtime

This commit is contained in:
AAA committed 2026-11-03 18:20:06 -04:00
1 parent b4812c6cb2
commit 5126b9a0de
15 files changed
+144 -2666

No files matched your search

@@ -13,6 +13,7 @@ import type { AppDiscovery } from "../../native/discovery";
import type { AppReleaseIdentity } from "../../lib/release-update";
import { useReleaseUpdate } from "../../lib/use-release-update";
import { AppReleaseNotice } from "./AppReleaseNotice";
import { channelAppDiscovery } from "../../channel/app-link";
interface AppConnectionProps {
onConnected?: () => void;
@@ -28,13 +29,7 @@ interface ConnectionAttempt {
cancel?: () => void;
}
export function AppConnectionButton({ onConnected, discovery, connected }: AppConnectionProps) {
const loadDiscovery = async (): Promise<AppDiscovery> => {
if (discovery) return discovery;
const native = await import("../../native/client");
return { health: native.discoverNativeHealth, connect: native.discoverNativeConnect,
isIncompatible: error => error instanceof native.NativeCompatibilityError };
};
export function AppConnectionButton({ onConnected, discovery = channelAppDiscovery, connected }: AppConnectionProps) {
const { t, vis } = useCopy();
const [state, setState] = useState<"idle" | "waking" | "busy" | "approval" | "approving" | "ready" | "unavailable" | "incompatible">("idle");
const wakeURL = androidAppIntent("piik://app");
@@ -62,7 +57,7 @@ export function AppConnectionButton({ onConnected, discovery, connected }: AppCo
if (help.current?.matches(":popover-open") || (!connected && !isClientActivated())) return;
healthCheck.current?.abort();
const current = healthCheck.current = new AbortController();
const native = await loadDiscovery();
const native = discovery;
if (current.signal.aborted) return;
try {
const health = await native.health({ signal: current.signal, waitForPermission: false });
@@ -155,7 +150,7 @@ export function AppConnectionButton({ onConnected, discovery, connected }: AppCo
const discover = async () => {
setState("busy");
try {
native = await loadDiscovery();
native = discovery;
if (signal.aborted) return;
const url = await native.connect(signal);
if (signal.aborted) return;
+1 -25
View File
@@ -1,28 +1,4 @@
import type { NativeAdapter, NativeCaptureTarget, NativeVideoCodec } from "./wire";
export interface NativeCapturePath {
adapterIndex: number;
encoderIndex: number;
}
export function defaultNativeCapturePath(
adapters: NativeAdapter[],
codec: NativeVideoCodec | "auto" = "auto",
softwareVP8 = false,
): NativeCapturePath | null {
if (codec !== "vp8") {
for (const adapter of adapters) {
const encoder = adapter.hardwareH264[0];
if (encoder) {
return { adapterIndex: adapter.index, encoderIndex: encoder.index };
}
}
}
const adapter = adapters[0];
return codec !== "h264" && softwareVP8 && adapter
? { adapterIndex: adapter.index, encoderIndex: 0 }
: null;
}
import type { NativeCaptureTarget } from "./wire";
export function nativeCaptureTargetKey(target: NativeCaptureTarget): string {
return target.kind === "window"
-841
View File
@@ -1,841 +0,0 @@
import type { z } from "zod";
import type { RemoteControlMode } from "../remote-control/protocol";
import { debugError, debugEvent } from "../lib/debug";
import { appApprovalURL, discoverLocalApp, isLoopbackPage, type AppDiscoveryOptions } from "./discovery";
export { isLoopbackPage } from "./discovery";
import type {
IceConfig,
QualitySettings,
SignalPayload,
SfuSignalMessage,
PunchPrediction,
} from "../../shared/protocol";
import { createOpaqueId } from "../lib/opaque-id";
import {
nativeCaptureTargetKey,
type NativeCapturePath,
} from "./capture-selection";
import {
captureOptionsResponseSchema,
edgeOfferResponseSchema,
nativeAckResponseSchema,
remoteStopShortcutResponseSchema,
nativeEventSchema,
nativeDiscoveryIdentitySchema,
nativeConnectSchema,
nativeHealthSchema,
NATIVE_CLIENT_PROTOCOL,
NATIVE_CLIENT_SUBPROTOCOL,
pongResponseSchema,
publicationResponseSchema,
receiveAnswerResponseSchema,
readyResponseSchema,
requestFailedResponseSchema,
shareStartedResponseSchema,
shareSourceReplacedResponseSchema,
shareUpdatedResponseSchema,
sourceListResponseSchema,
microphoneListResponseSchema,
sourcePreviewResponseSchema,
punchPreparedResponseSchema,
punchCompleteResponseSchema,
type NativeAdapter,
type NativeClientEvent,
type NativeHealth,
type NativeCaptureTarget,
type NativeIceCandidate,
type NativeVideoCodec,
type RemoteStopShortcut,
} from "./wire";
const REQUEST_TIMEOUT_MS = 8_000;
interface PendingRequest<T = unknown> {
operation: string;
schema: z.ZodType<T>;
resolve: (value: T) => void;
reject: (error: Error) => void;
timer: number | null;
}
export interface NativeShareInput {
shareId: string;
source: NativeCaptureTarget;
audio: boolean;
excludeAudio?: NativeCaptureTarget;
showCaptureBorder?: boolean;
adapterIndex: number;
encoderIndex: number;
edgeCapacity: number;
profile: QualitySettings;
codec: NativeVideoCodec | "auto";
}
export class NativeCompatibilityError extends Error {
constructor(readonly actualProtocol: number) {
super(`Piik App control protocol ${actualProtocol} is incompatible with ${NATIVE_CLIENT_PROTOCOL}`);
this.name = "NativeCompatibilityError";
}
}
/** The control boundary knows the failed operation, not the driver's cause. */
export class NativeRequestError extends Error {
constructor(
readonly reason: "unavailable" | "timeout" | "send-failed" | "rejected" | "invalid-response" | "disconnected",
readonly operation: string,
options?: ErrorOptions,
) {
super({
unavailable: "Piik App is unavailable",
timeout: "Piik App request timed out",
"send-failed": "Piik App request failed",
rejected: "Piik App request failed",
"invalid-response": "Piik App response is invalid",
disconnected: "Piik App disconnected",
}[reason], options);
this.name = "NativeRequestError";
}
}
export async function discoverNativeHealth(
options: AppDiscoveryOptions = {},
): Promise<NativeHealth | null> {
const health = await discoverNative("health", body => nativeHealthSchema.parse(body), options);
if (health) debugEvent("native", "discovered", { capabilities: health.nativeMedia });
return health;
}
/** A local approval address is not permission to use native media. */
export async function discoverNativeConnect(signal?: AbortSignal): Promise<string | null> {
return discoverNative("connect-discovery", body => {
const { connectURL } = nativeConnectSchema.parse(body);
return appApprovalURL(connectURL);
}, { signal });
}
async function discoverNative<T>(
path: "health" | "connect-discovery", read: (body: unknown) => T,
options: AppDiscoveryOptions,
): Promise<T | null> {
try {
return await discoverLocalApp(path, (body, port) => {
const identity = nativeDiscoveryIdentitySchema.safeParse(body);
if (!identity.success || identity.data.port !== port) throw new Error("Not a Piik App discovery response");
if (identity.data.protocol !== NATIVE_CLIENT_PROTOCOL) throw new NativeCompatibilityError(identity.data.protocol);
return read(body);
}, options, error => error instanceof NativeCompatibilityError);
} catch (error) {
if (error instanceof NativeCompatibilityError) debugEvent("native", "incompatible", {
expectedProtocol: NATIVE_CLIENT_PROTOCOL, actualProtocol: error.actualProtocol,
});
throw error;
}
}
export async function notifyNativePresentation(
language: "zh" | "en" | "vis",
signal: AbortSignal,
): Promise<void> {
if (signal.aborted) return;
const health = await discoverNativeHealth({ signal, waitForPermission: false });
if (!health || signal.aborted) return;
await fetch(`http://127.0.0.1:${health.port}/presentation`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ language }),
signal,
...(isLoopbackPage() ? {} : { targetAddressSpace: "loopback" }),
} as RequestInit);
}
export class NativeClient {
private readonly pending = new Map<string, PendingRequest>();
private readonly listeners = new Set<(event: NativeClientEvent) => void>();
private readonly closeListeners = new Set<() => void>();
private closed = false;
private audioVolumeUpdates = new Map<"set-microphone" | "set-share-volume", { shareId: string; volume: number; done: Promise<void> }>();
private constructor(
readonly health: NativeHealth,
private readonly socket: WebSocket,
) {
socket.addEventListener("message", (event) =>
this.handleMessage(event.data),
);
socket.addEventListener("close", () => this.handleClose());
socket.addEventListener("error", () => this.handleClose());
}
static async connect(options?: AppDiscoveryOptions): Promise<NativeClient | null> {
const signal = options?.signal;
const health = await discoverNativeHealth(options);
if (!health || signal?.aborted) return null;
const socket = new WebSocket(`ws://127.0.0.1:${health.port}/control`, [
`${NATIVE_CLIENT_SUBPROTOCOL}.${health.instanceToken}`,
]);
const client = new NativeClient(health, socket);
// Acquisition owns discovery, the WebSocket handshake and hello together.
// Once returned, the caller owns the live client independently of this signal.
const abort = () => client.close();
signal?.addEventListener("abort", abort, { once: true });
try {
const opened = await new Promise<boolean>((resolveOpen) => {
const finish = (value: boolean) => {
window.clearTimeout(timer);
socket.removeEventListener("open", onOpen);
socket.removeEventListener("error", fail);
socket.removeEventListener("close", fail);
signal?.removeEventListener("abort", fail);
resolveOpen(value);
};
const onOpen = () => finish(socket.protocol === `${NATIVE_CLIENT_SUBPROTOCOL}.${health.instanceToken}`);
const fail = () => finish(false);
const timer = window.setTimeout(fail, REQUEST_TIMEOUT_MS);
socket.addEventListener("open", onOpen);
socket.addEventListener("error", fail);
socket.addEventListener("close", fail);
signal?.addEventListener("abort", fail, { once: true });
});
if (!opened || client.closed || signal?.aborted) {
if (!signal?.aborted) debugEvent("native", "unavailable", { stage: "control" });
client.close();
return null;
}
await client.request("hello", {}, readyResponseSchema);
if (client.closed || signal?.aborted) { client.close(); return null; }
debugEvent("native", "connected");
return client;
} catch {
client.close();
return null;
} finally {
signal?.removeEventListener("abort", abort);
}
}
onEvent(listener: (event: NativeClientEvent) => void): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
onClose(listener: () => void): () => void {
if (this.closed) {
listener();
return () => undefined;
}
this.closeListeners.add(listener);
return () => this.closeListeners.delete(listener);
}
async ping(): Promise<void> {
await this.request("ping", {}, pongResponseSchema);
}
async captureOptions(): Promise<NativeAdapter[]> {
const response = await this.request(
"capture-options",
{},
captureOptionsResponseSchema,
);
return response.adapters;
}
async sources(): Promise<NativeCaptureTarget[]> {
const response = await this.request(
"list-sources",
{},
sourceListResponseSchema,
);
return response.sources;
}
async sourcePreview(target: NativeCaptureTarget): Promise<string | null> {
const response = await this.request(
"source-preview",
{ source: target },
sourcePreviewResponseSchema,
);
if (response.sourceKey !== nativeCaptureTargetKey(target)) {
throw new Error("Native capture preview identity changed");
}
return response.data
? `data:${response.mime};base64,${response.data}`
: null;
}
async startShare(
input: NativeShareInput,
onRequested?: () => void,
): Promise<{ audio: boolean; codec: NativeVideoCodec; sourceAudio?: boolean }> {
// Older Apps reject unknown command fields.
const { showCaptureBorder = false, excludeAudio, ...shareInput } = input;
this.validateAudioExclusion(excludeAudio);
const response = await this.request(
"start-share",
{
...shareInput,
...(excludeAudio ? { excludeAudio } : {}),
// Keep a stable output for source-audio toggles during sharing.
...(this.health.nativeMedia.microphone || this.health.nativeMedia.shareVolume ? { microphoneMixing: true } : {}),
...(this.health.nativeMedia.remoteInput ? { remoteInput: true } : {}),
...(this.health.nativeMedia.captureBorderControl ? { showCaptureBorder } : {}),
...(this.health.nativeMedia.sourceCancellation ? { reportSourceCancellation: true } : {}),
},
shareStartedResponseSchema,
input.source.kind === "picker" ? null : REQUEST_TIMEOUT_MS,
onRequested,
);
if (response.shareId !== input.shareId) {
throw new Error("Native share identity changed");
}
return { audio: response.audio, codec: response.codec, sourceAudio: response.sourceAudio };
}
async updateShare(shareId: string, profile: QualitySettings): Promise<void> {
const response = await this.request(
"update-share",
{ shareId, profile },
shareUpdatedResponseSchema,
null,
);
if (response.shareId !== shareId) {
throw new Error("Native share identity changed");
}
}
private validateAudioExclusion(target: NativeCaptureTarget | undefined): void {
if (target && !this.health.nativeMedia.processAudioExclusion) {
throw new Error("Piik App does not support audio exclusion");
}
}
async replaceShareSource(
shareId: string,
source: NativeCaptureTarget,
audio: boolean,
path: NativeCapturePath,
showCaptureBorder = false,
excludeAudio?: NativeCaptureTarget,
): Promise<void> {
this.validateAudioExclusion(excludeAudio);
const response = await this.request(
"replace-share-source",
{
shareId,
source,
audio,
...(excludeAudio ? { excludeAudio } : {}),
adapterIndex: path.adapterIndex,
encoderIndex: path.encoderIndex,
...(this.health.nativeMedia.captureBorderControl ? { showCaptureBorder } : {}),
...(this.health.nativeMedia.sourceCancellation ? { reportSourceCancellation: true } : {}),
},
shareSourceReplacedResponseSchema,
source.kind === "picker" ? null : REQUEST_TIMEOUT_MS,
);
if (response.shareId !== shareId) {
throw new Error("Native share identity changed");
}
}
async prepareEdge(
shareId: string,
connectionId: string,
iceConfig: IceConfig,
sourceConnectionId?: string,
punched = false,
): Promise<RTCSessionDescriptionInit> {
const response = await this.request(
"prepare-edge",
{
shareId,
connectionId,
...(punched ? { punched: true } : {}),
...(sourceConnectionId ? { sourceConnectionId } : {}),
iceServers: iceConfig.iceServers.map((server) => ({
urls: Array.isArray(server.urls) ? server.urls : [server.urls],
})),
},
edgeOfferResponseSchema,
);
if (
response.shareId !== shareId ||
response.connectionId !== connectionId
) {
throw new Error("Native edge identity changed");
}
return { type: "offer", sdp: response.sdp };
}
async preparePunch(shareId: string, connectionId: string, iceConfig: IceConfig,
secret: string, edgeCapacity?: number, sourceConnectionId?: string): Promise<PunchPrediction | null> {
const response = await this.request("prepare-punch", {
shareId, connectionId, secret,
...(edgeCapacity !== undefined ? { edgeCapacity } : {}),
...(sourceConnectionId ? { sourceConnectionId } : {}),
iceServers: iceConfig.iceServers.map(server => ({ urls: Array.isArray(server.urls) ? server.urls : [server.urls] })),
}, punchPreparedResponseSchema);
return response.prediction;
}
async runPunch(shareId: string, connectionId: string, prediction: PunchPrediction): Promise<boolean> {
return (await this.request("run-punch", { shareId, connectionId, prediction }, punchCompleteResponseSchema)).connected;
}
async closePunch(shareId: string, connectionId: string): Promise<void> {
await this.request("close-punch", { shareId, connectionId }, nativeAckResponseSchema);
}
async preparePublication(
shareId: string,
publicationGeneration: string,
connectionId: string,
iceConfig: IceConfig,
) {
const response = await this.request(
"prepare-publication",
{
shareId,
publicationGeneration,
connectionId,
iceServers: iceConfig.iceServers.map((server) => ({
urls: Array.isArray(server.urls) ? server.urls : [server.urls],
})),
},
publicationResponseSchema,
);
if (
response.type !== "publication-offer" ||
!response.sdp ||
response.shareId !== shareId ||
response.publicationGeneration !== publicationGeneration ||
response.connectionId !== connectionId
) {
throw new Error("Native publication identity changed");
}
return {
description: { type: "offer" as const, sdp: response.sdp },
media: response.media,
};
}
async publicationMedia(
shareId: string,
publicationGeneration: string,
connectionId: string,
) {
const response = await this.request(
"publication-media",
{
shareId,
publicationGeneration,
connectionId,
},
publicationResponseSchema,
);
if (
response.type !== "publication-media" ||
response.shareId !== shareId ||
response.publicationGeneration !== publicationGeneration ||
response.connectionId !== connectionId
) {
throw new Error("Native publication identity changed");
}
return response.media;
}
async acceptPublicationSignal(
shareId: string,
message: SfuSignalMessage,
): Promise<void> {
const identity = {
shareId,
publicationGeneration: message.publicationGeneration,
connectionId: message.connectionId,
};
if (
message.kind === "description" &&
message.description?.type === "answer"
) {
await this.request(
"publication-answer",
{ ...identity, sdp: message.description.sdp },
nativeAckResponseSchema,
);
} else if (message.kind === "candidate") {
await this.request(
"publication-candidate",
{ ...identity, candidate: message.candidate ?? null },
nativeAckResponseSchema,
);
} else if (message.kind === "layers") {
await this.request(
"publication-layers",
{ ...identity, activeCount: message.activeCount },
nativeAckResponseSchema,
);
}
}
async closePublication(
shareId: string,
publicationGeneration: string,
connectionId: string,
): Promise<void> {
await this.request(
"close-publication",
{ shareId, publicationGeneration, connectionId },
nativeAckResponseSchema,
);
}
async prepareLocalEdge(
shareId: string,
connectionId: string,
sourceConnectionId?: string,
restart = false,
): Promise<RTCSessionDescriptionInit & { offerId: string }> {
const response = await this.request(
"prepare-local-edge",
{
shareId,
connectionId,
restart,
...(sourceConnectionId ? { sourceConnectionId } : {}),
},
edgeOfferResponseSchema,
);
if (
response.shareId !== shareId ||
response.connectionId !== connectionId
) {
throw new Error("Native local edge identity changed");
}
return { type: "offer", sdp: response.sdp, offerId: response.id };
}
async receiveOffer(
shareId: string,
connectionId: string,
offer: RTCSessionDescriptionInit,
iceConfig: IceConfig,
edgeCapacity: number,
punched = false,
): Promise<{
answer: { type: "answer"; sdp: string };
audio: boolean;
codec: NativeVideoCodec;
reused: boolean;
}> {
if (offer.type !== "offer" || !offer.sdp) {
throw new Error("Native receiver requires an SDP offer");
}
const response = await this.request(
"receive-offer",
{
shareId,
connectionId,
...(this.health.nativeMedia.receiverReuse ? { reuseReceiver: true } : {}),
edgeCapacity,
...(punched ? { punched: true } : {}),
iceServers: iceConfig.iceServers.map((server) => ({
urls: Array.isArray(server.urls) ? server.urls : [server.urls],
})),
sdp: offer.sdp,
},
receiveAnswerResponseSchema,
);
if (
response.shareId !== shareId ||
response.connectionId !== connectionId
) {
throw new Error("Native receiver identity changed");
}
return {
answer: { type: "answer", sdp: response.sdp },
audio: response.audio,
codec: response.codec,
reused: response.reused === true,
};
}
async addReceiveCandidate(
shareId: string,
connectionId: string,
candidate: NativeIceCandidate | null,
): Promise<void> {
await this.request(
"receive-candidate",
{ shareId, connectionId, candidate },
nativeAckResponseSchema,
);
}
async closeReceiver(shareId: string, connectionId: string): Promise<void> {
await this.request(
"close-receiver",
{ shareId, connectionId },
nativeAckResponseSchema,
);
}
async stopReceive(shareId: string): Promise<void> {
await this.request("stop-receive", { shareId }, nativeAckResponseSchema);
}
async acceptSignal(
shareId: string,
connectionId: string,
payload: SignalPayload,
offerId?: string,
): Promise<void> {
if (payload.connectionId !== connectionId || payload.kind === "punch") return;
if (payload.kind === "description") {
if (payload.description.type !== "answer") return;
await this.request(
"edge-answer",
{ shareId, connectionId, sdp: payload.description.sdp, ...(offerId ? { offerId } : {}) },
nativeAckResponseSchema,
);
return;
}
await this.request(
"edge-candidate",
{ shareId, connectionId, candidate: payload.candidate },
nativeAckResponseSchema,
);
}
async closeEdge(shareId: string, connectionId: string): Promise<void> {
await this.request(
"close-edge",
{ shareId, connectionId },
nativeAckResponseSchema,
);
}
async microphones(): Promise<{ id: string; label: string }[]> {
if (!this.health.nativeMedia.microphone) throw new Error("Piik App microphone is unavailable");
return (await this.request("list-microphones", {}, microphoneListResponseSchema)).devices;
}
async setMicrophone(shareId: string, enabled: boolean, volume: number, deviceId = ""): Promise<void> {
if (!this.health.nativeMedia.microphone) throw new Error("Piik App microphone is unavailable");
await this.request("set-microphone", { shareId, enabled, volume, deviceId }, nativeAckResponseSchema, null);
}
// Dragging keeps at most one request in flight and one latest value. It cannot
// queue dozens of slider events ahead of Stop or reopen a lost microphone.
setMicrophoneVolume(shareId: string, volume: number): Promise<void> {
if (!this.health.nativeMedia.microphone) return Promise.reject(new Error("Piik App microphone is unavailable"));
return this.setAudioVolume("set-microphone", shareId, volume);
}
setShareVolume(shareId: string, volume: number): Promise<void> {
if (!this.health.nativeMedia.shareVolume) return Promise.reject(new Error("Piik App share volume is unavailable"));
return this.setAudioVolume("set-share-volume", shareId, volume);
}
private setAudioVolume(type: "set-microphone" | "set-share-volume", shareId: string, volume: number): Promise<void> {
const active = this.audioVolumeUpdates.get(type);
if (active?.shareId === shareId) { active.volume = volume; return active.done; }
const update = { shareId, volume, done: Promise.resolve() };
this.audioVolumeUpdates.set(type, update);
update.done = (async () => {
do {
const sent = update.volume;
await this.request(type, { shareId, volume: sent }, nativeAckResponseSchema);
if (sent === update.volume) break;
} while (this.audioVolumeUpdates.get(type) === update && !this.closed);
})().finally(() => { if (this.audioVolumeUpdates.get(type) === update) this.audioVolumeUpdates.delete(type); });
return update.done;
}
async setRemoteControl(shareId: string, requestId: string, allow: boolean): Promise<void> {
await this.request("set-remote-control", { shareId, requestId, allow }, nativeAckResponseSchema);
}
async setRemoteControlPolicy(shareId: string, mode: RemoteControlMode, password?: string): Promise<void> {
await this.request("set-remote-control-policy", { shareId, mode, ...(password !== undefined ? { password } : {}),
...(this.health.nativeMedia.remoteCoPlay ? { coPlay: true } : {}) }, nativeAckResponseSchema, null);
}
async remoteStopShortcut(shareId: string, key?: number): Promise<RemoteStopShortcut> {
if (!this.health.nativeMedia.remoteStopShortcut) throw new Error("Piik App shortcut settings are unavailable");
return this.request(key === undefined ? "get-remote-stop-shortcut" : "set-remote-stop-shortcut",
{ shareId, ...(key === undefined ? {} : { key }) }, remoteStopShortcutResponseSchema);
}
async setRemoteInputPeers(shareId: string, peers: { peerId: string; endpointId: string; secret: string }[]): Promise<void> {
await this.request("set-remote-input-peers", { shareId, peers }, nativeAckResponseSchema);
}
async setRemoteControlSimultaneous(shareId: string, enabled: boolean): Promise<void> {
await this.request("set-remote-control-simultaneous", { shareId, enabled }, nativeAckResponseSchema);
}
async stopShare(shareId: string): Promise<void> {
for (const [type, update] of this.audioVolumeUpdates) if (update.shareId === shareId) this.audioVolumeUpdates.delete(type);
await this.request("stop-share", { shareId }, nativeAckResponseSchema);
}
async setPaused(shareId: string, paused: boolean): Promise<void> {
await this.request(
"pause-share",
{ shareId, paused },
nativeAckResponseSchema,
);
}
close(): void {
if (this.closed) return;
this.closed = true;
this.audioVolumeUpdates.clear();
this.rejectPending();
this.listeners.clear();
this.closeListeners.clear();
if (this.socket.readyState < WebSocket.CLOSING) {
this.socket.close(1000, "page closed");
}
}
private request<T>(
type: string,
fields: object,
schema: z.ZodType<T>,
timeoutMs: number | null = REQUEST_TIMEOUT_MS,
onRequested?: () => void,
): Promise<T> {
if (this.closed || this.socket.readyState !== WebSocket.OPEN) {
return Promise.reject(new NativeRequestError("unavailable", type));
}
const id = createOpaqueId();
const began = performance.now();
const details = { type, requestId: id };
return new Promise<T>((resolveRequest, rejectRequest) => {
const timer =
timeoutMs === null
? null
: window.setTimeout(() => {
this.pending.delete(id);
debugEvent("native", "request-timeout", { ...details, durationMs: performance.now() - began });
rejectRequest(new NativeRequestError("timeout", type));
}, timeoutMs);
this.pending.set(id, {
operation: type,
schema,
resolve: (value) => {
debugEvent("native", "response", { ...details, durationMs: performance.now() - began, applied: value });
resolveRequest(value as T);
},
reject: (error) => {
debugError("native", "request-failed", error, { ...details, durationMs: performance.now() - began });
rejectRequest(error);
},
timer,
});
try {
debugEvent("native", "request", { ...details, requested: fields, timeoutMs });
this.socket.send(
JSON.stringify({
version: NATIVE_CLIENT_PROTOCOL,
id,
type,
...fields,
}),
);
} catch (error) {
if (timer !== null) window.clearTimeout(timer);
this.pending.delete(id);
debugError("native", "request-failed", error, { ...details, durationMs: performance.now() - began });
rejectRequest(new NativeRequestError("send-failed", type, { cause: error }));
return;
}
onRequested?.();
});
}
private handleMessage(raw: unknown): void {
let value: unknown;
try {
value = JSON.parse(String(raw));
} catch {
debugEvent("native", "protocol-failed", { stage: "json-invalid" });
this.failConnection();
return;
}
const id = requestId(value);
if (id) {
const pending = this.pending.get(id);
if (!pending) return;
this.pending.delete(id);
if (pending.timer !== null) window.clearTimeout(pending.timer);
const failure = requestFailedResponseSchema.safeParse(value);
if (failure.success) {
if (failure.data.code === "source-canceled") {
pending.reject(new DOMException("Source selection canceled", "NotAllowedError"));
return;
}
pending.reject(new NativeRequestError("rejected", pending.operation, { cause: { code: failure.data.code } }));
return;
}
const parsed = pending.schema.safeParse(value);
if (parsed.success) {
pending.resolve(parsed.data);
} else {
pending.reject(new NativeRequestError("invalid-response", pending.operation, { cause: parsed.error }));
}
return;
}
const event = nativeEventSchema.safeParse(value);
if (!event.success) {
// A rejected observation has no control authority. Drop it without
// retiring healthy media; its identity/state must still pass to be used.
if (value && typeof value === "object" && "type" in value &&
(value.type === "edge-quality" || value.type === "publication-quality")) {
debugError("native", "quality-sample-invalid", event.error);
return;
}
debugError("native", "protocol-failed", event.error, { stage: "event-invalid" });
this.failConnection();
return;
}
debugEvent("native", "event", event.data);
for (const listener of this.listeners) {
listener(event.data);
}
}
private handleClose(): void {
if (this.closed) return;
debugEvent("native", "closed");
this.closed = true;
this.rejectPending();
this.listeners.clear();
const listeners = [...this.closeListeners];
this.closeListeners.clear();
for (const listener of listeners) listener();
}
private failConnection(): void {
if (this.socket.readyState < WebSocket.CLOSING) {
this.socket.close(1008, "invalid Client message");
}
this.handleClose();
}
private rejectPending(): void {
for (const request of this.pending.values()) {
if (request.timer !== null) window.clearTimeout(request.timer);
request.reject(new NativeRequestError("disconnected", request.operation));
}
this.pending.clear();
}
}
function requestId(value: unknown): string | null {
if (!value || typeof value !== "object" || !("id" in value)) return null;
const id = (value as { id?: unknown }).id;
return typeof id === "string" ? id : null;
}
-298
View File
@@ -1,298 +0,0 @@
import type { SignalPayload } from "../../shared/protocol";
import { createOpaqueId } from "../lib/opaque-id";
import { browserDebugEnabled, debugError, debugEvent } from "../lib/debug";
import { observeDebugConnection } from "../lib/debug-webrtc";
import type { ConnectionMetrics } from "../types";
import { preferScreenAudioStereo } from "../webrtc/opus-receive-sdp";
import { requireReceivingVideo } from "../webrtc/video-codec";
import { RemoteInputChannel } from "../webrtc/remote-input-channel";
import {
collectConnectionMetrics,
decodedVideoFrames,
type StatsAccumulator,
} from "../webrtc/stats";
import type { NativeClientEvent } from "./wire";
const BRIDGE_TIMEOUT_MS = 8_000;
const DISCONNECTED_GRACE_MS = 3_000;
export class NativeMediaBridgeError extends Error {}
export class NativeMediaBridgeInitializationError extends NativeMediaBridgeError {}
export interface NativeMediaBridgeControl {
prepareLocalEdge(
shareId: string,
connectionId: string,
sourceConnectionId?: string,
restart?: boolean,
): Promise<RTCSessionDescriptionInit & { offerId: string }>;
acceptSignal(
shareId: string,
connectionId: string,
payload: SignalPayload,
offerId?: string,
): Promise<void>;
closeEdge(shareId: string, connectionId: string): Promise<void>;
onEvent(listener: (event: NativeClientEvent) => void): () => void;
}
export class NativeMediaBridge {
readonly stream: MediaStream;
readonly connectionId = createOpaqueId();
private readonly peer: RTCPeerConnection;
private readonly remoteInput: RemoteInputChannel;
private readonly lifetime = new AbortController();
private unsubscribe: (() => void) | null = null;
private edgeRequested = false;
private ready = false;
private disposed = false;
private expectedAudio = false;
private deadline: number | null = null;
private disconnectTimer: number | null = null;
private completeNegotiation: (() => void) | null = null;
private rejectNegotiation: ((error: Error) => void) | null = null;
private releaseDebug: (() => void) | undefined;
constructor(
private readonly shareId: string,
private readonly control: NativeMediaBridgeControl,
private readonly onFailed: () => void,
private readonly sourceConnectionId?: string,
onRemoteInput: () => void = () => {},
) {
this.remoteInput = new RemoteInputChannel(() => { if (!this.disposed) onRemoteInput(); });
let peer: RTCPeerConnection | undefined;
try {
this.stream = new MediaStream();
this.peer = peer = new RTCPeerConnection();
this.releaseDebug = observeDebugConnection(this.peer, { connectionId: this.connectionId, sourceConnectionId, shareId, role: "native-preview" });
} catch (error) {
peer?.close();
debugError("native-bridge", "initialization-failed", error);
throw new NativeMediaBridgeInitializationError("Native media bridge could not initialize", { cause: error });
}
}
collectMetrics(accumulator: StatsAccumulator): Promise<ConnectionMetrics> {
return collectConnectionMetrics(this.peer, "receive", accumulator);
}
getRemoteInput(): RTCDataChannel | null { return this.remoteInput.current; }
async decodedVideoFrames(): Promise<number | null> {
const track = this.stream.getVideoTracks()[0];
return decodedVideoFrames(
await this.peer.getStats(),
track ? { trackIdentifier: track.id } : null,
);
}
async start(expectedAudio = false): Promise<MediaStream> {
if (this.disposed || this.unsubscribe) {
throw new NativeMediaBridgeError("Native media bridge is unavailable");
}
this.expectedAudio = expectedAudio;
this.remoteInput.attach(this.peer);
this.peer.addEventListener("track", (event) => {
if (this.disposed) return;
if (!this.stream.getTracks().includes(event.track)) this.stream.addTrack(event.track);
this.completeNegotiation?.();
});
this.peer.addEventListener("connectionstatechange", () => {
debugEvent("native-bridge", "connection-state", { state: this.peer.connectionState });
this.connectionStateChanged(this.peer.connectionState);
this.completeNegotiation?.();
});
this.peer.addEventListener("iceconnectionstatechange", () => {
debugEvent("native-bridge", "ice-state", { state: this.peer.iceConnectionState });
});
this.peer.addEventListener("icegatheringstatechange", () => {
debugEvent("native-bridge", "ice-gathering-state", { state: this.peer.iceGatheringState });
});
this.unsubscribe = this.control.onEvent((event) => {
if (event.shareId !== this.shareId) return;
if (event.type === "share-ended") {
this.fail("share-ended");
return;
}
if (
!("connectionId" in event) ||
event.connectionId !== this.connectionId
) {
return;
}
if (event.type === "edge-state") this.connectionStateChanged(event.state);
});
return this.negotiate(false);
}
dispose(): void {
if (this.disposed) return;
this.disposed = true;
this.releaseDebug?.();
this.remoteInput.dispose();
this.lifetime.abort();
this.rejectNegotiation?.(new NativeMediaBridgeError("Native media bridge failed"));
this.rejectNegotiation = null;
this.completeNegotiation = null;
this.unsubscribe?.();
this.unsubscribe = null;
this.clearDeadline();
this.clearDisconnectTimer();
this.peer.close();
this.stream.getTracks().forEach((track) => track.stop());
if (this.edgeRequested) {
void this.control.closeEdge(this.shareId, this.connectionId).catch(
() => undefined,
);
}
}
private connectionStateChanged(state: RTCPeerConnectionState): void {
if (this.disposed) return;
if (state === "closed" || (!this.ready && state === "failed")) {
this.fail("connection-state");
return;
}
if (state === "connected") {
if (this.peer.connectionState === "connected") this.clearDisconnectTimer();
return;
}
if (!this.ready || this.completeNegotiation) return;
const restart = () => {
this.clearDisconnectTimer();
if (this.disposed || this.completeNegotiation) return;
debugEvent("native-bridge", "restart");
void this.negotiate(true).catch(() => undefined);
};
if (state === "failed") restart();
else if (state === "disconnected" && this.disconnectTimer === null) {
this.disconnectTimer = window.setTimeout(restart, DISCONNECTED_GRACE_MS);
}
}
private negotiate(restart: boolean): Promise<MediaStream> {
return new Promise((resolve, reject) => {
let signaled = false;
this.rejectNegotiation = reject;
this.deadline = window.setTimeout(() => this.fail("timeout"), BRIDGE_TIMEOUT_MS);
this.completeNegotiation = () => {
if (!signaled || this.disposed || this.peer.connectionState !== "connected" ||
this.stream.getVideoTracks().length === 0 ||
(this.expectedAudio && this.stream.getAudioTracks().length === 0)) return;
// This proves the local transport. First-frame/playback owners still
// prove media progress; an intentionally paused source can remain quiet.
this.ready = true;
this.completeNegotiation = null;
this.rejectNegotiation = null;
this.clearDeadline();
resolve(this.stream);
};
void this.exchangeDescriptions(restart).then(() => {
signaled = true;
this.completeNegotiation?.();
}).catch(error => this.fail("negotiation", error));
});
}
private async exchangeDescriptions(restart: boolean): Promise<void> {
this.edgeRequested = true;
const { offerId, ...offer } = await this.control.prepareLocalEdge(
this.shareId, this.connectionId, this.sourceConnectionId, restart,
);
this.lifetime.signal.throwIfAborted();
await this.peer.setRemoteDescription(offer);
this.lifetime.signal.throwIfAborted();
const answer = preferScreenAudioStereo(await this.peer.createAnswer());
this.lifetime.signal.throwIfAborted();
requireReceivingVideo(offer, answer);
await this.peer.setLocalDescription(answer);
await this.gatherCandidates();
this.lifetime.signal.throwIfAborted();
const sdp = this.peer.localDescription?.sdp;
if (!sdp) throw new Error("Native media bridge produced no SDP answer");
await this.control.acceptSignal(this.shareId, this.connectionId, {
kind: "description", connectionId: this.connectionId,
description: { type: "answer", sdp },
}, offerId);
}
private gatherCandidates(): Promise<void> {
const signal = this.lifetime.signal;
signal.throwIfAborted();
if (this.peer.iceGatheringState === "complete") return Promise.resolve();
return new Promise((resolve, reject) => {
const cleanup = () => {
this.peer.removeEventListener("icegatheringstatechange", complete);
signal.removeEventListener("abort", aborted);
};
const complete = () => {
if (this.peer.iceGatheringState !== "complete") return;
cleanup();
resolve();
};
const aborted = () => { cleanup(); reject(signal.reason); };
this.peer.addEventListener("icegatheringstatechange", complete);
signal.addEventListener("abort", aborted, { once: true });
});
}
private fail(reason: string, error?: unknown): void {
if (this.disposed) return;
const details = { type: reason, state: this.ready ? "active" : "starting" };
if (error === undefined) debugEvent("native-bridge", "failed", details);
else debugError("native-bridge", "failed", error, details);
void this.reportFailureDiagnostics();
this.rejectNegotiation?.(new NativeMediaBridgeError("Native media bridge failed", { cause: error }));
this.rejectNegotiation = null;
if (this.ready) this.onFailed();
this.dispose();
}
private async reportFailureDiagnostics(): Promise<void> {
if (!browserDebugEnabled) return;
try {
debugEvent("native-bridge", "connection-state", { state: this.peer.connectionState });
debugEvent("native-bridge", "ice-state", { state: this.peer.iceConnectionState });
debugEvent("native-bridge", "ice-gathering-state", { state: this.peer.iceGatheringState });
const receivers = this.peer.getReceivers();
for (const kind of ["video", "audio"]) {
debugEvent("native-bridge", "receiver-count", {
type: kind, state: "live",
count: receivers.filter((receiver) => receiver.track.kind === kind && receiver.track.readyState === "live").length,
});
}
for (const transport of new Set(receivers.map((receiver) => receiver.transport))) {
if (transport) debugEvent("native-bridge", "dtls-state", { state: transport.state });
}
// Start the one snapshot before disposal; it never delays the bridge deadline.
const stats = Array.from((await this.peer.getStats()).values());
for (const direction of ["local", "remote"]) {
for (const type of ["host", "srflx", "prflx", "relay"]) {
for (const protocol of ["udp", "tcp"]) {
debugEvent("native-bridge", "candidate-count", {
type: `${direction}-${type}`, state: protocol,
count: stats.filter((entry) => entry.type === `${direction}-candidate` &&
entry.candidateType === type && entry.protocol === protocol).length,
});
}
}
}
} catch (error) {
debugError("native-bridge", "diagnostics-failed", error);
}
}
private clearDeadline(): void {
if (this.deadline === null) return;
window.clearTimeout(this.deadline);
this.deadline = null;
}
private clearDisconnectTimer(): void {
if (this.disconnectTimer === null) return;
window.clearTimeout(this.disconnectTimer);
this.disconnectTimer = null;
}
}
+1 -121
View File
@@ -1,99 +1,4 @@
import type { ServerMessage } from "../../shared/protocol";
import { NativeRequestError } from "../native/client";
import { NativeMediaBridgeError, NativeMediaBridgeInitializationError } from "../native/media-bridge";
import { currentLang, joinSentences, say, type CopyKey } from "../ui/copy";
export type HostAction =
| "capture"
| "source"
| "sourceAudio"
| "quality"
| "connection"
| "room";
const HOST_ACTION_FALLBACK: Record<HostAction, CopyKey> = {
capture: "host.fail.start",
source: "host.fail.source",
sourceAudio: "host.fail.sourceAudio",
quality: "host.fail.quality",
connection: "host.fail.connection",
room: "host.fail.room",
};
type ServerErrorCode = Extract<
ServerMessage,
{ type: "error" }
>["code"];
const HOST_SERVER_ERROR_NOTICE: Record<ServerErrorCode, CopyKey> = {
AUTH_REQUIRED: "gate.expired",
INVALID_MESSAGE: "host.terminated.stale",
INVALID_TOKEN: "host.err.invalidToken",
ROOM_NOT_FOUND: "viewer.msg.notFound",
ROOM_ACCESS_DENIED: "host.err.accessDenied",
ROOM_FULL: "join.full",
HOST_ALREADY_CONNECTED: "host.err.alreadyConnected",
PEER_NOT_FOUND: "host.err.peerGone",
FORBIDDEN: "host.err.forbidden",
SERVER_ERROR: "host.err.serverError",
};
export function isCapturePermissionFailure(error: unknown, action: HostAction): boolean {
return (action === "capture" || action === "source") &&
error instanceof DOMException && error.name === "NotAllowedError";
}
export function hostActionErrorKey(
error: unknown,
action: HostAction,
): CopyKey {
if (error instanceof NativeRequestError) {
switch (error.reason) {
case "unavailable":
case "disconnected":
case "send-failed": return "native.fail.controlDisconnected";
case "timeout": return "native.fail.requestTimeout";
case "invalid-response": return "native.fail.invalidResponse";
case "rejected":
if (error.operation === "start-share") return "native.fail.captureStart";
if (error.operation === "prepare-edge") return "native.fail.edgePrepare";
break;
}
}
if (error instanceof NativeMediaBridgeInitializationError) return "native.fail.browserMedia";
if (error instanceof NativeMediaBridgeError) return "native.fail.edge";
if (isCapturePermissionFailure(error, action)) return "host.capture.cancelled";
if (
error instanceof DOMException &&
(action === "capture" || action === "source")
) {
switch (error.name) {
case "NotFoundError":
return "host.capture.noSource";
case "NotReadableError":
return "host.capture.readFailed";
case "SecurityError":
return "host.capture.unavailable";
case "InvalidStateError":
return "host.capture.inactive";
case "OverconstrainedError":
return "host.capture.constraints";
}
}
return HOST_ACTION_FALLBACK[action];
}
/** Safe support context: never copy arbitrary exception text or request fields. */
export function hostFailureCode(error: unknown, action: HostAction, source: "browser" | "camera" = "browser"): string {
if (error instanceof NativeRequestError) return `app/${error.operation}/${error.reason}`;
if (error instanceof NativeMediaBridgeInitializationError) return "app/browser-media/init";
if (error instanceof NativeMediaBridgeError) return "app/browser-media/connection";
if (error instanceof DOMException && ["NotAllowedError", "NotFoundError", "NotReadableError",
"SecurityError", "InvalidStateError", "OverconstrainedError", "AbortError"].includes(error.name)) {
return `${source}/${error.name}`;
}
return `${source === "camera" ? "camera" : action}/unknown`;
}
import type { CopyKey } from "../ui/copy";
export function hostFailureChecks(code: string): CopyKey[] {
const [scope, operation, reason] = code.split("/");
@@ -112,28 +17,3 @@ export function hostFailureChecks(code: string): CopyKey[] {
// A room/session or settings failure is not evidence that capture failed.
return [];
}
export function hostServerErrorKey(code: ServerErrorCode): CopyKey {
return HOST_SERVER_ERROR_NOTICE[code];
}
export function sourceSwitchNotice({
failedPeerCount,
sfuReplaced,
}: {
failedPeerCount: number;
sfuReplaced: boolean;
}): string {
const peerWarning =
failedPeerCount > 0 ? say("host.notice.reconnecting") : null;
if (!sfuReplaced) {
const parts = [
say("host.notice.sfuRecovering"),
peerWarning,
].filter((message): message is string => message !== null);
return joinSentences(currentLang(), parts);
}
return peerWarning
? say("host.notice.sourceSwitch.partial", { warning: peerWarning })
: say("host.notice.sourceSwitch.ok");
}
+3 -14
View File
@@ -2,20 +2,9 @@ import { parse, parsePayloads, write } from "sdp-transform";
import { OPUS_RECEIVE_MAX_BITRATE } from "../media/quality";
export function preferScreenAudioStereo(
answer: RTCSessionDescriptionInit,
): RTCSessionDescriptionInit {
return answer.type === "answer" ? preferOpusReceive(answer) : answer;
}
/** A shared transport can receive several pictures and voices in either SDP role.
* Stereo reception also accepts mono input; it does not configure capture. */
export function preferOpusStereoReceive(description: RTCSessionDescriptionInit): RTCSessionDescriptionInit {
return preferOpusReceive(description, "receiving");
}
function preferOpusReceive(answer: RTCSessionDescriptionInit,
scope: "single" | "receiving" = "single"): RTCSessionDescriptionInit {
export function preferOpusStereoReceive(answer: RTCSessionDescriptionInit): RTCSessionDescriptionInit {
const preferences = { stereo: "1", maxaveragebitrate: String(OPUS_RECEIVE_MAX_BITRATE) };
try {
if (!answer.sdp?.trim()) {
@@ -34,9 +23,9 @@ function preferOpusReceive(answer: RTCSessionDescriptionInit,
const audioSections = session.media.filter(
(media) => media.type === "audio" && media.port !== 0
&& (scope !== "receiving" || !["sendonly", "inactive"].includes(media.direction ?? session.direction ?? "sendrecv")),
&& !["sendonly", "inactive"].includes(media.direction ?? session.direction ?? "sendrecv"),
);
if (!audioSections.length || (scope === "single" && audioSections.length !== 1)) {
if (!audioSections.length) {
return answer;
}
-42
View File
@@ -1,42 +0,0 @@
import { INPUT_CHANNEL } from "../remote-control/input-route";
// Both Browser reception and the App's local playback bridge announce the
// same optional capability. Their media owner still owns the PeerConnection.
export class RemoteInputChannel {
private channel: RTCDataChannel | null = null;
private connection: RTCPeerConnection | null = null;
get current(): RTCDataChannel | null {
return this.connection?.connectionState === "connected" && this.channel?.readyState === "open" ? this.channel : null;
}
constructor(private readonly changed: () => void) {}
attach(connection: RTCPeerConnection): void {
this.dispose();
this.connection = connection;
connection.addEventListener("connectionstatechange", () => { if (this.connection === connection) this.changed(); });
connection.addEventListener("datachannel", ({ channel }) => {
if (this.connection !== connection || channel.label !== INPUT_CHANNEL || this.channel) {
channel.close();
return;
}
this.channel = channel;
channel.addEventListener("open", () => {
if (this.channel === channel) this.changed();
});
channel.addEventListener("close", () => {
if (this.channel === channel) {
this.channel = null;
this.changed();
}
});
if (channel.readyState === "open") this.changed();
});
}
dispose(): void {
this.connection = null;
const channel = this.channel;
this.channel = null;
channel?.close();
}
}
+26 -7
View File
@@ -10,6 +10,8 @@ import { ChannelShareControl } from "../src/client/channel/components/ChannelSha
import { DEFAULT_QUALITY_SETTINGS } from "../src/shared/protocol";
import type { ChannelController } from "../src/client/channel/types";
import { setCopy, t } from "../src/client/ui/copy";
import { channelAppDiscovery } from "../src/client/channel/app-link";
import { NATIVE_CLIENT_PORT_START } from "../src/client/native/discovery-ports";
vi.mock("react", async importOriginal => {
const actual = await importOriginal<typeof import("react")>();
@@ -127,8 +129,10 @@ const source = ts.createSourceFile("AppConnectionButton.tsx", readFileSync(
), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
let connect: string | undefined;
let rememberBuild: string | undefined;
let connectionProps: string | undefined;
const effects: string[] = [];
function collect(node: ts.Node): void {
if (ts.isFunctionDeclaration(node) && node.name?.text === "AppConnectionButton") connectionProps = node.parameters[0]!.getText(source);
if (ts.isFunctionDeclaration(node) && node.name?.text === "connect") connect = node.getText(source);
if (ts.isFunctionDeclaration(node) && node.name?.text === "rememberBuild") rememberBuild = node.getText(source);
if (ts.isCallExpression(node) && node.expression.getText(source) === "useEffect") {
@@ -168,16 +172,12 @@ function mount(activated = false, state: "idle" | "ready" = "idle", android = fa
window, document, pending, healthCheck, help, showHelp, setState, setBuild, activateClient, onConnected, AbortController, URL,
wakeURL: android ? "intent://app#Intent;scheme=piik;package=tv.piik.android;end" : null,
state, connected, isClientActivated: () => activated,
loadDiscovery: async () => ({ health: native.discoverNativeHealth, connect: native.discoverNativeConnect,
isIncompatible: (error: unknown) => error instanceof native.NativeCompatibilityError }),
discovery: { health: native.discoverNativeHealth, connect: native.discoverNativeConnect,
isIncompatible: (error: unknown) => error instanceof native.NativeCompatibilityError },
watchClientActivation: (changed: () => void) => {
window.addEventListener("activation", changed);
return () => window.removeEventListener("activation", changed);
},
require: (path: string) => {
if (path !== "../../native/client") throw new Error(`Unexpected dependency: ${path}`);
return native;
},
}) as { connect: (wake?: boolean) => Promise<void>; cleanup: () => void };
function message(overrides: Record<string, unknown> = {}) {
window.dispatchEvent(Object.assign(new Event("message"), {
@@ -190,6 +190,23 @@ function mount(activated = false, state: "idle" | "ready" = "idle", android = fa
}
describe("App connection approval", () => {
afterEach(() => vi.unstubAllGlobals());
it("recognizes the current App through the shared entry's default discovery", async () => {
const discovery = runInNewContext(ts.transpileModule(
`function entry(${connectionProps}) { return discovery; } entry({});`,
{ compilerOptions: { target: ts.ScriptTarget.ES2022 } },
).outputText, { channelAppDiscovery }) as typeof channelAppDiscovery;
expect(discovery).toBe(channelAppDiscovery);
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("http://127.0.0.1:8787/__status-preview") });
vi.stubGlobal("fetch", vi.fn(async (input: string) => {
const port = Number(new URL(input).port);
if (port !== NATIVE_CLIENT_PORT_START) throw new TypeError("No fixture App");
return Response.json({ service: "piik-channel-app", protocol: 1, port, token: "fixture-token" });
}));
await expect(discovery.health()).resolves.toMatchObject({ port: NATIVE_CLIENT_PORT_START });
});
it("uses fresh authorized health instead of offering approval again", async () => {
const page = mount();
page.native.discoverNativeHealth.mockResolvedValue({});
@@ -498,8 +515,10 @@ describe("App connection approval", () => {
it("does not let an earlier health check overwrite a newer approval", async () => {
const page = mount(true);
await settle();
let complete!: (health: object | null) => void;
page.native.discoverNativeHealth.mockImplementationOnce(() => new Promise(resolve => { complete = resolve; }));
page.native.discoverNativeHealth.mockClear().mockImplementationOnce(() => new Promise(resolve => { complete = resolve; }));
page.window.dispatchEvent(new Event("focus"));
await settle();
await page.openApproval();
expect(page.native.discoverNativeHealth.mock.calls[0]![0].signal.aborted).toBe(true);
-54
View File
@@ -276,58 +276,4 @@ describe("opt-in Browser diagnostics", () => {
}]);
expect(JSON.stringify(sample.details.ice)).not.toContain("192.0.2.");
});
it("correlates actual Native request and response using their existing wire identity", async () => {
const page = browser();
const token = "x".repeat(43);
class Socket extends EventTarget {
static OPEN = 1; static CLOSING = 2;
readyState = 1; protocol = `piik-client-v10.${token}`;
constructor() { super(); queueMicrotask(() => this.dispatchEvent(new Event("open"))); }
close() { this.readyState = 3; }
send(raw: string) {
const request = JSON.parse(raw);
queueMicrotask(() => this.dispatchEvent(Object.assign(new Event("message"), {
data: JSON.stringify({ version: 10, id: request.id,
type: request.type === "hello" ? "ready" : "share-updated",
...(request.shareId ? { shareId: request.shareId } : {}) }),
})));
}
}
vi.stubGlobal("WebSocket", Socket);
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({
protocol: 10, service: "piik-client", port: 39721, instanceToken: token,
nativeMedia: { video: true, processAudio: false, systemAudio: true, hardwareH264: true, softwareVP8: true },
}), { status: 200 })));
const debug = await import("../src/client/lib/debug");
debug.installBrowserDebug();
const { NativeClient } = await import("../src/client/native/client");
const { DEFAULT_QUALITY_SETTINGS } = await import("../src/shared/protocol");
const client = await NativeClient.connect();
expect(client).not.toBeNull();
try { await client!.updateShare("share_123456", DEFAULT_QUALITY_SETTINGS); }
finally { client!.close(); }
const history = page.__PIIK_DEBUG__!.events().filter((event) => event.details.type === "update-share");
expect(history.map((event) => event.event)).toEqual(["request", "response"]);
expect(history[1]!.details.requestId).toBe(history[0]!.details.requestId);
expect(history[1]!.details.durationMs).toBeGreaterThanOrEqual(0);
expect(history[0]!.details.requested).toMatchObject({ profile: DEFAULT_QUALITY_SETTINGS });
expect(await debug.exportBrowserDebug()).not.toContain(token);
});
it("reports an observed App mismatch without exposing its capability token", async () => {
const page = browser();
const token = "x".repeat(43);
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({
protocol: 8, service: "piik-client", port: 39721, instanceToken: token,
}))));
const debug = await import("../src/client/lib/debug");
debug.installBrowserDebug();
const { NativeClient } = await import("../src/client/native/client");
await expect(NativeClient.connect()).rejects.toMatchObject({ name: "NativeCompatibilityError" });
expect(page.__PIIK_DEBUG__!.events()).toContainEqual(expect.objectContaining({
scope: "native", event: "incompatible", details: { actualProtocol: 8, expectedProtocol: 10 },
}));
expect(await debug.exportBrowserDebug()).not.toContain(token);
});
});
+2 -115
View File
@@ -1,33 +1,8 @@
import { describe, expect, it } from "vitest";
import { say, setCopy } from "../src/client/ui/copy.ts";
import { NativeMediaBridgeError, NativeMediaBridgeInitializationError } from "../src/client/native/media-bridge";
import { NativeRequestError } from "../src/client/native/client";
import {
hostActionErrorKey,
hostFailureCode,
hostFailureChecks,
hostServerErrorKey,
sourceSwitchNotice,
} from "../src/client/pages/host-page-notices.ts";
import { hostFailureChecks } from "../src/client/pages/host-page-notices";
import { shouldPauseLocalPreview } from "../src/client/components/living/use-host-preview-playback";
setCopy({ lang: "zh" });
describe("host error notices", () => {
it("keeps known App failure boundaries and support context without claiming a driver diagnosis", () => {
const rejected = new NativeRequestError("rejected", "start-share", { cause: "private source title" });
const timeout = new NativeRequestError("timeout", "start-share");
const disconnected = new NativeRequestError("disconnected", "start-share");
expect(hostActionErrorKey(rejected, "capture")).toBe("native.fail.captureStart");
expect(hostActionErrorKey(timeout, "capture")).toBe("native.fail.requestTimeout");
expect(hostActionErrorKey(disconnected, "capture")).toBe("native.fail.controlDisconnected");
expect(hostFailureCode(rejected, "capture")).toBe("app/start-share/rejected");
expect(hostFailureCode(new Error("secret invitation and source"), "capture")).toBe("capture/unknown");
expect(hostFailureCode(new DOMException("secret", "UnrecognizedError"), "capture")).toBe("capture/unknown");
expect(hostFailureCode(new DOMException("secret", "NotAllowedError"), "capture", "camera")).toBe("camera/NotAllowedError");
});
describe("sharing troubleshooting", () => {
it.each([
["site/http-403", ["shareHelp.site"]],
["room/unknown", ["shareHelp.site"]],
@@ -48,74 +23,6 @@ describe("host error notices", () => {
])("keeps troubleshooting relevant to %s", (code, checks) => {
expect(hostFailureChecks(code as string)).toEqual(checks);
});
it.each([
["zh", "浏览器无法建立媒体连接,请刷新页面重试。"],
["en", "The browser could not create a media connection; reload to retry."],
] as const)("identifies Browser initialization failure in %s without blaming capture permission", (lang, notice) => {
setCopy({ lang });
try {
const failure = new NativeMediaBridgeInitializationError("private detail", {
cause: new DOMException("private cause", "NotAllowedError"),
});
expect(hostActionErrorKey(failure, "capture")).toBe("native.fail.browserMedia");
expect(say(hostActionErrorKey(failure, "capture"))).toBe(notice);
} finally {
setCopy({ lang: "zh" });
}
});
it("classifies the native preview bridge as a connection failure", () => {
expect(hostActionErrorKey(new NativeMediaBridgeError("private detail"), "capture"))
.toBe("native.fail.edge");
});
it("maps every server error code without exposing server text", () => {
const notices = {
AUTH_REQUIRED: "gate.expired",
INVALID_MESSAGE: "host.terminated.stale",
INVALID_TOKEN: "host.err.invalidToken",
ROOM_NOT_FOUND: "viewer.msg.notFound",
ROOM_ACCESS_DENIED: "host.err.accessDenied",
ROOM_FULL: "join.full",
HOST_ALREADY_CONNECTED: "host.err.alreadyConnected",
PEER_NOT_FOUND: "host.err.peerGone",
FORBIDDEN: "host.err.forbidden",
SERVER_ERROR: "host.err.serverError",
} as const;
for (const [code, notice] of Object.entries(notices)) {
expect(
hostServerErrorKey(code as keyof typeof notices),
).toBe(notice);
expect(notice).not.toContain("server-internal-sentinel");
}
});
it("uses stable action messages instead of arbitrary exception text", () => {
const sentinel = new Error("browser-internal-sentinel");
expect(hostActionErrorKey(sentinel, "quality")).toBe(
"host.fail.quality",
);
expect(hostActionErrorKey(sentinel, "connection")).toBe(
"host.fail.connection",
);
expect(hostActionErrorKey(sentinel, "room")).toBe("host.fail.room");
expect(hostActionErrorKey(sentinel, "source")).toBe("host.fail.source");
expect(hostActionErrorKey(sentinel, "sourceAudio")).toBe("host.fail.sourceAudio");
});
it.each([
["NotAllowedError", "host.capture.cancelled"],
["NotFoundError", "host.capture.noSource"],
["NotReadableError", "host.capture.readFailed"],
["SecurityError", "host.capture.unavailable"],
["InvalidStateError", "host.capture.inactive"],
["OverconstrainedError", "host.capture.constraints"],
])("maps capture DOMException %s", (name, notice) => {
expect(
hostActionErrorKey(new DOMException("raw-browser-text", name), "capture"),
).toBe(notice);
});
});
describe("shouldPauseLocalPreview", () => {
@@ -128,23 +35,3 @@ describe("shouldPauseLocalPreview", () => {
expect(shouldPauseLocalPreview("hidden", false, false, false)).toBe(false);
});
});
describe("sourceSwitchNotice", () => {
it("does not report success when the SFU source replacement failed", () => {
expect(
sourceSwitchNotice({
failedPeerCount: 0,
sfuReplaced: false,
}),
).toBe("服务器中转的画面来源未切换成功,正在恢复观看连接");
});
it("reports success only when every active route replacement succeeded", () => {
expect(
sourceSwitchNotice({
failedPeerCount: 0,
sfuReplaced: true,
}),
).toBe("分享来源已切换");
});
});
-32
View File
@@ -8,11 +8,9 @@ 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";
@@ -302,33 +300,3 @@ describe("native capture source selection", () => {
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();
});
});
+86 -640
View File
@@ -1,8 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { z } from "zod";
import { discoverNativeConnect, discoverNativeHealth, NativeClient, NativeCompatibilityError, notifyNativePresentation } from "../src/client/native/client";
import { DEFAULT_QUALITY_SETTINGS } from "../src/shared/protocol";
import { NATIVE_CLIENT_PORT_START, NATIVE_CLIENT_PORT_END } from "../src/client/native/discovery-ports";
import { channelAppDiscovery, discoverChannelAppHealth, nativeConnectionMetricsSchema } from "../src/client/channel/app-link";
@@ -76,23 +74,8 @@ it("uses an explicit non-secret App port outside the default scan range", async
}
});
describe("native App private wire", () => {
it("preserves the published strict failure reader for requests without cancellation opt-in", () => {
const published = z.object({ version: z.literal(10), id: z.string(), type: z.literal("request-failed"), code: z.literal("operation-failed") }).strict();
const legacy = { version: 10, id: "request_start", type: "request-failed", code: "operation-failed" };
expect(published.safeParse(legacy).success).toBe(true);
expect(requestFailedResponseSchema.safeParse(legacy).success).toBe(true);
const optedIn = { ...legacy, code: "source-canceled" };
expect(published.safeParse(optedIn).success).toBe(false);
expect(requestFailedResponseSchema.safeParse(optedIn).success).toBe(true);
});
const health = {
protocol: NATIVE_CLIENT_PROTOCOL,
service: "piik-client",
port: NATIVE_CLIENT_PORT_START,
instanceToken: "a".repeat(43),
nativeMedia: { video: true, hardwareH264: true },
};
describe("current App discovery", () => {
const health = { service: "piik-channel-app", protocol: 1, port: NATIVE_CLIENT_PORT_START, token: "fixture-token" };
it("discovers with caller cancellation when AbortSignal.any is unavailable", async () => {
vi.spyOn(AbortSignal, "any").mockImplementation(() => { throw new TypeError("AbortSignal.any is not a function"); });
@@ -102,64 +85,10 @@ describe("native App private wire", () => {
return new Response(JSON.stringify(health));
});
vi.stubGlobal("fetch", fetcher);
await expect(discoverNativeHealth({ signal: new AbortController().signal })).resolves.toMatchObject({ port: health.port });
await expect(discoverChannelAppHealth({ signal: new AbortController().signal })).resolves.toMatchObject({ port: health.port });
expect(fetcher).toHaveBeenCalled();
});
it.each(["localhost", "127.0.0.1", "[::1]"])("discovers and updates presentation from %s without an address-space hint", async hostname => {
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL(`http://${hostname}:8787/`) });
const query = vi.fn().mockResolvedValue({ state: "prompt" });
vi.stubGlobal("navigator", { permissions: { query } });
const fetcher = vi.fn((url: string, init: RequestInit) => {
if ("targetAddressSpace" in init) throw new TypeError("loopback is not a valid IPAddressSpace enum value");
return Promise.resolve(new Response(JSON.stringify(url.endsWith("quality-preference") ? DEFAULT_QUALITY_SETTINGS
: url.endsWith("connect-discovery") ? { ...health, connectURL: "http://127.0.0.1:54321/client" }
: { ...health, qualityPreference: true })));
});
vi.stubGlobal("fetch", fetcher);
await expect(discoverNativeHealth({ waitForPermission: false })).resolves.toMatchObject({ port: health.port });
await expect(discoverNativeConnect()).resolves.toContain("http://127.0.0.1:54321/client?");
await notifyNativePresentation("en", new AbortController().signal);
expect(query).not.toHaveBeenCalled();
expect(fetcher).toHaveBeenCalledWith(`http://127.0.0.1:${health.port}/presentation`, expect.objectContaining({ method: "POST" }));
expect(fetcher.mock.calls.every(([, init]) => !("targetAddressSpace" in init))).toBe(true);
});
it("retains the address-space hint for hosted discovery and presentation without a no-hint fallback", async () => {
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/") });
vi.stubGlobal("navigator", { permissions: { query: vi.fn().mockResolvedValue({ state: "granted" }) } });
const fetcher = vi.fn(async (url: string, _init: RequestInit) => new Response(JSON.stringify(
url.endsWith("quality-preference") ? DEFAULT_QUALITY_SETTINGS : { ...health, qualityPreference: true })));
vi.stubGlobal("fetch", fetcher);
await notifyNativePresentation("en", new AbortController().signal);
expect(fetcher.mock.calls.every(call => (call[1] as RequestInit & { targetAddressSpace: string }).targetAddressSpace === "loopback")).toBe(true);
expect(fetcher).toHaveBeenCalledWith(`http://127.0.0.1:${health.port}/presentation`, expect.objectContaining({ targetAddressSpace: "loopback" }));
fetcher.mockImplementation(() => { throw new TypeError("Unsupported IPAddressSpace"); });
fetcher.mockClear();
await expect(discoverNativeHealth()).resolves.toBeNull();
expect(fetcher).toHaveBeenCalledTimes(NATIVE_CLIENT_PORT_END - NATIVE_CLIENT_PORT_START + 1);
expect(fetcher.mock.calls.every(call => (call[1] as RequestInit & { targetAddressSpace: string }).targetAddressSpace === "loopback")).toBe(true);
});
it("requires the controlled App platform in remote-control state", () => {
const event = { version: NATIVE_CLIENT_PROTOCOL, type: "remote-control-state", shareId: "share_123456", mode: "off", requests: [] };
expect(nativeEventSchema.safeParse(event).success).toBe(false);
for (const platform of ["windows", "darwin", "linux"]) {
expect(nativeEventSchema.parse({ ...event, platform })).toMatchObject({ platform });
}
expect(nativeEventSchema.safeParse({ ...event, platform: "unknown" }).success).toBe(false);
});
it.each(["prompt", "denied"])("background App preferences do not request local access when permission is %s", async (state) => {
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/") });
vi.stubGlobal("navigator", { permissions: { query: vi.fn().mockResolvedValue({ state }) } });
const fetcher = vi.fn(async () => new Response(JSON.stringify(health)));
vi.stubGlobal("fetch", fetcher);
const controller = new AbortController();
await notifyNativePresentation("en", controller.signal);
expect(fetcher).not.toHaveBeenCalled();
});
it("discovers only a local approval page without opening native control", async () => {
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/r/9527") });
const socket = vi.fn();
@@ -168,7 +97,7 @@ describe("native App private wire", () => {
? new Response(JSON.stringify({ ...health, connectURL: "http://127.0.0.1:54321/client" }))
: new Response(null, { status: 404 }));
vi.stubGlobal("fetch", fetcher);
await expect(discoverNativeConnect()).resolves.toBe("http://127.0.0.1:54321/client?site=https%3A%2F%2Fpiik.example");
await expect(channelAppDiscovery.connect()).resolves.toBe("http://127.0.0.1:54321/client?site=https%3A%2F%2Fpiik.example");
expect(fetcher.mock.calls.every(([url]) => url.endsWith("/connect-discovery"))).toBe(true);
expect(socket).not.toHaveBeenCalled();
});
@@ -180,7 +109,7 @@ describe("native App private wire", () => {
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/") });
vi.stubGlobal("fetch", vi.fn(async (url: string) => url === `http://127.0.0.1:${health.port}/connect-discovery`
? new Response(JSON.stringify({ ...health, connectURL })) : new Response(null, { status: 404 })));
await expect(discoverNativeConnect()).resolves.toBeNull();
await expect(channelAppDiscovery.connect()).resolves.toBeNull();
});
it.each([false, true])("cancels the whole approval scan with its caller (permission prompt: %s)", async prompting => {
@@ -196,7 +125,7 @@ describe("native App private wire", () => {
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
})));
const controller = new AbortController();
const result = discoverNativeConnect(controller.signal);
const result = channelAppDiscovery.connect(controller.signal);
await vi.waitFor(() => expect(signals).toHaveLength(NATIVE_CLIENT_PORT_END - NATIVE_CLIENT_PORT_START + 1));
controller.abort();
await expect(result).resolves.toBeNull();
@@ -204,110 +133,6 @@ describe("native App private wire", () => {
expect(signals.every(signal => signal.aborted)).toBe(true);
});
it("reads numeric video capability descriptions and rejects malformed limits", () => {
const nativeMedia = { ...health.nativeMedia, maxVideoResolution: { width: 3840, height: 3840 },
maxVideoPixels: 3840 * 2160, maxVideoMacroblocksPerSecond: 983_040 };
expect(nativeHealthSchema.parse({ ...health, nativeMedia }).nativeMedia).toMatchObject(nativeMedia);
const stronger = { ...nativeMedia, maxVideoResolution: { width: 32768, height: 32768 },
maxVideoPixels: 32768 ** 2, maxVideoFramerate: 120, maxVideoBitrate: 100_000_000,
maxAudioBitrate: 960_000, maxRelayChildren: 32 };
const strongerHealth = nativeHealthSchema.parse({ ...health, nativeMedia: stronger });
expect(strongerHealth.nativeMedia).toMatchObject(stronger);
expect(nativeRelayCapacity(20, strongerHealth)).toBe(20);
expect(nativeHealthSchema.safeParse({ ...health, nativeMedia: { ...nativeMedia, maxVideoPixels: 0 } }).success).toBe(false);
expect(nativeHealthSchema.safeParse({ ...health, nativeMedia: { ...nativeMedia, maxVideoMacroblocksPerSecond: -1 } }).success).toBe(false);
expect(nativeHealthSchema.parse({ ...health, nativeMedia: { ...nativeMedia, maxRelayChildren: 20 } })
.nativeMedia.maxRelayChildren).toBe(20);
for (const maxRelayChildren of [0, 0x1_0000_0000, 1.5]) {
expect(nativeHealthSchema.safeParse({ ...health, nativeMedia: { ...nativeMedia, maxRelayChildren } }).success).toBe(false);
}
});
it.each(["opening", "hello", "close"])("retires App acquisition during %s without waiting for its timeout", async stage => {
vi.useFakeTimers();
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/") });
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify(health))));
const sockets: Socket[] = [];
class Socket extends EventTarget {
static readonly OPEN = 1;
static readonly CLOSING = 2;
readyState = 0;
protocol = `piik-client-v10.${health.instanceToken}`;
close = vi.fn(() => { this.readyState = Socket.CLOSING; });
send = vi.fn();
constructor() { super(); sockets.push(this); }
}
vi.stubGlobal("WebSocket", Socket);
const controller = new AbortController();
const settled = vi.fn();
const connecting = NativeClient.connect({ signal: controller.signal }).then(settled);
await vi.advanceTimersByTimeAsync(0);
const socket = sockets[0]!;
expect(socket).toBeDefined();
if (stage === "hello") {
socket.readyState = Socket.OPEN;
socket.dispatchEvent(new Event("open"));
await vi.advanceTimersByTimeAsync(0);
expect(socket.send).toHaveBeenCalledOnce();
}
if (stage === "close") {
socket.readyState = 3;
socket.dispatchEvent(new Event("close"));
} else controller.abort();
await vi.advanceTimersByTimeAsync(0);
expect(settled).toHaveBeenCalledExactlyOnceWith(null);
expect(vi.getTimerCount()).toBe(0);
if (stage !== "close") expect(socket.close).toHaveBeenCalledOnce();
// An obsolete opening event cannot start a hello or revive acquisition.
socket.dispatchEvent(new Event("open"));
await vi.advanceTimersByTimeAsync(0);
expect(socket.send).toHaveBeenCalledTimes(stage === "hello" ? 1 : 0);
await connecting;
});
it("binds a local answer to its prepare request across an ICE restart", async () => {
const requests: Record<string, unknown>[] = [];
class Socket extends EventTarget {
static readonly OPEN = 1;
static readonly CLOSING = 2;
readyState = Socket.OPEN;
protocol = `piik-client-v10.${health.instanceToken}`;
constructor() { super(); queueMicrotask(() => this.dispatchEvent(new Event("open"))); }
close() { this.readyState = Socket.CLOSING; }
send(payload: string) {
const request = JSON.parse(payload) as Record<string, unknown>;
requests.push(request);
const fields = request.type === "hello" ? { type: "ready" }
: request.type === "prepare-local-edge" ? {
type: "edge-offer", shareId: request.shareId, connectionId: request.connectionId, sdp: "v=0\r\n",
} : { type: "edge-answer-accepted" };
queueMicrotask(() => this.dispatchEvent(new MessageEvent("message", {
data: JSON.stringify({ version: 10, id: request.id, ...fields }),
})));
}
}
vi.stubGlobal("WebSocket", Socket);
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/") });
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify(health))));
const controller = new AbortController();
const client = (await NativeClient.connect({ signal: controller.signal }))!;
controller.abort(); // Acquisition cancellation no longer owns this accepted client.
try {
let lastOffer = "";
for (const restart of [false, true]) {
const offer = await client.prepareLocalEdge("share_123456", "local_123456", "source_123456", restart);
expect(offer.offerId).toBe(requests.at(-1)?.id);
expect(offer.offerId).not.toBe(lastOffer);
expect(requests.at(-1)).toMatchObject({ type: "prepare-local-edge", restart, sourceConnectionId: "source_123456" });
await client.acceptSignal("share_123456", "local_123456", {
kind: "description", connectionId: "local_123456", description: { type: "answer", sdp: "v=0\r\n" },
}, offer.offerId);
expect(requests.at(-1)).toMatchObject({ type: "edge-answer", offerId: offer.offerId });
lastOffer = offer.offerId;
}
} finally { client.close(); }
});
it.each(["prompt", "denied"] as const)("does not hold Viewer reception for %s permission and observes a later grant", async (state) => {
vi.stubGlobal("window", { setTimeout, clearTimeout, location: { hostname: "piik.example" } });
const query = vi.fn().mockResolvedValue({ state });
@@ -317,11 +142,11 @@ describe("native App private wire", () => {
const socket = vi.fn();
vi.stubGlobal("WebSocket", socket);
await expect(NativeClient.connect({ waitForPermission: false })).resolves.toBeNull();
await expect(discoverChannelAppHealth({ waitForPermission: false })).resolves.toBeNull();
expect(fetcher).not.toHaveBeenCalled();
expect(socket).not.toHaveBeenCalled();
query.mockResolvedValue({ state: "granted" });
await expect(discoverNativeHealth({ waitForPermission: false })).resolves.toMatchObject({ port: health.port });
await expect(discoverChannelAppHealth({ waitForPermission: false })).resolves.toMatchObject({ port: health.port });
});
it("still lets explicit source discovery ask for local permission", async () => {
@@ -329,7 +154,7 @@ describe("native App private wire", () => {
const query = vi.fn().mockResolvedValue(Object.assign(new EventTarget(), { state: "prompt" }));
vi.stubGlobal("navigator", { permissions: { query } });
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify(health))));
await expect(discoverNativeHealth()).resolves.toMatchObject({ port: health.port });
await expect(discoverChannelAppHealth()).resolves.toMatchObject({ port: health.port });
expect(query).toHaveBeenCalledOnce();
});
@@ -338,7 +163,7 @@ describe("native App private wire", () => {
const query = vi.fn().mockResolvedValue({ state: "prompt" });
vi.stubGlobal("navigator", { permissions: { query } });
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify(health))));
await expect(discoverNativeHealth({ waitForPermission: false })).resolves.toMatchObject({ port: health.port });
await expect(discoverChannelAppHealth({ waitForPermission: false })).resolves.toMatchObject({ port: health.port });
expect(query).not.toHaveBeenCalled();
});
@@ -349,7 +174,7 @@ describe("native App private wire", () => {
vi.stubGlobal("navigator", { permissions: { query } });
const fetcher = vi.fn();
vi.stubGlobal("fetch", fetcher);
await expect(discoverNativeHealth({ waitForPermission: false })).resolves.toBeNull();
await expect(discoverChannelAppHealth({ waitForPermission: false })).resolves.toBeNull();
expect(query).toHaveBeenLastCalledWith({ name: "local-network-access" });
expect(fetcher).not.toHaveBeenCalled();
});
@@ -360,28 +185,7 @@ describe("native App private wire", () => {
vi.stubGlobal("window", { setTimeout, clearTimeout, location: { hostname: "piik.example" } });
vi.stubGlobal("navigator", { permissions });
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify(health))));
await expect(discoverNativeHealth({ waitForPermission: false })).resolves.toMatchObject({ port: health.port });
},
);
it.each([NATIVE_CLIENT_PROTOCOL - 1, NATIVE_CLIENT_PROTOCOL + 1])(
"reports observed Piik App protocol %s without opening control or presentation",
async (protocol) => {
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("http://127.0.0.1/") });
const socket = vi.fn();
vi.stubGlobal("WebSocket", socket);
const fetcher = vi.fn(async (url: string) => url === `http://127.0.0.1:${health.port}/health`
? new Response(JSON.stringify({ ...health, protocol }))
: new Response(null, { status: 403 }));
vi.stubGlobal("fetch", fetcher);
await expect(NativeClient.connect()).rejects.toMatchObject({
name: "NativeCompatibilityError", actualProtocol: protocol,
});
await expect(notifyNativePresentation("en", new AbortController().signal))
.rejects.toBeInstanceOf(NativeCompatibilityError);
expect(socket).not.toHaveBeenCalled();
expect(fetcher.mock.calls.every(([url]) => url.endsWith("/health"))).toBe(true);
expect(fetcher).toHaveBeenCalledTimes(2 * (NATIVE_CLIENT_PORT_END - NATIVE_CLIENT_PORT_START + 1));
await expect(discoverChannelAppHealth({ waitForPermission: false })).resolves.toMatchObject({ port: health.port });
},
);
@@ -390,12 +194,12 @@ describe("native App private wire", () => {
const fetcher = vi.fn(async (url: string) => {
const port = Number(new URL(url).port);
return new Response(JSON.stringify({ ...health, port,
protocol: port === health.port ? NATIVE_CLIENT_PROTOCOL + 1 : NATIVE_CLIENT_PROTOCOL,
protocol: port === health.port ? 1 + 1 : 1,
}));
});
vi.stubGlobal("fetch", fetcher);
await expect(discoverNativeHealth()).resolves.toMatchObject({
protocol: NATIVE_CLIENT_PROTOCOL, port: NATIVE_CLIENT_PORT_START + 1,
await expect(discoverChannelAppHealth()).resolves.toMatchObject({
protocol: 1, port: NATIVE_CLIENT_PORT_START + 1,
});
expect(fetcher).toHaveBeenCalledTimes(NATIVE_CLIENT_PORT_END - NATIVE_CLIENT_PORT_START + 1);
});
@@ -414,7 +218,7 @@ describe("native App private wire", () => {
});
return new Response(JSON.stringify(health));
}));
const discovery = discoverNativeHealth();
const discovery = discoverChannelAppHealth();
await vi.advanceTimersByTimeAsync(1_500);
await expect(discovery).resolves.toMatchObject({ port: health.port });
expect(vi.getTimerCount()).toBe(0);
@@ -436,7 +240,7 @@ describe("native App private wire", () => {
});
}));
const settled = vi.fn();
const discovery = discoverNativeHealth().then(settled);
const discovery = discoverChannelAppHealth().then(settled);
await vi.advanceTimersByTimeAsync(12_000);
expect(settled).not.toHaveBeenCalled();
permission.state = "granted";
@@ -463,7 +267,7 @@ describe("native App private wire", () => {
if (port !== health.port + 1) throw new TypeError("No listener");
return new Response(JSON.stringify({ ...health, port }));
}));
await expect(discoverNativeHealth()).resolves.toMatchObject({ port: health.port + 1 });
await expect(discoverChannelAppHealth()).resolves.toMatchObject({ port: health.port + 1 });
expect(silentSignal?.aborted).toBe(true);
});
@@ -481,7 +285,7 @@ describe("native App private wire", () => {
options.signal!.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true });
});
}));
const discovery = discoverNativeHealth({ signal: new AbortController().signal });
const discovery = discoverChannelAppHealth({ signal: new AbortController().signal });
if (mode === "grant") {
await vi.advanceTimersByTimeAsync(12_000);
expect(signals.every(signal => !signal.aborted)).toBe(true);
@@ -503,21 +307,32 @@ describe("native App private wire", () => {
vi.stubGlobal("navigator", { permissions: { query: vi.fn().mockResolvedValue(permission) } });
const fetcher = vi.fn().mockRejectedValue(new TypeError("No listener"));
vi.stubGlobal("fetch", fetcher);
await expect(discoverNativeHealth()).resolves.toBeNull();
await expect(discoverChannelAppHealth()).resolves.toBeNull();
expect(fetcher).toHaveBeenCalledTimes(NATIVE_CLIENT_PORT_END - NATIVE_CLIENT_PORT_START + 1);
expect(remove).toHaveBeenCalledWith("change", expect.any(Function));
expect(vi.getTimerCount()).toBe(0);
});
it("identifies an incompatible App even when that protocol uses different token or media metadata", async () => {
it("retains the hosted address-space hint without a no-hint fallback", async () => {
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/") });
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({
...health, protocol: NATIVE_CLIENT_PROTOCOL + 1,
instanceToken: { format: "different-protocol" }, nativeMedia: "different-protocol",
}))));
await expect(NativeClient.connect()).rejects.toMatchObject({
name: "NativeCompatibilityError", actualProtocol: NATIVE_CLIENT_PROTOCOL + 1,
});
vi.stubGlobal("navigator", { permissions: { query: vi.fn().mockResolvedValue({ state: "granted" }) } });
const fetcher = vi.fn(async (_url: string, _init: RequestInit) => Response.json(health));
vi.stubGlobal("fetch", fetcher);
await expect(discoverChannelAppHealth()).resolves.toMatchObject({ port: health.port });
expect(fetcher.mock.calls.every(call => (call[1] as RequestInit & { targetAddressSpace: string }).targetAddressSpace === "loopback")).toBe(true);
fetcher.mockImplementation(() => { throw new TypeError("Unsupported IPAddressSpace"); });
fetcher.mockClear();
await expect(discoverChannelAppHealth()).resolves.toBeNull();
expect(fetcher).toHaveBeenCalledTimes(NATIVE_CLIENT_PORT_END - NATIVE_CLIENT_PORT_START + 1);
expect(fetcher.mock.calls.every(call => (call[1] as RequestInit & { targetAddressSpace: string }).targetAddressSpace === "loopback")).toBe(true);
});
it("identifies an incompatible App before reading its protocol-specific metadata", async () => {
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("http://127.0.0.1/") });
vi.stubGlobal("fetch", vi.fn(async (input: string) => Response.json({
service: "piik-channel-app", protocol: 2, port: Number(new URL(input).port), token: { format: "different-protocol" },
})));
await expect(discoverChannelAppHealth().catch(error => channelAppDiscovery.isIncompatible(error))).resolves.toBe(true);
});
it("treats denied, absent and malformed endpoints as ordinary Browser-only operation", async () => {
@@ -525,8 +340,8 @@ describe("native App private wire", () => {
const malformed = [
{ ...health, service: "another-service" },
{ ...health, protocol: "8" },
{ ...health, instanceToken: "invalid" },
{ ...health, nativeMedia: { video: "yes" } },
{ ...health, token: 42 },
{ ...health, token: undefined },
{ ...health, protocol: 8, port: NATIVE_CLIENT_PORT_END },
];
let responseIndex = 0;
@@ -536,137 +351,55 @@ describe("native App private wire", () => {
if (responseIndex % 2 === 0) return new Response(null, { status: 403 });
throw new TypeError("Network unavailable");
}));
await expect(NativeClient.connect()).resolves.toBeNull();
await expect(discoverChannelAppHealth()).resolves.toBeNull();
});
});
describe("published Native wire", () => {
const health = {
protocol: NATIVE_CLIENT_PROTOCOL,
service: "piik-client",
port: NATIVE_CLIENT_PORT_START,
instanceToken: "a".repeat(43),
nativeMedia: { video: true, hardwareH264: true },
};
it("preserves the published strict failure reader for requests without cancellation opt-in", () => {
const published = z.object({ version: z.literal(10), id: z.string(), type: z.literal("request-failed"), code: z.literal("operation-failed") }).strict();
const legacy = { version: 10, id: "request_start", type: "request-failed", code: "operation-failed" };
expect(published.safeParse(legacy).success).toBe(true);
expect(requestFailedResponseSchema.safeParse(legacy).success).toBe(true);
const optedIn = { ...legacy, code: "source-canceled" };
expect(published.safeParse(optedIn).success).toBe(false);
expect(requestFailedResponseSchema.safeParse(optedIn).success).toBe(true);
});
it("notifies only the current presentation request after App discovery", async () => {
vi.stubGlobal("window", {
setTimeout: globalThis.setTimeout,
clearTimeout: globalThis.clearTimeout,
location: new URL("http://127.0.0.1/"),
});
const fetcher = vi.fn(async (url: string) => url.endsWith("/health")
? new Response(JSON.stringify({
protocol: 10, service: "piik-client", port: 39_721,
instanceToken: "a".repeat(43),
nativeMedia: {video: true, processAudio: false, systemAudio: true, hardwareH264: true, softwareVP8: true},
}), {status: 200})
: new Response(null, {status: 204}));
vi.stubGlobal("fetch", fetcher);
const stale = new AbortController();
const staleNotification = notifyNativePresentation("zh", stale.signal);
stale.abort();
await staleNotification;
expect(fetcher).not.toHaveBeenCalled();
const current = new AbortController();
await notifyNativePresentation("vis", current.signal);
expect(fetcher).toHaveBeenCalledWith("http://127.0.0.1:39721/health", expect.anything());
expect(fetcher).toHaveBeenLastCalledWith("http://127.0.0.1:39721/presentation", expect.objectContaining({
method: "POST", body: JSON.stringify({language: "vis"}), signal: current.signal,
}));
});
it("notifies the owner once on an unexpected close and stays silent on cleanup", async () => {
const sockets: FakeWebSocket[] = [];
const token = "a".repeat(43);
let failureCode = "operation-failed";
class FakeWebSocket extends EventTarget {
static readonly OPEN = 1;
static readonly CLOSING = 2;
static readonly CLOSED = 3;
readyState = FakeWebSocket.OPEN;
protocol = `piik-client-v10.${token}`;
readonly close = vi.fn(() => {
this.readyState = FakeWebSocket.CLOSING;
});
constructor(readonly url: string, readonly protocols: string[]) {
super();
sockets.push(this);
queueMicrotask(() => this.dispatchEvent(new Event("open")));
}
send(payload: string): void {
const request = JSON.parse(payload) as { id: string; type: string };
if (!["hello", "update-share", "ping"].includes(request.type)) return;
queueMicrotask(() => {
const event = new Event("message");
Object.defineProperty(event, "data", {
value: JSON.stringify({
version: 10,
id: request.id,
type: request.type === "hello" ? "ready" : request.type === "ping" ? "pong" : "request-failed",
...(request.type === "update-share" ? { code: failureCode } : {}),
}),
});
this.dispatchEvent(event);
});
}
emitUnexpectedClose(): void {
this.readyState = FakeWebSocket.CLOSED;
this.dispatchEvent(new Event("close"));
}
it("requires the controlled App platform in remote-control state", () => {
const event = { version: NATIVE_CLIENT_PROTOCOL, type: "remote-control-state", shareId: "share_123456", mode: "off", requests: [] };
expect(nativeEventSchema.safeParse(event).success).toBe(false);
for (const platform of ["windows", "darwin", "linux"]) {
expect(nativeEventSchema.parse({ ...event, platform })).toMatchObject({ platform });
}
vi.stubGlobal("WebSocket", FakeWebSocket);
vi.stubGlobal("window", {
setTimeout: globalThis.setTimeout,
clearTimeout: globalThis.clearTimeout,
location: new URL("https://piik.example/"),
});
vi.stubGlobal("fetch", vi.fn(async () =>
new Response(JSON.stringify({
protocol: 10,
service: "piik-client",
port: 39_721,
instanceToken: token,
nativeMedia: {
video: true,
processAudio: false,
systemAudio: false,
hardwareH264: true,
softwareVP8: true,
},
}), { status: 200 }),
));
expect(nativeEventSchema.safeParse({ ...event, platform: "unknown" }).success).toBe(false);
});
const client = await NativeClient.connect();
expect(client).not.toBeNull();
const unexpected = vi.fn();
client!.onClose(unexpected);
await expect(client!.updateShare("share_123456", DEFAULT_QUALITY_SETTINGS))
.rejects.toMatchObject({ name: "NativeRequestError", reason: "rejected", operation: "update-share" });
failureCode = "source-canceled";
await expect(client!.updateShare("share_123456", DEFAULT_QUALITY_SETTINGS))
.rejects.toMatchObject({ name: "NotAllowedError" });
await client!.ping();
expect(sockets[0]!.close).not.toHaveBeenCalled();
expect(unexpected).not.toHaveBeenCalled();
vi.useFakeTimers();
window.setTimeout = globalThis.setTimeout;
window.clearTimeout = globalThis.clearTimeout;
const timedOut = expect(client!.sources()).rejects.toMatchObject({ reason: "timeout", operation: "list-sources" });
await vi.advanceTimersByTimeAsync(8_000);
await timedOut;
expect(sockets[0]!.close).not.toHaveBeenCalled();
vi.useRealTimers();
window.setTimeout = globalThis.setTimeout;
window.clearTimeout = globalThis.clearTimeout;
const pending = client!.sources();
const closedRequest = expect(pending).rejects.toMatchObject({ name: "NativeRequestError", reason: "disconnected", operation: "list-sources" });
sockets[0]!.emitUnexpectedClose();
sockets[0]!.emitUnexpectedClose();
expect(unexpected).toHaveBeenCalledOnce();
await closedRequest;
await expect(client!.sources()).rejects.toMatchObject({ reason: "unavailable", operation: "list-sources" });
const cleanClient = await NativeClient.connect();
expect(cleanClient).not.toBeNull();
const intentional = vi.fn();
cleanClient!.onClose(intentional);
cleanClient!.close();
sockets[1]!.emitUnexpectedClose();
expect(intentional).not.toHaveBeenCalled();
it("reads numeric video capability descriptions and rejects malformed limits", () => {
const nativeMedia = { ...health.nativeMedia, maxVideoResolution: { width: 3840, height: 3840 },
maxVideoPixels: 3840 * 2160, maxVideoMacroblocksPerSecond: 983_040 };
expect(nativeHealthSchema.parse({ ...health, nativeMedia }).nativeMedia).toMatchObject(nativeMedia);
const stronger = { ...nativeMedia, maxVideoResolution: { width: 32768, height: 32768 },
maxVideoPixels: 32768 ** 2, maxVideoFramerate: 120, maxVideoBitrate: 100_000_000,
maxAudioBitrate: 960_000, maxRelayChildren: 32 };
const strongerHealth = nativeHealthSchema.parse({ ...health, nativeMedia: stronger });
expect(strongerHealth.nativeMedia).toMatchObject(stronger);
expect(nativeRelayCapacity(20, strongerHealth)).toBe(20);
expect(nativeHealthSchema.safeParse({ ...health, nativeMedia: { ...nativeMedia, maxVideoPixels: 0 } }).success).toBe(false);
expect(nativeHealthSchema.safeParse({ ...health, nativeMedia: { ...nativeMedia, maxVideoMacroblocksPerSecond: -1 } }).success).toBe(false);
expect(nativeHealthSchema.parse({ ...health, nativeMedia: { ...nativeMedia, maxRelayChildren: 20 } })
.nativeMedia.maxRelayChildren).toBe(20);
for (const maxRelayChildren of [0, 0x1_0000_0000, 1.5]) {
expect(nativeHealthSchema.safeParse({ ...health, nativeMedia: { ...nativeMedia, maxRelayChildren } }).success).toBe(false);
}
});
it("accepts descriptive health extensions and treats absent media features as unavailable", () => {
@@ -718,250 +451,6 @@ describe("native App private wire", () => {
]) expect(nativeHealthSchema.safeParse({ ...health, ...invalid }).success).toBe(false);
});
it.each([undefined, false, true])("gates optional capture commands on advertised support: %s", async (supported) => {
const requests: Record<string, unknown>[] = [];
class CaptureSocket extends EventTarget {
static readonly OPEN = 1;
static readonly CLOSING = 2;
readyState = CaptureSocket.OPEN;
protocol = `piik-client-v10.${health.instanceToken}`;
constructor() {
super();
queueMicrotask(() => this.dispatchEvent(new Event("open")));
}
close() { this.readyState = CaptureSocket.CLOSING; }
send(payload: string) {
const request = JSON.parse(payload) as Record<string, unknown>;
requests.push(request);
queueMicrotask(() => this.dispatchEvent(new MessageEvent("message", {
data: JSON.stringify({
version: NATIVE_CLIENT_PROTOCOL, id: request.id,
...(request.type === "hello" ? { type: "ready" } : {
type: request.type === "start-share" ? "share-started" : "share-source-replaced",
shareId: request.shareId,
...(request.type === "start-share" ? { audio: true, codec: "h264" } : {}),
}),
}),
})));
}
}
vi.stubGlobal("WebSocket", CaptureSocket);
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/") });
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({
...health, nativeMedia: { ...health.nativeMedia, captureBorderControl: supported, remoteInput: supported, sourceCancellation: supported },
}))));
const client = await NativeClient.connect();
expect(client).not.toBeNull();
expect(client!.health.nativeMedia.captureBorderControl).toBe(supported ?? false);
const input = {
shareId: "share_123456", source: { kind: "display" as const, sourceId: "2", title: "Display 1" },
audio: true, adapterIndex: 0, encoderIndex: 0, edgeCapacity: 2,
profile: DEFAULT_QUALITY_SETTINGS, codec: "auto" as const,
};
try {
for (const showCaptureBorder of [undefined, false, true]) {
const onRequested = vi.fn(() => expect(requests.at(-1)?.type).toBe("start-share"));
let acknowledged = false;
const starting = client!.startShare({ ...input, showCaptureBorder }, onRequested);
void starting.then(() => { acknowledged = true; });
expect(onRequested).toHaveBeenCalledOnce();
expect(acknowledged).toBe(false);
await starting;
await client!.replaceShareSource(input.shareId, input.source, input.audio, input, showCaptureBorder);
const extension = supported ? { showCaptureBorder: showCaptureBorder ?? false, reportSourceCancellation: true } : {};
expect(requests.at(-2)).toEqual({
version: NATIVE_CLIENT_PROTOCOL, id: expect.any(String), type: "start-share", ...input, ...extension,
...(supported ? { remoteInput: true } : {}),
});
expect(requests.at(-1)).toEqual({
version: NATIVE_CLIENT_PROTOCOL, id: expect.any(String), type: "replace-share-source",
shareId: input.shareId, source: input.source, audio: true, adapterIndex: 0, encoderIndex: 0, ...extension,
});
}
const unsent = vi.fn();
vi.spyOn(CaptureSocket.prototype, "send").mockImplementationOnce(() => { throw new Error("send failed"); });
await expect(client!.startShare(input, unsent)).rejects.toMatchObject({ reason: "send-failed" });
expect(unsent).not.toHaveBeenCalled();
client!.close();
await expect(client!.startShare(input, unsent)).rejects.toMatchObject({ reason: "unavailable" });
expect(unsent).not.toHaveBeenCalled();
} finally { client!.close(); }
});
it.each([false, true])("never silently drops requested audio exclusion (%s)", async (supported) => {
const requests: Record<string, unknown>[] = [];
class Socket extends EventTarget {
static readonly OPEN = 1;
static readonly CLOSING = 2;
readyState = Socket.OPEN;
protocol = `piik-client-v10.${health.instanceToken}`;
constructor() { super(); queueMicrotask(() => this.dispatchEvent(new Event("open"))); }
close() { this.readyState = Socket.CLOSING; }
send(payload: string) {
const request = JSON.parse(payload) as Record<string, unknown>;
requests.push(request);
queueMicrotask(() => this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify({
version: NATIVE_CLIENT_PROTOCOL, id: request.id,
...(request.type === "hello" ? { type: "ready" } : {
type: request.type === "start-share" ? "share-started" : "share-source-replaced", shareId: request.shareId,
...(request.type === "start-share" ? { audio: true, codec: "vp8", sourceAudio: true } : {}),
}),
}) })));
}
}
vi.stubGlobal("WebSocket", Socket);
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/") });
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ ...health,
nativeMedia: { ...health.nativeMedia, microphone: true, ...(supported ? { processAudioExclusion: true } : {}) },
}))));
const client = (await NativeClient.connect())!;
const input = { shareId: "share_123456", source: { kind: "display" as const, sourceId: "1", title: "Display" },
audio: true, adapterIndex: 0, encoderIndex: 0, edgeCapacity: 1, profile: DEFAULT_QUALITY_SETTINGS, codec: "vp8" as const };
const excludeAudio = { kind: "window" as const, sourceId: "2", pid: 123, creationTime: "456", title: "Voice fixture" };
try {
expect(client.health.nativeMedia.processAudioExclusion).toBe(supported);
await client.startShare(input);
expect(requests.at(-1)).not.toHaveProperty("excludeAudio");
if (supported) {
await client.startShare({ ...input, excludeAudio });
await client.replaceShareSource(input.shareId, input.source, true, input, false, excludeAudio);
expect(requests.at(-2)?.excludeAudio).toEqual(excludeAudio);
expect(requests.at(-1)?.excludeAudio).toEqual(excludeAudio);
} else {
const count = requests.length;
await expect(client.startShare({ ...input, excludeAudio })).rejects.toThrow("audio exclusion");
await expect(client.replaceShareSource(input.shareId, input.source, true, input, false, excludeAudio)).rejects.toThrow("audio exclusion");
expect(requests).toHaveLength(count);
}
} finally { client.close(); }
});
it.each([
{ microphone: false, shareVolume: false },
{ microphone: true, shareVolume: true },
{ microphone: false, shareVolume: true },
])("gates audio mixing and coalesces volume without delaying Stop (%j)", async ({ microphone, shareVolume }) => {
const supported = microphone || shareVolume;
const requests: Record<string, unknown>[] = [];
let socket!: Socket;
class Socket extends EventTarget {
static readonly OPEN = 1;
static readonly CLOSING = 2;
readyState = Socket.OPEN;
protocol = `piik-client-v10.${health.instanceToken}`;
constructor() { super(); socket = this; queueMicrotask(() => this.dispatchEvent(new Event("open"))); }
close() { this.readyState = Socket.CLOSING; }
ack(request: Record<string, unknown>, type: string, fields = {}) {
this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify({ version: 10, id: request.id, type, ...fields }) }));
}
send(payload: string) {
const request = JSON.parse(payload) as Record<string, unknown>;
requests.push(request);
if (request.type === "set-microphone" || request.type === "set-share-volume") return;
if (request.type === "list-microphones") {
queueMicrotask(() => this.ack(request, "microphone-list", { devices: [{ id: "headset", label: "USB Headset" }] }));
return;
}
queueMicrotask(() => this.ack(request,
request.type === "hello" ? "ready" : request.type === "start-share" ? "share-started" : "share-stopped",
request.type === "start-share" ? { shareId: request.shareId, audio: supported, codec: "vp8", ...(supported ? { sourceAudio: false } : {}) } : {}));
}
}
vi.stubGlobal("WebSocket", Socket);
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/") });
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({
...health, nativeMedia: { ...health.nativeMedia, microphone, shareVolume },
}))));
const client = (await NativeClient.connect())!;
try {
const started = await client.startShare({ shareId: "share_123456", audio: false,
source: { kind: "display", sourceId: "1", title: "Screen" }, adapterIndex: 0, encoderIndex: 0,
edgeCapacity: 1, profile: DEFAULT_QUALITY_SETTINGS, codec: "vp8" });
expect(requests.at(-1)?.microphoneMixing).toBe(supported ? true : undefined);
expect(started.audio).toBe(supported);
if (!supported) {
await expect(client.setMicrophone("share_123456", true, 1)).rejects.toThrow();
await expect(client.setShareVolume("share_123456", 2)).rejects.toThrow();
await expect(client.microphones()).rejects.toThrow();
expect(requests.some(request => request.type === "set-microphone")).toBe(false);
expect(requests.some(request => request.type === "set-share-volume")).toBe(false);
return;
}
if (microphone) expect(await client.microphones()).toEqual([{ id: "headset", label: "USB Headset" }]);
else await expect(client.microphones()).rejects.toThrow();
const volume = client.setShareVolume("share_123456", .5);
expect(client.setShareVolume("share_123456", 2)).toBe(volume);
const shareVolumeRequest = requests.at(-1)!;
const microphoneVolume = microphone ? client.setMicrophoneVolume("share_123456", .4) : null;
if (microphone) expect(client.setMicrophoneVolume("share_123456", .9)).toBe(microphoneVolume);
const microphoneVolumeRequest = requests.at(-1)!;
socket.ack(shareVolumeRequest, "share-volume-set");
await vi.waitFor(() => expect(requests.at(-1)).toMatchObject({ type: "set-share-volume", volume: 2 }));
socket.ack(requests.at(-1)!, "share-volume-set");
await volume;
if (!microphone) {
expect(requests.some(request => request.type === "set-microphone")).toBe(false);
return;
}
socket.ack(microphoneVolumeRequest, "microphone-set");
await vi.waitFor(() => expect(requests.at(-1)).toMatchObject({ type: "set-microphone", volume: .9 }));
socket.ack(requests.at(-1)!, "microphone-set");
await microphoneVolume;
const choosing = client.setMicrophone("share_123456", true, 1, "headset");
expect(requests.at(-1)).toMatchObject({ type: "set-microphone", deviceId: "headset", enabled: true });
socket.ack(requests.at(-1)!, "microphone-set");
await choosing;
requests.length = 0;
const pending = client.setMicrophoneVolume("share_123456", 0.1);
for (let value = 2; value <= 20; value++) expect(client.setMicrophoneVolume("share_123456", value / 10)).toBe(pending);
expect(requests.filter(request => request.type === "set-microphone")).toHaveLength(1);
socket.ack(requests.at(-1)!, "microphone-set");
await vi.waitFor(() => expect(requests.at(-1)?.volume).toBe(2));
const last = requests.at(-1)!;
expect(last).not.toHaveProperty("enabled");
await client.stopShare("share_123456");
socket.ack(last, "microphone-set");
await pending;
expect(requests.at(-1)?.type).toBe("stop-share");
} finally { client.close(); }
});
it.each([false, true])("requests receiver reuse only from a capable App (%s)", async (supported) => {
const requests: Record<string, unknown>[] = [];
class Socket extends EventTarget {
static readonly OPEN = 1;
static readonly CLOSING = 2;
readyState = Socket.OPEN;
protocol = `piik-client-v10.${health.instanceToken}`;
constructor() { super(); queueMicrotask(() => this.dispatchEvent(new Event("open"))); }
close() { this.readyState = Socket.CLOSING; }
send(payload: string) {
const request = JSON.parse(payload) as Record<string, unknown>;
requests.push(request);
queueMicrotask(() => this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify({
version: 10, id: request.id, ...(request.type === "hello" ? { type: "ready" } : {
type: "receive-answer", shareId: request.shareId, connectionId: request.connectionId,
sdp: "answer", audio: false, codec: "vp8", ...(supported ? { reused: true } : {}),
}),
}) })));
}
}
vi.stubGlobal("WebSocket", Socket);
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/") });
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({
...health, nativeMedia: { ...health.nativeMedia, ...(supported ? { receiverReuse: true } : {}) },
}))));
const client = (await NativeClient.connect())!;
try {
const result = await client.receiveOffer("share_123456", "connection_1234", { type: "offer", sdp: "offer" }, { iceServers: [] }, 2);
expect(requests.at(-1)).toEqual({ version: 10, id: expect.any(String), type: "receive-offer",
shareId: "share_123456", connectionId: "connection_1234", sdp: "offer", iceServers: [], edgeCapacity: 2,
...(supported ? { reuseReceiver: true } : {}),
});
expect(result.reused).toBe(supported);
} finally { client.close(); }
});
it("keeps exact positive physical identities and accepts system picker zero", () => {
expect(
nativeCaptureTargetSchema.safeParse({
@@ -1144,47 +633,4 @@ describe("native App private wire", () => {
}).success,
).toBe(true);
});
it.each(["edge-quality", "publication-quality"] as const)("isolates %s observations from control lifetime", async (type) => {
class Socket extends EventTarget {
static readonly OPEN = 1;
static readonly CLOSING = 2;
static latest: Socket;
readyState = Socket.OPEN;
protocol = `piik-client-v10.${health.instanceToken}`;
close = vi.fn(() => { this.readyState = Socket.CLOSING; this.dispatchEvent(new Event("close")); });
constructor() { super(); Socket.latest = this; queueMicrotask(() => this.dispatchEvent(new Event("open"))); }
emit(value: unknown) { this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(value) })); }
send(payload: string) {
const request = JSON.parse(payload);
this.emit({ version: 10, id: request.id, type: request.type === "hello" ? "ready" : "pong" });
}
}
vi.stubGlobal("WebSocket", Socket);
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/") });
vi.stubGlobal("fetch", vi.fn(async () => Response.json(health)));
const client = (await NativeClient.connect())!;
const received = vi.fn();
client.onEvent(received);
const event = { version: 10, type, shareId: "share_123456", connectionId: "connection_123456",
sampleTimestampMs: 10_000, sampleWindowMs: 2_000, rtpStatsId: "rtp-1", trackIdentifier: "screen",
state: "healthy", reason: "none", framesPerSecond: 480, bitrateKbps: 120_000,
availableOutgoingKbps: 1_000_000, width: 1920, height: 1080,
...(type === "edge-quality" ? { intervalFramesEncoded: 60 } : {
publicationGeneration: "publication_123456", codec: "vp8", videoEncodingCount: 2,
activeVideoEncodingCount: 2, rid: "h", intervalFramesSent: 60, audioBitrateKbps: 192,
}),
};
Socket.latest.emit(event);
expect(received).toHaveBeenLastCalledWith(event);
Socket.latest.emit({ ...event, framesPerSecond: -1, availableOutgoingKbps: "invalid" });
expect(received).toHaveBeenLastCalledWith({ ...event, framesPerSecond: null, availableOutgoingKbps: null });
// Invalid identity/state never becomes evidence, but cannot retire media.
Socket.latest.emit({ ...event, shareId: "bad", state: "degraded", reason: "none" });
expect(received).toHaveBeenCalledTimes(2);
await expect(client.ping()).resolves.toBeUndefined();
expect(Socket.latest.close).not.toHaveBeenCalled();
Socket.latest.emit({ version: 10, type: "edge-state", shareId: "bad" });
expect(Socket.latest.close).toHaveBeenCalledWith(1008, "invalid Client message");
});
});
-445
View File
@@ -1,445 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
NativeMediaBridge,
NativeMediaBridgeError,
NativeMediaBridgeInitializationError,
type NativeMediaBridgeControl,
} from "../src/client/native/media-bridge";
import type { NativeClientEvent } from "../src/client/native/wire";
import { debugError, debugEvent } from "../src/client/lib/debug";
vi.mock("../src/client/lib/debug", () => ({
registerDebugCollector: vi.fn(() => vi.fn()),
browserDebugEnabled: true,
debugEvent: vi.fn(),
debugError: vi.fn(),
}));
class FakeMediaStream {
private readonly tracks: MediaStreamTrack[] = [];
addTrack(track: MediaStreamTrack): void {
this.tracks.push(track);
}
getTracks(): MediaStreamTrack[] {
return [...this.tracks];
}
getVideoTracks(): MediaStreamTrack[] {
return this.tracks.filter((track) => track.kind === "video");
}
getAudioTracks(): MediaStreamTrack[] {
return this.tracks.filter((track) => track.kind === "audio");
}
}
class FakePeerConnection extends EventTarget {
connectionState: RTCPeerConnectionState = "new";
iceConnectionState: RTCIceConnectionState = "new";
iceGatheringState: RTCIceGatheringState = "complete";
localDescription: RTCSessionDescriptionInit | null = null;
readonly getReceivers = vi.fn<() => RTCRtpReceiver[]>(() => []);
readonly getSenders = vi.fn<() => RTCRtpSender[]>(() => []);
readonly getStats = vi.fn(async () => new Map());
readonly addIceCandidate = vi.fn(async () => undefined);
readonly setRemoteDescription = vi.fn(async () => undefined);
readonly createAnswer = vi.fn(async () => ({
type: "answer" as const,
sdp: "v=0\r\n",
}));
readonly setLocalDescription = vi.fn(async (description: RTCSessionDescriptionInit): Promise<void> => {
this.localDescription = description;
});
readonly close = vi.fn(() => {
this.connectionState = "closed";
});
emitTrack(track: MediaStreamTrack): void {
this.dispatchEvent(Object.assign(new Event("track"), { track }));
}
setState(state: RTCPeerConnectionState): void {
this.connectionState = state;
this.dispatchEvent(new Event("connectionstatechange"));
}
}
function fixture(options: {
hangPreparation?: boolean;
} = {}) {
let listener: ((event: NativeClientEvent) => void) | null = null;
let peer: FakePeerConnection | null = null;
vi.stubGlobal("window", globalThis);
vi.stubGlobal("MediaStream", FakeMediaStream);
vi.stubGlobal("RTCPeerConnection", class {
constructor() {
peer = new FakePeerConnection();
return peer;
}
});
const prepareLocalEdge = vi.fn<
NativeMediaBridgeControl["prepareLocalEdge"]
>(async () => {
if (options.hangPreparation) {
return await new Promise<RTCSessionDescriptionInit & { offerId: string }>(() => undefined);
}
return { type: "offer", sdp: "v=0\r\n", offerId: "local_offer_1" };
});
const control: NativeMediaBridgeControl = {
prepareLocalEdge,
acceptSignal: vi.fn(async () => undefined),
closeEdge: vi.fn(async () => undefined),
onEvent: vi.fn((next) => {
listener = next;
return () => {
listener = null;
};
}),
};
const onFailed = vi.fn();
const bridge = new NativeMediaBridge(
"share_123456",
control,
onFailed,
);
return {
bridge,
control,
onFailed,
peer: () => peer!,
emit: (event: NativeClientEvent) => listener?.(event),
};
}
beforeEach(() => {
vi.useRealTimers();
vi.clearAllMocks();
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
describe("native media bridge", () => {
it("retires rejected local video through the existing bridge failure path", async () => {
const current = fixture();
vi.mocked(current.control.prepareLocalEdge).mockResolvedValueOnce({ type: "offer", offerId: "local_offer_1",
sdp: "m=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\n" });
current.peer().createAnswer.mockResolvedValueOnce({ type: "answer", sdp: "m=video 0 UDP/TLS/RTP/SAVPF 120\r\n" });
await expect(current.bridge.start()).rejects.toBeInstanceOf(NativeMediaBridgeError);
expect(current.control.acceptSignal).not.toHaveBeenCalled();
expect(current.control.closeEdge).toHaveBeenCalledOnce();
expect(current.peer().close).toHaveBeenCalledOnce();
});
it("recovers one retained transport after a disconnect grace, including a quiet source", async () => {
vi.useFakeTimers();
const current = fixture();
const starting = current.bridge.start(true);
const video = { kind: "video", stop: vi.fn() } as unknown as MediaStreamTrack;
const audio = { kind: "audio", stop: vi.fn() } as unknown as MediaStreamTrack;
current.peer().emitTrack(video);
current.peer().emitTrack(audio);
current.peer().setState("connected");
await starting;
current.peer().setState("disconnected");
await vi.advanceTimersByTimeAsync(2_000);
current.peer().setState("connected");
await vi.advanceTimersByTimeAsync(3_000);
expect(current.control.prepareLocalEdge).toHaveBeenCalledTimes(1);
vi.mocked(current.control.prepareLocalEdge).mockResolvedValueOnce({
type: "offer", sdp: "v=0\r\n", offerId: "local_offer_2",
});
current.peer().setState("disconnected");
await vi.advanceTimersByTimeAsync(3_000);
current.emit({ version: 10, type: "edge-state", shareId: "share_123456",
connectionId: current.bridge.connectionId, state: "failed" });
expect(current.control.prepareLocalEdge).toHaveBeenLastCalledWith(
"share_123456", current.bridge.connectionId, undefined, true,
);
expect(current.control.prepareLocalEdge).toHaveBeenCalledTimes(2);
expect(current.control.acceptSignal).toHaveBeenLastCalledWith(
"share_123456", current.bridge.connectionId, expect.objectContaining({ kind: "description" }), "local_offer_2",
);
current.peer().setState("connected");
await vi.advanceTimersByTimeAsync(8_000);
expect(current.bridge.stream.getTracks()).toEqual([video, audio]);
expect(video.stop).not.toHaveBeenCalled();
expect(audio.stop).not.toHaveBeenCalled();
expect(current.peer().close).not.toHaveBeenCalled();
expect(current.onFailed).not.toHaveBeenCalled();
current.bridge.dispose();
});
it("bounds a failed restart and ignores its late offer after disposal", async () => {
vi.useFakeTimers();
const current = fixture();
const starting = current.bridge.start();
current.peer().emitTrack({ kind: "video", stop: vi.fn() } as unknown as MediaStreamTrack);
current.peer().setState("connected");
await starting;
let finish!: (offer: RTCSessionDescriptionInit & { offerId: string }) => void;
vi.mocked(current.control.prepareLocalEdge).mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
current.peer().setState("failed");
current.peer().setState("failed");
expect(current.control.prepareLocalEdge).toHaveBeenCalledTimes(2);
await vi.advanceTimersByTimeAsync(8_000);
finish({ type: "offer", sdp: "v=0\r\n", offerId: "late_offer" });
await vi.advanceTimersByTimeAsync(1);
expect(current.onFailed).toHaveBeenCalledOnce();
expect(current.peer().setRemoteDescription).toHaveBeenCalledOnce();
expect(current.control.acceptSignal).toHaveBeenCalledOnce();
expect(current.control.closeEdge).toHaveBeenCalledOnce();
});
it("gathers the answer before signaling and cancels gathering on disposal", async () => {
const current = fixture();
current.peer().iceGatheringState = "gathering";
const starting = current.bridge.start();
const rejected = expect(starting).rejects.toBeInstanceOf(NativeMediaBridgeError);
await vi.waitFor(() => expect(current.peer().setLocalDescription).toHaveBeenCalledOnce());
expect(current.control.acceptSignal).not.toHaveBeenCalled();
current.bridge.dispose();
current.peer().iceGatheringState = "complete";
current.peer().dispatchEvent(new Event("icegatheringstatechange"));
await rejected;
expect(current.control.acceptSignal).not.toHaveBeenCalled();
});
it("advertises the same Opus receive range on local preview as remote viewers", async () => {
const current = fixture();
current.peer().createAnswer.mockResolvedValueOnce({ type: "answer", sdp:
"v=0\r\no=- 1 1 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n" +
"m=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=rtpmap:111 opus/48000/2\r\n" +
"a=fmtp:111 minptime=10;useinbandfec=1\r\n",
});
const starting = current.bridge.start(true);
await vi.waitFor(() => expect(current.control.acceptSignal).toHaveBeenCalledWith(
"share_123456", current.bridge.connectionId, expect.objectContaining({
kind: "description", description: expect.objectContaining({
sdp: expect.stringContaining("stereo=1;maxaveragebitrate=510000"),
}),
}), "local_offer_1",
));
expect(current.peer().setLocalDescription).toHaveBeenCalledWith(expect.objectContaining({
sdp: expect.stringContaining("stereo=1;maxaveragebitrate=510000"),
}));
current.peer().emitTrack({ kind: "video", stop: vi.fn() } as unknown as MediaStreamTrack);
current.peer().emitTrack({ kind: "audio", stop: vi.fn() } as unknown as MediaStreamTrack);
current.peer().setState("connected");
await expect(starting).resolves.toBe(current.bridge.stream);
current.bridge.dispose();
});
it("releases an unstarted Browser reservation without sending an edge command", async () => {
const current = fixture();
current.bridge.dispose();
current.bridge.dispose();
await expect(current.bridge.start()).rejects.toBeInstanceOf(NativeMediaBridgeError);
expect(current.peer().close).toHaveBeenCalledOnce();
expect(current.control.prepareLocalEdge).not.toHaveBeenCalled();
expect(current.control.closeEdge).not.toHaveBeenCalled();
expect(current.onFailed).not.toHaveBeenCalled();
});
it.each(["MediaStream", "RTCPeerConnection"])("preserves %s initialization failure without preparing an edge", (api) => {
const current = fixture();
current.bridge.dispose();
vi.clearAllMocks();
const cause = new DOMException("Browser media initialization rejected", "NotAllowedError");
vi.stubGlobal(api, class { constructor() { throw cause; } });
let failure: unknown;
try { new NativeMediaBridge("share_123456", current.control, current.onFailed); }
catch (error) { failure = error; }
expect(failure).toBeInstanceOf(NativeMediaBridgeError);
expect(failure).toBeInstanceOf(NativeMediaBridgeInitializationError);
expect((failure as Error).cause).toBe(cause);
expect(debugError).toHaveBeenCalledWith("native-bridge", "initialization-failed", cause);
expect(current.control.prepareLocalEdge).not.toHaveBeenCalled();
expect(current.control.closeEdge).not.toHaveBeenCalled();
expect(current.onFailed).not.toHaveBeenCalled();
});
it("records the negotiation cause before retiring a failed bridge", async () => {
const current = fixture();
const cause = new DOMException("Remote offer rejected", "OperationError");
current.peer().setRemoteDescription.mockRejectedValueOnce(cause);
await expect(current.bridge.start()).rejects.toMatchObject({ cause });
expect(debugError).toHaveBeenCalledWith("native-bridge", "failed", cause,
{ type: "negotiation", state: "starting" });
expect(current.peer().close).toHaveBeenCalledOnce();
expect(current.control.closeEdge).toHaveBeenCalledOnce();
expect(current.onFailed).not.toHaveBeenCalled();
});
it("releases a local edge when preparation exceeds the total deadline", async () => {
vi.useFakeTimers();
const current = fixture({ hangPreparation: true });
const starting = current.bridge.start();
const rejected = expect(starting).rejects.toThrow("Native media bridge failed");
await vi.advanceTimersByTimeAsync(8_000);
await rejected;
expect(current.peer().close).toHaveBeenCalledOnce();
expect(current.control.closeEdge).toHaveBeenCalledOnce();
});
it("does not publish a declared audio share before its audio track arrives", async () => {
const current = fixture();
const starting = current.bridge.start(true);
let resolved = false;
void starting.then(() => {
resolved = true;
});
await vi.waitFor(() => {
expect(current.peer().setLocalDescription).toHaveBeenCalledOnce();
});
current.peer().emitTrack({
kind: "video",
stop: vi.fn(),
} as unknown as MediaStreamTrack);
current.peer().setState("connected");
await Promise.resolve();
expect(resolved).toBe(false);
current.peer().emitTrack({
kind: "audio",
stop: vi.fn(),
} as unknown as MediaStreamTrack);
await expect(starting).resolves.toBe(current.bridge.stream);
expect(current.bridge.stream.getAudioTracks()).toHaveLength(1);
});
it("reports only categorical transport and candidate counts on timeout", async () => {
vi.useFakeTimers();
const current = fixture();
const peer = current.peer();
peer.connectionState = "connecting";
peer.iceConnectionState = "checking";
peer.iceGatheringState = "complete";
peer.getReceivers.mockReturnValue([{
track: { kind: "video", readyState: "live", id: "private-track" },
transport: { state: "new" },
} as unknown as RTCRtpReceiver]);
peer.getStats.mockResolvedValue(new Map([
["private-local", { type: "local-candidate", candidateType: "host", protocol: "tcp", address: "192.0.2.1", port: 54321 }],
["private-remote", { type: "remote-candidate", candidateType: "host", protocol: "udp", address: "192.0.2.2", port: 54322 }],
]));
const starting = current.bridge.start();
const rejected = expect(starting).rejects.toBeInstanceOf(NativeMediaBridgeError);
await vi.advanceTimersByTimeAsync(8_000);
await rejected;
expect(debugEvent).toHaveBeenCalledWith("native-bridge", "failed", { type: "timeout", state: "starting" });
expect(debugEvent).toHaveBeenCalledWith("native-bridge", "ice-state", { state: "checking" });
expect(debugEvent).toHaveBeenCalledWith("native-bridge", "ice-gathering-state", { state: "complete" });
expect(debugEvent).toHaveBeenCalledWith("native-bridge", "dtls-state", { state: "new" });
expect(debugEvent).toHaveBeenCalledWith("native-bridge", "receiver-count", { type: "video", state: "live", count: 1 });
expect(debugEvent).toHaveBeenCalledWith("native-bridge", "candidate-count", { type: "local-host", state: "udp", count: 0 });
expect(debugEvent).toHaveBeenCalledWith("native-bridge", "candidate-count", { type: "remote-host", state: "udp", count: 1 });
const report = JSON.stringify(vi.mocked(debugEvent).mock.calls);
for (const privateValue of ["private-track", "private-local", "private-remote", "192.0.2.", "54321", "54322"]) {
expect(report).not.toContain(privateValue);
}
expect(peer.getStats).toHaveBeenCalledOnce();
expect(peer.close).toHaveBeenCalledOnce();
});
it.each(["failed", "pending"])("does not delay timeout cleanup for %s diagnostics", async (state) => {
vi.useFakeTimers();
const current = fixture();
current.peer().getStats.mockImplementation(() => state === "failed"
? Promise.reject(new Error("private stats failure"))
: new Promise(() => undefined));
const rejected = expect(current.bridge.start()).rejects.toBeInstanceOf(NativeMediaBridgeError);
await vi.advanceTimersByTimeAsync(8_000);
await rejected;
expect(current.peer().close).toHaveBeenCalledOnce();
expect(current.control.closeEdge).toHaveBeenCalledOnce();
if (state === "failed") expect(debugError).toHaveBeenCalledWith(
"native-bridge", "diagnostics-failed", expect.any(Error),
);
});
it("retires an actively closed native edge once", async () => {
const current = fixture();
const starting = current.bridge.start();
await vi.waitFor(() => {
expect(current.peer().setLocalDescription).toHaveBeenCalledOnce();
});
current.peer().emitTrack({
kind: "video",
stop: vi.fn(),
} as unknown as MediaStreamTrack);
current.peer().setState("connected");
await starting;
current.emit({
version: 10,
type: "edge-state",
shareId: "share_123456",
connectionId: current.bridge.connectionId,
state: "closed",
});
current.emit({
version: 10,
type: "edge-state",
shareId: "share_123456",
connectionId: current.bridge.connectionId,
state: "closed",
});
expect(current.onFailed).toHaveBeenCalledOnce();
expect(current.peer().close).toHaveBeenCalledOnce();
expect(current.control.closeEdge).toHaveBeenCalledOnce();
});
it("rejects a pending start when the bridge is disposed", async () => {
const current = fixture();
const starting = current.bridge.start();
await vi.waitFor(() => {
expect(current.peer().setLocalDescription).toHaveBeenCalledOnce();
});
current.bridge.dispose();
await expect(starting).rejects.toThrow("Native media bridge failed");
expect(current.onFailed).not.toHaveBeenCalled();
expect(current.peer().close).toHaveBeenCalledOnce();
expect(current.control.closeEdge).toHaveBeenCalledOnce();
expect(debugError).not.toHaveBeenCalled();
});
it.each(["prepare", "answer"])("does not signal after disposal during %s", async (stage) => {
const current = fixture();
let complete!: () => void;
const pending = new Promise<void>(resolve => { complete = resolve; });
if (stage === "prepare") {
vi.mocked(current.control.prepareLocalEdge).mockImplementationOnce(async () => {
await pending;
return { type: "offer", sdp: "v=0\r\n", offerId: "local_offer_1" };
});
} else {
current.peer().setLocalDescription.mockImplementationOnce(() => pending);
}
const rejected = expect(current.bridge.start()).rejects.toBeInstanceOf(NativeMediaBridgeError);
if (stage === "answer") await vi.waitFor(() => expect(current.peer().setLocalDescription).toHaveBeenCalledOnce());
current.bridge.dispose();
complete();
current.peer().dispatchEvent(Object.assign(new Event("icecandidate"), { candidate: null }));
await rejected;
await new Promise(resolve => setTimeout(resolve, 0));
expect(current.control.acceptSignal).not.toHaveBeenCalled();
expect(current.control.closeEdge).toHaveBeenCalledOnce();
expect(current.onFailed).not.toHaveBeenCalled();
});
});
+12 -13
View File
@@ -1,6 +1,5 @@
import { createServer, type Server } from "node:http";
import { afterEach, expect, it, vi } from "vitest";
import { NATIVE_CLIENT_PROTOCOL } from "../src/client/native/wire";
import { NATIVE_CLIENT_PORT_START, NATIVE_CLIENT_PORT_END } from "../src/client/native/discovery-ports";
const servers: Server[] = [];
@@ -20,8 +19,8 @@ async function runtime(delay: number) {
requests.push(request.url!);
setTimeout(() => {
response.setHeader("Content-Type", "application/json");
response.end(JSON.stringify({ protocol: NATIVE_CLIENT_PROTOCOL, service: "piik-client",
port, instanceToken: "a".repeat(43), nativeMedia: { video: true },
response.end(JSON.stringify({ protocol: 1, service: "piik-channel-app",
port, token: "fixture-token",
...(request.url === "/connect-discovery" ? { connectURL: `http://127.0.0.1:${port}/client` } : {}),
}));
}, delay);
@@ -65,16 +64,16 @@ it("selects the launched runtime over a faster resident App and never substitute
} },
};
vi.stubGlobal("window", page);
const { discoverNativeHealth, discoverNativeConnect } = await import("../src/client/native/client");
const { discoverChannelAppHealth, channelAppDiscovery } = await import("../src/client/channel/app-link");
const { takeClientLaunchBootstrap, clientRuntimePort } = await import("../src/client/lib/session");
// Both actual HTTP stubs are discoverable; the older one responds first.
await expect(discoverNativeHealth()).resolves.toMatchObject({ port: old.port });
await expect(discoverChannelAppHealth()).resolves.toMatchObject({ port: old.port });
page.location.search = `?piik-client-port=${selected.port}`;
page.location.hash = "piik-client=1";
takeClientLaunchBootstrap();
old.requests.length = 0;
await expect(discoverNativeHealth()).resolves.toMatchObject({ port: selected.port });
await expect(discoverNativeConnect()).resolves.toContain(`127.0.0.1:${selected.port}/client?`);
await expect(discoverChannelAppHealth()).resolves.toMatchObject({ port: selected.port });
await expect(channelAppDiscovery.connect()).resolves.toContain(`127.0.0.1:${selected.port}/client?`);
expect(old.requests).toEqual([]);
expect(page.location.href).toBe("http://127.0.0.1:8787/");
expect([...saved.keys()]).toEqual(["piik:client-launch:v1"]);
@@ -82,16 +81,16 @@ it("selects the launched runtime over a faster resident App and never substitute
takeClientLaunchBootstrap(); // Consuming an already-clean URL keeps this page's affinity.
expect(clientRuntimePort()).toBe(selected.port);
await new Promise<void>(resolve => { selected.server.close(() => resolve()); selected.server.closeAllConnections(); });
await expect(discoverNativeHealth()).resolves.toBeNull();
await expect(discoverNativeConnect()).resolves.toBeNull();
await expect(discoverChannelAppHealth()).resolves.toBeNull();
await expect(channelAppDiscovery.connect()).resolves.toBeNull();
expect(old.requests).toEqual([]);
vi.resetModules();
const reloaded = await import("../src/client/lib/session");
reloaded.takeClientLaunchBootstrap();
expect(reloaded.clientRuntimePort()).toBe(selected.port);
expect(reloaded.isClientActivated()).toBe(true);
const reloadedDiscovery = await import("../src/client/native/client");
await expect(reloadedDiscovery.discoverNativeHealth()).resolves.toBeNull();
const reloadedDiscovery = await import("../src/client/channel/app-link");
await expect(reloadedDiscovery.discoverChannelAppHealth()).resolves.toBeNull();
expect(old.requests).toEqual([]);
// A new explicit launch replaces this tab's previous selection.
page.location.search = `?piik-client-port=${old.port}`;
@@ -104,6 +103,6 @@ it("selects the launched runtime over a faster resident App and never substitute
vi.resetModules();
const freshTab = await import("../src/client/lib/session");
expect(freshTab.clientRuntimePort()).toBeNull();
const freshDiscovery = await import("../src/client/native/client");
await expect(freshDiscovery.discoverNativeHealth()).resolves.toMatchObject({ port: old.port });
const freshDiscovery = await import("../src/client/channel/app-link");
await expect(freshDiscovery.discoverChannelAppHealth()).resolves.toMatchObject({ port: old.port });
});
+9 -10
View File
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { parse } from "sdp-transform";
import { preferOpusStereoReceive, preferScreenAudioStereo } from "../src/client/webrtc/opus-receive-sdp.ts";
import { preferOpusStereoReceive } from "../src/client/webrtc/opus-receive-sdp.ts";
function answerSdp(opusFmtp: string | null = "minptime=10;useinbandfec=1"): string {
return [
@@ -24,7 +24,7 @@ function answerSdp(opusFmtp: string | null = "minptime=10;useinbandfec=1"): stri
].join("\r\n");
}
describe("preferScreenAudioStereo", () => {
describe("preferOpusStereoReceive", () => {
it.each(["offer", "answer"] as const)("configures every receiving Opus section in a shared %s while preserving other directions", type => {
const audio = (mid: number, direction?: string, port = 9) => [
`m=audio ${port} UDP/TLS/RTP/SAVPF 111`, `a=mid:${mid}`, ...(direction ? [`a=${direction}`] : []),
@@ -44,7 +44,7 @@ describe("preferScreenAudioStereo", () => {
});
it("adds exact stereo and bitrate tokens without changing FEC or video fmtp", () => {
const result = preferScreenAudioStereo({
const result = preferOpusStereoReceive({
type: "answer",
sdp: answerSdp("minptime=10;useinbandfec=1;x-stereo=keep"),
});
@@ -58,11 +58,11 @@ describe("preferScreenAudioStereo", () => {
expect(session.media[1]?.fmtp).toEqual([
{ payload: 96, config: "packetization-mode=1;profile-level-id=42e01f" },
]);
expect(preferScreenAudioStereo(result)).toEqual(result);
expect(preferOpusStereoReceive(result)).toEqual(result);
});
it("replaces only exact stereo and bitrate tokens", () => {
const result = preferScreenAudioStereo({
const result = preferOpusStereoReceive({
type: "answer",
sdp: answerSdp(
"stereo=0;x-stereo=0;maxaveragebitrate=64000;x-maxaveragebitrate=keep",
@@ -75,7 +75,7 @@ describe("preferScreenAudioStereo", () => {
});
it("creates the Opus fmtp row when it is absent", () => {
const result = preferScreenAudioStereo({
const result = preferOpusStereoReceive({
type: "answer",
sdp: answerSdp(null),
});
@@ -92,7 +92,7 @@ describe("preferScreenAudioStereo", () => {
"a=rtpmap:112 opus/48000/2",
"a=fmtp:112 stereo=0",
].join("\r\n");
const result = preferScreenAudioStereo({
const result = preferOpusStereoReceive({
type: "answer",
sdp: answerSdp().replace("m=audio 9", `${rejected}\r\nm=audio 9`),
});
@@ -107,13 +107,12 @@ describe("preferScreenAudioStereo", () => {
["empty", { type: "answer", sdp: "" }],
["malformed", { type: "answer", sdp: "not SDP" }],
["parser exception", { type: "answer", sdp: { trim: () => "x" } as unknown as string }],
["not an answer", { type: "offer", sdp: answerSdp() }],
[
"missing Opus",
{ type: "answer", sdp: answerSdp().replace("opus/48000/2", "ISAC/16000") },
],
[
"multiple active audio sections",
"missing Opus in another active audio section",
{ type: "answer", sdp: `${answerSdp()}m=audio 9 RTP/AVP 0\r\n` },
],
[
@@ -136,7 +135,7 @@ describe("preferScreenAudioStereo", () => {
},
],
] as const)("returns the original answer for %s", (_case, answer) => {
const result = preferScreenAudioStereo(answer);
const result = preferOpusStereoReceive(answer);
expect(result).toBe(answer);
expect(result.sdp).toBe(answer.sdp);
});