Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DeviceStreamView.browser.test.tsx

359 lines12.1 KB

1import { act, useEffect, useSyncExternalStore } from "react";
2import { createRoot, type Root } from "react-dom/client";
3import { EnvironmentId } from "@t3tools/contracts";
4import { afterEach, beforeEach, expect, it, onTestFinished, vi } from "vite-plus/test";
5​
6const accessStore = {
7 value: { httpBase: "http://test", wsBase: "ws://test", query: {}, credentials: true },
8 listeners: new Set<() => void>(),
9 refresh() {
10 accessStore.value = { ...accessStore.value };
11 for (const listener of accessStore.listeners) listener();
12 },
13 subscribe(listener: () => void) {
14 accessStore.listeners.add(listener);
15 return () => accessStore.listeners.delete(listener);
16 },
17};
18vi.mock(import("~/state/device"), async (original) => ({
19 ...(await original()),
20 useDeviceHubAccess: () => useSyncExternalStore(accessStore.subscribe, () => accessStore.value),
21 refreshDeviceHubAccess: () => accessStore.refresh(),
22}));
23let viewerMounts = 0;
24let viewerUnmounts = 0;
25// The 3D phone frame needs WebGL; the test only cares whether it stays mounted.
26vi.mock(import("./DevicePhoneViewport"), async (original) => ({
27 ...(await original()),
28 DevicePhoneViewport: function Viewer(): React.ReactElement {
29 useEffect(() => {
30 viewerMounts++;
31 return () => {
32 viewerUnmounts++;
33 };
34 }, []);
35 return <></>;
36 },
37}));
38import { pasteTextToFocusComposer } from "../chat/composerFocusRedirect";
39import { DeviceStreamView } from "./DeviceStreamView";
40​
41// MJPEG frames come from the device hub, so images keep their src without loading it and a
42// test publishes a frame by setting the natural size and firing "load".
43const imageSources = new WeakMap<HTMLImageElement, string>();
44const framedImages = new WeakSet<HTMLImageElement>();
45let images: HTMLImageElement[] = [];
46const srcDescriptor = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, "src")!;
47const naturalWidthDescriptor = Object.getOwnPropertyDescriptor(
48 HTMLImageElement.prototype,
49 "naturalWidth",
50)!;
51const naturalHeightDescriptor = Object.getOwnPropertyDescriptor(
52 HTMLImageElement.prototype,
53 "naturalHeight",
54)!;
55const removeAttribute = Element.prototype.removeAttribute;
56function stubImages() {
57 Object.defineProperty(HTMLImageElement.prototype, "src", {
58 configurable: true,
59 get(this: HTMLImageElement) {
60 return imageSources.get(this) ?? "";
61 },
62 set(this: HTMLImageElement, value: string) {
63 if (!images.includes(this)) images.push(this);
64 imageSources.set(this, value);
65 },
66 });
67 for (const name of ["naturalWidth", "naturalHeight"]) {
68 Object.defineProperty(HTMLImageElement.prototype, name, {
69 configurable: true,
70 get(this: HTMLImageElement) {
71 if (!framedImages.has(this)) return 0;
72 return name === "naturalWidth" ? 400 : 800;
73 },
74 });
75 }
76 Element.prototype.removeAttribute = function (this: Element, name: string) {
77 if (this instanceof HTMLImageElement && name === "src") imageSources.delete(this);
78 return removeAttribute.call(this, name);
79 };
81function restoreImages() {
82 Object.defineProperty(HTMLImageElement.prototype, "src", srcDescriptor);
83 Object.defineProperty(HTMLImageElement.prototype, "naturalWidth", naturalWidthDescriptor);
84 Object.defineProperty(HTMLImageElement.prototype, "naturalHeight", naturalHeightDescriptor);
85 Element.prototype.removeAttribute = removeAttribute;
87async function publishFrame(image: HTMLImageElement) {
88 framedImages.add(image);
89 await act(async () => image.dispatchEvent(new Event("load")));
91let root: Root;
92let container: HTMLDivElement;
93let primes = 0;
94beforeEach(() => {
95 primes = 0;
96 viewerMounts = 0;
97 viewerUnmounts = 0;
98 images = [];
99 stubImages();
100 container = document.createElement("div");
101 container.style.cssText = "width: 400px; height: 800px; display: flex";
102 document.body.append(container);
103 root = createRoot(container);
104});
105afterEach(async () => {
106 await act(async () => root.unmount());
107 container.remove();
108 restoreImages();
109 vi.useRealTimers();
110 vi.unstubAllGlobals();
111});
112​
113async function setup(h264 = false, platform: "ios" | "android" = "ios") {
114 const touches: unknown[] = [];
115 vi.useFakeTimers();
116 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
117 let videoBody: ReadableStreamDefaultController<Uint8Array> | undefined;
118 let output: VideoFrameOutputCallback | undefined;
119 if (h264) {
120 vi.stubGlobal(
121 "VideoDecoder",
122 class {
123 static isConfigSupported = async () => ({ supported: true });
124 state = "unconfigured";
125 constructor(callbacks: VideoDecoderInit) {
126 output = callbacks.output;
127 }
128 configure() {
129 this.state = "configured";
130 }
131 close() {
132 this.state = "closed";
133 }
134 },
135 );
136 vi.stubGlobal("EncodedVideoChunk", vi.fn());
137 } else {
138 // Without WebCodecs the iOS client streams MJPEG.
139 const videoDecoder = Object.getOwnPropertyDescriptor(globalThis, "VideoDecoder");
140 if (videoDecoder) {
141 Reflect.deleteProperty(globalThis, "VideoDecoder");
142 onTestFinished(() => {
143 Object.defineProperty(globalThis, "VideoDecoder", videoDecoder);
144 });
145 }
146 }
147 vi.stubGlobal("fetch", (url: string, init: RequestInit) => {
148 if (url.endsWith("stream.avcc")) {
149 return Promise.resolve(
150 new Response(
151 new ReadableStream<Uint8Array>({
152 start(controller) {
153 videoBody = controller;
154 init.signal?.addEventListener("abort", () => controller.error(new Error("aborted")));
155 },
156 }),
157 ),
158 );
159 }
160 primes++;
161 return Promise.resolve(new Response("prime"));
162 });
163 const sockets: Array<{ onmessage?: (event: { data: ArrayBuffer }) => void }> = [];
164 const sent: unknown[] = [];
165 vi.stubGlobal(
166 "WebSocket",
167 class {
168 static OPEN = 1;
169 readyState = 1;
170 constructor() {
171 sockets.push(this);
172 }
173 onmessage?: (event: { data: ArrayBuffer }) => void;
174 send(message: string | Uint8Array) {
175 if (typeof message === "string") {
176 sent.push(message);
177 } else if (message[0] === 0x03) {
178 touches.push(JSON.parse(new TextDecoder().decode(message.subarray(1))));
179 }
180 }
181 close() {}
182 },
183 );
184 const view = (visible: boolean) => (
185 <DeviceStreamView
186 hostId="local"
187 environmentId={EnvironmentId.make("test")}
188 deviceId="test"
189 platform={platform}
190 visible={visible}
191 allowPhoneView={h264}
192 />
193 );
194 await act(async () => root.render(view(true)));
195 return {
196 images,
197 sent,
198 view,
199 touches,
200 configure() {
201 const json = new TextEncoder().encode(
202 JSON.stringify({ width: 400, height: 800, orientation: "portrait" }),
203 );
204 const packet = new Uint8Array(1 + json.length);
205 packet[0] = 0x82;
206 packet.set(json, 1);
207 sockets[0]?.onmessage?.({ data: Uint8Array.of(0x83).buffer });
208 sockets[0]?.onmessage?.({ data: packet.buffer });
209 videoBody?.enqueue(new Uint8Array([0, 0, 0, 5, 1, 1, 0x64, 0, 0x1f]));
210 },
211 frame() {
212 const source = new OffscreenCanvas(400, 800);
213 source.getContext("2d")!.fillRect(0, 0, 400, 800);
214 output?.(new VideoFrame(source, { timestamp: 0 }));
215 },
216 };
218​
219const alert = () => container.querySelector('[role="alert"]');
220const reconnect = () =>
221 act(async () =>
222 [...container.querySelectorAll("button")]
223 .find((button) => button.textContent?.includes("Reconnect"))!
224 .click(),
225 );
226​
227it.each([
228 { name: "middle", button: 1, buttons: 4 },
229 { name: "right", button: 2, buttons: 2 },
230])("ignores $name-button drags and forwards the next primary drag", async ({ button, buttons }) => {
231 const { touches, configure } = await setup();
232 await act(async () => configure());
233 const viewport = container.querySelector("canvas")!.parentElement!;
234 viewport.style.width = "400px";
235 viewport.style.height = "800px";
236 // Synthetic pointer events do not register an active browser pointer to capture.
237 viewport.setPointerCapture = () => {};
238 const rect = viewport.getBoundingClientRect();
239 const pointer = (type: string, button: number, buttons: number, y: number) =>
240 viewport.dispatchEvent(
241 new PointerEvent(type, {
242 bubbles: true,
243 pointerId: 1,
244 pointerType: "mouse",
245 button,
246 buttons,
247 clientX: rect.left + 100,
248 clientY: rect.top + y,
249 }),
250 );
251​
252 await act(async () => {
253 pointer("pointerdown", button, buttons, 600);
254 pointer("pointermove", -1, buttons, 200);
255 pointer("pointerup", button, 0, 200);
256 });
257 expect(touches).toEqual([]);
258​
259 await act(async () => {
260 pointer("pointerdown", 0, 1, 600);
261 pointer("pointermove", -1, 1, 200);
262 pointer("pointerup", 0, 0, 200);
263 pointer("pointermove", -1, 0, 400);
264 });
265 expect(touches).toEqual([
266 { type: "begin", x: 0.25, y: 0.75 },
267 { type: "move", x: 0.25, y: 0.25 },
268 { type: "end", x: 0.25, y: 0.25 },
269 ]);
270});
271​
272it("removes MJPEG requests while hidden and reconnects when shown", async () => {
273 const { images, view } = await setup();
274 expect(images[0]!.src).toContain("stream.mjpeg");
275 await act(async () => root.render(view(false)));
276 expect(container.querySelectorAll("img")).toHaveLength(0);
277 expect(images[0]!.src).toBe("");
278 expect(vi.getTimerCount()).toBe(0);
279 await act(async () => root.render(view(true)));
280 expect(images.at(-1)!.src).toContain("stream.mjpeg");
281});
282​
283it("offers Reconnect after the shared timeout and receives a frame after retry with unchanged access", async () => {
284 const { images } = await setup();
285 await act(async () => {
286 await vi.advanceTimersByTimeAsync(15_000);
287 });
288 expect(alert()?.textContent).toContain("No video");
289 expect(images[0]!.src).toBe("");
290 await reconnect();
291 expect(alert()).toBeNull();
292 expect(images[1]!.src).toContain("stream.mjpeg");
293 await publishFrame(images[1]!);
294 expect(container.querySelector('[role="status"]')).toBeNull();
295 expect(container.querySelectorAll("button")).toHaveLength(0);
296 expect(vi.getTimerCount()).toBe(0);
297});
298​
299it("starts exactly one new stream per Reconnect press", async () => {
300 await setup();
301 await act(async () => {
302 await vi.advanceTimersByTimeAsync(15_000);
303 });
304 expect(primes).toBe(1);
305 await reconnect();
306 expect(primes).toBe(2);
307});
308​
309it("keeps the 3D viewer mounted across iOS video recovery and releases it when hidden", async () => {
310 const { configure, frame, view } = await setup(true);
311 await act(async () => configure());
312 expect(viewerMounts).toBe(0);
313 await act(async () => frame());
314 expect(viewerMounts).toBe(1);
315 await act(async () => {
316 await vi.advanceTimersByTimeAsync(15_000);
317 });
318 expect(viewerUnmounts).toBe(0);
319 expect(viewerMounts).toBe(1);
320 await act(async () => {
321 await vi.advanceTimersByTimeAsync(1_000);
322 configure();
323 });
324 await act(async () => frame());
325 expect(viewerMounts).toBe(1);
326 await act(async () => root.render(view(false)));
327 expect(viewerUnmounts).toBe(1);
328 expect(vi.getTimerCount()).toBe(0);
329});
330​
331it("types a paste on the Android screen into the device and lets Ctrl+V reach the paste", async () => {
332 const { sent } = await setup(true, "android");
333 const screen = container.querySelector<HTMLElement>('[role="application"]')!;
334 screen.focus();
335 expect(document.activeElement).toBe(screen);
336 const chord = new KeyboardEvent("keydown", {
337 key: "v",
338 code: "KeyV",
339 ctrlKey: true,
340 bubbles: true,
341 cancelable: true,
342 });
343 screen.dispatchEvent(chord);
344 expect(chord.defaultPrevented).toBe(false);
345 const clipboardData = new DataTransfer();
346 clipboardData.setData("text/plain", "pässwörd 1");
347 const composerPastes: Array<string | null> = [];
348 const capturePaste = (event: ClipboardEvent) =>
349 composerPastes.push(pasteTextToFocusComposer(event));
350 window.addEventListener("paste", capturePaste, true);
351 onTestFinished(() => window.removeEventListener("paste", capturePaste, true));
352 const paste = new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true });
353 screen.dispatchEvent(paste);
354 expect(paste.defaultPrevented).toBe(true);
355 expect(sent.map((message) => JSON.parse(message as string) as unknown)).toEqual([
356 { type: "text", text: "pässwörd 1" },
357 ]);
358 expect(composerPastes).toEqual([null]);
359});