Files
piik/tests/app-connection-button.test.ts
T
TNTcraft e25bd00950 feat(maintenance): improve invitations and playback controls
## Problem and outcome / 问题与结果

Inviting another device, changing sources and adjusting playback should preserve the selected access and accepted settings. This update adds local QR invitations, optional translations and a video buffer setting, and repairs App discovery, source retirement, shared controls, remote-input geometry and audio reporting within the existing 2.x contracts.

## Release notes

### English

This update makes invitations easier to share and playback easier to adjust, while improving App connection, source switching and everyday controls. It also adds optional interface translations and more useful audio diagnostics.

- Show the current invitation as a locally generated QR code for another device to scan, preserving the selected access information.
- Add optional Traditional Chinese, Japanese and Korean translations. Chinese and English remain direct choices; the third menu includes extra languages and visual mode. Missing translations use English.
- Add an **Increase playback buffering** switch with an adjustable target. More buffering may reduce stalls from uneven packet arrival, at the cost of added viewing delay. Automatic remains the default.
- Ignore remote-control clicks on blank space outside a zoomed or rotated video.
- Check for a local Piik App once when a site opens. Automatic discovery respects local-network permission; explicit connection keeps approval under your control, and passive failures stay quiet.
- Keep a pending Browser screen or camera selection when the previous Native source ends or the App disconnects. Release the old source while allowing the new selection to finish; cancellation and Stop still end the operation correctly.
- Improve App-to-App connections when port mappings shift during setup.
- Keep playback hints clear of sharing controls, selection indicators inside their tracks, disabled action icons visible, and numeric settings aligned with accepted values.
- Use receiver audio reports for outgoing shared-sound loss statistics, and add opt-in Windows capture-progress diagnostics to help locate missing audio.

Existing 2.x App/site compatibility, saved room data and invitation privacy are preserved. Update the App for Native changes. After updating a hosted Server, refresh open site pages; App-local pages use the Web UI included in the updated App package.

### 中文

本次更新让邀请分享和播放调整更方便,并改善 App 连接、切换来源及日常控件。同时增加可选界面译文和更有帮助的音频诊断。

- 将当前邀请在本地生成二维码,保留所选访问凭证,方便另一台设备扫码加入。
- 增加繁体中文、日语和韩语可选译文。中英文保留快捷入口,第三个菜单提供附加语言与纯视觉模式;缺少的译文回退英文。
- 增加 **增加播放缓冲** 开关,并可调整目标值。更多缓冲可减少数据到达不均造成的停顿,但会增加观看延迟;默认仍由系统自动决定。
- 缩放或旋转画面后,不再把画面外空白区域的点击误传给远端。
- 打开站点时检查一次本地 Piik App。自动发现遵循本地网络权限,主动连接时才由你批准访问;被动发现失败保持安静。
- 旧 Native 来源结束或 App 断开时,保留正在进行的浏览器屏幕或摄像头选择。释放旧来源后仍可完成新选择;取消或主动停止时正确收尾。
- 改善建立连接时端口映射变化情况下的 App 间连接。
- 避免播放提示遮挡分享控件,让选中指示保持在轨道内,保留禁用按钮图标,并让数值设置显示实际接受的值。
- 共享声音的发送端丢包统计改用接收方音频报告,并增加可选的 Windows 采集进度诊断,帮助定位无声发生在哪一段。

保留现有 2.x App/站点兼容性、已保存的房间数据和邀请隐私。Native 改动需要更新 App。托管 Server 更新后请刷新已打开的页面;App 本地页面使用新版 App 包内的网页。

## Verification / 验证

- Complete frontend check: TypeScript, 110 test files / 2001 tests, Web build. Go core check: format, tests, vet and supported cross-target builds; macOS App builds require their native SDK.
- QR invitations passed independent local decoding, credential/rotation checks and short-window layout. Language/visual menus and guidance passed native and forced-polyfill Browser checks.
- Native preparation passed actual Pion socket adoption, VP8 SRTP and reverse SRTCP controls. Remote-input geometry and accepted numeric settings have focused regressions.
- Optional buffer transitions passed real P2P and actual SFU subscriber receiver-API controls for automatic to 300 ms to automatic. The SFU control used a Browser mock upstream rather than the embedded backend; Native preview delegation has unit coverage only.
- Windows diagnostics passed strict translation compilation, counter tests and stderr-to-diagnostic-ZIP verification. Physical capture, optical QR scanning and a public-network success-rate improvement are not claimed.

