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(bridge): the Firefox task on Windows sits in the root folder under the user's own name, where a user without elevation may create it, at normal priority, and is registered again whenever it has gone missing; a Bridge the task started is waited for instead of doubled inside the job that dies; a Mac counts a browser as installed by the file it writes into its profile, not the folder a baseline manifest made; a browser that pairs by code answers its pending request; a pairing setting of the wrong shape pairs only by code; approve --name keeps the name out of the id, and says when Reconnect is still to press

Shahriara30eeba1d275
diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md
index 8c639be..40cd779 100644
--- a/docs/guide/configuration.md
+++ b/docs/guide/configuration.md
@@ -8,7 +8,9 @@ without a restart. It also watches the file, so the settings page and the Mac ap
as soon as you save it.
`BROWSENTIC_HOME` moves the whole state directory somewhere other than `~/.browsentic`.
-[internals/state.md](../internals/state.md) has the full disk layout.
+[internals/state.md](../internals/state.md) has the full disk layout. A Bridge whose state lives
+outside your home folder leaves your browsers registered with the one inside it, so a scratch copy
+never takes them over; set `BROWSENTIC_REGISTER_HOST=1` to register it anyway.
---
diff --git a/docs/guide/pair.md b/docs/guide/pair.md
index 123a423..3a94701 100644
--- a/docs/guide/pair.md
+++ b/docs/guide/pair.md
@@ -147,8 +147,9 @@ browsentic approve <id> # let a revoked or denied browser back in
```
Revoking a browser also keeps it from pairing again by itself, so it does not come back a minute
-later. It returns when you press **Reconnect** in that browser (in `auto` mode), allow it in the app
-or with `browsentic approve <id>`, or pair it with a code. **Disconnect** in the extension does the
+later. It returns when you press **Reconnect** in that browser (in `auto` mode), or pair it with a
+code. In `ask` mode, allow it in the app or with `browsentic approve <id>` as well; either way the
+browser connects once you press **Reconnect** in it. **Disconnect** in the extension does the
same from the browser's side: it stays unpaired until you press **Connect** there.
Several browsers can be paired **and connected at once**: Chrome beside Brave, or two Chrome
@@ -181,8 +182,8 @@ The side panel's **Connection** sheet and the welcome page say why. The usual re
## 6. Browsers it registers with
`setup`, the apps and every Bridge start register the native host where each installed browser
-reads it, plus Chrome's and Mozilla's locations always, since Brave, Opera and other forks read
-Chrome's. On macOS, a Chromium fork no list names is found from its app's `Info.plist`.
+reads it. On macOS and Windows they also always register it in Chrome's and Mozilla's locations,
+since Brave, Opera and other forks read Chrome's. On macOS, a Chromium fork no list names is found from its app's `Info.plist`.
Registered: Chrome and its Beta, Dev and Canary channels, Edge and its channels, Brave, Vivaldi,
Arc, Opera, Opera GX, Comet, Thorium, Chromium, Firefox and its channels, Zen, LibreWolf, Waterfox
diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.md
index cf8a1a6..e6155ee 100644
--- a/docs/guide/troubleshooting.md
+++ b/docs/guide/troubleshooting.md
@@ -30,12 +30,12 @@ Those three answer most questions. The Bridge's log is at `~/.browsentic/daemon.
| `browsentic setup` keeps waiting for the browser | The extension is installed but not paired yet: it predates automatic pairing, pairing is set to `code`, or it is waiting for you to allow it | Open the side panel: it says which. Enter the code `setup` printed, or allow the browser when `setup` asks. Ctrl-C stops the wait without undoing anything |
| The panel says **Browsentic Bridge isn't on this computer yet**, but it is | This browser has no native messaging host registered: it was installed after the Bridge ran, or it is a browser the Bridge does not know | Open the app or run `browsentic setup`, which registers it; a running Bridge also does so within the hour. Or pair with a code |
| The panel says **Allow this browser in the Browsentic app** | `pairing` is `ask` and nobody has allowed it yet | Press **Allow** in the app's sheet or notification, or run `browsentic approve`. `browsentic requests` lists who is waiting |
-| The panel says **This computer disconnected this browser** | It was revoked, from the app or with `browsentic revoke`, and does not pair again by itself | Press **Reconnect**, or `browsentic approve <id>` |
+| The panel says **This computer disconnected this browser** | It was revoked, from the app or with `browsentic revoke`, and does not pair again by itself | Press **Reconnect**. In `ask` mode, also allow it in the app or with `browsentic approve <id>` |
| The panel says **Automatic pairing is off on this computer** | `pairing` is `code` | Pair with a code, or `browsentic pairing auto` |
| The panel says **Your organization's browser policy keeps Browsentic Bridge from starting** | A managed browser blocks Browsentic's native messaging host | Pair with a code. A policy that turns off per-user hosts altogether shows as "isn't on this computer yet" instead, so on a work computer try a code first |
| The panel says **Browsentic Bridge needs an update** | The Bridge on this computer is older than automatic pairing, or older than 0.8 and does not let store copies in | `npx browsentic@latest update`, or **Update now** in the app |
| The panel says **Browsentic Bridge was updated but the old one is still running** | Pairing is set to ask and the Bridge still running is the one from before the update | `browsentic restart`, or **Restart** in the app |
-| Firefox on Windows wakes the Bridge, then it is gone again | Firefox ends everything a native host starts when the host exits | Setup registers a scheduled task (Task Scheduler, `Browsentic\Bridge`) that starts the Bridge outside Firefox; run `browsentic setup` once if it was installed before that. Starting the Bridge from the app or `browsentic start` also works |
+| Firefox on Windows wakes the Bridge, then it is gone again | Firefox ends everything a native host starts when the host exits | Setup registers a scheduled task (Task Scheduler, `Browsentic Bridge for <your user name>`) that starts the Bridge outside Firefox; run `browsentic setup` once if it was installed before that. Starting the Bridge from the app or `browsentic start` also works |
| The side panel's **Connection** sheet shows `Expected {op:…}` | Stale service worker after a rebuild | At `chrome://extensions`, press ↻ on Browsentic |
| "That pairing code is wrong or expired" | Codes are single-use and last 10 minutes | Run `browsentic pair` for a new code. A failed attempt does not use up the outstanding code |
| "No Browsentic daemon is running" | Browsentic Bridge is not installed, or not running on 8765–8767 | [Install it](install.md#1-install-browsentic), open the app, or run `browsentic start`. Then check `browsentic status` and `browsentic logs` |
diff --git a/src/daemon/agent/config.test.ts b/src/daemon/agent/config.test.ts
index f3f9f7d..4e19550 100644
--- a/src/daemon/agent/config.test.ts
+++ b/src/daemon/agent/config.test.ts
@@ -5,12 +5,14 @@ import {
activeAgent,
configPath,
maxConcurrentRuns,
+ pairingMode,
readAgentConfig,
rememberExtensionDir,
siteMapSettings,
writeActiveAgent,
writeAgentModel,
writeGuardrailSetting,
+ writePairingMode,
writeTheme,
type AgentConfig,
} from './config';
@@ -51,6 +53,23 @@ describe('reading config.json', () => {
expect(readAgentConfig()).toEqual(DEFAULTS);
});
+ test('a pairing setting of the wrong shape pairs only by code, unless it names a mode', () => {
+ const read = (pairing: unknown) => {
+ store({ pairing });
+ return pairingMode();
+ };
+ expect([undefined, {}, { mode: 'ask' }, 'ask', 7, null, [], { mode: 'sometimes' }].map(read)).toEqual([
+ 'auto',
+ 'auto',
+ 'ask',
+ 'ask',
+ 'code',
+ 'code',
+ 'code',
+ 'code',
+ ]);
+ });
+
test('a file that is not an object reads as the defaults', () => {
store('null');
expect(readAgentConfig()).toEqual(DEFAULTS);
@@ -111,6 +130,15 @@ describe('limits', () => {
});
describe('writing config.json', () => {
+ test('setting how browsers pair keeps the rest of its key, and replaces one of the wrong shape', () => {
+ store({ pairing: { mode: 'ask', note: 'kept' } });
+ writePairingMode('code');
+ const kept = stored();
+ store({ pairing: 'ask' });
+ writePairingMode('auto');
+ expect([kept, stored()]).toEqual([{ pairing: { mode: 'code', note: 'kept' } }, { pairing: { mode: 'auto' } }]);
+ });
+
test('switching agents changes that one key and leaves everything else as it was written', () => {
store({ agents: { claude: { bin: 'claude' } }, custom: { keep: true } });
writeActiveAgent('antigravity');
diff --git a/src/daemon/agent/config.ts b/src/daemon/agent/config.ts
index ce3563a..e74c050 100644
--- a/src/daemon/agent/config.ts
+++ b/src/daemon/agent/config.ts
@@ -49,12 +49,13 @@ export interface AgentConfig {
/** Driving Chrome on an Android phone. Off stops every use of adb; `adb` names the binary to use. */
android?: { enabled?: boolean; adb?: string };
/** How a browser pairs through the native host: by itself, once someone allows it, or only with a code. */
- pairing?: { mode?: unknown };
+ pairing?: unknown;
}
/** A hand edit naming a mode Browsentic does not know pairs nothing by itself: whoever wrote it meant something stricter than the default, or made a typo worth noticing. */
export function pairingMode(config: AgentConfig = readAgentConfig()): PairingMode {
- const mode = config.pairing?.mode;
+ const { pairing } = config;
+ const mode = pairingObject(pairing) ? pairing.mode : pairing;
if (mode === undefined) return DEFAULT_PAIRING_MODE;
if (isPairingMode(mode)) return mode;
log(`pairing mode ${JSON.stringify(mode)} is not auto, ask or code; pairing by code only`);
@@ -64,10 +65,11 @@ export function pairingMode(config: AgentConfig = readAgentConfig()): PairingMod
/** Sets how browsers pair, leaving every other key in config.json untouched. */
export function writePairingMode(mode: PairingMode): void {
const stored = readStored();
- const pairing = { ...((stored.pairing as Record<string, unknown> | undefined) ?? {}), mode };
- write({ ...stored, pairing });
+ write({ ...stored, pairing: { ...(pairingObject(stored.pairing) ? stored.pairing : {}), mode } });
}
+const pairingObject = (value: unknown): value is { mode?: unknown } => typeof value === 'object' && value !== null && !Array.isArray(value);
+
export interface AndroidSettings {
enabled: boolean;
adb?: string;
diff --git a/src/daemon/cli.ts b/src/daemon/cli.ts
index f6a3a23..20bcd09 100644
--- a/src/daemon/cli.ts
+++ b/src/daemon/cli.ts
@@ -132,7 +132,8 @@ const servesBare = !!process.env.BROWSENTIC_AGENT_RUN;
const [command] = process.argv.slice(2);
const wantsJson = process.argv.includes('--json');
-const positional = process.argv.slice(3).filter((arg) => !arg.startsWith('--'));
+const VALUE_FLAGS = new Set(['--name']);
+const positional = process.argv.slice(3).filter((arg, at, args) => !arg.startsWith('--') && !VALUE_FLAGS.has(args[at - 1]));
switch (command) {
case undefined:
@@ -987,7 +988,7 @@ async function revoke(browser?: string): Promise<void> {
await bridge.close();
if (!revoked) return console.log(browser ? `No session for ${browser}.` : 'Nothing to revoke.');
console.log(`Revoked ${revoked} session(s). They will not pair again by themselves.`);
- console.log('Reconnect one from its extension, with "browsentic approve <id>", or with a code from "browsentic pair".');
+ console.log('Reconnect one from its extension, or pair it with a code from "browsentic pair".');
}
async function setPairing(mode?: string): Promise<void> {
@@ -1047,7 +1048,12 @@ async function approve(id?: string): Promise<void> {
console.error(error ?? `Nothing is waiting under ${chosen}.`);
process.exit(1);
}
- console.log('Allowed. It connects within a few seconds; "browsentic status" shows it.');
+ const waiting = requests.some((request) => request.id === chosen || request.installId === chosen);
+ console.log(
+ waiting
+ ? 'Allowed. It connects within a few seconds; "browsentic status" shows it.'
+ : 'Allowed. It connects once you press Reconnect in its Browsentic side panel.',
+ );
} finally {
await bridge.close();
}
@@ -1094,7 +1100,7 @@ async function showBlocked(): Promise<void> {
for (const browser of blocked) {
console.log(` ${browser.browser ?? browser.origin} ${browser.installId} ${browser.reason} ${browser.at}`);
}
- console.log('Let one back in with "browsentic approve <id>".');
+ console.log('Let one back in with "browsentic approve <id>", then press Reconnect in its Browsentic side panel.');
}
function valueAfter(flag: string): string | undefined {
diff --git a/src/daemon/daemon.ts b/src/daemon/daemon.ts
index 1a8bace..872f453 100644
--- a/src/daemon/daemon.ts
+++ b/src/daemon/daemon.ts
@@ -398,9 +398,8 @@ export async function startDaemon({ version, idleExit = true, android = androidO
consumePairing(matched.code);
// Typing a code is consent enough, so ask mode lets this browser back in by itself from now on.
approveInstall({ installId: install.installId, origin: install.origin, browser: install.browser });
- } else {
- desk.consume(install.installId);
}
+ desk.consume(install.installId);
secret = matched.secret;
const session = createSession(install, matched.pairedBy);
sealedSessionKey = await sealSessionKey(secret, transcript, session.key);
diff --git a/src/daemon/ensure-daemon.ts b/src/daemon/ensure-daemon.ts
index 95d6e99..2359f36 100644
--- a/src/daemon/ensure-daemon.ts
+++ b/src/daemon/ensure-daemon.ts
@@ -11,7 +11,6 @@ const SPAWN_TIMEOUT_MS = 8_000;
const POLL_INTERVAL_MS = 150;
const START_LOCK = join(stateDir, 'daemon.start.lock');
const STALE_START_MS = SPAWN_TIMEOUT_MS * 2;
-const TASK_GRACE_MS = 4_000;
export const daemonMainPath = () => join(dirname(fileURLToPath(import.meta.url)), 'daemon-main.js');
@@ -67,15 +66,13 @@ function readStartLock(): [number, number] {
}
}
+/** One the task started is waited for, never doubled by one spawned in the job that is about to die. */
async function spawnDaemon({ outsideJob = false }: EnsureOptions): Promise<Lockfile> {
if (outsideJob && process.platform === 'win32' && runBridgeTask()) {
log('no daemon reachable; starting one through Task Scheduler');
- const started = await waitForDaemon(TASK_GRACE_MS);
- if (started) return started;
- log('the Task Scheduler start never came up; spawning one directly');
- } else {
- log('no daemon reachable; spawning one');
+ return cameUp();
}
+ log('no daemon reachable; spawning one');
const env: NodeJS.ProcessEnv = { ...process.env };
delete env.BROWSENTIC_AGENT_RUN;
delete env.CLAUDECODE;
@@ -88,6 +85,10 @@ async function spawnDaemon({ outsideJob = false }: EnsureOptions): Promise<Lockf
windowsHide: true,
});
child.unref();
+ return cameUp();
+}
+
+async function cameUp(): Promise<Lockfile> {
const started = await waitForDaemon(SPAWN_TIMEOUT_MS);
if (started) return started;
throw new Error(`The Browsentic daemon did not come up within ${SPAWN_TIMEOUT_MS}ms — see the log with "browsentic logs"`);
diff --git a/src/daemon/native-host.test.ts b/src/daemon/native-host.test.ts
index e996747..57c3b24 100644
--- a/src/daemon/native-host.test.ts
+++ b/src/daemon/native-host.test.ts
@@ -78,7 +78,7 @@ describe('hostTargets', () => {
it('finds Firefox on macOS by its own profile folder, and writes to Mozilla’s', () => {
expect(mac('Firefox')).toMatchObject({
family: 'firefox',
- installs: expect.arrayContaining([`${support}/Firefox`, '/Applications/Firefox.app']),
+ installs: expect.arrayContaining([`${support}/Firefox/profiles.ini`, '/Applications/Firefox.app']),
manifestDirs: [`${support}/Mozilla/NativeMessagingHosts`],
baseline: true,
});
@@ -299,12 +299,20 @@ describe('registering the host on macOS', () => {
});
it('registers Firefox on a Mac that never made a Mozilla folder', () => {
- const machine = mac([posix.join(support, 'Firefox')]);
+ const machine = mac([posix.join(support, 'Firefox', 'profiles.ini')]);
expect(installNativeHost('/opt/browsentic/dist/cli.js', machine).browsers).toEqual(['Firefox']);
expect(existsSync(manifestIn('Mozilla'))).toBe(true);
});
+ it('does not take the Chrome folder its own baseline made for Chrome being installed', () => {
+ const onDisk = (path: string) => path.startsWith(support) && existsSync(path);
+ const machine = { ...mac(['/Applications/Brave Browser.app']), exists: (path: string) => path === '/Applications/Brave Browser.app' || onDisk(path) };
+
+ expect(installNativeHost('/opt/browsentic/dist/cli.js', machine).browsers).toEqual(['Brave']);
+ expect([existsSync(posix.join(support, 'Google/Chrome')), registeredBrowsers(machine)]).toEqual([true, ['Brave']]);
+ });
+
it('registers a fork in the data folder its Info.plist names', () => {
const machine = mac(['/Applications/Helium.app'], [{ browser: 'Helium', app: '/Applications/Helium.app', dataDir: 'net.imput.helium' }]);
@@ -377,6 +385,7 @@ describe('registering the host on Windows', () => {
register: (file) => void scheduled.push(`register ${readFileSync(file).subarray(2).toString('utf16le').includes('daemon-main.js')}`),
run: () => void scheduled.push('run'),
remove: () => void scheduled.push('remove'),
+ exists: () => scheduled.lastIndexOf('register true') > scheduled.lastIndexOf('remove'),
};
const windows = (installed: string[]) =>
({ platform: 'win32', home, env: {}, registry, tasks, state: 'C:\\Users\\me\\.browsentic', exists: (path: string) => installed.includes(path) }) as const;
@@ -420,6 +429,16 @@ describe('registering the host on Windows', () => {
expect(scheduled).toContain('remove');
});
+ it('registers the task again when it has gone missing, and leaves one that is there alone', () => {
+ installNativeHost('C:\\b\\dist\\cli.js', windows([]));
+ refreshNativeHost(windows([]));
+ expect(scheduled).toEqual(['register true']);
+
+ scheduled.push('remove');
+ refreshNativeHost(windows([]));
+ expect(scheduled).toEqual(['register true', 'remove', 'register true']);
+ });
+
it('removes every key on uninstall, the one written for Brave before it was known to read Chrome’s too', () => {
installNativeHost('C:\\b\\dist\\cli.js', windows([profile('Google\\Chrome')]));
keys.set(key('BraveSoftware\\Brave-Browser'), 'old');
diff --git a/src/daemon/native-host.ts b/src/daemon/native-host.ts
index 86bc5e7..90f5309 100644
--- a/src/daemon/native-host.ts
+++ b/src/daemon/native-host.ts
@@ -21,7 +21,7 @@ import { readAgentConfig } from './agent/config';
import { stateDir } from './lockfile';
import { log } from './log';
import { extensionDir } from './paths';
-import { registerBridgeTask, removeBridgeTask, windowsTasks, type TaskScheduler } from './windows-task';
+import { BRIDGE_TASK, registerBridgeTask, removeBridgeTask, windowsTasks, type TaskScheduler } from './windows-task';
export { NATIVE_HOST_NAME };
@@ -54,6 +54,9 @@ interface MacBrowser {
const CHROME = 'Google/Chrome';
const MOZILLA = 'Mozilla';
+/** A file the browser itself writes into its profile folder, which a baseline manifest written there does not make. */
+const PROFILE_MARK: Record<Family, string> = { chromium: 'Local State', firefox: 'profiles.ini' };
+
const MAC_BROWSERS: MacBrowser[] = [
{ browser: 'Chrome', profile: CHROME, apps: ['Google Chrome.app'], reads: [CHROME], baseline: true },
{ browser: 'Chrome Beta', profile: 'Google/Chrome Beta', apps: ['Google Chrome Beta.app'], reads: ['Google/Chrome Beta'] },
@@ -170,7 +173,7 @@ export function hostTargets(
const known = MAC_BROWSERS.map(({ browser, family = 'chromium', profile, apps, reads, baseline }) => ({
browser,
family,
- installs: [posix.join(support, profile), ...apps.flatMap((app) => macApps(home).map((root) => posix.join(root, app)))],
+ installs: [posix.join(support, profile, PROFILE_MARK[family]), ...apps.flatMap((app) => macApps(home).map((root) => posix.join(root, app)))],
manifestDirs: reads.map(hostsIn),
baseline,
}));
@@ -505,10 +508,9 @@ export function refreshNativeHost(options: Refresh = {}): void {
} catch (error) {
log(`native host: could not rewrite the launcher: ${String(error)}`);
}
- if (healed && (healed.cliPath !== pinned.cliPath || healed.nodePath !== pinned.nodePath)) {
- log(`native host: repinned the launcher to ${healed.nodePath} ${healed.cliPath}`);
- if (platform === 'win32') registerBridgeTask(healed.nodePath, daemonMainBeside(healed.cliPath), tasks);
- }
+ const repinned = !!healed && (healed.cliPath !== pinned.cliPath || healed.nodePath !== pinned.nodePath);
+ if (repinned) log(`native host: repinned the launcher to ${healed.nodePath} ${healed.cliPath}`);
+ if (platform === 'win32' && healed && (repinned || !tasks.exists())) registerBridgeTask(healed.nodePath, daemonMainBeside(healed.cliPath), tasks);
register(launcher, options);
}
@@ -516,7 +518,7 @@ export function removeNativeHost(options: HostOptions = {}): string[] {
if (!registersHosts(options)) return [];
const { platform, targets, registry } = machine(options);
const removed: string[] = [];
- if (platform === 'win32' && removeBridgeTask(options.tasks)) removed.push('the Browsentic\\Bridge task');
+ if (platform === 'win32' && removeBridgeTask(options.tasks)) removed.push(`the ${BRIDGE_TASK} task`);
if (platform === 'win32') {
const keys = new Set([...targets.map((target) => target.registryKey!), ...RETIRED_WINDOWS_VENDORS.map(windowsKey)]);
for (const key of keys) {
diff --git a/src/daemon/pairing-desk.test.ts b/src/daemon/pairing-desk.test.ts
index b0a0466..2108c1d 100644
--- a/src/daemon/pairing-desk.test.ts
+++ b/src/daemon/pairing-desk.test.ts
@@ -112,6 +112,16 @@ describe('ask mode', () => {
await expect(settled).resolves.toBeUndefined();
});
+ it('answers a request once its browser pairs some other way, as with a typed code', async () => {
+ const { desk: built, changed } = desk('ask');
+ built.ask(chrome);
+ const settled = built.settled(chrome.installId, 60_000);
+ built.consume(chrome.installId);
+ await expect(settled).resolves.toBeUndefined();
+ expect(built.pending()).toEqual([]);
+ expect(changed).toHaveBeenCalledTimes(2);
+ });
+
it('decides a blocked browser by its install id even with no request', () => {
const { desk: built } = desk('ask');
blockInstall({ installId: chrome.installId, origin: chrome.caller }, 'revoked');
diff --git a/src/daemon/pairing-desk.ts b/src/daemon/pairing-desk.ts
index aca0755..cf36bff 100644
--- a/src/daemon/pairing-desk.ts
+++ b/src/daemon/pairing-desk.ts
@@ -60,6 +60,7 @@ export interface PairingDesk {
pending(): PairRequestSummary[];
/** The live grant that browser may redeem from that socket origin. */
grantFor(installId: string, origin: string): HeldGrant | undefined;
+ /** That browser paired, by its grant or a typed code: the grant is spent and its request answered. */
consume(installId: string): void;
}
@@ -206,6 +207,11 @@ export function pairingDesk(options: DeskOptions): PairingDesk {
log(`a grant for ${installId.slice(0, 8)} was offered from ${origin}, not the origin it was given to; refused`);
return undefined;
},
- consume: (installId) => void grants.delete(installId),
+ consume: (installId) => {
+ grants.delete(installId);
+ if (!requests.delete(installId)) return;
+ wake(installId);
+ options.changed();
+ },
};
}
diff --git a/src/daemon/scripts/cli-smoke.ts b/src/daemon/scripts/cli-smoke.ts
index 4efeab7..3d6501b 100644
--- a/src/daemon/scripts/cli-smoke.ts
+++ b/src/daemon/scripts/cli-smoke.ts
@@ -26,6 +26,7 @@ const PORTS = [47811, 47812];
const CHROME_WEB_STORE = 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp/';
const COMMANDS = 'setup update uninstall browsers pair pairing requests approve deny status sessions rename revoke agent skills approvals tasks downloads tools logs start stop restart token mcp'.split(' ');
const version = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version as string;
+const TASK = `Browsentic Bridge for ${process.env.USERNAME || 'this user'}`;
const scratch = mkdtempSync(join(tmpdir(), 'browsentic-smoke-'));
const home = join(scratch, 'hömé José');
@@ -283,7 +284,7 @@ try {
must(!asked.ok && asked.wait?.request, JSON.stringify(asked));
const listed = json<{ requests: { id: string }[] }>(browsentic('requests', '--json'));
must(listed.requests.some((request) => request.id === asked.wait!.request), JSON.stringify(listed));
- says(browsentic('approve', asked.wait!.request), 'Allowed.');
+ says(browsentic('approve', '--name', 'Smoke Chrome'), 'Allowed. It connects within a few seconds');
must((await askHost<{ ok: boolean }>(PAIR)).ok, 'still not granted after approve');
says(browsentic('pairing', 'code'), 'Pairing: code only');
must(JSON.stringify(await askHost(PAIR)).includes('"refused":"off"'), 'code mode still paired');
@@ -291,7 +292,7 @@ try {
});
if (windows) {
await check('setup registered the task that starts the Bridge for Firefox', () =>
- must(spawnSync('schtasks', ['/Query', '/TN', 'Browsentic\\Bridge'], { windowsHide: true }).status === 0, 'no Browsentic\\Bridge task'),
+ must(spawnSync('schtasks', ['/Query', '/TN', TASK], { windowsHide: true }).status === 0, `no "${TASK}" task`),
);
}
await check('stop', async () => {
@@ -319,7 +320,7 @@ try {
must((await answering()).length === 0, 'the Bridge still answers');
says(browsentic('status'), 'not registered');
if (windows) must(spawnSync('reg', ['query', `HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts\\${HOST}`]).status !== 0, 'the key is left');
- if (windows) must(spawnSync('schtasks', ['/Query', '/TN', 'Browsentic\\Bridge'], { windowsHide: true }).status !== 0, 'the task is left');
+ if (windows) must(spawnSync('schtasks', ['/Query', '/TN', TASK], { windowsHide: true }).status !== 0, 'the task is left');
});
} finally {
if (await answering().then((ports) => ports.length)) browsentic('stop');
diff --git a/src/daemon/windows-task.ts b/src/daemon/windows-task.ts
index f8d6b7a..b77e51c 100644
--- a/src/daemon/windows-task.ts
+++ b/src/daemon/windows-task.ts
@@ -11,12 +11,17 @@ import { join } from 'node:path';
import { stateDir } from './lockfile';
import { log } from './log';
-export const BRIDGE_TASK = 'Browsentic\\Bridge';
+/**
+ * In the root folder, named for the user: without elevation Windows lets a user create tasks there but
+ * not a folder of their own, and every user of the computer needs a task of their own.
+ */
+export const BRIDGE_TASK = `Browsentic Bridge for ${process.env.USERNAME || 'this user'}`;
export interface TaskScheduler {
register(xmlFile: string): void;
run(): void;
remove(): void;
+ exists(): boolean;
}
const schtasks = (args: string[]) => execFileSync('schtasks', args, { stdio: 'ignore', windowsHide: true });
@@ -25,6 +30,14 @@ export const windowsTasks: TaskScheduler = {
register: (xmlFile) => schtasks(['/Create', '/TN', BRIDGE_TASK, '/XML', xmlFile, '/F']),
run: () => schtasks(['/Run', '/TN', BRIDGE_TASK]),
remove: () => schtasks(['/Delete', '/TN', BRIDGE_TASK, '/F']),
+ exists: () => {
+ try {
+ schtasks(['/Query', '/TN', BRIDGE_TASK]);
+ return true;
+ } catch {
+ return false;
+ }
+ },
};
const escapeXml = (value: string) =>
@@ -44,6 +57,7 @@ export function bridgeTaskXml(nodePath: string, daemonMain: string): string {
' <AllowStartOnDemand>true</AllowStartOnDemand>',
' <Hidden>true</Hidden>',
' <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>',
+ ' <Priority>5</Priority>',
' </Settings>',
' <Actions Context="Author">',
' <Exec>',