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(extension): connects to Browsentic Bridge by itself: on install, at browser start, when a page opens and on the alarm it asks the native host to pair, spaced by what the last attempt found, and redeems the grant on the Bridge's own port; a welcome page and the connection card show each state (Bridge missing, too old, off, stopped, blocked by policy, waiting for approval, revoked) with the code always one click away; Disconnect holds it off until Connect; a Bridge that forgot this browser is paired with again, and a revoked one waits for Reconnect

Shahriar3710babe3841
diff --git a/src/extension/components/daemon-link.tsx b/src/extension/components/daemon-link.tsx
index f87bbff..9671daf 100644
--- a/src/extension/components/daemon-link.tsx
+++ b/src/extension/components/daemon-link.tsx
@@ -1,103 +1,64 @@
import { useState } from 'react';
-import { Link2, Link2Off, Loader2 } from 'lucide-react';
+import { Link2Off, Loader2 } from 'lucide-react';
import { browser } from 'wxt/browser';
+import { PairingStatus } from '@/extension/components/pairing-status';
import { Button } from '@/extension/components/ui/button';
-import { Input } from '@/extension/components/ui/input';
-import { LINKS } from '@/lib/about';
-import { BRIDGE_CHANNEL, type ActionResult } from '@/lib/actions/protocol';
+import { BRIDGE_CHANNEL } from '@/lib/actions/protocol';
+import type { PairingMode } from '@/lib/pairing';
+import { useAutoPair } from '@/lib/bridge/use-auto-pair';
import { useDaemonState } from '@/lib/bridge/use-daemon-state';
+const MODE_LINE: Record<PairingMode, string> = {
+ auto: 'Browsers with Browsentic connect to this computer by themselves.',
+ ask: 'This computer asks you to allow each new browser.',
+ code: 'Browsers connect to this computer only with a code.',
+};
+
export function DaemonLink() {
const daemon = useDaemonState();
- const [code, setCode] = useState('');
+ const { connect } = useAutoPair(daemon);
const [busy, setBusy] = useState(false);
- const [error, setError] = useState<string | null>(null);
const connected = daemon?.connected ?? false;
const paired = daemon?.paired ?? false;
-
- async function pair() {
- setBusy(true);
- setError(null);
- const result = (await browser.runtime.sendMessage({
- channel: BRIDGE_CHANNEL,
- op: 'pair',
- token: code,
- })) as ActionResult;
- setBusy(false);
- if (result?.ok) setCode('');
- else setError(result?.error.message ?? 'Pairing failed');
- }
+ const mode = daemon?.preferences?.pairing?.mode;
async function disconnect() {
setBusy(true);
await browser.runtime.sendMessage({ channel: BRIDGE_CHANNEL, op: 'disconnect' });
setBusy(false);
- setError(null);
}
return (
<section className="space-y-2">
<div className="flex items-baseline justify-between gap-2">
<h2 className="font-mono text-[10px] tracking-[0.14em] text-ink-faint uppercase">Browser link</h2>
- {connected && (
- <span className="font-mono text-[10px] text-ink-faint">127.0.0.1:{daemon?.port}</span>
- )}
+ {connected && <span className="font-mono text-[10px] text-ink-faint">127.0.0.1:{daemon?.port}</span>}
</div>
{paired ? (
<>
<p className="text-[11px] leading-relaxed text-ink-dim">
{connected
- ? 'The daemon is driving this browser. Disconnecting revokes the key — you will need a new pairing code.'
- : 'Paired, but the daemon is not answering. Start it with browsentic, or disconnect to pair again.'}
+ ? 'Browsentic Bridge is driving this browser. Disconnecting stops it until you connect again here.'
+ : 'Paired, but Browsentic Bridge is not answering. Start it with browsentic start, or disconnect.'}
</p>
+ {connected && mode && (
+ <p className="text-[11px] leading-relaxed text-ink-faint">
+ {MODE_LINE[mode]} Change it in the app, or with <code className="font-mono">browsentic pairing</code>.
+ </p>
+ )}
<Button variant="outline" size="sm" className="w-full" onClick={disconnect} disabled={busy}>
{busy ? <Loader2 className="animate-spin" /> : <Link2Off />} Disconnect
</Button>
</>
) : (
- <>
- <p className="text-[11px] leading-relaxed text-ink-dim">
- Run <code className="rounded bg-surface px-1 py-px font-mono text-ink">browsentic pair</code> in a
- terminal and paste the code it prints.{' '}
- <a
- href={LINKS.pairing}
- target="_blank"
- rel="noreferrer"
- className="text-ink underline decoration-line-strong underline-offset-2 transition-colors hover:text-brand"
- >
- Learn more
- </a>
- </p>
- <form
- className="flex gap-1.5"
- onSubmit={(event) => {
- event.preventDefault();
- void pair();
- }}
- >
- <Input
- value={code}
- onChange={(event) => setCode(event.target.value)}
- placeholder="Pairing code"
- aria-label="Pairing code from browsentic pair"
- className="h-8 font-mono text-xs tracking-widest uppercase"
- autoComplete="off"
- spellCheck={false}
- />
- <Button type="submit" size="sm" disabled={busy || !code.trim()}>
- {busy ? <Loader2 className="animate-spin" /> : <Link2 />} Connect
- </Button>
- </form>
- </>
+ <PairingStatus daemon={daemon} onConnect={connect} />
)}
- {error && (
- <p className="rounded-lg border border-destructive/40 bg-destructive/10 px-2 py-1.5 text-[11px] text-destructive">
- {error}
- </p>
+ {daemon?.error && !paired && !daemon.pairing && (
+ <p className="rounded-lg border border-destructive/40 bg-destructive/10 px-2 py-1.5 text-[11px] text-destructive">{daemon.error}</p>
)}
</section>
);
diff --git a/src/extension/components/greeting.tsx b/src/extension/components/greeting.tsx
index d0f04dd..5f1aee6 100644
--- a/src/extension/components/greeting.tsx
+++ b/src/extension/components/greeting.tsx
@@ -11,8 +11,8 @@ const SUGGESTIONS = [
];
const BLOCKED: Record<StatusBlocker, string> = {
- unpaired: 'This browser isn’t paired yet, so nothing can drive it. Pairing takes one command and one code.',
- offline: 'Paired, but the daemon isn’t answering. Start browsentic and this reconnects on its own.',
+ unpaired: 'This browser isn’t connected to Browsentic Bridge yet. Once the Bridge is on this computer, it connects by itself.',
+ offline: 'Paired, but Browsentic Bridge isn’t answering. Start it and this reconnects on its own.',
agent: 'The chosen agent can’t run on this machine. Pick another one, or let Browsentic fix it.',
};
diff --git a/src/extension/components/pairing-status.tsx b/src/extension/components/pairing-status.tsx
new file mode 100644
index 0000000..a9b7f43
--- /dev/null
+++ b/src/extension/components/pairing-status.tsx
@@ -0,0 +1,206 @@
+import { useEffect, useState, type ReactNode } from 'react';
+import { Download, Link2, Loader2, RefreshCw } from 'lucide-react';
+import { browser } from 'wxt/browser';
+
+import { Button } from '@/extension/components/ui/button';
+import { Input } from '@/extension/components/ui/input';
+import { LINKS } from '@/lib/about';
+import { BRIDGE_CHANNEL, type ActionResult } from '@/lib/actions/protocol';
+import type { DaemonState } from '@/lib/bridge/socket';
+
+type Platform = 'mac' | 'win' | 'linux' | 'other';
+
+interface Shown {
+ text: ReactNode;
+ /** The action that might fix it, pressed by a person. */
+ retry?: string;
+ /** Lead with the code form: nothing automatic will connect this browser. */
+ codeFirst?: boolean;
+ busy?: boolean;
+ download?: boolean;
+}
+
+const Command = ({ children }: { children: ReactNode }) => (
+ <code className="rounded bg-surface px-1 py-px font-mono text-ink">{children}</code>
+);
+
+export function describePairing(daemon: DaemonState | null, unpacked: boolean): Shown {
+ const pairing = daemon?.pairing;
+ if (pairing?.manual) return { text: 'Disconnected. This browser won’t connect again until you connect it.', retry: 'Connect' };
+ if (pairing?.wait) {
+ return pairing.wait.approver === 'app'
+ ? { text: 'Allow this browser in the Browsentic app. It connects the moment you do.', busy: true }
+ : { text: <>Allow this browser on this computer: run <Command>browsentic approve</Command>. It connects the moment you do.</>, busy: true };
+ }
+ if (pairing?.blocked === 'revoked') return { text: 'This computer disconnected this browser.', retry: 'Reconnect' };
+ if (pairing?.blocked === 'denied') return { text: 'This computer turned this browser down.', retry: 'Ask again' };
+ switch (daemon?.bridge) {
+ case 'missing':
+ return {
+ text: (
+ <>
+ Browsentic Bridge isn’t on this computer yet. Install it and this browser connects by itself. Already installed?
+ Open the Browsentic app, or run <Command>browsentic setup</Command>. On a work computer, your organization’s
+ browser policy may block it.
+ </>
+ ),
+ retry: 'Try again',
+ download: true,
+ };
+ case 'old':
+ return {
+ text: (
+ <>
+ Browsentic Bridge needs an update to connect by itself. Update it from the app, or run{' '}
+ <Command>npx browsentic@latest update</Command>.
+ </>
+ ),
+ retry: 'Try again',
+ };
+ case 'forbidden':
+ return unpacked
+ ? { text: <>This copy isn’t registered with Browsentic Bridge. Run <Command>browsentic setup --unpacked</Command>, or pair with a code.</>, retry: 'Try again' }
+ : { text: <>Browsentic Bridge needs an update to let this browser in. Run <Command>npx browsentic@latest update</Command>.</>, retry: 'Try again' };
+ case 'policy':
+ return { text: 'Your organization’s browser policy keeps Browsentic Bridge from starting. Pair with a code instead.', codeFirst: true };
+ case 'stopped':
+ return { text: <>Browsentic Bridge is turned off. Turn it on in the app, or run <Command>browsentic start</Command>.</>, retry: 'Try again' };
+ case 'off':
+ return { text: <>Automatic pairing is off on this computer. Pair with a code from <Command>browsentic pair</Command> or the app.</>, codeFirst: true };
+ case 'failed':
+ return { text: `Browsentic Bridge couldn’t start. ${pairing?.error ?? ''}`.trim(), retry: 'Try again' };
+ default:
+ return pairing?.error ? { text: pairing.error, retry: 'Try again' } : { text: 'Looking for Browsentic Bridge on this computer…', busy: true };
+ }
+}
+
+function downloadFor(platform: Platform, arch: string): { href: string; label: string } | null {
+ if (platform === 'mac') return { href: LINKS.downloadMac, label: 'Get Browsentic for Mac' };
+ if (platform === 'win') {
+ return { href: arch === 'arm64' ? LINKS.downloadWindowsArm64 : LINKS.downloadWindowsX64, label: 'Get Browsentic for Windows' };
+ }
+ return null;
+}
+
+/** What this browser needs to connect while it is not paired, with a code as the way that always works. */
+export function PairingStatus({ daemon, onConnect }: { daemon: DaemonState | null; onConnect: () => Promise<void> }) {
+ const [unpacked, setUnpacked] = useState(false);
+ const [platform, setPlatform] = useState<{ os: Platform; arch: string }>({ os: 'other', arch: '' });
+ const [pressing, setPressing] = useState(false);
+ const [showCode, setShowCode] = useState(false);
+
+ useEffect(() => {
+ void browser.management.getSelf().then((self) => setUnpacked(self.installType === 'development')).catch(() => undefined);
+ void browser.runtime
+ .getPlatformInfo()
+ .then(({ os, arch }) => setPlatform({ os: os === 'mac' || os === 'win' || os === 'linux' ? os : 'other', arch }))
+ .catch(() => undefined);
+ }, []);
+
+ const shown = describePairing(daemon, unpacked);
+ const download = shown.download ? downloadFor(platform.os, platform.arch) : null;
+
+ async function press() {
+ setPressing(true);
+ await onConnect();
+ setPressing(false);
+ }
+
+ return (
+ <div className="space-y-2">
+ <p className="flex gap-1.5 text-[11px] leading-relaxed text-ink-dim">
+ {shown.busy && <Loader2 className="mt-0.5 size-3 shrink-0 animate-spin text-brand" />}
+ <span>{shown.text}</span>
+ </p>
+
+ {shown.download && platform.os === 'linux' && (
+ <p className="text-[11px] text-ink-dim">
+ Run <Command>npx browsentic@latest setup</Command> in a terminal.
+ </p>
+ )}
+
+ {(download || shown.retry) && (
+ <div className="flex flex-wrap gap-1.5">
+ {download && (
+ <Button asChild size="sm">
+ <a href={download.href} target="_blank" rel="noreferrer">
+ <Download /> {download.label}
+ </a>
+ </Button>
+ )}
+ {shown.retry && (
+ <Button variant={download ? 'outline' : 'default'} size="sm" onClick={() => void press()} disabled={pressing}>
+ {pressing ? <Loader2 className="animate-spin" /> : <RefreshCw />} {shown.retry}
+ </Button>
+ )}
+ </div>
+ )}
+
+ {shown.codeFirst || showCode ? (
+ <CodeForm />
+ ) : (
+ <button
+ type="button"
+ onClick={() => setShowCode(true)}
+ className="font-mono text-[10px] tracking-[0.12em] text-ink-faint uppercase transition-colors hover:text-brand"
+ >
+ Pair with a code instead
+ </button>
+ )}
+ </div>
+ );
+}
+
+function CodeForm() {
+ const [code, setCode] = useState('');
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ async function pair() {
+ setBusy(true);
+ setError(null);
+ const result = (await browser.runtime.sendMessage({ channel: BRIDGE_CHANNEL, op: 'pair', token: code })) as ActionResult;
+ setBusy(false);
+ if (result?.ok) setCode('');
+ else setError(result?.error.message ?? 'Pairing failed');
+ }
+
+ return (
+ <div className="space-y-2">
+ <p className="text-[11px] leading-relaxed text-ink-dim">
+ Run <Command>browsentic pair</Command> in a terminal, or press Get a pairing code in the app, and paste the code here.{' '}
+ <a
+ href={LINKS.pairing}
+ target="_blank"
+ rel="noreferrer"
+ className="text-ink underline decoration-line-strong underline-offset-2 transition-colors hover:text-brand"
+ >
+ Learn more
+ </a>
+ </p>
+ <form
+ className="flex gap-1.5"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void pair();
+ }}
+ >
+ <Input
+ value={code}
+ onChange={(event) => setCode(event.target.value)}
+ placeholder="Pairing code"
+ aria-label="Pairing code from browsentic pair"
+ className="h-8 font-mono text-xs tracking-widest uppercase"
+ autoComplete="off"
+ spellCheck={false}
+ />
+ <Button type="submit" size="sm" disabled={busy || !code.trim()}>
+ {busy ? <Loader2 className="animate-spin" /> : <Link2 />} Connect
+ </Button>
+ </form>
+ {error && (
+ <p className="rounded-lg border border-destructive/40 bg-destructive/10 px-2 py-1.5 text-[11px] text-destructive">{error}</p>
+ )}
+ </div>
+ );
+}
diff --git a/src/extension/entrypoints/background.ts b/src/extension/entrypoints/background.ts
index ea8eeb2..ba0d37b 100644
--- a/src/extension/entrypoints/background.ts
+++ b/src/extension/entrypoints/background.ts
@@ -26,6 +26,7 @@ import { endPhone, openChromeOnPhone, servePhone, startPhone } from '@/lib/bridg
import { servePhoneMirror } from '@/lib/bridge/phone-mirror';
import { servePhoneBackend } from '@/lib/bridge/phone-backend';
import { serveExtensionUpdates } from '@/lib/bridge/extension-update';
+import { autoPair, holdAutoPair, serveAutoPair } from '@/lib/bridge/auto-pair';
import { isAgentKind } from '@/lib/agents/catalog';
import { isPreferenceChange } from '@/lib/settings/preferences';
import {
@@ -33,6 +34,7 @@ import {
chooseAgent,
chooseAgentModel,
connectDaemon,
+ retryAfterUpdate,
disconnectDaemon,
onWelcome,
pairDaemon,
@@ -196,6 +198,14 @@ export default defineBackground(() => {
}
if (message.op === 'disconnect') {
disconnectDaemon()
+ .then(holdAutoPair)
+ .then(() => sendResponse(success(true)))
+ .catch((error) => sendResponse(failure('BRIDGE_ERROR', String(error))));
+ return true;
+ }
+ if (message.op === 'autoPair') {
+ const gesture = message.gesture === true;
+ autoPair(gesture ? 'gesture' : 'open', { gesture, wait: message.wait === true })
.then(() => sendResponse(success(true)))
.catch((error) => sendResponse(failure('BRIDGE_ERROR', String(error))));
return true;
@@ -203,18 +213,23 @@ export default defineBackground(() => {
sendResponse(
failure(
'INVALID_REQUEST',
- 'Expected {op:"describe"|"invoke"|"saveSkill"|"removeSkill"|"nameSession"|"recordEvents"|"recordingState"|"analyzeRecording"|"monitorSample"|"monitorState"|"listSkills"|"agentState"|"setAgent"|"setAgentModel"|"grantAgent"|"preferences"|"setPreference"|"tasks"|"saveTask"|"deleteTask"|"runTaskNow"|"pauseTasks"|"pair"|"panelOpened"|"disconnect"|"phoneStart"|"phoneEnd"|"phoneOpenChrome"}',
+ 'Expected {op:"describe"|"invoke"|"saveSkill"|"removeSkill"|"nameSession"|"recordEvents"|"recordingState"|"analyzeRecording"|"monitorSample"|"monitorState"|"listSkills"|"agentState"|"setAgent"|"setAgentModel"|"grantAgent"|"preferences"|"setPreference"|"tasks"|"saveTask"|"deleteTask"|"runTaskNow"|"pauseTasks"|"pair"|"autoPair"|"panelOpened"|"disconnect"|"phoneStart"|"phoneEnd"|"phoneOpenChrome"}',
),
);
return;
});
- browser.runtime.onInstalled.addListener(() => {
+ browser.runtime.onInstalled.addListener(({ reason }) => {
void browser.tabs.query({}).then((tabs) => {
for (const tab of tabs) {
if (tab.id != null && !tab.discarded) void injectContentScript(tab.id);
}
});
+ if (reason === 'install') {
+ void browser.tabs.create({ url: browser.runtime.getURL('/welcome.html') });
+ void autoPair('install');
+ }
+ if (reason === 'update') void retryAfterUpdate().then(() => autoPair('update'));
});
onPanelPresence((open) => {
@@ -249,8 +264,9 @@ export default defineBackground(() => {
});
void sweepFiles();
- void connectDaemon();
- browser.runtime.onStartup.addListener(() => void connectDaemon());
+ serveAutoPair();
+ void connectDaemon().then(() => autoPair('alarm'));
+ browser.runtime.onStartup.addListener(() => void connectDaemon().then(() => autoPair('startup')));
// With several browsers connected, a caller outside any of them reaches the one last in front.
browser.windows?.onFocusChanged.addListener((windowId) => {
@@ -259,6 +275,6 @@ export default defineBackground(() => {
browser.alarms.create(RECONNECT_ALARM, { periodInMinutes: 1 });
browser.alarms.onAlarm.addListener((alarm) => {
- if (alarm.name === RECONNECT_ALARM) void connectDaemon();
+ if (alarm.name === RECONNECT_ALARM) void connectDaemon().then(() => autoPair('alarm'));
});
});
diff --git a/src/extension/entrypoints/options/App.tsx b/src/extension/entrypoints/options/App.tsx
index 8c39067..2c95f6f 100644
--- a/src/extension/entrypoints/options/App.tsx
+++ b/src/extension/entrypoints/options/App.tsx
@@ -202,7 +202,7 @@ function Connection() {
<DaemonLink />
</Card>
<p className="text-xs leading-relaxed text-ink-faint">
- On a Mac, the Browsentic app’s Browsers tab also hands out pairing codes and lists every paired browser.
+ The Browsentic app’s Browsers tab lists every paired browser, and its Settings choose whether a new browser connects by itself, asks you first, or needs a code.
</p>
</div>
);
diff --git a/src/extension/entrypoints/welcome/App.tsx b/src/extension/entrypoints/welcome/App.tsx
new file mode 100644
index 0000000..a9b4bcd
--- /dev/null
+++ b/src/extension/entrypoints/welcome/App.tsx
@@ -0,0 +1,85 @@
+import { useEffect, useState, type ReactNode } from 'react';
+import { Check, PanelRight, Pin } from 'lucide-react';
+import { browser } from 'wxt/browser';
+
+import { AgentPicker } from '@/extension/components/agent-picker';
+import { Logo } from '@/extension/components/brand';
+import { PairingStatus } from '@/extension/components/pairing-status';
+import { Button } from '@/extension/components/ui/button';
+import { openSidePanel } from '@/lib/bridge/side-panel';
+import { useAutoPair } from '@/lib/bridge/use-auto-pair';
+import { useDaemonState } from '@/lib/bridge/use-daemon-state';
+import { cn } from '@/lib/utils';
+
+/** Opened once, when the extension is installed: it finds Browsentic Bridge, or says how to get it, and connects by itself. */
+export default function App() {
+ const daemon = useDaemonState();
+ const { connect } = useAutoPair(daemon);
+ const connected = daemon?.connected ?? false;
+ const [windowId, setWindowId] = useState<number | null>(null);
+
+ // Read ahead of the click: opening the panel needs the gesture, and an await spends it.
+ useEffect(() => {
+ void browser.windows.getCurrent().then((window) => setWindowId(window.id ?? null));
+ }, []);
+
+ return (
+ <main className="dot-grid min-h-screen bg-background px-6 py-14 text-ink">
+ <div className="mx-auto max-w-xl space-y-8">
+ <header className="flex items-start gap-3">
+ <Logo className="mt-1 size-9 shrink-0 text-brand" />
+ <div className="space-y-1">
+ <h1 className="text-xl font-semibold">Browsentic is in your browser</h1>
+ <p className="text-sm leading-relaxed text-ink-dim">
+ Your browser’s superpower: free, open source, and no API key, subscription or account. It runs on the agent
+ CLI you already use, through Browsentic Bridge on this computer.
+ </p>
+ </div>
+ </header>
+
+ <ol className="space-y-3">
+ <Step done title="The extension, in this browser">Added.</Step>
+ <Step done={connected} title="Browsentic Bridge, on this computer">
+ {connected ? 'Connected. Everything stays on this computer.' : <PairingStatus daemon={daemon} onConnect={connect} />}
+ </Step>
+ <Step done={connected && !!daemon?.agent} title="An agent CLI you’re signed in to">
+ {connected ? <AgentPicker /> : 'Claude Code, Codex or another supported one. You can pick it once the Bridge is connected.'}
+ </Step>
+ </ol>
+
+ {connected && (
+ <section className="panel-card space-y-3 rounded-xl p-5">
+ <p className="text-sm text-ink">You’re set. Open the side panel and tell it what to do on any page.</p>
+ <div className="flex flex-wrap items-center gap-3">
+ <Button onClick={() => windowId !== null && void openSidePanel(windowId)} disabled={windowId === null}>
+ <PanelRight /> Open the side panel
+ </Button>
+ <span className="inline-flex items-center gap-1.5 text-xs text-ink-faint">
+ <Pin className="size-3.5" /> Pin Browsentic from the puzzle piece in the toolbar to keep it one click away.
+ </span>
+ </div>
+ </section>
+ )}
+ </div>
+ </main>
+ );
+}
+
+function Step({ done, title, children }: { done: boolean; title: string; children: ReactNode }) {
+ return (
+ <li className="panel-card flex gap-3 rounded-xl p-4">
+ <span
+ className={cn(
+ 'mt-0.5 grid size-5 shrink-0 place-items-center rounded-full border',
+ done ? 'border-lime/60 bg-lime/15 text-lime' : 'border-line text-ink-faint',
+ )}
+ >
+ {done && <Check className="size-3" />}
+ </span>
+ <div className="min-w-0 flex-1 space-y-1.5">
+ <p className="text-sm font-medium text-ink">{title}</p>
+ <div className="text-xs leading-relaxed text-ink-dim">{children}</div>
+ </div>
+ </li>
+ );
+}
diff --git a/src/extension/entrypoints/welcome/index.html b/src/extension/entrypoints/welcome/index.html
new file mode 100644
index 0000000..967b401
--- /dev/null
+++ b/src/extension/entrypoints/welcome/index.html
@@ -0,0 +1,13 @@
+<!doctype html>
+<html lang="en" data-theme="ember" style="background-color: #1a1512">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="color-scheme" content="dark" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Welcome to Browsentic</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="./main.tsx"></script>
+ </body>
+</html>
diff --git a/src/extension/entrypoints/welcome/main.tsx b/src/extension/entrypoints/welcome/main.tsx
new file mode 100644
index 0000000..0026177
--- /dev/null
+++ b/src/extension/entrypoints/welcome/main.tsx
@@ -0,0 +1,13 @@
+import React from 'react';
+import ReactDOM from 'react-dom/client';
+import App from './App';
+import { mountTheme } from '@/lib/bridge/theme';
+import '@/extension/assets/globals.css';
+
+mountTheme();
+
+ReactDOM.createRoot(document.getElementById('root')!).render(
+ <React.StrictMode>
+ <App />
+ </React.StrictMode>,
+);
diff --git a/src/lib/about.ts b/src/lib/about.ts
index 3ee8dfb..cc4573e 100644
--- a/src/lib/about.ts
+++ b/src/lib/about.ts
@@ -8,6 +8,10 @@ export const LINKS = {
site: 'https://browsentic.com',
guide: 'https://browsentic.com/docs/guide/',
pairing: 'https://browsentic.com/docs/guide/install/#3-pair-them-once',
+ install: 'https://browsentic.com/install/',
+ downloadMac: 'https://browsentic.com/download/mac',
+ downloadWindowsX64: 'https://browsentic.com/download/windows-x64',
+ downloadWindowsArm64: 'https://browsentic.com/download/windows-arm64',
troubleshooting: 'https://browsentic.com/docs/guide/troubleshooting/',
windowsApp: 'https://browsentic.com/docs/guide/windows-app/',
changelog: 'https://browsentic.com/changelog/',
diff --git a/src/lib/actions/protocol.ts b/src/lib/actions/protocol.ts
index 4afd941..d0b07df 100644
--- a/src/lib/actions/protocol.ts
+++ b/src/lib/actions/protocol.ts
@@ -45,6 +45,8 @@ export type BridgeRequest =
| { channel: typeof BRIDGE_CHANNEL; op: 'invoke'; action: string; input?: unknown }
| { channel: typeof BRIDGE_CHANNEL; op: 'pair'; token: string }
| { channel: typeof BRIDGE_CHANNEL; op: 'disconnect' }
+ /** A page opened, or someone pressed Connect: pair through the native host. `wait` holds the ask open while a person decides. */
+ | { channel: typeof BRIDGE_CHANNEL; op: 'autoPair'; gesture?: boolean; wait?: boolean }
| { channel: typeof BRIDGE_CHANNEL; op: 'panelOpened' }
| { channel: typeof BRIDGE_CHANNEL; op: 'saveSkill'; skillId: string }
| { channel: typeof BRIDGE_CHANNEL; op: 'removeSkill'; skillId: string }
diff --git a/src/lib/bridge/auto-pair.test.ts b/src/lib/bridge/auto-pair.test.ts
new file mode 100644
index 0000000..37b10f0
--- /dev/null
+++ b/src/lib/bridge/auto-pair.test.ts
@@ -0,0 +1,253 @@
+import '@/daemon/test/sandbox';
+import { rmSync } from 'node:fs';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest';
+import { fakeBrowser } from 'wxt/testing';
+import { configPath, pairingMode } from '@/daemon/agent/config';
+import { clearAuth, listSessions } from '@/daemon/auth-store';
+import { startDaemon, type Daemon } from '@/daemon/daemon';
+import { readLockfile } from '@/daemon/lockfile';
+import { answerNativeMessage, type HostContext } from '@/daemon/native-messaging';
+import { RemoteBridge } from '@/daemon/remote-bridge';
+import type { DaemonState } from './socket';
+
+const ports = vi.hoisted(() => [] as number[]);
+vi.mock('@/lib/actions/protocol', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ DAEMON_PORTS: ports,
+}));
+
+const ORIGIN = 'chrome-extension://abcdefghijklmnopabcdefghijklmnop';
+
+type NodeWebSocket = new (url: string, init: { headers: Record<string, string> }) => WebSocket;
+
+class ExtensionSocket extends (WebSocket as unknown as NodeWebSocket) {
+ constructor(url: string) {
+ super(url, { headers: { origin: ORIGIN } });
+ }
+}
+vi.stubGlobal('WebSocket', ExtensionSocket);
+
+type Socket = typeof import('./socket');
+type AutoPair = typeof import('./auto-pair');
+
+let daemon: Daemon;
+let socket: Socket | undefined;
+let pairing: AutoPair;
+let host: ReturnType<typeof vi.fn>;
+const TEST_TIMEOUT_MS = 20_000;
+
+/** The real host's answer, as the browser would get it with Chrome passing this extension's origin. */
+const context: HostContext = {
+ ensure: async () => readLockfile()!,
+ held: () => false,
+ mode: () => pairingMode(),
+ version: '0.0.0-test',
+ app: () => null,
+ connect: (lock) => RemoteBridge.connect(lock.port, lock.token),
+};
+
+beforeAll(async () => {
+ daemon = await startDaemon({ version: '0.0.0-test', idleExit: false });
+ ports.push(daemon.port);
+});
+
+afterAll(() => daemon?.stop());
+
+beforeEach(async () => {
+ fakeBrowser.reset();
+ vi.resetModules();
+ vi.spyOn(fakeBrowser.runtime, 'getManifest').mockReturnValue({ version: '0.0.0-test' } as never);
+ host = vi.fn((_name: string, message: Record<string, unknown>) =>
+ answerNativeMessage(message, context, { family: 'chromium', origin: `${ORIGIN}/` }),
+ );
+ (fakeBrowser.runtime as unknown as { sendNativeMessage: typeof host }).sendNativeMessage = host;
+ socket = await import('./socket');
+ pairing = await import('./auto-pair');
+ pairing.serveAutoPair();
+});
+
+afterEach(async () => {
+ await socket?.disconnectDaemon();
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ clearAuth();
+ rmSync(configPath, { force: true });
+});
+
+const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+async function daemonState(): Promise<DaemonState | undefined> {
+ return (await fakeBrowser.storage.session.get('browsentic/daemon'))['browsentic/daemon'] as DaemonState | undefined;
+}
+
+async function until(check: (state: DaemonState | undefined) => boolean, what: string): Promise<void> {
+ for (let tries = 0; !check(await daemonState()); tries++) {
+ if (tries > 250) throw new Error(`never ${what}: ${JSON.stringify(await daemonState())}`);
+ await wait(20);
+ }
+}
+
+const online = () => until((state) => !!state?.connected, 'came online');
+
+async function control(): Promise<RemoteBridge> {
+ return RemoteBridge.connect(daemon.port, readLockfile()!.token);
+}
+
+describe('pairing by itself', () => {
+ test('a fresh install pairs with no code', async () => {
+ await pairing.autoPair('install');
+ await online();
+ expect(listSessions()).toEqual([expect.objectContaining({ pairedBy: 'auto', origin: ORIGIN })]);
+ }, TEST_TIMEOUT_MS);
+
+ test('a browser that holds a key never asks the host', async () => {
+ const bridge = await control();
+ const { code } = await bridge.pair();
+ bridge.close();
+ expect(await socket!.pairDaemon(code)).toEqual({ ok: true });
+
+ await pairing.autoPair('alarm');
+ expect(host).not.toHaveBeenCalled();
+ }, TEST_TIMEOUT_MS);
+
+ test('with no Bridge, says so and looks again a minute later, not at every alarm', async () => {
+ host.mockRejectedValue(new Error('Specified native messaging host not found.'));
+ await pairing.autoPair('install');
+ await until((state) => state?.bridge === 'missing', 'said the Bridge is missing');
+
+ await pairing.autoPair('alarm');
+ expect(host).toHaveBeenCalledOnce();
+ }, TEST_TIMEOUT_MS);
+
+ test('a click looks again at once', async () => {
+ host.mockRejectedValueOnce(new Error('Specified native messaging host not found.'));
+ await pairing.autoPair('install');
+ await pairing.autoPair('gesture', { gesture: true });
+ await online();
+ }, TEST_TIMEOUT_MS);
+
+ test('says when automatic pairing is off, and leaves the code to the user', async () => {
+ const bridge = await control();
+ await bridge.pairing('code');
+ bridge.close();
+
+ await pairing.autoPair('install');
+ await until((state) => state?.bridge === 'off', 'said pairing is off');
+ expect(listSessions()).toEqual([]);
+ }, TEST_TIMEOUT_MS);
+});
+
+describe('staying unpaired when asked to', () => {
+ test('Disconnect holds it off until Connect', async () => {
+ await pairing.autoPair('install');
+ await online();
+ await socket!.disconnectDaemon();
+ await pairing.holdAutoPair();
+ host.mockClear();
+
+ await pairing.autoPair('alarm');
+ expect(host).not.toHaveBeenCalled();
+ expect((await daemonState())?.pairing).toEqual({ manual: true });
+
+ await pairing.autoPair('gesture', { gesture: true });
+ await online();
+ }, TEST_TIMEOUT_MS);
+
+ test('a browser this computer unpaired is told so, and comes back only on Reconnect', async () => {
+ await pairing.autoPair('install');
+ await online();
+ const id = listSessions()[0].installId!;
+ const bridge = await control();
+ await bridge.revoke(id);
+ bridge.close();
+ await until((state) => !state?.connected, 'went offline');
+
+ await socket!.connectDaemon();
+ await until((state) => state?.pairing?.blocked === 'revoked', 'heard it was revoked');
+ host.mockClear();
+ await pairing.autoPair('alarm');
+ expect(host).not.toHaveBeenCalled();
+
+ await pairing.autoPair('gesture', { gesture: true });
+ await online();
+ }, TEST_TIMEOUT_MS);
+});
+
+describe('a Bridge that forgot this browser', () => {
+ test('is paired with again, and the old key is kept until the new one arrives', async () => {
+ await pairing.autoPair('install');
+ await online();
+ const { 'browsentic/sessionKey': before } = await fakeBrowser.storage.local.get('browsentic/sessionKey');
+ await socket!.disconnectDaemon();
+ await fakeBrowser.storage.local.set({ 'browsentic/sessionKey': before });
+ await fakeBrowser.storage.session.set({ 'browsentic/daemon': { connected: false, paired: true, lastChangeAt: Date.now() } });
+ clearAuth();
+
+ await socket!.connectDaemon();
+ await online();
+ const { 'browsentic/sessionKey': after } = await fakeBrowser.storage.local.get('browsentic/sessionKey');
+ expect(after).toBeTypeOf('string');
+ expect(after).not.toBe(before);
+ }, TEST_TIMEOUT_MS);
+});
+
+describe('ask mode', () => {
+ test('waits for someone to allow this browser, and connects the moment they do', async () => {
+ const approver = await control();
+ await approver.pairing('ask');
+
+ const asking = pairing.autoPair('open', { wait: true });
+ let requests = await approver.pairRequests();
+ while (!requests.length) {
+ await wait(20);
+ requests = await approver.pairRequests();
+ }
+ await approver.decide(requests[0].id, true);
+ approver.close();
+
+ await asking;
+ await online();
+ expect(listSessions()).toEqual([expect.objectContaining({ pairedBy: 'approved' })]);
+ }, TEST_TIMEOUT_MS);
+
+ test('shows who has to allow it while nobody has', async () => {
+ const bridge = await control();
+ await bridge.pairing('ask');
+ bridge.close();
+
+ await pairing.autoPair('open');
+ await until((state) => !!state?.pairing?.wait, 'said it is waiting');
+ expect((await daemonState())?.pairing).toMatchObject({ mode: 'ask', wait: { approver: 'terminal' } });
+ }, TEST_TIMEOUT_MS);
+});
+
+describe('isDue', () => {
+ const at = 1_000_000_000;
+ const minute = 60_000;
+
+ test('spaces attempts by what the last one found', () => {
+ const last = (outcome: Parameters<typeof pairing.isDue>[1] extends infer L ? (L extends { outcome: infer O } ? O : never) : never, ago: number, extra = {}) => ({
+ at: at - ago,
+ outcome,
+ failures: 0,
+ ...extra,
+ });
+ expect(pairing.isDue('alarm', undefined, false, at)).toBe(true);
+ expect(pairing.isDue('open', last('missing', 1_000), false, at)).toBe(false);
+ expect(pairing.isDue('open', last('missing', 6_000), false, at)).toBe(true);
+ expect(pairing.isDue('alarm', last('missing', minute, { missingSince: at - 2 * minute }), false, at)).toBe(true);
+ expect(pairing.isDue('alarm', last('missing', 2 * minute, { missingSince: at - 20 * minute }), false, at)).toBe(false);
+ expect(pairing.isDue('alarm', last('old', 30 * minute), false, at)).toBe(false);
+ expect(pairing.isDue('alarm', last('failed', 3 * minute, { failures: 3 }), false, at)).toBe(false);
+ expect(pairing.isDue('alarm', last('failed', 5 * minute, { failures: 3 }), false, at)).toBe(true);
+ expect(pairing.isDue('alarm', last('off', 600 * minute), false, at)).toBe(false);
+ expect(pairing.isDue('startup', last('off', 6_000), false, at)).toBe(true);
+ });
+
+ test('never tries a revoked or denied browser again unasked, and always on a click', () => {
+ for (const outcome of ['revoked', 'denied'] as const) {
+ const last = { at: at - 600 * minute, outcome, failures: 0 };
+ expect(['alarm', 'open', 'startup', 'install'].some((reason) => pairing.isDue(reason as 'alarm', last, false, at))).toBe(false);
+ expect(pairing.isDue('gesture', last, true, at)).toBe(true);
+ }
+ });
+});
diff --git a/src/lib/bridge/auto-pair.ts b/src/lib/bridge/auto-pair.ts
new file mode 100644
index 0000000..d84306e
--- /dev/null
+++ b/src/lib/bridge/auto-pair.ts
@@ -0,0 +1,135 @@
+/**
+ * Pairs this browser with Browsentic Bridge by itself, through the native host. Every attempt launches
+ * a process on the computer, so attempts are spaced by what the last one found, and nothing here ever
+ * replaces a session key except a new one the Bridge proved it issued.
+ */
+
+import { browser } from 'wxt/browser';
+import { MAX_PAIR_WAIT_MS, type PairReason } from '@/lib/pairing';
+import { askHost, type BridgeReach, type PairAttempt } from './native-pair';
+import { onStaleKey, onWelcome, pairingNow, redeemGrant, reportPairing, sessionKeyUsable, type PairingState } from './socket';
+
+/** Set when the user pressed Disconnect here; only Connect lifts it. */
+const MANUAL_KEY = 'browsentic/pairManual';
+const LAST_KEY = 'browsentic/pairLast';
+
+const MINUTE = 60_000;
+/** However it is asked for, an attempt waits this long after the last one, unless someone clicked. */
+const FLOOR_MS = 5_000;
+const MISSING_EARLY_MS = 10 * MINUTE;
+
+interface LastAttempt {
+ at: number;
+ outcome: BridgeReach | 'wait' | 'revoked' | 'denied';
+ /** When the current run of "Bridge missing" began, which decides how often to look again. */
+ missingSince?: number;
+ failures: number;
+ /** What the surfaces were shown, shown again when no attempt is due. */
+ reach?: BridgeReach;
+ pairing?: PairingState;
+}
+
+/** How long an alarm waits after an attempt that ended this way; Infinity leaves it to a person. */
+function alarmGap(last: LastAttempt, now: number): number {
+ switch (last.outcome) {
+ case 'missing':
+ return now - (last.missingSince ?? last.at) < MISSING_EARLY_MS ? MINUTE : 15 * MINUTE;
+ case 'old':
+ case 'forbidden':
+ case 'policy':
+ return 60 * MINUTE;
+ case 'stopped':
+ return 10 * MINUTE;
+ case 'failed':
+ return Math.min(30, 2 ** Math.max(0, last.failures - 1)) * MINUTE;
+ case 'wait':
+ case 'ready':
+ return MINUTE;
+ default:
+ return Infinity;
+ }
+}
+
+/** A revoke or a deny is never tried again unasked; a page opening, an install or a restart may try anything else, since the mode may have changed. */
+export function isDue(reason: PairReason, last: LastAttempt | undefined, gesture: boolean, now = Date.now()): boolean {
+ if (gesture || !last) return true;
+ if (now - last.at < FLOOR_MS || last.outcome === 'revoked' || last.outcome === 'denied') return false;
+ return reason !== 'alarm' || now - last.at >= alarmGap(last, now);
+}
+
+export interface PairOptions {
+ gesture?: boolean;
+ /** Hold the ask open while someone decides; only while a page is open to show it. */
+ wait?: boolean;
+}
+
+let inflight: Promise<void> | null = null;
+
+/** One attempt at a time; a click that arrives during one is answered by another right after it. */
+export function autoPair(reason: PairReason, options: PairOptions = {}): Promise<void> {
+ if (inflight) return options.gesture ? inflight.then(() => autoPair(reason, options)) : inflight;
+ inflight = attempt(reason, options).finally(() => (inflight = null));
+ return inflight;
+}
+
+async function attempt(reason: PairReason, { gesture = false, wait = false }: PairOptions): Promise<void> {
+ if (await sessionKeyUsable()) return;
+ if (gesture) await browser.storage.local.remove(MANUAL_KEY);
+ else if ((await browser.storage.local.get(MANUAL_KEY))[MANUAL_KEY]) return reportPairing(undefined, { manual: true });
+ else if ((await pairingNow())?.blocked) return;
+
+ const last = (await browser.storage.local.get(LAST_KEY))[LAST_KEY] as LastAttempt | undefined;
+ if (!isDue(reason, last, gesture)) return last?.pairing ? reportPairing(last.reach, last.pairing) : undefined;
+
+ const answer = await askHost(reason, { gesture, waitMs: wait ? MAX_PAIR_WAIT_MS : 0 });
+ if (answer.kind === 'grant') {
+ await reportPairing('ready', { mode: answer.mode });
+ const redeemed = await redeemGrant(answer.grant.code, answer.grant.port);
+ if (redeemed.ok) return;
+ const failed: PairingState = { mode: answer.mode, error: redeemed.error };
+ await remember(last, 'failed', 'ready', failed);
+ return reportPairing('ready', failed);
+ }
+ const [reach, pairing, outcome] = settled(answer);
+ await remember(last, outcome, reach, pairing);
+ await reportPairing(reach, pairing);
+}
+
+function settled(answer: Exclude<PairAttempt, { kind: 'grant' }>): [BridgeReach, PairingState, LastAttempt['outcome']] {
+ if (answer.kind === 'wait') return ['ready', { mode: answer.mode, wait: { approver: answer.approver } }, 'wait'];
+ if (answer.kind === 'unreachable') return [answer.reach, { error: answer.message }, answer.reach];
+ const { refusal, message, mode } = answer;
+ if (refusal === 'revoked' || refusal === 'denied') return ['ready', { mode, blocked: refusal, error: message }, refusal];
+ if (refusal === 'off') return ['off', { mode: 'code', error: message }, 'off'];
+ if (refusal === 'stopped') return ['stopped', { mode, error: message }, 'stopped'];
+ return ['failed', { mode, error: message }, 'failed'];
+}
+
+async function remember(last: LastAttempt | undefined, outcome: LastAttempt['outcome'], reach: BridgeReach, pairing: PairingState): Promise<void> {
+ const now = Date.now();
+ const next: LastAttempt = {
+ at: now,
+ outcome,
+ missingSince: outcome === 'missing' ? (last?.outcome === 'missing' ? last.missingSince ?? last.at : now) : undefined,
+ failures: outcome === 'failed' ? (last?.outcome === 'failed' ? last.failures + 1 : 1) : 0,
+ reach,
+ pairing,
+ };
+ await browser.storage.local.set({ [LAST_KEY]: next });
+}
+
+/** The user pressed Disconnect here: this browser stays unpaired until they press Connect. */
+export async function holdAutoPair(): Promise<void> {
+ await browser.storage.local.set({ [MANUAL_KEY]: true });
+ await reportPairing(undefined, { manual: true });
+}
+
+/** A browser coming back after a restart, an update or a Bridge that forgot it starts over, not where an old failure left it. */
+async function forgetLast(): Promise<void> {
+ await browser.storage.local.remove(LAST_KEY);
+}
+
+export function serveAutoPair(): void {
+ onWelcome(() => void forgetLast());
+ onStaleKey(() => void forgetLast().then(() => autoPair('unknown-session')));
+}
diff --git a/src/lib/bridge/native-pair.test.ts b/src/lib/bridge/native-pair.test.ts
new file mode 100644
index 0000000..8eaebbd
--- /dev/null
+++ b/src/lib/bridge/native-pair.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, test } from 'vitest';
+import { classifyHostError, readReply } from './native-pair';
+
+describe('classifyHostError', () => {
+ test('reads each browser’s own words', () => {
+ expect(classifyHostError('Specified native messaging host not found.')).toBe('missing');
+ expect(classifyHostError('No such native application com.browsentic.daemon')).toBe('missing');
+ expect(classifyHostError('Access to the specified native messaging host is forbidden.')).toBe('forbidden');
+ expect(classifyHostError('Access to the native messaging host was disabled by the system administrator.')).toBe('policy');
+ });
+
+ test('calls anything else a failure to start, never a confident cause', () => {
+ for (const message of ['Native host has exited.', 'Failed to start native messaging host.', 'Error when communicating with the native messaging host.', 'An unexpected error occurred', 'something new']) {
+ expect(classifyHostError(message)).toBe('failed');
+ }
+ });
+});
+
+describe('readReply', () => {
+ const grant = { code: 'G'.repeat(26), port: 8766, expiresAt: 1 };
+
+ test('takes a grant, a wait or a refusal as the host gave it', () => {
+ expect(readReply({ ok: true, grant, mode: 'auto', approver: 'app' })).toEqual({ kind: 'grant', grant, mode: 'auto', approver: 'app' });
+ expect(readReply({ ok: false, wait: { request: 'r', approver: 'app', retryAfterMs: 3000 }, mode: 'ask' })).toEqual({ kind: 'wait', approver: 'app', mode: 'ask' });
+ expect(readReply({ ok: false, refused: 'revoked', error: 'gone', mode: 'auto' })).toEqual({ kind: 'refused', refusal: 'revoked', message: 'gone', mode: 'auto' });
+ });
+
+ test('knows a host from before automatic pairing by the words it answers anything new with', () => {
+ expect(readReply({ ok: false, error: 'Expected {"op":"ensure"}.' })).toMatchObject({ kind: 'unreachable', reach: 'old' });
+ });
+
+ test('never pairs on a grant it cannot trust the shape of', () => {
+ for (const bad of [{ ...grant, port: 0 }, { ...grant, port: 70_000 }, { ...grant, code: 'short' }, { ...grant, port: '8766' }, null]) {
+ expect(readReply({ ok: true, grant: bad, mode: 'auto' })).toMatchObject({ kind: 'unreachable', reach: 'failed' });
+ }
+ expect(readReply(undefined)).toMatchObject({ kind: 'unreachable', reach: 'failed' });
+ expect(readReply({ ok: false, refused: 'whatever', error: 'x' })).toMatchObject({ kind: 'unreachable', reach: 'failed' });
+ });
+});
diff --git a/src/lib/bridge/native-pair.ts b/src/lib/bridge/native-pair.ts
new file mode 100644
index 0000000..c840a17
--- /dev/null
+++ b/src/lib/bridge/native-pair.ts
@@ -0,0 +1,119 @@
+import { browser } from 'wxt/browser';
+import { NATIVE_HOST_NAME, SOCKET_PROTOCOL_VERSION } from '@/lib/actions/protocol';
+import {
+ isPairingMode,
+ type Approver,
+ type Grant,
+ type HostPairRequest,
+ type PairRefusal,
+ type PairReason,
+ type PairingMode,
+} from '@/lib/pairing';
+import { identify } from './identity';
+
+/** Whether this browser can reach Browsentic Bridge's native host, and in what shape. */
+export type BridgeReach = 'ready' | 'old' | 'missing' | 'forbidden' | 'policy' | 'stopped' | 'failed' | 'off';
+
+export type PairAttempt =
+ | { kind: 'grant'; grant: Grant; mode: PairingMode; approver: Approver }
+ | { kind: 'wait'; approver: Approver; mode: PairingMode }
+ | { kind: 'refused'; refusal: PairRefusal; message: string; mode?: PairingMode }
+ | { kind: 'unreachable'; reach: Exclude<BridgeReach, 'ready' | 'stopped' | 'off'>; message: string };
+
+/** Past the host's own deadline, so the host's own answer wins whenever it gives one. */
+const HOST_TIMEOUT_MS = 15_000;
+
+/**
+ * The browsers' own words (native_message_host.cc, message_service.cc, NativeMessaging.sys.mjs). Chromium
+ * says "not found" for a missing manifest, a missing binary and a policy that turns per-user hosts off
+ * alike, and Firefox says it for a host that would not let this extension in too, on purpose.
+ */
+const HOST_ERRORS: [RegExp, BridgeReach][] = [
+ [/Specified native messaging host not found/i, 'missing'],
+ [/No such native application/i, 'missing'],
+ [/Access to the specified native messaging host is forbidden/i, 'forbidden'],
+ [/disabled by the system administrator/i, 'policy'],
+];
+
+export function classifyHostError(message: string): Exclude<BridgeReach, 'ready' | 'stopped' | 'off'> {
+ const known = HOST_ERRORS.find(([pattern]) => pattern.test(message))?.[1];
+ return known === 'missing' || known === 'forbidden' || known === 'policy' ? known : 'failed';
+}
+
+const OLD_HOST = 'Expected {"op":"ensure"}.';
+
+const APPROVERS: readonly Approver[] = ['app', 'terminal'];
+const REFUSALS: readonly PairRefusal[] = ['off', 'revoked', 'denied', 'stopped', 'origin', 'restart'];
+
+const isGrant = (value: unknown): value is Grant => {
+ const grant = value as Partial<Grant> | null;
+ return (
+ typeof grant?.code === 'string' &&
+ grant.code.length >= 8 &&
+ typeof grant.port === 'number' &&
+ Number.isInteger(grant.port) &&
+ grant.port > 0 &&
+ grant.port < 65_536 &&
+ typeof grant.expiresAt === 'number'
+ );
+};
+
+/** Anything a host says that is not plainly a grant, a wait or a refusal is a failure: it never pairs. */
+export function readReply(reply: unknown): PairAttempt {
+ const answer = (reply ?? {}) as Record<string, unknown>;
+ const mode = isPairingMode(answer.mode) ? answer.mode : undefined;
+ const approver = APPROVERS.includes(answer.approver as Approver) ? (answer.approver as Approver) : 'terminal';
+ if (answer.ok === true && isGrant(answer.grant)) return { kind: 'grant', grant: answer.grant, mode: mode ?? 'auto', approver };
+ const wait = answer.wait as { approver?: unknown } | undefined;
+ if (answer.ok === false && wait && typeof wait === 'object') {
+ return { kind: 'wait', approver: APPROVERS.includes(wait.approver as Approver) ? (wait.approver as Approver) : 'terminal', mode: mode ?? 'ask' };
+ }
+ const message = typeof answer.error === 'string' ? answer.error : 'Browsentic Bridge gave no answer it could read.';
+ if (answer.ok === false && REFUSALS.includes(answer.refused as PairRefusal)) {
+ return { kind: 'refused', refusal: answer.refused as PairRefusal, message, mode };
+ }
+ if (message === OLD_HOST) return { kind: 'unreachable', reach: 'old', message };
+ return { kind: 'unreachable', reach: 'failed', message };
+}
+
+export interface AskOptions {
+ gesture?: boolean;
+ /** How long the host may hold the answer while ask mode waits on a person. */
+ waitMs?: number;
+}
+
+export async function askHost(reason: PairReason, { gesture = false, waitMs = 0 }: AskOptions = {}): Promise<PairAttempt> {
+ const { installId, browser: name } = await identify();
+ const request: HostPairRequest = {
+ op: 'pair',
+ installId,
+ browser: name,
+ extensionVersion: browser.runtime.getManifest().version,
+ protocolVersion: SOCKET_PROTOCOL_VERSION,
+ reason,
+ gesture,
+ waitMs,
+ };
+ try {
+ return readReply(await withTimeout(browser.runtime.sendNativeMessage(NATIVE_HOST_NAME, request), HOST_TIMEOUT_MS + waitMs));
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ return { kind: 'unreachable', reach: classifyHostError(message), message };
+ }
+}
+
+function withTimeout<T>(pending: Promise<T>, ms: number): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('Browsentic Bridge took too long to answer.')), ms);
+ pending.then(
+ (value) => {
+ clearTimeout(timer);
+ resolve(value);
+ },
+ (error: unknown) => {
+ clearTimeout(timer);
+ reject(error);
+ },
+ );
+ });
+}
diff --git a/src/lib/bridge/socket.ts b/src/lib/bridge/socket.ts
index 3a0c5e6..24bec69 100644
--- a/src/lib/bridge/socket.ts
+++ b/src/lib/bridge/socket.ts
@@ -33,7 +33,9 @@ import type { PreferenceChange, Preferences } from '@/lib/settings/preferences';
import type { SkillDraft } from '@/lib/skills/format';
import type { SiteMapDraft } from '@/lib/skills/site-map';
import type { TaskList, TaskOrder, TaskResult } from '@/lib/schedules/task';
+import type { Approver, PairingMode, RefusalCode } from '@/lib/pairing';
import { identify } from './identity';
+import type { BridgeReach } from './native-pair';
import { invokeForHarness } from './invoke';
import { wakeDaemon } from './native-wake';
@@ -41,6 +43,8 @@ export const DAEMON_STATE_KEY = 'browsentic/daemon';
export const RECONNECT_ALARM = 'browsentic/reconnect';
export const TASKS_KEY = 'browsentic/tasks';
const SESSION_KEY_STORE = 'browsentic/sessionKey';
+/** Set when the Bridge said it holds no session for the stored key: kept until a new one replaces it, but no longer worth dialling with. */
+const STALE_KEY_STORE = 'browsentic/staleKey';
const BASE_DELAY_MS = 1_000;
const MAX_DELAY_MS = 30_000;
@@ -58,6 +62,7 @@ interface Credential {
interface Refusal {
reason: string;
retryable: boolean;
+ code?: RefusalCode;
}
interface Attempt {
@@ -88,9 +93,24 @@ export interface DaemonState {
/** The phones the Bridge sees. Pushed only by a Bridge that speaks Android, on connect and on every change. */
android?: AndroidState;
error?: string;
+ /** Whether this browser can reach Browsentic Bridge's native host. Absent until it has been asked. */
+ bridge?: BridgeReach;
+ /** Where pairing by itself stands, while this browser is not paired. */
+ pairing?: PairingState;
lastChangeAt: number;
}
+export interface PairingState {
+ mode?: PairingMode;
+ /** Waiting for someone to allow this browser, in the app or in a terminal. */
+ wait?: { approver: Approver };
+ /** This computer unpaired or turned down this browser; only Reconnect or a code brings it back. */
+ blocked?: 'revoked' | 'denied';
+ /** The user pressed Disconnect here, so it does not pair again by itself. */
+ manual?: boolean;
+ error?: string;
+}
+
let socket: WebSocket | null = null;
let welcomedSocket: WebSocket | null = null;
let daemonProtocol = 0;
@@ -103,6 +123,7 @@ const welcomeListeners = new Set<(daemonVersion: string) => void>();
let draftListener: ((runId: string, draft: SiteMapDraft) => void) | null = null;
let taskRunner: ((order: TaskOrder) => Promise<ActionResult>) | null = null;
let preferencesListener: ((preferences: Preferences) => void) | null = null;
+const staleKeyListeners = new Set<() => void>();
export type CdpEvent = Extract<SocketFrame, { t: 'cdpEvent' }>;
@@ -136,6 +157,14 @@ export function onRunEvent(listener: (runId: string, event: RunEvent) => void):
runListener = listener;
}
+/** The Bridge proved itself and does not know the stored key: a wiped or reinstalled Bridge, to pair with again. */
+export const onStaleKey = (listener: () => void) => listen(staleKeyListeners, listener);
+
+export async function sessionKeyUsable(): Promise<boolean> {
+ const stored = await browser.storage.session.get(STALE_KEY_STORE);
+ return !stored[STALE_KEY_STORE] && !!(await storedSessionKey());
+}
+
export function onWelcome(listener: (daemonVersion: string) => void): void {
welcomeListeners.add(listener);
}
@@ -460,7 +489,7 @@ async function reconnect(): Promise<void> {
const state = await readState();
if ((state && !state.paired && state.error) || isLive()) return;
clearTimeout(reconnectTimer);
- dial({ kind: 'session', secret: sessionKey }, 0);
+ dial({ kind: 'session', secret: sessionKey }, DAEMON_PORTS, 0);
}
export async function pairDaemon(pairingToken: string): Promise<{ ok: boolean; error?: string }> {
@@ -470,9 +499,25 @@ export async function pairDaemon(pairingToken: string): Promise<{ ok: boolean; e
disconnectSocket();
clearTimeout(reconnectTimer);
attempts = 0;
+ return pairWith(code, DAEMON_PORTS);
+}
+
+/**
+ * Redeems a grant the native host handed over: never typed, so never normalised, and tried first on the
+ * port of the Bridge that issued it, which may not be the first one answering.
+ */
+export function redeemGrant(code: string, port: number): Promise<{ ok: boolean; error?: string }> {
+ disconnectSocket();
+ clearTimeout(reconnectTimer);
+ attempts = 0;
+ return pairWith(code, [port, ...DAEMON_PORTS.filter((other) => other !== port)]);
+}
+
+function pairWith(code: string, ports: readonly number[]): Promise<{ ok: boolean; error?: string }> {
+ settlePairing({ ok: false, error: 'Superseded by a newer pairing attempt.' });
return new Promise((resolve) => {
pairingResult = resolve;
- dial({ kind: 'pair', secret: code }, 0);
+ dial({ kind: 'pair', secret: code }, ports, 0);
setTimeout(
() => settlePairing({ ok: false, error: 'No Browsentic daemon is running. Start one with "browsentic pair".' }),
PAIRING_TIMEOUT_MS,
@@ -484,9 +529,23 @@ export async function disconnectDaemon(): Promise<void> {
clearTimeout(reconnectTimer);
disconnectSocket();
await browser.storage.local.remove(SESSION_KEY_STORE);
+ await browser.storage.session.remove(STALE_KEY_STORE);
await setState({ connected: false, paired: false, error: undefined, agent: undefined, android: undefined, lastChangeAt: Date.now() });
}
+/** An update may be what a refusal was waiting for, so the link is tried again with the key it has. */
+export async function retryAfterUpdate(): Promise<void> {
+ const state = await readState();
+ if (state && !state.paired && state.error) await setState({ error: undefined, lastChangeAt: Date.now() });
+ await connectDaemon();
+}
+
+export const pairingNow = async (): Promise<PairingState | undefined> => (await readState())?.pairing;
+
+/** Where pairing by itself stands, for the surfaces to show while this browser is not paired. */
+export const reportPairing = (bridge: BridgeReach | undefined, pairing: PairingState | undefined): Promise<void> =>
+ setState({ bridge, pairing, lastChangeAt: Date.now() });
+
let pairingResult: ((result: { ok: boolean; error?: string }) => void) | null = null;
function settlePairing(result: { ok: boolean; error?: string }): void {
@@ -512,10 +571,10 @@ function disconnectSocket(): void {
}
}
-function dial(credential: Credential, portIndex: number, carried?: Refusal): void {
- if (portIndex >= DAEMON_PORTS.length) return giveUp(credential, carried);
+function dial(credential: Credential, ports: readonly number[], portIndex: number, carried?: Refusal): void {
+ if (portIndex >= ports.length) return giveUp(credential, carried);
- const port = DAEMON_PORTS[portIndex];
+ const port = ports[portIndex];
const ws = new WebSocket(`ws://127.0.0.1:${port}/extension`);
socket = ws;
let settled = false;
@@ -581,7 +640,7 @@ function dial(credential: Credential, portIndex: number, carried?: Refusal): voi
refusal ??= closeRefusal(event);
// Nothing on this port ever proved itself — a squatter, a stale daemon, an empty port — so the
// walk continues instead of pinning the extension to whoever answered first.
- if (!welcomed) return dial(credential, portIndex + 1, refusal);
+ if (!welcomed) return dial(credential, ports, portIndex + 1, refusal);
void setState({ connected: false, paired: true, error: undefined, android: undefined, lastChangeAt: Date.now() });
for (const [id] of pendingPhoneOps) settlePhoneOp(id, failure('PHONE_GONE', 'The link to Browsentic Bridge went down.'));
for (const listener of closedListeners) listener();
@@ -594,15 +653,13 @@ const OWN_CLOSE = new Set(['unproven daemon', '']);
function closeRefusal(event: CloseEvent): Refusal | undefined {
const reason = event.reason?.trim();
if (!reason || OWN_CLOSE.has(reason)) return undefined;
- return /protocol version mismatch/i.test(reason)
- ? { reason: `${reason}. Rebuild and reload the extension — “yarn build”, then Reload at chrome://extensions.`, retryable: false }
- : { reason, retryable: true };
+ return /protocol version mismatch/i.test(reason) ? { reason, retryable: false } : { reason, retryable: true };
}
function giveUp(credential: Credential, refusal?: Refusal): void {
if (refusal && !refusal.retryable) {
settlePairing({ ok: false, error: refusal.reason });
- void setState({ connected: false, paired: false, error: refusal.reason, lastChangeAt: Date.now() });
+ void refuse(credential, refusal);
return;
}
settlePairing({ ok: false, error: refusal?.reason ?? 'No Browsentic daemon is running.' });
@@ -615,6 +672,25 @@ function giveUp(credential: Credential, refusal?: Refusal): void {
});
}
+async function refuse(credential: Credential, refusal: Refusal): Promise<void> {
+ const reason = await adviceFor(refusal.reason);
+ const blocked = credential.kind === 'session' && refusal.code === 'revoked' ? { pairing: { blocked: 'revoked' as const } } : {};
+ await setState({ connected: false, paired: false, error: reason, ...blocked, lastChangeAt: Date.now() });
+ if (credential.kind !== 'session' || (refusal.code !== 'unknown' && refusal.code !== 'revoked')) return;
+ // Either way the Bridge holds no session for this key; only a Bridge that forgot it is paired with again unasked.
+ await browser.storage.session.set({ [STALE_KEY_STORE]: true });
+ if (refusal.code === 'unknown') for (const listener of staleKeyListeners) listener();
+}
+
+/** A store copy cannot be rebuilt: it is told the store update is on its way, and the store is asked for it now. */
+async function adviceFor(reason: string): Promise<string> {
+ if (!/protocol version mismatch/i.test(reason)) return reason;
+ const unpacked = (await browser.management.getSelf().catch(() => null))?.installType === 'development';
+ if (unpacked) return `${reason}. Rebuild and reload the extension — “yarn build”, then Reload at chrome://extensions.`;
+ if (!import.meta.env.FIREFOX) await browser.runtime.requestUpdateCheck().catch(() => undefined);
+ return `${reason}. This copy of Browsentic is older than Browsentic Bridge; the browser installs its update shortly.`;
+}
+
function transcriptOf(attempt: Attempt): Transcript {
return {
protocolVersion: SOCKET_PROTOCOL_VERSION,
@@ -645,7 +721,7 @@ async function handle(ws: WebSocket, raw: string, attempt: Attempt): Promise<voi
// Nothing has proved itself yet, so this is a claim, not a verdict: note it and try the next port.
case 'unauthorized':
- return attempt.walk({ reason: frame.reason, retryable: frame.retryable !== false });
+ return attempt.walk({ reason: frame.reason, retryable: frame.retryable !== false, code: frame.code });
case 'welcome': {
const secret = attempt.secret;
@@ -669,7 +745,10 @@ async function handle(ws: WebSocket, raw: string, attempt: Attempt): Promise<voi
// backoff on the welcome alone lets two peers take the link from each other every second.
clearTimeout(stableTimer);
stableTimer = setTimeout(() => (attempts = 0), STABLE_AFTER_MS);
- if (sessionKey) await browser.storage.local.set({ [SESSION_KEY_STORE]: sessionKey });
+ if (sessionKey) {
+ await browser.storage.local.set({ [SESSION_KEY_STORE]: sessionKey });
+ await browser.storage.session.remove(STALE_KEY_STORE);
+ }
settlePairing({ ok: true });
await setState({
connected: true,
@@ -679,6 +758,7 @@ async function handle(ws: WebSocket, raw: string, attempt: Attempt): Promise<voi
protocolVersion: frame.protocolVersion,
manifestInSync: frame.manifestInSync,
error: undefined,
+ pairing: undefined,
lastChangeAt: Date.now(),
});
for (const listener of welcomeListeners) listener(frame.daemonVersion);
diff --git a/src/lib/bridge/use-auto-pair.ts b/src/lib/bridge/use-auto-pair.ts
new file mode 100644
index 0000000..93d8362
--- /dev/null
+++ b/src/lib/bridge/use-auto-pair.ts
@@ -0,0 +1,43 @@
+import { useCallback, useEffect } from 'react';
+import { browser } from 'wxt/browser';
+import { BRIDGE_CHANNEL, type ActionResult } from '@/lib/actions/protocol';
+import type { DaemonState } from './socket';
+
+const BETWEEN_WAITS_MS = 3_000;
+
+const ask = (options: { gesture?: boolean; wait?: boolean } = {}) =>
+ browser.runtime.sendMessage({ channel: BRIDGE_CHANNEL, op: 'autoPair', ...options }) as Promise<ActionResult>;
+
+/**
+ * While a page that shows the link is open and this browser is not paired, it asks to pair once, and
+ * holds the ask open while someone decides in the app or a terminal, so the page connects the moment
+ * they allow it. `connect` is the click that lets a disconnected or turned-down browser try again.
+ */
+export function useAutoPair(daemon: DaemonState | null): { connect: () => Promise<void> } {
+ const unpaired = !!daemon && !daemon.paired;
+ const waiting = unpaired && !!daemon?.pairing?.wait;
+
+ useEffect(() => {
+ if (unpaired) void ask().catch(() => undefined);
+ }, [unpaired]);
+
+ useEffect(() => {
+ if (!waiting) return;
+ let live = true;
+ void (async () => {
+ while (live) {
+ await ask({ wait: true }).catch(() => undefined);
+ await new Promise((resolve) => setTimeout(resolve, BETWEEN_WAITS_MS));
+ }
+ })();
+ return () => {
+ live = false;
+ };
+ }, [waiting]);
+
+ const connect = useCallback(async () => {
+ await ask({ gesture: true }).catch(() => undefined);
+ }, []);
+
+ return { connect };
+}