/ CLAUDE.md
CLAUDE.md
1 # CLAUDE.md 2 3 This file provides guidance to AI coding assistants (e.g., Claude Code, GitHub Copilot, Cursor) when working with this repository. 4 5 ## Project Overview 6 7 Nanobrowser is an open-source AI web automation Chrome extension that runs multi-agent systems locally in the browser. It's a free alternative to OpenAI Operator with support for multiple LLM providers (OpenAI, Anthropic, Gemini, Ollama, etc.). 8 9 ## Development Commands 10 11 **Package Manager**: Always use `pnpm` (required, configured in Cursor rules) 12 13 **Core Commands**: 14 15 - `pnpm install` - Install dependencies 16 - `pnpm dev` - Start development mode with hot reload 17 - `pnpm build` - Build production version 18 - `pnpm type-check` - Run TypeScript type checking 19 - `pnpm lint` - Run ESLint with auto-fix 20 - `pnpm prettier` - Format code with Prettier 21 22 **Testing**: 23 24 - `pnpm e2e` - Run end-to-end tests (builds and zips first) 25 - `pnpm zip` - Create extension zip for distribution 26 - `pnpm -F chrome-extension test` - Run unit tests (Vitest) for core extension 27 - Targeted example: `pnpm -F chrome-extension test -- -t "Sanitizer"` 28 29 ### Workspace Tips 30 31 - Scope tasks to a single workspace to speed up runs: 32 - `pnpm -F chrome-extension build` 33 - `pnpm -F packages/ui lint` 34 - Prefer workspace-scoped commands over root-wide runs when possible. 35 36 Targeted examples (fast path): 37 - `pnpm -F pages/side-panel build` — build only the side panel 38 - `pnpm -F chrome-extension dev` — dev-watch background/service worker 39 - `pnpm -F packages/storage type-check` — TS checks for storage package 40 - `pnpm -F pages/side-panel lint -- src/components/ChatInput.tsx` — lint a file 41 - `pnpm -F chrome-extension prettier -- src/background/index.ts` — format a file 42 43 **Cleaning**: 44 45 - `pnpm clean` - Clean all build artifacts and node_modules 46 - `pnpm clean:bundle` - Clean just build outputs 47 - `pnpm clean:turbo` - Clear Turbo state/cache 48 - `pnpm clean:node_modules` - Remove dependencies in current workspace 49 - `pnpm clean:install` - Clean node_modules and reinstall dependencies 50 - `pnpm update-version` - Update version across all packages 51 52 ## Architecture 53 54 This is a **monorepo** using **Turbo** for build orchestration and **pnpm workspaces**. 55 56 ### Workspace Structure 57 58 **Core Extension**: 59 60 - `chrome-extension/` - Main Chrome extension manifest and background scripts 61 - `src/background/` - Background service worker with multi-agent system 62 - `src/background/agent/` - AI agent implementations (Navigator, Planner, Validator) 63 - `src/background/browser/` - Browser automation and DOM manipulation 64 65 **UI Pages** (`pages/`): 66 67 - `side-panel/` - Main chat interface (React + TypeScript + Tailwind) 68 - `options/` - Extension settings page (React + TypeScript) 69 - `content/` - Content script for page injection 70 71 **Shared Packages** (`packages/`): 72 73 - `shared/` - Common utilities and types 74 - `storage/` - Chrome extension storage abstraction 75 - `ui/` - Shared React components 76 - `schema-utils/` - Validation schemas 77 - `i18n/` - Internationalization 78 - Others: `dev-utils/`, `zipper/`, `vite-config/`, `tailwind-config/`, `hmr/`, 79 `tsconfig/` 80 81 ### Multi-Agent System 82 83 The core AI system consists of three specialized agents: 84 85 - **Navigator** - Handles DOM interactions and web navigation 86 - **Planner** - High-level task planning and strategy 87 - **Validator** - Validates task completion and results 88 89 Agent logic is under `chrome-extension/src/background/agent/`. 90 91 ### Build System 92 93 - **Turbo** manages task dependencies and caching 94 - **Vite** bundles each workspace independently 95 - **TypeScript** with strict configuration across all packages 96 - **ESLint** + **Prettier** for code quality 97 - Each workspace has its own `vite.config.mts` and `tsconfig.json` 98 99 ### Key Technologies 100 101 - **Chrome Extension Manifest V3** 102 - **React 18** with TypeScript 103 - **Tailwind CSS** for styling 104 - **Vite** for bundling 105 - **Puppeteer** for browser automation 106 - **Chrome APIs** for browser automation 107 - **LangChain.js** for LLM integration 108 109 ## Development Notes 110 111 - Extension loads as unpacked from `dist/` directory after build 112 - Hot reload works in development mode via Vite HMR 113 - Background scripts run as service workers (Manifest V3) 114 - Content scripts inject into web pages for DOM access 115 - Multi-agent coordination happens through Chrome messaging APIs 116 - Distribution zips are written to `dist-zip/` 117 - Build flags: set `__DEV__=true` for watch builds; 118 - Do not edit generated outputs: `dist/**`, `build/**`, `packages/i18n/lib/**` 119 120 ## Unit Tests 121 122 - Framework: Vitest 123 - Location/naming: `chrome-extension/src/**/__tests__` with `*.test.ts` 124 - Run: `pnpm -F chrome-extension test` 125 - Targeted example: `pnpm -F chrome-extension test -- -t "Sanitizer"` 126 - Prefer fast, deterministic tests; mock network/browser APIs 127 128 ## Testing Extension 129 130 After building, load the extension: 131 132 1. Open `chrome://extensions/` 133 2. Enable "Developer mode" 134 3. Click "Load unpacked" 135 4. Select the `dist/` directory 136 137 ## Internationalization (i18n) 138 139 ### Key Naming Convention 140 141 Follow the structured naming pattern: `component_category_specificAction_state` 142 143 **Semantic Prefixes by Component:** 144 145 - `bg_` - Background service worker operations 146 - `exec_` - Executor/agent execution lifecycle 147 - `act_` - Agent actions and web automation 148 - `errors_` - Global error messages 149 - `options_` - Settings page components 150 - `chat_` - Chat interface elements 151 - `nav_` - Navigation elements 152 - `permissions_` - Permission-related messages 153 154 **State-Based Suffixes:** 155 156 - `_start` - Action beginning (e.g., `act_goToUrl_start`) 157 - `_ok` - Successful completion (e.g., `act_goToUrl_ok`) 158 - `_fail` - Failure state (e.g., `exec_task_fail`) 159 - `_cancel` - Cancelled operation 160 - `_pause` - Paused state 161 162 **Error Categorization:** 163 164 - `_errors_` subcategory for component-specific errors 165 - Global `errors_` prefix for system-wide errors 166 - Descriptive error names (e.g., `act_errors_elementNotExist`) 167 168 **Command Structure:** 169 170 - `_cmd_` for command-related messages (e.g., `bg_cmd_newTask_noTask`) 171 - `_setup_` for configuration issues (e.g., `bg_setup_noApiKeys`) 172 173 ### Usage 174 175 ```typescript 176 import { t } from '@extension/i18n'; 177 178 // Simple message 179 t('bg_errors_noTabId') 180 181 // With placeholders 182 t('act_click_ok', ['5', 'Submit Button']) 183 ``` 184 185 ### Placeholders 186 187 Use Chrome i18n placeholder format with proper definitions: 188 189 ```json 190 { 191 "act_goToUrl_start": { 192 "message": "Navigating to $URL$", 193 "placeholders": { 194 "url": { 195 "content": "$1", 196 "example": "https://example.com" 197 } 198 } 199 } 200 } 201 ``` 202 203 **Guidelines:** 204 205 - Use descriptive, self-documenting key names 206 - Separate user-facing strings from internal/log strings 207 - Follow hierarchical naming for maintainability 208 - Add placeholders with examples for dynamic content 209 - Group related keys by component prefix 210 211 ### Generation 212 213 - Do not edit generated files under `packages/i18n/lib/**`. 214 - The generator `packages/i18n/genenrate-i18n.mjs` runs via the `@extension/i18n` 215 workspace `ready`/`build` scripts to (re)generate types and runtime helpers. 216 Edit source locale JSON in `packages/i18n/locales/**` instead. 217 218 ## Code Quality Standards 219 220 ### Development Principles 221 222 - **Simple but Complete Solutions**: Write straightforward, well-documented code that fully addresses requirements 223 - **Modular Design**: Structure code into focused, single-responsibility modules and functions 224 - **Testability**: Design components to be easily testable with clear inputs/outputs and minimal dependencies 225 - **Type Safety**: Leverage TypeScript's type system for better code reliability and maintainability 226 227 ### Code Organization 228 229 - Extract reusable logic into utility functions or shared packages 230 - Use dependency injection for better testability 231 - Keep functions small and focused on a single task 232 - Prefer composition over inheritance 233 - Write self-documenting code with clear naming 234 235 ### Style & Naming 236 237 - Formatting via Prettier (2 spaces, semicolons, single quotes, 238 trailing commas, `printWidth: 120`) 239 - ESLint rules include React/Hooks/Import/A11y + TypeScript 240 - Components: `PascalCase`; variables/functions: `camelCase`; 241 workspace/package directories: `kebab-case` 242 - Enforced rule: `@typescript-eslint/consistent-type-imports` 243 (use `import type { ... } from '...'` for type-only imports) 244 245 ### Quality Assurance 246 247 - Run `pnpm type-check` before committing to catch TypeScript errors 248 - Use `pnpm lint` to maintain code style consistency 249 - Write unit tests for business logic and utility functions 250 - Test UI components in isolation when possible 251 252 ### Security Guidelines 253 254 - **Input Validation**: Always validate and sanitize user inputs, especially URLs, file paths, and form data 255 - **Credential Management**: Never log, commit, or expose API keys, tokens, or sensitive configuration 256 - **Content Security Policy**: Respect CSP restrictions and avoid `eval()` or dynamic code execution 257 - **Permission Principle**: Request minimal Chrome extension permissions required for functionality 258 - **Data Privacy**: Handle user data securely and avoid unnecessary data collection or storage 259 - **XSS Prevention**: Sanitize content before rendering, especially when injecting into web pages 260 - **URL Validation**: Validate and restrict navigation to prevent malicious redirects 261 - **Error Handling**: Avoid exposing sensitive information in error messages or logs 262 - **Secrets/Config**: Use `.env.local` (git‑ignored) and prefix variables with `VITE_`. 263 Example: `VITE_POSTHOG_API_KEY`. Vite in `chrome-extension/vite.config.mts` loads 264 `VITE_*` from the parent directory. 265 266 ## Important Reminders 267 268 - Always use `pnpm` package manager (required for this project) 269 - Node.js version: follow `.nvmrc` and `package.json` engines 270 - Use `nvm use` to match `.nvmrc` before installing 271 - `engine-strict=true` is enabled in `.npmrc`; non-matching engines fail install 272 - Turbo manages task dependencies and caching across workspaces 273 - Extension builds to `dist/` directory which is loaded as unpacked extension 274 - Zipped distributions are written to `dist-zip/` 275 - Only supports Chrome/Edge 276 - Keep diffs minimal and scoped; avoid mass refactors or reformatting unrelated files 277 - Do not modify generated artifacts (`dist/**`, `build/**`, `packages/i18n/lib/**`) 278 or workspace/global configs (`turbo.json`, `pnpm-workspace.yaml`, `tsconfig*`) 279 without approval 280 - Prefer workspace-scoped checks: 281 `pnpm -F <workspace> type-check`, `pnpm -F <workspace> lint`, 282 `pnpm -F <workspace> prettier -- <changed-file>`, and build if applicable 283 - Vite aliases: pages use `@src` for page `src/`; the extension uses 284 `@root`, `@src`, `@assets` (see `chrome-extension/vite.config.mts`). Use 285 `packages/vite-config`’s `withPageConfig` for page workspaces. 286 - Only use scripts defined in `package.json`; do not invent new commands 287 - Change policy: ask first for new deps, file renames/moves/deletes, or 288 global/workspace config changes; allowed without asking: read/list files, 289 workspace‑scoped lint/format/type-check/build, and small focused patches 290 - Reuse existing building blocks: `packages/ui` components and 291 `packages/tailwind-config` tokens instead of re-implementing