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(daemon): let tests move the daemon off the real ports with BROWSENTIC_PORTS, and start one in the integration suite

Shahriardb841744cfe0
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 3860312..f2d6faa 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -61,7 +61,8 @@ Where a test lives decides what it runs in:
| --- | --- |
| `src/lib/**` | Node, with WXT's fake `browser` |
| `src/lib/actions/page/**` | happy-dom |
-| `src/daemon/**` | Node, with `HOME` and the daemon's state in a throwaway directory |
+| `src/daemon/**` | Node, with `HOME` and the daemon's state in a throwaway directory and ports the OS picks |
+| `src/daemon/test/**` | The same sandbox, for tests that start a real daemon |
Never put a test under `src/extension/entrypoints/`, because WXT builds every file there as an
entrypoint. The floors in [vitest.coverage.ts](vitest.coverage.ts) only ever go up: raise one when
diff --git a/docs/internals/contributing.md b/docs/internals/contributing.md
index f63c247..1b8cb48 100644
--- a/docs/internals/contributing.md
+++ b/docs/internals/contributing.md
@@ -39,6 +39,7 @@ yarn daemon:dev # rebuild the daemon on change
yarn daemon:restart # rebuild, then swap the running daemon for the fresh build
yarn daemon:manifest # print the tool manifest, no browser needed
yarn test # every test; pass a path to run fewer
+yarn test:integration # only the tests that start a real daemon
yarn coverage # the tests, then coverage by area against its floors
yarn check:intent "<utterance>" # how the local grammar routes one instruction
yarn check # both type checks, then the tests and their coverage floors
diff --git a/docs/internals/transport.md b/docs/internals/transport.md
index fab6af2..e0ace67 100644
--- a/docs/internals/transport.md
+++ b/docs/internals/transport.md
@@ -14,6 +14,11 @@ The daemon runs one HTTP server that answers `GET /health` and upgrades everythi
WebSocket. It binds the first free port of **8765, 8766, 8767**. If all three are taken it will not
start.
+`BROWSENTIC_PORTS` replaces that list for the daemon and the CLI: comma-separated, with `0` for
+whatever port the OS hands out. The test suite sets it so a test daemon never takes a port from the
+one you are running. The extension cannot read it and still walks the three, so a daemon moved off
+them is one no browser will find.
+
---
## The origin gate
diff --git a/package.json b/package.json
index 834eece..d002294 100644
--- a/package.json
+++ b/package.json
@@ -19,6 +19,7 @@
"check": "yarn compile && yarn daemon:compile && yarn coverage",
"check:intent": "node scripts/explain-intent.ts",
"test": "vitest run",
+ "test:integration": "vitest run --project integration",
"coverage": "vitest run --coverage",
"daemon:compile": "yarn --cwd src/daemon compile",
"daemon:build": "yarn --cwd src/daemon build",
diff --git a/src/daemon/daemon.ts b/src/daemon/daemon.ts
index aaed46a..a77532b 100644
--- a/src/daemon/daemon.ts
+++ b/src/daemon/daemon.ts
@@ -1,9 +1,9 @@
import { randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
import { createServer, type IncomingMessage, type Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
import type { Duplex } from 'node:stream';
import { WebSocketServer, type WebSocket } from 'ws';
import {
- DAEMON_PORTS,
EXTERNAL_RUN_ID,
SOCKET_PROTOCOL_VERSION,
failure,
@@ -67,6 +67,7 @@ import {
} from './guardrails';
import { log } from './log';
import { readLockfile, writeLockfile, clearLockfile, type Lockfile } from './lockfile';
+import { daemonPorts } from './ports';
type AgentFrame = Extract<SocketFrame, { t: 'agentState' | 'setAgent' | 'setAgentModel' | 'grantAgent' }>;
type GuardrailFrame = Extract<SocketFrame, { t: 'guardrails' | 'setGuardrail' }>;
@@ -689,16 +690,16 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):
function listen(http: Server): Promise<number> {
return new Promise((resolve, reject) => {
- const remaining = [...DAEMON_PORTS];
+ const remaining = [...daemonPorts];
const attempt = () => {
const port = remaining.shift();
if (port === undefined) {
- reject(new Error(`No free port in ${DAEMON_PORTS.join(', ')} — another process is using them all`));
+ reject(new Error(`No free port in ${daemonPorts.join(', ')} — another process is using them all`));
return;
}
const onListening = () => {
http.removeListener('error', onError);
- resolve(port);
+ resolve((http.address() as AddressInfo).port);
};
const onError = (error: NodeJS.ErrnoException) => {
http.removeListener('listening', onListening);
diff --git a/src/daemon/ensure-daemon.ts b/src/daemon/ensure-daemon.ts
index 55a25e0..78c15ea 100644
--- a/src/daemon/ensure-daemon.ts
+++ b/src/daemon/ensure-daemon.ts
@@ -1,9 +1,9 @@
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
-import { DAEMON_PORTS } from '@/lib/actions/protocol';
import { clearLockfile, isRunning, readLockfile, type Lockfile } from './lockfile';
import { log } from './log';
+import { daemonPorts } from './ports';
const SPAWN_TIMEOUT_MS = 8_000;
const POLL_INTERVAL_MS = 150;
@@ -41,7 +41,7 @@ export async function probeExisting(): Promise<Lockfile | null> {
// The control token is minted per daemon, so a daemon found on another port is only reachable
// through the lockfile it wrote itself — which its pid identifies.
- for (const port of DAEMON_PORTS) {
+ for (const port of daemonPorts) {
if (port === lock?.port) continue;
const pid = await healthyPid(port);
if (pid === null) continue;
@@ -67,7 +67,7 @@ export interface RunningDaemon {
*/
export async function runningDaemons(): Promise<RunningDaemon[]> {
const found = new Map<number, number>();
- for (const port of DAEMON_PORTS) {
+ for (const port of daemonPorts) {
const pid = await healthyPid(port);
if (pid !== null && !found.has(pid)) found.set(pid, port);
}
diff --git a/src/daemon/ports.test.ts b/src/daemon/ports.test.ts
new file mode 100644
index 0000000..af55448
--- /dev/null
+++ b/src/daemon/ports.test.ts
@@ -0,0 +1,31 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { DAEMON_PORTS } from '@/lib/actions/protocol';
+
+const portsWith = async (value: string | undefined) => {
+ vi.resetModules();
+ vi.stubEnv('BROWSENTIC_PORTS', value);
+ return (await import('./ports')).daemonPorts;
+};
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe('daemonPorts', () => {
+ test('unset, the daemon uses the ports the extension walks', async () => {
+ expect(await portsWith(undefined)).toEqual(DAEMON_PORTS);
+ });
+
+ test('a list is taken in order', async () => {
+ expect(await portsWith('9001, 9002')).toEqual([9001, 9002]);
+ });
+
+ test('0 leaves the choice to the OS', async () => {
+ expect(await portsWith('0')).toEqual([0]);
+ });
+
+ test('anything that is not a port is refused rather than ignored', async () => {
+ await expect(portsWith('8765,http')).rejects.toThrow('BROWSENTIC_PORTS');
+ await expect(portsWith('70000')).rejects.toThrow('BROWSENTIC_PORTS');
+ });
+});
diff --git a/src/daemon/ports.ts b/src/daemon/ports.ts
new file mode 100644
index 0000000..c4565a2
--- /dev/null
+++ b/src/daemon/ports.ts
@@ -0,0 +1,17 @@
+import { DAEMON_PORTS } from '@/lib/actions/protocol';
+
+/**
+ * The ports the daemon binds and its local clients probe. Relocatable like stateDir, so a test
+ * daemon never contends with the one the user is running; `0` lets the OS pick. The extension
+ * cannot read the environment and always walks DAEMON_PORTS.
+ */
+export const daemonPorts: readonly number[] = parsePorts(process.env.BROWSENTIC_PORTS) ?? DAEMON_PORTS;
+
+function parsePorts(value: string | undefined): number[] | null {
+ if (!value) return null;
+ const ports = value.split(',').map((port) => Number(port.trim()));
+ if (ports.some((port) => !Number.isInteger(port) || port < 0 || port > 65_535)) {
+ throw new Error(`BROWSENTIC_PORTS must be a comma-separated list of ports, not "${value}"`);
+ }
+ return ports;
+}
diff --git a/src/daemon/test/sandbox.ts b/src/daemon/test/sandbox.ts
index 7f96906..9aa6100 100644
--- a/src/daemon/test/sandbox.ts
+++ b/src/daemon/test/sandbox.ts
@@ -3,13 +3,14 @@ import { homedir, tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterAll } from 'vitest';
-// stateDir is read once at import and ~/browsentic only moves with HOME, so both have to be
-// in place before a test file imports anything from the daemon.
+// stateDir and the port list are read once at import and ~/browsentic only moves with HOME, so
+// all three have to be in place before a test file imports anything from the daemon.
const realHome = homedir();
const home = realpathSync(mkdtempSync(join(tmpdir(), 'browsentic-test-')));
process.env.HOME = home;
process.env.BROWSENTIC_HOME = join(home, '.browsentic');
+process.env.BROWSENTIC_PORTS = '0';
delete process.env.BROWSENTIC_AGENT_RUN;
if (homedir() === realHome) throw new Error(`the test sandbox did not move HOME away from ${realHome}`);
diff --git a/src/daemon/test/startup.test.ts b/src/daemon/test/startup.test.ts
new file mode 100644
index 0000000..4345eb8
--- /dev/null
+++ b/src/daemon/test/startup.test.ts
@@ -0,0 +1,41 @@
+import { get } from 'node:http';
+import { homedir } from 'node:os';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { DAEMON_PORTS } from '@/lib/actions/protocol';
+import { startDaemon, type Daemon } from '../daemon';
+import { readLockfile, stateDir } from '../lockfile';
+
+describe('a daemon started in the sandbox', () => {
+ let daemon: Daemon;
+ beforeAll(async () => {
+ daemon = await startDaemon({ version: '0.0.0-test', idleExit: false });
+ });
+ afterAll(async () => {
+ await daemon?.stop();
+ });
+
+ test('binds a port the OS picked, never one a real daemon would use', () => {
+ expect(DAEMON_PORTS).not.toContain(daemon.port);
+ });
+
+ test('writes its lockfile inside the sandboxed home', () => {
+ expect(stateDir.startsWith(homedir())).toBe(true);
+ expect(readLockfile()).toMatchObject({ pid: process.pid, port: daemon.port, daemonVersion: '0.0.0-test' });
+ });
+
+ test('answers /health on the port it recorded', async () => {
+ const response = await fetch(`http://127.0.0.1:${readLockfile()?.port}/health`);
+ expect(await response.json()).toEqual({ ok: true, pid: process.pid, version: '0.0.0-test', connected: false });
+ });
+
+ // fetch() will not send a Host of the caller's choosing, and a rebound page's Host is the whole point.
+ test('turns away a host that is not loopback', async () => {
+ const status = await new Promise((resolve, reject) => {
+ get({ host: '127.0.0.1', port: daemon.port, path: '/health', headers: { host: 'evil.example' } }, (response) => {
+ response.resume();
+ resolve(response.statusCode);
+ }).on('error', reject);
+ });
+ expect(status).toBe(403);
+ });
+});
diff --git a/vitest.config.ts b/vitest.config.ts
index d8eca17..f4fa79d 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -43,6 +43,15 @@ export default defineConfig({
setupFiles: ['src/daemon/test/sandbox.ts'],
},
},
+ {
+ resolve: daemonResolve,
+ test: {
+ name: 'integration',
+ include: ['src/daemon/test/**/*.test.ts'],
+ setupFiles: ['src/daemon/test/sandbox.ts'],
+ testTimeout: 20_000,
+ },
+ },
],
coverage: {
provider: 'v8',
diff --git a/vitest.coverage.ts b/vitest.coverage.ts
index f7edc3b..cb4fd14 100644
--- a/vitest.coverage.ts
+++ b/vitest.coverage.ts
@@ -9,10 +9,10 @@ import type { Reporter, Vitest } from 'vitest/node';
*/
export const COVERAGE_AREAS = [
{ name: 'Guardrails, secrets, intent', glob: 'src/{daemon/guardrails,lib/secrets,lib/intent}/**', lines: 93 },
- { name: 'Daemon', glob: 'src/daemon/{*.ts,!(guardrails)/**/*.ts}', lines: 11 },
- { name: 'Shared lib', glob: 'src/lib/{*.ts,actions/*.ts,!(actions|bridge|intent|secrets)/**/*.ts}', lines: 13 },
+ { name: 'Daemon', glob: 'src/daemon/{*.ts,!(guardrails)/**/*.ts}', lines: 16 },
+ { name: 'Shared lib', glob: 'src/lib/{*.ts,actions/*.ts,!(actions|bridge|intent|secrets)/**/*.ts}', lines: 22 },
{ name: 'Extension background', glob: 'src/lib/bridge/!(use-*).ts', lines: 1 },
- { name: 'Page actions', glob: 'src/lib/actions/page/**', lines: 3 },
+ { name: 'Page actions', glob: 'src/lib/actions/page/**', lines: 11 },
];
interface CoverageMap {