Files
piik/scripts/app-native-host-gate.ts
T
AAAandAkazaAkalin 3707e48225 feat!: expand media controls and simplify App connections
## Problem and outcome / 问题与结果

Piik's media settings were coupled to a small preset list, and using native App capture on a Site required a separate launcher mode. This release separates numeric media requests from presets and bounded runtime admission, remembers successfully applied settings, and lets a running App serve an explicitly approved Site independently of Local/public room startup.

The same phase repairs confirmed capture-retirement, ICE discovery, media-recovery and storage failures. P2P-first routing, one room authority and the existing Browser/Native media owners remain. This phase targets **v2.0.0** with incompatible Web/App contracts. The owner authorized publication after final acceptance; the verified package and deployment records own delivery completion.

## Release notes

### 中文

Piik 2.0 扩展了画质设置,简化了 App 与站点的连接,并集中修复采集和断线恢复问题。**本次升级调整了通信协议,App 与所用站点需要一起升级。**

#### 新功能与改进

- **自定义画面设置:** 保留三档推荐预设,支持填写分辨率上限、1–240 帧的帧率上限和 0.1–240 Mbps 的视频码率上限。滑动条沿用常用范围,更高数值可直接填写并显示为“自定义”。帧率范围随画幅变化,可请求 1080p240、1440p144、4K60 和超宽画面;输出保留来源比例。
- **自定义音频质量:** 在原有三档音频预设之外,可填写 6–320 kbps 的来源音频码率上限。
- **双端 App 协同连接:** 启用增强 NAT 穿透后,适用的重试可协调双方 App 准备 UDP 连接;首次连接仍走普通 ICE,不适用时继续现有流程。已通过受控网络验证,实际连通性仍取决于双方网络。
- **记住分享设置:** 下次打开时恢复已应用的画面与音频质量。仅用浏览器时按站点保存;通过新版 App 使用时,更换临时公网邀请网址也能保留设置。
- **更直接地连接 App:** 启动页提供本地房间和公网邀请,首次默认选择公网邀请。使用已有站点时,保持 App 运行,在站点点击 **App** 并确认授权即可。App 打开的本地房主页自动获得授权,站点按钮会显示 App 就绪状态。启动页可查看或取消授权;从另一个站点连接并批准,会替换原授权。
- **置顶聊天窗口:** 支持的桌面浏览器可将聊天移入独立置顶窗口,保留当前消息、草稿和阅读位置;关闭窗口后回到原页面。

#### 修复

- **连接与恢复:** 完善备用 STUN 与 NAT 采样信息的处理;重新收集 ICE 候选时刷新网卡地址。修正观众重连的机会计数、本机媒体连接恢复,以及恢复后遗留的发送队列和带宽统计问题。保留视频编码对应的标准重传能力,改善网络地址变化后的画面恢复。
- **采集稳定性:** 修正 Windows 停止采集或预览时的异步资源释放问题,保留采集边框偏好,更快跳过无法正常输出的编码器。采集与应用音频能力按实际接口探测,不再按 Windows 版本号排除;修正 Linux Portal 来源识别和早期采集失败通知,改善摄像头与原生采集的画面比例处理。
- **状态与清理:** 房间失效时及时释放 App 连接和待完成的选源请求;本地或公网房间启动失败时,App 保持待机并保留其他已授权站点的连接;公网邀请启动失败保留底层错误。修正启动页旧查询覆盖新设置的问题,并限制原生连接准备的待完成任务。SFU 诊断区分房主发布和观众接收状态。
- **其他维护:** 收到尚不支持的表情时跳过该效果;修正 SQLite 写入失败后的事务恢复。Gitee 镜像可独立重试,官网交互、指南和依赖同步更新。App 连接失败时提供重试与下载入口;统一选源设置与自定义数值的反馈。减少重复的随机短语,仅在持续等待时定时轮换。

#### 升级须知

**2.0 与 1.x 不能混用。** 自建站点请更新 Server 和连接该站点的 App,并刷新所有分享与观看页面。本地房间或公网邀请用户请停止分享、关闭旧 App,完整解压新版程序包后重新发送邀请链接。

本次不变更房间数据库结构。重启会中断正在进行的分享;麦克风、采集权限和设备选择不会自动恢复。4K60 等设置是输出上限,实际清晰度与帧率取决于来源、设备和网络。macOS/Linux 采集及部分移动设备仍需更多实机反馈。

### English

Piik 2.0 adds more control over sharing quality, simplifies connecting the App to a Site, and fixes capture and connection-recovery failures. **The communication contracts change in this release: update the App and its Site together.**

#### Highlights

- **Custom picture settings:** Keep the three recommended presets or enter a resolution ceiling, a 1–240 fps limit and a 0.1–240 Mbps video bitrate limit. Sliders retain their familiar ranges; higher entered values are clearly marked as custom. Frame-rate limits depend on picture size, admitting requests such as 1080p240, 1440p144, 4K60 and ultrawide pictures while preserving source proportions.
- **Custom audio quality:** Enter a 6–320 kbps source-audio bitrate limit alongside the three existing audio presets.
- **Coordinated App connections:** With enhanced NAT traversal enabled, eligible retries can coordinate UDP preparation between two Apps. The first attempt remains ordinary ICE, and ineligible preparation continues through the existing path. Controlled network checks pass; real-world connectivity still depends on both networks.
- **Remember sharing settings:** Restore successfully applied picture and audio quality next time. Browser-only use saves settings per site; an updated App can retain them across changing temporary public-invitation addresses.
- **Connect the App from a Site:** The launcher offers Local room and Public invite, with Public invite selected on first use. For an existing Site, keep the App running, click **App** on the Site and confirm its authorization. Host pages opened locally by App are authorized automatically, and the Site button reflects verified App readiness. View or revoke approval in the launcher. Connecting and approving another Site replaces the previous approval.
- **Always-on-top chat:** Supported desktop browsers can move chat into a separate always-on-top window while retaining messages, drafts and reading position. Closing the window returns chat to the page.

#### Fixes

- **Connections and recovery:** Improve fallback STUN discovery and NAT survey handling, and refresh interface addresses during ICE gathering. Fix Viewer recovery-opportunity accounting, local media-connection recovery, stale send queues and bandwidth accounting after recovery. Preserve standard video retransmission when selecting a codec to improve picture recovery after network-address changes.
- **Capture stability:** Fix asynchronous Windows resource retirement after capture or preview ends, retain the capture-border preference, and reject non-performing encoder candidates earlier. Detect capture and process-audio support through actual APIs rather than Windows-version gates. Correct Linux Portal target identification and early capture-failure delivery; improve source-aspect handling for camera and native capture.
- **State and cleanup:** Release App connections and pending source selection when room authority ends. Keep the App on standby and preserve other authorized Site connections when interactive Local/public room startup fails. Retain underlying public-invitation startup errors. Prevent stale launcher reads from replacing newer settings, bound pending native connection-preparation work, and distinguish Host publication from Viewer reception in SFU diagnostics.
- **Maintenance:** Skip unsupported incoming reaction effects, recover SQLite transactions after write failures, and retry Gitee mirroring independently. Update website interactions, guides and dependencies; clarify App connection recovery, source-selection settings and custom-value feedback. Reduce repeated playful captions, with timed rotation reserved for ongoing waits.

#### Upgrading

**2.0 and 1.x cannot be mixed.** For a hosted Site, update its Server and connected Apps, then refresh every Host and Viewer page. For Local rooms or Public invites, stop sharing, close the old App, extract the complete new package and send a fresh invitation.

The room database schema is unchanged. Restarting interrupts active shares; microphone activation, capture permission and device selection are not restored automatically. Settings such as 4K60 are output ceilings: actual resolution and frame rate depend on the source, device and network. macOS/Linux capture and some mobile devices still need more physical-device feedback.

## Verification / 验证

