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): stand in for a CLI with a Node script that Windows starts through an npm-shaped .cmd, assert file modes only where they exist, and run the daemon's tests on Windows in CI
Shahriar7b8380b818c6
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 4d07d00..2aaf4dc 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -46,6 +46,42 @@ jobs:node "$YARN" buildnode "$YARN" daemon:build+ # The daemon on Windows, where an npm-installed agent is a .cmd shim, a path has backslashes, a+ # kill takes nothing with it and a file has no POSIX mode. The extension's tests do not reach+ # the platform, so only the daemon project runs here.+ windows:+ runs-on: windows-latest+ defaults:+ run:+ shell: bash+ steps:+ # Recorded CLI output is read line by line, and a checkout that turned LF into CRLF would+ # hand every parser a stray carriage return.+ - name: Keep line endings as committed+ run: git config --global core.autocrlf false++ - uses: actions/checkout@v5++ - uses: actions/setup-node@v5+ with:+ node-version: 24++ - name: Install dependencies+ run: |+ yarn_bin=$(sed -n 's/^yarnPath: *//p' .yarnrc.yml)+ test -f "$yarn_bin" || { echo "::error::no vendored Yarn at '$yarn_bin'"; exit 1; }+ echo "YARN=$yarn_bin" >> "$GITHUB_ENV"+ node "$yarn_bin" install --immutable+ node "$yarn_bin" --cwd src/daemon install --immutable++ - name: Type-check and bundle the daemon+ run: |+ node "$YARN" daemon:compile+ node "$YARN" daemon:build++ - name: Test the daemon+ run: node "$YARN" vitest run --project daemon+mac:runs-on: macos-15steps:diff --git a/src/daemon/agent/approvals.test.ts b/src/daemon/agent/approvals.test.tsindex 5c12c54..e26367b 100644--- a/src/daemon/agent/approvals.test.ts+++ b/src/daemon/agent/approvals.test.ts@@ -1,8 +1,9 @@-import { mkdirSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { mkdirSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { beforeEach, describe, expect, test } from 'vitest';import { stateDir } from '../lockfile';import { forgetGrants, isGranted, listGrants, rememberGrant } from './approvals';+import { bits, modeOf } from '../test/modes';const approvalsPath = join(stateDir, 'approvals.json');const at = '2026-09-21T10:00:00.000Z';@@ -43,7 +44,7 @@ describe('standing approvals', () => {test('the file is readable only by the user', () => {rememberGrant('page.submitForm', 'example.com', at);- expect(statSync(approvalsPath).mode & 0o777).toBe(0o600);+ expect(modeOf(approvalsPath)).toBe(bits(0o600));});});diff --git a/src/daemon/agent/config.test.ts b/src/daemon/agent/config.test.tsindex 3d6ab89..ce12551 100644--- a/src/daemon/agent/config.test.ts+++ b/src/daemon/agent/config.test.ts@@ -1,4 +1,4 @@-import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { dirname } from 'node:path';import { beforeEach, describe, expect, test } from 'vitest';import {@@ -13,6 +13,7 @@ import {writeGuardrailSetting,type AgentConfig,} from './config';+import { bits, modeOf } from '../test/modes';const store = (value: unknown) => {mkdirSync(dirname(configPath), { recursive: true });@@ -117,7 +118,7 @@ describe('writing config.json', () => {test('the file is written readable only by the user', () => {writeActiveAgent('codex');- expect(statSync(configPath).mode & 0o777).toBe(0o600);+ expect(modeOf(configPath)).toBe(bits(0o600));});test("setting a model writes only that agent's model", () => {diff --git a/src/daemon/agent/file-analyst.test.ts b/src/daemon/agent/file-analyst.test.tsindex 7901f97..2188fcf 100644--- a/src/daemon/agent/file-analyst.test.ts+++ b/src/daemon/agent/file-analyst.test.ts@@ -1,10 +1,11 @@-import { readdirSync, readFileSync, rmSync, statSync } from 'node:fs';+import { readdirSync, readFileSync, rmSync } from 'node:fs';import { basename, dirname } from 'node:path';import { beforeEach, describe, expect, test, vi } from 'vitest';import type { SocketFrame } from '@/lib/actions/protocol';import { readAgentConfig } from './config';import { FileAnalyses, analyzeFile, promptFor } from './file-analyst';import { RunError, runAgentJson, taskDir } from './runner';+import { bits, modeOf } from '../test/modes';vi.mock('./runner', async (importOriginal) => ({ ...(await importOriginal<typeof import('./runner')>()), runAgentJson: vi.fn() }));@@ -36,7 +37,7 @@ const REPORT = `=== REPORT ===\n${JSON.stringify({})}`;/** The path the agent was told to read, and what was in it at that moment. */-let handed: { path: string; content: string; mode: number } | null;+let handed: { path: string; content: string; mode: number | null } | null;beforeEach(() => {rmSync(taskDir(config), { recursive: true, force: true });@@ -44,7 +45,7 @@ beforeEach(() => {agent.mockReset();agent.mockImplementation(async (prompt) => {const path = /The file is at (\S+)\. /.exec(prompt)?.[1] ?? '';- handed = { path, content: readFileSync(path, 'utf8'), mode: statSync(path).mode & 0o777 };+ handed = { path, content: readFileSync(path, 'utf8'), mode: modeOf(path) };return REPORT;});});@@ -63,7 +64,7 @@ describe('reading an attached file', () => {test("the file is put in the agent's own workspace for it to read, readable only by the user, and the agent may read", async () => {await analyze(csv);- expect([dirname(handed?.path ?? ''), handed?.content, handed?.mode, agent.mock.calls[0][3].reads]).toEqual([taskDir(config), csv, 0o600, true]);+ expect([dirname(handed?.path ?? ''), handed?.content, handed?.mode, agent.mock.calls[0][3].reads]).toEqual([taskDir(config), csv, bits(0o600), true]);});test('the copy is deleted afterwards, whether or not the analyst managed', async () => {diff --git a/src/daemon/agent/runners/cursor.test.ts b/src/daemon/agent/runners/cursor.test.tsindex b68fb23..29521ed 100644--- a/src/daemon/agent/runners/cursor.test.ts+++ b/src/daemon/agent/runners/cursor.test.ts@@ -1,10 +1,10 @@-import { chmodSync, existsSync, mkdirSync, rmSync, utimesSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, rmSync, utimesSync, writeFileSync } from 'node:fs';import { homedir } from 'node:os';import { dirname, join } from 'node:path';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import { stateDir } from '../../lockfile';import { cursorRunner } from './cursor';-import { jsonContext, readThrough, shown, streamContext, transcript, valueOf } from './fixtures/support';+import { jsonContext, readThrough, shown, streamContext, stubCli, transcript, valueOf } from './fixtures/support';const settings = { bin: 'cursor-agent' };const stream = (overrides: Parameters<typeof streamContext>[1] = {}) => cursorRunner.stream(streamContext(settings, overrides));@@ -338,12 +338,7 @@ describe('what a failed start is explained as', () => {});describe('whether it is signed in', () => {- const stubbed = (says: string) => {- const path = join(home, 'cursor-agent-stub');- writeFileSync(path, `#!/bin/sh\necho "${says}"\nexit 0\n`);- chmodSync(path, 0o755);- return path;- };+ const stubbed = (says: string) => stubCli(join(home, 'cursor-agent-stub'), `console.log(${JSON.stringify(says)});`);test('a signed-out CLI needs setup, though it exits 0 saying so', async () => {expect(await cursorRunner.check?.({ bin: stubbed('Not logged in') })).toEqual({diff --git a/src/daemon/agent/runners/fixtures/support.ts b/src/daemon/agent/runners/fixtures/support.tsindex 50721bd..7fffa78 100644--- a/src/daemon/agent/runners/fixtures/support.ts+++ b/src/daemon/agent/runners/fixtures/support.ts@@ -1,5 +1,6 @@-import { readFileSync } from 'node:fs';+import { chmodSync, readFileSync, writeFileSync } from 'node:fs';import { homedir } from 'node:os';+import { basename } from 'node:path';import type { AgentKind } from '@/lib/agents/catalog';import { stateDir } from '../../../lockfile';import type { AgentSettings } from '../../config';@@ -8,6 +9,23 @@ import type { JsonContext, Listing, McpServer, Plan, Runner, StreamContext, Streexport type Signal = keyof StreamSink;export type Call = [Signal, ...unknown[]];+/**+ * A stand-in CLI at `path` that runs the Node `script` with whatever arguments it is started with.+ * On Windows it is a batch shim of the shape npm writes, so a stub there is started the way an+ * npm-installed CLI is; elsewhere it is a shell script that hands over to Node.+ */+export function stubCli(path: string, script: string): string {+ const js = `${path}.js`;+ writeFileSync(js, script);+ if (process.platform === 'win32') {+ writeFileSync(`${path}.cmd`, `@ECHO off\r\n"${process.execPath}" "%~dp0\\${basename(js)}" %*\r\n`);+ } else {+ writeFileSync(path, `#!/bin/sh\nexec '${process.execPath}' '${js}' "$@"\n`);+ chmodSync(path, 0o755);+ }+ return path;+}+export function transcript(agent: AgentKind, name: string): string[] {return readFileSync(new URL(`./${agent}/${name}`, import.meta.url), 'utf8').split('\n')@@ -83,10 +101,20 @@ const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g;/** A plan as a snapshot shows it: the sandbox's paths and any freshly minted id replaced by names. */export function shown(plan: Plan): Plan {- const text = JSON.stringify(plan).replaceAll(stateDir, '<state>').replaceAll(homedir(), '<home>').replace(UUID, '<uuid>');+ // Each string is rewritten before it is escaped as JSON, where a Windows path's backslashes are doubled.+ const text = JSON.stringify(plan, (key, value: unknown) =>+ typeof value === 'string' ? portable(key, value.replaceAll(stateDir, '<state>').replaceAll(homedir(), '<home>')) : value,+ ).replace(UUID, '<uuid>');return JSON.parse(text) as Plan;}+/** A workspace file's path, and any path under a placeholder, read the same on every platform. */+function portable(key: string, value: string): string {+ if (process.platform !== 'win32') return value;+ if (key === 'path') return value.replaceAll('\\', '/');+ return value.replace(/<(state|home)>[^"\s]*/g, (path) => path.replaceAll('\\', '/'));+}+/** The value a flag takes, or undefined when the flag is absent. */export function valueOf(args: string[], flag: string): string | undefined {const at = args.indexOf(flag);diff --git a/src/daemon/agent/runners/models.test.ts b/src/daemon/agent/runners/models.test.tsindex 8c053fe..e54bc63 100644--- a/src/daemon/agent/runners/models.test.ts+++ b/src/daemon/agent/runners/models.test.ts@@ -1,10 +1,9 @@-import { execFileSync } from 'node:child_process';-import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest';import { AGENTS, type AgentKind } from '@/lib/agents/catalog';import { stateDir } from '../../lockfile';-import { listing } from './fixtures/support';+import { listing, stubCli } from './fixtures/support';import { RUNNERS } from './index';import { modelsFor, refreshModels } from './models';import type { Listing, Runner } from './types';@@ -63,12 +62,12 @@ describe("each CLI's own list, as recorded", () => {});describe('reading and keeping a list', () => {- const stub = (name: string, body: string) => {- const path = join(bin, name);- writeFileSync(path, `#!/bin/sh\necho "${name} $*" >> "${calls}"\n${body}\n`);- chmodSync(path, 0o755);- return path;- };+ const stub = (name: string, body: string) =>+ stubCli(+ join(bin, name),+ `require('node:fs').appendFileSync(${JSON.stringify(calls)}, [${JSON.stringify(name)}, ...process.argv.slice(2)].join(' ') + '\\n');\n${body}`,+ );+ const out = (text: string) => `process.stdout.write(${JSON.stringify(text)});`;const spawned = () => (existsSync(calls) ? readFileSync(calls, 'utf8').split('\n').filter(Boolean) : []);const agy = RUNNERS.antigravity;const settings = (path: string) => ({ bin: path });@@ -79,8 +78,11 @@ describe('reading and keeping a list', () => {beforeAll(() => {mkdirSync(bin, { recursive: true });- listed = stub('agy', `printf 'gemini-3.8-flash-high\\tFlash\\ngemini-3.1-pro-high\\tPro\\nother-model\\tOther\\n'`);- signedOut = stub('agy-signed-out', `echo 'Fetching available models...' >&2\necho 'Error: Please sign in to view available models.' >&2\nexit 1`);+ listed = stub('agy', out('gemini-3.8-flash-high\tFlash\ngemini-3.1-pro-high\tPro\nother-model\tOther\n'));+ signedOut = stub(+ 'agy-signed-out',+ `console.error('Fetching available models...'); console.error('Error: Please sign in to view available models.'); process.exit(1);`,+ );});beforeEach(() => {@@ -148,8 +150,8 @@ describe('reading and keeping a list', () => {});test('an id a CLI could read as a flag, or one with spaces, is dropped; a list of nothing else is a failure', async () => {- const hostile = stub('agy-hostile', `printf -- '--yolo\\tYolo\\nrm -rf\\tRm\\n'`);- const mixed = stub('agy-mixed', `printf -- '--yolo\\tYolo\\ngemini-3.1-pro-high\\tPro\\n'`);+ const hostile = stub('agy-hostile', out('--yolo\tYolo\nrm -rf\tRm\n'));+ const mixed = stub('agy-mixed', out('--yolo\tYolo\ngemini-3.1-pro-high\tPro\n'));await refreshModels(agy, settings(hostile), '1');const hostileList = modelsFor('antigravity');await refreshModels(agy, settings(mixed), '2');@@ -168,20 +170,28 @@ describe('reading and keeping a list', () => {});test('a CLI that floods its output is stopped at 512 KB', async () => {- const flood = stub('agy-flood', `yes 'gemini-3.8-flash-high\tFlash' | head -c 2000000`);+ const flood = stub('agy-flood', out('gemini-3.8-flash-high\tFlash\n'.repeat(80_000)));await refreshModels(agy, settings(flood), '1.2.11');expect(modelsFor('antigravity')).toMatchObject({ from: 'catalog', error: '"agy-flood models" printed more than 512 KB.' });});test('a CLI that hangs is killed at ten seconds, with whatever it started', async () => {- const hung = stub('agy-hung', 'sleep 37.25 &\nwait');+ const started = join(bin, 'agy-hung.child');+ rmSync(started, { force: true });+ const hung = stub(+ 'agy-hung',+ `const child = require('node:child_process').spawn(process.execPath, ['-e', 'setTimeout(() => {}, 37_250)'], { stdio: 'ignore' });+require('node:fs').writeFileSync(${JSON.stringify(started)}, String(child.pid));+setTimeout(() => {}, 37_250);`,+ );vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });const reading = refreshModels(agy, settings(hung), '1.2.11');- await vi.waitUntil(() => spawned().length === 1, { interval: 10, timeout: 5_000 });+ await vi.waitUntil(() => existsSync(started) && readFileSync(started, 'utf8') !== '', { interval: 10, timeout: 5_000 });vi.advanceTimersByTime(10_000);await reading;vi.useRealTimers();- await vi.waitUntil(() => !running('sleep 37.25'), { interval: 20, timeout: 2_000 });+ const child = Number(readFileSync(started, 'utf8'));+ await vi.waitUntil(() => !alive(child), { interval: 20, timeout: 2_000 });expect(modelsFor('antigravity').error).toBe('"agy-hung models" did not answer within 10 s.');});@@ -219,9 +229,9 @@ describe('reading and keeping a list', () => {});});-function running(pattern: string): boolean {+function alive(pid: number): boolean {try {- execFileSync('pgrep', ['-f', pattern]);+ process.kill(pid, 0);return true;} catch {return false;diff --git a/src/daemon/agent/site-map-store.test.ts b/src/daemon/agent/site-map-store.test.tsindex 95f3a90..8c308d8 100644--- a/src/daemon/agent/site-map-store.test.ts+++ b/src/daemon/agent/site-map-store.test.ts@@ -1,4 +1,4 @@-import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import { skillNameForHost } from '@/lib/skills/format';@@ -18,6 +18,7 @@ import {} from './site-map-store';import { loadSkills, uploadedSkillsDir } from './skills';import type { SiteIndex } from './sitemap';+import { bits, modeOf } from '../test/modes';const skills = () => uploadedSkillsDir();const target = (url = 'https://www.example.com/pricing'): MapTarget => {@@ -111,7 +112,7 @@ describe('what can be mapped', () => {describe('staging a map', () => {test('a staging area is made for the run, readable only by the user', () => {const staging = prepareStaging();- expect([staging.dir, staging.screenshots, staging.evidence, staging.pages].map((dir) => statSync(dir).mode & 0o777)).toEqual([0o700, 0o700, 0o700, 0o700]);+ expect([staging.dir, staging.screenshots, staging.evidence, staging.pages].map(modeOf)).toEqual([0o700, 0o700, 0o700, 0o700].map(bits));});test('evidence with nothing in it is not written', () => {diff --git a/src/daemon/agent/skill-store.test.ts b/src/daemon/agent/skill-store.test.tsindex d612f79..0a75c34 100644--- a/src/daemon/agent/skill-store.test.ts+++ b/src/daemon/agent/skill-store.test.ts@@ -1,10 +1,11 @@-import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { beforeEach, describe, expect, test } from 'vitest';import type { SkillDraft } from '@/lib/skills/format';import { stateDir } from '../lockfile';import { deleteSiteMap, deleteSkill, saveSkill } from './skill-store';import { loadSkills, uploadedSkillsDir } from './skills';+import { bits, modeOf } from '../test/modes';const draft = (overrides: Partial<SkillDraft> = {}): SkillDraft => ({name: 'expense-reports',@@ -30,9 +31,9 @@ describe('saving a skill from the panel', () => {const path = join(uploaded(), 'expense-reports.md');expect({saved,- mode: statSync(path).mode & 0o777,+ mode: modeOf(path),loaded: loadSkills().find((skill) => skill.name === 'expense-reports')?.source,- }).toEqual({ saved: { ok: true, data: { name: 'expense-reports', path, replaced: false } }, mode: 0o600, loaded: 'uploaded' });+ }).toEqual({ saved: { ok: true, data: { name: 'expense-reports', path, replaced: false } }, mode: bits(0o600), loaded: 'uploaded' });});test('it is written as front matter and the body', () => {diff --git a/src/daemon/auth-store.test.ts b/src/daemon/auth-store.test.tsindex e57f2d9..76d6ad1 100644--- a/src/daemon/auth-store.test.ts+++ b/src/daemon/auth-store.test.ts@@ -1,4 +1,4 @@-import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import {@@ -16,6 +16,7 @@ import {type Install,} from './auth-store';import { stateDir } from './lockfile';+import { bits, modeOf } from './test/modes';const authPath = join(stateDir, 'auth.json');const extension = 'chrome-extension://abcdefghijklmnopabcdefghijklmnop';@@ -126,7 +127,7 @@ describe('sessions', () => {describe('the file', () => {test('is readable only by the user', () => {createSession(chrome);- expect(statSync(authPath).mode & 0o777).toBe(0o600);+ expect(modeOf(authPath)).toBe(bits(0o600));});test('a damaged file pairs nothing, and the next write replaces it', () => {diff --git a/src/daemon/daemon.test.ts b/src/daemon/daemon.test.tsindex 778ac48..e102135 100644--- a/src/daemon/daemon.test.ts+++ b/src/daemon/daemon.test.ts@@ -1,4 +1,4 @@-import { existsSync, mkdirSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';import { homedir } from 'node:os';import { dirname, join } from 'node:path';import { beforeEach, describe, expect, test } from 'vitest';@@ -6,6 +6,7 @@ import { failure, success, type ActionResult } from '@/lib/actions/protocol';import { configPath } from './agent/config';import { uploadedSkillsDir } from './agent/skills';import { persistScreenshot } from './daemon';+import { bits, modeOf } from './test/modes';// Everything else in daemon.ts needs a running daemon with a browser attached, which is the integration suite's job.@@ -28,7 +29,7 @@ describe('keeping a screenshot', () => {test('save: true writes it, at mode 0600, and says where', () => {const kept = data(persistScreenshot('page.screenshot', { save: true, filename: 'pricing' }, capture));- expect([kept.savedTo, statSync(String(kept.savedTo)).mode & 0o777, kept.width]).toEqual([join(screenshotDir, 'pricing.png'), 0o600, 1280]);+ expect([kept.savedTo, modeOf(String(kept.savedTo)), kept.width]).toEqual([join(screenshotDir, 'pricing.png'), bits(0o600), 1280]);});test('only a real true asks for a save, since the content script applies the default and the daemon never sees it', () => {diff --git a/src/daemon/downloads.test.ts b/src/daemon/downloads.test.tsindex f487332..32f8180 100644--- a/src/daemon/downloads.test.ts+++ b/src/daemon/downloads.test.ts@@ -1,4 +1,4 @@-import { existsSync, mkdirSync, readFileSync, statSync, truncateSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, readFileSync, truncateSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { afterAll, beforeAll, describe, expect, test } from 'vitest';import type { ActionResult } from '@/lib/actions/protocol';@@ -14,6 +14,7 @@ import {type DownloadRecord,} from './downloads';import { stateDir } from './lockfile';+import { bits, modeOf } from './test/modes';// The store's refusals are only worth anything if the refused file is gone afterwards, so these// run against the real filesystem inside the sandboxed home.@@ -76,7 +77,7 @@ describe('what the store keeps', () => {});test('and written where only the user can read it', () => {- expect(statSync(kept.savedTo).mode & 0o777).toBe(0o600);+ expect(modeOf(kept.savedTo)).toBe(bits(0o600));});test('with notes about its shape, not its contents', () => {diff --git a/src/daemon/install.test.ts b/src/daemon/install.test.tsindex 8e1a3c4..55cbee4 100644--- a/src/daemon/install.test.ts+++ b/src/daemon/install.test.ts@@ -1,9 +1,10 @@-import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, 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';+import { bits, modeOf } from './test/modes';// 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 }));@@ -51,7 +52,7 @@ describe('installing the extension', () => {test('the files are readable by the browser', () => {install(target);- expect(statSync(join(target, 'background.js')).mode & 0o777).toBe(0o644);+ expect(modeOf(join(target, 'background.js'))).toBe(bits(0o644));});test('the same version again copies nothing', () => {diff --git a/src/daemon/lockfile.test.ts b/src/daemon/lockfile.test.tsindex 8a182f7..2b0c111 100644--- a/src/daemon/lockfile.test.ts+++ b/src/daemon/lockfile.test.ts@@ -1,10 +1,11 @@import { spawnSync } from 'node:child_process';-import { mkdirSync, statSync, writeFileSync } from 'node:fs';+import { mkdirSync, writeFileSync } from 'node:fs';import { homedir } from 'node:os';import { join } from 'node:path';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import { clearLockfile, isRunning, lockfilePath, readLockfile, stateDir, writeLockfile, type Lockfile } from './lockfile';import { extensionDir, installStampPath, userDir } from './paths';+import { bits, modeOf } from './test/modes';const lock: Lockfile = { pid: process.pid, port: 49_152, token: 'secret-token', protocolVersion: 9, daemonVersion: '0.6.2' };@@ -55,7 +56,7 @@ describe('the lockfile', () => {test('it holds the control token, so only the user can read it', () => {writeLockfile(lock);- expect(statSync(lockfilePath).mode & 0o777).toBe(0o600);+ expect(modeOf(lockfilePath)).toBe(bits(0o600));});test('no lockfile means no daemon', () => {diff --git a/src/daemon/native-host.test.ts b/src/daemon/native-host.test.tsindex 49021cd..356e336 100644--- a/src/daemon/native-host.test.ts+++ b/src/daemon/native-host.test.ts@@ -1,4 +1,4 @@-import { existsSync, mkdirSync, readFileSync, rmSync, statSync } from 'node:fs';+import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';import { homedir } from 'node:os';import { join } from 'node:path';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -18,6 +18,7 @@ import {unpackedExtensionOrigin,} from './native-host';import { extensionDir } from './paths';+import { bits, modeOf } from './test/modes';describe('unpackedExtensionOrigin', () => {it('names the folder the way Chrome does', () => {@@ -122,7 +123,7 @@ describe('registering the host', () => {const installed = installNativeHost('/opt/browsentic/dist/cli.js', 'linux');expect(installed.browsers).toEqual(['Chrome']);- expect(statSync(installed.launcher).mode & 0o777).toBe(0o755);+ expect(modeOf(installed.launcher)).toBe(bits(0o755));expect(JSON.parse(readFileSync(manifest, 'utf8'))).toMatchObject({path: installed.launcher,allowed_origins: [unpackedExtensionOrigin(extensionDir())],diff --git a/src/daemon/screenshots.test.ts b/src/daemon/screenshots.test.tsindex 9673a48..3a00127 100644--- a/src/daemon/screenshots.test.ts+++ b/src/daemon/screenshots.test.ts@@ -1,10 +1,11 @@-import { mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { homedir } from 'node:os';import { basename, dirname, join } from 'node:path';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import { configPath } from './agent/config';import { uploadedSkillsDir } from './agent/skills';import { saveScreenshot, screenshotDir } from './screenshots';+import { bits, modeOf } from './test/modes';const PNG_BYTES = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);const png = `data:image/png;base64,${PNG_BYTES.toString('base64')}`;@@ -32,8 +33,8 @@ describe('saving a screenshot', () => {dir: dirname(path),name: /^screenshot-20260921-140509-[0-9a-f]{6}\.png$/.test(basename(path)),bytes: readFileSync(path).equals(PNG_BYTES),- mode: statSync(path).mode & 0o777,- }).toEqual({ dir: defaultDir, name: true, bytes: true, mode: 0o600 });+ mode: modeOf(path),+ }).toEqual({ dir: defaultDir, name: true, bytes: true, mode: bits(0o600) });});test('the extension follows the image type', () => {diff --git a/src/daemon/self-update.test.ts b/src/daemon/self-update.test.tsindex 048afe0..3b7f7f8 100644--- a/src/daemon/self-update.test.ts+++ b/src/daemon/self-update.test.ts@@ -1,8 +1,9 @@-import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';import { createServer, type IncomingMessage } from 'node:http';import type { AddressInfo } from 'node:net';import { join } from 'node:path';import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi, type MockInstance } from 'vitest';+import { stubCli } from './agent/runners/fixtures/support';import { stateDir } from './lockfile';import type { InstallKind, NpxEntry } from './npx';@@ -35,8 +36,11 @@ beforeAll(async () => {mkdirSync(bin, { recursive: true });for (const name of ['npm', 'npx', 'browsentic']) {- writeFileSync(join(bin, name), `#!/bin/sh\necho "${name} $*" >> "${ran}"\nexit "\${FAKE_${name.toUpperCase()}_EXIT:-0}"\n`);- chmodSync(join(bin, name), 0o755);+ stubCli(+ join(bin, name),+ `require('node:fs').appendFileSync(${JSON.stringify(ran)}, [${JSON.stringify(name)}, ...process.argv.slice(2)].join(' ') + '\\n');+process.exit(Number(process.env.FAKE_${name.toUpperCase()}_EXIT || 0));`,+ );}});@@ -168,7 +172,8 @@ describe('updating the command itself', () => {]);});- test('a command that is not there at all is a failure with its name', async () => {+ // Windows runs npm through cmd.exe, which answers a missing command with an exit code, not a spawn error.+ test.skipIf(process.platform === 'win32')('a command that is not there at all is a failure with its name', async () => {vi.stubEnv('PATH', join(stateDir, 'empty-bin'));expect([await selfUpdate.upgradeCli('0.6.2', ['update']), stderr().includes('Could not run `npm`')]).toEqual([1, true]);});diff --git a/src/daemon/test/modes.ts b/src/daemon/test/modes.tsnew file mode 100644index 0000000..c1dfb0f--- /dev/null+++ b/src/daemon/test/modes.ts@@ -0,0 +1,9 @@+import { statSync } from 'node:fs';++/**+ * Windows keeps no POSIX permission bits — every file there reads as 0o666 or 0o444 — so a test+ * asserts a mode only where it means something: on Windows both of these answer null.+ */+export const modeOf = (path: string): number | null => (process.platform === 'win32' ? null : statSync(path).mode & 0o777);++export const bits = (mode: number): number | null => (process.platform === 'win32' ? null : mode);