Files
piik/tests/host-audio.test.ts
T
TNTcraft 07e37c7228 fix(app): stabilize authorization and compact room controls
## Problem and outcome / 问题与结果

App authorization could stay busy after a stalled save, a pending microphone request could survive a capture-source handoff, and compact room controls could lose focus, position or readable names. This maintenance phase corrects those owners and makes connection help easier to find.

## Verification / 验证

Validation: the exact candidate tree passed all 1,943 Web tests and documentation checks. Its unchanged product source has passed TypeScript and a production Web build. Controlled UI checks cover delayed microphone permission, stalled approval responses, keyboard viewport changes, rapid floating-panel hide/show and narrow nickname layouts. Published 2.x wire, native control and storage contracts are unchanged.

## Impact / 影响

Compatible 2.x maintenance release. Existing App, site and persisted room contracts are retained. Matching packages, download mirrors and both managed sites are verified through the normal release workflow.

## Release notes

**Piik, now in your pocket.**

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

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

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

### English

This maintenance update improves App authorization, capture-source switching and controls on smaller screens.

- Fix commentary controls remaining busy after switching from Browser capture to the App.
- Let App site approval recover from a stalled save, keeping access already granted.
- Preserve numeric-input focus when the mobile keyboard resizes the page, and provide increase/decrease buttons. Keep interaction windows at their remembered position after rapid hide/show actions.
- Give nicknames readable space on smaller screens, while retaining edit controls and accessible labels. Keep launcher diagnostics inside the shared Help menu.
- Make room-connection help easier to find, and clarify Safari screen-sharing and sound support.
- Complete package mirroring after a later CI publication step fails, and verify managed-service deployments against the intended source revision.

This maintenance update preserves the established 2.x room, invitation, media,
App-control and storage contracts. Refresh a site's open pages after it is
updated. App-local users need the updated App bundle to receive its included
Web fixes. Existing compatible 2.x App/site workflows remain supported.

### 中文

本次维护更新改善 App 授权、切换分享源和小屏操作。

- 修复浏览器切换为 App 采集后,分享麦克风控制一直处于忙碌状态的问题。
- App 站点授权不再因保存卡住而一直转圈;可以重试,已批准的授权也会保留。
- 手机键盘改变页面尺寸时保留数字输入焦点,并提供增减按钮;互动窗口快速隐藏再打开后保留记忆位置。
- 小屏上为昵称保留可读空间,同时保留编辑入口与无障碍名称;启动页诊断统一收进帮助菜单。
- 更容易找到房间连接问题的排查入口,并说明 Safari 屏幕分享与声音的支持情况。
- 发布流程后续步骤失败时,仍可补全已经发布的程序包镜像;部署核验明确比对预期源码版本。

本维护更新保留既有 2.x 房间、邀请、媒体、App 控制与存储契约。
站点更新后请刷新已打开的网页;App 本地使用者需更新程序包,才能使用其中的新网页修复。
已有兼容的 2.x App/站点使用方式继续支持。
2026-11-08 12:28:03 -04:00

174 lines
8.7 KiB
TypeScript