- Product candidate: `24a28738241b9012c0476386356a515aab21f1a5`, built as `v2.0.0`. [Final full candidate CI](https://github.com/TNTcraftHIM/Piik/actions/runs/38555494851) covers core validation, vulnerabilities, races, five App packages and both Server/container targets without publishing. Later commits extend race coverage, correct the capture test fixture's inherited Go race-exit delay, and update documentation/staged website screenshots; shipped product code is unchanged. [Additional control/loopback race checks](https://github.com/TNTcraftHIM/Piik/actions/runs/38561191343) use that updated collector. Product shutdown deadlines and test assertions are unchanged.
- Local Web acceptance passes **91 files / 1,612 tests**, type checking and production build. Full Go/native checks, Windows capture compilation, five-repeat control regressions, website/documentation build and repository checks pass. Existing documentation-size and bundle-size warnings remain visible.
- The Windows candidate's original descriptor, revision and SHA-256 are checked before extraction and packaged Local/control acceptance. All candidate packages pass the release publisher's read-only identity/checksum verification.
- Serial Windows native H.264 Host acceptance passes live/paused/custom/4K settings, background/source recovery and stop/re-share. VP8 two-room SFU and H.264 SFU-only checks pass live quality/audio changes, subscription/page-reload recovery and retirement; stopping one room preserves the other room's media. Browser-to-App fanout and App-exit fallback also pass. Gates clean their processes, profiles and listeners. These checks do not establish sustained game/4K performance.
- The final network run passes **37 cases and six negative controls**, with **32 actual media outcomes and five unavailable observations**. It covers all Browser/App pairings, IPv6, remapping, STUN backup, outages, quality recovery, healthy siblings and SFU policies. Sequential-NAT App/App preparation delivers media; a mixed sequential case also connects in this run, without a claim of deterministic benefit. Fault controls reject absent faults/frozen video and verify cancellation/cleanup. No public success percentage is inferred.
- Twenty Viewer topology acceptance delivers increasing decoded frames to all Viewers, preserves the two-copy bound and recovers from relay loss. Invitation privacy checks find no grant leakage in requests, cookies, persistent storage or logs. Both are bounded synthetic-source checks, not public-network endurance.
- Current UI checks cover Chinese/English/visual, both themes and 320/360/768/1366-pixel layouts, numeric limits, source selection, App approval/revocation, architecture downloads and reader navigation. Chat/PiP retains draft/history/scroll and returns to the page on close; retirement and refused opening clean up. Real Host/Viewer UI chat continues after capture stops and while the Host is absent. Film controls, mute/seek/end/replay, mobile containment and pointer-close unloading pass. README stills and the staged launcher now use current navigation. Scoped axe checks report no violations; contrast and physical assistive-technology coverage are not certified.
- Physical macOS/Linux capture, limited decoders, mixed HDR displays, mobile permissions and sustained game/4K use retain their [evidence limits](https://github.com/TNTcraftHIM/Piik/blob/ci/gitee-mirror/docs/verification-status.md). Unmatched field reports remain open. Gitee activation and public-domain checks are publication postflight; original v1.9.2 artifact/mirror recovery already passed without remote writes.

## Boundaries and contributor credit / 边界与贡献

The candidate uses Browser/server v24 and Native control v10; capture v7 and SQLite schema 2 are unchanged. Numeric wire values remain separate from codec/allocation admission. H.264/VP8, framework-owned adaptation and automatic P2P-first routing remain; this candidate adds neither codecs, room voice, end-to-end HDR, surround audio nor Magicsock.

Local controls confirm specific repairs, not the causes of unmatched user reports or a measured increase in NAT success rate. The STUN report in #471 remains subject to paired endpoint/network evidence. Gitee's separate workflow activation still needs post-merge verification; its original-artifact and anonymous-download path has passed against v1.9.2.

The Linux Portal fix from @AkazaAkali in #470 is incorporated with original commit authorship and the co-author trailer below. #462 and #469 propose higher audio rates and 4K; neither patch is merged. Their preset-expansion implementation is superseded by the independently established numeric-media contract, so overlapping functionality alone does not warrant merging or co-authorship. #475 identifies the Linux desktop entry’s missing terminal controls; that defect is independently corrected without accepting tray or Browser-owned process-exit additions. The settings request in #460 is implemented; issue/PR closure remains part of release follow-up.

Co-authored-by: AkazaAkalin <478080766@qq.com>
2026-10-14 08:09:45 -04:00

1580 lines
57 KiB
TypeScript

import {
spawn,
spawnSync,
type ChildProcess,
type ChildProcessWithoutNullStreams,
} from "node:child_process";
import { randomBytes } from "node:crypto";
import { createServer } from "node:http";
import { mkdir, mkdtemp, readFile, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { fittedCaptureSize, matchesCaptureSize } from "./media-gate-geometry";
import {
CdpConnection,
cleanupRun,
createPage,
evaluate,
launchChrome,
reservePort,
type PageHandle,
waitForVersion,
withDeadline,
} from "./browser-gate-harness";
import {
decodeAppEndpoint,
type AppEndpoint as Endpoint,
} from "./app-gate-endpoint";
const ROOT = resolve(import.meta.dirname, "..");
const BUILD_ROOT = join(ROOT, "build", "go-check");
export const SOURCE_TITLE = "Piik Native Gate Source";
type GateMode = "local" | "one-link";
type VideoCodec = "h264" | "vp8";
const CODEC_PROBE = `(() => {
const fitSize = ${fittedCaptureSize.toString()}, matchesSize = ${matchesCaptureSize.toString()};
window.__piikGateFitsProfile = (width, height) => {
const video = document.querySelector('video'), source = window.__piikGateSourceSize;
return Boolean(video && source && matchesSize(video.videoWidth, video.videoHeight, fitSize(source, width, height)));
};
const peers = [], BrowserPeer = RTCPeerConnection;
const sockets = [], BrowserSocket = WebSocket;
window.WebSocket = class extends BrowserSocket {
constructor(...args) { super(...args); sockets.push(this); }
};
window.__piikGatePublicSignal = () => sockets.some((socket) => {
const url = new URL(socket.url);
return socket.readyState === WebSocket.OPEN && url.protocol === 'wss:' &&
url.host === location.host && url.pathname === '/signal';
});
window.RTCPeerConnection = class extends BrowserPeer {
constructor(...args) { super(...args); peers.push(this); }
};
window.__piikGateVideoCodec = async () => {
const trackId = document.querySelector('video')?.srcObject?.getVideoTracks()[0]?.id;
if (!trackId) return null;
for (const peer of peers) {
if (peer.connectionState !== 'connected') continue;
const report = await peer.getStats();
for (const row of report.values()) {
if (row.type !== 'inbound-rtp' || row.kind !== 'video' ||
row.trackIdentifier !== trackId || !(row.framesDecoded > 0)) continue;
const mime = report.get(row.codecId)?.mimeType?.toLowerCase();
if (mime === 'video/h264' || mime === 'video/vp8') return mime.slice(6);
}
}
return null;
};
})()`;
interface GateResult {
passed: boolean;
requestedCodec: VideoCodec | "auto";
actualCodec: VideoCodec | null;
codecPreserved: boolean;
hostNativeActive: boolean;
hostInvite: boolean;
preSharePreferenceEnabled: boolean;
qualityControlsEnabled: boolean;
livePresetChanges: number;
liveQualityChanged: boolean;
fourKQualityChanged: boolean;
customQualityChanged: boolean;
rateQualityChanges: number;
pausedQualityChanged: boolean;
backgroundProfileRecovery: boolean | null;
sourceWindowRecovery: boolean | null;
mediaObjectPreserved: boolean;
nativeSourceChanged: boolean;
nativeQualityEvidence: boolean;
viewerConnected: boolean;
viewerFrames: number;
viewerWidth: number;
viewerHeight: number;
remoteViewerConnected: boolean;
remoteViewerPackets: number;
remoteLocalCandidateType: string;
remoteRemoteCandidateType: string;
remoteNatPath: boolean;
remotePeerExited: boolean | null;
sourceFailureEndedShare: boolean | null;
replacementViewerConnected: boolean | null;
replacementViewerFrames: number | null;
appCrashEndedShare: boolean | null;
mode: GateMode;
viewerLocation: "local-browser" | "public-url-browser" | "remote-peer";
publicViewerPage: boolean;
publicViewerSignal: boolean;
cleanup: Awaited<ReturnType<typeof cleanupRun>>;
error: string | null;
stage?: string;
}
interface RemoteGateOptions {
host: string;
user: string;
key: string;
bindAddress: string | null;
}
interface RemoteGateResult {
passed: boolean;
packets: number;
localCandidateType: string;
remoteCandidateType: string;
error: string | null;
}
function run(
command: string,
args: string[],
cwd = ROOT,
environment: NodeJS.ProcessEnv = process.env,
timeoutMs = 120_000,
): string {
const result = spawnSync(command, args, {
cwd,
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
env: environment,
timeout: timeoutMs,
killSignal: "SIGKILL",
windowsHide: true,
});
if (result.error) throw result.error;
if (result.status !== 0) {
throw new Error((result.stderr || result.stdout).trim() || command + " failed");
}
return result.stdout.trim();
}
async function waitForChild(
child: ChildProcessWithoutNullStreams | ChildProcess,
timeoutMs: number,
): Promise<number | null> {
if (child.exitCode !== null) return child.exitCode;
return withDeadline(
() => new Promise<number | null>((resolveExit, rejectExit) => {
child.once("error", rejectExit);
child.once("exit", resolveExit);
}),
Date.now() + timeoutMs,
);
}
async function stopChild(child: ChildProcessWithoutNullStreams | ChildProcess | null): Promise<boolean> {
if (!child || child.exitCode !== null || child.signalCode !== null) return true;
child.kill();
try {
await waitForChild(child, 5_000);
} catch {
if (process.platform === "win32" && child.pid !== undefined) {
spawnSync("taskkill.exe", ["/PID", String(child.pid), "/T", "/F"], {
stdio: "ignore",
timeout: 5_000,
windowsHide: true,
});
try {
await waitForChild(child, 2_000);
} catch {
// The process state below is the final cleanup check.
}
}
}
return child.exitCode !== null || child.signalCode !== null;
}
async function selectNativeSource(
cdp: CdpConnection,
page: PageHandle,
kind: "window" | "display",
title?: string,
): Promise<void> {
await waitForValue(
(deadline) => evaluate<boolean>(
cdp,
page,
`(() => {
const tab = document.querySelector('button[data-source-tab="${kind}"]');
if (!tab || tab.disabled) return false;
tab.click();
return true;
})()`,
deadline,
),
Boolean,
15_000,
);
const selector = kind === "display"
? "button[data-native-source^='display:']"
: "button[data-native-source]";
const predicate = title
? `(button) => button.textContent?.includes(${JSON.stringify(title)})`
: "() => true";
await waitForValue(
(deadline) => evaluate<boolean>(
cdp,
page,
`([...document.querySelectorAll(${JSON.stringify(selector)})].some(${predicate}))`,
deadline,
),
Boolean,
15_000,
);
await evaluate<void>(
cdp,
page,
`([...document.querySelectorAll(${JSON.stringify(selector)})].find(${predicate}))?.click()`,
Date.now() + 5_000,
);
}
async function clickHostControl(
cdp: CdpConnection,
page: PageHandle,
buttonExpression: string,
): Promise<void> {
await cdp.call("Page.bringToFront", {}, page.sessionId, Date.now() + 5_000);
const point = await evaluate<{ x: number; y: number }>(
cdp,
page,
`new Promise((resolve) => {
const button = ${buttonExpression};
if (!button || button.disabled || button.getAttribute('aria-disabled') === 'true')
throw new Error('Host control is unavailable');
button.scrollIntoView({block: 'center'});
requestAnimationFrame(() => requestAnimationFrame(() => {
const rect = button.getBoundingClientRect();
resolve({x: rect.x + rect.width / 2, y: rect.y + rect.height / 2});
}));
})`,
Date.now() + 5_000,
);
for (const type of ["mouseMoved", "mousePressed", "mouseReleased"]) {
await cdp.call("Input.dispatchMouseEvent", {
type, ...point, button: "left", clickCount: 1,
}, page.sessionId, Date.now() + 5_000);
}
}
async function readVideoCodec(cdp: CdpConnection, page: PageHandle): Promise<VideoCodec> {
const codec = await waitForValue(
(deadline) => evaluate<VideoCodec | null>(cdp, page, "window.__piikGateVideoCodec()", deadline),
(value) => value === "vp8" || value === "h264",
5_000,
);
if (codec === null) throw new Error("No decoded video codec was observed");
return codec;
}
async function assertVideoCodec(cdp: CdpConnection, page: PageHandle, expected: VideoCodec): Promise<void> {
const codec = await readVideoCodec(cdp, page);
if (codec !== expected) throw new Error(`Native codec changed from ${expected} to ${codec}`);
}
function remoteOptions(): RemoteGateOptions {
const host = process.env.PIIK_REMOTE_HOST?.trim();
const user = process.env.PIIK_REMOTE_USER?.trim() || "root";
const key = process.env.PIIK_REMOTE_SSH_KEY?.trim();
if (!host || !key) {
throw new Error(
"PIIK_REMOTE_HOST and PIIK_REMOTE_SSH_KEY are required",
);
}
return {
host,
user,
key,
bindAddress: process.env.PIIK_REMOTE_BIND_ADDRESS?.trim() || null,
};
}
function remoteTransportOptions(options: RemoteGateOptions): string[] {
return [
"-o", "BatchMode=yes",
"-o", "StrictHostKeyChecking=yes",
"-o", "ConnectTimeout=10",
...(options.bindAddress
? ["-o", `BindAddress=${options.bindAddress}`]
: []),
"-i", options.key,
];
}
async function runRemotePeerGate(
binary: string,
options: RemoteGateOptions,
signalUrl: string,
roomId: string,
viewerGrant: string,
origin: string,
): Promise<RemoteGateResult> {
const ssh = process.env.PIIK_SSH?.trim() || "ssh";
const scp = process.env.PIIK_SCP?.trim() || "scp";
const destination = `${options.user}@${options.host}`;
const remotePath = `/tmp/piik-peer-gate-${randomBytes(8).toString("hex")}`;
const transportOptions = remoteTransportOptions(options);
try {
run(scp, [...transportOptions, binary, `${destination}:${remotePath}`], ROOT, process.env, 30_000);
run(ssh, [...transportOptions, destination, "chmod", "700", remotePath], ROOT, process.env, 15_000);
const remote = spawn(
ssh,
[
...transportOptions,
"-T",
destination,
remotePath,
"--config",
"-",
],
{ stdio: "pipe", windowsHide: true },
);
let stdout = "";
remote.stdout.on("data", (chunk: Buffer) => {
stdout = (stdout + chunk.toString()).slice(-16_384);
});
remote.stderr.resume();
remote.stdin.end(JSON.stringify({
signalUrl,
origin,
roomId,
viewerGrant,
timeoutSeconds: 45,
minPackets: 30,
}));
let exitCode: number | null;
try {
exitCode = await waitForChild(remote, 60_000);
} catch {
await stopChild(remote);
return {
passed: false,
packets: 0,
localCandidateType: "",
remoteCandidateType: "",
error: "remote peer gate timed out",
};
}
const line = stdout
.split(/\r?\n/)
.map((value) => value.trim())
.filter(Boolean)
.at(-1);
let parsed: Partial<RemoteGateResult> = {};
if (line) {
try {
parsed = JSON.parse(line) as Partial<RemoteGateResult>;
} catch {
parsed = {};
}
}
return {
passed: parsed.passed === true && exitCode === 0,
packets: typeof parsed.packets === "number" ? parsed.packets : 0,
localCandidateType: typeof parsed.localCandidateType === "string"
? parsed.localCandidateType
: "",
remoteCandidateType: typeof parsed.remoteCandidateType === "string"
? parsed.remoteCandidateType
: "",
error: typeof parsed.error === "string"
? parsed.error
: exitCode === 0 ? null : "remote peer gate failed",
};
} finally {
try {
run(ssh, [...transportOptions, destination, "rm", "-f", remotePath], ROOT, process.env, 10_000);
} catch {
// The temporary binary is harmless if an already-closed SSH session
// prevents cleanup; the gate never places it in the repository.
}
}
}
export function powershell(): string {
return process.env.PIIK_POWERSHELL?.trim() || join(
process.env.SystemRoot || "C:\\Windows",
"System32",
"WindowsPowerShell",
"v1.0",
"powershell.exe",
);
}
function sourceHTML(): string {
return [
"<!doctype html><title>" + SOURCE_TITLE + "</title>",
"<style>html,body,canvas{margin:0;width:100%;height:100%;overflow:hidden;background:#102030}</style>",
"<canvas width=\"1280\" height=\"720\"></canvas><script>",
"const c=document.querySelector('canvas'),x=c.getContext('2d');let n=0;",
"function f(){x.fillStyle='hsl('+(n*5%360)+' 70% 45%)';x.fillRect(0,0,1280,720);",
"x.fillStyle='#fff';x.fillRect((n*19)%1100,160,180,400);x.font='60px sans-serif';x.fillText(n,42,92);n++;requestAnimationFrame(f)}f();",
"</script>",
].join("");
}
export async function sourceServer(port: number): Promise<{ close(): Promise<void> }> {
const server = createServer((_request, response) => {
response.writeHead(200, {
"Content-Type": "text/html; charset=utf-8",
"Cache-Control": "no-store",
});
response.end(sourceHTML());
});
await new Promise<void>((resolveListen, rejectListen) => {
server.once("error", rejectListen);
server.listen(port, "127.0.0.1", resolveListen);
});
return {
close: () => new Promise<void>((resolveClose, rejectClose) => {
server.close((error) => error ? rejectClose(error) : resolveClose());
}),
};
}
export async function startSourceBrowser(
chromePath: string,
profile: string,
debugPort: number,
sourcePort: number,
): Promise<{
child: ChildProcessWithoutNullStreams;
cdp: CdpConnection;
}> {
const child = await launchChrome(chromePath, debugPort, profile, [
"--no-first-run", "--no-default-browser-check",
"--disable-extensions", "--disable-logging",
"--disable-background-timer-throttling",
"--disable-backgrounding-occluded-windows",
"--disable-renderer-backgrounding",
"--app=http://127.0.0.1:" + sourcePort + "/",
]);
child.stdout.resume();
child.stderr.resume();
try {
const version = await waitForVersion(debugPort, child);
const cdp = await CdpConnection.connect(
version.webSocketDebuggerUrl,
Date.now() + 10_000,
);
return { child, cdp };
} catch (error) {
await cleanupRun({ chrome: child, cdp: null, native: null, server: null, profile: null, ports: [debugPort] });
throw error;
}
}
export async function closeSourceBrowser(
child: ChildProcessWithoutNullStreams,
cdp: CdpConnection,
): Promise<boolean> {
try {
await cdp.call("Browser.close", {}, undefined, Date.now() + 2_000);
} catch {}
cdp.close();
try {
await waitForChild(child, 5_000);
return true;
} catch {
return stopChild(child);
}
}
export async function waitForCaptureWindow(captureBinary: string): Promise<void> {
await waitForValue(
async () => JSON.parse(run(captureBinary, ["--list"], ROOT, process.env, 5_000)) as Array<{
title?: unknown;
}>,
(targets) => targets.some((target) =>
typeof target.title === "string" && target.title.includes(SOURCE_TITLE)
),
10_000,
);
}
async function waitForValue<T>(
sample: (deadline: number) => Promise<T>,
accept: (value: T) => boolean,
timeoutMs: number,
): Promise<T> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
try {
const value = await withDeadline(() => sample(deadline), deadline);
if (accept(value)) return value;
} catch {
// A transient page or signaling state is retried within the gate bound.
}
await new Promise((resolveWait) => setTimeout(resolveWait, 100));
}
throw new Error("Native Host gate timed out");
}
async function readAppEndpoint(
child: ChildProcessWithoutNullStreams,
requirePublicOrigin = false,
): Promise<{
endpoint: Endpoint;
password: string;
publicOrigin: string | null;
}> {
let buffered = "";
const lines: string[] = [];
let endpoint: Endpoint | null = null;
return withDeadline(
() => new Promise((resolveEndpoint, rejectEndpoint) => {
const onData = (chunk: Buffer) => {
buffered += chunk.toString();
for (;;) {
const newline = buffered.indexOf("\n");
if (newline < 0) return;
const line = buffered.slice(0, newline).trim();
buffered = buffered.slice(newline + 1);
if (!line) continue;
lines.push(line);
try {
endpoint = decodeAppEndpoint(line);
} catch {
// Informational lines are printed after the endpoint.
}
const passwordLine = lines.find((entry) => entry.startsWith("Local access password: "));
const openAccessLine = lines.find((entry) => entry === "Local access: open");
const publicOriginLine = lines.find((entry) =>
entry.startsWith("Public invitation origin: ")
);
if (endpoint && (passwordLine || openAccessLine) &&
(!requirePublicOrigin || publicOriginLine)) {
child.stdout.off("data", onData);
resolveEndpoint({
endpoint,
password: passwordLine
? passwordLine.slice("Local access password: ".length)
: "",
publicOrigin:
publicOriginLine?.slice("Public invitation origin: ".length) ?? null,
});
return;
}
}
};
child.stdout.on("data", onData);
child.once("error", rejectEndpoint);
child.once("exit", (code) =>
rejectEndpoint(new Error("App exited before readiness (" + String(code) + ")")),
);
}),
Date.now() + 15_000,
);
}
async function main(): Promise<void> {
if (process.platform !== "win32") {
throw new Error("The native Host gate currently requires Windows");
}
if (process.env.PIIK_CLIENT_NATIVE_HOST_GATE !== "true") {
throw new Error("PIIK_CLIENT_NATIVE_HOST_GATE=true is required");
}
const linkMedia = process.env.PIIK_CLIENT_LINK_MEDIA_GATE === "true";
const mode: GateMode = linkMedia ? "one-link" : "local";
const crashGate =
process.env.PIIK_CLIENT_NATIVE_HOST_CRASH_GATE === "true";
if (crashGate && mode !== "local") {
throw new Error("App crash gate requires local mode");
}
const sourceKind: "window" | "display" =
process.env.PIIK_CLIENT_NATIVE_HOST_SOURCE === "display"
? "display"
: "window";
const requestedCodec = process.env.PIIK_CLIENT_NATIVE_HOST_CODEC?.trim() || "auto";
if (requestedCodec !== "auto" && requestedCodec !== "h264" && requestedCodec !== "vp8") {
throw new Error("PIIK_CLIENT_NATIVE_HOST_CODEC must be auto, h264, or vp8");
}
const remote = mode === "one-link" &&
Boolean(process.env.PIIK_REMOTE_HOST?.trim() || process.env.PIIK_REMOTE_SSH_KEY?.trim())
? remoteOptions() : null;
const chromePath = process.env.CHROME_PATH?.trim();
if (!chromePath) throw new Error("CHROME_PATH is required");
const go = process.env.PIIK_GO?.trim() || "go";
const tunnel = process.env.PIIK_CLOUDFLARED?.trim() || join(
BUILD_ROOT,
"cloudflared.exe",
);
const profile = await mkdtemp(join(tmpdir(), "piik-client-media-"));
const sourceProfile = await mkdtemp(join(tmpdir(), "piik-client-media-"));
await mkdir(BUILD_ROOT, { recursive: true });
const diagnosticDirectory = await mkdtemp(join(BUILD_ROOT, "native-host-gate-"));
const sourcePort = await reservePort();
const appPort = await reservePort();
const debugPort = await reservePort();
const sourceDebugPort = await reservePort();
const appConfig = join(profile, "client.json");
const captureBuild = BUILD_ROOT;
const appBinary = join(BUILD_ROOT, "piik-app.exe");
const captureBinary = join(captureBuild, "piik-capture.exe");
const remoteBinary = join(BUILD_ROOT, "piik-peer-gate-linux");
let source: { close(): Promise<void> } | null = null;
let app: ChildProcessWithoutNullStreams | null = null;
let sourceChrome: ChildProcessWithoutNullStreams | null = null;
let sourceCdp: CdpConnection | null = null;
let chrome: ChildProcessWithoutNullStreams | null = null;
let cdp: CdpConnection | null = null;
let nativePort = 0;
let stage = "setup";
const result: GateResult = {
passed: false,
requestedCodec,
actualCodec: null,
codecPreserved: false,
hostNativeActive: false,
hostInvite: false,
preSharePreferenceEnabled: false,
qualityControlsEnabled: false,
livePresetChanges: 0,
liveQualityChanged: false,
fourKQualityChanged: false,
customQualityChanged: false,
rateQualityChanges: 0,
pausedQualityChanged: false,
backgroundProfileRecovery: mode === "local" && sourceKind === "window" ? false : null,
sourceWindowRecovery: mode === "local" && sourceKind === "window" ? false : null,
mediaObjectPreserved: false,
nativeSourceChanged: false,
nativeQualityEvidence: false,
viewerConnected: false,
viewerFrames: 0,
viewerWidth: 0,
viewerHeight: 0,
remoteViewerConnected: false,
remoteViewerPackets: 0,
remoteLocalCandidateType: "",
remoteRemoteCandidateType: "",
remoteNatPath: false,
remotePeerExited: null,
sourceFailureEndedShare: mode === "local" ? false : null,
replacementViewerConnected: mode === "local" ? false : null,
replacementViewerFrames: mode === "local" ? 0 : null,
appCrashEndedShare: crashGate ? false : null,
mode,
viewerLocation: remote ? "remote-peer" : mode === "one-link" ? "public-url-browser" : "local-browser",
publicViewerPage: false,
publicViewerSignal: false,
cleanup: {
browserExited: false,
nativeExited: false,
serverClosed: false,
portsClosed: false,
profileRemoved: false,
},
error: null,
};
try {
stage = "web-build";
run(process.env.ComSpec || "cmd.exe", [
"/d", "/s", "/c", "npm run build:web",
]);
stage = "source-server";
source = await sourceServer(sourcePort);
stage = "capture-build";
process.stderr.write(`${JSON.stringify({ stage, status: "started", at: new Date().toISOString() })}\n`);
run(powershell(), [
"-NoProfile", "-ExecutionPolicy", "Bypass", "-File",
join(ROOT, "native", "capture", "windows", "build.ps1"),
"-OutputDirectory", captureBuild,
]);
process.stderr.write(`${JSON.stringify({ stage, status: "finished", at: new Date().toISOString() })}\n`);
stage = "app-build";
run(go, [
"build", "-p", "1", "-trimpath", "-o", appBinary, "./cmd/piik-app",
], ROOT, { ...process.env, GOMAXPROCS: "2" });
if (remote) {
stage = "remote-peer-build";
run(
go,
["build", "-trimpath", "-o", remoteBinary, "./cmd/piik-peer-gate"],
ROOT,
{ ...process.env, GOOS: "linux", GOARCH: "amd64", CGO_ENABLED: "0" },
);
}
stage = "source-browser";
({ child: sourceChrome, cdp: sourceCdp } = await startSourceBrowser(
chromePath,
sourceProfile,
sourceDebugPort,
sourcePort,
));
await waitForCaptureWindow(captureBinary);
stage = "app-start";
app = spawn(appBinary, [
mode === "one-link" ? "--link" : "--local",
...(mode === "one-link"
? ["--tunnel-process", tunnel]
: []),
"--capture-process", captureBinary,
"--config", appConfig,
"--port", String(appPort),
"--debug", "--log-dir", diagnosticDirectory,
], {
stdio: "pipe",
windowsHide: true,
env: {
...process.env,
PIIK_DEBUG: "",
PIIK_CLIENT_GATE_NO_BROWSER: "true",
},
});
app.stderr.resume();
stage = "app-ready";
const appInfo = await readAppEndpoint(app, mode === "one-link");
nativePort = appInfo.endpoint.port;
stage = "local-server-ready";
await waitForValue(
async () => {
const response = await fetch("http://127.0.0.1:" + appPort + "/healthz");
return response.ok;
},
Boolean,
15_000,
);
stage = "host-browser";
chrome = await launchChrome(chromePath, debugPort, profile, [
"--no-first-run", "--no-default-browser-check",
"--disable-extensions", "--disable-logging",
"--disable-background-timer-throttling",
"--disable-backgrounding-occluded-windows",
"--disable-renderer-backgrounding",
"--window-size=1280,900",
]);
chrome.stdout.resume();
chrome.stderr.resume();
stage = "host-cdp";
const version = await waitForVersion(debugPort, chrome);
cdp = await CdpConnection.connect(version.webSocketDebuggerUrl, Date.now() + 10_000);
const hostBootstrap = new URLSearchParams({
...(appInfo.password ? { "client-access": appInfo.password } : {}),
"piik-client": "1",
}).toString();
stage = "host-page";
const host = await createPage(
cdp,
"http://localhost:" + appPort + "/?debug=1#" + hostBootstrap,
CODEC_PROBE,
true,
);
await waitForValue(
(deadline) => evaluate<boolean>(
cdp!,
host,
"Boolean(document.querySelector('button.lr-tv-big.is-action'))",
deadline,
),
Boolean,
15_000,
);
stage = "pre-share-quality-controls";
await evaluate<void>(
cdp,
host,
`document.querySelector('button[aria-controls="host-advanced-door"]')?.click()`,
Date.now() + 5_000,
);
result.preSharePreferenceEnabled = await waitForValue(
(deadline) => evaluate<boolean>(
cdp!,
host,
`(() => {
const preference = document.querySelector('button[name="degradationPreference"][value="maintain-resolution"]');
return Boolean(preference && !preference.disabled);
})()`,
deadline,
),
Boolean,
5_000,
);
stage = "pre-share-codec";
// Observe the source at the largest current ceiling before testing smaller
// ceilings. Native capture no longer pads/upscales every source to 16:9.
await clickHostControl(cdp, host, `document.querySelector('button.lr-chip[aria-label="1440p"]')`);
await clickHostControl(cdp, host, `document.querySelector('button[name="degradationPreference"][value="maintain-resolution"]')`);
await clickHostControl(cdp, host, `document.querySelector('.lr-sharing-technical > summary')`);
await clickHostControl(cdp, host,
`([...document.querySelectorAll('button.lr-chip')].find((button) =>
button.textContent?.trim() === ${JSON.stringify(requestedCodec.toUpperCase())}))`,
);
await evaluate<void>(
cdp,
host,
`document.querySelector('button[aria-controls="host-advanced-door"]')?.click()`,
Date.now() + 5_000,
);
stage = "host-click";
await evaluate<void>(
cdp,
host,
"document.querySelector('button.lr-tv-big.is-action')?.click()",
Date.now() + 5_000,
);
await selectNativeSource(
cdp,
host,
sourceKind,
sourceKind === "window" ? SOURCE_TITLE : undefined,
);
stage = "host-native-share";
let hostState: { invite: string | null; native: boolean };
try {
hostState = await waitForValue(
(deadline) => evaluate<{
invite: string | null;
native: boolean;
}>(
cdp!,
host,
"(async () => ({invite: document.querySelector('.lr-invite-url')?.value || null, " +
"native: (await window.__piikGateVideoCodec()) !== null, " +
"body: document.body.innerText.slice(0, 500)}))()",
deadline,
),
(state) => state.invite !== null && state.native,
40_000,
);
} catch (error) {
const diagnostic = await evaluate<unknown>(
cdp!,
host,
"({buttons: [...document.querySelectorAll('button')].map((button) => ({label: button.getAttribute('aria-label'), text: button.textContent?.slice(0, 120), disabled: button.disabled})), inputs: [...document.querySelectorAll('input')].map((input) => ({className: input.className, type: input.type, disabled: input.disabled}))})",
Date.now() + 2_000,
).catch(() => null);
throw new Error("native host stage failed: " +
(error instanceof Error ? error.message : String(error)) +
" diagnostic=" + JSON.stringify(diagnostic));
}
result.hostNativeActive = hostState.native;
result.hostInvite = hostState.invite !== null;
stage = "host-codec";
const actualCodec = await readVideoCodec(cdp, host);
result.actualCodec = actualCodec;
if (requestedCodec !== "auto" && actualCodec !== requestedCodec) {
throw new Error(`Native ${requestedCodec} selection produced ${actualCodec}`);
}
if (!hostState.invite) throw new Error("Host did not publish an invitation");
const inviteURL = new URL(hostState.invite);
const roomMatch = /^\/r\/([1-9][0-9]{3})$/.exec(inviteURL.pathname);
const viewerGrant = new URLSearchParams(inviteURL.hash.slice(1)).get("v");
if (!roomMatch || !viewerGrant) {
throw new Error("Host invitation is not a room grant");
}
if (remote) {
stage = "remote-viewer";
const signalUrl = new URL("/signal", appInfo.publicOrigin!).toString().replace(/^http/, "ws");
const remoteResult = await runRemotePeerGate(
remoteBinary,
remote,
signalUrl,
roomMatch[1],
viewerGrant,
appInfo.publicOrigin!,
);
result.remoteViewerConnected = remoteResult.passed;
result.remoteViewerPackets = remoteResult.packets;
result.remoteLocalCandidateType = remoteResult.localCandidateType;
result.remoteRemoteCandidateType = remoteResult.remoteCandidateType;
result.remoteNatPath = [
remoteResult.localCandidateType,
remoteResult.remoteCandidateType,
].some((value) => value === "srflx" || value === "prflx");
result.remotePeerExited = true;
if (!remoteResult.passed || !result.remoteNatPath) {
throw new Error(remoteResult.error || "remote peer did not use a reflexive ICE path");
}
} else {
const viewerURL = new URL(hostState.invite);
if (mode === "local") viewerURL.hostname = "localhost";
else {
if (viewerURL.protocol !== "https:" || viewerURL.origin !== appInfo.publicOrigin) {
throw new Error("One-link invitation does not use the actual public origin");
}
stage = "public-page-ready";
await waitForValue(async (deadline) => {
const response = await fetch(viewerURL, { signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())) });
return response.ok;
}, Boolean, 20_000);
}
stage = "viewer-page";
const viewer = await createPage(cdp, viewerURL.toString(), CODEC_PROBE, true);
stage = "viewer-media";
const viewerState = await waitForValue(
(deadline) => evaluate<{
frames: number;
width: number;
height: number;
connected: boolean;
}>(
cdp!,
viewer,
"(() => { const video = document.querySelector('video'); " +
"if (!video) return {frames:0,width:0,height:0,connected:false}; " +
"const q=video.getVideoPlaybackQuality(); return {frames:q.totalVideoFrames," +
"width:video.videoWidth,height:video.videoHeight,connected:video.videoWidth>0&&video.videoHeight>0}; })()",
deadline,
),
(state) => state.connected && state.frames >= 30 &&
state.width >= 320 && state.width <= 2560 && state.height >= 240 && state.height <= 1440,
40_000,
);
result.viewerConnected = viewerState.connected;
result.viewerFrames = viewerState.frames;
result.viewerWidth = viewerState.width;
result.viewerHeight = viewerState.height;
await evaluate<void>(cdp, viewer,
`window.__piikGateSourceSize = ${JSON.stringify({ width: viewerState.width, height: viewerState.height })}`,
Date.now() + 5_000);
await assertVideoCodec(cdp, viewer, actualCodec);
if (mode === "one-link") {
result.codecPreserved = true;
result.publicViewerPage = await evaluate<boolean>(cdp, viewer,
`location.origin === ${JSON.stringify(appInfo.publicOrigin)} && location.pathname === ${JSON.stringify(viewerURL.pathname)}`,
Date.now() + 5_000);
result.publicViewerSignal = await evaluate<boolean>(cdp, viewer,
"window.__piikGatePublicSignal()", Date.now() + 5_000);
} else {
await evaluate<boolean>(
cdp,
viewer,
`(() => {
const video = document.querySelector('video');
if (!video) return false;
window.__piikGateMedia = video.srcObject;
return window.__piikGateMedia !== null;
})()`,
Date.now() + 5_000,
);
stage = "native-quality-presets";
await clickHostControl(cdp, host,
`document.querySelector('button[aria-controls="host-advanced-door"]')`,
);
for (const [index, width, height] of [[0, 1280, 720], [1, 1920, 1080]] as const) {
await clickHostControl(cdp, host, `document.querySelectorAll('button.lr-tile')[${index}]`);
await waitForValue(
(deadline) => evaluate<boolean>(
cdp!,
viewer,
`window.__piikGateFitsProfile(${width}, ${height})`,
deadline,
),
Boolean,
20_000,
);
await assertVideoCodec(cdp, viewer, actualCodec);
result.livePresetChanges += 1;
}
stage = "native-quality-controls";
await waitForValue(
(deadline) => evaluate<boolean>(
cdp!,
host,
`Boolean(document.querySelector('button.lr-chip[aria-label="1440p"]'))`,
deadline,
),
Boolean,
5_000,
);
result.qualityControlsEnabled = await evaluate<boolean>(
cdp,
host,
`(() => {
const resolution = document.querySelector('button.lr-chip[aria-label="1440p"]');
const preference = document.querySelector('button[name="degradationPreference"][value="maintain-framerate"]');
const sliders = [...document.querySelectorAll('.lr-quality-rate input[type="range"]')];
return Boolean(
resolution && preference && !resolution.disabled && !preference.disabled &&
sliders.length === 2 && sliders.every((slider) => !slider.disabled)
);
})()`,
Date.now() + 5_000,
);
if (!result.qualityControlsEnabled) {
throw new Error("Native quality controls remained disabled");
}
await evaluate<void>(
cdp,
host,
`document.querySelector('button.lr-chip[aria-label="1440p"]')?.click()`,
Date.now() + 5_000,
);
result.liveQualityChanged = await waitForValue(
(deadline) => evaluate<boolean>(
cdp!,
viewer,
`(() => { const video = document.querySelector('video'); return Boolean(
video && window.__piikGateFitsProfile(2560, 1440) &&
video.getVideoPlaybackQuality().totalVideoFrames >= ${viewerState.frames + 10}
); })()`,
deadline,
),
Boolean,
20_000,
);
if (!result.liveQualityChanged) {
throw new Error("Native quality change did not reach the Viewer");
}
result.viewerWidth = viewerState.width;
result.viewerHeight = viewerState.height;
await assertVideoCodec(cdp, viewer, actualCodec);
stage = "native-4k-preset";
await clickHostControl(cdp, host, `document.querySelectorAll('button.lr-tile')[2]`);
await waitForValue(deadline => evaluate<boolean>(cdp!, host,
`document.querySelector('input[name="maxFramerate"]')?.value === '60' &&
document.querySelector('.lr-sharing-panel')?.getAttribute('aria-busy') === 'false'`,
deadline), Boolean, 20_000);
stage = "native-4k-controls";
const framesBefore4K = await evaluate<number>(cdp, viewer,
`document.querySelector('video')?.getVideoPlaybackQuality().totalVideoFrames ?? 0`, Date.now() + 5_000);
await evaluate<void>(cdp, host,
`document.querySelector('button.lr-chip[aria-label="4K"]')?.click()`, Date.now() + 5_000);
await waitForValue(deadline => evaluate<boolean>(cdp!, host, `(() => {
const fps = document.querySelector('input[name="maxFramerate"]');
const width = document.querySelector('.lr-video-size input[name="width"]');
const height = document.querySelector('.lr-video-size input[name="height"]');
return fps && Number(fps.max) >= 60 && fps.validity.valid && fps.value === '60' &&
width?.value === '3840' && height?.value === '2160';
})()`, deadline), Boolean, 10_000);
stage = "native-4k-decode";
result.fourKQualityChanged = await waitForValue(deadline => evaluate<boolean>(cdp!, viewer, `(() => {
const video = document.querySelector('video');
return Boolean(video && window.__piikGateFitsProfile(3840, 2160) &&
video.srcObject === window.__piikGateMedia &&
video.getVideoPlaybackQuality().totalVideoFrames >= ${framesBefore4K + 10});
})()`, deadline), Boolean, 20_000);
await assertVideoCodec(cdp, viewer, actualCodec);
stage = "native-custom-quality";
const framesBeforeCustom = await evaluate<number>(cdp, viewer,
`document.querySelector('video')?.getVideoPlaybackQuality().totalVideoFrames ?? 0`, Date.now() + 5_000);
await evaluate<void>(cdp, host, `(() => {
const width = document.querySelector('.lr-video-size input[name="width"]');
const height = document.querySelector('.lr-video-size input[name="height"]');
width.focus(); width.value = '960';
height.focus(); height.value = '600'; height.blur();
})()`, Date.now() + 5_000);
result.customQualityChanged = await waitForValue(
deadline => evaluate<boolean>(cdp!, viewer, `(() => {
const video = document.querySelector('video');
return Boolean(video && window.__piikGateFitsProfile(960, 600) &&
video.srcObject === window.__piikGateMedia &&
video.getVideoPlaybackQuality().totalVideoFrames >= ${framesBeforeCustom + 10});
})()`, deadline), Boolean, 20_000);
await assertVideoCodec(cdp, viewer, actualCodec);
stage = "native-rate-range";
for (const [fps, mbps] of [[1, 0.1], [60, 50]]) {
for (const [name, value] of [["maxFramerate", fps], ["maxBitrate", mbps]] as const) {
await evaluate<void>(cdp, host, `(() => {
const input = document.querySelector('input[name="${name}"]');
if (!input || input.disabled) throw new Error('Rate control is unavailable');
input.focus(); input.value = '${value}';
if (!input.validity.valid) throw new Error('Rate control rejected the candidate range');
input.blur();
})()`, Date.now() + 5_000);
await waitForValue(deadline => evaluate<boolean>(cdp!, host,
`document.querySelector('input[name="${name}"]')?.value === '${value}' &&
document.querySelector('.lr-sharing-panel')?.getAttribute('aria-busy') === 'false'`,
deadline), Boolean, 20_000);
}
const before = await evaluate<number>(cdp, viewer,
`document.querySelector('video')?.getVideoPlaybackQuality().totalVideoFrames ?? 0`, Date.now() + 5_000);
await waitForValue(deadline => evaluate<boolean>(cdp!, viewer, `(() => {
const video = document.querySelector('video');
return Boolean(video && video.srcObject === window.__piikGateMedia &&
video.getVideoPlaybackQuality().totalVideoFrames >= ${before + 3});
})()`, deadline), Boolean, 20_000);
await assertVideoCodec(cdp, viewer, actualCodec);
result.rateQualityChanges += 1;
}
const framesBeforePreference = await evaluate<number>(
cdp,
viewer,
`document.querySelector('video')?.getVideoPlaybackQuality().totalVideoFrames ?? 0`,
Date.now() + 5_000,
);
await evaluate<void>(
cdp,
host,
`document.querySelector('button[name="degradationPreference"][value="maintain-framerate"]')?.click()`,
Date.now() + 5_000,
);
await waitForValue(
(deadline) => evaluate<number>(
cdp!,
viewer,
`document.querySelector('video')?.getVideoPlaybackQuality().totalVideoFrames ?? 0`,
deadline,
),
(frames) => frames >= framesBeforePreference + 10,
15_000,
);
stage = "native-pause-ready";
await waitForValue(
(deadline) => evaluate<boolean>(
cdp!,
host,
`Boolean([...document.querySelectorAll('button')].find((candidate) =>
/^(Pause sharing|暂停分享)$/.test(candidate.getAttribute('aria-label') || '') &&
!candidate.disabled && candidate.getAttribute('aria-disabled') !== 'true'
))`,
deadline,
),
Boolean,
10_000,
);
await evaluate<void>(
cdp,
host,
`(() => {
const button = [...document.querySelectorAll('button')].find((candidate) =>
/^(Pause sharing|暂停分享)$/.test(candidate.getAttribute('aria-label') || '')
);
button?.click();
})()`,
Date.now() + 5_000,
);
stage = "native-pause-applied";
await waitForValue(
(deadline) => evaluate<boolean>(
cdp!,
host,
`Boolean([...document.querySelectorAll('button')].find((candidate) =>
/^(Resume sharing|恢复分享)$/.test(candidate.getAttribute('aria-label') || '')
))`,
deadline,
),
Boolean,
5_000,
);
await evaluate<void>(
cdp,
host,
`document.querySelector('button.lr-chip[aria-label="480p"]')?.click()`,
Date.now() + 5_000,
);
stage = "native-paused-profile";
await waitForValue(
(deadline) => evaluate<boolean>(
cdp!,
host,
`(() => {
const resolution = document.querySelector('button.lr-chip[aria-label="480p"]');
const resume = [...document.querySelectorAll('button')].find((candidate) =>
/^(Resume sharing|恢复分享)$/.test(candidate.getAttribute('aria-label') || '')
);
return Boolean(
resolution?.getAttribute('aria-pressed') === 'true' && resume &&
!resume.disabled && resume.getAttribute('aria-disabled') !== 'true'
);
})()`,
deadline,
),
Boolean,
10_000,
);
const framesBeforeResume = await evaluate<number>(
cdp,
viewer,
`document.querySelector('video')?.getVideoPlaybackQuality().totalVideoFrames ?? 0`,
Date.now() + 5_000,
);
await evaluate<void>(
cdp,
host,
`(() => {
const button = [...document.querySelectorAll('button')].find((candidate) =>
/^(Resume sharing|恢复分享)$/.test(candidate.getAttribute('aria-label') || '')
);
button?.click();
})()`,
Date.now() + 5_000,
);
stage = "native-resumed-profile";
const resumed = await waitForValue(
(deadline) => evaluate<{
frames: number;
width: number;
height: number;
sameMedia: boolean;
}>(
cdp!,
viewer,
`(() => {
const video = document.querySelector('video');
return {
frames: video?.getVideoPlaybackQuality().totalVideoFrames ?? 0,
width: video?.videoWidth ?? 0,
height: video?.videoHeight ?? 0,
sameMedia: Boolean(video && video.srcObject === window.__piikGateMedia),
};
})()`,
deadline,
),
(value) => value.frames >= framesBeforeResume + 10 &&
matchesCaptureSize(value.width, value.height, fittedCaptureSize(viewerState, 854, 480)),
20_000,
);
result.pausedQualityChanged = matchesCaptureSize(resumed.width, resumed.height, fittedCaptureSize(viewerState, 854, 480));
result.mediaObjectPreserved = resumed.sameMedia;
result.viewerWidth = resumed.width;
result.viewerHeight = resumed.height;
await assertVideoCodec(cdp, viewer, actualCodec);
if (sourceKind === "window") {
stage = "native-background-profile";
const { targetInfos } = await sourceCdp!.call<{
targetInfos: Array<{ targetId: string; type: string; url: string }>;
}>("Target.getTargets", {}, undefined, Date.now() + 5_000);
const target = targetInfos.find((value) =>
value.type === "page" && value.url === `http://127.0.0.1:${sourcePort}/`,
);
if (!target) throw new Error("Capture source page is missing");
const { windowId } = await sourceCdp!.call<{ windowId: number }>(
"Browser.getWindowForTarget", { targetId: target.targetId },
undefined, Date.now() + 5_000,
);
await sourceCdp!.call("Browser.setWindowBounds", {
windowId, bounds: { windowState: "minimized" },
}, undefined, Date.now() + 5_000);
try {
await evaluate<void>(cdp, host,
`new Promise((resolve) => {
document.querySelector('button.lr-chip[aria-label="720p"]')?.click();
requestAnimationFrame(() => requestAnimationFrame(resolve));
})`,
Date.now() + 5_000,
);
await waitForValue((deadline) => evaluate<boolean>(cdp!, host,
`Boolean(document.querySelector('#host-advanced-door .lr-sharing-panel[aria-busy="true"]'))`,
deadline,
), Boolean, 5_000);
} finally {
await sourceCdp!.call("Browser.setWindowBounds", {
windowId, bounds: { windowState: "normal" },
}, undefined, Date.now() + 5_000);
}
stage = "native-background-profile-recovery";
// A quiet source retains its pending replacement until restoration.
// Prove its actual delivery before applying the following profile.
for (const [label, width, height] of [["720p", 1280, 720], ["480p", 854, 480]] as const) {
const before = await evaluate<number>(cdp, viewer,
`document.querySelector('video')?.getVideoPlaybackQuality().totalVideoFrames ?? 0`,
Date.now() + 5_000,
);
await evaluate<void>(cdp, host,
`document.querySelector('button.lr-chip[aria-label="${label}"]')?.click()`,
Date.now() + 5_000,
);
await waitForValue((deadline) => evaluate<boolean>(cdp!, viewer,
`(() => {
const video = document.querySelector('video');
return Boolean(video && video.srcObject === window.__piikGateMedia &&
window.__piikGateFitsProfile(${width}, ${height}) &&
video.getVideoPlaybackQuality().totalVideoFrames >= ${before + 10});
})()`, deadline,
), Boolean, 20_000);
await waitForValue((deadline) => evaluate<boolean>(cdp!, host,
`Boolean(document.querySelector('#host-advanced-door .lr-sharing-panel[aria-busy="false"]'))`,
deadline,
), Boolean, 5_000);
}
result.backgroundProfileRecovery = true;
// WGC must keep the share through size changes and a temporarily quiet
// minimized window. This is a window-transition check, not a game test.
for (const bounds of [
{ width: 960, height: 650 },
{ windowState: "fullscreen" },
{ windowState: "normal" },
{ windowState: "minimized" },
]) {
stage = "native-window-" + (bounds.windowState ?? "resize");
await sourceCdp!.call("Browser.setWindowBounds", {
windowId, bounds,
}, undefined, Date.now() + 5_000);
if (bounds.windowState === "minimized") {
await new Promise((resolveWait) => setTimeout(resolveWait, 5_000));
await sourceCdp!.call("Browser.setWindowBounds", {
windowId, bounds: { windowState: "normal" },
}, undefined, Date.now() + 5_000);
}
const before = await evaluate<number>(cdp, viewer,
"document.querySelector('video')?.getVideoPlaybackQuality().totalVideoFrames ?? 0", Date.now() + 5_000);
await waitForValue((deadline) => evaluate<boolean>(cdp!, viewer,
`(() => {
const video = document.querySelector('video');
return Boolean(video && video.srcObject === window.__piikGateMedia &&
video.getVideoPlaybackQuality().totalVideoFrames >= ${before + 30});
})()`, deadline,
), Boolean, 20_000);
await assertVideoCodec(cdp, viewer, actualCodec);
}
result.sourceWindowRecovery = true;
}
stage = "native-source-picker";
await waitForValue(
(deadline) => evaluate<boolean>(
cdp!,
host,
`Boolean([...document.querySelectorAll('button')].find((candidate) =>
/^(Switch source|切换来源)$/.test(candidate.getAttribute('aria-label') || '') &&
!candidate.disabled && candidate.getAttribute('aria-disabled') !== 'true'
))`,
deadline,
),
Boolean,
10_000,
);
await evaluate<void>(
cdp,
host,
`(() => {
const button = [...document.querySelectorAll('button')].find((candidate) =>
/^(Switch source|切换来源)$/.test(candidate.getAttribute('aria-label') || '')
);
button?.click();
})()`,
Date.now() + 5_000,
);
await waitForValue(
(deadline) => evaluate<boolean>(
cdp!,
host,
`Boolean(document.querySelector('[role="dialog"] button[data-native-source]'))`,
deadline,
),
Boolean,
10_000,
);
const framesBeforeSourceChange = resumed.frames;
await selectNativeSource(cdp, host, sourceKind,
sourceKind === "window" ? SOURCE_TITLE : undefined,
);
stage = "native-source-replaced";
result.nativeSourceChanged = await waitForValue(
(deadline) => evaluate<boolean>(
cdp!,
viewer,
`(() => {
const video = document.querySelector('video');
return Boolean(
video && video.srcObject === window.__piikGateMedia &&
video.videoWidth > 0 && video.videoWidth <= 854 && video.videoHeight > 0 && video.videoHeight <= 480 &&
video.getVideoPlaybackQuality().totalVideoFrames >= ${framesBeforeSourceChange + 10}
);
})()`,
deadline,
),
Boolean,
20_000,
);
stage = "native-quality-evidence";
await assertVideoCodec(cdp, viewer, actualCodec);
result.codecPreserved = true;
result.nativeQualityEvidence = await waitForValue(
async () => {
const logPath = join(diagnosticDirectory, "client.log");
if ((await stat(logPath)).size > 8 * 1024 * 1024) {
throw new Error("Native Host gate diagnostic log exceeded its bound");
}
const diagnostics = await readFile(logPath, "utf8");
return diagnostics.split(/\r?\n/).some((line) => {
try {
const record = JSON.parse(line);
return record.msg === "piik-route" && record.event === "sender-quality-evidence" &&
(record.state === "healthy" || record.state === "degraded");
} catch {
return false;
}
});
},
Boolean,
12_000,
);
if (crashGate) {
stage = "app-crash";
if (!app || !(await stopChild(app))) {
throw new Error("App did not terminate for crash gate");
}
app = null;
result.appCrashEndedShare = await waitForValue(
(deadline) => evaluate<boolean>(
cdp!,
host,
"Boolean(document.querySelector('button.lr-tv-big.is-action'))",
deadline,
),
Boolean,
5_000,
);
} else if (sourceKind === "window") {
stage = "source-failure";
if (!sourceChrome || !sourceCdp ||
!(await closeSourceBrowser(sourceChrome, sourceCdp))) {
throw new Error("captured source did not close");
}
sourceChrome = null;
sourceCdp = null;
stage = "host-source-failure";
result.sourceFailureEndedShare = await waitForValue(
(deadline) => evaluate<boolean>(
cdp!,
host,
"Boolean(document.querySelector('button.lr-tv-big.is-action'))",
deadline,
),
Boolean,
20_000,
);
stage = "source-restart";
({ child: sourceChrome, cdp: sourceCdp } = await startSourceBrowser(
chromePath,
sourceProfile,
sourceDebugPort,
sourcePort,
));
await waitForCaptureWindow(captureBinary);
stage = "host-restart";
await evaluate<void>(
cdp,
host,
"document.querySelector('button.lr-tv-big.is-action')?.click()",
Date.now() + 5_000,
);
await selectNativeSource(
cdp,
host,
sourceKind,
sourceKind === "window" ? SOURCE_TITLE : undefined,
);
await waitForValue(
(deadline) => evaluate<boolean>(
cdp!,
host,
"Boolean(document.querySelector('.lr-tv-overlay[role=\"status\"]'))",
deadline,
),
Boolean,
40_000,
);
stage = "viewer-replacement-media";
result.replacementViewerConnected = await waitForValue(
(deadline) => evaluate<boolean>(
cdp!,
viewer,
`(() => {
const video = document.querySelector('video');
return Boolean(video && video.srcObject &&
video.srcObject !== window.__piikGateMedia &&
video.videoWidth > 0 && video.videoWidth <= 854 && video.videoHeight > 0 && video.videoHeight <= 480);
})()`,
deadline,
),
Boolean,
40_000,
);
result.replacementViewerFrames = await evaluate<number>(
cdp,
viewer,
`new Promise((resolve) => {
const video = document.querySelector('video');
let frames = 0;
const next = () => video.requestVideoFrameCallback(() => {
frames += 1;
if (frames >= 30) resolve(frames); else next();
});
next();
})`,
Date.now() + 10_000,
);
} else {
// A display remains available while the test Browser is open, so this
// arm does not claim source-end or same-room reselection evidence.
result.sourceFailureEndedShare = null;
result.replacementViewerConnected = null;
result.replacementViewerFrames = null;
}
}
}
} catch (error) {
// App stderr can contain implementation diagnostics or URLs; keep gate
// output independent of credentials and media-path identifiers.
result.error = error instanceof Error ? error.message : String(error);
result.stage = stage;
} finally {
if (sourceChrome && sourceCdp) {
await closeSourceBrowser(sourceChrome, sourceCdp);
sourceChrome = null;
sourceCdp = null;
} else if (sourceChrome && sourceChrome.exitCode === null) {
sourceChrome.kill();
}
result.cleanup = await cleanupRun({
cdp,
native: app,
chrome,
server: source,
profile,
ports: [sourcePort, appPort, debugPort, ...(nativePort ? [nativePort] : [])],
});
if (sourceProfile) {
const sourceCleanup = await cleanupRun({
cdp: null,
native: sourceChrome,
chrome: null,
server: null,
profile: sourceProfile,
ports: [sourceDebugPort],
});
result.cleanup.profileRemoved =
result.cleanup.profileRemoved && sourceCleanup.profileRemoved;
result.cleanup.portsClosed =
result.cleanup.portsClosed && sourceCleanup.portsClosed;
}
}
result.passed = result.error === null && result.actualCodec !== null && result.preSharePreferenceEnabled &&
result.hostNativeActive &&
result.hostInvite &&
(remote
? result.remoteViewerConnected && result.remoteViewerPackets >= 30 &&
result.remoteNatPath && result.remotePeerExited === true
: mode === "one-link"
? result.publicViewerPage && result.publicViewerSignal && result.viewerConnected &&
result.viewerFrames >= 30 && result.viewerWidth > 0 && result.viewerWidth <= 2560 &&
result.viewerHeight > 0 && result.viewerHeight <= 1440 && result.codecPreserved
: result.viewerConnected && result.viewerFrames >= 30 &&
result.qualityControlsEnabled && result.liveQualityChanged && result.fourKQualityChanged && result.customQualityChanged &&
result.rateQualityChanges === 2 &&
result.backgroundProfileRecovery !== false &&
result.sourceWindowRecovery !== false &&
result.livePresetChanges === 2 &&
result.codecPreserved &&
result.pausedQualityChanged && result.mediaObjectPreserved &&
result.nativeSourceChanged &&
result.viewerWidth > 0 && result.viewerWidth <= 854 && result.viewerHeight > 0 && result.viewerHeight <= 480 &&
result.nativeQualityEvidence &&
(crashGate
? result.appCrashEndedShare === true
: sourceKind === "display" ||
(result.sourceFailureEndedShare === true &&
result.replacementViewerConnected === true &&
(result.replacementViewerFrames ?? 0) >= 30))) &&
result.cleanup.browserExited && result.cleanup.nativeExited &&
result.cleanup.serverClosed && result.cleanup.portsClosed &&
result.cleanup.profileRemoved;
process.stdout.write(JSON.stringify(result) + "\n");
if (!result.passed) process.exitCode = 1;
}
if (
process.argv[1] &&
import.meta.url === pathToFileURL(resolve(process.argv[1])).href
) {
await main();
}