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.
TypeScript agentic-browseragentic-browsingagy-cliaiai-agentai-browser-extensionai-toolsbrave-extensionbrowser-agentbrowser-automationbrowser-extensionbrowser-usebrowserskillchrome-extensionclaude-codecodexfirefox-addonmcp-servernanobrowserweb-automation
fix(android): an open still in flight is cancelled when its browser lets go, closes the phone or the Bridge stops, and a slow DevTools connect is hung up; a phone that did not answer or is still booting is never sent to the Play Store; browsentic android answers at once from a Bridge older than protocol 23; command results reach the browser in Chrome's order among its events; a malformed cdp frame is refused instead of stopping the Bridge
Shahriar2f37ba0e9f2e
diff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex afdcc81..f4ac7ae 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -105,7 +105,9 @@ spelling still works and is undocumented.`android` takes `--json`: the state the apps read, with the setup steps as `guide`. Where theBridge looks for adb, and the keys that name one or stop it using adb at all, are under-[Android](../guide/configuration.md#android) in the configuration guide.+[Android](../guide/configuration.md#android) in the configuration guide. A Bridge still running+from before Android (protocol 22 or older) is not asked: both commands exit at once and say to+run `browsentic restart`.## MCPdiff --git a/src/daemon/android/relay.test.ts b/src/daemon/android/relay.test.tsindex 39daa51..79b5105 100644--- a/src/daemon/android/relay.test.ts+++ b/src/daemon/android/relay.test.ts@@ -2,10 +2,10 @@ import { readFileSync } from 'node:fs';import { createServer, type IncomingMessage, type Server } from 'node:http';import { afterEach, beforeEach, describe, expect, test } from 'vitest';import { WebSocketServer, type WebSocket } from 'ws';-import type { SocketFrame } from '@/lib/actions/protocol';+import type { ActionResult, SocketFrame } from '@/lib/actions/protocol';import type { AndroidState } from '@/lib/phone/types';import { logPath } from '../lockfile';-import { startRelay, type PhoneOwner, type Relay } from './relay';+import { startRelay, type CdpRequest, type PhoneOwner, type Relay } from './relay';const SERIAL = 'emulator-5554';const PAGE = 'A1B2C3D4E5F60718293A4B5C6D7E8F90';@@ -16,6 +16,10 @@ class FakeChrome {readonly origins: (string | undefined)[] = [];readonly commands: { method: string; params?: Record<string, unknown>; sessionId?: string }[] = [];readonly sockets: WebSocket[] = [];+ /** How long the DevTools connection waits before Chrome takes it. */+ upgradeDelayMs = 0;+ /** A command that makes Chrome hang up instead of answering. */+ hangUpOn?: string;private http!: Server;async listen(): Promise<number> {@@ -30,7 +34,7 @@ class FakeChrome {});this.http.on('upgrade', (req: IncomingMessage, socket, head) => {this.origins.push(req.headers.origin);- wss.handleUpgrade(req, socket, head, (ws) => this.serve(ws));+ setTimeout(() => wss.handleUpgrade(req, socket, head, (ws) => this.serve(ws)), this.upgradeDelayMs);});await new Promise<void>((resolve) => this.http.listen(0, '127.0.0.1', resolve));return (this.http.address() as { port: number }).port;@@ -55,7 +59,8 @@ class FakeChrome {const { id, method, params, sessionId } = JSON.parse(String(raw));this.commands.push({ method, params, sessionId });const reply = (body: object) => ws.send(JSON.stringify({ id, ...body }));- if (method === 'Target.setDiscoverTargets') reply({ result: {} });+ if (method === this.hangUpOn) ws.terminate();+ else if (method === 'Target.setDiscoverTargets') reply({ result: {} });else if (method === 'Target.getTargets') {reply({result: {@@ -67,7 +72,10 @@ class FakeChrome {},});} else if (method === 'Runtime.evaluate') reply({ result: { result: { type: 'string', value: 'Example' } } });- else if (method === 'Hang.forever') return;+ else if (method === 'Page.navigate') {+ reply({ result: { frameId: 'F' } });+ ws.send(JSON.stringify({ method: 'Page.frameStartedLoading', params: { frameId: 'F' } }));+ } else if (method === 'Hang.forever') return;else if (method !== 'Page.screencastFrameAck') reply({ error: { code: -32601, message: `'${method}' wasn't found` } });});}@@ -84,6 +92,9 @@ class Owner implements PhoneOwner {events(): string[] {return this.sent.flatMap((frame) => (frame.t === 'cdpEvent' ? [frame.method] : []));}+ answer(id: string): ActionResult | undefined {+ return this.sent.flatMap((frame) => (frame.t === 'cdpResult' && frame.id === id ? [frame.result] : []))[0];+ }}const READY: AndroidState = {@@ -100,13 +111,10 @@ let forwards: { made: string[]; removed: number[] };let sessions: AndroidState['session'][];let relay: Relay;-beforeEach(async () => {- chrome = new FakeChrome();- port = await chrome.listen();- state = READY;- forwards = { made: [], removed: [] };- sessions = [];- relay = startRelay({+const TIMEOUTS = { connect: 1_000, command: 100, slow: 200 };++function startTestRelay(timeouts = TIMEOUTS): Relay {+ return startRelay({server: {forward: async (serial, remote) => {forwards.made.push(`${serial} ${remote}`);@@ -118,8 +126,17 @@ beforeEach(async () => {},state: async () => state,onSession: (session) => sessions.push(session),- timeouts: { connect: 1_000, command: 100, slow: 200 },+ timeouts,});+}++beforeEach(async () => {+ chrome = new FakeChrome();+ port = await chrome.listen();+ state = READY;+ forwards = { made: [], removed: [] };+ sessions = [];+ relay = startTestRelay();});afterEach(async () => {@@ -127,6 +144,12 @@ afterEach(async () => {await chrome.close();});+/** Sends a command the way the Bridge does, and reads the answer the relay gave the owner. */+async function ask(owner: Owner, request: CdpRequest): Promise<ActionResult | undefined> {+ await relay.command(owner, request);+ return owner.answer(request.id);+}+const until = async (done: () => boolean) => {for (let tries = 0; !done(); tries++) {if (tries > 200) throw new Error('timed out waiting');@@ -172,7 +195,7 @@ describe('opening a phone', () => {await relay.open(new Owner('chrome-1'), SERIAL);const other = new Owner('edge-1');expect(await relay.open(other, SERIAL)).toMatchObject({ ok: false, error: { code: 'NOT_OWNER' } });- expect(await relay.command(other, { t: 'cdp', id: 'x', serial: SERIAL, method: 'Runtime.evaluate' })).toMatchObject({+ expect(await ask(other, { t: 'cdp', id: 'x', serial: SERIAL, method: 'Runtime.evaluate' })).toMatchObject({ok: false,error: { code: 'NOT_OWNER' },});@@ -185,6 +208,67 @@ describe('opening a phone', () => {chrome = new FakeChrome();await chrome.listen();});++ test('a Chrome too slow to take the connection is hung up on, not left to connect later', async () => {+ await relay.stop();+ relay = startTestRelay({ ...TIMEOUTS, connect: 100 });+ chrome.upgradeDelayMs = 300;+ expect(await relay.open(new Owner('chrome-1'), SERIAL)).toMatchObject({ ok: false, error: { code: 'PHONE_GONE' } });+ await new Promise((resolve) => setTimeout(resolve, 400));+ expect(chrome.sockets.filter((socket) => socket.readyState === socket.OPEN)).toEqual([]);+ });++ test('a Chrome that goes away while the session opens is no session at all', async () => {+ chrome.hangUpOn = 'Target.setDiscoverTargets';+ expect(await relay.open(new Owner('chrome-1'), SERIAL)).toMatchObject({ ok: false, error: { code: 'PHONE_GONE' } });+ expect(forwards.removed).toEqual([port]);+ expect(sessions.at(-1)).toBeUndefined();+ });+});++describe('letting go while a phone is opening', () => {+ beforeEach(() => {+ chrome.upgradeDelayMs = 100;+ });++ /** Wrapped, so awaiting this waits for the forward and not for the open itself. */+ const opening = async (owner: Owner) => {+ const attempt = relay.open(owner, SERIAL);+ await until(() => forwards.made.length === 1);+ return { attempt };+ };++ test('a browser that goes away leaves nothing behind, and the next one can open the phone', async () => {+ const leaving = new Owner('chrome-1');+ const { attempt } = await opening(leaving);+ await relay.release(leaving);+ expect(await attempt).toMatchObject({ ok: false, error: { code: 'PHONE_GONE' } });+ expect([forwards.removed, sessions]).toEqual([[port], []]);+ expect(await relay.open(new Owner('chrome-2'), SERIAL)).toMatchObject({ ok: true });+ });++ test('switching Android off ends it there', async () => {+ const owner = new Owner('chrome-1');+ const { attempt } = await opening(owner);+ await relay.close(owner, SERIAL);+ expect(await attempt).toMatchObject({ ok: false, error: { code: 'PHONE_GONE' } });+ expect(forwards.removed).toEqual([port]);+ });++ test('another browser switching Android off does not end it', async () => {+ const owner = new Owner('chrome-1');+ const { attempt } = await opening(owner);+ await relay.close(new Owner('edge-1'), SERIAL);+ expect(await attempt).toMatchObject({ ok: true });+ });++ test('the Bridge stopping waits for it, removes its forward, and opens nothing after', async () => {+ const { attempt } = await opening(new Owner('chrome-1'));+ await relay.stop();+ expect(forwards.removed).toEqual([port]);+ expect(await attempt).toMatchObject({ ok: false, error: { code: 'PHONE_GONE' } });+ expect(await relay.open(new Owner('chrome-1'), SERIAL)).toMatchObject({ ok: false, error: { code: 'PHONE_GONE' } });+ });});describe('commands and events', () => {@@ -195,36 +279,49 @@ describe('commands and events', () => {});test('a command goes to the phone with its session id, and its answer comes back', async () => {- const result = await relay.command(owner, { t: 'cdp', id: 'f1', serial: SERIAL, method: 'Runtime.evaluate', params: { expression: 'document.title' }, sessionId: 'S1' });+ const result = await ask(owner, { t: 'cdp', id: 'f1', serial: SERIAL, method: 'Runtime.evaluate', params: { expression: 'document.title' }, sessionId: 'S1' });expect(result).toEqual({ ok: true, data: { result: { type: 'string', value: 'Example' } } });expect(chrome.commands.at(-1)).toEqual({ method: 'Runtime.evaluate', params: { expression: 'document.title' }, sessionId: 'S1' });});test('a command can ask to wait longer than the default, for a page-side wait', async () => {- const asked = relay.command(owner, { t: 'cdp', id: 'f7', serial: SERIAL, method: 'Hang.forever', timeoutMs: 400 });+ const asked = ask(owner, { t: 'cdp', id: 'f7', serial: SERIAL, method: 'Hang.forever', timeoutMs: 400 });await new Promise((resolve) => setTimeout(resolve, 200));expect(await Promise.race([asked, Promise.resolve('still waiting')])).toBe('still waiting');expect(await asked).toMatchObject({ ok: false, error: { code: 'TIMEOUT' } });});test('Chrome\'s refusal is CDP_ERROR in its own words, and silence is TIMEOUT', async () => {- expect(await relay.command(owner, { t: 'cdp', id: 'f2', serial: SERIAL, method: 'Nope.nope' })).toEqual({+ expect(await ask(owner, { t: 'cdp', id: 'f2', serial: SERIAL, method: 'Nope.nope' })).toEqual({ok: false,error: { code: 'CDP_ERROR', message: "'Nope.nope' wasn't found" },});- expect(await relay.command(owner, { t: 'cdp', id: 'f3', serial: SERIAL, method: 'Hang.forever' })).toMatchObject({+ expect(await ask(owner, { t: 'cdp', id: 'f3', serial: SERIAL, method: 'Hang.forever' })).toMatchObject({ok: false,error: { code: 'TIMEOUT' },});});test('a command for a phone with no session is PHONE_GONE', async () => {- expect(await relay.command(owner, { t: 'cdp', id: 'f4', serial: 'R5CT1234567', method: 'Runtime.evaluate' })).toMatchObject({+ expect(await ask(owner, { t: 'cdp', id: 'f4', serial: 'R5CT1234567', method: 'Runtime.evaluate' })).toMatchObject({ok: false,error: { code: 'PHONE_GONE' },});});+ test('a command with no method is refused before it reaches the phone', async () => {+ const sent = chrome.commands.length;+ expect(await ask(owner, { t: 'cdp', id: 'f8', serial: SERIAL } as unknown as CdpRequest)).toMatchObject({ ok: false, error: { code: 'INVALID_INPUT' } });+ expect(chrome.commands).toHaveLength(sent);+ });++ test('an answer reaches the owner in the order Chrome sent it among the events', async () => {+ owner.sent.length = 0;+ await relay.command(owner, { t: 'cdp', id: 'f9', serial: SERIAL, method: 'Page.navigate', params: { url: 'https://example.com/b' } });+ await until(() => owner.events().length === 1);+ expect(owner.sent.map((frame) => (frame.t === 'cdpEvent' ? frame.method : frame.t))).toEqual(['cdpResult', 'Page.frameStartedLoading']);+ });+test('every event reaches the owner, with the session it came from', async () => {chrome.emit('Target.targetCreated', { targetInfo: { targetId: PAGE } });chrome.emit('Page.screencastFrame', { data: 'jpeg', sessionId: 1, metadata: {} }, 'S1');@@ -261,7 +358,7 @@ describe('when a session ends', () => {});test('Chrome going away fails the command in flight, tells the owner why, and removes the forward', async () => {- const pending = relay.command(owner, { t: 'cdp', id: 'g1', serial: SERIAL, method: 'Hang.forever' });+ const pending = ask(owner, { t: 'cdp', id: 'g1', serial: SERIAL, method: 'Hang.forever' });await until(() => chrome.commands.some(({ method }) => method === 'Hang.forever'));chrome.hangUp();expect(await pending).toMatchObject({ ok: false, error: { code: 'PHONE_GONE' } });diff --git a/src/daemon/android/relay.ts b/src/daemon/android/relay.tsindex 87bd4cc..885f9af 100644--- a/src/daemon/android/relay.ts+++ b/src/daemon/android/relay.ts@@ -16,7 +16,7 @@ type CdpResult = ActionResult<Record<string, unknown>>;export interface Relay {open(owner: PhoneOwner, serial: string): Promise<ActionResult<PhoneOpened>>;- command(owner: PhoneOwner, request: CdpRequest): Promise<CdpResult>;+ command(owner: PhoneOwner, request: CdpRequest): Promise<void>;close(owner: PhoneOwner, serial: string): Promise<void>;release(owner: PhoneOwner): Promise<void>;stop(): Promise<void>;@@ -41,7 +41,7 @@ const MAX_MESSAGE_BYTES = 256 * 1024 * 1024;const REAL_TARGET = /^[0-9A-F]{32}$/i;interface Call {- resolve(result: CdpResult): void;+ settle(result: CdpResult): void;timer: ReturnType<typeof setTimeout>;}@@ -56,31 +56,46 @@ interface Session {nextId: number;}+interface Opening {+ owner: PhoneOwner;+ abandoned: boolean;+ result?: Promise<ActionResult<PhoneOpened>>;+}+export function startRelay({ server, state, onSession, host = '127.0.0.1', timeouts = TIMEOUTS }: RelayDeps): Relay {const sessions = new Map<string, Session>();- const opening = new Map<string, Promise<unknown>>();+ const opening = new Map<string, Opening>();+ let stopping = false;const announce = () => {const [current] = sessions.values();onSession(current && { serial: current.serial, since: current.since });};- function call(session: Session, method: string, params?: Record<string, unknown>, sessionId?: string, asked?: number): Promise<CdpResult> {+ const abandon = (matches: (serial: string, attempt: Opening) => boolean) => {+ for (const [serial, attempt] of opening) if (matches(serial, attempt)) attempt.abandoned = true;+ };++ const waitFor = (method: string, asked?: unknown): number =>+ typeof asked === 'number' && asked > 0 ? Math.min(asked, LONGEST_COMMAND_MS) : SLOW_COMMANDS.has(method) ? timeouts.slow : timeouts.command;++ /** `settle` runs as the answer is read, so an owner hears it in the order Chrome sent it among the events. */+ function send(session: Session, request: Pick<CdpRequest, 'method' | 'params' | 'sessionId'>, timeoutMs: number, settle: (result: CdpResult) => void): void {if (sessions.get(session.serial) !== session || session.socket.readyState !== WebSocket.OPEN) {- return Promise.resolve(failure('PHONE_GONE', 'The phone disconnected.'));+ return settle(failure('PHONE_GONE', 'The phone disconnected.'));}const id = session.nextId++;- const timeoutMs = asked ? Math.min(asked, LONGEST_COMMAND_MS) : SLOW_COMMANDS.has(method) ? timeouts.slow : timeouts.command;- return new Promise((resolve) => {- const timer = setTimeout(() => {- session.calls.delete(id);- resolve(failure('TIMEOUT', `${method} got no answer from the phone within ${timeoutMs / 1000} s`));- }, timeoutMs);- session.calls.set(id, { resolve, timer });- session.socket.send(JSON.stringify({ id, method, params, sessionId }));- });+ const timer = setTimeout(() => {+ session.calls.delete(id);+ settle(failure('TIMEOUT', `${request.method} got no answer from the phone within ${timeoutMs / 1000} s`));+ }, timeoutMs);+ session.calls.set(id, { settle, timer });+ session.socket.send(JSON.stringify({ id, method: request.method, params: request.params, sessionId: request.sessionId }));}+ const call = (session: Session, method: string, params?: Record<string, unknown>): Promise<CdpResult> =>+ new Promise((resolve) => send(session, { method, params }, waitFor(method), resolve));+function receive(session: Session, raw: WebSocket.RawData): void {let message: { id?: number; result?: Record<string, unknown>; error?: { message?: string }; method?: string; params?: Record<string, unknown>; sessionId?: string };try {@@ -93,7 +108,7 @@ export function startRelay({ server, state, onSession, host = '127.0.0.1', timeoif (!waiting) return;session.calls.delete(message.id);clearTimeout(waiting.timer);- return waiting.resolve(message.error ? failure('CDP_ERROR', message.error.message ?? 'Chrome refused the command') : success(message.result ?? {}));+ return waiting.settle(message.error ? failure('CDP_ERROR', message.error.message ?? 'Chrome refused the command') : success(message.result ?? {}));}if (!message.method || !session.owner.isOpen) return;if (message.method === 'Page.screencastFrame' && session.owner.bufferedAmount > FRAME_BACKLOG_BYTES) {@@ -108,12 +123,10 @@ export function startRelay({ server, state, onSession, host = '127.0.0.1', timeosessions.delete(session.serial);for (const waiting of session.calls.values()) {clearTimeout(waiting.timer);- waiting.resolve(failure('PHONE_GONE', 'The phone disconnected while this command was on its way.'));+ waiting.settle(failure('PHONE_GONE', 'The phone disconnected while this command was on its way.'));}session.calls.clear();- session.socket.removeAllListeners();- session.socket.on('error', () => {});- session.socket.terminate();+ hangUp(session.socket);await server.removeForward(session.serial, session.port).catch(() => {});if (tellOwner && session.owner.isOpen) session.owner.send({ t: 'phoneClosed', serial: session.serial, reason });log(`phone ${session.serial} session ended: ${reason}`);@@ -133,7 +146,10 @@ export function startRelay({ server, state, onSession, host = '127.0.0.1', timeoconst path = version.webSocketDebuggerUrl ? new URL(version.webSocketDebuggerUrl).pathname : '/devtools/browser';const socket = new WebSocket(`ws://${host}:${port}${path}`, { perMessageDeflate: false, maxPayload: MAX_MESSAGE_BYTES });await new Promise<void>((resolve, reject) => {- const timer = setTimeout(() => reject(new Error(`Chrome on ${serial} did not accept the DevTools connection`)), timeouts.connect);+ const timer = setTimeout(() => {+ hangUp(socket);+ reject(new Error(`Chrome on ${serial} did not accept the DevTools connection`));+ }, timeouts.connect);socket.once('open', () => {clearTimeout(timer);resolve();@@ -153,25 +169,26 @@ export function startRelay({ server, state, onSession, host = '127.0.0.1', timeo.filter((info) => info.type === 'page' && REAL_TARGET.test(info.targetId)).map(({ targetId, url, title }) => ({ targetId, url, title }));const device = (await state()).devices.find((each) => each.serial === session.serial);- if (!device) return failure('PHONE_GONE', 'The phone disconnected while the session was opening.');+ if (!device || sessions.get(session.serial) !== session) return failure('PHONE_GONE', 'The phone disconnected while the session was opening.');return success({ device, targets, browserVersion: session.browserVersion });}async function open(owner: PhoneOwner, serial: string): Promise<ActionResult<PhoneOpened>> {- while (opening.has(serial)) await opening.get(serial);+ while (opening.has(serial)) await opening.get(serial)?.result;+ if (stopping) return failure('PHONE_GONE', 'Browsentic Bridge is stopping.');const held = sessions.get(serial);if (held && held.owner !== owner) return failure('NOT_OWNER', 'Another browser is driving this phone.');if (held) return opened(held);- const attempt = start(owner, serial);+ const attempt: Opening = { owner, abandoned: false };opening.set(serial, attempt);try {- return await attempt;+ return await (attempt.result = start(attempt, serial));} finally {opening.delete(serial);}}- async function start(owner: PhoneOwner, serial: string): Promise<ActionResult<PhoneOpened>> {+ async function start(attempt: Opening, serial: string): Promise<ActionResult<PhoneOpened>> {const device = (await state()).devices.find((each) => each.serial === serial);if (!device) return failure('NO_DEVICE', `No phone "${serial}" is connected.`);if (device.state !== 'ready') return failure(device.problem?.code ?? 'DEVICE_OFFLINE', device.problem?.message ?? 'The phone is not ready.');@@ -181,7 +198,11 @@ export function startRelay({ server, state, onSession, host = '127.0.0.1', timeotry {port = await server.forward(serial, DEVTOOLS_SOCKET);const { socket, browserVersion } = await connect(serial, port);- const session: Session = { serial, owner, port, socket, since: new Date().toISOString(), browserVersion, calls: new Map(), nextId: 1 };+ if (attempt.abandoned || !attempt.owner.isOpen) {+ hangUp(socket);+ throw new Error('the browser that asked for it let go first');+ }+ const session: Session = { serial, owner: attempt.owner, port, socket, since: new Date().toISOString(), browserVersion, calls: new Map(), nextId: 1 };sessions.set(serial, session);socket.on('message', (raw) => receive(session, raw));socket.on('close', () => void lost(session));@@ -201,31 +222,50 @@ export function startRelay({ server, state, onSession, host = '127.0.0.1', timeoreturn {open,- async command(owner, { serial, method, params, sessionId, timeoutMs }) {+ async command(owner, request) {+ const answer = (result: CdpResult) => owner.send({ t: 'cdpResult', id: request.id, result });+ const { serial, method, params, timeoutMs } = request;+ if (typeof method !== 'string' || !method) return answer(failure('INVALID_INPUT', 'A DevTools command needs a method.'));const session = sessions.get(serial);- if (!session) return failure('PHONE_GONE', 'No phone session is open. Switch Android on again.');- if (session.owner !== owner) return failure('NOT_OWNER', 'Another browser is driving this phone.');+ if (!session) return answer(failure('PHONE_GONE', 'No phone session is open. Switch Android on again.'));+ if (session.owner !== owner) return answer(failure('NOT_OWNER', 'Another browser is driving this phone.'));const started = Date.now();- const result = await call(session, method, params, sessionId, timeoutMs);- if (!isChatter(method, params)) log(`phone ${serial} ${method} ${result.ok ? 'ok' : result.error.code} in ${Date.now() - started} ms`);- return result;+ await new Promise<void>((done) =>+ send(session, request, waitFor(method, timeoutMs), (result) => {+ answer(result);+ if (!isChatter(method, params)) log(`phone ${serial} ${method} ${result.ok ? 'ok' : result.error.code} in ${Date.now() - started} ms`);+ done();+ }),+ );},async close(owner, serial) {+ abandon((opened, attempt) => opened === serial && attempt.owner === owner);const session = sessions.get(serial);if (session?.owner === owner) await teardown(session, 'closed', false);},async release(owner) {+ abandon((_, attempt) => attempt.owner === owner);await Promise.all([...sessions.values()].filter((session) => session.owner === owner).map((session) => teardown(session, 'closed', false)));},async stop() {+ stopping = true;+ abandon(() => true);await Promise.all([...sessions.values()].map((session) => teardown(session, 'bridge-stopping', true)));+ await Promise.allSettled([...opening.values()].map((attempt) => attempt.result));},};}+/** A socket still connecting reports its own end as an error, which nothing else is left listening for. */+function hangUp(socket: WebSocket): void {+ socket.removeAllListeners();+ socket.on('error', () => {});+ socket.terminate();+}+/** Screencast acks and finger or pointer moves arrive many times a second; one line each would bury everything else in daemon.log. */function isChatter(method: string, params?: Record<string, unknown>): boolean {return method === 'Page.screencastFrameAck' || (method.startsWith('Input.dispatch') && /move/i.test(String(params?.type ?? '')));diff --git a/src/daemon/android/service.test.ts b/src/daemon/android/service.test.tsindex be42167..45c2e96 100644--- a/src/daemon/android/service.test.ts+++ b/src/daemon/android/service.test.ts@@ -15,7 +15,8 @@ const SOCKET_LINE = '0000000000000000: 00000002 00000000 00010000 0001 01 50526class MemoryAdb implements AdbServer {running = true;list = fixture('devices-emulator.txt');- facts = fixture('facts-chrome-open.txt');+ /** Null is a phone that does not answer in time. */+ facts: string | null = fixture('facts-chrome-open.txt');readonly shells: string[] = [];trackers = 0;private onList?: (list: string) => void;@@ -41,9 +42,12 @@ class MemoryAdb implements AdbServer {async shell(_serial: string, command: string): Promise<string> {this.shells.push(command);- if (command === FACTS_COMMAND) return this.facts;+ if (command === FACTS_COMMAND) {+ if (this.facts === null) throw new AdbServerError('TIMEOUT', 'adb did not answer within 5000 ms');+ 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 : '';+ if (command.startsWith('grep')) return this.facts?.includes('@chrome_devtools_remote') ? SOCKET_LINE : '';return '';}@@ -185,6 +189,21 @@ describe('the Bridge\'s view of the phones', () => {expect(deps.locate).toHaveBeenCalledTimes(2);});+ test('letting go while the watch is still starting leaves nothing tracking, so a later look reads the phone again', async () => {+ start();+ let answer: (() => void) | undefined;+ adb.version = () => new Promise((resolve) => (answer = () => resolve(41)));+ const release = android.watch(() => {});+ await until(() => answer !== undefined);+ release();+ answer?.();+ await android.state();+ expect([adb.trackers, android.peek()]).toEqual([0, null]);++ adb.facts = fixture('facts-chrome-closed.txt');+ expect((await android.state()).problem?.code).toBe('CHROME_NOT_RUNNING');+ });+test('when adb\'s server goes away while watched, it watches again', async () => {vi.useFakeTimers();start();@@ -247,6 +266,15 @@ describe('opening Chrome on the phone', () => {expect(adb.shells).toContain(INSTALL_CHROME_COMMAND);});+ test('a phone that does not answer, or is still starting, is refused rather than sent to the Play Store', async () => {+ start();+ adb.facts = null;+ expect(await android.launch('emulator-5554')).toMatchObject({ ok: false, error: { code: 'DEVICE_OFFLINE' } });+ adb.facts = fixture('facts-chrome-open.txt').replace('@@browsentic:booted\n1\n', '@@browsentic:booted\n').replace(/(@@browsentic:chrome\n)(package:[^\n]*\n)+/, '$1');+ expect(await android.launch('emulator-5554')).toMatchObject({ ok: false, error: { code: 'DEVICE_BOOTING' } });+ expect(adb.shells.filter((command) => command.startsWith('am start'))).toEqual([]);+ });+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' } });diff --git a/src/daemon/android/service.ts b/src/daemon/android/service.tsindex ab93c38..d2f7dd4 100644--- a/src/daemon/android/service.ts+++ b/src/daemon/android/service.ts@@ -1,5 +1,5 @@import { failure, success, type ActionResult } from '@/lib/actions/protocol';-import type { AndroidState, PhoneOpened } from '@/lib/phone/types';+import type { AndroidProblemCode, AndroidState, PhoneOpened } from '@/lib/phone/types';import { androidSettings, readAgentConfig, type AndroidSettings } from '../agent/config';import { log } from '../log';import { locateAdb, startServer, type AdbFound } from './adb';@@ -22,7 +22,8 @@ export interface Android {launch(serial: string, url?: string): Promise<ActionResult<AndroidState>>;/** A session with Chrome on the phone, owned by the browser that opened it; only that browser's commands reach it. */open(owner: PhoneOwner, serial: string): Promise<ActionResult<PhoneOpened>>;- command(owner: PhoneOwner, request: CdpRequest): Promise<ActionResult<Record<string, unknown>>>;+ /** Answers the owner with a `cdpResult` itself, in the order Chrome sent it among the events. */+ command(owner: PhoneOwner, request: CdpRequest): Promise<void>;close(owner: PhoneOwner, serial: string): Promise<void>;/** The owner went away: its sessions end without telling it. */release(owner: PhoneOwner): Promise<void>;@@ -41,6 +42,8 @@ const REFRESH_MS = 5_000;const FACTS_TIMEOUT_MS = 5_000;const BROKEN_RECHECK_MS = 60_000;const RETRACK_MS = 2_000;+/** A phone that did not answer, or is still starting, reads as one without Chrome, so `launch` acts only past these problems. */+const LAUNCHABLE: ReadonlySet<AndroidProblemCode> = new Set(['CHROME_MISSING', 'CHROME_NOT_RUNNING', 'SCREEN_OFF']);export const ANDROID_OFF_STATE: AndroidState = judge({ enabled: false, platform: process.platform, devices: [] });@@ -54,7 +57,7 @@ export function androidOff(): Android {},launch: async () => switchedOff(),open: async () => switchedOff(),- command: async () => switchedOff(),+ command: async (owner, request) => owner.send({ t: 'cdpResult', id: request.id, result: switchedOff() }),close: async () => {},release: async () => {},stop: async () => {},@@ -125,6 +128,7 @@ export function startAndroid(deps: AndroidDeps = liveAndroidDeps()): Android {async function startTracking(path: string): Promise<void> {await withServer(path, () => deps.server.version());+ if (!watched()) return;const current: Tracker = { devices: null, stop: () => {} };tracker = current;current.stop = deps.server.track(@@ -239,7 +243,7 @@ export function startAndroid(deps: AndroidDeps = liveAndroidDeps()): Android {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') {+ if (device.state !== 'ready' || (device.problem && !LAUNCHABLE.has(device.problem.code))) {return failure(device.problem?.code ?? 'DEVICE_OFFLINE', device.problem?.message ?? 'The phone is not ready.');}try {diff --git a/src/daemon/daemon.ts b/src/daemon/daemon.tsindex f8ed30d..cb758c1 100644--- a/src/daemon/daemon.ts+++ b/src/daemon/daemon.ts@@ -577,14 +577,18 @@ export async function startDaemon({ version, idleExit = true, android = androidOif (!source.speaks(ANDROID_PROTOCOL)) {return answer(failure('UNSUPPORTED', `Android needs an extension that speaks protocol ${ANDROID_PROTOCOL}.`));}+ const broke = (error: unknown) => {+ log(`phone ${request.t} failed in the Bridge`, error);+ answer(failure('BRIDGE_ERROR', error instanceof Error ? error.message : String(error)));+ };if (request.t === 'phoneLaunch') {- void android.launch(request.serial, request.url).then((result) => source.send({ t: 'androidInfo', id: request.id, result }));+ void android.launch(request.serial, request.url).then((result) => source.send({ t: 'androidInfo', id: request.id, result }), broke);} else if (request.t === 'phoneOpen') {- void android.open(source, request.serial).then((result) => source.send({ t: 'phoneOpened', id: request.id, result }));+ void android.open(source, request.serial).then((result) => source.send({ t: 'phoneOpened', id: request.id, result }), broke);} else if (request.t === 'cdp') {- void android.command(source, request).then((result) => source.send({ t: 'cdpResult', id: request.id, result }));+ void android.command(source, request).catch(broke);} else {- void android.close(source, request.serial);+ void android.close(source, request.serial).catch(broke);}}diff --git a/src/daemon/remote-bridge.test.ts b/src/daemon/remote-bridge.test.tsindex 129c728..51c46c7 100644--- a/src/daemon/remote-bridge.test.ts+++ b/src/daemon/remote-bridge.test.ts@@ -101,6 +101,22 @@ describe('asking the daemon', () => {]);});+ test('Android, from a Bridge that speaks it, and refused at once by one too old to answer', async () => {+ const status = (protocolVersion: number) => ({ connected: true, daemonVersion: '0.8.1', protocolVersion, port, manifestInSync: true, connectedBrowsers: 1, pairedBrowsers: 1, pairingPending: false });+ const state = { enabled: true, ready: false, adb: { found: false }, devices: [] };+ let speaks = 23;+ answer = (request) => {+ const { id } = request;+ if (request.op === 'status') return { id, op: 'status', status: status(speaks) };+ if (request.op === 'android') return { id, op: 'android', result: { ok: true, data: state } };+ return null;+ };+ expect(await bridge.android({ peek: true })).toEqual({ ok: true, data: state });+ speaks = 22;+ expect(await bridge.android({ peek: true })).toMatchObject({ ok: false, error: { code: 'UNSUPPORTED' } });+ expect(received.map(({ op }) => op)).toEqual(['status', 'android', 'status']);+ });+test('an action its caller stops waiting for is cancelled with the daemon, under the same id', async () => {const abandoned = new AbortController();const pending = bridge.invoke('page.submitForm', {}, abandoned.signal);diff --git a/src/daemon/remote-bridge.ts b/src/daemon/remote-bridge.tsindex 931dcb8..07305e5 100644--- a/src/daemon/remote-bridge.ts+++ b/src/daemon/remote-bridge.ts@@ -4,7 +4,7 @@ import { awaitMonitor } from '@/lib/actions/page/await-monitor';import { PICK_DEFAULT_TIMEOUT_MS, pickElement } from '@/lib/actions/page/pick-element';import { SOLVE_CAPTCHA_TIMEOUT_MS, solveCaptcha } from '@/lib/actions/page/solve-captcha';import { startMonitor } from '@/lib/actions/page/start-monitor';-import { failure, type ActionResult } from '@/lib/actions/protocol';+import { ANDROID_PROTOCOL, failure, type ActionResult } from '@/lib/actions/protocol';import type { AgentKind, AgentState } from '@/lib/agents/catalog';import type { AndroidState } from '@/lib/phone/types';import { AWAIT_DEFAULT_TIMEOUT_MS } from '@/lib/monitor/events';@@ -73,7 +73,15 @@ export class RemoteBridge implements Bridge {throw new Error('The Browsentic daemon did not answer about its agent');}+ /** A Bridge older than Android leaves the op unanswered, so it is asked its protocol first rather than waited on for a minute. */async android(request?: { launch?: string; url?: string; watch?: boolean; peek?: boolean }): Promise<ActionResult<AndroidState>> {+ const { protocolVersion } = await this.status();+ if (protocolVersion < ANDROID_PROTOCOL) {+ return failure(+ 'UNSUPPORTED',+ `The Browsentic Bridge that is running speaks protocol ${protocolVersion}, and Android needs ${ANDROID_PROTOCOL}. Run "browsentic restart" to start the one installed.`,+ );+ }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.tsindex fd82300..17650d8 100644--- a/src/daemon/test/fake-android.ts+++ b/src/daemon/test/fake-android.ts@@ -33,6 +33,8 @@ export class FakeAndroid implements Android {/** Every phone request that reached the Bridge's Android half, by the browser that sent it. */readonly asked: { owner: string; t: string; serial: string; method?: string }[] = [];readonly released: string[] = [];+ /** Set to make every phone request fail inside the Bridge, as a bug there would. */+ broken = false;private readonly listeners = new Set<(state: AndroidState) => void>();get watchers(): number {@@ -54,22 +56,26 @@ export class FakeAndroid implements Android {}async launch(serial: string): Promise<ActionResult<AndroidState>> {+ this.breakIfAsked();this.launched.push(serial);return success(this.current);}async open(owner: PhoneOwner, serial: string): Promise<ActionResult<PhoneOpened>> {+ this.breakIfAsked();this.asked.push({ owner: owner.id, t: 'phoneOpen', serial });const device = this.current.devices.find((each) => each.serial === serial);return device ? success({ device, targets: [], browserVersion: 'Chrome/150.0.7871.186' }) : failure('NO_DEVICE', 'No such phone.');}- async command(owner: PhoneOwner, request: CdpRequest): Promise<ActionResult<Record<string, unknown>>> {+ async command(owner: PhoneOwner, request: CdpRequest): Promise<void> {+ this.breakIfAsked();this.asked.push({ owner: owner.id, t: 'cdp', serial: request.serial, method: request.method });- return success({ echoed: request.method });+ owner.send({ t: 'cdpResult', id: request.id, result: success({ echoed: request.method }) });}async close(owner: PhoneOwner, serial: string): Promise<void> {+ this.breakIfAsked();this.asked.push({ owner: owner.id, t: 'phoneClose', serial });}@@ -81,6 +87,10 @@ export class FakeAndroid implements Android {this.listeners.clear();}+ private breakIfAsked(): void {+ if (this.broken) throw new Error('the Android half broke');+ }+change(next: AndroidState): void {this.current = next;for (const listener of this.listeners) listener(next);diff --git a/src/daemon/test/protocol-window.test.ts b/src/daemon/test/protocol-window.test.tsindex 8e57a24..f2b85ce 100644--- a/src/daemon/test/protocol-window.test.ts+++ b/src/daemon/test/protocol-window.test.ts@@ -36,6 +36,7 @@ afterEach(async () => {android.launched.length = 0;android.asked.length = 0;android.released.length = 0;+ android.broken = false;});async function control(): Promise<RemoteBridge> {@@ -163,6 +164,18 @@ describe('Android across the protocol window', () => {expect(android.released).toEqual([store.installId]);});+ test('a phone request that fails inside the Bridge is still answered, and the Bridge stays up', async () => {+ android.current = READY_PHONE;+ const browser = await pair({ ...store, protocolVersion: ANDROID_PROTOCOL });+ android.broken = true;+ const broke = { ok: false, error: { code: 'BRIDGE_ERROR' } };+ expect(await browser.ask({ t: 'phoneOpen', id: 'open-3', serial: 'emulator-5554' })).toMatchObject({ t: 'phoneOpened', result: broke });+ expect(await browser.ask({ t: 'cdp', id: 'cdp-3', serial: 'emulator-5554', method: 'Runtime.evaluate' })).toMatchObject({ t: 'cdpResult', result: broke });+ expect(await browser.ask({ t: 'phoneLaunch', id: 'launch-3', serial: 'emulator-5554' })).toMatchObject({ t: 'androidInfo', result: broke });+ browser.tell({ t: 'phoneClose', id: 'close-3', serial: 'emulator-5554' });+ expect((await (await control()).status()).connected).toBe(true);+ });+test('a Firefox extension is not watched for phones, since its toggle is hidden', async () => {await pair({ origin: 'moz-extension://8f0e1d2c-0000-4000-8000-000000000000', installId: 'install-firefox-01', browser: 'Firefox', protocolVersion: ANDROID_PROTOCOL });expect(android.watchers).toBe(0);