Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Phone screen: the web client that decodes a phone's video stream and sends input
Xiaolei Shi0cfb2c3081bc
diff --git a/src/lib/phone-stream-client.test.ts b/src/lib/phone-stream-client.test.tsnew file mode 100644index 0000000000..99c58a184c--- /dev/null+++ b/src/lib/phone-stream-client.test.ts@@ -0,0 +1,304 @@+// @vitest-environment happy-dom+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { FakePhoneSocket, FakeVideoDecoder, PHONE_CONFIG, PHONE_DELTA_FRAME, PHONE_KEY_FRAME, fakePhoneStream, showPage } from "@/testing/phone-stream";+import { createPhoneStreamClient, phoneStreamUrl, type PhoneStreamClient, type PhoneStreamView } from "./phone-stream-client";++const clients: PhoneStreamClient[] = [];+const views: PhoneStreamView[] = [];+const view = () => views[views.length - 1];+const start = () => {+ views.length = 0;+ const canvas = document.createElement("canvas");+ const client = createPhoneStreamClient({ serial: "p1", canvas }, (next) => views.push(next));+ clients.push(client);+ return { client, canvas, socket: FakePhoneSocket.current };+};+/** A connected viewer whose first frame, 720 by 1280, is on the canvas. */+const watch = () => {+ const started = start();+ started.socket.packet(1, PHONE_CONFIG);+ started.socket.packet(2, PHONE_KEY_FRAME);+ FakeVideoDecoder.current.frame(720, 1280);+ return started;+};++beforeEach(fakePhoneStream);+afterEach(() => {+ for (const client of clients.splice(0)) client.stop();+ Reflect.deleteProperty(document, "visibilityState");+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++describe("the phone stream's address", () => {+ it("is the phone's stream route on the page's own origin", () => {+ expect(phoneStreamUrl("p1", { protocol: "http:", host: "omb.test" })).toBe("ws://omb.test/api/usb-phones/p1/stream");+ expect(phoneStreamUrl("a b", { protocol: "https:", host: "cloud.test" })).toBe("wss://cloud.test/api/usb-phones/a%20b/stream");+ });+});++describe("phone stream video", () => {+ it("configures the decoder once from the phone's parameter sets, then feeds the key frame with them in front and the next frame alone", () => {+ const { socket } = start();+ expect(view().status).toEqual({ kind: "connecting" });+ socket.packet(1, PHONE_CONFIG);+ socket.packet(2, PHONE_KEY_FRAME);+ socket.packet(3, PHONE_DELTA_FRAME);++ expect(socket.binaryType).toBe("arraybuffer");+ expect(FakeVideoDecoder.all).toHaveLength(1);+ const decoder = FakeVideoDecoder.current;+ expect(decoder.configured).toEqual([{ codec: "avc1.42c020", optimizeForLatency: true }]);+ expect(decoder.chunks.map((chunk) => chunk.type)).toEqual(["key", "delta"]);+ expect([...decoder.chunks[0].data]).toEqual([...PHONE_CONFIG, ...PHONE_KEY_FRAME]);+ expect([...decoder.chunks[1].data]).toEqual([...PHONE_DELTA_FRAME]);+ });++ it("sizes the canvas to each decoded frame, closes it, and follows a rotation", () => {+ const { socket, canvas } = start();+ socket.packet(1, PHONE_CONFIG);+ const upright = FakeVideoDecoder.current.frame(720, 1280);+ expect(upright.close).toHaveBeenCalledOnce();+ expect([canvas.width, canvas.height]).toEqual([720, 1280]);+ expect(view()).toMatchObject({ status: { kind: "live" }, frame: { width: 720, height: 1280 } });++ const turned = FakeVideoDecoder.current.frame(1280, 720);+ expect(turned.close).toHaveBeenCalledOnce();+ expect([canvas.width, canvas.height]).toEqual([1280, 720]);+ expect(view().frame).toEqual({ width: 1280, height: 720 });+ });++ it("closes the stream and connects again when the decoder fails", () => {+ vi.useFakeTimers();+ const { socket } = watch();+ FakeVideoDecoder.current.fail();+ expect(socket.readyState).toBe(3);+ expect(view().status).toEqual({ kind: "connecting" });+ vi.advanceTimersByTime(500);+ expect(FakePhoneSocket.all).toHaveLength(2);+ });++ it("closes the stream and connects again when the decoder refuses a frame", () => {+ vi.useFakeTimers();+ const { socket } = watch();+ vi.spyOn(FakeVideoDecoder.current, "decode").mockImplementation(() => {+ throw new DOMException("the decoder is closed", "InvalidStateError");+ });+ socket.packet(3, PHONE_DELTA_FRAME);+ expect(socket.readyState).toBe(3);+ expect(view().status).toEqual({ kind: "connecting" });+ vi.advanceTimersByTime(500);+ expect(FakePhoneSocket.all).toHaveLength(2);+ });+});++describe("phone stream control and input", () => {+ it("follows the server's word on who holds the phone", () => {+ const { socket } = start();+ expect(view().held).toBe(false);+ socket.control(true);+ expect(view().held).toBe(true);+ socket.control(false);+ expect(view().held).toBe(false);+ });++ it("sends take, hand back, touches with the frame's size, keys and text as the server reads them", () => {+ const { client, socket } = watch();+ client.take();+ client.touch("down", 10, 20);+ client.touch("move", 30, 40);+ client.touch("up", 30, 40);+ client.key("back");+ client.key("wakeup");+ client.text("你好");+ client.handBack();+ expect(socket.sent).toEqual([+ { type: "take" },+ { type: "touch", action: "down", x: 10, y: 20, w: 720, h: 1280 },+ { type: "touch", action: "move", x: 30, y: 40, w: 720, h: 1280 },+ { type: "touch", action: "up", x: 30, y: 40, w: 720, h: 1280 },+ { type: "key", key: "back" },+ { type: "key", key: "wakeup" },+ { type: "text", text: "你好" },+ { type: "handBack" },+ ]);++ FakeVideoDecoder.current.frame(1280, 720);+ client.touch("down", 5, 6);+ expect(socket.sent[socket.sent.length - 1]).toEqual({ type: "touch", action: "down", x: 5, y: 6, w: 1280, h: 720 });+ });++ it("splits text over 300 characters into messages of at most 300, keeping an emoji whole", () => {+ const { client, socket } = watch();+ client.text("a".repeat(650));+ expect(socket.sent).toEqual([+ { type: "text", text: "a".repeat(300) },+ { type: "text", text: "a".repeat(300) },+ { type: "text", text: "a".repeat(50) },+ ]);+ socket.sent.length = 0;+ client.text(`${"a".repeat(299)}😀b`);+ expect(socket.sent).toEqual([{ type: "text", text: "a".repeat(299) }, { type: "text", text: "😀b" }]);+ });++ it("drops input while the socket is not open", () => {+ const { client, socket } = watch();+ socket.readyState = 0;+ client.take();+ client.key("home");+ expect(socket.sent).toEqual([]);+ });+});++describe("phone stream reconnecting", () => {+ it.each([+ [1012, "reconnect", 500],+ [1006, "", 500],+ [1013, "Too many phone views are open.", 10_000],+ ])("connects again after close %i", (code, reason, afterMs) => {+ vi.useFakeTimers();+ const { socket } = watch();+ socket.closeWith(code, reason);+ expect(FakeVideoDecoder.current.state).toBe("closed");+ vi.advanceTimersByTime(afterMs - 1);+ expect(FakePhoneSocket.all).toHaveLength(1);+ vi.advanceTimersByTime(1);+ expect(FakePhoneSocket.all).toHaveLength(2);+ expect(FakePhoneSocket.current.url).toBe(socket.url);+ });++ it("is live again after connecting again, with a frame of the size it had", () => {+ vi.useFakeTimers();+ const { socket } = watch();+ socket.closeWith(1012, "reconnect");+ expect(view().status).toEqual({ kind: "connecting" });+ vi.advanceTimersByTime(500);+ FakePhoneSocket.current.packet(1, PHONE_CONFIG);+ FakeVideoDecoder.current.frame(720, 1280);+ expect(view()).toMatchObject({ status: { kind: "live" }, frame: { width: 720, height: 1280 } });+ });++ it("shows why the server is busy while it waits to try again", () => {+ vi.useFakeTimers();+ const { socket } = watch();+ socket.closeWith(1013, "Too many phone views are open.");+ expect(view().status).toEqual({ kind: "closed", code: 1013, reason: "Too many phone views are open." });+ });++ it("waits longer after each failed attempt, up to ten seconds", () => {+ vi.useFakeTimers();+ start();+ for (const waitMs of [500, 1_000, 2_000, 4_000, 8_000, 10_000, 10_000]) {+ const before = FakePhoneSocket.all.length;+ FakePhoneSocket.current.closeWith(1006);+ vi.advanceTimersByTime(waitMs - 1);+ expect(FakePhoneSocket.all).toHaveLength(before);+ vi.advanceTimersByTime(1);+ expect(FakePhoneSocket.all).toHaveLength(before + 1);+ }+ });++ it.each([+ [1011, "The phone's screen could not start."],+ [4404, "gone"],+ ])("stops for good on close %i and keeps the reason", (code, reason) => {+ vi.useFakeTimers();+ const { socket } = watch();+ socket.closeWith(code, reason);+ expect(view().status).toEqual({ kind: "closed", code, reason });+ vi.advanceTimersByTime(60_000);+ showPage(false);+ showPage(true);+ expect(FakePhoneSocket.all).toHaveLength(1);+ expect(view().status).toEqual({ kind: "closed", code, reason });+ });++ it("closes the stream while the page is hidden, held or not, and opens it again when the page shows", () => {+ const { socket } = watch();+ socket.control(true);+ showPage(false);+ expect(socket.readyState).toBe(3);+ expect(FakeVideoDecoder.current.state).toBe("closed");+ expect(view().status).toEqual({ kind: "connecting" });+ expect(FakePhoneSocket.all).toHaveLength(1);++ showPage(true);+ expect(FakePhoneSocket.all).toHaveLength(2);+ expect(FakePhoneSocket.current.readyState).toBe(1);+ });++ it.each([+ ["it starts", () => {+ showPage(false);+ start();+ }, 0],+ ["a retry comes due", () => {+ start();+ FakePhoneSocket.current.closeWith(1012);+ Object.defineProperty(document, "visibilityState", { configurable: true, value: "hidden" });+ }, 1],+ ])("opens nothing on a hidden page when %s, and connects once the page shows", (_name, hidden, opened) => {+ vi.useFakeTimers();+ hidden();+ vi.advanceTimersByTime(60_000);+ expect(FakePhoneSocket.all).toHaveLength(opened);++ showPage(true);+ expect(FakePhoneSocket.all).toHaveLength(opened + 1);+ });++ it("opens nothing after it is stopped", () => {+ vi.useFakeTimers();+ const { client, socket } = watch();+ socket.closeWith(1012);+ client.stop();+ vi.advanceTimersByTime(60_000);+ showPage(false);+ showPage(true);+ expect(FakePhoneSocket.all).toHaveLength(1);+ });+});++describe("a browser that cannot show the phone", () => {+ it.each([+ ["has no VideoDecoder", () => vi.stubGlobal("VideoDecoder", undefined)],+ ["is not a secure context", () => vi.stubGlobal("isSecureContext", false)],+ ])("%s: unsupported, and nothing is opened", (_name, lack) => {+ lack();+ const { client } = start();+ expect(view().status).toEqual({ kind: "unsupported" });+ client.take();+ showPage(false);+ showPage(true);+ expect(FakePhoneSocket.all).toHaveLength(0);+ expect(FakeVideoDecoder.all).toHaveLength(0);+ });++ it.each([+ ["after the decoder's own error", true],+ ["before the decoder's own error", false],+ ])("cannot decode the phone's codec, found %s: unsupported, the stream and the decoder closed, and no connecting again", async (_name, errorFirst) => {+ vi.useFakeTimers();+ FakeVideoDecoder.lacks = ["avc1.42c020"];+ const { socket } = start();+ socket.packet(1, PHONE_CONFIG);+ const decoder = FakeVideoDecoder.current;+ if (errorFirst) {+ decoder.fail();+ expect(view().status).toEqual({ kind: "connecting" });+ }++ await Promise.resolve();+ await Promise.resolve();+ expect(view().status).toEqual({ kind: "unsupported" });+ expect(socket.readyState).toBe(3);+ expect(decoder.state).toBe("closed");+ if (!errorFirst) decoder.fail();+ vi.advanceTimersByTime(60_000);+ showPage(false);+ showPage(true);+ expect(FakePhoneSocket.all).toHaveLength(1);+ expect(view().status).toEqual({ kind: "unsupported" });+ });+});diff --git a/src/lib/phone-stream-client.ts b/src/lib/phone-stream-client.tsnew file mode 100644index 0000000000..0e36423482--- /dev/null+++ b/src/lib/phone-stream-client.ts@@ -0,0 +1,231 @@+export const PHONE_STREAM_CLOSE = { failed: 1011, busy: 1013, gone: 4404 } as const;++export type PhoneKey = "back" | "home" | "recent" | "enter" | "delete" | "tab" | "up" | "down" | "left" | "right" | "wakeup";+export type PhoneTouchAction = "down" | "move" | "up";++export interface PhoneFrameSize {+ readonly width: number;+ readonly height: number;+}++export type PhoneStreamStatus =+ | { readonly kind: "connecting" | "live" | "unsupported" }+ | { readonly kind: "closed"; readonly code: number; readonly reason: string };++export interface PhoneStreamView {+ readonly status: PhoneStreamStatus;+ /** Video pixels of the frame on the canvas; a rotation changes it. */+ readonly frame: PhoneFrameSize | null;+ /** A person holds the phone, from this view or another. */+ readonly held: boolean;+}++export interface PhoneStreamTarget {+ readonly serial: string;+ readonly canvas: HTMLCanvasElement;+}++/** Input reaches the phone only while it is held; the server drops the rest. */+export interface PhoneStreamClient {+ readonly take: () => void;+ readonly handBack: () => void;+ /** `x` and `y` are video pixels of the frame on the canvas. */+ readonly touch: (action: PhoneTouchAction, x: number, y: number) => void;+ readonly key: (key: PhoneKey) => void;+ readonly text: (text: string) => void;+ readonly stop: () => void;+}++export const phoneStreamUrl = (serial: string, location: Pick<Location, "protocol" | "host"> = window.location): string =>+ `${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}/api/usb-phones/${encodeURIComponent(serial)}/stream`;++const PACKET = { config: 1, key: 2, delta: 3 } as const;+const TEXT_LIMIT = 300;+const MAX_RETRY_MS = 10_000;+const CONNECTING: PhoneStreamStatus = { kind: "connecting" };++const hex = (bytes: Uint8Array) => [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");++const joined = (head: Uint8Array, tail: Uint8Array) => {+ const all = new Uint8Array(head.length + tail.length);+ all.set(head);+ all.set(tail, head.length);+ return all;+};++/** The server takes at most 300 characters in one text message; a surrogate pair stays whole. */+function textPieces(text: string): string[] {+ const pieces: string[] = [];+ let piece = "";+ for (const character of text) {+ if (piece.length + character.length > TEXT_LIMIT) {+ pieces.push(piece);+ piece = "";+ }+ piece += character;+ }+ if (piece) pieces.push(piece);+ return pieces;+}++export function createPhoneStreamClient(target: PhoneStreamTarget, onChange: (view: PhoneStreamView) => void): PhoneStreamClient {+ // WebCodecs is exposed only in secure contexts: HTTPS or localhost.+ const supported = window.isSecureContext && typeof VideoDecoder === "function";+ const context = target.canvas.getContext("2d");+ let view: PhoneStreamView = { status: supported ? CONNECTING : { kind: "unsupported" }, frame: null, held: false };+ let socket: WebSocket | null = null;+ let decoder: VideoDecoder | null = null;+ let config: Uint8Array | null = null;+ let retryTimer: ReturnType<typeof setTimeout> | null = null;+ let failures = 0;+ let ended = !supported;++ const change = (next: Partial<PhoneStreamView>) => {+ view = { ...view, ...next };+ onChange(view);+ };++ const paint = (frame: VideoFrame) => {+ const { displayWidth: width, displayHeight: height } = frame;+ const resized = view.frame?.width !== width || view.frame.height !== height;+ if (resized) {+ target.canvas.width = width;+ target.canvas.height = height;+ }+ context?.drawImage(frame, 0, 0);+ frame.close();+ failures = 0;+ if (resized || view.status.kind !== "live") change({ status: { kind: "live" }, frame: { width, height } });+ };++ const drop = () => {+ if (retryTimer !== null) clearTimeout(retryTimer);+ retryTimer = null;+ const ws = socket;+ socket = null;+ ws?.close();+ if (decoder && decoder.state !== "closed") decoder.close();+ decoder = null;+ config = null;+ };++ const reconnect = () => {+ drop();+ change({ status: CONNECTING });+ retryTimer = setTimeout(open, Math.min(500 * 2 ** failures++, MAX_RETRY_MS));+ };++ const cannotDecode = () => {+ if (ended) return;+ ended = true;+ drop();+ change({ status: { kind: "unsupported" } });+ };++ const decode = (packet: Uint8Array) => {+ const kind = packet[0];+ const payload = packet.subarray(1);+ if (kind === PACKET.config) {+ config = payload;+ if (!decoder) {+ const created: VideoDecoder = new VideoDecoder({ output: paint, error: () => { if (decoder === created) reconnect(); } });+ decoder = created;+ }+ // The stream is H.264 Annex B: a config without `description` tells WebCodecs so. The three bytes after the+ // parameter set's NAL header are its profile, constraints and level.+ const settings: VideoDecoderConfig = { codec: `avc1.${hex(payload.subarray(5, 8))}`, optimizeForLatency: true };+ decoder.configure(settings);+ // A decoder configured with a codec the browser lacks only reports an error, as it does for one bad frame.+ void VideoDecoder.isConfigSupported(settings).then(({ supported }) => { if (!supported) cannotDecode(); }, () => {});+ } else if (decoder && config && (kind === PACKET.key || kind === PACKET.delta)) {+ const key = kind === PACKET.key;+ // An Annex B key chunk must carry its parameter sets; the phone's encoder sends them once, apart.+ decoder.decode(new EncodedVideoChunk({ type: key ? "key" : "delta", timestamp: performance.now() * 1000, data: key ? joined(config, payload) : payload }));+ }+ };++ const control = (data: string) => {+ let message: unknown;+ try {+ message = JSON.parse(data);+ } catch {+ return;+ }+ if (typeof message !== "object" || message === null) return;+ const { type, held } = message as Record<string, unknown>;+ if (type === "control" && typeof held === "boolean" && held !== view.held) change({ held });+ };++ function open() {+ retryTimer = null;+ if (ended || socket || document.visibilityState !== "visible") return;+ const ws = new WebSocket(phoneStreamUrl(target.serial));+ ws.binaryType = "arraybuffer";+ socket = ws;+ ws.addEventListener("message", (event) => {+ if (socket !== ws) return;+ if (typeof event.data === "string") {+ control(event.data);+ } else if (event.data instanceof ArrayBuffer) {+ try {+ decode(new Uint8Array(event.data));+ } catch {+ reconnect();+ }+ }+ });+ ws.addEventListener("close", (event) => {+ if (socket !== ws) return;+ const closed: PhoneStreamStatus = { kind: "closed", code: event.code, reason: event.reason };+ if (event.code === PHONE_STREAM_CLOSE.failed || event.code === PHONE_STREAM_CLOSE.gone) {+ ended = true;+ drop();+ change({ status: closed });+ } else if (event.code === PHONE_STREAM_CLOSE.busy) {+ drop();+ change({ status: closed });+ retryTimer = setTimeout(open, MAX_RETRY_MS);+ } else {+ reconnect();+ }+ });+ ws.addEventListener("error", () => ws.close());+ }++ const onVisibility = () => {+ if (ended) return;+ if (document.visibilityState === "visible") {+ open();+ } else {+ drop();+ failures = 0;+ change({ status: CONNECTING });+ }+ };++ const send = (message: Readonly<Record<string, unknown>>) => {+ if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify(message));+ };++ onChange(view);+ if (supported) {+ document.addEventListener("visibilitychange", onVisibility);+ open();+ }++ return {+ take: () => send({ type: "take" }),+ handBack: () => send({ type: "handBack" }),+ touch: (action, x, y) => {+ if (view.frame) send({ type: "touch", action, x, y, w: view.frame.width, h: view.frame.height });+ },+ key: (key) => send({ type: "key", key }),+ text: (text) => {+ for (const piece of textPieces(text)) send({ type: "text", text: piece });+ },+ stop: () => {+ document.removeEventListener("visibilitychange", onVisibility);+ drop();+ },+ };+}diff --git a/src/testing/phone-stream.ts b/src/testing/phone-stream.tsnew file mode 100644index 0000000000..dcf4ff1672--- /dev/null+++ b/src/testing/phone-stream.ts@@ -0,0 +1,110 @@+import { vi } from "vitest";++const bytes = (hex: string) => Uint8Array.from(hex.match(/../g) ?? [], (pair) => Number.parseInt(pair, 16));++/** The parameter sets scrcpy-server 5.0.1 sent from a Huawei MHA-AL00 (Android 9): H.264 Constrained Baseline, level 3.2. */+export const PHONE_CONFIG = bytes("000000016742c020da02d028440000000168ca8f20");+/** The first bytes of that recording's key frame and of one frame after it. */+export const PHONE_KEY_FRAME = bytes("0000000165b845");+export const PHONE_DELTA_FRAME = bytes("0000000161");++export class FakePhoneSocket extends EventTarget {+ static readonly OPEN = 1;+ static all: FakePhoneSocket[] = [];+ static get current(): FakePhoneSocket {+ return FakePhoneSocket.all[FakePhoneSocket.all.length - 1];+ }+ readyState = 1;+ binaryType = "";+ readonly sent: unknown[] = [];+ readonly url: string;+ constructor(url: string) {+ super();+ this.url = url;+ FakePhoneSocket.all.push(this);+ }+ send(value: string) {+ this.sent.push(JSON.parse(value));+ }+ close() {+ this.readyState = 3;+ }+ packet(tag: number, payload: Uint8Array) {+ const data = new Uint8Array(payload.length + 1);+ data[0] = tag;+ data.set(payload, 1);+ this.dispatchEvent(new MessageEvent("message", { data: data.buffer }));+ }+ control(held: boolean) {+ this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify({ type: "control", held }) }));+ }+ closeWith(code: number, reason = "") {+ this.readyState = 3;+ this.dispatchEvent(Object.assign(new Event("close"), { code, reason }));+ }+}++export class FakeEncodedVideoChunk {+ readonly type: string;+ readonly data: Uint8Array;+ constructor(init: { type: string; data: Uint8Array }) {+ this.type = init.type;+ this.data = init.data;+ }+}++export class FakeVideoDecoder {+ static all: FakeVideoDecoder[] = [];+ /** Codec strings this browser cannot decode. */+ static lacks: string[] = [];+ static isConfigSupported(config: VideoDecoderConfig) {+ return Promise.resolve({ supported: !FakeVideoDecoder.lacks.includes(config.codec), config });+ }+ static get current(): FakeVideoDecoder {+ return FakeVideoDecoder.all[FakeVideoDecoder.all.length - 1];+ }+ state = "unconfigured";+ readonly configured: unknown[] = [];+ readonly chunks: FakeEncodedVideoChunk[] = [];+ readonly #init: VideoDecoderInit;+ constructor(init: VideoDecoderInit) {+ this.#init = init;+ FakeVideoDecoder.all.push(this);+ }+ configure(config: unknown) {+ this.configured.push(config);+ this.state = "configured";+ }+ decode(chunk: FakeEncodedVideoChunk) {+ this.chunks.push(chunk);+ }+ close() {+ this.state = "closed";+ }+ /** Hands the client one decoded frame of this size. */+ frame(width: number, height: number) {+ const frame = { displayWidth: width, displayHeight: height, close: vi.fn() };+ this.#init.output(frame as unknown as VideoFrame);+ return frame;+ }+ fail() {+ this.state = "closed";+ this.#init.error(new DOMException("decode failed", "EncodingError"));+ }+}++/** A secure page whose browser has WebCodecs, with the socket and decoder replaced by the fakes. */+export function fakePhoneStream() {+ FakePhoneSocket.all = [];+ FakeVideoDecoder.all = [];+ FakeVideoDecoder.lacks = [];+ vi.stubGlobal("WebSocket", FakePhoneSocket);+ vi.stubGlobal("VideoDecoder", FakeVideoDecoder);+ vi.stubGlobal("EncodedVideoChunk", FakeEncodedVideoChunk);+ vi.stubGlobal("isSecureContext", true);+}++export function showPage(visible: boolean) {+ Object.defineProperty(document, "visibilityState", { configurable: true, value: visible ? "visible" : "hidden" });+ document.dispatchEvent(new Event("visibilitychange"));+}