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(settings): move settings out of the side panel into a page of their own, and keep the theme and the guardrails in config.json so every paired browser and the Mac app edit the same values and see each other's changes as they land

Shahriarbea54a90f347
diff --git a/src/daemon/agent/config.test.ts b/src/daemon/agent/config.test.ts
index 3d6ab89..105b374 100644
--- a/src/daemon/agent/config.test.ts
+++ b/src/daemon/agent/config.test.ts
@@ -11,6 +11,7 @@ import {
writeActiveAgent,
writeAgentModel,
writeGuardrailSetting,
+ writeTheme,
type AgentConfig,
} from './config';
@@ -172,6 +173,14 @@ describe('writing config.json', () => {
});
});
+ test('a theme is written as one key beside the rest, and read back only when it is one the extension has', () => {
+ store({ agent: 'codex' });
+ writeTheme('midnight');
+ const written = [stored(), readAgentConfig().theme];
+ store({ theme: 'solarized' });
+ expect([...written, readAgentConfig().theme]).toEqual([{ agent: 'codex', theme: 'midnight' }, 'midnight', undefined]);
+ });
+
test('where setup --dir put the extension is remembered, and forgotten when it goes back to the default', () => {
rememberExtensionDir('/var/flatpak/browsentic');
const remembered = stored();
diff --git a/src/daemon/agent/config.ts b/src/daemon/agent/config.ts
index 242990c..ccb6053 100644
--- a/src/daemon/agent/config.ts
+++ b/src/daemon/agent/config.ts
@@ -2,6 +2,7 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { AGENTS, AGENT_KINDS, DEFAULT_AGENT, isAgentKind, isModelId, type AgentKind } from '@/lib/agents/catalog';
import { FENCE_SETTING, UNATTENDED_SETTING, type GuardrailValue, type RuleEffect } from '@/lib/settings/guardrails';
+import { isThemeId, type ThemeId } from '@/lib/settings/theme';
import type { GuardrailConfig } from '../guardrails';
import { stateDir } from '../lockfile';
import { log } from '../log';
@@ -22,6 +23,8 @@ export interface AgentConfig {
maxConcurrentRuns?: number;
/** Overrides for the declared guardrail policy. See guardrails/policy.ts. */
guardrails?: GuardrailConfig;
+ /** The look every paired browser takes. Absent until someone picks one. */
+ theme?: ThemeId;
screenshotDir?: string;
downloadDir?: string;
/** Days a captured download is kept before the daemon sweeps it. Fractions allowed. Defaults to 14. */
@@ -118,6 +121,7 @@ export function readAgentConfig(): AgentConfig {
requireApproval: Array.isArray(stored.requireApproval)
? (stored.requireApproval as string[])
: DEFAULT_APPROVALS,
+ theme: isThemeId(stored.theme) ? stored.theme : undefined,
};
}
@@ -210,6 +214,11 @@ export function writeGuardrailSetting(setting: string, value: GuardrailValue): v
write(next);
}
+/** Sets the look every paired browser takes, leaving every other key in config.json untouched. */
+export function writeTheme(theme: ThemeId): void {
+ write({ ...readStored(), theme });
+}
+
function write(config: StoredConfig): void {
mkdirSync(stateDir, { recursive: true, mode: 0o700 });
writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
diff --git a/src/daemon/control.ts b/src/daemon/control.ts
index 38f4824..7daf3ec 100644
--- a/src/daemon/control.ts
+++ b/src/daemon/control.ts
@@ -1,6 +1,7 @@
import type { ActionResult } from '@/lib/actions/protocol';
import type { ToolDescriptor } from '@/lib/actions/manifest';
import type { AgentKind, AgentState } from '@/lib/agents/catalog';
+import type { Preferences } from '@/lib/settings/preferences';
export interface BridgeStatus {
connected: boolean;
@@ -40,7 +41,10 @@ export type ControlRequest =
| { id: string; op: 'pair' }
| { id: string; op: 'sessions' }
| { id: string; op: 'revoke'; session?: string; origin?: string }
- | { id: string; op: 'agent'; set?: AgentKind; grant?: AgentKind; models?: AgentKind };
+ | { id: string; op: 'agent'; set?: AgentKind; grant?: AgentKind; models?: AgentKind }
+ /** `watch` also subscribes this caller to `settings-changed`, which no other caller is sent. */
+ | { id: string; op: 'preferences'; watch?: boolean }
+ | { id: string; op: 'setPreference'; change: unknown };
export type ControlMessage =
| { id: string; op: 'describe'; tools: ToolDescriptor[]; reserved?: string[] }
@@ -51,7 +55,10 @@ export type ControlMessage =
| { id: string; op: 'sessions'; sessions: SessionSummary[] }
| { id: string; op: 'revoke'; revoked: number }
| { id: string; op: 'agent'; state: AgentState }
- | { event: 'manifest-changed' };
+ | { id: string; op: 'preferences'; result: ActionResult<Preferences> }
+ | { event: 'manifest-changed' }
+ /** config.json changed, from any side: read the preferences and the agent state again. */
+ | { event: 'settings-changed' };
export interface Described {
tools: ToolDescriptor[];
diff --git a/src/daemon/daemon.ts b/src/daemon/daemon.ts
index b5b28b0..3fd87e8 100644
--- a/src/daemon/daemon.ts
+++ b/src/daemon/daemon.ts
@@ -15,7 +15,6 @@ import {
type SkillCatalog,
type SocketFrame,
} from '@/lib/actions/protocol';
-import type { GuardrailSettings } from '@/lib/settings/guardrails';
import type { TaskList } from '@/lib/schedules/task';
import { hashManifest, type ToolDescriptor } from '@/lib/actions/manifest';
import { solveCaptcha } from '@/lib/actions/page/solve-captcha';
@@ -53,7 +52,7 @@ import { solveCaptchaWithAnalyst } from './agent/captcha-solver';
import { FileAnalyses } from './agent/file-analyst';
import { analyzeRecording } from './agent/recording';
import { nameSession } from './agent/title';
-import { configPath, readAgentConfig, writeActiveAgent, writeAgentModel, writeGuardrailSetting } from './agent/config';
+import { readAgentConfig, writeActiveAgent, writeAgentModel } from './agent/config';
import { agentSkills } from './agent/agent-skills';
import { agentState, grantRunner, refreshModelLists } from './agent/runners';
import { deleteSiteMap, deleteSkill, saveSkill } from './agent/skill-store';
@@ -78,18 +77,16 @@ import {
blocked,
decide,
describe as describeDecision,
- guardrailSettings,
policyFrom,
sealSecrets,
- settingWritable,
summary as summarizeDecision,
} from './guardrails';
import { log } from './log';
+import { applyPreference, markConfig, preferencesNow, watchConfig } from './preferences';
import { readLockfile, writeLockfile, clearLockfile, releaseWake, type Lockfile } from './lockfile';
import { daemonPorts } from './ports';
type AgentFrame = Extract<SocketFrame, { t: 'agentState' | 'setAgent' | 'setAgentModel' | 'grantAgent' }>;
-type GuardrailFrame = Extract<SocketFrame, { t: 'guardrails' | 'setGuardrail' }>;
type TaskFrame = Extract<SocketFrame, { t: 'tasks' | 'saveTask' | 'deleteTask' | 'pauseTasks' }>;
const IDLE_EXIT_MS = 30 * 60 * 1000;
@@ -179,6 +176,9 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):
const agents = new Map<ExtensionLink, AgentSession>();
const analyses = new FileAnalyses();
const controls = new Set<WebSocket>();
+ const settingsWatchers = new Set<WebSocket>();
+ let configSeen = markConfig();
+ const unwatchConfig = watchConfig(() => configChanged());
let controlSeq = 0;
const manifestListeners = new Set<() => void>();
let idleTimer: ReturnType<typeof setTimeout> | null = null;
@@ -431,15 +431,20 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):
source.send({ t: 'agentInfo', id: request.id, result: state });
// The catalog's agent-skill half belongs to the agent that just took over.
if (request.t === 'setAgent') pushSkillCatalog(source);
- if (request.t !== 'agentState') announceAgent(source);
+ if (request.t === 'grantAgent') announceAgent(source);
+ else if (request.t !== 'agentState') configChanged(source);
});
return;
}
if (request.t === 'listSkills') {
return source.send({ t: 'skillCatalog', id: request.id, result: skillCatalogNow(request.refresh === true) });
}
- if (request.t === 'guardrails' || request.t === 'setGuardrail') {
- return source.send({ t: 'guardrailInfo', id: request.id, result: settleGuardrail(request) });
+ if (request.t === 'preferences') {
+ return source.send({ t: 'preferencesInfo', id: request.id, result: success(preferencesNow()) });
+ }
+ if (request.t === 'setPreference') {
+ source.send({ t: 'preferencesInfo', id: request.id, result: applyPreference(request.change) });
+ return configChanged(source);
}
if (request.t === 'taskDone') return scheduler.finished(request.taskId, request.result);
if (request.t === 'runTaskNow') {
@@ -490,6 +495,7 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):
void pushAgentState(accepted);
watchModels();
pushSkillCatalog(accepted);
+ accepted.send({ t: 'preferencesInfo', id: '', result: success(preferencesNow()) });
accepted.send({ t: 'taskList', id: '', result: success(scheduler.list()) });
scheduler.linkOpened();
if (!known) await adoptExtensionManifest(accepted);
@@ -527,6 +533,27 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):
for (const link of openLinks()) pushSkillCatalog(link);
}
+ /**
+ * Hands every open surface what config.json now says, once per change however many paths
+ * noticed it: the write's own caller already has the answer, so it is skipped.
+ */
+ function configChanged(except?: ExtensionLink): void {
+ const mark = markConfig();
+ if (mark.file === configSeen.file) return;
+ const agentMoved = mark.agent !== configSeen.agent;
+ configSeen = mark;
+ const preferences = success(preferencesNow());
+ for (const link of openLinks()) {
+ if (link === except) continue;
+ link.send({ t: 'preferencesInfo', id: '', result: preferences });
+ if (agentMoved) {
+ void pushAgentState(link);
+ pushSkillCatalog(link);
+ }
+ }
+ for (const ws of settingsWatchers) send(ws, { event: 'settings-changed' });
+ }
+
async function settleAgent(request: AgentFrame): Promise<ActionResult<AgentState>> {
if (request.t !== 'agentState' && !isAgentKind(request.agent)) {
return failure('INVALID_INPUT', `"${String(request.agent)}" is not an agent Browsentic knows.`);
@@ -564,21 +591,6 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):
.catch((error: unknown) => log(`could not refresh the model lists: ${String(error)}`));
}
- function settleGuardrail(request: GuardrailFrame): ActionResult<GuardrailSettings> {
- if (request.t === 'setGuardrail') {
- if (!settingWritable(request.setting, request.value)) {
- return failure(
- 'INVALID_INPUT',
- `"${request.setting}" is not a guardrail the panel may set. Locked rules are edited in ${configPath}.`,
- );
- }
- writeGuardrailSetting(request.setting, request.value);
- log(`guardrail ${request.setting} → ${request.value === null ? 'default' : String(request.value)}`);
- }
- const config = readAgentConfig();
- return success(guardrailSettings(config.guardrails ?? {}, config.requireApproval, configPath));
- }
-
function settleTasks(request: TaskFrame): ActionResult<TaskList> {
if (request.t === 'saveTask') return scheduler.save(request.task);
if (request.t === 'deleteTask') return scheduler.remove(request.taskId);
@@ -696,6 +708,9 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):
function acceptControl(ws: WebSocket): void {
const client = `c${++controlSeq}`;
const binding: Binding = { usedAt: 0 };
+ // A connection that has spoken for an agent run is that run's own tool server, and a run
+ // never gets to loosen the guardrails it is running under.
+ let speaksForRun = false;
controls.add(ws);
scheduleIdleExit();
ws.on('message', async (raw) => {
@@ -705,6 +720,7 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):
} catch {
return log('dropped unparseable control frame');
}
+ if ((request.op === 'describe' || request.op === 'invoke') && request.runId) speaksForRun = true;
if (request.op === 'describe') {
return send(ws, { id: request.id, op: 'describe', ...describeFor(request.runId, binding) });
}
@@ -754,10 +770,27 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):
const listed = isAgentKind(request.models);
if (listed) await refreshModelLists(readAgentConfig(), { force: true, only: request.models });
const state = await agentState(readAgentConfig(), { refresh: !!changed || listed });
- if (changed || listed) announceAgent();
- else watchModels();
+ if (request.set) configChanged();
+ if (request.grant || listed) announceAgent();
+ else if (!request.set) watchModels();
return send(ws, { id: request.id, op: 'agent', state });
}
+ if (request.op === 'preferences') {
+ if (request.watch) settingsWatchers.add(ws);
+ return send(ws, { id: request.id, op: 'preferences', result: success(preferencesNow()) });
+ }
+ if (request.op === 'setPreference') {
+ if (speaksForRun) {
+ log(`control ${client} tried to change a setting from inside an agent run; refused`);
+ return send(ws, {
+ id: request.id,
+ op: 'preferences',
+ result: failure('BLOCKED', 'An agent run cannot change the settings it runs under. Change them from the settings page or the Mac app.'),
+ });
+ }
+ send(ws, { id: request.id, op: 'preferences', result: applyPreference(request.change) });
+ return configChanged();
+ }
if (request.op === 'revoke') {
const { session: id, origin } = request;
const revoked = revokeSessions((session) => (id ? sessionId(session) === id : !origin || session.origin === origin));
@@ -770,6 +803,7 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):
});
const drop = () => {
controls.delete(ws);
+ settingsWatchers.delete(ws);
scheduleIdleExit();
};
ws.on('close', drop);
@@ -886,6 +920,7 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):
async function stop(): Promise<void> {
if (idleTimer) clearTimeout(idleTimer);
scheduler.stop();
+ unwatchConfig();
for (const link of [...links.values()]) link.close('daemon shutting down');
for (const ws of controls) ws.close(1001, 'daemon shutting down');
wss.close();
diff --git a/src/daemon/preferences.ts b/src/daemon/preferences.ts
new file mode 100644
index 0000000..c58a413
--- /dev/null
+++ b/src/daemon/preferences.ts
@@ -0,0 +1,90 @@
+/**
+ * The settings two surfaces share: the extension's settings page and the Mac app both read
+ * and write them here, and config.json is the only copy. A change from either side, from the
+ * CLI, or from a hand edit of the file reaches every open surface through `watchConfig`.
+ */
+
+import { createHash } from 'node:crypto';
+import { mkdirSync, readFileSync, watch } from 'node:fs';
+import { basename } from 'node:path';
+import { failure, success, type ActionResult } from '@/lib/actions/protocol';
+import { isPreferenceChange, type Preferences } from '@/lib/settings/preferences';
+import { configPath, readAgentConfig, writeGuardrailSetting, writeTheme } from './agent/config';
+import { guardrailSettings, settingWritable } from './guardrails';
+import { log } from './log';
+import { stateDir } from './paths';
+
+const SETTLE_MS = 150;
+const CONFIG_FILE = basename(configPath);
+
+export function preferencesNow(): Preferences {
+ const config = readAgentConfig();
+ return {
+ theme: config.theme ?? null,
+ guardrails: guardrailSettings(config.guardrails ?? {}, config.requireApproval, configPath),
+ };
+}
+
+export function applyPreference(change: unknown): ActionResult<Preferences> {
+ if (!isPreferenceChange(change)) {
+ return failure('INVALID_INPUT', 'Expected {kind:"theme", theme} or {kind:"guardrail", setting, value}.');
+ }
+ if (change.kind === 'theme') {
+ if (readAgentConfig().theme !== change.theme) {
+ writeTheme(change.theme);
+ log(`theme → ${change.theme}`);
+ }
+ return success(preferencesNow());
+ }
+ if (!settingWritable(change.setting, change.value)) {
+ return failure(
+ 'INVALID_INPUT',
+ `"${change.setting}" is not a guardrail the settings screen may set. Locked rules are edited in ${configPath}.`,
+ );
+ }
+ writeGuardrailSetting(change.setting, change.value);
+ log(`guardrail ${change.setting} → ${change.value === null ? 'default' : String(change.value)}`);
+ return success(preferencesNow());
+}
+
+/** What config.json holds right now, and the part of it a change of agent or model moves. */
+export interface ConfigMark {
+ file: string;
+ agent: string;
+}
+
+export function markConfig(): ConfigMark {
+ let text = '';
+ try {
+ text = readFileSync(configPath, 'utf8');
+ } catch {
+ // No file is a state of its own: every setting at its default.
+ }
+ const { agent, agents } = readAgentConfig();
+ return { file: createHash('sha256').update(text).digest('hex'), agent: JSON.stringify([agent, agents]) };
+}
+
+/**
+ * Calls back once config.json settles after a write from anywhere. The directory is watched,
+ * not the file, because an editor that saves by replacing the file would end a file watch.
+ */
+export function watchConfig(onChange: () => void): () => void {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
+ const watcher = watch(stateDir, (_event, name) => {
+ if (name !== null && String(name) !== CONFIG_FILE) return;
+ clearTimeout(timer);
+ timer = setTimeout(onChange, SETTLE_MS);
+ });
+ watcher.on('error', (error) => log(`stopped watching ${configPath}: ${String(error)}`));
+ watcher.unref();
+ return () => {
+ clearTimeout(timer);
+ watcher.close();
+ };
+ } catch (error) {
+ log(`not watching ${configPath}, so a hand edit applies at the next change: ${String(error)}`);
+ return () => undefined;
+ }
+}
diff --git a/src/daemon/test/fake-browser.ts b/src/daemon/test/fake-browser.ts
index 287ff8b..c19dfc5 100644
--- a/src/daemon/test/fake-browser.ts
+++ b/src/daemon/test/fake-browser.ts
@@ -9,7 +9,9 @@ import {
type ExtensionRequest,
type SocketFrame,
} from '@/lib/actions/protocol';
+import type { AgentState } from '@/lib/agents/catalog';
import type { TaskList, TaskOrder } from '@/lib/schedules/task';
+import type { Preferences } from '@/lib/settings/preferences';
import { describeActions, type BrowserTarget } from '@/lib/actions/registry';
export interface Profile {
@@ -35,6 +37,10 @@ export class FakeBrowser {
taskReply: ActionResult = { ok: true, data: { sessionId: 'fake-session' } };
/** The task list the daemon last pushed or answered with. */
tasks: TaskList | null = null;
+ /** The settings the daemon last pushed or answered with. */
+ preferences: Preferences | null = null;
+ /** The agent state the daemon last pushed or answered with. */
+ agent: AgentState | null = null;
/** While set, every invoke is answered only once it resolves. */
holdInvokes: Promise<void> | null = null;
private readonly replies = new Map<string, (frame: SocketFrame) => void>();
@@ -122,6 +128,8 @@ export class FakeBrowser {
private receive(frame: SocketFrame | null): void {
if (frame?.t === 'taskList' && frame.result.ok) this.tasks = frame.result.data;
+ if (frame?.t === 'preferencesInfo' && frame.result.ok) this.preferences = frame.result.data;
+ if (frame?.t === 'agentInfo' && frame.result.ok) this.agent = frame.result.data;
const waiting = frame && 'id' in frame ? this.replies.get(frame.id) : undefined;
if (waiting && frame && 'id' in frame) {
this.replies.delete(frame.id);
diff --git a/src/daemon/test/preferences.test.ts b/src/daemon/test/preferences.test.ts
new file mode 100644
index 0000000..9171c67
--- /dev/null
+++ b/src/daemon/test/preferences.test.ts
@@ -0,0 +1,167 @@
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { dirname } from 'node:path';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest';
+import { WebSocket } from 'ws';
+import type { ActionResult, SocketFrame } from '@/lib/actions/protocol';
+import type { Preferences } from '@/lib/settings/preferences';
+import { clearAuth } from '../auth-store';
+import { configPath, writeAgentModel } from '../agent/config';
+import { startDaemon, type Daemon } from '../daemon';
+import { readLockfile } from '../lockfile';
+import { RemoteBridge } from '../remote-bridge';
+import { FakeBrowser, type Profile } from './fake-browser';
+
+const unpacked = 'chrome-extension://abcdefghijklmnopabcdefghijklmnop';
+const chrome: Profile = { origin: unpacked, installId: 'install-chrome-0001', browser: 'Google Chrome' };
+const brave: Profile = { origin: unpacked, installId: 'install-brave-00001', browser: 'Brave' };
+
+let daemon: Daemon;
+let opened: { close(): unknown }[] = [];
+
+beforeAll(async () => {
+ daemon = await startDaemon({ version: '0.0.0-test', idleExit: false });
+});
+
+afterAll(async () => {
+ await daemon?.stop();
+});
+
+beforeEach(() => rmSync(configPath, { force: true }));
+
+afterEach(async () => {
+ for (const each of opened) each.close();
+ opened = [];
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ clearAuth();
+});
+
+async function paired(profile: Profile): Promise<FakeBrowser> {
+ const bridge = await RemoteBridge.connect(daemon.port, readLockfile()!.token);
+ opened.push(bridge);
+ const browser = await FakeBrowser.connect(daemon.port, profile, { kind: 'pair', code: (await bridge.pair()).code });
+ opened.push(browser);
+ return browser;
+}
+
+type Reply = { result: ActionResult<Preferences> & { data?: Preferences } };
+
+/** The Mac app's side of /control: it asks for the settings, subscribes, and changes them. */
+async function macApp() {
+ const socket = new WebSocket(`ws://127.0.0.1:${daemon.port}/control`, {
+ headers: { authorization: `Bearer ${readLockfile()!.token}` },
+ });
+ opened.push(socket);
+ await new Promise((resolve) => socket.once('open', resolve));
+ const events: string[] = [];
+ const replies = new Map<string, (frame: Reply) => void>();
+ socket.on('message', (raw) => {
+ const frame = JSON.parse(String(raw)) as Reply & { id?: string; event?: string };
+ if (frame.event) events.push(frame.event);
+ if (frame.id) replies.get(frame.id)?.(frame);
+ });
+ const ask = (request: object) => {
+ const id = randomUUID();
+ const answered = new Promise<Reply>((resolve) => replies.set(id, resolve));
+ socket.send(JSON.stringify({ id, ...request }));
+ return answered;
+ };
+ await ask({ op: 'preferences', watch: true });
+ return { events, ask };
+}
+
+const theme = (frame: SocketFrame) => (frame.t === 'preferencesInfo' && frame.result.ok ? frame.result.data.theme : undefined);
+
+describe('settings shared by the extension and the Mac app', () => {
+ test('a browser hears what config.json holds the moment it connects, with no theme until someone picks one', async () => {
+ const browser = await paired(chrome);
+ await vi.waitFor(() => expect(browser.preferences).not.toBeNull());
+ expect(browser.preferences?.theme).toBeNull();
+ expect(browser.preferences?.guardrails.rules.length).toBeGreaterThan(0);
+ });
+
+ test('a theme picked in the Mac app reaches every paired browser, and the app hears the change', async () => {
+ const [first, second] = [await paired(chrome), await paired(brave)];
+ const app = await macApp();
+
+ const reply = await app.ask({ op: 'setPreference', change: { kind: 'theme', theme: 'midnight' } });
+ expect(reply.result.data?.theme).toBe('midnight');
+
+ await vi.waitFor(() => expect([first.preferences?.theme, second.preferences?.theme]).toEqual(['midnight', 'midnight']));
+ expect(app.events).toContain('settings-changed');
+ expect(JSON.parse(readFileSync(configPath, 'utf8'))).toMatchObject({ theme: 'midnight' });
+ });
+
+ test('a guardrail flipped in one browser reaches the other browser and the Mac app', async () => {
+ const [first, second] = [await paired(chrome), await paired(brave)];
+ const app = await macApp();
+
+ const answer = await first.ask({
+ t: 'setPreference',
+ id: randomUUID(),
+ change: { kind: 'guardrail', setting: 'fence', value: false },
+ });
+ expect(answer.t === 'preferencesInfo' && answer.result.ok && answer.result.data.guardrails.fence).toEqual({ enabled: false, overridden: true });
+
+ await vi.waitFor(() => expect(second.preferences?.guardrails.fence).toEqual({ enabled: false, overridden: true }));
+ await vi.waitFor(() => expect(app.events).toContain('settings-changed'));
+ });
+
+ test('a change that writes nothing new is announced to nobody', async () => {
+ const [first, second] = [await paired(chrome), await paired(brave)];
+ await first.ask({ t: 'setPreference', id: randomUUID(), change: { kind: 'theme', theme: 'daylight' } });
+ await vi.waitFor(() => expect(second.preferences?.theme).toBe('daylight'));
+ const app = await macApp();
+
+ const again = await first.ask({ t: 'setPreference', id: randomUUID(), change: { kind: 'theme', theme: 'daylight' } });
+ expect(theme(again)).toBe('daylight');
+ await new Promise((resolve) => setTimeout(resolve, 400));
+ expect(app.events).toEqual([]);
+ });
+
+ test('a locked rule, an unknown setting and a theme that does not exist are refused and written nowhere', async () => {
+ const browser = await paired(chrome);
+ const answers = await Promise.all(
+ [
+ { kind: 'guardrail', setting: 'secret-in-url', value: 'allow' },
+ { kind: 'guardrail', setting: 'no-such-rule', value: 'allow' },
+ { kind: 'theme', theme: 'solarized' },
+ ].map((change) => browser.ask({ t: 'setPreference', id: randomUUID(), change } as never)),
+ );
+ expect(answers.map((frame) => frame.t === 'preferencesInfo' && !frame.result.ok && frame.result.error.code)).toEqual([
+ 'INVALID_INPUT',
+ 'INVALID_INPUT',
+ 'INVALID_INPUT',
+ ]);
+ expect(() => readFileSync(configPath, 'utf8')).toThrow();
+ });
+
+ test('a control connection that has spoken for an agent run cannot loosen the guardrails it runs under', async () => {
+ const app = await macApp();
+ await app.ask({ op: 'describe', runId: 'run-under-guard' });
+ const refused = await app.ask({ op: 'setPreference', change: { kind: 'guardrail', setting: 'form-submission', value: 'allow' } });
+ expect(refused.result).toMatchObject({ ok: false, error: { code: 'BLOCKED' } });
+ expect(() => readFileSync(configPath, 'utf8')).toThrow();
+ });
+
+ test('a hand edit of config.json reaches every browser and the Mac app', async () => {
+ const browser = await paired(chrome);
+ const app = await macApp();
+ mkdirSync(dirname(configPath), { recursive: true });
+ writeFileSync(configPath, JSON.stringify({ theme: 'phosphor' }));
+
+ await vi.waitFor(() => expect(browser.preferences?.theme).toBe('phosphor'));
+ expect(app.events).toContain('settings-changed');
+ });
+
+ test('a model set from the terminal reaches the browsers’ agent picker', async () => {
+ const browser = await paired(chrome);
+ // The first push probes every agent CLI on PATH, which is slow on a busy machine.
+ await vi.waitFor(() => expect(browser.agent).not.toBeNull(), { timeout: 10_000 });
+ writeAgentModel('claude', 'opus');
+
+ await vi.waitFor(() => expect(browser.agent?.runners.find((runner) => runner.kind === 'claude')?.model).toBe('opus'), {
+ timeout: 10_000,
+ });
+ });
+});
diff --git a/src/extension/components/connection-sheet.tsx b/src/extension/components/connection-sheet.tsx
index ae972e2..e992ca2 100644
--- a/src/extension/components/connection-sheet.tsx
+++ b/src/extension/components/connection-sheet.tsx
@@ -1,4 +1,5 @@
-import { X } from 'lucide-react';
+import { SlidersHorizontal, X } from 'lucide-react';
+import { browser } from 'wxt/browser';
import { AgentPicker } from '@/extension/components/agent-picker';
import { DaemonLink } from '@/extension/components/daemon-link';
@@ -17,6 +18,13 @@ export function ConnectionSheet({ onClose }: { onClose: () => void }) {
<DaemonLink />
<AgentPicker />
</div>
+ <button
+ type="button"
+ onClick={() => void browser.runtime.openOptionsPage()}
+ className="mt-3 inline-flex items-center gap-1.5 font-mono text-[10px] tracking-[0.14em] text-ink-faint uppercase transition-colors hover:text-brand"
+ >
+ <SlidersHorizontal className="size-3" /> All settings
+ </button>
</div>
);
}
diff --git a/src/extension/components/guardrail-settings.tsx b/src/extension/components/guardrail-settings.tsx
new file mode 100644
index 0000000..562ac80
--- /dev/null
+++ b/src/extension/components/guardrail-settings.tsx
@@ -0,0 +1,286 @@
+import { useCallback, useEffect, useState, type ReactNode } from 'react';
+import { Loader2, Lock, RefreshCw, ShieldCheck } from 'lucide-react';
+import { browser } from 'wxt/browser';
+
+import { Switch } from '@/extension/components/ui/switch';
+import { BRIDGE_CHANNEL, type ActionResult } from '@/lib/actions/protocol';
+import { useDaemonState } from '@/lib/bridge/use-daemon-state';
+import {
+ EFFECT_LABEL,
+ FENCE_SETTING,
+ UNATTENDED_SETTING,
+ type GuardrailToggle,
+ type GuardrailValue,
+ type RuleEffect,
+} from '@/lib/settings/guardrails';
+import type { PreferenceChange, Preferences } from '@/lib/settings/preferences';
+import { cn } from '@/lib/utils';
+
+const EFFECTS: RuleEffect[] = ['allow', 'confirm', 'deny'];
+
+export function GuardrailSettings() {
+ const daemon = useDaemonState();
+ const connected = daemon?.connected ?? false;
+ const settings = daemon?.preferences?.guardrails;
+ const [busy, setBusy] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ const ask = useCallback(async (request: { op: 'preferences' } | { op: 'setPreference'; change: PreferenceChange }, marker: string) => {
+ setBusy(marker);
+ setError(null);
+ const result = (await browser.runtime
+ .sendMessage({ channel: BRIDGE_CHANNEL, ...request })
+ .catch(() => null)) as ActionResult<Preferences> | null;
+ setBusy(null);
+ if (!result?.ok) setError(result?.error.message ?? 'The daemon did not answer.');
+ }, []);
+
+ useEffect(() => {
+ if (connected && !settings) void ask({ op: 'preferences' }, 'load');
+ }, [connected, settings, ask]);
+
+ const write = (setting: string, value: GuardrailValue) =>
+ void ask({ op: 'setPreference', change: { kind: 'guardrail', setting, value } }, setting);
+
+ if (!daemon?.paired) {
+ return <Empty>Pair this browser to see what the agent is allowed to do. The Connection section has the steps.</Empty>;
+ }
+ if (!connected) {
+ return <Empty>The daemon is offline. Guardrails live in its config file, so they load when it reconnects.</Empty>;
+ }
+ if (!settings) {
+ return <Empty>{error ?? 'Reading the policy…'}</Empty>;
+ }
+
+ const editable = settings.rules.filter((rule) => !rule.locked);
+ const locked = settings.rules.filter((rule) => rule.locked);
+
+ return (
+ <div className="space-y-8">
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-ink-faint">
+ <span>
+ Overrides are written to <span className="font-mono text-ink-dim">{settings.configPath}</span>
+ </span>
+ <button
+ type="button"
+ onClick={() => void ask({ op: 'preferences' }, 'load')}
+ disabled={busy !== null}
+ className="ml-auto flex items-center gap-1 font-mono text-[10px] tracking-[0.14em] uppercase transition-colors hover:text-brand disabled:opacity-40"
+ >
+ <RefreshCw className={cn('size-3', busy === 'load' && 'animate-spin')} /> Reload
+ </button>
+ </div>
+
+ {error && <p className="rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive">{error}</p>}
+
+ <Group title="Rules" note="Each row starts on the default Browsentic ships. Switch one on to choose Allow, Ask or Block for it.">
+ {editable.map((rule) => (
+ <RuleRow key={rule.id} rule={rule} busy={busy === rule.id} onWrite={write} />
+ ))}
+ </Group>
+
+ <Group title="Everything else">
+ <Row
+ title="Fence page text"
+ note="Wraps every page result in a marker telling the model it is reading data, never instructions."
+ state={settings.fence.overridden ? (settings.fence.enabled ? 'On' : 'Off') : 'On (default)'}
+ on={settings.fence.overridden}
+ busy={busy === FENCE_SETTING}
+ onToggle={(next) => write(FENCE_SETTING, next ? settings.fence.enabled : null)}
+ >
+ {settings.fence.overridden && (
+ <Segmented
+ options={[
+ { value: true, label: 'Fence' },
+ { value: false, label: 'Do not fence' },
+ ]}
+ value={settings.fence.enabled}
+ onSelect={(next) => write(FENCE_SETTING, next)}
+ />
+ )}
+ </Row>
+ <Row
+ title="Callers with nobody to ask"
+ note="An MCP client outside the side panel cannot answer a prompt. This is what its “Ask” decisions become."
+ state={settings.unattended.overridden ? EFFECT_LABEL[settings.unattended.effect] : 'Block (default)'}
+ on={settings.unattended.overridden}
+ busy={busy === UNATTENDED_SETTING}
+ onToggle={(next) => write(UNATTENDED_SETTING, next ? settings.unattended.effect : null)}
+ >
+ {settings.unattended.overridden && (
+ <Segmented
+ options={[
+ { value: 'deny', label: 'Block' },
+ { value: 'allow', label: 'Allow' },
+ ]}
+ value={settings.unattended.effect}
+ onSelect={(next) => write(UNATTENDED_SETTING, next)}
+ />
+ )}
+ </Row>
+ {settings.hosts.length > 0 && (
+ <Fact title="Standing host allowlist" note="Added to every run’s scope. Edited in config.json.">
+ <p className="mt-1.5 font-mono text-[11px] leading-relaxed break-all text-ink-dim">{settings.hosts.join(' · ')}</p>
+ </Fact>
+ )}
+ </Group>
+
+ <Group title="Not switches" note="Shown so you know they are there. Hand-editing config.json still works, for whoever genuinely means it.">
+ <Fact
+ icon={<ShieldCheck className="size-3.5 text-brand" />}
+ title="Credential sealing"
+ badge="Always on"
+ note="Passwords, keys, tokens and cookies are replaced by a placeholder before a result leaves the browser. It is what keeps a plaintext credential off the socket in the first place."
+ />
+ {locked.map((rule) => (
+ <Fact
+ key={rule.id}
+ icon={<Lock className="size-3 text-ink-faint" />}
+ title={rule.title}
+ badge={EFFECT_LABEL[rule.fallback]}
+ note={rule.reason}
+ />
+ ))}
+ </Group>
+ </div>
+ );
+}
+
+function RuleRow({
+ rule,
+ busy,
+ onWrite,
+}: {
+ rule: GuardrailToggle;
+ busy: boolean;
+ onWrite: (setting: string, value: GuardrailValue) => void;
+}) {
+ const effect = rule.override ?? rule.fallback;
+ return (
+ <Row
+ title={rule.title}
+ note={rule.reason}
+ state={rule.override ? EFFECT_LABEL[rule.override] : `${EFFECT_LABEL[rule.fallback]} (default)`}
+ on={rule.override !== undefined}
+ busy={busy}
+ onToggle={(next) => onWrite(rule.id, next ? effect : null)}
+ >
+ {rule.override !== undefined && (
+ <Segmented
+ options={EFFECTS.map((value) => ({ value, label: EFFECT_LABEL[value] }))}
+ value={rule.override}
+ onSelect={(next) => onWrite(rule.id, next)}
+ />
+ )}
+ </Row>
+ );
+}
+
+function Group({ title, note, children }: { title: string; note?: string; children: ReactNode }) {
+ return (
+ <section className="space-y-2.5">
+ <header className="space-y-1">
+ <h3 className="font-mono text-[10px] tracking-[0.14em] text-ink-faint uppercase">{title}</h3>
+ {note && <p className="text-xs leading-relaxed text-ink-faint">{note}</p>}
+ </header>
+ <div className="panel-card divide-y divide-line overflow-hidden rounded-xl">{children}</div>
+ </section>
+ );
+}
+
+function Row({
+ title,
+ note,
+ state,
+ on,
+ busy,
+ onToggle,
+ children,
+}: {
+ title: string;
+ note: string;
+ state: string;
+ on: boolean;
+ busy: boolean;
+ onToggle: (next: boolean) => void;
+ children?: ReactNode;
+}) {
+ return (
+ <div className={cn('flex gap-6 px-4 py-3.5 transition-colors', on && 'bg-brand/5')}>
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium text-ink">{title}</p>
+ <p className="mt-0.5 text-xs leading-relaxed text-ink-faint">{note}</p>
+ {children}
+ </div>
+ <div className="flex shrink-0 items-start gap-2.5 pt-0.5">
+ <span className={cn('font-mono text-[10px] tracking-[0.1em] uppercase', on ? 'text-brand' : 'text-ink-faint')}>
+ {state}
+ </span>
+ {busy ? (
+ <Loader2 className="size-4 animate-spin text-ink-faint" />
+ ) : (
+ <Switch checked={on} label={`Override ${title}`} onChange={onToggle} />
+ )}
+ </div>
+ </div>
+ );
+}
+
+function Fact({
+ icon,
+ title,
+ badge,
+ note,
+ children,
+}: {
+ icon?: ReactNode;
+ title: string;
+ badge?: string;
+ note: string;
+ children?: ReactNode;
+}) {
+ return (
+ <div className="px-4 py-3.5">
+ <div className="flex items-center gap-2">
+ {icon}
+ <span className="text-sm font-medium text-ink-dim">{title}</span>
+ {badge && <span className="ml-auto font-mono text-[10px] tracking-[0.1em] text-ink-faint uppercase">{badge}</span>}
+ </div>
+ <p className="mt-0.5 text-xs leading-relaxed text-ink-faint">{note}</p>
+ {children}
+ </div>
+ );
+}
+
+function Segmented<T extends string | boolean>({
+ options,
+ value,
+ onSelect,
+}: {
+ options: { value: T; label: string }[];
+ value: T;
+ onSelect: (next: T) => void;
+}) {
+ return (
+ <div className="mt-2.5 inline-flex gap-0.5 rounded-lg border border-line bg-ground-2 p-0.5">
+ {options.map((option) => (
+ <button
+ key={String(option.value)}
+ type="button"
+ onClick={() => onSelect(option.value)}
+ aria-pressed={option.value === value}
+ className={cn(
+ 'rounded-md px-3 py-1 text-xs font-medium transition-colors',
+ option.value === value ? 'bg-brand/20 text-brand' : 'text-ink-faint hover:text-ink-dim',
+ )}
+ >
+ {option.label}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+function Empty({ children }: { children: ReactNode }) {
+ return <p className="panel-card rounded-xl px-6 py-10 text-center text-sm leading-relaxed text-ink-faint">{children}</p>;
+}
diff --git a/src/extension/components/panel-nav.tsx b/src/extension/components/panel-nav.tsx
index 3760291..d347251 100644
--- a/src/extension/components/panel-nav.tsx
+++ b/src/extension/components/panel-nav.tsx
@@ -1,5 +1,5 @@
import { useLayoutEffect, useRef, useState } from 'react';
-import { BookOpen, CalendarClock, Clapperboard, History, MessagesSquare, SlidersHorizontal, type LucideIcon } from 'lucide-react';
+import { BookOpen, CalendarClock, Clapperboard, History, MessagesSquare, type LucideIcon } from 'lucide-react';
import { type PanelTab } from '@/lib/rail/events';
import { cn } from '@/lib/utils';
@@ -14,7 +14,6 @@ export const TABS: { id: PanelTab; label: string; icon: LucideIcon }[] = [
{ id: 'skills', label: 'Skills', icon: BookOpen },
{ id: 'recordings', label: 'Recordings', icon: Clapperboard },
{ id: 'tasks', label: 'Schedules', icon: CalendarClock },
- { id: 'settings', label: 'Settings', icon: SlidersHorizontal },
];
/** Every label, then only the open tab's, then none — whichever the strip has room for. */
diff --git a/src/extension/components/settings-panel.tsx b/src/extension/components/settings-panel.tsx
deleted file mode 100644
index 4c5d21d..0000000
--- a/src/extension/components/settings-panel.tsx
+++ /dev/null
@@ -1,279 +0,0 @@
-import { useCallback, useEffect, useState } from 'react';
-import { Loader2, Lock, RefreshCw, ShieldCheck } from 'lucide-react';
-import { browser } from 'wxt/browser';
-
-import { ThemePicker } from '@/extension/components/theme-picker';
-import { Switch } from '@/extension/components/ui/switch';
-import { BRIDGE_CHANNEL, type ActionResult } from '@/lib/actions/protocol';
-import { useDaemonState } from '@/lib/bridge/use-daemon-state';
-import { useTheme } from '@/lib/bridge/use-theme';
-import {
- EFFECT_LABEL,
- FENCE_SETTING,
- UNATTENDED_SETTING,
- type GuardrailSettings,
- type GuardrailToggle,
- type GuardrailValue,
- type RuleEffect,
-} from '@/lib/settings/guardrails';
-import { cn } from '@/lib/utils';
-
-const EFFECTS: RuleEffect[] = ['allow', 'confirm', 'deny'];
-
-export function SettingsPanel() {
- const [theme, setTheme] = useTheme();
-
- return (
- <div className="space-y-6 px-3 pb-6">
- <ThemePicker theme={theme} onSelect={setTheme} />
- <Guardrails />
- </div>
- );
-}
-
-function Guardrails() {
- const daemon = useDaemonState();
- const connected = daemon?.connected ?? false;
- const [settings, setSettings] = useState<GuardrailSettings | null>(null);
- const [busy, setBusy] = useState<string | null>(null);
- const [error, setError] = useState<string | null>(null);
-
- const ask = useCallback(async (request: object, marker: string) => {
- setBusy(marker);
- setError(null);
- const result = (await browser.runtime
- .sendMessage({ channel: BRIDGE_CHANNEL, ...request })
- .catch(() => null)) as ActionResult<GuardrailSettings> | null;
- setBusy(null);
- if (result?.ok) setSettings(result.data);
- else setError(result?.error.message ?? 'The daemon did not answer.');
- }, []);
-
- useEffect(() => {
- if (connected) void ask({ op: 'guardrails' }, 'load');
- }, [connected, ask]);
-
- const write = (setting: string, value: GuardrailValue) =>
- void ask({ op: 'setGuardrail', setting, value }, setting);
-
- if (!daemon?.paired) {
- return <Empty>Pair a browser to see what this agent is allowed to do.</Empty>;
- }
- if (!connected) {
- return <Empty>The daemon is offline. Settings live in its config file, so they load when it reconnects.</Empty>;
- }
- if (!settings) {
- return <Empty>{error ?? 'Reading the policy…'}</Empty>;
- }
-
- return (
- <div className="space-y-5">
- <header className="space-y-1.5">
- <div className="flex items-center justify-between gap-2">
- <h2 className="font-mono text-[10px] tracking-[0.14em] text-ink-faint uppercase">Guardrails</h2>
- <button
- type="button"
- onClick={() => void ask({ op: 'guardrails' }, 'load')}
- disabled={busy !== null}
- className="flex items-center gap-1 font-mono text-[10px] tracking-[0.14em] text-ink-faint uppercase transition-colors hover:text-brand disabled:opacity-40"
- >
- <RefreshCw className={cn('size-3', busy === 'load' && 'animate-spin')} /> Reload
- </button>
- </div>
- <p className="text-[11px] leading-relaxed text-ink-faint">
- A row left off uses the default Browsentic ships. Turning one on writes an override to{' '}
- <span className="font-mono text-[10px] text-ink-dim">{settings.configPath}</span> and nothing else. A run
- takes its policy when it starts, so a change here applies to the next one.
- </p>
- </header>
-
- {error && <p className="text-[11px] text-destructive">{error}</p>}
-
- <section className="space-y-1.5">
- {settings.rules.map((rule) => (
- <RuleRow key={rule.id} rule={rule} busy={busy === rule.id} onWrite={write} />
- ))}
- </section>
-
- <section className="space-y-1.5">
- <h3 className="font-mono text-[10px] tracking-[0.14em] text-ink-faint uppercase">Everything else</h3>
-
- <Row
- title="Fence page text"
- note="Wraps every page result in a marker telling the model it is reading data, never instructions."
- state={settings.fence.overridden ? (settings.fence.enabled ? 'On' : 'Off') : 'On (default)'}
- on={settings.fence.overridden}
- busy={busy === FENCE_SETTING}
- onToggle={(next) => write(FENCE_SETTING, next ? settings.fence.enabled : null)}
- >
- {settings.fence.overridden && (
- <Segmented
- options={[
- { value: true, label: 'Fence' },
- { value: false, label: 'Do not fence' },
- ]}
- value={settings.fence.enabled}
- onSelect={(next) => write(FENCE_SETTING, next)}
- />
- )}
- </Row>
-
- <Row
- title="Callers with nobody to ask"
- note="An MCP client outside the side panel cannot answer a prompt. This is what its “Ask” decisions become."
- state={settings.unattended.overridden ? EFFECT_LABEL[settings.unattended.effect] : 'Block (default)'}
- on={settings.unattended.overridden}
- busy={busy === UNATTENDED_SETTING}
- onToggle={(next) => write(UNATTENDED_SETTING, next ? settings.unattended.effect : null)}
- >
- {settings.unattended.overridden && (
- <Segmented
- options={[
- { value: 'deny', label: 'Block' },
- { value: 'allow', label: 'Allow' },
- ]}
- value={settings.unattended.effect}
- onSelect={(next) => write(UNATTENDED_SETTING, next)}
- />
- )}
- </Row>
-
- <div className="rounded-md border border-line bg-surface/30 px-2.5 py-2">
- <div className="flex items-center gap-1.5">
- <ShieldCheck className="size-3 text-brand" />
- <span className="text-[11px] font-medium text-ink">Credential sealing</span>
- <span className="ml-auto font-mono text-[9px] tracking-[0.1em] text-brand uppercase">Always on</span>
- </div>
- <p className="mt-1 text-[11px] leading-relaxed text-ink-faint">
- Passwords, keys, tokens and cookies are replaced by a placeholder before a result leaves the browser.
- There is no switch: it is what keeps a plaintext credential off the socket in the first place.
- </p>
- </div>
-
- {settings.hosts.length > 0 && (
- <div className="rounded-md border border-line bg-surface/30 px-2.5 py-2">
- <span className="text-[11px] font-medium text-ink">Standing host allowlist</span>
- <p className="mt-1 font-mono text-[10px] leading-relaxed break-all text-ink-dim">
- {settings.hosts.join(' · ')}
- </p>
- <p className="mt-1 text-[11px] text-ink-faint">Added to every run’s scope. Edited in config.json.</p>
- </div>
- )}
- </section>
- </div>
- );
-}
-
-function RuleRow({
- rule,
- busy,
- onWrite,
-}: {
- rule: GuardrailToggle;
- busy: boolean;
- onWrite: (setting: string, value: GuardrailValue) => void;
-}) {
- if (rule.locked) {
- return (
- <div className="rounded-md border border-line bg-surface/20 px-2.5 py-2">
- <div className="flex items-center gap-1.5">
- <span className="text-[11px] font-medium text-ink-dim">{rule.title}</span>
- <span className="ml-auto flex items-center gap-1 font-mono text-[9px] tracking-[0.1em] text-ink-faint uppercase">
- <Lock className="size-2.5" />
- {EFFECT_LABEL[rule.fallback]}
- </span>
- </div>
- <p className="mt-1 text-[11px] leading-relaxed text-ink-faint">{rule.reason}</p>
- </div>
- );
- }
-
- const effect = rule.override ?? rule.fallback;
- return (
- <Row
- title={rule.title}
- note={rule.reason}
- state={rule.override ? EFFECT_LABEL[rule.override] : `${EFFECT_LABEL[rule.fallback]} (default)`}
- on={rule.override !== undefined}
- busy={busy}
- onToggle={(next) => onWrite(rule.id, next ? effect : null)}
- >
- {rule.override !== undefined && (
- <Segmented
- options={EFFECTS.map((value) => ({ value, label: EFFECT_LABEL[value] }))}
- value={rule.override}
- onSelect={(next) => onWrite(rule.id, next)}
- />
- )}
- </Row>
- );
-}
-
-function Row({
- title,
- note,
- state,
- on,
- busy,
- onToggle,
- children,
-}: {
- title: string;
- note: string;
- state: string;
- on: boolean;
- busy: boolean;
- onToggle: (next: boolean) => void;
- children?: React.ReactNode;
-}) {
- return (
- <div className={cn('rounded-md border px-2.5 py-2 transition-colors', on ? 'border-brand/30 bg-brand/5' : 'border-line bg-surface/20')}>
- <div className="flex items-center gap-2">
- <span className="text-[11px] font-medium text-ink">{title}</span>
- <span className="ml-auto flex items-center gap-1.5">
- <span className="font-mono text-[9px] tracking-[0.1em] text-ink-faint uppercase">{state}</span>
- {busy ? (
- <Loader2 className="size-3 animate-spin text-ink-faint" />
- ) : (
- <Switch checked={on} label={`Override ${title}`} onChange={onToggle} />
- )}
- </span>
- </div>
- <p className="mt-1 text-[11px] leading-relaxed text-ink-faint">{note}</p>
- {children}
- </div>
- );
-}
-
-function Segmented<T extends string | boolean>({
- options,
- value,
- onSelect,
-}: {
- options: { value: T; label: string }[];
- value: T;
- onSelect: (next: T) => void;
-}) {
- return (
- <div className="mt-2 flex gap-1">
- {options.map((option) => (
- <button
- key={String(option.value)}
- type="button"
- onClick={() => onSelect(option.value)}
- aria-pressed={option.value === value}
- className={cn(
- 'flex-1 rounded px-2 py-1 text-[10px] font-medium transition-colors',
- option.value === value ? 'bg-brand/20 text-brand' : 'bg-surface text-ink-faint hover:text-ink-dim',
- )}
- >
- {option.label}
- </button>
- ))}
- </div>
- );
-}
-
-function Empty({ children }: { children: React.ReactNode }) {
- return <p className="px-1 py-6 text-center text-[11px] leading-relaxed text-ink-faint">{children}</p>;
-}
diff --git a/src/extension/components/theme-picker.tsx b/src/extension/components/theme-picker.tsx
index 2c7cc56..c084291 100644
--- a/src/extension/components/theme-picker.tsx
+++ b/src/extension/components/theme-picker.tsx
@@ -7,53 +7,46 @@ const ACCENTS = ['bg-brand', 'bg-ember', 'bg-lime', 'bg-amber'];
export function ThemePicker({ theme, onSelect }: { theme: ThemeId; onSelect: (theme: ThemeId) => void }) {
return (
- <section className="space-y-2">
- <h3 className="font-mono text-[10px] tracking-[0.14em] text-ink-faint uppercase">Appearance</h3>
- <p className="text-[11px] leading-relaxed text-ink-faint">
- One click repaints the panel and the popup. Each tile is drawn in the theme it offers, so what you see is
- what you get.
- </p>
-
- <div className="grid grid-cols-2 gap-1.5">
- {THEMES.map(({ id, name, note }) => {
- const active = id === theme;
- return (
- <button
- key={id}
- type="button"
- data-theme={id}
- onClick={() => onSelect(id)}
- aria-pressed={active}
- className={cn(
- 'rounded-lg border bg-ground p-2 text-left transition-colors',
- active ? 'border-brand/60' : 'border-line hover:border-line-strong',
- )}
- >
- <div className="flex items-start gap-1.5">
- <div className="min-w-0 flex-1 space-y-1 rounded-md bg-surface px-1.5 py-1.5">
- <div className="h-1 w-9/12 rounded-full bg-ink/75" />
- <div className="h-1 w-6/12 rounded-full bg-ink/30" />
- <div className="flex gap-1 pt-1">
- {ACCENTS.map((accent) => (
- <span key={accent} className={cn('size-2 rounded-full', accent)} />
- ))}
- </div>
- </div>
- <span
- className={cn(
- 'mt-0.5 flex size-3.5 shrink-0 items-center justify-center rounded-full',
- active ? 'bg-brand text-ground' : 'border border-line-strong',
- )}
- >
- {active && <Check className="size-2.5" strokeWidth={3} />}
- </span>
+ <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
+ {THEMES.map(({ id, name, note }) => {
+ const active = id === theme;
+ return (
+ <button
+ key={id}
+ type="button"
+ data-theme={id}
+ onClick={() => onSelect(id)}
+ aria-pressed={active}
+ className={cn(
+ 'group rounded-xl border bg-ground p-3 text-left transition-colors',
+ active ? 'border-brand/60 glow-brand' : 'border-line hover:border-line-strong',
+ )}
+ >
+ <div className="dot-grid space-y-1.5 rounded-lg border border-line bg-surface p-3">
+ <div className="h-1.5 w-9/12 rounded-full bg-ink/75" />
+ <div className="h-1.5 w-6/12 rounded-full bg-ink/30" />
+ <div className="h-1.5 w-8/12 rounded-full bg-ink/20" />
+ <div className="flex gap-1.5 pt-2">
+ {ACCENTS.map((accent) => (
+ <span key={accent} className={cn('size-2.5 rounded-full', accent)} />
+ ))}
</div>
- <p className="mt-1.5 text-[11px] font-medium text-ink">{name}</p>
- <p className="text-[10px] leading-snug text-ink-faint">{note}</p>
- </button>
- );
- })}
- </div>
- </section>
+ </div>
+ <div className="mt-3 flex items-center gap-2">
+ <p className="flex-1 text-sm font-medium text-ink">{name}</p>
+ <span
+ className={cn(
+ 'flex size-4 shrink-0 items-center justify-center rounded-full',
+ active ? 'bg-brand text-ground' : 'border border-line-strong',
+ )}
+ >
+ {active && <Check className="size-3" strokeWidth={3} />}
+ </span>
+ </div>
+ <p className="mt-0.5 text-xs leading-snug text-ink-faint">{note}</p>
+ </button>
+ );
+ })}
+ </div>
);
}
diff --git a/src/extension/entrypoints/background.ts b/src/extension/entrypoints/background.ts
index a200e2e..ced5c38 100644
--- a/src/extension/entrypoints/background.ts
+++ b/src/extension/entrypoints/background.ts
@@ -20,7 +20,9 @@ import { serveToast } from '@/lib/bridge/toast';
import { serveHandsFree } from '@/lib/bridge/hands-free';
import { endHandsFree } from '@/lib/bridge/panel-view';
import { closeSidebar, openSidePanel } from '@/lib/bridge/side-panel';
+import { servePreferences } from '@/lib/bridge/preferences';
import { isAgentKind } from '@/lib/agents/catalog';
+import { isPreferenceChange } from '@/lib/settings/preferences';
import {
RECONNECT_ALARM,
chooseAgent,
@@ -30,10 +32,10 @@ import {
onWelcome,
pairDaemon,
readAgentState,
- readGuardrails,
+ readPreferences,
reportFocus,
readSkillCatalog,
- setGuardrail,
+ setPreference,
setUpAgent,
taskOp,
} from '@/lib/bridge/socket';
@@ -127,14 +129,14 @@ export default defineBackground(() => {
.catch((error) => sendResponse(failure('BRIDGE_ERROR', String(error))));
return true;
}
- if (message.op === 'guardrails') {
- readGuardrails()
+ if (message.op === 'preferences') {
+ readPreferences()
.then(sendResponse)
.catch((error) => sendResponse(failure('BRIDGE_ERROR', String(error))));
return true;
}
- if (message.op === 'setGuardrail' && typeof message.setting === 'string') {
- setGuardrail(message.setting, message.value)
+ if (message.op === 'setPreference' && isPreferenceChange(message.change)) {
+ setPreference(message.change)
.then(sendResponse)
.catch((error) => sendResponse(failure('BRIDGE_ERROR', String(error))));
return true;
@@ -180,7 +182,7 @@ export default defineBackground(() => {
sendResponse(
failure(
'INVALID_REQUEST',
- 'Expected {op:"describe"|"invoke"|"saveSkill"|"removeSkill"|"nameSession"|"recordEvents"|"recordingState"|"analyzeRecording"|"monitorSample"|"monitorState"|"listSkills"|"agentState"|"setAgent"|"setAgentModel"|"grantAgent"|"guardrails"|"setGuardrail"|"tasks"|"saveTask"|"deleteTask"|"runTaskNow"|"pauseTasks"|"pair"|"panelOpened"|"disconnect"}',
+ 'Expected {op:"describe"|"invoke"|"saveSkill"|"removeSkill"|"nameSession"|"recordEvents"|"recordingState"|"analyzeRecording"|"monitorSample"|"monitorState"|"listSkills"|"agentState"|"setAgent"|"setAgentModel"|"grantAgent"|"preferences"|"setPreference"|"tasks"|"saveTask"|"deleteTask"|"runTaskNow"|"pauseTasks"|"pair"|"panelOpened"|"disconnect"}',
),
);
return;
@@ -233,6 +235,7 @@ export default defineBackground(() => {
serveRail();
serveToast();
serveHandsFree();
+ servePreferences();
void syncRail();
onWelcome(() => {
diff --git a/src/extension/entrypoints/options/App.tsx b/src/extension/entrypoints/options/App.tsx
new file mode 100644
index 0000000..df4e0fe
--- /dev/null
+++ b/src/extension/entrypoints/options/App.tsx
@@ -0,0 +1,186 @@
+import { useEffect, useState, type ReactNode } from 'react';
+import { Link2, Palette, ShieldCheck, Sparkles, type LucideIcon } from 'lucide-react';
+import { browser } from 'wxt/browser';
+
+import { AgentPicker } from '@/extension/components/agent-picker';
+import { Wordmark } from '@/extension/components/brand';
+import { DaemonLink } from '@/extension/components/daemon-link';
+import { GuardrailSettings } from '@/extension/components/guardrail-settings';
+import { StatusPill, describeStatus } from '@/extension/components/status-pill';
+import { ThemePicker } from '@/extension/components/theme-picker';
+import { useDaemonState } from '@/lib/bridge/use-daemon-state';
+import { useTheme } from '@/lib/bridge/use-theme';
+import { cn } from '@/lib/utils';
+
+type SectionId = 'appearance' | 'guardrails' | 'agent' | 'connection';
+
+const SECTIONS: { id: SectionId; label: string; icon: LucideIcon; blurb: string }[] = [
+ {
+ id: 'appearance',
+ label: 'Appearance',
+ icon: Palette,
+ blurb: 'How the side panel, the popup and this page look. Every paired browser follows the same choice, and the Mac app can change it too.',
+ },
+ {
+ id: 'guardrails',
+ label: 'Guardrails',
+ icon: ShieldCheck,
+ blurb: 'What the agent may do without asking you first. A run takes its policy when it starts, so a change applies to the next one. The Mac app’s Settings tab edits the same rows.',
+ },
+ {
+ id: 'agent',
+ label: 'Agent',
+ icon: Sparkles,
+ blurb: 'Which agent CLI the side panel drives, and on which model. A switch here or in the Mac app reaches every paired browser.',
+ },
+ {
+ id: 'connection',
+ label: 'Connection',
+ icon: Link2,
+ blurb: 'The link between this browser and the Browsentic daemon on this computer.',
+ },
+];
+
+const isSection = (value: string): value is SectionId => SECTIONS.some((section) => section.id === value);
+
+function readSection(): SectionId {
+ const id = window.location.hash.slice(1);
+ return isSection(id) ? id : 'appearance';
+}
+
+function useSection(): SectionId {
+ const [section, setSection] = useState(readSection);
+ useEffect(() => {
+ const follow = () => setSection(readSection());
+ window.addEventListener('hashchange', follow);
+ return () => window.removeEventListener('hashchange', follow);
+ }, []);
+ return section;
+}
+
+export default function App() {
+ const daemon = useDaemonState();
+ const section = useSection();
+ const status = describeStatus(daemon);
+ const current = SECTIONS.find(({ id }) => id === section)!;
+
+ return (
+ <div className="min-h-screen md:flex">
+ <aside className="sticky top-0 z-10 border-b border-line bg-ground-2/85 backdrop-blur md:h-screen md:w-60 md:shrink-0 md:border-r md:border-b-0">
+ <div className="flex flex-col gap-3 px-4 pt-3 pb-2 md:h-full md:gap-8 md:px-5 md:py-6">
+ <div className="flex items-center gap-2">
+ <Wordmark className="flex-1" />
+ <StatusPill tone={status.tone} className="md:hidden">
+ {status.label}
+ </StatusPill>
+ </div>
+
+ <nav
+ aria-label="Settings sections"
+ className="-mx-1 flex gap-1 overflow-x-auto px-1 [scrollbar-width:none] md:flex-col md:overflow-visible [&::-webkit-scrollbar]:hidden"
+ >
+ {SECTIONS.map(({ id, label, icon: Icon }) => {
+ const active = id === section;
+ return (
+ <a
+ key={id}
+ href={`#${id}`}
+ aria-current={active ? 'page' : undefined}
+ className={cn(
+ 'inline-flex shrink-0 items-center gap-2 rounded-full px-3 py-1.5 text-xs font-medium transition-colors md:rounded-lg md:py-2 md:text-sm',
+ active ? 'bg-brand/12 text-brand' : 'text-ink-faint hover:bg-surface/60 hover:text-ink-dim',
+ )}
+ >
+ <Icon className="size-3.5 md:size-4" />
+ {label}
+ </a>
+ );
+ })}
+ </nav>
+
+ <footer className="mt-auto hidden space-y-2 md:block">
+ <StatusPill tone={status.tone}>{status.label}</StatusPill>
+ <p className="font-mono text-[10px] tracking-[0.1em] text-ink-faint">
+ v{browser.runtime.getManifest().version}
+ </p>
+ </footer>
+ </div>
+ </aside>
+
+ <main className="dot-grid min-w-0 flex-1">
+ <div className="mx-auto max-w-2xl px-4 py-8 md:px-10 md:py-14">
+ <header className="space-y-2">
+ <p className="font-mono text-[10px] tracking-[0.14em] text-ink-faint uppercase">Settings</p>
+ <h1 className="text-2xl font-semibold tracking-tight text-ink">{current.label}</h1>
+ <p className="text-sm leading-relaxed text-ink-dim">{current.blurb}</p>
+ </header>
+ <div key={section} className="enters mt-8">
+ {section === 'appearance' ? (
+ <Appearance />
+ ) : section === 'guardrails' ? (
+ <GuardrailSettings />
+ ) : section === 'agent' ? (
+ <Agent />
+ ) : (
+ <Connection />
+ )}
+ </div>
+ </div>
+ </main>
+ </div>
+ );
+}
+
+function Appearance() {
+ const [theme, setTheme] = useTheme();
+ const daemon = useDaemonState();
+
+ return (
+ <div className="space-y-4">
+ <ThemePicker theme={theme} onSelect={setTheme} />
+ <p className="text-xs leading-relaxed text-ink-faint">
+ {daemon?.connected
+ ? 'Kept in the daemon’s config, so every paired browser and the Mac app see the change at once.'
+ : 'Kept in this browser for now, and handed to the daemon the next time it connects.'}
+ </p>
+ </div>
+ );
+}
+
+function Agent() {
+ const daemon = useDaemonState();
+ if (!daemon?.paired) {
+ return (
+ <Card>
+ <p className="py-6 text-center text-sm leading-relaxed text-ink-faint">
+ Pair this browser first — the agent runs beside the daemon, not in here.{' '}
+ <a href="#connection" className="text-brand hover:underline">
+ Set up the connection
+ </a>
+ </p>
+ </Card>
+ );
+ }
+ return (
+ <Card>
+ <AgentPicker />
+ </Card>
+ );
+}
+
+function Connection() {
+ return (
+ <div className="space-y-4">
+ <Card>
+ <DaemonLink />
+ </Card>
+ <p className="text-xs leading-relaxed text-ink-faint">
+ On a Mac, the Browsentic app’s Browsers tab also hands out pairing codes and lists every paired browser.
+ </p>
+ </div>
+ );
+}
+
+function Card({ children }: { children: ReactNode }) {
+ return <div className="panel-card rounded-xl p-5">{children}</div>;
+}
diff --git a/src/extension/entrypoints/options/index.html b/src/extension/entrypoints/options/index.html
new file mode 100644
index 0000000..7d8ac1f
--- /dev/null
+++ b/src/extension/entrypoints/options/index.html
@@ -0,0 +1,14 @@
+<!doctype html>
+<html lang="en" data-theme="ember" style="background-color: #1a1512">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="color-scheme" content="dark" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Browsentic — Settings</title>
+ <meta name="manifest.open_in_tab" content="true" />
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="./main.tsx"></script>
+ </body>
+</html>
diff --git a/src/extension/entrypoints/options/main.tsx b/src/extension/entrypoints/options/main.tsx
new file mode 100644
index 0000000..0026177
--- /dev/null
+++ b/src/extension/entrypoints/options/main.tsx
@@ -0,0 +1,13 @@
+import React from 'react';
+import ReactDOM from 'react-dom/client';
+import App from './App';
+import { mountTheme } from '@/lib/bridge/theme';
+import '@/extension/assets/globals.css';
+
+mountTheme();
+
+ReactDOM.createRoot(document.getElementById('root')!).render(
+ <React.StrictMode>
+ <App />
+ </React.StrictMode>,
+);
diff --git a/src/extension/entrypoints/popup/App.tsx b/src/extension/entrypoints/popup/App.tsx
index a652ab5..082db89 100644
--- a/src/extension/entrypoints/popup/App.tsx
+++ b/src/extension/entrypoints/popup/App.tsx
@@ -1,5 +1,5 @@
import { useState } from 'react';
-import { Mic, MicOff, PanelRightOpen, Send } from 'lucide-react';
+import { Mic, MicOff, PanelRightOpen, Send, SlidersHorizontal } from 'lucide-react';
import { AgentPicker } from '@/extension/components/agent-picker';
import { Wordmark } from '@/extension/components/brand';
@@ -83,6 +83,15 @@ export default function App() {
<header className="flex items-center gap-2 px-4 py-3">
<Wordmark className="flex-1" />
<StatusPill tone={status.tone}>{status.label}</StatusPill>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ title="Settings"
+ aria-label="Open Browsentic settings in a tab"
+ onClick={() => void browser.runtime.openOptionsPage()}
+ >
+ <SlidersHorizontal className="size-3.5" />
+ </Button>
</header>
{paired && (
diff --git a/src/extension/entrypoints/sidepanel/App.tsx b/src/extension/entrypoints/sidepanel/App.tsx
index 6acb0eb..a3a85ae 100644
--- a/src/extension/entrypoints/sidepanel/App.tsx
+++ b/src/extension/entrypoints/sidepanel/App.tsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { ArrowDown, PanelRightClose, PictureInPicture2, SquarePen } from 'lucide-react';
+import { ArrowDown, PanelRightClose, PictureInPicture2, SlidersHorizontal, SquarePen } from 'lucide-react';
import { browser } from 'wxt/browser';
import { invokeInActiveTab } from '@/lib/actions/client';
@@ -21,7 +21,6 @@ import { RunTimeline } from '@/extension/components/run-timeline';
import { KeepToolPrompt, SavedToolList } from '@/extension/components/saved-tools';
import { SessionList } from '@/extension/components/session-list';
import { SessionRail } from '@/extension/components/session-rail';
-import { SettingsPanel } from '@/extension/components/settings-panel';
import { SiteMapReview } from '@/extension/components/site-map-review';
import { SkillsPanel } from '@/extension/components/skills-panel';
import { TaskPanel } from '@/extension/components/task-panel';
@@ -312,6 +311,15 @@ export default function App() {
<PictureInPicture2 className="size-3.5" />
</Button>
)}
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ title="Settings"
+ aria-label="Open Browsentic settings in a tab"
+ onClick={() => void browser.runtime.openOptionsPage()}
+ >
+ <SlidersHorizontal className="size-3.5" />
+ </Button>
<Button
variant="ghost"
size="icon-sm"
@@ -389,8 +397,6 @@ export default function App() {
/>
) : tab === 'skills' ? (
<SkillsPanel tabUrl={tabUrl} connected={connected} onMapSite={mapSite} mapping={run.running} />
- ) : tab === 'settings' ? (
- <SettingsPanel />
) : tab === 'tasks' ? (
<TaskPanel
tasks={tasks}
diff --git a/src/lib/actions/protocol.ts b/src/lib/actions/protocol.ts
index 35e9dc4..687e4d5 100644
--- a/src/lib/actions/protocol.ts
+++ b/src/lib/actions/protocol.ts
@@ -4,7 +4,7 @@ import type { FileReport, FileVerdict } from '@/lib/files/report';
import type { MonitorSample } from '@/lib/monitor/events';
import type { RecordedEvent } from '@/lib/recordings/events';
import type { RecordingWorkflow } from '@/lib/recordings/workflow';
-import type { GuardrailSettings, GuardrailValue } from '@/lib/settings/guardrails';
+import type { PreferenceChange, Preferences } from '@/lib/settings/preferences';
import type { SkillCategory, SkillDraft } from '@/lib/skills/format';
import type { SiteMapDraft } from '@/lib/skills/site-map';
import type { TaskContext, TaskList, TaskOrder, TaskResult } from '@/lib/schedules/task';
@@ -12,7 +12,7 @@ import type { TaskContext, TaskList, TaskOrder, TaskResult } from '@/lib/schedul
export const ACTION_CHANNEL = 'browsentic/action';
export const BRIDGE_CHANNEL = 'browsentic/bridge';
-export const SOCKET_PROTOCOL_VERSION = 20;
+export const SOCKET_PROTOCOL_VERSION = 21;
export const EXTERNAL_RUN_ID = 'external';
@@ -46,8 +46,8 @@ export type BridgeRequest =
| { channel: typeof BRIDGE_CHANNEL; op: 'setAgent'; agent: AgentKind }
| { channel: typeof BRIDGE_CHANNEL; op: 'setAgentModel'; agent: AgentKind; model: string | null }
| { channel: typeof BRIDGE_CHANNEL; op: 'grantAgent'; agent: AgentKind }
- | { channel: typeof BRIDGE_CHANNEL; op: 'guardrails' }
- | { channel: typeof BRIDGE_CHANNEL; op: 'setGuardrail'; setting: string; value: GuardrailValue }
+ | { channel: typeof BRIDGE_CHANNEL; op: 'preferences' }
+ | { channel: typeof BRIDGE_CHANNEL; op: 'setPreference'; change: PreferenceChange }
| { channel: typeof BRIDGE_CHANNEL; op: 'tasks' }
| { channel: typeof BRIDGE_CHANNEL; op: 'saveTask'; task: unknown }
| { channel: typeof BRIDGE_CHANNEL; op: 'deleteTask'; taskId: string }
@@ -254,9 +254,9 @@ export type SocketFrame =
| { t: 'agentInfo'; id: string; result: ActionResult<AgentState> }
| { t: 'listSkills'; id: string; refresh?: boolean }
| { t: 'skillCatalog'; id: string; result: ActionResult<SkillCatalog> }
- | { t: 'guardrails'; id: string }
- | { t: 'setGuardrail'; id: string; setting: string; value: GuardrailValue }
- | { t: 'guardrailInfo'; id: string; result: ActionResult<GuardrailSettings> }
+ | { t: 'preferences'; id: string }
+ | { t: 'setPreference'; id: string; change: PreferenceChange }
+ | { t: 'preferencesInfo'; id: string; result: ActionResult<Preferences> }
| { t: 'tasks'; id: string }
| { t: 'saveTask'; id: string; task: unknown }
| { t: 'deleteTask'; id: string; taskId: string }
@@ -296,8 +296,8 @@ export const EXTENSION_REQUEST_FRAMES = [
'setAgentModel',
'grantAgent',
'listSkills',
- 'guardrails',
- 'setGuardrail',
+ 'preferences',
+ 'setPreference',
'tasks',
'saveTask',
'deleteTask',
diff --git a/src/lib/bridge/panel-view.ts b/src/lib/bridge/panel-view.ts
index 9cceeca..25b96df 100644
--- a/src/lib/bridge/panel-view.ts
+++ b/src/lib/bridge/panel-view.ts
@@ -1,5 +1,5 @@
import { browser } from 'wxt/browser';
-import type { PanelTab } from '@/lib/rail/events';
+import { isPanelTab, type PanelTab } from '@/lib/rail/events';
export const PANEL_COLLAPSED_KEY = 'browsentic/panelCollapsed';
export const PANEL_TAB_KEY = 'browsentic/panelTab';
@@ -40,5 +40,5 @@ export const endHandsFree = (): Promise<void> => writeHandsFree(null);
export async function readPanelTab(): Promise<PanelTab> {
const stored = await browser.storage.local.get(PANEL_TAB_KEY);
const tab = stored[PANEL_TAB_KEY];
- return typeof tab === 'string' ? (tab as PanelTab) : 'chat';
+ return isPanelTab(tab) ? tab : 'chat';
}
diff --git a/src/lib/bridge/preferences.test.ts b/src/lib/bridge/preferences.test.ts
new file mode 100644
index 0000000..1d5c677
--- /dev/null
+++ b/src/lib/bridge/preferences.test.ts
@@ -0,0 +1,78 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { fakeBrowser } from 'wxt/testing';
+import { failure, success } from '@/lib/actions/protocol';
+import type { GuardrailSettings } from '@/lib/settings/guardrails';
+import type { Preferences } from '@/lib/settings/preferences';
+import type { ThemeId } from '@/lib/settings/theme';
+
+const socket = vi.hoisted(() => ({
+ listener: null as ((preferences: Preferences) => void) | null,
+ setPreference: vi.fn(),
+}));
+
+vi.mock('./socket', () => ({
+ DAEMON_STATE_KEY: 'browsentic/daemon',
+ onPreferences: (listener: (preferences: Preferences) => void) => (socket.listener = listener),
+ setPreference: socket.setPreference,
+}));
+
+const { THEME_UNSYNCED_KEY, servePreferences } = await import('./preferences');
+
+const THEME_KEY = 'browsentic/theme';
+const guardrails = {} as GuardrailSettings;
+
+/** What the socket does with a pushed snapshot: record it as the daemon's state, then hand it over. */
+async function push(theme: ThemeId | null): Promise<void> {
+ const preferences = { theme, guardrails };
+ await fakeBrowser.storage.session.set({ 'browsentic/daemon': { connected: true, paired: true, preferences, lastChangeAt: 0 } });
+ socket.listener?.(preferences);
+}
+
+const local = async () => (await fakeBrowser.storage.local.get([THEME_KEY, THEME_UNSYNCED_KEY])) as Record<string, unknown>;
+const handed = () => socket.setPreference.mock.calls.map(([change]) => change.theme);
+
+describe('one theme for this browser and config.json', () => {
+ beforeEach(() => {
+ fakeBrowser.reset();
+ socket.setPreference.mockReset().mockImplementation(async (change) => success({ theme: change.theme, guardrails }));
+ servePreferences();
+ });
+
+ it('hands a theme picked before pairing to a daemon that has none', async () => {
+ await fakeBrowser.storage.local.set({ [THEME_KEY]: 'phosphor' });
+ socket.setPreference.mockClear();
+ await push(null);
+ await vi.waitFor(() => expect(handed()).toEqual(['phosphor']));
+ });
+
+ it('hands nothing over when nobody ever picked one, so config.json stays free of a default', async () => {
+ await push(null);
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect([handed(), await local()]).toEqual([[], {}]);
+ });
+
+ it('takes the daemon’s theme, and does not send that change straight back', async () => {
+ await fakeBrowser.storage.local.set({ [THEME_KEY]: 'ember' });
+ await push('ember');
+ socket.setPreference.mockClear();
+
+ await push('daylight');
+ await vi.waitFor(async () => expect((await local())[THEME_KEY]).toBe('daylight'));
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(handed()).toEqual([]);
+ });
+
+ it('keeps a pick made while the daemon was unreachable, and hands it over at the next connect', async () => {
+ await push('ember');
+ await vi.waitFor(async () => expect((await local())[THEME_KEY]).toBe('ember'));
+ socket.setPreference.mockResolvedValue(failure('EXTENSION_OFFLINE', 'No Browsentic daemon is attached'));
+ await fakeBrowser.storage.local.set({ [THEME_KEY]: 'midnight' });
+ await vi.waitFor(async () => expect((await local())[THEME_UNSYNCED_KEY]).toBe(true));
+
+ socket.setPreference.mockImplementation(async (change) => success({ theme: change.theme, guardrails }));
+ socket.setPreference.mockClear();
+ await push('ember');
+ await vi.waitFor(() => expect(handed()).toEqual(['midnight']));
+ await vi.waitFor(async () => expect(await local()).toEqual({ [THEME_KEY]: 'midnight' }));
+ });
+});
diff --git a/src/lib/bridge/preferences.ts b/src/lib/bridge/preferences.ts
new file mode 100644
index 0000000..cb86783
--- /dev/null
+++ b/src/lib/bridge/preferences.ts
@@ -0,0 +1,43 @@
+import { browser } from 'wxt/browser';
+import type { Preferences } from '@/lib/settings/preferences';
+import { asTheme, type ThemeId } from '@/lib/settings/theme';
+import { DAEMON_STATE_KEY, onPreferences, setPreference, type DaemonState } from './socket';
+import { THEME_KEY, readChosenTheme } from './theme';
+
+/** Set while this browser holds a theme the daemon has not been told, because it could not be reached. */
+export const THEME_UNSYNCED_KEY = 'browsentic/theme.unsynced';
+
+/**
+ * Keeps this browser's theme and config.json's in step. What the daemon pushes wins, except
+ * over a pick made here that it has not heard yet — made while it was unreachable, or before
+ * this browser was ever paired — which is handed over at the next connect instead.
+ */
+export function servePreferences(): void {
+ onPreferences((preferences) => void adopt(preferences));
+ browser.storage.local.onChanged.addListener((changes) => {
+ if (THEME_KEY in changes) void forward(asTheme(changes[THEME_KEY].newValue));
+ });
+}
+
+async function adopt({ theme }: Preferences): Promise<void> {
+ const [chosen, unsynced] = await Promise.all([readChosenTheme(), readUnsynced()]);
+ if (chosen && chosen !== theme && (unsynced || theme === null)) return hand(chosen);
+ if (unsynced) await browser.storage.local.remove(THEME_UNSYNCED_KEY);
+ if (theme && theme !== chosen) await browser.storage.local.set({ [THEME_KEY]: theme });
+}
+
+async function forward(theme: ThemeId): Promise<void> {
+ const stored = await browser.storage.session.get(DAEMON_STATE_KEY);
+ if ((stored[DAEMON_STATE_KEY] as DaemonState | undefined)?.preferences?.theme === theme) return;
+ await hand(theme);
+}
+
+async function hand(theme: ThemeId): Promise<void> {
+ const result = await setPreference({ kind: 'theme', theme });
+ if (result.ok) await browser.storage.local.remove(THEME_UNSYNCED_KEY);
+ else await browser.storage.local.set({ [THEME_UNSYNCED_KEY]: true });
+}
+
+async function readUnsynced(): Promise<boolean> {
+ return (await browser.storage.local.get(THEME_UNSYNCED_KEY))[THEME_UNSYNCED_KEY] === true;
+}
diff --git a/src/lib/bridge/socket.ts b/src/lib/bridge/socket.ts
index dcda423..4c2fdcb 100644
--- a/src/lib/bridge/socket.ts
+++ b/src/lib/bridge/socket.ts
@@ -27,7 +27,7 @@ import {
} from '@/lib/actions/protocol';
import type { AgentKind, AgentState } from '@/lib/agents/catalog';
import type { FileReport } from '@/lib/files/report';
-import type { GuardrailSettings, GuardrailValue } from '@/lib/settings/guardrails';
+import type { PreferenceChange, Preferences } from '@/lib/settings/preferences';
import type { SkillDraft } from '@/lib/skills/format';
import type { SiteMapDraft } from '@/lib/skills/site-map';
import type { TaskList, TaskOrder, TaskResult } from '@/lib/schedules/task';
@@ -79,6 +79,8 @@ export interface DaemonState {
agent?: AgentState;
/** What the / picker offers: the daemon's skills plus the active agent CLI's own. Pushed on connect and when either changes. */
skillCatalog?: SkillCatalog;
+ /** The settings config.json holds for every surface. Pushed on connect and whenever the file changes. */
+ preferences?: Preferences;
error?: string;
lastChangeAt: number;
}
@@ -93,6 +95,11 @@ let runListener: ((runId: string, event: RunEvent) => void) | null = null;
const welcomeListeners = new Set<() => void>();
let draftListener: ((runId: string, draft: SiteMapDraft) => void) | null = null;
let taskRunner: ((order: TaskOrder) => Promise<ActionResult>) | null = null;
+let preferencesListener: ((preferences: Preferences) => void) | null = null;
+
+export function onPreferences(listener: (preferences: Preferences) => void): void {
+ preferencesListener = listener;
+}
export function onTaskOrder(runner: (order: TaskOrder) => Promise<ActionResult>): void {
taskRunner = runner;
@@ -287,28 +294,28 @@ export function readSkillCatalog(refresh = false): Promise<ActionResult<SkillCat
});
}
-const pendingGuardrailOps = new Map<string, (result: ActionResult<GuardrailSettings>) => void>();
+const pendingPreferenceOps = new Map<string, (result: ActionResult<Preferences>) => void>();
-export function readGuardrails(): Promise<ActionResult<GuardrailSettings>> {
- return guardrailOp({ t: 'guardrails', id: crypto.randomUUID() });
+export function readPreferences(): Promise<ActionResult<Preferences>> {
+ return preferenceOp({ t: 'preferences', id: crypto.randomUUID() });
}
-export function setGuardrail(setting: string, value: GuardrailValue): Promise<ActionResult<GuardrailSettings>> {
- return guardrailOp({ t: 'setGuardrail', id: crypto.randomUUID(), setting, value });
+export function setPreference(change: PreferenceChange): Promise<ActionResult<Preferences>> {
+ return preferenceOp({ t: 'setPreference', id: crypto.randomUUID(), change });
}
-function guardrailOp(
- frame: Extract<SocketFrame, { t: 'guardrails' | 'setGuardrail' }>,
-): Promise<ActionResult<GuardrailSettings>> {
+function preferenceOp(
+ frame: Extract<SocketFrame, { t: 'preferences' | 'setPreference' }>,
+): Promise<ActionResult<Preferences>> {
if (!post(frame)) {
return Promise.resolve(failure('EXTENSION_OFFLINE', 'No Browsentic daemon is attached — pair the browser first.'));
}
return new Promise((resolve) => {
const timer = setTimeout(() => {
- pendingGuardrailOps.delete(frame.id);
+ pendingPreferenceOps.delete(frame.id);
resolve(failure('TIMEOUT', 'The daemon did not answer in time.'));
}, AGENT_TIMEOUT_MS);
- pendingGuardrailOps.set(frame.id, (result) => {
+ pendingPreferenceOps.set(frame.id, (result) => {
clearTimeout(timer);
resolve(result);
});
@@ -644,9 +651,11 @@ async function handle(ws: WebSocket, raw: string, attempt: Attempt): Promise<voi
return;
}
- case 'guardrailInfo': {
- pendingGuardrailOps.get(frame.id)?.(frame.result);
- pendingGuardrailOps.delete(frame.id);
+ case 'preferencesInfo': {
+ if (frame.result.ok) await setState({ preferences: frame.result.data, lastChangeAt: Date.now() });
+ pendingPreferenceOps.get(frame.id)?.(frame.result);
+ pendingPreferenceOps.delete(frame.id);
+ if (frame.result.ok) preferencesListener?.(frame.result.data);
return;
}
diff --git a/src/lib/bridge/theme.ts b/src/lib/bridge/theme.ts
index aed37c2..4cc689a 100644
--- a/src/lib/bridge/theme.ts
+++ b/src/lib/bridge/theme.ts
@@ -1,15 +1,8 @@
import { browser } from 'wxt/browser';
+import { asTheme, isThemeId, type ThemeId } from '@/lib/settings/theme';
-export type ThemeId = 'ember' | 'midnight' | 'phosphor' | 'daylight';
+export { THEMES, DEFAULT_THEME, asTheme, type ThemeId } from '@/lib/settings/theme';
-export const THEMES: { id: ThemeId; name: string; note: string }[] = [
- { id: 'ember', name: 'Ember', note: 'Warm near-black, cyan brand.' },
- { id: 'midnight', name: 'Midnight', note: 'Cool blue-black, violet brand.' },
- { id: 'phosphor', name: 'Phosphor', note: 'A green CRT, grain turned up.' },
- { id: 'daylight', name: 'Daylight', note: 'Ink on paper, for a bright room.' },
-];
-
-export const DEFAULT_THEME: ThemeId = 'ember';
export const THEME_KEY = 'browsentic/theme';
/* storage.local answers a tick after the page has already painted, which on a
@@ -18,12 +11,14 @@ export const THEME_KEY = 'browsentic/theme';
and storage.local stays the truth that corrects it. */
const PAINT_HINT = 'browsentic/theme.paint';
-export function asTheme(value: unknown): ThemeId {
- return THEMES.some((theme) => theme.id === value) ? (value as ThemeId) : DEFAULT_THEME;
+export async function readTheme(): Promise<ThemeId> {
+ return asTheme(await readChosenTheme());
}
-export async function readTheme(): Promise<ThemeId> {
- return asTheme((await browser.storage.local.get(THEME_KEY))[THEME_KEY]);
+/** Null until someone picks one, so a first pairing can tell a choice from the default. */
+export async function readChosenTheme(): Promise<ThemeId | null> {
+ const stored = (await browser.storage.local.get(THEME_KEY))[THEME_KEY];
+ return isThemeId(stored) ? stored : null;
}
/* Clearing the inline colour hands the ground back to the stylesheet: index.html
diff --git a/src/lib/bridge/use-panel-view.ts b/src/lib/bridge/use-panel-view.ts
index 838f880..97990f1 100644
--- a/src/lib/bridge/use-panel-view.ts
+++ b/src/lib/bridge/use-panel-view.ts
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useState } from 'react';
import { browser } from 'wxt/browser';
-import type { PanelTab } from '@/lib/rail/events';
+import { isPanelTab, type PanelTab } from '@/lib/rail/events';
import { PANEL_COLLAPSED_KEY, PANEL_TAB_KEY } from './panel-view';
export function usePanelCollapsed(): [boolean, (collapsed: boolean) => void] {
@@ -8,7 +8,7 @@ export function usePanelCollapsed(): [boolean, (collapsed: boolean) => void] {
}
export function usePanelTab(): [PanelTab, (tab: PanelTab) => void] {
- return useStoredLocal(PANEL_TAB_KEY, 'chat' as PanelTab, (value): value is PanelTab => typeof value === 'string');
+ return useStoredLocal<PanelTab>(PANEL_TAB_KEY, 'chat', isPanelTab);
}
function useStoredLocal<T>(
diff --git a/src/lib/rail/events.test.ts b/src/lib/rail/events.test.ts
new file mode 100644
index 0000000..aeb692c
--- /dev/null
+++ b/src/lib/rail/events.test.ts
@@ -0,0 +1,12 @@
+import { describe, expect, test } from 'vitest';
+import { PANEL_TABS, RAIL_TABS, isPanelTab } from './events';
+
+describe('the panel’s tabs', () => {
+ test('a Settings tab stored before it moved to its own page is not one, so the panel opens on Chat', () => {
+ expect([isPanelTab('settings'), isPanelTab(undefined), isPanelTab('tasks')]).toEqual([false, false, true]);
+ });
+
+ test('the rail on the page offers exactly the panel’s tabs, in the same order', () => {
+ expect(RAIL_TABS.map(({ id }) => id)).toEqual([...PANEL_TABS]);
+ });
+});
diff --git a/src/lib/rail/events.ts b/src/lib/rail/events.ts
index 2ea1de3..43b94ea 100644
--- a/src/lib/rail/events.ts
+++ b/src/lib/rail/events.ts
@@ -1,8 +1,15 @@
-import type { ThemeId } from '@/lib/bridge/theme';
+import type { ThemeId } from '@/lib/settings/theme';
export const RAIL_CHANNEL = 'browsentic/rail';
-export type PanelTab = 'chat' | 'history' | 'skills' | 'recordings' | 'tasks' | 'settings';
+export const PANEL_TABS = ['chat', 'history', 'skills', 'recordings', 'tasks'] as const;
+
+export type PanelTab = (typeof PANEL_TABS)[number];
+
+/** A tab the panel no longer has — Settings moved to its own page — opens on Chat instead. */
+export function isPanelTab(value: unknown): value is PanelTab {
+ return (PANEL_TABS as readonly unknown[]).includes(value);
+}
export type RailTone = 'off' | 'pending' | 'live' | 'busy' | 'listening' | 'warn';
@@ -91,21 +98,6 @@ export const RAIL_TABS: { id: PanelTab; label: string; paths: string[] }[] = [
'M22 16a6 6 0 1 1-12 0 6 6 0 0 1 12 0',
],
},
- {
- id: 'settings',
- label: 'Settings',
- paths: [
- 'M10 5H3',
- 'M12 19H3',
- 'M14 3v4',
- 'M16 17v4',
- 'M21 12h-9',
- 'M21 19h-5',
- 'M21 5h-7',
- 'M8 10v4',
- 'M8 12H3',
- ],
- },
];
/** The panel's tokens, spelled out — a content script has no stylesheet to read them
diff --git a/src/lib/settings/preferences.test.ts b/src/lib/settings/preferences.test.ts
new file mode 100644
index 0000000..b8449a1
--- /dev/null
+++ b/src/lib/settings/preferences.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, test } from 'vitest';
+import { isPreferenceChange } from './preferences';
+
+describe('what a settings screen may ask the daemon to change', () => {
+ test('a theme the extension has, and a guardrail set to an effect, a switch or back to its default', () => {
+ const changes = [
+ { kind: 'theme', theme: 'phosphor' },
+ { kind: 'guardrail', setting: 'form-submission', value: 'confirm' },
+ { kind: 'guardrail', setting: 'fence', value: false },
+ { kind: 'guardrail', setting: 'file-upload', value: null },
+ ];
+ expect(changes.map(isPreferenceChange)).toEqual([true, true, true, true]);
+ });
+
+ test('anything else is refused before it reaches config.json', () => {
+ const changes = [
+ null,
+ 'theme',
+ { kind: 'theme', theme: 'solarized' },
+ { kind: 'guardrail', setting: 'form-submission', value: 'sometimes' },
+ { kind: 'guardrail', value: 'allow' },
+ { kind: 'agent', agent: 'codex' },
+ ];
+ expect(changes.map(isPreferenceChange)).toEqual([false, false, false, false, false, false]);
+ });
+});
diff --git a/src/lib/settings/preferences.ts b/src/lib/settings/preferences.ts
new file mode 100644
index 0000000..e8705ae
--- /dev/null
+++ b/src/lib/settings/preferences.ts
@@ -0,0 +1,29 @@
+/**
+ * Everything a person can set from either the extension's settings page or the Mac app. The
+ * daemon keeps it in config.json and hands the same snapshot to both, after every change,
+ * whichever side made it — or a hand edit of the file.
+ */
+
+import { isThemeId, type ThemeId } from './theme';
+import { isRuleEffect, type GuardrailSettings, type GuardrailValue } from './guardrails';
+
+export interface Preferences {
+ /** Null until someone picks one; a browser that already has a choice then hands it over. */
+ readonly theme: ThemeId | null;
+ readonly guardrails: GuardrailSettings;
+}
+
+export type PreferenceChange =
+ | { readonly kind: 'theme'; readonly theme: ThemeId }
+ | { readonly kind: 'guardrail'; readonly setting: string; readonly value: GuardrailValue };
+
+export function isPreferenceChange(value: unknown): value is PreferenceChange {
+ if (typeof value !== 'object' || value === null) return false;
+ const change = value as { kind?: unknown; theme?: unknown; setting?: unknown; value?: unknown };
+ if (change.kind === 'theme') return isThemeId(change.theme);
+ return (
+ change.kind === 'guardrail' &&
+ typeof change.setting === 'string' &&
+ (change.value === null || typeof change.value === 'boolean' || isRuleEffect(change.value))
+ );
+}
diff --git a/src/lib/settings/theme.ts b/src/lib/settings/theme.ts
new file mode 100644
index 0000000..9a76f87
--- /dev/null
+++ b/src/lib/settings/theme.ts
@@ -0,0 +1,24 @@
+/**
+ * The extension's four looks, named once for every side that sets one: the extension's own
+ * settings page, the Mac app, and config.json, where the daemon keeps the choice so each
+ * paired browser opens in the same one.
+ */
+
+export type ThemeId = 'ember' | 'midnight' | 'phosphor' | 'daylight';
+
+export const THEMES: { id: ThemeId; name: string; note: string }[] = [
+ { id: 'ember', name: 'Ember', note: 'Warm near-black, cyan brand.' },
+ { id: 'midnight', name: 'Midnight', note: 'Cool blue-black, violet brand.' },
+ { id: 'phosphor', name: 'Phosphor', note: 'A green CRT, grain turned up.' },
+ { id: 'daylight', name: 'Daylight', note: 'Ink on paper, for a bright room.' },
+];
+
+export const DEFAULT_THEME: ThemeId = 'ember';
+
+export function isThemeId(value: unknown): value is ThemeId {
+ return THEMES.some((theme) => theme.id === value);
+}
+
+export function asTheme(value: unknown): ThemeId {
+ return isThemeId(value) ? value : DEFAULT_THEME;
+}