An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.
TypeScript agentic-browseragentic-browsingagy-cliaiai-agentai-browser-extensionai-toolsbrave-extensionbrowser-agentbrowser-automationbrowser-extensionbrowser-usebrowserskillchrome-extensionclaude-codecodexfirefox-addonmcp-servernanobrowserweb-automation
feat(daemon): keep every paired browser connected at once, each known by an install id, because every Chromium browser loading the same folder presents one origin and a second link used to close the first
Shahriara75730b1cc1a
diff --git a/src/daemon/agent/service.ts b/src/daemon/agent/service.tsindex 748aaf1..0bcc95c 100644--- a/src/daemon/agent/service.ts+++ b/src/daemon/agent/service.ts@@ -58,6 +58,8 @@ export interface AgentSessionDeps {) => Promise<ActionResult>;emit: (runId: string, event: RunEvent) => void;draft: (runId: string, draft: import('@/lib/skills/site-map').SiteMapDraft) => void;+ /** Runs going in every connected browser: the limit bounds agent processes on the machine. */+ running?: () => number;}interface ActiveRun {@@ -116,6 +118,14 @@ export class AgentSession {}}+ get running(): number {+ return this.runs.size;+ }++ owns(runId: string): boolean {+ return this.runs.has(runId);+ }+async invokeForRun(runId: string, action: string, input?: unknown): Promise<ActionResult> {const run = this.runs.get(runId);if (!run) {@@ -232,7 +242,7 @@ export class AgentSession {const config = readAgentConfig();const limit = maxConcurrentRuns(config);- if (this.runs.size >= limit) {+ if ((this.deps.running?.() ?? this.runs.size) >= limit) {return emit({kind: 'error',code: 'RUN_LIMIT',diff --git a/src/daemon/auth-store.test.ts b/src/daemon/auth-store.test.tsindex f6bb5fa..e57f2d9 100644--- a/src/daemon/auth-store.test.ts+++ b/src/daemon/auth-store.test.ts@@ -2,6 +2,7 @@ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'noimport { join } from 'node:path';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import {+ claimSession,clearAuth,consumePairing,createPairing,@@ -10,14 +11,27 @@ import {listSessions,pendingPairings,revokeSessions,- sessionFor,- touchSession,+ sessionCandidates,+ sessionId,+ type Install,} from './auth-store';import { stateDir } from './lockfile';const authPath = join(stateDir, 'auth.json');const extension = 'chrome-extension://abcdefghijklmnopabcdefghijklmnop';+const chrome: Install = { installId: 'install-chrome-0001', origin: extension, extensionVersion: '0.6.2', browser: 'Google Chrome' };+const brave: Install = { installId: 'install-brave-00001', origin: extension, extensionVersion: '0.6.2', browser: 'Brave' };+const firefox: Install = { installId: 'install-firefox-001', origin: 'moz-extension://firefox-uuid', extensionVersion: '0.6.2' };++/** What auth.json holds for a browser paired before the extension sent an install id. */+function pairedBeforeInstallIds(origin: string): string {+ const key = 'k'.repeat(43);+ const legacy = { key, origin, extensionVersion: '0.6.1', pairedAt: '2026-09-01T00:00:00.000Z', lastSeenAt: '2026-09-01T00:00:00.000Z' };+ writeFileSync(authPath, JSON.stringify({ pairings: [], sessions: [legacy] }));+ return key;+}+beforeEach(() => {mkdirSync(stateDir, { recursive: true });clearAuth();@@ -55,57 +69,74 @@ describe('pairing codes', () => {});describe('sessions', () => {- test("pairing gives the browser a 256-bit key, bound to the extension's origin", () => {- const session = createSession(extension, '0.6.2');- expect([Buffer.from(session.key, 'base64url').length, sessionFor(extension)]).toEqual([32, session]);+ test('pairing gives the browser a 256-bit key, bound to its install id', () => {+ const session = createSession(chrome);+ expect([Buffer.from(session.key, 'base64url').length, sessionCandidates(chrome)]).toEqual([32, [session]]);});test('pairing the same browser again replaces its key rather than adding a second', () => {- const first = createSession(extension, '0.6.1');- const second = createSession(extension, '0.6.2');+ const first = createSession({ ...chrome, extensionVersion: '0.6.1' });+ const second = createSession(chrome);expect([listSessions(), first.key === second.key]).toEqual([[second], false]);});- test('seeing a browser again updates when it was last seen, and nothing else', () => {+ test('a second browser loading the same folder shares the origin and still pairs beside the first', () => {+ const first = createSession(chrome);+ const second = createSession(brave);+ expect([listSessions(), sessionCandidates(chrome), sessionCandidates(brave)]).toEqual([[first, second], [first], [second]]);+ });++ test('seeing a browser again updates when it was last seen and what it is running, and keeps its key', () => {vi.useFakeTimers({ now: new Date('2026-09-21T10:00:00Z') });- const paired = createSession(extension, '0.6.2');+ const paired = createSession({ ...chrome, extensionVersion: '0.6.1' });vi.setSystemTime(new Date('2026-09-21T12:00:00Z'));- touchSession(extension);- expect(sessionFor(extension)).toEqual({ ...paired, lastSeenAt: '2026-09-21T12:00:00.000Z' });+ claimSession(paired.key, chrome);+ expect(listSessions()).toEqual([{ ...paired, extensionVersion: '0.6.2', lastSeenAt: '2026-09-21T12:00:00.000Z' }]);});- test('seeing a browser that never paired changes nothing', () => {- touchSession('moz-extension://stranger');+ test('a key nobody holds claims nothing', () => {+ claimSession('no-such-key', chrome);expect(listSessions()).toEqual([]);});+ test('a browser paired before install ids is found by its origin, and named by it until it returns', () => {+ const key = pairedBeforeInstallIds(extension);+ expect([sessionCandidates(chrome).map((session) => session.key), listSessions().map(sessionId)]).toEqual([[key], [extension]]);+ });++ test('its first return claims that session, after which no other browser on the origin is offered it', () => {+ const key = pairedBeforeInstallIds(extension);+ claimSession(key, chrome);+ expect([listSessions().map(sessionId), sessionCandidates(brave)]).toEqual([[chrome.installId], []]);+ });+test('revoking removes the sessions that match, and says how many', () => {- createSession(extension, '0.6.2');- createSession('moz-extension://firefox-uuid', '0.6.2');+ createSession(chrome);+ createSession(firefox);expect([revokeSessions((session) => session.origin.startsWith('moz-')), listSessions().map((session) => session.origin)]).toEqual([1, [extension]]);});test('a revoked browser has no key left to present', () => {- createSession(extension, '0.6.2');+ createSession(chrome);revokeSessions(() => true);- expect(sessionFor(extension)).toBeNull();+ expect(sessionCandidates(chrome)).toEqual([]);});});describe('the file', () => {test('is readable only by the user', () => {- createSession(extension, '0.6.2');+ createSession(chrome);expect(statSync(authPath).mode & 0o777).toBe(0o600);});test('a damaged file pairs nothing, and the next write replaces it', () => {writeFileSync(authPath, '{"sessions": [');- const session = createSession(extension, '0.6.2');+ const session = createSession(chrome);expect(JSON.parse(readFileSync(authPath, 'utf8'))).toEqual({ pairings: [], sessions: [session] });});test('clearing it forgets every browser', () => {- createSession(extension, '0.6.2');+ createSession(chrome);clearAuth();expect([existsSync(authPath), listSessions()]).toEqual([false, []]);});diff --git a/src/daemon/auth-store.ts b/src/daemon/auth-store.tsindex 5967594..d99339f 100644--- a/src/daemon/auth-store.ts+++ b/src/daemon/auth-store.ts@@ -12,6 +12,9 @@ const PAIRING_TTL_MS = 10 * 60 * 1000;export interface Session {key: string;origin: string;+ /** Absent on a session paired before the extension sent one; the first reconnect claims it. */+ installId?: string;+ browser?: string;extensionVersion: string;pairedAt: string;lastSeenAt: string;@@ -68,30 +71,49 @@ export function hasPendingPairing(): boolean {return read().pairings.some((pairing) => pairing.expiresAt > Date.now());}-export function createSession(origin: string, extensionVersion: string): Session {+export interface Install {+ installId: string;+ origin: string;+ extensionVersion: string;+ browser?: string;+}++export const sessionId = (session: Pick<Session, 'installId' | 'origin'>): string =>+ session.installId ?? session.origin;++export function createSession({ installId, origin, extensionVersion, browser }: Install): Session {const auth = read();const now = new Date().toISOString();const session: Session = {key: randomBytes(32).toString('base64url'),origin,+ installId,+ browser,extensionVersion,pairedAt: now,lastSeenAt: now,};- const sessions = auth.sessions.filter((existing) => existing.origin !== origin);+ const sessions = auth.sessions.filter((existing) => existing.installId !== installId);write({ ...auth, sessions: [...sessions, session] });return session;}-export function sessionFor(origin: string): Session | null {- return read().sessions.find((candidate) => candidate.origin === origin) ?? null;+/**+ * The sessions this install may hold the key to. An origin names a browser only until a second+ * Chromium browser loads the same folder, so it is consulted just for sessions that predate the+ * install id, and which of those is this browser's is settled by the proof.+ */+export function sessionCandidates({ installId, origin }: Pick<Install, 'installId' | 'origin'>): Session[] {+ const sessions = read().sessions;+ const own = sessions.filter((candidate) => candidate.installId === installId);+ return own.length ? own : sessions.filter((candidate) => !candidate.installId && candidate.origin === origin);}-export function touchSession(origin: string): void {+export function claimSession(key: string, { installId, extensionVersion, browser }: Install): void {const auth = read();- const session = auth.sessions.find((candidate) => candidate.origin === origin);+ const session = auth.sessions.find((candidate) => candidate.key === key);if (!session) return;- session.lastSeenAt = new Date().toISOString();+ Object.assign(session, { installId, extensionVersion, browser, lastSeenAt: new Date().toISOString() });write(auth);}diff --git a/src/daemon/cli.ts b/src/daemon/cli.tsindex 950a89f..4062778 100644--- a/src/daemon/cli.ts+++ b/src/daemon/cli.ts@@ -31,7 +31,7 @@ const USAGE = `browsentic ${pkg.version} — hand your real browser to the agentbrowsentic pair issue a one-time code to type into the extensionbrowsentic status daemon, extension and agent statebrowsentic sessions list paired browsers- browsentic revoke [origin] unpair one browser, or all of them+ browsentic revoke [id] unpair one browser by the id "sessions" prints, or all of thembrowsentic agent show which agent runs the side panel, and which are installedbrowsentic agent <name> switch to claude, codex or antigravity@@ -403,6 +403,7 @@ async function setup(argv: string[]): Promise<void> {if (alreadyPaired) {console.log(` This browser is already paired. Press ↻ on the Browsentic card at`);console.log(` chrome://extensions to pick up this build, and you are done.\n`);+ console.log(` Adding another browser? Load the same folder there, then run "browsentic pair".\n`);return;}@@ -531,8 +532,8 @@ async function showSessions(): Promise<void> {return console.log('No paired browsers. Run "browsentic setup" to add one.');}for (const session of sessions) {- console.log(`${session.connected ? '●' : '○'} ${session.origin}`);- console.log(` extension v${session.extensionVersion}, paired ${session.pairedAt}, last seen ${session.lastSeenAt}`);+ console.log(`${session.connected ? '●' : '○'} ${session.browser ?? session.origin} ${session.id}`);+ console.log(` ${session.origin}, extension v${session.extensionVersion}, paired ${session.pairedAt}, last seen ${session.lastSeenAt}`);}}@@ -579,11 +580,11 @@ async function chooseAgent(first?: string, second?: string, third?: string): Proconsole.log(`\nThe side panel runs on ${AGENTS[state.active].label}.`);}-async function revoke(origin?: string): Promise<void> {+async function revoke(browser?: string): Promise<void> {const bridge = await connect();- const revoked = await bridge.revoke(origin);+ const revoked = await bridge.revoke(browser);await bridge.close();- if (!revoked) return console.log(origin ? `No session for ${origin}.` : 'Nothing to revoke.');+ if (!revoked) return console.log(browser ? `No session for ${browser}.` : 'Nothing to revoke.');console.log(`Revoked ${revoked} session(s). Pair again with "browsentic pair".`);}diff --git a/src/daemon/control.ts b/src/daemon/control.tsindex 13c441a..f64648e 100644--- a/src/daemon/control.ts+++ b/src/daemon/control.ts@@ -9,11 +9,16 @@ export interface BridgeStatus {port: number;manifestInSync: boolean;extensionVersion?: string;+ /** The connected browser this caller's tools reach, when more than one could answer. */+ browser?: string;+ connectedBrowsers: number;pairedBrowsers: number;pairingPending: boolean;}export interface SessionSummary {+ id: string;+ browser?: string;origin: string;extensionVersion: string;pairedAt: string;@@ -27,7 +32,7 @@ export type ControlRequest =| { id: string; op: 'invoke'; action: string; input?: unknown; runId?: string }| { id: string; op: 'pair' }| { id: string; op: 'sessions' }- | { id: string; op: 'revoke'; origin?: string }+ | { id: string; op: 'revoke'; session?: string; origin?: string }| { id: string; op: 'agent'; set?: AgentKind; grant?: AgentKind };export type ControlMessage =diff --git a/src/daemon/daemon.ts b/src/daemon/daemon.tsindex 38df494..bcbe41d 100644--- a/src/daemon/daemon.ts+++ b/src/daemon/daemon.ts@@ -7,6 +7,7 @@ import {EXTERNAL_RUN_ID,SOCKET_PROTOCOL_VERSION,failure,+ isInstallId,parseFrame,success,type ActionResult,@@ -32,6 +33,7 @@ import {type Transcript,} from '@/lib/actions/handshake';import {+ claimSession,consumePairing,createPairing,createSession,@@ -39,8 +41,10 @@ import {listSessions,pendingPairings,revokeSessions,- sessionFor,- touchSession,+ sessionCandidates,+ sessionId,+ type Install,+ type Session,} from './auth-store';import { AgentSession } from './agent/service';import { summarizeFile } from './agent/analyze';@@ -73,10 +77,22 @@ type AgentFrame = Extract<SocketFrame, { t: 'agentState' | 'setAgent' | 'setAgentype GuardrailFrame = Extract<SocketFrame, { t: 'guardrails' | 'setGuardrail' }>;const IDLE_EXIT_MS = 30 * 60 * 1000;+const BINDING_IDLE_MS = 2 * 60 * 1000;+const BROWSER_LABEL_MAX = 40;const HANDSHAKE_TIMEOUT_MS = 10_000;const EXTENSION_ORIGIN = /^(chrome|moz|safari-web)-extension:\/\//;const LOOPBACK_HOST = /^(127\.0\.0\.1|\[::1\]|localhost)(:\d+)?$/i;+interface Binding {+ id?: string;+ usedAt: number;+}++function browserLabel(claimed: unknown): string | undefined {+ if (typeof claimed !== 'string') return undefined;+ return claimed.replace(/[^\x20-\x7E]/g, '').trim().slice(0, BROWSER_LABEL_MAX) || undefined;+}+export interface DaemonOptions {version: string;idleExit?: boolean;@@ -137,9 +153,8 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):const bundledHash = hashManifest(bundled);let tools = bundled;- let manifestInSync = true;- let link: ExtensionLink | null = null;- let agent: AgentSession | null = null;+ const links = new Map<string, ExtensionLink>();+ const agents = new Map<ExtensionLink, AgentSession>();const controls = new Set<WebSocket>();let controlSeq = 0;const manifestListeners = new Set<() => void>();@@ -161,7 +176,7 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):}if (req.url?.startsWith('/health')) {res.writeHead(200, { 'content-type': 'application/json' });- res.end(JSON.stringify({ ok: true, pid: process.pid, version, connected: !!link?.isOpen }));+ res.end(JSON.stringify({ ok: true, pid: process.pid, version, connected: openLinks().length > 0 }));return;}res.writeHead(404).end();@@ -241,6 +256,17 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):ws.close(1002, 'expected a nonce');return;}+ if (!isInstallId(hello.installId)) {+ log('extension hello carried no install id; closing');+ ws.close(1002, 'expected an install id');+ return;+ }+ const install: Install = {+ installId: hello.installId,+ origin: req.headers.origin!,+ extensionVersion: hello.extensionVersion,+ browser: browserLabel(hello.browser),+ };const transcript: Transcript = {protocolVersion: SOCKET_PROTOCOL_VERSION,@@ -258,7 +284,6 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):return;}- const origin = req.headers.origin!;let secret: string;let sealedSessionKey: string | undefined;if (hello.auth?.kind === 'pair') {@@ -268,21 +293,28 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):}consumePairing(matched.code);secret = matched.secret;- const session = createSession(origin, hello.extensionVersion);+ const session = createSession(install);sealedSessionKey = await sealSessionKey(secret, transcript, session.key);- log(`paired ${origin} (extension ${hello.extensionVersion})`);+ log(`paired ${install.browser ?? install.origin} (extension ${hello.extensionVersion})`);} else if (hello.auth?.kind === 'session') {- const session = sessionFor(origin);- if (!session || !sameProof(proven.proof, await clientProof(session.key, transcript))) {+ const session = await matchSession(proven.proof, transcript, install);+ if (!session) {return reject('This browser is no longer paired. Run "browsentic-mcp pair" to pair again.', false);}- touchSession(origin);+ claimSession(session.key, install);secret = session.key;} else {return reject('That hello named no credential to prove.', false);}- await settle(ws, hello, origin, transcript, secret, sealedSessionKey);+ await settle(ws, hello, install, transcript, secret, sealedSessionKey);+ }++ async function matchSession(proof: unknown, transcript: Transcript, install: Install): Promise<Session | null> {+ for (const session of sessionCandidates(install)) {+ if (sameProof(proof, await clientProof(session.key, transcript))) return session;+ }+ return null;}async function matchPairing(@@ -299,23 +331,22 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):async function settle(ws: WebSocket,hello: Extract<SocketFrame, { t: 'hello' }>,- origin: string,+ install: Install,transcript: Transcript,secret: string,sealedSessionKey?: string,): Promise<void> {- link?.close('superseded by a newer connection');- agent?.dispose();- manifestInSync = hello.manifestHash === bundledHash;+ // Only the same browser profile is superseded: its worker restarted and the old socket lingers.+ links.get(install.installId)?.close('superseded by a newer connection');+ const manifestInSync = hello.manifestHash === bundledHash;const accepted = new ExtensionLink(ws,- { ...hello, origin },+ { ...hello, ...install },(closing) => {- if (link !== closing) return;- link = null;- agent?.dispose();- agent = null;- log('extension disconnected');+ agents.get(closing)?.dispose();+ agents.delete(closing);+ if (links.get(closing.id) === closing) links.delete(closing.id);+ log(`${closing.label} disconnected`);scheduleIdleExit();},(request, source) => {@@ -357,6 +388,7 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):source.send({ t: 'agentInfo', id: request.id, result: state });// The catalog's agent-skill half belongs to the agent that just took over.if (request.t === 'setAgent') pushSkillCatalog(source);+ if (request.t !== 'agentState') announceAgent(source);});return;}@@ -368,15 +400,15 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):}if (request.t === 'saveSkill') {source.send({ t: 'skillResult', id: request.id, result: saveSkill(request.skill) });- return pushSkillCatalog(source);+ return shareSkillCatalog();}if (request.t === 'deleteSkill') {source.send({ t: 'skillResult', id: request.id, result: deleteSkill(request.name) });- return pushSkillCatalog(source);+ return shareSkillCatalog();}if (request.t === 'deleteSiteMap') {source.send({ t: 'skillResult', id: request.id, result: deleteSiteMap(request.name) });- return pushSkillCatalog(source);+ return shareSkillCatalog();}if (request.t === 'activateSiteMap') {const result = commitStaging(request.stagingId, request.exactHost === true);@@ -385,7 +417,7 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):id: request.id,result: result.ok ? { ok: true, data: { name: result.data.name, path: result.data.path } } : result,});- return pushSkillCatalog(source);+ return shareSkillCatalog();}if (request.t === 'discardSiteMap') {return source.send({ t: 'skillResult', id: request.id, result: discardStaging(request.stagingId) });@@ -393,15 +425,47 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):session(source).handle(request);},);- link = accepted;- log(`extension ${hello.extensionVersion} connected from ${origin} (manifest ${manifestInSync ? 'in sync' : 'DRIFTED'})`);+ links.set(accepted.id, accepted);+ log(`extension ${hello.extensionVersion} connected from ${accepted.label} (manifest ${manifestInSync ? 'in sync' : 'DRIFTED'})`);const welcome = { daemonVersion: version, manifestHash: bundledHash, manifestInSync, sealedSessionKey };accepted.send({ t: 'welcome', ...welcome, proof: await serverProof(secret, transcript, welcome) });scheduleIdleExit();void pushAgentState(accepted);pushSkillCatalog(accepted);- if (manifestInSync) restoreBundledManifest();- else await adoptExtensionManifest(accepted);+ if (!manifestInSync) await adoptExtensionManifest(accepted);+ else if (openLinks().every(inSync)) restoreBundledManifest();+ }++ function openLinks(): ExtensionLink[] {+ return [...links.values()].filter((link) => link.isOpen);+ }++ function inSync(link: ExtensionLink): boolean {+ return link.manifestHash === bundledHash;+ }++ /** The browser the user was last in, for a caller that has no run to say which one it means. */+ function activeLink(): ExtensionLink | null {+ return openLinks().reduce<ExtensionLink | null>(+ (latest, link) => (latest && latest.lastActiveAt >= link.lastActiveAt ? latest : link),+ null,+ );+ }++ function resetConversations(): void {+ for (const agent of agents.values()) agent.handle({ t: 'reset' });+ }++ function announceAgent(except?: ExtensionLink): void {+ for (const link of openLinks()) {+ if (link === except) continue;+ void pushAgentState(link);+ pushSkillCatalog(link);+ }+ }++ function shareSkillCatalog(): void {+ for (const link of openLinks()) pushSkillCatalog(link);}async function settleAgent(request: AgentFrame): Promise<ActionResult<AgentState>> {@@ -411,7 +475,7 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):if (request.t === 'setAgent') {writeActiveAgent(request.agent);// The held conversation belongs to the agent that just left; the next turn starts fresh.- agent?.handle({ t: 'reset' });+ resetConversations();log(`agent set to ${AGENTS[request.agent].label}`);}if (request.t === 'setAgentModel') {@@ -466,11 +530,20 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):}function session(source: ExtensionLink): AgentSession {- return (agent ??= new AgentSession({- invoke,+ const held = agents.get(source);+ if (held) return held;+ const created = new AgentSession({+ invoke: (action, input, opts) => invokeOn(source, action, input, opts),emit: (id, event) => source.send({ t: 'run', id, event }),draft: (id, draft) => source.send({ t: 'siteMapDraft', id, draft }),- }));+ running: () => [...agents.values()].reduce((total, agent) => total + agent.running, 0),+ });+ agents.set(source, created);+ return created;+ }++ function sessionRunning(runId: string): AgentSession | undefined {+ return [...agents.values()].find((agent) => agent.owns(runId));}async function adoptExtensionManifest(source: ExtensionLink): Promise<void> {@@ -499,8 +572,21 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):broadcast({ event: 'manifest-changed' });}+ /**+ * A caller's tab ids only mean something in the browser that issued them, so a burst of calls+ * stays with one browser. Once the caller goes quiet, its next call follows the user instead.+ */+ function routeFor(binding: Binding): ExtensionLink | null {+ const held = binding.id ? links.get(binding.id) : undefined;+ const target = held?.isOpen && Date.now() - binding.usedAt < BINDING_IDLE_MS ? held : activeLink();+ binding.id = target?.id;+ binding.usedAt = Date.now();+ return target;+ }+function acceptControl(ws: WebSocket): void {const client = `c${++controlSeq}`;+ const binding: Binding = { usedAt: 0 };controls.add(ws);scheduleIdleExit();ws.on('message', async (raw) => {@@ -511,18 +597,20 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):return log('dropped unparseable control frame');}if (request.op === 'describe') return send(ws, { id: request.id, op: 'describe', tools });- if (request.op === 'status') return send(ws, { id: request.id, op: 'status', status: statusNow() });+ if (request.op === 'status') {+ return send(ws, { id: request.id, op: 'status', status: statusNow(routeFor(binding)) });+ }if (request.op === 'invoke') {let result: ActionResult;if (request.runId) {result =- (await agent?.invokeForRun(request.runId, request.action, request.input)) ??+ (await sessionRunning(request.runId)?.invokeForRun(request.runId, request.action, request.input)) ??failure('RUN_INACTIVE', 'This agent run is no longer active');if (!result.ok && result.error.code === 'RUN_INACTIVE') {log(`control ${client} invoked ${request.action} for inactive run ${request.runId}`);}} else {- result = await invokeExternal(request.action, request.input, client);+ result = await invokeExternal(routeFor(binding), request.action, request.input, client);}return send(ws, { id: request.id, op: 'invoke', result });}@@ -541,22 +629,19 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):}if (request.set) {writeActiveAgent(request.set);- agent?.handle({ t: 'reset' });+ resetConversations();log(`control ${client} set the agent to ${AGENTS[request.set].label}`);}if (request.grant) await grantRunner(request.grant);const state = await agentState(readAgentConfig(), { refresh: !!changed });- if (changed && link?.isOpen) {- void pushAgentState(link);- pushSkillCatalog(link);- }+ if (changed) announceAgent();return send(ws, { id: request.id, op: 'agent', state });}if (request.op === 'revoke') {- const target = request.origin;- const revoked = revokeSessions((session) => !target || session.origin === target);- if (revoked && link?.isOpen && (!target || link.origin === target)) {- link.close('pairing revoked');+ const { session: id, origin } = request;+ const revoked = revokeSessions((session) => (id ? sessionId(session) === id : !origin || session.origin === origin));+ for (const link of openLinks()) {+ if (id ? link.id === id : !origin || link.origin === origin) link.close('pairing revoked');}log(`revoked ${revoked} session(s)`);return send(ws, { id: request.id, op: 'revoke', revoked });@@ -579,26 +664,29 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):}function sessionSummaries(): SessionSummary[] {- return listSessions().map(({ key: _key, ...session }) => ({- ...session,- connected: link?.isOpen === true && link.origin === session.origin,- }));+ return listSessions().map(({ key: _key, installId: _installId, ...session }) => {+ const id = sessionId({ installId: _installId, origin: session.origin });+ return { id, ...session, connected: links.get(id)?.isOpen === true };+ });}- function statusNow(): BridgeStatus {+ function statusNow(target: ExtensionLink | null): BridgeStatus {return {- connected: !!link?.isOpen,+ connected: !!target,daemonVersion: version,protocolVersion: SOCKET_PROTOCOL_VERSION,port,- manifestInSync,- extensionVersion: link?.extensionVersion,+ manifestInSync: !target || inSync(target),+ extensionVersion: target?.extensionVersion,+ browser: target?.browser,+ connectedBrowsers: openLinks().length,pairedBrowsers: listSessions().length,pairingPending: hasPendingPairing(),};}- async function invoke(+ async function invokeOn(+ link: ExtensionLink | null,action: string,input?: unknown,opts?: { saveTo?: { dir: string; filename: string }; tabId?: number; runId?: string; hosts?: readonly string[] },@@ -619,8 +707,12 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):return persistDownload(action, persistScreenshot(action, input, result, opts?.saveTo), opts?.hosts);}- async function invokeExternal(action: string, input: unknown, client: string): Promise<ActionResult> {- const target = link;+ async function invokeExternal(+ target: ExtensionLink | null,+ action: string,+ input: unknown,+ client: string,+ ): Promise<ActionResult> {const toolId = randomUUID();const tell = (event: RunEvent) => {if (target?.isOpen) target.send({ t: 'run', id: EXTERNAL_RUN_ID, event });@@ -643,7 +735,7 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):log(`external ${client} → ${action} waived: ${describeDecision(decision)}`);}- const result = await invoke(action, input);+ const result = await invokeOn(target, action, input);log(`external ${client} → ${action} ${result.ok ? 'ok' : result.error.code}`);tell({kind: 'toolResult',@@ -657,9 +749,9 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):function scheduleIdleExit(): void {if (idleTimer) clearTimeout(idleTimer);if (!idleExit) return;- if (link?.isOpen || controls.size > 0) return;+ if (openLinks().length || controls.size > 0) return;idleTimer = setTimeout(() => {- if (link?.isOpen || controls.size > 0) return scheduleIdleExit();+ if (openLinks().length || controls.size > 0) return scheduleIdleExit();log('idle with no clients; exiting');void stop().then(() => process.exit(0));}, IDLE_EXIT_MS);@@ -668,8 +760,7 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):async function stop(): Promise<void> {if (idleTimer) clearTimeout(idleTimer);- agent?.dispose();- link?.close('daemon shutting down');+ for (const link of [...links.values()]) link.close('daemon shutting down');for (const ws of controls) ws.close(1001, 'daemon shutting down');wss.close();await new Promise<void>((resolve) => http.close(() => resolve()));@@ -677,11 +768,12 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):log('daemon stopped');}+ const local: Binding = { usedAt: 0 };return {port,describe: async () => tools,- invoke,- status: async () => statusNow(),+ invoke: (action, input) => invokeOn(routeFor(local), action, input),+ status: async () => statusNow(routeFor(local)),onManifestChanged: (listener) => manifestListeners.add(listener),close: stop,stop,diff --git a/src/daemon/extension-link.test.ts b/src/daemon/extension-link.test.tsindex d473efd..e902f48 100644--- a/src/daemon/extension-link.test.ts+++ b/src/daemon/extension-link.test.ts@@ -22,7 +22,7 @@ class FakeSocket extends EventEmitter {}}-const hello = { extensionVersion: '0.6.2', manifestHash: 'abc', origin: 'chrome-extension://abcdefghijklmnop' };+const hello = { extensionVersion: '0.6.2', manifestHash: 'abc', origin: 'chrome-extension://abcdefghijklmnop', installId: 'install-chrome-0001' };let socket: FakeSocket;let closed: ExtensionLink[];diff --git a/src/daemon/extension-link.ts b/src/daemon/extension-link.tsindex 83d3cd7..b937e20 100644--- a/src/daemon/extension-link.ts+++ b/src/daemon/extension-link.ts@@ -29,19 +29,25 @@ export class ExtensionLink {readonly extensionVersion: string;readonly manifestHash: string;readonly origin: string;+ readonly id: string;+ readonly browser?: string;+ /** Which connected browser the user was last in, so a caller that names none reaches that one. */+ lastActiveAt = Date.now();private readonly pending = new Map<string, Pending>();private readonly ping: ReturnType<typeof setTimeout>;private closed = false;constructor(private readonly socket: WebSocket,- hello: { extensionVersion: string; manifestHash: string; origin: string },+ hello: { extensionVersion: string; manifestHash: string; origin: string; installId: string; browser?: string },private readonly onClose: (link: ExtensionLink) => void,private readonly onRequest?: (request: ExtensionRequest, link: ExtensionLink) => void,) {this.extensionVersion = hello.extensionVersion;this.manifestHash = hello.manifestHash;this.origin = hello.origin;+ this.id = hello.installId;+ this.browser = hello.browser;socket.on('message', (raw) => this.receive(String(raw)));socket.on('close', () => this.dispose('socket closed'));socket.on('error', (error) => {@@ -51,6 +57,10 @@ export class ExtensionLink {this.ping = setInterval(() => this.send({ t: 'ping', id: randomUUID() }), PING_INTERVAL_MS);}+ get label(): string {+ return this.browser ?? this.origin;+ }+get isOpen(): boolean {return !this.closed && this.socket.readyState === this.socket.OPEN;}@@ -100,7 +110,11 @@ export class ExtensionLink {if (!frame) return log('dropped unparseable frame from extension');if (frame.t === 'ping') return this.send({ t: 'pong', id: frame.id });if (frame.t === 'pong') return;- if (isExtensionRequest(frame)) return this.onRequest?.(frame, this);+ if (frame.t === 'focus') return void (this.lastActiveAt = Date.now());+ if (isExtensionRequest(frame)) {+ this.lastActiveAt = Date.now();+ return this.onRequest?.(frame, this);+ }const id = 'id' in frame ? frame.id : undefined;const waiting = id ? this.pending.get(id) : undefined;diff --git a/src/daemon/paths.ts b/src/daemon/paths.tsindex a3c3cf5..bcf1acb 100644--- a/src/daemon/paths.ts+++ b/src/daemon/paths.ts@@ -21,9 +21,9 @@ export const userDir = join(homedir(), 'browsentic');* Two properties of this path are load-bearing, and both are easy to break:** - **It never carries a version.** Chrome derives an unpacked extension's ID from the- * absolute path of its directory, and the daemon binds each session key to the resulting- * `chrome-extension://<id>` origin. A versioned path would hand out a new identity on- * every update and silently unpair the browser.+ * absolute path of its directory, and the browser keeps the extension's storage under that+ * ID — the install id and session key the daemon knows it by. A versioned path would hand+ * out a new identity on every update and silently unpair the browser.* - **It does not live under stateDir.** stateDir moves with BROWSENTIC_HOME, which would* make the extension ID hostage to an environment variable. It is also a dotfolder, and* Chrome's "Load unpacked" dialog is the native folder picker, which hides those.diff --git a/src/daemon/remote-bridge.test.ts b/src/daemon/remote-bridge.test.tsindex 543e2a7..3f01604 100644--- a/src/daemon/remote-bridge.test.ts+++ b/src/daemon/remote-bridge.test.ts@@ -76,7 +76,7 @@ describe('asking the daemon', () => {});test('its status, a pairing code, the paired browsers, its agent, and a revocation', async () => {- const status = { connected: true, daemonVersion: '0.6.2', protocolVersion: 9, port, manifestInSync: true, pairedBrowsers: 1, pairingPending: false };+ const status = { connected: true, daemonVersion: '0.6.2', protocolVersion: 9, port, manifestInSync: true, connectedBrowsers: 1, pairedBrowsers: 1, pairingPending: false };const agentState = { active: 'claude' as const, runners: [] };answer = (request) => {const { id } = request;diff --git a/src/daemon/remote-bridge.ts b/src/daemon/remote-bridge.tsindex 959704e..50960ef 100644--- a/src/daemon/remote-bridge.ts+++ b/src/daemon/remote-bridge.ts@@ -69,8 +69,10 @@ export class RemoteBridge implements Bridge {throw new Error('The Browsentic daemon did not answer about its agent');}- async revoke(origin?: string): Promise<number> {- const reply = await this.request({ id: randomUUID(), op: 'revoke', origin });+ /** A browser is named by its session id; an origin still unpairs every browser presenting it. */+ async revoke(browser?: string): Promise<number> {+ const named = browser?.includes('://') ? { origin: browser } : { session: browser };+ const reply = await this.request({ id: randomUUID(), op: 'revoke', ...named });return reply && 'revoked' in reply ? reply.revoked : 0;}diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.tsindex eb6be9f..d7db7b9 100644--- a/src/daemon/server.test.ts+++ b/src/daemon/server.test.ts@@ -35,6 +35,7 @@ function fakeBridge(answers: Record<string, ActionResult> | Answer = {}, status:protocolVersion: 1,port: 0,manifestInSync: true,+ connectedBrowsers: 1,pairedBrowsers: 1,pairingPending: false,...status,diff --git a/src/extension/entrypoints/background.ts b/src/extension/entrypoints/background.tsindex 90389c6..1992959 100644--- a/src/extension/entrypoints/background.ts+++ b/src/extension/entrypoints/background.ts@@ -28,6 +28,7 @@ import {pairDaemon,readAgentState,readGuardrails,+ reportFocus,readSkillCatalog,setGuardrail,setUpAgent,@@ -222,6 +223,11 @@ export default defineBackground(() => {void connectDaemon();browser.runtime.onStartup.addListener(() => void connectDaemon());+ // With several browsers connected, a caller outside any of them reaches the one last in front.+ browser.windows?.onFocusChanged.addListener((windowId) => {+ if (windowId !== browser.windows.WINDOW_ID_NONE) reportFocus();+ });+browser.alarms.create(RECONNECT_ALARM, { periodInMinutes: 1 });browser.alarms.onAlarm.addListener((alarm) => {if (alarm.name === RECONNECT_ALARM) void connectDaemon();diff --git a/src/lib/actions/protocol.ts b/src/lib/actions/protocol.tsindex 72ed42c..ac5813e 100644--- a/src/lib/actions/protocol.ts+++ b/src/lib/actions/protocol.ts@@ -10,7 +10,7 @@ import type { SiteMapDraft } from '@/lib/skills/site-map';export const ACTION_CHANNEL = 'browsentic/action';export const BRIDGE_CHANNEL = 'browsentic/bridge';-export const SOCKET_PROTOCOL_VERSION = 16;+export const SOCKET_PROTOCOL_VERSION = 17;export const EXTERNAL_RUN_ID = 'external';@@ -169,6 +169,12 @@ export type SocketFrame =manifestHash: string;auth: SocketAuth;nonce: string;+ /**+ * Which browser profile this is. The extension origin cannot say: every Chromium browser+ * loading the same unpacked folder presents the same one.+ */+ installId: string;+ browser?: string;}| { t: 'challenge'; nonce: string }| { t: 'prove'; proof: string }@@ -188,6 +194,7 @@ export type SocketFrame =| { t: 'result'; id: string; result: ActionResult }| { t: 'ping'; id: string }| { t: 'pong'; id: string }+ | { t: 'focus' }| { t: 'instruct'; id: string; text: string; context?: RunContext }| { t: 'cancel'; id: string }| { t: 'decision'; id: string; toolId: string; allow: boolean; remember?: boolean }@@ -256,6 +263,12 @@ export function isExtensionRequest(frame: SocketFrame): frame is ExtensionRequesreturn (EXTENSION_REQUEST_FRAMES as readonly string[]).includes(frame.t);}+const INSTALL_ID = /^[A-Za-z0-9_-]{16,64}$/;++export function isInstallId(value: unknown): value is string {+ return typeof value === 'string' && INSTALL_ID.test(value);+}+export function parseFrame(raw: string): SocketFrame | null {try {const frame = JSON.parse(raw);diff --git a/src/lib/bridge/identity.ts b/src/lib/bridge/identity.tsnew file mode 100644index 0000000..7f8ca7f--- /dev/null+++ b/src/lib/bridge/identity.ts@@ -0,0 +1,49 @@+import { browser } from 'wxt/browser';++const INSTALL_ID_STORE = 'browsentic/installId';++const PLACEHOLDER_BRAND = /not.?a.?brand/i;++export interface Identity {+ installId: string;+ browser?: string;+}++let identity: Promise<Identity> | undefined;++/**+ * Kept apart from the session key so unpairing does not mint a new browser: pairing again then+ * replaces this browser's old session instead of leaving it behind as one that never returns.+ */+export function identify(): Promise<Identity> {+ return (identity ??= Promise.all([installId(), browserName()]).then(([id, name]) => ({+ installId: id,+ browser: name,+ })));+}++async function installId(): Promise<string> {+ const stored = (await browser.storage.local.get(INSTALL_ID_STORE))[INSTALL_ID_STORE];+ if (typeof stored === 'string' && stored) return stored;+ const minted = crypto.randomUUID();+ await browser.storage.local.set({ [INSTALL_ID_STORE]: minted });+ return minted;+}++export function brandFrom(brands: readonly { brand: string }[]): string | undefined {+ const named = brands.map(({ brand }) => brand).filter((brand) => !PLACEHOLDER_BRAND.test(brand));+ return named.find((brand) => brand !== 'Chromium') ?? named[0];+}++async function browserName(): Promise<string | undefined> {+ try {+ if (import.meta.env.FIREFOX) {+ const gecko = browser.runtime as typeof browser.runtime & { getBrowserInfo(): Promise<{ name: string }> };+ return (await gecko.getBrowserInfo()).name;+ }+ const agent = navigator as Navigator & { userAgentData?: { brands?: { brand: string }[] } };+ return brandFrom(agent.userAgentData?.brands ?? []);+ } catch {+ return undefined;+ }+}diff --git a/src/lib/bridge/socket.ts b/src/lib/bridge/socket.tsindex 7bbb04c..7954a96 100644--- a/src/lib/bridge/socket.ts+++ b/src/lib/bridge/socket.ts@@ -29,6 +29,7 @@ import type { AgentKind, AgentState } from '@/lib/agents/catalog';import type { GuardrailSettings, GuardrailValue } from '@/lib/settings/guardrails';import type { SkillDraft } from '@/lib/skills/format';import type { SiteMapDraft } from '@/lib/skills/site-map';+import { identify } from './identity';import { invokeForHarness } from './invoke';export const DAEMON_STATE_KEY = 'browsentic/daemon';@@ -78,6 +79,7 @@ export interface DaemonState {}let socket: WebSocket | null = null;+let welcomedSocket: WebSocket | null = null;let attempts = 0;let reconnectTimer: ReturnType<typeof setTimeout> | undefined;let stableTimer: ReturnType<typeof setTimeout> | undefined;@@ -422,14 +424,19 @@ function dial(credential: Credential, portIndex: number, carried?: Refusal): voiconst handshakeTimer = setTimeout(() => attempt.walk(), HANDSHAKE_TIMEOUT_MS);ws.onopen = () => {- send(ws, {- t: 'hello',- protocolVersion: SOCKET_PROTOCOL_VERSION,- extensionVersion: attempt.hello.extensionVersion,- manifestHash: attempt.hello.manifestHash,- auth: { kind: credential.kind },- nonce: attempt.hello.nonce,- });+ void identify()+ .then((identity) =>+ send(ws, {+ t: 'hello',+ protocolVersion: SOCKET_PROTOCOL_VERSION,+ extensionVersion: attempt.hello.extensionVersion,+ manifestHash: attempt.hello.manifestHash,+ auth: { kind: credential.kind },+ nonce: attempt.hello.nonce,+ ...identity,+ }),+ )+ .catch(() => attempt.walk());};ws.onmessage = (event) => {@@ -519,6 +526,7 @@ async function handle(ws: WebSocket, raw: string, attempt: Attempt): Promise<voiif (!sessionKey && (sealed || attempt.credential.kind === 'pair')) return attempt.walk();attempt.done();+ welcomedSocket = ws;// A link that is welcomed and then dropped at once has not recovered, and forgetting the// backoff on the welcome alone lets two peers take the link from each other every second.clearTimeout(stableTimer);@@ -603,6 +611,11 @@ async function handle(ws: WebSocket, raw: string, attempt: Attempt): Promise<voi}}+/** Held back until the daemon has welcomed us: mid-handshake it would be read as the proof. */+export function reportFocus(): void {+ if (socket && socket === welcomedSocket) post({ t: 'focus' });+}+function send(ws: WebSocket, frame: SocketFrame): void {if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(frame));}