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): blocked sites are checked on the phone as on the desktop: every frame on the focused path, the live address after every tool, and phone tabs on a blocked site never listed, matched, named or closed; a new worker or a mirror tab taken elsewhere ends the session; switching phones keeps the first one if the second fails; a reload forgets the entered frame and isolated worlds; a run stays on the phone it started on
Shahriar5048a9e0a468
diff --git a/docs/guide/features/android.md b/docs/guide/features/android.mdindex e5fd578..7c07b83 100644--- a/docs/guide/features/android.md+++ b/docs/guide/features/android.md@@ -81,8 +81,9 @@ phone's tabs, and timers. The differences:| A screenshot is of the desktop tab | A screenshot is of the phone's screen, at the page's size || Tabs are your browser window's tabs | Tabs are the phone's Chrome tabs |-[Blocked sites](blocked-sites.md) are checked against the phone's own address, and-[approvals](../approvals.md) work as they do on a desktop tab.+[Blocked sites](blocked-sites.md) are checked against the phone's own address and its frames, a+phone tab on a blocked site is never shown to the agent, and [approvals](../approvals.md) work as+they do on a desktop tab.**[A-Eye](a-eye.md)** works on the phone tab too. Press its button in the side panel and the phonetab's picture becomes the lens: the element under your pointer is outlined on the phone, and a clickdiff --git a/docs/internals/android.md b/docs/internals/android.mdindex 4a57807..7033c6a 100644--- a/docs/internals/android.md+++ b/docs/internals/android.md@@ -114,6 +114,10 @@ the background over the `browsentic/phone` Port, served by `phone-mirror.ts`:becomes wheel steps, keys become key events, and the bar's back, forward, reload, address and tablist become commands.+The session ends, and the tab stays as the user's, when the phone tab is taken to any other page. A+worker that starts ends a stored session too, because the Bridge let go of the phone with the old+worker's link.+A conversation started on the phone tab is anchored on the phone's page, never on `phone.html`(`phone-conversation.ts`), and its `TabSession` carries `phone: { serial }`. Each run's`RunContext.phone` carries the model, the Android and Chrome versions and the viewport, read when@@ -133,11 +137,14 @@ tab.3. **The phone branch.** Before any desktop check, `phoneRoute` (`phone-invoke.ts`) sees that therun's tab is the phone tab, and `invokeOnPhone` takes over. Host-side tools (the timers) skip thebranch. `invokeOnPhone` checks `PHONE_TOOLS`, checks the blocked-sites list against the **phone- page's** address, releases sealed secrets, and calls the backend. Tab tools (`navigate`,- `openTab`, `switchTab`, `closeTab`) have their own handlers there, over `Target.*` and `Page.*`.+ page's** address as it is now and every frame on the focused path (`openTab`, `switchTab` and+ `closeTab` check the tab they pick instead), releases sealed secrets, and calls the backend. Tab+ tools (`navigate`, `openTab`, `switchTab`, `closeTab`) have their own handlers there, over+ `Target.*` and `Page.*`; a phone tab on a blocked site is never listed, matched or named.4. **Finding the element.** `pageSideOnPhone` (`phone-backend.ts`) asks the page where the elementis. The page side runs in an isolated world named `browsentic`, made with- `Page.createIsolatedWorld` on first use and cached per tab and frame; the bundle `phone-page.js`+ `Page.createIsolatedWorld` on first use and cached per DevTools session and frame until that+ document navigates; the bundle `phone-page.js`(built from `entrypoints/phone-page.ts` and `src/lib/phone/page-api.ts`) is evaluated in it once.It holds the same action code desktop tabs run, under `__browsenticPhone.dispatch`, with noextension API in it. A call that finds its world gone, because the page navigated, makes it again@@ -149,8 +156,9 @@ tab.6. **Bridge → phone.** `daemon.ts` passes the frame to the relay's `command`, which sends it on thephone's WebSocket, through the adb forward, to Chrome. The result comes back the same way as`cdpResult`.-7. **The result.** `invokeOnPhone` checks the landing address against blocked sites again for- tools that navigate, seals any secret in what came back, and the result returns to the agent.+7. **The result.** `invokeOnPhone` checks the phone page and its focused frames against blocked+ sites again after every tool but `switchTab` and `closeTab`, seals any secret in what came back,+ and the result returns to the agent.The phone tab shows the tap as the next screencast frame.## Touch, keys and scrollingdiff --git a/src/extension/entrypoints/background.ts b/src/extension/entrypoints/background.tsindex b574c22..1c31c7d 100644--- a/src/extension/entrypoints/background.ts+++ b/src/extension/entrypoints/background.ts@@ -24,6 +24,7 @@ import { serveLaunchers } from '@/lib/bridge/launchers';import { servePreferences } from '@/lib/bridge/preferences';import { endPhone, openChromeOnPhone, servePhone, startPhone } from '@/lib/bridge/phone';import { servePhoneMirror } from '@/lib/bridge/phone-mirror';+import { servePhoneBackend } from '@/lib/bridge/phone-backend';import { isAgentKind } from '@/lib/agents/catalog';import { isPreferenceChange } from '@/lib/settings/preferences';import {@@ -236,6 +237,7 @@ export default defineBackground(() => {servePreferences();servePhone();servePhoneMirror();+ servePhoneBackend();void syncRail();onWelcome(() => {diff --git a/src/lib/bridge/phone-backend.test.ts b/src/lib/bridge/phone-backend.test.tsindex 166ff2c..5060210 100644--- a/src/lib/bridge/phone-backend.test.ts+++ b/src/lib/bridge/phone-backend.test.ts@@ -10,14 +10,20 @@ const phone = vi.hoisted(() => ({contexts: 0,answer: (_expression: string): unknown => ({ ok: true, data: {} }),goneOnce: false,+ missingOnce: false,viewport: { offsetX: 0, offsetY: 50, clientWidth: 411, clientHeight: 675 },+ events: [] as ((event: unknown) => void)[],}));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.getFrameTree') return success({ frameTree: { frame: { id: 'TOP' } } });+ if (method === 'Page.getFrameTree') {+ return success({ frameTree: { frame: { id: 'TOP', url: 'http://localhost:8080/now' }, childFrames: [{ frame: { id: 'AD', url: 'https://ads.example/slot' } }] } });+ }+ if (method === 'DOM.describeNode') return success({ node: { frameId: 'AD' } });+ if (method === 'Runtime.evaluate' && String(params?.expression).startsWith('__browsenticPhone.frame')) return success({ result: { objectId: 'IFRAME' } });if (method === 'Page.createIsolatedWorld') return success({ executionContextId: ++phone.contexts });if (method === 'Page.getLayoutMetrics') return success({ cssVisualViewport: phone.viewport, cssLayoutViewport: { pageX: 0, pageY: 300, clientWidth: 411, clientHeight: 675 } });if (method === 'Page.captureScreenshot') return success({ data: 'SHOT' });@@ -26,12 +32,16 @@ vi.mock('./socket', () => ({phone.goneOnce = false;return failure('CDP_ERROR', 'Cannot find context with specified id');}+ if (phone.missingOnce) {+ phone.missingOnce = false;+ return success({ exceptionDetails: { text: 'Uncaught', exception: { description: 'ReferenceError: __browsenticPhone is not defined\n at <anonymous>:1:1' } } });+ }return success({ result: { value: await phone.answer(String(params?.expression)) } });}if (method === 'Runtime.evaluate' && String(params?.expression).includes('scrollY')) return success({ result: { value: { scrollX: 0, scrollY: 574 } } });return success({});},- onCdpEvent: () => undefined,+ onCdpEvent: (listener: (event: unknown) => void) => phone.events.push(listener),onPhoneClosed: () => undefined,onDaemonClosed: () => undefined,}));@@ -46,7 +56,8 @@ vi.mock('./phone-mirror', () => ({},}));-const { pageSideOnPhone, pickClip, shotClip } = await import('./phone-backend');+const { pageSideOnPhone, phoneUrls, pickClip, servePhoneBackend, shotClip } = await import('./phone-backend');+servePhoneBackend();const SESSION: PhoneSession = {serial: 'emulator-5554',@@ -64,6 +75,7 @@ beforeEach(() => {fakeBrowser.reset();phone.sent.length = 0;phone.goneOnce = false;+ phone.missingOnce = false;phone.viewport = { offsetX: 0, offsetY: 50, clientWidth: 411, clientHeight: 675 };phone.answer = () => ({ ok: true, data: {} });vi.stubGlobal('fetch', async () => new Response('/* the bundle */'));@@ -86,6 +98,47 @@ describe('page-side tools on the phone', () => {expect((await pageSideOnPhone('page.getPageInfo', {}, SESSION)).ok).toBe(true);expect(methods().filter((method) => method === 'Page.createIsolatedWorld').length - before).toBe(1);});++ test('a stale context that lands somewhere without the bundle makes the world again too', async () => {+ await pageSideOnPhone('page.getPageInfo', {}, SESSION);+ const before = methods().filter((method) => method === 'Page.createIsolatedWorld').length;+ phone.missingOnce = true;+ expect((await pageSideOnPhone('page.getPageInfo', {}, SESSION)).ok).toBe(true);+ expect(methods().filter((method) => method === 'Page.createIsolatedWorld').length - before).toBe(1);+ });+});++const navigated = (frame: { id: string; parentId?: string }) => phone.events.forEach((listener) => listener({ t: 'cdpEvent', serial: 'emulator-5554', method: 'Page.frameNavigated', params: { frame }, sessionId: 'session-1' }));++describe('the phone tab as it is now', () => {+ const leave = () => pageSideOnPhone('page.switchFrame', {}, SESSION);++ test('is the address it last reported, the one it has now, and every frame on the focused path', async () => {+ await leave();+ expect(await phoneUrls(SESSION)).toEqual(['http://localhost:8080/', 'http://localhost:8080/now']);+ expect(await pageSideOnPhone('page.switchFrame', { frame: { selector: 'iframe' } }, SESSION)).toMatchObject({ ok: true, data: { frame: { frameId: 'AD' } } });+ expect(await phoneUrls(SESSION)).toEqual(['http://localhost:8080/', 'http://localhost:8080/now', 'https://ads.example/slot']);+ });++ test('a document that navigates forgets the frame it was in and its isolated worlds, as a desktop tab that loads does', async () => {+ await pageSideOnPhone('page.switchFrame', { frame: { selector: 'iframe' } }, SESSION);+ await pageSideOnPhone('page.getPageInfo', {}, SESSION);+ const worlds = () => methods().filter((method) => method === 'Page.createIsolatedWorld').length;+ const before = worlds();+ navigated({ id: 'TOP' });+ expect(await phoneUrls(SESSION)).toEqual(['http://localhost:8080/', 'http://localhost:8080/now']);+ await pageSideOnPhone('page.getPageInfo', {}, SESSION);+ expect(worlds() - before).toBe(1);+ });++ test('a frame that navigates forgets only its own world', async () => {+ await leave();+ await pageSideOnPhone('page.getPageInfo', {}, SESSION);+ const before = methods().filter((method) => method === 'Page.createIsolatedWorld').length;+ navigated({ id: 'AD', parentId: 'TOP' });+ await pageSideOnPhone('page.getPageInfo', {}, SESSION);+ expect(methods().filter((method) => method === 'Page.createIsolatedWorld').length).toBe(before);+ });});describe('touch on the phone', () => {diff --git a/src/lib/bridge/phone-backend.ts b/src/lib/bridge/phone-backend.tsindex fecdff2..8957676 100644--- a/src/lib/bridge/phone-backend.ts+++ b/src/lib/bridge/phone-backend.ts@@ -10,10 +10,10 @@ import { failure, success, type ActionResult } from '@/lib/actions/protocol';import { PHONE_API } from '@/lib/phone/page-api';import { drag, keyPress, onScreen, tap, typing, wheel, type InputStep, type Point, type Viewport } from '@/lib/phone/touch';import type { EvaluateReply, ToolkitPlace } from './code-toolkit';-import { currentTarget, type PhoneSession } from './phone';+import { currentTarget, onPhoneReset, type PhoneSession } from './phone';import { attachedSession, steerLensFromMirror } from './phone-mirror';import { refusalFor } from './site-guard';-import { sendCdp } from './socket';+import { onCdpEvent, onDaemonClosed, onPhoneClosed, sendCdp, type CdpEvent } from './socket';const BUNDLE = '/phone-page.js';const WORLD = 'browsentic';@@ -41,6 +41,11 @@ interface Here {cdp(method: string, params?: Record<string, unknown>, timeoutMs?: number): Promise<CdpResult>;}+interface FrameTree {+ frame: { id: string; url?: string };+ childFrames?: FrameTree[];+}+let bundle: Promise<string> | null = null;const worlds = new Map<string, number>();const topFrames = new Map<string, string>();@@ -93,9 +98,9 @@ async function topFrame(here: Here): Promise<string> {return id;}-/** The frame a page action runs in: the one `switchFrame` entered, until the tab's address changes. */+/** The frame a page action runs in: the one `switchFrame` entered, until the tab navigates or its address changes. */async function focusedFrame(here: Here): Promise<{ frameId: string; path: string[] }> {- const held = framePaths.get(here.targetId);+ const held = framePaths.get(here.sessionId);const path = held && held.url === here.url ? held.frames : [];return { frameId: path.at(-1) ?? (await topFrame(here)), path };}@@ -118,7 +123,9 @@ async function world(here: Here, frameId: string, fresh: boolean): Promise<numbereturn contextId;}-const contextGone = (message: string) => /Cannot find context|context was destroyed|Execution context/i.test(message);+const CONTEXT_GONE = new RegExp(`Cannot find context|context was destroyed|Execution context|${PHONE_API} is not defined`, 'i');++const contextGone = (message: string) => CONTEXT_GONE.test(message);async function evaluateIn(here: Here, frameId: string, expression: string, options: { timeoutMs?: number; byValue?: boolean } = {}): Promise<ActionResult<unknown>> {const { timeoutMs = CALL_TIMEOUT_MS, byValue = true } = options;@@ -368,7 +375,7 @@ async function switchFrameOn(here: Here, input: unknown): Promise<ActionResult>const { frameId, path } = await focusedFrame(here);if (!frame) {const frames = to === 'parent' ? path.slice(0, -1) : [];- framePaths.set(here.targetId, { url: here.url, frames });+ framePaths.set(here.sessionId, { url: here.url, frames });return success({ frame: frames.length ? { depth: frames.length } : 'top' });}const element = await evaluateIn(here, frameId, `${PHONE_API}.frame(${JSON.stringify(frame)})`, { byValue: false });@@ -376,8 +383,11 @@ async function switchFrameOn(here: Here, input: unknown): Promise<ActionResult>const described = await here.cdp('DOM.describeNode', { objectId: (element.data as { objectId?: string }).objectId });const childFrame = described.ok ? (described.data.node as { frameId?: string } | undefined)?.frameId : undefined;if (!childFrame) return failure('UNSUPPORTED', 'That frame cannot be entered on the phone: Chrome keeps it in another process.');+ const tree = await here.cdp('Page.getFrameTree');+ const refused = await refusalFor(tree.ok ? frameUrls(tree.data.frameTree as FrameTree).get(childFrame) : undefined);+ if (refused) return refused;const frames = [...path, childFrame];- framePaths.set(here.targetId, { url: here.url, frames });+ framePaths.set(here.sessionId, { url: here.url, frames });return success({ frame: { depth: frames.length, frameId: childFrame } });}@@ -419,10 +429,51 @@ export async function phoneToolkitPlace(phone: PhoneSession): Promise<ToolkitPlareturn evaluated.ok ? success(evaluated.data as EvaluateReply) : evaluated;},call: (input) => inPage(here, 'page.runCode', input),- refusal: () => refusalFor(here.url),+ refusal: async () => refusalFor(...(await phoneUrls(phone))),};}+function frameUrls(tree: FrameTree, into = new Map<string, string | undefined>()): Map<string, string | undefined> {+ into.set(tree.frame.id, tree.frame.url);+ for (const child of tree.childFrames ?? []) frameUrls(child, into);+ return into;+}++/** The phone's front tab as it is right now, read from the page and not from the last event: its address, and every frame on the focused path. */+export async function phoneUrls(phone: PhoneSession): Promise<(string | undefined)[]> {+ const here = await hereOn(phone);+ if (!here) return [currentTarget(phone)?.url];+ const tree = await here.cdp('Page.getFrameTree');+ const root = tree.ok ? (tree.data.frameTree as FrameTree | undefined) : undefined;+ if (!root) return [here.url];+ topFrames.set(here.sessionId, root.frame.id);+ const urls = frameUrls(root);+ const { path } = await focusedFrame(here);+ return [here.url, root.frame.url, ...path.map((frameId) => urls.get(frameId))];+}++function forgetNavigated({ method, params, sessionId }: CdpEvent): void {+ if (method !== 'Page.frameNavigated' || !sessionId) return;+ const frame = params.frame as { id: string; parentId?: string };+ if (frame.parentId) return void worlds.delete(`${sessionId}:${frame.id}`);+ framePaths.delete(sessionId);+ for (const key of worlds.keys()) if (key.startsWith(`${sessionId}:`)) worlds.delete(key);+}++function forgetAll(): void {+ worlds.clear();+ topFrames.clear();+ framePaths.clear();+}++/** A document that navigates takes its isolated worlds and the frame `switchFrame` entered with it, as a desktop tab that starts loading does. */+export function servePhoneBackend(): void {+ onCdpEvent(forgetNavigated);+ onPhoneReset(forgetAll);+ onPhoneClosed(forgetAll);+ onDaemonClosed(forgetAll);+}+/** Every page-side tool on the phone: its own code in the page where it can be, real input where the page cannot fake it. */export async function pageSideOnPhone(action: string, input: unknown, phone: PhoneSession): Promise<ActionResult> {const here = await hereOn(phone);diff --git a/src/lib/bridge/phone-invoke.test.ts b/src/lib/bridge/phone-invoke.test.tsindex ea9b8b3..53dbe39 100644--- a/src/lib/bridge/phone-invoke.test.ts+++ b/src/lib/bridge/phone-invoke.test.ts@@ -12,6 +12,8 @@ const phone = vi.hoisted(() => ({location: 'https://news.example/',fronted: [] as string[],followed: [] as string[],+ tree: undefined as { frame: { id: string; url: string }; childFrames?: { frame: { id: string; url: string } }[] } | undefined,+ read: () => undefined as void,}));vi.mock('./socket', () => ({@@ -19,6 +21,14 @@ vi.mock('./socket', () => ({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 === 'Page.getFrameTree') return success(phone.tree ? { frameTree: phone.tree } : {});+ if (method === 'Page.createIsolatedWorld') return success({ executionContextId: 1 });+ if (method === 'DOM.describeNode') return success({ node: { frameId: 'AD' } });+ if (method === 'Runtime.evaluate' && String(params?.expression).startsWith('__browsenticPhone.frame')) return success({ result: { objectId: 'IFRAME' } });+ if (method === 'Runtime.evaluate' && String(params?.expression).startsWith('__browsenticPhone.dispatch')) {+ phone.read();+ return success({ result: { value: { ok: true, data: { text: 'what the page says' } } } });+ }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 } });@@ -51,6 +61,9 @@ beforeEach(async () => {phone.fronted.length = 0;phone.followed.length = 0;phone.location = 'https://news.example/';+ phone.tree = undefined;+ phone.read = () => undefined;+ vi.stubGlobal('fetch', async () => new Response('/* the bundle */'));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({@@ -84,6 +97,13 @@ describe('which calls go to the phone', () => {expect(await phoneRoute(desktopTabId, undefined)).toBeNull();});+ test('a run on one phone is told it is gone once the session moved to another phone', async () => {+ const ensured = await ensureSessionForTab({ tabId: mirrorTabId });+ if (!ensured.ok) throw new Error('no session');+ await patchSession(ensured.session.sessionId, { runId: 'run-4', phone: { serial: 'R5CT1234567' } });+ expect(await phoneRoute(mirrorTabId, 'run-4')).toBe('gone');+ });+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');@@ -143,12 +163,44 @@ describe('a tool on the phone', () => {expect(await landed).toMatchObject({ ok: false, error: { code: 'SITE_BLOCKED' } });});+ test('a phone page that moved on since the last event is judged by where it is now', async () => {+ await block('bank.example');+ phone.tree = { frame: { id: HOME, url: 'https://bank.example/login' } };+ expect(await invokeOnPhone('page.getPageInfo', {}, await route())).toMatchObject({ ok: false, error: { code: 'SITE_BLOCKED' } });+ expect(phone.sent.map(({ method }) => method)).toEqual(['Page.getFrameTree']);+ });++ test('a blocked frame is never entered, and one that becomes blocked refuses everything after', async () => {+ const enter = async () => invokeOnPhone('page.switchFrame', { frame: { selector: 'iframe' } }, await route());+ phone.tree = { frame: { id: HOME, url: 'https://news.example/' }, childFrames: [{ frame: { id: 'AD', url: 'https://ads.example/slot' } }] };+ await block('ads.example');+ expect(await enter()).toMatchObject({ ok: false, error: { code: 'SITE_BLOCKED' } });+ expect(await invokeOnPhone('page.extractText', {}, await route())).toMatchObject({ ok: true });++ await block();+ expect(await enter()).toMatchObject({ ok: true });+ await block('ads.example');+ const before = phone.sent.length;+ expect(await invokeOnPhone('page.extractText', {}, await route())).toMatchObject({ ok: false, error: { code: 'SITE_BLOCKED' } });+ expect(phone.sent.slice(before).some(({ params }) => String(params?.expression).startsWith('__browsenticPhone.dispatch'))).toBe(false);++ await block();+ expect(await invokeOnPhone('page.switchFrame', {}, await route())).toMatchObject({ ok: true });+ });++ test('a read that ends on a blocked page sends nothing back', async () => {+ await block('bank.example');+ phone.tree = { frame: { id: HOME, url: 'https://news.example/' } };+ phone.read = () => void (phone.tree = { frame: { id: HOME, url: 'https://bank.example/' } });+ expect(await invokeOnPhone('page.extractText', {}, await route())).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/' } });+ expect(phone.sent.find(({ method }) => method === 'Page.navigate')).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 () => {@@ -160,6 +212,26 @@ describe('a tool on the phone', () => {});});+ test('a tab on a blocked site is never listed, matched or closed, as on desktop', async () => {+ await block('shop.example');+ expect(await invokeOnPhone('page.switchTab', {}, await route())).toEqual({+ ok: true,+ data: { tabs: [{ tabId: 1, url: 'https://news.example/', title: 'News', active: true }], hidden: 1 },+ });+ const matched = await invokeOnPhone('page.switchTab', { match: 'shop' }, await route());+ expect(matched).toMatchObject({ ok: false, error: { code: 'INVALID_TARGET' } });+ expect(JSON.stringify(matched)).not.toContain('shop.example');+ expect(await invokeOnPhone('page.closeTab', { tabId: 2 }, await route())).toMatchObject({ ok: false, error: { code: 'SITE_BLOCKED' } });+ expect(phone.sent.map(({ method }) => method)).not.toContain('Target.closeTarget');+ });++ test('a blocked phone page still lets the agent switch away or open another tab', async () => {+ await block('news.example');+ expect(await invokeOnPhone('page.switchTab', { tabId: 2 }, await route())).toMatchObject({ ok: true, data: { activeTabId: 2 } });+ expect(await invokeOnPhone('page.openTab', { url: 'https://docs.example/', active: false }, await route())).toMatchObject({ ok: true });+ expect(await invokeOnPhone('page.openTab', { url: 'https://news.example/' }, await route())).toMatchObject({ ok: false, error: { code: 'SITE_BLOCKED' } });+ });+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 } });diff --git a/src/lib/bridge/phone-invoke.ts b/src/lib/bridge/phone-invoke.tsindex b4d701c..bdd69c4 100644--- a/src/lib/bridge/phone-invoke.ts+++ b/src/lib/bridge/phone-invoke.ts@@ -10,23 +10,23 @@ 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 type { PhoneTarget } from '@/lib/phone/types';import { currentTarget, isLive, readPhone, targetForNumber, updatePhone, numbered, type PhoneSession } from './phone';import { installToolkit, runToolkit, tabPlace, type ToolkitPlace } from './code-toolkit';-import { hereOn, pageSideOnPhone, phoneToolkitPlace, waitForLoad } from './phone-backend';+import { hereOn, pageSideOnPhone, phoneToolkitPlace, phoneUrls, waitForLoad } from './phone-backend';import { attachedSession, bringToFront, followTarget } from './phone-mirror';import { releaseForAction, sealForPage } from './secret-vault';-import { refusalFor } from './site-guard';+import { refusalFor, siteCheck } 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.';-/** 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']);+/** These pick another phone tab to land on or close, and check that tab where they pick it. */+const PICKS_ITS_TAB = new Set([openTab, switchTab, closeTab].map((action) => action.name));type PhoneBackend = (action: string, input: unknown, phone: PhoneSession) => Promise<ActionResult>;-/*** 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.@@ -34,7 +34,7 @@ type PhoneBackend = (action: string, input: unknown, phone: PhoneSession) => Proexport 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 (owner) return owner.phone ? (phone && isLive(phone) && phone.serial === owner.phone.serial ? 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;@@ -47,8 +47,7 @@ export async function invokeOnPhone(action: string, input: unknown, route: Phoneif (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));+ const refused = await guardPhone(action, input, route);if (refused) return refused;const release = await releaseForAction(action, input);@@ -56,14 +55,33 @@ export async function invokeOnPhone(action: string, input: unknown, route: Phoneif (release.unresolved.length) return failure('SECRET_EXPIRED', EXPIRED_MESSAGE);const result = await (TAB_TOOLS[action] ?? pageSideOnPhone)(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));+ const after = (await readPhone()) ?? route;+ const landed = await guardPhoneLanding(action, result, after);+ if (landed) return landed;+ const { value } = await sealForPage(result, hostOf(currentTarget(after)?.url));return value;}+/** The phone's blocked-sites gate, as `guardTarget` is the desktop's: the tab's address, every frame on the focused path, and wherever the action would send the phone. */+async function guardPhone(action: string, input: unknown, phone: PhoneSession): Promise<ActionResult | null> {+ const here = currentTarget(phone)?.url;+ const destinations = destinationsOf(action, input, here);+ if (PICKS_ITS_TAB.has(action)) return refusalFor(...destinations);+ return (await refusalFor(here, ...destinations)) ?? refusalFor(...(await phoneUrls(phone)));+}++/** A redirect, a tap or a slow read can leave the phone somewhere blocked; nothing read there goes back. */+async function guardPhoneLanding(action: string, result: ActionResult, phone: PhoneSession): Promise<ActionResult | null> {+ if (!result.ok || action === switchTab.name || action === closeTab.name) return null;+ const reported = result.data as { tabId?: unknown; finalUrl?: unknown; landedOn?: unknown } | undefined;+ const reportedUrls = [textOf(reported?.finalUrl), textOf(reported?.landedOn)];+ if (action === openTab.name) {+ const opened = typeof reported?.tabId === 'number' ? targetForNumber(phone, reported.tabId) : undefined;+ return refusalFor(phone.targets.find((target) => target.targetId === opened)?.url, ...reportedUrls);+ }+ return refusalFor(...(await phoneUrls(phone)), ...reportedUrls);+}+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 [];@@ -174,20 +192,42 @@ async function openPhoneTab(_action: string, input: unknown, phone: PhoneSessionreturn 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 }));+type Usable = (target: PhoneTarget) => boolean;++/** A phone tab on a blocked site is treated as a desktop one is: never listed, never matched, never named. */+async function usableTargets(): Promise<Usable> {+ const blocked = await siteCheck();+ return (target) => !blocked(target.url);+}++const describeTabs = (phone: PhoneSession, usable: Usable) =>+ phone.targets+ .filter(usable)+ .map((target) => ({ tabId: phone.tabNumbers?.[target.targetId], url: target.url, title: target.title, active: target.targetId === phone.activeTargetId }));++function inventory(phone: PhoneSession, usable: Usable) {+ const tabs = describeTabs(phone, usable);+ const hidden = phone.targets.length - tabs.length;+ return { tabs, ...(hidden ? { hidden } : {}) };+}++const noMatch = (phone: PhoneSession, usable: Usable) => failure('INVALID_TARGET', `No phone tab matches. The phone's tabs: ${JSON.stringify(describeTabs(phone, usable))}`);++function pickTarget(phone: PhoneSession, { tabId, match }: { tabId?: number; match?: string }, usable: Usable): PhoneTarget | undefined {+ if (tabId != null) return phone.targets.find((target) => target.targetId === targetForNumber(phone, tabId));+ if (match == null) return phone.targets.find((target) => target.targetId === phone.activeTargetId);+ const needle = match.toLowerCase();+ return phone.targets.filter(usable).find((target) => `${target.title} ${target.url}`.toLowerCase().includes(needle));+}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 usable = await usableTargets();+ if (tabId == null && match == null) return success(inventory(phone, usable));+ const target = pickTarget(phone, { tabId, match }, usable);+ if (!target) return noMatch(phone, usable);const refused = await refusalFor(target.url);if (refused) return refused;await bringToFront(phone.serial, target.targetId);@@ -199,14 +239,11 @@ async function closePhoneTab(_action: string, input: unknown, phone: PhoneSessioconst 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))}`);+ const usable = await usableTargets();+ const target = pickTarget(phone, { tabId, match }, usable);+ if (!target) return noMatch(phone, usable);+ const refused = await refusalFor(target.url);+ if (refused) return refused;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;diff --git a/src/lib/bridge/phone.test.ts b/src/lib/bridge/phone.test.tsindex 6caedf7..dd28774 100644--- a/src/lib/bridge/phone.test.ts+++ b/src/lib/bridge/phone.test.ts@@ -20,7 +20,7 @@ vi.mock('./socket', () => ({onPhoneClosed: (listener: (serial: string, reason: PhoneClosedReason) => void) => socket.phoneClosed.push(listener),}));-const { endPhone, openChromeOnPhone, readPhone, servePhone, startPhone } = await import('./phone');+const { endPhone, leftMirror, openChromeOnPhone, readPhone, servePhone, startPhone, updatePhone } = await import('./phone');const SERIAL = 'emulator-5554';const OPENED: PhoneOpened = {@@ -130,6 +130,60 @@ describe('the phone session', () => {expect(notify).toHaveBeenCalledTimes(1);});+ test('Reconnect keeps the numbers the phone’s tabs already had in this conversation', async () => {+ await startPhone(SERIAL);+ await updatePhone((session) => ({ ...session, tabNumbers: { ['A'.repeat(32)]: 3 } }));+ socket.phoneClosed.forEach((listener) => listener(SERIAL, 'unplugged'));+ await settle();+ await startPhone(SERIAL);+ expect((await readPhone())?.tabNumbers).toEqual({ ['A'.repeat(32)]: 3 });+ });++ test('moving to another phone that cannot be opened leaves the first one on', async () => {+ await startPhone(SERIAL);+ socket.openPhone.mockResolvedValueOnce(failure('NOT_OWNER', 'Another browser is driving this phone.'));+ expect(await startPhone('R5CT1234567')).toMatchObject({ ok: false, error: { code: 'NOT_OWNER' } });+ expect(socket.closePhone).not.toHaveBeenCalled();+ expect(await readPhone()).toMatchObject({ serial: SERIAL });+ expect((await readPhone())?.ended).toBeUndefined();+ });++ test('moving to another phone closes the first only once the second is open, in the same tab', async () => {+ await startPhone(SERIAL);+ const { mirrorTabId } = (await readPhone())!;+ expect((await startPhone('R5CT1234567')).ok).toBe(true);+ expect(socket.closePhone).toHaveBeenCalledWith(SERIAL);+ expect(socket.openPhone.mock.invocationCallOrder[1]).toBeLessThan(socket.closePhone.mock.invocationCallOrder[0]);+ expect(await readPhone()).toMatchObject({ serial: 'R5CT1234567', mirrorTabId });+ });++ test('a worker that starts with a session in storage ends it: the Bridge let go of the phone with the old worker’s link', async () => {+ await startPhone(SERIAL);+ servePhone();+ await settle();+ expect((await readPhone())?.ended?.reason).toBe('bridge-gone');+ });++ test('a mirror tab the user takes to another page ends the session and keeps the tab', async () => {+ await startPhone(SERIAL);+ const { mirrorTabId } = (await readPhone())!;+ const mirror = await fakeBrowser.tabs.get(mirrorTabId);+ await fakeBrowser.tabs.onUpdated.trigger(mirrorTabId, { url: 'https://mail.example/' }, { ...mirror, url: 'https://mail.example/' });+ await settle();+ expect(await readPhone()).toBeNull();+ expect(socket.closePhone).toHaveBeenCalledWith(SERIAL);+ expect((await fakeBrowser.tabs.get(mirrorTabId)).id).toBe(mirrorTabId);+ });++ test('any other page counts as leaving the mirror, never the mirror page itself or a blank tab on the way', () => {+ expect(leftMirror(undefined)).toBe(false);+ expect(leftMirror(fakeBrowser.runtime.getURL('/phone.html'))).toBe(false);+ expect(leftMirror('about:blank')).toBe(false);+ expect(leftMirror('https://mail.example/')).toBe(true);+ expect(leftMirror('chrome://newtab/')).toBe(true);+ expect(leftMirror('file:///Users/me/notes.html')).toBe(true);+ });+test('any other refusal opens nothing and says why', async () => {socket.openPhone.mockResolvedValueOnce(failure('NOT_OWNER', 'Another browser is driving this phone.'));expect(await startPhone(SERIAL)).toMatchObject({ ok: false, error: { code: 'NOT_OWNER' } });diff --git a/src/lib/bridge/phone.ts b/src/lib/bridge/phone.tsindex 1afd3c5..77363d8 100644--- a/src/lib/bridge/phone.ts+++ b/src/lib/bridge/phone.ts@@ -104,16 +104,16 @@ export function startPhone(serial: string, windowId?: number): Promise<ActionResawait showTab(held.mirrorTabId, held.windowId);return success(held);}- if (held && !held.ended) closePhone(held.serial);- reset();-const opened = await openPhone(serial);if (!opened.ok && opened.error.code !== 'CHROME_NOT_RUNNING') return opened;+ if (held && !held.ended) closePhone(held.serial);+ reset();const reusable = held && (await tabExists(held.mirrorTabId)) ? held : null;const mirror = reusable ? await showTab(reusable.mirrorTabId, reusable.windowId) : await openMirror(windowId);if (!mirror?.id) {if (opened.ok) closePhone(serial);+ await writePhone(null);return failure('BRIDGE_ERROR', 'The phone tab could not be opened.');}const session: PhoneSession = numbered({@@ -121,6 +121,7 @@ export function startPhone(serial: string, windowId?: number): Promise<ActionResmirrorTabId: mirror.id,windowId: mirror.windowId ?? windowId ?? browser.windows.WINDOW_ID_CURRENT,openedAt: Date.now(),+ tabNumbers: reusable?.serial === serial ? reusable.tabNumbers : undefined,...opening(opened),...(await describedPhone(serial, opened)),});@@ -136,10 +137,7 @@ export function endPhone(reason: PhoneEndReason): Promise<void> {const held = await readPhone();if (!held) return;if (reason === 'closed') {- if (!held.ended) closePhone(held.serial);- reset();- await writePhone(null);- await clearNotification();+ await dropPhone(held);if (await tabExists(held.mirrorTabId)) await browser.tabs.remove(held.mirrorTabId).catch(() => undefined);return;}@@ -148,6 +146,26 @@ export function endPhone(reason: PhoneEndReason): Promise<void> {});}+async function dropPhone(held: PhoneSession): Promise<void> {+ if (!held.ended) closePhone(held.serial);+ reset();+ await writePhone(null);+ await clearNotification();+}++const mirrorUrl = () => (browser.runtime.getURL as (path: string) => string)(PHONE_PAGE);++/** Any page but the mirror in the mirror's tab: the user took the tab somewhere else. A tab being made reports about:blank on its way in. */+export const leftMirror = (url: string | undefined): boolean => !!url && url !== 'about:blank' && !url.startsWith(mirrorUrl());++/** The mirror tab went to another page: the session ends, and the tab, now the user's, stays. */+function mirrorLeft(tabId: number): Promise<void> {+ return locked(async () => {+ const held = await readPhone();+ if (held?.mirrorTabId === tabId) await dropPhone(held);+ });+}+/** Asks Chrome on the phone to open, then tries the session again: what the notification's button and the mirror's button do. */export function openChromeOnPhone(): Promise<ActionResult<PhoneSession>> {return locked(async () => {@@ -164,11 +182,16 @@ export function openChromeOnPhone(): Promise<ActionResult<PhoneSession>> {}export function servePhone(): void {+ // A worker that starts has a new link, and the Bridge let go of the phone with the old one.+ void endPhone('bridge-gone');browser.tabs.onRemoved.addListener((tabId) => {void readPhone().then((held) => {if (held?.mirrorTabId === tabId) void endPhone('closed');});});+ browser.tabs.onUpdated.addListener((tabId, change) => {+ if (leftMirror(change.url)) void mirrorLeft(tabId);+ });onPhoneClosed((serial, reason) => {void readPhone().then((held) => {if (held?.serial === serial) void endPhone(reason);@@ -192,7 +215,7 @@ async function describedPhone(serial: string, opened: ActionResult<PhoneOpened>)async function openMirror(windowId?: number) {const [current] = await browser.tabs.query(windowId === undefined ? { active: true, lastFocusedWindow: true } : { active: true, windowId });return browser.tabs.create({- url: (browser.runtime.getURL as (path: string) => string)(PHONE_PAGE),+ url: mirrorUrl(),windowId: current?.windowId ?? windowId,index: current ? current.index + 1 : undefined,openerTabId: current?.id,diff --git a/src/lib/bridge/run-port.ts b/src/lib/bridge/run-port.tsindex d8795c0..7e377e9 100644--- a/src/lib/bridge/run-port.ts+++ b/src/lib/bridge/run-port.ts@@ -19,6 +19,7 @@ import { navigate } from '@/lib/actions/page/navigate';import { autoRunReady, syncAutoRuns } from './auto-run';import { onToolOffer, runSavedTool, toolkitCode, type ToolOffer } from './code-toolkit';import { toolkitPlaceFor } from './phone-invoke';+import { leftMirror } from './phone';import { CONTEXT_COMMAND, isContextCommand, type ContextBreakdown } from './commands';import { listSavedTools, withoutCode, type SavedToolMeta } from './saved-tools';import { dropTool, keepTool, switchAutoRun } from './tool-registry';@@ -858,8 +859,8 @@ export function serveTabSessions(): void {if (changeInfo.title === undefined && changeInfo.url === undefined) return;void serialized(async () => {const session = await sessionForTab(tabId);- if (!session || session.phone) return;- const patch: Partial<TabSession> = {};+ if (!session || (session.phone && !leftMirror(changeInfo.url))) return;+ const patch: Partial<TabSession> = session.phone ? { phone: undefined } : {};if (tabId === session.mainTabId && tab.title && tab.title !== session.title) patch.title = tab.title;if (tabId === session.currentTabId && changeInfo.url) {patch.url = changeInfo.url;