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.

test(daemon): pair two fake browsers that share an origin with a real daemon, and pin that both stay connected, who supersedes whom, where an outside call lands and how an old session is claimed

Shahriaref736ac5e18e
diff --git a/src/daemon/test/browsers.test.ts b/src/daemon/test/browsers.test.ts
new file mode 100644
index 0000000..b3b55ce
--- /dev/null
+++ b/src/daemon/test/browsers.test.ts
@@ -0,0 +1,171 @@
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';
+import { clearAuth } from '../auth-store';
+import { startDaemon, type Daemon } from '../daemon';
+import { readLockfile, stateDir } from '../lockfile';
+import { RemoteBridge } from '../remote-bridge';
+import { FakeBrowser, type Profile } from './fake-browser';
+
+// Every Chromium browser loading ~/browsentic/extension/chrome-mv3 presents this one origin.
+const unpacked = 'chrome-extension://abcdefghijklmnopabcdefghijklmnop';
+const chrome: Profile = { origin: unpacked, installId: 'install-chrome-0001', browser: 'Google Chrome' };
+const brave: Profile = { origin: unpacked, installId: 'install-brave-00001', browser: 'Brave' };
+
+let daemon: Daemon;
+let opened: { close(): unknown }[] = [];
+
+beforeAll(async () => {
+ daemon = await startDaemon({ version: '0.0.0-test', idleExit: false });
+});
+
+afterAll(async () => {
+ await daemon?.stop();
+});
+
+afterEach(async () => {
+ for (const each of opened) each.close();
+ opened = [];
+ await settled();
+ clearAuth();
+});
+
+const settled = () => new Promise((resolve) => setTimeout(resolve, 20));
+
+async function control(): Promise<RemoteBridge> {
+ const bridge = await RemoteBridge.connect(daemon.port, readLockfile()!.token);
+ opened.push(bridge);
+ return bridge;
+}
+
+async function pair(profile: Profile): Promise<FakeBrowser> {
+ const { code } = await (await control()).pair();
+ return returnOf(profile, { kind: 'pair', code });
+}
+
+async function returnOf(profile: Profile, credential: Parameters<typeof FakeBrowser.connect>[2]): Promise<FakeBrowser> {
+ const browser = await FakeBrowser.connect(daemon.port, profile, credential);
+ opened.push(browser);
+ return browser;
+}
+
+const answeredBy = async (bridge: RemoteBridge) =>
+ ((await bridge.invoke('page.getPageInfo')) as { data?: { answeredBy?: string } }).data?.answeredBy;
+
+describe('two browsers paired with one daemon', () => {
+ test('sharing an origin, both pair and both stay connected', async () => {
+ const first = await pair(chrome);
+ const second = await pair(brave);
+ await settled();
+ const sessions = await (await control()).sessions();
+ expect([first.isOpen, second.isOpen, sessions.map(({ id, browser, connected }) => [id, browser, connected])]).toEqual([
+ true,
+ true,
+ [
+ [chrome.installId, 'Google Chrome', true],
+ [brave.installId, 'Brave', true],
+ ],
+ ]);
+ });
+
+ test('each returns on its own key, and neither takes the link from the other', async () => {
+ const first = await pair(chrome);
+ const second = await pair(brave);
+ first.close();
+ await settled();
+ const back = await returnOf(chrome, { kind: 'session', key: first.sessionKey });
+ await settled();
+ expect([back.isOpen, second.isOpen]).toEqual([true, true]);
+ });
+
+ test("a browser cannot return on the other's key", async () => {
+ const first = await pair(chrome);
+ await pair(brave);
+ await expect(returnOf(brave, { kind: 'session', key: first.sessionKey })).rejects.toThrow(/no longer paired/);
+ });
+
+ test('the same browser connecting twice supersedes only itself', async () => {
+ const first = await pair(chrome);
+ const other = await pair(brave);
+ const again = await returnOf(chrome, { kind: 'session', key: first.sessionKey });
+ expect([await first.closed, again.isOpen, other.isOpen]).toEqual(['superseded by a newer connection', true, true]);
+ });
+
+ test('unpairing one by its id leaves the other connected and paired', async () => {
+ const first = await pair(chrome);
+ const second = await pair(brave);
+ const bridge = await control();
+ const revoked = await bridge.revoke(chrome.installId);
+ expect([revoked, await first.closed, second.isOpen, (await bridge.sessions()).map(({ id }) => id)]).toEqual([
+ 1,
+ 'pairing revoked',
+ true,
+ [brave.installId],
+ ]);
+ });
+});
+
+describe('a caller outside any browser', () => {
+ test('reaches the browser the user was last in', async () => {
+ const first = await pair(chrome);
+ await pair(brave);
+ await settled();
+ await first.focus();
+ expect(await answeredBy(await control())).toBe(chrome.installId);
+ });
+
+ test('stays with that browser through a burst of calls, while a new caller follows the user', async () => {
+ const first = await pair(chrome);
+ const second = await pair(brave);
+ await settled();
+ await first.focus();
+ const busy = await control();
+ const before = await answeredBy(busy);
+ await settled();
+ await second.focus();
+ expect([before, await answeredBy(busy), await answeredBy(await control())]).toEqual([
+ chrome.installId,
+ chrome.installId,
+ brave.installId,
+ ]);
+ });
+
+ test('moves to the browser still connected when its own goes away', async () => {
+ const first = await pair(chrome);
+ await pair(brave);
+ await settled();
+ await first.focus();
+ const bridge = await control();
+ await answeredBy(bridge);
+ first.close();
+ await settled();
+ expect(await answeredBy(bridge)).toBe(brave.installId);
+ });
+
+ test('is told which browser answers it, and how many could', async () => {
+ await pair(chrome);
+ const second = await pair(brave);
+ await settled();
+ await second.focus();
+ const { connected, browser, connectedBrowsers, pairedBrowsers } = await (await control()).status();
+ expect([connected, browser, connectedBrowsers, pairedBrowsers]).toEqual([true, 'Brave', 2, 2]);
+ });
+
+ test('with no browser connected, is told the extension is offline', async () => {
+ const result = await (await control()).invoke('page.getPageInfo');
+ expect(result.ok ? null : result.error.code).toBe('EXTENSION_OFFLINE');
+ });
+});
+
+describe('a browser paired before install ids', () => {
+ test('returns on the key it already holds and is known by its install id from then on', async () => {
+ const key = 'k'.repeat(43);
+ const paired = { key, origin: unpacked, extensionVersion: '0.6.1', pairedAt: '2026-09-01T00:00:00.000Z', lastSeenAt: '2026-09-01T00:00:00.000Z' };
+ mkdirSync(stateDir, { recursive: true });
+ writeFileSync(join(stateDir, 'auth.json'), JSON.stringify({ pairings: [], sessions: [paired] }));
+
+ const back = await returnOf(chrome, { kind: 'session', key });
+ const sessions = await (await control()).sessions();
+ expect([back.isOpen, sessions.map(({ id, connected }) => [id, connected])]).toEqual([true, [[chrome.installId, true]]]);
+ });
+});
diff --git a/src/daemon/test/fake-browser.ts b/src/daemon/test/fake-browser.ts
new file mode 100644
index 0000000..459275d
--- /dev/null
+++ b/src/daemon/test/fake-browser.ts
@@ -0,0 +1,111 @@
+import { randomUUID } from 'node:crypto';
+import WebSocket from 'ws';
+import { clientProof, newNonce, openSessionKey, pairingSecret, type Transcript } from '@/lib/actions/handshake';
+import { hashManifest } from '@/lib/actions/manifest';
+import { SOCKET_PROTOCOL_VERSION, parseFrame, type SocketFrame } from '@/lib/actions/protocol';
+import { describeActions } from '@/lib/actions/registry';
+
+export interface Profile {
+ origin: string;
+ installId: string;
+ browser?: string;
+}
+
+export type Credential = { kind: 'pair'; code: string } | { kind: 'session'; key: string };
+
+const EXTENSION_VERSION = '0.0.0-test';
+
+/** The extension's half of the socket: it proves itself, then answers every invoke with its own name. */
+export class FakeBrowser {
+ readonly invoked: string[] = [];
+ readonly closed: Promise<string>;
+ private readonly pongs = new Map<string, () => void>();
+
+ private constructor(
+ private readonly socket: WebSocket,
+ readonly profile: Profile,
+ readonly sessionKey: string,
+ ) {
+ this.closed = new Promise((resolve) => socket.once('close', (_code, reason) => resolve(String(reason))));
+ socket.on('message', (raw) => this.receive(parseFrame(String(raw))));
+ }
+
+ static async connect(port: number, profile: Profile, credential: Credential): Promise<FakeBrowser> {
+ const socket = new WebSocket(`ws://127.0.0.1:${port}/extension`, { headers: { origin: profile.origin } });
+ const inbox = frames(socket);
+ await new Promise((resolve, reject) => socket.once('open', resolve).once('error', reject));
+
+ const hello = { extensionVersion: EXTENSION_VERSION, manifestHash: hashManifest(describeActions()), nonce: newNonce() };
+ send(socket, {
+ t: 'hello',
+ protocolVersion: SOCKET_PROTOCOL_VERSION,
+ auth: { kind: credential.kind },
+ installId: profile.installId,
+ browser: profile.browser,
+ ...hello,
+ });
+
+ const challenge = await inbox.next();
+ if (challenge?.t !== 'challenge') throw new Error(`expected a challenge, got ${challenge?.t}`);
+ const transcript: Transcript = {
+ protocolVersion: SOCKET_PROTOCOL_VERSION,
+ extensionVersion: hello.extensionVersion,
+ manifestHash: hello.manifestHash,
+ clientNonce: hello.nonce,
+ serverNonce: challenge.nonce,
+ };
+ const secret = credential.kind === 'pair' ? await pairingSecret(credential.code, transcript) : credential.key;
+ send(socket, { t: 'prove', proof: await clientProof(secret, transcript) });
+
+ const verdict = await inbox.next();
+ if (verdict?.t === 'unauthorized') throw new Error(verdict.reason);
+ if (verdict?.t !== 'welcome') throw new Error(`expected a welcome, got ${verdict?.t}`);
+ inbox.stop();
+ const minted = verdict.sealedSessionKey ? await openSessionKey(secret, transcript, verdict.sealedSessionKey) : null;
+ return new FakeBrowser(socket, profile, minted ?? secret);
+ }
+
+ get isOpen(): boolean {
+ return this.socket.readyState === WebSocket.OPEN;
+ }
+
+ /** Resolves once the daemon has read everything sent before it, focus included. */
+ async focus(): Promise<void> {
+ send(this.socket, { t: 'focus' });
+ const id = randomUUID();
+ const answered = new Promise<void>((resolve) => this.pongs.set(id, resolve));
+ send(this.socket, { t: 'ping', id });
+ await answered;
+ }
+
+ close(): void {
+ this.socket.close(1000, 'test over');
+ }
+
+ private receive(frame: SocketFrame | null): void {
+ if (frame?.t === 'pong') {
+ this.pongs.get(frame.id)?.();
+ this.pongs.delete(frame.id);
+ }
+ if (frame?.t !== 'invoke') return;
+ this.invoked.push(frame.action);
+ send(this.socket, { t: 'result', id: frame.id, result: { ok: true, data: { answeredBy: this.profile.installId } } });
+ }
+}
+
+function send(socket: WebSocket, frame: SocketFrame): void {
+ socket.send(JSON.stringify(frame));
+}
+
+function frames(socket: WebSocket): { next(): Promise<SocketFrame | null>; stop(): void } {
+ const queued: (SocketFrame | null)[] = [];
+ const waiting: ((frame: SocketFrame | null) => void)[] = [];
+ const deliver = (frame: SocketFrame | null) => (waiting.length ? waiting.shift()!(frame) : void queued.push(frame));
+ const onMessage = (raw: WebSocket.RawData) => deliver(parseFrame(String(raw)));
+ const onClose = () => deliver(null);
+ socket.on('message', onMessage).once('close', onClose);
+ return {
+ next: () => (queued.length ? Promise.resolve(queued.shift()!) : new Promise((resolve) => waiting.push(resolve))),
+ stop: () => void socket.off('message', onMessage).off('close', onClose),
+ };
+}
diff --git a/src/lib/bridge/identity.test.ts b/src/lib/bridge/identity.test.ts
new file mode 100644
index 0000000..2599bb1
--- /dev/null
+++ b/src/lib/bridge/identity.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, test } from 'vitest';
+import { brandFrom } from './identity';
+
+const chromium = { brand: 'Chromium' };
+const placeholder = { brand: 'Not/A)Brand' };
+
+describe("naming the browser from the brands it reports", () => {
+ test('the product wins over the engine and over the placeholder Chromium shuffles in', () => {
+ const named = [
+ brandFrom([placeholder, chromium, { brand: 'Google Chrome' }]),
+ brandFrom([{ brand: 'Brave' }, chromium, { brand: 'Not;A=Brand' }]),
+ brandFrom([chromium, { brand: 'Microsoft Edge' }, { brand: 'Not_A Brand' }]),
+ ];
+ expect(named).toEqual(['Google Chrome', 'Brave', 'Microsoft Edge']);
+ });
+
+ test('a build that reports only the engine is called Chromium', () => {
+ expect(brandFrom([placeholder, chromium])).toBe('Chromium');
+ });
+
+ test('a browser that reports nothing is left unnamed', () => {
+ expect(brandFrom([])).toBeUndefined();
+ });
+});