Files
piik/scripts/app-browser-fanout-gate.ts
T
AAA 499789671c feat(app): bring Android sharing and touch control into the shared runtime (#504)
## Problem and outcome / 问题与结果

Bring Android into Piik's shared App workflow and make phone control usable without a separate Web UI. One signed APK covers ARM64 and x64; screen capture, room authority, routing, voice and site approval reuse the existing Go and Browser owners. Android opens the user's system browser rather than shipping an embedded browser.

This phase also fixes capture replacement and encoding-clock failures, improves source-audio startup, contains recoverable input and transport failures, adds a bounded relay-volunteer setting and supports hostnames in `SFU_PUBLIC_IP`. The website separates desktop and mobile downloads, gives iOS users an online entry and aligns the bilingual installation guides.

Related reports: #495, #499, #500, #501, #502 and #503. For #502, input execution failures now preserve authorization, and temporary target observations suspend rather than revoke it; the original Windows report remains open for candidate feedback.

## Release notes

**Piik, now in your pocket.**

Piik App now supports Android screen sharing, with touch controls for a friend's computer.

**手机,也能开播。**

Piik App 现已支持 Android 屏幕分享,也能用手机控制朋友的电脑。

### English

Piik v2.5.0 brings the App to Android and improves capture reliability, touch control and everyday startup. The existing 2.x compatibility baseline is unchanged.

- **Android App:** share your screen, join room voice or control a supported computer. One APK supports ARM64 and x64, using your own browser and the same Piik interface.
- **Phone controls:** use direct touch or a compact floating mouse with dragging, left/right buttons and a scroll wheel. Pinch to zoom and pan the picture while controlling.
- **More reliable sharing:** keep video progressing through source and encoder-output changes, and improve low-bitrate recovery and stationary-screen keyframes. Correct Windows window-size handling and Linux NVENC settings; start optional source sound after video is ready.
- **Smoother App entry:** retry failed startup in place, reopen the running room and retain the correct App connection when returning from the browser. Compress shared page assets to reduce loading traffic and keep microphone choices stable during ordinary page updates.
- **Recovery stays local:** a rejected input or canceled source replacement no longer revokes remote-control permission. Full ICE candidate queues and failed audio-parameter updates retain healthy connections. A failed local room leaves the App and unrelated approved sites running.
- **Connection settings:** relay volunteers can cap their downstream viewers. Self-hosted SFU setups can use a DNS hostname in `SFU_PUBLIC_IP`.
- **Clearer help:** refine sharing-error guidance, preserve input-failure diagnostics without recording input content, and update the bilingual platform and network guides.

Update both the App and your self-hosted site to use the new features. Android can control a supported computer; the Android device itself is not a controlled endpoint.

If you previously installed a test APK, uninstall it once before installing this release: the official signing key is different. Uninstalling clears App-local site approvals and starred-site choices; browser settings remain in the browser. Later official releases can be installed over this one.

### 中文

Piik v2.5.0 带来 Android App,并改善采集稳定性、手机远控与日常启动体验。沿用现有 2.x 兼容基线。

- **Android App:** 分享手机画面、加入房间语音,或控制支持远控的电脑。一个安装包同时支持 ARM64 与 x64,使用自己的浏览器和熟悉的 Piik 界面。
- **手机远控:** 直接触摸操作,或展开小巧的悬浮鼠标,使用拖拽、左右键与滚轮;控制时也能双指缩放、移动画面。
- **分享更稳定:** 修复切换采集来源、编码输出时画面停止推进的问题,改善低码率恢复与静止画面的关键帧响应。修正 Windows 窗口尺寸处理和 Linux NVENC 设置,来源声音会在画面就绪后启动。
- **App 进出更顺畅:** 启动失败可原地重试,再次打开会回到正在运行的房间;从浏览器返回时保持连接到正确的 App。共用页面资源启用压缩,减少加载流量,麦克风选项不再随普通页面更新反复加载。
- **局部问题就地恢复:** 单次操作失败或取消换源不再撤销远控授权;ICE 候选队列满或音频参数调整失败时保留健康连接。本地房间故障不会连带停止 App 和其他已授权站点的分享。
- **连接设置:** 帮助转发的观众可设置承接人数上限;自部署 SFU 的 `SFU_PUBLIC_IP` 现在支持 DNS 主机名。
- **排查更直接:** 打磨分享失败提示,补充不记录输入内容的远控故障诊断,并更新中英文平台说明与网络指南。

使用新功能时,请一起更新 App 与自部署站点。Android 可作为控制端操作电脑,手机本身不作为被控端。

曾安装测试 APK 的用户需先卸载一次,再安装正式版,两者签名不同。卸载会清除 App 内的站点授权和收藏,浏览器设置仍保留在浏览器中;后续正式版可直接覆盖安装。

## Verification / 验证

- Local full Web/type/build checks passed: 104 test files, 1,848 tests; the website and documentation builds passed.
- Android full-App emulator acceptance covered real decoded screen sharing, concurrent 1080p/540p encoder allocation, live bitrate changes, stationary keyframes, Viewer departure, consent reuse/reentry and final capture-resource retirement.
- A local universal release APK passed signing, package identity, version-code, ABI and non-debuggable checks using the permanent release key. GitHub Actions receives the same key through encrypted Secrets; manual candidate runs use a disposable candidate signer.
- Windows real capture checks covered H264/VP8 window resizing and restoration. Source-audio startup and failure/close ordering passed focused runtime checks; Linux race checks passed.
- Desktop/mobile website layouts were reviewed in English and Chinese, both themes, including grouped downloads, the iOS online entry and self-hosting links.
- All three Server and six App candidate targets, including the signed Android universal APK, passed in https://github.com/TNTcraftHIM/Piik/actions/runs/40350004792. This uses the same release packaging path with publication disabled.
- The complete network laboratory passed in https://github.com/TNTcraftHIM/Piik/actions/runs/40354253735: 43 expected scenario outcomes (37 media connections, six expected-unavailable controls), six negative controls, and complete process/network cleanup.
- Recoverable-error checks cover real encrypted input replies and legacy opt-in, retained grants and held-key cleanup, real Windows target geometry recovery, candidate queue overflow, and audio-parameter retry on the existing edge. Android room failure and full shutdown use real launcher, control WebSocket and supervised-process checks; unrelated site resources remain intact.
- The lifecycle fixes at `7eb04de373567cfe7aff2db6c93adf2a38e0b1aa` passed all nine package targets and Go/vulnerability/race/Web checks in https://github.com/TNTcraftHIM/Piik/actions/runs/40362794088, including macOS x64/ARM64 cgo and Android. Publication was skipped.
- Final cross-review found and fixed the same candidate-overflow false failure in the SFU voice owner. Its real-Pion regression verifies the first 64 candidates remain queued, a valid answer drains them, and renegotiation succeeds. Independent reviews confirmed real SDP and authorization failures still propagate.
- A real-browser before/after check reduced microphone enumeration from nine calls to one across eight ordinary Host rerenders. Changing the native client or switching to Browser capture still enumerates the new devices. The separate focused contribution #507 preserves input focus during queued floating-panel opening and is not attributed to this phase.
- The verified Windows candidate and reproduction steps have been updated in #502. macOS/Linux physical-device coverage and iOS device acceptance keep their documented boundaries.

## Impact / 影响

- Planned release: **v2.5.0**; no public wire or storage version bump.
- Android is a sharing and controlling endpoint, not a remotely controlled Android device. iOS is held outside this release.
- New Android release target joins the existing complete-target, checksum, GitHub and Gitee artifact pipeline. Signing material stays outside Git; optional input SDKs/drivers are not bundled.
- The owner authorized closure and publication after the final design review and acceptance checks. Restore the publication gate after the held focused contribution and merge this complete phase once; CI publishes only after its full checks and registered packages pass.
- Current TODO, platform guidance, media/routing evidence and release operations retain their existing document owners; no additional audit ledger or changelog archive is introduced.
2026-10-26 13:37:33 -04:00

352 lines
20 KiB
TypeScript

import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
import { once } from "node:events";
import { mkdtemp, mkdir, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import {
CdpConnection, cleanupRun, createPage, evaluate, fetchJsonBefore, launchChrome, reservePort,
waitForSample, waitForVersion, type PageHandle,
} from "./browser-gate-harness";
import { readAppEndpoint } from "./app-gate-endpoint";
import { fittedCaptureSize, matchesCaptureSize, parseVideoGateSize } from "./media-gate-geometry";
const ROOT = resolve(import.meta.dirname, "..");
const BUILD_ROOT = join(ROOT, "build/go-check");
// A documentation-only LAN address: it makes the room server publish a LAN
// invitation the gate rewrites to its loopback origins, exactly as the packaged
// App does on a real network.
const LAN_ADDRESS = "192.0.2.1";
const initialAudio = process.env.PIIK_CLIENT_GATE_AUDIO !== "false";
const punchRetry = process.env.PIIK_CLIENT_PUNCH_GATE === "true";
const captureSize = parseVideoGateSize(process.env.PIIK_CLIENT_GATE_VIDEO_SIZE || "1920x1080");
const probe = String.raw`(() => {
localStorage.setItem('piik:ui-lang', 'en');
localStorage.setItem('piik:ui-mode', 'text');
const pcs = [], requests = [], sockets = [], errors = [];
window.addEventListener('unhandledrejection', (e) => errors.push(String(e.reason)));
const codecPreferences = RTCRtpTransceiver.prototype.setCodecPreferences;
RTCRtpTransceiver.prototype.setCodecPreferences = function(value) {
try { return codecPreferences.call(this,value); }
catch (error) { errors.push(String(error)); throw error; }
};
const PC = RTCPeerConnection, WS = WebSocket;
let rejectFirstEdge = ${punchRetry};
window.RTCPeerConnection = class extends PC { constructor(...args) { super(...args); pcs.push(this); } };
window.WebSocket = class extends WS {
constructor(...args) { super(...args); if (String(args[0]).includes('/control')) {
sockets.push(this);
} }
send(raw) {
if (this.url.includes('/control')) {
const value = JSON.parse(raw); requests.push(value.type);
// Fail one candidate through the ordinary operation-error boundary.
// The real room controller must authorize the next preparation.
if (rejectFirstEdge && value.type === 'prepare-edge') {
rejectFirstEdge = false;
queueMicrotask(() => this.dispatchEvent(new MessageEvent('message', {data: JSON.stringify({
version:value.version, id:value.id, type:'request-failed', code:'operation-failed',
})})));
return;
}
}
super.send(raw);
}
};
let audio = ${initialAudio}, captures = 0;
navigator.mediaDevices.getDisplayMedia = async () => {
captures++;
const canvas = document.createElement('canvas'); canvas.width = ${captureSize.width}; canvas.height = ${captureSize.height};
const context = canvas.getContext('2d'); context.scale(canvas.width/1920,canvas.height/1080); let frame = 0;
const draw = () => { context.fillStyle = '#14242a'; context.fillRect(0,0,1920,1080);
context.fillStyle = '#68dab3'; context.fillRect((frame++ * 17)%1800,100,120,400);
context.fillStyle = '#ffffff'; context.font = '80px sans-serif'; context.fillText(String(frame),100,700); };
draw(); const timer = setInterval(draw, 1000/30);
const stream = canvas.captureStream(30);
const track = stream.getVideoTracks()[0]; const stop = track.stop.bind(track);
track.stop = () => { clearInterval(timer); stop(); };
if (audio) {
const ac = new AudioContext(), osc = ac.createOscillator(), dest = ac.createMediaStreamDestination();
osc.frequency.value = 440; osc.connect(dest); osc.start(); await ac.resume();
const sound = dest.stream.getAudioTracks()[0], stopSound = sound.stop.bind(sound);
let soundStopped=false;
sound.stop = () => { if (soundStopped) return; soundStopped=true; osc.stop(); void ac.close(); stopSound(); };
stream.addTrack(sound);
}
return stream;
};
window.fanoutGate = {
audio(value) { audio = value; },
breakIngress() { const pc = pcs.find((p) => p.connectionState === 'connected' && p.getSenders().some((s) => s.track?.kind === 'video'));
pc?.close(); },
async sample() {
let outbound = 0, encoded = 0, received = 0;
const videoStats=[], feedback=[];
for (const pc of pcs) { if (pc.connectionState === 'closed') continue;
const stats = await pc.getStats(); stats.forEach((s) => {
if (s.type==='remote-inbound-rtp') feedback.push({kind:s.kind,lost:s.packetsLost,fraction:s.fractionLost,rtt:s.roundTripTime,reports:s.reportsReceived});
if (s.type==='candidate-pair' && s.nominated) feedback.push({rtt:s.currentRoundTripTime,bwe:s.availableOutgoingBitrate,sent:s.bytesSent,received:s.bytesReceived});
if (s.type === 'outbound-rtp' && s.kind === 'video' && s.framesEncoded > 0) { outbound++; encoded += s.framesEncoded;
const source=stats.get(s.mediaSourceId);
videoStats.push({width:s.frameWidth,height:s.frameHeight,fps:s.framesPerSecond,reason:s.qualityLimitationReason,
sourceFps:source?.framesPerSecond,target:s.targetBitrate,encoder:s.encoderImplementation}); }
if (s.type === 'inbound-rtp' && s.kind === 'video') {
received += s.framesDecoded || 0;
feedback.push({inbound:true,fps:s.framesPerSecond,receivedFrames:s.framesReceived,decodedFrames:s.framesDecoded,
dropped:s.framesDropped,lost:s.packetsLost,received:s.packetsReceived,nack:s.nackCount,pli:s.pliCount,
decodeTime:s.totalDecodeTime,buffer:s.jitterBufferDelay,bufferEmitted:s.jitterBufferEmittedCount});
}
}); }
const video = document.querySelector('video');
return { outbound, encoded, received, captures, videoStats, feedback, width: video?.videoWidth || 0, height: video?.videoHeight || 0,
requests, errors, peers: pcs.map((p) => ({state:p.connectionState, tracks:p.getSenders().map((s)=>s.track?.kind)})),
frames: video?.getVideoPlaybackQuality().totalVideoFrames || 0,
sharing: Boolean(document.querySelector('button[aria-label="Stop sharing"]')),
captureLive: Boolean(video?.srcObject?.getVideoTracks()[0]?.readyState === 'live'),
capturesEnabled: video?.srcObject?.getVideoTracks()[0]?.enabled,
receiveRequests: requests.filter((r) => r === 'receive-offer').length,
edgeRequests: requests.filter((r) => r === 'prepare-edge').length,
controlOpen: sockets.some((s) => s.readyState === WS.OPEN),
codecSelected: [...document.querySelectorAll('button.lr-chip.is-selected')].map((b) => b.textContent),
audio: video?.srcObject?.getAudioTracks().length || 0,
buttons: [...document.querySelectorAll('.lr-host-share-slot button')].map((b) => b.getAttribute('aria-label')) };
}
};
})()`;
function build(command: string, args: string[]): void {
const result = spawnSync(command, args, { cwd: ROOT, encoding: "utf8", windowsHide: true,
timeout: 120_000, killSignal: "SIGKILL" });
if (result.error) throw result.error;
if (result.status !== 0) {
throw new Error((result.stderr || result.stdout).trim() || command + " failed");
}
}
// startRoomServer builds and starts the Piik server the Browser pages and
// both Apps share. PIIK_ENV stays development because production
// requires an HTTPS public origin and STUN; the Web assets are
// embedded either way.
async function startRoomServer(
port: number,
workingDirectory: string,
): Promise<ChildProcessWithoutNullStreams> {
const go = process.env.PIIK_GO?.trim() || "go";
await mkdir(BUILD_ROOT, { recursive: true });
// The server embeds the Vite output, so the Web build precedes the Go build.
build(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", "npm run build:web"]);
const binary = join(BUILD_ROOT, "piik-server.exe");
build(go, ["build", "-trimpath", "-o", binary, "./cmd/piik-server"]);
const origins = [`http://localhost:${port}`, `http://127.0.0.1:${port}`, `http://${LAN_ADDRESS}:${port}`];
const child = spawn(binary, [], {
// The gate profile has no .env, and the environment is explicit: the
// configuration this measurement runs against is these five values, never
// the repository's development file or the operator's shell.
cwd: workingDirectory, stdio: "pipe", windowsHide: true,
env: {
PATH: process.env.PATH,
SystemRoot: process.env.SystemRoot,
PIIK_ENV: "development",
ROOM_DATABASE_PATH: ":memory:",
PORT: String(port),
LISTEN_HOST: "127.0.0.1",
PUBLIC_BASE_URL: `http://${LAN_ADDRESS}:${port}`,
ALLOWED_ORIGINS: origins.join(","),
...(punchRetry ? { STUN_URLS: "stun:127.0.0.1:3478", STUN_LISTEN_HOST: "127.0.0.1",
NAT_PREDICTION_ENABLED: "true" } : {}),
},
});
child.stdout.resume();
child.stderr.resume();
try {
await once(child, "spawn");
await waitForSample(
(deadline) => fetchJsonBefore<{ status: string }>(`http://127.0.0.1:${port}/healthz`, deadline),
(value) => value.status === "ok",
20000,
);
return child;
} catch (error) {
await cleanupRun({ server: child, chrome: null, native: null, cdp: null, profile: null, ports: [port] });
throw error;
}
}
async function main(): Promise<void> {
if (process.env.PIIK_CLIENT_BROWSER_FANOUT_GATE !== "true") throw new Error("Browser fanout gate was not enabled");
const chromePath = process.env.CHROME_PATH;
if (!chromePath) throw new Error("CHROME_PATH is required");
const profile = await mkdtemp(join(tmpdir(), "piik-client-media-"));
const appPort = await reservePort(), debugPort = await reservePort();
const origin = `http://localhost:${appPort}`;
let app: ChildProcessWithoutNullStreams | null = null;
let relayApp: ChildProcessWithoutNullStreams | null = null;
let chrome: ChildProcessWithoutNullStreams | null = null;
let cdp: CdpConnection | null = null;
let server: ChildProcessWithoutNullStreams | null = null;
let nativePort = 0;
let relayPort = 0;
const pages: PageHandle[] = [];
const checks: Record<string, unknown> = {};
let stage = "startup", error: string | null = null;
try {
server = await startRoomServer(appPort, profile);
app = spawn(process.env.PIIK_CLIENT_EXE || join(BUILD_ROOT, "piik-app.exe"), [
"--site", origin, "--config", join(profile, "client.json"),
"--capture-process", join(BUILD_ROOT, "piik-capture.exe"),
], { windowsHide: true, stdio: "pipe", env: { ...process.env, PIIK_CLIENT_GATE_NO_BROWSER: "true" } });
await once(app, "spawn");
app.stderr.resume();
nativePort = (await readAppEndpoint(app)).port;
app.stdout.resume();
chrome = await launchChrome(chromePath, debugPort, profile, [
"--headless=new",
"--no-first-run", "--no-default-browser-check", "--no-proxy-server",
"--autoplay-policy=no-user-gesture-required", "--disable-background-timer-throttling",
"--disable-renderer-backgrounding", "--disable-backgrounding-occluded-windows",
]);
chrome.stdout.resume(); chrome.stderr.resume();
const version = await waitForVersion(debugPort, chrome);
checks.browser = version.Browser;
cdp = await CdpConnection.connect(version.webSocketDebuggerUrl, Date.now() + 10000);
await cdp.call("Browser.setPermission", { origin, permission: {name:"loopback-network"}, setting:"granted" }, undefined, Date.now()+5000);
const host = await createPage(cdp, `${origin}/#piik-client=1`, probe);
pages.push(host);
const read = async (page: PageHandle) => {
const sample = await evaluate<any>(cdp!, page, "fanoutGate.sample()", Date.now()+5000);
if (page === host) checks.lastHost = sample;
return sample;
};
const click = async (page: PageHandle, selector: string) => {
await waitForSample((deadline) => evaluate<boolean>(cdp!, page,
`Boolean(document.querySelector(${JSON.stringify(selector)}))`, deadline), Boolean, 10000);
await evaluate(cdp!, page, `document.querySelector(${JSON.stringify(selector)}).click()`, Date.now()+5000);
};
stage = "share";
await click(host, 'button[aria-controls="host-advanced-door"]');
stage = "share-codec";
await click(host, 'button[aria-label^="H264"]');
await evaluate(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 = '${captureSize.width}';
height.focus(); height.value = '${captureSize.height}'; height.blur();
})()`, Date.now()+5000);
stage = "share-picker";
await click(host, 'button.lr-tv-big.is-action');
// This arm measures Native ingress. Browser capture can start without App
// discovery, so first establish the control connection this gate requires.
await waitForSample(() => read(host),
(sample) => sample.controlOpen && sample.requests.includes("list-sources"), 10000);
stage = "share-browser-capture";
await click(host, 'button[data-source-tab="browser"]');
await click(host, 'button.lr-source-option[aria-label="Choose what to share"]');
stage = "share-ingress";
await waitForSample(() => read(host), (s) => s.sharing && s.receiveRequests === 1 && s.outbound === 1, 30000);
let invite = await evaluate<string>(cdp, host, "document.querySelector('.lr-invite-url').value", Date.now()+5000);
const url = new URL(invite);
url.protocol = "http:";
url.host = `localhost:${appPort}`;
invite = url.toString();
const relayOrigin = `http://127.0.0.1:${appPort}`;
relayApp = spawn(process.env.PIIK_CLIENT_EXE || join(BUILD_ROOT,"piik-app.exe"), [
"--site", relayOrigin, "--config", join(profile,"relay-client.json"),
"--capture-process", join(BUILD_ROOT,"piik-capture.exe"),
], { windowsHide:true, stdio:"pipe", env:{...process.env,PIIK_CLIENT_GATE_NO_BROWSER:"true"} });
await once(relayApp, "spawn");
relayApp.stderr.resume();
relayPort = (await readAppEndpoint(relayApp)).port;
relayApp.stdout.resume();
const viewers: PageHandle[] = [];
for (let index=0; index<2; index++) {
stage = `viewer-${index+1}`;
const context = await cdp.call<{browserContextId: string}>("Target.createBrowserContext", {}, undefined, Date.now()+5000);
await cdp.call("Browser.setPermission", { origin:index===0?relayOrigin:origin, permission: {name:"loopback-network"}, setting:"granted", browserContextId: context.browserContextId }, undefined, Date.now()+5000);
const viewerURL = index===0 ? invite.replace(origin,relayOrigin)+"&piik-client=1" : invite;
const viewer = await createPage(cdp, viewerURL, probe, true, context.browserContextId);
viewers.push(viewer);
pages.push(viewer);
await waitForSample(() => read(viewer), (s) => s.width > 0 && s.frames >= 30, 30000);
}
stage = "shared-encode";
for (const viewer of viewers) await waitForSample(() => read(viewer),
(s) => matchesCaptureSize(s.width, s.height, captureSize) && s.outbound===0, 30000);
checks.host = await read(host);
checks.viewers = await Promise.all(viewers.map(read));
if (punchRetry) {
// Loopback mappings are deliberately ineligible. Both real App controls
// must prepare, decline and continue ordinary ICE without losing media.
const source = checks.host as Awaited<ReturnType<typeof read>>;
const target = (checks.viewers as Awaited<ReturnType<typeof read>>[])[0];
if (!source.requests.includes("prepare-punch") || !target.requests.includes("prepare-punch") ||
source.requests.includes("run-punch") || target.requests.includes("run-punch")) {
throw new Error("Authorized retry did not decline its ineligible Native preparation");
}
checks.nativePreparationDeclined = true;
}
if ((checks.host as any).outbound !== 1 || !(checks.viewers as any[]).every((v) => v.outbound === 0)) {
throw new Error("Shared encode count did not match the Native fanout");
}
const beforeSteady = await Promise.all(viewers.map(read));
const steadyStart = Date.now();
await waitForSample(async () => Date.now()-steadyStart, (elapsed) => elapsed>=5000, 6000);
const afterSteady = await Promise.all(viewers.map(read));
checks.viewerFps = afterSteady.map((sample,index) => (sample.received-beforeSteady[index].received)*1000/(Date.now()-steadyStart));
if (!(checks.viewerFps as number[]).every((fps) => fps>=27)) throw new Error("Viewer delivery did not sustain the 30 fps source");
stage = "quality";
await click(host, 'button[aria-label="720p"]');
// Canvas capture can crop when applyConstraints changes its aspect. This
// gate checks fanout of the actual input; --display in the pool probe owns
// real display-capture geometry.
await waitForSample(async () => ({ source: await read(host), viewer: await read(viewers[0]!) }),
({ source, viewer }) => source.width > 0 && source.height > 0 &&
matchesCaptureSize(viewer.width, viewer.height, fittedCaptureSize(source, 1280, 720)), 20000);
checks.liveQuality = true;
stage = "pause-resume";
await click(host, 'button[aria-label="Pause sharing"]');
await waitForSample(() => read(host), (s) => s.capturesEnabled === false, 5000);
await click(host, 'button[aria-label="Resume sharing"]');
const before = await read(viewers[0]!);
await waitForSample(() => read(viewers[0]!), (s) => s.frames >= before.frames+20, 10000);
checks.pauseResume = true;
stage = "source-audio-change";
await evaluate(cdp, host, `fanoutGate.audio(${!initialAudio})`, Date.now()+5000);
await click(host, 'button[aria-label="Switch source"]');
await click(host, 'button[data-source-tab="browser"]');
await click(host, 'button.lr-source-option[aria-label="Choose what to share"]');
await waitForSample(() => read(host), (s) => s.receiveRequests === 2 && s.captures === 2 && s.sharing, 15000);
const beforeSource = await read(viewers[1]!);
await waitForSample(() => read(viewers[1]!), (s) => s.width > 0 && s.frames >= beforeSource.frames+20 && s.audio===Number(!initialAudio), 25000);
checks.sourceAudioChange = true;
stage = "app-exit";
app.stdin.write("\n");
await waitForSample(() => read(host), (s) => !s.controlOpen && s.sharing && s.captureLive && s.outbound === 2, 25000);
for (const viewer of viewers) {
const prior = await read(viewer);
await waitForSample(() => read(viewer), (s) => s.width > 0 && s.frames >= prior.frames+15, 30000);
}
checks.appExitRecovery = true;
checks.finalHost = await read(host);
if ((checks.finalHost as any).errors.length > 0) throw new Error("Browser reported an unhandled media error");
await mkdir(BUILD_ROOT, {recursive:true});
const screenshot = await cdp.call<{data:string}>("Page.captureScreenshot", {format:"png"}, host.sessionId, Date.now()+5000);
await writeFile(join(BUILD_ROOT,"browser-fanout.png"), Buffer.from(screenshot.data,"base64"));
await click(host, 'button[aria-label="Stop sharing"]');
stage = "done";
} catch (caught) {
error = caught instanceof Error ? caught.message : String(caught);
if (cdp) checks.atFailure = await Promise.all(pages.map((page) =>
evaluate(cdp!,page,"fanoutGate.sample()",Date.now()+5000).catch(()=>null)));
} finally {
const relayCleanup = await cleanupRun({cdp:null,native:relayApp,chrome:null,server:null,profile:null,ports:relayPort?[relayPort]:[]});
const cleanup = await cleanupRun({cdp, native:app, chrome, server, profile, ports:[appPort,debugPort,...(nativePort?[nativePort]:[])]});
const result = {passed: error===null && Object.values(cleanup).every(Boolean) && relayCleanup.nativeExited && relayCleanup.portsClosed, stage, checks, error, cleanup};
await mkdir(BUILD_ROOT,{recursive:true});
await writeFile(join(BUILD_ROOT,punchRetry ? "browser-fanout-punch.json" : "browser-fanout.json"), JSON.stringify(result,null,2));
process.stdout.write(JSON.stringify(result)+"\n");
if (!result.passed) process.exitCode=1;
}
}
await main();