Open History to see the last commit
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 { DeviceStreamView } from "./DeviceStreamView";
39
40// MJPEG frames come from the device hub, so images keep their src without loading it and a
41// test publishes a frame by setting the natural size and firing "load".
42const imageSources = new WeakMap<HTMLImageElement, string>();
43const framedImages = new WeakSet<HTMLImageElement>();
44let images: HTMLImageElement[] = [];
45const srcDescriptor = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, "src")!;
46const naturalWidthDescriptor = Object.getOwnPropertyDescriptor(
47 HTMLImageElement.prototype,
48 "naturalWidth",
49)!;
50const naturalHeightDescriptor = Object.getOwnPropertyDescriptor(
51 HTMLImageElement.prototype,
52 "naturalHeight",
53)!;
54const removeAttribute = Element.prototype.removeAttribute;
55function stubImages() {
56 Object.defineProperty(HTMLImageElement.prototype, "src", {
57 configurable: true,
58 get(this: HTMLImageElement) {
59 return imageSources.get(this) ?? "";
60 },
61 set(this: HTMLImageElement, value: string) {
62 if (!images.includes(this)) images.push(this);
63 imageSources.set(this, value);
64 },
65 });
66 for (const name of ["naturalWidth", "naturalHeight"]) {
67 Object.defineProperty(HTMLImageElement.prototype, name, {
68 configurable: true,
69 get(this: HTMLImageElement) {
70 if (!framedImages.has(this)) return 0;
71 return name === "naturalWidth" ? 400 : 800;
72 },
73 });
74 }
75 Element.prototype.removeAttribute = function (this: Element, name: string) {
76 if (this instanceof HTMLImageElement && name === "src") imageSources.delete(this);
77 return removeAttribute.call(this, name);
78 };
79}
80function restoreImages() {
81 Object.defineProperty(HTMLImageElement.prototype, "src", srcDescriptor);
82 Object.defineProperty(HTMLImageElement.prototype, "naturalWidth", naturalWidthDescriptor);
83 Object.defineProperty(HTMLImageElement.prototype, "naturalHeight", naturalHeightDescriptor);
84 Element.prototype.removeAttribute = removeAttribute;
85}
86async function publishFrame(image: HTMLImageElement) {
87 framedImages.add(image);
88 await act(async () => image.dispatchEvent(new Event("load")));
89}
90let root: Root;
91let container: HTMLDivElement;
92let primes = 0;
93beforeEach(() => {
94 primes = 0;
95 viewerMounts = 0;
96 viewerUnmounts = 0;
97 images = [];
98 stubImages();
99 container = document.createElement("div");
100 container.style.cssText = "width: 400px; height: 800px; display: flex";
101 document.body.append(container);
102 root = createRoot(container);
103});
104afterEach(async () => {
105 await act(async () => root.unmount());
106 container.remove();
107 restoreImages();
108 vi.useRealTimers();
109 vi.unstubAllGlobals();
110});
111
112async function setup(h264 = false) {
113 vi.useFakeTimers();
114 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
115 let videoBody: ReadableStreamDefaultController<Uint8Array> | undefined;
116 let output: VideoFrameOutputCallback | undefined;
117 if (h264) {
118 vi.stubGlobal(
119 "VideoDecoder",
120 class {
121 static isConfigSupported = async () => ({ supported: true });
122 state = "unconfigured";
123 constructor(callbacks: VideoDecoderInit) {
124 output = callbacks.output;
125 }
126 configure() {
127 this.state = "configured";
128 }
129 close() {
130 this.state = "closed";
131 }
132 },
133 );
134 vi.stubGlobal("EncodedVideoChunk", vi.fn());
135 } else {
136 // Without WebCodecs the iOS client streams MJPEG.
137 const videoDecoder = Object.getOwnPropertyDescriptor(globalThis, "VideoDecoder");
138 if (videoDecoder) {
139 Reflect.deleteProperty(globalThis, "VideoDecoder");
140 onTestFinished(() => {
141 Object.defineProperty(globalThis, "VideoDecoder", videoDecoder);
142 });
143 }
144 }
145 vi.stubGlobal("fetch", (url: string, init: RequestInit) => {
146 if (url.endsWith("stream.avcc")) {
147 return Promise.resolve(
148 new Response(
149 new ReadableStream<Uint8Array>({
150 start(controller) {
151 videoBody = controller;
152 init.signal?.addEventListener("abort", () => controller.error(new Error("aborted")));
153 },
154 }),
155 ),
156 );
157 }
158 primes++;
159 return Promise.resolve(new Response("prime"));
160 });
161 const sockets: Array<{ onmessage?: (event: { data: ArrayBuffer }) => void }> = [];
162 vi.stubGlobal(
163 "WebSocket",
164 class {
165 static OPEN = 1;
166 readyState = 1;
167 constructor() {
168 sockets.push(this);
169 }
170 onmessage?: (event: { data: ArrayBuffer }) => void;
171 send() {}
172 close() {}
173 },
174 );
175 const view = (visible: boolean) => (
176 <DeviceStreamView
177 hostId="local"
178 environmentId={EnvironmentId.make("test")}
179 deviceId="test"
180 platform="ios"
181 visible={visible}
182 allowPhoneView={h264}
183 />
184 );
185 await act(async () => root.render(view(true)));
186 return {
187 images,
188 view,
189 configure() {
190 const json = new TextEncoder().encode(
191 JSON.stringify({ width: 400, height: 800, orientation: "portrait" }),
192 );
193 const packet = new Uint8Array(1 + json.length);
194 packet[0] = 0x82;
195 packet.set(json, 1);
196 sockets[0]?.onmessage?.({ data: Uint8Array.of(0x83).buffer });
197 sockets[0]?.onmessage?.({ data: packet.buffer });
198 videoBody?.enqueue(new Uint8Array([0, 0, 0, 5, 1, 1, 0x64, 0, 0x1f]));
199 },
200 frame() {
201 const source = new OffscreenCanvas(400, 800);
202 source.getContext("2d")!.fillRect(0, 0, 400, 800);
203 output?.(new VideoFrame(source, { timestamp: 0 }));
204 },
205 };
206}
207
208const alert = () => container.querySelector('[role="alert"]');
209const reconnect = () =>
210 act(async () =>
211 [...container.querySelectorAll("button")]
212 .find((button) => button.textContent?.includes("Reconnect"))!
213 .click(),
214 );
215
216it("removes MJPEG requests while hidden and reconnects when shown", async () => {
217 const { images, view } = await setup();
218 expect(images[0]!.src).toContain("stream.mjpeg");
219 await act(async () => root.render(view(false)));
220 expect(container.querySelectorAll("img")).toHaveLength(0);
221 expect(images[0]!.src).toBe("");
222 expect(vi.getTimerCount()).toBe(0);
223 await act(async () => root.render(view(true)));
224 expect(images.at(-1)!.src).toContain("stream.mjpeg");
225});
226
227it("offers Reconnect after the shared timeout and receives a frame after retry with unchanged access", async () => {
228 const { images } = await setup();
229 await act(async () => {
230 await vi.advanceTimersByTimeAsync(15_000);
231 });
232 expect(alert()?.textContent).toContain("No video");
233 expect(images[0]!.src).toBe("");
234 await reconnect();
235 expect(alert()).toBeNull();
236 expect(images[1]!.src).toContain("stream.mjpeg");
237 await publishFrame(images[1]!);
238 expect(container.querySelector('[role="status"]')).toBeNull();
239 expect(container.querySelectorAll("button")).toHaveLength(0);
240 expect(vi.getTimerCount()).toBe(0);
241});
242
243it("starts exactly one new stream per Reconnect press", async () => {
244 await setup();
245 await act(async () => {
246 await vi.advanceTimersByTimeAsync(15_000);
247 });
248 expect(primes).toBe(1);
249 await reconnect();
250 expect(primes).toBe(2);
251});
252
253it("keeps the 3D viewer mounted across iOS video recovery and releases it when hidden", async () => {
254 const { configure, frame, view } = await setup(true);
255 await act(async () => configure());
256 expect(viewerMounts).toBe(0);
257 await act(async () => frame());
258 expect(viewerMounts).toBe(1);
259 await act(async () => {
260 await vi.advanceTimersByTimeAsync(15_000);
261 });
262 expect(viewerUnmounts).toBe(0);
263 expect(viewerMounts).toBe(1);
264 await act(async () => {
265 await vi.advanceTimersByTimeAsync(1_000);
266 configure();
267 });
268 await act(async () => frame());
269 expect(viewerMounts).toBe(1);
270 await act(async () => root.render(view(false)));
271 expect(viewerUnmounts).toBe(1);
272 expect(vi.getTimerCount()).toBe(0);
273});