## Problem and outcome Stale ICE and transport callbacks, interrupted media ownership, and optional encoder capabilities could break otherwise recoverable sharing sessions. This maintenance phase corrects those owners across Web, Native and embedded SFU, improves current-state diagnostics, and finishes the affected UI and documentation animation paths. Android, QR invitations and App/Server headline presentation stay on their feature branch. This PR contains the accepted maintenance scope only. ## Release notes **Play together. Your turn!** Approved friends can play together with shared keyboard and mouse controls or optional gamepads. **远程同乐,轮到你啦!** 获准的朋友可以共用键鼠,或使用可选手柄,一起玩本地多人游戏。 ### English This maintenance update improves connection recovery, capture compatibility and troubleshooting for existing Piik rooms. - Keep ICE candidates and gathering completion tied to their current connection. Preserve Viewer route preferences through reconnection and retry newly available Peer opportunities after SFU fallback. - Correct picture and voice ownership during restart, source replacement and connection retirement. Report failed picture dependencies while keeping room voice available. - Separate capture and forwarding statistics and isolate pooled sender attachment failures. - Improve Windows H.264 compatibility with optional encoder properties, retain safe capture failure codes, and keep shared sound volume usable without microphone support. - Improve remote input continuity and mouse responsiveness after idle. - Fix fullscreen handling in some mobile browsers, source-picker refresh, delayed chat confirmations, starred-site startup and local App requests. Refine control motion and reduced-motion behavior. - Restore the mascot's face and shared animation lifecycle in the documentation header. - Include current connection and playback state in diagnostic exports, update Zod to 4.6.6 and simplify shared lifecycle code. Existing 2.x protocols, configuration and default quality settings are preserved. ### 中文 本次维护更新改善现有房间的连接恢复、采集兼容性和故障诊断。 - ICE 候选和收集结束事件跟随当前连接;重连保留观众线路偏好,SFU 兜底后出现新的可用 P2P 机会仍可尝试。 - 修正重启、换源和连接结束时的画面与语音生命周期;语音继续时,画面失败会明确反馈。 - 区分采集与转发统计,隔离编码池中单个输出连接的失败。 - 改善 Windows H.264 可选属性兼容性,保留有效的采集失败原因;没有麦克风能力时也能调整共享声音音量。 - 修复部分移动浏览器全屏、选源刷新、迟到聊天确认、收藏站点启动和本机 App 请求问题,打磨控件动效及减少动态效果行为。 - 修复文档导航 mascot 面部一直隐藏的问题,接回共用动画生命周期。 - 诊断导出补取当前连接与播放状态,升级 Zod 至 4.6.6,精简共用生命周期代码。 沿用现有 2.x 协议、配置和画质默认值。Android、二维码邀请及 App/Server 新增的 HEADLINE 展示留待后续版本。 ## Verification - `npm run check`: type-check, 98 test files / 1,765 tests, production Web build passed. - `npm run check:go-core`: Go formatting, tests, vet, Windows/Linux builds passed; Darwin builds require the native CI runners. - `npm run check:native`: current Windows capture compilation, fixtures and capability probe passed. - `npm run build:website`, TypeScript and repository hygiene checks passed after the documentation-brand fix. - Existing controlled media lifecycle and P2P/SFU voice acceptance covered the retained route/transport changes. Final local browser acceptance covered actual sharing and pause/resume, fullscreen, source refresh, voice/keyboard/settings, 320px to desktop layouts, both themes and all presentation modes. Documentation brand was reproduced broken, then verified on load, replay and reduced motion. - Independent scoped reviews found no integration blocker. ## Impact Patch release v2.4.1. Existing 2.x wire, configuration, authority, capacity and default quality contracts remain intact; no data migration. Source volume no longer depends on microphone availability. Zod 4.6.6 fixes GHSA-mrhx-c7xc-m3w5. The device-specific Windows reports #495 and #452 remain under investigation; this PR improves compatibility and diagnostics without claiming those reports fully resolved. Physical macOS acceptance remains with its native runner/device checks.
161 lines
11 KiB
TypeScript
161 lines
11 KiB
TypeScript
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
|
import { once } from "node:events";
|
|
import { readFile, writeFile } from "node:fs/promises";
|
|
import { join, resolve } from "node:path";
|
|
import { createInterface } from "node:readline";
|
|
import { CdpConnection, cleanupRun, createPage, evaluate, fetchJsonBefore, launchChrome, reservePort, waitForSample,
|
|
waitForVersion, type PageHandle } from "../browser-gate-harness";
|
|
import { readAppEndpoint } from "../app-gate-endpoint";
|
|
import { pageProbe, type MediaSample } from "./page";
|
|
import { filteringProbe, preparePeerProbe, udpProbe } from "./udp";
|
|
|
|
export async function endpointWorker(): Promise<void> {
|
|
let chrome: ChildProcessWithoutNullStreams | null = null, app: ChildProcessWithoutNullStreams | null = null;
|
|
let cdp: CdpConnection | null = null, page: PageHandle | null = null;
|
|
const profile = process.env.PIIK_NETWORK_LAB_PROFILE;
|
|
if (!profile) throw new Error("Parent-owned browser profile is required");
|
|
const ports: number[] = [];
|
|
let rendezvous: Awaited<ReturnType<typeof preparePeerProbe>> | null = null;
|
|
const logs: Record<string, string> = {};
|
|
const log = (name: string, data: Buffer) => { logs[name] = ((logs[name] ?? "") + data).slice(-64_000); };
|
|
let closed = false;
|
|
const cleanup = async () => {
|
|
if (closed) return;
|
|
closed = true;
|
|
rendezvous?.close();
|
|
return cleanupRun({ chrome, native: app, cdp, server: null, profile, ports });
|
|
};
|
|
const sample = () => evaluate<MediaSample>(cdp!, page!, "networkLab.sample()", Date.now() + 5000);
|
|
const click = async (selector: string) => {
|
|
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`(()=>{const node=document.querySelector(${JSON.stringify(selector)});return !!node&&!node.disabled&&node.getAttribute('aria-disabled')!=='true';})()`, deadline), Boolean, 10_000);
|
|
await evaluate(cdp!, page!, `document.querySelector(${JSON.stringify(selector)}).click()`, Date.now() + 5000);
|
|
};
|
|
try {
|
|
for await (const line of createInterface({ input: process.stdin })) {
|
|
const request = JSON.parse(line) as { id: number; action: string; origin?: string; app?: boolean; loopbackMedia?: boolean;
|
|
url?: string; output?: string; delayMs?: number; load?: boolean; ipv6?: boolean; prediction?: boolean; sfuOnly?: boolean; peer?: { address: string; port: number } };
|
|
try {
|
|
let result: unknown;
|
|
if (request.action === "probe") {
|
|
result = await udpProbe(request.load === true, request.ipv6 === true);
|
|
} else if (request.action === "filter-probe") {
|
|
result = await filteringProbe();
|
|
} else if (request.action === "peer-prepare") {
|
|
rendezvous?.close(); rendezvous = await preparePeerProbe(); result = rendezvous.mapping;
|
|
} else if (request.action === "peer-probe") {
|
|
if (!rendezvous) throw new Error("Survey must precede peer probing");
|
|
result = await rendezvous.run(request.peer!);
|
|
} else if (request.action === "start") {
|
|
const origin = new URL(request.origin!).origin;
|
|
await waitForSample(deadline => fetchJsonBefore<{ status: string }>(`${origin}/healthz`, deadline),
|
|
value => value.status === "ok", 10_000);
|
|
if (request.app) {
|
|
app = spawn(resolve(`build/network-lab/bin/piik-app${process.platform === "win32" ? ".exe" : ""}`), ["--site", origin, "--debug", "--config", join(profile, "app.json")],
|
|
{ stdio: "pipe", windowsHide: true, env: { ...process.env, PIIK_CLIENT_GATE_NO_BROWSER: "true", PIIK_LOG_DIR: join(profile, "logs") } });
|
|
app.stderr.on("data", data => log("app", data));
|
|
await once(app, "spawn");
|
|
ports.push((await readAppEndpoint(app)).port); app.stdout.resume();
|
|
}
|
|
const debugPort = await reservePort(); ports.push(debugPort);
|
|
chrome = await launchChrome(process.env.CHROME_PATH!, debugPort, profile, [
|
|
"--headless=new", "--no-sandbox", "--disable-dev-shm-usage", "--no-first-run", "--no-default-browser-check",
|
|
"--no-proxy-server", "--autoplay-policy=no-user-gesture-required", "--disable-background-timer-throttling",
|
|
// The lifecycle SFU binds only loopback; namespace trials keep ordinary ICE interfaces.
|
|
...(request.loopbackMedia ? ["--allow-loopback-in-peer-connection"] : []),
|
|
"--use-fake-device-for-media-stream", "--use-fake-ui-for-media-stream",
|
|
"--disable-renderer-backgrounding", "--disable-backgrounding-occluded-windows",
|
|
`--unsafely-treat-insecure-origin-as-secure=${origin}`,
|
|
]);
|
|
chrome.stdout.resume(); chrome.stderr.on("data", data => log("browser", data));
|
|
const version = await waitForVersion(debugPort, chrome);
|
|
cdp = await CdpConnection.connect(version.webSocketDebuggerUrl, Date.now() + 10_000);
|
|
await cdp.call("Browser.setPermission", { origin, permission: { name: "loopback-network" }, setting: "granted" }, undefined, Date.now() + 5000);
|
|
result = { browser: version.Browser, app: request.app === true, appPort: request.app ? ports[0] : null };
|
|
} else if (request.action === "navigate") {
|
|
if (page) {
|
|
const oldTimeOrigin = await evaluate<number>(cdp!, page!, "performance.timeOrigin", Date.now() + 5000);
|
|
const navigation = await cdp!.call<{ loaderId?: string; errorText?: string }>("Page.navigate", { url: request.url! }, page.sessionId, Date.now() + 5000);
|
|
if (navigation.errorText) throw new Error(navigation.errorText);
|
|
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`${navigation.loaderId ? `performance.timeOrigin !== ${oldTimeOrigin} && ` : ""}document.readyState === 'complete' && Boolean(window.networkLab)`, deadline), Boolean, 10_000);
|
|
} else page = await createPage(cdp!, request.url!, pageProbe);
|
|
result = true;
|
|
} else if (request.action === "reload") {
|
|
const oldTimeOrigin = await evaluate<number>(cdp!, page!, "performance.timeOrigin", Date.now() + 5000);
|
|
await cdp!.call("Page.reload", {}, page!.sessionId, Date.now() + 5000);
|
|
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`performance.timeOrigin !== ${oldTimeOrigin} && document.readyState === 'complete' && Boolean(window.networkLab)`, deadline), Boolean, 10_000);
|
|
result = true;
|
|
} else if (request.action === "share") {
|
|
const advanced = 'button[aria-controls="host-advanced-door"]';
|
|
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`Boolean(document.querySelector(${JSON.stringify(advanced)}))`, deadline), Boolean, 10_000);
|
|
if (await evaluate<boolean>(cdp!, page!, `document.querySelector(${JSON.stringify(advanced)}).getAttribute('aria-expanded') !== 'true'`, Date.now() + 5000)) await click(advanced);
|
|
if (request.sfuOnly) {
|
|
if (request.prediction) throw new Error("SFU-only cannot request NAT enhancement");
|
|
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`Boolean(document.querySelector('button[role="switch"][aria-label^="Server media"][aria-disabled="true"][aria-checked="true"]'))`, deadline), Boolean, 10_000);
|
|
}
|
|
// Browser-to-App encoded fanout is the production H264 path. VP8
|
|
// deliberately stays in the Browser and must not masquerade as App WAN.
|
|
await click(app ? 'button[aria-label^="H264"]' : 'button[aria-label^="VP8"]');
|
|
await click('button[aria-label="720p"]');
|
|
await click("button.lr-tv-big.is-action");
|
|
// Selecting Browser before App discovery completes intentionally uses
|
|
// Browser fanout. An App scenario waits for the real control session.
|
|
if (app) await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`Boolean(document.querySelector('.lr-source-picker-refresh:not(:disabled)')) && networkLab.sample().then(value => value.controlOpen)`,
|
|
deadline), Boolean, 10_000);
|
|
await click('button[data-source-tab="browser"]');
|
|
await click(".lr-source-option.is-browser");
|
|
await waitForSample(sample, value => value.sharing && value.width > 0 &&
|
|
(request.prediction === undefined || value.natPrediction === request.prediction), 30_000);
|
|
result = await evaluate<string>(cdp!, page!, "document.querySelector('.lr-invite-url').value", Date.now() + 5000);
|
|
} else if (request.action === "sample") {
|
|
result = await sample();
|
|
} else if (request.action === "delay-peer-signals") {
|
|
if (!Number.isInteger(request.delayMs) || request.delayMs! < 0 || request.delayMs! > 30_000) throw new Error("Invalid signal delay");
|
|
await evaluate(cdp!, page!, `networkLab.delayPeerSignals(${request.delayMs})`, Date.now() + 5000);
|
|
result = true;
|
|
} else if (request.action === "reset-playback-progress") {
|
|
await evaluate(cdp!, page!, "networkLab.resetPlaybackProgress()", Date.now() + 5000);
|
|
result = true;
|
|
} else if (request.action === "restart-upstream") {
|
|
result = await evaluate(cdp!, page!, "networkLab.restartUpstream()", Date.now() + 5000);
|
|
} else if (request.action === "freeze-picture") {
|
|
result = await evaluate(cdp!, page!, "networkLab.freezeCapture()", Date.now() + 5000);
|
|
} else if (request.action === "resume-picture") {
|
|
result = await evaluate(cdp!, page!, "networkLab.resumeCapture()", Date.now() + 5000);
|
|
} else if (request.action === "signal-probe") {
|
|
result = await evaluate(cdp!, page!, "networkLab.signalProbe()", Date.now() + 5000);
|
|
} else if (request.action === "logs") {
|
|
if (app) logs.app = await readFile(join(profile, "logs", "client.log"), "utf8")
|
|
.then(text => text.slice(-64_000), error => String(error));
|
|
result = logs;
|
|
} else if (request.action === "stop") {
|
|
await click('button[aria-label="Stop sharing"]'); result = true;
|
|
} else if (request.action === "voice-open" || request.action === "voice-join") {
|
|
await click('button[aria-label="Interact"]');
|
|
await click('[role="tab"][id$="-voice-tab"]');
|
|
await click(`button[aria-label="${request.action === "voice-open" ? "Open room voice" : "Join voice"}"]`);
|
|
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`Boolean(document.querySelector('button[aria-label="Microphone"][aria-pressed="false"]'))`, deadline), Boolean, 10_000);
|
|
await click('button[aria-label="Microphone"][aria-pressed="false"]'); result = true;
|
|
} else if (request.action === "voice-sample") {
|
|
result = await evaluate(cdp!, page!, "networkLab.voiceSample()", Date.now() + 5000);
|
|
} else if (request.action === "screenshot") {
|
|
const shot = await cdp!.call<{ data: string }>("Page.captureScreenshot", { format: "png" }, page!.sessionId, Date.now() + 5000);
|
|
await writeFile(request.output!, Buffer.from(shot.data, "base64")); result = true;
|
|
} else if (request.action === "close") {
|
|
result = await cleanup();
|
|
} else throw new Error("Unknown endpoint action");
|
|
process.stdout.write(JSON.stringify({ id: request.id, result }) + "\n");
|
|
if (closed) break;
|
|
} catch (error) {
|
|
process.stdout.write(JSON.stringify({ id: request.id, error: error instanceof Error ? error.message : String(error) }) + "\n");
|
|
}
|
|
}
|
|
} finally { await cleanup(); }
|
|
}
|