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
fix(daemon): leave a daemon stopped with browsentic stop down until something starts it on purpose, rather than woken a second later by a paired browser, and unregister the wake-up before uninstall stops it
Shahriarcb30081d07b6
diff --git a/docs/guide/features/scheduling.md b/docs/guide/features/scheduling.mdindex 6b8a283..3de2f3a 100644--- a/docs/guide/features/scheduling.md+++ b/docs/guide/features/scheduling.md@@ -50,6 +50,9 @@ A run needs the browser open and the daemon up. The daemon starts itself when th`browsentic setup` registers a small helper that Chrome, Edge, Brave and Firefox can launch, and`browsentic status` says which browsers have it.+After `browsentic stop` the browser leaves the daemon down until `browsentic start`, or an MCP+client, brings it back.+A run that falls due while the browser is closed or the computer is asleep is logged as **missed**. Bydefault it then runs once when both are back; a task set to **Skip it** just waits for its next time.diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.mdindex 555a0d4..6acfce1 100644--- a/docs/guide/troubleshooting.md+++ b/docs/guide/troubleshooting.md@@ -29,6 +29,7 @@ Those three answer most questions. The daemon log also lives at `~/.browsentic/d| "This browser has no speech service" | Brave and some Chromium builds ship speech recognition without a transcription service behind it | Type instead, or use Chrome or Edge for dictation || `EXTENSION_OFFLINE` | Browser closed, or not paired | Open the browser; `browsentic sessions` to check pairing || After a reboot the panel stays offline until you run a command | The browser has no helper registered to start the daemon | Run `browsentic setup` once. `browsentic status` then lists the browsers under `wake-up:` |+| The panel stays offline after `browsentic stop` | A stop holds the browser's wake-up, so the daemon stays down as asked | `browsentic start`. `browsentic status` says `held` while it lasts || A scheduled task shows **Missed** | The browser was closed, the computer asleep, or no daemon was running at that time | Nothing to fix — it runs once when things are back unless the task says **Skip it**. `browsentic status` shows whether the browser can start the daemon itself || "Load unpacked" cannot see `~/browsentic` | A Flatpak or Snap browser, sandboxed away from your home directory. Snap Chromium is the Ubuntu default | Grant it: `flatpak override --user --filesystem=~/browsentic com.google.Chrome`. Or install somewhere the sandbox can read: `browsentic setup --dir ~/snap/chromium/common/browsentic-extension` || The folder picker does not show `~/browsentic` | It is there; some pickers open elsewhere by default | macOS: press ⇧⌘G and paste the path. Linux: Ctrl+L |diff --git a/docs/internals/extension.md b/docs/internals/extension.mdindex 7278a86..753893c 100644--- a/docs/internals/extension.md+++ b/docs/internals/extension.md@@ -245,7 +245,9 @@ on can answer, only with `isTrusted` clicks, and none in its first 800 ms.`nativeMessaging` is what lets a browser start a daemon that is down. When no port answers,`giveUp` calls `wakeDaemon`, which asks the browser to run the `com.browsentic.daemon` host that-`browsentic setup` registered. That host runs `ensureDaemon` and exits.+`browsentic setup` registered. That host runs `ensureDaemon` and exits. `browsentic stop` leaves+`~/.browsentic/stopped` behind, and while it is there the host starts nothing; the next daemon to+start, by any other path, removes it.---diff --git a/docs/internals/state.md b/docs/internals/state.mdindex 192873f..c34dd9b 100644--- a/docs/internals/state.md+++ b/docs/internals/state.md@@ -13,6 +13,7 @@ Nothing lives in the repository.├── models.json 0600 each agent CLI's own model list, as last read├── schedules.json 0600 scheduled tasks and the last twenty runs of each├── native-host/ the helper a browser launches to start the daemon+├── stopped only after `browsentic stop`: the helper leaves the daemon down├── daemon.log run starts, routed skills, every tool call and its outcome├── skills/ hand-written skill overrides├── cli/ macOS app only: the command, the daemon, bundled skills, the extension payload@@ -36,6 +37,7 @@ Nothing lives in the repository.| `models.json` | The daemon, reading each agent CLI's model list | A cache: deleting it only means the lists are read again. A failed read keeps the last list that read cleanly || `schedules.json` | The Schedules tab, `browsentic tasks` | At most 25 tasks. The daemon re-reads it every minute, so an edit from the CLI lands without a restart. Transcripts stay in the extension: the last three runs of each task || `native-host/` | `browsentic setup` | A launcher that runs this CLI with the `PATH` setup saw. Each browser gets a manifest in its own `NativeMessagingHosts` folder (a registry key on Windows) naming the extension origins allowed to use it; pairing adds the new one. `browsentic uninstall` removes both |+| `stopped` | `browsentic stop` and `restart` | While it exists the helper starts no daemon, so a paired browser cannot undo a stop. The next daemon to start removes it || `cli/`, `bin/`, `runtime/` | [Browsentic.app](../guide/mac-app.md) | Replaced whole on every app update. `cli/.browsentic-app.json` is what makes `installKind()` answer `app`, which turns the npm self-update off || `daemon.log` | The daemon | `browsentic logs`. Local [instant commands](../guide/features/instant-commands.md) never appear here, by design |diff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex 57b8bdb..d4eb4c2 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -116,7 +116,7 @@ reads, so the app and a terminal can never disagree about what is on disk.| Command | Does || --- | --- || `browsentic start` | Bring the background daemon up, if it is not already |-| `browsentic stop` | Stop the background daemon, whichever of 8765–8767 is answering |+| `browsentic stop` | Stop the background daemon, whichever of 8765–8767 is answering. A paired browser leaves it stopped until `browsentic start`, or an MCP client, starts it || `browsentic restart` | Stop the daemon and bring up a fresh one || `browsentic --version` / `-v` | Print the version || `browsentic help` / `--help` / `-h` | Usage |diff --git a/src/daemon/cli.ts b/src/daemon/cli.tsindex 2cf53f4..620f328 100644--- a/src/daemon/cli.ts+++ b/src/daemon/cli.ts@@ -17,7 +17,7 @@ import { readAgentConfig, rememberExtensionDir, writeAgentModel } from './agent/import { loadSkills, skillDirNames, uploadedSkillsDir } from './agent/skills';import { ensureDaemon, probeExisting, runningDaemons, stopDaemons } from './ensure-daemon';import { install, InstallError, readStamp } from './install';-import { logPath, readLockfile } from './lockfile';+import { logPath, readLockfile, wakeHeld } from './lockfile';import { log } from './log';import { installKind } from './npx';import { installNativeHost, registeredBrowsers, removeNativeHost, serveNativeHost } from './native-host';@@ -100,7 +100,7 @@ switch (command) {await uninstall(process.argv.slice(3));break;case 'native-host':- await serveNativeHost(ensureDaemon);+ await serveNativeHost(ensureDaemon, wakeHeld);break;case 'pair':await pair();@@ -232,7 +232,13 @@ function printSkills(): void {async function showStatus(): Promise<void> {const lock = await probeExisting();const waking = registeredBrowsers();- const wake = `wake-up: ${waking.length ? `${waking.join(', ')} can start the daemon` : 'not registered — run "browsentic setup"'}`;+ const wake = `wake-up: ${+ !waking.length+ ? 'not registered — run "browsentic setup"'+ : wakeHeld()+ ? `held since "browsentic stop" — "browsentic start" lets ${waking.join(', ')} start it again`+ : `${waking.join(', ')} can start the daemon`+ }`;if (!lock) {console.log('daemon: not running');console.log(wake);@@ -278,6 +284,7 @@ async function stop(): Promise<void> {console.error(`Daemon (pid ${daemon.pid}) on 127.0.0.1:${daemon.port} would not exit — kill it by hand.`);}if (!stopped.length && !stubborn.length) console.log('No daemon is answering; nothing to stop.');+ console.log('A paired browser leaves it stopped until "browsentic start", or an MCP client, starts it again.');if (stubborn.length) process.exitCode = 1;}@@ -326,16 +333,16 @@ async function pair(): Promise<void> {* A function declaration, not a const arrow: the switch at the top of this file invokes* commands before execution reaches the bottom, so anything they call has to be hoisted.*/+function groupCode(code: string): string {+ return `${code.slice(0, 4)}-${code.slice(4)}`;+}+function wakeLine(browsers: string[]): string {return browsers.length? `✓ Wake-up ${browsers.join(', ')} can start the daemon when it is down`: '· Wake-up no supported browser found, so start the daemon yourself after a reboot';}-function groupCode(code: string): string {- return `${code.slice(0, 4)}-${code.slice(4)}`;-}-/*** Install the extension, bring up the daemon, and hand back a pairing code. The two steps* left after this happen inside the browser, so only the user can do them.@@ -600,13 +607,14 @@ async function uninstall(argv: string[]): Promise<void> {}}+ // Before the daemon goes, or a browser that sees it go could have the host start another.+ const unregistered = removeNativeHost();+ if (unregistered.length) console.log(` ✓ Wake-up unregistered from ${unregistered.length} place${unregistered.length === 1 ? '' : 's'}`);+const { stopped, stubborn } = await stopDaemons();if (stopped.length) console.log(` ✓ Daemon stopped (pid ${stopped.map((daemon) => daemon.pid).join(', ')})`);for (const daemon of stubborn) console.log(` ✗ Daemon pid ${daemon.pid} would not exit — kill it by hand`);- const unregistered = removeNativeHost();- if (unregistered.length) console.log(` ✓ Wake-up unregistered from ${unregistered.length} place${unregistered.length === 1 ? '' : 's'}`);-for (const outcome of removeAll(plan.removals)) {if (!outcome.removed) console.log(` ✗ ${outcome.removal.path} — ${outcome.error}`);else if (outcome.kept.length) console.log(` ✓ Emptied ${outcome.removal.path} — kept ${outcome.kept.join(', ')}/`);diff --git a/src/daemon/daemon.ts b/src/daemon/daemon.tsindex 1e0c020..0df5896 100644--- a/src/daemon/daemon.ts+++ b/src/daemon/daemon.ts@@ -85,7 +85,7 @@ import {summary as summarizeDecision,} from './guardrails';import { log } from './log';-import { readLockfile, writeLockfile, clearLockfile, type Lockfile } from './lockfile';+import { readLockfile, writeLockfile, clearLockfile, releaseWake, type Lockfile } from './lockfile';import { daemonPorts } from './ports';type AgentFrame = Extract<SocketFrame, { t: 'agentState' | 'setAgent' | 'setAgentModel' | 'grantAgent' }>;@@ -227,6 +227,7 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):const port = await listen(http);lock.port = port;writeLockfile(lock);+ releaseWake();log(`daemon ${version} listening on 127.0.0.1:${port} (pid ${process.pid})`);scheduleIdleExit();diff --git a/src/daemon/ensure-daemon.ts b/src/daemon/ensure-daemon.tsindex 78c15ea..8c9530e 100644--- a/src/daemon/ensure-daemon.ts+++ b/src/daemon/ensure-daemon.ts@@ -1,7 +1,7 @@import { spawn } from 'node:child_process';import { fileURLToPath } from 'node:url';import { dirname, join } from 'node:path';-import { clearLockfile, isRunning, readLockfile, type Lockfile } from './lockfile';+import { clearLockfile, holdWake, isRunning, readLockfile, type Lockfile } from './lockfile';import { log } from './log';import { daemonPorts } from './ports';@@ -81,6 +81,7 @@ export interface StopResult {/** SIGTERM every daemon, then SIGKILL whatever is still standing, and drop the lockfile. */export async function stopDaemons(graceMs = 5_000): Promise<StopResult> {+ holdWake();const daemons = await runningDaemons();for (const { pid } of daemons) kill(pid, 'SIGTERM');diff --git a/src/daemon/lockfile.ts b/src/daemon/lockfile.tsindex 1e64cba..eea6916 100644--- a/src/daemon/lockfile.ts+++ b/src/daemon/lockfile.ts@@ -1,4 +1,4 @@-import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { stateDir } from './paths.js';@@ -35,6 +35,24 @@ export function clearLockfile(): void {rmSync(lockfilePath, { force: true });}+/**+ * Left by a stop and cleared by the next daemon to start. While it is there the browser's+ * wake-up leaves the daemon down, so `browsentic stop` is not undone a second later by a+ * paired browser reconnecting.+ */+export const stoppedPath = join(stateDir, 'stopped');++export function holdWake(): void {+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });+ writeFileSync(stoppedPath, `${new Date().toISOString()}\n`, { mode: 0o600 });+}++export function releaseWake(): void {+ rmSync(stoppedPath, { force: true });+}++export const wakeHeld = (): boolean => existsSync(stoppedPath);+export function isRunning(pid: number): boolean {try {process.kill(pid, 0);diff --git a/src/daemon/native-host.test.ts b/src/daemon/native-host.test.tsindex 85a307a..49021cd 100644--- a/src/daemon/native-host.test.ts+++ b/src/daemon/native-host.test.ts@@ -1,9 +1,11 @@import { existsSync, mkdirSync, readFileSync, rmSync, statSync } from 'node:fs';import { homedir } from 'node:os';import { join } from 'node:path';-import { beforeEach, describe, expect, it } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';import {NATIVE_HOST_NAME,+ STOPPED_REPLY,+ answerNativeMessage,decodeNativeMessage,encodeNativeMessage,hostManifest,@@ -85,6 +87,27 @@ describe('the message frame', () => {});});+describe('answering the browser', () => {+ const ensure = vi.fn(async () => ({ port: 8765 }));++ beforeEach(() => ensure.mockClear());++ it('starts the daemon when asked', async () => {+ expect(await answerNativeMessage({ op: 'ensure' }, ensure, () => false)).toEqual({ ok: true, port: 8765 });+ expect(ensure).toHaveBeenCalledOnce();+ });++ it('leaves a daemon stopped on purpose down', async () => {+ expect(await answerNativeMessage({ op: 'ensure' }, ensure, () => true)).toBe(STOPPED_REPLY);+ expect(ensure).not.toHaveBeenCalled();+ });++ it('refuses anything but ensure', async () => {+ expect(await answerNativeMessage({ op: 'spawn' }, ensure, () => false)).toMatchObject({ ok: false });+ expect(ensure).not.toHaveBeenCalled();+ });+});+describe('registering the host', () => {const chromeHome = join(homedir(), '.config', 'google-chrome');const manifest = join(chromeHome, 'NativeMessagingHosts', `${NATIVE_HOST_NAME}.json`);diff --git a/src/daemon/native-host.ts b/src/daemon/native-host.tsindex e0e3d14..d33fe4f 100644--- a/src/daemon/native-host.ts+++ b/src/daemon/native-host.ts@@ -262,15 +262,26 @@ function readNativeMessage(input: NodeJS.ReadableStream): Promise<unknown> {});}-export async function serveNativeHost(ensure: () => Promise<{ port: number }>): Promise<void> {+export const STOPPED_REPLY = { ok: false, error: 'Stopped with "browsentic stop"; "browsentic start" lets the browser start it again.' };++export async function serveNativeHost(ensure: () => Promise<{ port: number }>, held: () => boolean): Promise<void> {const message = (await readNativeMessage(process.stdin)) as { op?: unknown } | null;- const reply =- message?.op === 'ensure'- ? await ensure()- .then((lock) => ({ ok: true, port: lock.port }))- .catch((error) => ({ ok: false, error: String(error) }))- : { ok: false, error: 'Expected {"op":"ensure"}.' };- log(`native host: ${reply.ok ? 'daemon ready' : `could not start the daemon — ${'error' in reply ? reply.error : ''}`}`);+ const reply = await answerNativeMessage(message, ensure, held);+ if (reply !== STOPPED_REPLY) {+ log(`native host: ${reply.ok ? 'daemon ready' : `could not start the daemon — ${'error' in reply ? reply.error : ''}`}`);+ }await new Promise<void>((resolve) => process.stdout.write(encodeNativeMessage(reply), () => resolve()));}+export async function answerNativeMessage(+ message: { op?: unknown } | null,+ ensure: () => Promise<{ port: number }>,+ held: () => boolean,+): Promise<{ ok: boolean; port?: number; error?: string }> {+ if (message?.op !== 'ensure') return { ok: false, error: 'Expected {"op":"ensure"}.' };+ if (held()) return STOPPED_REPLY;+ return ensure()+ .then((lock) => ({ ok: true, port: lock.port }))+ .catch((error) => ({ ok: false, error: String(error) }));+}+diff --git a/src/daemon/test/startup.test.ts b/src/daemon/test/startup.test.tsindex d37f713..0b128f5 100644--- a/src/daemon/test/startup.test.ts+++ b/src/daemon/test/startup.test.ts@@ -3,11 +3,12 @@ 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';+import { holdWake, readLockfile, stateDir, wakeHeld } from '../lockfile';describe('a daemon started in the sandbox', () => {let daemon: Daemon;beforeAll(async () => {+ holdWake();daemon = await startDaemon({ version: '0.0.0-test', idleExit: false });});afterAll(async () => {@@ -23,6 +24,10 @@ describe('a daemon started in the sandbox', () => {expect(readLockfile()).toMatchObject({ pid: process.pid, port: daemon.port, daemonVersion: '0.0.0-test' });});+ test('clears the mark a stop left, so the browser can wake a daemon again', () => {+ expect(wakeHeld()).toBe(false);+ });+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 });