# https://github.com/nocobase/nocobase 项目说明书

生成时间：2026-05-18 02:07:18 UTC

## 目录

- [Overview](#overview)
- [System Architecture](#system-architecture)
- [Deployment](#deployment)
- [Plugin System](#plugin-system)
- [Data Modeling](#data-modeling)
- [Interface Builder](#interface-builder)
- [Workflow Engine](#workflow-engine)
- [Authentication and Permissions](#authentication-permissions)
- [AI Integration](#ai-integration)
- [File Storage](#file-storage)
- [Cluster Mode](#cluster-mode)
- [Plugin Development](#plugin-development)

<a id='overview'></a>

## Overview

### 相关页面

相关主题：[System Architecture](#system-architecture), [Plugin System](#plugin-system), [AI Integration](#ai-integration)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/nocobase/nocobase/blob/main/README.md)
- [docs/README.md](https://github.com/nocobase/nocobase/blob/main/docs/README.md)
- [docs/docs/en/index.md](https://github.com/nocobase/nocobase/blob/main/docs/docs/en/index.md)
- [packages/core/client/src/schema-initializer/index.md](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-initializer/index.md)
- [packages/core/client/src/schema-component/index.md](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-component/index.md)
- [packages/core/flow-engine/src/flowSettings.ts](https://github.com/nocobase/nocobase/blob/main/packages/core/flow-engine/src/flowSettings.ts)
- [packages/core/client/src/variables/hooks/useBuiltinVariables.ts](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/variables/hooks/useBuiltinVariables.ts)
- [packages/plugins/@nocobase/plugin-mobile/src/client/pages/index.md](https://github.com/nocobase/nocobase/blob/main/packages/plugins/@nocobase/plugin-mobile/src/client/pages/index.md)
- [packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/chatbox/stores/chat-messages.ts](https://github.com/nocobase/nocobase/blob/main/packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/chatbox/stores/chat-messages.ts)
</details>

# Overview

NocoBase is an open-source **NoCode/LowCode platform** that enables users to build scalable business applications through a visual interface without writing code. It provides a comprehensive system for creating data models, designing user interfaces, configuring business workflows, and extending functionality through a plugin-based architecture.

## Architecture Overview

NocoBase follows a modern full-stack architecture with clear separation between client and server components. The platform is built on a plugin-based architecture that allows for flexible extension and customization.

```mermaid
graph TD
    Client["Client (React)"]
    Server["Server (Node.js)"]
    Database["Database"]
    Client --> Server
    Server --> Database
    
    subgraph Client
        UI["UI Components"]
        Schema["Schema System"]
        Variables["Variable System"]
        PM["Plugin Manager"]
    end
    
    subgraph Server
        API["API Layer"]
        FlowEngine["Flow Engine"]
        Plugins["Plugin System"]
    end
    
    subgraph Plugins
        Mobile["Mobile Plugin"]
        AI["AI Plugin"]
        ThemeEditor["Theme Editor Plugin"]
    end
```

### Core Components

| Component | Description | Location |
|-----------|-------------|----------|
| Schema System | Declarative UI and data structure definition | `packages/core/client/src/schema-component/` |
| Flow Engine | Business workflow execution engine | `packages/core/flow-engine/` |
| Plugin Manager | Dynamic plugin loading and management | `packages/core/client/src/pm/` |
| Variable System | Runtime variable resolution and context | `packages/core/client/src/variables/` |
| Schema Initializer | Visual block insertion and configuration | `packages/core/client/src/schema-initializer/` |
| Schema Settings | Configuration panel for schema blocks | `packages/core/client/src/schema-settings/` |

资料来源：[packages/core/client/src/schema-component/index.md:1]()

## Data Model Architecture

NocoBase uses a schema-based approach for defining data models and user interfaces. Collections represent database tables, and fields define the structure of data entries.

```mermaid
graph LR
    Collection["Collection<br/>(Data Model)"]
    Field["Field<br/>(Column Definition)"]
    Association["Association<br/>(Relationship)"]
    Schema["Schema<br/>(UI Configuration)"]
    
    Collection --> Field
    Collection --> Association
    Schema --> Collection
```

The system supports multiple data types and associations, enabling complex business data modeling scenarios.

资料来源：[packages/core/client/src/schema-component/antd/association-select/index.md:1]()

## User Interface System

### Schema Component Architecture

The UI in NocoBase is built using a **Schema-based Component System**. Each UI element is defined through a schema configuration that describes its type, properties, and behavior.

#### Built-in Components

NocoBase provides several built-in components ready for use:

| Component | Purpose | Location |
|-----------|---------|----------|
| `GeneralSchemaDesigner` | Main schema designer wrapper | `packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx` |
| `LinkageFilter` | Frontend linkage rules and condition configuration | `packages/core/client/src/schema-component/antd/linkageFilter/index.md` |
| `AssociationSelect` | Data selection linked to collections and fields | `packages/core/client/src/schema-component/antd/association-select/index.md` |

#### Schema Designer Features

The schema designer provides visual editing capabilities for:

- **Drag and Drop**: Rearrange schema blocks within the interface
- **Designable Toggle**: Switch between view and edit modes
- **Initializer Integration**: Insert new schema blocks dynamically
- **Settings Panel**: Configure properties of selected blocks

```mermaid
graph TD
    User["User"] --> Designer["Schema Designer"]
    Designer --> Drag["Drag & Drop"]
    Designer --> Initializer["Schema Initializer"]
    Designer --> Settings["Schema Settings"]
    
    Drag --> Block1["Block 1"]
    Drag --> Block2["Block 2"]
    Initializer --> Block3["New Block"]
    Settings --> Config["Configuration"]
```

资料来源：[packages/core/client/src/schema-component/index.md:1]()

### Schema Initializer

The Schema Initializer enables dynamic insertion of schema blocks into the design canvas. It supports:

- **Built-in Types**: Pre-configured component templates
- **Dynamic Visibility**: Show/hide items based on conditions
- **Dynamic Children**: Load child items on demand
- **Insert Schema**: Insert complete schema structures including actions and form items

资料来源：[packages/core/client/src/schema-initializer/index.md:1]()

## Variable System

Variables provide dynamic data context for formulas, conditions, and display values throughout the application. NocoBase includes a comprehensive built-in variable system.

### Built-in Variables

| Variable | Description | Type |
|----------|-------------|------|
| `$date` | Current date (deprecated, use `$nDate`) | DateTime |
| `$nDate` | Current date in ISO format | DateTime |
| `$nExactDate` | Exact current datetime | DateTime |
| `$system` | System context with `now()` function (deprecated) | Object |
| `$nRole` | Current user's role information | Object |
| `$nUser` | Current authenticated user details | Object |
| `currentTime` | Current timestamp (deprecated) | String |
| URL Parameters | Query string variables | Various |

### Variable Resolution Flow

```mermaid
graph LR
    Request["Request Context"]
    Resolver["Variable Resolver"]
    Context["Context Variables"]
    Output["Resolved Values"]
    
    Request --> Resolver
    Context --> Resolver
    Resolver --> Output
```

Variables are evaluated at runtime and support context-dependent values from:

- Current user session
- Current role permissions
- URL query parameters
- Environment variables
- Date/time calculations

资料来源：[packages/core/client/src/variables/hooks/useBuiltinVariables.ts:1]()

## Plugin System

NocoBase adopts a **plugin-first architecture**. All features are implemented as plugins that can be dynamically loaded, enabled, disabled, and configured.

### Plugin Manager

The Plugin Manager (`pm`) handles plugin lifecycle operations:

| Operation | Description |
|-----------|-------------|
| Install | Add new plugin to the system |
| Uninstall | Remove plugin from the system |
| Enable | Activate plugin functionality |
| Disable | Deactivate plugin without removal |
| Configure | Manage plugin-specific settings |

```mermaid
graph TD
    PM["Plugin Manager"]
    Store["Plugin Store"]
    Loader["Plugin Loader"]
    Registry["Plugin Registry"]
    
    PM --> Store
    PM --> Loader
    PM --> Registry
    Loader --> Plugin["Plugin Instance"]
    Registry --> Plugin
```

### Plugin Detail View

Each plugin displays comprehensive information:

- **Package Name**: Unique plugin identifier
- **Version**: Semantic version number
- **Description**: Plugin functionality summary
- **Homepage**: Documentation or project URL
- **Author**: Plugin maintainer information
- **License**: Legal usage terms
- **Dependencies**: Compatibility check with core system

资料来源：[packages/core/client/src/pm/PluginDetail.tsx:1]()

### Available Plugin Categories

| Category | Examples | Purpose |
|----------|----------|---------|
| Mobile | `@nocobase/plugin-mobile` | Mobile-specific UI and navigation |
| AI | `@nocobase/plugin-ai` | AI-powered features and assistants |
| Theme | `@nocobase/plugin-theme-editor` | Visual theme customization |
| Workflow | Flow Engine | Business process automation |

## Mobile Support

The Mobile plugin provides responsive interfaces and navigation optimized for mobile devices.

### Desktop Mode

When accessing mobile pages from a desktop browser, the `DesktopMode` component renders a responsive wrapper:

```tsx
<DesktopMode>
  <Mobile />
</DesktopMode>
```

### Page Types

| Page Type | Description |
|-----------|-------------|
| Home Page | Default landing page; redirects to first route if not configured |
| NotFound Page | 404 error page for unmatched routes |
| Custom Pages | User-defined pages with custom components |

#### Home Page Modes

- **Basic**: Default empty home page
- **Custom Home**: User-defined home page component
- **No Routes**: Configuration without any routes

资料来源：[packages/plugins/@nocobase/plugin-mobile/src/client/pages/index.md:1]()

### Mobile Navigation

The `MobileTabBar` component provides tab-based navigation with `Bar.Item` elements:

```mermaid
graph LR
    TabBar["MobileTabBar"]
    BarItem["Bar.Item"]
    Link["Link Component"]
    
    TabBar --> BarItem
    BarItem --> Link
    Link --> Route["Route Path"]
```

#### Link Types

| Type | Description |
|------|-------------|
| Inner Link | Navigate to internal application routes |
| Outer Page | Link to external URLs |
| Selected | Display currently active/selected state |

资料来源：[packages/plugins/@nocobase/plugin-mobile/src/client/mobile-layout/index.md:1]()

## Workflow Engine

The Flow Engine (`flow-engine`) provides a visual workflow execution environment for business process automation.

### Flow Settings

Flows can be configured with custom interfaces and behaviors:

| Setting | Description |
|---------|-------------|
| `title` | Display name for the flow |
| `description` | Human-readable flow description |
| `footer` | Customizable footer with buttons |
| `onCancel` | Callback when cancel is triggered |
| `onSaved` | Callback when configuration is saved |

#### Footer Configuration Options

- **Default**: Use system-provided buttons
- **Wrap**: Add custom content around origin buttons
- **Functional**: Completely replace with custom composition
- **Hidden**: Set to `null` to hide footer entirely

```typescript
// Wrap existing buttons
footer: (originNode, { OkBtn, CancelBtn }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
    <span>Additional info</span>
    {originNode}
  </div>
)

// Hide footer
footer: null
```

资料来源：[packages/core/flow-engine/src/flowSettings.ts:1]()

## AI Integration

The AI plugin (`@nocobase/plugin-ai`) extends NocoBase with artificial intelligence capabilities.

### Chat Messages Store

AI features utilize a state management system for chat interactions:

```mermaid
graph TD
    ChatStore["ChatMessages Store"]
    Messages["messages[]"]
    Attachments["attachments[]"]
    Context["contextItems[]"]
    System["systemMessage"]
    
    ChatStore --> Messages
    ChatStore --> Attachments
    ChatStore --> Context
    ChatStore --> System
```

#### Store Actions

| Action | Purpose |
|--------|---------|
| `setMessages` | Replace all messages |
| `addMessage` | Append single message |
| `addMessages` | Append multiple messages |
| `updateLastMessage` | Modify most recent message |
| `removeMessage` | Delete message by key |
| `setAttachments` | Update file attachments |
| `addContextItems` | Add context items with deduplication |
| `setSystemMessage` | Update system prompt |

#### Datasource Management

AI features support multiple data sources with configuration:

- **Collection**: Target collection reference
- **Limit**: Maximum records to retrieve
- **Description**: Data source purpose documentation

资料来源：[packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/chatbox/stores/chat-messages.ts:1]()

### Documentation Tools

The AI plugin includes tools for reading and navigating documentation:

```mermaid
graph LR
    Input["Module Key Input"]
    Parser["Path Parser"]
    Resolver["Path Resolver"]
    Output["File/Directory Content"]
    
    Input --> Parser
    Parser --> Resolver
    Resolver --> Output
```

Key functions:

- `normalizeModuleKey`: Validates and normalizes module identifiers
- `resolveDocPath`: Maps module keys to absolute file paths
- Documentation entries include both files and subdirectories with hierarchical structure

资料来源：[packages/plugins/@nocobase/plugin-ai/src/server/tools/docs.ts:1]()

## Frontend Utilities

### CSS Module Resolution

Utility functions support frontend asset handling:

| Function | Purpose |
|----------|---------|
| `isCssFile(url)` | Determines if a URL points to a CSS file |

The function handles:

- Query string parameters (e.g., `style.css?v=123`)
- Hash fragments (e.g., `style.css#section`)
- Extension-based file type detection

```typescript
isCssFile('style.css')        // true
isCssFile('style.css?v=123')   // true
isCssFile('style.css#section') // true
isCssFile('script.js')         // false
```

资料来源：[packages/core/flow-engine/src/utils/resolveModuleUrl.ts:1]()

## Technology Stack

| Layer | Technology | Purpose |
|-------|------------|---------|
| Frontend Framework | React | UI component rendering |
| State Management | Zustand | Lightweight state management |
| UI Library | Ant Design | Pre-built component library |
| Backend Runtime | Node.js | Server-side execution |
| Database | Multiple (via ORM) | Data persistence |
| Package Manager | Monorepo (npm workspaces) | Code organization |

## Key Design Principles

1. **Schema-Driven**: All configurations are declarative schema definitions
2. **Plugin-First**: Every feature is a plugin with isolated scope
3. **Visual Configuration**: No-code interfaces for common operations
4. **Code Extension**: Low-code escape hatch for custom requirements
5. **Dynamic Loading**: Runtime plugin activation without full reload

## Documentation Structure

The NocoBase documentation is organized as follows:

```
docs/
├── README.md                 # Documentation index
├── docs/
│   └── en/                   # English documentation
│       └── index.md          # Entry point
├── packages/
│   └── plugins/              # Plugin-specific docs
└── README.md                 # Root documentation
```

资料来源：[docs/README.md:1]()

## Getting Started

To begin working with NocoBase:

1. **Understand the Architecture**: Familiarize yourself with the plugin-based structure
2. **Define Data Models**: Create collections and configure fields in the admin interface
3. **Design UI Schemas**: Use the schema designer to build application interfaces
4. **Configure Workflows**: Set up automation using the flow engine
5. **Extend with Plugins**: Add custom functionality through the plugin system

---

<a id='system-architecture'></a>

## System Architecture

### 相关页面

相关主题：[Overview](#overview), [Plugin System](#plugin-system), [Deployment](#deployment)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/nocobase/nocobase/blob/main/README.md)
- [packages/plugins/@nocobase/plugin-data-source-main/README.md](https://github.com/nocobase/nocobase/blob/main/packages/plugins/@nocobase/plugin-data-source-main/README.md)
- [packages/plugins/@nocobase/plugin-form-drafts/README.md](https://github.com/nocobase/nocobase/blob/main/packages/plugins/@nocobase/plugin-form-drafts/README.md)
- [packages/plugins/@nocobase/plugin-audit-logs/README.md](https://github.com/nocobase/nocobase/blob/main/packages/plugins/@nocobase/plugin-audit-logs/README.md)
- [packages/plugins/@nocobase/plugin-mobile/README.md](https://github.com/nocobase/nocobase/blob/main/packages/plugins/@nocobase/plugin-mobile/README.md)
</details>

# System Architecture

## Overview

NocoBase is an open-source AI + no-code platform designed for building business systems rapidly. The platform adopts a **data model-driven architecture** that separates data structure from user interface, enabling unlimited possibilities for application development. 资料来源：[README.md:1]()

The architecture is built with **plugin-first extensibility** at its core, allowing developers and AI agents to extend functionality without modifying the core codebase. This design philosophy enables organizations to adapt quickly to changing business requirements while maintaining system stability and performance. 资料来源：[packages/plugins/@nocobase/plugin-data-source-main/README.md:1]()

## Core Architectural Principles

### Data Model-Driven Approach

Unlike traditional form or table-driven platforms, NocoBase implements a data model-driven approach that decouples UI and data structure completely. This architectural decision provides several key advantages:

| Characteristic | Traditional Platforms | NocoBase Architecture |
|----------------|----------------------|----------------------|
| UI-Data Coupling | Tightly coupled | Fully decoupled |
| Interface Flexibility | Limited to table/form views | Unlimited block types |
| Data Source Support | Main database only | Main DB, external DBs, third-party APIs |
| Multiple Views | One view per entity | Multiple blocks for same table/record |

资料来源：[packages/plugins/@nocobase/plugin-form-drafts/README.md:1-15]()

### Plugin-Based Extensibility

The entire NocoBase system is constructed as a collection of plugins. This modular architecture allows:

- **Selective Feature Loading**: Only required plugins are loaded, reducing footprint
- **Independent Updates**: Plugins can be updated without affecting core functionality
- **Hot Module Replacement**: Plugins can be enabled/disabled at runtime
- **AI Integration**: AI employees can programmatically interact with any plugin

```graph TD
    A[NocoBase Core] --> B[Plugin System]
    B --> C[Data Source Plugins]
    B --> D[UI Block Plugins]
    B --> E[Workflow Plugins]
    B --> F[AI Agent Plugins]
    C --> G[Main Database]
    C --> H[External Databases]
    C --> I[Third-party APIs]
```

资料来源：[packages/plugins/@nocobase/plugin-data-source-main/README.md:1-10]()

## System Components

### Plugin Categories

NocoBase organizes its functionality into distinct plugin categories based on responsibility:

| Category | Purpose | Example Plugins |
|----------|---------|-----------------|
| Data Management | Handle data operations and storage | `plugin-data-source-main` |
| User Interface | Provide UI components and blocks | `plugin-mobile`, `plugin-block-workbench` |
| Workflow Automation | Manage business processes | `plugin-workflow-manual`, `plugin-workflow-notification` |
| System Utilities | Core system features | `plugin-audit-logs`, `plugin-verification` |
| AI Integration | Enable AI capabilities | `plugin-ai` |

### Database Layer

The database layer in NocoBase supports multiple data source types through a unified abstraction:

- **Main Database**: Primary storage engine (configurable type)
- **External Databases**: Direct connections to external SQL databases
- **Third-party APIs**: REST/GraphQL API integrations as data sources

资料来源：[packages/plugins/@nocobase/plugin-data-source-main/README.md:1-12]()

```graph TD
    A[Application Layer] --> B[Data Source Abstraction]
    B --> C[Main Database Engine]
    B --> D[External DB Connectors]
    B --> E[API Connectors]
    C --> F[SQL Translation Layer]
    D --> F
    E --> F
    F --> G[Query Optimization]
```

### User Interface Architecture

NocoBase provides a flexible UI system that supports both desktop and mobile clients:

#### Desktop Client

The desktop client (`packages/core/client`) implements a schema-driven UI system where:

- Components are defined as schemas
- UI blocks are composed declaratively
- Schema settings control component behavior

资料来源：[packages/plugins/@nocobase/plugin-mobile/README.md:1-8]()

#### Mobile Client

The mobile plugin provides:

- Mobile-optimized page layouts
- Responsive design support
- Native-like navigation patterns
- Mobile-specific UI components

```graph TD
    A[Client Request] --> B{Router}
    B -->|Desktop| C[Desktop UI Renderer]
    B -->|Mobile| D[Mobile UI Renderer]
    C --> E[Schema Component Tree]
    D --> F[Mobile Page Layouts]
    E --> G[Block Designer]
    F --> G
```

资料来源：[packages/plugins/@nocobase/plugin-mobile/README.md:1-15]()

## Workflow System Architecture

### Plugin-Based Workflows

NocoBase implements workflows as plugins, enabling:

- **Manual Triggers**: User-initiated workflow execution
- **Automated Triggers**: Event-based workflow activation
- **Notification System**: Multi-channel alert delivery
- **Dynamic Calculation**: Runtime computation within workflows

资料来源：[packages/plugins/@nocobase/plugin-workflow-manual/README.md:1-10]()

### Workflow Components

| Component | Function | Plugin |
|-----------|----------|--------|
| Trigger | Initiates workflow execution | `plugin-workflow-manual` |
| Actions | Perform operations | Core system |
| Conditions | Control flow logic | Core system |
| Notifications | Send alerts | `plugin-workflow-notification` |
| Calculations | Compute values | `plugin-workflow-dynamic-calculation` |

```graph TD
    A[Workflow Start] --> B{Trigger Type}
    B -->|Manual| C[User Action]
    B -->|Automated| D[Event Listener]
    C --> E[Condition Evaluation]
    D --> E
    E -->|True| F[Execute Actions]
    E -->|False| G[Skip Workflow]
    F --> H{Notification?}
    H -->|Yes| I[Send Notification]
    H -->|No| J[Continue Actions]
    I --> K[Workflow Complete]
    J --> K
    G --> K
```

## Audit and Logging Architecture

The audit logs plugin (`plugin-audit-logs`) captures comprehensive system activity:

- **Data Changes**: All database modifications
- **User Actions**: User interactions with the system
- **System Events**: Server-side operations
- **Access Patterns**: Authentication and authorization events

资料来源：[packages/plugins/@nocobase/plugin-audit-logs/README.md:1-12]()

## AI Integration Architecture

NocoBase integrates AI capabilities through a dedicated AI plugin system:

### AI Employee System

Unlike standalone AI implementations, NocoBase allows embedding AI capabilities seamlessly into:

- **Interfaces**: AI-powered form components and data displays
- **Workflows**: AI-driven decision making and automation
- **Business Logic**: Custom AI agents for domain-specific tasks
- **Data Operations**: Intelligent data processing and analysis

```graph TD
    A[AI Plugin System] --> B[AI Employees]
    A --> C[Prompt Templates]
    A --> D[Model Adapters]
    B --> E[Business Interfaces]
    B --> F[Workflow Integration]
    B --> G[Data Processing]
    C --> H[System Context]
    D --> I[LLM Providers]
    E --> J[User Interface]
    F --> K[Automation Engine]
    G --> L[Data Layer]
```

资料来源：[packages/plugins/@nocobase/plugin-data-source-main/README.md:1-8]()

## Extensibility Patterns

### Plugin Development

Developers can extend NocoBase by creating custom plugins:

1. **Plugin Structure**: Each plugin is a self-contained module
2. **Dependency Management**: Plugins can depend on other plugins
3. **Lifecycle Hooks**: Initialization, activation, and deactivation
4. **Schema Extension**: Custom schema types and components

```graph TD
    A[Custom Plugin] --> B[Plugin Manifest]
    A --> C[Server Code]
    A --> D[Client Code]
    A --> E[Resources]
    B --> F[Plugin Metadata]
    B --> G[Dependencies]
    C --> H[Database Models]
    C --> I[API Routes]
    C --> J[Services]
    D --> K[UI Components]
    D --> L[Schema Definitions]
    D --> M[State Management]
```

### Schema-Driven UI

The schema system allows declarative UI definition:

| Schema Type | Purpose | Extensibility |
|-------------|---------|---------------|
| `Field` | Data display/input | Custom field types |
| `Block` | Layout containers | Custom block types |
| `Action` | User interactions | Custom action handlers |
| `Selector` | Data filtering | Custom filter types |

## System Requirements and Deployment

### Database Support

NocoBase supports multiple database engines:

| Database | Status | Notes |
|----------|--------|-------|
| PostgreSQL | Full Support | Recommended for production |
| MySQL | Full Support | Wide compatibility |
| SQLite | Development Only | Limited concurrent access |
| Others | Via External DB Plugin | API-based connectivity |

### Runtime Requirements

- **Node.js**: v18+ required
- **Package Manager**: npm or yarn
- **Memory**: Minimum 2GB RAM for development
- **Storage**: Varies by database and data volume

## Architectural Benefits

### Scalability

- **Horizontal Scaling**: Stateless server design enables load balancing
- **Vertical Scaling**: Efficient resource utilization supports larger deployments
- **Plugin Isolation**: Prevents resource contention between features

### Maintainability

- **Modular Design**: Each plugin can be developed and tested independently
- **Clear Boundaries**: Well-defined interfaces between components
- **Version Management**: Plugins maintain their own version history

### Flexibility

- **Multiple Data Sources**: Connect to various databases and APIs
- **Custom UI**: Schema-driven interface allows infinite combinations
- **AI Integration**: Built-in support for AI-augmented functionality

## Summary

NocoBase's system architecture is designed around three fundamental principles:

1. **Data Model Centrality**: The data model drives all application behavior, not forms or tables
2. **Plugin-Based Extensibility**: Every feature is a plugin that can be added, removed, or customized
3. **AI Integration**: AI capabilities are first-class citizens integrated throughout the system

This architecture enables organizations to build sophisticated business applications rapidly while maintaining the flexibility to adapt to changing requirements. The separation of concerns between data, logic, and presentation layers ensures that changes in one area do not cascade into others, resulting in a maintainable and scalable system.

---

<a id='deployment'></a>

## Deployment

### 相关页面

相关主题：[Cluster Mode](#cluster-mode), [System Architecture](#system-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [docker-compose.yml](https://github.com/nocobase/nocobase/blob/main/docker-compose.yml)
- [Dockerfile](https://github.com/nocobase/nocobase/blob/main/Dockerfile)
- [docker/nocobase/Dockerfile](https://github.com/nocobase/nocobase/blob/main/docker/nocobase/Dockerfile)
- [docker/app-postgres/docker-compose.yml](https://github.com/nocobase/nocobase/blob/main/docker/app-postgres/docker-compose.yml)
- [docker/app-mysql/docker-compose.yml](https://github.com/nocobase/nocobase/blob/main/docker/app-mysql/docker-compose.yml)
- [docker/app-mariadb/docker-compose.yml](https://github.com/nocobase/nocobase/blob/main/docker/app-mariadb/docker-compose.yml)
- [docker/app-sqlite/docker-compose.yml](https://github.com/nocobase/nocobase/blob/main/docker/app-sqlite/docker-compose.yml)
- [docs/docs/en/get-started/deployment/production.md](https://github.com/nocobase/nocobase/blob/main/docs/docs/en/get-started/deployment/production.md)
- [docs/docs/en/get-started/installation/docker.mdx](https://github.com/nocobase/nocobase/blob/main/docs/docs/en/get-started/installation/docker.mdx)
</details>

# Deployment

NocoBase provides flexible deployment options to accommodate various infrastructure requirements and operational preferences. The platform supports containerized deployment via Docker, traditional server deployment, and development-focused installations.

## Overview

NocoBase is designed as a headless CMS with an API-first architecture. The application server exposes REST and GraphQL APIs, while the admin client is a separate SPA (Single Page Application). This separation allows for flexible deployment strategies where the server and client can be scaled independently.

## Deployment Methods

### Docker Deployment (Recommended)

Docker deployment is the recommended approach for production environments. It provides the easiest setup with no-code requirements and simplified maintenance through image updates.

**Minimal Quick Start:**
```bash
npm install -g @nocobase/cli@beta
mkdir my-nocobase && cd my-nocobase
nb init --ui
```

资料来源：[README.md:8-13]()

### Database Support

NocoBase supports multiple database backends. Each database type has a dedicated Docker Compose configuration:

| Database   | Configuration File                        | Use Case                        |
|------------|-------------------------------------------|----------------------------------|
| PostgreSQL | `docker/app-postgres/docker-compose.yml`  | Production, enterprise scale    |
| MySQL      | `docker/app-mysql/docker-compose.yml`     | Production, wide compatibility  |
| MariaDB    | `docker/app-mariadb/docker-compose.yml`   | Production, MySQL fork           |
| SQLite     | `docker/app-sqlite/docker-compose.yml`    | Development, small deployments  |

资料来源：[docker/app-postgres/docker-compose.yml](https://github.com/nocobase/nocobase/blob/main/docker/app-postgres/docker-compose.yml), [docker/app-mysql/docker-compose.yml](https://github.com/nocobase/nocobase/blob/main/docker/app-mysql/docker-compose.yml)

### Docker Architecture

```mermaid
graph TD
    A[Client Browser] -->|HTTPS| B[NocoBase Application]
    B -->|API Requests| C[API Server :13000]
    B -->|Static Assets| D[Admin SPA :13000]
    C --> E[(PostgreSQL<br/>MySQL<br/>MariaDB)]
    C --> F[(SQLite)]
    E --> G[Uploaded Files<br/>/uploads]
    F --> G
```

## Docker Configuration

### Main Dockerfile

The primary Dockerfile (`docker/nocobase/Dockerfile`) builds the NocoBase application image. It uses a multi-stage build process to:

1. Install dependencies
2. Build the application
3. Create an optimized production image

### Environment Variables

Key environment variables for Docker deployment:

| Variable | Description | Default |
|----------|-------------|---------|
| `APP_KEY` | Application encryption key | Generated on first run |
| `DB_DIALECT` | Database type (postgres, mysql, sqlite) | postgres |
| `DB_HOST` | Database host | db |
| `DB_PORT` | Database port | 5432 / 3306 |
| `DB_DATABASE` | Database name | nocobase |
| `DB_USER` | Database username | nocobase |
| `DB_PASSWORD` | Database password | nocobase |
| `API_PORT` | API server port | 13000 |

### Docker Compose Services

Typical Docker Compose configuration includes:

```yaml
services:
  app:
    image: nocobase/app:latest
    ports:
      - "13000:13000"
    environment:
      - DB_DIALECT=postgres
      - DB_HOST=db
      - DB_PORT=5432
    volumes:
      - ./uploads:/app/uploads
    depends_on:
      - db

  db:
    image: postgres:15
    environment:
      - POSTGRES_DB=nocobase
      - POSTGRES_USER=nocobase
      - POSTGRES_PASSWORD=nocobase
    volumes:
      - db_data:/var/lib/postgresql/data

volumes:
  db_data:
```

## Production Deployment

### Prerequisites

For production deployments, ensure:

1. **Reverse Proxy**: Configure nginx or similar for SSL termination
2. **Database**: Use PostgreSQL or MySQL for production workloads
3. **Storage**: Configure persistent storage for uploaded files
4. **Environment**: Set secure `APP_KEY` in production

### Deployment Checklist

| Item | Priority | Description |
|------|----------|-------------|
| SSL Certificate | Required | Enable HTTPS for production |
| Database Backup | Required | Configure automated backups |
| APP_KEY Configuration | Required | Use unique, secure key |
| Environment Variables | Required | Set production values |
| Upload Storage | Required | Configure persistent storage |
| Monitoring | Recommended | Set up application monitoring |
| Log Management | Recommended | Configure centralized logging |

资料来源：[docs/docs/en/get-started/deployment/production.md](https://github.com/nocobase/nocobase/blob/main/docs/docs/en/get-started/deployment/production.md)

### Production Reverse Proxy Configuration

```nginx
server {
    listen 80;
    server_name your-domain.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name your-domain.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    client_max_body_size 100M;

    location / {
        proxy_pass http://localhost:13000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_cache_bypass $http_upgrade;
    }

    location /uploads/ {
        alias /path/to/uploads/;
        expires 7d;
        add_header Cache-Control "public, immutable";
    }
}
```

## Installation Methods Comparison

| Method | Best For | Code Writing | Upgrade Process | Development |
|--------|----------|--------------|-----------------|-------------|
| Docker | Production, no-code | No | Pull image, restart | Limited |
| create-nocobase-app | Business projects | Yes (low-code) | Rebuild project | Full |
| Git Clone | Contributing, latest | Yes | Git pull | Full |

资料来源：[README.md:18-33]()

## Upgrading

### Docker Upgrades

For Docker deployments, upgrading involves:

```bash
# Pull latest image
docker pull nocobase/app:latest

# Restart container
docker-compose down
docker-compose up -d
```

### Database Migration

NocoBase automatically runs database migrations on startup. Ensure:

1. Database backup before upgrade
2. Sufficient downtime window for migration
3. Rollback plan if migration fails

## File Structure Reference

```
├── docker-compose.yml          # Main compose file
├── Dockerfile                  # Legacy Dockerfile
├── docker/
│   ├── nocobase/
│   │   └── Dockerfile         # Modern app Dockerfile
│   ├── app-postgres/
│   │   └── docker-compose.yml
│   ├── app-mysql/
│   │   └── docker-compose.yml
│   ├── app-mariadb/
│   │   └── docker-compose.yml
│   └── app-sqlite/
│       └── docker-compose.yml
└── uploads/                   # User uploads directory
```

## Troubleshooting

### Common Issues

| Issue | Solution |
|-------|----------|
| Container won't start | Check environment variables and volume permissions |
| Database connection failed | Verify DB_HOST, DB_PORT, and credentials |
| File upload fails | Check uploads directory permissions and size limits |
| Slow performance | Increase memory limits, enable caching |

### Health Check

NocoBase provides health check endpoint at the root path:

```bash
curl http://localhost:13000/
```

A successful response indicates the application is running correctly.

## Next Steps

- [Installation Guide](https://docs.nocobase.com/welcome/getting-started/installation/docker-compose)
- [Production Best Practices](https://docs.nocobase.com/welcome/getting-started/deployment/production)
- [Plugin Development](https://docs.nocobase.com/development/server/plugins)

---

<a id='plugin-system'></a>

## Plugin System

### 相关页面

相关主题：[Plugin Development](#plugin-development), [Data Modeling](#data-modeling), [Workflow Engine](#workflow-engine)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/core/client/src/pm/PluginDetail.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/pm/PluginDetail.tsx)
- [packages/core/client/src/pm/PluginManagerLink.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/pm/PluginManagerLink.tsx)
- [packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx)
- [packages/core/flow-engine/src/flowSettings.ts](https://github.com/nocobase/nocobase/blob/main/packages/core/flow-engine/src/flowSettings.ts)
- [packages/plugins/@nocobase/plugin-mobile/src/client/pages/index.md](https://github.com/nocobase/nocobase/blob/main/packages/plugins/@nocobase/plugin-mobile/src/client/pages/index.md)
</details>

# Plugin System

## Overview

NocoBase implements a modular plugin-based architecture that enables developers to extend core functionality without modifying the framework's source code. Plugins in NocoBase are self-contained packages that can add new features, customize existing behavior, and integrate with external services.

The plugin system provides a unified mechanism for both server-side and client-side extensions, allowing developers to hook into application lifecycle events, register custom components, define database schemas, and expose APIs.

## Architecture

```graph TD
    subgraph Core["NocoBase Core"]
        PM[Plugin Manager]
        ER[Event Router]
        SM[Schema Manager]
    end
    
    subgraph PluginTypes["Plugin Types"]
        SP[Server Plugin]
        CP[Client Plugin]
        FP[Full-Stack Plugin]
    end
    
    subgraph Lifecycle["Lifecycle Phases"]
        LOAD[Load]
        BOOT[Boot]
        MOUNT[Mount]
        ACTIVE[Active]
    end
    
    PM -->|manages| SP
    PM -->|manages| CP
    PM -->|manages| FP
    SP --> LOAD
    CP --> LOAD
    FP --> LOAD
    LOAD --> BOOT
    BOOT --> MOUNT
    MOUNT --> ACTIVE
```

## Plugin Manager

The Plugin Manager (`PluginManagerLink.tsx`) handles the registration and lifecycle of all plugins within the application.

### Core Components

| Component | File | Purpose |
|-----------|------|---------|
| `PluginDetail` | `packages/core/client/src/pm/PluginDetail.tsx` | Displays plugin metadata and dependency information |
| `PluginManagerLink` | `packages/core/client/src/pm/PluginManagerLink.tsx` | Provides UI navigation to plugin settings |
| `SchemaToolbar` | `packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx` | Enables schema-based plugin configuration |

### Plugin Detail Display

The `PluginDetail` component renders comprehensive information about installed plugins:

```tsx
<Typography.Title level={3}>{plugin.packageName}</Typography.Title>
<Space split={<span>&nbsp;•&nbsp;</span>}>
  <span>{plugin.version}</span>
</Space>
<Tabs
  style={{ minHeight: '50vh' }}
  items={tabItems}
  defaultActiveKey={!plugin.isCompatible ? 'dependencies' : undefined}
/>
```

资料来源：[packages/core/client/src/pm/PluginDetail.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/pm/PluginDetail.tsx)

### Dependencies Compatibility Check

Plugins validate their dependencies through the compatibility checking system:

```tsx
{data?.data?.depsCompatible === false ? (
  <Typography.Text type="danger">
    {t('`dist/externalVersion.js` not found or failed to `require`. Please rebuild this plugin.')}
  </Typography.Text>
) : (
  <>
    {!data?.data?.['isCompatible'] && (
      <Alert
        showIcon
        type={'error'}
        message={t('Plugin dependencies check failed, you should change the dependent version to meet the version requirements.')}
      />
    )}
    <Table
      style={{ marginTop: theme.margin }}
      rowKey={'name'}
      pagination={false}
      columns={dependenciesCompatibleTableColumns}
      dataSource={data?.data?.depsCompatible}
    />
  </>
)}
```

资料来源：[packages/core/client/src/pm/PluginDetail.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/pm/PluginDetail.tsx)

## Plugin Settings Management

### Settings Menu Integration

The `PluginManagerLink` component integrates with the application settings menu:

```tsx
const settingItems = useMemo(() => {
  const pinnedSettings = app.pluginSettingsManager
    .getPinnedSettings()
    .filter((setting) => setting.snippet !== false)
    .map((setting) => {
      return {
        key: setting.name,
        icon: setting.icon,
        label: setting.link ? (
          <div onClick={() => window.open(setting.link)}>{compile(setting.title)}</div>
        ) : (
          <Link to={setting.path}>{compile(setting.title)}</Link>
        ),
      };
    });
  // ...
}, [app, t]);
```

资料来源：[packages/core/client/src/pm/PluginManagerLink.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/pm/PluginManagerLink.tsx)

### Mobile Layout Handling

Settings are hidden in mobile layouts:

```tsx
const { isMobileLayout } = useMobileLayout();

if (isMobileLayout) {
  return null;
}
```

资料来源：[packages/core/client/src/pm/PluginManagerLink.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/pm/PluginManagerLink.tsx)

## Schema-Based Plugin Extensions

### Schema Designer Integration

Plugins can extend the schema designer through the `GeneralSchemaDesigner` component:

```tsx
<div className={'general-schema-designer-icons'}>
  <Space size={3} align={'center'}>
    {draggable && (
      <DragHandler>
        <DragOutlined role="button" aria-label={getAriaLabel('drag-handler')} />
      </DragHandler>
    )}
    {!disableInitializer &&
      (ctx?.InitializerComponent ? (
        <ctx.InitializerComponent {...initializerProps} />
      ) : (
        ctx?.renderSchemaInitializer?.(initializerProps)
      ))}
    {schemaSettingsExists ? (
      schemaSettingsRender(contextValue)
    ) : (
      <SchemaSettingsDropdown
        title={
          <MenuOutlined
            role="button"
            aria-label={getAriaLabel('schema-settings')}
            style={{ cursor: 'pointer', fontSize: 12 }}
          />
        }
        {...schemaSettingsProps}
      >
        {props.children}
      </SchemaSettingsDropdown>
    )}
  </Space>
</div>
```

资料来源：[packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx)

### Toolbar Components

The schema toolbar provides a unified interface for plugin-defined tools:

```tsx
<div className={classNames('toolbar-icons', spaceWrapperClassName)} style={spaceWrapperStyle}>
  <Space size={3} align={'center'} className={spaceClassName} style={spaceStyle}>
    {dragElement}
    <RefreshComponentProvider refresh={refresh}>{initializerElement}</RefreshComponentProvider>
    {settingsElement}
  </Space>
</div>
```

资料来源：[packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx)

## Plugin Lifecycle

```graph LR
    A[Install] --> B[Load]
    B --> C[Configure]
    C --> D[Enable]
    D --> E[Boot]
    E --> F[Mount]
    F --> G[Disable]
    G --> H[Uninstall]
```

### Flow Settings Integration

The flow engine demonstrates plugin extensibility through settings:

```tsx
export class FlowSettings {
  public components: Record<string, any> = {};
  public scopes: Record<string, any> = {};
  private antdComponentsLoaded = false;
  public enabled: boolean;
  #forceEnabled = false; // Force enable state
}
```

资料来源：[packages/core/flow-engine/src/flowSettings.ts](https://github.com/nocobase/nocobase/blob/main/packages/core/flow-engine/src/flowSettings.ts)

### Modal Footer Customization

Plugins can customize modal dialogs through the footer API:

```tsx
footer?:
  | React.ReactNode
  | ((originNode: React.ReactNode, extra: { OkBtn: React.FC; CancelBtn: React.FC }) => React.ReactNode)
  | null;
```

资料来源：[packages/core/flow-engine/src/flowSettings.ts](https://github.com/nocobase/nocobase/blob/main/packages/core/flow-engine/src/flowSettings.ts)

## Client-Side Plugin Components

### Page Components

Mobile plugins extend the application through page components:

| Page Type | Description |
|-----------|-------------|
| Home Page | Default landing page with routing support |
| NotFound Page | 404 error handling |
| Desktop Mode | Desktop layout wrapper for mobile content |

```tsx
<DesktopMode>
  <Mobile />
</DesktopMode>
```

资料来源：[packages/plugins/@nocobase/plugin-mobile/src/client/desktop-mode/index.md](https://github.com/nocobase/nocobase/blob/main/packages/plugins/@nocobase/plugin-mobile/src/client/desktop-mode/index.md)

### Schema Initializer Extensions

Plugins extend schema initialization through:

```tsx
### Insert schema
#### Basic
<code src="./demos/insert-schema-basic.tsx"></code>
#### Action
<code src="./demos/insert-schema-action.tsx"></code>
#### FormItem
<code src="./demos/insert-schema-form-item.tsx"></code>
```

资料来源：[packages/core/client/src/schema-initializer/index.md](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-initializer/index.md)

## Error Handling

### Error Fallback Component

Plugins integrate with the error handling system through the `ErrorFallback` component:

```tsx
<ErrorFallback
  error={error}
  info={info}
>
  <Result
    status="error"
    title={t('Render Failed')}
    subTitle={subTitle}
    extra={[
      <Button type="primary" key="feedback" href="https://github.com/nocobase/nocobase/issues" target="_blank">
        {t('Feedback')}
      </Button>,
      <Button key="log" loading={loading} onClick={download}>
        {t('Download logs')}
      </Button>,
    ]}
  />
</ErrorFallback>
```

资料来源：[packages/core/client/src/schema-component/antd/error-fallback/ErrorFallback.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-component/antd/error-fallback/ErrorFallback.tsx)

## Plugin Package Structure

| Directory/File | Purpose |
|---------------|---------|
| `src/server/` | Server-side plugin logic |
| `src/client/` | Client-side React components |
| `src/locale/` | Internationalization files |
| `dist/` | Compiled distribution files |
| `dist/externalVersion.js` | Version compatibility manifest |

## Built-in Variables System

Plugins can access built-in variables for dynamic content:

| Variable | Context | Description |
|----------|---------|-------------|
| `$date` | datetimeCtx | Current date (deprecated) |
| `$nExactDate` | exactDateTimeCtx | Precise timestamp |
| `$nDate` | datetimeCtx | Current date |
| `$system` | now | System time (deprecated) |
| `currentTime` | () => dayjs | Legacy time variable |

资料来源：[packages/core/client/src/variables/hooks/useBuiltinVariables.ts](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/variables/hooks/useBuiltinVariables.ts)

---

<a id='data-modeling'></a>

## Data Modeling

### 相关页面

相关主题：[Plugin System](#plugin-system), [Interface Builder](#interface-builder), [Authentication and Permissions](#authentication-permissions)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/core/database/src/database.ts](https://github.com/nocobase/nocobase/blob/main/packages/core/database/src/database.ts)
- [packages/core/client/src/schema-templates/SchemaTemplateManagerProvider.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-templates/SchemaTemplateManagerProvider.tsx)
- [packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx)
- [packages/core/client/src/schema-component/antd/table/index.md](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-component/antd/table/index.md)
- [packages/core/client/src/schema-settings/index.md](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-settings/index.md)
</details>

# Data Modeling

## Overview

Data Modeling in NocoBase represents the foundational system for defining, organizing, and managing data structures within the application. It provides a comprehensive framework that enables users to create collections, define fields, establish relationships, and configure data sources through both programmatic APIs and user interfaces.

The data modeling system serves as the core abstraction layer that bridges the gap between application-level schema definitions and the underlying database infrastructure. It supports multiple database dialects and provides consistent data management capabilities across different storage backends.

## Architecture

### Core Database System

The `Database` class in NocoBase acts as the central orchestrator for all data modeling operations. It maintains several internal maps and registries that track collections, fields, models, and their relationships.

```mermaid
graph TD
    A[Database] --> B[Collections Map]
    A --> C[Repositories Map]
    A --> D[Operators Map]
    A --> E[Model-Collection Maps]
    A --> F[Query Interface]
    A --> G[Dialect Layer]
    B --> H[Collection Metadata]
    E --> I[Model-Collection Binding]
    E --> J[Model Name Mapping]
    E --> K[Table Name Mapping]
```

The database system initializes with the following key components:

| Component | Type | Purpose |
|-----------|------|---------|
| `collections` | `Map<string, Collection>` | Stores all registered collections by name |
| `collectionsSort` | `Map<string, number>` | Manages collection ordering/priority |
| `repositories` | `Map<string, RepositoryType>` | Caches repository instances |
| `modelCollection` | `Map<ModelStatic, Collection>` | Binds model classes to collections |
| `modelNameCollectionMap` | `Map<string, Collection>` | Lookup by model name |
| `tableNameCollectionMap` | `Map<string, Collection>` | Lookup by table name |
| `pendingFields` | `Map<string, RelationField[]>` | Handles deferred field relations |
| `interfaceManager` | `InterfaceManager` | Manages field type interfaces |

资料来源：[packages/core/database/src/database.ts:26-45]()

### Dialect Support

The database layer implements a dialect pattern through `BaseDialect` to support multiple database engines. The dialect system is registered statically and enables the framework to generate appropriate SQL syntax for different database backends.

```mermaid
graph LR
    A[Database] --> B[Dialect Abstraction]
    B --> C[PostgreSQL]
    B --> D[MySQL]
    B --> E[SQLite]
    B --> F[Other Engines]
    
    G[SQL Identifier Quoting] --> C
    G --> D
    G --> E
    G --> F
```

资料来源：[packages/core/database/src/database.ts:47-59]()

## Collections

Collections are the primary units of data organization in NocoBase. They represent database tables and serve as containers for fields and their associated metadata.

### Collection Management

The system provides multiple mechanisms for retrieving collections:

| Method | Description |
|--------|-------------|
| `getCollection(name)` | Retrieve collection by exact name |
| `getRepository(name)` | Get repository instance for collection |
| `getModel(name)` | Access the ORM model |
| `tableNameCollectionMap` | Lookup by database table name |

The collection system supports template-based creation through the `SchemaTemplateManagerProvider`, which enables reusable collection schemas:

```typescript
getTemplatesByCollection: useCallback(
  (dataSource: string, collectionName: string) => {
    const parentCollections = getInheritCollections(collectionName, dataSource);
    const totalCollections = parentCollections.concat([collectionName]);
    const items = templates?.filter?.(
      (template) =>
        (template.dataSourceKey || DEFAULT_DATA_SOURCE_KEY) === dataSource &&
        totalCollections.includes(template.collectionName),
    );
    return items || [];
  },
  [getInheritCollections, templates],
),
```

资料来源：[packages/core/client/src/schema-templates/SchemaTemplateManagerProvider.tsx:45-60]()

### Collection Inheritance

Collections support inheritance through the `InheritanceMap`, allowing child collections to derive schema from parent collections. This enables hierarchical data modeling where common fields are defined once and inherited by specialized collections.

## Fields

Fields define the structure and behavior of data within collections. Each field has a type, validation rules, and UI configurations.

### Field Types

The system includes built-in field types and supports custom interface extensions:

| Category | Description |
|----------|-------------|
| Built-in Types | Standard field types provided by NocoBase |
| Custom Interfaces | Extensible field type system |
| Relation Fields | References to other collections |
| Virtual Fields | Computed or derived fields |

Fields can be configured with dynamic visibility and child elements:

```tsx
// Dynamic visible & children
// Supports conditional display and dynamic loading of child fields
```

资料来源：[packages/core/client/src/schema-settings/index.md:15-17]()

### Field Configuration

Fields support various configuration options including:

- Display names and descriptions
- Default values
- Validation rules
- UI components and templates
- Access control permissions

## Schema System

The schema system provides a declarative way to define UI and data structures. It integrates with collections to render appropriate interface components.

### Schema Designer

The `GeneralSchemaDesigner` component provides the visual interface for editing schema configurations:

```mermaid
graph TD
    A[GeneralSchemaDesigner] --> B[Title Bar]
    A --> C[Drag Handler]
    A --> D[Initializer Component]
    A --> E[Schema Settings Dropdown]
    
    B --> F[Data Source Display]
    B --> G[Template Reference]
    
    D --> H[Dynamic Initializer]
    
    E --> I[Custom Settings Menu]
```

资料来源：[packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx:1-50]()

### Schema Templates

Schema templates enable reusable component configurations:

| Method | Purpose |
|--------|---------|
| `getTemplateBySchemaId` | Find template by schema UID |
| `getTemplateById` | Find template by key |
| `getTemplatesByComponentName` | Filter by component type |
| `getTemplatesByCollection` | Filter by collection with inheritance |

资料来源：[packages/core/client/src/schema-templates/SchemaTemplateManagerProvider.tsx:32-44]()

## Data Sources

The system supports multiple data sources, allowing connections to different databases within a single application.

### Data Source Manager

Data sources are managed through a dedicated configuration system that handles:

- Connection configuration
- Dialect-specific settings
- SQL identifier quoting rules
- Cross-database relationships

The quoting rules vary by database type and must be respected when generating SQL:

> Quote SQL identifiers according to each data source's database type specified in `<data_sources>`.
> - Convert camelCase names to snake_case for databases that use underscore naming

资料来源：[packages/plugins/@nocobase/plugin-ai/src/server/ai-employees/prompts.ts:15-20]()

## Table Components

The system provides multiple table rendering modes for different use cases:

| Mode | Use Case |
|------|----------|
| `Table.Void` | Read-only display without interaction |
| `Table.RowSelection` | Selectable rows for batch operations |
| `Table.Array` | Editable array-based table |

资料来源：[packages/core/client/src/schema-component/antd/table/index.md:1-14]()

### Table Examples

The table component supports various configurations:

- Basic void table display
- Row selection with checkboxes
- Array-based inline editing
- Integrated action buttons

## Workflow Integration

Data modeling integrates with the workflow engine through the `FlowSettings` system, which provides:

- Custom variable definitions
- Linkage rules configuration
- Condition evaluation based on field values
- Action triggers tied to data changes

The linkage rules system allows conditional logic based on collection fields:

```typescript
// Condition evaluation structure
{
  condition: FilterGroup,
  actions: Action[]
}
```

资料来源：[packages/core/client/src/flow/actions/linkageRules.tsx:60-80]()

## API Reference

### Database Initialization

```typescript
const database = new Database({
  dialect: 'postgres',
  // ... connection options
});
```

### Collection Definition

```typescript
database.collection({
  name: 'users',
  fields: [
    { type: 'string', name: 'name' },
    { type: 'hasMany', name: 'posts' },
  ],
});
```

### Query Operations

| Method | Description |
|--------|-------------|
| `db.getCollection(name)` | Get collection instance |
| `collection.repository` | Access CRUD operations |
| `collection.model` | Access ORM model |

## Summary

The Data Modeling system in NocoBase provides a comprehensive solution for defining and managing application data structures. It combines:

1. **Collection Management**: Organize data into logical groupings
2. **Field Definition**: Configure data attributes with types and validation
3. **Schema Templates**: Enable reusable configurations
4. **Multi-Datasource Support**: Connect to various database backends
5. **UI Integration**: Seamless rendering through schema components
6. **Workflow Connection**: Trigger actions based on data conditions

The architecture emphasizes extensibility through plugins, custom field interfaces, and dialect-specific optimizations.

---

<a id='interface-builder'></a>

## Interface Builder

### 相关页面

相关主题：[Data Modeling](#data-modeling), [Workflow Engine](#workflow-engine), [Plugin Development](#plugin-development)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/core/client/src/schema-settings/index.md](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-settings/index.md)
- [packages/core/client/src/schema-initializer/index.md](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-initializer/index.md)
- [packages/core/client/src/schema-component/index.md](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-component/index.md)
- [packages/core/flow-engine/src/flowSettings.ts](https://github.com/nocobase/nocobase/blob/main/packages/core/flow-engine/src/flowSettings.ts)
- [packages/core/client/src/schema-component/antd/markdown/index.md](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-component/antd/markdown/index.md)
- [packages/core/client/src/schema-component/antd/association-select/index.md](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-component/antd/association-select/index.md)
- [packages/core/client/src/schema-component/antd/linkageFilter/index.md](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-component/antd/linkageFilter/index.md)
</details>

# Interface Builder

## Overview

The Interface Builder is NocoBase's core visual configuration system that enables users to create and customize application interfaces through a schema-driven approach. It provides a declarative way to define UI components, their behaviors, and data relationships without requiring code modifications.

### Core Concepts

The Interface Builder operates on a schema-based architecture where every UI element is defined through JSON schemas that describe:

- Component type and properties
- Data binding and field mappings
- Action handlers and event callbacks
- Styling and layout configurations
- Conditional visibility rules

### Architecture Overview

```mermaid
graph TD
    A[Interface Builder] --> B[Schema Settings]
    A --> C[Schema Initializers]
    A --> D[Schema Components]
    A --> E[Variables System]
    
    B --> B1[Built-in Types]
    B --> B2[Designer Context]
    
    C --> C1[Block Initializers]
    C --> C2[Field Initializers]
    C --> C3[Action Initializers]
    
    D --> D1[Form Components]
    D --> D2[Display Components]
    D --> D3[Action Components]
    
    E --> E1[System Variables]
    E --> E2[Custom Variables]
    E --> E3[Flow Variables]
```

## Schema System

The schema system is the foundation of the Interface Builder. Schemas define the structure, behavior, and appearance of interface elements.

### Schema Properties

| Property | Type | Description |
|----------|------|-------------|
| `x-component` | string | The component to render |
| `x-component-props` | object | Component-specific props |
| `x-decorator` | string | Wrapper component (e.g., FormItem) |
| `x-decorator-props` | object | Decorator component props |
| `x-designable` | boolean | Enable visual editing |
| `x-hidden` | boolean | Hide the element |
| `x-visible` | expression | Conditional visibility |

### Basic Schema Example

```tsx
{
  type: 'string',
  'x-component': 'Markdown',
  'x-decorator': 'FormItem',
  'x-component-props': {
    mode: 'sv',
    height: '82vh'
  }
}
```

资料来源：[packages/core/client/src/flow/flows/editMarkdownFlow.tsx](./packages/core/client/src/flow/flows/editMarkdownFlow.tsx)

## Schema Settings

Schema Settings provide configuration panels for customizing schema properties in design mode. They appear when users click the settings icon on schema elements.

### Built-in Schema Settings

The system includes several built-in schema settings components:

| Component | Purpose |
|-----------|---------|
| `GeneralSchemaDesigner` | General schema configuration |
| `SchemaSettings` | Base settings collection |
| `SchemaSettingsDropdown` | Dropdown menu for settings |
| `SchemaToolbar` | Toolbar for schema operations |

### Designer Toolbar

The schema designer toolbar provides quick access to common operations:

```tsx
<SchemaToolbar 
  title="Block Title"
  showDataSource={true}
  draggable={true}
  designable={true}
/>
```

资料来源：[packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx](./packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx)

### Toolbar Components

| Component | Function |
|-----------|----------|
| `DragHandler` | Drag handle for reordering |
| `InitializerComponent` | Insert new elements |
| `SchemaSettingsDropdown` | Open settings panel |

### Toolbar Title Display

The toolbar displays hierarchical information when configured:

```tsx
<span key={titleArr[0]} className={'toolbar-title-tag'}>
  {dataSource ? `${compile(dataSource?.displayName)} > ${titleArr[0]}` : titleArr[0]}
</span>
```

## Schema Initializers

Schema Initializers define where and what elements can be inserted into the interface. They provide the "Add" functionality within design mode.

### Initializer Types

#### Block Initializers

Block initializers add container-level components like tables, forms, and grids.

```tsx
{
  type: 'array',
  title: '{{t("Blocks")}}',
  name: 'blockInitializers',
  children: [
    // Table block
    {
      title: '{{t("Table")}}',
      name: 'tableSelector',
      Component: TableSelectorInitializer
    },
    // Form block
    {
      title: '{{t("Form")}}',
      name: 'formItemInitializers',
      Component: FormItemInitializers
    }
  ]
}
```

#### Field Initializers

Field initializers add data fields to forms and tables.

```tsx
{
  type: 'array',
  title: '{{t("Fields")}}',
  name: 'fieldInitializers',
  children: [
    {
      title: '{{t("Text")}}',
      name: 'text',
      Component: DateFormatInitializer
    }
  ]
}
```

### Dynamic Visibility

Initializers can dynamically show or hide items based on context:

```tsx
{
  'x-visible': '{{curdModel === "list"}}',
  children: [
    // Dynamic children
  ]
}
```

## Schema Components

NocoBase provides a rich library of schema components for building interfaces.

### Form Components

#### Markdown

A rich text editor supporting Markdown syntax.

```tsx
interface MarkdownProps extends TextAreaProps {
  value?: string;
  onChange?: (value: string) => void;
  mode?: 'sv' | 'wysiwyg';
}
```

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `mode` | `'sv' \| 'wysiwyg'` | `'sv'` | Editor mode |
| `height` | `string \| number` | `200` | Editor height |
| `value` | `string` | - | Markdown content |
| `onChange` | `function` | - | Change handler |

资料来源：[packages/core/client/src/schema-component/antd/markdown/index.md](./packages/core/client/src/schema-component/antd/markdown/index.md)

#### Markdown.Void

A void component for inline markdown editing.

```tsx
interface MarkdownVoidProps extends Omit<TextAreaProps, 'onSubmit'> {
  defaultValue?: string;
  onSubmit?: (value: string) => void;
  onCancel?: (e: React.MouseEvent) => void;
}
```

### Association Components

#### AssociationSelect

Select component for related data from specified tables.

```tsx
type AssociationSelectProps<P = any> = RemoteSelectProps<P> & {
  action?: string;
  multiple?: boolean;
};
```

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `action` | `string` | `'list'` | Data fetching action |
| `multiple` | `boolean` | `false` | Enable multi-select |
| `type` | `'string' \| 'array'` | `'string'` | Value type |
| `fieldNames` | `object` | - | Field name mappings |

资料来源：[packages/core/client/src/schema-component/antd/association-select/index.md](./packages/core/client/src/schema-component/antd/association-select/index.md)

### Filter Components

#### LinkageFilter

Component for frontend linkage rules and condition configuration.

```tsx
type FilterActionProps<T = {}> = ActionProps & {
  options?: any[];
  form?: Form;
  onSubmit?: (values: T) => void;
  onReset?: (values: T) => void;
}
```

### Built-in Component Types

| Category | Components |
|----------|------------|
| Input | Input, TextArea, NumberPicker, Password |
| Select | Select, Checkbox, Radio, Switch |
| Display | Markdown, Markdown.Void, LinkageFilter |
| Association | AssociationSelect, RecordPicker |
| DateTime | DatePicker, TimePicker, DateRangePicker |

## Variables System

The Variables system provides dynamic data access within the Interface Builder, enabling context-aware functionality.

### Variable Types

| Type | Label | Description |
|------|-------|-------------|
| `system` | System | Built-in system variables |
| `currentUser` | Current User | Logged-in user information |
| `currentRole` | Current Role | Current user's role |
| `dateNow` | Date Now | Current timestamp |
| `form` | Form | Form values and state |
| `record` | Record | Current data record |
| `variable` | Custom Variable | User-defined variables |

### Variable Table Structure

Variables are displayed in a structured table:

| Column | Description |
|--------|-------------|
| `title` | Variable display name |
| `key` | Variable identifier |
| `type` | Variable data type |
| `actions` | Edit and delete operations |

### Custom Variables

Custom variables can be created and managed in workflows:

```tsx
{
  title: t('Custom Variables'),
  key: 'customVariables',
  type: 'object',
  children: [
    {
      title: variable.title,
      key: variable.key,
      type: variable.type
    }
  ]
}
```

资料来源：[packages/core/client/src/flow/actions/customVariable.tsx](./packages/core/client/src/flow/actions/customVariable.tsx)

## Actions

Actions define user interactions and their corresponding behaviors within the Interface Builder.

### Action Types

| Action | Description |
|--------|-------------|
| `submit` | Submit form data |
| `cancel` | Cancel current operation |
| `create` | Create new record |
| `update` | Update existing record |
| `delete` | Delete record |
| `custom` | Custom action handler |

### Action Schema Configuration

```tsx
{
  type: 'object',
  'x-component': 'Action',
  'x-component-props': {
    type: 'primary',
    icon: 'CheckOutlined'
  }
}
```

## UI Mode Configuration

The UI Mode system allows customization of dialog and modal appearances.

### Footer Configuration

```tsx
footer: (originNode, { OkBtn, CancelBtn }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
    <span>Additional info</span>
    {originNode}
  </div>
)
```

### Footer Options

| Option | Type | Description |
|--------|------|-------------|
| `null` | `null` | Hide footer |
| `ReactNode` | `ReactNode` | Static footer content |
| `function` | `(originNode, { OkBtn, CancelBtn }) => ReactNode` | Dynamic footer |

资料来源：[packages/core/flow-engine/src/flowSettings.ts](./packages/core/flow-engine/src/flowSettings.ts)

## Designer Context

The Designer Context provides runtime information and utilities for schema design mode.

### Context Features

- `designable` - Current design mode state
- `designerProps` - Designer-specific properties
- `resources` - Available schema resources
- `schema` - Current schema instance
- `refresh` - Refresh handler for data updates

### Context Usage

```tsx
const { designable, schema, refresh } = useDesigner();

if (designable) {
  return <DesignablePlugin {...props} />;
}
```

## Integration with Flow Engine

The Interface Builder integrates with NocoBase's Flow Engine to provide workflow-driven interface behavior.

### Flow Settings Integration

Flow settings can be embedded within schema components:

```tsx
{
  type: 'object',
  'x-component': 'FlowSettings',
  properties: {
    content: {
      type: 'string',
      'x-component': 'Markdown',
      'x-component-props': {
        mode: 'sv'
      }
    }
  }
}
```

### Default Parameters

Schemas can define default parameters for flows:

```tsx
defaultParams: (ctx) => {
  return {
    content: ctx.t('{{t("Default content")}}'),
  };
}
```

### Liquid Template Rendering

Variables support Liquid template syntax:

```tsx
const result = await ctx.liquid.renderWithFullContext(content, ctx);
```

## Mobile Interface Builder

NocoBase supports mobile-specific interface building through the mobile plugin.

### Mobile Pages

| Page | Description |
|------|-------------|
| Home Page | Application homepage |
| NotFound Page | 404 error page |

### Mobile Layout Components

| Component | Description |
|-----------|-------------|
| `MobileTabBar` | Bottom navigation bar |
| `MobileTabBar.Item` | Tab bar items |
| `MobileTabBar.Link` | Link navigation items |

### Desktop Mode

Mobile pages can be wrapped for desktop viewing:

```tsx
<DesktopMode>
  <Mobile />
</DesktopMode>
```

## Plugin Manager Integration

The Plugin Manager provides configuration UI for plugins built with the Interface Builder system.

### Plugin Details Display

```tsx
{
  key: 'info',
  label: t('Plugin Info'),
  children: (
    <>
      <Typography.Title level={3}>{plugin.packageName}</Typography.Title>
      <Tabs items={tabItems} />
    </>
  )
}
```

### Dependency Compatibility

Plugin details include dependency compatibility checking:

```tsx
{
  key: 'dependencies',
  label: t('Dependencies compatibility check'),
  children: (
    <DependenciesCheck status={data?.data?.depsCompatible} />
  )
}
```

## Best Practices

### Schema Organization

1. Use meaningful `name` properties for schema identification
2. Group related components under consistent parent schemas
3. Leverage decorators (`x-decorator`) for common patterns

### Performance Optimization

1. Use `x-hidden` over conditional rendering for hidden elements
2. Leverage `designable` flag to skip rendering logic in production
3. Use void components for modal content

### Accessibility

1. Include `aria-label` on interactive elements
2. Use proper heading hierarchy within schema blocks
3. Ensure keyboard navigation support

## See Also

- [Schema Settings Reference](./schema-settings/index.md)
- [Schema Components Reference](./schema-component/index.md)
- [Variables System](./variables.md)
- [Mobile Interface](./mobile/index.md)

---

<a id='workflow-engine'></a>

## Workflow Engine

### 相关页面

相关主题：[Interface Builder](#interface-builder), [Plugin System](#plugin-system), [Authentication and Permissions](#authentication-permissions)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/plugins/@nocobase/plugin-workflow/src/client/ExecutionCanvas.tsx](https://github.com/nocobase/nocobase/blob/main/packages/plugins/@nocobase/plugin-workflow/src/client/ExecutionCanvas.tsx)
- [packages/plugins/@nocobase/plugin-workflow/src/locale/ko-KR.json](https://github.com/nocobase/nocobase/blob/main/packages/plugins/@nocobase/plugin-workflow/src/locale/ko-KR.json)
- [packages/core/flow-engine/src/flowSettings.ts](https://github.com/nocobase/nocobase/blob/main/packages/core/flow-engine/src/flowSettings.ts)
- [packages/core/flow-engine/src/components/FlowModelRenderer.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/flow-engine/src/components/FlowModelRenderer.tsx)
- [packages/core/client/src/flow/actions/customVariable.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/flow/actions/customVariable.tsx)
- [packages/plugins/@nocobase/plugin-workflow/src/client/CanvasContent.tsx](https://github.com/nocobase/nocobase/blob/main/packages/plugins/@nocobase/plugin-workflow/src/client/CanvasContent.tsx)
</details>

# Workflow Engine

## Overview

The Workflow Engine is NocoBase's core system for designing, executing, and managing automated business processes. It provides a visual canvas-based interface where users can create workflows by connecting different node types, define triggers that initiate workflow execution, and configure custom variables for data transformation.

The engine is designed as a plugin (`@nocobase/plugin-workflow`) that integrates with the broader NocoBase platform, leveraging the `flow-engine` core module for rendering and execution logic.

## Architecture

The Workflow Engine follows a provider-based architecture with clear separation between UI rendering and execution logic.

```graph TD
    A[Workflow Canvas] --> B[FlowContext Provider]
    B --> C[ExecutionCanvas Component]
    C --> D[CanvasContent Component]
    C --> E[JobModal Component]
    D --> F[FlowModelRenderer]
    F --> G[FlowModelProvider]
    G --> H[ErrorBoundary]
    F --> I[MemoFlowModelRenderer]
```

## Core Components

### FlowContext Provider

The `FlowContext` provides runtime data to all workflow-related components. It encapsulates the current workflow, nodes, execution context, and view state.

```typescript
<FlowContext.Provider
  value={{
    workflow: workflow.type ? workflow : null,
    nodes,
    execution,
    viewJob,
    setViewJob,
  }}
>
```

**Context Values:**

| Property | Type | Description |
|----------|------|-------------|
| `workflow` | `Workflow` | The workflow configuration object |
| `nodes` | `Node[]` | Array of nodes in the workflow |
| `execution` | `Execution` | Current execution instance |
| `viewJob` | `Job \| null` | Job selected for detailed view |
| `setViewJob` | `Function` | Callback to update viewJob state |

资料来源：[packages/plugins/@nocobase/plugin-workflow/src/client/ExecutionCanvas.tsx:21-28]()

### ExecutionCanvas

The `ExecutionCanvas` is the main container component for viewing workflow executions. It renders the toolbar, status indicators, and delegates content rendering to child components.

**Key Features:**

- Breadcrumb navigation to workflow details
- Execution status badge with color coding
- Cancel execution capability (when execution is not in terminal state)
- Last updated timestamp display

```typescript
<Breadcrumb
  items={[
    { title: <Link to={app.pluginSettingsManager.getRoutePath('workflow')}>{lang('Workflow')}</Link> },
    {
      title: (
        <Tooltip title={`Key: ${workflow.key}`}>
          <Link to={getWorkflowDetailPath(workflow.id)}>{workflow.title}</Link>
        </Tooltip>
      ),
    },
    { title: <ExecutionsDropdown /> },
  ]}
/>
```

资料来源：[packages/plugins/@nocobase/plugin-workflow/src/client/ExecutionCanvas.tsx:31-44]()

### FlowModelRenderer

The `FlowModelRenderer` is the core rendering component that displays the workflow model with all connected nodes. It supports several configuration options:

**Props:**

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `model` | `Model` | Required | The data model to render |
| `showFlowSettings` | `boolean` | `true` | Whether to show flow settings panel |
| `flowSettingsVariant` | `string` | `undefined` | Visual variant for settings |
| `hideRemoveInSettings` | `boolean` | `false` | Hide remove button in settings |
| `showTitle` | `boolean` | `true` | Show the model title |
| `inputArgs` | `any[]` | `[]` | Input arguments for the flow |
| `showErrorFallback` | `boolean` | `true` | Show error fallback UI |
| `settingsMenuLevel` | `string` | `undefined` | Settings menu hierarchy level |
| `extraToolbarItems` | `ReactNode` | `undefined` | Additional toolbar content |
| `fallback` | `React.FC` | `undefined` | Custom fallback component |
| `useCache` | `boolean` | `false` | Enable render caching |

资料来源：[packages/core/flow-engine/src/components/FlowModelRenderer.tsx:1-50]()

**Memoization:**

```typescript
export const MemoFlowModelRenderer = React.memo(FlowModelRenderer);
MemoFlowModelRenderer.displayName = 'MemoFlowModelRenderer';
```

The component includes a memoized version (`MemoFlowModelRenderer`) that skips re-rendering when parent components re-render but props remain unchanged. This optimization does not affect internal reactive updates.

资料来源：[packages/core/flow-engine/src/components/FlowModelRenderer.tsx:110-112]()

### CanvasContent

The `CanvasContent` component renders the actual workflow visualization including nodes, edges, and clipboard preview functionality.

**Features:**

- Terminal node display (Start/End markers)
- Clipboard preview for copied nodes
- Zoom slider control

```typescript
<div className="workflow-canvas-zoomer">
  <Slider vertical reverse defaultValue={100} step={10} min={10} value={zoom} onChange={setZoom} />
</div>
```

资料来源：[packages/plugins/@nocobase/plugin-workflow/src/client/CanvasContent.tsx:1-100]()

## Flow Settings

The `FlowSettings` class manages flow configuration dialogs and their component registry.

```typescript
export class FlowSettings {
  public components: Record<string, any> = {};
  public scopes: Record<string, any> = {};
  private antdComponentsLoaded = false;
  public enabled: boolean;
  #forceEnabled = false;
}
```

资料来源：[packages/core/flow-engine/src/flowSettings.ts:1-10]()

### Footer Configuration

Flow settings support customizable footer content through a flexible API:

```typescript
footer?:
  | React.ReactNode
  | ((originNode: React.ReactNode, extra: { OkBtn: React.FC; CancelBtn: React.FC }) => React.ReactNode)
  | null;
```

**Footer Patterns:**

| Pattern | Example |
|---------|---------|
| **Default** | Preserves original footer with Ok/Cancel buttons |
| **Overlay** | Add content above origin footer |
| **Replace** | Full custom footer composition |
| **Hidden** | Set `footer: null` to hide |

资料来源：[packages/core/flow-engine/src/flowSettings.ts:1-30]()

## Variables System

The workflow engine supports variable injection for data transformation between nodes.

### Custom Variables Configuration

The `customVariable.tsx` file provides the UI for managing custom workflow variables:

**Variable Properties:**

| Property | Data Index | Description |
|----------|------------|-------------|
| Title | `title` | Display name for the variable |
| Identifier | `key` | Unique key for referencing |
| Type | `type` | Data type classification |

**Available Variable Types:**

| Type | Label | Usage |
|------|-------|-------|
| `string` | String | Text data |
| `number` | Number | Numeric values |
| `boolean` | Boolean | True/false flags |
| `array` | Array | List of values |
| `object` | Object | Complex structured data |

**Actions:**

| Action | Icon | Description |
|--------|------|-------------|
| Edit | `EditOutlined` | Modify variable configuration |
| Delete | `DeleteOutlined` | Remove variable from workflow |

```typescript
render: (_: unknown, __: FlowVariable, index: number) => (
  <Space size={12} style={{ whiteSpace: 'nowrap' }}>
    <Button
      type="link"
      size="small"
      icon={<EditOutlined />}
      onClick={() => handleEdit(index)}
      disabled={disabled}
      title={t('Edit')}
    />
    <Button
      type="link"
      size="small"
      icon={<DeleteOutlined />}
      danger
      onClick={() => handleDelete(index)}
      disabled={disabled}
      title={t('Delete')}
    />
  </Space>
)
```

资料来源：[packages/core/client/src/flow/actions/customVariable.tsx:1-80]()

## Execution States

The engine tracks execution status through a state machine:

```graph TD
    A[Created] --> B[Running]
    B --> C[Success]
    B --> D[Failed]
    B --> E[Cancelled]
    D --> F[Retry]
    F --> B
```

**Status Options:**

| Status | Color | Description |
|--------|-------|-------------|
| Running | Processing | Execution in progress |
| Success | Success | Completed successfully |
| Failed | Error | Execution encountered an error |
| Cancelled | Warning | Execution manually stopped |

资料来源：[packages/plugins/@nocobase/plugin-workflow/src/locale/ko-KR.json:1-50]()

## Trigger Points

Workflows can be triggered at various points in the application lifecycle:

| Trigger | Description |
|---------|-------------|
| After Saving | Triggered after data save completes |
| After Submitting | Triggered after form submission succeeds |
| Before Deleting | Triggered before deletion (local mode only) |
| Button Click | Triggered directly on button click without saving |

资料来源：[packages/plugins/@nocobase/plugin-workflow/src/locale/ko-KR.json:50-100]()

## Error Handling

The system implements multi-level error handling:

1. **ErrorBoundary Wrapper:** Catches rendering errors around the FlowModelRenderer
2. **FlowModelProvider:** Provides error context to child components
3. **FlowErrorFallback:** Renders user-friendly error messages with recovery options

```typescript
if (showErrorFallback) {
  return (
    <FlowModelProvider model={model}>
      <ErrorBoundary FallbackComponent={FlowErrorFallback}>{content}</ErrorBoundary>
    </FlowModelProvider>
  );
}
```

资料来源：[packages/core/flow-engine/src/components/FlowModelRenderer.tsx:85-92]()

## Integration with Plugin System

The workflow plugin integrates with NocoBase's plugin manager through:

- **Route Registration:** `/workflow` path for navigation
- **Settings Manager:** `app.pluginSettingsManager.getRoutePath('workflow')`
- **Localization:** Multi-language support via JSON locale files

资料来源：[packages/plugins/@nocobase/plugin-workflow/src/client/ExecutionCanvas.tsx:35]()

## Summary

The Workflow Engine provides a comprehensive system for building and executing automated workflows within NocoBase. Key aspects include:

- **Visual Canvas:** Drag-and-drop workflow design interface
- **Context-Based Architecture:** React Context for global state management
- **Flexible Configuration:** Customizable settings dialogs and footers
- **Variable System:** Support for custom variables with type classification
- **Error Resilience:** Built-in error boundaries and fallback components
- **Execution Tracking:** Real-time status updates and execution history
- **Plugin Integration:** Seamless integration with the NocoBase plugin ecosystem

---

<a id='authentication-permissions'></a>

## Authentication and Permissions

### 相关页面

相关主题：[Workflow Engine](#workflow-engine), [Data Modeling](#data-modeling), [Plugin Development](#plugin-development)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [docs/docs/en/auth-verification/index.md](https://github.com/nocobase/nocobase/blob/main/docs/docs/en/auth-verification/index.md)
- [docs/docs/en/users-permissions/acl/permissions.md](https://github.com/nocobase/nocobase/blob/main/docs/docs/en/users-permissions/acl/permissions.md)
- [docs/docs/en/users-permissions/index.md](https://github.com/nocobase/nocobase/blob/main/docs/docs/en/users-permissions/index.md)
- [docs/docs/en/plugins/@nocobase/plugin-acl/index.md](https://github.com/nocobase/nocobase/blob/main/docs/docs/en/plugins/@nocobase/plugin-acl/index.md)
- [docs/docs/en/plugins/@nocobase/plugin-auth/index.md](https://github.com/nocobase/nocobase/blob/main/docs/docs/en/plugins/@nocobase/plugin-auth/index.md)
- [docs/docs/en/users-permissions/index.md](https://github.com/nocobase/nocobase/blob/main/docs/docs/en/users-permissions/index.md)
</details>

# Authentication and Permissions

## Overview

NocoBase implements a comprehensive authentication and permissions system built on a plugin-based architecture. The system is designed to provide secure access control through multiple integrated plugins that handle user authentication, role-based access control (RBAC), and granular resource permissions.

## Authentication System

### Authentication Plugin

The `@nocobase/plugin-auth` plugin provides the core authentication capabilities for NocoBase. This plugin handles user identity verification, session management, and integrates with various authentication providers.

### Authentication Verification Flow

The auth-verification system implements a multi-step verification process to ensure secure access to NocoBase resources.

```mermaid
graph TD
    A[Client Request] --> B{Authentication Required?}
    B -->|Yes| C[Auth Plugin Verification]
    B -->|No| G[Resource Access]
    C --> D{Credentials Valid?}
    D -->|Yes| E[Generate Session Token]
    D -->|No| F[Authentication Failed - 401]
    E --> G[Resource Access with Token]
```

### User Management

The `@nocobase/plugin-users` plugin extends the authentication system by providing comprehensive user management capabilities. User records store essential identity information and serve as the basis for permission assignments.

## Access Control List (ACL) System

### ACL Plugin Architecture

The `@nocobase/plugin-acl` plugin implements NocoBase's Access Control List system, providing fine-grained permission management across collections, actions, and fields.

```mermaid
graph TD
    A[User Request] --> B{ACL Check}
    B --> C{Role Assigned?}
    C -->|No| D[Default Deny]
    C -->|Yes| E[Check Resource Permissions]
    E --> F{Action Allowed?}
    F -->|Yes| G[Execute Action]
    F -->|No| H[Permission Denied - 403]
```

### Permission Model

NocoBase's permissions system follows a hierarchical structure:

| Permission Level | Scope | Description |
|-----------------|-------|-------------|
| Collection | `collections:*` | Global collection access |
| Specific Collection | `collections:posts` | Single collection access |
| Action | `collections:posts:*` | All actions on collection |
| Field | `fields:posts:title` | Specific field access |
| Resource | `resources:posts` | Resource-level permissions |

资料来源：[docs/docs/en/users-permissions/acl/permissions.md]()

### Built-in Roles

| Role | Description | Default Permissions |
|------|-------------|---------------------|
| `admin` | Full system access | All permissions |
| `member` | Basic user access | Limited to assigned resources |
| `guest` | Unauthenticated users | Minimal or no access |

资料来源：[docs/docs/en/plugins/@nocobase/plugin-acl/index.md]()

## Permissions Management

### Role-Based Access Control

The permissions system in NocoBase is built on the principle of assigning permissions to roles, then assigning roles to users. This follows the standard RBAC (Role-Based Access Control) model.

```mermaid
graph LR
    A[Users] -->|assigned to| B[Roles]
    B -->|grants| C[Permissions]
    C -->|apply to| D[Resources/Actions]
    
    E[Collections] -->|scope| C
    F[Fields] -->|scope| C
    G[Actions] -->|scope| C
```

资料来源：[docs/docs/en/users-permissions/index.md]()

### Permission Configuration

Permissions can be configured at multiple levels:

| Level | Syntax | Example |
|-------|--------|---------|
| All resources | `*` | `collections:*` |
| Specific resource | `resourceName` | `collections:posts` |
| Nested resource | `parent.child` | `collections:posts.comments` |
| Field-level | `resource:field` | `collections:posts:title` |

### UI Permission Handling

In the client-side implementation, permission checks are integrated throughout the UI components. Fields that users lack permission to modify are automatically restricted:

```typescript
// From: packages/core/client/src/flow/models/fields/AssociationFieldModel/SubTableFieldModel/SubTableColumnModel.tsx
const messageValue = useMemo(() => {
  return t(
    `The current user only has the UI configuration permission, but don't have "{{actionName}}" permission for field "{{name}}"`,
    {
      name: nameValue,
      actionName: t(capitalize(actionName)),
    },
  ).replaceAll('&gt;', '>');
}, [nameValue, t]);
```

This code demonstrates how NocoBase handles field-level permissions, displaying lock icons and tooltip messages when users lack action permissions on specific fields.

## Security Implementation

### Safe Globals in Execution Contexts

For sensitive operations like custom JavaScript execution (e.g., RunJS nodes in workflows), NocoBase implements safe globals to prevent unauthorized access:

```typescript
// From: packages/core/flow-engine/src/utils/safeGlobals.ts
const allowed: Record<string, any> = {
  clipboard,
};

Object.defineProperty(allowed, 'onLine', {
  get: () => !!nav?.onLine,
  enumerable: true,
  configurable: false,
});

return new Proxy(
  {},
  {
    get(_t, prop: string) {
      if (prop in allowed) return (allowed as any)[prop];
      throw new Error(`Access to navigator property "${String(prop)}" is not allowed.`);
    },
  },
);
```

This security measure ensures that sensitive browser APIs are either read-only or completely blocked in untrusted execution contexts.

### URL Security Validation

When workflows or scripts need to open URLs, NocoBase enforces strict URL validation:

```typescript
// From: packages/core/flow-engine/src/utils/safeGlobals.ts
const isSafeUrl = (u: string): boolean => {
  try {
    const parsed = new URL(u, getSafeBaseHref());
    const protocol = parsed.protocol.toLowerCase();
    if (protocol === 'about:') return parsed.href === 'about:blank';
    return protocol === 'http:' || protocol === 'https:';
  } catch {
    return false;
  }
};
```

Only `http://`, `https://`, and `about:blank` URLs are permitted, preventing potential security vulnerabilities from malicious URL schemes.

## Plugin Dependencies

The authentication and permissions system depends on a plugin hierarchy:

```mermaid
graph BT
    A[plugin-auth] --> B[plugin-users]
    C[plugin-acl] --> B
    B --> D[plugin-core]
```

| Plugin | Purpose |
|--------|---------|
| `plugin-auth` | Authentication mechanisms |
| `plugin-users` | User management |
| `plugin-acl` | Access Control List implementation |

## Related Documentation

| Document | Path |
|----------|------|
| Auth Verification | `docs/docs/en/auth-verification/index.md` |
| ACL Permissions | `docs/docs/en/users-permissions/acl/permissions.md` |
| User Permissions Guide | `docs/docs/en/users-permissions/index.md` |
| ACL Plugin | `docs/docs/en/plugins/@nocobase/plugin-acl/index.md` |
| Auth Plugin | `docs/docs/en/plugins/@nocobase/plugin-auth/index.md` |
| Users Plugin | `docs/docs/en/plugins/@nocobase/plugin-users/index.md` |

---

<a id='ai-integration'></a>

## AI Integration

### 相关页面

相关主题：[Overview](#overview), [Workflow Engine](#workflow-engine), [Plugin Development](#plugin-development)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/chatbox/Messages.tsx](https://github.com/nocobase/nocobase/blob/main/packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/chatbox/Messages.tsx)
- [packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/admin/Employees.tsx](https://github.com/nocobase/nocobase/blob/main/packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/admin/Employees.tsx)
- [packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/admin/Templates.tsx](https://github.com/nocobase/nocobase/blob/main/packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/admin/Templates.tsx)
- [packages/plugins/@nocobase/plugin-ai/src/server/tools/docs.ts](https://github.com/nocobase/nocobase/blob/main/packages/plugins/@nocobase/plugin-ai/src/server/tools/docs.ts)
- [packages/core/flow-engine/src/runjs-context/contexts/base.ts](https://github.com/nocobase/nocobase/blob/main/packages/core/flow-engine/src/runjs-context/contexts/base.ts)
- [packages/core/client/src/flow/actions/customVariable.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/flow/actions/customVariable.tsx)
</details>

# AI Integration

NocoBase provides a comprehensive AI Integration system through the `@nocobase/plugin-ai` package. This system enables users to create, manage, and deploy AI employees that can collaborate with human users to build and manage business applications. The AI integration leverages modern LLM (Large Language Model) technology to provide intelligent assistance throughout the platform.

## Overview

The AI Integration feature in NocoBase is designed to:

- Enable AI agents to work alongside human users in a collaborative environment
- Provide customizable AI employees with different roles and capabilities
- Support knowledge base integration for context-aware responses
- Offer tool-calling capabilities for AI to interact with the NocoBase system

资料来源：[packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/chatbox/Messages.tsx:1-40]()

## Architecture

The AI Integration system follows a plugin-based architecture that integrates seamlessly with the NocoBase core system.

### System Components

| Component | Purpose | Location |
|-----------|---------|----------|
| AI Employees | Virtual team members that can perform tasks | `packages/plugins/@nocobase/plugin-ai` |
| Chat Interface | Real-time messaging between users and AI | `src/client/ai-employees/chatbox/` |
| Admin Panel | Management interface for AI configurations | `src/client/ai-employees/admin/` |
| Templates | Pre-configured AI employee templates | `src/client/ai-employees/admin/Templates.tsx` |
| Tool System | Server-side tools for AI operations | `src/server/tools/` |

资料来源：[packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/admin/Employees.tsx:1-80]()

## AI Employees

AI Employees are virtual team members that can be assigned tasks, communicate with users, and perform various operations within the NocoBase ecosystem.

### Employee Management

The `Employees` component provides a comprehensive interface for managing AI employees:

```tsx
<SchemaComponent
  components={{ AIEmployeeForm, Avatar, Templates, Enabled, EnableSwitch, CategoryFilter, Username }}
  scope={{
    t,
    useCreateFormProps,
    useEditFormProps,
    useCancelActionProps,
    useCreateActionProps,
    useEditActionProps,
    useDeleteActionProps,
  }}
  schema={{
    type: 'void',
    name: 'ai-employees',
    properties: {
      block: {
        type: 'void',
        'x-component': 'CardItem',
        'x-component-props': {
          heightMode: 'fullHeight',
        },
        'x-decorator': 'TableBlockProvider',
        'x-decorator-props': {
          collection: 'aiEmployees',
          action: 'list',
          params: {
            filter: {
              category: 'business',
            },
          },
          rowKey: 'username',
          dragSort: true,
          dragSortBy: 'sort',
        },
      },
    },
  }}
/>
```

资料来源：[packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/admin/Employees.tsx:35-75]()

### Employee Data Model

| Field | Type | Description |
|-------|------|-------------|
| username | string | Unique identifier for the AI employee |
| category | string | Classification category (e.g., 'business') |
| enabled | boolean | Whether the employee is active |
| sort | number | Display order |
| templates | array | Pre-configured task templates |

### Category Filtering

AI employees can be filtered by category using the `CategoryFilter` component, allowing administrators to organize employees based on their functional areas or roles.

资料来源：[packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/admin/Employees.tsx:50-55]()

## Chat Interface

The chatbox component provides a real-time messaging interface for user interaction with AI employees.

### Message Display

Messages are rendered using the `Messages` component which handles different message states:

```tsx
<div className={styles.chatBox}>
  {messages.length > 0 ? (
    <div className={styles.messages}>
      {messages.map((msg) => {
        return (
          <Message
            key={msg.key}
            loading={msg.loading}
            content={msg.content}
          />
        );
      })}
    </div>
  ) : (
    <div
      style={{
        position: 'absolute',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        color: token.colorTextDescription,
      }}
    >
      {t('Work with your AI crew')}
    </div>
  )}
</div>
```

资料来源：[packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/chatbox/Messages.tsx:10-40]()

### Message States

| State | Description | Visual Indicator |
|-------|-------------|------------------|
| normal | Standard message display | Default styling |
| loading | Message being processed | Loading spinner |
| error | Failed message | Error styling |
| streaming | Real-time response | Progressive rendering |

## Templates System

Templates provide pre-configured AI employee configurations that can be quickly deployed to create new AI team members.

### Template Loading

Templates are loaded dynamically from the server:

```tsx
const { data: templates, loading } = useRequest<{ data: AIEmployee[] }>(() =>
  api
    .resource('aiEmployees')
    .getTemplates()
    .then((res) => res?.data?.data),
);
```

资料来源：[packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/admin/Templates.tsx:1-30]()

### Template Creation Flow

When creating a new employee from a template, the system uses a drawer component with form validation:

```tsx
<SchemaComponent
  scope={{ useCancelActionProps, useCreateActionProps, useTemplateFormProps }}
  schema={{
    type: 'void',
    name: uid(),
    'x-component': 'Action.Drawer',
    title: '{{t("New AI employee")}}',
    'x-decorator': 'FormV2',
    'x-use-decorator-props': 'useTemplateFormProps',
    properties: {
      form: {
        type: 'void',
        'x-component': 'AIEmployeeForm',
      },
      footer: {
        type: 'void',
        'x-component': 'Action.Drawer.Footer',
        properties: {
          close: {
            title: 'Cancel',
            'x-component': 'Action',
            'x-component-props': {
              type: 'default',
            },
            'x-use-component-props': 'useCancelActionProps',
          },
          submit: {
            title: '{{t("Submit")}}',
            'x-component': 'Action',
            'x-component-props': {
              type: 'primary',
            },
            'x-use-component-props': 'useCreateActionProps',
          },
        },
      },
    },
  }}
/>
```

资料来源：[packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/admin/Templates.tsx:35-85]()

## Server-Side Tools

The AI integration includes server-side tools that allow AI employees to interact with various NocoBase system components.

### Documentation Reader Tool

The `readDocEntry` tool enables AI employees to access and read documentation entries:

```tsx
readDocEntry: {
  description: 'Read a documentation entry',
  parameters: {
    type: 'object',
    properties: {
      module: {
        type: 'string',
        description: 'The module key (e.g., "runjs")',
      },
    },
    required: ['module'],
  },
  async handler(ctx) {
    try {
      const { pluginKey, relativePath, canonicalPath } = parseDocPath(input);
      const meta = docsModules.get(pluginKey);
      if (!meta) {
        throw new Error(`Document module "${pluginKey}" not found.`);
      }
      // Read and return documentation content
    } catch (error) {
      ctx.log?.error?.(error, {
        module: 'ai',
        subModule: 'toolCalling',
        toolName: 'readDocEntry',
      });
      return {
        status: 'error',
        content: `Failed to read docs entry: ${error.message}`,
      };
    }
  },
},
```

资料来源：[packages/plugins/@nocobase/plugin-ai/src/server/tools/docs.ts:1-80]()

### Tool Execution Flow

```mermaid
graph TD
    A[User Request] --> B[AI Employee Processing]
    B --> C{Requires Tool?}
    C -->|Yes| D[Tool Selection]
    C -->|No| E[Direct Response]
    D --> F[Execute Server Tool]
    F --> G[Tool Handler]
    G --> H[Error Handling]
    H --> I[Return Result]
    E --> I
    I --> J[Response to User]
```

### Available Server Tools

| Tool Name | Purpose | Module |
|-----------|---------|--------|
| readDocEntry | Read documentation entries | ai |
| customVariable | Manage flow variables | flow |
| runjs | Execute JavaScript code | flow-engine |

## AI Context in Workflows

The AI system integrates with NocoBase's workflow engine through a comprehensive context system that provides AI employees access to system resources.

### Resource Context

AI employees can interact with resources through the context API:

```typescript
interface ResourceContext {
  setData: {
    description: '设置资源当前数据（仅前端）';
    detail: '(value: any) => this';
    completion: { insertText: 'ctx.resource.setData(value)' };
  };
  refresh: {
    description: '从后端刷新数据';
    detail: '() => Promise<any>';
    completion: { insertText: 'await ctx.resource.refresh()' };
  };
  on: {
    description: '订阅资源事件';
    detail: '(event: string, callback: (...args) => void) => void';
    completion: { insertText: "ctx.resource.on('refresh', () => {})" };
  };
  setResourceName: {
    description: '设置资源名称';
    detail: '(resourceName: string) => this';
    completion: { insertText: "ctx.resource.setResourceName('users')" };
  };
  setFilterByTk: {
    description: '设置主键/过滤键';
    detail: '(filterByTk: any) => this';
    completion: { insertText: 'ctx.resource.setFilterByTk(filterByTk)' };
  };
  runAction: {
    description: '执行资源动作';
  };
}
```

资料来源：[packages/core/flow-engine/src/runjs-context/contexts/base.ts:1-50]()

## Flow Variables

AI integration supports custom variables that can be used in workflows and shared between human and AI collaborators.

### Variable Management Interface

The variable management UI provides full CRUD operations:

```tsx
columns={[
  {
    title: t('Name'),
    dataIndex: 'name',
    key: 'name',
    ellipsis: true,
    render: (text: string) => <span style={{ whiteSpace: 'nowrap' }}>{text}</span>,
  },
  {
    title: t('Identifier'),
    dataIndex: 'key',
    key: 'key',
    ellipsis: true,
  },
  {
    title: t('Type'),
    dataIndex: 'type',
    key: 'type',
    render: (type: FlowVariableType) => (
      <Tag style={{ whiteSpace: 'nowrap' }}>{t(VARIABLE_TYPE_LABELS[type] || type)}</Tag>
    ),
  },
  {
    title: t('Actions'),
    key: 'actions',
    render: (_: unknown, __: FlowVariable, index: number) => (
      <Space size={12}>
        <Button
          type="link"
          size="small"
          icon={<EditOutlined />}
          onClick={() => handleEdit(index)}
        />
        <Button
          type="link"
          size="small"
          icon={<DeleteOutlined />}
          danger
          onClick={() => handleDelete(index)}
        />
      </Space>
    ),
  },
]}
```

资料来源：[packages/core/client/src/flow/actions/customVariable.tsx:1-70]()

### Variable Types

| Type | Label | Description |
|------|-------|-------------|
| string | String | Text value |
| number | Number | Numeric value |
| boolean | Boolean | True/false value |
| date | Date | Date and time value |
| object | Object | Complex data structure |
| array | Array | Collection of values |

## Error Handling

The AI integration system includes comprehensive error handling for both client and server components.

### Client-Side Error Fallback

```tsx
<Result
  style={{ maxWidth: '60vw', margin: 'auto' }}
  status="error"
  title={t('Render Failed')}
  subTitle={subTitle}
  extra={[
    <Button type="primary" key="feedback" href="https://github.com/nocobase/nocobase/issues" target="_blank">
      {t('Feedback')}
    </Button>,
    <Button key="log" loading={loading} onClick={download}>
      {t('Download logs')}
    </Button>,
  ]}
>
  <Paragraph copyable={{ text: error.stack }}>
    <Text type="danger" style={{ whiteSpace: 'pre-line', textAlign: 'center' }}>
      {error.stack}
    </Text>
  </Paragraph>
</Result>
```

资料来源：[packages/core/client/src/schema-component/antd/error-fallback/ErrorFallback.tsx:1-30]()

### Server-Side Error Logging

Errors are logged with module context for debugging:

```tsx
ctx.log?.error?.(error, {
  module: 'ai',
  subModule: 'toolCalling',
  toolName: 'readDocEntry',
});
```

## Installation and Setup

To enable AI integration in NocoBase:

1. Install the `@nocobase/plugin-ai` package
2. Configure the plugin in the NocoBase administration panel
3. Set up AI provider credentials (API keys for LLM services)
4. Create AI employees and assign roles
5. Configure knowledge bases and tools as needed

## Summary

The AI Integration system in NocoBase provides a powerful framework for creating intelligent AI employees that can collaborate with human users. Key features include:

- **Employee Management**: Create, edit, and organize AI team members with different roles
- **Real-time Chat**: Direct communication channel between users and AI employees
- **Template System**: Quick deployment of pre-configured AI employees
- **Tool Integration**: AI can access NocoBase system capabilities through server-side tools
- **Workflow Integration**: AI context available in NocoBase workflow engine
- **Error Handling**: Comprehensive error reporting and recovery mechanisms

This system enables organizations to build AI-powered business applications that leverage the intelligence of large language models while maintaining the flexibility and extensibility of the NocoBase no-code platform.

---

<a id='file-storage'></a>

## File Storage

### 相关页面

相关主题：[Data Modeling](#data-modeling), [Interface Builder](#interface-builder)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/core/client/src/schema-component/antd/upload/index.md](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-component/antd/upload/index.md)
- [packages/core/client/src/schema-component/antd/upload/Upload.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-component/antd/upload/Upload.tsx)
- [packages/core/client/src/schema-component/antd/input/ScanInput/QRCodeScanner.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-component/antd/input/ScanInput/QRCodeScanner.tsx)
- [packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx)
- [packages/core/flow-engine/src/utils/resolveModuleUrl.ts](https://github.com/nocobase/nocobase/blob/main/packages/core/flow-engine/src/utils/resolveModuleUrl.ts)
</details>

# File Storage

## Overview

File Storage in NocoBase is a comprehensive system for managing file uploads, storage, and preview capabilities across the platform. The system is built on top of Ant Design's Upload component and extends it with additional features such as thumbnail preview, file type validation, size restrictions, and integration with the broader schema system.

The file storage subsystem consists of several key components:

- **Upload Component**: The primary interface for file uploads
- **Storage Adapters**: Backend mechanisms for persisting files
- **File Preview**: Preview capabilities for various file types
- **Schema Integration**: Deep integration with NocoBase's schema system

资料来源：[packages/core/client/src/schema-component/antd/upload/index.md:1-24]()

## Upload Component

### Type Definitions

The Upload component is defined with the following type signature:

```typescript
type UploadProps = Omit<AntdUploadProps, 'onChange'> & {
  onChange?: (fileList: UploadFile[]) => void;
  serviceErrorMessage?: string;
  value?: any;
  size?: string;
};
```

资料来源：[packages/core/client/src/schema-component/antd/upload/index.md:8-13]()

The component accepts all Ant Design Upload props while extending them with NocoBase-specific functionality. The `value` prop allows for controlled usage within schema forms, and `size` can be used to restrict upload behavior.

### Read Pretty Mode

For display-only scenarios, a specialized read-pretty variant is available:

```typescript
type UploadReadPrettyProps = AntdUploadProps;
```

资料来源：[packages/core/client/src/schema-component/antd/upload/index.md:17-18]()

## File List Item Rendering

The file list rendering in `Upload.tsx` demonstrates how individual uploaded files are displayed to users:

```typescript
const item = [
  <span key="thumbnail" className={`${prefixCls}-list-item-thumbnail`}>
    <ThumbnailPreviewer file={file} />
  </span>,
  showFileName !== false && file.title ? (
    <span key="title" className={`${prefixCls}-list-item-name`} title={file.title}>
      {file.status === 'uploading' ? t('Uploading') : file.title}
    </span>
  ) : null,
];
```

资料来源：[packages/core/client/src/schema-component/antd/upload/Upload.tsx:1-11]()

The rendered item can be either a clickable link (if `file.url` exists) or a plain span:

```typescript
const wrappedItem = file.url ? (
  <a target="_blank" rel="noopener noreferrer" href={file.url} onClick={handleClick}>
    {item}
  </a>
) : (
  <span className={`${prefixCls}-span`}>{item}</span>
);
```

资料来源：[packages/core/client/src/schema-component/antd/upload/Upload.tsx:13-20]()

### File Actions

Each file item includes action buttons for managing the upload:

| Action | Condition | Icon | Handler |
|--------|-----------|------|---------|
| Download | `!readPretty && file.url` | `DownloadOutlined` | `onDownload` |
| Delete | `!readPretty && !disabled && file.status !== 'uploading'` | `DeleteOutlined` | `onDelete` |

资料来源：[packages/core/client/src/schema-component/antd/upload/Upload.tsx:23-35]()

## Upload Workflow

```mermaid
graph TD
    A[User Selects File] --> B{File Size Check}
    B -->|Greater than 1MB| C[Show Error Alert]
    B -->|Within Limit| D[startScanFile]
    D --> E[Upload to Server]
    E --> F{Upload Status}
    F -->|uploading| G[Show Progress]
    F -->|done| H[Display Thumbnail]
    F -->|error| I[Show Error State]
```

## File Size Validation

The system enforces a 1MB limit on uploaded images with user-friendly error messaging:

```typescript
if (file && file.size < 1024 * 1024) {
  startScanFile(file);
} else {
  alert(t('The image size is too large. Please compress it to below 1MB before uploading'));
}
```

资料来源：[packages/core/client/src/schema-component/antd/input/ScanInput/QRCodeScanner.tsx:1-8]()

This validation pattern ensures users receive clear guidance when attempting to upload oversized files.

## Thumbnail Preview

The thumbnail previewer component handles generating previews for uploaded files. The `ThumbnailPreviewer` component is referenced in the upload component's item rendering and provides visual feedback for uploaded content.

## Integration with Schema System

### Schema Designer Integration

Files can be configured and managed through NocoBase's schema system using the `GeneralSchemaDesigner` component:

```typescript
<span className={'title-tag'}>
  {showDataSource && dataSource
    ? `${compile(dataSource?.displayName)} > ${compile(title)}`
    : compile(title)}
</span>
```

资料来源：[packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx:1-8]()

This allows file storage configurations to be embedded within the broader schema initialization and settings infrastructure.

## File Type Detection

The upload system includes utility functions for determining file types, including CSS file detection:

```typescript
export function isCssFile(url: string): boolean {
  if (!url || typeof url !== 'string') {
    return false;
  }
  // 去掉 query 和 hash 后判断文件扩展名
  const pathPart = url.split('?')[0].split('#')[0];
  return pathPart.endsWith('.css');
}
```

资料来源：[packages/core/flow-engine/src/utils/resolveModuleUrl.ts:1-14]()

This utility strips query parameters and hash fragments before checking file extensions, supporting URLs like `example.css?v=123` or `example.css#section`.

## Configuration Options

### Upload Component Properties

| Property | Type | Description | Default |
|----------|------|-------------|---------|
| `value` | `any` | Controlled value for the file list | - |
| `onChange` | `(fileList: UploadFile[]) => void` | Callback when file list changes | - |
| `serviceErrorMessage` | `string` | Custom error message for upload failures | - |
| `size` | `string` | Size restriction identifier | - |
| `readPretty` | `boolean` | Display-only mode | `false` |

### File List Item States

| Status | UI Indicator | Available Actions |
|--------|--------------|-------------------|
| `uploading` | Progress indicator | None |
| `done` | Thumbnail + filename | Download, Delete |
| `error` | Error state | Delete |

## Best Practices

1. **Size Limits**: Always validate file sizes before upload to provide immediate user feedback
2. **Thumbnail Previews**: Enable thumbnails to improve user experience for image files
3. **Accessible Links**: Use proper `target="_blank"` and `rel="noopener noreferrer"` for downloaded files
4. **Status Indicators**: Show upload progress and error states clearly
5. **URL Handling**: Strip query parameters and hash fragments when determining file types

---

<a id='cluster-mode'></a>

## Cluster Mode

### 相关页面

相关主题：[Deployment](#deployment), [System Architecture](#system-architecture)

<details>
<summary>Related Source Files</summary>

The following source files were referenced for this documentation:

- [docs/docs/en/cluster-mode/index.md](https://github.com/nocobase/nocobase/blob/main/docs/docs/en/cluster-mode/index.md)
- [docs/docs/en/cluster-mode/kubernetes.md](https://github.com/nocobase/nocobase/blob/main/docs/docs/en/cluster-mode/kubernetes.md)
- [docs/docs/en/cluster-mode/development.md](https://github.com/nocobase/nocobase/blob/main/docs/docs/en/cluster-mode/development.md)
- [docs/docs/en/cluster-mode/operations.md](https://github.com/nocobase/nocobase/blob/main/docs/docs/en/cluster-mode/operations.md)
- [docs/docs/en/cluster-mode/preparations.md](https://github.com/nocobase/nocobase/blob/main/docs/docs/en/cluster-mode/preparations.md)
- [docs/docs/en/plugins/@nocobase/plugin-lock-adapter-redis/index.md](https://github.com/nocobase/nocobase/blob/main/docs/docs/en/plugins/@nocobase/plugin-lock-adapter-redis/index.md)
- [docs/docs/en/plugins/@nocobase/plugin-pubsub-adapter-redis/index.md](https://github.com/nocobase/nocobase/blob/main/docs/docs/en/plugins/@nocobase/plugin-pubsub-adapter-redis/index.md)
</details>

# Cluster Mode

## Overview

Cluster Mode in NocoBase enables horizontal scaling by running multiple application instances behind a load balancer. This architecture provides high availability, improved performance under concurrent load, and fault tolerance for production deployments.

## Architecture Overview

```mermaid
graph TD
    Client1[Client] --> LB[Load Balancer]
    Client2[Client] --> LB
    Client3[Client] --> LB
    LB --> App1[NocoBase Instance 1]
    LB --> App2[NocoBase Instance 2]
    LB --> App3[NocoBase Instance N]
    App1 <--> Redis[(Redis)]
    App2 <--> Redis
    App3 <--> Redis
    App1 <--> DB[(Database)]
    App2 <--> DB
    App3 <--> DB
```

### Core Components

| Component | Purpose | Required |
|-----------|---------|----------|
| Load Balancer | Distributes traffic across instances | Yes |
| NocoBase Instances | Application servers running the same codebase | Yes |
| Shared Database | MySQL/PostgreSQL for persistent data storage | Yes |
| Redis | Lock adapter and pub/sub for inter-instance communication | Yes |
| File Storage | S3/MinIO for file uploads (shared across instances) | Yes |

## Prerequisites

### Infrastructure Requirements

Before deploying in cluster mode, ensure the following:

1. **Database**: MySQL 8.0+ or PostgreSQL 12+ with proper network access
2. **Redis**: Redis 6.0+ for distributed locking and pub/sub
3. **File Storage**: Shared storage solution (S3-compatible, MinIO, or NFS)
4. **Load Balancer**: Nginx, HAProxy, or cloud provider LB

### Environment Variables

| Variable | Description | Example |
|----------|-------------|---------|
| `APP_ENV` | Application environment | `production` |
| `DB_DIALECT` | Database type | `mysql` or `postgres` |
| `DB_HOST` | Database host | `localhost` |
| `DB_PORT` | Database port | `3306` |
| `DB_DATABASE` | Database name | `nocobase` |
| `DB_USER` | Database user | `nocobase` |
| `DB_PASSWORD` | Database password | `***` |
| `REDIS_URL` | Redis connection string | `redis://localhost:6379` |
| `CACHE_STORAGE` | Cache storage type | `redis` |

## Redis Plugins

NocoBase requires two Redis plugins for cluster operation:

### Lock Adapter (Redis)

Handles distributed locking to prevent race conditions across instances.

**Plugin**: `@nocobase/plugin-lock-adapter-redis`

```bash
npm install @nocobase/plugin-lock-adapter-redis
```

Configuration in `database.yml`:

```yaml
plugins:
  - name: lock
    options:
      type: redis
      redis:
        port: 6379
        host: localhost
        password: ''
        db: 0
```

### Pub/Sub Adapter (Redis)

Enables real-time communication between instances for features like:

- Live query updates
- Real-time collaboration
- Broadcast notifications

**Plugin**: `@nocobase/plugin-pubsub-adapter-redis`

```bash
npm install @nocobase/plugin-pubsub-adapter-redis
```

## Deployment Options

### Docker Compose (Development/Testing)

```yaml
version: '3.8'
services:
  app:
    image: nocobase/app:latest
    replicas: 3
    depends_on:
      - redis
      - db
    environment:
      - APP_ENV=production
      - DB_DIALECT=postgres
      - REDIS_URL=redis://redis:6379
    deploy:
      replicas: 3

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

  db:
    image: postgres:15
    environment:
      - POSTGRES_DB=nocobase
      - POSTGRES_USER=nocobase
      - POSTGRES_PASSWORD=nocobase
```

### Kubernetes Deployment

For production environments, Kubernetes provides:

- Automatic scaling
- Rolling updates
- Self-healing capabilities
- Service discovery

Refer to the [Kubernetes Deployment Guide](kubernetes.md) for detailed configuration.

## Configuration

### Load Balancer Configuration (Nginx)

```nginx
upstream nocobase_backend {
    least_conn;
    server app1:13000 weight=5;
    server app2:13000 weight=5;
    server app3:13000 weight=5;
}

server {
    listen 80;
    server_name your-domain.com;

    location / {
        proxy_pass http://nocobase_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location /socket.io/ {
        proxy_pass http://nocobase_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}
```

### Application Configuration

In `data/source/database.yml`:

```yaml
database:
  type: mysql
  ...
  pool: 10

redis:
  host: redis-host
  port: 6379

plugins:
  - '@nocobase/plugin-lock-adapter-redis'
  - '@nocobase/plugin-pubsub-adapter-redis'
```

## Operations

### Health Checks

Configure health check endpoints on the load balancer:

| Endpoint | Expected Response | Purpose |
|----------|-------------------|---------|
| `/api/health` | `200 OK` | Instance health status |
| `/api/healthy` | `200 OK` | Readiness probe |

### Scaling

```mermaid
graph LR
    A[Request] --> B{Higher Load?}
    B -->|Yes| C[Scale Up Instances]
    B -->|No| D[Current Scale]
    C --> E[Update LB Pool]
    E --> A
```

### Monitoring

Key metrics to monitor:

- Request latency per instance
- Database connection pool usage
- Redis connection status
- Session distribution
- Error rates per instance

### Rolling Updates

1. Deploy new version to subset of instances
2. Remove updated instances from LB pool temporarily
3. Update remaining instances
4. Restore full instance count

## Troubleshooting

### Common Issues

| Issue | Cause | Solution |
|-------|-------|----------|
| 502 Bad Gateway | All instances down | Check instance logs, restart services |
| Stale data displayed | Cache inconsistency | Clear Redis cache, check pub/sub connectivity |
| Lock contention | High concurrency | Increase Redis resources, optimize locking strategy |
| WebSocket disconnection | Proxy timeout | Configure longer timeouts in load balancer |

### Diagnostics

```bash
# Check instance connectivity
curl http://instance-ip:13000/api/health

# Verify Redis connectivity
redis-cli -h redis-host ping

# Check database connectivity
npm run nocobase db:ping
```

## Best Practices

1. **Stateless Design**: Ensure applications do not store user state locally
2. **Session Management**: Use Redis-backed sessions for sticky sessions
3. **Database Connection Pooling**: Configure appropriate pool sizes per instance
4. **File Storage**: Use shared storage to ensure file consistency
5. **Graceful Shutdown**: Configure proper shutdown handlers for rolling updates
6. **Logging**: Centralize logs from all instances for debugging

## Related Documentation

- [Kubernetes Deployment](kubernetes.md)
- [Development Setup](development.md)
- [Operations Guide](operations.md)
- [Preparations](preparations.md)
- [Redis Lock Adapter Plugin](../plugins/@nocobase/plugin-lock-adapter-redis/index.md)
- [Redis Pub/Sub Adapter Plugin](../plugins/@nocobase/plugin-pubsub-adapter-redis/index.md)

---

<a id='plugin-development'></a>

## Plugin Development

### 相关页面

相关主题：[Plugin System](#plugin-system), [System Architecture](#system-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/core/client/src/pm/PluginDetail.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/pm/PluginDetail.tsx)
- [packages/core/client/src/pm/PluginManagerLink.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/pm/PluginManagerLink.tsx)
- [packages/core/client/src/application/utils/remotePlugins.ts](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/application/utils/remotePlugins.ts)
- [packages/core/client/src/nocobase-buildin-plugin/index.tsx](https://github.com/nocobase/nocobase/blob/main/packages/core/client/src/nocobase-buildin-plugin/index.tsx)
</details>

# Plugin Development

## Overview

NocoBase adopts a **plugin-based architecture** where every feature is implemented as a plugin. This modular design enables:

- **Extensibility**: Add new functionality without modifying the core system
- **Maintainability**: Features are isolated and independently deployable
- **Reusability**: Plugins can be shared and reused across different projects
- **Hot-loading**: Plugins can be loaded/unloaded at runtime

```mermaid
graph TD
    A[NocoBase Core] --> B[Plugin System]
    B --> C[Server Plugins]
    B --> D[Client Plugins]
    C --> E[Database Operations]
    C --> F[API Routes]
    C --> G[Event Handlers]
    D --> H[UI Components]
    D --> I[Schema Initializers]
    D --> J[Schema Settings]
```

## Plugin Structure

A typical NocoBase plugin follows this directory structure:

```bash
my-plugin/
├── src/
│   ├── client/           # Client-side code
│   │   ├── index.ts      # Client plugin entry
│   │   └── components/   # UI components
│   ├── server/           # Server-side code
│   │   ├── index.ts      # Server plugin entry
│   │   ├── actions/      # Custom actions
│   │   └── migrations/   # Database migrations
│   └── index.ts          # Main entry (client + server)
├── package.json
└── dist/                 # Build output
    └── externalVersion.js
```

## Plugin Types

### Server Plugins

Server plugins handle backend logic including database operations, API routes, and event handling.

**Entry Point** (`src/server/index.ts`):

```typescript
import { Plugin } from '@nocobase/server';

export default class MyPlugin extends Plugin {
  async load() {
    // Register collections
    this.app.collection({
      name: 'posts',
      fields: [
        { type: 'string', name: 'title' },
        { type: 'text', name: 'content' },
      ],
    });

    // Register API routes
    this.app.resourcer.define({
      name: 'posts',
      actions: {
        async list(ctx, next) {
          ctx.body = await ctx.db.getRepository('posts').find();
          await next();
        },
      },
    });
  }
}

Plugin.register(MyPlugin);
```

资料来源：[packages/core/client/src/pm/PluginDetail.tsx:1-50]()

### Client Plugins

Client plugins manage UI components, schema initializers, and schema settings.

**Entry Point** (`src/client/index.ts`):

```typescript
import { Plugin } from '@nocobase/client';

export default class MyPlugin extends Plugin {
  async load() {
    // Register schema initializer
    this.schemaInitializerManager.addItem(
      'charts',
      'my-plugin:item',
      {
        title: 'My Chart',
        component: 'MyChartComponent',
      }
    );

    // Register schema settings
    this.schemaSettingsManager.add('my-plugin:settings', {
      title: 'My Settings',
      items: [
        { name: 'title', component: 'Input' },
        { name: 'delete', type: 'danger' },
      ],
    });
  }
}

Plugin.register(MyPlugin);
```

资料来源：[packages/core/client/src/pm/PluginManagerLink.tsx:1-30]()

## Remote Plugins

NocoBase supports loading plugins remotely via require.js. Remote plugins are configured through the application settings and loaded on demand.

**Configuration** (`src/application/utils/remotePlugins.ts`):

```typescript
export function configRequirejs(requirejs: any, pluginData: PluginData[]) {
  requirejs.requirejs.config({
    waitSeconds: 120,
    paths: pluginData.reduce<Record<string, string>>((acc, cur) => {
      acc[cur.packageName] = cur.url;
      return acc;
    }, {}),
  });
}

export function processRemotePlugins(
  pluginData: PluginData[], 
  resolve: (plugins: [string, typeof Plugin][]) => void
) {
  return (...pluginModules: (typeof Plugin & { default?: typeof Plugin })[]) => {
    const res: [string, typeof Plugin][] = pluginModules
      .map<[string, typeof Plugin]>((item, index) => [
        pluginData[index].name, 
        item?.default || item
      ])
      .filter((item) => item[1]);
    resolve(res);
  };
}
```

Key characteristics:
- **Timeout**: 120 seconds wait time for plugin loading
- **Path Mapping**: Maps package names to remote URLs
- **Default Export**: Automatically handles both default and named exports

资料来源：[packages/core/client/src/application/utils/remotePlugins.ts:40-70]()

## Plugin Lifecycle

```mermaid
stateDiagram-v2
    [*] --> Registered
    Registered --> Loading
    Loading --> Loaded
    Loaded --> Enabled
    Enabled --> Disabled
    Disabled --> Enabled
    Enabled --> Unloaded
    Unloaded --> [*]
```

### Application States

The plugin system tracks various application states during initialization:

| State Code | Status | Icon | Description |
|------------|--------|------|-------------|
| `APP_PREPARING` | info | LoadingOutlined | App preparing |
| `APP_INITIALIZING` | info | LoadingOutlined | App initializing |
| `APP_INITIALIZED` | info | - | App initialized |
| `APP_NOT_INSTALLED_ERROR` | warning | - | App not installed |
| `APP_STOPPED` | warning | - | App stopped |
| `APP_COMMANDING` | info | LoadingOutlined | App commanding |
| `ENOENT`, `APP_ERROR`, `LOAD_ERROR` | error | - | App error |

资料来源：[packages/core/client/src/nocobase-buildin-plugin/index.tsx:1-60]()

## Plugin Manager

The Plugin Manager provides a UI interface for managing plugins with the following features:

### Plugin Detail Display

```typescript
interface PluginDetailProps {
  plugin: {
    packageName: string;
    version: string;
    name: string;
    displayName?: string;
    description?: string;
    version?: string;
  };
  data?: {
    packageJson: {
      license?: string;
    };
    homepage?: string;
    depsCompatible: boolean | null;
    isCompatible: boolean;
  };
}
```

The plugin detail view displays:

- **Package Name**: Unique identifier for the plugin
- **Version**: Current installed version
- **Display Name**: Human-readable name
- **Description**: Plugin functionality description
- **License**: Package license type
- **Homepage**: External documentation URL
- **Dependencies**: Compatibility status

资料来源：[packages/core/client/src/pm/PluginDetail.tsx:1-100]()

### Dependencies Compatibility Check

```typescript
{
  key: 'dependencies',
  label: t('Dependencies compatibility check'),
  children: (
    <>
      {data?.data?.depsCompatible === false ? (
        <Typography.Text type="danger">
          {t('`dist/externalVersion.js` not found or failed to `require`. Please rebuild this plugin.')}
        </Typography.Text>
      ) : (
        <>
          {!data?.data?.['isCompatible'] && (
            <Alert
              showIcon
              type={'error'}
              message={t('Plugin dependencies check failed...')}
            />
          )}
          <Table
            rowKey={'name'}
            pagination={false}
            columns={dependenciesCompatibleTableColumns}
            dataSource={data?.data?.depsCompatible}
          />
        </>
      )}
    </>
  ),
}
```

| Check Type | Condition | Message |
|------------|-----------|---------|
| Build Required | `dist/externalVersion.js` not found | Rebuild plugin required |
| Compatibility | `isCompatible === false` | Dependency version mismatch |
| Success | All checks pass | Dependencies compatible |

资料来源：[packages/core/client/src/pm/PluginDetail.tsx:20-45]()

## Plugin Settings

Plugins can register their own settings pages in the administration interface:

```typescript
const settingItems = settings
  .filter((setting) => setting.visible !== false)
  .map((setting) => {
    return {
      key: setting.name,
      icon: setting.icon,
      label: setting.link ? (
        <div onClick={() => window.open(setting.link)}>
          {compile(setting.title)}
        </div>
      ) : (
        <Link to={setting.path}>{compile(setting.title)}</Link>
      ),
    };
  });
```

| Property | Type | Description |
|----------|------|-------------|
| `name` | string | Unique setting identifier |
| `title` | string | Display title |
| `icon` | ReactNode | Setting icon |
| `path` | string | Navigation route |
| `link` | string | External link (optional) |
| `visible` | boolean | Visibility control |

资料来源：[packages/core/client/src/pm/PluginManagerLink.tsx:1-50]()

## Building Plugins

### Build Output Requirements

After building a plugin, ensure the following files exist in the `dist/` directory:

```
dist/
├── index.js
├── client.js
├── server.js
└── externalVersion.js    # Required for compatibility
```

The `externalVersion.js` file exports version information for dependency compatibility checks.

### Remote Plugin Loading

```typescript
interface PluginData {
  packageName: string;
  url: string;
  name: string;
}
```

Plugins loaded remotely must:
1. Export a default class extending `Plugin`
2. Be accessible via the configured URL
3. Include `externalVersion.js` for dependency validation

资料来源：[packages/core/client/src/application/utils/remotePlugins.ts:1-40]()

## Error Handling

### Plugin Load Errors

When plugins fail to load, the system logs detailed error messages:

```typescript
if (emptyPlugins.length > 0) {
  console.error(
    '[nocobase load plugin error]: These plugins do not have an `export.default` exported content or there is an error in the plugins. error plugins: \r\n%s',
    emptyPlugins.join(', \r\n'),
  );
}
```

Common error causes:
- Missing `export default` in the plugin entry
- Syntax errors in plugin code
- Circular dependency issues
- Timeout during remote plugin loading

### App Error States

| Error Code | Severity | Resolution |
|------------|----------|------------|
| `ENOENT` | error | Check file paths and build output |
| `APP_ERROR` | error | Review application logs |
| `LOAD_ERROR` | error | Verify plugin exports and dependencies |
| `APP_NOT_INSTALLED` | warning | Run installation command |
| `APP_STOPPED` | warning | Restart the application |

资料来源：[packages/core/client/src/nocobase-buildin-plugin/index.tsx:40-55]()

## Schema Integration

Plugins can extend the application schema system by registering:

### Schema Initializers

Enable adding new items to schema initialization panels:

```typescript
this.schemaInitializerManager.addItem(
  scope: string,      // Parent group identifier
  key: string,        // Unique item key
  item: SchemaInitializerItem  // Item configuration
);
```

### Schema Settings

Add configuration panels for schema components:

```typescript
this.schemaSettingsManager.add(
  name: string,
  config: SchemaSettingsConfig
);
```

## Best Practices

1. **Always export default**: Plugin classes must use `export default` for proper loading
2. **Include externalVersion.js**: Required for dependency compatibility checks
3. **Handle errors gracefully**: Wrap async operations in try-catch blocks
4. **Use unique namespacing**: Prefix plugin-specific names with plugin name
5. **Document dependencies**: Clearly specify version requirements in package.json

## Related Documentation

- [Write Your First Plugin](write-your-first-plugin.md)
- [Server Development](server/index.md)
- [Client Development](client/index.md)
- [Dependency Management](dependency-management.md)
- [Building Plugins](build.md)
- [Internationalization](languages.md)

---

---

## Doramagic 踩坑日志

项目：nocobase/nocobase

摘要：发现 17 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：安全/权限坑 - 来源证据：REST API: Multiple select field not working in edit form。

## 1. 安全/权限坑 · 来源证据：REST API: Multiple select field not working in edit form

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：REST API: Multiple select field not working in edit form
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_36b6b605781f4652849d06443cd76da9 | https://github.com/nocobase/nocobase/issues/8836 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 2. 安装坑 · 来源证据：v2.1.0-alpha.33

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v2.1.0-alpha.33
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_71fc97aec74e43618fab9e19d0aa9a9f | https://github.com/nocobase/nocobase/releases/tag/v2.1.0-alpha.33 | 来源类型 github_release 暴露的待验证使用条件。

## 3. 安装坑 · 来源证据：v2.1.0-beta.30

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v2.1.0-beta.30
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_3eea74dae9c548fc8058563df21058d3 | https://github.com/nocobase/nocobase/releases/tag/v2.1.0-beta.30 | 来源类型 github_release 暴露的待验证使用条件。

## 4. 配置坑 · 来源证据：v2.0.51

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：v2.0.51
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_06f3ce01049e42f586931cf6e9a46335 | https://github.com/nocobase/nocobase/releases/tag/v2.0.51 | 来源类型 github_release 暴露的待验证使用条件。

## 5. 配置坑 · 来源证据：v2.1.0-alpha.32

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：v2.1.0-alpha.32
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_7055255c88f94ecc84dfc5c09fc6c3a3 | https://github.com/nocobase/nocobase/releases/tag/v2.1.0-alpha.32 | 来源类型 github_release 暴露的待验证使用条件。

## 6. 配置坑 · 来源证据：v2.1.0-beta.29

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：v2.1.0-beta.29
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_c4b7dfdc1a164f5cb82fec5622b80342 | https://github.com/nocobase/nocobase/releases/tag/v2.1.0-beta.29 | 来源类型 github_release 暴露的待验证使用条件。

## 7. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:306829688 | https://github.com/nocobase/nocobase | README/documentation is current enough for a first validation pass.

## 8. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:306829688 | https://github.com/nocobase/nocobase | last_activity_observed missing

## 9. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:306829688 | https://github.com/nocobase/nocobase | no_demo; severity=medium

## 10. 安全/权限坑 · 存在安全注意事项

- 严重度：medium
- 证据强度：source_linked
- 发现：No sandbox install has been executed yet; downstream must verify before user use.
- 对用户的影响：用户安装前需要知道权限边界和敏感操作。
- 建议检查：转成明确权限清单和安全审查提示。
- 防护动作：安全注意事项必须面向用户前置展示。
- 证据：risks.safety_notes | github_repo:306829688 | https://github.com/nocobase/nocobase | No sandbox install has been executed yet; downstream must verify before user use.

## 11. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:306829688 | https://github.com/nocobase/nocobase | no_demo; severity=medium

## 12. 安全/权限坑 · 来源证据：v2.0.52

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v2.0.52
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_1ca2b2aac82447ea8ca5b5536fff978e | https://github.com/nocobase/nocobase/releases/tag/v2.0.52 | 来源类型 github_release 暴露的待验证使用条件。

## 13. 安全/权限坑 · 来源证据：v2.1.0-alpha.31

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v2.1.0-alpha.31
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_7a2bc590f0974b79880f86db553b3a2e | https://github.com/nocobase/nocobase/releases/tag/v2.1.0-alpha.31 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 14. 安全/权限坑 · 来源证据：v2.1.0-beta.27

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v2.1.0-beta.27
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_43d1bbbbee81474cb8e2e4f722fdb398 | https://github.com/nocobase/nocobase/releases/tag/v2.1.0-beta.27 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 15. 安全/权限坑 · 来源证据：v2.1.0-beta.32

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v2.1.0-beta.32
- 对用户的影响：可能阻塞安装或首次运行。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_31e3065c9e884205a29f181cbbc50458 | https://github.com/nocobase/nocobase/releases/tag/v2.1.0-beta.32 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。

## 16. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:306829688 | https://github.com/nocobase/nocobase | issue_or_pr_quality=unknown

## 17. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:306829688 | https://github.com/nocobase/nocobase | release_recency=unknown

<!-- canonical_name: nocobase/nocobase; human_manual_source: deepwiki_human_wiki -->
