* refactor tests
* ♻️ refactor(test): improve test layering and fix type errors
Improved test architecture by fixing test layer violations:
1. **internal_coreProcessMessage tests**: Changed to spy on direct dependency `internal_fetchAIChatMessage` instead of lower-level `chatService.createAssistantMessageStream`
2. **internal_fetchAIChatMessage tests**: Fixed to mock correct service (`chatService` instead of global `fetch`)
3. **beforeEach cleanup**: Removed global `spyOnChatService()` to reduce implicit coupling - tests now spy `chatService` only when needed
4. **Type fixes**:
- Fixed mockResolvedValue() to include required undefined arguments
- Fixed ChatMessageError type to include required `type` property
- Fixed MessageDispatch type guard for safer property access
Benefits:
✅ Clear test layers - each test only spies on direct dependencies
✅ Correct mocks matching actual implementation
✅ Coverage improved from 81.48% to 82.03%
✅ All 52 tests passing with no type errors
* ♻️ refactor: rename isLocalUrl to isDesktopLocalStaticServerUrl
Rename the function to better reflect its specific purpose of checking
desktop local static server URLs (127.0.0.1 only). Update all usages
across the codebase including imports, function calls, and test cases.
* ✨ feat(model-bank): add Vertex AI image generation models
- Add Nano Banana (Gemini 2.5 Flash Image) models
- Add Imagen 4 series (Standard, Ultra, Fast, Preview variants)
- Export shared parameters for reuse across providers
* ✅ test(context-engine): fix mock after function rename
Update test mock from isLocalUrl to isDesktopLocalStaticServerUrl
* ♻️ refactor: use submodule imports for @lobechat/utils
- Change from barrel imports to direct submodule imports
- Update test to mock only necessary functions (imageUrlToBase64)
- Fix test URL from localhost to 127.0.0.1 for isDesktopLocalStaticServerUrl
- Update package.json exports for utils submodules
* ✅ test: update mocks after function rename
Update test mocks from isLocalUrl to isDesktopLocalStaticServerUrl
* ✅ test(chat): fix mocks to use submodule imports
- Add special case for VertexAI in getProviderAuthPayload to skip random API key selection
- Vertex AI uses JSON format credentials that contain commas, which should not be split
- Add test case to verify JSON credentials remain intact
Fixes the issue introduced in #9477 where random API key splitting broke Vertex AI authentication
🤖 Generated with [Claude Code](https://claude.com/claude-code)
When the origin of the Worker script is different from the current page, reconstruct the URL relative to the current origin to avoid cross-origin errors.
🐛 fix(ci): Improve Claude translator prompt to prevent hallucination
Add critical rules to prevent translation hallucination issues:
- Enforce exact preservation of original content without modification
- Ensure code blocks, error logs, and JSON appear in both sections
- Clarify that only natural language should be translated
- Add verification step to check original content accuracy
- Prevent dropping or hallucinating end-of-comment sentences
This addresses issues where the translator was hallucinating content
in the "Original Content" section and incorrectly handling large
technical blocks like error logs and JSON structures.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude <noreply@anthropic.com>
* fix: update models and refactor InfiniAI model handling
* fix: enable models and update InfiniAI configuration
* fix: update DeepSeek model versions and descriptions in modelscope
* 🐛 fix: add searchKeywords support and imageOutput match to model parsing logic
* 🐛 fix: add imageOutputKeywords support to model parsing logic
* 🐛 fix: test
* 🐛 fix: enhance model parsing to support local enabled
* 🐛 fix: refine model parsing by removing unnecessary properties from image models
* 💄 style: update form items to support search and imageOutput abilities
* 🐛 fix: improve model parsing logic to conditionally display search options for Perplexity and Jina
* 🐛 fix: parsing imageOutput model will get other abilities
* style: add model search setting when search ability = true and remove when false
* 🐛 fix: prevent 'internal' search models use fcSearch
* 🐛 fix: update search mode handling for internal models in Controls component
* 🐛 fix: test
* 🐛 fix: refine model parsing by updating keyword matching and removing redundant checks
* 🐛 fix: enhance model search configuration by incorporating internal model checks
* 🐛 fix: streamline settings cleanup by using destructuring to remove unused properties
* 💄 style: add video support to model configuration and parsing
* fix(bedrock): add parameter conflict handling for Claude 4+ models
- Add logic to prevent sending both temperature and top_p for Claude 4+ models
- Matches existing implementation in Anthropic provider
- Fixes ValidationException error for Claude 4.5 models via Bedrock
- Includes support for both standard and Bedrock-specific model IDs
Fixes#9523🤖 Generated with [Claude Code](https://claude.ai/code)
Co-authored-by: Arvin Xu <arvinxx@users.noreply.github.com>
* 🧪 test(bedrock): add parameter conflict handling tests
Add comprehensive tests for Claude 4+ models parameter conflict detection:
- Test temperature preference over top_p when both provided
- Test top_p usage when temperature not provided
- Test both parameters allowed for non-Claude-4+ models
- Test standard and Bedrock-specific model ID formats
- Test US region model IDs
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-authored-by: Arvin Xu <arvinxx@users.noreply.github.com>
* 🔧 fix: make temperature optional in ChatStreamPayload interface
The temperature property should be optional to support test cases and scenarios where only top_p is provided. This resolves TypeScript error TS2741 in Bedrock provider tests.
Co-authored-by: Arvin Xu <arvinxx@users.noreply.github.com>
* 🔧 fix: correct test assertions to handle JSON.stringify undefined omission
- Remove undefined properties from test expectations since JSON.stringify omits them
- Fix temperature/top_p conflict test assertions for Claude 4+ models
- Ensure tests match actual JSON serialization behavior
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-authored-by: Arvin Xu <arvinxx@users.noreply.github.com>
* 🔧 fix: add null safety checks for optional temperature parameter
- Added proper undefined checks before temperature arithmetic operations in anthropic and bedrock providers
- Added null checks before temperature comparisons in groq, perplexity, and search1api providers
- Resolves TS18048 errors where temperature is possibly undefined
- Maintains existing logic while satisfying TypeScript strict null checks
Co-authored-by: Arvin Xu <arvinxx@users.noreply.github.com>
* refactor with parameterResolver
* upgrade
* upgrade swr
* refactor context-builder
---------
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: Arvin Xu <arvinxx@users.noreply.github.com>
- Update Search component to handle different search keywords based on current tab (MCP vs Plugin)
- Add missing useEffect in Plugin List to reset list when search keywords change
- Fixes issue where typing in search bar didn't trigger plugin filtering
Fixes#9645
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: Shinji-Li <ONLY-yours@users.noreply.github.com>
* 🐛 fix(zhipu): update maxOutput and contextWindowTokens for various models
* ✨ feat(hotkeys): add delete last message and delete & regenerate message hotkeys
- Distinguish between global (src/features/) and page-specific features
- Update code example to show page-specific pattern
- Add explanatory note on when to use each pattern
Fixes#9585
- Update folder-structure.mdx and zh-CN version to reflect current Next.js 13+ App Router architecture
- Replace outdated simple desktop/mobile structure with actual complex structure
- Add documentation for (backend), [variants], @modal, and desktop route groups
- Include API architecture explanation with tRPC and REST endpoints
- Document platform organization and deployment targets
Fixes#9522🤖 Generated with [Claude Code](https://claude.ai/code)
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: Arvin Xu <arvinxx@users.noreply.github.com>
* 🐛 fix(database): prevent empty array insertion in aiModel batch operations
- Add validation to batchUpdateAiModels to return early if models array is empty
- Add validation to batchToggleAiModels to return early if models array is empty
- Add validation to updateModelsOrder to return early if sortMap array is empty
- Fixes 'values() must be called with at least one value' error when OpenRouter returns empty model list
Fixes#9429
Co-authored-by: Arvin Xu <arvinxx@users.noreply.github.com>
* ✅ test(database): add tests for empty array validation in aiModel batch operations
- Add test for batchUpdateAiModels with empty array returning empty result
- Add test for batchToggleAiModels with empty array returning early
- Add test for updateModelsOrder with empty sortMap returning early
These tests verify the fix for issue #9429 where empty arrays caused
"values() must be called with at least one value" database errors.
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-authored-by: Arvin Xu <arvinxx@users.noreply.github.com>
* 🐛 fix(test): remove invalid sort property access in aiModel test
- Remove test assertion accessing sort property on AiProviderModelListItem
- AiProviderModelListItem interface doesn't include sort property
- Fix TypeScript error: Property 'sort' does not exist on type 'AiProviderModelListItem'
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-authored-by: Arvin Xu <arvinxx@users.noreply.github.com>
* ♻️ refactor(database): extract shared validation helper for empty arrays
- Add private isEmptyArray() helper method to AiModelModel class
- Replace duplicate empty array checks in batch methods with shared helper
- Improve code maintainability and reduce duplication
- Address Sourcery AI feedback for better code organization
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-authored-by: Arvin Xu <arvinxx@users.noreply.github.com>
* 🐛 fix(database): respect enabled parameter in aiModel create method
The create method was forcing enabled: true regardless of input.
This fix allows explicit enabled: false while maintaining true as default.
Fixes failing test: batchToggleAiModels empty array validation.
Co-authored-by: Arvin Xu <arvinxx@users.noreply.github.com>
---------
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: Arvin Xu <arvinxx@users.noreply.github.com>
* ✨ feat: enhance EdgeConfig with per-user feature flags support
- Add EdgeConfigKeys constants for better maintainability
- Add getFeatureFlags() and getFlagByKey() methods to EdgeConfig
- Enhance isEnabled() with debugging console logs
- Implement per-user feature flag evaluation logic
- Add EdgeConfig integration for feature flags with env var fallback
- Support feature flags as boolean or array of user IDs
- Export IFeatureFlagsState type for type safety
* update log
* refactor
* refactor schema
---------
Co-authored-by: arvinxx <arvinx@foxmail.com>
* ✨ feat: add frontend random API key selection support
- Implement ClientApiKeyManager for random selection from comma-separated keys
- Update getProviderAuthPayload to use random key picking for all providers
- Add comprehensive tests for the new functionality
- Mirror existing server-side implementation for consistency
Closes#9255🤖 Generated with [Claude Code](https://claude.ai/code)
Co-authored-by: LobeHub Bot <lobehubbot@users.noreply.github.com>
* fix tests
* fix implement
* fix test
* fix test
* 🔧 fix: resolve missing imageurls convertion
* ✅ test: add comprehensive tests for qwen-image-edit imageUrls conversion
- Add tests for imageUrls array to imageUrl conversion
- Add tests for multiple elements using first element
- Add tests for empty array error handling
- Add tests for imageUrl priority over imageUrls
- Add tests for missing parameters error handling
- All 20 test cases pass (5 new + 15 existing)
---------
Co-authored-by: Arvin Xu <arvinx@foxmail.com>
This fixes the missing API URL configuration field in the NEW API provider settings UI.
The showEndpoint logic requires either proxyUrl or isCustom to be true for the
configuration field to be displayed. Since NEW API is a built-in provider
(not custom), it needs the proxyUrl field defined in its configuration.
This enables users to configure the API endpoint through the UI as originally
intended, while maintaining compatibility with existing NEWAPI_PROXY_URL
environment variable configuration.
Closes#9420
* ✨ feat(config): add assetPrefix to nextConfig for environment variable support
* ✨ feat(docs): add NEXT_PUBLIC_ASSET_PREFIX environment variable for CDN support
* fix
* fix non stream
* ✅ test: add comprehensive unit tests for nonStreamToStream functions
- Add tests for transformResponseToStream covering ChatCompletion conversion, reasoning content, tool calls, and edge cases
- Add tests for transformResponseAPIToStream covering Response API conversion, missing outputs, and error cases
- Tests verify complete event arrays as requested, not partial verification
- Tests will help expose issues with tool call handling and Response API compatibility
Co-authored-by: Arvin Xu <arvinxx@users.noreply.github.com>
* 🧪 test: fix nonStreamToStream test array comparisons and TypeScript errors
- Change test assertions to use array comparisons instead of individual equals
- Add missing refusal property to ChatCompletionMessage objects
- Fix Response API object types and add missing usage properties
- Resolve all TypeScript build errors in test file
Co-authored-by: Arvin Xu <arvinxx@users.noreply.github.com>
* fix
* fix tests
* Refactor VercelAIGateway integration: Enhance model card structure and error handling
* ✨ feat(vercelaigateway): Update model card structure and change check model to GPT-5
* ✨ feat(vercelaigateway): 添加模型设置以支持推理努力和文本详细程度参数
* update
fix tools
Update route.ts
Update next dependency version to ^15.5.0
更新 package.json
test prebuild type-check
try
* Change 'next' dependency version in package.json
Updated 'next' dependency version from ^15.5.3 to ~15.3.5.
* ✨ feat: Add scroll support for pinned assistants using ScrollShadow
- Import ScrollShadow component from @lobehub/ui
- Wrap pinned assistants list with ScrollShadow for vertical scrolling
- Remove 9-item limitation to show all pinned assistants
- Maintain hotkey support for first 9 items
- Add proper styling and padding for consistent layout
Fixes#9316
Co-authored-by: Shinji-Li <ONLY-yours@users.noreply.github.com>
* fix: add some style
---------
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: Shinji-Li <ONLY-yours@users.noreply.github.com>
* 🐛 fix: add qwen provider support for image-edit model
- Register qwen provider in baseRuntimeMap
- Add qwen routing support in NewAPI provider
- Implement qwen-image-edit model with correct multimodal API
- Fix API endpoint and request format for image-to-image generation
Fixes#9184
* Update packages/model-runtime/src/providers/qwen/createImage.ts
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* 🐛 fix: add usage data to chat completion chunk for stream = false
* 🐛 fix: ensure reasoning_content is included in chat completion chunks for non-stream responses
* 🐛 fix: include reasoning content and usage data in non-streaming chat completion responses
* 🐛 fix: test
* 🐛 fix: non stream Deeply Thought stop correctly
* 🐛 fix: test
* 🐛 fix: test
* ✨ feat: Enhance Search Action with mobile support and update agent chat config
* ✨ feat: Update History component to support mobile interactions and enhance Controls with form handling
♻️ refactor: consolidate image generation docs with server database setup
- Merge image-generation-setup content into work-with-server-side-database docs
- Remove duplicate image-generation-setup documentation files
- Add server-side database links to setup-development guides
- Add missing .env.development copy step to setup instructions
- Add .env.development to .gitignore for security
The setup script approach has been replaced by Docker Compose configuration
with .env.example.development file, eliminating documentation duplication
and providing a unified server-side development workflow.
✨ feat: enhance NewAPI with environment variables and fix routers compatibility
- Add NEWAPI_API_KEY and NEWAPI_PROXY_URL environment variable support
- Update documentation for NewAPI configuration options
- Fix routers baseURL handling to prevent duplicate version paths
- Remove /v1 baseURL requirement to avoid SDK compatibility issues
- Auto-detect model capabilities based on provider detection
- Support dynamic routing to correct provider endpoints
This resolves URL duplication issues like /v1beta/v1beta/ and ensures
proper routing to Anthropic, Google, OpenAI, and XAI endpoints.
- You are a senior full-stack engineer skilled in performance optimization, security, and design systems.
- You excel at reviewing code and providing constructive feedback.
- Your task is to review submitted Git diffs **in Chinese** and return a structured review report.
- Review style: concise, direct, focused on what matters most, with actionable suggestions.
## Before the Review
Gather the modified code and context. Please strictly follow the process below:
1. Use `read_file` to read [package.json](mdc:package.json)
2. Use terminal to run command `git diff HEAD | cat` to obtain the diff and list the changed files. If you recieived empty result, run the same command once more.
3. Use `read_file` to open each changed file.
4. Use `read_file` to read [rules-attach.mdc](mdc:.cursor/rules/rules-attach.mdc). Even if you think it's unnecessary, you must read it.
5. combine changed files, step3 and `agent_requestable_workspace_rules`, list the rules which need to read
6. Use `read_file` to read the rules list in step 5
## Review
### Code Style
read [typescript.mdc](mdc:.cursor/rules/typescript.mdc) for the consolidated project code style and optimization rules.
### Code Optimization
The optimization checklist has been consolidated into [typescript.mdc](mdc:.cursor/rules/typescript.mdc): loops, debouncing/throttling, design system components, theming tokens, concurrency with `Promise.*`, minimal DB column selection, and package reuse.
### Obvious Bugs
- Do not silently swallow errors in `catch` blocks; at minimum, log them.
- Revert temporary code used only for testing (e.g., debug logs, temporary configs).
- Remove empty handlers (e.g., an empty `onClick`).
- Confirm the UI degrades gracefully for unauthenticated users.
- Don't leave any debug logs in the code (except when using the `debug` module properly).
- When using the `debug` module, avoid `import { log } from 'debug'` as it logs directly to console. Use proper debug namespaces instead.
- Check logs for sensitive information like api key, etc
## After the Review: output
1. Summary
- Start with a brief explanation of what the change set does.
- Summarize the changes for each modified file (or logical group).
2. Comments Issues
- List the most critical issues first.
- Use an ordered list, which will be convenient for me to reference later.
- For each issue:
- Mark severity tag (`❌ Must fix`, `⚠️ Should fix`, `💅 Nitpick`)
- Provode file path to the relevant file.
- Provide recommended fix
- End with a **git commit** command, instruct the author to run it.
- We use gitmoji to label commit messages, format: [emoji] <type>(<scope>): <subject>
Always use defensive clauses to make migrations idempotent:
```sql
-- ✅ Good: Idempotent operations
ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "avatar" text;
DROP TABLE IF EXISTS "old_table";
CREATE INDEX IF NOT EXISTS "users_email_idx" ON "users" ("email");
ALTER TABLE "posts" DROP COLUMN IF EXISTS "deprecated_field";
-- ❌ Bad: Non-idempotent operations
ALTER TABLE "users" ADD COLUMN "avatar" text;
DROP TABLE "old_table";
CREATE INDEX "users_email_idx" ON "users" ("email");
```
**Important**: After modifying migration SQL (e.g., adding `IF NOT EXISTS` clauses), run `bun run db:generate-client` to update the hash in `packages/database/src/core/migrations.json`.
description: Explain how group chat works in LobeHub (Multi-agent orchestratoin)
globs:
alwaysApply: false
---
This rule explains how group chat (multi-agent orchestration) works. Not confused with session group, which is a organization method to manage session.
## Key points
- A supervisor will devide who and how will speak next
- Each agent will speak just like in single chat (if was asked to speak)
Generally, you don't need to help me run the automatic translation tool as it takes a long time. I'll run it myself when needed. However, to see immediate results, you still need to translate `locales/zh-CN/namespace.json` first, no need to translate other languages.
- Add server service: `src/server/services/<domain>`
- Add a new model/provider: `src/config/modelProviders/<provider>.ts` + `packages/model-bank/src/aiModels/<provider>.ts` + `packages/model-runtime/src/<provider>/index.ts`
- Add DB schema/model/repository: `packages/database/src/{schemas|models|repositories}`
- Add Zustand slice: `src/store/<domain>/slices`
## Env Modes
- `NEXT_PUBLIC_CLIENT_DB`: selects client DB mode (e.g., `pglite`) vs server-backed
- `NEXT_PUBLIC_IS_DESKTOP_APP`: enables desktop-specific routes and behavior
- `NEXT_PUBLIC_SERVICE_MODE`: controls service routing preference (client/server)
## Boundaries
- Keep client logic in `src/services`; server-only logic stays in `src/server/services`
- Don’t mix Web API (`webapi/`) with tRPC (`src/server/routers/`)
- Place business UI under `src/features`, global reusable UI under `src/components`
- **Web with ClientDB**: React UI → Client Service → Direct Model Access → PGLite (Web WASM)
- **Web with ServerDB**: React UI → Client Service → tRPC Lambda → Server Services → PostgreSQL (Remote)
- **Desktop**:
- Cloud sync disabled: Electron UI → Client Service → tRPC Lambda → Local Server Services → PGLite (Node WASM)
- Cloud sync enabled: Electron UI → Client Service → tRPC Lambda → Cloud Server Services → PostgreSQL (Remote)
You are an expert in full-stack Web development, proficient in JavaScript, TypeScript, CSS, React, Node.js, Next.js, Postgresql, Redis, S3, all kinds of network protocols.
You are an LLM expert, you are familiar with all kinds of LLM models, ai agents, ai workflow, prompt engineering and context engineering.
You are an expert in Ai art. In Ai image generation, you are proficient in Stable Diffusion and ComfyUI's architectural principles, workflows, model structures, parameter configurations, training methods, and inference optimization.
You are an expert in UI/UX design, proficient in web interaction patterns, responsive design, accessibility, and user behavior optimization. You excel at improving user retention and paid conversion rates through various interaction details.
## Problem Solving
- When modifying existing code, clearly describe the differences and reasons for the changes
- Provide alternative solutions that may be better overall or superior in specific aspects
- Provide optimization suggestions for deprecated API usage
- Cite sources whenever possible at the end, not inline
- When you provide multiple solutions, provide the recommended solution first, and note it as `Recommended`
- Express uncertainty when there might not be a correct answer, instead of take action by guessing and assuming
## Code Implementation
- Focus on maintainable over being performant
- Be sure to reference file path
- If doc links or required files are missing, ask for them before proceeding with the task rather than making assumptions
- If you're unable to get valid result when using tools, please clearly state in the output
constlockComment=`This issue has been automatically locked since it was closed and has not had any activity for 7 days. If you're experiencing a similar issue, please file a new issue and reference this one if it's relevant.`;
You are a multilingual translation assistant. You need to respond to the following four types of GitHub Webhook events:
- issues
- issue_comment
- pull_request_review
- pull_request_review_comment
Please complete the following tasks:
1. Retrieve complete information for the current event.
- If the current event is 'issues', get the issue information.
- If the current event is 'issue_comment', get the comment information.
- If the current event is 'pull_request_review', get the review information.
- If the current event is 'pull_request_review_comment', get the comment information.
2. Intelligently detect content.
- If the retrieved information is already translated content following the format requirements, check if the translation matches the original content. If not, retranslate to match and follow the format requirements.
- If the retrieved information is untranslated content, check its language. If not in English, translate to English.
- If the retrieved information is partially translated to English, translate it completely to English.
- If the retrieved information contains references to already translated content, clean the referenced content to contain only English. Referenced content should not include "This xxx was translated by Claude" and "Original Content" etc.
- If the retrieved information contains other types of references (i.e., references to non-Claude translated content), keep them as-is without translation.
- If the retrieved information is email reply content, place email content references at the end during translation. Include only the reply content itself in both original and translated content, without email content references.
- If the retrieved information doesn't need any processing, skip the task.
3. Format requirements:
- Title: English translation (if non-English)
- Content format:
[Translated content]
---
> This issue/comment/review was translated by Claude.
<details>
<summary>Original Content</summary>
[Original content]
</details>
4. CRITICAL RULES to prevent hallucination and ensure accuracy:
- The "Original Content" section MUST contain the EXACT, UNMODIFIED original text byte-for-byte. NEVER add, remove, modify, or hallucinate ANY content in this section.
- Code blocks, error logs, JSON structures, and other technical content MUST appear in BOTH the translated section AND the original content section WITHOUT ANY MODIFICATION.
- When translating content with code/logs/JSON:
* Copy the code/logs/JSON blocks identically to both sections
* Only translate the natural language text (e.g., Chinese, Japanese) surrounding the code blocks
* Keep all technical content (URLs, variable names, error messages in English) unchanged
- ALWAYS verify the "Original Content" section matches the source text exactly before updating
- If you detect any discrepancy, retrieve the original content again to ensure accuracy
- Pay special attention to the end of comments - do not drop or hallucinate the last sentences
5. Update using gh tool:
- Choose the correct command based on the Event type in environment information:
- If Event is 'issues': gh issue edit [ISSUE_NUMBER] --title "[English title]" --body "[Translated content + Original content]"
- If Event is 'issue_comment': gh api -X PATCH /repos/${{ github.repository }}/issues/comments/${{ github.event.comment.id }} -f body="[Translated content + Original content]"
- If Event is 'pull_request_review': gh api -X PUT /repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/reviews/${{ github.event.review.id }} -f body="[Translated content]"
- If Event is 'pull_request_review_comment': gh api -X PATCH /repos/${{ github.repository }}/pulls/comments/${{ github.event.comment.id }} -f body="[Translated content + Original content]"
Please make sure you have given us as much context as possible.
- name:Auto Comment on Issues Closed
uses:wow-actions/auto-comment@v1
with:
@@ -37,8 +36,7 @@ jobs:
issuesClosed:|
✅ @{{ author }}
This issue is closed, If you have any questions, you can comment and reply.\
此问题已经关闭。如果您有任何问题,可以留言并回复。
This issue is closed, If you have any questions, you can comment and reply.
- name:Auto Comment on Pull Request Opened
uses:wow-actions/auto-comment@v1
with:
@@ -48,9 +46,7 @@ jobs:
Thank you for raising your pull request and contributing to our Community
Please make sure you have followed our contributing guidelines. We will review it as soon as possible.
If you encounter any problems, please feel free to connect with us.\
非常感谢您提出拉取请求并为我们的社区做出贡献,请确保您已经遵循了我们的贡献指南,我们会尽快审查它。
如果您遇到任何问题,请随时与我们联系。
If you encounter any problems, please feel free to connect with us.
- name:Auto Comment on Pull Request Merged
uses:actions-cool/pr-welcome@main
if:github.event.pull_request.merged == true
@@ -59,8 +55,7 @@ jobs:
comment:|
❤️ Great PR @${{ github.event.pull_request.user.login }} ❤️
The growth of project is inseparable from user feedback and contribution, thanks for your contribution! If you are interesting with the lobehub developer community, please join our [discord](https://discord.com/invite/AYFPHvv2jT) and then dm @arvinxx or @canisminor1990. They will invite you to our private developer channel. We are talking about the lobe-chat development or sharing ai newsletter around the world.\
The growth of project is inseparable from user feedback and contribution, thanks for your contribution! If you are interesting with the lobehub developer community, please join our [discord](https://discord.com/invite/AYFPHvv2jT) and then dm @arvinxx or @canisminor1990. They will invite you to our private developer channel. We are talking about the lobe-chat development or sharing ai newsletter around the world.
Since the issue was labeled with `✅ Fixed`, but no response in 3 days. This issue will be closed. If you have any questions, you can comment and reply.\
Since the issue was labeled with `✅ Fixed`, but no response in 3 days. This issue will be closed. If you have any questions, you can comment and reply.
- name:need reproduce
uses:actions-cool/issues-helper@v3
with:
@@ -50,8 +49,7 @@ jobs:
body:|
👋 @{{ author }}
<br/>
Since the issue was labeled with `🤔 Need Reproduce`, but no response in 3 days. This issue will be closed. If you have any questions, you can comment and reply.\
Since the issue was labeled with `🤔 Need Reproduce`, but no response in 3 days. This issue will be closed. If you have any questions, you can comment and reply.
- name:need reproduce
uses:actions-cool/issues-helper@v3
with:
@@ -62,5 +60,4 @@ jobs:
body:|
👋 @{{ github.event.issue.user.login }}
<br/>
Since the issue was labeled with `🙅🏻♀️ WON'T DO`, and no response in 3 days. This issue will be closed. If you have any questions, you can comment and reply.\
Since the issue was labeled with `🙅🏻♀️ WON'T DO`, and no response in 3 days. This issue will be closed. If you have any questions, you can comment and reply.
- wrapped the file path in single quotes to avoid shell expansion
- wrap the file path in single quotes to avoid shell expansion
- Never run `bun run test` etc to run tests, this will run all tests and cost about 10mins
- If try to fix the same test twice, but still failed, stop and ask for help.
- If trying to fix the same test twice, but still failed, stop and ask for help.
### Typecheck
@@ -61,40 +51,9 @@ Testing work follows the Rule-Aware Task Execution system above.
### i18n
- **Keys**: Add to `src/locales/default/namespace.ts`
- **Dev**: Translate `locales/zh-CN/namespace.json`locale file only for preview
- **Dev**: Translate `locales/zh-CN/namespace.json`and `locales/en-US/namespace.json` locales file only for dev preview
- DON'T run `pnpm i18n`, let CI auto handle it
## Rules Index
Some useful rules of this project. Read them when needed.
**IMPORTANT**: All rule files referenced in this document are located in the `.cursor/rules/` directory. Throughout this document, rule files are referenced by their filename only for brevity.
### 📋 Complete Rule Files
**Core Development**
-`backend-architecture.mdc` - Three-layer architecture, data flow
Copyright (c) 2024/06/17 - current LobeHub LLC. All rights reserved.
----------
From 1.0, LobeChat is licensed under the Apache License 2.0, with the following additional conditions:
From 1.0, LobeChat is licensed under the LobeHub Community License, based on Apache License 2.0 with the following additional conditions:
1. The commercial usage of LobeChat:
@@ -22,17 +22,3 @@ Please contact hello@lobehub.com by email to inquire about licensing matters.
b. Your contributed code may be used for commercial purposes, including but not limited to its cloud edition.
Apart from the specific conditions mentioned above, all other rights and restrictions follow the Apache License 2.0. Detailed information about the Apache License 2.0 can be found at http://www.apache.org/licenses/LICENSE-2.0.
----------
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
| [PortfolioMeta](https://lobechat.com/discover/plugin/StockData)<br/><sup>By **portfoliometa** on **2025-07-21**</sup> | Analyze stocks and get comprehensive real-time investment data and analytics.<br/>`stock` |
| [PortfolioMeta](https://lobechat.com/discover/plugin/StockData)<br/><sup>By **portfoliometa** on **2025-09-27**</sup> | Analyze stocks and get comprehensive real-time investment data and analytics.<br/>`stock` |
| [Web](https://lobechat.com/discover/plugin/web)<br/><sup>By **Proghit** on **2025-01-24**</sup> | Smart web search that reads and analyzes pages to deliver comprehensive answers from Google results.<br/>`web``search` |
| [Bing_websearch](https://lobechat.com/discover/plugin/Bingsearch-identifier)<br/><sup>By **FineHow** on **2024-12-22**</sup> | Search for information from the internet base BingApi<br/>`bingsearch` |
| [Google CSE](https://lobechat.com/discover/plugin/google-cse)<br/><sup>By **vsnthdev** on **2024-12-02**</sup> | Searches Google through their official CSE API.<br/>`web``search` |
@@ -819,7 +819,7 @@ Every bit counts and your one-time donation sparkles in our galaxy of support! Y
| [PortfolioMeta](https://lobechat.com/discover/plugin/StockData)<br/><sup>By **portfoliometa** on **2025-07-21**</sup> | 分析股票并获取全面的实时投资数据和分析。<br/>`股票` |
| [PortfolioMeta](https://lobechat.com/discover/plugin/StockData)<br/><sup>By **portfoliometa** on **2025-09-27**</sup> | 分析股票并获取全面的实时投资数据和分析。<br/>`股票` |
| [网页](https://lobechat.com/discover/plugin/web)<br/><sup>By **Proghit** on **2025-01-24**</sup> | 智能网页搜索,读取和分析页面,以提供来自 Google 结果的全面答案。<br/>`网页``搜索` |
| [必应网页搜索](https://lobechat.com/discover/plugin/Bingsearch-identifier)<br/><sup>By **FineHow** on **2024-12-22**</sup> | 通过 BingApi 搜索互联网上的信息<br/>`bingsearch` |
| [谷歌自定义搜索引擎](https://lobechat.com/discover/plugin/google-cse)<br/><sup>By **vsnthdev** on **2024-12-02**</sup> | 通过他们的官方自定义搜索引擎 API 搜索谷歌。<br/>`网络``搜索` |
"improvements":["Add more AWS regions, Update infini-ai models."]
},
"date":"2025-10-11",
"version":"1.136.12"
},
{
"children":{
"improvements":[
"Add capability inference for web search, image output and video recognition in model parsing and update UI form items to support search, imageOutput and video abilities."
]
},
"date":"2025-10-11",
"version":"1.136.11"
},
{
"children":{
"improvements":["Improve search experience."]
},
"date":"2025-10-11",
"version":"1.136.10"
},
{
"children":{
"improvements":["Add lab to support disable/enable rich text."]
},
"date":"2025-10-11",
"version":"1.136.9"
},
{
"children":{},
"date":"2025-10-11",
"version":"1.136.8"
},
{
"children":{
"fixes":["Disable rich text in markdown editor."]
},
"date":"2025-10-11",
"version":"1.136.7"
},
{
"children":{},
"date":"2025-10-11",
"version":"1.136.6"
},
{
"children":{},
"date":"2025-10-11",
"version":"1.136.5"
},
{
"children":{
"fixes":["Add 'gemini-2.5-flash-image' to disabled models Thinking."]
# Other environment variables, as needed. You can refer to the environment variables configuration for the client version, making sure not to have ACCESS_CODE.
# OPENAI_API_KEY=sk-xxxx
# OPENAI_PROXY_URL=https://api.openai.com/v1
# OPENAI_MODEL_LIST=...
# ===========================
# ====== Preset config ======
# ===========================
# if no special requirements, no need to change
LOBE_PORT=3210
CASDOOR_PORT=8000
MINIO_PORT=9000
APP_URL=http://localhost:3210
AUTH_URL=http://localhost:3210/api/auth
# Postgres related, which are the necessary environment variables for DB
# Other environment variables, as needed. You can refer to the environment variables configuration for the client version, making sure not to have ACCESS_CODE.
# OPENAI_API_KEY=sk-xxxx
# OPENAI_PROXY_URL=https://api.openai.com/v1
# OPENAI_MODEL_LIST=...
# ===========================
# ====== Preset config ======
# ===========================
# if no special requirements, no need to change
LOBE_PORT=3210
CASDOOR_PORT=8000
MINIO_PORT=9000
APP_URL=http://localhost:3210
AUTH_URL=http://localhost:3210/api/auth
# Postgres related, which are the necessary environment variables for DB
In `src/app/<new-page>/features/<new-feature>.tsx`, we need to create a new page or component to display "Chat Messages". In this file, we can use the Zustand Store created earlier and Ant Design components to build the UI:
```jsx
// src/features/chat/index.tsx
// src/app/chat/features/ChatPage/index.tsx
// Note: Use src/app/<page>/features/ for page-specific components
import { List, Typography } from 'antd';
import { useChatStore } from 'src/store/chatStore';
@@ -82,6 +85,12 @@ const ChatPage = () => {
export default ChatPage;
```
> **Note on Feature Organization**: LobeChat uses two patterns for organizing features:
> - **Global features** (`src/features/`): Shared components like `ChatInput`, `Conversation` used across the app
> - **Page-specific features** (`src/app/<page>/features/`): Components used only within a specific page route
>
> Choose based on reusability. If unsure, start with page-specific and refactor to global if needed elsewhere.
## 5. Function Binding
In a page or component, we need to bind the Zustand Store's state and methods to the UI. In the example above, we have already bound the `messages` state to the `dataSource` property of the list. Now, we also need a method to add new messages. We can define this method in the Zustand Store and then use it in the page or component:
├── services # Encapsulated backend service interfaces, such as HTTP requests
├── store # Zustand store for state management
├── styles # Global styles and CSS-in-JS configurations
├── types # TypeScript type definition files
└── utils # Common utility functions
```
## app
In the `app` folder, we organize each route page according to the app router's [Route Groups](https://nextjs.org/docs/app/building-your-application/routing/route-groups) to separately handle the implementation of desktop and mobile code. Taking the file structure of the `welcome` page as an example:
The `app` directory follows Next.js 13+ App Router conventions with a sophisticated architecture using [Route Groups](https://nextjs.org/docs/app/building-your-application/routing/route-groups) to organize backend services, platform variants, and application routes:
├── features # This folder contains features code shared by both desktop and mobile, such as the Banner component
│ └── Banner
└── page.tsx # This is the main entry file for the page, used to load desktop or mobile code based on the device type
app
├── (backend)/ # Backend API routes and services
│ ├── api/ # REST API endpoints
│ │ ├── auth/ # Authentication routes
│ │ └── webhooks/ # Webhook handlers
│ ├── middleware/ # Request middleware
│ ├── oidc/ # OpenID Connect routes
│ ├── trpc/ # tRPC API endpoints
│ │ ├── async/ # Async tRPC routes
│ │ ├── desktop/ # Desktop-specific tRPC routes
│ │ ├── edge/ # Edge runtime tRPC routes
│ │ ├── lambda/ # Lambda tRPC routes
│ │ └── tools/ # Tools tRPC routes
│ └── webapi/ # Web API endpoints
│ ├── chat/ # Chat-related APIs
│ ├── models/ # Model management APIs
│ ├── tts/ # Text-to-speech APIs
│ └── ...
├── [variants]/ # Platform and device variants
│ ├── (auth)/ # Authentication pages
│ │ ├── login/
│ │ ├── signup/
│ │ └── next-auth/
│ ├── (main)/ # Main application routes
│ │ ├── (mobile)/ # Mobile-specific routes
│ │ │ └── me/ # Mobile profile pages
│ │ ├── _layout/ # Layout components
│ │ ├── chat/ # Chat interface
│ │ ├── discover/ # Discovery pages
│ │ ├── files/ # File management
│ │ ├── image/ # Image generation
│ │ ├── profile/ # User profile
│ │ ├── repos/ # Repository management
│ │ └── settings/ # Application settings
│ └── @modal/ # Parallel modal routes
│ ├── (.)changelog/
│ └── _layout/
├── desktop/ # Desktop-specific routes
│ └── devtools/
├── manifest.ts # PWA manifest
├── robots.tsx # Robots.txt generation
├── sitemap.tsx # Sitemap generation
└── sw.ts # Service worker
```
In this way, we can clearly distinguish and manage desktop and mobile code, while also easily reusing code required on both devices, thereby improving development efficiency and maintaining code cleanliness and maintainability.
### Architecture Explanation
**Route Groups:**
- `(backend)` - Contains all server-side API routes, middleware, and backend services
- `[variants]` - Dynamic route group handling different platform variants and main application pages
- `@modal` - Parallel routes for modal dialogs using Next.js parallel routing
**Platform Organization:**
- The architecture supports multiple platforms (web, desktop, mobile) through route organization
- Desktop-specific routes are in the `desktop/` directory
- Mobile-specific routes are organized under `(main)/(mobile)/`
- Shared layouts and components are in `_layout/` directories
**API Architecture:**
- REST APIs in `(backend)/api/` and `(backend)/webapi/`
description: Configure local environment for developing text-to-image and image-to-image features
---
# Image Generation Development Setup
This guide helps developers set up the local environment for developing image generation features (text-to-image, image-to-image) with file storage capabilities.
## Prerequisites
- Docker installed and running
- Node.js and pnpm installed
- PostgreSQL client tools (optional, for debugging)
<Callout type="warning">
**Security Notice**: This setup is designed for local development only. It uses default credentials and open permissions that are NOT suitable for production environments.
</Callout>
## Quick Setup
Run the provided script to automatically set up all required services:
```bash
# Set up PostgreSQL and MinIO for image storage
./scripts/setup-image-generation-dev.sh
# Start the development server
pnpm dev:desktop
```
This script will:
1. Start PostgreSQL (no authentication for local development)
2. Run database migrations to initialize schema
3. Start MinIO (S3-compatible storage)
4. Create and configure the storage bucket
5. Add necessary S3 environment variables to `.env.desktop`
## Architecture Overview
The image generation feature requires:
- **PostgreSQL**: Stores metadata about generated images
- **MinIO/S3**: Stores the actual image files
- **Server Mode**: Required for file handling (`NEXT_PUBLIC_SERVICE_MODE=server`)
## Environment Configuration
The following environment variables are automatically configured by the setup script:
```bash
# S3 Storage Configuration (MinIO for local development)
S3_ACCESS_KEY_ID=minioadmin
S3_SECRET_ACCESS_KEY=minioadmin
S3_ENDPOINT=http://localhost:9000
S3_BUCKET=lobe-chat
S3_REGION=us-east-1
S3_PUBLIC_DOMAIN=http://localhost:9000/lobe-chat
S3_ENABLE_PATH_STYLE=1 # Required for MinIO
```
## Development Workflow
### 1. Image Generation API
When developing image generation features, generated images will be:
The basic setup above uses LobeChat's client-side database mode. If you need to work with server-side features such as:
- Database persistence
- File uploads and storage
- Image generation
- Multi-user authentication
- Advanced server-side integrations
Please refer to the [Work with Server-Side Database](/docs/development/basic/work-with-server-side-database) guide for complete setup instructions.
During the development process, if you encounter any issues with environment setup or have any questions about LobeChat development, feel free to ask us at any time. We look forward to seeing your contributions!
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.