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): the Bridge finds adb, follows phones through adb's own server socket, and says whether one is ready and what to fix if not; it can open Chrome on the phone, and the android setting turns it all off

Shahriar795546e460a5
diff --git a/src/daemon/agent/config.ts b/src/daemon/agent/config.ts
index d56bba0..1151c28 100644
--- a/src/daemon/agent/config.ts
+++ b/src/daemon/agent/config.ts
@@ -45,6 +45,17 @@ export interface AgentConfig {
maxScreenshots?: number;
timeoutMs?: number;
};
+ /** Driving Chrome on an Android phone. Off stops every use of adb; `adb` names the binary to use. */
+ android?: { enabled?: boolean; adb?: string };
+}
+
+export interface AndroidSettings {
+ enabled: boolean;
+ adb?: string;
+}
+
+export function androidSettings(config: AgentConfig): AndroidSettings {
+ return { enabled: config.android?.enabled !== false, adb: text(config.android?.adb) };
}
export const CONCURRENT_RUNS = { fallback: 3, max: 8 } as const;
diff --git a/src/daemon/agent/runners/command.ts b/src/daemon/agent/runners/command.ts
index 7c59c21..32a9b9f 100644
--- a/src/daemon/agent/runners/command.ts
+++ b/src/daemon/agent/runners/command.ts
@@ -69,7 +69,7 @@ function onPath(bin: string, env: NodeJS.ProcessEnv, exists: (path: string) => b
}
/** Windows spells a variable any way it likes, and a plain copy of the environment keeps that spelling. */
-function variable(env: NodeJS.ProcessEnv, name: string): string | undefined {
+export function variable(env: NodeJS.ProcessEnv, name: string): string | undefined {
return Object.entries(env).find(([key]) => key.toUpperCase() === name)?.[1];
}
diff --git a/src/daemon/android/adb-server.test.ts b/src/daemon/android/adb-server.test.ts
new file mode 100644
index 0000000..7fd0fee
--- /dev/null
+++ b/src/daemon/android/adb-server.test.ts
@@ -0,0 +1,166 @@
+import { createServer, type Server, type Socket } from 'node:net';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { AdbServerError, adbServer, request, type AdbServer } from './adb-server';
+
+const prefixed = (text: string) => `${Buffer.byteLength(text).toString(16).padStart(4, '0')}${text}`;
+
+/** adb's server as far as the host protocol goes: each request is answered the way a real one answered it on 9 Oct 2026. */
+class FakeAdbServer {
+ readonly requests: string[] = [];
+ readonly trackers: Socket[] = [];
+ readonly forwards = new Set<number>();
+ devices = 'emulator-5554 device product:sdk_gphone16k_arm64 model:sdk_gphone16k_arm64 device:emu64a16k transport_id:21\n';
+ shellOutput = 'hi\n';
+ silent = false;
+ private server!: Server;
+
+ async listen(): Promise<number> {
+ this.server = createServer((socket) => this.serve(socket));
+ await new Promise<void>((resolve) => this.server.listen(0, '127.0.0.1', resolve));
+ return (this.server.address() as { port: number }).port;
+ }
+
+ async close(): Promise<void> {
+ for (const tracker of this.trackers) tracker.destroy();
+ await new Promise((resolve) => this.server.close(resolve));
+ }
+
+ private serve(socket: Socket): void {
+ let buffered = '';
+ let transport: string | null = null;
+ socket.on('data', (chunk) => {
+ buffered += chunk.toString('utf8');
+ for (;;) {
+ if (buffered.length < 4) return;
+ const length = Number.parseInt(buffered.slice(0, 4), 16);
+ if (buffered.length < 4 + length) return;
+ const service = buffered.slice(4, 4 + length);
+ buffered = buffered.slice(4 + length);
+ this.requests.push(service);
+ if (this.silent) continue;
+ if (service === 'host:version') socket.end(`OKAY${prefixed('0029')}`);
+ else if (service === 'host:devices-l') socket.end(`OKAY${prefixed(this.devices)}`);
+ else if (service === 'host:track-devices-l') {
+ this.trackers.push(socket);
+ socket.write(`OKAY${prefixed(this.devices)}`);
+ } else if (service.startsWith('host:transport:')) {
+ transport = service.slice('host:transport:'.length);
+ if (transport === 'emulator-5554') socket.write('OKAY');
+ else socket.end(`FAIL${prefixed(`device '${transport}' not found`)}`);
+ } else if (service.startsWith('shell:') && transport) socket.end(`OKAY${this.shellOutput}`);
+ else if (/^host-serial:[^:]+:forward:tcp:0;/.test(service)) {
+ const port = 50_000 + this.forwards.size;
+ this.forwards.add(port);
+ socket.end(`OKAYOKAY${prefixed(String(port))}`);
+ } else if (/^host-serial:[^:]+:killforward:tcp:(\d+)$/.test(service)) {
+ const port = Number(/(\d+)$/.exec(service)![1]);
+ socket.end(this.forwards.delete(port) ? 'OKAYOKAY' : `FAIL${prefixed(`listener 'tcp:${port}' not found`)}`);
+ } else socket.end(`FAIL${prefixed(`unknown host service`)}`);
+ }
+ });
+ }
+}
+
+const CALL_TIMEOUT_MS = 100;
+
+let fake: FakeAdbServer;
+let port: number;
+let adb: AdbServer;
+
+beforeEach(async () => {
+ fake = new FakeAdbServer();
+ port = await fake.listen();
+ adb = adbServer({ port, callTimeoutMs: CALL_TIMEOUT_MS });
+});
+
+afterEach(() => fake.close());
+
+const until = async (done: () => boolean) => {
+ for (let tries = 0; !done(); tries++) {
+ if (tries > 200) throw new Error('timed out waiting');
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ }
+};
+
+describe('adb\'s server over its socket', () => {
+ test('a request is its length in four hex digits, then the service', () => {
+ expect(request('host:version').toString()).toBe('000chost:version');
+ });
+
+ test('the version and the device list', async () => {
+ expect(await adb.version()).toBe(41);
+ expect(await adb.devices()).toBe(fake.devices);
+ });
+
+ test('a shell command goes through the device\'s transport, and its output is everything until adb hangs up', async () => {
+ fake.shellOutput = 'one\ntwo\n';
+ expect(await adb.shell('emulator-5554', 'echo one; echo two')).toBe('one\ntwo\n');
+ expect(fake.requests).toEqual(['host:transport:emulator-5554', 'shell:echo one; echo two']);
+ });
+
+ test('a FAIL carries adb\'s own words', async () => {
+ await expect(adb.shell('nope', 'true')).rejects.toMatchObject({ code: 'FAIL', message: "device 'nope' not found" });
+ });
+
+ test('a forward answers its port, and removing it twice fails the second time', async () => {
+ const port = await adb.forward('emulator-5554', 'localabstract:chrome_devtools_remote');
+ expect(port).toBe(50_000);
+ expect(fake.requests).toEqual(['host-serial:emulator-5554:forward:tcp:0;localabstract:chrome_devtools_remote']);
+ await adb.removeForward('emulator-5554', port);
+ await expect(adb.removeForward('emulator-5554', port)).rejects.toMatchObject({ code: 'FAIL' });
+ });
+
+ test('no server listening is NO_SERVER', async () => {
+ const vacant = createServer();
+ await new Promise<void>((resolve) => vacant.listen(0, '127.0.0.1', resolve));
+ const { port: unused } = vacant.address() as { port: number };
+ await new Promise((resolve) => vacant.close(resolve));
+ await expect(adbServer({ port: unused }).version()).rejects.toMatchObject({ code: 'NO_SERVER' });
+ });
+
+ test('a server that never answers is a TIMEOUT', async () => {
+ fake.silent = true;
+ await expect(adb.shell('emulator-5554', 'sleep 60')).rejects.toMatchObject({ code: 'TIMEOUT' });
+ });
+});
+
+describe('tracking the devices', () => {
+ test('hears the list at once, then each change, whether it arrives in pieces or two at a time', async () => {
+ const lists: string[] = [];
+ const stop = adb.track((list) => lists.push(list), () => lists.push('ended'));
+ await until(() => lists.length === 1);
+ expect(lists).toEqual([fake.devices]);
+
+ const tracker = fake.trackers[0];
+ for (const byte of prefixed('A1\tdevice\n')) tracker.write(byte);
+ await until(() => lists.length === 2);
+ tracker.write(`${prefixed('')}${prefixed('A2\toffline\n')}`);
+ await until(() => lists.length === 4);
+ expect(lists.slice(1)).toEqual(['A1\tdevice\n', '', 'A2\toffline\n']);
+ stop();
+ });
+
+ test('says when the server goes away, and says nothing once stopped', async () => {
+ const ends: AdbServerError[] = [];
+ adb.track(() => {}, (error) => ends.push(error));
+ await until(() => fake.trackers.length === 1);
+ fake.trackers[0].destroy();
+ await until(() => ends.length === 1);
+ expect(ends[0]).toBeInstanceOf(AdbServerError);
+
+ const quiet: AdbServerError[] = [];
+ const stop = adb.track(() => {}, (error) => quiet.push(error));
+ await until(() => fake.trackers.length === 2);
+ stop();
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ expect(quiet).toEqual([]);
+ });
+
+ test('a tracker is not cut off by the call timeout', async () => {
+ const lists: string[] = [];
+ const stop = adb.track((list) => lists.push(list), () => lists.push('ended'));
+ await new Promise((resolve) => setTimeout(resolve, CALL_TIMEOUT_MS * 3));
+ expect(lists).toEqual([fake.devices]);
+ stop();
+ });
+});
diff --git a/src/daemon/android/adb-server.ts b/src/daemon/android/adb-server.ts
new file mode 100644
index 0000000..e4f054a
--- /dev/null
+++ b/src/daemon/android/adb-server.ts
@@ -0,0 +1,201 @@
+import { connect, type Socket } from 'node:net';
+
+/**
+ * adb's own server, spoken to over its socket rather than through the adb binary. A client binary
+ * whose version differs from the running server's kills that server (and Android Studio's session
+ * with it); a socket never does, and it needs no process per call.
+ */
+
+export const ADB_SERVER_PORT = Number(process.env.ANDROID_ADB_SERVER_PORT) || 5037;
+
+const CALL_TIMEOUT_MS = 5_000;
+const MAX_REPLY_BYTES = 1 << 20;
+
+export type AdbServerErrorCode = 'NO_SERVER' | 'FAIL' | 'TIMEOUT' | 'CLOSED';
+
+export class AdbServerError extends Error {
+ constructor(
+ readonly code: AdbServerErrorCode,
+ message: string,
+ ) {
+ super(message);
+ }
+}
+
+export interface AdbServer {
+ version(): Promise<number>;
+ devices(): Promise<string>;
+ /** Hears the device list now and on every change, until the returned function is called or the server goes away. */
+ track(onList: (list: string) => void, onEnd: (error: AdbServerError) => void): () => void;
+ shell(serial: string, command: string, timeoutMs?: number): Promise<string>;
+ forward(serial: string, remote: string): Promise<number>;
+ removeForward(serial: string, port: number): Promise<void>;
+}
+
+export const request = (service: string): Buffer => {
+ const payload = Buffer.from(service, 'utf8');
+ return Buffer.concat([Buffer.from(payload.length.toString(16).padStart(4, '0'), 'ascii'), payload]);
+};
+
+export function adbServer({ port = ADB_SERVER_PORT, host = '127.0.0.1', callTimeoutMs = CALL_TIMEOUT_MS } = {}): AdbServer {
+ const once = async <T>(timeoutMs: number, talk: (wire: Wire) => Promise<T>): Promise<T> => {
+ const wire = await Wire.open(port, host, timeoutMs);
+ try {
+ return await talk(wire);
+ } finally {
+ wire.close();
+ }
+ };
+
+ return {
+ version: () =>
+ once(callTimeoutMs, async (wire) => {
+ await wire.ask('host:version');
+ return Number.parseInt(await wire.prefixed(), 16);
+ }),
+
+ devices: () =>
+ once(callTimeoutMs, async (wire) => {
+ await wire.ask('host:devices-l');
+ return wire.prefixed();
+ }),
+
+ track(onList, onEnd) {
+ let stopped = false;
+ let current: Wire | undefined;
+ void (async () => {
+ try {
+ current = await Wire.open(port, host, callTimeoutMs);
+ if (stopped) return current.close();
+ await current.ask('host:track-devices-l');
+ current.unlimited();
+ for (;;) onList(await current.prefixed());
+ } catch (error) {
+ current?.close();
+ if (!stopped) onEnd(asServerError(error));
+ }
+ })();
+ return () => {
+ stopped = true;
+ current?.close();
+ };
+ },
+
+ shell: (serial, command, timeoutMs = callTimeoutMs) =>
+ once(timeoutMs, async (wire) => {
+ await wire.ask(`host:transport:${serial}`);
+ await wire.ask(`shell:${command}`);
+ return wire.rest();
+ }),
+
+ forward: (serial, remote) =>
+ once(callTimeoutMs, async (wire) => {
+ await wire.ask(`host-serial:${serial}:forward:tcp:0;${remote}`);
+ await wire.status();
+ const port = Number(await wire.prefixed());
+ if (!Number.isInteger(port) || port <= 0) throw new AdbServerError('FAIL', `adb forwarded to "${port}", not a port`);
+ return port;
+ }),
+
+ removeForward: (serial, local) =>
+ once(callTimeoutMs, async (wire) => {
+ await wire.ask(`host-serial:${serial}:killforward:tcp:${local}`);
+ await wire.status();
+ }),
+ };
+}
+
+function asServerError(error: unknown): AdbServerError {
+ return error instanceof AdbServerError ? error : new AdbServerError('CLOSED', String(error));
+}
+
+/** One conversation with the server: requests out, replies read by exact length or to the end. */
+class Wire {
+ private buffered = Buffer.alloc(0);
+ private ended: AdbServerError | null = null;
+ private wake: (() => void) | null = null;
+ private deadline: ReturnType<typeof setTimeout> | undefined;
+
+ private constructor(private readonly socket: Socket) {
+ socket.on('data', (chunk: Buffer) => {
+ this.buffered = Buffer.concat([this.buffered, chunk]);
+ if (this.buffered.length > MAX_REPLY_BYTES) this.end(new AdbServerError('FAIL', 'adb replied with more than expected'));
+ this.notify();
+ });
+ socket.on('close', () => this.end(new AdbServerError('CLOSED', 'adb closed the connection')));
+ socket.on('error', (error: NodeJS.ErrnoException) =>
+ this.end(new AdbServerError(error.code === 'ECONNREFUSED' ? 'NO_SERVER' : 'CLOSED', error.message)),
+ );
+ }
+
+ static open(port: number, host: string, timeoutMs: number): Promise<Wire> {
+ return new Promise((resolve, reject) => {
+ const socket = connect(port, host);
+ const wire = new Wire(socket);
+ wire.deadline = setTimeout(() => wire.end(new AdbServerError('TIMEOUT', `adb did not answer within ${timeoutMs} ms`)), timeoutMs);
+ socket.once('connect', () => resolve(wire));
+ socket.once('close', () => reject(wire.ended));
+ });
+ }
+
+ unlimited(): void {
+ clearTimeout(this.deadline);
+ }
+
+ async ask(service: string): Promise<void> {
+ this.socket.write(request(service));
+ await this.status();
+ }
+
+ async status(): Promise<void> {
+ const word = (await this.take(4)).toString('ascii');
+ if (word === 'OKAY') return;
+ if (word === 'FAIL') throw new AdbServerError('FAIL', await this.prefixed());
+ throw new AdbServerError('FAIL', `adb answered "${word}"`);
+ }
+
+ async prefixed(): Promise<string> {
+ const length = Number.parseInt((await this.take(4)).toString('ascii'), 16);
+ if (!Number.isInteger(length)) throw new AdbServerError('FAIL', 'adb sent a malformed length');
+ return (await this.take(length)).toString('utf8');
+ }
+
+ async rest(): Promise<string> {
+ while (!this.ended) await this.next();
+ if (this.ended.code !== 'CLOSED') throw this.ended;
+ return this.buffered.toString('utf8');
+ }
+
+ close(): void {
+ clearTimeout(this.deadline);
+ this.socket.destroy();
+ }
+
+ private async take(count: number): Promise<Buffer> {
+ while (this.buffered.length < count) {
+ if (this.ended) throw this.ended;
+ await this.next();
+ }
+ const taken = this.buffered.subarray(0, count);
+ this.buffered = this.buffered.subarray(count);
+ return taken;
+ }
+
+ private next(): Promise<void> {
+ return new Promise((resolve) => (this.wake = resolve));
+ }
+
+ private notify(): void {
+ const wake = this.wake;
+ this.wake = null;
+ wake?.();
+ }
+
+ private end(error: AdbServerError): void {
+ if (this.ended) return;
+ this.ended = error;
+ clearTimeout(this.deadline);
+ this.socket.destroy();
+ this.notify();
+ }
+}
diff --git a/src/daemon/android/adb.test.ts b/src/daemon/android/adb.test.ts
new file mode 100644
index 0000000..e13f322
--- /dev/null
+++ b/src/daemon/android/adb.test.ts
@@ -0,0 +1,91 @@
+import { mkdtempSync, readFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
+import { stubCli } from '../agent/runners/fixtures/support';
+import { adbCandidates, isProgram, locateAdb, startServer } from './adb';
+
+const VERSION = readFileSync(new URL('./fixtures/adb-version.txt', import.meta.url), 'utf8');
+
+describe('where adb is looked for', () => {
+ test('macOS: the setting, PATH, the SDK variables, Android Studio\'s SDK, then Homebrew', () => {
+ expect(
+ adbCandidates({
+ configured: '/custom/adb',
+ platform: 'darwin',
+ home: '/Users/me',
+ env: { PATH: '/usr/bin:/bin', ANDROID_HOME: '/sdk', ANDROID_SDK_ROOT: '/old-sdk' },
+ }),
+ ).toEqual([
+ '/custom/adb',
+ '/usr/bin/adb',
+ '/bin/adb',
+ '/sdk/platform-tools/adb',
+ '/old-sdk/platform-tools/adb',
+ '/Users/me/Library/Android/sdk/platform-tools/adb',
+ '/opt/homebrew/bin/adb',
+ '/usr/local/bin/adb',
+ ]);
+ });
+
+ test('Windows: adb.exe on PATH however the variable is spelled, then the SDK under LOCALAPPDATA', () => {
+ expect(
+ adbCandidates({
+ platform: 'win32',
+ home: 'C:\\Users\\me',
+ env: { Path: '"C:\\Tools";C:\\Windows', LOCALAPPDATA: 'C:\\Users\\me\\AppData\\Local' },
+ }),
+ ).toEqual(['C:\\Tools\\adb.exe', 'C:\\Windows\\adb.exe', 'C:\\Users\\me\\AppData\\Local\\Android\\Sdk\\platform-tools\\adb.exe']);
+ });
+
+ test('Linux: the SDK Android Studio makes in the home directory', () => {
+ expect(adbCandidates({ platform: 'linux', home: '/home/me', env: {} })).toEqual([
+ '/home/me/Android/Sdk/platform-tools/adb',
+ '/opt/homebrew/bin/adb',
+ '/usr/local/bin/adb',
+ ]);
+ });
+
+ test('a place named twice is tried once', () => {
+ expect(adbCandidates({ platform: 'linux', home: '/h', env: { PATH: '/a:/a', ANDROID_HOME: '/h/Android/Sdk' } })).toEqual([
+ '/a/adb',
+ '/h/Android/Sdk/platform-tools/adb',
+ '/opt/homebrew/bin/adb',
+ '/usr/local/bin/adb',
+ ]);
+ });
+});
+
+describe('finding adb', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'browsentic-adb-'));
+ const fake = (name: string, script: string) => stubCli(join(dir, name), script);
+
+ test('nothing anywhere is null', async () => {
+ expect(await locateAdb({ platform: 'linux', home: dir, env: {} }, () => false)).toBeNull();
+ });
+
+ test('the first one that exists is run once for its version', async () => {
+ const adb = fake('adb-good', `process.stdout.write(${JSON.stringify(VERSION)});`);
+ expect(await locateAdb({ configured: adb, env: {} }, (path) => path === adb)).toEqual({ path: adb, version: '37.0.0-14910828' });
+ });
+
+ test('one that fails says how, in its own first line', async () => {
+ const adb = fake('adb-broken', `process.stderr.write('dyld: Library not loaded\\nmore\\n'); process.exit(1);`);
+ expect(await locateAdb({ configured: adb, env: {} }, (path) => path === adb)).toEqual({ path: adb, broken: 'dyld: Library not loaded' });
+ });
+
+ test.skipIf(process.platform === 'win32')('a directory or a file that cannot run is not a program', () => {
+ expect(isProgram(dir)).toBe(false);
+ expect(isProgram(new URL('./fixtures/adb-version.txt', import.meta.url).pathname)).toBe(false);
+ expect(isProgram(fake('adb-runs', ''))).toBe(true);
+ });
+
+ test.skipIf(process.platform === 'win32')('start-server is judged by its exit, not by output a forked server could hold open', async () => {
+ const forks = fake('adb-forks', `require('node:child_process').spawn(process.execPath, ['-e', 'setTimeout(() => {}, 3000)'], { stdio: 'inherit', detached: true }).unref();`);
+ const started = Date.now();
+ expect(await startServer(forks)).toBe(true);
+ expect(Date.now() - started).toBeLessThan(2_000);
+ expect(await startServer(fake('adb-refuses', 'process.exit(1);'))).toBe(false);
+ expect(await startServer(join(dir, 'missing'))).toBe(false);
+ });
+});
diff --git a/src/daemon/android/adb.ts b/src/daemon/android/adb.ts
new file mode 100644
index 0000000..2c75337
--- /dev/null
+++ b/src/daemon/android/adb.ts
@@ -0,0 +1,126 @@
+import { spawn } from 'node:child_process';
+import { accessSync, constants, statSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { posix, win32 } from 'node:path';
+import { spawnCli, stopTree, variable } from '../agent/runners/command';
+
+const VERSION_TIMEOUT_MS = 5_000;
+const START_SERVER_TIMEOUT_MS = 15_000;
+
+export interface AdbFound {
+ path: string;
+ version?: string;
+ /** The first line adb printed when it failed to run. */
+ broken?: string;
+}
+
+export interface Where {
+ configured?: string;
+ env?: NodeJS.ProcessEnv;
+ platform?: NodeJS.Platform;
+ home?: string;
+}
+
+/** Where adb is looked for, first match first: the user's own setting, PATH, the SDK variables, then where installers put it. */
+export function adbCandidates({ configured, env = process.env, platform = process.platform, home = homedir() }: Where = {}): string[] {
+ const windows = platform === 'win32';
+ const path = windows ? win32 : posix;
+ const exe = windows ? 'adb.exe' : 'adb';
+ const sdkRoots = [
+ variable(env, 'ANDROID_HOME'),
+ variable(env, 'ANDROID_SDK_ROOT'),
+ platform === 'darwin' ? path.join(home, 'Library', 'Android', 'sdk') : undefined,
+ windows ? path.join(variable(env, 'LOCALAPPDATA') ?? path.join(home, 'AppData', 'Local'), 'Android', 'Sdk') : undefined,
+ platform === 'linux' ? path.join(home, 'Android', 'Sdk') : undefined,
+ ];
+ const candidates = [
+ configured,
+ ...(variable(env, 'PATH') ?? '')
+ .split(windows ? ';' : ':')
+ .map((dir) => dir.replace(/^"|"$/g, ''))
+ .filter(Boolean)
+ .map((dir) => path.join(dir, exe)),
+ ...sdkRoots.filter((root): root is string => !!root).map((root) => path.join(root, 'platform-tools', exe)),
+ ...(windows ? [] : ['/opt/homebrew/bin/adb', '/usr/local/bin/adb']),
+ ];
+ return [...new Set(candidates.filter((candidate): candidate is string => !!candidate))];
+}
+
+export function isProgram(path: string, platform: NodeJS.Platform = process.platform): boolean {
+ try {
+ if (!statSync(path).isFile()) return false;
+ if (platform !== 'win32') accessSync(path, constants.X_OK);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export async function locateAdb(where: Where = {}, exists: (path: string) => boolean = isProgram): Promise<AdbFound | null> {
+ const path = adbCandidates(where).find((candidate) => exists(candidate));
+ if (!path) return null;
+ const answer = await capture(path, ['version'], VERSION_TIMEOUT_MS);
+ return answer.ok ? { path, version: versionOf(answer.output) } : { path, broken: firstLine(answer.output) ?? answer.error ?? 'it did not run' };
+}
+
+/** `Version 37.0.0-14910828` names the platform-tools release; older builds print only the protocol's `version 1.0.41`. */
+export function versionOf(output: string): string | undefined {
+ return /^Version (\S+)/m.exec(output)?.[1] ?? /Android Debug Bridge version (\S+)/.exec(output)?.[1];
+}
+
+/**
+ * Started only when no server answers: `adb start-server` against a running server of another
+ * version would kill it. Its output is not read, because the server it forks keeps any pipe it
+ * inherits open for as long as it runs.
+ */
+export function startServer(path: string): Promise<boolean> {
+ return new Promise((resolve) => {
+ const child = spawn(path, ['start-server'], { stdio: 'ignore', windowsHide: true });
+ const timer = setTimeout(() => {
+ stopTree(child, 'SIGKILL');
+ resolve(false);
+ }, START_SERVER_TIMEOUT_MS);
+ child.once('error', () => {
+ clearTimeout(timer);
+ resolve(false);
+ });
+ child.once('exit', (code) => {
+ clearTimeout(timer);
+ resolve(code === 0);
+ });
+ });
+}
+
+function capture(path: string, args: string[], timeoutMs: number): Promise<{ ok: boolean; output: string; error?: string }> {
+ return new Promise((resolve) => {
+ let output = '';
+ let child: ReturnType<typeof spawnCli>;
+ try {
+ child = spawnCli(path, args);
+ } catch (error) {
+ return resolve({ ok: false, output, error: (error as Error).message });
+ }
+ const timer = setTimeout(() => {
+ stopTree(child, 'SIGKILL');
+ resolve({ ok: false, output, error: `timed out after ${timeoutMs} ms` });
+ }, timeoutMs);
+ const collect = (chunk: Buffer) => (output += chunk.toString());
+ child.stdout.on('data', collect);
+ child.stderr.on('data', collect);
+ child.once('error', (error) => {
+ clearTimeout(timer);
+ resolve({ ok: false, output, error: error.message });
+ });
+ child.once('close', (code) => {
+ clearTimeout(timer);
+ resolve({ ok: code === 0, output });
+ });
+ });
+}
+
+const firstLine = (output: string): string | undefined =>
+ output
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .find(Boolean)
+ ?.slice(0, 200);
diff --git a/src/daemon/android/devices.ts b/src/daemon/android/devices.ts
new file mode 100644
index 0000000..6ad3cbb
--- /dev/null
+++ b/src/daemon/android/devices.ts
@@ -0,0 +1,44 @@
+import type { AndroidDevice, AndroidDeviceState } from '@/lib/phone/types';
+
+export interface TrackedDevice {
+ serial: string;
+ state: AndroidDeviceState;
+ /** adb's own word, which says more than `other` does: `recovery`, `sideload`, `bootloader`. */
+ adbState: string;
+ transport: AndroidDevice['transport'];
+ model?: string;
+ /** A new one for the same serial means the connection was reset and every forward on it is gone. */
+ transportId?: string;
+}
+
+const STATES: Record<string, AndroidDeviceState> = {
+ device: 'ready',
+ unauthorized: 'unauthorized',
+ offline: 'offline',
+ 'no permissions': 'no-permissions',
+};
+
+const LINE = /^(\S+)\s+(no permissions|\S+)(.*)$/;
+const PROPERTY = /\b(model|transport_id):(\S+)/g;
+const WIRELESS = /:|_adb-tls-connect/;
+
+export const transportOf = (serial: string): AndroidDevice['transport'] => (WIRELESS.test(serial) ? 'wifi' : 'usb');
+
+/** Reads `adb devices -l`, or one message of `host:track-devices-l`, which is the same list without its heading. */
+export function parseDeviceList(text: string): TrackedDevice[] {
+ return text
+ .split(/\r?\n/)
+ .map((line) => LINE.exec(line.trim()))
+ .filter((match): match is RegExpExecArray => match !== null && match[1] !== 'List')
+ .map(([, serial, adbState, rest]) => {
+ const properties = Object.fromEntries([...rest.matchAll(PROPERTY)].map(([, key, value]) => [key, value]));
+ return {
+ serial,
+ state: STATES[adbState] ?? 'other',
+ adbState,
+ transport: transportOf(serial),
+ model: properties.model?.replaceAll('_', ' '),
+ transportId: properties.transport_id,
+ };
+ });
+}
diff --git a/src/daemon/android/fixtures/adb-version.txt b/src/daemon/android/fixtures/adb-version.txt
new file mode 100644
index 0000000..9484d9d
--- /dev/null
+++ b/src/daemon/android/fixtures/adb-version.txt
@@ -0,0 +1,4 @@
+Android Debug Bridge version 1.0.41
+Version 37.0.0-14910828
+Installed as /Users/shahriar/Library/Android/sdk/platform-tools/adb
+Running on Darwin 25.6.0 (arm64)
diff --git a/src/daemon/android/fixtures/devices-emulator.txt b/src/daemon/android/fixtures/devices-emulator.txt
new file mode 100644
index 0000000..4b0a1b4
--- /dev/null
+++ b/src/daemon/android/fixtures/devices-emulator.txt
@@ -0,0 +1 @@
+emulator-5554 device product:sdk_gphone16k_arm64 model:sdk_gphone16k_arm64 device:emu64a16k transport_id:21
diff --git a/src/daemon/android/fixtures/devices-no-permissions.handwritten.txt b/src/daemon/android/fixtures/devices-no-permissions.handwritten.txt
new file mode 100644
index 0000000..01c3b58
--- /dev/null
+++ b/src/daemon/android/fixtures/devices-no-permissions.handwritten.txt
@@ -0,0 +1 @@
+0123456789ABCDEF no permissions (missing udev rules? user is in the plugdev group); see [http://developer.android.com/tools/device.html] usb:1-1 transport_id:3
diff --git a/src/daemon/android/fixtures/devices-none.txt b/src/daemon/android/fixtures/devices-none.txt
new file mode 100644
index 0000000..8213a91
--- /dev/null
+++ b/src/daemon/android/fixtures/devices-none.txt
@@ -0,0 +1,2 @@
+List of devices attached
+
diff --git a/src/daemon/android/fixtures/devices-offline.txt b/src/daemon/android/fixtures/devices-offline.txt
new file mode 100644
index 0000000..7386ac0
--- /dev/null
+++ b/src/daemon/android/fixtures/devices-offline.txt
@@ -0,0 +1,2 @@
+List of devices attached
+emulator-5554 offline transport_id:18
diff --git a/src/daemon/android/fixtures/devices-unauthorized.handwritten.txt b/src/daemon/android/fixtures/devices-unauthorized.handwritten.txt
new file mode 100644
index 0000000..277f07f
--- /dev/null
+++ b/src/daemon/android/fixtures/devices-unauthorized.handwritten.txt
@@ -0,0 +1 @@
+R5CT1234567 unauthorized usb:1-1 transport_id:4
diff --git a/src/daemon/android/fixtures/devices-wireless.handwritten.txt b/src/daemon/android/fixtures/devices-wireless.handwritten.txt
new file mode 100644
index 0000000..871a397
--- /dev/null
+++ b/src/daemon/android/fixtures/devices-wireless.handwritten.txt
@@ -0,0 +1,2 @@
+adb-R5CT1234567-AbCdEf._adb-tls-connect._tcp device product:dm3q model:SM_S918B device:dm3q transport_id:7
+192.168.1.20:5555 offline transport_id:8
diff --git a/src/daemon/android/fixtures/facts-chrome-closed.txt b/src/daemon/android/fixtures/facts-chrome-closed.txt
new file mode 100644
index 0000000..46c93e6
--- /dev/null
+++ b/src/daemon/android/fixtures/facts-chrome-closed.txt
@@ -0,0 +1,29 @@
+@@browsentic:booted
+1
+@@browsentic:model
+sdk_gphone16k_arm64
+@@browsentic:manufacturer
+Google
+@@browsentic:release
+17
+@@browsentic:sdk
+37
+@@browsentic:size
+Physical size: 1080x2092
+@@browsentic:density
+Physical density: 420
+@@browsentic:power
+ mWakefulness=Awake
+mWakefulness=1
+@@browsentic:chrome
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/base.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_chrome.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_config.en.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_dev_ui.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_on_demand.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_stack_unwinder.apk
+@@browsentic:version
+ versionName=150.0.7871.186
+ versionName=145.0.7632.218
+@@browsentic:pid
+@@browsentic:socket
diff --git a/src/daemon/android/fixtures/facts-chrome-open.txt b/src/daemon/android/fixtures/facts-chrome-open.txt
new file mode 100644
index 0000000..24638b7
--- /dev/null
+++ b/src/daemon/android/fixtures/facts-chrome-open.txt
@@ -0,0 +1,31 @@
+@@browsentic:booted
+1
+@@browsentic:model
+sdk_gphone16k_arm64
+@@browsentic:manufacturer
+Google
+@@browsentic:release
+17
+@@browsentic:sdk
+37
+@@browsentic:size
+Physical size: 1080x2092
+@@browsentic:density
+Physical density: 420
+@@browsentic:power
+ mWakefulness=Awake
+mWakefulness=1
+@@browsentic:chrome
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/base.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_chrome.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_config.en.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_dev_ui.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_on_demand.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_stack_unwinder.apk
+@@browsentic:version
+ versionName=150.0.7871.186
+ versionName=145.0.7632.218
+@@browsentic:pid
+3802
+@@browsentic:socket
+0000000000000000: 00000002 00000000 00010000 0001 01 25972 @chrome_devtools_remote
diff --git a/src/daemon/android/fixtures/facts-overridden.txt b/src/daemon/android/fixtures/facts-overridden.txt
new file mode 100644
index 0000000..0ef9636
--- /dev/null
+++ b/src/daemon/android/fixtures/facts-overridden.txt
@@ -0,0 +1,31 @@
+@@browsentic:booted
+1
+@@browsentic:model
+sdk_gphone16k_arm64
+@@browsentic:manufacturer
+Google
+@@browsentic:release
+17
+@@browsentic:sdk
+37
+@@browsentic:size
+Physical size: 1080x2092
+Override size: 1000x1900
+@@browsentic:density
+Physical density: 420
+Override density: 400
+@@browsentic:power
+ mWakefulness=Awake
+mWakefulness=1
+@@browsentic:chrome
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/base.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_chrome.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_config.en.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_dev_ui.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_on_demand.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_stack_unwinder.apk
+@@browsentic:version
+ versionName=150.0.7871.186
+ versionName=145.0.7632.218
+@@browsentic:pid
+@@browsentic:socket
diff --git a/src/daemon/android/fixtures/facts-screen-off.txt b/src/daemon/android/fixtures/facts-screen-off.txt
new file mode 100644
index 0000000..60cc39c
--- /dev/null
+++ b/src/daemon/android/fixtures/facts-screen-off.txt
@@ -0,0 +1,31 @@
+@@browsentic:booted
+1
+@@browsentic:model
+sdk_gphone16k_arm64
+@@browsentic:manufacturer
+Google
+@@browsentic:release
+17
+@@browsentic:sdk
+37
+@@browsentic:size
+Physical size: 1080x2092
+@@browsentic:density
+Physical density: 420
+@@browsentic:power
+ mWakefulness=Asleep
+mWakefulness=0
+@@browsentic:chrome
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/base.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_chrome.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_config.en.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_dev_ui.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_on_demand.apk
+package:/data/app/~~AJeAuDkePtHt3J0QDHOM6Q==/com.android.chrome-0E0i7Tl56_ENSRNcs5ki3g==/split_stack_unwinder.apk
+@@browsentic:version
+ versionName=150.0.7871.186
+ versionName=145.0.7632.218
+@@browsentic:pid
+3802
+@@browsentic:socket
+0000000000000000: 00000002 00000000 00010000 0001 01 25972 @chrome_devtools_remote
diff --git a/src/daemon/android/launch.ts b/src/daemon/android/launch.ts
new file mode 100644
index 0000000..5b821c2
--- /dev/null
+++ b/src/daemon/android/launch.ts
@@ -0,0 +1,44 @@
+import type { AdbServer } from './adb-server';
+import { CHROME_PACKAGE, DEVTOOLS_SOCKET, isDebuggable } from './phone-facts';
+
+const CHROME_ACTIVITY = `${CHROME_PACKAGE}/com.google.android.apps.chrome.Main`;
+const SOCKET_WAIT_MS = 10_000;
+const SOCKET_POLL_MS = 250;
+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.
+ */
+export function launchChromeCommand(url?: string): string {
+ const target = url && webUrl(url);
+ return target
+ ? `am start -a android.intent.action.VIEW -d '${target.replaceAll("'", "'\\''")}' -n ${CHROME_ACTIVITY}`
+ : `am start -n ${CHROME_ACTIVITY}`;
+}
+
+function webUrl(url: string): string | undefined {
+ try {
+ const parsed = new URL(url);
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? parsed.href : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/** Starts Chrome and waits until its DevTools socket is open: 2 to 5 seconds from a cold start. */
+export async function launchChrome(server: AdbServer, serial: string, url?: string): Promise<boolean> {
+ await server.shell(serial, launchChromeCommand(url), AM_TIMEOUT_MS);
+ const deadline = Date.now() + SOCKET_WAIT_MS;
+ while (Date.now() < deadline) {
+ if (isDebuggable(await server.shell(serial, `grep ${DEVTOOLS_SOCKET} /proc/net/unix`).catch(() => ''))) return true;
+ await new Promise((resolve) => setTimeout(resolve, SOCKET_POLL_MS));
+ }
+ return false;
+}
+
+export async function openChromeListing(server: AdbServer, serial: string): Promise<void> {
+ await server.shell(serial, INSTALL_CHROME_COMMAND, AM_TIMEOUT_MS);
+}
diff --git a/src/daemon/android/parsers.test.ts b/src/daemon/android/parsers.test.ts
new file mode 100644
index 0000000..c7659d0
--- /dev/null
+++ b/src/daemon/android/parsers.test.ts
@@ -0,0 +1,141 @@
+import { readFileSync } from 'node:fs';
+import { describe, expect, test } from 'vitest';
+import { parseDeviceList, transportOf } from './devices';
+import { FACTS_COMMAND, isDebuggable, parseFacts } from './phone-facts';
+import { versionOf } from './adb';
+
+const fixture = (name: string) => readFileSync(new URL(`./fixtures/${name}`, import.meta.url), 'utf8');
+
+/** A captured answer with one probe's section replaced, for the states the emulator cannot be put in. */
+const answering = (text: string, probe: string, lines: string[]) =>
+ text.replace(new RegExp(`(@@browsentic:${probe}\\n)(?:(?!@@browsentic:)[^\\n]*\\n?)*`), `$1${lines.map((line) => `${line}\n`).join('')}`);
+
+describe('the device list', () => {
+ test('an emulator that is ready, with its model and transport id', () => {
+ expect(parseDeviceList(fixture('devices-emulator.txt'))).toEqual([
+ { serial: 'emulator-5554', state: 'ready', adbState: 'device', transport: 'usb', model: 'sdk gphone16k arm64', transportId: '21' },
+ ]);
+ });
+
+ test('none attached is an empty list, heading or not', () => {
+ expect(parseDeviceList(fixture('devices-none.txt'))).toEqual([]);
+ expect(parseDeviceList('')).toEqual([]);
+ });
+
+ test('offline and unauthorized keep their meaning', () => {
+ expect(parseDeviceList(fixture('devices-offline.txt'))).toMatchObject([{ serial: 'emulator-5554', state: 'offline', transportId: '18' }]);
+ expect(parseDeviceList(fixture('devices-unauthorized.handwritten.txt'))).toMatchObject([
+ { serial: 'R5CT1234567', state: 'unauthorized', transport: 'usb', transportId: '4' },
+ ]);
+ });
+
+ test('"no permissions" is one state although it is two words, and its link is not read as a property', () => {
+ expect(parseDeviceList(fixture('devices-no-permissions.handwritten.txt'))).toEqual([
+ { serial: '0123456789ABCDEF', state: 'no-permissions', adbState: 'no permissions', transport: 'usb', model: undefined, transportId: '3' },
+ ]);
+ });
+
+ test('wireless serials, from mDNS pairing and from adb connect, are wifi', () => {
+ expect(parseDeviceList(fixture('devices-wireless.handwritten.txt'))).toMatchObject([
+ { serial: 'adb-R5CT1234567-AbCdEf._adb-tls-connect._tcp', state: 'ready', transport: 'wifi', model: 'SM S918B' },
+ { serial: '192.168.1.20:5555', state: 'offline', transport: 'wifi' },
+ ]);
+ expect(transportOf('emulator-5554')).toBe('usb');
+ });
+
+ test('every other adb state is other, and adb\'s word for it is kept', () => {
+ const list = ['A1 recovery transport_id:1', 'A2 sideload', 'A3 bootloader', 'A4 authorizing transport_id:9'].join('\n');
+ expect(parseDeviceList(list).map(({ state, adbState }) => [state, adbState])).toEqual([
+ ['other', 'recovery'],
+ ['other', 'sideload'],
+ ['other', 'bootloader'],
+ ['other', 'authorizing'],
+ ]);
+ });
+
+ test('a track-devices message with Windows line ends reads the same', () => {
+ expect(parseDeviceList(fixture('devices-emulator.txt').replaceAll('\n', '\r\n'))).toHaveLength(1);
+ });
+});
+
+describe('the phone facts', () => {
+ test('one shell call asks every probe, each under its own marker', () => {
+ expect(FACTS_COMMAND.match(/echo @@browsentic:\w+/g)).toHaveLength(12);
+ expect(FACTS_COMMAND).not.toMatch(/"/);
+ });
+
+ test('Chrome open on an awake phone', () => {
+ expect(parseFacts(fixture('facts-chrome-open.txt'))).toEqual({
+ booted: true,
+ 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 },
+ });
+ });
+
+ test('the running Chrome is the update, not the copy the system image shipped', () => {
+ expect(parseFacts(fixture('facts-chrome-open.txt')).chrome.version).toBe('150.0.7871.186');
+ });
+
+ test('Chrome closed: installed, no process and no socket', () => {
+ expect(parseFacts(fixture('facts-chrome-closed.txt')).chrome).toEqual({
+ installed: true,
+ version: '150.0.7871.186',
+ running: false,
+ debuggable: false,
+ });
+ });
+
+ test('a process Android started at boot is running but not debuggable', () => {
+ expect(parseFacts(answering(fixture('facts-chrome-closed.txt'), 'pid', ['7953'])).chrome).toMatchObject({ running: true, debuggable: false });
+ });
+
+ test('the screen off', () => {
+ expect(parseFacts(fixture('facts-screen-off.txt')).screen?.awake).toBe(false);
+ });
+
+ test('an override is what the phone renders at', () => {
+ expect(parseFacts(fixture('facts-overridden.txt')).screen).toEqual({ width: 1000, height: 1900, density: 400, awake: true });
+ });
+
+ test('Chrome missing: pm path prints nothing', () => {
+ const missing = ['chrome', 'version', 'pid', 'socket'].reduce((text, probe) => answering(text, probe, []), fixture('facts-chrome-open.txt'));
+ expect(parseFacts(missing).chrome).toEqual({ installed: false, version: undefined, running: false, debuggable: false });
+ });
+
+ test('still booting', () => {
+ expect(parseFacts(answering(fixture('facts-chrome-open.txt'), 'booted', [])).booted).toBe(false);
+ });
+
+ test('another app\'s DevTools socket is not Chrome\'s', () => {
+ const others = [
+ '0000000000000000: 00000002 00000000 00010000 0001 01 16893 @stetho_com.google.android.apps.messaging_devtools_remote',
+ '0000000000000000: 00000002 00000000 00010000 0001 01 16894 @chrome_devtools_remote_1234',
+ ].join('\n');
+ expect(isDebuggable(others)).toBe(false);
+ expect(isDebuggable(`${others}\n0000000000000000: 00000002 00000000 00010000 0001 01 50526 @chrome_devtools_remote`)).toBe(true);
+ });
+
+ test('an empty or garbled answer knows nothing, and claims nothing', () => {
+ expect(parseFacts('')).toEqual({
+ booted: false,
+ model: undefined,
+ manufacturer: undefined,
+ android: undefined,
+ sdk: undefined,
+ screen: undefined,
+ chrome: { installed: false, version: undefined, running: false, debuggable: false },
+ });
+ });
+});
+
+describe('the adb version', () => {
+ test('the platform-tools release when adb prints one, the protocol version otherwise', () => {
+ expect(versionOf(fixture('adb-version.txt'))).toBe('37.0.0-14910828');
+ expect(versionOf('Android Debug Bridge version 1.0.39\n')).toBe('1.0.39');
+ expect(versionOf('something else')).toBeUndefined();
+ });
+});
diff --git a/src/daemon/android/phone-facts.ts b/src/daemon/android/phone-facts.ts
new file mode 100644
index 0000000..aac23d3
--- /dev/null
+++ b/src/daemon/android/phone-facts.ts
@@ -0,0 +1,84 @@
+import type { AndroidDevice } from '@/lib/phone/types';
+
+export const CHROME_PACKAGE = 'com.android.chrome';
+export const DEVTOOLS_SOCKET = '@chrome_devtools_remote';
+
+const PROBES = {
+ booted: 'getprop sys.boot_completed',
+ model: 'getprop ro.product.model',
+ manufacturer: 'getprop ro.product.manufacturer',
+ release: 'getprop ro.build.version.release',
+ sdk: 'getprop ro.build.version.sdk',
+ size: 'wm size',
+ density: 'wm density',
+ power: 'dumpsys power | grep mWakefulness=',
+ chrome: `pm path ${CHROME_PACKAGE}`,
+ version: `dumpsys package ${CHROME_PACKAGE} | grep versionName=`,
+ pid: `pidof ${CHROME_PACKAGE}`,
+ socket: `grep ${DEVTOOLS_SOCKET} /proc/net/unix`,
+} as const;
+
+type Probe = keyof typeof PROBES;
+
+const MARK = '@@browsentic:';
+
+/** Every probe in one `adb shell`, each answer under its own marker, so one that fails or prints nothing cannot shift the others. */
+export const FACTS_COMMAND = Object.entries(PROBES)
+ .map(([probe, command]) => `echo ${MARK}${probe}; ${command}`)
+ .join('; ');
+
+export interface PhoneFacts {
+ booted: boolean;
+ model?: string;
+ manufacturer?: string;
+ android?: string;
+ sdk?: number;
+ screen?: NonNullable<AndroidDevice['screen']>;
+ chrome: AndroidDevice['chrome'];
+}
+
+export function parseFacts(output: string): PhoneFacts {
+ const answers = sections(output);
+ const line = (probe: Probe) => answers[probe]?.[0];
+ const size = dimension(answers.size, /size: (\d+)x(\d+)/);
+ const density = dimension(answers.density, /density: (\d+)/);
+ const sdk = Number(line('sdk'));
+ return {
+ booted: line('booted') === '1',
+ model: line('model'),
+ manufacturer: line('manufacturer'),
+ android: line('release'),
+ sdk: Number.isInteger(sdk) && sdk > 0 ? sdk : undefined,
+ screen:
+ size && density
+ ? { width: size[0], height: size[1], density: density[0], awake: /mWakefulness=Awake\b/.test(answers.power?.join('\n') ?? '') }
+ : undefined,
+ chrome: {
+ installed: (answers.chrome ?? []).some((entry) => entry.startsWith('package:')),
+ version: answers.version?.map((entry) => /versionName=(\S+)/.exec(entry)?.[1]).find(Boolean),
+ running: (answers.pid ?? []).some((entry) => /^\d+(\s+\d+)*$/.test(entry)),
+ debuggable: isDebuggable(answers.socket?.join('\n') ?? ''),
+ },
+ };
+}
+
+/** The socket's name ends its line; a bare `devtools_remote` would also match other apps', such as `@stetho_…_devtools_remote`. */
+export const isDebuggable = (unixSockets: string): boolean =>
+ unixSockets.split(/\r?\n/).some((entry) => entry.trim().endsWith(` ${DEVTOOLS_SOCKET}`));
+
+function sections(output: string): Partial<Record<Probe, string[]>> {
+ const found: Partial<Record<string, string[]>> = {};
+ let current: string[] | undefined;
+ for (const raw of output.split(/\r?\n/)) {
+ const entry = raw.trim();
+ if (entry.startsWith(MARK)) found[entry.slice(MARK.length)] = current = [];
+ else if (entry) current?.push(entry);
+ }
+ return found;
+}
+
+/** `wm` prints the physical value, then an override when one is set; the override is what the phone renders at. */
+function dimension(entries: string[] | undefined, pattern: RegExp): number[] | undefined {
+ const values = (entries ?? []).map((entry) => pattern.exec(entry)?.slice(1).map(Number)).filter((value) => value !== undefined);
+ return values.at(-1);
+}
diff --git a/src/daemon/android/readiness.test.ts b/src/daemon/android/readiness.test.ts
new file mode 100644
index 0000000..a5ed5d0
--- /dev/null
+++ b/src/daemon/android/readiness.test.ts
@@ -0,0 +1,106 @@
+import { readFileSync } from 'node:fs';
+import { describe, expect, test } from 'vitest';
+import type { AndroidProblemCode } from '@/lib/phone/types';
+import { parseDeviceList, type TrackedDevice } from './devices';
+import { parseFacts, type PhoneFacts } from './phone-facts';
+import { judge, type Observed } from './readiness';
+
+const fixture = (name: string) => readFileSync(new URL(`./fixtures/${name}`, import.meta.url), 'utf8');
+
+const ADB = { path: '/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 observed = (devices: Observed['devices'], more: Partial<Observed> = {}): Observed => ({
+ enabled: true,
+ platform: 'darwin',
+ adb: ADB,
+ devices,
+ ...more,
+});
+
+const phone = (device: Partial<TrackedDevice>, facts: PhoneFacts | null = null) => ({ device: { ...emulator, ...device }, facts });
+const withChrome = (chrome: Partial<PhoneFacts['chrome']>): PhoneFacts => ({ ...open, chrome: { ...open.chrome, ...chrome } });
+
+describe('readiness', () => {
+ test('a phone with Chrome open for debugging is ready, with no problem', () => {
+ const state = judge(observed([phone({}, open)]));
+ expect(state).toMatchObject({ enabled: true, ready: true, adb: { found: true, ...ADB }, problem: undefined });
+ expect(state.devices).toEqual([
+ {
+ 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 },
+ problem: undefined,
+ },
+ ]);
+ });
+
+ const rows: [string, Observed, AndroidProblemCode, Partial<{ ready: boolean; fix: RegExp; action: string }>?][] = [
+ ['switched off in config.json', observed([], { enabled: false, adb: undefined }), 'ANDROID_OFF', { fix: /"enabled": true/ }],
+ ['no adb on macOS', observed([], { adb: null }), 'ADB_MISSING', { fix: /^brew install --cask android-platform-tools$/ }],
+ ['no adb on Windows', observed([], { adb: null, platform: 'win32' }), 'ADB_MISSING', { fix: /^winget install Google\.PlatformTools$/ }],
+ ['no adb on Linux', observed([], { adb: null, platform: 'linux' }), 'ADB_MISSING', { fix: /adb/ }],
+ ['an adb that does not run', observed([], { adb: { path: ADB.path, broken: 'Bad CPU type in executable' } }), 'ADB_BROKEN'],
+ ['adb\'s server that will not start', observed([], { serverError: 'start-server did not start adb\'s server' }), 'ADB_BROKEN'],
+ ['adb with no phone', observed([]), 'NO_DEVICE', { fix: /USB debugging/ }],
+ ['a phone waiting for Allow', observed([phone({ state: 'unauthorized', adbState: 'unauthorized' })]), 'DEVICE_UNAUTHORIZED', { fix: /tap Allow/ }],
+ ['a phone offline on USB', observed([phone({ state: 'offline', adbState: 'offline' })]), 'DEVICE_OFFLINE', { fix: /plug it in again/ }],
+ [
+ 'a phone offline over Wi-Fi',
+ observed([phone({ serial: '192.168.1.20:5555', transport: 'wifi', state: 'offline', adbState: 'offline' })]),
+ 'DEVICE_OFFLINE',
+ { fix: /^adb connect 192\.168\.1\.20:5555$/ },
+ ],
+ ['a phone in recovery', observed([phone({ state: 'other', adbState: 'recovery' })]), 'DEVICE_OFFLINE', { fix: /Restart the phone/ }],
+ ['a phone that stopped answering', observed([phone({}, null)]), 'DEVICE_OFFLINE'],
+ ['Linux without udev rules', observed([phone({ state: 'no-permissions', adbState: 'no permissions' })], { platform: 'linux' }), 'NO_PERMISSIONS', { fix: /udev/ }],
+ ['a phone still booting', observed([phone({}, { ...open, booted: false })]), 'DEVICE_BOOTING'],
+ ['no Chrome on the phone', observed([phone({}, withChrome({ installed: false, version: undefined, running: false, debuggable: false }))]), 'CHROME_MISSING', { action: 'installChrome' }],
+ ['Chrome closed', observed([phone({}, withChrome({ running: false, debuggable: false }))]), 'CHROME_NOT_RUNNING', { action: 'launchChrome' }],
+ ['Chrome pre-started by Android but never opened', observed([phone({}, withChrome({ running: true, debuggable: false }))]), 'CHROME_NOT_RUNNING'],
+ [
+ 'the screen off, which is only advice',
+ observed([phone({}, { ...open, screen: { ...open.screen!, awake: false } })]),
+ 'SCREEN_OFF',
+ { ready: true },
+ ],
+ ];
+
+ test.each(rows)('%s', (_name, seen, code, expected = {}) => {
+ const state = judge(seen);
+ expect(state.problem?.code).toBe(code);
+ expect(state.ready).toBe(expected.ready ?? false);
+ if (expected.fix) expect(state.problem?.fix).toMatch(expected.fix);
+ if (expected.action) expect(state.problem?.action).toBe(expected.action);
+ expect(state.problem?.message).not.toMatch(/—/);
+ });
+
+ test('adb problems sit on adb as well as at the top', () => {
+ expect(judge(observed([], { adb: null })).adb).toMatchObject({ found: false, problem: { code: 'ADB_MISSING' } });
+ expect(judge(observed([], { adb: { path: ADB.path, broken: 'boom' } })).adb).toMatchObject({ found: true, path: ADB.path, problem: { code: 'ADB_BROKEN', message: expect.stringContaining('boom') } });
+ });
+
+ test('Windows mentions the USB driver when it sees no phone', () => {
+ expect(judge(observed([], { platform: 'win32' })).problem?.message).toMatch(/USB driver/);
+ expect(judge(observed([])).problem?.message).not.toMatch(/driver/);
+ });
+
+ test('a ready phone beside an unready one makes the whole ready', () => {
+ const state = judge(observed([phone({ serial: 'R5CT1234567', state: 'unauthorized', adbState: 'unauthorized' }), phone({}, open)]));
+ expect(state.ready).toBe(true);
+ expect(state.problem).toBeUndefined();
+ expect(state.devices.map((device) => device.problem?.code)).toEqual(['DEVICE_UNAUTHORIZED', undefined]);
+ });
+
+ test('the session rides along', () => {
+ const session = { serial: 'emulator-5554', since: '2026-10-09T20:00:00.000Z' };
+ expect(judge(observed([phone({}, open)], { session })).session).toEqual(session);
+ });
+});
diff --git a/src/daemon/android/readiness.ts b/src/daemon/android/readiness.ts
new file mode 100644
index 0000000..5e602fe
--- /dev/null
+++ b/src/daemon/android/readiness.ts
@@ -0,0 +1,152 @@
+import type { AndroidDevice, AndroidProblem, AndroidState } from '@/lib/phone/types';
+import type { AdbFound } from './adb';
+import type { TrackedDevice } from './devices';
+import type { PhoneFacts } from './phone-facts';
+
+export const PLATFORM_TOOLS_URL = 'https://developer.android.com/tools/releases/platform-tools';
+
+const INSTALL_ADB: Partial<Record<NodeJS.Platform, string>> = {
+ darwin: 'brew install --cask android-platform-tools',
+ win32: 'winget install Google.PlatformTools',
+ linux: 'sudo apt install adb',
+};
+
+export interface Observed {
+ enabled: boolean;
+ platform: NodeJS.Platform;
+ adb?: AdbFound | null;
+ /** Why the list of phones could not be read from adb's server. */
+ serverError?: string;
+ /** `facts` is null for a phone that is not ready, or that did not answer. */
+ devices: { device: TrackedDevice; facts: PhoneFacts | null }[];
+ session?: AndroidState['session'];
+}
+
+export const PROBLEMS = {
+ off: (): AndroidProblem => ({
+ code: 'ANDROID_OFF',
+ message: 'Android is switched off for this computer.',
+ fix: 'Set "android": { "enabled": true } in ~/.browsentic/config.json',
+ }),
+ adbMissing: (platform: NodeJS.Platform): AndroidProblem => ({
+ 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 ${PLATFORM_TOOLS_URL}.`,
+ fix: INSTALL_ADB[platform] ?? PLATFORM_TOOLS_URL,
+ }),
+ adbBroken: (path: string, why: string): AndroidProblem => ({
+ code: 'ADB_BROKEN',
+ message: `adb at ${path} does not run: ${why}`,
+ fix: `Reinstall platform-tools, or set "android": { "adb": "<path to a working adb>" } in ~/.browsentic/config.json`,
+ }),
+ noDevice: (platform: NodeJS.Platform): AndroidProblem => ({
+ code: 'NO_DEVICE',
+ message:
+ platform === 'win32'
+ ? 'No Android phone is connected. On Windows the phone also needs its USB driver, from its maker or Google, before adb can see it.'
+ : '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.',
+ }),
+ unauthorized: (): AndroidProblem => ({
+ 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.',
+ }),
+ offline: (device: TrackedDevice): AndroidProblem => ({
+ code: 'DEVICE_OFFLINE',
+ message: 'The phone is connected but not answering adb.',
+ fix: device.transport === 'wifi' ? `adb connect ${device.serial}` : 'Unplug the phone and plug it in again.',
+ }),
+ otherMode: (device: TrackedDevice): AndroidProblem => ({
+ code: 'DEVICE_OFFLINE',
+ message: `The phone is in ${device.adbState} mode.`,
+ fix: 'Restart the phone normally.',
+ }),
+ silent: (): AndroidProblem => ({
+ code: 'DEVICE_OFFLINE',
+ message: 'The phone stopped answering adb.',
+ fix: 'Unlock the phone. If that does not help, unplug it and plug it in again.',
+ }),
+ noPermissions: (): AndroidProblem => ({
+ code: 'NO_PERMISSIONS',
+ message: 'This computer is not allowed to open the phone\'s USB connection.',
+ fix: 'Add udev rules for Android phones (the android-sdk-platform-tools-common package has them), then plug the phone in again.',
+ }),
+ booting: (): AndroidProblem => ({
+ code: 'DEVICE_BOOTING',
+ message: 'The phone is still starting up.',
+ }),
+ chromeMissing: (): AndroidProblem => ({
+ code: 'CHROME_MISSING',
+ message: 'Chrome is not installed on the phone.',
+ fix: 'Install Google Chrome from the Play Store on the phone.',
+ action: 'installChrome',
+ }),
+ chromeClosed: (): AndroidProblem => ({
+ code: 'CHROME_NOT_RUNNING',
+ message: 'Chrome is not open on the phone.',
+ fix: 'Open Chrome on the phone.',
+ action: 'launchChrome',
+ }),
+ screenOff: (): AndroidProblem => ({
+ code: 'SCREEN_OFF',
+ message: 'The phone\'s screen is off, so Chrome is not drawing the page.',
+ fix: 'Unlock the phone.',
+ }),
+} as const;
+
+export function judge(observed: Observed): AndroidState {
+ const { enabled, platform, adb, serverError, session } = observed;
+ const base = { enabled, adb: { found: !!adb, path: adb?.path, version: adb?.version }, session };
+ const stopped = (problem: AndroidProblem, onAdb = false): AndroidState => ({
+ ...base,
+ ready: false,
+ adb: onAdb ? { ...base.adb, problem } : base.adb,
+ devices: [],
+ problem,
+ });
+
+ if (!enabled) return stopped(PROBLEMS.off());
+ if (!adb) return stopped(PROBLEMS.adbMissing(platform), true);
+ if (adb.broken) return stopped(PROBLEMS.adbBroken(adb.path, adb.broken), true);
+ if (serverError) return stopped(PROBLEMS.adbBroken(adb.path, serverError), true);
+
+ const devices = observed.devices.map(({ device, facts }) => describe(device, facts));
+ const ready = devices.find(isDrivable);
+ return {
+ ...base,
+ ready: !!ready,
+ devices,
+ problem: ready ? ready.problem : (devices.find((device) => device.problem)?.problem ?? PROBLEMS.noDevice(platform)),
+ };
+}
+
+export const isDrivable = (device: AndroidDevice): boolean =>
+ device.state === 'ready' && device.chrome.debuggable && (!device.problem || device.problem.code === 'SCREEN_OFF');
+
+function describe(device: TrackedDevice, facts: PhoneFacts | null): AndroidDevice {
+ const known: AndroidDevice = {
+ serial: device.serial,
+ transport: device.transport,
+ state: device.state,
+ model: facts?.model ?? device.model,
+ manufacturer: facts?.manufacturer,
+ android: facts?.android,
+ sdk: facts?.sdk,
+ screen: facts?.screen,
+ chrome: facts?.chrome ?? { installed: false, running: false, debuggable: false },
+ };
+ return { ...known, problem: problemOf(device, facts) };
+}
+
+function problemOf(device: TrackedDevice, facts: PhoneFacts | null): AndroidProblem | undefined {
+ if (device.state === 'unauthorized') return PROBLEMS.unauthorized();
+ if (device.state === 'offline') return PROBLEMS.offline(device);
+ if (device.state === 'no-permissions') return PROBLEMS.noPermissions();
+ if (device.state === 'other') return PROBLEMS.otherMode(device);
+ if (!facts) return PROBLEMS.silent();
+ if (!facts.booted) return PROBLEMS.booting();
+ if (!facts.chrome.installed) return PROBLEMS.chromeMissing();
+ if (!facts.chrome.debuggable) return PROBLEMS.chromeClosed();
+ if (facts.screen && !facts.screen.awake) return PROBLEMS.screenOff();
+ return undefined;
+}
diff --git a/src/daemon/android/service.test.ts b/src/daemon/android/service.test.ts
new file mode 100644
index 0000000..168e0a7
--- /dev/null
+++ b/src/daemon/android/service.test.ts
@@ -0,0 +1,243 @@
+import { readFileSync } from 'node:fs';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import type { AndroidState } from '@/lib/phone/types';
+import type { AdbFound } from './adb';
+import { AdbServerError, type AdbServer } from './adb-server';
+import { INSTALL_CHROME_COMMAND, launchChromeCommand } from './launch';
+import { FACTS_COMMAND } from './phone-facts';
+import { startAndroid, type Android, type AndroidDeps } from './service';
+
+const fixture = (name: string) => readFileSync(new URL(`./fixtures/${name}`, import.meta.url), 'utf8');
+const ADB: AdbFound = { path: '/sdk/platform-tools/adb', version: '37.0.0-14910828' };
+const SOCKET_LINE = '0000000000000000: 00000002 00000000 00010000 0001 01 50526 @chrome_devtools_remote\n';
+
+/** adb's server held in memory: a phone whose state the test sets, and a record of everything asked of it. */
+class MemoryAdb implements AdbServer {
+ running = true;
+ list = fixture('devices-emulator.txt');
+ facts = fixture('facts-chrome-open.txt');
+ readonly shells: string[] = [];
+ trackers = 0;
+ private onList?: (list: string) => void;
+ private onEnd?: (error: AdbServerError) => void;
+
+ private serving<T>(value: T): Promise<T> {
+ return this.running ? Promise.resolve(value) : Promise.reject(new AdbServerError('NO_SERVER', 'connect ECONNREFUSED'));
+ }
+
+ version = () => this.serving(41);
+ devices = () => this.serving(this.list);
+
+ track(onList: (list: string) => void, onEnd: (error: AdbServerError) => void): () => void {
+ this.trackers++;
+ this.onList = onList;
+ this.onEnd = onEnd;
+ queueMicrotask(() => onList(this.list));
+ return () => {
+ this.trackers--;
+ this.onList = this.onEnd = undefined;
+ };
+ }
+
+ async shell(_serial: string, command: string): Promise<string> {
+ this.shells.push(command);
+ if (command === FACTS_COMMAND) return this.facts;
+ if (command.startsWith('am start -n') || command.includes('-n com.android.chrome/')) this.facts = fixture('facts-chrome-open.txt');
+ if (command.startsWith('grep')) return this.facts.includes('@chrome_devtools_remote') ? SOCKET_LINE : '';
+ return '';
+ }
+
+ forward = () => Promise.resolve(50_000);
+ removeForward = () => Promise.resolve();
+
+ plug(list: string): void {
+ this.list = list;
+ this.onList?.(list);
+ }
+
+ die(): void {
+ this.running = false;
+ this.onEnd?.(new AdbServerError('CLOSED', 'adb closed the connection'));
+ }
+}
+
+let adb: MemoryAdb;
+let android: Android;
+let deps: AndroidDeps & { locate: ReturnType<typeof vi.fn>; startServer: ReturnType<typeof vi.fn> };
+
+function start(overrides: Partial<AndroidDeps> = {}): Android {
+ adb = new MemoryAdb();
+ deps = {
+ settings: () => ({ enabled: true }),
+ locate: vi.fn(async () => ADB),
+ startServer: vi.fn(async () => {
+ adb.running = true;
+ return true;
+ }),
+ server: adb,
+ platform: 'darwin',
+ ...overrides,
+ } as typeof deps;
+ android = startAndroid(deps);
+ return android;
+}
+
+afterEach(async () => {
+ await android?.stop();
+ vi.useRealTimers();
+});
+
+const heard = () => {
+ const states: AndroidState[] = [];
+ return { states, listener: (state: AndroidState) => states.push(state) };
+};
+
+const until = async (done: () => boolean) => {
+ for (let tries = 0; !done(); tries++) {
+ if (tries > 200) throw new Error('timed out waiting');
+ await new Promise((resolve) => setTimeout(resolve, 2));
+ }
+};
+
+describe('the Bridge\'s view of the phones', () => {
+ test('asked with nobody watching, it lists the phones once and tracks nothing', async () => {
+ const state = await start().state();
+ expect(state).toMatchObject({ ready: true, adb: { found: true, path: ADB.path } });
+ expect([adb.trackers, adb.shells]).toEqual([0, [FACTS_COMMAND]]);
+ });
+
+ test('a watcher hears the state, then each change the device list brings, and letting go stops the tracking', async () => {
+ start();
+ const { states, listener } = heard();
+ const release = android.watch(listener);
+ await until(() => states.length === 1);
+ expect(states[0].ready).toBe(true);
+ expect(adb.trackers).toBe(1);
+
+ adb.plug(fixture('devices-offline.txt'));
+ await until(() => states.length === 2);
+ expect(states[1].problem?.code).toBe('DEVICE_OFFLINE');
+
+ adb.plug(fixture('devices-none.txt'));
+ await until(() => states.length === 3);
+ expect(states[2].problem?.code).toBe('NO_DEVICE');
+
+ release();
+ expect(adb.trackers).toBe(0);
+ });
+
+ test('every five seconds the phone is asked again, and an unchanged answer is not sent again', async () => {
+ vi.useFakeTimers();
+ start();
+ const { states, listener } = heard();
+ android.watch(listener);
+ await vi.advanceTimersByTimeAsync(10);
+ const asked = adb.shells.length;
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(adb.shells.length).toBe(asked + 1);
+ expect(states).toHaveLength(1);
+
+ adb.facts = fixture('facts-chrome-closed.txt');
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(states.map((state) => state.problem?.code)).toEqual([undefined, 'CHROME_NOT_RUNNING']);
+ });
+
+ test('a second watcher hears what is known at once, without asking the phone again', async () => {
+ start();
+ const first = heard();
+ android.watch(first.listener);
+ await until(() => first.states.length === 1);
+ const asked = adb.shells.length;
+ const second = heard();
+ android.watch(second.listener);
+ await until(() => second.states.length === 1);
+ expect(second.states[0]).toEqual(first.states[0]);
+ expect(adb.shells.length).toBe(asked);
+ });
+
+ test('switched off, it never looks for adb', async () => {
+ const state = await start({ settings: () => ({ enabled: false }) }).state();
+ expect(state).toMatchObject({ enabled: false, problem: { code: 'ANDROID_OFF' } });
+ expect(deps.locate).not.toHaveBeenCalled();
+ expect(adb.shells).toEqual([]);
+ });
+
+ test('with no adb server running, it starts one with the adb it found, once', async () => {
+ start();
+ adb.running = false;
+ expect((await android.state()).ready).toBe(true);
+ expect(deps.startServer.mock.calls).toEqual([[ADB.path]]);
+ });
+
+ test('a server that will not start is reported against adb', async () => {
+ start({ startServer: vi.fn(async () => false) });
+ adb.running = false;
+ expect(await android.state()).toMatchObject({ ready: false, problem: { code: 'ADB_BROKEN' } });
+ });
+
+ test('a missing adb is looked for again each time, and one installed later is used', async () => {
+ start();
+ deps.locate.mockResolvedValueOnce(null);
+ expect((await android.state()).problem?.code).toBe('ADB_MISSING');
+ expect((await android.state()).ready).toBe(true);
+ expect(deps.locate).toHaveBeenCalledTimes(2);
+ await android.state();
+ expect(deps.locate).toHaveBeenCalledTimes(2);
+ });
+
+ test('when adb\'s server goes away while watched, it watches again', async () => {
+ vi.useFakeTimers();
+ start();
+ const { states, listener } = heard();
+ android.watch(listener);
+ await vi.advanceTimersByTimeAsync(10);
+ adb.die();
+ expect(adb.trackers).toBe(1);
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(deps.startServer).toHaveBeenCalledTimes(1);
+ expect(adb.trackers).toBe(2);
+ expect(states.at(-1)?.ready).toBe(true);
+ });
+});
+
+describe('opening Chrome on the phone', () => {
+ test('a closed Chrome is started, and the answer is the state once its socket is open', async () => {
+ start();
+ adb.facts = fixture('facts-chrome-closed.txt');
+ const result = await android.launch('emulator-5554');
+ expect(result).toMatchObject({ ok: true, data: { ready: true } });
+ expect(adb.shells).toContain(launchChromeCommand());
+ });
+
+ test('a URL rides along on a cold start only', async () => {
+ start();
+ adb.facts = fixture('facts-chrome-closed.txt');
+ await android.launch('emulator-5554', 'https://example.com/a');
+ expect(adb.shells).toContain(launchChromeCommand('https://example.com/a'));
+ expect(launchChromeCommand('https://example.com/a')).toMatch(/-a android\.intent\.action\.VIEW -d 'https:\/\/example\.com\/a' -n /);
+ expect(launchChromeCommand("https://example.com/it's")).toContain("'https://example.com/it'\\''s'");
+ expect(launchChromeCommand('javascript:alert(1)')).toBe(launchChromeCommand());
+ });
+
+ test('an open Chrome is left alone', async () => {
+ start();
+ await android.launch('emulator-5554', 'https://example.com');
+ expect(adb.shells.filter((command) => command.startsWith('am start'))).toEqual([]);
+ });
+
+ test('a missing Chrome opens its Play Store page instead', async () => {
+ start();
+ adb.facts = fixture('facts-chrome-open.txt').replace(/(@@browsentic:chrome\n)(package:[^\n]*\n)+/, '$1');
+ await android.launch('emulator-5554');
+ expect(adb.shells).toContain(INSTALL_CHROME_COMMAND);
+ });
+
+ test('a phone that is not connected, or not ready, is refused with its reason', async () => {
+ start();
+ expect(await android.launch('R5CT1234567')).toMatchObject({ ok: false, error: { code: 'NO_DEVICE' } });
+ adb.list = fixture('devices-unauthorized.handwritten.txt');
+ expect(await android.launch('R5CT1234567')).toMatchObject({ ok: false, error: { code: 'DEVICE_UNAUTHORIZED' } });
+ adb.list = fixture('devices-none.txt');
+ expect(await android.launch('R5CT1234567')).toMatchObject({ ok: false, error: { code: 'NO_DEVICE' } });
+ });
+});
diff --git a/src/daemon/android/service.ts b/src/daemon/android/service.ts
index 0aa2979..8b0ebd4 100644
--- a/src/daemon/android/service.ts
+++ b/src/daemon/android/service.ts
@@ -1,5 +1,13 @@
-import { failure, type ActionResult } from '@/lib/actions/protocol';
-import type { AndroidProblem, AndroidState } from '@/lib/phone/types';
+import { failure, success, type ActionResult } from '@/lib/actions/protocol';
+import type { AndroidState } from '@/lib/phone/types';
+import { androidSettings, readAgentConfig, type AndroidSettings } from '../agent/config';
+import { log } from '../log';
+import { locateAdb, startServer, type AdbFound } from './adb';
+import { AdbServerError, adbServer, type AdbServer } from './adb-server';
+import { parseDeviceList, type TrackedDevice } from './devices';
+import { launchChrome, openChromeListing } from './launch';
+import { FACTS_COMMAND, parseFacts, type PhoneFacts } from './phone-facts';
+import { judge } from './readiness';
export interface Android {
state(): Promise<AndroidState>;
@@ -12,19 +20,20 @@ export interface Android {
stop(): Promise<void>;
}
-const SWITCHED_OFF: AndroidProblem = {
- code: 'ANDROID_OFF',
- message: 'Android is switched off for this computer.',
- fix: 'Set "android": { "enabled": true } in ~/.browsentic/config.json',
-};
+export interface AndroidDeps {
+ settings(): AndroidSettings;
+ locate(configured?: string): Promise<AdbFound | null>;
+ startServer(path: string): Promise<boolean>;
+ server: AdbServer;
+ platform: NodeJS.Platform;
+}
+
+const REFRESH_MS = 5_000;
+const FACTS_TIMEOUT_MS = 5_000;
+const BROKEN_RECHECK_MS = 60_000;
+const RETRACK_MS = 2_000;
-export const ANDROID_OFF_STATE: AndroidState = {
- enabled: false,
- ready: false,
- adb: { found: false },
- devices: [],
- problem: SWITCHED_OFF,
-};
+export const ANDROID_OFF_STATE: AndroidState = judge({ enabled: false, platform: process.platform, devices: [] });
export function androidOff(): Android {
return {
@@ -33,7 +42,196 @@ export function androidOff(): Android {
queueMicrotask(() => listener(ANDROID_OFF_STATE));
return () => {};
},
- launch: async () => failure(SWITCHED_OFF.code, SWITCHED_OFF.message),
+ launch: async () => failure('ANDROID_OFF', ANDROID_OFF_STATE.problem?.message ?? 'Android is switched off.'),
stop: async () => {},
};
}
+
+export function liveAndroidDeps(): AndroidDeps {
+ return {
+ settings: () => androidSettings(readAgentConfig()),
+ locate: (configured) => locateAdb({ configured }),
+ startServer,
+ server: adbServer(),
+ platform: process.platform,
+ };
+}
+
+interface Tracker {
+ devices: TrackedDevice[] | null;
+ stop(): void;
+}
+
+export function startAndroid(deps: AndroidDeps = liveAndroidDeps()): Android {
+ const heard = new Map<(state: AndroidState) => void, string>();
+ let latest: AndroidState | null = null;
+ let located: { adb: AdbFound | null; configured?: string; at: number } | undefined;
+ let tracker: Tracker | null = null;
+ let ticker: ReturnType<typeof setInterval> | undefined;
+ let retrack: ReturnType<typeof setTimeout> | undefined;
+ let refreshing: Promise<AndroidState> | null = null;
+ let again = false;
+
+ const watched = () => heard.size > 0;
+
+ async function adbFor(settings: AndroidSettings): Promise<AdbFound | null> {
+ const recheck =
+ !located?.adb || located.configured !== settings.adb || (!!located.adb.broken && Date.now() - located.at > BROKEN_RECHECK_MS);
+ if (recheck) {
+ const adb = await deps.locate(settings.adb);
+ if (adb && adb.path !== located?.adb?.path) log(`android: adb at ${adb.path} (${adb.broken ? `broken: ${adb.broken}` : adb.version})`);
+ located = { adb, configured: settings.adb, at: Date.now() };
+ }
+ return located?.adb ?? null;
+ }
+
+ async function withServer<T>(path: string, call: () => Promise<T>): Promise<T> {
+ try {
+ return await call();
+ } catch (error) {
+ if (!(error instanceof AdbServerError) || error.code !== 'NO_SERVER') throw error;
+ log(`android: no adb server is running; starting one with ${path}`);
+ if (!(await deps.startServer(path))) throw new AdbServerError('NO_SERVER', `"${path} start-server" did not start adb's server`);
+ return call();
+ }
+ }
+
+ async function startTracking(path: string): Promise<void> {
+ await withServer(path, () => deps.server.version());
+ const current: Tracker = { devices: null, stop: () => {} };
+ tracker = current;
+ current.stop = deps.server.track(
+ (list) => {
+ current.devices = parseDeviceList(list);
+ if (tracker === current) void refresh();
+ },
+ (error) => {
+ if (tracker !== current) return;
+ log(`android: lost adb's device list (${error.message}); watching again in ${RETRACK_MS} ms`);
+ tracker = null;
+ retrack = setTimeout(() => void refresh(), RETRACK_MS);
+ },
+ );
+ }
+
+ function stopTracking(): void {
+ clearTimeout(retrack);
+ tracker?.stop();
+ tracker = null;
+ }
+
+ const factsOf = (serial: string): Promise<PhoneFacts | null> =>
+ deps.server
+ .shell(serial, FACTS_COMMAND, FACTS_TIMEOUT_MS)
+ .then(parseFacts)
+ .catch(() => null);
+
+ async function observe(): Promise<AndroidState> {
+ const settings = deps.settings();
+ const seen = { enabled: settings.enabled, platform: deps.platform, devices: [] };
+ if (!settings.enabled) {
+ stopTracking();
+ return judge(seen);
+ }
+ const adb = await adbFor(settings);
+ if (!adb || adb.broken) {
+ stopTracking();
+ return judge({ ...seen, adb });
+ }
+ try {
+ if (watched() && !tracker) await startTracking(adb.path);
+ const listed = tracker?.devices ?? parseDeviceList(await withServer(adb.path, () => deps.server.devices()));
+ const devices = await Promise.all(
+ listed.map(async (device) => ({ device, facts: device.state === 'ready' ? await factsOf(device.serial) : null })),
+ );
+ return judge({ ...seen, adb, devices });
+ } catch (error) {
+ return judge({ ...seen, adb, serverError: error instanceof Error ? error.message : String(error) });
+ }
+ }
+
+ function refresh(): Promise<AndroidState> {
+ if (refreshing) {
+ again = true;
+ return refreshing;
+ }
+ const run = async (): Promise<AndroidState> => {
+ try {
+ let state: AndroidState;
+ do {
+ again = false;
+ state = await observe();
+ publish(state);
+ } while (again);
+ return state;
+ } finally {
+ refreshing = null;
+ }
+ };
+ return (refreshing = run());
+ }
+
+ function publish(state: AndroidState): void {
+ if (watched() && headline(state) !== (latest && headline(latest))) log(`android: ${headline(state)}`);
+ latest = state;
+ for (const listener of heard.keys()) deliver(listener, state);
+ }
+
+ function deliver(listener: (state: AndroidState) => void, state: AndroidState): void {
+ const json = JSON.stringify(state);
+ if (heard.get(listener) === json) return;
+ heard.set(listener, json);
+ listener(state);
+ }
+
+ return {
+ state: () => (latest && tracker ? Promise.resolve(latest) : refresh()),
+
+ watch(listener) {
+ heard.set(listener, '');
+ if (heard.size === 1) {
+ ticker = setInterval(() => void refresh(), REFRESH_MS);
+ ticker.unref();
+ }
+ if (latest && tracker) {
+ const known = latest;
+ queueMicrotask(() => heard.has(listener) && deliver(listener, known));
+ } else void refresh();
+ return () => {
+ if (!heard.delete(listener) || watched()) return;
+ clearInterval(ticker);
+ stopTracking();
+ };
+ },
+
+ async launch(serial, url) {
+ const before = await refresh();
+ const device = before.devices.find((each) => each.serial === serial);
+ if (!device) {
+ const problem = before.devices.length ? undefined : before.problem;
+ return failure(problem?.code ?? 'NO_DEVICE', problem?.message ?? `No phone "${serial}" is connected.`);
+ }
+ if (device.state !== 'ready') {
+ return failure(device.problem?.code ?? 'DEVICE_OFFLINE', device.problem?.message ?? 'The phone is not ready.');
+ }
+ try {
+ if (!device.chrome.installed) await openChromeListing(deps.server, serial);
+ else if (!device.chrome.debuggable) 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)}`);
+ }
+ return success(await refresh());
+ },
+
+ async stop() {
+ heard.clear();
+ clearInterval(ticker);
+ stopTracking();
+ },
+ };
+}
+
+function headline(state: AndroidState): string {
+ const ready = state.devices.find((device) => device.state === 'ready' && device.chrome.debuggable);
+ return state.ready ? `ready (${ready?.serial})${state.problem ? `, ${state.problem.code}` : ''}` : (state.problem?.code ?? 'not ready');
+}
diff --git a/src/daemon/daemon-main.ts b/src/daemon/daemon-main.ts
index b755703..6ed63de 100644
--- a/src/daemon/daemon-main.ts
+++ b/src/daemon/daemon-main.ts
@@ -1,3 +1,4 @@
+import { startAndroid } from './android/service';
import { startDaemon } from './daemon';
import { log } from './log';
import pkg from './package.json';
@@ -5,6 +6,7 @@ import pkg from './package.json';
const daemon = await startDaemon({
version: pkg.version,
idleExit: !process.argv.includes('--no-idle-exit'),
+ android: startAndroid(),
}).catch((error) => {
log('daemon failed to start', error);
process.stderr.write(`browsentic-mcpd: ${error instanceof Error ? error.message : error}\n`);
diff --git a/src/daemon/daemon.ts b/src/daemon/daemon.ts
index 4756105..0915f29 100644
--- a/src/daemon/daemon.ts
+++ b/src/daemon/daemon.ts
@@ -112,6 +112,7 @@ const BINDING_IDLE_MS = 2 * 60 * 1000;
const BROWSER_LABEL_MAX = 40;
const HANDSHAKE_TIMEOUT_MS = 10_000;
const EXTENSION_ORIGIN = /^(chrome|moz|safari-web)-extension:\/\//;
+const CHROMIUM_ORIGIN = /^chrome-extension:\/\//;
const LOOPBACK_HOST = /^(127\.0\.0\.1|\[::1\]|localhost)(:\d+)?$/i;
interface Binding {
@@ -546,7 +547,7 @@ export async function startDaemon({ version, idleExit = true, android = androidO
accepted.send({ t: 'preferencesInfo', id: '', result: success(preferencesNow()) });
accepted.send({ t: 'taskList', id: '', result: success(scheduler.list()) });
scheduler.linkOpened();
- if (accepted.speaks(ANDROID_PROTOCOL)) watchAndroid(accepted);
+ if (accepted.speaks(ANDROID_PROTOCOL) && CHROMIUM_ORIGIN.test(accepted.origin)) watchAndroid(accepted);
if (!known) await adoptExtensionManifest(accepted);
}
diff --git a/src/lib/phone/guide.ts b/src/lib/phone/guide.ts
new file mode 100644
index 0000000..184bc8f
--- /dev/null
+++ b/src/lib/phone/guide.ts
@@ -0,0 +1,36 @@
+export interface GuideStep {
+ title: string;
+ detail: string;
+ /** Shown only for phones on that Android version or later. */
+ platform?: 'android11+';
+}
+
+/** The one copy of the phone setup steps. The CLI and the Windows app read it; the Mac app mirrors it by hand and must match. */
+export const PHONE_GUIDE: readonly GuideStep[] = [
+ {
+ 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.',
+ },
+];