Skip to content

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

Phone screen: watch and take over the bots' USB phone in the Android tab, behind an experimental setting

Xiaolei Shie3e18fca3d8f
diff --git a/docs/feature-flags.md b/docs/feature-flags.md
index c0bdb67a05..4c2c1cbd32 100644
--- a/docs/feature-flags.md
+++ b/docs/feature-flags.md
@@ -59,6 +59,7 @@ text and extra work can increase token usage.
| `acpPlanLines` | Off | Shows an ACP agent's plan as activity lines. | Each emitted line counts as a tool call wherever tool calls are counted; environment override below. |
| `agentsToolBridge` | Off, except eligible local-model turns | Lists a smaller tool catalog with `find_tool` and `use_tool`. | Tool lookup can add model calls; smaller initial context is not a guaranteed saving. See [Agents tool bridge](agents-tool-bridge.md) for eligibility and measurements. |
| `savedSteps` | On | Allows saving and repeating computer tasks from their steps on a supported host. | Currently requires a Mac server. Enabling it does not add host support. |
+| `usbPhoneTakeover` | Off | Shows the server's USB Android phone live in the Screen panel and lets a person take it over from the bots. | Not offered on a Cloud home or a hosted workspace. The first use downloads the scrcpy server (734 KB) from GitHub. |
With `skillsLibrary` on, the every-bot skills a bot was taken off live in
`<data>/skill-state/<bot id>/library-opt-out.json`. If that file is there but
diff --git a/src/components/AndroidDevicePanel.server.test.ts b/src/components/AndroidDevicePanel.server.test.ts
new file mode 100644
index 0000000000..c8d6f19664
--- /dev/null
+++ b/src/components/AndroidDevicePanel.server.test.ts
@@ -0,0 +1,169 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { FakePhoneSocket, fakePhoneStream } from "@/testing/phone-stream";
+import type { AndroidDeviceStatus, AndroidUsbDevice } from "@/types/ogb";
+import { AndroidDevicePanel, useAndroidUsbDevices, type AndroidUsbDevicesStatus } from "./AndroidDevicePanel";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+vi.mock("@/lib/page-visible", () => ({ usePageVisible: () => true }));
+
+const PHONE: AndroidUsbDevice = { serial: "p1", state: "device", connection: "usb", model: "Pixel" };
+const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
+
+let root: Root | null = null;
+let latest: AndroidUsbDevicesStatus;
+const bridge = { status: vi.fn(async () => ({ available: true, devices: [] })), frame: vi.fn(async () => ({ serial: "", dataUrl: "" })), input: vi.fn(async () => {}) };
+
+function Probe({ serverPhones = true }: { serverPhones?: boolean }) {
+ latest = useAndroidUsbDevices(serverPhones);
+ return null;
+}
+
+async function draw(element: ReturnType<typeof createElement>) {
+ const container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ await act(async () => {
+ root!.render(element);
+ for (let turn = 0; turn < 5; turn++) await Promise.resolve();
+ });
+}
+
+/** Answers the server's phone list; the desktop app's bridge is present too, and must stay unused. */
+function server(answer: () => Promise<Response>) {
+ const fetch = vi.fn((_path: string, _init?: RequestInit) => answer());
+ vi.stubGlobal("fetch", fetch);
+ vi.stubGlobal("ogb", { androidDevice: bridge });
+ return fetch;
+}
+
+beforeEach(() => {
+ fakePhoneStream();
+ vi.clearAllMocks();
+});
+afterEach(() => {
+ act(() => root?.unmount());
+ root = null;
+ document.body.innerHTML = "";
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+});
+
+describe("useAndroidUsbDevices asking the server", () => {
+ it("reads the server's phone list instead of the desktop app's", async () => {
+ const fetch = server(async () => json({ available: true, devices: [PHONE] }));
+ await draw(createElement(Probe));
+ expect(fetch.mock.calls.map(([path]) => path)).toEqual(["/api/usb-phones"]);
+ expect(bridge.status).not.toHaveBeenCalled();
+ expect(latest).toEqual({ available: true, devices: [PHONE], scanned: true });
+ });
+
+ it("passes the server's reason on when it has no adb", async () => {
+ server(async () => json({ available: false, reasonCode: "adb-unavailable", devices: [] }));
+ await draw(createElement(Probe));
+ expect(latest).toEqual({ available: false, reasonCode: "adb-unavailable", devices: [], scanned: true });
+ });
+
+ it.each([
+ ["the feature is off (404)", async () => json({ error: "Not found" }, 404)],
+ ["the answer is not a phone list", async () => new Response("<html>", { status: 200 })],
+ ])("has no phones, scanned, when %s", async (_name, answer) => {
+ server(answer);
+ await draw(createElement(Probe));
+ expect(latest).toEqual({ available: false, devices: [], scanned: true });
+ });
+
+ it.each([
+ ["the request does not reach the server", async () => { throw new TypeError("Failed to fetch"); }, "Failed to fetch"],
+ ["the server fails", async () => json({ error: "adb timed out" }, 500), "adb timed out"],
+ ])("says the check failed, not that no phone is there, when %s", async (_name, answer, message) => {
+ server(answer);
+ await draw(createElement(Probe));
+ expect(latest).toEqual({ available: false, devices: [], reasonCode: "adb-failed", message, scanned: true });
+ });
+
+ it("asks again every two seconds and keeps the newest answer when an older one is late", async () => {
+ vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });
+ const answers: Array<(response: Response) => void> = [];
+ const fetch = server(() => new Promise((resolve) => answers.push(resolve)));
+ await draw(createElement(Probe));
+ expect(latest.scanned).toBe(false);
+ expect(fetch).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ vi.advanceTimersByTime(1_999);
+ await Promise.resolve();
+ });
+ expect(fetch).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ vi.advanceTimersByTime(1);
+ await Promise.resolve();
+ });
+ expect(fetch).toHaveBeenCalledTimes(2);
+
+ await act(async () => {
+ answers[1](json({ available: true, devices: [PHONE] }));
+ for (let turn = 0; turn < 5; turn++) await Promise.resolve();
+ });
+ expect(latest.devices.map((device) => device.serial)).toEqual(["p1"]);
+
+ await act(async () => {
+ answers[0](json({ available: true, devices: [] }));
+ for (let turn = 0; turn < 5; turn++) await Promise.resolve();
+ });
+ expect(latest.devices.map((device) => device.serial)).toEqual(["p1"]);
+ });
+
+ it("forgets the server's phones and stops asking when the feature goes off on a page without the desktop app", async () => {
+ vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });
+ const fetch = server(async () => json({ available: true, devices: [PHONE] }));
+ vi.stubGlobal("ogb", undefined);
+ await draw(createElement(Probe));
+ expect(latest.devices).toEqual([PHONE]);
+
+ await act(async () => {
+ root!.render(createElement(Probe, { serverPhones: false }));
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(2_000);
+ await Promise.resolve();
+ });
+ expect(latest).toEqual({ available: false, devices: [], scanned: true });
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("AndroidDevicePanel with the server's phones", () => {
+ const panel = (status: AndroidDeviceStatus, serverPhones: boolean) => {
+ vi.stubGlobal("ogb", { androidDevice: bridge });
+ return draw(createElement(AndroidDevicePanel, { status, serverPhones }));
+ };
+
+ it("shows a ready phone's live screen from the server, not the desktop app's screenshots", async () => {
+ await panel({ available: true, devices: [PHONE] }, true);
+ expect(FakePhoneSocket.all.map((socket) => new URL(socket.url, "http://omb.test").pathname)).toEqual(["/api/usb-phones/p1/stream"]);
+ expect(bridge.frame).not.toHaveBeenCalled();
+ expect(document.body.textContent).toContain("Watching · the bots keep working");
+ expect(document.body.textContent).toContain("First-time USB setup");
+ expect(document.body.textContent).toContain("Connected over USB to the computer that runs OpenMausBot.");
+ expect(document.body.textContent).not.toContain("stay on this computer");
+ });
+
+ it("keeps the unauthorized notice and opens no stream for a phone that is not ready", async () => {
+ await panel({ available: true, devices: [{ ...PHONE, state: "unauthorized" }] }, true);
+ expect(FakePhoneSocket.all).toHaveLength(0);
+ expect(document.body.textContent).toContain("Allow USB debugging");
+ expect(document.body.textContent).toContain("First-time USB setup");
+ });
+
+ it("stays the desktop app's panel without the server's phones", async () => {
+ await panel({ available: true, devices: [PHONE] }, false);
+ expect(FakePhoneSocket.all).toHaveLength(0);
+ expect(bridge.frame).toHaveBeenCalledWith("p1");
+ expect(document.body.textContent).not.toContain("Watching · the bots keep working");
+ expect(document.body.textContent).toContain("Connected directly over USB. The screen and controls stay on this computer.");
+ });
+});
diff --git a/src/components/AndroidDevicePanel.tsx b/src/components/AndroidDevicePanel.tsx
index 1b46a1a77b..108379923c 100644
--- a/src/components/AndroidDevicePanel.tsx
+++ b/src/components/AndroidDevicePanel.tsx
@@ -1,12 +1,13 @@
import { useEffect, useRef, useState } from "react";
-import { ArrowLeft, Circle, Loader2, RotateCcw, ShieldCheck, Smartphone, Usb } from "lucide-react";
+import { Loader2, ShieldCheck, Smartphone, Usb } from "lucide-react";
import { usePageVisible } from "@/lib/page-visible";
import { t } from "@/lib/i18n";
+import { api, ApiError } from "@/state/api";
+import { ANDROID_KEY_NAMES, AndroidNavButtons, fittedUnitPoint, type UnitPoint } from "./android-device-parts";
+import { PhoneScreenPanel } from "./PhoneScreenPanel";
import { Select } from "./Select";
import type { AndroidDeviceInput, AndroidDeviceStatus, AndroidUsbDevice } from "@/types/ogb";
-type UnitPoint = { x: number; y: number };
-
const EMPTY_STATUS: AndroidDeviceStatus = { available: false, devices: [] };
export type AndroidUsbDevicesStatus = AndroidDeviceStatus & {
@@ -14,14 +15,27 @@ export type AndroidUsbDevicesStatus = AndroidDeviceStatus & {
scanned: boolean;
};
-export function useAndroidUsbDevices(): AndroidUsbDevicesStatus {
+async function readServerPhones(): Promise<AndroidDeviceStatus> {
+ try {
+ const answer = await api<AndroidDeviceStatus>("/api/usb-phones", { background: true });
+ return Array.isArray(answer.devices) ? answer : EMPTY_STATUS;
+ } catch (cause) {
+ if (cause instanceof ApiError && cause.status === 404) return EMPTY_STATUS;
+ throw cause;
+ }
+}
+
+/** With `serverPhones` the server lists the phones plugged into its own computer; otherwise the desktop app does. */
+export function useAndroidUsbDevices(serverPhones = false): AndroidUsbDevicesStatus {
const bridge = window.ogb?.androidDevice;
const [status, setStatus] = useState<AndroidDeviceStatus>(EMPTY_STATUS);
const [scanned, setScanned] = useState(false);
const pageVisible = usePageVisible();
useEffect(() => {
- if (!bridge) {
+ const read = serverPhones ? readServerPhones : bridge && (() => bridge.status());
+ if (!read) {
+ setStatus(EMPTY_STATUS);
setScanned(true);
return;
}
@@ -35,7 +49,7 @@ export function useAndroidUsbDevices(): AndroidUsbDevicesStatus {
const check = ++issued;
const superseded = () => check < answered;
try {
- const next = await bridge.status();
+ const next = await read();
if (alive && !superseded()) {
answered = check;
setStatus(next);
@@ -60,7 +74,7 @@ export function useAndroidUsbDevices(): AndroidUsbDevicesStatus {
alive = false;
window.clearInterval(timer);
};
- }, [bridge, pageVisible]);
+ }, [bridge, pageVisible, serverPhones]);
return { ...status, scanned };
}
@@ -69,8 +83,8 @@ function deviceLabel(device: AndroidUsbDevice) {
return device.model === "Android device" ? device.serial : device.model;
}
-export function AndroidDevicePanel({ status }: { status: AndroidDeviceStatus }) {
- const bridge = window.ogb?.androidDevice;
+export function AndroidDevicePanel({ status, serverPhones = false }: { status: AndroidDeviceStatus; serverPhones?: boolean }) {
+ const bridge = serverPhones ? undefined : window.ogb?.androidDevice;
const pageVisible = usePageVisible();
const authorized = status.devices.filter((device) => device.state === "device");
const [serial, setSerial] = useState(authorized[0]?.serial ?? status.devices[0]?.serial ?? "");
@@ -140,39 +154,15 @@ export function AndroidDevicePanel({ status }: { status: AndroidDeviceStatus })
const unitPoint = (
event: React.PointerEvent<HTMLDivElement>,
clampToPhone = false,
- ): UnitPoint | null => {
- const image = imageRef.current;
- if (!image || !dimensions.width || !dimensions.height) return null;
- const bounds = event.currentTarget.getBoundingClientRect();
- const scale = Math.min(bounds.width / dimensions.width, bounds.height / dimensions.height);
- const fittedWidth = dimensions.width * scale;
- const fittedHeight = dimensions.height * scale;
- const left = bounds.left + (bounds.width - fittedWidth) / 2;
- const top = bounds.top + (bounds.height - fittedHeight) / 2;
- const x = (event.clientX - left) / fittedWidth;
- const y = (event.clientY - top) / fittedHeight;
- if (clampToPhone) {
- return { x: Math.max(0, Math.min(1, x)), y: Math.max(0, Math.min(1, y)) };
- }
- return x >= 0 && x <= 1 && y >= 0 && y <= 1 ? { x, y } : null;
- };
+ ): UnitPoint | null =>
+ imageRef.current ? fittedUnitPoint(event.currentTarget.getBoundingClientRect(), dimensions, event, clampToPhone) : null;
const keyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.metaKey || event.ctrlKey || event.altKey) return;
- const named: Record<string, string> = {
- ArrowDown: "down",
- ArrowLeft: "left",
- ArrowRight: "right",
- ArrowUp: "up",
- Backspace: "delete",
- Delete: "delete",
- Enter: "enter",
- Escape: "back",
- Tab: "tab",
- };
- if (named[event.key]) {
+ const named = ANDROID_KEY_NAMES[event.key];
+ if (named) {
event.preventDefault();
- send({ type: "key", key: named[event.key] });
+ send({ type: "key", key: named });
} else if (/^[A-Za-z0-9 _.,@-]$/.test(event.key)) {
event.preventDefault();
send({ type: "text", text: event.key });
@@ -224,7 +214,7 @@ export function AndroidDevicePanel({ status }: { status: AndroidDeviceStatus })
<Smartphone size={16} className="text-success" /> {deviceLabel(selected)}
</div>
<div className="mt-1 text-[12px] leading-relaxed text-ink-secondary">
- {t("computer.android.usbSubtitle")}
+ {t(serverPhones ? "computer.android.serverSubtitle" : "computer.android.usbSubtitle")}
</div>
</div>
<span className="flex shrink-0 items-center gap-1 text-[11px] text-success">
@@ -252,6 +242,8 @@ export function AndroidDevicePanel({ status }: { status: AndroidDeviceStatus })
? t("computer.android.unauthorized")
: t("computer.android.badState", { state: selected.state })}
</div>
+ ) : serverPhones ? (
+ <PhoneScreenPanel key={selected.serial} serial={selected.serial} name={deviceLabel(selected)} />
) : (
<>
<div
@@ -311,24 +303,7 @@ export function AndroidDevicePanel({ status }: { status: AndroidDeviceStatus })
)}
</div>
<div className="grid grid-cols-3 gap-2">
- <button
- onClick={() => send({ type: "key", key: "back" })}
- className="flex items-center justify-center gap-1.5 rounded-lg bg-raised py-2 text-[12px] text-ink hover:bg-raised-hover"
- >
- <ArrowLeft size={13} /> {t("computer.android.back")}
- </button>
- <button
- onClick={() => send({ type: "key", key: "home" })}
- className="flex items-center justify-center gap-1.5 rounded-lg bg-raised py-2 text-[12px] text-ink hover:bg-raised-hover"
- >
- <Circle size={12} /> {t("computer.android.home")}
- </button>
- <button
- onClick={() => send({ type: "key", key: "recent" })}
- className="flex items-center justify-center gap-1.5 rounded-lg bg-raised py-2 text-[12px] text-ink hover:bg-raised-hover"
- >
- <RotateCcw size={13} /> {t("computer.android.recent")}
- </button>
+ <AndroidNavButtons onKey={(key) => send({ type: "key", key })} />
</div>
<div className="text-center text-[11px] leading-relaxed text-ink-secondary">
{t("computer.android.hint")}
diff --git a/src/components/AppSettingsRows.tsx b/src/components/AppSettingsRows.tsx
index c235d5e394..6c5e0c1540 100644
--- a/src/components/AppSettingsRows.tsx
+++ b/src/components/AppSettingsRows.tsx
@@ -8,6 +8,7 @@ import { completionPatch } from "@/lib/onboarding";
import { updaterMessage, useUpdaterState } from "@/lib/updater";
import { productName } from "../lib/brand";
import { BrowserProfilesManager } from "./BrowserProfilesManager";
+import { UsbPhoneTakeoverSettings } from "./UsbPhoneTakeoverSettings";
import { MoreText, SettingRow, SettingsGroup, SettingsRows, Switch } from "./SettingsPrimitives";
import { LearnedSkillsSettings } from "./ShareLearnedSkillsSettings";
import { effortLabel } from "./ModelPicker";
@@ -421,6 +422,7 @@ export function ExperimentalFeaturesRow() {
/>
</SettingRow>
<LearnedSkillsSettings />
+ <UsbPhoneTakeoverSettings />
</SettingsRows>
</SettingsGroup>
);
diff --git a/src/components/BrowserSettingsRows.tsx b/src/components/BrowserSettingsRows.tsx
index cd99e69b21..1e6994f635 100644
--- a/src/components/BrowserSettingsRows.tsx
+++ b/src/components/BrowserSettingsRows.tsx
@@ -7,7 +7,7 @@ import { api, useStore, type ConfigStatus } from "@/state/store";
import { MoreText, SettingRow, Switch } from "./SettingsPrimitives";
/** Saves one config change through PATCH /api/config, one at a time, and shows the server's answer or its error. */
-function useConfigSave() {
+export function useConfigSave() {
const { dispatch } = useStore();
const [saving, setSaving] = useState(false);
const [error, setError] = useState("");
diff --git a/src/components/ComputerPanel.android.test.ts b/src/components/ComputerPanel.android.test.ts
index 4a96f54a91..4a8058c5e6 100644
--- a/src/components/ComputerPanel.android.test.ts
+++ b/src/components/ComputerPanel.android.test.ts
@@ -25,9 +25,13 @@ vi.mock("./DesktopCapabilities", async (importOriginal) => ({
vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => true, setAdvancedMode: () => {} }));
vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));
vi.mock("./CloudScreenPreview", () => ({ CloudScreenPreview: () => null }));
+const androidPanel = vi.hoisted(() => ({ props: undefined as { status: AndroidDeviceStatus; serverPhones?: boolean } | undefined }));
vi.mock("./AndroidDevicePanel", async (importOriginal) => ({
...await importOriginal<typeof import("./AndroidDevicePanel")>(),
- AndroidDevicePanel: () => null,
+ AndroidDevicePanel: (props: NonNullable<typeof androidPanel.props>) => {
+ androidPanel.props = props;
+ return null;
+ },
}));
vi.mock("./BrowserPanel", () => ({ BrowserPanel: () => null }));
vi.mock("./CloudBackendPicker", () => ({ CloudBackendPicker: () => null }));
@@ -70,8 +74,9 @@ const makeBot = (patch: Partial<Bot> = {}): Bot => ({
}) as unknown as Bot;
let root: Root | null = null;
+let features: NonNullable<AppState["config"]>["features"];
const value = (): Parameters<typeof BotEditorStore>[0]["value"] => ({
- state: { ...initialState, instances: [engine("claude"), engine("codex")], config: { box: { configured: true } } as AppState["config"] } as AppState,
+ state: { ...initialState, instances: [engine("claude"), engine("codex")], config: { box: { configured: true }, features } as AppState["config"] } as AppState,
dispatch: vi.fn(),
flushBotPatches: async () => null,
refreshInstances: async () => {},
@@ -98,6 +103,15 @@ const close = () => {
const selectedTab = () => [...document.querySelectorAll<HTMLButtonElement>('[data-testid="computer-tabs"] button')]
.find((candidate) => candidate.getAttribute("aria-selected") === "true" || candidate.getAttribute("aria-pressed") === "true")?.textContent?.trim();
+/** The desktop app's answer to an adb check, and the server's answer to its phone list. */
+function hosts(serverPhones: AndroidDeviceStatus, desktopPhones: AndroidDeviceStatus = { available: true, devices: [] }) {
+ const bridge = { status: vi.fn(async () => desktopPhones), frame: async () => ({ serial: "", dataUrl: "" }), input: async () => {} };
+ const fetch = vi.fn(async (_path: string) => new Response(JSON.stringify(serverPhones), { headers: { "content-type": "application/json" } }));
+ vi.stubGlobal("ogb", { androidDevice: bridge });
+ vi.stubGlobal("fetch", fetch);
+ return { bridge, asked: () => fetch.mock.calls.map(([path]) => path) };
+}
+
/** An adb check that never answers, leaving discovery unfinished. */
const pendingCheck = () => new Promise<AndroidDeviceStatus>(() => {});
/** Points the native bridge at an answer and re-renders, restarting the poll. */
@@ -116,6 +130,8 @@ afterEach(() => {
close();
vi.unstubAllGlobals();
panelViewStore.current = "computer";
+ features = undefined;
+ androidPanel.props = undefined;
});
describe("Computer panel Android tab", () => {
@@ -191,4 +207,39 @@ describe("Computer panel Android tab", () => {
expect(panelViewStore.current).toBe("data");
expect(selectedTab()).toBe("Data");
});
+
+ it("shows the server's phones while features.usbPhoneTakeover is on", async () => {
+ features = { skillAuthoring: true, usbPhoneTakeover: true };
+ panelViewStore.current = "android";
+ const { bridge, asked } = hosts({ available: true, devices: [PHONE] });
+ await open(makeBot());
+
+ expect(asked()).toEqual(["/api/usb-phones"]);
+ expect(bridge.status).not.toHaveBeenCalled();
+ expect(selectedTab()).toBe("Android");
+ expect(androidPanel.props).toEqual({ status: { available: true, devices: [PHONE], scanned: true }, serverPhones: true });
+ });
+
+ it("keeps the stored Android view when the server's phone list fails, and leaves it once the server has no phone", async () => {
+ features = { skillAuthoring: true, usbPhoneTakeover: true };
+ panelViewStore.current = "android";
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ error: "adb timed out" }), { status: 500 })));
+ await open(makeBot());
+ expect(panelViewStore.current).toBe("android");
+
+ hosts({ available: true, devices: [] });
+ await open(makeBot());
+ expect(panelViewStore.current).toBe("computer");
+ });
+
+ it("shows the desktop app's phones while features.usbPhoneTakeover is off", async () => {
+ features = { skillAuthoring: true, usbPhoneTakeover: false };
+ panelViewStore.current = "android";
+ const { bridge, asked } = hosts({ available: true, devices: [] }, { available: true, devices: [PHONE] });
+ await open(makeBot());
+
+ expect(asked()).toEqual([]);
+ expect(bridge.status).toHaveBeenCalled();
+ expect(androidPanel.props).toEqual({ status: { available: true, devices: [PHONE], scanned: true }, serverPhones: false });
+ });
});
diff --git a/src/components/ComputerPanel.tsx b/src/components/ComputerPanel.tsx
index 708f50dae9..528065d479 100644
--- a/src/components/ComputerPanel.tsx
+++ b/src/components/ComputerPanel.tsx
@@ -31,7 +31,7 @@ import { usePanelPage, type PanelPage } from "@/lib/page-open";
const DataPanel = lazy(() => import("./data/DataPanel").then((module) => ({ default: module.DataPanel })));
const loadLiveDesktop = () => import("./LiveDesktop").then((module) => ({ default: module.LiveDesktop }));
const LiveDesktop = lazy(loadLiveDesktop);
-import { browserAvailable, browserUnavailableReason, builtInBrowserEnabled } from "@/lib/feature-flags";
+import { browserAvailable, browserUnavailableReason, builtInBrowserEnabled, usbPhoneTakeoverEnabled } from "@/lib/feature-flags";
import { parseComputerHelp, transitionComputerControlLease, type ComputerControlAction } from "@/lib/computer-control";
import { openProviderDesktop, useComputerTakeover } from "./computer-takeover";
import { SignInBanner } from "./SignInRequestCard";
@@ -253,7 +253,7 @@ export function ComputerPanel({
const [storedPanelView, setPanelView] = useState<ComputerPanelView>(() => readComputerPanelView(bot.id));
const requestedDataResult = state.dataResultFocus?.botId === bot.id ? state.dataResultFocus : undefined;
const [dataRequest, setDataRequest] = useState<{ id: string; requestId: number }>();
- const androidStatus = useAndroidUsbDevices();
+ const androidStatus = useAndroidUsbDevices(usbPhoneTakeoverEnabled(state.config));
const androidConnected = androidStatus.devices.length > 0;
const panelTabs = computerPanelTabs({ advanced, androidConnected });
const panelView = resolveComputerPanelView(storedPanelView, { advanced, androidConnected });
@@ -1298,7 +1298,7 @@ export function ComputerPanel({
</div>
) : panelView === "android" && androidConnected ? (
<div {...tabPanelProps("android")} className={cn("flex-1 overflow-y-auto px-4 pt-2", TAB_PANEL_FOCUS)}>
- <AndroidDevicePanel status={androidStatus} />
+ <AndroidDevicePanel status={androidStatus} serverPhones={usbPhoneTakeoverEnabled(state.config)} />
</div>
) : (
<div {...tabPanelProps("computer")} className={cn("flex-1 overflow-y-auto px-5 pb-5", TAB_PANEL_FOCUS)}>
diff --git a/src/components/PhoneScreenPanel.test.ts b/src/components/PhoneScreenPanel.test.ts
new file mode 100644
index 0000000000..6e92229063
--- /dev/null
+++ b/src/components/PhoneScreenPanel.test.ts
@@ -0,0 +1,347 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { FakePhoneSocket, FakeVideoDecoder, PHONE_CONFIG, fakePhoneStream, showPage } from "@/testing/phone-stream";
+import { PhoneScreenPanel } from "./PhoneScreenPanel";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let root: Root | null = null;
+let animationFrames: Array<() => void> = [];
+
+type Shown = { box?: { left: number; top: number; width: number; height: number }; frame?: { width: number; height: number } };
+
+const panel = (serial: string) => createElement(PhoneScreenPanel, { serial, name: "Pixel" });
+
+/** The panel for phone p1, with its screen 720 by 640 at the page's corner unless `box` says otherwise. */
+async function mount({ box = { left: 0, top: 0, width: 720, height: 640 } }: Shown = {}) {
+ const container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ await act(async () => root!.render(panel("p1")));
+ const screen = container.querySelector<HTMLElement>('[role="application"]')!;
+ screen.getBoundingClientRect = () => ({ ...box, right: box.left + box.width, bottom: box.top + box.height, x: box.left, y: box.top, toJSON: () => ({}) });
+ return { screen, socket: FakePhoneSocket.current };
+}
+
+/** A frame, 720 by 1280 unless `frame` says otherwise, is on the canvas: fitted into the default screen it is 360 by
+ * 640, starting 180 from the left. */
+async function watching(shown: Shown = {}) {
+ const { width, height } = shown.frame ?? { width: 720, height: 1280 };
+ const mounted = await mount(shown);
+ act(() => {
+ mounted.socket.packet(1, PHONE_CONFIG);
+ FakeVideoDecoder.current.frame(width, height);
+ });
+ return mounted;
+}
+
+async function holding(shown: Shown = {}) {
+ const mounted = await watching(shown);
+ act(() => mounted.socket.control(true));
+ return mounted;
+}
+
+const pointer = (screen: HTMLElement, type: string, clientX: number, clientY: number, more: PointerEventInit = {}) =>
+ act(() => { screen.dispatchEvent(new PointerEvent(type, { bubbles: true, clientX, clientY, pointerId: 1, ...more })); });
+const press = (screen: HTMLElement, key: string, more: KeyboardEventInit = {}) => {
+ const event = new KeyboardEvent("keydown", { bubbles: true, cancelable: true, key, ...more });
+ act(() => { screen.dispatchEvent(event); });
+ return event;
+};
+const nextAnimationFrame = () => act(() => { for (const run of animationFrames.splice(0)) run(); });
+const button = (label: string) => [...document.querySelectorAll("button")].find((candidate) => candidate.textContent?.trim() === label);
+const click = (label: string) => act(() => button(label)!.click());
+const textField = () => document.querySelector<HTMLInputElement>('input[type="text"]')!;
+const submit = (text: string) => act(() => {
+ textField().value = text;
+ textField().form!.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
+});
+const compose = (type: "compositionstart" | "compositionend") => act(() => { textField().dispatchEvent(new Event(type, { bubbles: true })); });
+const touch = (action: string, x: number, y: number) => ({ type: "touch", action, x, y, w: 720, h: 1280 });
+
+beforeEach(() => {
+ fakePhoneStream();
+ animationFrames = [];
+ vi.stubGlobal("requestAnimationFrame", (run: () => void) => animationFrames.push(run));
+ vi.stubGlobal("cancelAnimationFrame", (id: number) => { animationFrames[id - 1] = () => {}; });
+});
+afterEach(() => {
+ act(() => root?.unmount());
+ root = null;
+ document.body.innerHTML = "";
+ Reflect.deleteProperty(document, "visibilityState");
+ vi.unstubAllGlobals();
+});
+
+describe("watching the phone", () => {
+ it("opens the phone's stream and shows a spinner until the first frame", async () => {
+ const { socket, screen } = await mount();
+ expect(socket.url.endsWith("/api/usb-phones/p1/stream")).toBe(true);
+ expect(screen.getAttribute("aria-label")).toBe("Interactive Android screen for Pixel");
+ expect(screen.tabIndex).toBe(0);
+ expect(screen.querySelector(".animate-spin")).not.toBeNull();
+ act(() => {
+ socket.packet(1, PHONE_CONFIG);
+ FakeVideoDecoder.current.frame(720, 1280);
+ });
+ expect(screen.querySelector(".animate-spin")).toBeNull();
+ });
+
+ it("says the bots keep working and sends no pointer, key or text input", async () => {
+ const { socket, screen } = await watching();
+ expect(document.body.textContent).toContain("Watching · the bots keep working");
+ pointer(screen, "pointerdown", 270, 160);
+ pointer(screen, "pointermove", 360, 320);
+ nextAnimationFrame();
+ pointer(screen, "pointerup", 360, 320);
+ press(screen, "Enter");
+ press(screen, "a");
+ expect(button("Back")!.disabled).toBe(true);
+ expect(button("Wake")!.disabled).toBe(true);
+ expect(textField().disabled).toBe(true);
+ submit("hello");
+ expect(socket.sent).toEqual([]);
+ });
+
+ it("takes control with the Take control button", async () => {
+ const { socket } = await watching();
+ click("Take control");
+ expect(socket.sent).toEqual([{ type: "take" }]);
+ });
+
+ it("keeps Take control disabled until the first frame", async () => {
+ const { socket } = await mount();
+ expect(button("Take control")!.disabled).toBe(true);
+ act(() => {
+ socket.packet(1, PHONE_CONFIG);
+ FakeVideoDecoder.current.frame(720, 1280);
+ });
+ expect(button("Take control")!.disabled).toBe(false);
+ });
+
+ it.each([
+ ["goes away", () => act(() => root!.unmount())],
+ ["shows another phone", () => act(() => root!.render(panel("p2")))],
+ ])("closes the phone's stream when the panel %s", async (_name, leave) => {
+ const { socket } = await watching();
+ const decoder = FakeVideoDecoder.current;
+ leave();
+ expect(socket.readyState).toBe(3);
+ expect(decoder.state).toBe("closed");
+ });
+});
+
+describe("driving the phone", () => {
+ it("says the person is in control and hands the phone back with the button", async () => {
+ const { socket } = await holding();
+ expect(document.body.textContent).toContain("You're in control");
+ expect(button("Take control")).toBeUndefined();
+ click("Hand control back");
+ expect(socket.sent).toEqual([{ type: "handBack" }]);
+ });
+
+ it("sends a press, the drag and the release in the frame's own pixels", async () => {
+ const { socket, screen } = await holding();
+ pointer(screen, "pointerdown", 270, 160);
+ pointer(screen, "pointermove", 360, 320);
+ nextAnimationFrame();
+ pointer(screen, "pointerup", 450, 480);
+ expect(socket.sent).toEqual([touch("down", 180, 320), touch("move", 360, 640), touch("up", 540, 960)]);
+ });
+
+ it("sends one move an animation frame, the latest, and keeps a drag that leaves the picture on its edge", async () => {
+ const { socket, screen } = await holding();
+ pointer(screen, "pointerdown", 270, 160);
+ pointer(screen, "pointermove", 300, 200);
+ pointer(screen, "pointermove", 360, 320);
+ nextAnimationFrame();
+ pointer(screen, "pointermove", 700, 320);
+ nextAnimationFrame();
+ nextAnimationFrame();
+ expect(socket.sent).toEqual([touch("down", 180, 320), touch("move", 360, 640), touch("move", 719, 640)]);
+ });
+
+ it("puts a release below the picture on its bottom row, and a drag past its left and top edges on the first", async () => {
+ const { socket, screen } = await holding();
+ pointer(screen, "pointerdown", 270, 160);
+ pointer(screen, "pointermove", 100, -20);
+ nextAnimationFrame();
+ pointer(screen, "pointerup", 360, 700);
+ expect(socket.sent).toEqual([touch("down", 180, 320), touch("move", 0, 0), touch("up", 360, 1279)]);
+ });
+
+ it("finds the pixel under the pointer when the screen is not at the page's corner", async () => {
+ const { socket, screen } = await holding({ box: { left: 40, top: 100, width: 720, height: 640 } });
+ pointer(screen, "pointerdown", 310, 260);
+ pointer(screen, "pointerup", 400, 420);
+ expect(socket.sent).toEqual([touch("down", 180, 320), touch("up", 360, 640)]);
+ });
+
+ it("maps a landscape frame in a tall screen from its middle band, and ignores a press in the bar above it", async () => {
+ const landscape = { width: 1280, height: 720 };
+ const { socket, screen } = await holding({ box: { left: 0, top: 0, width: 320, height: 640 }, frame: landscape });
+ pointer(screen, "pointerdown", 160, 100);
+ pointer(screen, "pointerup", 160, 100);
+ expect(socket.sent).toEqual([]);
+
+ pointer(screen, "pointerdown", 160, 320);
+ pointer(screen, "pointerup", 160, 320);
+ expect(socket.sent).toEqual(["down", "up"].map((action) => ({ type: "touch", action, x: 640, y: 360, w: 1280, h: 720 })));
+ });
+
+ it("captures the pointer on a press", async () => {
+ const { screen } = await holding();
+ pointer(screen, "pointerdown", 270, 160);
+ expect(screen.hasPointerCapture(1)).toBe(true);
+ });
+
+ it("sends no touch for a right-click, or for a second pointer pressed during a press", async () => {
+ const { socket, screen } = await holding();
+ pointer(screen, "pointerdown", 270, 160, { button: 2 });
+ pointer(screen, "pointerup", 270, 160, { button: 2 });
+ expect(socket.sent).toEqual([]);
+
+ pointer(screen, "pointerdown", 270, 160);
+ pointer(screen, "pointerdown", 360, 320, { pointerId: 2 });
+ pointer(screen, "pointerup", 450, 480);
+ expect(socket.sent).toEqual([touch("down", 180, 320), touch("up", 540, 960)]);
+ });
+
+ it("leaves a press where it is when another pointer moves or lifts", async () => {
+ const { socket, screen } = await holding();
+ pointer(screen, "pointerdown", 270, 160);
+ pointer(screen, "pointermove", 360, 320, { pointerId: 2 });
+ nextAnimationFrame();
+ pointer(screen, "pointerup", 360, 320, { pointerId: 2 });
+ pointer(screen, "pointerup", 270, 160);
+ expect(socket.sent).toEqual([touch("down", 180, 320), touch("up", 180, 320)]);
+ });
+
+ it("ignores a press beside the picture, and moves with nothing pressed", async () => {
+ const { socket, screen } = await holding();
+ pointer(screen, "pointerdown", 100, 160);
+ pointer(screen, "pointermove", 360, 320);
+ nextAnimationFrame();
+ pointer(screen, "pointerup", 360, 320);
+ expect(socket.sent).toEqual([]);
+ });
+
+ it.each(["pointercancel", "lostpointercapture"])("lifts the finger where it last was on %s, once", async (lost) => {
+ const { socket, screen } = await holding();
+ pointer(screen, "pointerdown", 270, 160);
+ pointer(screen, "pointermove", 360, 320);
+ pointer(screen, lost, 0, 0);
+ nextAnimationFrame();
+ pointer(screen, "pointerup", 450, 480);
+ expect(socket.sent).toEqual([touch("down", 180, 320), touch("up", 360, 640)]);
+ });
+
+ it("stops sending a drag once the phone is no longer held", async () => {
+ const { socket, screen } = await holding();
+ pointer(screen, "pointerdown", 270, 160);
+ act(() => socket.control(false));
+ pointer(screen, "pointermove", 360, 320);
+ nextAnimationFrame();
+ pointer(screen, "pointerup", 360, 320);
+ expect(socket.sent).toEqual([touch("down", 180, 320)]);
+ });
+
+ it("disables the buttons and the text field and sends nothing while the stream connects again, still held", async () => {
+ const { screen } = await holding();
+ act(() => {
+ showPage(false);
+ showPage(true);
+ });
+ expect(FakePhoneSocket.all).toHaveLength(2);
+ expect(document.body.textContent).toContain("You're in control");
+ for (const label of ["Hand control back", "Back", "Home", "Recent", "Wake"]) expect(button(label)!.disabled).toBe(true);
+ expect(textField().disabled).toBe(true);
+
+ pointer(screen, "pointerdown", 270, 160);
+ pointer(screen, "pointermove", 360, 320);
+ nextAnimationFrame();
+ pointer(screen, "pointerup", 360, 320);
+ press(screen, "Enter");
+ press(screen, "a");
+ submit("hello");
+ expect(FakePhoneSocket.current.sent).toEqual([]);
+ });
+
+ it("sends the four buttons as keys", async () => {
+ const { socket } = await holding();
+ for (const label of ["Back", "Home", "Recent", "Wake"]) click(label);
+ expect(socket.sent).toEqual(["back", "home", "recent", "wakeup"].map((key) => ({ type: "key", key })));
+ });
+
+ it("sends the keyboard's editing and arrow keys as keys, Escape as back, and what it types as text", async () => {
+ const { socket, screen } = await holding();
+ for (const key of ["Enter", "Backspace", "Tab", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Escape"]) press(screen, key);
+ press(screen, "a");
+ press(screen, "é");
+ press(screen, "Shift");
+ press(screen, "c", { ctrlKey: true });
+ expect(socket.sent).toEqual([
+ ...["enter", "delete", "tab", "up", "down", "left", "right", "back"].map((key) => ({ type: "key", key })),
+ { type: "text", text: "a" },
+ { type: "text", text: "é" },
+ ]);
+ });
+
+ it("leaves Shift+Tab to the browser and sends nothing, and still sends Tab", async () => {
+ const { socket, screen } = await holding();
+ expect(press(screen, "Tab", { shiftKey: true }).defaultPrevented).toBe(false);
+ expect(socket.sent).toEqual([]);
+
+ expect(press(screen, "Tab").defaultPrevented).toBe(true);
+ expect(socket.sent).toEqual([{ type: "key", key: "tab" }]);
+ });
+
+ it("sends the text field on Enter and clears it, but nothing while an input method is composing", async () => {
+ const { socket } = await holding();
+ compose("compositionstart");
+ submit("ni hao");
+ expect(socket.sent).toEqual([]);
+ expect(textField().value).toBe("ni hao");
+
+ compose("compositionend");
+ submit("你好");
+ expect(socket.sent).toEqual([{ type: "text", text: "你好" }]);
+ expect(textField().value).toBe("");
+ });
+});
+
+describe("a phone screen that cannot be shown", () => {
+ it("always notes what stays black on Android 12 and later", async () => {
+ await mount();
+ expect(document.body.textContent).toContain("On Android 12 and later, the lock screen and protected pages appear black here; do those steps on the phone.");
+ });
+
+ it("explains what the live screen needs when the browser cannot decode it", async () => {
+ vi.stubGlobal("isSecureContext", false);
+ await mount();
+ expect(document.body.textContent).toContain("The live phone screen needs HTTPS or localhost and a browser with WebCodecs.");
+ expect(button("Take control")).toBeUndefined();
+ expect(FakePhoneSocket.all).toHaveLength(0);
+ });
+
+ it("shows why the screen failed and connects again on Retry", async () => {
+ const { socket } = await holding();
+ act(() => socket.closeWith(1011, "The phone's screen could not start."));
+ expect(document.body.textContent).toContain("The phone's screen could not start.");
+ expect(button("Hand control back")).toBeUndefined();
+ click("Retry");
+ expect(FakePhoneSocket.all).toHaveLength(2);
+ expect(document.body.textContent).not.toContain("The phone's screen could not start.");
+ expect(button("Take control")).toBeDefined();
+ });
+
+ it("shows why the phone is gone, with nothing to retry", async () => {
+ const { socket } = await watching();
+ act(() => socket.closeWith(4404, "The phone was unplugged."));
+ expect(document.body.textContent).toContain("The phone was unplugged.");
+ expect(button("Retry")).toBeUndefined();
+ });
+});
diff --git a/src/components/PhoneScreenPanel.tsx b/src/components/PhoneScreenPanel.tsx
new file mode 100644
index 0000000000..eca4343d8d
--- /dev/null
+++ b/src/components/PhoneScreenPanel.tsx
@@ -0,0 +1,191 @@
+import { useEffect, useRef, useState } from "react";
+import { Hand, Loader2, Power } from "lucide-react";
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+import { createPhoneStreamClient, PHONE_STREAM_CLOSE, type PhoneStreamClient, type PhoneStreamView } from "@/lib/phone-stream-client";
+import { ANDROID_KEY_NAMES, AndroidKeyButton, AndroidNavButtons, fittedUnitPoint } from "./android-device-parts";
+
+type Press = { pointerId: number; x: number; y: number; moveFrame: number | null };
+
+const CONNECTING: PhoneStreamView = { status: { kind: "connecting" }, frame: null, held: false };
+
+export function PhoneScreenPanel({ serial, name }: { serial: string; name: string }) {
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const clientRef = useRef<PhoneStreamClient | null>(null);
+ const viewRef = useRef(CONNECTING);
+ const textRef = useRef<HTMLInputElement>(null);
+ const pressRef = useRef<Press | null>(null);
+ const composingRef = useRef(false);
+ const [view, setView] = useState(CONNECTING);
+ const [attempt, setAttempt] = useState(0);
+
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas) return;
+ const client = createPhoneStreamClient({ serial, canvas }, (next) => {
+ viewRef.current = next;
+ setView(next);
+ });
+ clientRef.current = client;
+ return () => {
+ clientRef.current = null;
+ client.stop();
+ };
+ }, [serial, attempt]);
+
+ const drives = (shown: PhoneStreamView) => shown.held && shown.status.kind === "live";
+ const driver = () => (drives(viewRef.current) ? clientRef.current : null);
+
+ const videoPoint = (event: React.PointerEvent<HTMLDivElement>, clampToPicture = false) => {
+ const frame = viewRef.current.frame;
+ const unit = frame && fittedUnitPoint(event.currentTarget.getBoundingClientRect(), frame, event, clampToPicture);
+ if (!frame || !unit) return null;
+ return {
+ x: Math.min(frame.width - 1, Math.floor(unit.x * frame.width)),
+ y: Math.min(frame.height - 1, Math.floor(unit.y * frame.height)),
+ };
+ };
+
+ const lift = (event: React.PointerEvent<HTMLDivElement>, at: { x: number; y: number } | null) => {
+ const press = pressRef.current;
+ if (!press || press.pointerId !== event.pointerId) return;
+ pressRef.current = null;
+ if (press.moveFrame !== null) cancelAnimationFrame(press.moveFrame);
+ driver()?.touch("up", (at ?? press).x, (at ?? press).y);
+ };
+
+ const keyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
+ const client = driver();
+ const movesFocusOut = event.key === "Tab" && event.shiftKey;
+ if (!client || movesFocusOut || event.metaKey || event.ctrlKey || event.altKey) return;
+ const named = ANDROID_KEY_NAMES[event.key];
+ if (named) {
+ event.preventDefault();
+ client.key(named);
+ } else if ([...event.key].length === 1) {
+ event.preventDefault();
+ client.text(event.key);
+ }
+ };
+
+ const sendText = (event: React.FormEvent<HTMLFormElement>) => {
+ event.preventDefault();
+ const field = textRef.current;
+ const client = driver();
+ if (!client || !field?.value || composingRef.current) return;
+ client.text(field.value);
+ field.value = "";
+ };
+
+ const { status, held } = view;
+ const driving = drives(view);
+ const streaming = status.kind === "connecting" || status.kind === "live";
+
+ return (
+ <>
+ {streaming && (
+ <div className="flex items-center justify-between gap-3 rounded-xl bg-card px-4 py-2.5">
+ <span role="status" className="flex items-center gap-1.5 text-[12px] text-ink-secondary">
+ {held && <span className="size-1.5 rounded-full bg-success" />}
+ {t(held ? "computer.inControl" : "computer.android.watching")}
+ </span>
+ <button
+ onClick={() => (held ? clientRef.current?.handBack() : clientRef.current?.take())}
+ disabled={status.kind !== "live"}
+ className={cn(
+ "flex shrink-0 items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12px] disabled:opacity-50",
+ held ? "bg-accent font-medium text-accent-ink hover:brightness-110" : "bg-control text-ink hover:bg-raised-hover",
+ )}
+ >
+ <Hand size={13} /> {t(held ? "computer.handBack" : "computer.takeControl")}
+ </button>
+ </div>
+ )}
+
+ <div
+ role="application"
+ aria-label={t("computer.android.screenAria", { name })}
+ tabIndex={0}
+ onKeyDown={keyDown}
+ onPointerDown={(event) => {
+ const client = driver();
+ const point = videoPoint(event);
+ if (!client || !point || pressRef.current || event.button !== 0) return;
+ event.currentTarget.setPointerCapture(event.pointerId);
+ event.currentTarget.focus();
+ pressRef.current = { pointerId: event.pointerId, ...point, moveFrame: null };
+ client.touch("down", point.x, point.y);
+ }}
+ onPointerMove={(event) => {
+ const press = pressRef.current;
+ const point = videoPoint(event, true);
+ if (!press || press.pointerId !== event.pointerId || !point) return;
+ press.x = point.x;
+ press.y = point.y;
+ press.moveFrame ??= requestAnimationFrame(() => {
+ press.moveFrame = null;
+ if (pressRef.current === press) driver()?.touch("move", press.x, press.y);
+ });
+ }}
+ onPointerUp={(event) => lift(event, videoPoint(event, true))}
+ onPointerCancel={(event) => lift(event, null)}
+ onLostPointerCapture={(event) => lift(event, null)}
+ className={cn(
+ "relative mx-auto flex h-[520px] w-full touch-none items-center justify-center overflow-hidden overscroll-none rounded-[28px] bg-black outline-none ring-1 ring-white/10 focus:ring-2 focus:ring-accent",
+ driving && "cursor-pointer",
+ )}
+ >
+ <canvas ref={canvasRef} className={cn("pointer-events-none h-full w-full select-none object-contain", status.kind !== "live" && "opacity-40")} />
+ {status.kind !== "live" && (
+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-3 px-6 text-center text-[12px] leading-relaxed text-white/80">
+ {status.kind === "connecting" ? (
+ <Loader2 size={20} className="animate-spin" />
+ ) : status.kind === "closed" ? (
+ <>
+ <span role="alert">{status.reason || t("computer.android.liveStopped")}</span>
+ {status.code === PHONE_STREAM_CLOSE.failed && (
+ <button
+ onClick={() => setAttempt((count) => count + 1)}
+ className="rounded-lg bg-white/15 px-3 py-1.5 text-white hover:bg-white/25"
+ >
+ {t("computer.android.retry")}
+ </button>
+ )}
+ </>
+ ) : (
+ t("computer.android.liveUnsupported")
+ )}
+ </div>
+ )}
+ </div>
+
+ {streaming && (
+ <>
+ <div className="grid grid-cols-4 gap-2">
+ <AndroidNavButtons onKey={(key) => driver()?.key(key)} disabled={!driving} />
+ <AndroidKeyButton onClick={() => driver()?.key("wakeup")} disabled={!driving}>
+ <Power size={13} /> {t("computer.android.wake")}
+ </AndroidKeyButton>
+ </div>
+ <form onSubmit={sendText}>
+ <input
+ ref={textRef}
+ type="text"
+ autoComplete="off"
+ disabled={!driving}
+ aria-label={t("computer.android.textAria")}
+ placeholder={t("computer.android.textPlaceholder")}
+ onCompositionStart={() => { composingRef.current = true; }}
+ onCompositionEnd={() => { composingRef.current = false; }}
+ className="w-full rounded-lg bg-raised px-3 py-2 text-[12px] text-ink outline-none placeholder:text-ink-secondary focus:ring-2 focus:ring-accent disabled:opacity-50"
+ />
+ </form>
+ </>
+ )}
+
+ <div className="text-center text-[11px] leading-relaxed text-ink-secondary">
+ {t("computer.android.secureNote")}
+ </div>
+ </>
+ );
+}
diff --git a/src/components/UsbPhoneTakeoverSettings.test.ts b/src/components/UsbPhoneTakeoverSettings.test.ts
new file mode 100644
index 0000000000..b03f43c393
--- /dev/null
+++ b/src/components/UsbPhoneTakeoverSettings.test.ts
@@ -0,0 +1,80 @@
+// @vitest-environment happy-dom
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { setLocale } from "@/lib/i18n";
+import { UsbPhoneTakeoverSettings } from "./UsbPhoneTakeoverSettings";
+
+const fixture = vi.hoisted(() => ({
+ config: undefined as Record<string, unknown> | undefined,
+ api: vi.fn(),
+ dispatch: vi.fn(),
+}));
+vi.mock("@/state/store", () => ({
+ api: fixture.api,
+ useStore: () => ({ state: { config: fixture.config }, dispatch: fixture.dispatch }),
+}));
+
+let host: HTMLDivElement;
+let root: Root;
+const render = () => flushSync(() => root.render(createElement(UsbPhoneTakeoverSettings)));
+const toggle = () => host.querySelector<HTMLButtonElement>('button[aria-label="Watch and take over the USB phone"]');
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ setLocale("en");
+ fixture.dispatch.mockImplementation((action: { type: string; config?: Record<string, unknown> }) => {
+ if (action.type === "configStatus") fixture.config = action.config;
+ });
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(() => {
+ flushSync(() => root.unmount());
+ host.remove();
+});
+
+describe("Watch and take over the USB phone setting", () => {
+ it("is not shown by a server that does not report the flag", () => {
+ fixture.config = { features: { skillAuthoring: true } };
+ render();
+ expect(host.textContent).toBe("");
+ });
+
+ it("starts off, and turns on as features.usbPhoneTakeover with the server's answer", async () => {
+ fixture.config = { features: { usbPhoneTakeover: false } };
+ const saved = { features: { usbPhoneTakeover: true } };
+ fixture.api.mockResolvedValue(saved);
+ render();
+ expect(toggle()!.getAttribute("aria-checked")).toBe("false");
+ expect(host.textContent).toContain("Shows the bots' USB Android phone live");
+ expect(host.textContent).not.toContain("Off by default.");
+ flushSync(() => [...host.querySelectorAll("button")].find((button) => !button.hasAttribute("aria-label"))!.click());
+ expect(host.textContent).toContain("Off by default.");
+
+ flushSync(() => toggle()!.click());
+ await vi.waitFor(() => expect(fixture.dispatch).toHaveBeenCalledWith({ type: "configStatus", config: saved }));
+ expect(fixture.api).toHaveBeenCalledExactlyOnceWith("/api/config", {
+ method: "PATCH",
+ body: JSON.stringify({ features: { usbPhoneTakeover: true } }),
+ });
+ render();
+ expect(toggle()!.getAttribute("aria-checked")).toBe("true");
+ });
+
+ it("turns off again, and shows a refusal from the server", async () => {
+ fixture.config = { features: { usbPhoneTakeover: true } };
+ fixture.api.mockRejectedValue(new Error("only an admin may change this"));
+ render();
+ flushSync(() => toggle()!.click());
+ await vi.waitFor(() => expect(host.querySelector('[role="alert"]')?.textContent).toBe("only an admin may change this"));
+ expect(fixture.api).toHaveBeenCalledExactlyOnceWith("/api/config", {
+ method: "PATCH",
+ body: JSON.stringify({ features: { usbPhoneTakeover: false } }),
+ });
+ expect(toggle()!.getAttribute("aria-checked")).toBe("true");
+ });
+});
diff --git a/src/components/UsbPhoneTakeoverSettings.tsx b/src/components/UsbPhoneTakeoverSettings.tsx
new file mode 100644
index 0000000000..9ee6d10a00
--- /dev/null
+++ b/src/components/UsbPhoneTakeoverSettings.tsx
@@ -0,0 +1,29 @@
+import { usbPhoneTakeoverEnabled } from "@/lib/feature-flags";
+import { t } from "@/lib/i18n";
+import { useStore } from "@/state/store";
+import { useConfigSave } from "./BrowserSettingsRows";
+import { MoreText, SettingRow, Switch } from "./SettingsPrimitives";
+
+/** features.usbPhoneTakeover. Shown only where the server reports the flag: one with no USB port leaves it out. */
+export function UsbPhoneTakeoverSettings() {
+ const { state } = useStore();
+ const on = usbPhoneTakeoverEnabled(state.config);
+ const { saving, error, save } = useConfigSave();
+ if (state.config?.features?.usbPhoneTakeover === undefined) return null;
+
+ return (
+ <div data-testid="usb-phone-takeover-settings" className="contents">
+ <SettingRow title={t("settings.experimental.usbPhoneTakeover")} tag={t("settings.early.tag")}
+ subtitle={<MoreText short={t("settings.experimental.usbPhoneTakeoverShort")} long={t("settings.experimental.usbPhoneTakeoverDetail")} />}
+ message={error ? <span role="alert" className="text-danger">{error}</span> : undefined}>
+ <Switch
+ checked={on}
+ aria-label={t("settings.experimental.usbPhoneTakeover")}
+ disabled={saving}
+ onClick={() => void save({ features: { usbPhoneTakeover: !on } })}
+ className="disabled:cursor-wait disabled:opacity-50"
+ />
+ </SettingRow>
+ </div>
+ );
+}
diff --git a/src/components/android-device-parts.tsx b/src/components/android-device-parts.tsx
new file mode 100644
index 0000000000..0e88178023
--- /dev/null
+++ b/src/components/android-device-parts.tsx
@@ -0,0 +1,68 @@
+import type { ReactNode } from "react";
+import { ArrowLeft, Circle, RotateCcw } from "lucide-react";
+import { t } from "@/lib/i18n";
+import type { PhoneKey } from "@/lib/phone-stream-client";
+
+export type UnitPoint = { x: number; y: number };
+
+/** Where a pointer falls on a picture fitted (`object-contain`) inside `bounds`, as fractions of the picture: null
+ * outside it, unless clamped to its edge. */
+export function fittedUnitPoint(
+ bounds: Pick<DOMRect, "left" | "top" | "width" | "height">,
+ picture: { width: number; height: number },
+ pointer: { clientX: number; clientY: number },
+ clampToPicture = false,
+): UnitPoint | null {
+ if (!picture.width || !picture.height) return null;
+ const scale = Math.min(bounds.width / picture.width, bounds.height / picture.height);
+ const fittedWidth = picture.width * scale;
+ const fittedHeight = picture.height * scale;
+ const left = bounds.left + (bounds.width - fittedWidth) / 2;
+ const top = bounds.top + (bounds.height - fittedHeight) / 2;
+ const x = (pointer.clientX - left) / fittedWidth;
+ const y = (pointer.clientY - top) / fittedHeight;
+ if (clampToPicture) {
+ return { x: Math.max(0, Math.min(1, x)), y: Math.max(0, Math.min(1, y)) };
+ }
+ return x >= 0 && x <= 1 && y >= 0 && y <= 1 ? { x, y } : null;
+}
+
+export const ANDROID_KEY_NAMES: Readonly<Record<string, PhoneKey>> = {
+ ArrowDown: "down",
+ ArrowLeft: "left",
+ ArrowRight: "right",
+ ArrowUp: "up",
+ Backspace: "delete",
+ Delete: "delete",
+ Enter: "enter",
+ Escape: "back",
+ Tab: "tab",
+};
+
+export function AndroidKeyButton({ onClick, disabled, children }: { onClick: () => void; disabled?: boolean; children: ReactNode }) {
+ return (
+ <button
+ onClick={onClick}
+ disabled={disabled}
+ className="flex items-center justify-center gap-1.5 rounded-lg bg-raised py-2 text-[12px] text-ink hover:bg-raised-hover disabled:opacity-50 disabled:hover:bg-raised"
+ >
+ {children}
+ </button>
+ );
+}
+
+export function AndroidNavButtons({ onKey, disabled }: { onKey: (key: "back" | "home" | "recent") => void; disabled?: boolean }) {
+ return (
+ <>
+ <AndroidKeyButton onClick={() => onKey("back")} disabled={disabled}>
+ <ArrowLeft size={13} /> {t("computer.android.back")}
+ </AndroidKeyButton>
+ <AndroidKeyButton onClick={() => onKey("home")} disabled={disabled}>
+ <Circle size={12} /> {t("computer.android.home")}
+ </AndroidKeyButton>
+ <AndroidKeyButton onClick={() => onKey("recent")} disabled={disabled}>
+ <RotateCcw size={13} /> {t("computer.android.recent")}
+ </AndroidKeyButton>
+ </>
+ );
+}
diff --git a/src/lib/feature-flags.test.ts b/src/lib/feature-flags.test.ts
index 31fb50d47a..da2d93d47e 100644
--- a/src/lib/feature-flags.test.ts
+++ b/src/lib/feature-flags.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { builtInBrowserEnabled, llmThreadTitlesEnabled, parseSkillReviewSteps, roomMemoryCaptureEnabled, savedStepsEnabled, shareLearnedSkillsMode, sharedComputersEnabled, showToolCallsEnabled, skillAuthoringEnabled, skillReviewEnabled, skillReviewSteps, skillReviewUnavailableEngines } from "./feature-flags";
+import { builtInBrowserEnabled, llmThreadTitlesEnabled, parseSkillReviewSteps, roomMemoryCaptureEnabled, savedStepsEnabled, shareLearnedSkillsMode, sharedComputersEnabled, showToolCallsEnabled, skillAuthoringEnabled, skillReviewEnabled, skillReviewSteps, skillReviewUnavailableEngines, usbPhoneTakeoverEnabled } from "./feature-flags";
describe("experimental feature flags", () => {
it("keeps skill authoring on by default, before and after the config arrives", () => {
@@ -82,6 +82,13 @@ describe("experimental feature flags", () => {
expect(roomMemoryCaptureEnabled({ features: { roomMemoryCapture: true } })).toBe(true);
});
+ it("keeps the USB phone's screen and takeover off until switched on", () => {
+ expect(usbPhoneTakeoverEnabled(null)).toBe(false);
+ expect(usbPhoneTakeoverEnabled({ features: {} })).toBe(false);
+ expect(usbPhoneTakeoverEnabled({ features: { usbPhoneTakeover: false } })).toBe(false);
+ expect(usbPhoneTakeoverEnabled({ features: { usbPhoneTakeover: true } })).toBe(true);
+ });
+
it("offers sharing learned skills only with the skills library, asking by default", () => {
expect(shareLearnedSkillsMode(null)).toBe("off");
expect(shareLearnedSkillsMode({ features: { shareLearnedSkills: "auto" } })).toBe("off");
diff --git a/src/lib/feature-flags.ts b/src/lib/feature-flags.ts
index 307f9c5f6a..1dc1ee5302 100644
--- a/src/lib/feature-flags.ts
+++ b/src/lib/feature-flags.ts
@@ -1,7 +1,7 @@
import { t } from "./i18n";
export interface FeatureFlagConfig {
- features?: { skillAuthoring?: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; claudeUserSkills?: boolean; llmThreadTitles?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; savedSteps?: boolean; savedStepsHere?: boolean };
+ features?: { skillAuthoring?: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; claudeUserSkills?: boolean; llmThreadTitles?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; savedSteps?: boolean; savedStepsHere?: boolean; usbPhoneTakeover?: boolean };
browserEngine?: { kind: "engine" | "unavailable"; reason?: string; installable?: boolean; installing?: boolean; installError?: string };
}
@@ -97,3 +97,7 @@ export function savedStepsEnabled(config: FeatureFlagConfig | null | undefined):
export function savedStepsHere(config: FeatureFlagConfig | null | undefined): boolean {
return config?.features?.savedStepsHere === true;
}
+
+export function usbPhoneTakeoverEnabled(config: FeatureFlagConfig | null | undefined): boolean {
+ return config?.features?.usbPhoneTakeover === true;
+}
diff --git a/src/locales/en.json b/src/locales/en.json
index bf963b7654..62d4361ee8 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -3653,6 +3653,9 @@
"settings.experimental.newBrowser": "New browser",
"settings.experimental.newBrowserDetail": "Off by default. Bots' browsers run on {app}'s own Chrome driver instead of agent-browser: pages render at your screen's sharpness, and bots can handle uploads, downloads, dialogs and pop-ups. Profiles that use your own Chrome are not affected. Switching closes open browsers, and sign-ins saved in one do not carry over to the other.",
"settings.experimental.newBrowserAria": "Use the new browser",
+ "settings.experimental.usbPhoneTakeover": "Watch and take over the USB phone",
+ "settings.experimental.usbPhoneTakeoverShort": "Shows the bots' USB Android phone live in the Screen panel and lets you take it over.",
+ "settings.experimental.usbPhoneTakeoverDetail": "Off by default. Shows the bots' USB Android phone live in the Screen panel and lets you take it over. The first use downloads the scrcpy server (734 KB) from GitHub.",
"browser.notInstalled": "The browser isn't installed here yet. Turn on the browser switches in App Settings → Devices and in the bot's Access settings, then open Bot's screen → Browser to install it. Or run `openmausbot browser install` where the app runs.",
"browser.panel.profileTitle": "Browser profile: {name}",
"browser.panel.profiles": "Browser profiles",
@@ -5747,6 +5750,7 @@
"computer.screen.choose": "Choose a screen",
"computer.screen.start": "Start preview",
"computer.android.usbSubtitle": "Connected directly over USB. The screen and controls stay on this computer.",
+ "computer.android.serverSubtitle": "Connected over USB to the computer that runs OpenMausBot.",
"computer.android.usb": "USB",
"computer.android.unauthorized": "Unlock the Android phone, accept the “Allow USB debugging” prompt, and optionally choose Always allow from this computer.",
"computer.android.badState": "The phone is {state}. Reconnect the USB cable and keep USB debugging enabled.",
@@ -5766,6 +5770,14 @@
"computer.android.agentNote": "Agent control uses this same authorized USB connection. No phone companion app, account, Tailscale, or wireless pairing is needed.",
"computer.android.harnessNote": "Once connected, ask any compatible Maus to open an Android app or complete a task on your phone. The bundled Phone Harness skill loads automatically for phone requests.",
"computer.android.step2": "Enable Developer options by tapping {buildNumber} seven times in About phone, then turn on {usbDebugging}.",
+ "computer.android.watching": "Watching · the bots keep working",
+ "computer.android.wake": "Wake",
+ "computer.android.textAria": "Text to send to the phone",
+ "computer.android.textPlaceholder": "Type here, then press Enter to send it to the phone",
+ "computer.android.liveUnsupported": "The live phone screen needs HTTPS or localhost and a browser with WebCodecs.",
+ "computer.android.liveStopped": "The live phone screen stopped.",
+ "computer.android.retry": "Retry",
+ "computer.android.secureNote": "On Android 12 and later, the lock screen and protected pages appear black here; do those steps on the phone.",
"connectors.card.popupBlocked": "Your browser blocked the connection page. Allow pop-ups, then try again.",
"connectors.card.connected": "Connected",
"connectors.card.alsoUseful": "Also useful",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index c0b918a2a6..4f97983342 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -3476,6 +3476,9 @@
"settings.experimental.newBrowser": "Novo navegador",
"settings.experimental.newBrowserDetail": "Desligado por padrão. Os navegadores dos bots usam o driver Chrome do próprio app {app} em vez do agent-browser. As páginas aparecem com a nitidez da sua tela, e os bots podem lidar com envios, downloads, diálogos e pop-ups. Perfis que usam seu próprio Chrome não são afetados. A mudança fecha os navegadores abertos, e os logins salvos em um não passam para o outro.",
"settings.experimental.newBrowserAria": "Usar o novo navegador",
+ "settings.experimental.usbPhoneTakeover": "Ver e assumir o controle do celular USB",
+ "settings.experimental.usbPhoneTakeoverShort": "Mostra ao vivo o celular Android USB dos bots no painel Tela e permite que você assuma o controle dele.",
+ "settings.experimental.usbPhoneTakeoverDetail": "Desligado por padrão. Mostra ao vivo o celular Android USB dos bots no painel Tela e permite que você assuma o controle dele. O primeiro uso baixa o servidor scrcpy (734 KB) do GitHub.",
"browser.notInstalled": "O navegador ainda não está instalado aqui. Ligue as opções de navegador em Configurações do app → Dispositivos e nas configurações de acesso do bot. Depois, abra Tela do bot → Navegador para instalá-lo. Ou execute `openmausbot browser install` onde o app roda.",
"browser.panel.profileTitle": "Perfil do navegador: {name}",
"browser.panel.profiles": "Perfis do navegador",
@@ -5433,6 +5436,7 @@
"computer.screen.choose": "Escolher uma tela",
"computer.screen.start": "Iniciar prévia",
"computer.android.usbSubtitle": "Conectado direto por USB. A tela e os controles ficam neste computador.",
+ "computer.android.serverSubtitle": "Conectado por USB ao computador onde o OpenMausBot roda.",
"computer.android.usb": "USB",
"computer.android.unauthorized": "Desbloqueie o celular Android, aceite o aviso “Permitir depuração USB” e, se quiser, escolha Sempre permitir a partir deste computador.",
"computer.android.badState": "Estado do celular: {state}. Reconecte o cabo USB e mantenha a depuração USB ativada.",
@@ -5452,6 +5456,14 @@
"computer.android.agentNote": "O controle pelo agente usa esta mesma conexão USB autorizada. Não é preciso app complementar no celular, conta, Tailscale nem pareamento sem fio.",
"computer.android.harnessNote": "Depois de conectar, peça a qualquer Maus compatível para abrir um app Android ou concluir uma tarefa no seu celular. A habilidade Phone Harness já vem incluída e é carregada automaticamente quando há pedidos para o celular.",
"computer.android.step2": "Ative as opções do desenvolvedor tocando sete vezes em {buildNumber}, em Sobre o telefone, e depois ligue {usbDebugging}.",
+ "computer.android.watching": "Assistindo · os bots continuam trabalhando",
+ "computer.android.wake": "Acordar",
+ "computer.android.textAria": "Texto para enviar ao celular",
+ "computer.android.textPlaceholder": "Digite aqui e aperte Enter para enviar ao celular",
+ "computer.android.liveUnsupported": "A tela ao vivo do celular precisa de HTTPS ou localhost e de um navegador com WebCodecs.",
+ "computer.android.liveStopped": "A tela ao vivo do celular parou.",
+ "computer.android.retry": "Tentar novamente",
+ "computer.android.secureNote": "No Android 12 e posteriores, a tela de bloqueio e as páginas protegidas aparecem em preto aqui; faça essas etapas no celular.",
"connectors.card.popupBlocked": "Seu navegador bloqueou a página de conexão. Permita pop-ups e tente novamente.",
"connectors.card.connected": "Conectado",
"connectors.card.alsoUseful": "Também úteis",
diff --git a/src/state/config-status.ts b/src/state/config-status.ts
index 4ce7c1ea18..2145dc7a79 100644
--- a/src/state/config-status.ts
+++ b/src/state/config-status.ts
@@ -147,7 +147,7 @@ export interface ConfigStatus {
/** What a paired phone calls this computer; "" uses the default. */
computerName?: string;
/** Opt-in flags. Absent means off. */
- features?: { skillAuthoring: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; llmThreadTitles?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; savedSteps?: boolean; savedStepsHere?: boolean };
+ features?: { skillAuthoring: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; llmThreadTitles?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; savedSteps?: boolean; savedStepsHere?: boolean; usbPhoneTakeover?: boolean };
/** First-run progress: whether the welcome tour was finished and which
* one-time hints were dismissed. Server-owned so it follows the workspace. */
onboarding?: OnboardingStatus;