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
test(daemon): pin how the extension is installed over itself, what an uninstall removes or keeps, and which npx caches it finds
Shahriare702df18dea7
diff --git a/src/daemon/install.test.ts b/src/daemon/install.test.tsnew file mode 100644index 0000000..8e1a3c4--- /dev/null+++ b/src/daemon/install.test.ts@@ -0,0 +1,122 @@+import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { install, InstallError, readStamp } from './install';+import { stateDir } from './lockfile';+import { extensionDir, installStampPath } from './paths';++// Only a built package or a source checkout carries the extension; the test builds a small one of its own.+const packaged = vi.hoisted(() => ({ current: null as { dir: string; source: 'package' | 'repo' } | null }));+vi.mock('./paths', async (importOriginal) => ({ ...(await importOriginal<typeof import('./paths')>()), packagedExtension: () => packaged.current }));++const build = join(stateDir, 'package', 'extension', 'chrome-mv3');+const target = extensionDir();++const put = (dir: string, files: Record<string, string>) => {+ for (const [path, content] of Object.entries(files)) {+ mkdirSync(dirname(join(dir, path)), { recursive: true });+ writeFileSync(join(dir, path), content);+ }+};++const release = (version: string, files: Record<string, string> = {}) => {+ rmSync(build, { recursive: true, force: true });+ put(build, { 'manifest.json': JSON.stringify({ version }), 'background.js': 'bg v1', 'content.js': 'cs', 'icons/icon-16.png': 'png', ...files });+};++const installed = () =>+ readdirSync(target, { recursive: true, withFileTypes: true })+ .filter((entry) => entry.isFile())+ .map((entry) => join(entry.parentPath, entry.name).slice(target.length + 1))+ .sort();++beforeEach(() => {+ packaged.current = { dir: build, source: 'package' };+ rmSync(target, { recursive: true, force: true });+ release('1.2.0');+});++afterEach(() => {+ if (existsSync(target)) chmodSync(target, 0o755);+});++describe('installing the extension', () => {+ test('a first install copies every file, and records what it installed', () => {+ expect(install(target)).toEqual({ dir: target, version: '1.2.0', source: 'package', files: 4, changed: 4, alreadyCurrent: false });+ expect([installed(), readStamp(target)]).toEqual([+ ['.browsentic-install.json', 'background.js', 'content.js', 'icons/icon-16.png', 'manifest.json'],+ { version: '1.2.0', installedAt: expect.any(String), source: 'package', files: 4 },+ ]);+ });++ test('the files are readable by the browser', () => {+ install(target);+ expect(statSync(join(target, 'background.js')).mode & 0o777).toBe(0o644);+ });++ test('the same version again copies nothing', () => {+ install(target);+ expect(install(target)).toMatchObject({ changed: 0, alreadyCurrent: true, files: 4 });+ });++ test('forcing it copies everything again', () => {+ install(target);+ expect(install(target, true)).toMatchObject({ changed: 4, alreadyCurrent: false });+ });++ test('a new version replaces only what changed, and removes what the new build dropped', () => {+ install(target);+ release('1.3.0', { 'background.js': 'bg v2', 'popup.html': '<html>' });+ rmSync(join(build, 'icons'), { recursive: true });+ expect([install(target), installed(), readFileSync(join(target, 'background.js'), 'utf8')]).toEqual([+ { dir: target, version: '1.3.0', source: 'package', files: 4, changed: 3, alreadyCurrent: false },+ ['.browsentic-install.json', 'background.js', 'content.js', 'manifest.json', 'popup.html'],+ 'bg v2',+ ]);+ });++ test('a copy left half-written by a run that died is cleared away', () => {+ put(target, { 'background.js.tmp-4242': 'partial' });+ install(target);+ expect(installed()).not.toContain('background.js.tmp-4242');+ });++ test('a file the browser will not let go of is explained, with what to do', () => {+ install(target);+ release('1.3.0', { 'background.js': 'bg v2' });+ chmodSync(target, 0o555);+ const error = (() => {+ try {+ install(target);+ } catch (thrown) {+ return thrown;+ }+ })();+ expect([error instanceof InstallError, (error as InstallError).message, (error as InstallError).hint]).toEqual([+ true,+ 'the browser is holding background.js open',+ 'Disable the Browsentic card at chrome://extensions (or quit the browser), then run `browsentic update` again.',+ ]);+ });++ test('a build with no extension in it says how to get one', () => {+ packaged.current = null;+ expect(() => install(target)).toThrow(+ expect.objectContaining({+ message: 'this build carries no extension payload',+ hint: 'Reinstall with `npm i -g browsentic`, or run `yarn build` if you are in a source checkout.',+ }),+ );+ });+});++describe('the install stamp', () => {+ test('is absent before anything was installed', () => {+ expect(readStamp(target)).toBeNull();+ });++ test('that cannot be read counts as absent', () => {+ put(target, { '.browsentic-install.json': '{"version": ' });+ expect([readStamp(target), existsSync(installStampPath(target))]).toEqual([null, true]);+ });+});diff --git a/src/daemon/npx.test.ts b/src/daemon/npx.test.tsnew file mode 100644index 0000000..f172bf1--- /dev/null+++ b/src/daemon/npx.test.ts@@ -0,0 +1,61 @@+import { mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { stateDir } from './lockfile';+import { npxEntries } from './npx';++const npmCache = join(homedir(), '.npm', '_npx');+const configuredCache = join(stateDir, 'npm-cache');++/** An npx cache entry as npm leaves it: what was asked for, and the package it resolved. */+const npxEntry =(root: string, key: string, version: string | null, packages = ['browsentic@latest']) => {+ const dir = join(root, key);+ mkdirSync(join(dir, 'node_modules', 'browsentic'), { recursive: true });+ writeFileSync(join(dir, 'package.json'), JSON.stringify({ _npx: { packages } }));+ if (version) writeFileSync(join(dir, 'node_modules', 'browsentic', 'package.json'), JSON.stringify({ name: 'browsentic', version }));+ return dir;+};++beforeEach(() => {+ vi.stubEnv('npm_config_cache', configuredCache);+ rmSync(join(homedir(), '.npm'), { recursive: true, force: true });+ rmSync(configuredCache, { recursive: true, force: true });+});++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('npx caches holding browsentic', () => {+ test('are found in the configured npm cache and in ~/.npm, with the version each holds and what was asked for', () => {+ const configured = npxEntry(join(configuredCache, '_npx'), 'a1', '0.6.1', ['[email protected]']);+ const home = npxEntry(npmCache, 'b2', '0.5.0');+ expect(npxEntries()).toEqual([+ { dir: configured, version: '0.6.1', packages: ['[email protected]'], running: false },+ { dir: home, version: '0.5.0', packages: ['browsentic@latest'], running: false },+ ]);+ });++ test('an entry holding some other package is not ours', () => {+ mkdirSync(join(npmCache, 'c3', 'node_modules', 'cowsay'), { recursive: true });+ expect(npxEntries()).toEqual([]);+ });++ test('an entry whose version cannot be read is still listed, so it can still be cleared', () => {+ const dir = npxEntry(npmCache, 'd4', null);+ writeFileSync(join(dir, 'node_modules', 'browsentic', 'package.json'), '{"name": "browsentic"}');+ expect(npxEntries()).toEqual([{ dir, version: null, packages: ['browsentic@latest'], running: false }]);+ });++ test('the same entry reached twice is listed once', () => {+ const dir = npxEntry(npmCache, 'e5', '0.6.2');+ mkdirSync(join(configuredCache, '_npx'), { recursive: true });+ symlinkSync(dir, join(configuredCache, '_npx', 'e5'));+ expect(npxEntries().map((entry) => entry.dir)).toEqual([dir]);+ });++ test('with no npx cache there is nothing to find', () => {+ expect(npxEntries()).toEqual([]);+ });+});diff --git a/src/daemon/uninstall.test.ts b/src/daemon/uninstall.test.tsnew file mode 100644index 0000000..285b830--- /dev/null+++ b/src/daemon/uninstall.test.ts@@ -0,0 +1,135 @@+import { chmodSync, existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { configPath } from './agent/config';+import { stateDir } from './lockfile';+import { userDir } from './paths';+import { planUninstall, purgeNpxCache, removeAll } from './uninstall';++const npxEntry = (root: string, key: string, version: string) => {+ const dir = join(root, key);+ mkdirSync(join(dir, 'node_modules', 'browsentic'), { recursive: true });+ writeFileSync(join(dir, 'package.json'), JSON.stringify({ _npx: { packages: ['browsentic@latest'] } }));+ writeFileSync(join(dir, 'node_modules', 'browsentic', 'package.json'), JSON.stringify({ name: 'browsentic', version }));+ return dir;+};++const configure = (value: Record<string, unknown>) => writeFileSync(configPath, JSON.stringify(value));+const made = (...paths: string[]) => {+ for (const path of paths) mkdirSync(path, { recursive: true });+};+const outside = join(homedir(), 'Elsewhere');++beforeEach(() => {+ vi.stubEnv('npm_config_cache', join(stateDir, 'npm-cache'));+ for (const dir of [stateDir, userDir, outside, join(homedir(), '.npm')]) rmSync(dir, { recursive: true, force: true });+ made(stateDir, join(userDir, 'skills'), join(userDir, 'extension', 'chrome-mv3'));+});++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('planning an uninstall', () => {+ test('by default it is the private state and the visible files, the extension among them', () => {+ expect(planUninstall()).toEqual({+ removals: [+ { label: 'state', path: stateDir, holds: 'pairing keys, config, approvals, logs', keep: undefined },+ { label: 'files', path: userDir, holds: 'the extension, skills, site maps, screenshots, captured downloads', keep: undefined },+ ],+ elsewhere: [],+ npx: [],+ });+ });++ test('an extension installed somewhere else with setup --dir is removed too', () => {+ made(join(outside, 'browsentic-ext'));+ configure({ extensionDir: join(outside, 'browsentic-ext') });+ expect(planUninstall().removals[0]).toEqual({ label: 'extension', path: join(outside, 'browsentic-ext'), holds: 'the unpacked build Chrome loads' });+ });++ test('keeping skills keeps them in both places', () => {+ expect(planUninstall({ keepSkills: true }).removals.map((removal) => removal.keep)).toEqual([['skills'], ['skills']]);+ });++ test('folders the user configured outside both roots are named, never deleted', () => {+ made(join(outside, 'skills'), join(outside, 'shots'));+ configure({ skillsDir: join(outside, 'skills'), screenshotDir: join(outside, 'shots'), downloadDir: join(userDir, 'downloads') });+ expect(planUninstall().elsewhere).toEqual([+ { label: 'skills', path: join(outside, 'skills'), holds: 'site maps and uploaded skills' },+ { label: 'screenshots', path: join(outside, 'shots'), holds: 'captures taken with save: true' },+ ]);+ });++ test('a configured folder that does not exist is not mentioned', () => {+ configure({ screenshotDir: join(outside, 'never-made') });+ expect(planUninstall().elsewhere).toEqual([]);+ });++ test('npx caches holding a copy are included', () => {+ const dir = npxEntry(join(homedir(), '.npm', '_npx'), 'f6', '0.6.0');+ expect(planUninstall().npx).toEqual([{ dir, version: '0.6.0', packages: ['browsentic@latest'], running: false }]);+ });++ test('with nothing installed there is nothing to remove', () => {+ rmSync(stateDir, { recursive: true, force: true });+ rmSync(userDir, { recursive: true, force: true });+ expect(planUninstall().removals).toEqual([]);+ });+});++describe('removing', () => {+ test('everything planned goes', () => {+ const outcomes = removeAll(planUninstall().removals);+ expect([outcomes.map((outcome) => [outcome.removal.label, outcome.removed, outcome.kept]), existsSync(stateDir), existsSync(userDir)]).toEqual([+ [+ ['state', true, []],+ ['files', true, []],+ ],+ false,+ false,+ ]);+ });++ test('keeping skills empties each folder around them and says what was left', () => {+ writeFileSync(join(userDir, 'skills', 'mine.md'), 'Mine.');+ const [, files] = removeAll(planUninstall({ keepSkills: true }).removals);+ expect([files.kept, readdirSync(userDir), existsSync(join(userDir, 'skills', 'mine.md'))]).toEqual([['skills'], ['skills'], true]);+ });++ test('a folder with nothing to keep is removed outright', () => {+ removeAll(planUninstall({ keepSkills: true }).removals);+ expect(existsSync(stateDir)).toBe(false);+ });++ test('a removal that fails is reported, not thrown, and the rest still happen', () => {+ made(outside);+ writeFileSync(join(outside, 'not-a-folder'), '');+ const [failed, removed] = removeAll([+ { label: 'odd', path: join(outside, 'not-a-folder'), holds: '', keep: ['skills'] },+ { label: 'state', path: stateDir, holds: '' },+ ]);+ expect([failed.removed, failed.error, removed.removed]).toEqual([false, expect.stringContaining('ENOTDIR'), true]);+ });+});++describe('purging npx caches', () => {+ test('each cache is deleted, and each outcome reported', () => {+ const dir = npxEntry(join(homedir(), '.npm', '_npx'), 'g7', '0.6.0');+ const [purged] = purgeNpxCache(planUninstall().npx);+ expect([purged.removed, existsSync(dir)]).toEqual([true, false]);+ });++ test('a cache that cannot be deleted is reported rather than stopping the uninstall', () => {+ const root = join(homedir(), '.npm', '_npx');+ const dir = npxEntry(root, 'h8', '0.6.0');+ chmodSync(root, 0o555);+ try {+ const [purged] = purgeNpxCache(planUninstall().npx);+ expect([purged.removed, typeof purged.error, existsSync(dir)]).toEqual([false, 'string', true]);+ } finally {+ chmodSync(root, 0o755);+ }+ });+});