agentleFS
airweave-aiairweave-ai/airweave/.cursor/rules/frontend-rules.mdc

airweave / rules

Cursor rule6.6k starsChanged 8 months agoMITArchived repositoryView on GitHub

The API client is the central hub for all backend communication with sophisticated features:

The file

Show its rules and text

We split this frontend-rules.mdc into the rules it gives an agent

20 rules. About 0 are common, 5 are distinctive, and 15 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈5

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 15

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Redirect validation: Always use safeRedirectPath() from lib/utils/url-validation.ts when assigning window.location.href after an OAuth …

    line 131
  2. Distinctive:

    All browser OAuth flows use a two-step handoff to trigger the initial sync:

    line 134
  3. Very specific:

    Cleanup: Only remove the oauth_claim_token:* entry from sessionStorage after verify-oauth returns a successful (response.ok) response — …

    line 138
  4. Very specific:

    Use onNext, onBack, onCancel callbacks

    line 153
  5. Distinctive:

    Use appropriate toast types for different scenarios

    line 245
  6. Distinctive:

    Keep messages concise and actionable

    line 246
  7. Distinctive:

    Avoid overusing toasts for non-critical information

    line 247
  8. Very specific:

    Always try to user interfaces defined universally in /types/index.ts (which wrap Pydantic schemas defined in backend)

    line 262
  9. Distinctive:

    Use Zustand stores for global state

    line 295
  10. Very specific:

    Use Tailwind classes with cn() utility

    line 320
  11. Very specific:

    Use useOrganizationContext() to gate mutation actions by the current user's organization role:

    line 355
  12. Very specific:

    Never assign window.location.href (or similar navigation) to a URL derived from query parameters, sessionStorage, or any external input …

    line 381
  13. Very specific:

    Use safeRedirectPath() from lib/utils/url-validation.ts — it rejects absolute URLs, protocol-relative paths, and other open-redirect …

    line 382
  14. Very specific:

    Use isSafeRedirectPath() from the same module when you need a boolean check without a fallback

    line 383
  15. Very specific:

    Never use Math.random() — it is banned by ESLint

    line 387
  16. Very specific:

    Use crypto.getRandomValues() for random bytes/integers

    line 388
  17. Very specific:

    Use crypto.randomUUID() for UUIDs

    line 389
  18. Very specific:

    Never assign to innerHTML — it is banned by ESLint (CASA-41)

    line 392
  19. Very specific:

    Never use dangerouslySetInnerHTML — it is banned by ESLint (CASA-41)

    line 393
  20. Very specific:

    Use React state-driven rendering and textContent instead

    line 394

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
frontend-rules.mdc
---
globs: **/frontend/**
alwaysApply: false
---
# Airweave Frontend Architecture & Guidelines

## Tech Stack & Core Technologies
- **React 18** with TypeScript for type-safe component development
- **Vite** for fast development builds and HMR
- **TailwindCSS** with **ShadCN UI** components for consistent design
- **Radix UI** primitives with **Lucide** icons for accessible components
- **React Router** for client-side routing with file-based organization
- **Zustand** for state management with persistence
- **React Query** for server state and data fetching
- **Auth0** for authentication with custom context wrapper
- **SSE (Server-Sent Events)** for real-time sync progress

## Project Structure
```
frontend/src/
├── components/         # Reusable UI components
│   ├── ui/            # ShadCN UI primitives
│   ├── shared/        # Shared business components
│   └── [feature]/     # Feature-specific components
├── pages/             # Route-level components
├── lib/               # Core utilities and providers
│   ├── api.ts         # API client with auth integration
│   ├── stores/        # Zustand state stores
│   └── auth-context.tsx # Auth provider
├── hooks/             # Custom React hooks
├── services/          # Business logic services
├── config/            # Configuration files
├── constants/         # App constants
└── styles/            # Global CSS styles
    └── toast.css      # Custom toast styling
```

## API Layer (`lib/api.ts`)

The API client is the central hub for all backend communication with sophisticated features:

### Core Features
- **Token Management**: Automatic token injection via provider pattern
- **Request Queuing**: Queues requests while auth initializes
- **Organization Context**: Auto-injects `X-Organization-ID` header
- **Session Tracking**: Auto-injects `X-Airweave-Session-ID` header with PostHog session ID for session replay linking
- **Auto-Retry**: Refreshes token on 401/403 and retries
- **Organization Auto-Switching**: Detects resource org mismatches and switches context
- **Type-Safe Responses**: Returns typed Response objects

### Usage Pattern
```typescript
// Always use relative paths (no /api/v1 prefix)
const response = await apiClient.get('/collections');
const response = await apiClient.post('/source-connections', data);
const response = await apiClient.delete('/api-keys', { id: keyId });
```

### Token Provider Pattern
The API client uses a pluggable token provider set up in `main.tsx`:
```typescript
setTokenProvider({
  getToken: async () => await auth.getToken(),
  clearToken: () => auth.clearToken(),
  isReady: () => auth.isReady()
});
```

## State Management Architecture

### 1. **Organization Store** (`stores/organizations.ts`)
- Manages user organizations with persistence
- Handles organization switching with state cleanup
- Auto-selects best organization (current → primary → first)
- Clears org-specific data on switch (collections, API keys)

### 2. **Collections Store** (`stores/collections.ts`)
- Caches collections (with API-provided `source_connection_summaries` for list views)
- Implements event-driven updates via custom event bus
- Smart caching with force refresh option
- Handles collection CRUD events automatically
- Source connection details for list pages come from `GET /collections` response (no per-card fetching)

### 3. **Sync State Store** (`stores/syncStateStore.ts`)
- Real-time sync progress via SSE
- Manages multiple concurrent subscriptions
- Session storage for progress persistence
- Automatic cleanup and health checks

### 4. **API Keys Store** (`stores/apiKeys.ts`)
- Organization-scoped API key management
- Auto-clears on organization switch

## Authentication Flow

### Auth0 Integration
1. **Provider Hierarchy**:
   ```
   PostHogProvider → ThemeProvider → BrowserRouter → Auth0Provider → AuthProvider → ApiAuthConnector → App
   ```
   - **PostHogProvider**: Initializes PostHog analytics and session tracking (outermost)
   - **ThemeProvider**: Manages dark/light theme persistence
   - **BrowserRouter**: React Router client-side routing
   - **Auth0Provider**: Handles user authentication
   - **AuthProvider**: Manages token lifecycle and auth state
   - **ApiAuthConnector**: Connects auth to API client

2. **Auth Context** (`lib/auth-context.tsx`):
   - Manages Auth0 token lifecycle
   - Provides `getToken()` for API calls
   - Handles dev mode (auth disabled)
   - Token initialization tracking

3. **Token Caching Strategy** (`lib/auth0-provider.tsx`):
   - `getCacheLocation()` selects `memory` for custom Auth0 domains and `localstorage` for standard `*.auth0.com` tenants
   - Custom domains share the app's eTLD+1, so the Auth0 session cookie is first-party — tokens stay in memory only (no XSS surface via localStorage)
   - Standard tenants use a third-party cookie that Safari ITP / Firefox strict / Chrome incognito block, so tokens must be persisted in localStorage
   - `useRefreshTokens={true}` — refresh token rotation is always enabled
   - `useRefreshTokensFallback={true}` — enables iframe-based silent auth as a fallback when the refresh token is unavailable (e.g. after a page refresh with memory cache)

4. **Auth Guard** (`components/AuthGuard.tsx`):
   - Protects routes requiring authentication
   - Initializes organizations on first load
   - Redirects to `/no-organization` if needed

### OAuth2 Source Authentication
- Separate OAuth flow for connecting data sources
- State preserved in sessionStorage during redirect
- Handles both standard and SemanticMcp flows
- Error recovery with detailed user feedback
- **Redirect validation**: Always use `safeRedirectPath()` from `lib/utils/url-validation.ts` when assigning `window.location.href` after an OAuth callback — never use raw query-string values

#### Browser OAuth Claim-Token Contract
All browser OAuth flows use a two-step handoff to trigger the initial sync:

1. **Before redirect**: `POST /source-connections` returns `auth.claim_token`. Store it in `sessionStorage` keyed as `oauth_claim_token:{source_connection_id}` before navigating to `auth.auth_url`.
2. **After redirect**: The backend callback 303-redirects to the frontend with `?status=success&source_connection_id=...`. On landing, retrieve the stored claim token and call `POST /source-connections/{id}/verify-oauth` with `{ claim_token }` to trigger the deferred sync workflow.
3. **Cleanup**: Only remove the `oauth_claim_token:*` entry from `sessionStorage` after `verify-oauth` returns a successful (`response.ok`) response — this preserves the token for retry on failure.

Skipping the `verify-oauth` call leaves the sync job stuck in `PENDING` indefinitely.

## Component Patterns

### 1. **Dialog Flow System** (`components/shared/DialogFlow.tsx`)
- Multi-step dialog orchestration
- State preservation across OAuth redirects
- Error handling with retry capabilities
- Flexible view composition

### 2. **View Components**
- Encapsulate specific UI flows
- Accept `viewData` prop for state
- Use `onNext`, `onBack`, `onCancel` callbacks
- Handle errors via `onError` prop

### 3. **Error Handling Pattern**
```typescript
const handleError = (error: Error | string, errorSource?: string) => {
  if (onError) {
    onError(error, errorSource);
  } else {
    redirectWithError(navigate, {
      serviceName: errorSource,
      errorMessage: error.message,
      dialogId: viewData?.dialogId
    });
  }
};
```

## Real-Time Features

### SSE (Server-Sent Events)
- Used for sync job progress updates
- Automatic reconnection handling
- Progress persistence across page reloads
- Multiple concurrent subscriptions

### Event Bus System
- Custom events for collection updates
- Window-level event dispatching
- Auto-refresh on CRUD operations

## Routing Architecture

### Route Structure
```typescript
// Public routes (no auth required)
/login
/callback
/semantic-mcp
/no-organization

// Protected routes (auth required)
/ (dashboard)
/collections
/collections/:readable_id
/organization/settings
```

### Route Protection
- `AuthGuard` wrapper for protected routes
- Organization initialization on first access
- Automatic redirects for unauthenticated users

## Error Handling & User Feedback

### Error Utils (`lib/error-utils.ts`)
- Centralized error storage in localStorage
- Redirect with error context preservation
- Dialog-specific error targeting via `dialogId`

### Toast Notifications

#### Setup & Configuration
- **Sonner** library with custom styling via `toast-custom` class
- Global CSS import: `import '@/styles/toast.css'` in `App.tsx`
- Toaster configured with `className: 'toast-custom'` for custom styling

#### Toast Types & Patterns
```typescript
import { toast } from 'sonner';

// Success notifications (green theme)
toast.success('Operation completed successfully');

// Error notifications (red theme)
toast.error('Something went wrong');

// Info notifications (blue theme)
toast.info('Additional information');

// Warning notifications (yellow theme)
toast.warning('Please review this action');
```

#### Custom Styling Features
- **Enhanced animations**: Slide-in from right with custom easing
- **Type-specific styling**: Each toast type has distinct colors and borders
- **Colored left border**: Visual indicator for toast type
- **Consistent theming**: Uses CSS variables for dark/light mode
- **Hover effects**: Subtle transform and shadow changes

#### Usage Guidelines
- Use appropriate toast types for different scenarios
- Keep messages concise and actionable
- Avoid overusing toasts for non-critical information
- Organization switch notifications use success type

### Error Views
- `ConnectionErrorView` for connection failures
- Retry capabilities with state restoration
- Technical details with copy functionality

## Development Patterns

### 1. **TypeScript Usage**
- Strict typing for all components
- Interface definitions for props
- Type inference where possible
- Avoid `any` types
- Always try to user interfaces defined universally in /types/index.ts (which wrap Pydantic schemas defined in backend)

### 2. **Component Organization**
```typescript
// Standard component structure
interface ComponentProps {
  // Required props first
  onAction: () => void;
  data: DataType;
  // Optional props with defaults
  variant?: 'primary' | 'secondary';
}

export const Component: React.FC<ComponentProps> = ({
  onAction,
  data,
  variant = 'primary'
}) => {
  // Hooks first
  const [state, setState] = useState();

  // Effects next
  useEffect(() => {}, []);

  // Handlers
  const handleClick = () => {};

  // Render
  return <div>...</div>;
};
```

### 3. **State Management Best Practices**
- Use Zustand stores for global state
- React Query for server state
- Local state for UI-only concerns
- Custom hooks for shared logic

### 4. **API Integration Patterns**
```typescript
// Always check response.ok
const response = await apiClient.get('/endpoint');
if (!response.ok) {
  throw new Error(`Failed: ${response.status}`);
}
const data = await response.json();

// Handle loading states
const [isLoading, setIsLoading] = useState(false);
try {
  setIsLoading(true);
  // ... API call
} finally {
  setIsLoading(false);
}
```

### 5. **Styling Guidelines**
- Use Tailwind classes with `cn()` utility
- Component variants with CVA
- Consistent spacing with Tailwind scale
- Dark mode support via CSS variables

## Performance Optimizations

### 1. **Data Caching**
- Collections cached until force refresh
- Source details cached by short name
- API keys cached per organization

### 2. **Request Deduplication**
- Prevents duplicate requests while loading
- Smart organization context switching
- Request queuing during auth init

### 3. **Component Optimization**
- Memoization for expensive computations
- Callback refs for stable references
- Lazy loading for route components

## Security Considerations

### 1. **Token Management**
- Tokens never exposed in URLs
- Automatic cleanup on logout
- Secure storage in Auth0

### 2. **Organization Isolation**
- API automatically scopes to current org
- State cleared on organization switch
- Proper access control checks

### 3. **Role-Based UI Gating**
Use `useOrganizationContext()` to gate mutation actions by the current user's organization role:

```typescript
const { canManageOrganization } = useOrganizationContext();
const canManage = canManageOrganization();
```

Standard pattern — disable controls with a tooltip for non-admins:
```typescript
<Button disabled={!canManage} title={!canManage ? "Admin access required" : undefined}>
  Create
</Button>
```

Available helpers from `useOrganizationContext()`:
- `canManageOrganization(orgId?)` — returns `true` for `admin` or `owner`
- `canDeleteOrganization(orgId?)` — returns `true` for `owner` only
- `isCurrentUserOwner(orgId?)` — owner check
- `isCurrentUserAdmin(orgId?)` — admin or owner check

### 4. **Error Handling**
- Sensitive data stripped from errors
- Token cache location is conditional: custom Auth0 domains use `memory` (no localStorage exposure), standard `*.auth0.com` tenants use `localstorage` (necessary due to third-party cookie restrictions)
- Secure OAuth state management

### 5. **Redirect Safety**
- Never assign `window.location.href` (or similar navigation) to a URL derived from query parameters, `sessionStorage`, or any external input without validation
- Use `safeRedirectPath()` from `lib/utils/url-validation.ts` — it rejects absolute URLs, protocol-relative paths, and other open-redirect vectors, returning a safe fallback
- Use `isSafeRedirectPath()` from the same module when you need a boolean check without a fallback
- This applies everywhere, but is especially critical in OAuth callback handlers (`AuthCallback.tsx`, `SemanticMcpCallback.tsx`)

### 6. **Randomness**
- Never use `Math.random()` — it is banned by ESLint
- Use `crypto.getRandomValues()` for random bytes/integers
- Use `crypto.randomUUID()` for UUIDs

### 7. **XSS Prevention**
- Never assign to `innerHTML` — it is banned by ESLint (CASA-41)
- Never use `dangerouslySetInnerHTML` — it is banned by ESLint (CASA-41)
- Use React state-driven rendering and `textContent` instead

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.