Skip to content

Commit d26fe46

Browse files
wojteknsejas
andauthored
Add AI instructions to the repository (#2015)
* Add AI instructions to the repository * Update heading to make it more generic Co-authored-by: Antonio Sejas <[email protected]> --------- Co-authored-by: Antonio Sejas <[email protected]>
1 parent 612f3c4 commit d26fe46

File tree

3 files changed

+360
-0
lines changed

3 files changed

+360
-0
lines changed

.cursorrules

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
docs/ai-instructions.md

CLAUDE.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
docs/ai-instructions.md

docs/ai-instructions.md

Lines changed: 358 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,358 @@
1+
# AI Instructions
2+
3+
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4+
5+
## Common Development Commands
6+
7+
### Building and Running
8+
- `npm start` - Start Electron app in dev mode (opens automatically with DevTools)
9+
- `npm run cli:build` - Build CLI once (outputs to `dist/cli/main.js`)
10+
- `npm run cli:watch` - Build CLI in watch mode
11+
- `node dist/cli/main.js` - Run the built CLI
12+
13+
### Testing
14+
- `npm test` - Run unit tests (Jest)
15+
- `npm run test:watch` - Run tests in watch mode
16+
- `npm run e2e` - Run end-to-end tests (Playwright)
17+
- `npm run test:metrics` - Run performance metrics tests
18+
19+
### Code Quality
20+
- `npm run lint` - Lint TypeScript/JavaScript files
21+
- `npm run format` - Format code with Prettier
22+
23+
### Building Installers
24+
- `npm run package` - Package the app (no installer)
25+
- `npm run make` - Build installers for current platform
26+
- `npm run make:macos-x64` - Build macOS Intel installer
27+
- `npm run make:macos-arm64` - Build macOS Apple Silicon installer
28+
- `npm run make:windows-x64` - Build Windows x64 installer
29+
- `npm run make:windows-arm64` - Build Windows ARM64 installer
30+
31+
### Process Considerations
32+
When editing code, hot reload behavior differs by process:
33+
- **Renderer Process** (React/UI): Reloads automatically
34+
- **Main Process** (Node.js/backend): Requires restart - either restart the app or type `rs` in the terminal
35+
36+
### Running a Single Test
37+
```bash
38+
npm test -- path/to/test.test.ts
39+
npm test -- --testNamePattern="test name pattern"
40+
```
41+
42+
## WordPress Studio - Architecture Overview
43+
44+
WordPress Studio is a desktop application for creating, managing, and testing WordPress sites locally. It's built as an Electron desktop application with a React renderer, powered by WordPress Playground and PHP WASM.
45+
46+
## High-Level Architecture
47+
48+
```
49+
┌─────────────────────────────────────────────────────┐
50+
│ ELECTRON MAIN PROCESS (Node.js) │
51+
├─────────────────────────────────────────────────────┤
52+
│ • IPC Handler Layer (ipc-handlers.ts) │
53+
│ • Site Server Management (site-server.ts) │
54+
│ • WordPress Provider Abstraction │
55+
│ • Storage & User Data Management │
56+
│ • OAuth / Authentication │
57+
│ • Sync Operations (WordPress.com / Pressable) │
58+
│ • File Operations & Migrations │
59+
└──────────────┬──────────────────┬───────────────────┘
60+
│ │
61+
┌────────▼─────────┐ ┌────▼──────────┐
62+
│ RENDERER PROCESS │ │ PRELOAD SCRIPT│
63+
│ (React App) │ │ (IPC Bridge) │
64+
└────────────────┬─┘ └───────────────┘
65+
66+
┌──────────────────────▼──────────────────────┐
67+
│ WORDPRESS PROVIDERS │
68+
├──────────────────────────────────────────────┤
69+
│ • Playground-CLI Provider (with Blueprints) │
70+
│ • WP-Now Provider (fallback) │
71+
│ • PHP WASM Runtime │
72+
│ • Server Process Management │
73+
└─────────────────────────────────────────────┘
74+
```
75+
76+
## Directory Structure
77+
78+
### `/src` - Main Electron Application (Renderer + Main Process)
79+
- **`index.ts`** - Electron main process entry point, app lifecycle management
80+
- **`renderer.ts`** - React renderer initialization
81+
- **`preload.ts`** - Preload script defining IPC API bridge (contextBridge)
82+
- **`ipc-handlers.ts`** - All IPC handler implementations (communication between main and renderer)
83+
- **`ipc-utils.ts`** - IPC utility functions for sending events to renderer
84+
- **`main-window.ts`** - BrowserWindow creation and management
85+
- **`menu.ts`** - Application menu setup
86+
- **`site-server.ts`** - SiteServer class managing individual WordPress site instances
87+
- **`storage/`** - User data persistence and app state storage
88+
- **`stores/`** - Redux RTK stores (centralized state management)
89+
- **`lib/`** - Utility libraries and business logic
90+
- `wordpress-provider/` - Abstraction layer for WordPress runtime (Playground vs WP-Now)
91+
- `import-export/` - Site backup/restore functionality
92+
- `sync/` - WordPress.com sync operations
93+
- `certificate-manager.ts` - HTTPS certificate generation for custom domains
94+
- `proxy-server.ts` - Local HTTP proxy for custom domain routing
95+
- `wp-cli-process.ts` - WP-CLI command execution wrapper
96+
- **`components/`** - React UI components
97+
- `root.tsx` - Root component with all context providers
98+
- `app.tsx` - Main app layout
99+
- `main-sidebar.tsx` - Site list and navigation
100+
- `site-content-tabs.tsx` - Tabbed interface (Overview, Settings, etc.)
101+
- **`hooks/`** - Custom React hooks for data fetching and state management
102+
- **`modules/`** - Feature-specific modules with their own UI and logic
103+
- `sync/` - WordPress.com sync UI and logic
104+
- `cli/` - CLI command handling
105+
- `user-settings/` - Settings UI
106+
- `preview-site/` - Preview sites functionality
107+
- **`migrations/`** - Database/storage migrations for app updates
108+
109+
### `/cli` - Command-Line Interface
110+
- **`index.ts`** - CLI entry point using yargs
111+
- **`commands/`** - Command implementations
112+
- `preview/` - Preview site management commands
113+
- `site/` - Local site management commands (beta)
114+
- **`lib/`** - CLI-specific utilities and helpers
115+
- `appdata.ts` - Reading app configuration
116+
- `i18n.ts` - Locale loading for CLI
117+
118+
### `/common` - Shared Code (Both Main and Renderer)
119+
- **`lib/`** - Shared utility libraries
120+
- `fs-utils.ts` - File system operations
121+
- `port-finder.ts` - Port management and availability checking
122+
- `locale.ts` - Localization/i18n utilities
123+
- `oauth.ts` - OAuth URL construction
124+
- **`types/`** - TypeScript type definitions used across the app
125+
- `snapshot.ts` - Site snapshot types
126+
- `stats.ts` - Analytics/telemetry types
127+
- `site.ts` - Core site data types
128+
- **`translations/`** - i18n translation strings in multiple languages
129+
130+
### `/packages` - Monorepo Packages
131+
- **`eslint-plugin-studio`** - Custom ESLint rules for the project
132+
133+
## Key Architecture Patterns
134+
135+
### 1. Electron Process Architecture
136+
- **Main Process** (`src/index.ts`): Handles app lifecycle, creates windows, file operations, server management
137+
- **Renderer Process** (React app): UI layer, communicates with main via IPC
138+
- **Preload Script** (`src/preload.ts`): Sandboxed bridge between renderer and main process via `contextBridge`
139+
140+
### 2. IPC Communication Pattern
141+
```typescript
142+
// Preload (src/preload.ts) exposes:
143+
window.ipcApi.startServer(siteId) // Invoke (request-response)
144+
window.ipcApi.openSiteURL(id) // Send (one-way)
145+
146+
// Main (src/ipc-handlers.ts) handles:
147+
ipcMain.handle('startServer', async (event, siteId) => { ... })
148+
ipcMain.on('openSiteURL', (event, id) => { ... })
149+
```
150+
151+
### 3. WordPress Provider Pattern (Strategy Pattern)
152+
Two implementations for running WordPress:
153+
- **PlaygroundCliProvider**: Uses `@wp-playground/cli` with Blueprint support (feature-gated)
154+
- **WpNowProvider**: Fallback provider with core functionality
155+
156+
Both implement the `WordPressProvider` interface with methods:
157+
- `startServer()` - Start a WordPress site
158+
- `setupWordPressSite()` - Initialize WordPress installation
159+
- `createServerProcess()` - Create server child process
160+
161+
### 4. Redux Store Architecture (RTK)
162+
```typescript
163+
// src/stores/index.ts
164+
- chat: Chat/AI Assistant messages
165+
- sync: WordPress.com sync state
166+
- connectedSites: Connected WordPress.com sites
167+
- snapshot: Site snapshots/backups
168+
- onboarding: First-run experience state
169+
- provider constants: WordPress/PHP versions
170+
- RTK Query APIs for data fetching:
171+
- wpcomApi: WordPress.com API calls
172+
- installedAppsApi: System apps detection
173+
- wordpressVersionsApi: Available WP versions
174+
```
175+
176+
### 5. Site Management
177+
**SiteServer Class** (`src/site-server.ts`):
178+
- Manages individual WordPress site instances
179+
- Handles server start/stop
180+
- Manages SSL certificates for custom domains
181+
- Integrates with port finder and host file management
182+
- Metadata: WordPress version, blueprint configuration
183+
184+
### 6. Data Flow
185+
```
186+
User Action (React)
187+
188+
IPC Call to Main Process (via contextBridge)
189+
190+
IPC Handler Logic (src/ipc-handlers.ts)
191+
192+
Business Logic (lib/*, modules/*)
193+
194+
WordPress Provider / SiteServer
195+
196+
Response back to Renderer
197+
198+
Redux State Update / Re-render
199+
```
200+
201+
## Core Technologies & Dependencies
202+
203+
### Frontend (Renderer)
204+
- **React 18** - UI library
205+
- **Redux Toolkit** - State management
206+
- **RTK Query** - Data fetching and caching
207+
- **@wordpress/components** - WordPress UI component library
208+
- **TailwindCSS** - Utility-first CSS
209+
- **TypeScript** - Type safety
210+
- **Vite** - Build tool and dev server
211+
212+
### Main Process
213+
- **Electron 38** - Desktop framework
214+
- **@php-wasm/node** - PHP runtime in Node.js
215+
- **@php-wasm/universal** - Universal PHP WASM
216+
- **@wp-playground/blueprints** - Blueprint compilation
217+
- **@wp-playground/cli** - Playground CLI integration
218+
- **express** - Lightweight HTTP server for sites
219+
220+
### Development
221+
- **electron-vite** - Electron build orchestration
222+
- **electron-forge** - Electron packaging and distribution
223+
- **jest** - Unit testing
224+
- **Playwright** - E2E testing
225+
- **ESLint / Prettier** - Code quality
226+
227+
### Other Key Libraries
228+
- **Sentry** - Error tracking and monitoring
229+
- **wpcom** - WordPress.com API client
230+
- **zod** - Schema validation
231+
- **yargs** - CLI argument parsing
232+
233+
## Build & Distribution
234+
235+
### Build Process
236+
1. **CLI Build** (`vite build --config vite.cli.config.ts`) - Build standalone CLI
237+
2. **Electron Build** (`electron-vite build`) - Compiles main, preload, and renderer
238+
3. **Package** (`electron-forge make`) - Creates platform-specific installers
239+
240+
### Supported Platforms
241+
- **macOS** (Intel x64, Apple Silicon ARM64) - DMG installers
242+
- **Windows** (x64, ARM64) - MSIX/Squirrel.Windows
243+
- **Linux** - DEB packages
244+
245+
### Bundling
246+
- Main process: Rollup bundles to single file with multiple entry points
247+
- Renderer: Vite with React plugin, CSS code splitting, chunk optimization
248+
- Resources: wp-files, assets, bin scripts, CLI executable included in ASAR archive
249+
250+
## Important Conventions
251+
252+
### File Naming
253+
- React components: PascalCase (e.g., `MainSidebar.tsx`)
254+
- Utilities/helpers: camelCase (e.g., `get-site-url.ts`)
255+
- Types/interfaces: Define in separate files or within usage files
256+
- Tests: `.test.ts` or `.test.tsx` suffix
257+
258+
### IPC Handler Pattern
259+
```typescript
260+
// In src/ipc-handlers.ts - always follows this pattern:
261+
export async function handlerName(
262+
event: IpcMainInvokeEvent,
263+
...args: Parameters
264+
): Promise<ReturnType> {
265+
// Implementation
266+
}
267+
268+
// Define handler names in src/constants.ts
269+
export const IPC_VOID_HANDLERS = ['openSiteURL', ...] // Fire-and-forget
270+
```
271+
272+
### Storage Pattern
273+
User data stored at:
274+
- **macOS**: `~/Library/Application Support/WordPress Studio/appdata-v1.json`
275+
- **Windows**: `%APPDATA%/WordPress Studio/appdata-v1.json`
276+
- **Linux**: `~/.config/WordPress Studio/appdata-v1.json`
277+
278+
Storage is protected by file locking (`lockAppdata()` / `unlockAppdata()`).
279+
280+
### Localization
281+
- Strings use `@wordpress/i18n` (`__()` function)
282+
- Locales loaded from `common/translations/`
283+
- Renderer uses `<I18nProvider>` context
284+
- CLI translates via `loadTranslations()` in CLI bootstrap
285+
286+
## WordPress Playground Integration
287+
288+
### Blueprints
289+
- Complex site configurations declaratively defined
290+
- Compiled to runtime executable by `@wp-playground/blueprints`
291+
- Feature detection/filtering: `filterUnsupportedBlueprintFeatures()` in `src/lib/blueprint-features.ts`
292+
- Passed to server startup for automatic setup
293+
294+
### PHP WASM Runtime
295+
- `@php-wasm/node` provides PHP runtime in Node.js
296+
- Runs in child processes via `WorkerThreads`
297+
- WP-CLI integration: `WpCliProcess` class wraps CLI commands
298+
- Server process: Handles PHP execution and WordPress HTTP requests
299+
300+
## Sync & WordPress.com Integration
301+
302+
### Authentication
303+
- OAuth flow via `common/lib/oauth.ts`
304+
- Token stored securely in app storage
305+
- Integrated with `wpcom` library for API calls
306+
307+
### Sync Operations
308+
- Modeled as async operations with progress tracking
309+
- Stored in Redux state (`sync` slice)
310+
- Can be canceled by user
311+
- Persist state across app restarts
312+
313+
### Supported Sync Features
314+
- Pull: Download WordPress.com site to local
315+
- Push: Upload local site to WordPress.com
316+
- Selective sync: Choose what content to transfer (plugins, themes, database, etc.)
317+
318+
## Key Entry Points
319+
320+
- **App Start**: `npm start` → electron-vite dev server
321+
- **CLI**: `npm run cli:build` → builds `/dist/cli/index.js`
322+
- **Tests**: `npm test` → Jest test runner
323+
- **E2E Tests**: `npm run e2e` → Playwright
324+
- **Packaging**: `npm run make` → electron-forge make (creates installers)
325+
326+
## State Management Strategy
327+
328+
Redux is used for UI state that needs to be preserved:
329+
- Chat message history (localStorage persisted)
330+
- Sync operations in progress
331+
- Connected WordPress.com sites
332+
- Snapshots/backups
333+
- Onboarding completion status
334+
335+
Local component state used for temporary UI interactions.
336+
337+
## Security Considerations
338+
339+
1. **Renderer Sandbox**: All renderers run sandboxed (enforced with `app.enableSandbox()`)
340+
2. **IPC Validation**: All IPC senders validated against expected origin
341+
3. **Content Security Policy**: Strict CSP header set for main window
342+
4. **No Node Integration**: Renderer cannot access Node.js APIs directly
343+
5. **HTTPS Support**: Optional HTTPS for custom domains with self-signed certificates
344+
6. **Password Encoding**: Admin passwords encoded/decoded for storage
345+
346+
## Performance Optimizations
347+
348+
- **Code Splitting**: Vendor and Sentry chunks extracted separately
349+
- **CSS Code Split**: Separate CSS files for better caching
350+
- **WASM Bundling**: WASM files included as external assets
351+
- **Port Finder**: Efficient port availability checking with caching
352+
- **Snapshot System**: Browser-like snapshots for fast site restoration
353+
354+
---
355+
356+
Last Updated: 2025-11-05
357+
Repository: https://github.com/Automattic/studio
358+
License: GPLv2 or later

0 commit comments

Comments
 (0)