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): a conversation on the phone tab drives the phone: its tool calls take a phone branch before any desktop check, blocked sites are checked against the phone's own address before and after, tabs mean phone tabs, and the run is told which phone it is on

Shahriar5f2065d9c920
diff --git a/src/lib/bridge/invoke.ts b/src/lib/bridge/invoke.ts
index b469758..e18085f 100644
--- a/src/lib/bridge/invoke.ts
+++ b/src/lib/bridge/invoke.ts
@@ -63,6 +63,7 @@ import { screenshotTab } from '@/lib/bridge/screenshot';
import { dragInTab, trustedClickInTab } from '@/lib/bridge/trusted-input';
import { closeOpenTab, openNewTab, switchToTab, watchForLoad, type TabRef } from '@/lib/bridge/tabs';
import { adoptSubtab, sessionForRun, sessionForTab, setCurrentTab, type TabSession } from '@/lib/bridge/tab-sessions';
+import { invokeOnPhone, phoneRoute } from '@/lib/bridge/phone-invoke';
/**
* The sanitizer's client-side half, wrapped around every action the harness runs.
@@ -78,6 +79,9 @@ export async function invokeForHarness(
tabId?: number,
runId?: string,
): Promise<ActionResult> {
+ const phone = await phoneRoute(tabId, runId);
+ if (phone) return invokeOnPhone(action, input, phone);
+
const refused = await guardTarget(action, input, tabId, runId);
if (refused) return refused;
diff --git a/src/lib/bridge/phone-conversation.ts b/src/lib/bridge/phone-conversation.ts
new file mode 100644
index 0000000..ec85b7c
--- /dev/null
+++ b/src/lib/bridge/phone-conversation.ts
@@ -0,0 +1,37 @@
+import { browser } from 'wxt/browser';
+import type { PhoneContext } from '@/lib/phone/types';
+import { isLive, readPhone } from './phone';
+import { currentTarget, inCurrentTab } from './phone-invoke';
+import { DAEMON_STATE_KEY, type DaemonState } from './socket';
+import type { TabAnchor, TabSession } from './tab-sessions';
+
+const DEFAULT_DENSITY = 160;
+
+/** A conversation started on the phone tab is anchored on the phone's page, never on the extension page that shows it. */
+export async function phoneAnchor(anchor: TabAnchor): Promise<{ anchor: TabAnchor; serial?: string }> {
+ const phone = await readPhone();
+ if (!phone || phone.mirrorTabId !== anchor.tabId) return { anchor };
+ const target = currentTarget(phone);
+ return { anchor: { ...anchor, url: target?.url, title: target?.title || phone.model || 'Android' }, serial: phone.serial };
+}
+
+/** What a run on the phone is told about it: the device from the Bridge, the viewport from the page as it is now. */
+export async function phoneContext(session: TabSession): Promise<PhoneContext | undefined> {
+ const phone = await readPhone();
+ if (!session.phone || !phone || !isLive(phone)) return undefined;
+ const stored = await browser.storage.session.get(DAEMON_STATE_KEY);
+ const device = (stored[DAEMON_STATE_KEY] as DaemonState | undefined)?.android?.devices.find((each) => each.serial === phone.serial);
+ const metrics = await inCurrentTab(phone, 'Page.getLayoutMetrics');
+ const visual = (metrics.ok ? metrics.data.cssVisualViewport : undefined) as { clientWidth?: number; clientHeight?: number } | undefined;
+ return {
+ serial: phone.serial,
+ model: device?.model ?? phone.model ?? 'Android phone',
+ android: device?.android ?? '',
+ chrome: device?.chrome.version ?? '',
+ viewport: {
+ width: Math.round(visual?.clientWidth ?? 0),
+ height: Math.round(visual?.clientHeight ?? 0),
+ dpr: (device?.screen?.density ?? DEFAULT_DENSITY) / DEFAULT_DENSITY,
+ },
+ };
+}
diff --git a/src/lib/bridge/phone-invoke.test.ts b/src/lib/bridge/phone-invoke.test.ts
new file mode 100644
index 0000000..2b3cbfa
--- /dev/null
+++ b/src/lib/bridge/phone-invoke.test.ts
@@ -0,0 +1,190 @@
+import { beforeEach, describe, expect, test, vi } from 'vitest';
+import { fakeBrowser } from 'wxt/testing';
+import { success } from '@/lib/actions/protocol';
+import { BLOCKED_SITES_KEY } from '@/lib/settings/blocked-sites';
+
+const SERIAL = 'emulator-5554';
+const HOME = 'A'.repeat(32);
+const OTHER = 'B'.repeat(32);
+
+const phone = vi.hoisted(() => ({
+ sent: [] as { method: string; params?: Record<string, unknown> }[],
+ location: 'https://news.example/',
+ fronted: [] as string[],
+ followed: [] as string[],
+}));
+
+vi.mock('./socket', () => ({
+ DAEMON_STATE_KEY: 'browsentic/daemon',
+ sendCdp: async (_serial: string, method: string, params?: Record<string, unknown>) => {
+ phone.sent.push({ method, params });
+ if (method === 'Page.navigate') phone.location = String(params?.url);
+ if (method === 'Runtime.evaluate') return success({ result: { value: JSON.stringify({ url: phone.location, title: 'Landed', readyState: 'complete' }) } });
+ if (method === 'Target.createTarget') return success({ targetId: 'C'.repeat(32) });
+ if (method === 'Page.getLayoutMetrics') return success({ cssVisualViewport: { clientWidth: 411, clientHeight: 675 } });
+ return success({});
+ },
+ closePhone: () => undefined,
+ openPhone: async () => success({}),
+ launchPhoneChrome: async () => success({}),
+ onPhoneClosed: () => undefined,
+ onDaemonClosed: () => undefined,
+}));
+
+vi.mock('./phone-mirror', () => ({
+ attachedSession: async (_serial: string, targetId: string) => `session-${targetId}`,
+ bringToFront: async (_serial: string, targetId: string) => void phone.fronted.push(targetId),
+ followTarget: async (targetId: string) => void phone.followed.push(targetId),
+}));
+
+const { invokeOnPhone, phoneRoute } = await import('./phone-invoke');
+const { phoneAnchor, phoneContext } = await import('./phone-conversation');
+const { invokeForHarness } = await import('./invoke');
+const { ensureSessionForTab, patchSession } = await import('./tab-sessions');
+
+let mirrorTabId: number;
+let desktopTabId: number;
+
+beforeEach(async () => {
+ fakeBrowser.reset();
+ phone.sent.length = 0;
+ phone.fronted.length = 0;
+ phone.followed.length = 0;
+ phone.location = 'https://news.example/';
+ desktopTabId = (await fakeBrowser.tabs.create({ url: 'https://desktop.example/', active: false })).id!;
+ mirrorTabId = (await fakeBrowser.tabs.create({ url: 'chrome-extension://abc/phone.html', active: true })).id!;
+ await fakeBrowser.storage.session.set({
+ 'browsentic/phone': {
+ serial: SERIAL,
+ model: 'Pixel 8',
+ mirrorTabId,
+ windowId: 1,
+ openedAt: 0,
+ activeTargetId: HOME,
+ targets: [
+ { targetId: HOME, url: 'https://news.example/', title: 'News' },
+ { targetId: OTHER, url: 'https://shop.example/', title: 'Shop' },
+ ],
+ tabNumbers: { [HOME]: 1, [OTHER]: 2 },
+ },
+ 'browsentic/daemon': {
+ connected: true,
+ paired: true,
+ lastChangeAt: 0,
+ android: { devices: [{ serial: SERIAL, model: 'Pixel 8', android: '16', screen: { width: 1080, height: 2400, density: 420, awake: true }, chrome: { version: '150.0.7871.186' } }] },
+ },
+ });
+});
+
+const block = (...patterns: string[]) => fakeBrowser.storage.local.set({ [BLOCKED_SITES_KEY]: patterns });
+
+describe('which calls go to the phone', () => {
+ test('a call landing on the phone tab with no run does, and a desktop tab’s does not', async () => {
+ expect(await phoneRoute(mirrorTabId, undefined)).toMatchObject({ serial: SERIAL });
+ expect(await phoneRoute(desktopTabId, undefined)).toBeNull();
+ });
+
+ test('a run whose conversation lives on the phone tab does, wherever its tab id points', async () => {
+ const ensured = await ensureSessionForTab({ tabId: mirrorTabId, url: 'https://news.example/' });
+ if (!ensured.ok) throw new Error('no session');
+ await patchSession(ensured.session.sessionId, { runId: 'run-1', phone: { serial: SERIAL } });
+ expect(await phoneRoute(desktopTabId, 'run-1')).toMatchObject({ serial: SERIAL });
+ const desktop = await ensureSessionForTab({ tabId: desktopTabId, url: 'https://desktop.example/' });
+ if (!desktop.ok) throw new Error('no session');
+ await patchSession(desktop.session.sessionId, { runId: 'run-2' });
+ expect(await phoneRoute(mirrorTabId, 'run-2')).toBeNull();
+ });
+
+ test('a phone run after the phone went away is told so', async () => {
+ const ensured = await ensureSessionForTab({ tabId: mirrorTabId });
+ if (!ensured.ok) throw new Error('no session');
+ await patchSession(ensured.session.sessionId, { runId: 'run-3', phone: { serial: SERIAL } });
+ const stored = (await fakeBrowser.storage.session.get('browsentic/phone'))['browsentic/phone'] as object;
+ await fakeBrowser.storage.session.set({ 'browsentic/phone': { ...stored, ended: { reason: 'unplugged', at: 1 } } });
+ expect(await invokeForHarness('page.getPageInfo', {}, mirrorTabId, 'run-3')).toMatchObject({ ok: false, error: { code: 'PHONE_GONE' } });
+ });
+
+ test('invokeForHarness takes the phone branch before any desktop check of the extension page', async () => {
+ expect(await invokeForHarness('page.hoverElement', {}, mirrorTabId)).toMatchObject({ ok: false, error: { code: 'NOT_ON_PHONE' } });
+ });
+});
+
+describe('a tool on the phone', () => {
+ const route = async () => (await phoneRoute(mirrorTabId, undefined))!;
+
+ test('a tool off the list is refused with where it does work', async () => {
+ expect(await invokeOnPhone('page.injectCode', {}, await route())).toEqual({
+ ok: false,
+ error: { code: 'NOT_ON_PHONE', message: 'page.injectCode isn’t available on the phone. It works in desktop tabs.' },
+ });
+ });
+
+ test('a blocked phone page refuses every action, before the phone hears of it', async () => {
+ await block('news.example');
+ expect(await invokeOnPhone('page.getPageInfo', {}, await route())).toMatchObject({ ok: false, error: { code: 'SITE_BLOCKED' } });
+ expect(phone.sent).toEqual([]);
+ });
+
+ test('navigating to a blocked host is refused before it goes', async () => {
+ await block('bank.example');
+ expect(await invokeOnPhone('page.navigate', { url: 'https://bank.example/' }, await route())).toMatchObject({ ok: false, error: { code: 'SITE_BLOCKED' } });
+ expect(phone.sent.map(({ method }) => method)).not.toContain('Page.navigate');
+ });
+
+ test('a page that lands somewhere blocked is refused after it lands', async () => {
+ await block('landing.example');
+ const landed = invokeOnPhone('page.navigate', { url: 'https://ok.example/' }, await route());
+ phone.location = 'https://landing.example/';
+ await fakeBrowser.storage.session.get('browsentic/phone').then(async (stored) => {
+ const session = stored['browsentic/phone'] as { targets: { targetId: string; url: string; title: string }[] };
+ session.targets[0].url = 'https://landing.example/';
+ await fakeBrowser.storage.session.set({ 'browsentic/phone': session });
+ });
+ expect(await landed).toMatchObject({ ok: false, error: { code: 'SITE_BLOCKED' } });
+ });
+
+ test('navigate opens the URL in the phone’s current tab and waits for it to load', async () => {
+ expect(await invokeOnPhone('page.navigate', { url: 'https://wikipedia.org/' }, await route())).toEqual({
+ ok: true,
+ data: { navigatedTo: 'https://wikipedia.org/', finalUrl: 'https://wikipedia.org/', title: 'Landed', loaded: true },
+ });
+ expect(phone.sent[0]).toEqual({ method: 'Page.navigate', params: { url: 'https://wikipedia.org/' } });
+ });
+
+ test('switchTab takes the phone’s tab numbers, brings that tab to the front and moves the mirror to it', async () => {
+ expect(await invokeOnPhone('page.switchTab', { tabId: 2 }, await route())).toMatchObject({ ok: true, data: { activeTabId: 2 } });
+ expect([phone.fronted, phone.followed]).toEqual([[OTHER], [OTHER]]);
+ expect(await invokeOnPhone('page.switchTab', {}, await route())).toMatchObject({
+ ok: true,
+ data: { tabs: [{ tabId: 1, active: true }, { tabId: 2, active: false }] },
+ });
+ });
+
+ test('openTab in the background opens in front, as Android insists, then puts the previous tab back', async () => {
+ const opened = await invokeOnPhone('page.openTab', { url: 'https://docs.example/', active: false }, await route());
+ expect(opened).toMatchObject({ ok: true, data: { tabId: 3, activeTabId: 1 } });
+ expect(phone.fronted).toEqual([HOME]);
+ expect(phone.followed).toEqual([]);
+ });
+});
+
+describe('a conversation on the phone tab', () => {
+ test('is anchored on the phone’s page, never the extension page', async () => {
+ const { anchor, serial } = await phoneAnchor({ tabId: mirrorTabId, url: 'chrome-extension://abc/phone.html', title: 'Android · Pixel 8' });
+ expect([anchor.url, anchor.title, serial]).toEqual(['https://news.example/', 'News', SERIAL]);
+ expect((await phoneAnchor({ tabId: desktopTabId, url: 'https://desktop.example/' })).serial).toBeUndefined();
+ });
+
+ test('tells its run which phone, and the viewport as the page has it now', async () => {
+ const ensured = await ensureSessionForTab({ tabId: mirrorTabId });
+ if (!ensured.ok) throw new Error('no session');
+ expect(await phoneContext({ ...ensured.session, phone: { serial: SERIAL } })).toEqual({
+ serial: SERIAL,
+ model: 'Pixel 8',
+ android: '16',
+ chrome: '150.0.7871.186',
+ viewport: { width: 411, height: 675, dpr: 2.625 },
+ });
+ expect(await phoneContext({ ...ensured.session, phone: undefined })).toBeUndefined();
+ });
+});
diff --git a/src/lib/bridge/phone-invoke.ts b/src/lib/bridge/phone-invoke.ts
new file mode 100644
index 0000000..27cb05a
--- /dev/null
+++ b/src/lib/bridge/phone-invoke.ts
@@ -0,0 +1,216 @@
+import { browser } from 'wxt/browser';
+import { z } from 'zod';
+import { ActionError } from '@/lib/actions/core';
+import { closeTab } from '@/lib/actions/page/close-tab';
+import { navigate, resolveNavigation, type NavigateInput } from '@/lib/actions/page/navigate';
+import { openTab } from '@/lib/actions/page/open-tab';
+import { switchTab } from '@/lib/actions/page/switch-tab';
+import { failure, success, type ActionResult } from '@/lib/actions/protocol';
+import { EXPIRED_MESSAGE, REFUSED_MESSAGE } from '@/lib/secrets';
+import { notOnPhone, phoneOffers } from '@/lib/phone/features';
+import { isLive, readPhone, targetForNumber, updatePhone, numbered, type PhoneSession } from './phone';
+import { attachedSession, bringToFront, followTarget } from './phone-mirror';
+import { releaseForAction, sealForPage } from './secret-vault';
+import { refusalFor } from './site-guard';
+import { sendCdp } from './socket';
+import { sessionForRun, type TabSession } from './tab-sessions';
+
+const GONE = 'The phone disconnected. Reconnect it and switch Android on again.';
+const LOAD_TIMEOUT_MS = 15_000;
+const LOAD_POLL_MS = 150;
+
+/** Pages a tool lands on, checked against the blocked list once it has run. */
+const LANDS = new Set([navigate.name, openTab.name, 'page.searchSite', 'page.submitForm', 'page.clickElement', 'page.trustedClick']);
+
+type PhoneBackend = (action: string, input: unknown, phone: PhoneSession) => Promise<ActionResult>;
+
+const pageSide: PhoneBackend = async (action) => failure('NOT_BUILT', `${action} is not built for the phone yet.`);
+
+/**
+ * The phone session a call belongs to: its run's conversation lives on the phone tab, or, with no
+ * run, the tab it resolves to is the phone tab. Null for every desktop call.
+ */
+export async function phoneRoute(tabId: number | undefined, runId: string | undefined): Promise<PhoneSession | 'gone' | null> {
+ const owner: TabSession | null = runId ? await sessionForRun(runId) : null;
+ const phone = await readPhone();
+ if (owner) return owner.phone ? (isLive(phone) && phone ? phone : 'gone') : null;
+ if (!phone) return null;
+ const tab = tabId ?? (await browser.tabs.query({ active: true, currentWindow: true }))[0]?.id;
+ if (tab !== phone.mirrorTabId) return null;
+ return isLive(phone) ? phone : 'gone';
+}
+
+export const currentTarget = (phone: PhoneSession) => phone.targets.find((target) => target.targetId === phone.activeTargetId) ?? phone.targets[0];
+
+export async function invokeOnPhone(action: string, input: unknown, route: PhoneSession | 'gone'): Promise<ActionResult> {
+ if (route === 'gone') return failure('PHONE_GONE', GONE);
+ if (!phoneOffers(action)) return failure('NOT_ON_PHONE', notOnPhone(action));
+
+ const here = currentTarget(route)?.url;
+ const refused = await refusalFor(here, ...destinationsOf(action, input, here));
+ if (refused) return refused;
+
+ const release = await releaseForAction(action, input);
+ if (release.refused.length) return failure('SECRET_NOT_RELEASABLE', REFUSED_MESSAGE);
+ if (release.unresolved.length) return failure('SECRET_EXPIRED', EXPIRED_MESSAGE);
+
+ const result = await (TAB_TOOLS[action] ?? pageSide)(action, release.input, route);
+ if (result.ok && LANDS.has(action)) {
+ const landed = await refusalFor(currentTarget((await readPhone()) ?? route)?.url, textOf((result.data as { finalUrl?: unknown })?.finalUrl));
+ if (landed) return landed;
+ }
+ const { value } = await sealForPage(result, hostOf(currentTarget((await readPhone()) ?? route)?.url));
+ return value;
+}
+
+function destinationsOf(action: string, input: unknown, base?: string): (string | undefined)[] {
+ const url = (input as { url?: unknown } | undefined)?.url;
+ if ((action !== navigate.name && action !== openTab.name) || typeof url !== 'string') return [];
+ try {
+ return [new URL(url, base).href];
+ } catch {
+ return [];
+ }
+}
+
+const TAB_TOOLS: Record<string, PhoneBackend> = {
+ [navigate.name]: navigateOnPhone,
+ [openTab.name]: openPhoneTab,
+ [switchTab.name]: switchPhoneTab,
+ [closeTab.name]: closePhoneTab,
+};
+
+export async function inCurrentTab(phone: PhoneSession, method: string, params?: Record<string, unknown>) {
+ const target = currentTarget(phone);
+ const sessionId = target && (await attachedSession(phone.serial, target.targetId));
+ return sessionId ? sendCdp(phone.serial, method, params, sessionId) : failure('PHONE_GONE', GONE);
+}
+
+async function loaded(phone: PhoneSession, sinceUrl?: string): Promise<{ url: string; title: string; loaded: boolean }> {
+ const deadline = Date.now() + LOAD_TIMEOUT_MS;
+ let seen = { url: sinceUrl ?? '', title: '', readyState: '' };
+ while (Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, LOAD_POLL_MS));
+ const state = await inCurrentTab(phone, 'Runtime.evaluate', {
+ expression: 'JSON.stringify({ url: location.href, title: document.title, readyState: document.readyState })',
+ returnByValue: true,
+ });
+ if (!state.ok) continue;
+ seen = JSON.parse(String((state.data.result as { value?: unknown }).value ?? '{}'));
+ if (seen.readyState === 'complete' && seen.url !== 'about:blank') return { url: seen.url, title: seen.title, loaded: true };
+ }
+ return { url: seen.url, title: seen.title, loaded: false };
+}
+
+async function navigateOnPhone(_action: string, input: unknown, phone: PhoneSession): Promise<ActionResult> {
+ const parsed = navigate.input.safeParse(input ?? {});
+ if (!parsed.success) return failure('INVALID_INPUT', z.prettifyError(parsed.error));
+ let plan;
+ try {
+ plan = resolveNavigation(parsed.data as NavigateInput, currentTarget(phone)?.url);
+ } catch (error) {
+ return error instanceof ActionError ? failure(error.code, error.message) : failure('ACTION_FAILED', String(error));
+ }
+ if (plan.kind === 'url') {
+ const went = await inCurrentTab(phone, 'Page.navigate', { url: plan.href });
+ if (!went.ok) return went;
+ if (went.data.errorText) return failure('NAVIGATION_FAILED', `The phone could not open ${plan.href}: ${went.data.errorText}`);
+ const landing = await loaded(phone);
+ return success({ navigatedTo: plan.href, finalUrl: landing.url, title: landing.title, loaded: landing.loaded });
+ }
+ if (plan.action === 'reload') {
+ const reloaded = await inCurrentTab(phone, 'Page.reload');
+ if (!reloaded.ok) return reloaded;
+ } else {
+ const history = await inCurrentTab(phone, 'Page.getNavigationHistory');
+ if (!history.ok) return history;
+ const entries = (history.data.entries as { id: number }[] | undefined) ?? [];
+ const entry = entries[Number(history.data.currentIndex) + (plan.action === 'back' ? -1 : 1)];
+ if (!entry) return failure('ACTION_FAILED', `Cannot go ${plan.action}: this phone tab has no ${plan.action === 'back' ? 'previous' : 'next'} page in its history.`);
+ const went = await inCurrentTab(phone, 'Page.navigateToHistoryEntry', { entryId: entry.id });
+ if (!went.ok) return went;
+ }
+ const landing = await loaded(phone);
+ return success({ performed: plan.action, finalUrl: landing.url, title: landing.title, loaded: landing.loaded });
+}
+
+async function openPhoneTab(_action: string, input: unknown, phone: PhoneSession): Promise<ActionResult> {
+ const parsed = openTab.input.safeParse(input ?? {});
+ if (!parsed.success) return failure('INVALID_INPUT', z.prettifyError(parsed.error));
+ const { url, active } = parsed.data;
+ const previous = currentTarget(phone);
+ let href: string;
+ try {
+ const plan = resolveNavigation({ url }, previous?.url);
+ if (plan.kind !== 'url') return failure('INVALID_INPUT', 'page.openTab opens a URL — it has no history to walk.');
+ href = plan.href;
+ } catch (error) {
+ return error instanceof ActionError ? failure(error.code, error.message) : failure('ACTION_FAILED', String(error));
+ }
+ const created = await sendCdp(phone.serial, 'Target.createTarget', { url: href });
+ if (!created.ok) return created;
+ const targetId = String(created.data.targetId);
+ const held = await updatePhone((session) => numbered(session, session.targets.some((each) => each.targetId === targetId) ? session.targets : [...session.targets, { targetId, url: href, title: '' }]));
+ const tabId = held?.tabNumbers?.[targetId];
+ if (active === false && previous) {
+ await bringToFront(phone.serial, previous.targetId);
+ return success({
+ performed: `opened ${href} in a new phone tab, then went back to tab ${phone.tabNumbers?.[previous.targetId]}; the phone shows a new tab in front for a moment, since Chrome on Android opens every new tab there`,
+ openedUrl: href,
+ tabId,
+ activeTabId: phone.tabNumbers?.[previous.targetId],
+ });
+ }
+ await followTarget(targetId);
+ const landing = await loaded({ ...phone, ...held, activeTargetId: targetId });
+ return success({ performed: `opened ${href} in a new phone tab`, openedUrl: href, finalUrl: landing.url, tabId, loaded: landing.loaded, activeTabId: tabId, previousTabId: previous && phone.tabNumbers?.[previous.targetId] });
+}
+
+const describeTabs = (phone: PhoneSession) =>
+ phone.targets.map((target) => ({ tabId: phone.tabNumbers?.[target.targetId], url: target.url, title: target.title, active: target.targetId === phone.activeTargetId }));
+
+async function switchPhoneTab(_action: string, input: unknown, phone: PhoneSession): Promise<ActionResult> {
+ const parsed = switchTab.input.safeParse(input ?? {});
+ if (!parsed.success) return failure('INVALID_INPUT', z.prettifyError(parsed.error));
+ const { tabId, match } = parsed.data;
+ if (tabId == null && match == null) return success({ tabs: describeTabs(phone) });
+ const targetId =
+ tabId != null
+ ? targetForNumber(phone, tabId)
+ : phone.targets.find((target) => `${target.title} ${target.url}`.toLowerCase().includes(String(match).toLowerCase()))?.targetId;
+ const target = phone.targets.find((each) => each.targetId === targetId);
+ if (!target) return failure('INVALID_TARGET', `No phone tab matches. The phone's tabs: ${JSON.stringify(describeTabs(phone))}`);
+ const refused = await refusalFor(target.url);
+ if (refused) return refused;
+ await bringToFront(phone.serial, target.targetId);
+ await followTarget(target.targetId);
+ return success({ performed: `switched to phone tab ${phone.tabNumbers?.[target.targetId]}`, activeTabId: phone.tabNumbers?.[target.targetId], tab: { url: target.url, title: target.title } });
+}
+
+async function closePhoneTab(_action: string, input: unknown, phone: PhoneSession): Promise<ActionResult> {
+ const parsed = closeTab.input.safeParse(input ?? {});
+ if (!parsed.success) return failure('INVALID_INPUT', z.prettifyError(parsed.error));
+ const { tabId, match } = parsed.data;
+ const targetId =
+ tabId != null
+ ? targetForNumber(phone, tabId)
+ : match != null
+ ? phone.targets.find((target) => `${target.title} ${target.url}`.toLowerCase().includes(String(match).toLowerCase()))?.targetId
+ : phone.activeTargetId;
+ const target = phone.targets.find((each) => each.targetId === targetId);
+ if (!target) return failure('INVALID_TARGET', `No phone tab matches. The phone's tabs: ${JSON.stringify(describeTabs(phone))}`);
+ if (phone.targets.length <= 1) return failure('INVALID_TARGET', 'That is the only tab open on the phone. Open another first, or leave this one alone.');
+ const closed = await sendCdp(phone.serial, 'Target.closeTarget', { targetId: target.targetId });
+ if (!closed.ok) return closed;
+ return success({ performed: `closed phone tab ${phone.tabNumbers?.[target.targetId]}`, closed: { url: target.url, title: target.title } });
+}
+
+const textOf = (value: unknown): string | undefined => (typeof value === 'string' ? value : undefined);
+
+function hostOf(url: string | undefined): string | undefined {
+ try {
+ return url ? new URL(url).hostname.toLowerCase() || undefined : undefined;
+ } catch {
+ return undefined;
+ }
+}
diff --git a/src/lib/bridge/phone-mirror.ts b/src/lib/bridge/phone-mirror.ts
index 117eb14..f0f31f0 100644
--- a/src/lib/bridge/phone-mirror.ts
+++ b/src/lib/bridge/phone-mirror.ts
@@ -1,9 +1,10 @@
import { browser, type Browser } from 'wxt/browser';
import { PHONE_PORT, keyEvents, type MirrorCommand, type MirrorMessage, type PageState } from '@/lib/phone/mirror';
import type { PhoneTarget } from '@/lib/phone/types';
-import { readPhone, updatePhone, type PhoneSession } from './phone';
+import { numbered, readPhone, updatePhone, type PhoneSession } from './phone';
import { refusalFor } from './site-guard';
import { onCdpEvent, onDaemonClosed, onPhoneClosed, sendCdp, type CdpEvent } from './socket';
+import { hostOf, patchSession, sessionForTab } from './tab-sessions';
type Port = Browser.runtime.Port;
type InputCommand = Extract<MirrorCommand, { op: 'touch' | 'wheel' | 'text' | 'key' }>;
@@ -28,6 +29,7 @@ let page: PageState | null = null;
let finding: Promise<void> | null = null;
const inputs: InputCommand[] = [];
let pumping = false;
+const attachments = new Map<string, Promise<string | null>>();
const broadcast = (message: MirrorMessage) => {
for (const port of ports) port.postMessage(message);
@@ -54,15 +56,43 @@ function call(method: string, params?: Record<string, unknown>) {
return held ? sendCdp(held.serial, method, params, held.sessionId) : Promise.resolve(null);
}
+/** One DevTools session per phone tab, shared by the mirror and the tools, made on first use. */
+export function attachedSession(serial: string, targetId: string): Promise<string | null> {
+ const held = attachments.get(targetId);
+ if (held) return held;
+ const attaching = sendCdp(serial, 'Target.attachToTarget', { targetId, flatten: true }).then(async (attached) => {
+ if (!attached.ok) {
+ attachments.delete(targetId);
+ return null;
+ }
+ const sessionId = String(attached.data.sessionId);
+ await sendCdp(serial, 'Page.enable', {}, sessionId);
+ return sessionId;
+ });
+ attachments.set(targetId, attaching);
+ return attaching;
+}
+
+/** Moves the mirror, and with it the conversation's idea of the current phone tab, to this one. */
+export async function followTarget(targetId: string): Promise<void> {
+ const session = await liveSession();
+ if (session) await follow(session, targetId);
+}
+
+async function reflect(url: string, title: string): Promise<void> {
+ const phone = await readPhone();
+ const conversation = phone && (await sessionForTab(phone.mirrorTabId));
+ if (!conversation?.phone || (conversation.url === url && conversation.title === title)) return;
+ await patchSession(conversation.sessionId, { url, host: hostOf(url), title: title || conversation.title });
+}
+
async function follow(session: PhoneSession, targetId: string): Promise<void> {
if (followed?.serial === session.serial && followed.targetId === targetId) return;
await stopStream();
- if (followed) void sendCdp(followed.serial, 'Target.detachFromTarget', { sessionId: followed.sessionId });
followed = null;
- const attached = await sendCdp(session.serial, 'Target.attachToTarget', { targetId, flatten: true });
- if (!attached.ok) return tellError(attached.error.message);
- followed = { serial: session.serial, targetId, sessionId: String(attached.data.sessionId) };
- await call('Page.enable');
+ const sessionId = await attachedSession(session.serial, targetId);
+ if (!sessionId) return tellError('The phone did not let Browsentic attach to that tab.');
+ followed = { serial: session.serial, targetId, sessionId };
await updatePhone((held) => ({ ...held, activeTargetId: targetId }));
await publishPage();
if (watchers.size) await startStream();
@@ -112,6 +142,7 @@ async function publishPage(): Promise<void> {
canGoForward: current < entries.length - 1,
};
broadcast({ kind: 'page', ...page });
+ await reflect(page.url, page.title);
}
/** A tab switch made on the phone fires no Target event; the tab whose document is visible is the one in front. */
@@ -128,18 +159,19 @@ function findFront(): Promise<void> {
}
async function isVisible(serial: string, targetId: string): Promise<boolean> {
- const own = followed?.targetId === targetId ? followed.sessionId : undefined;
- const attached = own ? null : await sendCdp(serial, 'Target.attachToTarget', { targetId, flatten: true });
- const sessionId = own ?? (attached?.ok ? String(attached.data.sessionId) : null);
+ const sessionId = await attachedSession(serial, targetId);
if (!sessionId) return false;
const state = await sendCdp(serial, 'Runtime.evaluate', { expression: 'document.visibilityState', returnByValue: true }, sessionId);
- if (!own) void sendCdp(serial, 'Target.detachFromTarget', { sessionId });
return state.ok && (state.data.result as { value?: unknown } | undefined)?.value === 'visible';
}
async function trackTargets(event: CdpEvent): Promise<void> {
const info = (event.params.targetInfo ?? {}) as TargetInfo;
- if (event.method === 'Target.detachedFromTarget' && event.params.sessionId === followed?.sessionId) {
+ if (event.method === 'Target.detachedFromTarget') {
+ for (const [targetId, attaching] of attachments) {
+ if ((await attaching) === event.params.sessionId) attachments.delete(targetId);
+ }
+ if (event.params.sessionId !== followed?.sessionId) return;
followed = null;
streaming = false;
if (watchers.size) void ensureFollowed();
@@ -147,6 +179,7 @@ async function trackTargets(event: CdpEvent): Promise<void> {
}
if (event.method === 'Target.targetDestroyed') {
const targetId = String(event.params.targetId);
+ attachments.delete(targetId);
await updatePhone((held) => ({ ...held, targets: held.targets.filter((target) => target.targetId !== targetId) }));
if (followed?.targetId === targetId) {
followed = null;
@@ -157,15 +190,18 @@ async function trackTargets(event: CdpEvent): Promise<void> {
}
if ((event.method !== 'Target.targetCreated' && event.method !== 'Target.targetInfoChanged') || !isPageTarget(info)) return;
const target: PhoneTarget = { targetId: info.targetId, url: info.url ?? '', title: info.title ?? '' };
- await updatePhone((held) => ({
- ...held,
- targets: held.targets.some((each) => each.targetId === target.targetId)
- ? held.targets.map((each) => (each.targetId === target.targetId ? target : each))
- : [...held.targets, target],
- }));
+ await updatePhone((held) =>
+ numbered(
+ held,
+ held.targets.some((each) => each.targetId === target.targetId)
+ ? held.targets.map((each) => (each.targetId === target.targetId ? target : each))
+ : [...held.targets, target],
+ ),
+ );
if (page && followed?.targetId === target.targetId) {
page = { ...page, url: target.url, title: target.title };
broadcast({ kind: 'page', ...page });
+ await reflect(target.url, target.title);
}
}
@@ -216,7 +252,7 @@ async function dispatchInput(command: InputCommand): Promise<void> {
}
/** Chrome on Android can ignore an activation that lands just after a tab opened, so it is asked again until the tab is in front. */
-async function bringToFront(serial: string, targetId: string): Promise<void> {
+export async function bringToFront(serial: string, targetId: string): Promise<void> {
for (let attempt = 0; attempt < ACTIVATE_TRIES; attempt++) {
await sendCdp(serial, 'Target.activateTarget', { targetId });
await new Promise((resolve) => setTimeout(resolve, ACTIVATE_SETTLE_MS));
@@ -296,6 +332,7 @@ function forget(): void {
streaming = false;
page = null;
inputs.length = 0;
+ attachments.clear();
}
export function servePhoneMirror(): void {
diff --git a/src/lib/bridge/phone.ts b/src/lib/bridge/phone.ts
index 02498b9..5f4ae6b 100644
--- a/src/lib/bridge/phone.ts
+++ b/src/lib/bridge/phone.ts
@@ -23,6 +23,8 @@ export interface PhoneSession {
targets: PhoneTarget[];
/** The tab the mirror follows: the one in front on the phone, found once the mirror starts. */
activeTargetId?: string;
+ /** The number each phone tab goes by in tool results, counting from 1 and never reused, since a tab id is an integer there. */
+ tabNumbers?: Record<string, number>;
/** Chrome was not open on the phone; the mirror waits, and the notification offers to open it. */
waitingForChrome?: boolean;
/** The session is over but its mirror tab is still open, to say why and offer to reconnect. */
@@ -31,6 +33,17 @@ export interface PhoneSession {
export const isLive = (session: PhoneSession | null | undefined): boolean => !!session && !session.ended;
+/** The session with every tab it knows numbered. */
+export function numbered(session: PhoneSession, targets: PhoneTarget[] = session.targets): PhoneSession {
+ const tabNumbers = { ...session.tabNumbers };
+ let next = Math.max(0, ...Object.values(tabNumbers)) + 1;
+ for (const { targetId } of targets) tabNumbers[targetId] ??= next++;
+ return { ...session, targets, tabNumbers };
+}
+
+export const targetForNumber = (session: PhoneSession, number: number): string | undefined =>
+ Object.entries(session.tabNumbers ?? {}).find(([, value]) => value === number)?.[0];
+
let queue: Promise<unknown> = Promise.resolve();
function locked<T>(work: () => Promise<T>): Promise<T> {
@@ -90,14 +103,14 @@ export function startPhone(serial: string, windowId?: number): Promise<ActionRes
if (opened.ok) closePhone(serial);
return failure('BRIDGE_ERROR', 'The phone tab could not be opened.');
}
- const session: PhoneSession = {
+ const session: PhoneSession = numbered({
serial,
mirrorTabId: mirror.id,
windowId: mirror.windowId ?? windowId ?? browser.windows.WINDOW_ID_CURRENT,
openedAt: Date.now(),
...opening(opened),
...(await describedPhone(serial, opened)),
- };
+ });
await writePhone(session);
if (session.waitingForChrome) await askToOpenChrome(session);
return success(session);
@@ -129,7 +142,7 @@ export function openChromeOnPhone(): Promise<ActionResult<PhoneSession>> {
const launched = await launchPhoneChrome(held.serial);
if (!launched.ok) return launched;
const opened = await openPhone(held.serial);
- const session = { ...held, ...opening(opened) };
+ const session = numbered({ ...held, ...opening(opened) });
await writePhone(session);
if (!session.waitingForChrome) await clearNotification();
return success(session);
diff --git a/src/lib/bridge/run-port.ts b/src/lib/bridge/run-port.ts
index b838e7c..96ad28e 100644
--- a/src/lib/bridge/run-port.ts
+++ b/src/lib/bridge/run-port.ts
@@ -35,6 +35,7 @@ import {
type NewFile,
} from './file-store';
import { invokeForHarness } from './invoke';
+import { phoneAnchor, phoneContext } from './phone-conversation';
import {
acknowledgeCompleted,
activeMonitorStates,
@@ -67,6 +68,7 @@ import {
activateSiteMap,
cancelRun,
discardSiteMap,
+ onPhoneClosed,
onRunEvent,
onSiteMapDraft,
onTaskOrder,
@@ -87,6 +89,7 @@ import {
remapTab,
sessionForRun,
sessionForTab,
+ type Ensured,
type TabAnchor,
type TabSession,
type TaskTag,
@@ -428,7 +431,7 @@ type Attached = { ok: true } | { ok: false; error: string };
/** A file belongs to the conversation of the tab it was dropped on, which is started here if need be. */
async function attach(file: NewFile, anchor: TabAnchor): Promise<Attached> {
- const ensured = await ensureSessionForTab(anchor);
+ const ensured = await ensureConversation(anchor);
if (!ensured.ok) {
await removeFile(file.id);
broadcast({ op: 'event', runId: LOCAL_RUN, event: { kind: 'error', code: 'SESSION_LIMIT', message: ensured.message } });
@@ -540,6 +543,15 @@ async function settle(sessionId: string): Promise<void> {
await nameStoredSession(sessionId).catch(() => undefined);
}
+/** The conversation of the tab the user is on; on the phone tab it is bound to the phone and carries the phone's address. */
+async function ensureConversation(anchor: TabAnchor): Promise<Ensured> {
+ const { anchor: anchored, serial } = await phoneAnchor(anchor);
+ const ensured = await ensureSessionForTab(anchored);
+ if (!ensured.ok || !serial || ensured.session.phone?.serial === serial) return ensured;
+ await patchSession(ensured.session.sessionId, { phone: { serial } });
+ return { ok: true, session: { ...ensured.session, phone: { serial } } };
+}
+
async function instruct(
text: string,
anchor: TabAnchor,
@@ -547,7 +559,7 @@ async function instruct(
focus?: FocusedElement,
liveTools?: boolean,
): Promise<void> {
- const ensured = await ensureSessionForTab(anchor);
+ const ensured = await ensureConversation(anchor);
if (!ensured.ok) {
broadcast({
op: 'event',
@@ -609,10 +621,11 @@ async function startTurn(
agentSessionId: session.agentSessionId,
agentSkillId,
focus: hidden ? undefined : focus,
- liveTools,
+ liveTools: session.phone ? undefined : liveTools,
files: await attachedFiles(session),
- recordings: await attachedRecordings(),
+ recordings: session.phone ? undefined : await attachedRecordings(),
task,
+ phone: await phoneContext(session),
});
if (!runId) {
await append(
@@ -728,6 +741,7 @@ async function restore(sessionId: string, anchor: TabAnchor): Promise<void> {
transcript?.items ?? [notice('error', 'That conversation’s messages are no longer stored.')],
);
+ const { anchor: anchored, serial } = await phoneAnchor(anchor);
const session = await bindStoredSession(
{
sessionId,
@@ -735,14 +749,15 @@ async function restore(sessionId: string, anchor: TabAnchor): Promise<void> {
agent: meta.agent,
agentSessionId: meta.agentSessionId,
usage: meta.usage,
- url: meta.url,
- title: titleOf(meta) ?? anchor.title,
+ url: serial ? anchored.url : meta.url,
+ title: titleOf(meta) ?? anchored.title,
},
- anchor,
+ anchored,
);
+ if (serial) await patchSession(sessionId, { phone: { serial } });
broadcast({ op: 'items', sessionId, items: buffers.get(sessionId) ?? [] });
- if (meta.url && /^https?:$/.test(safeProtocol(meta.url))) {
+ if (!serial && meta.url && /^https?:$/.test(safeProtocol(meta.url))) {
await invokeForHarness(navigate.name, { url: meta.url }, session.currentTabId).catch(() => undefined);
}
}
@@ -824,6 +839,14 @@ export function serveTabSessions(): void {
});
});
+ onPhoneClosed(() => {
+ void serialized(async () => {
+ for (const session of Object.values(await readTabSessions())) {
+ if (session.phone && session.runId) await append(session.sessionId, notice('error', 'PHONE_GONE: The phone disconnected. Reconnect it and switch Android on again.'));
+ }
+ });
+ });
+
browser.tabs.onReplaced.addListener((added, removed) => {
void serialized(() => remapTab(removed, added));
});
@@ -832,7 +855,7 @@ export function serveTabSessions(): void {
if (changeInfo.title === undefined && changeInfo.url === undefined) return;
void serialized(async () => {
const session = await sessionForTab(tabId);
- if (!session) return;
+ if (!session || session.phone) return;
const patch: Partial<TabSession> = {};
if (tabId === session.mainTabId && tab.title && tab.title !== session.title) patch.title = tab.title;
if (tabId === session.currentTabId && changeInfo.url) {
diff --git a/src/lib/bridge/tab-sessions.ts b/src/lib/bridge/tab-sessions.ts
index be5c420..87effb3 100644
--- a/src/lib/bridge/tab-sessions.ts
+++ b/src/lib/bridge/tab-sessions.ts
@@ -50,6 +50,8 @@ export interface TabSession {
handing?: string[];
/** Set when a schedule opened this conversation; it files to the task's runs, not History. */
task?: TaskTag;
+ /** Set when this conversation lives on the phone tab: its url and title are the phone's, and its tools act on the phone. */
+ phone?: { serial: string };
}
export type TabSessionMap = Record<string, TabSession>;
diff --git a/src/lib/phone/features.ts b/src/lib/phone/features.ts
new file mode 100644
index 0000000..91a84e9
--- /dev/null
+++ b/src/lib/phone/features.ts
@@ -0,0 +1,39 @@
+/** The tools a phone run is offered. A tool not listed here stays off on the phone until someone makes it work there and adds it, with a test. */
+export const PHONE_TOOLS: ReadonlySet<string> = new Set([
+ 'page.navigate',
+ 'page.searchSite',
+ 'page.findSearch',
+ 'page.getPageInfo',
+ 'page.extractText',
+ 'page.waitForElement',
+ 'page.findProgress',
+ 'page.clickElement',
+ 'page.trustedClick',
+ 'page.fillInput',
+ 'page.typeText',
+ 'page.pressKey',
+ 'page.focusInput',
+ 'page.selectOption',
+ 'page.selectText',
+ 'page.submitForm',
+ 'page.scrollTo',
+ 'page.dragElement',
+ 'page.screenshot',
+ 'page.highlightElement',
+ 'page.readTheme',
+ 'page.auditContrast',
+ 'page.applyTheme',
+ 'page.openTab',
+ 'page.switchTab',
+ 'page.closeTab',
+ 'page.switchFrame',
+ 'page.startTimer',
+ 'page.timerStatus',
+ 'page.stopTimer',
+]);
+
+export const PHONE_RESERVED: ReadonlySet<string> = new Set();
+
+export const phoneOffers = (action: string): boolean => PHONE_TOOLS.has(action) || PHONE_RESERVED.has(action);
+
+export const notOnPhone = (action: string): string => `${action} isn’t available on the phone. It works in desktop tabs.`;