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.

fix(extension): a browser start or a page opening during an attempt gets a look of its own, and starting again looks for a missing Bridge every minute again; a page asks again when it comes back into view and stops holding an approval open after ten minutes; a refusal with no code behind it shows its reason with the code form first; a code typed after Disconnect lifts the hold; a grant is not redeemed over a key a code gave meanwhile; a refused grant, an old Bridge still running and a browser without a side panel each get words of their own; a pairing timer no longer fails the attempt after it

Shahriar9aef2e26e263
diff --git a/src/extension/components/daemon-link.tsx b/src/extension/components/daemon-link.tsx
index 9671daf..cf8bfaa 100644
--- a/src/extension/components/daemon-link.tsx
+++ b/src/extension/components/daemon-link.tsx
@@ -56,10 +56,6 @@ export function DaemonLink() {
) : (
<PairingStatus daemon={daemon} onConnect={connect} />
)}
-
- {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/pairing-status.tsx b/src/extension/components/pairing-status.tsx
index 0597598..d8c1e30 100644
--- a/src/extension/components/pairing-status.tsx
+++ b/src/extension/components/pairing-status.tsx
@@ -20,6 +20,8 @@ interface Shown {
busy?: boolean;
/** Show the command that installs the Bridge, and the install guide. */
install?: boolean;
+ /** The Bridge refused this browser's key, and says why. */
+ alert?: boolean;
}
const Command = ({ children }: { children: ReactNode }) => (
@@ -36,6 +38,7 @@ export function describePairing(daemon: DaemonState | null, unpacked: boolean):
}
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' };
+ if (!pairing && daemon?.error) return { text: daemon.error, codeFirst: true, alert: true };
switch (daemon?.bridge) {
case 'missing':
return {
@@ -90,10 +93,14 @@ export function PairingStatus({ daemon, onConnect }: { daemon: DaemonState | nul
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.alert ? (
+ <p className="rounded-lg border border-destructive/40 bg-destructive/10 px-2 py-1.5 text-[11px] text-destructive">{shown.text}</p>
+ ) : (
+ <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.install && <InstallSteps />}
diff --git a/src/extension/entrypoints/background.ts b/src/extension/entrypoints/background.ts
index ba0d37b..7db1b99 100644
--- a/src/extension/entrypoints/background.ts
+++ b/src/extension/entrypoints/background.ts
@@ -26,7 +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 { autoPair, holdAutoPair, releaseAutoPair, serveAutoPair } from '@/lib/bridge/auto-pair';
import { isAgentKind } from '@/lib/agents/catalog';
import { isPreferenceChange } from '@/lib/settings/preferences';
import {
@@ -184,9 +184,10 @@ export default defineBackground(() => {
}
if (message.op === 'pair' && typeof message.token === 'string') {
pairDaemon(message.token)
- .then((result) =>
- sendResponse(result.ok ? success(true) : failure('PAIRING_FAILED', result.error ?? 'Pairing failed')),
- )
+ .then(async (result) => {
+ if (result.ok) await releaseAutoPair();
+ sendResponse(result.ok ? success(true) : failure('PAIRING_FAILED', result.error ?? 'Pairing failed'));
+ })
.catch((error) => sendResponse(failure('BRIDGE_ERROR', String(error))));
return true;
}
diff --git a/src/extension/entrypoints/welcome/App.tsx b/src/extension/entrypoints/welcome/App.tsx
index a9b4bcd..172f38f 100644
--- a/src/extension/entrypoints/welcome/App.tsx
+++ b/src/extension/entrypoints/welcome/App.tsx
@@ -6,7 +6,7 @@ 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 { hasSidePanel, 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';
@@ -49,11 +49,17 @@ export default function App() {
{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>
+ {hasSidePanel() ? (
+ <p className="text-sm text-ink">You’re set. Open the side panel and tell it what to do on any page.</p>
+ ) : (
+ <p className="text-sm text-ink">You’re set. Click Browsentic in the toolbar 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>
+ {hasSidePanel() && (
+ <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>
diff --git a/src/lib/bridge/auto-pair.test.ts b/src/lib/bridge/auto-pair.test.ts
index 37b10f0..b9895c7 100644
--- a/src/lib/bridge/auto-pair.test.ts
+++ b/src/lib/bridge/auto-pair.test.ts
@@ -125,6 +125,40 @@ describe('pairing by itself', () => {
await online();
}, TEST_TIMEOUT_MS);
+ test('a browser start during an alarm that was not due still gets its own look', async () => {
+ await fakeBrowser.storage.local.set({ 'browsentic/pairLast': { at: Date.now() - 2 * 60_000, outcome: 'stopped', failures: 0 } });
+
+ await Promise.all([pairing.autoPair('alarm'), pairing.autoPair('startup')]);
+
+ expect(host).toHaveBeenCalledOnce();
+ await online();
+ }, TEST_TIMEOUT_MS);
+
+ test('looks for a missing Bridge every minute again once the browser starts again', async () => {
+ host.mockRejectedValue(new Error('Specified native messaging host not found.'));
+ const longAgo = Date.now() - 60 * 60_000;
+ await fakeBrowser.storage.local.set({ 'browsentic/pairLast': { at: Date.now() - 6_000, outcome: 'missing', missingSince: longAgo, failures: 0 } });
+
+ await pairing.autoPair('startup');
+
+ const { 'browsentic/pairLast': last } = await fakeBrowser.storage.local.get('browsentic/pairLast');
+ expect((last as { missingSince: number }).missingSince).toBeGreaterThan(longAgo);
+ }, TEST_TIMEOUT_MS);
+
+ test('keeps the key a typed code gave it while the host was answering, rather than redeeming the grant', async () => {
+ host.mockImplementationOnce(async (_name: string, message: Record<string, unknown>) => {
+ const bridge = await control();
+ const { code } = await bridge.pair();
+ bridge.close();
+ expect(await socket!.pairDaemon(code)).toEqual({ ok: true });
+ return answerNativeMessage(message, context, { family: 'chromium', origin: `${ORIGIN}/` });
+ });
+
+ await pairing.autoPair('install');
+
+ expect(listSessions()).toEqual([expect.objectContaining({ pairedBy: 'code' })]);
+ }, 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');
diff --git a/src/lib/bridge/auto-pair.ts b/src/lib/bridge/auto-pair.ts
index d84306e..3ef89f8 100644
--- a/src/lib/bridge/auto-pair.ts
+++ b/src/lib/bridge/auto-pair.ts
@@ -17,6 +17,8 @@ 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;
+/** The browser starting, or this extension arriving, begins the frequent looks for a missing Bridge again. */
+const FRESH_STARTS: ReadonlySet<PairReason> = new Set(['install', 'update', 'startup']);
interface LastAttempt {
at: number;
@@ -65,9 +67,9 @@ export interface PairOptions {
let inflight: Promise<void> | null = null;
-/** One attempt at a time; a click that arrives during one is answered by another right after it. */
+/** One attempt at a time; anything but the alarm 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;
+ if (inflight) return options.gesture || reason !== 'alarm' ? inflight.then(() => autoPair(reason, options)) : inflight;
inflight = attempt(reason, options).finally(() => (inflight = null));
return inflight;
}
@@ -83,18 +85,21 @@ async function attempt(reason: PairReason, { gesture = false, wait = false }: Pa
const answer = await askHost(reason, { gesture, waitMs: wait ? MAX_PAIR_WAIT_MS : 0 });
if (answer.kind === 'grant') {
+ if (await sessionKeyUsable()) return;
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);
+ const failed: PairingState = { mode: answer.mode, error: GRANT_REFUSED };
+ await remember(last, 'failed', 'ready', failed, reason);
return reportPairing('ready', failed);
}
const [reach, pairing, outcome] = settled(answer);
- await remember(last, outcome, reach, pairing);
+ await remember(last, outcome, reach, pairing, reason);
await reportPairing(reach, pairing);
}
+const GRANT_REFUSED = 'Browsentic Bridge didn’t let this browser in. Try again.';
+
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];
@@ -102,15 +107,22 @@ function settled(answer: Exclude<PairAttempt, { kind: 'grant' }>): [BridgeReach,
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'];
+ return ['ready', { mode, error: message }, 'failed'];
}
-async function remember(last: LastAttempt | undefined, outcome: LastAttempt['outcome'], reach: BridgeReach, pairing: PairingState): Promise<void> {
+async function remember(
+ last: LastAttempt | undefined,
+ outcome: LastAttempt['outcome'],
+ reach: BridgeReach,
+ pairing: PairingState,
+ reason: PairReason,
+): Promise<void> {
const now = Date.now();
+ const stillMissing = last?.outcome === 'missing' && !FRESH_STARTS.has(reason);
const next: LastAttempt = {
at: now,
outcome,
- missingSince: outcome === 'missing' ? (last?.outcome === 'missing' ? last.missingSince ?? last.at : now) : undefined,
+ missingSince: outcome === 'missing' ? (stillMissing ? last.missingSince ?? last.at : now) : undefined,
failures: outcome === 'failed' ? (last?.outcome === 'failed' ? last.failures + 1 : 1) : 0,
reach,
pairing,
@@ -129,6 +141,11 @@ async function forgetLast(): Promise<void> {
await browser.storage.local.remove(LAST_KEY);
}
+/** A typed code connected it again after a Disconnect, which is as deliberate as pressing Connect. */
+export async function releaseAutoPair(): Promise<void> {
+ await browser.storage.local.remove(MANUAL_KEY);
+}
+
export function serveAutoPair(): void {
onWelcome(() => void forgetLast());
onStaleKey(() => void forgetLast().then(() => autoPair('unknown-session')));
diff --git a/src/lib/bridge/side-panel.ts b/src/lib/bridge/side-panel.ts
index c8cd142..93626d5 100644
--- a/src/lib/bridge/side-panel.ts
+++ b/src/lib/bridge/side-panel.ts
@@ -6,6 +6,9 @@ function sidebarAction(): SidebarAction {
return (browser as unknown as { sidebarAction: SidebarAction }).sidebarAction;
}
+/** Some Chromium browsers have no side panel, and their toolbar button opens the launcher instead. */
+export const hasSidePanel = (): boolean => import.meta.env.FIREFOX || typeof browser.sidePanel?.open === 'function';
+
export function openSidePanel(windowId: number) {
if (import.meta.env.FIREFOX) return sidebarAction().open();
return browser.sidePanel.open({ windowId });
diff --git a/src/lib/bridge/socket.ts b/src/lib/bridge/socket.ts
index 4a8ed77..60b7698 100644
--- a/src/lib/bridge/socket.ts
+++ b/src/lib/bridge/socket.ts
@@ -518,7 +518,7 @@ function pairWith(code: string, ports: readonly number[]): Promise<{ ok: boolean
return new Promise((resolve) => {
pairingResult = resolve;
dial({ kind: 'pair', secret: code }, ports, 0);
- setTimeout(
+ pairingTimer = setTimeout(
() => settlePairing({ ok: false, error: 'No Browsentic daemon is running. Start one with "browsentic pair".' }),
PAIRING_TIMEOUT_MS,
);
@@ -547,8 +547,10 @@ export const reportPairing = (bridge: BridgeReach | undefined, pairing: PairingS
setState({ bridge, pairing, lastChangeAt: Date.now() });
let pairingResult: ((result: { ok: boolean; error?: string }) => void) | null = null;
+let pairingTimer: ReturnType<typeof setTimeout> | undefined;
function settlePairing(result: { ok: boolean; error?: string }): void {
+ clearTimeout(pairingTimer);
pairingResult?.(result);
pairingResult = null;
}
@@ -759,6 +761,7 @@ async function handle(ws: WebSocket, raw: string, attempt: Attempt): Promise<voi
protocolVersion: frame.protocolVersion,
manifestInSync: frame.manifestInSync,
error: undefined,
+ bridge: undefined,
pairing: undefined,
lastChangeAt: Date.now(),
});
diff --git a/src/lib/bridge/use-auto-pair.ts b/src/lib/bridge/use-auto-pair.ts
index 93d8362..aa2eff4 100644
--- a/src/lib/bridge/use-auto-pair.ts
+++ b/src/lib/bridge/use-auto-pair.ts
@@ -4,28 +4,38 @@ import { BRIDGE_CHANNEL, type ActionResult } from '@/lib/actions/protocol';
import type { DaemonState } from './socket';
const BETWEEN_WAITS_MS = 3_000;
+/** Each ask starts the native host; after this the background's own minute alarm keeps asking. */
+const WAIT_AT_MOST_MS = 10 * 60_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.
+ * While a page that shows the link is open and this browser is not paired, it asks to pair whenever
+ * the page comes into view, 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);
+ if (!unpaired) return;
+ const inView = () => {
+ if (document.visibilityState === 'visible') void ask().catch(() => undefined);
+ };
+ inView();
+ document.addEventListener('visibilitychange', inView);
+ return () => document.removeEventListener('visibilitychange', inView);
}, [unpaired]);
useEffect(() => {
if (!waiting) return;
let live = true;
+ const until = Date.now() + WAIT_AT_MOST_MS;
void (async () => {
- while (live) {
+ while (live && Date.now() < until) {
await ask({ wait: true }).catch(() => undefined);
await new Promise((resolve) => setTimeout(resolve, BETWEEN_WAITS_MS));
}