Skip to content

feat: Server with Go(Team tenants users POST API) - #15301

Closed
whitepicker wants to merge 75 commits into
infiniflow:mainfrom
whitepicker:feat/team-tenants-user-post
Closed

whitepicker wants to merge 75 commits into
infiniflow:mainfrom
whitepicker:feat/team-tenants-user-post

Conversation

@whitepicker

Copy link
Copy Markdown
Contributor

Summary

This PR implements POST /api/v1/tenants/<tenant_id>/users in the Go server for User setting / Team, following the Python reference in api/apps/restful_apis/tenant_api.py.

The new Go endpoint now:

  • validates the request body and requires email
  • allows only the tenant owner (current_user.id == tenant_id)
  • looks up the invited user by email
  • rejects duplicate team membership with Python-compatible messages
  • creates a user_tenant invite record with role invite
  • sends the invite email using SMTP config
  • returns the invited user payload with id, avatar, email, and nickname

Related Issue

Closes: #15240

Change Type

  • New feature
  • Bug fix
  • Tests
  • Build / validation fix
  • Breaking change
  • Documentation only
  • Refactor only

API Behavior

Endpoint

POST /api/v1/tenants/{tenant_id}/users

Request body

{
  "email": "[email protected]"
}

Success behavior

  • checks authenticated user
  • checks tenant_id == current_user.id
  • finds existing user by email
  • creates user_tenant relation with:
    • role = "invite"
    • invited_by = current_user.id
    • status = "1"
  • sends invite email
  • returns invited user info

Success response example

{
  "code": 0,
  "data": {
    "id": "invitee_user_id",
    "avatar": "https://example.com/avatar.png",
    "email": "[email protected]",
    "nickname": "Invitee"
  },
  "message": "success"
}

Error behavior

Matches Python logic for:

  • No authorization.
  • User not found.
  • {email} is already in the team.
  • {email} is the owner of the team.
  • {email} is in the team, but the role: {role} is invalid.
  • Failed to send invite email.

Real Behavior Proof

Implementation proof

  • Route added in internal/router/router.go
  • Handler added in internal/handler/tenant.go
  • Service logic added in internal/service/tenant.go
  • Email sender added in internal/handler/tenant_mail.go

Test proof

Passed:

go test ./internal/handler -run TestAddTenantUser -count=1

Passed:

go test ./internal/service ./internal/handler ./internal/router -count=1

Build proof

Passed:

./build.sh --go

Passed:

./bin/server_main --help

Checklist

  • Implemented only the requested tenant user POST endpoint
  • Matched Python endpoint behavior as closely as practical
  • Added route, handler, service, and email sending support
  • Added test coverage for the new handler
  • Ran targeted tests
  • Ran broader Go package tests
  • Built Go binaries successfully
  • Verified server_main starts and prints help without errors

Haruko386 and others added 30 commits May 21, 2026 18:28
### What problem does this PR solve?

implement ASR and TTS for Xinference

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
- [x] Refactoring
### What problem does this PR solve?

1. update python version to 3.13
2. upgrade ormsgpack to 1.6.0

### Type of change

- [x] Refactoring

---------

Signed-off-by: Jin Hai <[email protected]>
…a different event loop (infiniflow#15100)

Fix: <asyncio.locks.Semaphore object at 0xabcd [locked]> is bound to a
different event loop
### What problem does this PR solve?

implement rerank, asr, tts for TogetherAI

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
### What problem does this PR solve?

Updated v0.25.5 release notes.

### Type of change


- [x] Documentation Update
### What problem does this PR solve?

Fixed a docusaurus deployment issue.

### Type of change

- [x] Documentation Update
### What problem does this PR solve?

guard missing task language

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve?

Closes infiniflow#15089.

Adds PPIO support to the Go model-provider layer so PPIO instances can
be routed through the Go API server with the same OpenAI-compatible
chat, streaming, model listing, and connection-check flow used by other
SaaS providers.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

## Summary

- Added a PPIO Go model driver.
- Added the PPIO provider catalog and default OpenAI-compatible API URL.
- Registered PPIO in the model factory.
- Added focused provider and provider-manager tests.

## What changed

- Implemented chat completions, SSE streaming, ListModels, and
CheckConnection for PPIO.
- Covered request shape, stream termination, reasoning fallback, model
listing, custom base URLs, safe transport setup, unsupported methods,
and provider config loading.
- Kept the provider catalog aligned with the existing RAGFlow PPIO
factory model set.
- Cleaned up pre-existing Go model package validation blockers so the
scoped provider tests can run normally with vet enabled.

## Why

The existing Python/provider catalog path includes PPIO, but the Go
model-provider layer did not have a PPIO driver, so the Go API server
could not instantiate or use PPIO as requested in infiniflow#15089.
### What problem does this PR solve?

This PR implements ASR and TTS support for the ZhipuAI Go driver.

The ZhipuAI model config already advertises `glm-asr-2512` as an ASR
model, but the Go driver returned `zhipu, no such method` from
`TranscribeAudio`. This adds the documented audio transcription endpoint
suffix and sends multipart transcription requests with `model`,
`stream=false`, and `file` fields.

Per maintainer review, this also adds the ZhipuAI TTS endpoint suffix
and implements `AudioSpeech` / `AudioSpeechWithSender` for `glm-tts`.

Closes infiniflow#15133

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] New Feature (non-breaking change which adds functionality)
…low#14868)

### What problem does this PR solve?

Closes infiniflow#14865

`download_img` in `common/misc_utils.py` is used for OAuth avatar URLs.
The previous implementation called `async_request` from
`common.http_client`, which followed redirects without re-validating
each hop and did not apply the same SSRF protections as this path needs.
That made it possible to reach non-public or disallowed targets (for
example via redirects or unsafe URLs) when fetching avatars.

