Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Phone screen: scrcpy's control socket, with touch, key and text messages
Xiaolei Shiccc2fc78e3e8
diff --git a/scripts/phone-screen-probe.ts b/scripts/phone-screen-probe.tsindex ef9c8ddab5..761c09f8db 100644--- a/scripts/phone-screen-probe.ts+++ b/scripts/phone-screen-probe.ts@@ -1,6 +1,7 @@-// Checks the scrcpy video client against a real USB phone. It only watches: the phone gets no input.+// Checks the scrcpy client against a real USB phone. It only watches, and the phone gets no input, unless --keys is+// given: then it presses wakeup and home at the end of the watch, which turns the screen on and leaves the open app.//-// node --experimental-strip-types scripts/phone-screen-probe.ts --serial <serial> [--data-dir <dir>]+// node --experimental-strip-types scripts/phone-screen-probe.ts --serial <serial> [--data-dir <dir>] [--keys]import { execFile } from "node:child_process";import { mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";@@ -10,21 +11,25 @@ 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 { control, KEYCODES } from "../server/phone-screen/scrcpy-wire.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 KEY_GAP_MS = 1_000;+const START_CODE = Buffer.from("00000001", "hex");+// H.264: the low five bits of a NAL header are its type, and 7 is a sequence parameter set; the bits above vary.+const startsWithSps = (data: Buffer) => data.subarray(0, START_CODE.length).equals(START_CODE) && (data[START_CODE.length] & 0x1f) === 7;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 { values } = parseArgs({ options: { serial: { type: "string" }, "data-dir": { type: "string" }, keys: { type: "boolean" } } });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>]");+ 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>] [--keys]");process.exit(2);}@@ -40,6 +45,13 @@ const scrcpyProcesses = async () => {const problems: string[] = [];+const sessionDirs = async () => {+ // 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");+ return new Set(listing);+};+const watch = async (serverFile: string) => {const startedAt = performance.now();const session = await openPhoneSession({ adbPath, serverFile }, serial);@@ -51,11 +63,21 @@ const watch = async (serverFile: string) => {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 === "config") parameterSets ||= startsWithSps(packet.data);else if (packet.kind === "key") firstKeyMs ??= performance.now() - openedAt;});const endedEarly = await Promise.race([session.closed, delay(WATCH_MS).then(() => undefined)]);+ const pressesKeys = values.keys && !endedEarly;+ if (pressesKeys) {+ session.send(control.key(KEYCODES.wakeup));+ await delay(KEY_GAP_MS);+ session.send(control.key(KEYCODES.home));+ // Closing at once would stop scrcpy before the phone has acted on the key.+ await delay(KEY_GAP_MS);+ }await session.close();+ const ended = await session.closed;+ if (pressesKeys && ended === "closed") console.log("keys sent: wakeup, then home one second later");const packets = counts.session + counts.config + counts.key + counts.delta;console.log(`codec ${packets ? "h264" : "unknown"}`);@@ -64,9 +86,9 @@ const watch = async (serverFile: string) => {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 (ended !== "closed") problems.push(`the session ended by itself: ${ended}`);if (!size) problems.push("no session packet arrived");- if (!parameterSets) problems.push("no config packet starting 00 00 00 01 67 arrived");+ if (!parameterSets) problems.push("no config packet starting with a sequence parameter set (00 00 00 01, then a NAL header of type 7) arrived");if (firstKeyMs === undefined || firstKeyMs > KEY_FRAME_WITHIN_MS) problems.push(`no key frame arrived within ${KEY_FRAME_WITHIN_MS / 1000} s of opening`);};@@ -76,12 +98,10 @@ try {const serverFile = await ensureScrcpyServer(values["data-dir"] ?? temporaryDataDir!);const forwardsBefore = await forwards();const scrcpyBefore = await scrcpyProcesses();+ const dirsBefore = await sessionDirs();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 dir of await sessionDirs()) if (!dirsBefore.has(dir)) problems.push(`left on the phone: ${dir}`);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));diff --git a/server/phone-screen/scrcpy-wire.test.ts b/server/phone-screen/scrcpy-wire.test.tsindex 3ae58d8a85..a3a68d552a 100644--- a/server/phone-screen/scrcpy-wire.test.ts+++ b/server/phone-screen/scrcpy-wire.test.ts@@ -3,7 +3,7 @@ import { isDeepStrictEqual } from "node:util";import { describe, expect, it } from "vitest";import { SCRCPY_VIDEO, SCRCPY_VIDEO_PACKETS } from "../testing/scrcpy-video.ts";-import { deviceSocket, SCRCPY_SERVER, ScrcpyProtocolError, serverArgs, VideoReader, type VideoPacket } from "./scrcpy-wire.ts";+import { control, deviceSocket, KEYCODES, SCRCPY_SERVER, ScrcpyProtocolError, serverArgs, textMessage, VideoReader, type VideoPacket } from "./scrcpy-wire.ts";const PREAMBLE = Buffer.from("0068323634", "hex");const hex = (packet: VideoPacket | undefined, bytes: number) =>@@ -20,14 +20,14 @@ describe("the scrcpy server this client is written for", () => {});});- it("starts view-only, without waking the phone, syncing its clipboard or logging below errors", () => {+ it("starts with a control socket, without waking the phone, syncing its clipboard or logging below errors", () => {expect(serverArgs(0x1a2b3c)).toEqual(["5.0.1","scid=001a2b3c","log_level=error","tunnel_forward=true","audio=false",- "control=false",+ "control=true","send_device_meta=false","clipboard_autosync=false","power_on=false",@@ -43,6 +43,75 @@ describe("the scrcpy server this client is written for", () => {});});+// The expected bytes are the arrays in scrcpy v5.0.1's app/tests/test_control_msg_serialize.c, field by field. Where+// a field holds another value than in scrcpy's test, the comment beside it gives scrcpy's.+describe("control messages", () => {+ const sent = (message: Buffer) => message.toString("hex");+ const fields = (...parts: string[]) => parts.join("");+ const ascii = (text: string) => Buffer.from(text, "latin1").toString("hex");+ const NO_SEQUENCE = "0000000000000000";++ it.each([+ ["down", "00", "ffff"],+ ["up", "01", "0000"],+ ["move", "02", "ffff"],+ ] as const)("builds a touch %s of scrcpy's generic finger with no button", (action, actionByte, pressure) => {+ // test_serialize_inject_touch_event, which is the "down" row.+ expect(sent(control.touch(action, 100, 200, 1080, 1920))).toBe(+ fields(+ "02",+ actionByte,+ "fffffffffffffffe", // scrcpy's test: pointer id 1234567887654321+ "00000064",+ "000000c8",+ "0438",+ "0780",+ pressure,+ "00000000", // scrcpy's test: action button 00000001+ "00000000", // scrcpy's test: buttons 00000001+ ),+ );+ });++ it("builds a key as its press, then its release", () => {+ // test_serialize_inject_keycode, which is the release, with repeat 00000005 and metastate 00000041.+ expect(sent(control.key(66))).toBe(+ fields("00", "00", "00000042", "00000000", "00000000") + fields("00", "01", "00000042", "00000000", "00000000"),+ );+ });++ it.each([+ // test_serialize_inject_text+ ["hello, world!", "0000000d"],+ // test_serialize_inject_text_long+ ["a".repeat(300), "0000012c"],+ ])("builds injected text with its length before it", (text, length) => {+ expect(sent(control.text(text))).toBe(fields("01", length, ascii(text)));+ });++ it("builds a clipboard to set and paste", () => {+ // test_serialize_set_clipboard, with sequence 0102030405060708.+ expect(sent(control.paste("hello, world!"))).toBe(fields("09", NO_SEQUENCE, "01", "0000000d", ascii("hello, world!")));+ });++ it.each([+ ["injects", "letters", "abc", fields("01", "00000003", "616263")],+ ["injects", "the first and the last printable character", " ~", fields("01", "00000002", "207e")],+ ["injects", "300 bytes", "a".repeat(300), fields("01", "0000012c", "61".repeat(300))],+ ["pastes", "301 bytes", "a".repeat(301), fields("09", NO_SEQUENCE, "01", "0000012d", "61".repeat(301))],+ ["pastes", "Chinese", "你好", fields("09", NO_SEQUENCE, "01", "00000006", "e4bda0e5a5bd")],+ ["pastes", "a tab", "a\tb", fields("09", NO_SEQUENCE, "01", "00000003", "610962")],+ ["pastes", "the character after the last printable one", "\x7f", fields("09", NO_SEQUENCE, "01", "00000001", "7f")],+ ["pastes", "the character before the first printable one", "\x1f", fields("09", NO_SEQUENCE, "01", "00000001", "1f")],+ ])("%s %s", (_how, _what, text, message) => {+ expect(sent(textMessage(text))).toBe(message);+ });++ it("knows the Android key codes of the phone panel's keys, and no others", () => {+ expect(KEYCODES).toEqual({ back: 4, home: 3, recent: 187, enter: 66, delete: 67, tab: 61, up: 19, down: 20, left: 21, right: 22, wakeup: 224 });+ });+});+describe("VideoReader", () => {it("reads a real phone's stream: its size, the encoder's parameters, a key frame, then the frames after it", () => {const reader = new VideoReader();diff --git a/server/phone-screen/scrcpy-wire.ts b/server/phone-screen/scrcpy-wire.tsindex f708dff526..4d83008735 100644--- a/server/phone-screen/scrcpy-wire.ts+++ b/server/phone-screen/scrcpy-wire.ts@@ -21,7 +21,7 @@ export function serverArgs(scid: number): string[] {"log_level=error","tunnel_forward=true","audio=false",- "control=false",+ "control=true","send_device_meta=false","clipboard_autosync=false","power_on=false",@@ -31,6 +31,91 @@ export function serverArgs(scid: number): string[] {];}+/** Android key codes, under the names the Android panel and the phone tool give the keys. */+export const KEYCODES = {+ back: 4,+ home: 3,+ recent: 187,+ enter: 66,+ delete: 67,+ tab: 61,+ up: 19,+ down: 20,+ left: 21,+ right: 22,+ wakeup: 224,+} as const;++const INJECT_KEYCODE = 0;+const INJECT_TEXT = 1;+const INJECT_TOUCH_EVENT = 2;+const SET_CLIPBOARD = 9;+const KEY_DOWN = 0;+const KEY_UP = 1;+const PASTE = 1;+const TOUCH_ACTIONS = { down: 0, up: 1, move: 2 };+// scrcpy's SC_POINTER_ID_GENERIC_FINGER, -2.+const GENERIC_FINGER = 0xffff_ffff_ffff_fffen;+const FULL_PRESSURE = 0xffff;+// scrcpy's SC_CONTROL_MSG_INJECT_TEXT_MAX_LENGTH.+const INJECT_TEXT_MAX_BYTES = 300;+const PRINTABLE_ASCII = /^[\x20-\x7e]*$/;++function keyEvent(action: number, keycode: number): Buffer {+ const message = Buffer.alloc(14);+ message[0] = INJECT_KEYCODE;+ message[1] = action;+ message.writeUInt32BE(keycode, 2);+ return message;+}++function withText(head: Buffer, text: string): Buffer {+ const bytes = Buffer.from(text, "utf8");+ const length = Buffer.alloc(4);+ length.writeUInt32BE(bytes.length);+ return Buffer.concat([head, length, bytes]);+}++/** Messages for the control socket. Coordinates are video pixels; `width` and `height` are the video's size. */+export const control = {+ touch(action: "down" | "up" | "move", x: number, y: number, width: number, height: number): Buffer {+ const message = Buffer.alloc(32);+ message[0] = INJECT_TOUCH_EVENT;+ message[1] = TOUCH_ACTIONS[action];+ message.writeBigUInt64BE(GENERIC_FINGER, 2);+ message.writeUInt32BE(x, 10);+ message.writeUInt32BE(y, 14);+ message.writeUInt16BE(width, 18);+ message.writeUInt16BE(height, 20);+ message.writeUInt16BE(action === "up" ? 0 : FULL_PRESSURE, 22);+ return message;+ },++ /** The key pressed, then released. */+ key(keycode: number): Buffer {+ return Buffer.concat([keyEvent(KEY_DOWN, keycode), keyEvent(KEY_UP, keycode)]);+ },++ /** scrcpy types this as key events, which it can only for printable ASCII of at most 300 bytes. */+ text(ascii: string): Buffer {+ return withText(Buffer.from([INJECT_TEXT]), ascii);+ },++ /** Replaces the phone's clipboard with `text` and pastes it. */+ paste(text: string): Buffer {+ // Bytes 1 to 8 are a sequence number: scrcpy acknowledges only one other than 0.+ const head = Buffer.alloc(10);+ head[0] = SET_CLIPBOARD;+ head[9] = PASTE;+ return withText(head, text);+ },+};++/** The message that enters `text` on the phone. */+export function textMessage(text: string): Buffer {+ return PRINTABLE_ASCII.test(text) && text.length <= INJECT_TEXT_MAX_BYTES ? control.text(text) : control.paste(text);+}+export type VideoPacket =| { kind: "session"; width: number; height: number }| { kind: "config" | "key" | "delta"; data: Buffer };diff --git a/server/phone-screen/session.test.ts b/server/phone-screen/session.test.tsindex cd77a5c90e..6a9a064c98 100644--- a/server/phone-screen/session.test.ts+++ b/server/phone-screen/session.test.ts@@ -1,4 +1,4 @@-import { chmodSync, copyFileSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { chmodSync, copyFileSync, existsSync, mkdtempSync, readFileSync, watch, writeFileSync } from "node:fs";import { connect } from "node:net";import { tmpdir } from "node:os";import { join } from "node:path";@@ -62,6 +62,20 @@ describe("openPhoneSession", () => {/** 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")),+ /** What the phone's control socket has received, in hex. */+ controlBytes: () => (existsSync(join(dir, "control.hex")) ? read("control.hex") : ""),+ /** The same, once it is at least `bytes` long. */+ controlBytesOnce: (bytes: number) =>+ new Promise<string>((resolve) => {+ const look = () => {+ const received = phone.controlBytes();+ if (received.length < bytes * 2) return;+ changes.close();+ resolve(received);+ };+ const changes = watch(dir, look);+ look();+ }),serverPid: () => Number(read("server.pid")),};phone.become(mode);@@ -106,6 +120,64 @@ describe("openPhoneSession", () => {await expect(session.closed).resolves.toBe("closed");});+ it("delivers exactly what is sent to the phone's control socket, in order", async () => {+ const phone = fakePhone();+ session = await openPhoneSession(phone.deps, SERIAL);+ const messages = ["0200fffe", "00", "09000000e4bda0"];++ for (const message of messages) session.send(Buffer.from(message, "hex"));++ await expect(phone.controlBytesOnce(12)).resolves.toBe(messages.join(""));+ });++ it("writes nothing that is sent after close(), though the phone's scrcpy still reads", async () => {+ const phone = fakePhone("outlives-adb");+ session = await openPhoneSession(phone.deps, SERIAL);+ session.send(Buffer.from("0201", "hex"));+ await phone.controlBytesOnce(2);++ const closing = session.close();+ session.send(Buffer.from("0304", "hex"));+ await closing;+ session.send(Buffer.from("0506", "hex"));++ expect(phone.controlBytes()).toBe("0201");+ });++ it("closes the control connection on close(), which stops a scrcpy that stopping adb leaves running", async () => {+ const phone = fakePhone("outlives-adb");+ session = await openPhoneSession(phone.deps, SERIAL);++ await session.close();++ expect(existsSync(join(dir, "control.closed"))).toBe(true);+ });++ it("says the server stopped, and raises no uncaught error, when the phone resets the control connection", async () => {+ const uncaught: unknown[] = [];+ const note = (error: unknown) => uncaught.push(error);+ process.on("uncaughtException", note);+ try {+ const phone = fakePhone("resets-control");+ session = await openPhoneSession(phone.deps, SERIAL);++ await expect(session.closed).resolves.toBe("server-exit");+ expect(uncaught).toEqual([]);+ expect(phone.calls().at(-1)).toEqual(removal(phone.scids()[0]));+ } finally {+ process.off("uncaughtException", note);+ }+ });++ it("says the server stopped when the phone closes the control connection, whatever it sent there, and ends the adb child", async () => {+ const phone = fakePhone("drops-control");+ session = await openPhoneSession(phone.deps, SERIAL);++ await expect(session.closed).resolves.toBe("server-exit");+ expect(isRunning(phone.serverPid())).toBe(false);+ expect(phone.calls().at(-1)).toEqual(removal(phone.scids()[0]));+ });+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);@@ -250,6 +322,17 @@ describe("openPhoneSession", () => {}});+ it("fails to open when the control connection is refused, and leaves nothing behind", async () => {+ const phone = fakePhone("no-control");++ await expect(openPhoneSession(phone.deps, SERIAL)).rejects.toThrow("Could not open the phone's screen. The control connection to the phone could not be opened.");++ expect(phone.calls().map(step)).toEqual(["push", "forward", "start server", "remove forward", "remove files"]);+ expect(phone.calls().at(-1)).toEqual(removal(phone.scids()[0]));+ expect(isRunning(phone.serverPid())).toBe(false);+ 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");diff --git a/server/phone-screen/session.ts b/server/phone-screen/session.tsindex b7f1385a5a..21e67ed302 100644--- a/server/phone-screen/session.ts+++ b/server/phone-screen/session.ts@@ -1,4 +1,5 @@import { randomInt } from "node:crypto";+import { once } from "node:events";import { connect, type Socket } from "node:net";import { setTimeout as delay } from "node:timers/promises";@@ -18,6 +19,8 @@ export type PhoneSessionEnd = "device-gone" | "server-exit" | "protocol" | "closexport 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;+ /** Writes a scrcpy control message to the phone. Does nothing once the session has started to end. */+ send(message: Buffer): 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>;@@ -30,7 +33,7 @@ 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> {+export 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));@@ -93,6 +96,7 @@ export async function openPhoneSession(deps: PhoneSessionDeps, serial: string):let forwardedPort: number | undefined;let server: ReturnType<typeof spawnCli> | undefined;let socket: Socket | undefined;+ let controlSocket: Socket | undefined;let serverStderr = "";let ending: Promise<void> | undefined;let settleClosed!: (end: PhoneSessionEnd) => void;@@ -102,6 +106,7 @@ export async function openPhoneSession(deps: PhoneSessionDeps, serial: string):const end = (reason: PhoneSessionEnd): Promise<void> => (ending ??= (async () => {socket?.destroy();+ controlSocket?.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);@@ -151,6 +156,15 @@ export async function openPhoneSession(deps: PhoneSessionDeps, serial: string):}socket.on("data", deliver);socket.once("close", () => void end("server-exit"));+ // scrcpy 5.0.1 accepts its control connection next, on the same port, without a byte to say so. Nothing it sends+ // there later is used.+ controlSocket = connect({ host: "127.0.0.1", port: forwardedPort });+ controlSocket.on("error", () => {});+ await once(controlSocket, "connect", { signal: starting.signal }).catch(() => {+ throw new Error("The control connection to the phone could not be opened.");+ });+ controlSocket.once("close", () => void end("server-exit"));+ controlSocket.resume();await adb("forward", "--remove", `tcp:${forwardedPort}`);forwardedPort = undefined;} catch (error) {@@ -160,6 +174,7 @@ export async function openPhoneSession(deps: PhoneSessionDeps, serial: string):}const video = socket;+ const control = controlSocket;return {onPacket(listener) {listeners.add(listener);@@ -168,6 +183,9 @@ export async function openPhoneSession(deps: PhoneSessionDeps, serial: string):listeners.delete(listener);};},+ send(message) {+ if (!ending) control.write(message);+ },closed,close: () => end("closed"),};diff --git a/server/testing/fake-adb.mjs b/server/testing/fake-adb.mjsindex eb4af4ea0c..f92d469afc 100755--- a/server/testing/fake-adb.mjs+++ b/server/testing/fake-adb.mjs@@ -1,14 +1,20 @@#!/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+// calls.ndjson every invocation's arguments, one JSON array per line+// mode "" | "gone" | "no-port" | "vanishes" | "exits" | "silent" | "hangs-up" | "no-control" |+// "drops-control" | "resets-control" | "outlives-adb" |+// "stderr:<what the server writes to its stderr>", read on every invocation+// video.bin what the scrcpy server sends on its video socket: the first byte 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+// control.hex every byte the scrcpy server has received on its control socket, in hex+// control.closed written once the scrcpy server has seen its control connection close+// devices what `devices -l` lists under its heading, one line per device+// port the local port the last `forward tcp:0` chose+// remove-<port> where `forward --remove tcp:<port>` reaches the server running behind that port. A test that+// connects there afterwards sends more video: what it writes goes out on the video socket+// server.pid the running `shell … app_process …`, once it listensimport { appendFileSync, existsSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";import { connect, createServer } from "node:net";import { dirname, join } from "node:path";@@ -23,7 +29,10 @@ const mode = existsSync(state("mode")) ? readFileSync(state("mode"), "utf8").triconst [, serial, command, ...rest] = args;const startsServer = command === "shell" && rest.includes("app_process");-if (mode === "gone" && !startsServer) {+if (args[0] === "devices") {+ const listed = mode !== "gone" && existsSync(state("devices")) ? readFileSync(state("devices"), "utf8") : "";+ process.stdout.write(`List of devices attached\n${listed}\n`);+} else if (mode === "gone" && !startsServer) {process.stderr.write(`adb: device '${serial}' not found\n`);process.exit(1);}@@ -40,14 +49,21 @@ if (command === "forward" && rest[0] === "tcp:0" && mode !== "no-port") {}if (command === "forward" && rest[0] === "--remove") {- connect({ host: "127.0.0.1", port: Number(rest[1].slice("tcp:".length)) })- .on("error", () => {})- .resume();+ const server = state(`remove-${rest[1].slice("tcp:".length)}`);+ if (existsSync(server)) {+ connect({ host: "127.0.0.1", port: Number(readFileSync(server, "utf8")) })+ .on("error", () => {})+ .resume();+ }}if (startsServer) {if (mode === "exits") process.exit(1);if (mode.startsWith("stderr:")) process.stderr.write(`${mode.slice("stderr:".length)}\n`);+ // The phone's scrcpy outlives the adb child that started it and reads its control socket meanwhile: those bytes+ // reach it through the adb server.+ if (mode === "outlives-adb") process.on("SIGTERM", () => {});+ const port = Number(readFileSync(state("port"), "utf8"));const video = readFileSync(state("video.bin"));const pieceLength = Math.ceil(video.length / 4);const writeInTurns = (socket, bytes, written) => {@@ -56,20 +72,45 @@ if (startsServer) {};let connections = 0;let viewer;- createServer((socket) => {+ let control;+ const phone = 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();- });+ else if (connections === 2) {+ if (mode === "no-control") phone.close();+ // scrcpy 5.0.1 sends one byte on its video connection, then takes its control connection before it sends more.+ (viewer = socket).write(video.subarray(0, 1));+ } else {+ phone.close();+ control = socket;+ if (mode === "drops-control") socket.end("unread");+ // scrcpy 5.0.1 stops when its control connection closes.+ else {+ socket.on("data", (bytes) => appendFileSync(state("control.hex"), bytes.toString("hex"))).on("close", () => {+ writeFileSync(state("control.closed"), "");+ process.exit();+ });+ }}- }).listen(Number(readFileSync(state("port"), "utf8")), "127.0.0.1", () => {+ }).listen(port, "127.0.0.1", () => {writeFileSync(state("server.pid"), String(process.pid));});+ let removed = false;+ const forwardRemoved = createServer((socket) => {+ socket.on("error", () => {});+ if (removed) return void socket.pipe(viewer, { end: false });+ removed = true;+ // Like adb, which takes no connection to a forward it has removed.+ phone.close();+ writeInTurns(viewer, video.subarray(1), () => {+ if (mode === "hangs-up") viewer.end();+ if (mode === "resets-control") control.resetAndDestroy();+ socket.end();+ });+ }).listen(0, "127.0.0.1", () => {+ writeFileSync(state(`remove-${port}`), String(forwardRemoved.address().port));+ });}