Files
Piik/tests/client-launch-presentation.test.ts
AAA 799d6efb4a fix: improve sharing recovery and UI feedback
## Problem and outcome / 问题与结果

Browser sharing can remain connected to a local encoding transport that never becomes usable, leaving viewers without frames. This phase bounds that startup at eight seconds and restores ordinary encoding through the existing failure path. It also keeps ready App services running after a browser-open failure, preserves user presentation/playback choices, and aligns room feedback, illustrated hints, metrics and documentation.

部分环境下,本机编码连接一直无法建立会让观众收不到画面。本轮在八秒后进入现有降级流程,同时修复客户端启动移交、播放状态和前端反馈的一致性问题,并更新官网与中英文教程。

Closes #399.

Related: #396. The release contains relevant startup/error-handling repairs, but the reporting machine has not been retested. Keep this issue open for a current-build result. #401 (optional Windows capture-border hiding) remains deferred.

Release / 发布版本:**v1.3.1**.

## Release notes

### 中文

- 客户端记住上次确认的启动模式;启动移交保留已保存的语言、纯视觉模式和主题选择。
- 系统浏览器未能自动打开时,客户端继续运行,并在终端保留页面地址、重试入口和具体错误。
- 改善浏览器共享画面的启动兜底,避免 App 媒体因短暂信令中断被误判为失败。
- 音轨变化保持现有视频与观众的本机暂停状态;连接恢复和暂停恢复不再重复播放电视开机动画。
- 修复昵称编辑及长昵称查看,减少重复的角色提示,统一人物选择和连接状态的区别。
- 完善房间准入、密码和邀请说明;复制反馈对应当前链接及当前操作,避免迟到结果覆盖新反馈。
- 修正采集参数、统计单位与采样区间的展示,未知参数不再用配置上限代替。
- 统一提示漫画、状态图标与动效,改善选源器还焦、键盘操作、剧场布局和触控目标尺寸。
- 服务端默认支持 20 位观众,可在配置中设为 1–20 位,房主不占观众名额。
- 更新官网、教程入口和中英文说明,清理过时预览及失用代码。

兼容说明:使用旧版 App 连接更新后的站点时,站点会优先保留自己的显示偏好。如需更改语言或主题,请在进入后的页面调整。

### English

- Remember the last confirmed App launch mode and preserve saved language, visual-mode and theme choices during launch handoff.
- Keep the App running if the system browser fails to open, with the page address, retry action and error details available in the terminal.
- Improve the browser sharing startup fallback and avoid treating brief signaling outages as App media failures.
- Keep existing video and local pause state when audio tracks change. Reconnecting and resuming no longer replay the television startup animation over the picture.
- Fix nickname editing and full-name access, remove redundant role hints, and distinguish participant selection from connection state.
- Clarify room access, passwords and invitations. Copy feedback now belongs to the current link and operation, so late results cannot replace newer feedback.
- Correct capture details, metric units and observation intervals. Unknown capture values are no longer replaced with configured ceilings.
- Align illustrated hints, status icons and motion. Improve source-picker focus, keyboard operation, theater layout and touch targets.
- Default the Server to 20 viewers, configurable from 1 to 20. The host does not count toward that limit.
- Update the website, guide links and bilingual instructions, and remove obsolete previews and unused code.

Compatibility: when an older App connects to an updated Site, the Site keeps its saved presentation preferences. Change language or theme on the destination page when using an older launcher.

## Verification / 验证