This change replaces that flow with an explicit, bounded fetch: each URL
(including every redirect target) is checked with
`common.ssrf_guard.assert_url_is_safe`, DNS is pinned with
`pin_dns_global`, `httpx` streams the body with `follow_redirects=False`
and a manual redirect loop (capped by
`RAGFLOW_OAUTH_AVATAR_MAX_REDIRECTS`), and total response size is capped
(`RAGFLOW_OAUTH_AVATAR_MAX_BYTES`). Timeouts, proxy, and user agent
align with `HTTP_CLIENT_*` env vars without importing `http_client`, so
lightweight tests stay simple.

Unit tests cover empty/None URLs, loopback, cloud metadata-style
addresses, and disallowed schemes so SSRF regressions are caught early.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)

---------

Co-authored-by: Kevin Hu <[email protected]>
… and retrieval (infiniflow#4310) (infiniflow#14208)

Closes infiniflow#4310

### What problem does this PR solve?

Issue infiniflow#4310 requests practical examples for the RAGFlow SDK and HTTP API
to help developers get started faster. The existing `example/sdk/`
folder only contains `dataset_example.py`. This PR fills the remaining
gaps by adding examples for three key API areas not yet covered in
`main` or by other open PRs (infiniflow#13904, infiniflow#13284):

- **Chunk management** — add, list, update, delete, and retrieve chunks
within a dataset
- **Chat assistant** — create a chat assistant, open a session, send
messages (streaming and non-streaming), and clean up
- **Retrieval** — perform semantic retrieval across one or multiple
datasets

### Type of change

- [x] Documentation Update
- [x] New Feature (non-breaking change which adds functionality)
### What problem does this PR solve?

1. Enhance retry and timeout, and adjust the default timeout
2. NER: spacy do not batch chunks
3. extract _has_cancel_and_exit
4. enhance log messages

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
- [x] Refactoring
### What problem does this PR solve?

Refactor: enahnce CI

### Type of change

- [x] Refactoring
…iniflow#14792)

Closes infiniflow#14789

### What problem does this PR solve?

User API endpoints (`login`, `user_profile`, `user_add`,
`forget_reset_password`) were returning full user objects via
`to_json()` / `to_dict()`, which included sensitive fields like
`password` and `access_token` in the response body. This leaks
credentials to the client.

This PR adds a `to_safe_dict()` method on the `User` model that strips
sensitive fields (`password`, `access_token`) and replaces all affected
call sites to use it.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
…flow#14542)

### What problem does this PR solve?

The agent API currently does not pass chat_template_kwargs to the
underlying LLM call path, so clients cannot control template-level model
behavior (such as thinking-mode toggles) when invoking
/agents/chat/completion. This PR adds passthrough support for
chat_template_kwargs across agent execution flows (session and
non-session, streaming and non-streaming) by propagating it through
canvas runtime state and into LLM invocation kwargs. This addresses the
feature gap raised in [Issue
infiniflow#14182](infiniflow#14182).

Closes infiniflow#14182 

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
### What problem does this PR solve?

Fixes infiniflow#15066

OpenRouter now exposes an official speech-to-text endpoint at `POST
/api/v1/audio/transcriptions`, but the Go model driver still returned
`openrouter, no such method` from `TranscribeAudio`. This left
OpenRouter ASR models unavailable through the Go API server even though
the provider already has OpenRouter audio support for TTS.

Related provider-tracking context: infiniflow#14736

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

Co-authored-by: Jin Hai <[email protected]>
…#13487)

## Summary

Implements the TODO in `evaluation_service.py`: **Track token usage** in
evaluation results.

## Changes

- **Import** `num_tokens_from_string` from `common.token_utils`
- **Prompt tokens**: Use the full prompt returned by `async_chat` when
available (includes system prompt + knowledge base + query), otherwise
fall back to the question token count
- **Completion tokens**: Count tokens in the generated answer
- **Storage**: Store `token_usage` as `{prompt_tokens,
completion_tokens, total_tokens}` in each `EvaluationResult` instead of
`None`

## Why

The evaluation pipeline previously saved `token_usage: None` for every
result. This change allows downstream consumers (e.g. evaluation
dashboards, cost tracking) to see approximate token usage per test case
using the same tokenizer (tiktoken cl100k_base) used elsewhere in
RAGFlow.

## Testing

- No new tests added; existing evaluation flow unchanged
- Token counting uses existing `num_tokens_from_string` utility

---------

Co-authored-by: kiannidev <[email protected]>
## Summary
- Adds a `TokenPony` Go driver so the new API server can route TokenPony
chat instances, matching the existing Python `TokenPonyChat`
(`rag/llm/chat_model.py:1210`). Follows the same SaaS-driver shape used
for Astraflow, Avian, Novita, TogetherAI, Replicate, DeepInfra, Upstage,
and LongCat.

Closes infiniflow#15086

---------

Co-authored-by: Jin Hai <[email protected]>
### What problem does this PR solve?

move agent attachment download api to the correct route and update
frontend callers

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)

### Notes

- Move the attachment download endpoint from document routes to agent
routes.
- Update frontend download callers to use the agent attachment endpoint.
- Reuse the shared file response header helper instead of duplicating it
in `agent_api.py`.
### What problem does this PR solve?

Add model_type into llm_setting

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve?

Closes infiniflow#15088.

Adds Groq support to the Go model-provider layer so Groq instances can
be routed through the Go API server with the same OpenAI-compatible
chat, streaming, model listing, and connection-check flow used by other
SaaS providers.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

## Summary

- Added a Groq Go model driver.
- Added the Groq provider catalog and default OpenAI-compatible API URL.
- Registered Groq in the model factory.
- Added focused provider tests.

## What changed

- Implemented chat completions, SSE streaming, ListModels, and
CheckConnection for Groq.
- Covered request shape, stream termination, reasoning fallback, model
listing, custom base URLs, safe transport setup, and unsupported
methods.
- Kept the provider catalog scoped to current Groq chat-capable model
IDs.
- Cleaned up pre-existing Go model package validation blockers so the
package can be tested normally with vet enabled.

## Why

The existing Python/provider catalog path includes Groq, but the Go
model-provider layer did not have a Groq driver, so the Go API server
could not instantiate or use Groq as requested in infiniflow#15088.

## Notes

The model package now validates without disabling vet.

---------

Co-authored-by: Jin Hai <[email protected]>
### What problem does this PR solve?

Fix search vector_similarity_weight

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve?

How to ingest messages from your Discord server.

### Type of change

- [x] Documentation Update
### What problem does this PR solve?

implement embed, rerank, tts for AstraFlow

**Verify from CLI**

```
# Astraflow
RAGFlow(user)> tts with 'IndexTeam/IndexTTS-2@test3@astraflow' text 'hello? show yourself' play format 'wav' param '{"voice": "jack_cheng"}'
SUCCESS

RAGFlow(user)> rerank query 'what is rag' document 'rag is retrieval augment generation' 'rag need llm' 'famous rag project includes ragflow' with 'bge-reranker-v2-m3@test3@astraflow' top 3;
+-------+---------------------+
| index | relevance_score     |
+-------+---------------------+
| 0     | 0.9837390184402466  |
| 2     | 0.06322699040174484 |
| 1     | 0.04663187265396118 |
+-------+---------------------+

RAGFlow(user)> embed text 'walkerwhat' 'jumperwho' with 'text-embedding-3-large@test3@astraflow' dimension 16
+-----------+-------+
| dimension | index |
+-----------+-------+
| 3072      | 0     |
| 3072      | 1     |
+-----------+-------+

# Xinference


```

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
- [x] Refactoring
### What problem does this PR solve?

Go: implement reasoning_chat, TTS, ASR for Groq

**Verify from CLI**
```
RAGFlow(user)> think chat with 'qwen/qwen3-32b@test@groq' message 'who r u'
Thinking: Okay, the user asked, who r u. I need to determine what the user is asking. They may be asking about my identity. I should introduce my name and basic functions. The user might want to know what I can do, so I should list some common use cases, such as answering questions, creating writing, coding, and expressing opinions. The user may be curious about how they can interact with me, so they can be advised to ask any questions or provide instructions. Keep your answers conversational, avoid overly technical terms, keep answers concise, and encourage further interaction. Check if there's any ambiguity in the answer and make sure it's accurate and meets the user's needs. Also consider if there are other aspects the user may be interested in, such as my training data or performance. But since the question is basic, I'll focus on the essentials first and invite the user to ask more. In summary, respond to the user's questions by introducing yourself, your functions, and encouraging further interaction.

Answer: Hello! I'm Qwen. I am a large-scale language model developed by Tongyi Lab, designed to assist you in various ways, such as answering questions, creating text, logical reasoning, programming, and more. I aim to provide clear, accurate, and helpful information and support. How can I assist you today? Feel free to ask any questions or give me tasks! 😊
Time: 2.199908


RAGFlow(user)> stream think chat with 'openai/gpt-oss-20b@test@groq' message 'who r u'
Thinking:  to respond politely.
Answer: ’m ChatGPT—an AI language model created by OpenAI. I’m here to answer questions, offer explanations, and help with a wide range of topics. How can I assist you today?


RAGFlow(user)> tts with 'canopylabs/orpheus-arabic-saudi@test@groq' text 'hello? show yourself' play format 'wav' param '{"voice": "fahad"}'
SUCCESS


RAGFlow(user)> asr with 'whisper-large-v3-turbo@test@groq' audio './internal/test.wav' param '{"language": "en"}'
+----------------------------------------------------------------------------------------------------------------------+
| text                                                                                                                 |
+----------------------------------------------------------------------------------------------------------------------+
|  The examination and testimony of the experts enabled the Commission to conclude that five shots may have been fired |
+----------------------------------------------------------------------------------------------------------------------+
```

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
…niflow#15155)

### What problem does this PR solve?

Fix: /openai/<chat_id>/chat/completions not aware of session_id

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve?

Closes infiniflow#15102.

OpenAI's Go provider config advertises `whisper-1` as ASR and `tts-1` as
TTS, but the Go driver returned `openai, no such method` for both audio
paths and did not define `url_suffix.asr` / `url_suffix.tts`.

This PR:

- adds OpenAI audio URL suffixes for `audio/transcriptions` and
`audio/speech`
- implements non-streaming `TranscribeAudio` using multipart form
uploads
- implements non-streaming `AudioSpeech` using the OpenAI speech JSON
request shape
- keeps streaming TTS explicitly unsupported instead of sending binary
audio through the text SSE sender
- adds focused tests for config coverage, ASR/TTS request shape,
required TTS voice validation, and unsupported streaming TTS


### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)

---------

Co-authored-by: Jin Hai <[email protected]>
…iniflow#15192)

## Summary

- Brings the French locale (`web/src/locales/fr.ts`) to full parity with
the English reference
- Adds ~1400 missing translation keys across **all sections**: `common`,
`chat`, `header`, `login`, `admin`, `setting`, `flow`,
`knowledgeDetails`, `knowledgeConfiguration`, `memory`, `skills`,
`skillSearch`, `chunk`, `mcp`, `fileManager`, `search`,
`dataflowParser`, `datasetOverview`, `deleteModal`, `empty`, `explore`,
`memories`, `pagination`, `language`, `knowledgeList`
- All strings containing French apostrophes use double-quote delimiters
(prevents JS syntax errors)

## Test plan

- [ ] `npx esbuild src/locales/fr.ts --bundle=false` — no errors
- [ ] `npx eslint src/locales/fr.ts` — no errors
- [ ] Switch UI language to French and verify key sections render
correctly (chat, knowledge base, admin panel, agent flow)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
JSONbored and others added 12 commits May 26, 2026 17:12
## Summary
- Wire the Go TokenHub provider through the model factory.
- Harden TokenHub request handling for chat, streaming, embeddings, and
model listing.
- Add focused TokenHub unit coverage for factory wiring and provider
behavior.

## Notes
- Refs infiniflow#14736.
- Follows up infiniflow#15159.

Co-authored-by: Jin Hai <[email protected]>
### What problem does this PR solve?

  This PR adds HuaweiCloud provider integration in RAGFlow.

  Supported capabilities:

  - [x] Chat / Think Chat / Stream Chat / Stream Think Chat
  - [x] Embedding
  - [x] Rerank
  - [x] Model listing
  - [x] Provider connection checking

  Verified examples from the CLI:

  ```
  check instance 'test' from 'HuaweiCloud';

  chat with 'deepseek-v4-flash@test@HuaweiCloud' message 'hello';

  think chat with 'deepseek-v4-flash@test@HuaweiCloud' message 'hello';

  stream chat with 'deepseek-v4-flash@test@HuaweiCloud' message 'hello';

stream think chat with 'deepseek-v4-flash@test@HuaweiCloud' message
'hello';

embed text 'what is rag' 'who are you' with 'bge-m3@test@HuaweiCloud'
dimension 1024;

rerank query 'what is rag' document 'rag is retrieval augmented
generation' 'rag need llm' 'famous rag
project includes ragflow' with 'bge-reranker-v2-m3@test@HuaweiCloud' top
3;

  list supported models from 'HuaweiCloud' 'test';

  LIST MODELS FROM 'HuaweiCloud' 'test';
```
  ### Type of change

  - [x] New Feature
  - [x] Provider integration
Closes infiniflow#15040.

ModelScope was listed unchecked in the Go-rewrite tracker infiniflow#14736 and
already had an llm_factories.json entry (tags: LLM) but no Go driver, so
the new Go API server could not route ModelScope instances. The Python
side has supported it through the OpenAI-compatible base at
rag/llm/chat_model.py:618 (ModelScopeChat), which requires a
user-supplied base URL and appends /v1.

This adds:
- internal/entity/models/modelscope.go: self-hosted OpenAI-compatible
driver with chat (sync + SSE stream with idle-timeout cancellation),
list_models, and check_connection. Auth header is optional, matching the
xinference pattern, so deployments without auth and auth-enabled
deployments both work. Base URL is normalized so users can configure
either the root endpoint or the /v1 endpoint.
- internal/entity/models/modelscope_test.go: 12 tests covering name, URL
normalization, factory routing, chat happy path / auth header /
reasoning_content extraction, stream happy path / stream=false rejection
/ idle cancellation, list_models + check_connection, missing-base-URL
clear error, and the no-such-method sentinels.
- conf/models/modelscope.json: shipped config (class: "local",
url_suffix v1/chat/completions and v1/models).
- internal/entity/models/factory.go: case "modelscope" →
ModelScopeModel.
- internal/service/llm.go: ModelScope added to the selfDeployed map
alongside Ollama, Xinference, LocalAI, LM-Studio, GPUStack — the Python
side requires user-supplied URL with no default, so the Go side
classifies it the same way.

Follow-on issues will add Embed and Rerank, in line with how Novita,
NVIDIA, TogetherAI, and other providers landed method-by-method.

---------

Co-authored-by: Jin Hai <[email protected]>
### What problem does this PR solve?

implement provider `OrcaRouter`
**The following functionalities are now supported:**

**Cohere:**
- [x] Chat / Think Chat / Stream Chat / Stream Think Chat
- [x] Model listing
- [x] TTS
- [ ] Balance


### Type of change

- [x] New Feature (non-breaking change which adds functionality)

---------

Co-authored-by: Jin Hai <[email protected]>
…iflow#15248)

### What problem does this PR solve?

- Update version tags in README files (including translations) from
v0.25.5 to v0.25.6
- Modify Docker image references and documentation to reflect new
version
- Update version badges and image descriptions
- Maintain consistency across all language variants of README files

### Type of change

- [x] Documentation Update
### What problem does this PR solve?

Initial draft: v0.25.6 release notes.

### Type of change

- [x] Documentation Update
## Summary
- add the xAI `models` URL suffix used by the existing Go `ListModels`
implementation
- return a clear error when the xAI models suffix is missing
- add focused xAI model-listing and connection-check regression tests

## What changed
- Added `url_suffix.models` to `conf/models/xai.json`.
- Normalized the configured models suffix before building the request
URL.
- Covered config loading, successful model listing, upstream errors,
API-key validation, missing suffix handling, and `CheckConnection`
delegation.

## Why
`XAIModel.ListModels` already builds requests from `URLSuffix.Models`,
and `CheckConnection` delegates to that method. The bundled xAI config
did not define that suffix, which left the model-listing path unable to
call the provider `/models` endpoint from the existing provider config.

## Validation
- `go test ./internal/entity/models -run TestXAI -count=1`
- `go test ./internal/entity -count=1`
- `git diff HEAD~1..HEAD --check`

## Notes
- `go test ./internal/entity/models -count=1` currently fails in
unchanged Astraflow coverage: `TestAstraflowEmbedReturnsNoSuchMethod`
panics before reaching any xAI assertions.

---------

Co-authored-by: Jin Hai <[email protected]>
## Summary
- Add LongCat model-list support through the documented
OpenAI-compatible models endpoint.

## What changed
- Add the LongCat `models` URL suffix for `/openai/v1/models`.
- Implement `ListModels` for the LongCat Go driver.
- Delegate `CheckConnection` to the lightweight model-list request.
- Add focused regression coverage for successful, malformed, oversized,
and missing-key responses.

## Why
LongCat documents a models endpoint under the OpenAI-compatible API
surface, but the Go driver still returned `no such method` for model
listing and connection checks.

## Validation
- `go test ./internal/entity/models -run TestLongCat -count=1`
- `go test -race ./internal/entity/models -run TestLongCat -count=1`
- `go test ./internal/entity -count=1`
- `git diff --check`

## Notes
- Related to the broader Go model provider tracking in infiniflow#14736, but this
PR only handles LongCat model listing.
- `go test ./internal/entity/models -count=1` is currently blocked by an
unrelated Astraflow test panic outside this LongCat change.

---------

Co-authored-by: Jin Hai <[email protected]>
…w#15233)

## Summary
- route hosted MinerU.Net and PaddleOCR.Net provider names to their
existing Go drivers
- add regression coverage for loading the hosted OCR provider configs
through ProviderManager

## What changed
- Added canonical provider-name aliases for the hosted OCR provider
display names.
- Covered both bundled configs with a focused provider-manager test.

## Why
The hosted provider configs use display names with `.Net`, while model
factory dispatch lowercases the provider name. Without aliases, those
configs fall through to `DummyModel` instead of using the existing
MinerU and PaddleOCR drivers.

---------

Co-authored-by: Jin Hai <[email protected]>
### What problem does this PR solve?

v0.25.6 release notes draft updated.

### Type of change

- [x] Documentation Update
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 27, 2026
@coderabbitai

coderabbitai Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

An error occurred during the review process. Please try again later.

📝 Walkthrough

Walkthrough

This PR implements the tenant user invitation API endpoint (POST /api/v1/tenants/:tenant_id/users) with SMTP-based email delivery and configuration support. It also improves PCRE2 build detection to support dynamic linking and environment-based configuration. The change introduces 152 lines of email delivery logic, 67 lines of service-layer invitation logic, 62 lines of handler logic, plus configuration, routing, and test coverage.

Changes

Tenant User Invitation Feature

Layer / File(s) Summary
SMTP Configuration and Response Types
internal/server/config.go, internal/service/tenant.go
Adds SMTPConfig struct for email server/port/TLS/auth/sender configuration and TenantInvitedUserResponse type containing invited user details (ID, email, nickname, optional avatar).
Tenant Service Invitation Logic
internal/service/tenant.go
Extends TenantService with userDAO dependency and implements InviteTenantUser method that validates inputs, enforces current user matches tenant ID, looks up the invitee by email, checks for existing membership with role-based error messaging, creates a UserTenant record with "invite" role and Valid status, and returns user details with error code.
SMTP Email Delivery System
internal/handler/tenant_mail.go
Adds deliverTenantInviteEmail with SMTP config/server validation, plain-text message construction (including tenant ID and frontend URL), conditional auth selection, and branching between implicit TLS and plain SMTP with optional STARTTLS; includes sendMailWithTLS for TLS connection, SMTP client setup, optional auth, sender/recipient setup, and RFC822 message delivery.
Handler Interface and AddTenantUser Endpoint
internal/handler/tenant.go
Introduces tenantService interface for testability, adds AddTenantUserRequest struct, and implements AddTenantUser handler that extracts current user from context, binds JSON input, calls tenantService.InviteTenantUser with tenant_id and user IDs, sends invitation email via sendTenantInviteEmail, and returns standardized JSON response with invited user data or error details.
Routing and Tests
internal/router/router.go, internal/handler/tenant_test.go
Wires POST /api/v1/tenants/:tenant_id/users endpoint to tenantHandler.AddTenantUser; provides unit test with fake tenant service, patches sendTenantInviteEmail to assert email parameters, validates HTTP 200 response, and checks response JSON contains invited user ID and email.

PCRE2 Build and Linking Updates

Layer / File(s) Summary
Build Script PCRE2 Detection and Dynamic Linking
build.sh, internal/binding/rag_analyzer.go
Expands build_go() PCRE2 detection to check for both static (.a) and shared (.so, .so.0) libraries in system paths, Homebrew path on macOS, and treats non-empty CGO_LDFLAGS as sufficient override; changes rag_analyzer.go Linux cgo flags from hardcoded /usr/lib/x86_64-linux-gnu/libpcre2-8.a to dynamic -lpcre2-8 linking.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

  • Implements the missing POST /api/v1/tenants/{tenant_id}/users tenant-member invite endpoint from the Go API rewrite initiative, directly satisfying the feature request to invite users to team/tenant workspaces.

Possibly related PRs

  • infiniflow/ragflow#15009: Both PRs update PCRE2 build setup in build.sh and internal/binding/rag_analyzer.go—this PR broadens detection to include dynamic libraries and environment overrides, while that PR addressed macOS arm64 and Homebrew PCRE2 locations.

Suggested labels

size:M

Poem

🐰 A tenant now may beckon friends with mail,
SMTP swift delivers the invite trail,
Dynamic libraries lighten the build's weight,
Interfaces keep handlers flexible and great!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Out of Scope Changes check ❓ Inconclusive While most changes are in-scope, the build.sh modifications (updating pcre2 dependency checks and linking strategy) appear tangential to the tenant user endpoint feature and could potentially be scope creep. Clarify whether build.sh changes were necessary for this PR or should be submitted separately. If necessary, explain the dependency relationship to the main feature.
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed The PR description is comprehensive and well-structured, covering problem statement, change type, API behavior, implementation proof, and test results.
Linked Issues check ✅ Passed All coding objectives from issue #15240 are met: the POST /api/v1/tenants/<tenant_id>/users endpoint is fully implemented with validation, authorization, email sending, and Python-compatible error handling.
Title check ✅ Passed The title 'feat: Server with Go(Team tenants users POST API)' directly addresses the main implementation: a new POST endpoint for managing team tenant users in the Go server.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/handler/tenant_mail.go`:
- Around line 37-42: The handler currently validates SMTP fields but does not
reject a blank frontend URL, causing successful invites with broken links; add a
required non-empty check for the frontend URL (smtpCfg.MailFrontendURL or the
mail_frontend_url field) alongside the existing SMTP checks (the block that
checks smtpCfg.MailServer, smtpCfg.MailPort, smtpCfg.MailDefaultSender) and
return an error like "mail_frontend_url must be set" if empty; also add the same
validation in the other invite-sending validation path (the second block around
lines 50-56 that mirrors the SMTP checks) so no invite is treated as successful
when the frontend URL is missing.
- Around line 73-111: The SMTP send path blocks on network ops and lacks
timeouts; update both the non-SSL path using smtp.Dial and the SSL path used by
sendMailWithTLS to use dial timeouts and per-operation deadlines: create a
net.Dialer with a sensible Timeout and use it for dialing (smtp non-TLS via
Dialer.Dial and TLS via tls.DialWithDialer), and after creating the smtp.Client
obtain the underlying net.Conn (from client.Text.Conn or the tls.Conn returned
by tls.DialWithDialer) and call SetDeadline (or SetReadDeadline/SetWriteDeadline
before StartTLS/Auth/Data/Write/Quit) so each network operation times out;
change deliverTenantInviteEmail/sendMailWithTLS and the code around smtp.Dial,
client.StartTLS, client.Auth, client.Data, writer.Write and client.Quit to apply
these timeouts.

In `@internal/handler/tenant.go`:
- Around line 237-249: The handler currently returns an error when
sendTenantInviteEmail fails even though InviteTenantUser already committed the
user_tenant row; change the flow in the InviteTenantUser call handling so that
failures from sendTenantInviteEmail do not abort the request or roll back DB
state—capture the error from sendTenantInviteEmail, log it (or enqueue a retry)
and still return the successful invite response (use the previously obtained
result/code) instead of calling jsonError; specifically update the logic around
InviteTenantUser and sendTenantInviteEmail in tenant.go to avoid returning on
SMTP failure and to surface/log the email error for later retry.
- Around line 59-60: Remove the Gin binding constraint on
AddTenantUserRequest.Email so the request body is passed to
TenantService.InviteTenantUser for canonical validation (keep the struct
AddTenantUserRequest but remove `binding:"required"`), and change
TenantHandler.AddTenantUser flow so it does not persist the "invite" user_tenant
row before sending email: first validate the email via
TenantService.InviteTenantUser validation helper (or call a new
ValidateEmail/PrepareInvite method on TenantService), attempt
sendTenantInviteEmail and only on successful SMTP return call
TenantService.InviteTenantUser to create the invite row with role "invite";
ensure errors from the service validation are returned unchanged and that
InviteTenantUser insertion is skipped/rolled back if sendTenantInviteEmail fails
to avoid durable invite rows on SMTP failures.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1ce78879-75d4-4915-a978-fe08aa3dc068

📥 Commits

Reviewing files that changed from the base of the PR and between 129e1e3 and 608c370.

📒 Files selected for processing (9)
  • build.sh
  • internal/binding/rag_analyzer.go
  • internal/handler/tenant.go
  • internal/handler/tenant_mail.go
  • internal/handler/tenant_test.go
  • internal/router/router.go
  • internal/server/config.go
  • internal/service/llm.go
  • internal/service/tenant.go

Comment on lines +37 to +42
if smtpCfg.MailServer == "" || smtpCfg.MailPort == 0 {
return fmt.Errorf("smtp config is incomplete")
}
if len(smtpCfg.MailDefaultSender) < 2 {
return fmt.Errorf("mail_default_sender must include display name and email address")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Reject blank mail_frontend_url before sending.

This email tells the recipient to click a link, but the current validation still sends a "successful" invite when that URL is empty. That leaves the user with a broken onboarding message.

Suggested fix
 	if smtpCfg.MailServer == "" || smtpCfg.MailPort == 0 {
 		return fmt.Errorf("smtp config is incomplete")
 	}
 	if len(smtpCfg.MailDefaultSender) < 2 {
 		return fmt.Errorf("mail_default_sender must include display name and email address")
 	}
+	if strings.TrimSpace(smtpCfg.MailFrontendURL) == "" {
+		return fmt.Errorf("mail_frontend_url is required")
+	}

Also applies to: 50-56

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/handler/tenant_mail.go` around lines 37 - 42, The handler currently
validates SMTP fields but does not reject a blank frontend URL, causing
successful invites with broken links; add a required non-empty check for the
frontend URL (smtpCfg.MailFrontendURL or the mail_frontend_url field) alongside
the existing SMTP checks (the block that checks smtpCfg.MailServer,
smtpCfg.MailPort, smtpCfg.MailDefaultSender) and return an error like
"mail_frontend_url must be set" if empty; also add the same validation in the
other invite-sending validation path (the second block around lines 50-56 that
mirrors the SMTP checks) so no invite is treated as successful when the frontend
URL is missing.

Comment on lines +73 to +111
if smtpCfg.MailUseSSL {
return sendMailWithTLS(address, smtpCfg.MailServer, auth, from.Address, []string{to.Address}, []byte(message))
}

client, err := smtp.Dial(address)
if err != nil {
return err
}
defer client.Close()

if smtpCfg.MailUseTLS {
tlsConfig := &tls.Config{ServerName: smtpCfg.MailServer}
if err := client.StartTLS(tlsConfig); err != nil {
return err
}
}
if auth != nil {
if err := client.Auth(auth); err != nil {
return err
}
}
if err := client.Mail(from.Address); err != nil {
return err
}
if err := client.Rcpt(to.Address); err != nil {
return err
}
writer, err := client.Data()
if err != nil {
return err
}
if _, err := writer.Write([]byte(message)); err != nil {
_ = writer.Close()
return err
}
if err := writer.Close(); err != nil {
return err
}
return client.Quit()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate and print the relevant section of tenant_mail.go with line numbers
FILE="internal/handler/tenant_mail.go"
if [ ! -f "$FILE" ]; then
  echo "Missing file: $FILE" >&2
  exit 1
fi

echo "=== $FILE (lines 1-220) ==="
nl -ba "$FILE" | sed -n '1,220p'

echo
echo "=== Search for sendMailWithTLS and any timeout/deadline usage ==="
rg -n --hidden --no-ignore-vcs "sendMailWithTLS|Timeout|SetDeadline|Dialer|DialWithDialer|Deadline" "$FILE"

Repository: infiniflow/ragflow

Length of output: 178


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="internal/handler/tenant_mail.go"
test -f "$FILE"

echo "=== $FILE (lines 1-220) ==="
cat -n "$FILE" | sed -n '1,220p'

echo
echo "=== Search for sendMailWithTLS and any timeout/deadline usage ==="
rg -n --hidden --no-ignore-vcs "sendMailWithTLS|Timeout|SetDeadline|Dialer|DialWithDialer|Deadline" "$FILE"

Repository: infiniflow/ragflow

Length of output: 5311


Add SMTP dial/IO deadlines to prevent handler hangs
deliverTenantInviteEmail does blocking smtp.Dial / tls.Dial and then StartTLS/Auth/Data/Write/Quit with no timeouts, so a slow/unreachable mail server can tie up the request (non-SSL: 77-111; SSL: 115-151). Add dial timeouts and conn.SetDeadline (or per-operation deadlines) for both code paths.

Suggested direction
 import (
 	"crypto/tls"
 	"fmt"
+	"net"
 	"net/mail"
 	"net/smtp"
 	"ragflow/internal/server"
 	"strings"
+	"time"
 )
+
+const smtpTimeout = 10 * time.Second
@@
-	client, err := smtp.Dial(address)
+	conn, err := (&net.Dialer{Timeout: smtpTimeout}).Dial("tcp", address)
 	if err != nil {
 		return err
 	}
-	defer client.Close()
+	_ = conn.SetDeadline(time.Now().Add(smtpTimeout))
+	client, err := smtp.NewClient(conn, smtpCfg.MailServer)
+	if err != nil {
+		_ = conn.Close()
+		return err
+	}
+	defer client.Close()
@@
-	conn, err := tls.Dial("tcp", addr, &tls.Config{ServerName: host})
+	conn, err := tls.DialWithDialer(
+		&net.Dialer{Timeout: smtpTimeout},
+		"tcp",
+		addr,
+		&tls.Config{ServerName: host},
+	)
 	if err != nil {
 		return err
 	}
 	defer conn.Close()
+	_ = conn.SetDeadline(time.Now().Add(smtpTimeout))
🧰 Tools
🪛 ast-grep (0.42.3)

[warning] 83-83: MinVersionis missing from this TLS configuration. By default, TLS 1.2 is currently used as the minimum when acting as a client, and TLS 1.0 when acting as a server. General purpose web applications should default to TLS 1.3 with all other protocols disabled. Only where it is known that a web server must support legacy clients with unsupported an insecure browsers (such as Internet Explorer 10), it may be necessary to enable TLS 1.0 to provide support. AddMinVersion: tls.VersionTLS13' to the TLS configuration to bump the minimum version to TLS 1.3.
Context: tls.Config{ServerName: smtpCfg.MailServer}
Note: [CWE-327]: Use of a Broken or Risky Cryptographic Algorithm [OWASP A03:2017]: Sensitive Data Exposure [OWASP A02:2021]: Cryptographic Failures [REFERENCES]
https://owasp.org/Top10/A02_2021-Cryptographic_Failures

(missing-ssl-minversion-go)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/handler/tenant_mail.go` around lines 73 - 111, The SMTP send path
blocks on network ops and lacks timeouts; update both the non-SSL path using
smtp.Dial and the SSL path used by sendMailWithTLS to use dial timeouts and
per-operation deadlines: create a net.Dialer with a sensible Timeout and use it
for dialing (smtp non-TLS via Dialer.Dial and TLS via tls.DialWithDialer), and
after creating the smtp.Client obtain the underlying net.Conn (from
client.Text.Conn or the tls.Conn returned by tls.DialWithDialer) and call
SetDeadline (or SetReadDeadline/SetWriteDeadline before
StartTLS/Auth/Data/Write/Quit) so each network operation times out; change
deliverTenantInviteEmail/sendMailWithTLS and the code around smtp.Dial,
client.StartTLS, client.Auth, client.Data, writer.Write and client.Quit to apply
these timeouts.

Comment thread internal/handler/tenant.go Outdated
Comment on lines +59 to +60
type AddTenantUserRequest struct {
Email string `json:"email" binding:"required"`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate relevant files
fd -i "tenant.go" internal | head -n 20
fd -i "tenantservice|inviteTenantUser|sendTenantInviteEmail|jsonError" internal internal/service internal/handler 2>/dev/null || true

# Print key portions of internal/handler/tenant.go around the reported lines
echo "---- internal/handler/tenant.go (lines 1-140) ----"
sed -n '1,140p' internal/handler/tenant.go

echo "---- internal/handler/tenant.go (lines 40-120) ----"
sed -n '40,120p' internal/handler/tenant.go

echo "---- internal/handler/tenant.go (lines 200-280) ----"
sed -n '200,280p' internal/handler/tenant.go

# Search for AddTenantUserRequest usage and gin binding
echo "---- rg AddTenantUserRequest ----"
rg -n "type AddTenantUserRequest|AddTenantUserRequest|binding:\"required\"|ShouldBindJSON\(&req\)" internal/handler/tenant.go internal/handler -S || true

# Search for InviteTenantUser and any "email is required" message
echo "---- rg InviteTenantUser + email error strings ----"
rg -n "InviteTenantUser|email is required|\"email is required\"|json:\"email\"|binding:\"required\"" internal/service internal -S || true

# Search for sendTenantInviteEmail and see sequencing relative to InviteTenantUser
echo "---- rg sendTenantInviteEmail ----"
rg -n "sendTenantInviteEmail|smtp|email" internal/handler internal/service -S || true

Repository: infiniflow/ragflow

Length of output: 38469


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "---- internal/service/tenant.go (InviteTenantUser, lines 260-360) ----"
sed -n '250,360p' internal/service/tenant.go

echo "---- internal/handler/tenant_mail.go (sendTenantInviteEmail, lines 1-220) ----"
sed -n '1,220p' internal/handler/tenant_mail.go

echo "---- internal/handler/tenant.go (AddTenantUser, lines 210-270) ----"
sed -n '210,270p' internal/handler/tenant.go

Repository: infiniflow/ragflow

Length of output: 9455


🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n "func jsonError\\(" -S internal | head -n 20
sed -n '1,220p' internal/handler/error.go 2>/dev/null || true
sed -n '1,260p' internal/handler/handler.go 2>/dev/null || true
rg -n "jsonError\\(c, common\\.CodeDataError, err\\.Error\\(\\)\\)" -S internal/handler/tenant.go internal/handler | head -n 20

Repository: infiniflow/ragflow

Length of output: 3086


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "---- internal/handler/kb.go (jsonError function) ----"
# Find exact line region by printing around the function signature
line=$(rg -n "func jsonError\\(" internal/handler -S | head -n 1 | cut -d: -f1)
echo "jsonError at line: $line"
start=$((line-10))
end=$((line+60))
sed -n "${start},${end}p" internal/handler/kb.go

echo "---- internal/dao/user_tenant.go (FilterByUserIDAndTenantID + role/status handling) ----"
rg -n "FilterByUserIDAndTenantID\\(" internal/dao/user_tenant.go internal/dao -S
sed -n '1,220p' internal/dao/user_tenant.go
sed -n '220,520p' internal/dao/user_tenant.go

Repository: infiniflow/ragflow

Length of output: 222


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# jsonError implementation (get line number correctly)
json_err_line="$(rg -n "func jsonError\\(" internal/handler -S | head -n 1 | cut -d: -f2)"
echo "jsonError line: $json_err_line"
start=$((json_err_line-20))
end=$((json_err_line+80))
sed -n "${start},${end}p" internal/handler/kb.go

# Invite retry semantics: inspect UserTenant entity + DAO query used by InviteTenantUser
echo "---- internal/entity/user_tenant.go ----"
sed -n '1,200p' internal/entity/user_tenant.go

echo "---- internal/dao/user_tenant.go (FilterByUserIDAndTenantID + Create) ----"
rg -n "FilterByUserIDAndTenantID\\(|Create\\(&entity\\.UserTenant|type UserTenantDAO" internal/dao/user_tenant.go -S
sed -n '1,260p' internal/dao/user_tenant.go

Repository: infiniflow/ragflow

Length of output: 10187


Fix AddTenantUser: let service validate missing/empty email and avoid durable invite rows on SMTP failure

binding:"required" on AddTenantUserRequest.Email makes Gin reject {} / {"email":""} before TenantService.InviteTenantUser runs, so the client no longer receives the service’s canonical errors.New("email is required").

TenantHandler.AddTenantUser also calls InviteTenantUser (which inserts user_tenant with role "invite") before sendTenantInviteEmail; if SMTP fails, the invite remains and retries won’t be idempotent.

Suggested fix:

Diff
 type AddTenantUserRequest struct {
-	Email string `json:"email" binding:"required"`
+	Email string `json:"email"`
 }
@@
 	var req AddTenantUserRequest
 	if err := c.ShouldBindJSON(&req); err != nil {
-		jsonError(c, common.CodeDataError, err.Error())
+		jsonError(c, common.CodeDataError, "Invalid request body.")
 		return
 	}

internal/handler/tenant.go

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/handler/tenant.go` around lines 59 - 60, Remove the Gin binding
constraint on AddTenantUserRequest.Email so the request body is passed to
TenantService.InviteTenantUser for canonical validation (keep the struct
AddTenantUserRequest but remove `binding:"required"`), and change
TenantHandler.AddTenantUser flow so it does not persist the "invite" user_tenant
row before sending email: first validate the email via
TenantService.InviteTenantUser validation helper (or call a new
ValidateEmail/PrepareInvite method on TenantService), attempt
sendTenantInviteEmail and only on successful SMTP return call
TenantService.InviteTenantUser to create the invite row with role "invite";
ensure errors from the service validation are returned unchanged and that
InviteTenantUser insertion is skipped/rolled back if sendTenantInviteEmail fails
to avoid durable invite rows on SMTP failures.

Comment on lines +237 to +249
result, code, err := h.tenantService.InviteTenantUser(c.Param("tenant_id"), user.ID, req.Email)
if err != nil {
jsonError(c, code, err.Error())
return
}

inviter := user.Nickname
if inviter == "" {
inviter = user.Email
}
if err := sendTenantInviteEmail(req.Email, req.Email, c.Param("tenant_id"), inviter); err != nil {
jsonError(c, common.CodeServerError, "Failed to send invite email.")
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Don't fail the request after the invite row is already committed.

By the time sendTenantInviteEmail runs, InviteTenantUser has already inserted the user_tenant record. If SMTP fails here, the API returns an error but the persisted invite remains, and the next retry will hit the duplicate/invalid-role path instead of resending.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/handler/tenant.go` around lines 237 - 249, The handler currently
returns an error when sendTenantInviteEmail fails even though InviteTenantUser
already committed the user_tenant row; change the flow in the InviteTenantUser
call handling so that failures from sendTenantInviteEmail do not abort the
request or roll back DB state—capture the error from sendTenantInviteEmail, log
it (or enqueue a retry) and still return the successful invite response (use the
previously obtained result/code) instead of calling jsonError; specifically
update the logic around InviteTenantUser and sendTenantInviteEmail in tenant.go
to avoid returning on SMTP failure and to surface/log the email error for later
retry.

@whitepicker whitepicker changed the title fix: Server with Go(Team tenants users POST API) feat: Server with Go(Team tenants users POST API) May 27, 2026
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 27, 2026
JinHai-CN pushed a commit that referenced this pull request May 28, 2026
## Summary
- Add Go REST support for `GET /api/v1/system/healthz`.
- Return Python-compatible `ok`/`nok` dependency fields for DB, Redis,
document engine, and storage.
- Return HTTP 200 only when all checks pass; otherwise return HTTP 500
with `_meta` failure details.
- Add focused service coverage for the unhealthy dependency response
when Go dependencies are not initialized.

## Scope
This is a small, isolated slice of #15240. It avoids current open
connector PRs (#15274, #15300, #15265, #15264), tenant/member PRs
(#15295, #15301, #15276), MCP PRs (#15281, #15253, #15254, #15260,
#15261, #15262), and the memory-message PR (#15256).

Refs #15240
@JinHai-CN JinHai-CN self-assigned this Sep 2, 2026
@wangq8
wangq8 requested a review from Lynn-Inf September 2, 2026 07:18
@JinHai-CN

Copy link
Copy Markdown
Member

@taillred would you please resolve the conflicts?

@JinHai-CN

Copy link
Copy Markdown
Member

fixed by #19675

@JinHai-CN JinHai-CN closed this Sep 15, 2026
JinHai-CN added a commit that referenced this pull request Sep 15, 2026
refer to #15301

---------

Signed-off-by: Jin Hai <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Implement API of RAGFlow server in Go