### Install Frontend Dependencies Source: https://github.com/lianjiatech/bella-openapi/blob/develop/contributor-guide.md Navigate to the web directory and install frontend dependencies using npm. This is a required step before developing the frontend. ```bash cd web npm install ``` -------------------------------- ### Capacity Evaluation Example: Cold Start Source: https://github.com/lianjiatech/bella-openapi/blob/develop/docs/design/openapi-as-worker.md Shows the capacity calculation during a cold start scenario where no historical data is available, resulting in the 'fully open' strategy and 100% remaining capacity. ```text Historical 429 Fitted Capacity: 0 Historical Max Completed RPM: 0 Fallback Strategy: Fully Open Remaining Capacity: 1.0 (100%) ``` -------------------------------- ### Install Backend Dependencies Source: https://github.com/lianjiatech/bella-openapi/blob/develop/contributor-guide.md Navigate to the API directory and install backend dependencies using Maven. The -DskipTests flag is used to skip running tests during installation. ```bash cd api mvn install -DskipTests ``` -------------------------------- ### Start Bella OpenAPI Services with Docker Source: https://github.com/lianjiatech/bella-openapi/blob/develop/CLAUDE.md Use this command to start all services. Optional flags allow for rebuilding services, specifying ports, setting server domains, skipping authorization, or configuring OAuth. ```bash # Start all services with Docker ./start.sh # Start with specific configurations ./start.sh --build # Rebuild services ./start.sh --rebuild # Force rebuild without cache ./start.sh --nginx-port 8080 # Use custom port ./start.sh --server https://domain.com # Set server domain ./start.sh --skip-auth # Skip admin authorization # OAuth configuration ./start.sh --github-oauth CLIENT_ID:SECRET --google-oauth CLIENT_ID:SECRET # Stop services ./stop.sh ``` -------------------------------- ### Install Project to Local Repository Source: https://github.com/lianjiatech/bella-openapi/blob/develop/api/CLAUDE.md Installs all modules to the local Maven repository, skipping tests. ```bash mvn install -DskipTests ``` -------------------------------- ### Initialize and Start System with Data Reset Source: https://github.com/lianjiatech/bella-openapi/blob/develop/README.md Commands to initialize the system and clear existing data, suitable for development or testing environments. This involves dropping the database, stopping services, and removing data directories before rebuilding and starting. ```bash docker exec -it bella-openapi-mysql mysql -uroot -p123456 -e "drop database bella_openapi;" ``` ```bash docker-compose down ``` ```bash rm -rf ./mysql ``` ```bash rm -rf ./redis ``` ```bash ./start.sh -b ``` -------------------------------- ### Start Bella OpenAPI Services Source: https://github.com/lianjiatech/bella-openapi/blob/develop/README_EN.md Execute this script to start all services. It automatically pulls images if they don't exist locally. Additional parameters can configure OAuth login and service domains. ```bash ./start.sh ./start.sh --github-oauth CLIENT_ID:CLIENT_SECRET --google-oauth CLIENT_ID:CLIENT_SECRET --server URL (configure oauth login service and service domain through startup parameters) ``` -------------------------------- ### Develop Bella OpenAPI Frontend with Next.js Source: https://github.com/lianjiatech/bella-openapi/blob/develop/CLAUDE.md Essential commands for frontend development using Next.js. Includes starting the development server, building for production, starting the production server, and running linting. ```bash cd web/ # Development npm run dev # Start dev server (http://localhost:3000) npm run build # Build for production npm run start # Start production server npm run lint # Run linting ``` -------------------------------- ### Start Bella OpenAPI Service Source: https://github.com/lianjiatech/bella-openapi/blob/develop/README.md Use this script to start the Bella OpenAPI service. It automatically pulls the latest image if not found locally. Configuration for OAuth login and server domain can be passed as arguments. ```bash ./start.sh ``` ```bash ./start.sh --github-oauth CLIENT_ID:CLIENT_SECRET --google-oauth CLIENT_ID:CLIENT_SECRET --server URL ``` -------------------------------- ### Start Bella OpenAPI Service with Skip Auth Source: https://github.com/lianjiatech/bella-openapi/blob/develop/README.md This command starts the Bella OpenAPI service while skipping the administrator authorization process. System AK generation will still be checked. ```bash ./start.sh --skip-auth ``` -------------------------------- ### Capacity Evaluation Example: No Historical Data Source: https://github.com/lianjiatech/bella-openapi/blob/develop/docs/design/openapi-as-worker.md Demonstrates capacity calculation when historical 429 data is unavailable, relying on the fallback strategy of using 70% of the historical maximum completed RPM. ```text Historical 429 Fitted Capacity: 0 (No Data) Historical Max Completed RPM: 500 Fallback Capacity: 500 * 0.7 = 350 Current Load: 300 Remaining Capacity: 1.0 - (300/350) = 0.143 (14.3%) ``` -------------------------------- ### Rebuild and Restart Services Source: https://github.com/lianjiatech/bella-openapi/blob/develop/README_EN.md This command rebuilds the services after code modifications and then restarts them. It's part of the process for initializing and starting the system with cleared data. ```bash ./start.sh -b ``` -------------------------------- ### Clone Bella OpenAPI Repository Source: https://github.com/lianjiatech/bella-openapi/blob/develop/contributor-guide.md Clone the Bella OpenAPI repository to your local machine to start contributing. Ensure you replace YOUR-USERNAME with your GitHub username. ```bash git clone https://github.com/YOUR-USERNAME/bella-openapi.git cd bella-openapi ``` -------------------------------- ### Capacity Evaluation Example: Normal Operation Source: https://github.com/lianjiatech/bella-openapi/blob/develop/docs/design/openapi-as-worker.md Illustrates a capacity calculation scenario during normal operation, showing how current load and historical fitted capacity result in a low remaining capacity percentage. ```text Historical 429 Fitted Capacity: 400 RPM Current Concurrent Requests: 15 Current Completed RPM: 380 Current Load: 15 + 380 = 395 Remaining Capacity: 1.0 - (395/400) = 0.0125 (1.25%) ``` -------------------------------- ### Run Application Script Source: https://github.com/lianjiatech/bella-openapi/blob/develop/api/CLAUDE.md Launches the application with optimized JVM settings, including G1GC and 2GB heap. ```bash ./run.sh ``` -------------------------------- ### 配置环境变量 Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/readme.md 编辑 `.env.local` 文件来配置环境变量,包括是否使用 Mock 数据和后端 API 地址。 ```bash # 使用 Mock 数据 NEXT_PUBLIC_USE_MOCK=true # 使用真实后端时配置 BACKEND_API_URL=http://localhost:8080 # 可选:暴露给浏览器的真实后端地址 # 不填时默认走相对路径,由 rewrites 或反向代理处理 NEXT_PUBLIC_API_ORIGIN=http://localhost:8080 ``` -------------------------------- ### 使用 Mock 数据配置 Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/readme.md 在 `.env.local` 文件中设置 `NEXT_PUBLIC_USE_MOCK=true` 以启用 Mock 数据,适用于前端独立开发。 ```bash # .env.local NEXT_PUBLIC_USE_MOCK=true ``` -------------------------------- ### 复制环境变量示例文件 Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/readme.md 如果项目中没有 `.env.local` 文件,请复制示例文件以开始配置。 ```bash cp .env.example .env.local ``` -------------------------------- ### Get Model Info Source: https://github.com/lianjiatech/bella-openapi/blob/develop/api/server/src/test/resources/metadata.txt Retrieves information about a specific model. Requires the model name. ```APIDOC ## GET /v1/meta/model/info/{modelName} ### Description Retrieves information about a specific model. ### Method GET ### Endpoint /v1/meta/model/info/{modelName} ### Parameters #### Path Parameters - **modelName** (string) - Required - The name of the model to retrieve information for. ### Response #### Success Response (200) Returns the model's information including its name, owner details, properties, and features. ### Response Example ```json { "modelName": "gpt-5", "ownerType": "system", "ownerCode": "0", "ownerName": "system", "properties": "{\"max_input_context\":128000,\"max_output_context\":4096}", "features": "{\"stream\":true,\"function_call\":true,\"stream_function_call\":true,\"parallel_tool_calls\":true,\"vision\":true,\"json_format\":false}" } ``` ``` -------------------------------- ### Get Model Info Source: https://github.com/lianjiatech/bella-openapi/blob/develop/api/server/src/test/resources/metadata.txt Retrieves detailed information about a specific model, including its visibility and status. ```APIDOC ## GET /v1/meta/model/info/{modelName} ### Description Retrieves information about a specific model. ### Method GET ### Endpoint /v1/meta/model/info/{modelName} ### Parameters #### Path Parameters - **modelName** (string) - Required - The name of the model to retrieve information for. ### Response #### Success Response (200) - **modelName** (string) - The name of the model. - **visibility** (string) - The visibility status of the model (e.g., "public"). - **status** (string) - The operational status of the model (e.g., "inactive", "active"). ### Response Example ```json { "modelName": "gpt-5", "visibility": "public" } ``` ```json { "modelName": "gpt-5", "status": "inactive" } ``` ```json { "modelName": "gpt-5", "status": "active" } ``` ``` -------------------------------- ### Get API Key Page Source: https://github.com/lianjiatech/bella-openapi/blob/develop/api/server/src/test/resources/apikey.txt Retrieves a paginated list of API keys based on owner type and code. ```APIDOC ## GET /console/apikey/page ### Description Retrieves a paginated list of API keys. ### Method GET ### Endpoint /console/apikey/page ### Query Parameters - **ownerType** (string) - Required - The type of the owner. - **ownerCode** (string) - Required - The code of the owner. ### Response #### Success Response (200) Returns a list of API keys. ``` -------------------------------- ### Clean Build from Scratch Source: https://github.com/lianjiatech/bella-openapi/blob/develop/api/CLAUDE.md Performs a complete clean build, removing all previous artifacts and packaging without running tests. ```bash mvn clean package -DskipTests ``` -------------------------------- ### Build and Run Bella OpenAPI Backend Source: https://github.com/lianjiatech/bella-openapi/blob/develop/CLAUDE.md Commands for building the Java Spring Boot backend project using Maven. Includes options for compiling, packaging without tests, generating jOOQ code, and running the application locally. ```bash cd api/ # Build the project mvn clean compile mvn clean package -DskipTests # Generate jOOQ code from database mvn jooq:generate -pl server # Build script (compiles and prepares release) ./build.sh # Run locally with optimized JVM settings ./run.sh ``` -------------------------------- ### 使用真实后端 API 配置 Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/readme.md 在 `.env.local` 文件中设置 `NEXT_PUBLIC_USE_MOCK=false` 并配置 `BACKEND_API_URL` 以使用真实后端 API,适用于前后端联调或生产环境。 ```bash # .env.local NEXT_PUBLIC_USE_MOCK=false BACKEND_API_URL=http://your-backend-api.com ``` -------------------------------- ### Run All Tests Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/app/[locale]/(dashboard)/playground/chat/components/conversation/chatInput/__tests__/README.md Execute all unit tests for the project using npm. ```bash npm run test ``` -------------------------------- ### Frontend Entry Points and API Calls Source: https://github.com/lianjiatech/bella-openapi/blob/develop/docs/design/apikey-manager-design.md Diagram illustrating the frontend entry points like ManagerPage and ApiKeyAdminPage, and the API calls they make, such as getManagerApiKeys. Also shows the backend interaction flow. ```text ┌─────────────────────────────────────────────────────┐ │ 前端入口 │ │ │ │ ManagerPage(/manager) │ └─ ManagedKeysTable │ ├─ DelegatedSection(委托管理-顶层AK) │ │ → getManagerApiKeys(page, userId) │ │ → 操作:进入子AK管理页 │ └─ AssignedSection(分配给我-子AK) │ → getManagerApiKeys(page, userId, │ search, onlyChild=true) │ → 操作:重置密钥 │ │ ApiKeyAdminPage(/apikey-admin) │ └─ AdminKeysTable │ └─ 设置管理人 → ManagerDialog │ │ SubAkPage(/apikey/sub-ak/[code]?viewer=manager) │ └─ SubAkTable(fetchMode=admin) │ └─ 设置管理人 → ManagerDialog └─────────────────────────────────────────────────────┘ │ │ HTTP ▼ ┌─────────────────────────────────────────────────────┐ │ ApikeyConsoleController │ POST /console/apikey/manager/update │ GET /console/apikey/page?managerCode=... └──────────────────────┬──────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────┐ │ ApikeyService │ updateManager() fillManagerCode() │ fillPermissionCode() └──────────────────────┬──────────────────────────────┘ │ ┌────────────┼────────────┐ ▼ ▼ ▼ ┌──────────────┐ ┌──────────┐ ┌──────────────────────┐ │ ApikeyRepo │ │UserRepo │ │ AkPermissionChecker │ │ update() │ │queryById │ │ check(existing, │ │ syncManager │ │ │ │ UPDATE_MANAGER) │ │ ToChildren() │ │ │ └──────────────────────┘ └──────────────┘ └──────────┘ ``` -------------------------------- ### Build All Modules with Maven Source: https://github.com/lianjiatech/bella-openapi/blob/develop/api/CLAUDE.md Use this command to clean, compile, and build all modules in the Maven project. ```bash mvn clean compile ``` -------------------------------- ### 重启开发服务器 Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/readme.md 修改环境变量后,需要重启开发服务器才能使更改生效。 ```bash npm run dev ``` -------------------------------- ### Worker Initialization and Task Processing Flow Source: https://github.com/lianjiatech/bella-openapi/blob/develop/docs/design/openapi-as-worker.md Illustrates the main workflow of the WorkerManager, including initialization, task polling, capacity checking, and execution delegation. It highlights the role of BackoffTask, CapacityCalculator, and TaskProcessor in managing and processing tasks. ```mermaid graph TD A[BackoffTask Polling Loop] --> B{CapacityCalculator Assess Channel Capacity}; B --> C{Capacity > 70%?}; C -- Yes --> D[Batch Get Tasks takeAndRun()]; C -- No --> E[Skip This Round Backoff Wait]; D --> F[TaskProcessor Protocol Conversion + Execution]; F --> G[Handle Response Status Codes]; G -- 200: Success --> H[Record Metrics]; G -- 429/503: Retry --> H; G -- Other: Failure --> H; H -- Update Capacity (429 Errors) --> A; ``` -------------------------------- ### Run Unit Tests for ChatStore Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/lib/chat/store/chat/__tests__/README.md Commands to execute unit tests for the store.test.ts file, including options for coverage and watch mode. ```bash npm test -- store.test.ts ``` ```bash npm run test:coverage -- store.test.ts ``` ```bash npm run test:watch -- store.test.ts ``` -------------------------------- ### Build Application Script Source: https://github.com/lianjiatech/bella-openapi/blob/develop/api/CLAUDE.md Executes the build script to create release artifacts for the application. ```bash ./build.sh ``` -------------------------------- ### Multi-Block Scene Considerations Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/lib/chat/store/chat/__tests__/README.md Provides notes on handling multi-block scenarios in ChatStore, specifically regarding `startBlock` behavior and content persistence. ```markdown ⚠️ **多 block 场景** - 每次 `startBlock` 会切换 `streamingBlockId` - 前一个 block 的内容保留(不会自动 flush) ``` -------------------------------- ### Run Backend Tests with Maven Source: https://github.com/lianjiatech/bella-openapi/blob/develop/CLAUDE.md Commands to execute backend tests using Maven. Note that backend tests require a connection to the MySQL database. ```bash # Run backend tests cd api/ mvn test # Run all tests mvn test -pl server # Run server module tests only mvn test -Dtest=ChatControllerTest # Run specific test class ``` -------------------------------- ### Child API Key Creation and Manager Update Logic Source: https://github.com/lianjiatech/bella-openapi/blob/develop/docs/design/apikey-permission-design.md Illustrates the logic for creating a child API key by inheriting the manager's code and name from the parent. Also shows the process for updating a parent API key's manager, which synchronizes to all child API keys and clears relevant caches. ```java 创建子AK(createByParentCode) └─ db.setManagerCode(parent.getManagerCode()) └─ db.setManagerName(parent.getManagerName()) 更新父AK的管理人(updateManager) └─ apikeyRepo.update(db, parentCode) └─ apikeyRepo.syncManagerToChildren(parentCode, db) // 同步到所有子AK └─ clearApikeyCache(parent + all children) ``` -------------------------------- ### Run All Tests with Maven Source: https://github.com/lianjiatech/bella-openapi/blob/develop/api/CLAUDE.md Executes all unit and integration tests across the project. ```bash mvn test ``` -------------------------------- ### Test Command: Run ChatInput Tests Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/app/[locale]/(dashboard)/playground/chat/components/conversation/chatInput/__tests__/TEST_RESULTS.md Command to specifically run tests for the ChatInput component. ```bash npm test chatInput/__tests__ ``` -------------------------------- ### Test Command: Run All Tests Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/app/[locale]/(dashboard)/playground/chat/components/conversation/chatInput/__tests__/TEST_RESULTS.md Command to execute all tests within the project using npm. ```bash npm test ``` -------------------------------- ### Watch Mode for Development Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/app/[locale]/(dashboard)/playground/chat/components/conversation/chatInput/__tests__/README.md Run tests in watch mode for continuous feedback during development. ```bash npm run test -- --watch ``` -------------------------------- ### Run jOOQ Code Generation with Maven Source: https://github.com/lianjiatech/bella-openapi/blob/develop/CLAUDE.md Execute jOOQ code generation from the database schema using Maven. This command should be run from the 'api/' directory. ```bash cd api/ mvn jooq:generate -pl server ``` -------------------------------- ### API Key Pagination Service Logic Source: https://github.com/lianjiatech/bella-openapi/blob/develop/docs/design/apikey-manager-design.md Illustrates the service logic for paginating API keys, including permission code filling and manager code filling. It details how different user roles and query parameters affect the results, especially concerning manager code validation and search capabilities. ```go pageApikey(condition) │ ├─ fillPermissionCode() │ └─ 普通用户 + 传了 managerCode │ → 不叠加 personalCode(否则无法查到他人/组织的AK) │ └─ fillManagerCode() ├─ SYSTEM 类型 AK → 不受限 ├─ 管理员(console/all)→ 不受限,支持 managerSearch 模糊查询 └─ 普通用户 ├─ managerCode 必须等于自己的 userId └─ 禁止使用 managerSearch(防止遍历他人管理关系) ``` -------------------------------- ### Mock Tools Used in Testing Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/app/[locale]/(dashboard)/playground/chat/components/conversation/chatInput/__tests__/TEST_RESULTS.md Description of mock tools employed for testing, including FileReader, File, and ChatInputController mocks. ```text - **FileReader Mock**: 模拟文件读取和 base64 转换 - **File Mock**: 创建各种大小和类型的测试文件 - **Controller Mock**: 模拟 ChatInputController 状态 ``` -------------------------------- ### Package Application without Tests Source: https://github.com/lianjiatech/bella-openapi/blob/develop/api/CLAUDE.md Creates a package artifact (e.g., JAR) for the application while skipping the test execution phase. ```bash mvn package -DskipTests ``` -------------------------------- ### Create API Key (v1) Source: https://github.com/lianjiatech/bella-openapi/blob/develop/api/server/src/test/resources/apikey.txt Creates a new API key with specified parameters, including parent code, entity code, safety level, role, and quota. ```APIDOC ## POST /v1/apikey/create ### Description Creates a new API key. ### Method POST ### Endpoint /v1/apikey/create ### Request Body - **parentCode** (string) - Required - The code of the parent entity. - **outEntityCode** (string) - Required - The code of the external entity. - **safetyLevel** (integer) - Required - The safety level for the API key. - **roleCode** (string) - Optional - The role code to assign. - **monthQuota** (integer) - Optional - The monthly quota for the API key. - **paths** (array of strings) - Optional - A list of paths the API key can access. ### Request Example ```json { "parentCode": "%{81-data-0-code}%", "outEntityCode": "10009999", "safetyLevel": 0, "roleCode": "low", "monthQuota": 0 } ``` ### Response #### Success Response (200) Indicates the API key creation was successful. ``` -------------------------------- ### Generate Coverage Report Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/app/[locale]/(dashboard)/playground/chat/components/conversation/chatInput/__tests__/README.md Generate a test coverage report for the project. ```bash npm run test -- --coverage ``` -------------------------------- ### Create a New Feature Branch Source: https://github.com/lianjiatech/bella-openapi/blob/develop/contributor-guide.md Create a new Git branch for your feature development. Replace 'your-feature-name' with a descriptive name for your branch. ```bash git checkout -b feature/your-feature-name ``` -------------------------------- ### Optional Optimization Suggestions Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/app/[locale]/(dashboard)/playground/chat/components/conversation/chatInput/__tests__/TEST_RESULTS.md Suggestions for optional improvements to the testing strategy, including adding E2E, performance, and accessibility tests. ```text 1. 增加 E2E 测试验证真实文件上传 2. 添加性能测试 (大文件处理时间) 3. 增加可访问性测试 (a11y) ``` -------------------------------- ### Commit Changes Source: https://github.com/lianjiatech/bella-openapi/blob/develop/contributor-guide_EN.md Stage and commit your code changes. Use a concise and descriptive commit message. ```bash git commit -m "describe your changes" ``` -------------------------------- ### 在 API 路由中使用 Mock 数据 Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/readme.md 在 API 路由中,根据 `NEXT_PUBLIC_USE_MOCK` 环境变量的值来决定是返回 Mock 数据还是调用真实 API。 ```typescript // src/app/api/v1/example/route.ts import { NextResponse } from 'next/server'; import exampleData from '@/mocks/data/example.json'; export async function GET() { const useMock = process.env.NEXT_PUBLIC_USE_MOCK === 'true'; if (useMock) { return NextResponse.json({ code: 200, data: exampleData, message: null, timestamp: Date.now(), }); } // 真实 API 调用逻辑 // ... } ``` -------------------------------- ### Run Tests for Specific Module with Maven Source: https://github.com/lianjiatech/bella-openapi/blob/develop/api/CLAUDE.md Focuses test execution on a particular module like 'server', 'sdk', or 'spi'. ```bash mvn test -pl server ``` ```bash mvn test -pl sdk ``` ```bash mvn test -pl spi ``` -------------------------------- ### Activate API Key Source: https://github.com/lianjiatech/bella-openapi/blob/develop/api/server/src/test/resources/apikey.txt Activates an existing API key. ```APIDOC ## POST /console/apikey/activate ### Description Activates an existing API key. ### Method POST ### Endpoint /console/apikey/activate ### Request Body - **code** (string) - Required - The unique code of the API key to activate. ### Request Example ```json { "code": "%{6-data-0-code}%" } ``` ### Response #### Success Response (200) Indicates the API key activation was successful. ``` -------------------------------- ### View Test Output Verbose Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/app/[locale]/(dashboard)/playground/chat/components/conversation/chatInput/__tests__/README.md Run tests with verbose output to see detailed logs. ```bash npm run test -- --verbose ``` -------------------------------- ### Apply for API Key Source: https://github.com/lianjiatech/bella-openapi/blob/develop/api/server/src/test/resources/apikey.txt Allows a user to apply for a new API key. Requires owner details. ```APIDOC ## POST /console/apikey/apply ### Description Applies for a new API key with specified owner details. ### Method POST ### Endpoint /console/apikey/apply ### Request Body - **ownerType** (string) - Required - Type of owner. - **ownerCode** (string) - Required - Unique code for the owner. - **ownerName** (string) - Required - Name of the owner. - **role_code** (string) - Optional - The role code to assign to the API key. ### Request Example ```json { "ownerType": "person", "ownerCode": "10000000", "ownerName": "test" } ``` ### Response #### Success Response (200) Indicates the API key application was successful. ``` -------------------------------- ### Data Transformation Test Cases Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/app/[locale]/(dashboard)/playground/chat/components/conversation/chatInput/__tests__/TEST_RESULTS.md Test cases for data transformation logic, focusing on converting strings and media files into the ContentPart[] format. ```text | # | 测试用例 | 状态 | 耗时 | |---|---------|------|------| | 1 | 空字符串 + 图片 → [image_url] | ✅ | 184ms | | 2 | 文本 + 图片 → [text, image_url] | ✅ | 79ms | | 3 | 纯空格文本 + 图片 → [image_url] | ✅ | 73ms | | 4 | 已有数组 + 图片 → 追加到数组 | ✅ | 76ms | | 5 | 连续上传多个文件 | ✅ | 150ms | | 6 | 文本 + 图片 + 视频混合场景 | ✅ | 239ms | | 7 | 空数组 + 图片 | ✅ | 69ms | ``` -------------------------------- ### Run Tests with Specific Profile Source: https://github.com/lianjiatech/bella-openapi/blob/develop/api/CLAUDE.md Executes tests using a specific Spring profile, such as 'ut' for unit testing. ```bash mvn test -Dspring.profiles.active=ut ``` -------------------------------- ### Testing Strategy Overview Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/app/[locale]/(dashboard)/playground/chat/components/conversation/chatInput/__tests__/TEST_RESULTS.md Outline of the testing strategy, encompassing unit tests, integration tests, and boundary tests for comprehensive coverage. ```text - **单元测试**: 独立函数和逻辑 - **集成测试**: 组件整体行为 - **边界测试**: 文件过大、类型错误、空输入 ``` -------------------------------- ### Mocking nanoid for Predictable IDs Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/lib/chat/store/chat/__tests__/README.md Demonstrates how to mock the 'nanoid' library to generate predictable IDs during testing, facilitating assertions and debugging. ```typescript nanoid: Mock为固定ID生成器 `mock-id-{counter}` 便于断言和调试 ``` -------------------------------- ### ChatStore Three-Layer Buffering Mechanism Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/lib/chat/store/chat/__tests__/README.md Explains the roles and behaviors of the three buffering layers in ChatStore: typingBuffer for UI, segmentBuffer for aggregation, and segments for persistence. ```markdown 1. **typingBuffer** 🥉 - 用途:UI 打字机效果 - 行为:持续累积,不受 flush 影响 - 清空时机:finishStreaming 2. **segmentBuffer** 🥈 - 用途:聚合 token,减少写入频率 - 行为:达到 2KB 自动 flush - 清空时机:flush 或 finishStreaming 3. **segments** 🥇 - 用途:持久化存储 - 行为:低频写入(每 2KB 一次) - 内容:已固化的文本段数组 ``` -------------------------------- ### Run Specific Test File Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/app/[locale]/(dashboard)/playground/chat/components/conversation/chatInput/__tests__/README.md Execute tests for a specific file, such as file upload functionality. ```bash # 文件上传功能测试 npm run test fileUpload.test.tsx # 数据转换逻辑测试 npm run test dataTransform.test.tsx # 组件集成测试 npm run test index.test.tsx ``` -------------------------------- ### Buffer Flush Logic Caveats Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/lib/chat/store/chat/__tests__/README.md Highlights important considerations for the buffer flush logic, including handling of large single writes versus cumulative writes. ```markdown ⚠️ **buffer flush 逻辑** - 一次性追加 > 2KB 的内容会全部 flush - 累积追加达到阈值才触发 flush ``` -------------------------------- ### Delete MySQL Database Source: https://github.com/lianjiatech/bella-openapi/blob/develop/README_EN.md Command to drop the Bella OpenAPI database in MySQL. Ensure you replace the username and password if they differ from the defaults. ```bash docker exec -it bella-openapi-mysql mysql -uroot -p123456 -e "drop database bella_openapi;" ``` -------------------------------- ### ChatStore finishStreaming Behavior Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/lib/chat/store/chat/__tests__/README.md Details how `finishStreaming` operates, focusing on its handling of the current streaming block versus preceding blocks. ```markdown 只处理当前流式的 block(最后一个),前面的 blocks 内容保留在原有状态: - 最后一个 block:flush + 清空 typingBuffer - 之前的 blocks:保持原状 这是合理的设计,因为流式场景下只有最后一个 block 是"正在输入"的。 ``` -------------------------------- ### Asynchronous Handling in Tests Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/app/[locale]/(dashboard)/playground/chat/components/conversation/chatInput/__tests__/TEST_RESULTS.md Explanation of how asynchronous operations, such as file reading and validation, are handled during testing using utilities like `waitFor()` and `setTimeout`. ```text - 使用 `waitFor()` 等待异步操作 - 使用 `setTimeout` 等待文件验证 - 使用 Mock FileReader 控制异步流程 ``` -------------------------------- ### Create Endpoint Source: https://github.com/lianjiatech/bella-openapi/blob/develop/api/server/src/test/resources/metadata.txt Registers a new endpoint with the system. Requires endpoint details and a name. ```APIDOC ## POST /console/endpoint ### Description Registers a new endpoint with the system. ### Method POST ### Endpoint /console/endpoint ### Request Body - **endpoint** (string) - Required - The full path of the endpoint. - **endpointName** (string) - Required - A unique name for the endpoint. - **maintainerCode** (string) - Optional - The code of the maintainer. - **maintainerName** (string) - Optional - The name of the maintainer. ### Request Example ```json { "endpoint": "/v1/chat/completions", "endpointName": "test", "maintainerCode": "0", "maintainerName": "system" } ``` ### Response #### Success Response (200) Returns a success message if the endpoint is registered. #### Error Response (400) Returns an error message if the input is invalid or the endpoint already exists. ``` -------------------------------- ### Capacity Calculation Algorithm Source: https://github.com/lianjiatech/bella-openapi/blob/develop/docs/design/openapi-as-worker.md Presents the core formula for calculating remaining channel capacity, which considers current load (concurrent requests + completed RPM) against total capacity derived from historical data or performance estimates. ```text Remaining Capacity = 1.0 - (Current Load / Total Capacity) Where: - Current Load = Current Concurrent Requests + Current Completed RPM - Total Capacity = Historical 429 Fitted Capacity OR Current Max RPM * 0.7 OR Fully Open ``` -------------------------------- ### Correct State Reading from Zustand Store Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/lib/chat/store/chat/__tests__/README.md Illustrates the correct pattern for reading state from a Zustand store by calling `getState()` after actions to ensure the latest state is accessed. ```typescript // ✅ 正确:调用后重新获取状态 useChatStore.getState().startAssistantMessage() const state = useChatStore.getState() const messageId = state.streamingMessageId ``` ```typescript // ❌ 错误:状态可能过期 const store = useChatStore.getState() store.startAssistantMessage() console.log(store.streamingMessageId) // 可能是旧值 ``` -------------------------------- ### API Key Service and Permission Checker Interaction Source: https://github.com/lianjiatech/bella-openapi/blob/develop/docs/design/apikey-permission-design.md Illustrates the interaction between `ApikeyService` and `AkPermissionChecker`. The service calls permission checks, which are then resolved by the checker, potentially involving role matrix lookups and repository queries for parent API key data. ```java ┌─────────────────────────────────────────────┐ │ ApikeyService │ │ checkPermission(code, AkOperation.RESET) │ │ checkPermission(code, AkOperation.TRANSFER) │ │ ...(各方法只传操作类型,不含权限逻辑) │ └─────────────────────┬───────────────────────┘ │ ▼ ┌─────────────────────────────────────────────┐ │ AkPermissionChecker │ │ check(ApikeyDB, AkOperation) │ │ - checkOperatorPermission() (无AK分支) │ │ - resolveRelation() (有AK分支) │ │ - parentCode 追溯 (子AK场景) │ └──────────┬──────────────────────────────────┘ │ │ ▼ ▼ ┌──────────────────┐ ┌──────────────────────┐ │ AkPermissionMatrix│ │ ApikeyRepo │ │ isAllowed( │ │ queryByUniqueKey() │ │ roleCode, │ │ (父AK追溯时查询) │ │ relation, │ └──────────────────────┘ │ operation) │ └──────────────────┘ ``` -------------------------------- ### Component Integration Test Cases Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/app/[locale]/(dashboard)/playground/chat/components/conversation/chatInput/__tests__/TEST_RESULTS.md Details of integration tests for the ChatInput component, covering rendering, content logic, upload compatibility, sending functionality, streaming state, and disabled state. ```text #### 组件渲染 (3 个用例) - ✅ 组件正常渲染 - ✅ 下拉菜单包含上传选项 - ✅ 隐藏的 file input 存在 #### 内容判断逻辑 (5 个用例) - ✅ 空字符串 → hasContent = false - ✅ 纯空格 → hasContent = false - ✅ 有效文本 → hasContent = true - ✅ 空数组 → hasContent = false - ✅ 有内容的数组 → hasContent = true #### 上传与输入兼容性 (3 个用例) - ✅ 上传图片后不影响 Textarea - ✅ value 为数组时 Textarea 显示为空 - ✅ 输入文本调用 setValue #### 发送功能 (4 个用例) - ✅ 上传文件后发送按钮启用 - ✅ 点击发送按钮调用 send() - ✅ Enter 键触发发送 - ✅ Shift+Enter 不触发发送 #### Streaming 状态 (2 个用例) - ✅ streaming 状态显示停止按钮 - ✅ 点击停止按钮调用 abort() #### 禁用状态 (1 个用例) - ✅ connecting 状态禁用 Textarea ``` -------------------------------- ### Create Model Source: https://github.com/lianjiatech/bella-openapi/blob/develop/api/server/src/test/resources/metadata.txt Registers a new model with associated endpoints. Requires model name and a list of endpoints. ```APIDOC ## POST /console/model ### Description Registers a new model with associated endpoints. ### Method POST ### Endpoint /console/model ### Request Body - **modelName** (string) - Required - The name of the model. - **endpoints** (array of strings) - Required - A list of endpoint paths associated with the model. - **ownerType** (string) - Optional - The type of owner. - **ownerCode** (string) - Optional - The code of the owner. - **ownerName** (string) - Optional - The name of the owner. - **documentUrl** (string) - Optional - URL to the model's documentation. - **properties** (string) - Optional - JSON string representing model properties. - **features** (string) - Optional - JSON string representing model features. ### Request Example ```json { "modelName": "gpt-5", "endpoints": [ "/v1/chat/completions" ], "ownerType": "system", "ownerCode": "0", "ownerName": "system", "documentUrl": null, "properties": "{\"max_input_context\":128000,\"max_output_context\":4096}", "features": "{\"stream\":true,\"function_call\":true,\"stream_function_call\":true,\"parallel_tool_calls\":true,\"vision\":true,\"json_format\":false}" } ``` ### Response #### Success Response (200) Returns a success message if the model is registered. #### Error Response (400) Returns an error message if the input is invalid or the model name already exists with conflicting endpoints. ``` -------------------------------- ### Core Features Tested Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/app/[locale]/(dashboard)/playground/chat/components/conversation/chatInput/__tests__/TEST_RESULTS.md List of core functionalities covered by the tests, including file uploads, format conversions, and validation. ```text 1. 图片上传并转换为 base64 2. 视频上传并转换为 base64 3. 文件类型验证 4. 文件大小限制 5. 数据格式转换 ``` -------------------------------- ### Create Channel Source: https://github.com/lianjiatech/bella-openapi/blob/develop/api/server/src/test/resources/metadata.txt This endpoint is used to create a new channel for a model. It requires specific channel information and pricing details. ```APIDOC ## POST /console/channel ### Description Creates a new channel for a model with specified configuration. ### Method POST ### Endpoint /console/channel ### Request Body - **entityType** (string) - Required - Type of the entity (e.g., "model") - **entityCode** (string) - Required - Unique code for the entity - **dataDestination** (string) - Required - Destination for the data - **priority** (string) - Required - Priority level - **protocol** (string) - Required - Communication protocol - **supplier** (string) - Required - The supplier of the model - **url** (string) - Optional - URL for the model endpoint - **channelInfo** (string) - Optional - JSON string containing channel deployment details - **priceInfo** (string) - Optional - JSON string containing pricing information ### Request Example ```json { "entityType": "model", "entityCode": "gpt-5-111", "dataDestination": "overseas", "priority": "high", "protocol": "OpenAIAdaptor", "supplier": "Azure", "url": null, "channelInfo": "{\"deployName\":\"GPT-4o-PTU\",\"version\":\"0513\",\"apiKey\":\"123458789\",\"apiVersion\":\"2024-02-15-preview\"}", "priceInfo": "{\"input\":21.0,\"output\":1.0}" } ``` ### Response #### Success Response (200) Indicates successful channel creation. #### Error Response (400) Indicates a bad request, likely due to invalid input data. ``` -------------------------------- ### Child API Key Permission Traceability Logic Source: https://github.com/lianjiatech/bella-openapi/blob/develop/docs/design/apikey-permission-design.md Explains the scenario where a child API key's manager is changed, and how permissions are correctly traced by checking the parent API key if the direct relationship is insufficient. This ensures that owners/managers of parent API keys retain equivalent permissions for all their child API keys. ```java 场景:manager 将子AK的管理人改为他人 → 子AK.managerCode 不再是 manager 自己 → 直接校验子AK → UNRELATED → 拒绝(错误) 正确做法: → 直接校验子AK → UNRELATED → 查父AK,manager 是父AK的 MANAGER → 继承父AK的 MANAGER 权限 → 放行(正确) ``` -------------------------------- ### File Upload Test Cases Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/app/[locale]/(dashboard)/playground/chat/components/conversation/chatInput/__tests__/TEST_RESULTS.md Details of test cases for the file upload functionality, covering image and video uploads, format conversion, and validation. ```text | # | 测试用例 | 状态 | 耗时 | |---|---------|------|------| | 1 | 点击"添加图片"按钮应该打开文件选择对话框 | ✅ | 199ms | | 2 | 点击"添加视频"按钮应该打开文件选择对话框 | ✅ | 43ms | | 3 | 上传图片后应该转换为 base64 格式 | ✅ | 76ms | | 4 | 上传视频后应该转换为 base64 格式 | ✅ | 170ms | | 5 | 文件类型验证 - 拒绝不支持的格式 | ✅ | 6ms | | 6 | 文件大小验证 - 图片超过 10MB | ✅ | 457ms | | 7 | 文件大小验证 - 视频超过 50MB | ✅ | 1413ms | | 8 | 上传后 input.value 应该被重置 | ✅ | 69ms | | 9 | 取消文件选择不应该触发 setValue | ✅ | 6ms | ``` -------------------------------- ### Redis Keys for Real-time Metrics Source: https://github.com/lianjiatech/bella-openapi/blob/develop/docs/design/openapi-as-worker.md Defines the Redis keys for tracking real-time performance metrics such as completed requests per minute (RPM) and current concurrent requests. ```text bella-openapi-channel-metrics:{channelCode}:total.completed ``` ```text bella-openapi-channel-concurrent:{entityCode} ``` -------------------------------- ### Test Command: Generate Coverage Report Source: https://github.com/lianjiatech/bella-openapi/blob/develop/web_v2/src/app/[locale]/(dashboard)/playground/chat/components/conversation/chatInput/__tests__/TEST_RESULTS.md Command to generate a code coverage report using npm test with the --coverage flag. ```bash npm test -- --coverage ```