Non-publishing [CI candidate run 34919320511](https://github.com/TNTcraftHIM/Piik/actions/runs/34919320511) passed Go core, race, Web checks, Server/container verification and all three native App package checks at source 188376e8. Subsequent commits only update deployment documentation, status and TODO; documentation/hygiene checks passed. Product inputs are unchanged.

- `npm run check`: TypeScript, 64 test files / 854 tests, and the Web production build passed.
- `npm run check:client-core`: final Go source passed tests, formatting, vet and core target builds. Windows capture compilation and geometry checks passed earlier in this phase; later edits did not change native capture.
- Website build, documentation checks, repository hygiene and diff checks passed. Existing documentation-size and bundle-size warnings remain.
- Actual browser flows covered sharing, source changes, pause/resume, late audio, brief signaling loss, invitation/copy feedback, entry preferences, source-picker focus, and narrow layouts.
- A local three-viewer P2P relay check covered quality-report expiry, recovery and cleanup without interrupting video. A controlled browser-helper failure returning `0xc0000005` left the real App launcher and Local service available.
- Homepage checks covered Chinese/English, light/dark preferences and inline-film open/close after removing the separate-page entry.

Limits: no new reporter-machine confirmation for #396 or the Windows URL-handler crash; physical Safari/mobile, macOS/Linux capture and wider public-network/endurance coverage remain deferred. Formal release artifacts will be built from the approved squash-merge revision. Hero-loop controls and video-adjacent tooltip placement remain open design items in TODO.

## Impact / 影响

Compatible patch; signaling, Native control and capture contracts are unchanged. Older App launch handoff keeps the updated Site's saved presentation preferences. The Server's default viewer limit is corrected to 20; an explicit 1–20 configuration remains valid.

Service updates retain persisted room authority but restart active media sessions. Deploy the verified immutable Server artifact through the existing bounded health/recovery process. Public Demo remains open and P2P-only; deployment does not enable SFU or change infrastructure/configuration.
2026-09-15 10:13:29 +08:00

111 lines
6.2 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import { readFileSync } from "node:fs";
import { runInNewContext } from "node:vm";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
const firstPaint = readFileSync(new URL("../index.html", import.meta.url), "utf8")
.match(/<script>([\s\S]*?)<\/script>/)![1]!;
const keys = ["piik:ui-lang", "piik:ui-mode", "piik:ui-theme"];
afterEach(() => { vi.unstubAllGlobals(); vi.resetModules(); });
function browser(saved: string[] = [], blocked = false) {
const values = new Map(keys.flatMap((key, index) => saved[index] ? [[key, saved[index]!]] : []));
const localStorage = {
getItem(key: string) { if (blocked) throw new Error("blocked"); return values.get(key) ?? null; },
setItem(key: string, value: string) { if (blocked) throw new Error("blocked"); values.set(key, value); },
removeItem(key: string) { if (blocked) throw new Error("blocked"); values.delete(key); },
};
const page = {
location: new URL("https://site.example/"),
localStorage,
sessionStorage: { getItem: () => null, setItem: vi.fn() },
addEventListener: vi.fn(),
matchMedia: () => ({ matches: false, addEventListener: vi.fn() }),
history: {
state: null,
replaceState: (_state: unknown, _unused: string, url: string) => {
page.location = new URL(url, page.location);
},
},
};
const document = { documentElement: { lang: "en", dataset: {} as Record<string, string> } };
vi.stubGlobal("navigator", { language: "en-US" });
vi.stubGlobal("document", document);
vi.stubGlobal("window", page);
return { page, document, values, saved: () => keys.map(key => values.get(key) ?? null) };
}
describe("App presentation handoff authority", () => {
it.each([
{ name: "old launcher preserves saved choices", saved: ["zh", "vis", "dark"], fields: "", selection: "zh:true", theme: "dark", result: ["zh", "vis", "dark"] },
{ name: "old launcher supplies only temporary first-use defaults", saved: [], fields: "", selection: "en:false", theme: "light", result: [null, null, null] },
{ name: "explicit language keeps the destination theme", saved: ["zh", "vis", "dark"], fields: "copy", selection: "en:false", theme: "dark", result: ["en", "text", "dark"] },
{ name: "explicit theme keeps the destination language and visual mode", saved: ["zh", "vis", "dark"], fields: "theme", selection: "zh:true", theme: "light", result: ["zh", "vis", "light"] },
{ name: "both explicit domains replace saved choices", saved: ["zh", "vis", "dark"], fields: "copy,theme", selection: "en:false", theme: "light", result: ["en", "text", "light"] },
])("$name", async ({ saved, fields, selection, theme, result }) => {
const env = browser(saved);
env.page.location = new URL(`https://site.example/${fields ? `?piik-preferences=${fields}` : ""}#piik-client=1&piik-lang=en&piik-mode=text&piik-theme=light`);
runInNewContext(firstPaint, { ...env.page, document: env.document, URLSearchParams, matchMedia: env.page.matchMedia });
expect(env.document.documentElement.dataset.theme).toBe(theme);
const copy = await import("../src/client/ui/copy");
const themes = await import("../src/client/ui/theme");
const { takeClientLaunchBootstrap } = await import("../src/client/lib/session");
const presentation = takeClientLaunchBootstrap().presentation!;
themes.initTheme(presentation.theme, presentation.explicit!.includes("theme"));
copy.applyLaunchCopy(presentation, presentation.explicit!.includes("copy"));
function Selection() { const { lang, vis } = copy.useCopy(); return `${lang}:${vis}`; }
expect(renderToStaticMarkup(createElement(Selection))).toBe(selection);
expect(env.document.documentElement.dataset.theme).toBe(theme);
expect(env.saved()).toEqual(result);
expect(env.page.location.search).toBe("");
expect(env.page.location.hash).toBe("");
});
it("does not clear a saved dark theme on an old system-theme handoff", async () => {
const env = browser(["zh", "vis", "dark"]);
const theme = await import("../src/client/ui/theme");
theme.initTheme(null, false);
expect(env.saved()).toEqual(["zh", "vis", "dark"]);
expect(env.document.documentElement.dataset.theme).toBe("dark");
});
it("retains explicit in-memory choices when storage is unavailable", async () => {
const env = browser([], true);
const copy = await import("../src/client/ui/copy");
const theme = await import("../src/client/ui/theme");
theme.initTheme();
copy.setCopy({ lang: "zh", vis: true });
theme.applyTheme("dark");
copy.applyLaunchCopy({ lang: "en", vis: false }, false);
theme.initTheme(null, false);
function Selection() { const { lang, vis } = copy.useCopy(); return `${lang}:${vis}`; }
expect(renderToStaticMarkup(createElement(Selection))).toBe("zh:true");
expect(copy.hasCopyPreference()).toBe(true);
expect(theme.currentThemePreference()).toBe("dark");
expect(env.document.documentElement.dataset.theme).toBe("dark");
expect(env.saved()).toEqual([null, null, null]);
});
it("keeps the old complete tuple and exact invitation fragment usable on old Sites", async () => {
const env = browser();
const { clientLaunchURL, takeClientLaunchBootstrap, readViewerRoute } = await import("../src/client/lib/session");
const grant = `${"a".repeat(21)}A`;
const target = new URL(clientLaunchURL(`https://site.example/r/9527?debug=1#piik-client=1&v=${grant}`, {
lang: "zh", vis: true, theme: "dark", explicit: ["copy", "theme"],
}));
const oldFragment = new URLSearchParams(target.hash.slice(1));
expect(oldFragment.get("piik-lang")).toBe("zh");
expect(oldFragment.get("piik-mode")).toBe("vis");
expect(oldFragment.get("piik-theme")).toBe("dark");
// The released reader removes only these keys before its exact #v= parser.
for (const key of ["piik-client", "client-access", "piik-lang", "piik-mode", "piik-theme"]) oldFragment.delete(key);
expect(oldFragment.toString()).toBe(`v=${grant}`);
env.page.location = target;
expect(takeClientLaunchBootstrap().presentation?.explicit).toEqual(["copy", "theme"]);
expect(env.page.location.search).toBe("?debug=1");
expect(readViewerRoute()).toEqual({ roomId: "9527", viewerGrant: grant });
});
});