Skip to content

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

feat(android): the Mac app gets an Android tab after Browsers with the same checklist the CLI prints, worded once in src/lib/phone/checks.ts; it watches for phones only while the tab is open, and a problem's fix is now only ever something to copy

Shahriar9167cf6bdf57
diff --git a/docs/guide/mac-app.md b/docs/guide/mac-app.md
index 067959a..0fd7a6a 100644
--- a/docs/guide/mac-app.md
+++ b/docs/guide/mac-app.md
@@ -73,7 +73,7 @@ the folder holds a newer build than the browser has loaded.
## The window
-The tabs float at the top; ⌘1 to ⌘8 switch between them.
+The tabs float at the top; ⌘1 to ⌘9 switch between them.
![Browsentic Bridge running, with one row per browser: Chrome connected from the Chrome Web Store, Brave from an unpacked folder, and Edge and Firefox with an add button each.](../assets/mac-app/overview.webp "Overview")
![The Get a pairing code button, and two paired browsers, each with where its extension came from.](../assets/mac-app/browsers.webp "Browsers")
@@ -86,6 +86,7 @@ The tabs float at the top; ⌘1 to ⌘8 switch between them.
| --- | --- |
| **Overview** | Turn Browsentic Bridge on and off with the power button, restart it, see its address and version. One row per browser: where its extension comes from, whether it is connected, and a button that adds it from the store. The unpacked folder sits behind **Load it unpacked instead** |
| **Browsers** | Get a [pairing code](pair.md) with a live countdown, see every paired browser and the store its extension came from, unpair one or all |
+| **Android** | Whether a phone is ready to drive from the side panel: adb, the phone, USB debugging, Chrome, Chrome open and the screen, one row each, the same checks `browsentic android` prints. A row that fails says what to do, with **Open Chrome on the phone**, **Get Chrome** or the adb install command to copy. **Set up your phone** has the steps. The Bridge looks for phones only while this tab is open |
| **Agents** | See which agent CLIs are ready, [switch](agents.md) between them, pick a model, install a missing one, or let Browsentic fix what one still needs |
| **Skills** | Every [skill](features/skills.md) the router can see and which folder it came from |
| **Activity** | Your standing [approvals](approvals.md), forgettable per site, and the downloads agents captured |
diff --git a/src/daemon/android/readiness.test.ts b/src/daemon/android/readiness.test.ts
index a5ed5d0..69228e9 100644
--- a/src/daemon/android/readiness.test.ts
+++ b/src/daemon/android/readiness.test.ts
@@ -42,25 +42,25 @@ describe('readiness', () => {
]);
});
- const rows: [string, Observed, AndroidProblemCode, Partial<{ ready: boolean; fix: RegExp; action: string }>?][] = [
- ['switched off in config.json', observed([], { enabled: false, adb: undefined }), 'ANDROID_OFF', { fix: /"enabled": true/ }],
- ['no adb on macOS', observed([], { adb: null }), 'ADB_MISSING', { fix: /^brew install --cask android-platform-tools$/ }],
- ['no adb on Windows', observed([], { adb: null, platform: 'win32' }), 'ADB_MISSING', { fix: /^winget install Google\.PlatformTools$/ }],
- ['no adb on Linux', observed([], { adb: null, platform: 'linux' }), 'ADB_MISSING', { fix: /adb/ }],
- ['an adb that does not run', observed([], { adb: { path: ADB.path, broken: 'Bad CPU type in executable' } }), 'ADB_BROKEN'],
+ const rows: [string, Observed, AndroidProblemCode, Partial<{ ready: boolean; says: RegExp; fix: string; action: string }>?][] = [
+ ['switched off in config.json', observed([], { enabled: false, adb: undefined }), 'ANDROID_OFF', { says: /config\.json/, fix: '"android": { "enabled": true }' }],
+ ['no adb on macOS', observed([], { adb: null }), 'ADB_MISSING', { fix: 'brew install --cask android-platform-tools' }],
+ ['no adb on Windows', observed([], { adb: null, platform: 'win32' }), 'ADB_MISSING', { fix: 'winget install Google.PlatformTools' }],
+ ['no adb on Linux', observed([], { adb: null, platform: 'linux' }), 'ADB_MISSING', { fix: 'sudo apt install adb' }],
+ ['an adb that does not run', observed([], { adb: { path: ADB.path, broken: 'Bad CPU type in executable' } }), 'ADB_BROKEN', { says: /Bad CPU type in executable\. Reinstall/ }],
['adb\'s server that will not start', observed([], { serverError: 'start-server did not start adb\'s server' }), 'ADB_BROKEN'],
- ['adb with no phone', observed([]), 'NO_DEVICE', { fix: /USB debugging/ }],
- ['a phone waiting for Allow', observed([phone({ state: 'unauthorized', adbState: 'unauthorized' })]), 'DEVICE_UNAUTHORIZED', { fix: /tap Allow/ }],
- ['a phone offline on USB', observed([phone({ state: 'offline', adbState: 'offline' })]), 'DEVICE_OFFLINE', { fix: /plug it in again/ }],
+ ['adb with no phone', observed([]), 'NO_DEVICE', { says: /USB debugging/ }],
+ ['a phone waiting for Allow', observed([phone({ state: 'unauthorized', adbState: 'unauthorized' })]), 'DEVICE_UNAUTHORIZED', { says: /tap Allow/ }],
+ ['a phone offline on USB', observed([phone({ state: 'offline', adbState: 'offline' })]), 'DEVICE_OFFLINE', { says: /plug it in again/ }],
[
'a phone offline over Wi-Fi',
observed([phone({ serial: '192.168.1.20:5555', transport: 'wifi', state: 'offline', adbState: 'offline' })]),
'DEVICE_OFFLINE',
- { fix: /^adb connect 192\.168\.1\.20:5555$/ },
+ { fix: 'adb connect 192.168.1.20:5555' },
],
- ['a phone in recovery', observed([phone({ state: 'other', adbState: 'recovery' })]), 'DEVICE_OFFLINE', { fix: /Restart the phone/ }],
+ ['a phone in recovery', observed([phone({ state: 'other', adbState: 'recovery' })]), 'DEVICE_OFFLINE', { says: /recovery mode\. Restart it normally/ }],
['a phone that stopped answering', observed([phone({}, null)]), 'DEVICE_OFFLINE'],
- ['Linux without udev rules', observed([phone({ state: 'no-permissions', adbState: 'no permissions' })], { platform: 'linux' }), 'NO_PERMISSIONS', { fix: /udev/ }],
+ ['Linux without udev rules', observed([phone({ state: 'no-permissions', adbState: 'no permissions' })], { platform: 'linux' }), 'NO_PERMISSIONS', { says: /udev/, fix: 'sudo apt install android-sdk-platform-tools-common' }],
['a phone still booting', observed([phone({}, { ...open, booted: false })]), 'DEVICE_BOOTING'],
['no Chrome on the phone', observed([phone({}, withChrome({ installed: false, version: undefined, running: false, debuggable: false }))]), 'CHROME_MISSING', { action: 'installChrome' }],
['Chrome closed', observed([phone({}, withChrome({ running: false, debuggable: false }))]), 'CHROME_NOT_RUNNING', { action: 'launchChrome' }],
@@ -77,9 +77,10 @@ describe('readiness', () => {
const state = judge(seen);
expect(state.problem?.code).toBe(code);
expect(state.ready).toBe(expected.ready ?? false);
- if (expected.fix) expect(state.problem?.fix).toMatch(expected.fix);
+ if (expected.says) expect(state.problem?.message).toMatch(expected.says);
+ expect(state.problem?.fix).toBe(expected.fix ?? (code === 'ADB_BROKEN' ? '"android": { "adb": "/path/to/adb" }' : undefined));
if (expected.action) expect(state.problem?.action).toBe(expected.action);
- expect(state.problem?.message).not.toMatch(/—/);
+ expect(state.problem?.message).not.toMatch(/\u2014/);
});
test('adb problems sit on adb as well as at the top', () => {
diff --git a/src/daemon/android/readiness.ts b/src/daemon/android/readiness.ts
index 5e602fe..80dba0a 100644
--- a/src/daemon/android/readiness.ts
+++ b/src/daemon/android/readiness.ts
@@ -22,11 +22,12 @@ export interface Observed {
session?: AndroidState['session'];
}
+/** `message` says what is wrong and what to do; `fix`, when there is one, is only ever something to copy: a command or a line of config. */
export const PROBLEMS = {
off: (): AndroidProblem => ({
code: 'ANDROID_OFF',
- message: 'Android is switched off for this computer.',
- fix: 'Set "android": { "enabled": true } in ~/.browsentic/config.json',
+ message: 'Android is switched off in ~/.browsentic/config.json.',
+ fix: '"android": { "enabled": true }',
}),
adbMissing: (platform: NodeJS.Platform): AndroidProblem => ({
code: 'ADB_MISSING',
@@ -35,41 +36,36 @@ export const PROBLEMS = {
}),
adbBroken: (path: string, why: string): AndroidProblem => ({
code: 'ADB_BROKEN',
- message: `adb at ${path} does not run: ${why}`,
- fix: `Reinstall platform-tools, or set "android": { "adb": "<path to a working adb>" } in ~/.browsentic/config.json`,
+ message: `adb at ${path} does not run: ${why}. Reinstall platform-tools, or name a working adb in ~/.browsentic/config.json.`,
+ fix: '"android": { "adb": "/path/to/adb" }',
}),
noDevice: (platform: NodeJS.Platform): AndroidProblem => ({
code: 'NO_DEVICE',
message:
platform === 'win32'
- ? 'No Android phone is connected. On Windows the phone also needs its USB driver, from its maker or Google, before adb can see it.'
- : 'No Android phone is connected.',
- fix: 'Turn on USB debugging on the phone and connect it with a USB cable. Run "browsentic android" for the steps.',
+ ? 'No Android phone is connected. Turn on USB debugging on the phone and connect it with a USB cable. On Windows the phone also needs its USB driver, from its maker or Google, before adb can see it.'
+ : 'No Android phone is connected. Turn on USB debugging on the phone and connect it with a USB cable.',
}),
unauthorized: (): AndroidProblem => ({
code: 'DEVICE_UNAUTHORIZED',
- message: 'The phone has not allowed this computer yet.',
- fix: 'Unlock your phone and tap Allow on the USB debugging prompt. If no prompt shows, unplug the phone and plug it in again.',
- }),
- offline: (device: TrackedDevice): AndroidProblem => ({
- code: 'DEVICE_OFFLINE',
- message: 'The phone is connected but not answering adb.',
- fix: device.transport === 'wifi' ? `adb connect ${device.serial}` : 'Unplug the phone and plug it in again.',
+ message: 'The phone has not allowed this computer yet. Unlock it and tap Allow on the USB debugging prompt. If no prompt shows, unplug it and plug it in again.',
}),
+ offline: (device: TrackedDevice): AndroidProblem =>
+ device.transport === 'wifi'
+ ? { code: 'DEVICE_OFFLINE', message: 'The phone is connected over Wi-Fi but not answering adb. Connect to it again.', fix: `adb connect ${device.serial}` }
+ : { code: 'DEVICE_OFFLINE', message: 'The phone is connected but not answering adb. Unplug it and plug it in again.' },
otherMode: (device: TrackedDevice): AndroidProblem => ({
code: 'DEVICE_OFFLINE',
- message: `The phone is in ${device.adbState} mode.`,
- fix: 'Restart the phone normally.',
+ message: `The phone is in ${device.adbState} mode. Restart it normally.`,
}),
silent: (): AndroidProblem => ({
code: 'DEVICE_OFFLINE',
- message: 'The phone stopped answering adb.',
- fix: 'Unlock the phone. If that does not help, unplug it and plug it in again.',
+ message: 'The phone stopped answering adb. Unlock it, or unplug it and plug it in again.',
}),
noPermissions: (): AndroidProblem => ({
code: 'NO_PERMISSIONS',
- message: 'This computer is not allowed to open the phone\'s USB connection.',
- fix: 'Add udev rules for Android phones (the android-sdk-platform-tools-common package has them), then plug the phone in again.',
+ message: "This computer is not allowed to open the phone's USB connection. Add udev rules for Android phones, then plug the phone in again.",
+ fix: 'sudo apt install android-sdk-platform-tools-common',
}),
booting: (): AndroidProblem => ({
code: 'DEVICE_BOOTING',
@@ -77,20 +73,17 @@ export const PROBLEMS = {
}),
chromeMissing: (): AndroidProblem => ({
code: 'CHROME_MISSING',
- message: 'Chrome is not installed on the phone.',
- fix: 'Install Google Chrome from the Play Store on the phone.',
+ message: 'Chrome is not installed on the phone. Install Google Chrome from the Play Store.',
action: 'installChrome',
}),
chromeClosed: (): AndroidProblem => ({
code: 'CHROME_NOT_RUNNING',
message: 'Chrome is not open on the phone.',
- fix: 'Open Chrome on the phone.',
action: 'launchChrome',
}),
screenOff: (): AndroidProblem => ({
code: 'SCREEN_OFF',
- message: 'The phone\'s screen is off, so Chrome is not drawing the page.',
- fix: 'Unlock the phone.',
+ message: "The phone's screen is off, so Chrome is not drawing the page. Unlock the phone.",
}),
} as const;
diff --git a/src/daemon/android/report.test.ts b/src/daemon/android/report.test.ts
index e2838aa..638f00b 100644
--- a/src/daemon/android/report.test.ts
+++ b/src/daemon/android/report.test.ts
@@ -59,26 +59,26 @@ describe('browsentic android', () => {
test('no phone: the phone row fails, then the setup steps, with the Wi-Fi one marked for Android 11', () => {
const lines = androidLines(STATES.noDevice);
- expect(lines[1]).toBe('✗ Phone No Android phone is connected.');
+ expect(lines[1]).toBe('✗ Phone No Android phone is connected. Turn on USB debugging on the phone and connect it with a USB cable.');
expect(lines.find((line) => line.startsWith(' 4. '))).toMatch(/^ {2}4\. Or connect over Wi-Fi \(Android 11 or later\): /);
});
test('waiting for Allow: the USB debugging row fails with what to tap', () => {
expect(androidLines(STATES.unauthorized).slice(1, 4)).toEqual([
'✓ Phone Android phone, USB (R5CT1234567)',
- '✗ USB debugging The phone has not allowed this computer yet.',
- ' Unlock your phone and tap Allow on the USB debugging prompt. If no prompt shows, unplug the phone and plug it in again.',
+ '✗ USB debugging The phone has not allowed this computer yet. Unlock it and tap Allow on the USB debugging prompt. If no prompt shows, unplug it and plug it in again.',
+ '',
]);
});
const failingRows: [string, AndroidState, string][] = [
- ['offline', seen([phone(null, { ...emulator, state: 'offline', adbState: 'offline' })]), '✗ Phone sdk gphone16k arm64, USB (emulator-5554): The phone is connected but not answering adb.'],
- ['silent', seen([phone(null)]), '✗ Phone sdk gphone16k arm64, USB (emulator-5554): The phone stopped answering adb.'],
+ ['offline', seen([phone(null, { ...emulator, state: 'offline', adbState: 'offline' })]), '✗ Phone sdk gphone16k arm64, USB (emulator-5554): The phone is connected but not answering adb. Unplug it and plug it in again.'],
+ ['silent', seen([phone(null)]), '✗ Phone sdk gphone16k arm64, USB (emulator-5554): The phone stopped answering adb. Unlock it, or unplug it and plug it in again.'],
['booting', seen([phone({ ...open, booted: false })]), '✗ Phone sdk_gphone16k_arm64, Android 17, USB (emulator-5554): The phone is still starting up.'],
- ['no udev rules', seen([phone(null, { ...emulator, state: 'no-permissions', adbState: 'no permissions' })], { platform: 'linux' }), "✗ Phone sdk gphone16k arm64, USB (emulator-5554): This computer is not allowed to open the phone's USB connection."],
- ['no Chrome', seen([phone(chrome({ installed: false, version: undefined, running: false, debuggable: false }))]), '✗ Chrome Chrome is not installed on the phone.'],
+ ['no udev rules', seen([phone(null, { ...emulator, state: 'no-permissions', adbState: 'no permissions' })], { platform: 'linux' }), "✗ Phone sdk gphone16k arm64, USB (emulator-5554): This computer is not allowed to open the phone's USB connection. Add udev rules for Android phones, then plug the phone in again."],
+ ['no Chrome', seen([phone(chrome({ installed: false, version: undefined, running: false, debuggable: false }))]), '✗ Chrome Chrome is not installed on the phone. Install Google Chrome from the Play Store.'],
['Chrome closed', seen([phone(chrome({ running: false, debuggable: false }))]), '✗ Chrome open Chrome is not open on the phone.'],
- ['adb broken', seen([], { adb: { path: ADB.path, broken: 'Bad CPU type in executable' } }), `✗ adb adb at ${ADB.path} does not run: Bad CPU type in executable`],
+ ['adb broken', seen([], { adb: { path: ADB.path, broken: 'Bad CPU type in executable' } }), `✗ adb adb at ${ADB.path} does not run: Bad CPU type in executable. Reinstall platform-tools, or name a working adb in ~/.browsentic/config.json.`],
];
test.each(failingRows)('%s: one failing row, and nothing past it', (_name, state, failing) => {
@@ -98,23 +98,22 @@ describe('browsentic android', () => {
test('Chrome closed also names the command that opens it', () => {
const lines = androidLines(failingRows[5][1]);
const at = lines.indexOf('✗ Chrome open Chrome is not open on the phone.');
- expect(lines.slice(at, at + 3)).toEqual([
+ expect(lines.slice(at, at + 2)).toEqual([
'✗ Chrome open Chrome is not open on the phone.',
- ' Open Chrome on the phone.',
- ' or run "browsentic android open"',
+ ' Open it on the phone, or run "browsentic android open".',
]);
});
test('the screen off is advice under a ready phone', () => {
const lines = androidLines(seen([phone({ ...open, screen: { ...open.screen!, awake: false } })]));
- expect(lines).toContain("· Screen The phone's screen is off, so Chrome is not drawing the page.");
+ expect(lines).toContain("· Screen The phone's screen is off, so Chrome is not drawing the page. Unlock the phone.");
expect(lines.at(-1)).toMatch(/^Ready\./);
});
test('switched off is one line', () => {
expect(androidLines(judge({ enabled: false, platform: 'darwin', devices: [] }))).toEqual([
- '· Android Android is switched off for this computer.',
- ' Set "android": { "enabled": true } in ~/.browsentic/config.json',
+ '· Android Android is switched off in ~/.browsentic/config.json.',
+ ' "android": { "enabled": true }',
]);
});
@@ -122,6 +121,7 @@ describe('browsentic android', () => {
const lines = androidLines(seen([phone(), phone(null, { ...emulator, serial: 'R5CT1234567', state: 'unauthorized', adbState: 'unauthorized' })]));
expect(lines.filter((line) => line === 'emulator-5554' || line === 'R5CT1234567')).toEqual(['emulator-5554', 'R5CT1234567']);
expect(lines.indexOf('R5CT1234567')).toBe(lines.indexOf('emulator-5554') + 7);
+ expect(lines[0]).toMatch(/^✓ adb /);
});
});
diff --git a/src/daemon/android/report.ts b/src/daemon/android/report.ts
index 9553a6c..f984ca5 100644
--- a/src/daemon/android/report.ts
+++ b/src/daemon/android/report.ts
@@ -1,28 +1,21 @@
+import { phoneReport, type CheckMark, type PhoneCheck, type PhoneReport } from '@/lib/phone/checks';
import { PHONE_GUIDE, type GuideStep } from '@/lib/phone/guide';
-import type { AndroidDevice, AndroidProblem, AndroidProblemCode, AndroidState } from '@/lib/phone/types';
+import type { AndroidFixAction, AndroidProblemCode, AndroidState } from '@/lib/phone/types';
const LABEL_WIDTH = 19;
const INDENT = ' '.repeat(LABEL_WIDTH + 2);
-
-type Mark = '✓' | '·' | '✗';
-
-const row = (mark: Mark, label: string, value: string): string => `${mark} ${label.padEnd(LABEL_WIDTH)}${value}`;
-
-const failed = (label: string, problem: AndroidProblem, mark: Mark = '✗'): string[] => [
- row(mark, label, problem.message),
- ...(problem.fix ? [`${INDENT}${problem.fix}`] : []),
-];
-
-const PHONE_ROW_PROBLEMS: ReadonlySet<AndroidProblemCode> = new Set(['DEVICE_OFFLINE', 'NO_PERMISSIONS', 'DEVICE_BOOTING']);
-
-/** Problems the setup steps answer. Once the phone is connected and allowed, each row's own fix says more than the steps would. */
-const GUIDED: ReadonlySet<AndroidProblemCode> = new Set(['ADB_MISSING', 'NO_DEVICE', 'DEVICE_UNAUTHORIZED']);
+const MARKS: Record<CheckMark, string> = { passed: '✓', failed: '✗', advisory: '·' };
+const ACTION_HINTS: Record<AndroidFixAction, string> = {
+ launchChrome: 'Open it on the phone, or run "browsentic android open".',
+ installChrome: 'Run "browsentic android open" to open its Play Store page on the phone.',
+};
export interface AndroidJson extends AndroidState {
guide: readonly GuideStep[];
+ report: PhoneReport;
}
-export const androidJson = (state: AndroidState): AndroidJson => ({ ...state, guide: PHONE_GUIDE });
+export const androidJson = (state: AndroidState): AndroidJson => ({ ...state, guide: PHONE_GUIDE, report: phoneReport(state) });
/** What follows `browsentic android`: `open`, a URL, and `--serial <serial>` anywhere among them. */
export function androidArgs(args: readonly string[]): { sub?: string; url?: string; serial?: string } {
@@ -32,46 +25,20 @@ export function androidArgs(args: readonly string[]): { sub?: string; url?: stri
return { sub, url, serial };
}
-/** `browsentic android`: one checklist row per check, stopping at the first that fails, then the setup steps while no phone is connected and allowed. */
+/** `browsentic android`: the shared checklist as text, then the setup steps while no phone is connected and allowed. */
export function androidLines(state: AndroidState): string[] {
- if (!state.enabled) return state.problem ? failed('Android', state.problem, '·') : [];
- const adb = state.adb.problem ? failed('adb', state.adb.problem) : [row('✓', 'adb', `${state.adb.path}${state.adb.version ? ` (${state.adb.version})` : ''}`)];
- if (state.adb.problem) return [...adb, ...(GUIDED.has(state.adb.problem.code) ? guide() : [])];
-
- const phones = state.devices.length
- ? state.devices.flatMap((device, index) => [...(index ? [''] : []), ...deviceLines(device, state.devices.length > 1)])
- : state.problem
- ? failed('Phone', state.problem)
- : [];
- const closing = state.ready
- ? ['', state.session ? `Android is on in a browser, driving ${state.session.serial}.` : 'Ready. Switch on Android in the Browsentic side panel to drive it.']
- : state.problem && GUIDED.has(state.problem.code)
- ? guide()
- : [];
- return [...adb, ...phones, ...closing];
+ const report = phoneReport(state);
+ const sections = report.sections.flatMap((section) => [...(section.serial ? ['', section.serial] : []), ...section.checks.flatMap(checkLines)]);
+ const closing = report.summary ? ['', report.summary] : report.guided ? guide() : [];
+ return [...sections, ...closing];
}
-function deviceLines(device: AndroidDevice, several: boolean): string[] {
- const problem = device.problem;
- const code = problem?.code;
- const phone = [
- device.model ?? 'Android phone',
- ...(device.android ? [`Android ${device.android}`] : []),
- device.transport === 'wifi' ? 'Wi-Fi' : 'USB',
- ].join(', ');
- const heading = several ? [device.serial] : [];
- const phoneRow = `${phone}${several ? '' : ` (${device.serial})`}`;
-
- if (code && PHONE_ROW_PROBLEMS.has(code)) return [...heading, ...failed('Phone', { ...problem, message: `${phoneRow}: ${problem.message}` })];
- const lines = [...heading, row('✓', 'Phone', phoneRow)];
- if (code === 'DEVICE_UNAUTHORIZED') return [...lines, ...failed('USB debugging', problem!)];
- lines.push(row('✓', 'USB debugging', 'allowed'));
- if (code === 'CHROME_MISSING') return [...lines, ...failed('Chrome', problem!)];
- lines.push(row('✓', 'Chrome', device.chrome.version ?? 'installed'));
- if (code === 'CHROME_NOT_RUNNING') return [...lines, ...failed('Chrome open', problem!), `${INDENT}or run "browsentic android open"`];
- lines.push(row('✓', 'Chrome open', 'its DevTools socket is open'));
- if (code === 'SCREEN_OFF') return [...lines, ...failed('Screen', problem!, '·')];
- return [...lines, row('✓', 'Screen', 'awake')];
+function checkLines(check: PhoneCheck): string[] {
+ return [
+ `${MARKS[check.mark]} ${check.label.padEnd(LABEL_WIDTH)}${check.value}`,
+ ...(check.fix ? [`${INDENT}${check.fix}`] : []),
+ ...(check.action ? [`${INDENT}${ACTION_HINTS[check.action]}`] : []),
+ ];
}
function guide(): string[] {
diff --git a/src/daemon/control.ts b/src/daemon/control.ts
index 556e72a..f4d4dde 100644
--- a/src/daemon/control.ts
+++ b/src/daemon/control.ts
@@ -53,7 +53,8 @@ export type ControlRequest =
| { id: string; op: 'setPreference'; change: unknown }
/**
* `launch` opens Chrome on that phone, at `url` when one is given. `watch` subscribes this caller to
- * `android-changed`. `peek` answers only what is already known, NOT_CHECKED while nobody watches.
+ * `android-changed` and `watch: false` lets go, so the Bridge stops looking once nobody shows phones.
+ * `peek` answers only what is already known, NOT_CHECKED while nobody watches.
*/
| { id: string; op: 'android'; launch?: string; url?: string; watch?: boolean; peek?: boolean };
diff --git a/src/daemon/daemon.ts b/src/daemon/daemon.ts
index ba9a46c..f8ed30d 100644
--- a/src/daemon/daemon.ts
+++ b/src/daemon/daemon.ts
@@ -892,6 +892,7 @@ export async function startDaemon({ version, idleExit = true, android = androidO
if (request.watch && !androidWatches.has(ws)) {
androidWatches.set(ws, android.watch((state) => send(ws, { event: 'android-changed', state })));
}
+ if (request.watch === false) unwatchAndroid(ws);
const result = request.launch
? await android.launch(request.launch, request.url)
: request.peek
diff --git a/src/daemon/test/protocol-window.test.ts b/src/daemon/test/protocol-window.test.ts
index c672705..2ed4ba9 100644
--- a/src/daemon/test/protocol-window.test.ts
+++ b/src/daemon/test/protocol-window.test.ts
@@ -169,6 +169,12 @@ describe('Android across the protocol window', () => {
android.change(READY_PHONE);
await bridge.status();
expect(heard).toEqual([NO_PHONE, READY_PHONE]);
+ await bridge.android({ watch: false });
+ expect(android.watchers).toBe(0);
+ android.change(NO_PHONE);
+ await bridge.status();
+ expect(heard).toHaveLength(2);
+ await bridge.android({ watch: true });
bridge.close();
await new Promise((resolve) => setTimeout(resolve, 20));
expect(android.watchers).toBe(0);
diff --git a/src/lib/phone/checks.ts b/src/lib/phone/checks.ts
new file mode 100644
index 0000000..be8b367
--- /dev/null
+++ b/src/lib/phone/checks.ts
@@ -0,0 +1,89 @@
+import type { AndroidDevice, AndroidFixAction, AndroidProblem, AndroidProblemCode, AndroidState } from './types';
+
+export type CheckMark = 'passed' | 'failed' | 'advisory';
+
+export interface PhoneCheck {
+ label: string;
+ mark: CheckMark;
+ value: string;
+ fix?: string;
+ action?: AndroidFixAction;
+ code?: AndroidProblemCode;
+}
+
+export interface PhoneSection {
+ /** Set when more than one phone is connected, to head that phone's checks. */
+ serial?: string;
+ checks: PhoneCheck[];
+}
+
+/** The checklist every surface shows, in one order and one wording: the CLI prints it, the apps draw it. */
+export interface PhoneReport {
+ sections: PhoneSection[];
+ ready: boolean;
+ /** The setup steps answer what is wrong: the phone is not connected or not allowed yet. */
+ guided: boolean;
+ /** A closing line once a phone is ready. */
+ summary?: string;
+}
+
+const PHONE_ROW_PROBLEMS: ReadonlySet<AndroidProblemCode> = new Set(['DEVICE_OFFLINE', 'NO_PERMISSIONS', 'DEVICE_BOOTING']);
+const GUIDED: ReadonlySet<AndroidProblemCode> = new Set(['ADB_MISSING', 'NO_DEVICE', 'DEVICE_UNAUTHORIZED']);
+
+const passed = (label: string, value: string): PhoneCheck => ({ label, mark: 'passed', value });
+
+const failed = (label: string, problem: AndroidProblem, mark: CheckMark = 'failed', value = problem.message): PhoneCheck => ({
+ label,
+ mark,
+ value,
+ fix: problem.fix,
+ action: problem.action,
+ code: problem.code,
+});
+
+export function phoneReport(state: AndroidState): PhoneReport {
+ const guided = !state.ready && !!state.problem && GUIDED.has(state.problem.code);
+ if (!state.enabled) return { sections: state.problem ? [{ checks: [failed('Android', state.problem, 'advisory')] }] : [], ready: false, guided: false };
+
+ const adb = state.adb.problem
+ ? failed('adb', state.adb.problem)
+ : passed('adb', `${state.adb.path}${state.adb.version ? ` (${state.adb.version})` : ''}`);
+ if (state.adb.problem) return { sections: [{ checks: [adb] }], ready: false, guided };
+
+ const several = state.devices.length > 1;
+ const phones: PhoneSection[] = state.devices.length
+ ? state.devices.map((device) => ({ ...(several ? { serial: device.serial } : {}), checks: deviceChecks(device, several) }))
+ : [{ checks: state.problem ? [failed('Phone', state.problem)] : [] }];
+ return {
+ sections: [{ checks: [adb] }, ...phones],
+ ready: state.ready,
+ guided,
+ summary: state.ready
+ ? state.session
+ ? `Android is on in a browser, driving ${state.session.serial}.`
+ : 'Ready. Switch on Android in the Browsentic side panel to drive it.'
+ : undefined,
+ };
+}
+
+function deviceChecks(device: AndroidDevice, several: boolean): PhoneCheck[] {
+ const problem = device.problem;
+ const code = problem?.code;
+ const phone = [
+ device.model ?? 'Android phone',
+ ...(device.android ? [`Android ${device.android}`] : []),
+ device.transport === 'wifi' ? 'Wi-Fi' : 'USB',
+ ].join(', ');
+ const named = `${phone}${several ? '' : ` (${device.serial})`}`;
+
+ if (problem && code && PHONE_ROW_PROBLEMS.has(code)) return [failed('Phone', problem, 'failed', `${named}: ${problem.message}`)];
+ const checks = [passed('Phone', named)];
+ if (problem && code === 'DEVICE_UNAUTHORIZED') return [...checks, failed('USB debugging', problem)];
+ checks.push(passed('USB debugging', 'allowed'));
+ if (problem && code === 'CHROME_MISSING') return [...checks, failed('Chrome', problem)];
+ checks.push(passed('Chrome', device.chrome.version ?? 'installed'));
+ if (problem && code === 'CHROME_NOT_RUNNING') return [...checks, failed('Chrome open', problem)];
+ checks.push(passed('Chrome open', 'its DevTools socket is open'));
+ if (problem && code === 'SCREEN_OFF') return [...checks, failed('Screen', problem, 'advisory')];
+ return [...checks, passed('Screen', 'awake')];
+}
diff --git a/src/lib/phone/fixtures/android-adbMissing.json b/src/lib/phone/fixtures/android-adbMissing.json
index c8d45fa..7a06bc2 100644
--- a/src/lib/phone/fixtures/android-adbMissing.json
+++ b/src/lib/phone/fixtures/android-adbMissing.json
@@ -41,5 +41,22 @@
"title": "Switch on Android",
"detail": "In your browser, open the Browsentic side panel and switch on Android."
}
- ]
+ ],
+ "report": {
+ "sections": [
+ {
+ "checks": [
+ {
+ "label": "adb",
+ "mark": "failed",
+ "value": "Browsentic reaches your phone through adb, from Android's platform-tools, and it is not installed. Install it with the command below or download it from https://developer.android.com/tools/releases/platform-tools.",
+ "fix": "brew install --cask android-platform-tools",
+ "code": "ADB_MISSING"
+ }
+ ]
+ }
+ ],
+ "ready": false,
+ "guided": true
+ }
}
diff --git a/src/lib/phone/fixtures/android-noDevice.json b/src/lib/phone/fixtures/android-noDevice.json
index dd0dc09..6ba18bb 100644
--- a/src/lib/phone/fixtures/android-noDevice.json
+++ b/src/lib/phone/fixtures/android-noDevice.json
@@ -9,8 +9,7 @@
"devices": [],
"problem": {
"code": "NO_DEVICE",
- "message": "No Android phone is connected.",
- "fix": "Turn on USB debugging on the phone and connect it with a USB cable. Run \"browsentic android\" for the steps."
+ "message": "No Android phone is connected. Turn on USB debugging on the phone and connect it with a USB cable."
},
"guide": [
{
@@ -38,5 +37,30 @@
"title": "Switch on Android",
"detail": "In your browser, open the Browsentic side panel and switch on Android."
}
- ]
+ ],
+ "report": {
+ "sections": [
+ {
+ "checks": [
+ {
+ "label": "adb",
+ "mark": "passed",
+ "value": "/Users/me/Library/Android/sdk/platform-tools/adb (37.0.0-14910828)"
+ }
+ ]
+ },
+ {
+ "checks": [
+ {
+ "label": "Phone",
+ "mark": "failed",
+ "value": "No Android phone is connected. Turn on USB debugging on the phone and connect it with a USB cable.",
+ "code": "NO_DEVICE"
+ }
+ ]
+ }
+ ],
+ "ready": false,
+ "guided": true
+ }
}
diff --git a/src/lib/phone/fixtures/android-ready.json b/src/lib/phone/fixtures/android-ready.json
index fb7173b..4836864 100644
--- a/src/lib/phone/fixtures/android-ready.json
+++ b/src/lib/phone/fixtures/android-ready.json
@@ -55,5 +55,50 @@
"title": "Switch on Android",
"detail": "In your browser, open the Browsentic side panel and switch on Android."
}
- ]
+ ],
+ "report": {
+ "sections": [
+ {
+ "checks": [
+ {
+ "label": "adb",
+ "mark": "passed",
+ "value": "/Users/me/Library/Android/sdk/platform-tools/adb (37.0.0-14910828)"
+ }
+ ]
+ },
+ {
+ "checks": [
+ {
+ "label": "Phone",
+ "mark": "passed",
+ "value": "sdk_gphone16k_arm64, Android 17, USB (emulator-5554)"
+ },
+ {
+ "label": "USB debugging",
+ "mark": "passed",
+ "value": "allowed"
+ },
+ {
+ "label": "Chrome",
+ "mark": "passed",
+ "value": "150.0.7871.186"
+ },
+ {
+ "label": "Chrome open",
+ "mark": "passed",
+ "value": "its DevTools socket is open"
+ },
+ {
+ "label": "Screen",
+ "mark": "passed",
+ "value": "awake"
+ }
+ ]
+ }
+ ],
+ "ready": true,
+ "guided": false,
+ "summary": "Ready. Switch on Android in the Browsentic side panel to drive it."
+ }
}
diff --git a/src/lib/phone/fixtures/android-unauthorized.json b/src/lib/phone/fixtures/android-unauthorized.json
index c8b9de3..792814a 100644
--- a/src/lib/phone/fixtures/android-unauthorized.json
+++ b/src/lib/phone/fixtures/android-unauthorized.json
@@ -18,15 +18,13 @@
},
"problem": {
"code": "DEVICE_UNAUTHORIZED",
- "message": "The phone has not allowed this computer yet.",
- "fix": "Unlock your phone and tap Allow on the USB debugging prompt. If no prompt shows, unplug the phone and plug it in again."
+ "message": "The phone has not allowed this computer yet. Unlock it and tap Allow on the USB debugging prompt. If no prompt shows, unplug it and plug it in again."
}
}
],
"problem": {
"code": "DEVICE_UNAUTHORIZED",
- "message": "The phone has not allowed this computer yet.",
- "fix": "Unlock your phone and tap Allow on the USB debugging prompt. If no prompt shows, unplug the phone and plug it in again."
+ "message": "The phone has not allowed this computer yet. Unlock it and tap Allow on the USB debugging prompt. If no prompt shows, unplug it and plug it in again."
},
"guide": [
{
@@ -54,5 +52,35 @@
"title": "Switch on Android",
"detail": "In your browser, open the Browsentic side panel and switch on Android."
}
- ]
+ ],
+ "report": {
+ "sections": [
+ {
+ "checks": [
+ {
+ "label": "adb",
+ "mark": "passed",
+ "value": "/Users/me/Library/Android/sdk/platform-tools/adb (37.0.0-14910828)"
+ }
+ ]
+ },
+ {
+ "checks": [
+ {
+ "label": "Phone",
+ "mark": "passed",
+ "value": "Android phone, USB (R5CT1234567)"
+ },
+ {
+ "label": "USB debugging",
+ "mark": "failed",
+ "value": "The phone has not allowed this computer yet. Unlock it and tap Allow on the USB debugging prompt. If no prompt shows, unplug it and plug it in again.",
+ "code": "DEVICE_UNAUTHORIZED"
+ }
+ ]
+ }
+ ],
+ "ready": false,
+ "guided": true
+ }
}
diff --git a/src/mac/Sources/Browsentic/App/AppModel.swift b/src/mac/Sources/Browsentic/App/AppModel.swift
index c8d35e9..f7d3570 100644
--- a/src/mac/Sources/Browsentic/App/AppModel.swift
+++ b/src/mac/Sources/Browsentic/App/AppModel.swift
@@ -17,7 +17,7 @@ enum DaemonPhase: Equatable {
}
enum Tab: String, CaseIterable, Identifiable {
- case overview, browsers, agents, skills, activity, logs, settings, about
+ case overview, browsers, android, agents, skills, activity, logs, settings, about
var id: String { rawValue }
var label: String { rawValue.capitalized }
@@ -25,6 +25,7 @@ enum Tab: String, CaseIterable, Identifiable {
switch self {
case .overview: "power"
case .browsers: "globe"
+ case .android: "candybarphone"
case .agents: "sparkles"
case .skills: "book.closed"
case .activity: "checkmark.shield"
@@ -55,6 +56,8 @@ final class AppModel: ObservableObject {
@Published var sessions: [BrowserSession] = []
@Published var pairing: PairingCode?
@Published var agents: AgentState?
+ /// `browsentic android --json` while the Android tab is open; the Bridge looks for phones only then.
+ @Published var android: AndroidState?
@Published var preferences: Preferences?
/// The running daemon never answered for its settings: it predates this app and needs a restart.
@Published var preferencesUnsupported = false
@@ -79,6 +82,7 @@ final class AppModel: ObservableObject {
private var poller: Task<Void, Never>?
private var eventWatcher: Task<Void, Never>?
private var updateWatcher: Task<Void, Never>?
+ private var watchingAndroid = false
var cli: CLI? { node.map(CLI.init) }
var appVersion: String { Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? Payload.bundledVersion ?? "dev" }
@@ -227,9 +231,16 @@ final class AppModel: ObservableObject {
func startPolling() {
eventWatcher?.cancel()
eventWatcher = Task { [weak self, control] in
- for await event in control.events where event == "settings-changed" {
- await self?.loadPreferences()
- await self?.loadAgents()
+ for await event in control.events {
+ switch event {
+ case "settings-changed":
+ await self?.loadPreferences()
+ await self?.loadAgents()
+ case "android-changed":
+ await self?.loadAndroid()
+ default:
+ break
+ }
}
}
poller?.cancel()
@@ -245,6 +256,7 @@ final class AppModel: ObservableObject {
guard let lock = Self.readLock() else { return markOff() }
if await control.connect(lock) {
Task { await self.loadPreferences(watch: true) }
+ if watchingAndroid { Task { await self.watchAndroid(true) } }
}
do {
let status = try await control.status()
@@ -323,6 +335,25 @@ final class AppModel: ObservableObject {
if let state = try? await cli.agents() { agents = state }
}
+ /// The tab subscribes while it shows and lets go when it leaves, so phones are looked for only while someone is looking at them.
+ func watchAndroid(_ on: Bool) async {
+ watchingAndroid = on
+ guard daemon == .on else { return }
+ _ = try? await control.android(watch: on)
+ if on { await loadAndroid() }
+ }
+
+ func loadAndroid() async {
+ await perform("android", quiet: true) { cli, _ in self.android = try await cli.android() }
+ }
+
+ func openChrome(on serial: String) async {
+ await perform("android:\(serial)") { cli, control in
+ _ = try await control.android(launch: serial)
+ self.android = try await cli.android()
+ }
+ }
+
func loadPreferences(watch: Bool = false) async {
do {
preferences = try await control.preferences(watch: watch)
diff --git a/src/mac/Sources/Browsentic/Core/CLI.swift b/src/mac/Sources/Browsentic/Core/CLI.swift
index 7b85349..10d094f 100644
--- a/src/mac/Sources/Browsentic/Core/CLI.swift
+++ b/src/mac/Sources/Browsentic/Core/CLI.swift
@@ -53,6 +53,7 @@ struct CLI {
func browsers() async throws -> [BrowserRow] { try await json(["browsers"], as: BrowserListing.self).browsers }
func agents() async throws -> AgentState { try await json(["agent"], as: AgentState.self) }
+ func android() async throws -> AndroidState { try await json(["android"], as: AndroidState.self, timeout: 30) }
func setModel(_ model: String?, for kind: String) async throws { try await run(["agent", "model", kind] + (model.map { [$0] } ?? [])) }
func skills() async throws -> SkillListing { try await json(["skills"], as: SkillListing.self) }
func approvals() async throws -> [Grant] { try await json(["approvals"], as: GrantListing.self).grants }
diff --git a/src/mac/Sources/Browsentic/Core/ControlClient.swift b/src/mac/Sources/Browsentic/Core/ControlClient.swift
index 7b5b69d..9f0ebda 100644
--- a/src/mac/Sources/Browsentic/Core/ControlClient.swift
+++ b/src/mac/Sources/Browsentic/Core/ControlClient.swift
@@ -84,6 +84,14 @@ actor ControlClient {
try await request(["op": "preferences", "watch": watch], as: Reply<Outcome<Preferences>>.self, key: "result").value()
}
+ /// `watch` subscribes this socket to `android-changed`, and `false` lets go so the Bridge stops looking for phones. `launch` opens Chrome on that phone.
+ func android(watch: Bool? = nil, launch: String? = nil) async throws -> AndroidState {
+ var frame: [String: Any] = ["op": "android"]
+ if let watch { frame["watch"] = watch }
+ if let launch { frame["launch"] = launch }
+ return try await request(frame, as: Reply<Outcome<AndroidState>>.self, key: "result", timeout: launch == nil ? 20 : 40).value()
+ }
+
func setTheme(_ theme: BrowserTheme) async throws -> Preferences {
try await setPreference(["kind": "theme", "theme": theme.rawValue])
}
diff --git a/src/mac/Sources/Browsentic/Core/Models.swift b/src/mac/Sources/Browsentic/Core/Models.swift
index 679361a..e747eb1 100644
--- a/src/mac/Sources/Browsentic/Core/Models.swift
+++ b/src/mac/Sources/Browsentic/Core/Models.swift
@@ -310,3 +310,90 @@ enum Version {
Int(version.trimmingCharacters(in: CharacterSet(charactersIn: "v \n")).split(separator: ".").first ?? "") ?? 0
}
}
+
+/// `browsentic android --json`, and the control socket's `android` answer without `guide` and `report`. Every field is optional, so an older or newer Bridge still decodes.
+struct AndroidState: Decodable, Equatable {
+ struct Problem: Decodable, Equatable {
+ let code: String
+ let message: String
+ let fix: String?
+ let action: String?
+ }
+
+ struct Adb: Decodable, Equatable {
+ let found: Bool?
+ let path: String?
+ let version: String?
+ let problem: Problem?
+ }
+
+ struct Chrome: Decodable, Equatable {
+ let installed: Bool?
+ let version: String?
+ let running: Bool?
+ let debuggable: Bool?
+ }
+
+ struct Device: Decodable, Identifiable, Equatable {
+ let serial: String
+ let transport: String?
+ let state: String?
+ let model: String?
+ let android: String?
+ let chrome: Chrome?
+ let problem: Problem?
+
+ var id: String { serial }
+ }
+
+ struct Session: Decodable, Equatable {
+ let serial: String
+ let since: String?
+ }
+
+ struct GuideStep: Decodable, Equatable, Identifiable {
+ let title: String
+ let detail: String
+ let platform: String?
+
+ var id: String { title }
+ }
+
+ /// One row of the checklist the CLI prints, worded once in src/lib/phone/checks.ts for every surface.
+ struct Check: Decodable, Equatable, Identifiable {
+ let label: String
+ let mark: String
+ let value: String
+ let fix: String?
+ let action: String?
+ let code: String?
+
+ var id: String { label }
+ var failed: Bool { mark == "failed" }
+ }
+
+ struct Section: Decodable, Equatable, Identifiable {
+ let serial: String?
+ let checks: [Check]
+
+ var id: String { serial ?? checks.first?.label ?? "" }
+ }
+
+ struct Report: Decodable, Equatable {
+ let sections: [Section]
+ let ready: Bool?
+ let guided: Bool?
+ let summary: String?
+ }
+
+ let enabled: Bool?
+ let ready: Bool?
+ let adb: Adb?
+ let devices: [Device]?
+ let problem: Problem?
+ let session: Session?
+ let guide: [GuideStep]?
+ let report: Report?
+
+ var isReady: Bool { ready == true }
+}
diff --git a/src/mac/Sources/Browsentic/Views/AndroidView.swift b/src/mac/Sources/Browsentic/Views/AndroidView.swift
new file mode 100644
index 0000000..808466d
--- /dev/null
+++ b/src/mac/Sources/Browsentic/Views/AndroidView.swift
@@ -0,0 +1,207 @@
+import AppKit
+import SwiftUI
+
+/// The same words as the Windows app's Android tab (src/windows/ui/views/android.tsx): change both together.
+enum AndroidCopy {
+ static let title = "Drive Chrome on your Android phone"
+ static let subtitle = "Browsentic Bridge reaches Chrome on your phone through adb, Android's debugging tool. Nothing is installed on the phone."
+ static let phoneCard = "Your phone"
+ static let guideCard = "Set up your phone"
+ static let guideSubtitle = "Once per phone. After that, plug it in and open Chrome."
+ static let checkAgain = "Check again"
+ static let openChrome = "Open Chrome on the phone"
+ static let getChrome = "Get Chrome"
+ static let copyInstall = "Copy install command"
+ static let downloadTools = "Download platform-tools"
+ static let offline = "Phone checks"
+ static let androidEleven = "Android 11 or later"
+ static let platformToolsURL = URL(string: "https://developer.android.com/tools/releases/platform-tools")!
+}
+
+struct AndroidView: View {
+ @EnvironmentObject private var model: AppModel
+ @AppStorage("androidReadyOnce") private var readyOnce = false
+ @State private var guideOpen: Bool?
+
+ var body: some View {
+ VStack(spacing: 18) {
+ if model.daemon != .on {
+ OfflineHint(what: AndroidCopy.offline)
+ } else if let android = model.android {
+ header
+ PhoneCard(android: android)
+ if let guide = android.guide, !guide.isEmpty {
+ guideCard(guide, open: guideOpen ?? (android.report?.guided == true || (!readyOnce && !android.isReady)))
+ }
+ } else {
+ ProgressView().padding(60)
+ }
+ }
+ .task(id: model.daemon) { await model.watchAndroid(true) }
+ .onDisappear { Task { await model.watchAndroid(false) } }
+ .onChange(of: model.android?.isReady, initial: true) { _, ready in if ready == true { readyOnce = true } }
+ }
+
+ private var header: some View {
+ Card {
+ HStack(alignment: .top, spacing: 14) {
+ SectionTitle(title: AndroidCopy.title, subtitle: AndroidCopy.subtitle)
+ Spacer(minLength: 12)
+ if model.busy.contains("android") { ProgressView().controlSize(.small) }
+ Button { Task { await model.loadAndroid() } } label: { Label(AndroidCopy.checkAgain, systemImage: "arrow.clockwise") }
+ .buttonStyle(QuietButtonStyle())
+ .disabled(model.busy.contains("android"))
+ }
+ }
+ }
+
+ private func guideCard(_ guide: [AndroidState.GuideStep], open: Bool) -> some View {
+ Card {
+ VStack(alignment: .leading, spacing: 14) {
+ Button { withAnimation(.spring(duration: 0.3)) { guideOpen = !open } } label: {
+ HStack {
+ SectionTitle(title: AndroidCopy.guideCard, subtitle: AndroidCopy.guideSubtitle)
+ Spacer()
+ Image(systemName: "chevron.down")
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundStyle(Palette.inkDim)
+ .rotationEffect(.degrees(open ? 0 : -90))
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+
+ if open {
+ VStack(alignment: .leading, spacing: 12) {
+ ForEach(Array(guide.enumerated()), id: \.element.id) { index, step in
+ HStack(alignment: .top, spacing: 12) {
+ Text("\(index + 1)")
+ .font(.system(size: 11.5, weight: .bold))
+ .foregroundStyle(Palette.brand)
+ .frame(width: 22, height: 22)
+ .background(Palette.brand.opacity(0.13), in: Circle())
+ VStack(alignment: .leading, spacing: 3) {
+ HStack(spacing: 8) {
+ Text(step.title).font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)
+ if step.platform == "android11+" { Pill(text: AndroidCopy.androidEleven) }
+ }
+ Text(step.detail)
+ .font(.system(size: 12))
+ .foregroundStyle(Palette.inkDim)
+ .fixedSize(horizontal: false, vertical: true)
+ .textSelection(.enabled)
+ }
+ }
+ }
+ }
+ .transition(.opacity)
+ }
+ }
+ }
+ }
+}
+
+struct PhoneCard: View {
+ @EnvironmentObject private var model: AppModel
+ let android: AndroidState
+
+ var body: some View {
+ Card {
+ VStack(alignment: .leading, spacing: 10) {
+ SectionTitle(title: AndroidCopy.phoneCard)
+ ForEach(android.report?.sections ?? []) { section in
+ if let serial = section.serial {
+ Text(serial).font(.code(11.5, weight: .semibold)).foregroundStyle(Palette.inkDim).padding(.top, 6)
+ }
+ ForEach(section.checks) { check in
+ PhoneCheckRow(check: check, serial: section.serial ?? android.devices?.first?.serial)
+ }
+ }
+ if let summary = android.report?.summary {
+ Label(summary, systemImage: android.session == nil ? "checkmark.seal" : "dot.radiowaves.left.and.right")
+ .font(.system(size: 12.5, weight: .medium))
+ .foregroundStyle(Palette.lime)
+ .padding(.top, 4)
+ }
+ }
+ }
+ }
+}
+
+private struct PhoneCheckRow: View {
+ @EnvironmentObject private var model: AppModel
+ let check: AndroidState.Check
+ let serial: String?
+
+ private static let icons = [
+ "adb": "terminal", "Phone": "candybarphone", "USB debugging": "cable.connector",
+ "Chrome": "globe", "Chrome open": "macwindow", "Screen": "sun.max", "Android": "power",
+ ]
+
+ private var working: Bool { serial.map { model.busy.contains("android:\($0)") } ?? false }
+
+ var body: some View {
+ HStack(alignment: .top, spacing: 12) {
+ Image(systemName: Self.icons[check.label] ?? "circle")
+ .font(.system(size: 14, weight: .medium))
+ .foregroundStyle(Palette.brand)
+ .frame(width: 30, height: 30)
+ .background(Palette.ground2, in: RoundedRectangle(cornerRadius: 9, style: .continuous))
+
+ VStack(alignment: .leading, spacing: 6) {
+ Text(check.label).font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)
+ Text(check.value)
+ .font(.system(size: 11.5))
+ .foregroundStyle(check.failed ? Palette.ink : Palette.inkDim)
+ .fixedSize(horizontal: false, vertical: true)
+ .textSelection(.enabled)
+ if let fix = check.fix {
+ Text(fix)
+ .font(.code(11.5))
+ .foregroundStyle(Palette.ink)
+ .textSelection(.enabled)
+ .fixedSize(horizontal: false, vertical: true)
+ .padding(.horizontal, 10)
+ .padding(.vertical, 6)
+ .background(Palette.ground2, in: RoundedRectangle(cornerRadius: 8, style: .continuous))
+ }
+ if check.fix != nil || check.action != nil { actions }
+ }
+ Spacer(minLength: 8)
+ if working { ProgressView().controlSize(.small) }
+ indicator.frame(width: 22)
+ }
+ .padding(.horizontal, 14)
+ .padding(.vertical, 10)
+ .background(Palette.surface.opacity(0.72), in: RoundedRectangle(cornerRadius: 14, style: .continuous))
+ .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(check.failed ? Palette.amber.opacity(0.45) : Palette.line))
+ }
+
+ @ViewBuilder private var actions: some View {
+ HStack(spacing: 8) {
+ if let serial, check.action == "launchChrome" {
+ Button { Task { await model.openChrome(on: serial) } } label: { Label(AndroidCopy.openChrome, systemImage: "play.fill") }
+ .buttonStyle(PrimaryButtonStyle())
+ .disabled(working)
+ } else if let serial, check.action == "installChrome" {
+ Button { Task { await model.openChrome(on: serial) } } label: { Label(AndroidCopy.getChrome, systemImage: "arrow.down.circle") }
+ .buttonStyle(PrimaryButtonStyle())
+ .disabled(working)
+ } else if let fix = check.fix, check.code == "ADB_MISSING" {
+ if Shell.which("brew") != nil { CopyButton(value: fix, label: AndroidCopy.copyInstall) }
+ Button { NSWorkspace.shared.open(AndroidCopy.platformToolsURL) } label: { Label(AndroidCopy.downloadTools, systemImage: "arrow.down.circle") }
+ .buttonStyle(QuietButtonStyle())
+ } else if let fix = check.fix {
+ CopyButton(value: fix)
+ }
+ }
+ }
+
+ @ViewBuilder private var indicator: some View {
+ switch check.mark {
+ case "passed": Image(systemName: "checkmark.circle.fill").foregroundStyle(Palette.lime)
+ case "advisory": Image(systemName: "exclamationmark.circle.fill").foregroundStyle(Palette.amber)
+ default: Image(systemName: "xmark.octagon.fill").foregroundStyle(Palette.danger)
+ }
+ }
+}
diff --git a/src/mac/Sources/Browsentic/Views/MainView.swift b/src/mac/Sources/Browsentic/Views/MainView.swift
index 8973902..7984a61 100644
--- a/src/mac/Sources/Browsentic/Views/MainView.swift
+++ b/src/mac/Sources/Browsentic/Views/MainView.swift
@@ -10,6 +10,7 @@ struct MainView: View {
switch model.tab {
case .overview: OverviewView()
case .browsers: BrowsersView()
+ case .android: AndroidView()
case .agents: AgentsView()
case .skills: SkillsView()
case .activity: ActivityView()
@@ -34,7 +35,7 @@ struct MainView: View {
}
}
-/// The view switcher floats at the top centre, ⌘1…⌘8.
+/// The view switcher floats at the top centre, ⌘1…⌘9.
private struct TabCapsule: View {
@EnvironmentObject private var model: AppModel
@Namespace private var highlight
diff --git a/src/mac/Tests/BrowsenticTests/ModelTests.swift b/src/mac/Tests/BrowsenticTests/ModelTests.swift
index 3caebe6..ba4c552 100644
--- a/src/mac/Tests/BrowsenticTests/ModelTests.swift
+++ b/src/mac/Tests/BrowsenticTests/ModelTests.swift
@@ -175,3 +175,59 @@ import Testing
}
}
+
+/// The samples `browsentic android --json` writes in src/lib/phone/fixtures, kept current by the CLI's own tests.
+@Suite struct AndroidDecodingTests {
+ private func sample(_ name: String) throws -> AndroidState {
+ let repo = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("../../../..").standardized
+ let data = try Data(contentsOf: repo.appendingPathComponent("src/lib/phone/fixtures/android-\(name).json"))
+ return try JSONDecoder().decode(AndroidState.self, from: data)
+ }
+
+ @Test func ready() throws {
+ let state = try sample("ready")
+ #expect(state.isReady)
+ #expect(state.devices?.first?.chrome?.debuggable == true)
+ #expect(state.report?.sections.flatMap(\.checks).map(\.label) == ["adb", "Phone", "USB debugging", "Chrome", "Chrome open", "Screen"])
+ #expect(state.report?.summary == "Ready. Switch on Android in the Browsentic side panel to drive it.")
+ #expect(state.guide?.count == 6)
+ }
+
+ @Test func noAdb() throws {
+ let state = try sample("adbMissing")
+ #expect(state.adb?.found == false)
+ let check = state.report?.sections.first?.checks.first
+ #expect(check?.code == "ADB_MISSING" && check?.failed == true)
+ #expect(check?.fix == "brew install --cask android-platform-tools")
+ #expect(state.report?.guided == true)
+ }
+
+ @Test func noPhone() throws {
+ let state = try sample("noDevice")
+ #expect(state.devices?.isEmpty == true)
+ #expect(state.problem?.code == "NO_DEVICE")
+ #expect(state.report?.sections.last?.checks.last?.label == "Phone")
+ }
+
+ @Test func unauthorized() throws {
+ let state = try sample("unauthorized")
+ #expect(state.devices?.first?.state == "unauthorized")
+ #expect(state.report?.sections.last?.checks.last?.code == "DEVICE_UNAUTHORIZED")
+ #expect(state.guide?.contains { $0.platform == "android11+" } == true)
+ }
+
+ @Test func theControlSocketAnswerHasNoReport() throws {
+ let answer = #"{"enabled":true,"ready":false,"adb":{"found":true,"path":"/x/adb"},"devices":[],"problem":{"code":"NO_DEVICE","message":"No Android phone is connected."}}"#
+ let state = try JSONDecoder().decode(AndroidState.self, from: Data(answer.utf8))
+ #expect(state.report == nil && state.guide == nil && state.isReady == false)
+ }
+}
+
+@Suite struct TabTests {
+ /// The View menu gives tab n the shortcut ⌘n, and `Character("10")` traps: nine tabs is the most there can be.
+ @Test func everyTabHasADigitShortcut() {
+ #expect(Tab.allCases.count <= 9)
+ #expect(Tab.allCases.firstIndex(of: .android) == 2)
+ #expect(Tab.allCases.last == .about)
+ }
+}