Skip to content

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

Phone swipe and tap: a chosen start, distance and duration, and a held tap

Xiaolei Shi29ef84f489d8
diff --git a/server/drivers/phone-proxy.test.ts b/server/drivers/phone-proxy.test.ts
index 92438dd14e..e3fcb2424d 100644
--- a/server/drivers/phone-proxy.test.ts
+++ b/server/drivers/phone-proxy.test.ts
@@ -346,6 +346,12 @@ describe("phone batch step parsing", () => {
{ case: "a zero wait on another action", raw: [{ action: "tap", x: 1, y: 2, seconds: 0 }], error: 'Step 1 (tap) does not take seconds; put a separate {"action":"wait","seconds":0} step after it. No step was performed.' },
{ case: "an endless wait on another action", raw: [{ action: "tap", x: 1, y: 2, seconds: "Infinity" }], error: 'Step 1 (tap) does not take seconds; put a separate {"action":"wait","seconds":3} step after it. No step was performed.' },
{ case: "a list as a wait on another action", raw: [{ action: "tap", x: 1, y: 2, seconds: [5] }], error: 'Step 1 (tap) does not take seconds; put a separate {"action":"wait","seconds":3} step after it. No step was performed.' },
+ { case: "a swipe shorter than 50 pixels", raw: [{ action: "swipe", direction: "up", distance: 10 }], error: 'Step 1 (swipe) needs x and y from 0 to 10000, distance from 50 to 10000 and duration_ms from 50 to 2000, e.g. {"action":"swipe","direction":"up","x":300,"y":1400,"distance":400,"duration_ms":800}. No step was performed.' },
+ { case: "a tap held for 0 ms", raw: [{ action: "tap", x: 540, y: 900, duration_ms: 0 }], error: 'Step 1 (tap) needs duration_ms from 50 to 2000, e.g. {"action":"tap","x":540,"y":900,"duration_ms":1000}. No step was performed.' },
+ { case: "a tap held for 49 ms", raw: [{ action: "tap", x: 540, y: 900, duration_ms: 49 }], error: 'Step 1 (tap) needs duration_ms from 50 to 2000, e.g. {"action":"tap","x":540,"y":900,"duration_ms":1000}. No step was performed.' },
+ { case: "a tap held for 2001 ms", raw: [{ action: "tap", x: 540, y: 900, duration_ms: 2001 }], error: 'Step 1 (tap) needs duration_ms from 50 to 2000, e.g. {"action":"tap","x":540,"y":900,"duration_ms":1000}. No step was performed.' },
+ { case: "a distance on an action that is not swipe", raw: [{ action: "press", key: "enter", distance: 400 }], error: 'Step 1 (press) does not take distance, which belongs to swipe; write it like {"action":"press","key":"enter"}. No step was performed.' },
+ { case: "a duration on an action that is neither tap nor swipe", raw: [{ action: "press", key: "enter", duration_ms: 1000 }], error: 'Step 1 (press) does not take duration_ms, which belongs to tap or swipe; write it like {"action":"press","key":"enter"}. No step was performed.' },
])("refuses $case", ({ raw, error }) => {
expect(() => parseSteps(raw)).toThrow(new Error(error));
});
@@ -463,6 +469,19 @@ describe("phone MCP tool surface", () => {
}
});
+ it("offers swipe a start, a distance and a duration, and tap a duration to hold, as designed", () => {
+ expect(tool("swipe").description).toBe("Swipe the Android screen in a direction. By default the finger moves half the screen through the centre in 260 ms. To scroll a list, a pane or a picker wheel by a chosen amount, give x and y (where the finger starts), distance (pixels it moves) and duration_ms (longer is slower). To do several steps, or to act and then read the screen, in one call, use batch.");
+ expect(tool("swipe").inputSchema).toEqual({ type: "object", properties: { direction: { type: "string", enum: ["up", "down", "left", "right"] }, x: { type: "number" }, y: { type: "number" }, distance: { type: "number" }, duration_ms: { type: "integer" }, serial: { type: "string" } }, required: ["direction"] });
+ expect(tool("tap").description).toBe("Tap Android screen pixel coordinates obtained from read_screen or screenshot. Add duration_ms to hold the tap; about 1000 is a long press. To do several steps, or to act and then read the screen, in one call, use batch.");
+ expect(tool("tap").inputSchema).toEqual({ type: "object", properties: { x: { type: "number" }, y: { type: "number" }, duration_ms: { type: "integer" }, serial: { type: "string" } }, required: ["x", "y"] });
+ });
+
+ it("tells a step what distance and duration_ms mean, naming their actions", () => {
+ const fields = tool("batch").inputSchema.properties.steps.items.properties;
+ expect(fields.distance).toEqual({ type: "number", description: "swipe: pixels the finger moves, 50 to 10000, default half the screen." });
+ expect(fields.duration_ms).toEqual({ type: "integer", description: "tap and swipe: milliseconds a tap is held or a swipe takes, 50 to 2000; without it a tap is not held and a swipe takes 260." });
+ });
+
it("keeps serial out of a step's fields", () => {
expect(tool("batch").inputSchema.properties.steps.items.properties).not.toHaveProperty("serial");
});
@@ -787,7 +806,14 @@ describe("phone MCP calls claim before each command sent to the phone", () => {
["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"],
+ ["tap", { x: 540, y: 900, duration_ms: 1000 }, [onPhone("shell", "input", "swipe", "540", "900", "540", "900", "1000")], "Pressed 540,900 for 1000 ms"],
+ ["tap", { x: 540, y: 900, duration_ms: null }, [onPhone("shell", "input", "tap", "540", "900")], "Tapped 540,900"],
["swipe", { direction: "up" }, [onPhone("shell", "wm", "size"), onPhone("shell", "input", "swipe", "540", "1440", "540", "480", "260")], "Swiped up"],
+ ["swipe", { direction: "down", x: 300, y: 1430, distance: 375, duration_ms: 1500 }, [onPhone("shell", "wm", "size"), onPhone("shell", "input", "swipe", "300", "1430", "300", "1805", "1500")], "Swiped from 300,1430 to 300,1805 in 1500 ms"],
+ ["swipe", { direction: "left", distance: 300 }, [onPhone("shell", "wm", "size"), onPhone("shell", "input", "swipe", "810", "960", "510", "960", "260")], "Swiped from 810,960 to 510,960 in 260 ms"],
+ ["swipe", { direction: "up", x: "300" }, [onPhone("shell", "wm", "size"), onPhone("shell", "input", "swipe", "300", "1440", "300", "480", "260")], "Swiped from 300,1440 to 300,480 in 260 ms"],
+ ["swipe", { direction: "up", x: "", y: null, distance: null, duration_ms: null }, [onPhone("shell", "wm", "size"), onPhone("shell", "input", "swipe", "540", "1440", "540", "480", "260")], "Swiped up"],
+ ["swipe", { direction: "up", distance: 49.6 }, [onPhone("shell", "wm", "size"), onPhone("shell", "input", "swipe", "540", "1440", "540", "1390", "260")], "Swiped from 540,1440 to 540,1390 in 260 ms"],
["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) => {
@@ -799,6 +825,18 @@ describe("phone MCP calls claim before each command sent to the phone", () => {
expect(claims()).toBe(1 + deviceCommands.length);
});
+ const SWIPE_FIELDS_ERROR = 'swipe needs x and y from 0 to 10000, distance from 50 to 10000 and duration_ms from 50 to 2000, e.g. {"direction":"up","x":300,"y":1400,"distance":400,"duration_ms":800}';
+ const TAP_HOLD_ERROR = 'tap needs duration_ms from 50 to 2000, e.g. {"x":540,"y":900,"duration_ms":1000}';
+ it.each([
+ ...[{ distance: 0 }, { distance: 49 }, { distance: -5 }, { distance: 10001 }, { distance: "abc" }, { duration_ms: 0 }, { duration_ms: 0.4 }, { duration_ms: 49 }, { duration_ms: 2001 }, { x: -1 }, { y: 10001 }]
+ .map((field): [string, Record<string, unknown>, string] => ["swipe", { direction: "up", ...field }, SWIPE_FIELDS_ERROR]),
+ ...[0, 49, 2001].map((duration_ms): [string, Record<string, unknown>, string] => ["tap", { x: 540, y: 900, duration_ms }, TAP_HOLD_ERROR]),
+ ])("%s refuses %j and sends nothing to the phone", async (name, args, error) => {
+ const { commands, call } = phone();
+ expect(await call(name, args)).toEqual({ content: [{ type: "text", text: error }], isError: true });
+ expect(commands).toEqual([DEVICES]);
+ });
+
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?" });
@@ -834,6 +872,12 @@ describe("phone MCP calls claim before each command sent to the phone", () => {
expect(midCall).toEqual([false, true, true, true, true]);
});
+ it("a batch step swipes by the distance it gives", async () => {
+ const { commands, call } = phone();
+ expect(await call("batch", { steps: [{ action: "swipe", direction: "up", distance: "400" }, { action: "read_screen" }] })).toEqual({ content: [{ type: "text", text: '1. swipe: Swiped from 540,1440 to 540,1040 in 260 ms\n2. read_screen:\n0: "Where to? · Destination" bounds=12,100,400,180 class=android.widget.TextView' }] });
+ expect(commands).toEqual([DEVICES, onPhone("shell", "wm", "size"), onPhone("shell", "input", "swipe", "540", "1440", "540", "1040", "260"), DUMP]);
+ });
+
it.each([
{ n: 1, steps: [TAP_TEXT_STEP], refusals: [undefined, undefined, REFUSED], done: "", isError: true, sent: [DEVICES, DUMP] },
{ n: 2, steps: [TAP_STEP, TAP_TEXT_STEP], refusals: [undefined, undefined, undefined, undefined, REFUSED], done: "1. tap: Tapped 10,20\n", sent: [DEVICES, TAP, DUMP] },
diff --git a/server/drivers/phone-proxy.ts b/server/drivers/phone-proxy.ts
index d6ea3a720a..b99d629dfe 100644
--- a/server/drivers/phone-proxy.ts
+++ b/server/drivers/phone-proxy.ts
@@ -296,8 +296,8 @@ const SINGLE_TOOLS = [
{ name: "list_apps", description: "List installed launchable Android package names, optionally filtered by a human app name. Prefer open_app first.", inputSchema: { type: "object", properties: { query: { type: "string" }, serial: { type: "string" } } } },
{ name: "open_app", description: "Open an installed Android app directly by its English name, such as Uber or Skyscanner, or by its package name. Do not scan the app drawer first.", inputSchema: { type: "object", properties: { name: { type: "string" }, serial: { type: "string" } }, required: ["name"] } },
{ name: "tap_text", description: "Tap visible Android text or an accessibility label.", inputSchema: { type: "object", properties: { text: { type: "string" }, exact: { type: "boolean" }, index: { type: "integer", minimum: 0 }, serial: { type: "string" } }, required: ["text"] } },
- { name: "tap", description: "Tap Android screen pixel coordinates obtained from read_screen or screenshot.", inputSchema: { type: "object", properties: { x: { type: "number" }, y: { type: "number" }, serial: { type: "string" } }, required: ["x", "y"] } },
- { name: "swipe", description: "Swipe the Android screen in a direction.", inputSchema: { type: "object", properties: { direction: { type: "string", enum: ["up", "down", "left", "right"] }, serial: { type: "string" } }, required: ["direction"] } },
+ { name: "tap", description: "Tap Android screen pixel coordinates obtained from read_screen or screenshot. Add duration_ms to hold the tap; about 1000 is a long press.", inputSchema: { type: "object", properties: { x: { type: "number" }, y: { type: "number" }, duration_ms: { type: "integer" }, serial: { type: "string" } }, required: ["x", "y"] } },
+ { name: "swipe", description: "Swipe the Android screen in a direction. By default the finger moves half the screen through the centre in 260 ms. To scroll a list, a pane or a picker wheel by a chosen amount, give x and y (where the finger starts), distance (pixels it moves) and duration_ms (longer is slower).", inputSchema: { type: "object", properties: { direction: { type: "string", enum: ["up", "down", "left", "right"] }, x: { type: "number" }, y: { type: "number" }, distance: { type: "number" }, duration_ms: { type: "integer" }, serial: { type: "string" } }, required: ["direction"] } },
{ name: "type_text", description: "Type text into the focused Android field. Letters, digits, spaces and _.,@- always work; other text, such as Chinese, emoji or +, needs the ADBKeyBoard keyboard selected on the phone. Set clear to true to empty the field first, which also needs ADBKeyBoard. Never enter passwords or payment details. A one-time code only for a sign-in the person asked for, into the app it was sent for.", inputSchema: { type: "object", properties: { text: { type: "string", maxLength: 256 }, clear: { type: "boolean" }, serial: { type: "string" } }, required: ["text"] } },
{ name: "press", description: "Press an Android navigation or keyboard key. wakeup turns the screen on and sleep turns it off.", inputSchema: { type: "object", properties: { key: { type: "string", enum: Object.keys(KEYCODES) }, serial: { type: "string" } }, required: ["key"] } },
] as const;
@@ -319,6 +319,8 @@ const STEP_FIELD_NOTES: Record<string, string> = {
x: "pixel x from read_screen or screenshot",
y: "pixel y from read_screen or screenshot",
direction: "which way to swipe",
+ distance: "pixels the finger moves, 50 to 10000, default half the screen",
+ duration_ms: "milliseconds a tap is held or a swipe takes, 50 to 2000; without it a tap is not held and a swipe takes 260",
key: "the key to press",
seconds: `how long to wait, 0 to ${MAX_WAIT_SECONDS}, default ${DEFAULT_WAIT_SECONDS}`,
};
@@ -333,13 +335,26 @@ const STEP_EXAMPLES: Record<StepAction, Json> = {
wait: { action: "wait", seconds: 3 },
};
const inPixels = (value: unknown) => Number.isFinite(value) && Number(value) >= 0 && Number(value) <= 10_000;
+const given = (value: unknown) => value !== undefined && value !== null && value !== "";
+const rounded = (value: unknown) => Math.round(toNumber(value));
+const absentOrWithin = (value: unknown, min: number, max: number) => !given(value) || (rounded(value) >= min && rounded(value) <= max);
+const DURATION_NEEDS = "duration_ms from 50 to 2000";
+const HELD_TAP_EXAMPLE = { x: 540, y: 900, duration_ms: 1000 };
+const durationOk = (args: Json) => absentOrWithin(args.duration_ms, 50, 2000);
+const SWIPE_NEEDS = `x and y from 0 to 10000, distance from 50 to 10000 and ${DURATION_NEEDS}`;
+const SWIPE_EXAMPLE = { direction: "up", x: 300, y: 1400, distance: 400, duration_ms: 800 };
+const swipeFieldsOk = (args: Json) => absentOrWithin(args.x, 0, 10_000) && absentOrWithin(args.y, 0, 10_000) && absentOrWithin(args.distance, 50, 10_000) && durationOk(args);
const STEP_RULES: Partial<Record<StepAction, StepRule[]>> = {
open_app: [{ ok: (step) => String(step.name).trim() !== "", needs: "name, an app's English name or package name" }],
tap_text: [
{ ok: (step) => String(step.text).trim() !== "", needs: "text that is not blank" },
{ ok: (step) => step.index === undefined || (Number.isInteger(step.index) && Number(step.index) >= 0), needs: "index as a whole number from 0", example: { action: "tap_text", text: "Search", index: 1 } },
],
- tap: [{ ok: (step) => inPixels(step.x) && inPixels(step.y), needs: "x and y from 0 to 10000" }],
+ tap: [
+ { ok: (step) => inPixels(step.x) && inPixels(step.y), needs: "x and y from 0 to 10000" },
+ { ok: durationOk, needs: DURATION_NEEDS, example: { action: "tap", ...HELD_TAP_EXAMPLE } },
+ ],
+ swipe: [{ ok: swipeFieldsOk, needs: SWIPE_NEEDS, example: { action: "swipe", ...SWIPE_EXAMPLE } }],
type_text: [{ ok: (step) => [...String(step.text)].length <= 256, needs: "text of at most 256 characters" }],
wait: [{ ok: (step) => step.seconds === undefined || Number(step.seconds) >= 0, needs: `seconds as a number from 0 to ${MAX_WAIT_SECONDS}` }],
};
@@ -598,25 +613,34 @@ async function callToolOn(onDevice: OnDevice, serial: string, name: string, args
if (name === "tap") {
const x = Number(args.x); const y = Number(args.y);
if (!Number.isFinite(x) || !Number.isFinite(y) || x < 0 || y < 0 || x > 10000 || y > 10000) throw new Error("Invalid Android coordinates");
- await onDevice(serial, ["shell", "input", "tap", String(Math.round(x)), String(Math.round(y))]);
- return textResult(`Tapped ${Math.round(x)},${Math.round(y)}`);
+ if (!durationOk(args)) throw new Error(`tap needs ${DURATION_NEEDS}, e.g. ${JSON.stringify(HELD_TAP_EXAMPLE)}`);
+ const at = [String(Math.round(x)), String(Math.round(y))];
+ const held = given(args.duration_ms) ? String(rounded(args.duration_ms)) : undefined;
+ // Android's `input` has no touch long press: a swipe that ends where it starts holds the finger there (seen on Android 9).
+ await onDevice(serial, ["shell", "input", ...(held ? ["swipe", ...at, ...at, held] : ["tap", ...at])]);
+ return textResult(held ? `Pressed ${at.join(",")} for ${held} ms` : `Tapped ${at.join(",")}`);
}
if (name === "swipe") {
const direction = String(args.direction ?? "");
+ if (!swipeFieldsOk(args)) throw new Error(`swipe needs ${SWIPE_NEEDS}, e.g. ${JSON.stringify(SWIPE_EXAMPLE)}`);
const size = (await onDevice(serial, ["shell", "wm", "size"])).toString("utf8");
const match = /(\d+)x(\d+)/.exec(size);
if (!match) throw new Error("Could not read Android screen size");
const width = Number(match[1]); const height = Number(match[2]);
- const points: Record<string, [number, number, number, number]> = {
- up: [width / 2, height * 0.75, width / 2, height * 0.25],
- down: [width / 2, height * 0.25, width / 2, height * 0.75],
- left: [width * 0.75, height / 2, width * 0.25, height / 2],
- right: [width * 0.25, height / 2, width * 0.75, height / 2],
+ const moves: Record<string, { x: number; y: number; dx: number; dy: number; distance: number }> = {
+ up: { x: width / 2, y: height * 0.75, dx: 0, dy: -1, distance: height / 2 },
+ down: { x: width / 2, y: height * 0.25, dx: 0, dy: 1, distance: height / 2 },
+ left: { x: width * 0.75, y: height / 2, dx: -1, dy: 0, distance: width / 2 },
+ right: { x: width * 0.25, y: height / 2, dx: 1, dy: 0, distance: width / 2 },
};
- const point = points[direction];
- if (!point) throw new Error("Invalid swipe direction");
- await onDevice(serial, ["shell", "input", "swipe", ...point.map((value) => String(Math.round(value))), "260"]);
- return textResult(`Swiped ${direction}`);
+ const move = moves[direction];
+ if (!move) throw new Error("Invalid swipe direction");
+ const or = (value: unknown, fallback: number) => (given(value) ? rounded(value) : fallback);
+ const x = or(args.x, move.x); const y = or(args.y, move.y); const distance = or(args.distance, move.distance);
+ const sent = [x, y, x + move.dx * distance, y + move.dy * distance, or(args.duration_ms, 260)].map((value) => String(Math.round(value)));
+ await onDevice(serial, ["shell", "input", "swipe", ...sent]);
+ const chosen = [args.x, args.y, args.distance, args.duration_ms].some(given);
+ return textResult(chosen ? `Swiped from ${sent[0]},${sent[1]} to ${sent[2]},${sent[3]} in ${sent[4]} ms` : `Swiped ${direction}`);
}
if (name === "type_text") return textResult(await typePhoneText(deviceShell(onDevice, serial), String(args.text ?? ""), args.clear === true));
if (name === "press") {