Skip to content

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

Phone: a person's hold on the USB phone, and the claim gate and proxy that respect it

Xiaolei Shifcaf0b076c6c
diff --git a/server/config.ts b/server/config.ts
index 39ecc3b994..14c18b5520 100644
--- a/server/config.ts
+++ b/server/config.ts
@@ -244,7 +244,7 @@ const featureConfigSchema = z.object({
/** Room jobs to several members run side by side, each in a thread of its own. Off unless true. */
parallelRoomJobs: z.boolean().optional(),
acpPlanLines: z.boolean().optional(), // An ACP agent's plan as activity lines. Off unless true.
-}).extend({ agentsToolBridge: z.boolean().optional(), savedSteps: z.boolean().optional() }); // agentsToolBridge: the find_tool / use_tool bridge, off unless true; savedSteps: repeat a computer task from its saved steps, on unless false
+}).extend({ agentsToolBridge: z.boolean().optional(), savedSteps: z.boolean().optional(), usbPhoneTakeover: z.boolean().optional() }); // agentsToolBridge: the find_tool / use_tool bridge, off unless true; savedSteps: repeat a computer task from its saved steps, on unless false; usbPhoneTakeover: watch and take over the bots' USB phone, off unless true
const onboardingConfigSchema = z.object({
completedAt: z.string().trim().max(40).optional(),
version: z.number().int().min(0).max(1000).optional(),
@@ -483,7 +483,7 @@ export interface AppConfig extends HelperConfig {
context?: { rebuildBytes?: number; compactAt?: number; autoCompact?: boolean; roomCompactAt?: number; roomSessions?: boolean; replayToolHistory?: boolean };
memory?: { captureQuietMs?: number; tidyHour?: number };
localVm?: { mode?: "shared" | "per-bot" | "pool"; maxInstances?: number; idleTimeoutMinutes?: number; preserveInstalledApps?: boolean; memoryGb?: number; cpus?: number };
- features?: { skillAuthoring?: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; claudeUserSkills?: boolean; llmThreadTitles?: boolean; smartSetupChoices?: boolean; autoRecall?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; parallelRoomJobs?: boolean; acpPlanLines?: boolean; agentsToolBridge?: boolean; savedSteps?: boolean };
+ features?: { skillAuthoring?: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; claudeUserSkills?: boolean; llmThreadTitles?: boolean; smartSetupChoices?: boolean; autoRecall?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; parallelRoomJobs?: boolean; acpPlanLines?: boolean; agentsToolBridge?: boolean; savedSteps?: boolean; usbPhoneTakeover?: boolean };
onboarding?: { completedAt?: string; version?: number; reelSeen?: boolean; hintsSeen?: string[]; firstTurnAt?: string };
browserProfiles?: BrowserProfile[];
browserEngine?: BrowserEngineConfig;
diff --git a/server/drivers/phone-proxy.test.ts b/server/drivers/phone-proxy.test.ts
index 7175d7a6ce..721d5fd323 100644
--- a/server/drivers/phone-proxy.test.ts
+++ b/server/drivers/phone-proxy.test.ts
@@ -1,6 +1,9 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { TOOLS, createPhoneClaim, findPackages, launchTarget, parseDevices, parseLaunchablePackages, parseUiNodes, typePhoneText } from "./phone-proxy.ts";
+import { createPhoneHold } from "../phone-screen/hold.ts";
+import { createPhoneGate } from "../routes/phone-gate.ts";
+import { TurnResources } from "../turn-resources.ts";
+import { TOOLS, callPhoneTool, createPhoneClaim, findPackages, launchTarget, parseDevices, parseLaunchablePackages, parseUiNodes, typePhoneText } from "./phone-proxy.ts";
describe("phone MCP parsing", () => {
it("keeps physical USB devices distinguishable from network and emulator transports", () => {
@@ -135,6 +138,14 @@ describe("phone MCP lazy claim gate", () => {
expect(calls[0].headers.get("authorization")).toBe("Bearer tok");
});
+ it("tells the harness which claim comes from the middle of a call", async () => {
+ const { calls, fetchImpl } = stub(async () => ({ ok: true, status: 200 }));
+ const ensure = createPhoneClaim(harnessEnv, fetchImpl);
+ await ensure();
+ await ensure(true);
+ expect(await Promise.all(calls.map((call) => call.json()))).toEqual([{}, { wait: false }]);
+ });
+
it.each([401, 403, 409])("rejects a previously successful caller after ownership is lost (%s)", async (status) => {
let active = true;
const { calls, fetchImpl } = stub(async () => active ? { ok: true, status: 200 } : { ok: false, status });
@@ -167,3 +178,249 @@ describe("phone MCP lazy claim gate", () => {
await expect(ensure()).resolves.toMatchObject({ ok: false, message: expect.stringContaining("could not be reached") });
});
});
+
+const PERSON_TEXT = "A person has taken control of the phone, so this call was NOT performed. Do not act until they hand it back. To wait, call read_screen: each phone call waits up to 45 seconds and returns as soon as they hand the phone back. Meanwhile you may work on anything that does not need the phone.";
+const HANDED_BACK_TEXT = "The person has handed the phone back. This call was NOT performed: the screen may have changed. Call read_screen, then continue the task.";
+
+describe("phone MCP claim while a person may hold the phone", () => {
+ const harnessEnv = { OMB_HARNESS_URL: "http://127.0.0.1:8799", OMB_PHONE_TOKEN: "tok" };
+ const answering = (answer: () => Response) => (async () => answer()) as unknown as typeof fetch;
+ const refusal = (body: unknown) => answering(() => new Response(JSON.stringify(body), { status: 423 }));
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ it.each([
+ [{ reason: "person" }, PERSON_TEXT],
+ [{ reason: "handed-back" }, HANDED_BACK_TEXT],
+ [{}, "OpenMausBot could not reserve the phone for this call. This call was not performed; try again, or start a new turn if it keeps failing."],
+ ])("tells the bot what a 423 %j means", async (body, message) => {
+ await expect(createPhoneClaim(harnessEnv, refusal(body))()).resolves.toEqual({ ok: false, message });
+ });
+
+ it("gives the harness 55 seconds to answer, past its 45-second wait", async () => {
+ const timeout = vi.spyOn(AbortSignal, "timeout");
+ await createPhoneClaim(harnessEnv, answering(() => new Response("{}")))();
+ expect(timeout.mock.calls).toEqual([[55_000]]);
+ });
+
+ it.each([
+ [5_000, { ok: true }],
+ [5_001, { ok: false, message: "The phone is free now, but this call had to wait for it, so it was NOT performed. Call again: the next call goes through at once. If you meant to tap or type from an earlier read_screen, call read_screen again first: the screen may have changed while you waited." }],
+ ])("acts on a claim granted after %i ms only when that is within 5 seconds", async (waitedMs, outcome) => {
+ vi.useFakeTimers();
+ const slow = answering(() => {
+ vi.advanceTimersByTime(waitedMs);
+ return new Response(JSON.stringify({ claimed: true }));
+ });
+ await expect(createPhoneClaim(harnessEnv, slow)()).resolves.toEqual(outcome);
+ });
+});
+
+describe("phone MCP calls claim before each command sent to the phone", () => {
+ const DEVICES = ["devices", "-l"];
+ const onPhone = (...command: string[]) => ["-s", "USB123", ...command];
+ const DUMP = onPhone("shell", "uiautomator", "dump", "/dev/tty");
+ const APPS = onPhone("shell", "cmd", "package", "query-activities", "--brief", "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER");
+ const SAVED_DUMP = "/data/local/tmp/openmaus-window.xml";
+ const SAVE_READ_AND_REMOVE = onPhone("shell", `rm -f ${SAVED_DUMP}; uiautomator dump ${SAVED_DUMP} >/dev/null && cat ${SAVED_DUMP}; status=$?; rm -f ${SAVED_DUMP}; exit $status`);
+ const namingTheSavedDumpWithoutRemovingIt = (commands: string[][]) =>
+ commands.filter((command) => command.join(" ").includes(SAVED_DUMP) && !command.join(" ").includes(`rm -f ${SAVED_DUMP}`));
+ const DEVICE_LIST = "List of devices attached\nUSB123 device product:husky model:Pixel_8 usb:1-2 transport_id:4\n";
+ const SCREEN_XML = `<?xml version="1.0"?><hierarchy><node text="Where to?" resource-id="com.ubercab:id/input" class="android.widget.TextView" content-desc="Destination" bounds="[12,100][400,180]" /></hierarchy>`;
+ const REPLIES: Array<[string, string | Buffer]> = [
+ ["devices -l", DEVICE_LIST],
+ ["uiautomator dump", `${SCREEN_XML}UI hierchary dumped to: /dev/tty\n`],
+ ["screencap", Buffer.from("89504e470d0a1a0a", "hex")],
+ ["query-activities", "1 activities found:\n com.ubercab/.presidio.RootActivity\n"],
+ ["wm size", "Physical size: 1080x1920\n"],
+ ];
+ const REFUSED = { ok: false as const, message: PERSON_TEXT };
+
+ function phone(...refusals: Array<typeof REFUSED | undefined>) {
+ const commands: string[][] = [];
+ const options: unknown[] = [];
+ const midCall: boolean[] = [];
+ let claims = 0;
+ const adb = async (args: string[], option?: unknown) => {
+ commands.push(args);
+ options.push(option);
+ const line = args.join(" ");
+ return Buffer.from(REPLIES.find(([part]) => line.includes(part))?.[1] ?? "");
+ };
+ const ensureClaim = async (inCall = false) => {
+ midCall.push(inCall);
+ return refusals[claims++] ?? { ok: true as const };
+ };
+ const call = (name: string, args: Record<string, unknown> = {}) => callPhoneTool(name, args, ensureClaim, adb);
+ return { commands, options, call, claims: () => claims, midCall };
+ }
+
+ /** adb for a phone whose `uiautomator dump /dev/tty` prints no XML, so the screen is read from a saved file. `saved` is what that file holds
+ * at first, `dump` what `uiautomator dump` writes to it and exits with, `left` what it holds afterwards; `duringRead` runs while the phone's
+ * shell runs the command line that names the file. */
+ function adbOfPhoneThatSavesItsDump({ duringRead = () => {}, saved, dump = { writes: SCREEN_XML, exit: 0 } }: { duringRead?: () => void; saved?: string; dump?: { writes?: string; exit: number } } = {}) {
+ const commands: string[][] = [];
+ let file = saved;
+ const adb = async (args: string[]) => {
+ commands.push(args);
+ const line = args.join(" ");
+ if (line.includes("devices -l")) return Buffer.from(DEVICE_LIST);
+ if (!line.includes(SAVED_DUMP)) return Buffer.from("");
+ duringRead();
+ let printed = "";
+ const run = (command: string) => {
+ if (command === `rm -f ${SAVED_DUMP}`) {
+ file = undefined;
+ return 0;
+ }
+ if (command === `uiautomator dump ${SAVED_DUMP} >/dev/null`) {
+ file = dump.writes ?? file;
+ return dump.exit;
+ }
+ if (command !== `cat ${SAVED_DUMP}`) throw new Error(`The fake phone cannot run: ${command}`);
+ printed += file ?? "";
+ return file === undefined ? 1 : 0;
+ };
+ let lastExit = 0;
+ let status = 0;
+ for (const statement of (args.at(-1) ?? "").split("; ")) {
+ if (statement === "status=$?") status = lastExit;
+ else if (statement !== "exit $status") lastExit = statement.split(" && ").reduce((exit, command) => exit || run(command), 0);
+ else if (status !== 0) throw new Error(`The phone's shell exited with ${status}.`);
+ }
+ return Buffer.from(printed);
+ };
+ return { commands, adb, left: () => file };
+ }
+
+ beforeEach(() => {
+ vi.stubEnv("OMB_ADB_PATH", process.execPath);
+ vi.stubEnv("PH_ANDROID_SERIAL", "");
+ });
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it.each([
+ ["status", {}, [], "\"serial\": \"USB123\""],
+ ["read_screen", {}, [DUMP], "0: \"Where to? · Destination\" bounds=12,100,400,180 class=android.widget.TextView"],
+ ["screenshot", {}, [onPhone("exec-out", "screencap", "-p")], "Android screenshot from USB123"],
+ ["list_apps", {}, [APPS], "com.ubercab"],
+ ["open_app", { name: "Uber" }, [APPS, onPhone("shell", "monkey", "-p", "com.ubercab", "-c", "android.intent.category.LAUNCHER", "1")], "Opened Uber (com.ubercab)"],
+ ["tap_text", { text: "Where to?" }, [DUMP, onPhone("shell", "input", "tap", "206", "140")], "Tapped \"Where to?\""],
+ ["tap", { x: 10, y: 20 }, [onPhone("shell", "input", "tap", "10", "20")], "Tapped 10,20"],
+ ["swipe", { direction: "up" }, [onPhone("shell", "wm", "size"), onPhone("shell", "input", "swipe", "540", "1440", "540", "480", "260")], "Swiped up"],
+ ["type_text", { text: "hi" }, [onPhone("shell", "input", "text", "hi")], "Typed text into the focused Android field"],
+ ["press", { key: "home" }, [onPhone("shell", "input", "keyevent", "KEYCODE_HOME")], "Pressed home"],
+ ])("%s sends its commands when every claim is granted", async (name, args, deviceCommands, text) => {
+ const { commands, call, claims } = phone();
+ const result = await call(name, args);
+ expect(result.isError).toBeUndefined();
+ expect(result.content[0]).toMatchObject({ type: "text", text: expect.stringContaining(text) });
+ expect(commands).toEqual([DEVICES, ...deviceCommands]);
+ expect(claims()).toBe(1 + deviceCommands.length);
+ });
+
+ it("only a call's first claim may wait for a person: each one before a command says it comes from the middle of the call", async () => {
+ const { call, midCall } = phone();
+ await call("tap_text", { text: "Where to?" });
+ expect(midCall).toEqual([false, true, true]);
+ });
+
+ it.each(["status", "tap"])("%s runs no adb command when the call is refused at its start", async (name) => {
+ const { commands, call } = phone(REFUSED);
+ expect(await call(name, { x: 10, y: 20 })).toEqual({ content: [{ type: "text", text: PERSON_TEXT }], isError: true });
+ expect(commands).toEqual([]);
+ });
+
+ it.each(["screenshot", "read_screen"])("%s sends nothing to the phone when a person takes it during the device list", async (name) => {
+ const { commands, call } = phone(undefined, REFUSED);
+ expect(await call(name)).toEqual({ content: [{ type: "text", text: PERSON_TEXT }], isError: true });
+ expect(commands).toEqual([DEVICES]);
+ });
+
+ it("tap_text does not tap when a person takes the phone during its screen read", async () => {
+ const { commands, call } = phone(undefined, undefined, REFUSED);
+ expect(await call("tap_text", { text: "Where to?" })).toEqual({ content: [{ type: "text", text: PERSON_TEXT }], isError: true });
+ expect(commands).toEqual([DEVICES, DUMP]);
+ });
+
+ it("screenshot asks adb for the screen capture as binary output", async () => {
+ const { commands, options, call } = phone();
+ await call("screenshot");
+ expect(commands[1]).toEqual(onPhone("exec-out", "screencap", "-p"));
+ expect(options[1]).toEqual({ binary: true });
+ });
+
+ it("read_screen has the phone save a dump to a file, print it and remove it in one command, under one claim", async () => {
+ const { commands, adb } = adbOfPhoneThatSavesItsDump();
+ let claims = 0;
+ const result = await callPhoneTool("read_screen", {}, async () => { claims += 1; return { ok: true }; }, adb);
+ expect(result).toEqual({ content: [{ type: "text", text: "0: \"Where to? · Destination\" bounds=12,100,400,180 class=android.widget.TextView" }] });
+ expect(commands).toEqual([DEVICES, DUMP, SAVE_READ_AND_REMOVE]);
+ expect(namingTheSavedDumpWithoutRemovingIt(commands)).toEqual([]);
+ expect(claims).toBe(3);
+ });
+
+ it("read_screen sends no command that leaves the saved dump on the phone when a person takes it during the read", async () => {
+ let taken = false;
+ const { commands, adb, left } = adbOfPhoneThatSavesItsDump({
+ duringRead: () => {
+ taken = true;
+ },
+ });
+ await callPhoneTool("read_screen", {}, async () => (taken ? REFUSED : { ok: true }), adb);
+ expect(commands.filter((command) => command.join(" ").includes(SAVED_DUMP))).toHaveLength(1);
+ expect(namingTheSavedDumpWithoutRemovingIt(commands)).toEqual([]);
+ expect(left()).toBeUndefined();
+ });
+
+ const NO_DUMP = { exit: 0 };
+ const PART_OF_A_DUMP = { writes: SCREEN_XML.slice(0, SCREEN_XML.indexOf("</hierarchy>")), exit: 1 };
+ it.each([
+ ["read_screen", "writes no dump, though it exits 0", NO_DUMP],
+ ["tap_text", "writes no dump, though it exits 0", NO_DUMP],
+ ["read_screen", "exits 1 after writing part of a dump", PART_OF_A_DUMP],
+ ["tap_text", "exits 1 after writing part of a dump", PART_OF_A_DUMP],
+ ])("%s fails, taps nothing and leaves no file when the phone %s, with an older saved dump still there", async (name, _what, dump) => {
+ const older = SCREEN_XML.replace("[12,100][400,180]", "[12,900][400,980]");
+ const { commands, adb, left } = adbOfPhoneThatSavesItsDump({ saved: older, dump });
+ const result = await callPhoneTool(name, { text: "Where to?" }, async () => ({ ok: true }), adb);
+ expect(result.isError).toBe(true);
+ expect(commands.filter((command) => command.includes("input"))).toEqual([]);
+ expect(left()).toBeUndefined();
+ });
+
+ it("tap_text does not tap when a person takes the phone and hands it back while the saved dump is read", async () => {
+ const resources = new TurnResources();
+ const hold = createPhoneHold({ onChange: (held) => gate.holdChanged(held) });
+ const gate = createPhoneGate({ enabled: () => true, hold, resources, claim: (owner, resource) => resources.claim(resource, owner) });
+ const turn = { threadId: "a", generation: "1" };
+ const harness = (async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
+ const request = new Request(input, init);
+ let answer = new Response(null, { status: 404 });
+ await gate.internal({
+ method: request.method, path: new URL(request.url).pathname, res: {} as never, turn, signal: request.signal,
+ json: (_res, status, body) => { answer = new Response(JSON.stringify(body), { status }); },
+ requireActive: () => {},
+ readBody: () => request.json(),
+ });
+ return answer;
+ }) as typeof fetch;
+ const { commands, adb } = adbOfPhoneThatSavesItsDump({
+ duringRead: () => {
+ hold.take();
+ hold.release();
+ },
+ });
+
+ const result = await callPhoneTool("tap_text", { text: "Where to?" }, createPhoneClaim({ OMB_HARNESS_URL: "http://127.0.0.1:8799", OMB_PHONE_TOKEN: "tok" }, harness), adb);
+
+ expect(result).toEqual({ content: [{ type: "text", text: HANDED_BACK_TEXT }], isError: true });
+ expect(commands.filter((command) => command.includes("input"))).toEqual([]);
+ hold.stop();
+ });
+});
diff --git a/server/drivers/phone-proxy.ts b/server/drivers/phone-proxy.ts
index 12157f8340..b9fa17ad74 100644
--- a/server/drivers/phone-proxy.ts
+++ b/server/drivers/phone-proxy.ts
@@ -5,13 +5,27 @@ import { createInterface } from "node:readline";
import { delimiter, join } from "node:path";
import { homedir } from "node:os";
+import { CONTROL_ACT_WITHIN_MS, CONTROL_WAIT_MS } from "../control-client.ts";
+
type Json = Record<string, unknown>;
type Device = { serial: string; state: string; model: string; connection: "usb" | "network" | "emulator" };
type UiNode = { text: string; description: string; id: string; className: string; bounds: [number, number, number, number] };
type ClaimOutcome = { ok: true } | { ok: false; message: string };
+/** `midCall`: the call has already claimed the phone once, so it has no time left to wait for a person to hand it back. */
+type EnsureClaim = (midCall?: boolean) => Promise<ClaimOutcome>;
+type Adb = typeof runAdb;
+type OnDevice = (serial: string, args: string[], binary?: boolean) => Promise<Buffer>;
const MAX_ADB_OUTPUT = 16 * 1024 * 1024;
const PHONE_BUSY_TEXT = "Another thread is using the phone. This call was not performed. Pause phone work until that thread finishes, then read the screen again before acting.";
+const PHONE_PERSON_TEXT = "A person has taken control of the phone, so this call was NOT performed. Do not act until they hand it back. " +
+ `To wait, call read_screen: each phone call waits up to ${CONTROL_WAIT_MS / 1000} seconds and returns as soon as they hand the phone back. ` +
+ "Meanwhile you may work on anything that does not need the phone.";
+const PHONE_HANDED_BACK_TEXT = "The person has handed the phone back. This call was NOT performed: the screen may have changed. Call read_screen, then continue the task.";
+const PHONE_WAITED_TEXT = "The phone is free now, but this call had to wait for it, so it was NOT performed. " +
+ "Call again: the next call goes through at once. If you meant to tap or type from an earlier read_screen, call read_screen again first: the screen may have changed while you waited.";
+/** Past the harness's longest answer, so a claim it still legitimately holds is never cut off. */
+const CLAIM_TIMEOUT_MS = CONTROL_WAIT_MS + 10_000;
const PACKAGE = /^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)+$/;
const COMPONENT = /^([A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)+)\/\S+$/;
const SAFE_TEXT = /^[A-Za-z0-9 _.,@-]+$/;
@@ -120,13 +134,13 @@ export function parseDevices(output: string): Device[] {
return devices;
}
-async function usbDevices() {
+async function usbDevices(adb: Adb) {
if (!resolveAdbPath()) return [];
- return parseDevices((await runAdb(["devices", "-l"])).toString("utf8")).filter((device) => device.connection === "usb");
+ return parseDevices((await adb(["devices", "-l"])).toString("utf8")).filter((device) => device.connection === "usb");
}
-async function readySerial(requested?: unknown): Promise<string> {
- const devices = await usbDevices();
+async function readySerial(adb: Adb, requested?: unknown): Promise<string> {
+ const devices = await usbDevices(adb);
const serial = typeof requested === "string" && requested ? requested : process.env.PH_ANDROID_SERIAL;
const candidates = serial ? devices.filter((device) => device.serial === serial) : devices;
if (!candidates.length) throw new Error("No physical USB Android device is connected");
@@ -137,12 +151,15 @@ async function readySerial(requested?: unknown): Promise<string> {
return device.serial;
}
-async function onDevice(serial: string, args: string[], binary = false) {
- return runAdb(["-s", serial, ...args], { binary });
-}
+// A call runs several commands and a person may take the phone between two of them, so each one asks again.
+const claimedDevice = (ensureClaim: EnsureClaim, adb: Adb): OnDevice => async (serial, args, binary = false) => {
+ const claim = await ensureClaim(true);
+ if (!claim.ok) throw new Error(claim.message);
+ return adb(["-s", serial, ...args], { binary });
+};
type Shell = (...command: string[]) => Promise<string>;
-const deviceShell = (serial: string): Shell => async (...command) => (await onDevice(serial, ["shell", ...command])).toString("utf8");
+const deviceShell = (onDevice: OnDevice, serial: string): Shell => async (...command) => (await onDevice(serial, ["shell", ...command])).toString("utf8");
export async function typePhoneText(shell: Shell, text: string): Promise<string> {
if (!text || [...text].length > 256) throw new Error("Android text must be 1 to 256 characters");
@@ -199,7 +216,7 @@ export function launchTarget(name: string, packages: string[]) {
: `No installed launchable app matches ${JSON.stringify(name)}. open_app knows English names and package names; call list_apps without a query and pass the package name.`);
}
-async function launchablePackages(serial: string) {
+async function launchablePackages(onDevice: OnDevice, serial: string) {
const output = await onDevice(serial, [
"shell", "cmd", "package", "query-activities", "--brief",
"-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER",
@@ -239,15 +256,13 @@ export function parseUiNodes(xml: string): UiNode[] {
return nodes;
}
-async function readNodes(serial: string) {
+async function readNodes(onDevice: OnDevice, serial: string) {
const streamed = (await onDevice(serial, ["shell", "uiautomator", "dump", "/dev/tty"])).toString("utf8");
const streamedStart = streamed.indexOf("<?xml");
if (streamedStart >= 0) return parseUiNodes(streamed.slice(streamedStart));
const remotePath = "/data/local/tmp/openmaus-window.xml";
- await onDevice(serial, ["shell", "uiautomator", "dump", remotePath]);
- const saved = (await onDevice(serial, ["shell", "cat", remotePath])).toString("utf8");
- void onDevice(serial, ["shell", "rm", "-f", remotePath]).catch(() => undefined);
+ const saved = (await onDevice(serial, ["shell", `rm -f ${remotePath}; uiautomator dump ${remotePath} >/dev/null && cat ${remotePath}; status=$?; rm -f ${remotePath}; exit $status`])).toString("utf8");
const savedStart = saved.indexOf("<?xml");
return parseUiNodes(savedStart >= 0 ? saved.slice(savedStart) : saved);
}
@@ -280,23 +295,29 @@ const textResult = (text: string, isError = false): ToolResult => ({ content: [{
export function createPhoneClaim(
env: NodeJS.ProcessEnv = process.env,
fetchImpl: typeof fetch = fetch,
-): () => Promise<ClaimOutcome> {
+): EnsureClaim {
const url = env.OMB_HARNESS_URL?.trim();
const token = env.OMB_PHONE_TOKEN?.trim();
if (!url || !token) {
return async () => ({ ok: true });
}
- return async () => {
+ return async (midCall = false) => {
try {
+ const asked = Date.now();
const response = await fetchImpl(new URL("/api/internal/phone/claim", url), {
method: "POST",
redirect: "error",
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
- body: "{}",
- signal: AbortSignal.timeout(10_000),
+ body: midCall ? '{"wait":false}' : "{}",
+ signal: AbortSignal.timeout(CLAIM_TIMEOUT_MS),
});
- if (response.ok) return { ok: true };
+ if (response.ok) return Date.now() - asked > CONTROL_ACT_WITHIN_MS ? { ok: false, message: PHONE_WAITED_TEXT } : { ok: true };
if (response.status === 409) return { ok: false, message: PHONE_BUSY_TEXT };
+ if (response.status === 423) {
+ const reason = ((await response.json().catch(() => null)) as { reason?: unknown } | null)?.reason;
+ if (reason === "person") return { ok: false, message: PHONE_PERSON_TEXT };
+ if (reason === "handed-back") return { ok: false, message: PHONE_HANDED_BACK_TEXT };
+ }
if (response.status === 401 || response.status === 403) {
return { ok: false, message: "This turn no longer has phone access. Start a new turn to use the phone." };
}
@@ -307,28 +328,28 @@ export function createPhoneClaim(
};
}
-async function callTool(name: string, args: Json): Promise<ToolResult> {
+async function callTool(name: string, args: Json, adb: Adb, onDevice: OnDevice): Promise<ToolResult> {
if (name === "status") {
- const adb = resolveAdbPath();
- const devices = adb ? await usbDevices() : [];
- return textResult(JSON.stringify({ available: Boolean(adb), devices }, null, 2));
+ const available = Boolean(resolveAdbPath());
+ const devices = available ? await usbDevices(adb) : [];
+ return textResult(JSON.stringify({ available, devices }, null, 2));
}
- const serial = await readySerial(args.serial);
- if (name === "read_screen") return textResult(nodeLines(await readNodes(serial)));
+ const serial = await readySerial(adb, args.serial);
+ if (name === "read_screen") return textResult(nodeLines(await readNodes(onDevice, serial)));
if (name === "screenshot") {
const png = await onDevice(serial, ["exec-out", "screencap", "-p"], true);
if (!png.subarray(0, 8).equals(Buffer.from("89504e470d0a1a0a", "hex"))) throw new Error("Android returned an invalid screenshot");
return { content: [{ type: "text", text: `Android screenshot from ${serial}` }, { type: "image", data: png.toString("base64"), mimeType: "image/png" }] };
}
if (name === "list_apps") {
- const packages = await launchablePackages(serial);
+ const packages = await launchablePackages(onDevice, serial);
const query = typeof args.query === "string" ? args.query : "";
return textResult((query ? findPackages(query, packages) : packages).join("\n") || "No matching launchable app found");
}
if (name === "open_app") {
const appName = String(args.name ?? "").trim();
if (!appName) throw new Error("name is required");
- const target = launchTarget(appName, await launchablePackages(serial));
+ const target = launchTarget(appName, await launchablePackages(onDevice, serial));
await onDevice(serial, ["shell", "monkey", "-p", target, "-c", "android.intent.category.LAUNCHER", "1"]);
return textResult(`Opened ${appName} (${target})`);
}
@@ -336,7 +357,7 @@ async function callTool(name: string, args: Json): Promise<ToolResult> {
const query = String(args.text ?? "").trim().toLowerCase();
if (!query) throw new Error("text is required");
const exact = args.exact === true;
- const hits = (await readNodes(serial)).filter((node) => {
+ const hits = (await readNodes(onDevice, serial)).filter((node) => {
const labels = [node.text, node.description].filter(Boolean).map((value) => value.toLowerCase());
return labels.some((label) => exact ? label === query : label.includes(query));
});
@@ -370,7 +391,7 @@ async function callTool(name: string, args: Json): Promise<ToolResult> {
await onDevice(serial, ["shell", "input", "swipe", ...point.map((value) => String(Math.round(value))), "260"]);
return textResult(`Swiped ${direction}`);
}
- if (name === "type_text") return textResult(await typePhoneText(deviceShell(serial), String(args.text ?? "")));
+ if (name === "type_text") return textResult(await typePhoneText(deviceShell(onDevice, serial), String(args.text ?? "")));
if (name === "press") {
const key = String(args.key ?? "").toLowerCase();
if (!KEYCODES[key]) throw new Error("Unsupported Android key");
@@ -380,11 +401,21 @@ async function callTool(name: string, args: Json): Promise<ToolResult> {
throw new Error(`Unknown phone tool: ${name}`);
}
+export async function callPhoneTool(name: string, args: Json, ensureClaim: EnsureClaim, adb: Adb = runAdb): Promise<ToolResult> {
+ const claim = await ensureClaim();
+ if (!claim.ok) return textResult(claim.message, true);
+ try {
+ return await callTool(name, args, adb, claimedDevice(ensureClaim, adb));
+ } catch (error) {
+ return textResult(error instanceof Error ? error.message : String(error), true);
+ }
+}
+
const send = (message: Json) => process.stdout.write(`${JSON.stringify(message)}\n`);
const ok = (id: unknown, result: unknown) => send({ jsonrpc: "2.0", id, result });
const rpcError = (id: unknown, code: number, message: string) => send({ jsonrpc: "2.0", id, error: { code, message } });
-async function handle(message: Json, ensureClaim: () => Promise<ClaimOutcome>) {
+async function handle(message: Json, ensureClaim: EnsureClaim) {
const id = message.id;
const method = message.method;
const params = (message.params ?? {}) as Json;
@@ -395,13 +426,7 @@ async function handle(message: Json, ensureClaim: () => Promise<ClaimOutcome>) {
if (method === "tools/call") {
const name = String(params.name ?? "");
if (!TOOLS.some((tool) => tool.name === name)) return rpcError(id, -32602, `Unknown tool: ${name}`);
- const claim = await ensureClaim();
- if (!claim.ok) return ok(id, textResult(claim.message, true));
- try {
- return ok(id, await callTool(name, (params.arguments ?? {}) as Json));
- } catch (error) {
- return ok(id, textResult(error instanceof Error ? error.message : String(error), true));
- }
+ return ok(id, await callPhoneTool(name, (params.arguments ?? {}) as Json, ensureClaim));
}
if (id !== undefined) rpcError(id, -32601, `Method not found: ${String(method)}`);
}
diff --git a/server/index.ts b/server/index.ts
index f8906fd387..fadfcebf77 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -334,6 +334,8 @@ import { callTitleExcerpt } from "./thread-title.ts";
import { generateThreadTitle, llmThreadTitlesEnabled } from "./thread-title-generate.ts";
import { engineProcessGone, stallLimitMs, TurnWatchdog } from "./turn-watchdog.ts"; import { createIdleThreads } from "./host/idle-threads.ts";
import { TurnResources, type TurnOwner } from "./turn-resources.ts";
+import { createPhoneHold } from "./phone-screen/hold.ts"; import { createPhoneGate } from "./routes/phone-gate.ts";
+import { endHoldUnlessOn, usbPhoneOffered, usbPhoneTakeoverEnabled } from "./phone-screen/flag.ts";
import {
ensureWorkspace,
workspaceLocationsPrompt,
@@ -490,7 +492,7 @@ import {
mergeSkills,
renderSkillInstructions,
selectBundledSkills,
- skillsLibraryEnabled, readSkillLibraryIndex, type BundledSkill,
+ skillsLibraryEnabled, readSkillLibraryIndex,
} from "./skill-library.ts";
import { runSkillsLibraryBootSweep } from "./skills-library-migration.ts";
import { installedPlaybookInstructions } from "./installed-playbooks.ts";
@@ -1410,9 +1412,7 @@ const firstEngineRead = holdUntilFirstEngineRead();
await registry.load(providerConfigs(), decorateHostedProvider);
const bundledSkills = loadBundledSkills();
const availableSkills = () => mergeSkills(bundledSkills, loadUserSkills(join(DATA_DIR, "skills")));
-/** Every turn the engine can mount it, whatever its words: they pick only the skill's instructions. A Cloud home or a hosted workspace has no USB port. */
-const usbPhoneOffered = (instance: { adapter: { capabilities: { phoneMcp?: boolean } } }, skills: readonly BundledSkill[]) => instance.adapter.capabilities.phoneMcp === true &&
- !CLOUD_HOME && !HOSTED_WORKSPACE && skills.some(({ manifest }) => manifest.defaultEnabled && manifest.requiredCapabilities.includes("phoneMcp"));
+const HAS_USB_PORT = !CLOUD_HOME && !HOSTED_WORKSPACE, usbPhoneTakeoverOn = () => HAS_USB_PORT && usbPhoneTakeoverEnabled(cfg); // A Cloud home or a hosted workspace has no USB port.
type UtilityParentPort = {
on(event: "message", listener: (event: { data?: object }) => void): void;
@@ -2079,6 +2079,8 @@ const turnPromptBytes = new Map<string, { stable: number; volatile: number }>();
let providerFleetReloading = false;
const turnResources = new TurnResources(); engineMemory.useTurnOrder(createTurnOrder({ turn: (threadId) => directRequestOwners.get(threadId), unattended: (threadId) => isUnattended(store.botByThread(threadId)?.id, threadId), running: (threadId) => coordinator.runningIn(threadId), roomLine: (threadId) => [...(groupTurnOperations.get(store.groupByThread(threadId)?.id ?? "") ?? [])].some((operation) => operation.threadId === threadId && operation.requestMessageId !== undefined) })); const waitWords = createWaitWords({ language: (threadId) => threadLanguage(threadId), starter: () => cloudPlanTier.starter(), held: (threadId, why) => coordinator.held(threadId, why), changed: () => broadcast({ kind: "config", ...configStatus() }) }); engineMemory.useWaits(waitWords);
const sharedComputerControl = new SharedComputerControl(turnResources, (owner) => store.botByThread(owner.threadId)?.name);
+const phoneHold = createPhoneHold({ onChange: (held) => phoneGate.holdChanged(held) });
+const phoneGate = createPhoneGate({ enabled: usbPhoneTakeoverOn, hold: phoneHold, resources: turnResources, claim: claimTurnResource }); onConfigSaved((_before, after) => endHoldUnlessOn(phoneHold, after));
const turnResourceOwners = new Map<string, TurnOwner>();
const turnComputerResources = new Map<string, { owner: TurnOwner; resource: string }>();
const teamComputerTurns = new Map<string, { owner: TurnOwner; computerId: string; botId: string }>();
@@ -7892,7 +7894,7 @@ async function beginTurn(
const integrations: NonNullable<Parameters<typeof instance.adapter.sendTurn>[0]["integrations"]> = {};
let browser: Awaited<ReturnType<typeof browserIntegration>> = null;
- const skills = availableSkills(), phoneOffered = usbPhoneOffered(instance, skills) && !proactive.fence.confines(threadId) && !botApiThread(threadId);
+ const skills = availableSkills(), phoneOffered = HAS_USB_PORT && usbPhoneOffered(instance, skills) && !proactive.fence.confines(threadId) && !botApiThread(threadId);
const selectedSkills = selectBundledSkills(
providerText,
[
@@ -9795,7 +9797,7 @@ async function runClaimedGroupMemberTurn(
);
const roomContext = roomWindow.text;
const turnImages = usesNativeImageInput ? [...burstImages, ...resolvedLatestImages.images, ...await videoFramesWithin(burstImages.length + resolvedLatestImages.images.length, resolvedLatestImages.videos)] : [];
- const skills = availableSkills(), phoneOffered = usbPhoneOffered(instance, skills);
+ const skills = availableSkills(), phoneOffered = HAS_USB_PORT && usbPhoneOffered(instance, skills);
const selectedSkills = mergeSkills(
selectBundledSkills(
roomContext,
@@ -13181,13 +13183,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
if (method === "POST" && path === PHONE_INTERNAL_MCP_PATH) {
return json(res, 200, { result: await phones.handle(await readInternalBody(), internalCapability, requireActiveInternalCapability) });
}
- if (method === "POST" && path === "/api/internal/phone/claim") {
- requireActiveInternalCapability();
- if (!claimTurnResource(internalCapability, "computer:phone")) {
- return json(res, 409, { error: "another thread is using the phone" });
- }
- return json(res, 200, { claimed: true });
- }
+ if (await phoneGate.internal({ method, path, res, json, turn: internalCapability, requireActive: requireActiveInternalCapability, readBody: readInternalBody, signal: callSignal }) !== PASS) return;
// Off: a 404 like a route that never existed. On: a turn sees only the computers of the person it provably acts for.
if (method === "GET" && path === "/api/internal/shared-computers" && botLending()) {
const principal = sharedComputerPrincipal(internalCapability); await sharedComputers.settledAfterWake(principal, () => internalCapabilityIsActive(internalCapability));
diff --git a/server/phone-screen/flag.test.ts b/server/phone-screen/flag.test.ts
new file mode 100644
index 0000000000..2b169183bc
--- /dev/null
+++ b/server/phone-screen/flag.test.ts
@@ -0,0 +1,63 @@
+import { afterEach, describe, expect, it } from "vitest";
+
+import type { BundledSkill } from "../skill-library.ts";
+import { endHoldUnlessOn, usbPhoneOffered, usbPhoneTakeoverEnabled } from "./flag.ts";
+import { createPhoneHold, type PhoneHold } from "./hold.ts";
+
+const skill = (defaultEnabled: boolean, ...requiredCapabilities: string[]) => ({ manifest: { defaultEnabled, requiredCapabilities } }) as unknown as BundledSkill;
+const engine = (phoneMcp?: boolean) => ({ adapter: { capabilities: { phoneMcp } } });
+const ON = { features: { usbPhoneTakeover: true } };
+
+describe("usbPhoneTakeoverEnabled", () => {
+ it.each([
+ [{}, false],
+ [{ features: {} }, false],
+ [{ features: null }, false],
+ [{ features: { usbPhoneTakeover: false } }, false],
+ [{ features: { usbPhoneTakeover: "true" } }, false],
+ [ON, true],
+ ])("%j → %s", (cfg, on) => {
+ expect(usbPhoneTakeoverEnabled(cfg)).toBe(on);
+ });
+});
+
+describe("usbPhoneOffered", () => {
+ it.each([
+ ["an engine that mounts the phone and a default-on phone skill", engine(true), [skill(true, "phoneMcp")], true],
+ ["an engine that cannot mount the phone", engine(), [skill(true, "phoneMcp")], false],
+ ["a phone skill that is off by default", engine(true), [skill(false, "phoneMcp")], false],
+ ["no phone skill", engine(true), [skill(true, "computerMcp")], false],
+ ])("%s → %s", (_what, instance, skills, offered) => {
+ expect(usbPhoneOffered(instance, skills)).toBe(offered);
+ });
+});
+
+describe("a saved config while a person holds the phone and no stream is open", () => {
+ let hold: PhoneHold;
+ const heldUnwatched = () => {
+ hold = createPhoneHold();
+ hold.take();
+ hold.watched(false);
+ return hold;
+ };
+ afterEach(() => hold.stop());
+
+ it.each([
+ ["turns the feature off", { features: { usbPhoneTakeover: false, browser: true } }],
+ ["has no features", {}],
+ ])("ends the hold at once and answers a waiting claim when it %s; the phone is free when the feature is on again", async (_what, saved) => {
+ const waiting = heldUnwatched().wait(new AbortController().signal, 45_000);
+
+ endHoldUnlessOn(hold, saved);
+ expect(hold.held).toBe(false);
+ await expect(waiting).resolves.toBe("handed-back");
+
+ endHoldUnlessOn(hold, ON);
+ expect(hold.held).toBe(false);
+ });
+
+ it("keeps the hold when it leaves the feature on", () => {
+ endHoldUnlessOn(heldUnwatched(), { features: { usbPhoneTakeover: true, browser: false } });
+ expect(hold.held).toBe(true);
+ });
+});
diff --git a/server/phone-screen/flag.ts b/server/phone-screen/flag.ts
new file mode 100644
index 0000000000..93366bf88e
--- /dev/null
+++ b/server/phone-screen/flag.ts
@@ -0,0 +1,18 @@
+import type { BundledSkill } from "../skill-library.ts";
+import type { PhoneHold } from "./hold.ts";
+
+/** `features.usbPhoneTakeover`: a person watches and takes over the bots' USB phone. Off unless true. */
+export function usbPhoneTakeoverEnabled({ features }: { features?: unknown }): boolean {
+ return typeof features === "object" && features !== null && "usbPhoneTakeover" in features && features.usbPhoneTakeover === true;
+}
+
+/** For `onConfigSaved`: a hold must not outlive the feature, and with no stream open nothing else notices it going off. */
+export function endHoldUnlessOn(hold: Pick<PhoneHold, "release">, saved: { features?: unknown }): void {
+ if (!usbPhoneTakeoverEnabled(saved)) hold.release();
+}
+
+/** Every turn the engine can mount it, whatever its words: they pick only the skill's instructions. */
+export function usbPhoneOffered(instance: { adapter: { capabilities: { phoneMcp?: boolean } } }, skills: readonly BundledSkill[]): boolean {
+ return instance.adapter.capabilities.phoneMcp === true &&
+ skills.some(({ manifest }) => manifest.defaultEnabled && manifest.requiredCapabilities.includes("phoneMcp"));
+}
diff --git a/server/phone-screen/hold.test.ts b/server/phone-screen/hold.test.ts
new file mode 100644
index 0000000000..d0cdc864fb
--- /dev/null
+++ b/server/phone-screen/hold.test.ts
@@ -0,0 +1,176 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createPhoneHold } from "./hold.ts";
+
+const SECOND = 1000;
+const MINUTE = 60 * SECOND;
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("a person's hold on the phone", () => {
+ it("starts when taken and ends when released", () => {
+ const hold = createPhoneHold();
+ expect(hold.held).toBe(false);
+ hold.take();
+ expect(hold.held).toBe(true);
+ hold.release();
+ expect(hold.held).toBe(false);
+ });
+
+ it("ends after 5 minutes without input", () => {
+ const hold = createPhoneHold();
+ hold.take();
+ vi.advanceTimersByTime(5 * MINUTE - 1);
+ expect(hold.held).toBe(true);
+ vi.advanceTimersByTime(1);
+ expect(hold.held).toBe(false);
+ });
+
+ it.each(["used", "take"] as const)("counts the 5 minutes again from each input (%s)", (input) => {
+ const hold = createPhoneHold();
+ hold.take();
+ vi.advanceTimersByTime(100 * SECOND);
+ hold[input]();
+ vi.advanceTimersByTime(5 * MINUTE - 1);
+ expect(hold.held).toBe(true);
+ vi.advanceTimersByTime(1);
+ expect(hold.held).toBe(false);
+ });
+
+ it("stays when every view closed for 1 minute 59 seconds and one came back", () => {
+ const hold = createPhoneHold();
+ hold.take();
+ hold.watched(false);
+ vi.advanceTimersByTime(119 * SECOND);
+ hold.watched(true);
+ vi.advanceTimersByTime(2 * MINUTE);
+ expect(hold.held).toBe(true);
+ });
+
+ it("ends when every view has been closed for 2 minutes", () => {
+ const hold = createPhoneHold();
+ hold.take();
+ hold.watched(false);
+ vi.advanceTimersByTime(2 * MINUTE - 1);
+ expect(hold.held).toBe(true);
+ vi.advanceTimersByTime(1);
+ expect(hold.held).toBe(false);
+ });
+
+ it("ends at 300 s when the last input was at 0 s and the views closed from 290 s to 409 s", () => {
+ const hold = createPhoneHold();
+ hold.take();
+ vi.advanceTimersByTime(290 * SECOND);
+ hold.watched(false);
+ vi.advanceTimersByTime(10 * SECOND - 1);
+ expect(hold.held).toBe(true);
+ vi.advanceTimersByTime(1);
+ expect(hold.held).toBe(false);
+ vi.advanceTimersByTime(109 * SECOND);
+ hold.watched(true);
+ expect(hold.held).toBe(false);
+ });
+
+ it("gives a hold taken while no view is open the 2 minutes for one to open", () => {
+ const hold = createPhoneHold();
+ hold.watched(false);
+ hold.take();
+ vi.advanceTimersByTime(2 * MINUTE);
+ expect(hold.held).toBe(false);
+ });
+
+ it("gives a hold taken 1 minute 50 seconds after the last view closed 2 minutes of its own", () => {
+ const hold = createPhoneHold();
+ hold.watched(false);
+ vi.advanceTimersByTime(110 * SECOND);
+ hold.take();
+ vi.advanceTimersByTime(11 * SECOND);
+ expect(hold.held).toBe(true);
+ });
+
+ it("does not start on input alone", () => {
+ const changes: boolean[] = [];
+ const hold = createPhoneHold({ onChange: (held) => changes.push(held) });
+ hold.used();
+ expect([hold.held, changes, vi.getTimerCount()]).toEqual([false, [], 0]);
+ });
+
+ it("uses the limits it is given", () => {
+ const hold = createPhoneHold({ limits: { idleMs: 2 * SECOND, graceMs: SECOND } });
+ hold.take();
+ vi.advanceTimersByTime(2 * SECOND);
+ expect(hold.held).toBe(false);
+ });
+
+ it("reports each start and each end once", () => {
+ const changes: boolean[] = [];
+ const hold = createPhoneHold({ onChange: (held) => changes.push(held) });
+ hold.take();
+ hold.take();
+ hold.release();
+ hold.release();
+ expect(changes).toEqual([true, false]);
+ hold.take();
+ vi.advanceTimersByTime(5 * MINUTE);
+ expect(changes).toEqual([true, false, true, false]);
+ });
+
+ it("leaves no timer running after stop", async () => {
+ const hold = createPhoneHold();
+ hold.take();
+ hold.watched(false);
+ const waiting = hold.wait(new AbortController().signal, 45 * SECOND);
+ hold.stop();
+ expect(vi.getTimerCount()).toBe(0);
+ await expect(waiting).resolves.toBe("held");
+ });
+});
+
+describe("waiting for the phone", () => {
+ it("answers free at once when nobody holds it", async () => {
+ const hold = createPhoneHold();
+ await expect(hold.wait(new AbortController().signal, 45 * SECOND)).resolves.toBe("free");
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it("answers handed-back as soon as the hold ends", async () => {
+ const hold = createPhoneHold();
+ hold.take();
+ const answered = vi.fn();
+ const waiting = hold.wait(new AbortController().signal, 45 * SECOND).then((outcome) => { answered(); return outcome; });
+ await vi.advanceTimersByTimeAsync(10 * SECOND);
+ expect(answered).not.toHaveBeenCalled();
+ hold.release();
+ await expect(waiting).resolves.toBe("handed-back");
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it("answers held when the longest wait passes", async () => {
+ const hold = createPhoneHold();
+ hold.take();
+ const answered = vi.fn();
+ const waiting = hold.wait(new AbortController().signal, 45 * SECOND).then((outcome) => { answered(); return outcome; });
+ await vi.advanceTimersByTimeAsync(45 * SECOND - 1);
+ expect(answered).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ await expect(waiting).resolves.toBe("held");
+ expect(hold.held).toBe(true);
+ });
+
+ it.each(["before", "during"] as const)("answers held when the caller is gone %s the wait", async (when) => {
+ const hold = createPhoneHold();
+ hold.take();
+ const caller = new AbortController();
+ if (when === "before") caller.abort();
+ const waiting = hold.wait(caller.signal, 45 * SECOND);
+ caller.abort();
+ await expect(waiting).resolves.toBe("held");
+ hold.release();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});
diff --git a/server/phone-screen/hold.ts b/server/phone-screen/hold.ts
new file mode 100644
index 0000000000..f484b3aa2c
--- /dev/null
+++ b/server/phone-screen/hold.ts
@@ -0,0 +1,77 @@
+import { HoldClock, type HoldLimits } from "../browser/hold.ts";
+
+export type PhoneHoldWait = "free" | "held" | "handed-back";
+
+export interface PhoneHold {
+ readonly held: boolean;
+ take(): void;
+ release(): void;
+ /** The holder sent input. */
+ used(): void;
+ /** Whether any stream of the phone is open. */
+ watched(open: boolean): void;
+ /** `"handed-back"` once the hold ends; `"held"` when `maxMs` passes or `signal` aborts first. */
+ wait(signal: AbortSignal, maxMs: number): Promise<PhoneHoldWait>;
+ stop(): void;
+}
+
+/** A person's hold on the bots' USB phone: one for every phone and every admin, as the bots share one claim on it. */
+export function createPhoneHold(options: { limits?: HoldLimits; onChange?: (held: boolean) => void } = {}): PhoneHold {
+ let held = false;
+ let unwatched = false;
+ const waiting = new Set<(outcome: PhoneHoldWait) => void>();
+ const settleWaits = (outcome: PhoneHoldWait) => {
+ for (const settle of waiting) settle(outcome);
+ };
+ const release = () => {
+ if (!held) return;
+ held = false;
+ clock.stop();
+ settleWaits("handed-back");
+ options.onChange?.(false);
+ };
+ const clock = new HoldClock(release, options.limits);
+
+ return {
+ get held() {
+ return held;
+ },
+ take() {
+ if (!held) {
+ held = true;
+ clock.watched(!unwatched);
+ options.onChange?.(true);
+ }
+ clock.used();
+ },
+ release,
+ used() {
+ if (held) clock.used();
+ },
+ watched(open) {
+ unwatched = !open;
+ if (held) clock.watched(open);
+ },
+ wait(signal, maxMs) {
+ if (!held) return Promise.resolve("free");
+ if (signal.aborted) return Promise.resolve("held");
+ return new Promise((resolve) => {
+ const settle = (outcome: PhoneHoldWait) => {
+ clearTimeout(timer);
+ signal.removeEventListener("abort", stillHeld);
+ waiting.delete(settle);
+ resolve(outcome);
+ };
+ const stillHeld = () => settle("held");
+ const timer = setTimeout(stillHeld, maxMs);
+ timer.unref?.();
+ signal.addEventListener("abort", stillHeld, { once: true });
+ waiting.add(settle);
+ });
+ },
+ stop() {
+ clock.stop();
+ settleWaits("held");
+ },
+ };
+}
diff --git a/server/routes/phone-gate.test.ts b/server/routes/phone-gate.test.ts
new file mode 100644
index 0000000000..f8fb3e0f18
--- /dev/null
+++ b/server/routes/phone-gate.test.ts
@@ -0,0 +1,238 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createPhoneHold } from "../phone-screen/hold.ts";
+import { TurnResources, type TurnOwner } from "../turn-resources.ts";
+import { createPhoneGate } from "./phone-gate.ts";
+import { PASS } from "./table.ts";
+
+const PHONE = "computer:phone";
+const SECOND = 1000;
+const CLAIMED = { status: 200, body: { claimed: true } };
+const BUSY = { status: 409, body: { error: "another thread is using the phone" } };
+const PERSON = { status: 423, body: { reason: "person" } };
+const HANDED_BACK = { status: 423, body: { reason: "handed-back" } };
+const TURN_ENDED = Object.assign(new Error("turn ended"), { status: 401 });
+const MID_CALL = { wait: false };
+
+const turn = (threadId: string, generation = "1"): TurnOwner => ({ threadId, generation });
+
+function phone(enabled = true) {
+ const resources = new TurnResources();
+ const hold = createPhoneHold({ onChange: (held) => gate.holdChanged(held) });
+ const gate = createPhoneGate({ enabled: () => enabled, hold, resources, claim: (owner, resource) => resources.claim(resource, owner) });
+ const request = async (owner: TurnOwner, options: { method?: string; path?: string; signal?: AbortSignal; active?: () => boolean; body?: unknown } = {}) => {
+ const json = vi.fn();
+ const outcome = await gate.internal({
+ method: options.method ?? "POST", path: options.path ?? "/api/internal/phone/claim", res: {} as never, json, turn: owner,
+ signal: options.signal ?? new AbortController().signal,
+ requireActive: () => { if (options.active && !options.active()) throw TURN_ENDED; },
+ readBody: async () => options.body ?? {},
+ });
+ if (outcome === PASS) return PASS;
+ const [, status, body] = json.mock.calls[0] ?? [];
+ return { status, body };
+ };
+ return { resources, hold, claim: request };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("the phone claim while no person holds the phone", () => {
+ it("claims the phone for the turn", async () => {
+ const { resources, claim } = phone();
+ const a = turn("a");
+ expect(await claim(a)).toEqual(CLAIMED);
+ expect(resources.holder(PHONE)).toBe(a);
+ });
+
+ it("refuses while another thread's turn has the phone", async () => {
+ const { resources, claim } = phone();
+ const b = turn("b");
+ expect(await claim(b)).toEqual(CLAIMED);
+ expect(await claim(turn("a"))).toEqual(BUSY);
+ expect(resources.holder(PHONE)).toBe(b);
+ });
+
+ it("refuses a turn that has ended", async () => {
+ const { resources, claim } = phone();
+ await expect(claim(turn("a"), { active: () => false })).rejects.toBe(TURN_ENDED);
+ expect(resources.free(PHONE)).toBe(true);
+ });
+
+ it("asks again whether the turn is still on after the wait", async () => {
+ const { resources, claim } = phone();
+ const answers = [true, false];
+ await expect(claim(turn("a"), { active: () => answers.shift() ?? false })).rejects.toBe(TURN_ENDED);
+ expect(resources.free(PHONE)).toBe(true);
+ });
+
+ it.each([["GET", "/api/internal/phone/claim"], ["POST", "/api/internal/phone/mcp"]])("passes %s %s on", async (method, path) => {
+ const { claim } = phone();
+ expect(await claim(turn("a"), { method, path })).toBe(PASS);
+ });
+});
+
+describe("the phone claim while a person holds the phone", () => {
+ it("answers person after 45 seconds and claims nothing", async () => {
+ const { resources, hold, claim } = phone();
+ hold.take();
+ const answered = vi.fn();
+ const answer = claim(turn("a")).then((result) => { answered(); return result; });
+ await vi.advanceTimersByTimeAsync(45 * SECOND - 1);
+ expect(answered).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(await answer).toEqual(PERSON);
+ expect(resources.free(PHONE)).toBe(true);
+ });
+
+ it.each([[{ wait: true }], [{ wait: "false" }], [null]])("makes a claim with the body %j wait as one with no body does", async (body) => {
+ const { hold, claim } = phone();
+ hold.take();
+ const answered = vi.fn();
+ const answer = claim(turn("a"), { body }).then((result) => { answered(); return result; });
+ await vi.advanceTimersByTimeAsync(45 * SECOND - 1);
+ expect(answered).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(await answer).toEqual(PERSON);
+ });
+
+ it("answers person at once to a claim from the middle of a call, and claims nothing", async () => {
+ const { resources, hold, claim } = phone();
+ hold.take();
+ const waits = vi.getTimerCount();
+ expect(await claim(turn("a"), { body: MID_CALL })).toEqual(PERSON);
+ expect(vi.getTimerCount()).toBe(waits);
+ expect(resources.free(PHONE)).toBe(true);
+ });
+
+ it("answers a claim from the middle of a call as any other once the person has handed back", async () => {
+ const { hold, claim } = phone();
+ const a = turn("a");
+ expect(await claim(a)).toEqual(CLAIMED);
+ hold.take();
+ hold.release();
+ expect(await claim(a, { body: MID_CALL })).toEqual(HANDED_BACK);
+ expect(await claim(a, { body: MID_CALL })).toEqual(CLAIMED);
+ expect(await claim(turn("b"), { body: MID_CALL })).toEqual(BUSY);
+ });
+
+ it("answers handed-back to a waiting call as soon as the person hands back, then lets the turn claim", async () => {
+ const { resources, hold, claim } = phone();
+ const a = turn("a");
+ hold.take();
+ const answer = claim(a);
+ await vi.advanceTimersByTimeAsync(10 * SECOND);
+ hold.release();
+ expect(await answer).toEqual(HANDED_BACK);
+ expect(resources.free(PHONE)).toBe(true);
+ expect(await claim(a)).toEqual(CLAIMED);
+ });
+
+ it("refuses a waiting turn that already had the phone once, not twice", async () => {
+ const { hold, claim } = phone();
+ const a = turn("a");
+ expect(await claim(a)).toEqual(CLAIMED);
+ hold.take();
+ const answer = claim(a);
+ await vi.advanceTimersByTimeAsync(10 * SECOND);
+ hold.release();
+ expect(await answer).toEqual(HANDED_BACK);
+ expect(await claim(a)).toEqual(CLAIMED);
+ });
+
+ it("refuses the next call of the turn that had the phone and was not waiting, once", async () => {
+ const { hold, claim } = phone();
+ const a = turn("a");
+ expect(await claim(a)).toEqual(CLAIMED);
+ hold.take();
+ hold.release();
+ expect(await claim(a)).toEqual(HANDED_BACK);
+ expect(await claim(a)).toEqual(CLAIMED);
+ });
+
+ it("claims nothing for a waiting call whose turn was stopped, so another thread gets the phone", async () => {
+ const { resources, hold, claim } = phone();
+ hold.take();
+ const stopped = new AbortController();
+ const answer = claim(turn("a"), { signal: stopped.signal });
+ stopped.abort();
+ expect(await answer).toEqual(PERSON);
+ hold.release();
+ expect(resources.free(PHONE)).toBe(true);
+ expect(await claim(turn("b"))).toEqual(CLAIMED);
+ });
+
+ it("answers handed-back to a waiting thread that does not have the phone, and busy until the turn that has it ends", async () => {
+ const { resources, hold, claim } = phone();
+ const a = turn("a");
+ const b = turn("b");
+ expect(await claim(a)).toEqual(CLAIMED);
+ hold.take();
+ const answer = claim(b);
+ await vi.advanceTimersByTimeAsync(10 * SECOND);
+ hold.release();
+ expect(await answer).toEqual(HANDED_BACK);
+ expect(await claim(b)).toEqual(BUSY);
+ expect(await claim(a)).toEqual(HANDED_BACK);
+ expect(await claim(a)).toEqual(CLAIMED);
+ expect(await claim(b)).toEqual(BUSY);
+ resources.release(a);
+ expect(await claim(b)).toEqual(CLAIMED);
+ });
+
+ it.each([
+ ["the same thread's next turn", turn("a", "2")],
+ ["another thread's turn", turn("b")],
+ ])("never refuses %s for a hand-back to a turn that has ended", async (_, next) => {
+ const { resources, hold, claim } = phone();
+ const a = turn("a");
+ expect(await claim(a)).toEqual(CLAIMED);
+ hold.take();
+ hold.release();
+ resources.release(a);
+ expect(await claim(next)).toEqual(CLAIMED);
+ });
+
+ it("refuses only the turn that has the phone at the latest hand-back", async () => {
+ const { resources, hold, claim } = phone();
+ const a = turn("a");
+ const b = turn("b");
+ expect(await claim(a)).toEqual(CLAIMED);
+ hold.take();
+ hold.release();
+ resources.release(a);
+ expect(await claim(b)).toEqual(CLAIMED);
+ hold.take();
+ hold.release();
+ expect(await claim(b)).toEqual(HANDED_BACK);
+ expect(await claim(b)).toEqual(CLAIMED);
+ });
+});
+
+describe("the phone claim with the feature off", () => {
+ it("claims and refuses a busy phone as before", async () => {
+ const { resources, claim } = phone(false);
+ const a = turn("a");
+ expect(await claim(a)).toEqual(CLAIMED);
+ expect(await claim(a)).toEqual(CLAIMED);
+ expect(await claim(turn("b"))).toEqual(BUSY);
+ expect(resources.holder(PHONE)).toBe(a);
+ await expect(claim(a, { active: () => false })).rejects.toBe(TURN_ENDED);
+ });
+
+ it("neither waits for a hold nor refuses for a hand-back", async () => {
+ const { hold, claim } = phone(false);
+ const a = turn("a");
+ hold.take();
+ expect(await claim(a)).toEqual(CLAIMED);
+ expect(await claim(a, { body: MID_CALL })).toEqual(CLAIMED);
+ hold.release();
+ expect(await claim(a)).toEqual(CLAIMED);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});
diff --git a/server/routes/phone-gate.ts b/server/routes/phone-gate.ts
new file mode 100644
index 0000000000..41fcf238fc
--- /dev/null
+++ b/server/routes/phone-gate.ts
@@ -0,0 +1,63 @@
+import type { ServerResponse } from "node:http";
+
+import { CONTROL_WAIT_MS } from "../control-client.ts";
+import type { json } from "../harness/http.ts";
+import type { PhoneHold } from "../phone-screen/hold.ts";
+import type { TurnOwner, TurnResources } from "../turn-resources.ts";
+import { PASS } from "./table.ts";
+
+const PHONE = "computer:phone";
+
+export interface PhoneGateContext {
+ method: string;
+ path: string;
+ res: ServerResponse;
+ json: typeof json;
+ turn: TurnOwner;
+ requireActive: () => void;
+ /** The claim's JSON body. `{ "wait": false }` comes from the middle of a tool call, which cannot wait for a person. */
+ readBody: () => Promise<unknown>;
+ /** Aborts when the bot's request is gone. */
+ signal: AbortSignal;
+}
+
+export function createPhoneGate(deps: {
+ enabled: () => boolean;
+ hold: Pick<PhoneHold, "held" | "wait">;
+ resources: Pick<TurnResources, "holder">;
+ claim: (owner: TurnOwner, resource: string) => boolean;
+}) {
+ let handedBackTo: Pick<TurnOwner, "threadId" | "generation"> | undefined;
+ const takeHandBack = (turn: TurnOwner): boolean => {
+ if (handedBackTo?.threadId !== turn.threadId || handedBackTo.generation !== turn.generation) return false;
+ handedBackTo = undefined;
+ return true;
+ };
+
+ return {
+ /** For the hold's `onChange`: the turn that has the phone when a person's hold ends must read the screen again before it acts. */
+ holdChanged(held: boolean): void {
+ if (held) return;
+ const holder = deps.resources.holder(PHONE);
+ handedBackTo = holder && { threadId: holder.threadId, generation: holder.generation };
+ },
+
+ async internal(ctx: PhoneGateContext): Promise<typeof PASS | void> {
+ if (ctx.method !== "POST" || ctx.path !== "/api/internal/phone/claim") return PASS;
+ ctx.requireActive();
+ if (deps.enabled()) {
+ const midCall = ((await ctx.readBody()) as { wait?: unknown } | null)?.wait === false;
+ const waited = midCall && deps.hold.held ? "held" : await deps.hold.wait(ctx.signal, CONTROL_WAIT_MS);
+ if (waited === "held") return ctx.json(ctx.res, 423, { reason: "person" });
+ if (waited === "handed-back") {
+ takeHandBack(ctx.turn);
+ return ctx.json(ctx.res, 423, { reason: "handed-back" });
+ }
+ ctx.requireActive();
+ if (takeHandBack(ctx.turn)) return ctx.json(ctx.res, 423, { reason: "handed-back" });
+ }
+ if (!deps.claim(ctx.turn, PHONE)) return ctx.json(ctx.res, 409, { error: "another thread is using the phone" });
+ return ctx.json(ctx.res, 200, { claimed: true });
+ },
+ };
+}