Skip to content

An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.

feat(android): browsentic android says whether a phone is ready, one checklist row per check with its fix, and android open [url] opens Chrome on it; status gets an android line that never starts adb

Shahriar87fcece69247
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index f84279c..640ec12 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -96,6 +96,18 @@ See [guide/pair.md](../guide/pair.md).
`agent fix` was called `agent setup` before `setup` came to mean installing Browsentic. The old
spelling still works and is undocumented.
+## Android
+
+| Command | Does |
+| --- | --- |
+| `browsentic android` | Whether a phone is ready to drive from the side panel: adb, the phone, USB debugging, Chrome, Chrome open and the screen, one row each. A row that fails says what to do; when nothing is ready, the setup steps follow |
+| `browsentic android open [url]` | Open Chrome on the phone, at that page if one is given (in a new tab when Chrome is already open). With more than one phone, name it with `--serial <serial>` |
+
+`android` takes `--json`: the state the apps read, with the setup steps as `guide`. Browsentic finds
+adb on `PATH`, under `ANDROID_HOME` or `ANDROID_SDK_ROOT`, in Android Studio's SDK, or where Homebrew
+puts it; `"android": { "adb": "<path>" }` in `config.json` names one, and
+`"android": { "enabled": false }` stops the Bridge using adb at all.
+
## MCP
| Command | Does |
@@ -109,7 +121,7 @@ configurations written against the older name keep working.
| Command | Does |
| --- | --- |
-| `browsentic status` | The Bridge, which browsers can start it, the agent, and one row per paired browser with its extension version, its store and whether it is connected; flags an unpacked copy that needs ↻ and two copies answering in one browser |
+| `browsentic status` | The Bridge, which browsers can start it, the agent, Android, and one row per paired browser with its extension version, its store and whether it is connected; flags an unpacked copy that needs ↻ and two copies answering in one browser. The Android line says what the Bridge already knows and never starts adb: `not checked` until a browser is watching for phones |
| `browsentic logs` | Print the Bridge's log (`~/.browsentic/daemon.log`) |
| `browsentic tools` | Print the bundled tool manifest as JSON. **No browser needed** |
| `browsentic skills` | Every skill the router can see, tagged `bundled`, `user` or `uploaded` |
@@ -122,7 +134,7 @@ configurations written against the older name keep working.
| `browsentic downloads clear` | Delete all of them |
| `browsentic token` | The control token, for MCP clients. Not for the browser |
-`agent`, `skills`, `approvals`, `tasks` and `downloads` take `--json`. It is what the [macOS](../guide/mac-app.md) and
+`agent`, `android`, `skills`, `approvals`, `tasks` and `downloads` take `--json`. It is what the [macOS](../guide/mac-app.md) and
[Windows](../guide/windows-app.md) apps read, so an app and a terminal can never disagree about what is on disk.
## Lifecycle
diff --git a/src/daemon/android/launch.ts b/src/daemon/android/launch.ts
index 5b821c2..0d4c3b9 100644
--- a/src/daemon/android/launch.ts
+++ b/src/daemon/android/launch.ts
@@ -9,8 +9,8 @@ const AM_TIMEOUT_MS = 10_000;
export const INSTALL_CHROME_COMMAND = `am start -a android.intent.action.VIEW -d 'market://details?id=${CHROME_PACKAGE}'`;
/**
- * A VIEW intent opens a new tab every time Chrome is already running, so a URL rides along only
- * on a cold start; a running Chrome is sent its URLs over DevTools.
+ * With a URL this is a VIEW intent, which opens a new tab every time Chrome is already running:
+ * only a person asking for that page sends one, and a session opens its pages over DevTools.
*/
export function launchChromeCommand(url?: string): string {
const target = url && webUrl(url);
diff --git a/src/daemon/android/report.test.ts b/src/daemon/android/report.test.ts
new file mode 100644
index 0000000..e2838aa
--- /dev/null
+++ b/src/daemon/android/report.test.ts
@@ -0,0 +1,163 @@
+import { readFileSync } from 'node:fs';
+import { describe, expect, test } from 'vitest';
+import type { AndroidState } from '@/lib/phone/types';
+import { parseDeviceList } from './devices';
+import { parseFacts, type PhoneFacts } from './phone-facts';
+import { judge, type Observed } from './readiness';
+import { androidArgs, androidJson, androidLines, androidStatus } from './report';
+
+const fixture = (name: string) => readFileSync(new URL(`./fixtures/${name}`, import.meta.url), 'utf8');
+
+const ADB = { path: '/Users/me/Library/Android/sdk/platform-tools/adb', version: '37.0.0-14910828' };
+const [emulator] = parseDeviceList(fixture('devices-emulator.txt'));
+const open = parseFacts(fixture('facts-chrome-open.txt'));
+const SESSION = { serial: 'emulator-5554', since: '2026-10-09T19:10:01.839Z' };
+
+const seen = (devices: Observed['devices'], more: Partial<Observed> = {}): AndroidState =>
+ judge({ enabled: true, platform: 'darwin', adb: ADB, devices, ...more });
+const phone = (facts: PhoneFacts | null = open, device = emulator) => ({ device, facts });
+const chrome = (change: Partial<PhoneFacts['chrome']>): PhoneFacts => ({ ...open, chrome: { ...open.chrome, ...change } });
+
+const STATES = {
+ ready: seen([phone()]),
+ adbMissing: seen([], { adb: null }),
+ noDevice: seen([]),
+ unauthorized: seen([phone(null, { ...emulator, serial: 'R5CT1234567', state: 'unauthorized', adbState: 'unauthorized', model: undefined })]),
+};
+
+const text = (state: AndroidState) => androidLines(state).join('\n');
+
+describe('browsentic android', () => {
+ test('ready: every check passes, and the side panel is next', () => {
+ expect(text(STATES.ready)).toBe(
+ [
+ '✓ adb /Users/me/Library/Android/sdk/platform-tools/adb (37.0.0-14910828)',
+ '✓ Phone sdk_gphone16k_arm64, Android 17, USB (emulator-5554)',
+ '✓ USB debugging allowed',
+ '✓ Chrome 150.0.7871.186',
+ '✓ Chrome open its DevTools socket is open',
+ '✓ Screen awake',
+ '',
+ 'Ready. Switch on Android in the Browsentic side panel to drive it.',
+ ].join('\n'),
+ );
+ });
+
+ test('in use: says which phone a browser is driving', () => {
+ expect(androidLines({ ...STATES.ready, session: SESSION }).at(-1)).toBe('Android is on in a browser, driving emulator-5554.');
+ });
+
+ test('no adb: the adb row fails with the install command, then the setup steps', () => {
+ const lines = androidLines(STATES.adbMissing);
+ expect(lines.slice(0, 2)).toEqual([
+ expect.stringMatching(/^✗ adb {16}Browsentic reaches your phone through adb/),
+ ' brew install --cask android-platform-tools',
+ ]);
+ expect(lines).toContain('To connect a phone:');
+ expect(lines.filter((line) => /^ {2}\d\. /.test(line))).toHaveLength(6);
+ });
+
+ test('no phone: the phone row fails, then the setup steps, with the Wi-Fi one marked for Android 11', () => {
+ const lines = androidLines(STATES.noDevice);
+ expect(lines[1]).toBe('✗ Phone No Android phone is connected.');
+ expect(lines.find((line) => line.startsWith(' 4. '))).toMatch(/^ {2}4\. Or connect over Wi-Fi \(Android 11 or later\): /);
+ });
+
+ test('waiting for Allow: the USB debugging row fails with what to tap', () => {
+ expect(androidLines(STATES.unauthorized).slice(1, 4)).toEqual([
+ '✓ Phone Android phone, USB (R5CT1234567)',
+ '✗ USB debugging The phone has not allowed this computer yet.',
+ ' Unlock your phone and tap Allow on the USB debugging prompt. If no prompt shows, unplug the phone and plug it in again.',
+ ]);
+ });
+
+ const failingRows: [string, AndroidState, string][] = [
+ ['offline', seen([phone(null, { ...emulator, state: 'offline', adbState: 'offline' })]), '✗ Phone sdk gphone16k arm64, USB (emulator-5554): The phone is connected but not answering adb.'],
+ ['silent', seen([phone(null)]), '✗ Phone sdk gphone16k arm64, USB (emulator-5554): The phone stopped answering adb.'],
+ ['booting', seen([phone({ ...open, booted: false })]), '✗ Phone sdk_gphone16k_arm64, Android 17, USB (emulator-5554): The phone is still starting up.'],
+ ['no udev rules', seen([phone(null, { ...emulator, state: 'no-permissions', adbState: 'no permissions' })], { platform: 'linux' }), "✗ Phone sdk gphone16k arm64, USB (emulator-5554): This computer is not allowed to open the phone's USB connection."],
+ ['no Chrome', seen([phone(chrome({ installed: false, version: undefined, running: false, debuggable: false }))]), '✗ Chrome Chrome is not installed on the phone.'],
+ ['Chrome closed', seen([phone(chrome({ running: false, debuggable: false }))]), '✗ Chrome open Chrome is not open on the phone.'],
+ ['adb broken', seen([], { adb: { path: ADB.path, broken: 'Bad CPU type in executable' } }), `✗ adb adb at ${ADB.path} does not run: Bad CPU type in executable`],
+ ];
+
+ test.each(failingRows)('%s: one failing row, and nothing past it', (_name, state, failing) => {
+ const lines = androidLines(state);
+ const at = lines.indexOf(failing);
+ expect(at).toBeGreaterThanOrEqual(0);
+ expect(lines.slice(0, at).every((line) => line.startsWith('✓ '))).toBe(true);
+ expect(lines.slice(at + 1).some((line) => /^[✓✗·] /.test(line))).toBe(false);
+ });
+
+ test('only a phone not yet connected or allowed gets the setup steps', () => {
+ const guided = (state: AndroidState) => androidLines(state).includes('To connect a phone:');
+ expect([STATES.adbMissing, STATES.noDevice, STATES.unauthorized].map(guided)).toEqual([true, true, true]);
+ expect(failingRows.map(([, state]) => guided(state))).toEqual(failingRows.map(() => false));
+ });
+
+ test('Chrome closed also names the command that opens it', () => {
+ const lines = androidLines(failingRows[5][1]);
+ const at = lines.indexOf('✗ Chrome open Chrome is not open on the phone.');
+ expect(lines.slice(at, at + 3)).toEqual([
+ '✗ Chrome open Chrome is not open on the phone.',
+ ' Open Chrome on the phone.',
+ ' or run "browsentic android open"',
+ ]);
+ });
+
+ test('the screen off is advice under a ready phone', () => {
+ const lines = androidLines(seen([phone({ ...open, screen: { ...open.screen!, awake: false } })]));
+ expect(lines).toContain("· Screen The phone's screen is off, so Chrome is not drawing the page.");
+ expect(lines.at(-1)).toMatch(/^Ready\./);
+ });
+
+ test('switched off is one line', () => {
+ expect(androidLines(judge({ enabled: false, platform: 'darwin', devices: [] }))).toEqual([
+ '· Android Android is switched off for this computer.',
+ ' Set "android": { "enabled": true } in ~/.browsentic/config.json',
+ ]);
+ });
+
+ test('two phones get a block each, headed by its serial', () => {
+ const lines = androidLines(seen([phone(), phone(null, { ...emulator, serial: 'R5CT1234567', state: 'unauthorized', adbState: 'unauthorized' })]));
+ expect(lines.filter((line) => line === 'emulator-5554' || line === 'R5CT1234567')).toEqual(['emulator-5554', 'R5CT1234567']);
+ expect(lines.indexOf('R5CT1234567')).toBe(lines.indexOf('emulator-5554') + 7);
+ });
+});
+
+describe('the command line', () => {
+ test.each<[string[], ReturnType<typeof androidArgs>]>([
+ [[], { sub: undefined, url: undefined, serial: undefined }],
+ [['--json'], { sub: undefined, url: undefined, serial: undefined }],
+ [['open'], { sub: 'open', url: undefined, serial: undefined }],
+ [['open', 'https://example.com/'], { sub: 'open', url: 'https://example.com/', serial: undefined }],
+ [['open', '--serial', 'R5CT1234567', 'https://example.com/'], { sub: 'open', url: 'https://example.com/', serial: 'R5CT1234567' }],
+ [['--serial', 'R5CT1234567', 'open'], { sub: 'open', url: undefined, serial: 'R5CT1234567' }],
+ ])('%j', (args, parsed) => {
+ expect(androidArgs(args)).toEqual(parsed);
+ });
+});
+
+describe('the status line', () => {
+ test.each<[string, AndroidState | null, string]>([
+ ['not watched', null, 'not checked (no browser is watching for phones)'],
+ ['ready', STATES.ready, 'ready (sdk_gphone16k_arm64, Chrome 150)'],
+ ['ready and in use', { ...STATES.ready, session: SESSION }, 'ready (sdk_gphone16k_arm64, Chrome 150), in use'],
+ ['screen off', seen([phone({ ...open, screen: { ...open.screen!, awake: false } })]), 'ready (sdk_gphone16k_arm64, Chrome 150), screen off'],
+ ['Chrome closed', seen([phone(chrome({ debuggable: false }))]), 'phone connected, Chrome closed'],
+ ['no phone', STATES.noDevice, 'no phone'],
+ ['no adb', STATES.adbMissing, 'adb not found'],
+ ['waiting for Allow', STATES.unauthorized, 'phone connected, waiting for Allow on the phone'],
+ ['off', judge({ enabled: false, platform: 'darwin', devices: [] }), 'off in config.json'],
+ ])('%s', (_name, state, line) => {
+ expect(androidStatus(state)).toBe(line);
+ });
+});
+
+describe('--json, as the apps read it', () => {
+ test.each(Object.entries(STATES))('%s', async (name, state) => {
+ const json = androidJson(state);
+ expect(json.guide).toHaveLength(6);
+ await expect(`${JSON.stringify(json, null, 2)}\n`).toMatchFileSnapshot(`../../lib/phone/fixtures/android-${name}.json`);
+ });
+});
diff --git a/src/daemon/android/report.ts b/src/daemon/android/report.ts
new file mode 100644
index 0000000..9553a6c
--- /dev/null
+++ b/src/daemon/android/report.ts
@@ -0,0 +1,103 @@
+import { PHONE_GUIDE, type GuideStep } from '@/lib/phone/guide';
+import type { AndroidDevice, AndroidProblem, AndroidProblemCode, AndroidState } from '@/lib/phone/types';
+
+const LABEL_WIDTH = 19;
+const INDENT = ' '.repeat(LABEL_WIDTH + 2);
+
+type Mark = '✓' | '·' | '✗';
+
+const row = (mark: Mark, label: string, value: string): string => `${mark} ${label.padEnd(LABEL_WIDTH)}${value}`;
+
+const failed = (label: string, problem: AndroidProblem, mark: Mark = '✗'): string[] => [
+ row(mark, label, problem.message),
+ ...(problem.fix ? [`${INDENT}${problem.fix}`] : []),
+];
+
+const PHONE_ROW_PROBLEMS: ReadonlySet<AndroidProblemCode> = new Set(['DEVICE_OFFLINE', 'NO_PERMISSIONS', 'DEVICE_BOOTING']);
+
+/** Problems the setup steps answer. Once the phone is connected and allowed, each row's own fix says more than the steps would. */
+const GUIDED: ReadonlySet<AndroidProblemCode> = new Set(['ADB_MISSING', 'NO_DEVICE', 'DEVICE_UNAUTHORIZED']);
+
+export interface AndroidJson extends AndroidState {
+ guide: readonly GuideStep[];
+}
+
+export const androidJson = (state: AndroidState): AndroidJson => ({ ...state, guide: PHONE_GUIDE });
+
+/** What follows `browsentic android`: `open`, a URL, and `--serial <serial>` anywhere among them. */
+export function androidArgs(args: readonly string[]): { sub?: string; url?: string; serial?: string } {
+ const serialAt = args.indexOf('--serial');
+ const serial = serialAt >= 0 ? args[serialAt + 1] : undefined;
+ const [sub, url] = args.filter((arg, index) => !arg.startsWith('--') && (serialAt < 0 || index !== serialAt + 1));
+ return { sub, url, serial };
+}
+
+/** `browsentic android`: one checklist row per check, stopping at the first that fails, then the setup steps while no phone is connected and allowed. */
+export function androidLines(state: AndroidState): string[] {
+ if (!state.enabled) return state.problem ? failed('Android', state.problem, '·') : [];
+ const adb = state.adb.problem ? failed('adb', state.adb.problem) : [row('✓', 'adb', `${state.adb.path}${state.adb.version ? ` (${state.adb.version})` : ''}`)];
+ if (state.adb.problem) return [...adb, ...(GUIDED.has(state.adb.problem.code) ? guide() : [])];
+
+ const phones = state.devices.length
+ ? state.devices.flatMap((device, index) => [...(index ? [''] : []), ...deviceLines(device, state.devices.length > 1)])
+ : state.problem
+ ? failed('Phone', state.problem)
+ : [];
+ const closing = state.ready
+ ? ['', state.session ? `Android is on in a browser, driving ${state.session.serial}.` : 'Ready. Switch on Android in the Browsentic side panel to drive it.']
+ : state.problem && GUIDED.has(state.problem.code)
+ ? guide()
+ : [];
+ return [...adb, ...phones, ...closing];
+}
+
+function deviceLines(device: AndroidDevice, several: boolean): string[] {
+ const problem = device.problem;
+ const code = problem?.code;
+ const phone = [
+ device.model ?? 'Android phone',
+ ...(device.android ? [`Android ${device.android}`] : []),
+ device.transport === 'wifi' ? 'Wi-Fi' : 'USB',
+ ].join(', ');
+ const heading = several ? [device.serial] : [];
+ const phoneRow = `${phone}${several ? '' : ` (${device.serial})`}`;
+
+ if (code && PHONE_ROW_PROBLEMS.has(code)) return [...heading, ...failed('Phone', { ...problem, message: `${phoneRow}: ${problem.message}` })];
+ const lines = [...heading, row('✓', 'Phone', phoneRow)];
+ if (code === 'DEVICE_UNAUTHORIZED') return [...lines, ...failed('USB debugging', problem!)];
+ lines.push(row('✓', 'USB debugging', 'allowed'));
+ if (code === 'CHROME_MISSING') return [...lines, ...failed('Chrome', problem!)];
+ lines.push(row('✓', 'Chrome', device.chrome.version ?? 'installed'));
+ if (code === 'CHROME_NOT_RUNNING') return [...lines, ...failed('Chrome open', problem!), `${INDENT}or run "browsentic android open"`];
+ lines.push(row('✓', 'Chrome open', 'its DevTools socket is open'));
+ if (code === 'SCREEN_OFF') return [...lines, ...failed('Screen', problem!, '·')];
+ return [...lines, row('✓', 'Screen', 'awake')];
+}
+
+function guide(): string[] {
+ return ['', 'To connect a phone:', ...PHONE_GUIDE.map((step, index) => ` ${index + 1}. ${step.title}${step.platform === 'android11+' ? ' (Android 11 or later)' : ''}: ${step.detail}`)];
+}
+
+const SHORT: Record<AndroidProblemCode, string> = {
+ ANDROID_OFF: 'off in config.json',
+ ADB_MISSING: 'adb not found',
+ ADB_BROKEN: 'adb does not run',
+ NO_DEVICE: 'no phone',
+ DEVICE_UNAUTHORIZED: 'phone connected, waiting for Allow on the phone',
+ DEVICE_OFFLINE: 'phone connected, not answering',
+ DEVICE_BOOTING: 'phone starting up',
+ NO_PERMISSIONS: 'phone connected, no USB permission',
+ CHROME_MISSING: 'phone connected, no Chrome',
+ CHROME_NOT_RUNNING: 'phone connected, Chrome closed',
+ SCREEN_OFF: 'screen off',
+};
+
+/** `browsentic status`'s line: what the Bridge already knows, or `not checked` when nobody has asked it to look. */
+export function androidStatus(state: AndroidState | null): string {
+ if (!state) return 'not checked (no browser is watching for phones)';
+ const drivable = state.devices.find((device) => device.state === 'ready' && device.chrome.debuggable);
+ if (!state.ready || !drivable) return state.problem ? SHORT[state.problem.code] : 'not ready';
+ const chrome = drivable.chrome.version ? `, Chrome ${drivable.chrome.version.split('.')[0]}` : '';
+ const extras = [...(drivable.problem ? [SHORT[drivable.problem.code]] : []), ...(state.session ? ['in use'] : [])];
+ return `ready (${drivable.model ?? drivable.serial}${chrome})${extras.length ? `, ${extras.join(', ')}` : ''}`;
+}
diff --git a/src/daemon/android/service.test.ts b/src/daemon/android/service.test.ts
index 168e0a7..be42167 100644
--- a/src/daemon/android/service.test.ts
+++ b/src/daemon/android/service.test.ts
@@ -209,7 +209,7 @@ describe('opening Chrome on the phone', () => {
expect(adb.shells).toContain(launchChromeCommand());
});
- test('a URL rides along on a cold start only', async () => {
+ test('a URL rides along with the start', async () => {
start();
adb.facts = fixture('facts-chrome-closed.txt');
await android.launch('emulator-5554', 'https://example.com/a');
@@ -219,10 +219,25 @@ describe('opening Chrome on the phone', () => {
expect(launchChromeCommand('javascript:alert(1)')).toBe(launchChromeCommand());
});
- test('an open Chrome is left alone', async () => {
+ test('an open Chrome is left alone, unless a page was asked for, which opens in a new tab', async () => {
start();
- await android.launch('emulator-5554', 'https://example.com');
+ await android.launch('emulator-5554');
expect(adb.shells.filter((command) => command.startsWith('am start'))).toEqual([]);
+ await android.launch('emulator-5554', 'https://example.com/');
+ expect(adb.shells.filter((command) => command.startsWith('am start'))).toEqual([launchChromeCommand('https://example.com/')]);
+ });
+
+ test('a peek knows nothing until someone watches, and never asks the phone', async () => {
+ start();
+ expect(android.peek()).toBeNull();
+ const { states, listener } = heard();
+ const release = android.watch(listener);
+ await until(() => states.length === 1);
+ const asked = adb.shells.length;
+ expect(android.peek()).toEqual(states[0]);
+ expect(adb.shells.length).toBe(asked);
+ release();
+ expect(android.peek()).toBeNull();
});
test('a missing Chrome opens its Play Store page instead', async () => {
diff --git a/src/daemon/android/service.ts b/src/daemon/android/service.ts
index 10a4876..ab93c38 100644
--- a/src/daemon/android/service.ts
+++ b/src/daemon/android/service.ts
@@ -12,6 +12,8 @@ import { startRelay, type CdpRequest, type PhoneOwner } from './relay';
export interface Android {
state(): Promise<AndroidState>;
+ /** What is already known, without looking: null while nobody watches, so a status line never starts adb. */
+ peek(): AndroidState | null;
/**
* A watcher hears the state as soon as it is known, then every change. The Bridge looks for phones
* only while someone holds a watch, and the returned function lets go of it.
@@ -45,6 +47,7 @@ export const ANDROID_OFF_STATE: AndroidState = judge({ enabled: false, platform:
export function androidOff(): Android {
return {
state: async () => ANDROID_OFF_STATE,
+ peek: () => ANDROID_OFF_STATE,
watch: (listener) => {
queueMicrotask(() => listener(ANDROID_OFF_STATE));
return () => {};
@@ -210,6 +213,7 @@ export function startAndroid(deps: AndroidDeps = liveAndroidDeps()): Android {
return {
state: current,
+ peek: () => (watched() ? latest : null),
watch(listener) {
heard.set(listener, '');
@@ -240,7 +244,7 @@ export function startAndroid(deps: AndroidDeps = liveAndroidDeps()): Android {
}
try {
if (!device.chrome.installed) await openChromeListing(deps.server, serial);
- else if (!device.chrome.debuggable) await launchChrome(deps.server, serial, url);
+ else if (!device.chrome.debuggable || url) await launchChrome(deps.server, serial, url);
} catch (error) {
return failure('DEVICE_OFFLINE', `The phone did not open Chrome: ${error instanceof Error ? error.message : String(error)}`);
}
diff --git a/src/daemon/cli.ts b/src/daemon/cli.ts
index 5c26243..02f2da4 100644
--- a/src/daemon/cli.ts
+++ b/src/daemon/cli.ts
@@ -2,6 +2,8 @@ import { readFileSync } from 'node:fs';
import { createInterface } from 'node:readline/promises';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { describeActions } from '@/lib/actions/registry';
+import { ANDROID_PROTOCOL } from '@/lib/actions/protocol';
+import type { AndroidState } from '@/lib/phone/types';
import { AGENTS, AGENT_KINDS, AGENT_LIST, isAgentKind, type AgentKind, type AgentState, type ModelList } from '@/lib/agents/catalog';
import { SOURCE_LABEL } from '@/lib/stores';
import { RESERVED_ACTIONS } from '@/lib/actions/reserved';
@@ -10,6 +12,7 @@ import { formatWhen } from '@/lib/format-when';
import { basename, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { agentSkills } from './agent/agent-skills';
+import { androidArgs, androidJson, androidLines, androidStatus } from './android/report';
import {
BROWSER_IDS,
BROWSERS,
@@ -62,6 +65,9 @@ const USAGE = `browsentic ${pkg.version} — Browsentic Bridge, the half of Brow
browsentic agent model <name> [model] pin that agent's model, or omit it for the CLI's default
browsentic agent models <name> list the models that agent offers; --refresh asks its CLI again
+ browsentic android whether a phone is ready to drive from the side panel, and what to fix if not
+ browsentic android open [url] open Chrome on the phone, at that page if one is given; --serial picks the phone
+
browsentic skills list the skills the agent can route to, and where they came from
browsentic approvals list the “always on this site” approvals you have granted
browsentic approvals clear [host] forget them, all of them or one site's
@@ -77,7 +83,7 @@ const USAGE = `browsentic ${pkg.version} — Browsentic Bridge, the half of Brow
browsentic restart stop the Bridge and bring up a fresh one
browsentic token print the control token (for MCP clients, not the browser)
- setup, browsers, agent, skills, approvals, tasks and downloads take --json, which is what the apps read.
+ setup, browsers, agent, android, skills, approvals, tasks and downloads take --json, which is what the apps read.
browsentic --version print the version
Getting started: browsentic setup
@@ -146,6 +152,9 @@ switch (command) {
case 'agent':
await chooseAgent(positional[0], positional[1], positional[2]);
break;
+ case 'android':
+ await android(process.argv.slice(3));
+ break;
case 'tools':
printTools();
break;
@@ -289,6 +298,7 @@ async function showStatus(): Promise<void> {
const status = await bridge.status();
const sessions = await bridge.sessions();
const agents = await bridge.agent();
+ const phone = status.protocolVersion >= ANDROID_PROTOCOL ? await bridge.android({ peek: true }) : null;
await bridge.close();
const active = agents.runners.find((runner) => runner.kind === agents.active);
console.log(`bridge: running on 127.0.0.1:${status.port} (pid ${lock.pid}, v${status.daemonVersion})`);
@@ -296,6 +306,7 @@ async function showStatus(): Promise<void> {
console.log(
`agent: ${AGENTS[agents.active].label} — ${active?.ready ? active.version ?? 'ready' : active?.problem?.message ?? 'unavailable'}`,
);
+ if (phone) console.log(`android: ${androidStatus(phone.ok ? phone.data : null)}`);
// An unpacked copy is the one thing an update cannot reach: "updated, never pressed ↻" is the
// failure the reload hint names. A store copy updates when its browser says, so it gets none.
@@ -907,6 +918,52 @@ async function revoke(browser?: string): Promise<void> {
console.log(`Revoked ${revoked} session(s). Pair again with "browsentic pair".`);
}
+async function android(args: string[]): Promise<void> {
+ const { sub, url, serial: named } = androidArgs(args);
+ if (sub && sub !== 'open') {
+ console.error(`Unknown command "android ${sub}". Use "browsentic android" or "browsentic android open [url]".`);
+ process.exit(1);
+ }
+
+ const bridge = await connect();
+ const read = await bridge.android();
+ if (!read.ok) {
+ await bridge.close();
+ console.error(read.error.message);
+ process.exit(1);
+ }
+ if (!sub) {
+ await bridge.close();
+ if (wantsJson) console.log(JSON.stringify(androidJson(read.data), null, 2));
+ else console.log(androidLines(read.data).join('\n'));
+ return;
+ }
+
+ const serial = named ?? onlyPhone(read.data);
+ const opened = await bridge.android({ launch: serial, url });
+ await bridge.close();
+ if (!opened.ok) {
+ console.error(opened.error.message);
+ process.exit(1);
+ }
+ const phone = opened.data.devices.find((device) => device.serial === serial);
+ if (!phone?.chrome.debuggable) {
+ console.error(phone?.problem?.message ?? 'Chrome did not open on the phone.');
+ process.exit(1);
+ }
+ console.log(url ? `Opened ${url} in Chrome on ${phone.model ?? serial}.` : `Chrome is open on ${phone.model ?? serial}.`);
+}
+
+function onlyPhone(state: AndroidState): string {
+ if (state.devices.length === 1) return state.devices[0].serial;
+ if (!state.devices.length) {
+ console.error(state.problem?.message ?? 'No Android phone is connected.');
+ process.exit(1);
+ }
+ console.error(`${state.devices.length} phones are connected. Name one with --serial: ${state.devices.map((device) => device.serial).join(', ')}`);
+ process.exit(1);
+}
+
async function connect(): Promise<RemoteBridge> {
const lock = await ensureDaemon();
return RemoteBridge.connect(lock.port, lock.token);
diff --git a/src/daemon/control.ts b/src/daemon/control.ts
index 777609f..556e72a 100644
--- a/src/daemon/control.ts
+++ b/src/daemon/control.ts
@@ -51,8 +51,11 @@ export type ControlRequest =
/** `watch` also subscribes this caller to `settings-changed`, which no other caller is sent. */
| { id: string; op: 'preferences'; watch?: boolean }
| { id: string; op: 'setPreference'; change: unknown }
- /** `launch` opens Chrome on that phone. `watch` subscribes this caller to `android-changed`. */
- | { id: string; op: 'android'; launch?: string; watch?: boolean };
+ /**
+ * `launch` opens Chrome on that phone, at `url` when one is given. `watch` subscribes this caller to
+ * `android-changed`. `peek` answers only what is already known, NOT_CHECKED while nobody watches.
+ */
+ | { id: string; op: 'android'; launch?: string; url?: string; watch?: boolean; peek?: boolean };
export type ControlMessage =
| { id: string; op: 'describe'; tools: ToolDescriptor[]; reserved?: string[]; withheld?: ToolDescriptor[] }
diff --git a/src/daemon/daemon.ts b/src/daemon/daemon.ts
index bf18c84..ba9a46c 100644
--- a/src/daemon/daemon.ts
+++ b/src/daemon/daemon.ts
@@ -559,6 +559,11 @@ export async function startDaemon({ version, idleExit = true, android = androidO
androidWatches.set(link, android.watch(push));
}
+ function peekAndroid(): ActionResult<AndroidState> {
+ const known = android.peek();
+ return known ? success(known) : failure('NOT_CHECKED', 'Nobody is watching for phones, so the Bridge has not looked.');
+ }
+
function unwatchAndroid(watcher: ExtensionLink | WebSocket): void {
androidWatches.get(watcher)?.();
androidWatches.delete(watcher);
@@ -887,7 +892,11 @@ export async function startDaemon({ version, idleExit = true, android = androidO
if (request.watch && !androidWatches.has(ws)) {
androidWatches.set(ws, android.watch((state) => send(ws, { event: 'android-changed', state })));
}
- const result = request.launch ? await android.launch(request.launch) : success(await android.state());
+ const result = request.launch
+ ? await android.launch(request.launch, request.url)
+ : request.peek
+ ? peekAndroid()
+ : success(await android.state());
return send(ws, { id: request.id, op: 'android', result });
}
if (request.op === 'setPreference') {
diff --git a/src/daemon/remote-bridge.ts b/src/daemon/remote-bridge.ts
index 05c7fbc..931dcb8 100644
--- a/src/daemon/remote-bridge.ts
+++ b/src/daemon/remote-bridge.ts
@@ -73,7 +73,7 @@ export class RemoteBridge implements Bridge {
throw new Error('The Browsentic daemon did not answer about its agent');
}
- async android(request?: { launch?: string; watch?: boolean }): Promise<ActionResult<AndroidState>> {
+ async android(request?: { launch?: string; url?: string; watch?: boolean; peek?: boolean }): Promise<ActionResult<AndroidState>> {
const reply = await this.request({ id: randomUUID(), op: 'android', ...request });
if (reply && 'op' in reply && reply.op === 'android') return reply.result;
return failure('DAEMON_UNREACHABLE', 'The Browsentic daemon did not answer about Android');
diff --git a/src/daemon/test/fake-android.ts b/src/daemon/test/fake-android.ts
index 70233fd..fd82300 100644
--- a/src/daemon/test/fake-android.ts
+++ b/src/daemon/test/fake-android.ts
@@ -43,6 +43,10 @@ export class FakeAndroid implements Android {
return this.current;
}
+ peek(): AndroidState | null {
+ return this.watchers ? this.current : null;
+ }
+
watch(listener: (state: AndroidState) => void): () => void {
this.listeners.add(listener);
queueMicrotask(() => this.listeners.has(listener) && listener(this.current));
diff --git a/src/daemon/test/protocol-window.test.ts b/src/daemon/test/protocol-window.test.ts
index c2688e4..c672705 100644
--- a/src/daemon/test/protocol-window.test.ts
+++ b/src/daemon/test/protocol-window.test.ts
@@ -174,6 +174,12 @@ describe('Android across the protocol window', () => {
expect(android.watchers).toBe(0);
});
+ test('a peek answers only while someone watches', async () => {
+ expect(await (await control()).android({ peek: true })).toMatchObject({ ok: false, error: { code: 'NOT_CHECKED' } });
+ await pair({ ...store, protocolVersion: ANDROID_PROTOCOL });
+ expect(await (await control()).android({ peek: true })).toEqual({ ok: true, data: NO_PHONE });
+ });
+
test('an agent run cannot open Chrome on the phone through the control socket', async () => {
const run = await RemoteBridge.connect(daemon.port, readLockfile()!.token, 'run-1');
opened.push(run);
diff --git a/src/lib/phone/fixtures/android-adbMissing.json b/src/lib/phone/fixtures/android-adbMissing.json
new file mode 100644
index 0000000..c8d45fa
--- /dev/null
+++ b/src/lib/phone/fixtures/android-adbMissing.json
@@ -0,0 +1,45 @@
+{
+ "enabled": true,
+ "adb": {
+ "found": false,
+ "problem": {
+ "code": "ADB_MISSING",
+ "message": "Browsentic reaches your phone through adb, from Android's platform-tools, and it is not installed. Install it with the command below or download it from https://developer.android.com/tools/releases/platform-tools.",
+ "fix": "brew install --cask android-platform-tools"
+ }
+ },
+ "ready": false,
+ "devices": [],
+ "problem": {
+ "code": "ADB_MISSING",
+ "message": "Browsentic reaches your phone through adb, from Android's platform-tools, and it is not installed. Install it with the command below or download it from https://developer.android.com/tools/releases/platform-tools.",
+ "fix": "brew install --cask android-platform-tools"
+ },
+ "guide": [
+ {
+ "title": "Turn on Developer options",
+ "detail": "On the phone, open Settings, then About phone, and tap Build number seven times."
+ },
+ {
+ "title": "Turn on USB debugging",
+ "detail": "Open Settings, then System, then Developer options, and turn on USB debugging."
+ },
+ {
+ "title": "Connect the phone",
+ "detail": "Connect it to this computer with a USB cable. When the phone asks, tick \"Always allow from this computer\" and tap Allow."
+ },
+ {
+ "title": "Or connect over Wi-Fi",
+ "detail": "In Developer options, turn on Wireless debugging and tap Pair device with pairing code. On this computer, run \"adb pair <ip:port> <code>\", then \"adb connect <ip:port>\".",
+ "platform": "android11+"
+ },
+ {
+ "title": "Open Chrome on the phone",
+ "detail": "Browsentic drives the Chrome app, so it has to be open."
+ },
+ {
+ "title": "Switch on Android",
+ "detail": "In your browser, open the Browsentic side panel and switch on Android."
+ }
+ ]
+}
diff --git a/src/lib/phone/fixtures/android-noDevice.json b/src/lib/phone/fixtures/android-noDevice.json
new file mode 100644
index 0000000..dd0dc09
--- /dev/null
+++ b/src/lib/phone/fixtures/android-noDevice.json
@@ -0,0 +1,42 @@
+{
+ "enabled": true,
+ "adb": {
+ "found": true,
+ "path": "/Users/me/Library/Android/sdk/platform-tools/adb",
+ "version": "37.0.0-14910828"
+ },
+ "ready": false,
+ "devices": [],
+ "problem": {
+ "code": "NO_DEVICE",
+ "message": "No Android phone is connected.",
+ "fix": "Turn on USB debugging on the phone and connect it with a USB cable. Run \"browsentic android\" for the steps."
+ },
+ "guide": [
+ {
+ "title": "Turn on Developer options",
+ "detail": "On the phone, open Settings, then About phone, and tap Build number seven times."
+ },
+ {
+ "title": "Turn on USB debugging",
+ "detail": "Open Settings, then System, then Developer options, and turn on USB debugging."
+ },
+ {
+ "title": "Connect the phone",
+ "detail": "Connect it to this computer with a USB cable. When the phone asks, tick \"Always allow from this computer\" and tap Allow."
+ },
+ {
+ "title": "Or connect over Wi-Fi",
+ "detail": "In Developer options, turn on Wireless debugging and tap Pair device with pairing code. On this computer, run \"adb pair <ip:port> <code>\", then \"adb connect <ip:port>\".",
+ "platform": "android11+"
+ },
+ {
+ "title": "Open Chrome on the phone",
+ "detail": "Browsentic drives the Chrome app, so it has to be open."
+ },
+ {
+ "title": "Switch on Android",
+ "detail": "In your browser, open the Browsentic side panel and switch on Android."
+ }
+ ]
+}
diff --git a/src/lib/phone/fixtures/android-ready.json b/src/lib/phone/fixtures/android-ready.json
new file mode 100644
index 0000000..fb7173b
--- /dev/null
+++ b/src/lib/phone/fixtures/android-ready.json
@@ -0,0 +1,59 @@
+{
+ "enabled": true,
+ "adb": {
+ "found": true,
+ "path": "/Users/me/Library/Android/sdk/platform-tools/adb",
+ "version": "37.0.0-14910828"
+ },
+ "ready": true,
+ "devices": [
+ {
+ "serial": "emulator-5554",
+ "transport": "usb",
+ "state": "ready",
+ "model": "sdk_gphone16k_arm64",
+ "manufacturer": "Google",
+ "android": "17",
+ "sdk": 37,
+ "screen": {
+ "width": 1080,
+ "height": 2092,
+ "density": 420,
+ "awake": true
+ },
+ "chrome": {
+ "installed": true,
+ "version": "150.0.7871.186",
+ "running": true,
+ "debuggable": true
+ }
+ }
+ ],
+ "guide": [
+ {
+ "title": "Turn on Developer options",
+ "detail": "On the phone, open Settings, then About phone, and tap Build number seven times."
+ },
+ {
+ "title": "Turn on USB debugging",
+ "detail": "Open Settings, then System, then Developer options, and turn on USB debugging."
+ },
+ {
+ "title": "Connect the phone",
+ "detail": "Connect it to this computer with a USB cable. When the phone asks, tick \"Always allow from this computer\" and tap Allow."
+ },
+ {
+ "title": "Or connect over Wi-Fi",
+ "detail": "In Developer options, turn on Wireless debugging and tap Pair device with pairing code. On this computer, run \"adb pair <ip:port> <code>\", then \"adb connect <ip:port>\".",
+ "platform": "android11+"
+ },
+ {
+ "title": "Open Chrome on the phone",
+ "detail": "Browsentic drives the Chrome app, so it has to be open."
+ },
+ {
+ "title": "Switch on Android",
+ "detail": "In your browser, open the Browsentic side panel and switch on Android."
+ }
+ ]
+}
diff --git a/src/lib/phone/fixtures/android-unauthorized.json b/src/lib/phone/fixtures/android-unauthorized.json
new file mode 100644
index 0000000..c8b9de3
--- /dev/null
+++ b/src/lib/phone/fixtures/android-unauthorized.json
@@ -0,0 +1,58 @@
+{
+ "enabled": true,
+ "adb": {
+ "found": true,
+ "path": "/Users/me/Library/Android/sdk/platform-tools/adb",
+ "version": "37.0.0-14910828"
+ },
+ "ready": false,
+ "devices": [
+ {
+ "serial": "R5CT1234567",
+ "transport": "usb",
+ "state": "unauthorized",
+ "chrome": {
+ "installed": false,
+ "running": false,
+ "debuggable": false
+ },
+ "problem": {
+ "code": "DEVICE_UNAUTHORIZED",
+ "message": "The phone has not allowed this computer yet.",
+ "fix": "Unlock your phone and tap Allow on the USB debugging prompt. If no prompt shows, unplug the phone and plug it in again."
+ }
+ }
+ ],
+ "problem": {
+ "code": "DEVICE_UNAUTHORIZED",
+ "message": "The phone has not allowed this computer yet.",
+ "fix": "Unlock your phone and tap Allow on the USB debugging prompt. If no prompt shows, unplug the phone and plug it in again."
+ },
+ "guide": [
+ {
+ "title": "Turn on Developer options",
+ "detail": "On the phone, open Settings, then About phone, and tap Build number seven times."
+ },
+ {
+ "title": "Turn on USB debugging",
+ "detail": "Open Settings, then System, then Developer options, and turn on USB debugging."
+ },
+ {
+ "title": "Connect the phone",
+ "detail": "Connect it to this computer with a USB cable. When the phone asks, tick \"Always allow from this computer\" and tap Allow."
+ },
+ {
+ "title": "Or connect over Wi-Fi",
+ "detail": "In Developer options, turn on Wireless debugging and tap Pair device with pairing code. On this computer, run \"adb pair <ip:port> <code>\", then \"adb connect <ip:port>\".",
+ "platform": "android11+"
+ },
+ {
+ "title": "Open Chrome on the phone",
+ "detail": "Browsentic drives the Chrome app, so it has to be open."
+ },
+ {
+ "title": "Switch on Android",
+ "detail": "In your browser, open the Browsentic side panel and switch on Android."
+ }
+ ]
+}