Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Phone screen: one scrcpy run on one phone, and a probe for a real phone

Xiaolei Shid37b72601e3e
diff --git a/scripts/phone-screen-probe.ts b/scripts/phone-screen-probe.ts
new file mode 100644
index 0000000000..ef9c8ddab5
--- /dev/null
+++ b/scripts/phone-screen-probe.ts
@@ -0,0 +1,103 @@
+// Checks the scrcpy video client against a real USB phone. It only watches: the phone gets no input.
+//
+// node --experimental-strip-types scripts/phone-screen-probe.ts --serial <serial> [--data-dir <dir>]
+import { execFile } from "node:child_process";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { setTimeout as delay } from "node:timers/promises";
+import { parseArgs, promisify } from "node:util";
+
+import { resolveAdbPath } from "../server/drivers/phone-proxy.ts";
+import { ensureScrcpyServer } from "../server/phone-screen/scrcpy-server-file.ts";
+import { openPhoneSession } from "../server/phone-screen/session.ts";
+
+const WATCH_MS = 5_000;
+const KEY_FRAME_WITHIN_MS = 3_000;
+const SPS_START = Buffer.from("0000000167", "hex");
+const LEFTOVERS = "/data/local/tmp/openmausbot-scrcpy-*";
+const SCRCPY_STOPS_WITHIN_MS = 5_000;
+const LIST_PROCESSES = ["ps", "-A", "-o", "PID,ARGS"];
+const FEWEST_PROCESS_LINES = 5;
+
+const { values } = parseArgs({ options: { serial: { type: "string" }, "data-dir": { type: "string" } } });
+const serial = values.serial;
+const adbPath = resolveAdbPath();
+if (!serial || !adbPath) {
+ console.error(serial ? "adb was not found. Install Android platform tools or set OMB_ADB_PATH." : "Usage: phone-screen-probe.ts --serial <serial> [--data-dir <dir>]");
+ process.exit(2);
+}
+
+const run = promisify(execFile);
+const adb = async (...args: string[]) => (await run(adbPath, args, { timeout: 15_000 })).stdout;
+const forwards = async () => new Set((await adb("forward", "--list")).split(/\r?\n/).filter(Boolean));
+const scrcpyProcesses = async () => {
+ const lines = (await adb("-s", serial, "shell", ...LIST_PROCESSES)).split(/\r?\n/).filter(Boolean);
+ // A ps that knows these options lists itself (seen on Android 9); one that does not may print only a header.
+ if (lines.length < FEWEST_PROCESS_LINES || !lines.some((line) => line.includes(LIST_PROCESSES.join(" ")))) throw new Error("the phone's processes could not be listed");
+ return new Set(lines.filter((line) => line.includes("com.genymobile.scrcpy")));
+};
+
+const problems: string[] = [];
+
+const watch = async (serverFile: string) => {
+ const startedAt = performance.now();
+ const session = await openPhoneSession({ adbPath, serverFile }, serial);
+ const openedAt = performance.now();
+ const counts = { session: 0, config: 0, key: 0, delta: 0 };
+ let size = "";
+ let parameterSets = false;
+ let firstKeyMs: number | undefined;
+ session.onPacket((packet) => {
+ counts[packet.kind] += 1;
+ if (packet.kind === "session") size = `${packet.width}x${packet.height}`;
+ else if (packet.kind === "config") parameterSets ||= packet.data.subarray(0, SPS_START.length).equals(SPS_START);
+ else if (packet.kind === "key") firstKeyMs ??= performance.now() - openedAt;
+ });
+ const endedEarly = await Promise.race([session.closed, delay(WATCH_MS).then(() => undefined)]);
+ await session.close();
+
+ const packets = counts.session + counts.config + counts.key + counts.delta;
+ console.log(`codec ${packets ? "h264" : "unknown"}`);
+ console.log(`session ${size || "none"}`);
+ console.log(`opened in ${Math.round(openedAt - startedAt)} ms`);
+ console.log(`first key frame ${firstKeyMs === undefined ? "none" : `${Math.round(firstKeyMs)} ms after opening`}`);
+ console.log(`packets session=${counts.session} config=${counts.config} key=${counts.key} delta=${counts.delta}`);
+
+ if (endedEarly) problems.push(`the session ended by itself: ${endedEarly}`);
+ if (!size) problems.push("no session packet arrived");
+ if (!parameterSets) problems.push("no config packet starting 00 00 00 01 67 arrived");
+ if (firstKeyMs === undefined || firstKeyMs > KEY_FRAME_WITHIN_MS) problems.push(`no key frame arrived within ${KEY_FRAME_WITHIN_MS / 1000} s of opening`);
+};
+
+const reason = (error: unknown) => (error instanceof Error ? error.message : String(error));
+const temporaryDataDir = values["data-dir"] ? undefined : mkdtempSync(join(tmpdir(), "omb-phone-screen-probe-"));
+try {
+ const serverFile = await ensureScrcpyServer(values["data-dir"] ?? temporaryDataDir!);
+ const forwardsBefore = await forwards();
+ const scrcpyBefore = await scrcpyProcesses();
+ await watch(serverFile).catch((error: unknown) => problems.push(reason(error)));
+
+ // The device shell runs this line; "checked" tells an empty listing from a phone adb could not reach.
+ const listing = (await adb("-s", serial, "shell", `ls -d ${LEFTOVERS} 2>/dev/null; echo checked`)).split(/\r?\n/).filter(Boolean);
+ if (listing.pop() !== "checked") problems.push("the phone could not be checked for leftover files");
+ for (const file of listing) problems.push(`left on the phone: ${file}`);
+ for (const forward of await forwards()) if (!forwardsBefore.has(forward)) problems.push(`adb still forwards: ${forward}`);
+
+ const stillRunning = async () => [...(await scrcpyProcesses())].some((line) => !scrcpyBefore.has(line));
+ const giveUpAt = performance.now() + SCRCPY_STOPS_WITHIN_MS;
+ let running = await stillRunning();
+ while (running && performance.now() < giveUpAt) {
+ await delay(250);
+ running = await stillRunning();
+ }
+ if (running) problems.push("scrcpy is still running on the phone");
+} catch (error) {
+ problems.push(reason(error));
+} finally {
+ if (temporaryDataDir) rmSync(temporaryDataDir, { recursive: true, force: true });
+}
+
+for (const problem of problems) console.error(`FAILED: ${problem}`);
+console.log(problems.length ? "phone screen probe failed" : "phone screen probe passed: video as expected, nothing left on the phone or in adb");
+process.exitCode = problems.length ? 1 : 0;
diff --git a/server/phone-screen/session.test.ts b/server/phone-screen/session.test.ts
new file mode 100644
index 0000000000..cd77a5c90e
--- /dev/null
+++ b/server/phone-screen/session.test.ts
@@ -0,0 +1,260 @@
+import { chmodSync, copyFileSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { connect } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import { removeTempDir } from "../testing/cleanup.ts";
+import { SCRCPY_VIDEO, SCRCPY_VIDEO_PACKETS } from "../testing/scrcpy-video.ts";
+import { serverArgs, type VideoPacket } from "./scrcpy-wire.ts";
+import { openPhoneSession, type PhoneSession } from "./session.ts";
+
+const FAKE_ADB = fileURLToPath(new URL("../testing/fake-adb.mjs", import.meta.url));
+const SERIAL = "PHONE1";
+const deviceDir = (scid: string | undefined) => `/data/local/tmp/openmausbot-scrcpy-${scid}`;
+const deviceJar = (scid: string | undefined) => `${deviceDir(scid)}/scrcpy-server.jar`;
+const removal = (scid: string | undefined) => ["-s", SERIAL, "shell", "rm", "-rf", deviceDir(scid)];
+
+const isRunning = (pid: number) => {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+const refusesConnections = (port: number) =>
+ new Promise<boolean>((resolve) => {
+ const socket = connect({ host: "127.0.0.1", port });
+ socket.once("connect", () => {
+ socket.destroy();
+ resolve(false);
+ });
+ socket.once("error", () => resolve(true));
+ });
+
+describe("openPhoneSession", () => {
+ let dir = "";
+ let session: PhoneSession | undefined;
+
+ afterEach(async () => {
+ await session?.close();
+ session = undefined;
+ await removeTempDir(dir);
+ });
+
+ function fakePhone(mode = "", video = SCRCPY_VIDEO) {
+ dir = mkdtempSync(join(tmpdir(), "omb-fake-adb-"));
+ const adbPath = join(dir, "adb.mjs");
+ copyFileSync(FAKE_ADB, adbPath);
+ chmodSync(adbPath, 0o755);
+ const serverFile = join(dir, "scrcpy-server");
+ writeFileSync(serverFile, "the scrcpy server file");
+ writeFileSync(join(dir, "video.bin"), video);
+ const read = (name: string) => readFileSync(join(dir, name), "utf8");
+ const phone = {
+ deps: { adbPath, serverFile },
+ become: (next: string) => writeFileSync(join(dir, "mode"), next),
+ calls: () => read("calls.ndjson").trim().split("\n").map((line) => JSON.parse(line) as string[]),
+ /** The scid of each session started on this phone, read from where it pushed its file. */
+ scids: () => phone.calls().filter((call) => call[2] === "push").map((push) => /-([0-9a-f]{8})\/[^/]*$/.exec(push[4] ?? "")?.[1]),
+ port: () => Number(read("port")),
+ serverPid: () => Number(read("server.pid")),
+ };
+ phone.become(mode);
+ return phone;
+ }
+
+ const packetsOf = (opened: PhoneSession, count: number) =>
+ new Promise<VideoPacket[]>((resolve) => {
+ const packets: VideoPacket[] = [];
+ opened.onPacket((packet) => {
+ packets.push(packet);
+ if (packets.length === count) resolve(packets);
+ });
+ });
+
+ it("starts scrcpy through adb, hands out the phone's video in order, and leaves nothing behind when closed", async () => {
+ const phone = fakePhone();
+ session = await openPhoneSession(phone.deps, SERIAL);
+
+ const seenBeforeLeaving: VideoPacket[] = [];
+ const leave = session.onPacket((packet) => {
+ seenBeforeLeaving.push(packet);
+ leave();
+ });
+ await expect(packetsOf(session, SCRCPY_VIDEO_PACKETS.length)).resolves.toEqual(SCRCPY_VIDEO_PACKETS);
+ expect(seenBeforeLeaving).toEqual(SCRCPY_VIDEO_PACKETS.slice(0, 1));
+
+ const started = phone.calls();
+ const [scid = ""] = phone.scids();
+ expect(started).toEqual([
+ ["-s", SERIAL, "push", phone.deps.serverFile, deviceJar(scid)],
+ ["-s", SERIAL, "forward", "tcp:0", `localabstract:scrcpy_${scid}`],
+ ["-s", SERIAL, "shell", `CLASSPATH=${deviceJar(scid)}`, "app_process", "/", "com.genymobile.scrcpy.Server", ...serverArgs(Number.parseInt(scid, 16))],
+ ["-s", SERIAL, "forward", "--remove", `tcp:${phone.port()}`],
+ ]);
+ expect(isRunning(phone.serverPid())).toBe(true);
+
+ await session.close();
+
+ expect(phone.calls().slice(started.length)).toEqual([removal(scid)]);
+ expect(isRunning(phone.serverPid())).toBe(false);
+ await expect(session.closed).resolves.toBe("closed");
+ });
+
+ it("keeps two sessions on one phone apart: closing one removes only its own directory", async () => {
+ const phone = fakePhone();
+ const first = await openPhoneSession(phone.deps, SERIAL);
+ try {
+ session = await openPhoneSession(phone.deps, SERIAL);
+ const started = phone.calls();
+ const [firstScid, secondScid] = phone.scids();
+ expect(secondScid).not.toBe(firstScid);
+ expect(started.filter((call) => call[2] === "push").map((push) => push[4])).toEqual([deviceJar(firstScid), deviceJar(secondScid)]);
+ expect(started.filter((call) => call[3] === "tcp:0").map((forward) => forward[4])).toEqual([`localabstract:scrcpy_${firstScid}`, `localabstract:scrcpy_${secondScid}`]);
+
+ await first.close();
+
+ expect(phone.calls().slice(started.length)).toEqual([removal(firstScid)]);
+ } finally {
+ await first.close();
+ }
+ });
+
+ it("settles closed only after the cleanup when close() ends the session", async () => {
+ const phone = fakePhone();
+ session = await openPhoneSession(phone.deps, SERIAL);
+
+ void session.close();
+
+ await expect(session.closed).resolves.toBe("closed");
+ expect(isRunning(phone.serverPid())).toBe(false);
+ expect(phone.calls().at(-1)).toEqual(removal(phone.scids()[0]));
+ });
+
+ it("says closed when close() ends the session, even if the phone is gone by then", async () => {
+ const phone = fakePhone();
+ session = await openPhoneSession(phone.deps, SERIAL);
+
+ phone.become("gone");
+ await session.close();
+
+ await expect(session.closed).resolves.toBe("closed");
+ });
+
+ it.each([
+ ["throws", () => {
+ throw new Error("a listener failed");
+ }],
+ ["closes the session", (opened: PhoneSession) => void opened.close()],
+ ])("ends the session as closed when a listener %s on its first packet, and hands out nothing more", async (_what, leave) => {
+ const phone = fakePhone();
+ const opened = await openPhoneSession(phone.deps, SERIAL);
+ session = opened;
+ const seenBefore: VideoPacket[] = [];
+ const seenAfter: VideoPacket[] = [];
+ let left = 0;
+ opened.onPacket((packet) => seenBefore.push(packet));
+ opened.onPacket(() => {
+ left += 1;
+ leave(opened);
+ });
+ opened.onPacket((packet) => seenAfter.push(packet));
+
+ await expect(opened.closed).resolves.toBe("closed");
+ expect(left).toBe(1);
+ expect(seenBefore).toEqual(SCRCPY_VIDEO_PACKETS.slice(0, 1));
+ expect(seenAfter).toEqual([]);
+ expect(isRunning(phone.serverPid())).toBe(false);
+ expect(phone.calls().at(-1)).toEqual(removal(phone.scids()[0]));
+ });
+
+ it("says the server stopped when it exits by itself, and still removes its files", async () => {
+ const phone = fakePhone();
+ session = await openPhoneSession(phone.deps, SERIAL);
+
+ process.kill(phone.serverPid());
+
+ await expect(session.closed).resolves.toBe("server-exit");
+ expect(phone.calls().at(-1)).toEqual(removal(phone.scids()[0]));
+ });
+
+ it("says the server stopped when the phone closes the video stream, and ends the adb child", async () => {
+ const phone = fakePhone("hangs-up");
+ session = await openPhoneSession(phone.deps, SERIAL);
+
+ await expect(packetsOf(session, SCRCPY_VIDEO_PACKETS.length)).resolves.toEqual(SCRCPY_VIDEO_PACKETS);
+ await expect(session.closed).resolves.toBe("server-exit");
+ expect(isRunning(phone.serverPid())).toBe(false);
+ });
+
+ it("says the phone is gone when adb no longer finds it", async () => {
+ const phone = fakePhone();
+ session = await openPhoneSession(phone.deps, SERIAL);
+
+ phone.become("gone");
+ process.kill(phone.serverPid());
+
+ await expect(session.closed).resolves.toBe("device-gone");
+ });
+
+ it.each(["adb: device 'PHONE1' not found", "error: device offline", "adb: no devices/emulators found"])(
+ "says the phone is gone when only the stopped server's stderr says %s",
+ async (words) => {
+ const phone = fakePhone(`stderr:${words}`);
+ session = await openPhoneSession(phone.deps, SERIAL);
+
+ process.kill(phone.serverPid());
+
+ await expect(session.closed).resolves.toBe("device-gone");
+ expect(phone.calls().at(-1)).toEqual(removal(phone.scids()[0]));
+ },
+ );
+
+ it("ends with a protocol error when the phone sends something other than scrcpy 5.0.1 H.264 video", async () => {
+ const phone = fakePhone("", Buffer.concat([Buffer.from("0068323635", "hex"), SCRCPY_VIDEO.subarray(5)]));
+ session = await openPhoneSession(phone.deps, SERIAL);
+ const seen: VideoPacket[] = [];
+ session.onPacket((packet) => seen.push(packet));
+
+ await expect(session.closed).resolves.toBe("protocol");
+ expect(seen).toEqual([]);
+ expect(isRunning(phone.serverPid())).toBe(false);
+ expect(phone.calls().at(-1)).toEqual(removal(phone.scids()[0]));
+ });
+
+ const step = ([, , command, first]: string[]) =>
+ command === "shell" ? (first === "rm" ? "remove files" : "start server") : command === "forward" ? (first === "tcp:0" ? "forward" : "remove forward") : command;
+
+ it.each([
+ ["adb does not find the phone", "gone", "adb: device 'PHONE1' not found", ["push", "remove files"]],
+ ["adb names no forwarded port", "no-port", "adb did not name the port it forwarded.", ["push", "forward", "remove files"]],
+ ["the server exits at once", "exits", "scrcpy stopped on the phone before the screen was open.", ["push", "forward", "remove forward", "remove files"]],
+ ["the phone never sends a byte", "silent", "The phone sent no video within 0.3 seconds.", ["push", "forward", "remove forward", "remove files"]],
+ ])("fails to open when %s, and leaves nothing behind", async (_what, mode, reason, steps) => {
+ const phone = fakePhone(mode);
+
+ await expect(openPhoneSession({ ...phone.deps, startTimeoutMs: 300 }, SERIAL)).rejects.toThrow(`Could not open the phone's screen. ${reason}`);
+
+ // The time limit can end a server that had not yet logged its start.
+ const calls = phone.calls().filter((call) => step(call) !== "start server");
+ expect(calls.map(step)).toEqual(steps);
+ expect(calls.at(-1)).toEqual(removal(phone.scids()[0]));
+ if (steps.includes("remove forward")) {
+ expect(calls.at(-2)).toEqual(["-s", SERIAL, "forward", "--remove", `tcp:${phone.port()}`]);
+ await expect(refusesConnections(phone.port())).resolves.toBe(true);
+ }
+ });
+
+ it("fails to open when adb cannot be started for the server", async () => {
+ const phone = fakePhone("vanishes");
+
+ await expect(openPhoneSession(phone.deps, SERIAL)).rejects.toThrow(`Could not open the phone's screen. spawn ${phone.deps.adbPath} ENOENT`);
+
+ expect(phone.calls().map(step)).toEqual(["push", "forward"]);
+ });
+});
diff --git a/server/phone-screen/session.ts b/server/phone-screen/session.ts
new file mode 100644
index 0000000000..b7f1385a5a
--- /dev/null
+++ b/server/phone-screen/session.ts
@@ -0,0 +1,174 @@
+import { randomInt } from "node:crypto";
+import { connect, type Socket } from "node:net";
+import { setTimeout as delay } from "node:timers/promises";
+
+import { execCli, killCliTree, spawnCli } from "../procs.ts";
+import { deviceDir, deviceSocket, serverArgs, VideoReader, type VideoPacket } from "./scrcpy-wire.ts";
+
+export type PhoneSessionDeps = {
+ adbPath: string;
+ /** A verified scrcpy server file, as `ensureScrcpyServer` returns it. */
+ serverFile: string;
+ /** How long the phone gets to send its first byte. Default 10 seconds. */
+ startTimeoutMs?: number;
+};
+
+export type PhoneSessionEnd = "device-gone" | "server-exit" | "protocol" | "closed";
+
+export type PhoneSession = {
+ /** Video waits until the first listener is added, so that listener sees the stream from its first packet. */
+ onPacket(listener: (packet: VideoPacket) => void): () => void;
+ /** Settles once the cleanup has run: the adb child stopped, then the forward and the session's files removed if adb still reaches the phone. */
+ closed: Promise<PhoneSessionEnd>;
+ close(): Promise<void>;
+};
+
+const ADB_TIMEOUT_MS = 15_000;
+const START_TIMEOUT_MS = 10_000;
+const CONNECT_RETRY_MS = 100;
+const SERVER_STDERR_KEPT = 2_048;
+// adb's words for a serial that is unplugged or has dropped off the bus.
+const DEVICE_GONE = /device '.*' not found|device offline|no devices\/emulators found/;
+
+function runAdb(adbPath: string, args: string[]): Promise<string> {
+ return new Promise((resolve, reject) => {
+ execCli(adbPath, args, { timeout: ADB_TIMEOUT_MS }, (error, stdout, stderr) => {
+ if (error) reject(new Error(stderr?.trim() || error.message));
+ else resolve(stdout);
+ });
+ });
+}
+
+function forwardedPortFrom(output: string): number {
+ const port = Number(output.trim());
+ if (!Number.isInteger(port) || port < 1 || port > 65_535) throw new Error("adb did not name the port it forwarded.");
+ return port;
+}
+
+/** The socket once the phone has sent a byte, paused with that byte still unread. */
+function firstByte(port: number, starting: AbortSignal): Promise<Socket | null> {
+ return new Promise((resolve, reject) => {
+ const socket = connect({ host: "127.0.0.1", port });
+ const giveUp = () => {
+ socket.destroy();
+ reject(starting.reason);
+ };
+ const settle = (connected: Socket | null) => {
+ starting.removeEventListener("abort", giveUp);
+ resolve(connected);
+ };
+ starting.addEventListener("abort", giveUp, { once: true });
+ // Node emits "close" after every socket "error".
+ socket.on("error", () => {});
+ socket.once("close", () => settle(null));
+ socket.once("data", (first: Buffer) => {
+ socket.pause();
+ socket.unshift(first);
+ settle(socket);
+ });
+ });
+}
+
+// adb accepts a connection to the forwarded port before the phone listens, then closes it without a byte.
+async function connectVideo(port: number, starting: AbortSignal): Promise<Socket> {
+ for (;;) {
+ starting.throwIfAborted();
+ const socket = await firstByte(port, starting);
+ if (socket) return socket;
+ await delay(CONNECT_RETRY_MS, undefined, { signal: starting });
+ }
+}
+
+/** One run of scrcpy-server on one phone. The serial reaches adb only as an argument. */
+export async function openPhoneSession(deps: PhoneSessionDeps, serial: string): Promise<PhoneSession> {
+ const adb = (...args: string[]) => runAdb(deps.adbPath, ["-s", serial, ...args]);
+ const scid = randomInt(2 ** 31);
+ // Android 9 compiles the jar into oat/<abi>/ beside it, so each session has a directory of its own to remove whole.
+ // `adb push` creates it.
+ const dir = deviceDir(scid);
+ const jar = `${dir}/scrcpy-server.jar`;
+ const starting = new AbortController();
+ const reader = new VideoReader();
+ const listeners = new Set<(packet: VideoPacket) => void>();
+ let forwardedPort: number | undefined;
+ let server: ReturnType<typeof spawnCli> | undefined;
+ let socket: Socket | undefined;
+ let serverStderr = "";
+ let ending: Promise<void> | undefined;
+ let settleClosed!: (end: PhoneSessionEnd) => void;
+ const closed = new Promise<PhoneSessionEnd>((resolve) => {
+ settleClosed = resolve;
+ });
+
+ const end = (reason: PhoneSessionEnd): Promise<void> => (ending ??= (async () => {
+ socket?.destroy();
+ if (server) await killCliTree(server);
+ if (forwardedPort !== undefined) await adb("forward", "--remove", `tcp:${forwardedPort}`).catch(() => {});
+ const cleanupError = await adb("shell", "rm", "-rf", dir).then(() => "", (error: Error) => error.message);
+ settleClosed(reason === "server-exit" && DEVICE_GONE.test(serverStderr + cleanupError) ? "device-gone" : reason);
+ })());
+
+ const serverStopped = (cause: Error) => {
+ starting.abort(cause);
+ void end("server-exit");
+ };
+
+ const deliver = (chunk: Buffer) => {
+ let packets: VideoPacket[];
+ try {
+ packets = reader.push(chunk);
+ } catch {
+ void end("protocol");
+ return;
+ }
+ try {
+ for (const packet of packets) for (const listener of listeners) if (!ending) listener(packet);
+ } catch {
+ void end("closed");
+ }
+ };
+
+ try {
+ await adb("push", deps.serverFile, jar);
+ forwardedPort = forwardedPortFrom(await adb("forward", "tcp:0", deviceSocket(scid)));
+ server = spawnCli(
+ deps.adbPath,
+ ["-s", serial, "shell", `CLASSPATH=${jar}`, "app_process", "/", "com.genymobile.scrcpy.Server", ...serverArgs(scid)],
+ { stdio: ["ignore", "pipe", "pipe"] },
+ );
+ server.once("error", serverStopped);
+ server.once("exit", () => serverStopped(new Error("scrcpy stopped on the phone before the screen was open.")));
+ server.stdout.resume();
+ server.stderr.on("data", (chunk: Buffer) => {
+ serverStderr = (serverStderr + chunk.toString("utf8")).slice(-SERVER_STDERR_KEPT);
+ });
+ const limitMs = deps.startTimeoutMs ?? START_TIMEOUT_MS;
+ const limit = setTimeout(() => starting.abort(new Error(`The phone sent no video within ${limitMs / 1000} seconds.`)), limitMs);
+ try {
+ socket = await connectVideo(forwardedPort, starting.signal);
+ } finally {
+ clearTimeout(limit);
+ }
+ socket.on("data", deliver);
+ socket.once("close", () => void end("server-exit"));
+ await adb("forward", "--remove", `tcp:${forwardedPort}`);
+ forwardedPort = undefined;
+ } catch (error) {
+ const cause: unknown = starting.signal.aborted ? starting.signal.reason : error;
+ await end("closed");
+ throw new Error(`Could not open the phone's screen. ${cause instanceof Error ? cause.message : String(cause)}`);
+ }
+
+ const video = socket;
+ return {
+ onPacket(listener) {
+ listeners.add(listener);
+ if (video.isPaused()) video.resume();
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ closed,
+ close: () => end("closed"),
+ };
+}
diff --git a/server/testing/fake-adb.mjs b/server/testing/fake-adb.mjs
new file mode 100755
index 0000000000..eb4af4ea0c
--- /dev/null
+++ b/server/testing/fake-adb.mjs
@@ -0,0 +1,75 @@
+#!/usr/bin/env node
+// A scripted adb with a phone that runs scrcpy-server. Its state lives beside the script, so a test runs its own
+// copy in a throwaway folder:
+// calls.ndjson every invocation's arguments, one JSON array per line
+// mode "" | "gone" | "no-port" | "vanishes" | "exits" | "silent" | "hangs-up" | "stderr:<what the server
+// writes to its stderr>", read on every invocation
+// video.bin what the scrcpy server sends on its video socket: a first piece at once, the rest in further writes
+// when `forward --remove` runs, which returns once all of it is written, so that an opened session
+// always has several chunks waiting
+// port the local port the last `forward tcp:0` chose
+// server.pid the running `shell … app_process …`, once it listens
+import { appendFileSync, existsSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
+import { connect, createServer } from "node:net";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const state = (name) => join(here, name);
+const args = process.argv.slice(2);
+appendFileSync(state("calls.ndjson"), `${JSON.stringify(args)}\n`);
+
+const mode = existsSync(state("mode")) ? readFileSync(state("mode"), "utf8").trim() : "";
+const [, serial, command, ...rest] = args;
+const startsServer = command === "shell" && rest.includes("app_process");
+
+if (mode === "gone" && !startsServer) {
+ process.stderr.write(`adb: device '${serial}' not found\n`);
+ process.exit(1);
+}
+
+if (command === "forward" && rest[0] === "tcp:0" && mode !== "no-port") {
+ const probe = createServer().listen(0, "127.0.0.1", () => {
+ const { port } = probe.address();
+ probe.close(() => {
+ writeFileSync(state("port"), String(port));
+ if (mode === "vanishes") unlinkSync(fileURLToPath(import.meta.url));
+ process.stdout.write(`${port}\n`);
+ });
+ });
+}
+
+if (command === "forward" && rest[0] === "--remove") {
+ connect({ host: "127.0.0.1", port: Number(rest[1].slice("tcp:".length)) })
+ .on("error", () => {})
+ .resume();
+}
+
+if (startsServer) {
+ if (mode === "exits") process.exit(1);
+ if (mode.startsWith("stderr:")) process.stderr.write(`${mode.slice("stderr:".length)}\n`);
+ const video = readFileSync(state("video.bin"));
+ const pieceLength = Math.ceil(video.length / 4);
+ const writeInTurns = (socket, bytes, written) => {
+ if (bytes.length === 0) written();
+ else socket.write(bytes.subarray(0, pieceLength), () => setImmediate(writeInTurns, socket, bytes.subarray(pieceLength), written));
+ };
+ let connections = 0;
+ let viewer;
+ createServer((socket) => {
+ connections += 1;
+ socket.on("error", () => {});
+ if (mode === "silent") return;
+ // Like adb before the phone listens: the first connection is accepted, then closed without a byte.
+ if (connections === 1) socket.destroy();
+ else if (connections === 2) (viewer = socket).write(video.subarray(0, pieceLength));
+ else {
+ writeInTurns(viewer, video.subarray(pieceLength), () => {
+ if (mode === "hangs-up") viewer.end();
+ socket.end();
+ });
+ }
+ }).listen(Number(readFileSync(state("port"), "utf8")), "127.0.0.1", () => {
+ writeFileSync(state("server.pid"), String(process.pid));
+ });
+}