## Impact / 影响

Compatible 2.x update: Browser/server v24, Native control v10, capture v7 and SQLite schema 2 remain unchanged. Optional translations preserve English fallback and the independent visual preference. Playback buffer is a local viewing preference and leaves the default automatic. Existing room authority and invitation handling are preserved.

The HTTP compression dependency receives a compatible patch update. Mirror preparation detects a rejected missing tag before original-artifact downloads; the platform restriction remains open, with original-package validation and continuation rules intact. This does not establish fixes for #499, #502, #529 or #534.
2026-11-15 18:23:50 -04:00

524 lines
24 KiB
TypeScript

import { readFileSync } from "node:fs";
import { runInNewContext } from "node:vm";
import ts from "typescript";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { afterEach, describe, expect, it, vi } from "vitest";
import { AppConnectionButton } from "../src/client/components/living/AppConnectionButton";
import { CaptureSourcePicker } from "../src/client/components/living/CaptureSourcePicker";
describe("shared App connection entry", () => {
afterEach(() => vi.unstubAllGlobals());
it.each([
["iPhone", "Mozilla/5.0 (iPhone; CPU iPhone OS 26_0 like Mac OS X)", "iPhone", 5],
["iPad", "Mozilla/5.0 (iPad; CPU OS 26_0 like Mac OS X)", "iPad", 5],
["desktop-mode iPad", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15)", "MacIntel", 5],
["Android phone", "Mozilla/5.0 (Linux; Android 16) Mobile", "Linux armv8l", 5],
["Android tablet", "Mozilla/5.0 (Linux; Android 16)", "Linux armv8l", 5],
["touch Windows", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", "Win32", 10],
["Mac", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15)", "MacIntel", 0],
["Linux", "Mozilla/5.0 (X11; Linux x86_64)", "Linux x86_64", 0],
["unknown", "", "", 0],
])("offers the same connection entry on %s without hiding Browser capture", (_, userAgent, platform, maxTouchPoints) => {
vi.stubGlobal("navigator", { userAgent, platform, maxTouchPoints });
expect(renderToStaticMarkup(createElement(AppConnectionButton))).toContain("lr-app-connect");
const html = renderToStaticMarkup(createElement(CaptureSourcePicker, {
nativeSources: { kind: "browser" },
onBrowser: () => {}, onNative: () => {}, onCamera: () => {},
onPreview: async () => null, onRefresh: () => {}, onCancel: () => {},
}));
expect(html).toContain('data-source-tab="browser"');
expect(html).toContain('data-source-tab="camera"');
expect(html).not.toContain("lr-source-app-connection");
expect(html).not.toContain("lr-app-connect");
});
});
// Exercise the button's actual operation and unmount effect without a Browser.
// Discovery has separate transport tests; this covers who may activate a page.
const source = ts.createSourceFile("AppConnectionButton.tsx", readFileSync(
new URL("../src/client/components/living/AppConnectionButton.tsx", import.meta.url), "utf8",
), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
let connect: string | undefined;
let rememberBuild: string | undefined;
const effects: string[] = [];
function collect(node: ts.Node): void {
if (ts.isFunctionDeclaration(node) && node.name?.text === "connect") connect = node.getText(source);
if (ts.isFunctionDeclaration(node) && node.name?.text === "rememberBuild") rememberBuild = node.getText(source);
if (ts.isCallExpression(node) && node.expression.getText(source) === "useEffect") {
effects.push(node.arguments[0]!.getText(source));
}
ts.forEachChild(node, collect);
}
collect(source);
if (!connect || !effects.length) throw new Error("Missing App connection operation or cleanup");
const executable = ts.transpileModule(`${rememberBuild}\n${connect}\nconst cleanups = [${effects.map(effect => effect.includes("connect(false, true)") ? `(automatic ? (${effect})() : undefined)` : `(${effect})()`).join(",")}];
({ connect, cleanup: () => { cleanups.reverse().forEach(fn => fn?.()); pending.current?.controller.abort(); pending.current?.popup?.close(); } });`, {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
}).outputText;
const settle = () => new Promise<void>(resolve => setImmediate(resolve));
const site = "https://site.example";
const approval = `http://127.0.0.1:39721/client?site=${encodeURIComponent(site)}`;
function mount(activated = false, state: "idle" | "ready" = "idle", android = false, automatic = false) {
const popup = { closed: false, close: vi.fn(() => { popup.closed = true; }) };
const window = Object.assign(new EventTarget(), { open: vi.fn((): typeof popup | null => popup), location: { origin: site, assign: vi.fn() } });
const document = Object.assign(new EventTarget(), { visibilityState: "visible" });
const native = {
discoverNativeConnect: vi.fn(async (_options: { signal: AbortSignal; waitForPermission?: boolean }): Promise<string | null> => approval),
discoverNativeHealth: vi.fn(async (options: { signal: AbortSignal; waitForPermission?: boolean }): Promise<object | null> =>
options.waitForPermission === false && !activated ? null : {}),
NativeCompatibilityError: class extends Error {},
};
const pending = { current: null as { controller: AbortController; cancel?: () => void } | null };
const healthCheck = { current: null as AbortController | null };
const help = { current: { hidePopover: vi.fn(), matches: vi.fn(() => false) } };
const showHelp = vi.fn();
const setState = vi.fn();
const setBuild = vi.fn();
const activateClient = vi.fn();
const onConnected = vi.fn();
const operation = runInNewContext(executable, {
automatic, automaticFailed: { current: false }, window, document, pending, healthCheck, help, showHelp, setState, setAutomaticHint: vi.fn(), setBuild, activateClient, onConnected, AbortController, URL,
wakeURL: android ? "intent://app#Intent;scheme=piik;package=tv.piik.android;end" : null,
state, isClientActivated: () => activated,
watchClientActivation: (changed: () => void) => {
window.addEventListener("activation", changed);
return () => window.removeEventListener("activation", changed);
},
require: (path: string) => {
if (path !== "../../native/client") throw new Error(`Unexpected dependency: ${path}`);
return native;
},
}) as { connect: (wake?: boolean) => Promise<void>; cleanup: () => void };
function message(overrides: Record<string, unknown> = {}) {
window.dispatchEvent(Object.assign(new Event("message"), {
source: popup, origin: new URL(approval).origin, data: { type: "piik-app-approved", site }, ...overrides,
}));
}
const activateElsewhere = () => { activated = true; window.dispatchEvent(new Event("activation")); };
const openApproval = async () => { await operation.connect(); await operation.connect(); };
return { ...operation, openApproval, popup, window, document, native, pending, help, showHelp, setState, setBuild, activateClient, activateElsewhere, onConnected, message };
}
describe("App connection approval", () => {
it("uses the approved App's build and drops credentials from the update input", async () => {
const page = mount(true);
const build = { version: "v2.5.1", revision: "a".repeat(40), packageTarget: "android-universal" };
page.native.discoverNativeHealth.mockResolvedValue({ ...build, token: "local-secret" });
page.window.dispatchEvent(new Event("focus"));
await settle();
expect(page.setBuild).toHaveBeenLastCalledWith(build);
expect(page.setBuild.mock.calls.flat()).not.toContainEqual(expect.objectContaining({ token: expect.anything() }));
page.cleanup();
});
it("uses fresh authorized health instead of offering approval again", async () => {
const page = mount();
page.native.discoverNativeHealth.mockResolvedValue({});
await page.connect();
expect(page.setState).toHaveBeenLastCalledWith("ready");
expect(page.setState).not.toHaveBeenCalledWith("approval");
expect(page.window.open).not.toHaveBeenCalled();
expect(page.activateClient).toHaveBeenCalledOnce();
expect(page.onConnected).toHaveBeenCalledOnce();
expect(page.pending.current).toBeNull();
page.cleanup();
});
it("wakes Android in the original tab, then resumes discovery and explicit approval on return", async () => {
const page = mount(false, "idle", true);
await page.connect(true);
expect(page.window.location.assign).toHaveBeenCalledWith("intent://app#Intent;scheme=piik;package=tv.piik.android;end");
expect(page.window.open).not.toHaveBeenCalled();
expect(page.native.discoverNativeConnect).not.toHaveBeenCalled();
expect(page.activateClient).not.toHaveBeenCalled();
page.window.dispatchEvent(new Event("focus"));
page.document.dispatchEvent(new Event("visibilitychange"));
await settle();
expect(page.native.discoverNativeConnect).toHaveBeenCalledOnce();
expect(page.setState).toHaveBeenLastCalledWith("approval");
expect(page.window.open).not.toHaveBeenCalled();
await page.connect();
expect(page.window.open).toHaveBeenCalledWith(approval, "_blank");
page.message();
await settle();
expect(page.native.discoverNativeHealth).toHaveBeenCalledTimes(2);
expect(page.activateClient).toHaveBeenCalledOnce();
page.cleanup();
});
it("cancels a cold wake without reviving discovery after a late App return", async () => {
const page = mount(false, "idle", true);
await page.connect(true);
page.pending.current!.cancel!();
page.window.dispatchEvent(new Event("focus"));
page.document.dispatchEvent(new Event("visibilitychange"));
await settle();
expect(page.native.discoverNativeConnect).not.toHaveBeenCalled();
expect(page.window.open).not.toHaveBeenCalled();
expect(page.activateClient).not.toHaveBeenCalled();
expect(page.pending.current).toBeNull();
page.cleanup();
});
it("keeps permission discovery in the original tab and opens only on a later click", async () => {
const page = mount();
let complete!: (url: string) => void;
page.native.discoverNativeConnect.mockImplementation(() => new Promise(resolve => { complete = resolve; }));
const connecting = page.connect();
await settle();
expect(page.setState).toHaveBeenLastCalledWith("busy");
expect(page.showHelp).toHaveBeenCalledOnce();
expect(page.window.open).not.toHaveBeenCalled();
complete(approval);
await connecting;
expect(page.setState).toHaveBeenLastCalledWith("approval");
expect(page.window.open).not.toHaveBeenCalled();
page.message({ source: null });
expect(page.native.discoverNativeHealth).toHaveBeenCalledOnce();
await page.connect();
expect(page.window.open).toHaveBeenCalledWith(approval, "_blank");
expect(page.setState).toHaveBeenLastCalledWith("approving");
page.cleanup();
});
it("cancels dismissed discovery and ignores its late result before a retry", async () => {
const page = mount();
let complete!: (url: string) => void;
page.native.discoverNativeConnect.mockImplementationOnce(() => new Promise(resolve => { complete = resolve; }));
const connecting = page.connect();
await settle();
const first = page.pending.current!;
first.cancel!();
expect(first.controller.signal.aborted).toBe(true);
expect(page.pending.current).toBeNull();
expect(page.setState).toHaveBeenLastCalledWith("idle");
await page.connect();
complete(approval);
await connecting;
expect(page.setState).toHaveBeenLastCalledWith("approval");
expect(page.pending.current).not.toBe(first);
expect(page.window.open).not.toHaveBeenCalled();
await page.connect();
expect(page.window.open).toHaveBeenCalledOnce();
page.cleanup();
});
it("opens the launcher for an already connected Site without changing approval", async () => {
const page = mount(true, "ready");
await page.connect();
expect(page.setState).toHaveBeenLastCalledWith("ready");
expect(page.setState).not.toHaveBeenCalledWith("approval");
await page.connect();
expect(page.window.open).toHaveBeenCalledWith("http://127.0.0.1:39721/client", "_blank");
expect(page.setState).toHaveBeenLastCalledWith("ready");
expect(page.pending.current).toBeNull();
expect(page.activateClient).not.toHaveBeenCalled();
expect(page.onConnected).not.toHaveBeenCalled();
page.cleanup();
expect(page.popup.closed).toBe(false);
});
it("rechecks the managed App on return without interrupting approval or retaining a disconnected build", async () => {
const page = mount(true, "ready");
await page.connect();
const build = { version: "v2.5.2", revision: "b".repeat(40), packageTarget: "windows-amd64" };
page.native.discoverNativeHealth.mockResolvedValue(build);
page.window.dispatchEvent(new Event("focus"));
await settle();
expect(page.native.discoverNativeHealth).toHaveBeenLastCalledWith({ signal: expect.any(AbortSignal), waitForPermission: false });
expect(page.setBuild).toHaveBeenLastCalledWith(build);
expect(page.pending.current).not.toBeNull();
expect(page.onConnected).not.toHaveBeenCalled();
page.native.discoverNativeHealth.mockResolvedValue(null);
page.window.dispatchEvent(new Event("focus"));
await settle();
expect(page.setBuild).toHaveBeenLastCalledWith(undefined);
expect(page.setState).toHaveBeenLastCalledWith("idle");
expect(page.pending.current).toBeNull();
expect(page.window.open).not.toHaveBeenCalled();
page.cleanup();
});
it("offers recovery without activation or a stranded popup when no App is found", async () => {
const page = mount();
page.native.discoverNativeConnect.mockResolvedValue(null);
await page.connect();
expect(page.setState).toHaveBeenLastCalledWith("unavailable");
expect(page.showHelp).toHaveBeenCalledTimes(2);
expect(page.window.open).not.toHaveBeenCalled();
expect(page.pending.current).toBeNull();
expect(page.activateClient).not.toHaveBeenCalled();
page.cleanup();
});
it("offers recovery when the browser blocks the approval window", async () => {
const page = mount();
page.window.open.mockReturnValue(null);
await page.openApproval();
expect(page.setState).toHaveBeenLastCalledWith("unavailable");
expect(page.showHelp).toHaveBeenCalledTimes(2);
expect(page.native.discoverNativeConnect).toHaveBeenCalledOnce();
expect(page.activateClient).not.toHaveBeenCalled();
page.cleanup();
});
it("requires the exact window, origin and site, then verifies App health once", async () => {
const page = mount();
await page.openApproval();
page.native.discoverNativeHealth.mockClear();
let complete!: (health: object) => void;
page.native.discoverNativeHealth.mockImplementation(() => new Promise(resolve => { complete = resolve; }));
await page.connect();
expect(page.window.open).toHaveBeenCalledOnce();
expect(page.window.open).toHaveBeenCalledWith(approval, "_blank");
for (const invalid of [
{ source: {} }, { origin: "http://127.0.0.1:39722" },
{ data: { type: "piik-app-approved", site: "https://another.example" } },
{ data: { type: "other", site } }, { data: null },
]) page.message(invalid);
expect(page.native.discoverNativeHealth).not.toHaveBeenCalled();
page.message();
page.message();
expect(page.native.discoverNativeHealth).toHaveBeenCalledOnce();
expect(page.activateClient).not.toHaveBeenCalled();
complete({});
await settle();
expect(page.activateClient).toHaveBeenCalledOnce();
expect(page.onConnected).toHaveBeenCalledOnce();
expect(page.setState).toHaveBeenLastCalledWith("ready");
expect(page.popup.closed).toBe(true);
expect(page.pending.current).toBeNull();
expect(page.native.discoverNativeConnect.mock.calls[0]![0].signal.aborted).toBe(true);
page.message();
expect(page.native.discoverNativeHealth).toHaveBeenCalledOnce();
});
it.each(["absent", "failed"])("does not activate from an approval message when health is %s", async result => {
const page = mount();
await page.openApproval();
if (result === "absent") page.native.discoverNativeHealth.mockResolvedValue(null);
else page.native.discoverNativeHealth.mockRejectedValue(new Error("network unavailable"));
page.message();
await settle();
expect(page.activateClient).not.toHaveBeenCalled();
expect(page.onConnected).not.toHaveBeenCalled();
expect(page.setState).toHaveBeenLastCalledWith("unavailable");
expect(page.popup.closed).toBe(true);
expect(page.pending.current).toBeNull();
page.native.discoverNativeHealth.mockResolvedValue(null);
await page.openApproval();
expect(page.window.open).toHaveBeenCalledTimes(2);
page.cleanup();
});
it("ignores a late healthy response after unmount and closes the popup", async () => {
const page = mount();
await page.openApproval();
page.native.discoverNativeHealth.mockClear();
let complete!: (health: object) => void;
page.native.discoverNativeHealth.mockImplementation(() => new Promise(resolve => { complete = resolve; }));
page.message();
page.cleanup();
complete({});
await settle();
page.message();
expect(page.native.discoverNativeHealth).toHaveBeenCalledOnce();
expect(page.activateClient).not.toHaveBeenCalled();
expect(page.onConnected).not.toHaveBeenCalled();
expect(page.popup.closed).toBe(true);
expect(page.native.discoverNativeHealth.mock.calls[0]![0].signal.aborted).toBe(true);
expect(page.setState).toHaveBeenLastCalledWith("approving");
});
it("never opens an approval page when discovery completes after unmount", async () => {
const page = mount();
let complete!: (url: string) => void;
page.native.discoverNativeConnect.mockImplementation(() => new Promise(resolve => { complete = resolve; }));
const connecting = page.connect();
await settle();
page.cleanup();
complete(approval);
await connecting;
expect(page.window.open).not.toHaveBeenCalled();
expect(page.activateClient).not.toHaveBeenCalled();
});
it("verifies authorization on return even when the approval message is unavailable", async () => {
const page = mount();
await page.openApproval();
page.native.discoverNativeHealth.mockClear();
page.window.dispatchEvent(new Event("focus"));
await settle();
expect(page.native.discoverNativeHealth).toHaveBeenCalledOnce();
expect(page.setState).toHaveBeenLastCalledWith("ready");
expect(page.activateClient).toHaveBeenCalledOnce();
expect(page.onConnected).toHaveBeenCalledOnce();
expect(page.pending.current).toBeNull();
page.cleanup();
});
it("releases an unapproved closed window on focus and permits retry", async () => {
const page = mount();
await page.openApproval();
page.native.discoverNativeHealth.mockResolvedValue(null);
page.popup.closed = true;
page.window.dispatchEvent(new Event("focus"));
await settle();
expect(page.pending.current).toBeNull();
expect(page.setState).toHaveBeenLastCalledWith("idle");
page.message();
expect(page.native.discoverNativeHealth).toHaveBeenCalledTimes(2);
await page.openApproval();
expect(page.window.open).toHaveBeenCalledTimes(2);
page.cleanup();
});
it("verifies remembered activation without prompting and refreshes it on return", async () => {
const page = mount(true);
await settle();
expect(page.native.discoverNativeHealth).toHaveBeenCalledWith(expect.objectContaining({ waitForPermission: false }));
expect(page.setState).toHaveBeenLastCalledWith("ready");
expect(page.window.open).not.toHaveBeenCalled();
expect(page.activateClient).not.toHaveBeenCalled();
page.native.discoverNativeHealth.mockResolvedValue(null);
page.window.dispatchEvent(new Event("focus"));
await settle();
expect(page.setState).toHaveBeenLastCalledWith("idle");
page.cleanup();
});
it("reflects another App entry's activation without needing a focus change", async () => {
const page = mount();
await settle();
expect(page.native.discoverNativeHealth).not.toHaveBeenCalled();
page.activateElsewhere();
await settle();
expect(page.setState).toHaveBeenLastCalledWith("ready");
expect(page.window.open).not.toHaveBeenCalled();
page.cleanup();
page.activateElsewhere();
await settle();
expect(page.native.discoverNativeHealth).toHaveBeenCalledOnce();
});
it("does not let an earlier health check overwrite a newer approval", async () => {
const page = mount(true);
let complete!: (health: object | null) => void;
page.native.discoverNativeHealth.mockImplementationOnce(() => new Promise(resolve => { complete = resolve; }));
await settle();
await page.openApproval();
expect(page.native.discoverNativeHealth.mock.calls[0]![0].signal.aborted).toBe(true);
page.message();
await settle();
expect(page.setState).toHaveBeenLastCalledWith("ready");
complete(null);
await settle();
expect(page.setState).toHaveBeenLastCalledWith("ready");
page.cleanup();
});
});
describe("initial App discovery", () => {
it("keeps automatic permission passive and waits only for an explicit connection", async () => {
const page = mount(false, "idle", false, true);
page.native.discoverNativeConnect.mockResolvedValue(null);
try {
await settle();
expect(page.native.discoverNativeConnect).toHaveBeenLastCalledWith(expect.objectContaining({ waitForPermission: false }));
await page.connect();
expect(page.native.discoverNativeConnect).toHaveBeenLastCalledWith(expect.objectContaining({ waitForPermission: true }));
} finally { page.cleanup(); }
});
it("keeps passive focus incompatibility idle while explicit connection shows recovery", async () => {
const page = mount(true);
const incompatible = new page.native.NativeCompatibilityError("incompatible");
page.native.discoverNativeHealth.mockRejectedValue(incompatible);
page.native.discoverNativeConnect.mockRejectedValue(incompatible);
try {
await settle();
page.window.dispatchEvent(new Event("focus"));
await settle();
expect(page.setState).toHaveBeenLastCalledWith("idle");
expect(page.showHelp).not.toHaveBeenCalled();
await page.connect();
expect(page.setState).toHaveBeenLastCalledWith("incompatible");
expect(page.showHelp).toHaveBeenCalled();
} finally { page.cleanup(); }
});
it("automatically verifies an approved App without opening another page", async () => {
const page = mount(true, "idle", false, true);
await settle();
expect(page.native.discoverNativeConnect).toHaveBeenCalledOnce();
expect(page.onConnected).toHaveBeenCalledOnce();
expect(page.window.open).not.toHaveBeenCalled();
expect(page.showHelp).not.toHaveBeenCalled();
page.cleanup();
});
it("keeps unapproved discovery pending for the real approval click", async () => {
const page = mount(false, "idle", false, true);
await settle();
expect(page.setState).toHaveBeenLastCalledWith("approval");
expect(page.onConnected).not.toHaveBeenCalled();
expect(page.window.open).not.toHaveBeenCalled();
await page.connect();
expect(page.window.open).toHaveBeenCalledOnce();
page.cleanup();
});
it("does not repeat failed discovery on focus and aborts a manual retry on unmount", async () => {
const page = mount(true, "idle", false, true);
page.native.discoverNativeConnect.mockResolvedValue(null);
await settle();
expect(page.setState).toHaveBeenLastCalledWith("idle");
page.window.dispatchEvent(new Event("focus"));
page.activateElsewhere();
await settle();
expect(page.native.discoverNativeConnect).toHaveBeenCalledOnce();
expect(page.native.discoverNativeHealth).not.toHaveBeenCalled();
let signal: AbortSignal | undefined;
page.native.discoverNativeConnect.mockImplementationOnce(value => {
signal = value.signal;
return new Promise(() => {});
});
void page.connect();
await settle();
expect(page.native.discoverNativeConnect).toHaveBeenCalledTimes(2);
page.cleanup();
expect(signal?.aborted).toBe(true);
});
it.each([false, true])("automatic discovery stays idle; explicit failure keeps recovery guidance (incompatible: %s)", async incompatible => {
const page = mount(false, "idle", false, true);
page.native.discoverNativeConnect.mockImplementation(async () => {
if (incompatible) throw new page.native.NativeCompatibilityError("incompatible");
return null;
});
try {
await settle();
expect(page.setState).toHaveBeenLastCalledWith("idle");
expect(page.showHelp).not.toHaveBeenCalled();
await page.connect();
expect(page.setState).toHaveBeenLastCalledWith(incompatible ? "incompatible" : "unavailable");
expect(page.showHelp).toHaveBeenCalled();
} finally { page.cleanup(); }
});
it("an explicit approval click takes over the automatic attempt's failure feedback", async () => {
const page = mount(false, "idle", false, true);
try {
await settle();
expect(page.setState).toHaveBeenLastCalledWith("approval");
page.window.open.mockReturnValue(null);
await page.connect();
expect(page.setState).toHaveBeenLastCalledWith("unavailable");
expect(page.showHelp).toHaveBeenCalled();
} finally { page.cleanup(); }
});
});