import { afterEach, expect, test, vi } from "vitest";
import { HostAudio } from "../src/client/media/host-audio";
import { captureBrowserSource, QUALITY_PROFILES } from "../src/client/media/quality";
class Track extends EventTarget {
enabled = true;
readyState = "live";
onended: (() => void) | null = null;
constructor(readonly kind: string) { super(); }
stop = vi.fn(() => { this.readyState = "ended"; });
}
class Stream {
constructor(private tracks: Track[]) {}
getTracks() { return this.tracks; }
getAudioTracks() { return this.tracks.filter((track) => track.kind === "audio"); }
getVideoTracks() { return this.tracks.filter((track) => track.kind === "video"); }
}
const media = (...tracks: Track[]) => new Stream(tracks) as unknown as MediaStream;
function setup() {
const getUserMedia = vi.fn();
vi.stubGlobal("navigator", { mediaDevices: { getUserMedia } });
return { getUserMedia };
}
afterEach(() => vi.unstubAllGlobals());
class AudioNode {
connect = vi.fn();
disconnect = vi.fn();
}
class Context {
currentTime = 0;
state = "running";
close = vi.fn(async () => { this.state = "closed"; });
resume = vi.fn(async () => {});
createMediaStreamDestination() { return Object.assign(new AudioNode(), { stream: media(new Track("audio")) }); }
createMediaStreamSource = vi.fn(() => new AudioNode());
createGain = vi.fn(() => Object.assign(new AudioNode(), { gain: { value: 1, setTargetAtTime: vi.fn() } }));
createAnalyser() { return Object.assign(new AudioNode(), { fftSize: 256, getFloatTimeDomainData: vi.fn() }); }
}
function mixerSetup() {
const { getUserMedia } = setup();
const contexts: Context[] = [];
vi.stubGlobal("AudioContext", class extends Context { constructor() { super(); contexts.push(this); } });
vi.stubGlobal("MediaStream", Stream);
return { getUserMedia, contexts };
}
test("failed optional mixing preserves source sharing and retires its partial graph", async () => {
const { getUserMedia } = mixerSetup();
const context = new Context();
context.resume.mockRejectedValueOnce(new Error("Audio unavailable"));
vi.stubGlobal("AudioContext", class { constructor() { return context; } });
const destination = vi.spyOn(context, "createMediaStreamDestination");
const video = new Track("video"), sound = new Track("audio"), source = media(video, sound);
const audio = new HostAudio(source);
expect(await audio.start()).toBe(source);
expect(audio.commentaryAvailable).toBe(false);
expect(audio.audioAvailable).toBe(true);
expect(video.stop).not.toHaveBeenCalled(); expect(sound.stop).not.toHaveBeenCalled();
expect(destination.mock.results[0]!.value.stream.getAudioTracks()[0].readyState).toBe("ended");
expect(context.close).toHaveBeenCalledOnce();
await expect(audio.setMicrophone(true, { deviceId: "", volume: 1, voiceProcessing: true })).rejects.toThrow("Shared audio is unavailable");
expect(getUserMedia).not.toHaveBeenCalled();
const nextSound = new Track("audio"), replacement = media(video, nextSound);
expect(audio.attach(replacement)).toBe(replacement);
expect(sound.stop).toHaveBeenCalledOnce();
audio.dispose();
expect(nextSound.stop).toHaveBeenCalledOnce(); expect(video.stop).not.toHaveBeenCalled();
});
test("commentary and source replacement retain one published output and retire their own inputs", async () => {
const { getUserMedia, contexts } = mixerSetup();
const microphone = new Track("audio"), nextMic = new Track("audio"), video = new Track("video"), sound = new Track("audio");
const changed = vi.fn(), microphoneChanged = vi.fn();
const audio = new HostAudio(media(video, sound), "browser", changed, microphoneChanged);
const output = await audio.start(), outputTrack = output.getAudioTracks()[0];
expect(audio.commentaryAvailable).toBe(true);
expect(outputTrack!.contentHint).toBe("music");
audio.setVolume(.5);
expect(contexts[0]!.createGain.mock.results[0]!.value.gain.setTargetAtTime).toHaveBeenCalledWith(.5, 0, .01);
getUserMedia.mockResolvedValueOnce(media(microphone));
await audio.setMicrophone(true, { deviceId: "headset", volume: 1, voiceProcessing: true });
expect(getUserMedia).toHaveBeenCalledWith({ audio: expect.objectContaining({ deviceId: { exact: "headset" }, echoCancellation: true }), video: false });
const nextVideo = new Track("video");
const replacement = audio.attach(media(nextVideo), "camera");
expect(replacement.getAudioTracks()[0]).toBe(outputTrack);
expect(replacement.getVideoTracks()[0]).toBe(nextVideo);
expect(audio.sourceAudioAvailable).toBe(false);
expect(audio.audioAvailable).toBe(true);
expect(sound.stop).toHaveBeenCalledOnce();
getUserMedia.mockRejectedValueOnce(new Error("Device unavailable"));
await expect(audio.setMicrophone(true, { deviceId: "missing", volume: 1, voiceProcessing: true })).rejects.toThrow("Device unavailable");
expect(audio.audioAvailable).toBe(true);
expect(microphone.stop).not.toHaveBeenCalled();
getUserMedia.mockResolvedValueOnce(media(nextMic));
changed.mockClear();
microphoneChanged.mockClear();
await audio.setMicrophone(true, { deviceId: "other", volume: .5, voiceProcessing: false });
expect(changed).toHaveBeenCalledExactlyOnceWith(true);
expect(microphoneChanged).toHaveBeenCalledExactlyOnceWith(true);
expect(microphone.stop).toHaveBeenCalledOnce();
expect(outputTrack.readyState).toBe("live");
await audio.setMicrophone(false, { deviceId: "", volume: 1, voiceProcessing: true });
expect(nextMic.stop).toHaveBeenCalledOnce();
expect(changed).toHaveBeenLastCalledWith(false);
expect(contexts[0]!.close).not.toHaveBeenCalled();
audio.dispose();
expect(outputTrack.readyState).toBe("ended");
expect(contexts.every(context => context.state === "closed")).toBe(true);
expect(nextVideo.stop).not.toHaveBeenCalled();
});
test("ending a share retires microphone permission completed after disposal", async () => {
const { getUserMedia, contexts } = mixerSetup();
let complete!: (stream: MediaStream) => void;
getUserMedia.mockReturnValue(new Promise<MediaStream>(resolve => { complete = resolve; }));
const microphone = new Track("audio"), enabled = vi.fn();
const audio = new HostAudio(media(new Track("video")), "browser", () => {}, enabled);
await audio.start();
const pending = audio.setMicrophone(true, { deviceId: "", volume: 1, voiceProcessing: true });
expect(getUserMedia).toHaveBeenCalledOnce();
audio.dispose();
await pending;
expect(contexts.every(context => context.state === "closed")).toBe(true);
complete(media(microphone));
await Promise.resolve();
expect(microphone.stop).toHaveBeenCalledOnce();
expect(enabled).not.toHaveBeenCalledWith(true);
expect(contexts.every(context => context.state === "closed")).toBe(true);
});
test("source-audio availability follows live input and replacement without owning video or room voice", () => {
const video = new Track("video"), sound = new Track("audio"), next = new Track("audio");
const changed = vi.fn(), audio = new HostAudio(media(video, sound), "browser", changed);
expect(audio.audioAvailable).toBe(true);
sound.stop(); sound.dispatchEvent(new Event("ended"));
expect(changed).toHaveBeenLastCalledWith(false);
const replacement = media(video, next);
expect(audio.attach(replacement, "camera")).toBe(replacement);
expect(audio.sourceStream).toBe(replacement);
expect(audio.sourceKind).toBe("camera");
expect(changed).toHaveBeenLastCalledWith(true);
next.enabled = false;
expect(audio.audioAvailable).toBe(true);
audio.dispose(); changed.mockClear();
expect(next.stop).toHaveBeenCalledOnce();
expect(video.stop).not.toHaveBeenCalled();
next.dispatchEvent(new Event("ended"));
expect(changed).not.toHaveBeenCalled();
});
test("camera is a bounded video source and never implicitly requests a microphone", async () => {
const { getUserMedia } = setup();
const video = new Track("video");
const source = media(video);
getUserMedia.mockResolvedValue(source);
expect(await captureBrowserSource(QUALITY_PROFILES["1080p30"], "camera")).toBe(source);
expect(getUserMedia).toHaveBeenCalledWith({ audio: false, video: {
resizeMode: { exact: "none" },
facingMode: { ideal: "environment" }, width: { ideal: 1920 }, height: { ideal: 1080 },
frameRate: { ideal: 30, max: 30 },
} });
});
test("camera selection requests one exact device without microphone permission", async () => {
const { getUserMedia } = setup();
getUserMedia.mockResolvedValue(media(new Track("video")));
await captureBrowserSource(QUALITY_PROFILES["1080p30"], "camera", "front-camera");
expect(getUserMedia).toHaveBeenCalledWith({ audio: false, video: expect.objectContaining({ deviceId: { exact: "front-camera" } }) });
expect(getUserMedia.mock.calls[0][0].video).toHaveProperty("resizeMode", { exact: "none" });
expect(getUserMedia.mock.calls[0][0].video).not.toHaveProperty("facingMode");
});