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
feat(settings): a profile of the user's details and standing instructions, kept by the daemon in profile.json beside config.json and shared with every paired browser over the preferences channel
Shahriar8cbee6afe5e8
diff --git a/src/daemon/preferences.ts b/src/daemon/preferences.tsindex dbe1072..b690f47 100644--- a/src/daemon/preferences.ts+++ b/src/daemon/preferences.ts@@ -1,34 +1,40 @@/*** The settings two surfaces share: the extension's settings page and the desktop 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`.+ * and write them here, and config.json — with profile.json beside it — is the only copy. A change+ * from either side, from the CLI, or from a hand edit of either 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 { findSecrets } from '@/lib/secrets';import { isPreferenceChange, type Preferences } from '@/lib/settings/preferences';+import { normalizeProfile, PROFILE_FIELDS, sameProfile, type UserProfile } from '@/lib/settings/profile';import { configPath, readAgentConfig, writeGuardrailSetting, writeTheme } from './agent/config';import { guardrailSettings, settingWritable } from './guardrails';import { log } from './log';import { stateDir } from './paths';+import { profilePath, readProfile, readProfileText, writeProfile } from './profile';const SETTLE_MS = 150;-const CONFIG_FILE = basename(configPath);+const WATCHED = [basename(configPath), basename(profilePath)];export function preferencesNow(): Preferences {const config = readAgentConfig();return {theme: config.theme ?? null,guardrails: guardrailSettings(config.guardrails ?? {}, config.requireApproval, configPath),+ profile: readProfile(),};}export function applyPreference(change: unknown): ActionResult<Preferences> {if (!isPreferenceChange(change)) {- return failure('INVALID_INPUT', 'Expected {kind:"theme", theme} or {kind:"guardrail", setting, value}.');+ return failure('INVALID_INPUT', 'Expected {kind:"theme", theme}, {kind:"guardrail", setting, value} or {kind:"profile", profile}.');}+ if (change.kind === 'profile') return saveProfile(change.profile);if (change.kind === 'theme') {if (readAgentConfig().theme !== change.theme) {writeTheme(change.theme);@@ -47,7 +53,34 @@ export function applyPreference(change: unknown): ActionResult<Preferences> {return success(preferencesNow());}-/** What config.json holds right now, and the part of it a change of agent or model moves. */+function saveProfile(profile: UserProfile): ActionResult<Preferences> {+ const next = normalizeProfile(profile);+ const secret = secretIn(next);+ if (secret) {+ return failure(+ 'INVALID_INPUT',+ `“${secret}” looks like a password, key or card number. Browsentic keeps those sealed in the browser and never hands them to a model — leave it out of your profile.`,+ );+ }+ if (!sameProfile(next, readProfile())) {+ writeProfile(next);+ log(`profile saved (${Object.keys(next.fields).length + next.details.length} details, ${next.instructions ? 'with' : 'no'} instructions)`);+ }+ return success(preferencesNow());+}++/** The label of the first entry that holds a secret. A phone number is never read as a card, however its digits add up. */+function secretIn(profile: UserProfile): string | undefined {+ const field = PROFILE_FIELDS.find(({ id }) =>+ findSecrets(profile.fields[id] ?? '').some((span) => id !== 'phone' || span.kind !== 'card'),+ );+ if (field) return field.label;+ const detail = profile.details.find((each) => findSecrets(`${each.label}: ${each.value}`).length);+ if (detail) return detail.label;+ return findSecrets(profile.instructions).length ? 'Instructions' : undefined;+}++/** What config.json and profile.json hold right now, and the part of it a change of agent or model moves. */export interface ConfigMark {file: string;agent: string;@@ -61,19 +94,20 @@ export function markConfig(): ConfigMark {// 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]) };+ const file = createHash('sha256').update(text).update('\0').update(readProfileText()).digest('hex');+ return { file, 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.+ * Calls back once config.json or profile.json settles after a write from anywhere. The directory+ * is watched, not the files, because an editor that saves by replacing a 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;+ if (name !== null && !WATCHED.includes(String(name))) return;clearTimeout(timer);timer = setTimeout(onChange, SETTLE_MS);});diff --git a/src/daemon/profile.ts b/src/daemon/profile.tsnew file mode 100644index 0000000..9c8a5b8--- /dev/null+++ b/src/daemon/profile.ts@@ -0,0 +1,44 @@+/**+ * The user's profile, kept in its own file beside config.json so the config stays safe to paste+ * into a bug report. Read fresh on every run, like the config, and written only by the settings+ * page — an empty profile removes the file, so it only ever names what someone filled in.+ */++import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { asUserProfile, EMPTY_PROFILE, isEmptyProfile, isUserProfile, normalizeProfile, type UserProfile } from '@/lib/settings/profile';+import { log } from './log';+import { stateDir } from './paths';++export const profilePath = join(stateDir, 'profile.json');++export function readProfileText(): string {+ try {+ return readFileSync(profilePath, 'utf8');+ } catch {+ return '';+ }+}++export function readProfile(): UserProfile {+ const text = readProfileText();+ if (!text) return EMPTY_PROFILE;+ let parsed: unknown;+ try {+ parsed = JSON.parse(text);+ } catch {+ log(`${profilePath} is not JSON; the agent runs without a profile until it is fixed or saved again`);+ return EMPTY_PROFILE;+ }+ if (!isUserProfile(parsed)) log(`${profilePath} has entries the settings page cannot hold; they are left out`);+ return asUserProfile(parsed);+}++export function writeProfile(profile: UserProfile): void {+ if (isEmptyProfile(profile)) {+ rmSync(profilePath, { force: true });+ return;+ }+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });+ writeFileSync(profilePath, `${JSON.stringify(normalizeProfile(profile), null, 2)}\n`, { mode: 0o600 });+}diff --git a/src/daemon/test/preferences.test.ts b/src/daemon/test/preferences.test.tsindex 9171c67..6d31762 100644--- a/src/daemon/test/preferences.test.ts+++ b/src/daemon/test/preferences.test.ts@@ -1,5 +1,5 @@import { randomUUID } from 'node:crypto';-import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, 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';@@ -9,8 +9,10 @@ import { clearAuth } from '../auth-store';import { configPath, writeAgentModel } from '../agent/config';import { startDaemon, type Daemon } from '../daemon';import { readLockfile } from '../lockfile';+import { profilePath } from '../profile';import { RemoteBridge } from '../remote-bridge';import { FakeBrowser, type Profile } from './fake-browser';+import { bits, modeOf } from './modes';const unpacked = 'chrome-extension://abcdefghijklmnopabcdefghijklmnop';const chrome: Profile = { origin: unpacked, installId: 'install-chrome-0001', browser: 'Google Chrome' };@@ -27,7 +29,10 @@ afterAll(async () => {await daemon?.stop();});-beforeEach(() => rmSync(configPath, { force: true }));+beforeEach(() => {+ rmSync(configPath, { force: true });+ rmSync(profilePath, { force: true });+});afterEach(async () => {for (const each of opened) each.close();@@ -165,3 +170,82 @@ describe('settings shared by the extension and the Mac app', () => {});});});++describe('the profile the settings page keeps for the agent', () => {+ const ada = {+ fields: { givenName: 'Ada', email: '[email protected]', phone: '+8801711234567' },+ details: [{ label: 'Frequent flyer', value: 'BA 123456' }],+ instructions: 'Always choose the cheapest shipping.',+ };+ const saveFrom = (browser: FakeBrowser, profile: object) =>+ browser.ask({ t: 'setPreference', id: randomUUID(), change: { kind: 'profile', profile } } as never);+ const refusal = (frame: SocketFrame) => (frame.t === 'preferencesInfo' && !frame.result.ok ? frame.result.error.message : undefined);++ test('a profile saved in one browser lands in profile.json alone, and 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 saveFrom(first, { ...ada, fields: { ...ada.fields, familyName: ' ' } });+ expect(answer.t === 'preferencesInfo' && answer.result.ok && answer.result.data.profile).toEqual(ada);++ await vi.waitFor(() => expect(second.preferences?.profile).toEqual(ada));+ await vi.waitFor(() => expect(app.events).toContain('settings-changed'));+ expect(JSON.parse(readFileSync(profilePath, 'utf8'))).toEqual(ada);+ expect(modeOf(profilePath)).toBe(bits(0o600));+ expect(existsSync(configPath)).toBe(false);+ });++ test('a hand edit of profile.json reaches every browser', async () => {+ const browser = await paired(chrome);+ await vi.waitFor(() => expect(browser.preferences).not.toBeNull());+ mkdirSync(dirname(profilePath), { recursive: true });+ writeFileSync(profilePath, JSON.stringify({ fields: { email: '[email protected]' }, details: [], instructions: '' }));++ await vi.waitFor(() => expect(browser.preferences?.profile.fields.email).toBe('[email protected]'));+ });++ test('a key, a password or a card number is refused by name and written nowhere', async () => {+ const browser = await paired(chrome);+ const answers = await Promise.all(+ [+ { ...ada, instructions: 'My Anthropic key is sk-ant-api03-abcdefghijklmnopqrstuvwx' },+ { ...ada, details: [{ label: 'Wi-Fi password', value: 'correct-horse-battery' }] },+ { ...ada, details: [{ label: 'Card', value: '4111 1111 1111 1111' }] },+ ].map((profile) => saveFrom(browser, profile)),+ );+ expect(answers.map(refusal)).toEqual([+ expect.stringContaining('“Instructions” looks like a password, key or card number'),+ expect.stringContaining('“Wi-Fi password” looks like'),+ expect.stringContaining('“Card” looks like'),+ ]);+ expect(existsSync(profilePath)).toBe(false);+ });++ test('a phone number is never taken for a card, however its digits add up', async () => {+ const browser = await paired(chrome);+ const answers = await Promise.all(+ ['+8801711234567', '4111 1111 1111 1111', '+44 20 7946 0958'].map((phone) =>+ saveFrom(browser, { fields: { phone }, details: [], instructions: '' }),+ ),+ );+ expect(answers.map(refusal)).toEqual([undefined, undefined, undefined]);+ });++ test('saving an empty profile removes the file, so nothing about the user is left on disk', async () => {+ const browser = await paired(chrome);+ await saveFrom(browser, ada);+ expect(existsSync(profilePath)).toBe(true);++ const answer = await saveFrom(browser, { fields: { email: ' ' }, details: [], instructions: '' });+ expect(answer.t === 'preferencesInfo' && answer.result.ok && answer.result.data.profile).toEqual({ fields: {}, details: [], instructions: '' });+ expect(existsSync(profilePath)).toBe(false);+ });++ test('a control connection that has spoken for an agent run cannot rewrite the profile', async () => {+ const app = await macApp();+ await app.ask({ op: 'describe', runId: 'run-under-guard' });+ const refused = await app.ask({ op: 'setPreference', change: { kind: 'profile', profile: ada } });+ expect(refused.result).toMatchObject({ ok: false, error: { code: 'BLOCKED' } });+ expect(existsSync(profilePath)).toBe(false);+ });+});diff --git a/src/lib/actions/protocol.ts b/src/lib/actions/protocol.tsindex 687e4d5..c639c6a 100644--- a/src/lib/actions/protocol.ts+++ b/src/lib/actions/protocol.ts@@ -12,7 +12,7 @@ import type { TaskContext, TaskList, TaskOrder, TaskResult } from '@/lib/schedulexport const ACTION_CHANNEL = 'browsentic/action';export const BRIDGE_CHANNEL = 'browsentic/bridge';-export const SOCKET_PROTOCOL_VERSION = 21;+export const SOCKET_PROTOCOL_VERSION = 22;export const EXTERNAL_RUN_ID = 'external';diff --git a/src/lib/bridge/preferences.test.ts b/src/lib/bridge/preferences.test.tsindex 1d5c677..bd7342c 100644--- a/src/lib/bridge/preferences.test.ts+++ b/src/lib/bridge/preferences.test.ts@@ -3,6 +3,7 @@ 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 { EMPTY_PROFILE } from '@/lib/settings/profile';import type { ThemeId } from '@/lib/settings/theme';const socket = vi.hoisted(() => ({@@ -23,7 +24,7 @@ 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 };+ const preferences = { theme, guardrails, profile: EMPTY_PROFILE };await fakeBrowser.storage.session.set({ 'browsentic/daemon': { connected: true, paired: true, preferences, lastChangeAt: 0 } });socket.listener?.(preferences);}@@ -34,7 +35,7 @@ const handed = () => socket.setPreference.mock.calls.map(([change]) => change.thdescribe('one theme for this browser and config.json', () => {beforeEach(() => {fakeBrowser.reset();- socket.setPreference.mockReset().mockImplementation(async (change) => success({ theme: change.theme, guardrails }));+ socket.setPreference.mockReset().mockImplementation(async (change) => success({ theme: change.theme, guardrails, profile: EMPTY_PROFILE }));servePreferences();});@@ -69,7 +70,7 @@ describe('one theme for this browser and config.json', () => {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.mockImplementation(async (change) => success({ theme: change.theme, guardrails, profile: EMPTY_PROFILE }));socket.setPreference.mockClear();await push('ember');await vi.waitFor(() => expect(handed()).toEqual(['midnight']));diff --git a/src/lib/settings/preferences.test.ts b/src/lib/settings/preferences.test.tsindex b8449a1..aa2a53e 100644--- a/src/lib/settings/preferences.test.ts+++ b/src/lib/settings/preferences.test.ts@@ -2,14 +2,15 @@ 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', () => {+ test('a theme the extension has, a guardrail set to an effect, a switch or back to its default, and a whole profile', () => {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 },+ { kind: 'profile', profile: { fields: { email: '[email protected]' }, details: [], instructions: 'Be brief.' } },];- expect(changes.map(isPreferenceChange)).toEqual([true, true, true, true]);+ expect(changes.map(isPreferenceChange)).toEqual([true, true, true, true, true]);});test('anything else is refused before it reaches config.json', () => {@@ -20,7 +21,9 @@ describe('what a settings screen may ask the daemon to change', () => {{ kind: 'guardrail', setting: 'form-submission', value: 'sometimes' },{ kind: 'guardrail', value: 'allow' },{ kind: 'agent', agent: 'codex' },+ { kind: 'profile', profile: { fields: { nickname: 'Ada' }, details: [], instructions: '' } },+ { kind: 'profile' },];- expect(changes.map(isPreferenceChange)).toEqual([false, false, false, false, false, false]);+ expect(changes.map(isPreferenceChange)).toEqual(changes.map(() => false));});});diff --git a/src/lib/settings/preferences.ts b/src/lib/settings/preferences.tsindex e9f5539..c7abb63 100644--- a/src/lib/settings/preferences.ts+++ b/src/lib/settings/preferences.ts@@ -1,26 +1,30 @@/*** Everything a person can set from either the extension's settings page or the desktop 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.+ * daemon keeps it in config.json — the profile in profile.json beside it — 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';+import { isUserProfile, type UserProfile } from './profile';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;+ readonly profile: UserProfile;}export type PreferenceChange =| { readonly kind: 'theme'; readonly theme: ThemeId }- | { readonly kind: 'guardrail'; readonly setting: string; readonly value: GuardrailValue };+ | { readonly kind: 'guardrail'; readonly setting: string; readonly value: GuardrailValue }+ | { readonly kind: 'profile'; readonly profile: UserProfile };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 };+ const change = value as { kind?: unknown; theme?: unknown; setting?: unknown; value?: unknown; profile?: unknown };if (change.kind === 'theme') return isThemeId(change.theme);+ if (change.kind === 'profile') return isUserProfile(change.profile);return (change.kind === 'guardrail' &&typeof change.setting === 'string' &&diff --git a/src/lib/settings/profile.test.ts b/src/lib/settings/profile.test.tsnew file mode 100644index 0000000..bf9c5eb--- /dev/null+++ b/src/lib/settings/profile.test.ts@@ -0,0 +1,66 @@+import { describe, expect, test } from 'vitest';+import { asUserProfile, isEmptyProfile, isUserProfile, normalizeProfile, PROFILE_LIMITS, sameProfile } from './profile';++const full = {+ fields: { givenName: 'Ada', familyName: 'Lovelace', email: '[email protected]', street: '12 St James’s Square\nFlat 3' },+ details: [{ label: 'Frequent flyer', value: 'BA 123456' }],+ instructions: 'Always choose the cheapest shipping.',+};++describe('what a settings page may save as the profile', () => {+ test('known fields, labelled details and instructions', () => {+ expect(isUserProfile(full)).toBe(true);+ expect(isUserProfile({ fields: {}, details: [], instructions: '' })).toBe(true);+ });++ test('anything else is refused before it reaches profile.json', () => {+ const refused = [+ null,+ [],+ { ...full, fields: { nickname: 'Ada' } },+ { ...full, fields: { email: 42 } },+ { ...full, fields: { email: 'a'.repeat(PROFILE_LIMITS.value + 1) } },+ { ...full, details: [{ label: 'x'.repeat(PROFILE_LIMITS.label + 1), value: 'y' }] },+ { ...full, details: Array.from({ length: PROFILE_LIMITS.details + 1 }, () => ({ label: 'a', value: 'b' })) },+ { ...full, details: [{ label: 'Loyalty' }] },+ { ...full, instructions: 'x'.repeat(PROFILE_LIMITS.instructions + 1) },+ { fields: {}, details: [] },+ ];+ expect(refused.map(isUserProfile)).toEqual(refused.map(() => false));+ });+});++describe('what is kept', () => {+ test('values are trimmed, and empty fields and half-filled details are left out', () => {+ const profile = normalizeProfile({+ fields: { givenName: ' Ada ', familyName: ' ', email: '' },+ details: [+ { label: ' Loyalty ', value: ' 991 ' },+ { label: '', value: 'no label' },+ { label: 'No value', value: ' ' },+ ],+ instructions: '\n Be brief. \n',+ });+ expect(profile).toEqual({ fields: { givenName: 'Ada' }, details: [{ label: 'Loyalty', value: '991' }], instructions: 'Be brief.' });+ });++ test('a profile with nothing filled in is empty, whatever whitespace it holds', () => {+ expect(isEmptyProfile({ fields: { email: ' ' }, details: [{ label: ' ', value: '' }], instructions: '\n' })).toBe(true);+ expect(isEmptyProfile({ fields: {}, details: [], instructions: 'Be brief.' })).toBe(false);+ });++ test('two profiles that differ only in whitespace are the same', () => {+ expect(sameProfile(full, { ...full, instructions: ` ${full.instructions} ` })).toBe(true);+ expect(sameProfile(full, { ...full, instructions: 'Be brief.' })).toBe(false);+ });++ test('a hand-edited file keeps every entry that fits and never cuts one short', () => {+ const read = asUserProfile({+ fields: { email: '[email protected]', phone: '1'.repeat(PROFILE_LIMITS.value + 1), nickname: 'Ada' },+ details: [{ label: 'Loyalty', value: '991' }, 'stray', { label: 'Broken' }],+ instructions: 7,+ });+ expect(read).toEqual({ fields: { email: '[email protected]' }, details: [{ label: 'Loyalty', value: '991' }], instructions: '' });+ expect(asUserProfile('not a profile')).toEqual({ fields: {}, details: [], instructions: '' });+ });+});diff --git a/src/lib/settings/profile.ts b/src/lib/settings/profile.tsnew file mode 100644index 0000000..55a37dd--- /dev/null+++ b/src/lib/settings/profile.ts@@ -0,0 +1,103 @@+/**+ * What the user tells the agent about themselves from the settings page: the details a form may+ * ask for, and rules for every task. The daemon keeps it in profile.json and puts whatever is+ * filled in into each side-panel run's system prompt, so the model uses these values rather than+ * guessing at them.+ */++export const PROFILE_FIELDS = [+ { id: 'givenName', label: 'First name', autocomplete: 'given-name' },+ { id: 'familyName', label: 'Last name', autocomplete: 'family-name' },+ { id: 'email', label: 'Email', autocomplete: 'email' },+ { id: 'phone', label: 'Phone', autocomplete: 'tel' },+ { id: 'street', label: 'Street address', autocomplete: 'street-address', multiline: true },+ { id: 'city', label: 'City', autocomplete: 'address-level2' },+ { id: 'region', label: 'State / region', autocomplete: 'address-level1' },+ { id: 'postalCode', label: 'Postal code', autocomplete: 'postal-code' },+ { id: 'country', label: 'Country', autocomplete: 'country-name' },+ { id: 'company', label: 'Company', autocomplete: 'organization' },+ { id: 'jobTitle', label: 'Job title', autocomplete: 'organization-title' },+] as const;++export type ProfileFieldId = (typeof PROFILE_FIELDS)[number]['id'];++export interface ProfileDetail {+ readonly label: string;+ readonly value: string;+}++export interface UserProfile {+ readonly fields: Partial<Record<ProfileFieldId, string>>;+ /** Anything the fixed fields do not cover, labelled by the user. */+ readonly details: readonly ProfileDetail[];+ /** Rules the user wants kept on every task. */+ readonly instructions: string;+}++export const PROFILE_LIMITS = { value: 300, label: 60, details: 20, instructions: 4000 } as const;++export const EMPTY_PROFILE: UserProfile = { fields: {}, details: [], instructions: '' };++const FIELD_IDS: readonly string[] = PROFILE_FIELDS.map((field) => field.id);++export function isProfileFieldId(value: string): value is ProfileFieldId {+ return FIELD_IDS.includes(value);+}++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const fits = (value: unknown, limit: number): value is string => typeof value === 'string' && value.length <= limit;++const isDetail = (value: unknown): value is ProfileDetail =>+ isRecord(value) && fits(value.label, PROFILE_LIMITS.label) && fits(value.value, PROFILE_LIMITS.value);++export function isUserProfile(value: unknown): value is UserProfile {+ return (+ isRecord(value) &&+ isRecord(value.fields) &&+ Object.entries(value.fields).every(([id, text]) => isProfileFieldId(id) && fits(text, PROFILE_LIMITS.value)) &&+ Array.isArray(value.details) &&+ value.details.length <= PROFILE_LIMITS.details &&+ value.details.every(isDetail) &&+ fits(value.instructions, PROFILE_LIMITS.instructions)+ );+}++/** Trimmed, with every empty field and every detail missing a label or a value left out. */+export function normalizeProfile(profile: UserProfile): UserProfile {+ const fields: Partial<Record<ProfileFieldId, string>> = {};+ for (const { id } of PROFILE_FIELDS) {+ const text = profile.fields[id]?.trim();+ if (text) fields[id] = text;+ }+ const details = profile.details+ .map((detail) => ({ label: detail.label.trim(), value: detail.value.trim() }))+ .filter((detail) => detail.label && detail.value);+ return { fields, details, instructions: profile.instructions.trim() };+}++/**+ * What a hand-edited profile.json can be read as: every entry that fits kept, anything that does+ * not left out, never cut short — a truncated phone number is worse than none.+ */+export function asUserProfile(value: unknown): UserProfile {+ if (!isRecord(value)) return EMPTY_PROFILE;+ const fields = isRecord(value.fields)+ ? Object.fromEntries(+ Object.entries(value.fields).filter(([id, text]) => isProfileFieldId(id) && fits(text, PROFILE_LIMITS.value)),+ )+ : {};+ const details = Array.isArray(value.details) ? value.details.filter(isDetail).slice(0, PROFILE_LIMITS.details) : [];+ const instructions = fits(value.instructions, PROFILE_LIMITS.instructions) ? value.instructions : '';+ return normalizeProfile({ fields, details, instructions });+}++export function isEmptyProfile(profile: UserProfile): boolean {+ const normal = normalizeProfile(profile);+ return !Object.keys(normal.fields).length && !normal.details.length && !normal.instructions;+}++export function sameProfile(a: UserProfile, b: UserProfile): boolean {+ return JSON.stringify(normalizeProfile(a)) === JSON.stringify(normalizeProfile(b));+}diff --git a/src/windows/ui/mock-backend.ts b/src/windows/ui/mock-backend.tsindex f49277d..a440dc5 100644--- a/src/windows/ui/mock-backend.ts+++ b/src/windows/ui/mock-backend.ts@@ -1,6 +1,7 @@import { AGENT_LIST, AGENTS, type AgentKind } from '@/lib/agents/catalog';import type { GuardrailSettings } from '@/lib/settings/guardrails';import type { PreferenceChange } from '@/lib/settings/preferences';+import { EMPTY_PROFILE } from '@/lib/settings/profile';import type { AgentListing, Backend, CliOutput, InstallStamp, Lockfile, NodeInstall, Preferences } from './backend';/**@@ -20,7 +21,7 @@ export function mockBackend({ instant = false, fresh = location.hash === '#freshlet active: AgentKind = 'claude';const models: Partial<Record<AgentKind, string>> = {};const listeners = new Set<(event: string) => void>();- let preferences: Preferences = { theme: null, guardrails: guardrails(`${home}\\.browsentic\\config.json`) };+ let preferences: Preferences = { theme: null, guardrails: guardrails(`${home}\\.browsentic\\config.json`), profile: EMPTY_PROFILE };const ok = (stdout: string): CliOutput => ({ ok: true, code: 0, stdout, stderr: '' });const later = <T>(value: T, ms = 350) => new Promise<T>((resolve) => setTimeout(() => resolve(value), instant ? 0 : ms));@@ -37,7 +38,7 @@ export function mockBackend({ instant = false, fresh = location.hash === '#freshconst replies: Record<string, (frame: Record<string, unknown>) => Record<string, unknown>> = {status: () => ({- status: { connected: true, daemonVersion: version, protocolVersion: 21, port: 8765, manifestInSync: true, extensionVersion: version, connectedBrowsers: 1, pairedBrowsers: 1, pairingPending: false },+ status: { connected: true, daemonVersion: version, protocolVersion: 22, port: 8765, manifestInSync: true, extensionVersion: version, connectedBrowsers: 1, pairedBrowsers: 1, pairingPending: false },}),sessions: () => ({sessions: [@@ -50,7 +51,12 @@ export function mockBackend({ instant = false, fresh = location.hash === '#freshpreferences: () => ({ result: { ok: true, data: preferences } }),setPreference: ({ change }) => {const next = change as PreferenceChange;- preferences = next.kind === 'theme' ? { ...preferences, theme: next.theme } : { ...preferences, guardrails: applyGuardrail(preferences.guardrails, next.setting, next.value) };+ preferences =+ next.kind === 'theme'+ ? { ...preferences, theme: next.theme }+ : next.kind === 'profile'+ ? { ...preferences, profile: next.profile }+ : { ...preferences, guardrails: applyGuardrail(preferences.guardrails, next.setting, next.value) };listeners.forEach((listener) => listener('settings-changed'));return { result: { ok: true, data: preferences } };},