Skip to content

feat(i18n): add Brazilian Portuguese (pt-BR) translation - #5238

Closed
giovannimnz wants to merge 13 commits into
QuantumNous:mainfrom
giovannimnz:feat/portuguese-translation
Closed

giovannimnz wants to merge 13 commits into
QuantumNous:mainfrom
giovannimnz:feat/portuguese-translation

Conversation

@giovannimnz

@giovannimnz giovannimnz commented Jun 2, 2026 •

Copy link
Copy Markdown

Summary

Adds complete Brazilian Portuguese (pt-BR) translation to the new-api
frontend and backend, including test infrastructure for i18n
normalization.

What's included

  • Backend: i18n/locales/pt-BR.yaml (265 lines, translated error messages)
  • Frontend: web/default/src/i18n/locales/pt-BR.json (5380 lines, full UI translation)
  • i18n registration: i18n/i18n.go, web/default/src/i18n/config.ts, web/default/src/i18n/languages.ts
  • Test infrastructure: vitest + @testing-library/react setup (web/default/vitest.config.ts, web/default/src/test/setup.ts)
  • Tests: unit tests for normalizeInterfaceLanguage() case-insensitivity + integration test reproducing the user-reported regression

Commits

  1. feat(i18n): add Brazilian Portuguese (pt-BR) translation — backend + frontend + registration
  2. chore(deps): add vitest + testing-library for i18n tests — test toolchain
  3. test(i18n): add normalizeInterfaceLanguage unit + integration tests — covers the case-insensitive lookup bug

Why a third commit for tests

normalizeInterfaceLanguage() in web/default/src/i18n/languages.ts was
case-sensitive: i18next stores 'pt-BR' (mixed case) but the function
lowercased it to 'pt-br' which failed to match any code in
INTERFACE_LANGUAGE_OPTIONS, silently falling back to 'en'. Result:
the language selector on /profile showed English even when
i18n.language was 'pt-BR'. Fixed in commit 1; covered by tests in
commit 3.

Test results

bun run test — 7/7 tests pass (6 unit + 1 integration). One pre-existing
test in the upstream (src/components/ui/dropdown-menu.test.tsx) uses
node:test instead of vitest and is unrelated to this PR.

go build ./i18n/ — clean.

Checklist

  • All new files licensed under the project's existing AGPL-3.0
  • No references to private/fork-specific paths
  • No modifications to README or non-i18n docs
  • 10 files changed, +5,868/-9 — translation only

Summary by CodeRabbit

Release Notes

  • New Features

    • Added Portuguese (Brazil) language support across the application
    • Implemented CJK character stripping feature for model responses
    • Added global channel settings system for feature management
  • Tests

    • Added comprehensive test suite with Vitest for language preferences and normalization verification
  • Chores

    • Updated Docker configuration patterns
    • Added database migration for channel global settings infrastructure

- Backend: i18n/locales/pt-BR.yaml with translated error messages
- Frontend: web/default/src/i18n/locales/pt-BR.json with full UI translation
- i18n.go: add LangPt constant, load pt-BR.yaml, normalizeLang case
- config.ts: register pt-BR in resources and supportedLngs
- languages.ts: add pt-BR entry to INTERFACE_LANGUAGE_OPTIONS
@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

This PR adds Portuguese (Brazil) language support across the backend and frontend, introduces a global CJK-stripping feature with per-channel opt-in, and adds a new FastAPI proxy middleware for model request/response post-processing with docs authentication.

Changes

Portuguese (Brazil) Language Support

Layer / File(s) Summary
Backend Portuguese constants and initialization
i18n/i18n.go, i18n/locales/pt.yaml
LangPt = "pt-BR" constant added, embedded Portuguese translation file loaded during init, pt-BR localizer pre-created, and language normalization maps pt* prefixes to pt-BR. SupportedLanguages() now includes pt-BR.
Frontend i18n registration and normalization
web/default/src/i18n/config.ts, web/default/src/i18n/languages.ts
Imports and registers pt-BR.json locale resources, adds pt-BR to i18next supportedLngs, extends INTERFACE_LANGUAGE_OPTIONS with Portuguese entry, and updates normalizeInterfaceLanguage() to return canonical option codes via case-insensitive matching.
Test infrastructure and test coverage
web/default/vitest.config.ts, web/default/package.json, web/default/src/test/setup.ts, web/default/src/i18n/__tests__/*
Vitest config with jsdom environment and path aliases, test scripts and dev dependencies (Vitest, Testing Library, jsdom), loadI18n() helper for test setup with conditional window.matchMedia stub, and unit tests for language normalization and integration test for LanguagePreferencesCard UI display with Portuguese.

CJK Stripping Global & Channel Settings

Layer / File(s) Summary
DB-backed global settings and cache
model/channel_global_settings.go, model/main.go
New ChannelGlobalSetting model with in-memory RWMutex-protected cache, LoadChannelGlobalSettings() to refresh from DB, GetChannelGlobalSetting(key) with 5-minute staleness refresh, SetChannelGlobalSetting(key, value) to upsert, and GlobalStripCJKEnabled() accessor. Model added to DB AutoMigrate.
Channel settings payload extension
dto/channel_settings.go
Adds StripCJK and UseGlobalStripCJK boolean fields to ChannelSettings struct for JSON serialization.
CJK stripping utility
common/str.go
Adds compiled cjkRegex matching CJK Unicode ranges and exported StripCJK(s string) string helper to remove matched characters.
Middleware and startup integration
main.go, middleware/distributor.go
Main calls LoadChannelGlobalSettings() with best-effort/non-blocking error handling; SetupContextForSelectedChannel applies global strip_cjk override when channel has UseGlobalStripCJK enabled and global feature is active.
Channel settings merge on upstream update
controller/channel_upstream_update.go
updateChannelUpstreamModelSettings() preserves pre-existing unknown keys in channel settings JSON via new mergeChannelSettingsKeepingOthers() helper that unmarshal-merge-remarshal to maintain backwards compatibility.
Database migration for CJK opt-in
docs/migrations/migration_v0.5-cjk-strip-global.sql
Idempotent migration creates channel_global_settings table, upserts strip_cjk=true, and conditionally sets use_global_strip_cjk=true for existing type-35 channels, making global mode the single source of truth.
Relay implementations
relay/channel/claude/relay-claude.go, relay/channel/openai/relay-openai.go
Both relay handlers conditionally apply CJK stripping gated by info.ChannelSetting.StripCJK; Claude includes stripClaudeResponseCJK() helper to safely mutate all text fields; OpenAI applies stripping to streaming chunks and non-stream response choices.
Docker build exclusions
.dockerignore
Adds data/postgres_data, data/pg_backup, and db-data to ignore list.

Model Detailed FastAPI Proxy and Docs

Layer / File(s) Summary
Response text post-processing helpers
integration/middleware/model_detailed_fastapi.py (lines 1–179)
Utilities to remove MiniMax <think> blocks via last closing-tag detection, strip CJK via compiled Unicode regex, normalize markdown code fences, and extract XML fragments. strip_thinking_blocks() parses JSON response bodies for Anthropic and OpenAI formats, conditionally applying thinking removal and CJK stripping to message content fields.
HTTP client and configuration
integration/middleware/model_detailed_fastapi.py (lines 184–519)
Environment-driven constants (port, backend URL, timeout), lazy httpx.AsyncClient creation with connection limits, curated OpenAPI spec loader/cache, and static metadata dictionaries for DeepSeek and MiniMax models.
Session and Basic Auth for docs
integration/middleware/model_detailed_fastapi.py (lines 224–363)
Session-cookie HMAC validation using New-Api-User header, verify_session_or_basic_auth() with fallback to Basic Auth and event-loop-safe thread execution, and verify_basic_auth() raising HTTP 401 when missing/invalid.
Docs routes and OpenAPI serving
integration/middleware/model_detailed_fastapi.py (lines 734–917)
/docs/auth-check endpoint for auth status, protected /docs/ with admin gating and HTML injection, /openapi.json with fallback public spec, /docs/json and /docs.json aliases, /logo.svg static serving, and /docs redirect.
Models endpoints and catch-all proxy
integration/middleware/model_detailed_fastapi.py (lines 615–985)
FastAPI app lifespan (preload spec, init/close HTTP client), /health backend connectivity check, /v1/models and /models with enriched metadata (Anthropic-compatible for MiniMax), and catch-all /{path:path} proxy that forwards to backend while selectively stripping thinking blocks (non-chunked message endpoints) and CJK (all message/chat paths) without breaking chunked SSE responses; includes uvicorn entrypoint.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Browser as Browser/Client
    participant FastAPI as FastAPI Proxy
    participant Backend as New-API Backend
    participant DB as Database

    User->>Browser: Load docs with pt-BR language
    Browser->>FastAPI: GET /docs/ with session cookie
    FastAPI->>FastAPI: validate_session_or_basic_auth()
    FastAPI->>Backend: POST /api/user/self (via HMAC header)
    Backend->>DB: Query user session
    DB-->>Backend: User data
    Backend-->>FastAPI: 200 OK
    FastAPI->>FastAPI: Inject IS_ADMIN flag into HTML
    FastAPI-->>Browser: /docs/ with Scalar UI (pt-BR)
    
    User->>Browser: Request chat completion
    Browser->>FastAPI: POST /v1/chat/completions
    FastAPI->>Backend: Forward to BACKEND_URL
    Backend-->>FastAPI: Response with <think> + CJK
    FastAPI->>FastAPI: strip_thinking_blocks() + StripCJK
    FastAPI-->>Browser: Cleaned response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • QuantumNous/new-api#2842: Extends existing backend i18n language-detection logic (SupportedLanguages, normalizeLang, context/parse functions) to add pt-BR support, building on the retrieved PR's original i18n framework.
  • QuantumNous/new-api#4876: Both PRs modify frontend i18n language normalization/options and language-preferences UI components, with this PR extending support to pt-BR.

Suggested reviewers

  • Calcium-Ion
  • seefs001

Poem

🐰 A rabbit hops through translation lands,
Portuguese and thinking blocks now in hand.
CJK stripped, docs guard with session care,
FastAPI proxies—no broken streams anywhere! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat(i18n): add Brazilian Portuguese (pt-BR) translation' accurately and specifically describes the main change: adding Brazilian Portuguese localization support.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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: 1

🧹 Nitpick comments (2)
web/default/src/features/profile/__tests__/language-preferences-card-integration.test.tsx (1)

46-50: ⚡ Quick win

Prefer React Testing Library queries over direct DOM access.

The test uses document.body and querySelector to verify the select value, which couples the test to implementation details rather than user-visible behavior. As per coding guidelines, React Testing Library should focus on "interactions and behavior rather than implementation details."

♻️ Use RTL queries for better maintainability
-    const container = document.body
-    expect(container.textContent).toContain('Português')
-    // The English label should also be present in the options,
-    // but the *displayed* value should be the Portuguese one.
-    expect(container.querySelector('[data-slot=select-value]')?.textContent).toBe('Português')
+    const { container } = render(
       <I18nextProvider i18n={i18n}>
         <LanguagePreferencesCard profile={null} onProfileUpdate={() => {}} />
       </I18nextProvider>,
     )
+
+    // The select trigger should display "Português"
+    expect(container).toHaveTextContent('Português')
+    
+    // More specific: verify the select value using a semantic query
+    const selectTrigger = container.querySelector('[data-slot=select-value]')
+    expect(selectTrigger).toHaveTextContent('Português')

Alternatively, if the select has an accessible role, prefer:

const selectButton = screen.getByRole('combobox', { name: /interface language/i })
expect(selectButton).toHaveTextContent('Português')
🤖 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
`@web/default/src/features/profile/__tests__/language-preferences-card-integration.test.tsx`
around lines 46 - 50, The test currently inspects document.body and uses
container.querySelector('[data-slot=select-value]') to assert the displayed
language, coupling it to implementation details; replace that DOM access with
React Testing Library queries (use screen.getByRole for the select/combobox with
the accessible name like "Interface language" or screen.getByText / getByRole
for the visible option) and assert its textContent equals "Português", removing
any reliance on document.body, container, or the data-slot selector.
web/default/package.json (1)

94-94: ⚡ Quick win

Consider adding version range prefix for Vitest dependencies.

The Vitest packages are pinned without ^ or ~ prefixes:

  • Line 94: "@vitest/coverage-v8": "3.2.4"
  • Line 108: "vitest": "3.2.4"

As per coding guidelines: "control versions using ^/~; regularly update for security patches". Other devDependencies in this file use ^ (e.g., @testing-library/*, jsdom).

Exact pinning prevents automatic patch updates and is inconsistent with the rest of the dependencies.

📦 Add version range prefix
-    "`@vitest/coverage-v8`": "3.2.4",
+    "`@vitest/coverage-v8`": "^3.2.4",
-    "vitest": "3.2.4"
+    "vitest": "^3.2.4"

Also applies to: 108-108

🤖 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 `@web/default/package.json` at line 94, The Vitest devDependencies are pinned
exactly which prevents patch updates; update the package.json entries for
"`@vitest/coverage-v8`" and "vitest" to use a caret range (e.g., "^3.2.4") so they
follow the project's dependency versioning convention and allow automatic
patch/minor updates; modify the values for the keys "`@vitest/coverage-v8`" and
"vitest" accordingly and run a quick install to verify no lockfile conflicts.
🤖 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 `@web/default/src/test/setup.ts`:
- Line 60: The test's supportedLngs array in setup.ts contains both 'pt-BR' and
'pt', which is inconsistent with the production config's supportedLngs (only
'pt-BR'); update the test to match production by removing 'pt' from the
supportedLngs array in setup.ts, or if 'pt' is intentionally present to exercise
language-normalization behavior, keep it but add a brief inline comment next to
supportedLngs explaining that 'pt' is included intentionally for normalization
tests.

---

Nitpick comments:
In `@web/default/package.json`:
- Line 94: The Vitest devDependencies are pinned exactly which prevents patch
updates; update the package.json entries for "`@vitest/coverage-v8`" and "vitest"
to use a caret range (e.g., "^3.2.4") so they follow the project's dependency
versioning convention and allow automatic patch/minor updates; modify the values
for the keys "`@vitest/coverage-v8`" and "vitest" accordingly and run a quick
install to verify no lockfile conflicts.

In
`@web/default/src/features/profile/__tests__/language-preferences-card-integration.test.tsx`:
- Around line 46-50: The test currently inspects document.body and uses
container.querySelector('[data-slot=select-value]') to assert the displayed
language, coupling it to implementation details; replace that DOM access with
React Testing Library queries (use screen.getByRole for the select/combobox with
the accessible name like "Interface language" or screen.getByText / getByRole
for the visible option) and assert its textContent equals "Português", removing
any reliance on document.body, container, or the data-slot selector.
🪄 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: e91041cc-a551-45a4-8837-c4c1383b13e3

📥 Commits

Reviewing files that changed from the base of the PR and between 0ff9c35 and f1d4c1f.

📒 Files selected for processing (10)
  • i18n/i18n.go
  • i18n/locales/pt-BR.yaml
  • web/default/package.json
  • web/default/src/features/profile/__tests__/language-preferences-card-integration.test.tsx
  • web/default/src/i18n/__tests__/normalize-interface-language.test.ts
  • web/default/src/i18n/config.ts
  • web/default/src/i18n/languages.ts
  • web/default/src/i18n/locales/pt-BR.json
  • web/default/src/test/setup.ts
  • web/default/vitest.config.ts

Comment thread web/default/src/test/setup.ts Resolved
Adds vitest 3.2.4, @testing-library/react 16.3.2, @testing-library/jest-dom,
@testing-library/user-event, @vitest/coverage-v8, jsdom as devDependencies.
Adds test/test:watch/test:coverage scripts to package.json.
Adds vitest.config.ts and src/test/setup.ts (jest-dom matchers).
normalizeInterfaceLanguage() in web/default/src/i18n/languages.ts was
case-sensitive: i18next stores 'pt-BR' (mixed case) but the function
lowercased it to 'pt-br' which failed to match any code in
INTERFACE_LANGUAGE_OPTIONS, silently falling back to 'en'. Result: the
<Select> on /profile showed 'English' even when i18n.language was 'pt-BR'.

Fix in this branch (languages.ts): match case-insensitively against the
option codes, then return the canonical mixed-case code.

Tests:
- normalize-interface-language.test.ts: 6 unit tests covering exact
  matches, case-insensitive matches (PT-BR, pt-br, Pt-Br), underscored
  variants (pt_BR), zh variants, unknown fallback, empty/null/undefined
- language-preferences-card-integration.test.tsx: 1 integration test
  rendering LanguagePreferencesCard with lng=pt-BR and asserting the
  select trigger shows 'Português' (not 'English')
@giovannimnz
giovannimnz force-pushed the feat/portuguese-translation branch from f1d4c1f to a387c05 Compare June 2, 2026 04:25
@giovannimnz

Copy link
Copy Markdown
Author

CodeRabbit feedback addressed in latest push:

1. web/default/src/test/setup.ts:60 — 'pt' in supportedLngs
Kept 'pt' but added a 4-line inline comment explaining the rationale: it's
included to exercise language normalization ('pt' -> 'pt-BR') in tests.
Production config.ts exposes only 'pt-BR'; i18next resolves 'pt' to
'pt-BR' via the pt-BR resources entry.

2. web/default/package.json:94,108 — Vitest pinned without caret
Fixed: both @vitest/coverage-v8 and vitest now use ^3.2.4, matching
the convention used by all other devDependencies in the file (^ for caret,
~ for ~).

3. language-preferences-card-integration.test.tsx:46-50 — DOM access
Replaced document.body + querySelector('[data-slot=select-value]')
with screen.getByRole('combobox'). Note: Base UI's <Select.Trigger>
renders as <button role="combobox"> without an accessible name
(aria-labelledby is not auto-applied), so the role-only query is the
right level of abstraction here. The internal data-slot attribute is no
longer referenced.

All 7 tests pass. go build ./i18n/ is clean. Diff stays at 10 files,
+5,871/-9.

Re-requesting review.

Giovanni Muniz and others added 2 commits June 2, 2026 01:30
Coverage gaps closed:
1. relay/channel/claude/relay-claude.go: ClaudeHandler (non-stream) and
   HandleStreamResponseData (stream) now strip CJK. Was 100% leak before.
2. integration/middleware/model_detailed_fastapi.py: CJK strip now applies
   to BOTH streaming and non-streaming responses (was gated on non-stream
   only). Thinking-block strip still requires non-stream (legit reason:
   blocks can span chunks), but CJK is per-chunk safe.
3. Regex extended to cover Hiragana (U+3040-U+309F), Katakana
   (U+30A0-U+30FF, U+31F0-U+31FF), and Hangul Syllables (U+AC00-U+D7AF).
   Was missing all Japanese kana and Korean.

Global key infrastructure:
- model/channel_global_settings.go: new table (key, value, updated_at)
  with in-memory cache (5min refresh) and convenience helpers
  (GlobalStripCJKEnabled, SetChannelGlobalSetting).
- model/main.go: AutoMigrate adds the new table.
- main.go: cache loaded at startup alongside InitChannelCache.
- dto/channel_settings.go: new UseGlobalStripCJK bool field.
- middleware/distributor.go: when channel has use_global_strip_cjk=true
  AND global strip_cjk=true, force channel's strip_cjk to true.

DB activation (migration v0.5):
- docs/migrations/migration_v0.5-cjk-strip-global.sql: creates table,
  inserts strip_cjk=true global, and opts channel type=35 (MiniMax)
  into use_global_strip_cjk. Idempotent.

Source of truth verified against:
- relay/channel/claude/relay-claude.go:789,895 (was 0 StripCJK calls)
- common/str.go:22-25 (regex)
- integration/middleware/model_detailed_fastapi.py:949 (was stream skip)
- dto/channel_settings.go:3-10 (struct)
…model update

The upstream model update task serializes ChannelOtherSettings back to
channel.settings, which silently overwrites any external keys (e.g.
use_global_strip_cjk) that aren't part of the typed struct.

Fix: capture pre-update raw JSON, then merge it with the new struct fields
via mergeChannelSettingsKeepingOthers. Keys present in both keep the new
value (managed); keys only in the stored map are preserved (external).

Without this fix, the upstream model update would wipe use_global_strip_cjk
on the MiniMax channel within the first 30 minutes of operation, defeating
the global strip_cjk key.

@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: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
docs/migrations/migration_v0.5-cjk-strip-global.sql (1)

1-42: ⚠️ Potential issue | 🔴 Critical | 🏗️ Heavy lift

Migration uses PostgreSQL-only syntax; will fail on MySQL and SQLite.

This migration violates the multi-database compatibility requirement. It uses PostgreSQL-specific constructs throughout:

Lines PostgreSQL-only syntax Issue
20–21 EXTRACT(EPOCH FROM NOW())::bigint, ON CONFLICT ... DO UPDATE MySQL uses ON DUPLICATE KEY UPDATE; SQLite has limited upsert
27–31 ::jsonb cast, jsonb_set(), ? operator, ->>' Forbidden JSONB operators per guidelines
36–41 Same JSONB operations Same issue

Recommended approaches:

  1. Separate migration files per DB — e.g., migration_v0.5-cjk-strip-global-postgres.sql, migration_v0.5-cjk-strip-global-mysql.sql, etc.

  2. GORM-based migration in Go — Use GORM's Migrator with the common.UsingPostgreSQL, common.UsingMySQL, common.UsingSQLite flags to branch DB-specific logic, keeping the migration within the application where the DB type is known.

  3. Application-level data migration — Run the settings update logic through GORM methods (fetch channels, unmarshal settings JSON with common.Unmarshal, modify, persist) which handles cross-DB compatibility automatically.

As per coding guidelines: "All database code MUST be fully compatible with SQLite, MySQL >= 5.7.8, and PostgreSQL >= 9.6 simultaneously" and "Forbidden database patterns: ... PostgreSQL-only operators (e.g., @>, ?, JSONB operators)".

🤖 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 `@docs/migrations/migration_v0.5-cjk-strip-global.sql` around lines 1 - 42, The
SQL migration uses PostgreSQL-only constructs (EXTRACT(...)::bigint, ON
CONFLICT, ::jsonb, jsonb_set, ? and ->> operators) and must be replaced with a
multi-DB safe approach: either split into DB-specific SQL files (e.g.,
migration_v0.5-cjk-strip-global-postgres.sql and MySQL/SQLite variants) or,
preferably, convert this migration into a GORM-based migration that runs at
runtime and branches on DB type (use
common.UsingPostgreSQL/common.UsingMySQL/common.UsingSQLite) — implement
creation of the channel_global_settings record (`key='strip_cjk'`) and then
perform the channels settings updates by loading Channel rows via GORM, using
common.Unmarshal to parse settings, set use_global_strip_cjk=true for channels
with type=35 and for those with existing strip_cjk=true, then marshal and Save
back; reference table/key names: channel_global_settings, channels, settings,
strip_cjk, use_global_strip_cjk.
🧹 Nitpick comments (6)
model/channel_global_settings.go (1)

22-22: 💤 Low value

Malformed GORM tag: gorm:"bigint" is not a valid directive.

GORM tags are key or key:value; a bare bigint is treated as an unknown tag and ignored. The column already maps to bigint because the field is int64, so there's no functional impact, but the tag is misleading. Also note UpdatedAt is a GORM auto-managed timestamp field, so it's set automatically on Save in addition to your manual assignment in SetChannelGlobalSetting.

♻️ Suggested fix
-	UpdatedAt int64  `json:"updated_at" gorm:"bigint"`
+	UpdatedAt int64  `json:"updated_at" gorm:"type:bigint"`
🤖 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 `@model/channel_global_settings.go` at line 22, Remove the invalid GORM tag on
the UpdatedAt field in the ChannelGlobalSettings struct (replace `UpdatedAt
int64  `json:"updated_at" gorm:"bigint"` with a plain field tag or only the json
tag) and stop manually setting UpdatedAt in the SetChannelGlobalSetting function
so GORM can manage the timestamp automatically; locate the UpdatedAt field in
model/channel_global_settings.go and the SetChannelGlobalSetting method where
UpdatedAt is being assigned and remove that manual assignment.
common/str.go (1)

22-26: 💤 Low value

cjkRegex coverage is partial — some CJK ranges are not stripped.

The documented ranges cover the common cases, but a few notable CJK blocks are missing: CJK Compatibility Ideographs (\x{f900}-\x{faff}), Hangul Jamo / Compatibility Jamo (\x{1100}-\x{11ff}, \x{3130}-\x{318f}), and supplementary-plane ideographs such as CJK Extension B+ (\x{20000}-\x{2fa1f}). For the stated MiniMax use case the current set is likely sufficient, but characters in these blocks will pass through unstripped. Worth confirming whether that's acceptable.

Also applies to: 278-280

🤖 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 `@common/str.go` around lines 22 - 26, cjkRegex currently omits several CJK
Unicode blocks (e.g., CJK Compatibility Ideographs, Hangul Jamo/Compatibility
Jamo, and supplementary-plane CJK Extension B+) so characters from those ranges
are not stripped; update the implementation referenced by cjkRegex to include
the missing ranges (\x{f900}-\x{faff}, \x{1100}-\x{11ff}, \x{3130}-\x{318f}, and
the supplementary-plane range \x{20000}-\x{2fa1f}) or replace the regex with a
rune-based filter that uses unicode.RangeTable/unicode.In to reliably detect all
CJK blocks (ensuring handling of code points beyond the BMP). Ensure the chosen
approach correctly handles supplementary-plane code points supported by Go's
regexp or by iterating runes.
integration/middleware/model_detailed_fastapi.py (4)

961-970: 💤 Low value

Dead code: response_content is always bytes here.

response.content is always bytes. The else branches at lines 964-965 and 969-970 are unreachable.

♻️ Simplified version
         if path.startswith("v1/messages") or path.startswith("v1/chat") or path.startswith("v1/responses"):
             try:
-                if isinstance(response_content, (bytes, bytearray)):
-                    decoded = response_content.decode("utf-8", errors="ignore")
-                else:
-                    decoded = response_content
+                decoded = response_content.decode("utf-8", errors="ignore")
                 cleaned = strip_cjk_from_text(decoded)
-                if isinstance(response_content, (bytes, bytearray)):
-                    response_content = cleaned.encode("utf-8")
-                else:
-                    response_content = cleaned
+                response_content = cleaned.encode("utf-8")
             except Exception as e:
🤖 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 `@integration/middleware/model_detailed_fastapi.py` around lines 961 - 970, The
branches treating response_content as non-bytes are dead because
response.content is always bytes; update the block around
response_content/strip_cjk_from_text to treat it as bytes only: decode
response_content to a string, call strip_cjk_from_text(decoded), then re-encode
the cleaned string back to bytes and assign to response_content (referencing the
response_content variable and strip_cjk_from_text function to locate the code),
removing the unreachable else branches.

140-150: 💤 Low value

Unconditional modified = True causes unnecessary re-serialization.

modified is set to True at line 146 for every text block, even when the text is unchanged after processing. This triggers re-serialization even when the response body is identical.

♻️ Track actual modifications
             text = strip_cjk_from_text(text)
-            block = dict(block)
-            block["text"] = text
-            modified = True
-            new_content.append(block)
+            if block.get("text") != text:
+                block = dict(block)
+                block["text"] = text
+                modified = True
+                new_content.append(block)
+            else:
+                new_content.append(block)
🤖 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 `@integration/middleware/model_detailed_fastapi.py` around lines 140 - 150, The
code currently sets modified = True unconditionally inside the loop, causing
re-serialization even when text hasn't changed; in the loop that processes each
block (the dict named block, variable text) before calling strip_cjk_from_text
and the regex trimming, save the original_text, run the existing transformations
(regex and strip_cjk_from_text) into a new text variable, then only set modified
= True and update block["text"] when new_text != original_text; keep appending
either the original block or the updated block to new_content accordingly, and
only replace data["content"] with new_content if modified remains True so that
json.dumps(...) / .encode("utf-8") is avoided when the body is identical.

867-904: 💤 Low value

Dead code: auth checks don't gate access.

The function performs session and Basic Auth validation but serves the spec regardless (lines 900-904). The auth checks at lines 867-898 are redundant since access is always granted.

Either remove the unused auth logic, or return the spec immediately after successful auth checks to avoid redundant validation:

♻️ Simplified version (if truly public)
 `@app.get`("/openapi.json", include_in_schema=False)
 async def get_openapi_json(request: Request):
-    """
-    Serve curated OpenAPI spec (PUBLIC).
-    
-    Anyone can access the OpenAPI spec. ?key=<DOCS_PASSWORD> for full spec.
-    """
-    # Quick admin bypass: ?key=<DOCS_PASSWORD>
-    provided_key = request.query_params.get("key", "")
-    if provided_key == DOCS_PASSWORD:
-        spec = load_curated_spec()
-        if spec is None:
-            raise HTTPException(status_code=404, detail="OpenAPI spec not found")
-        return JSONResponse(content=spec)
-
-    # Try session validation first
-    session_cookie = get_session_cookie(request)
-    if session_cookie:
-        is_valid = await validate_session_cookie(session_cookie)
-        if is_valid:
-            spec = load_curated_spec()
-            if spec is None:
-                raise HTTPException(status_code=404, detail="OpenAPI spec not found")
-            return JSONResponse(content=spec)
-
-    # Fall back to Basic Auth
-    auth_header = request.headers.get("authorization", "")
-    if auth_header.startswith("Basic "):
-        import base64
-        try:
-            creds = base64.b64decode(auth_header[6:]).decode("utf-8")
-            username, password = creds.split(":", 1)
-            if username == DOCS_USERNAME and password == DOCS_PASSWORD:
-                spec = load_curated_spec()
-                if spec is None:
-                    raise HTTPException(status_code=404, detail="OpenAPI spec not found")
-                return JSONResponse(content=spec)
-        except Exception:
-            pass
-
-    # Not authenticated — serve spec anyway (public)
+    """Serve curated OpenAPI spec (PUBLIC)."""
     spec = load_curated_spec()
     if spec is None:
         raise HTTPException(status_code=404, detail="OpenAPI spec not found")
     return JSONResponse(content=spec)
🤖 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 `@integration/middleware/model_detailed_fastapi.py` around lines 867 - 904, The
auth branches (provided_key, get_session_cookie/validate_session_cookie, Basic
auth via auth_header) are dead because the handler unconditionally loads and
returns load_curated_spec() at the end; either delete the unused auth logic or
enforce gating: after checking provided_key, session_cookie/is_valid, and Basic
auth (DOCS_USERNAME/DOCS_PASSWORD) return the spec as you already do, otherwise
raise HTTPException(status_code=401) (or 403) instead of falling through to the
final public return; adjust code paths around provided_key, get_session_cookie,
validate_session_cookie, auth_header, load_curated_spec so that an
unauthenticated request does not reach the final JSONResponse when the intent is
to restrict access.

224-224: 💤 Low value

Consolidate imports at file top.

Several imports are scattered through the file (line 224, 291, 311, 323, 778, 815, 888). Consider moving to the top for clarity.

🤖 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 `@integration/middleware/model_detailed_fastapi.py` at line 224, Move the
scattered imports (e.g. the line importing hmac, hashlib, base64, struct, time
as _time) to the top of the module and remove duplicate imports elsewhere so all
imports are consolidated and follow PEP8 ordering; locate uses of these modules
(functions that call hmac, hashlib, base64, struct or use _time) to ensure no
name/alias changes break references when you centralize them.
🤖 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 `@controller/channel_upstream_update.go`:
- Around line 1014-1040: The function mergeChannelSettingsKeepingOthers
currently logs but continues when Unmarshal of storedRaw fails, causing silent
loss of unknown keys; change the behavior in mergeChannelSettingsKeepingOthers
so that if common.Unmarshal into storedMap returns an error (when storedRaw !=
""), immediately log the error and return string(newBytes) (i.e., the canonical
new settings) instead of proceeding with a nil storedMap—use the existing
newBytes/newMap flow to produce the returned canonical JSON and ensure the error
is logged with context.

In `@integration/middleware/model_detailed_fastapi.py`:
- Around line 30-31: The THINK_CLOSE constant is incorrect (set to "</final>")
which prevents strip_thinking_from_text from finding </think> tags; change
THINK_CLOSE to "</think>" so it matches THINK_OPEN ("<think>") and the
docstring, and verify the strip_thinking_from_text function and its
docstring/reference use THINK_OPEN/THINK_CLOSE symbols consistently (update any
mismatched docstring text if needed).
- Around line 301-339: The verify_session_or_basic_auth function should be
converted to an async FastAPI dependency (change signature to async def
verify_session_or_basic_auth(...)) and await the existing
validate_session_cookie(session_cookie) instead of using
ThreadPoolExecutor/asyncio.run; if await validate_session_cookie(session_cookie)
returns True return "session". After that, perform an actual Basic Auth check
(use the project's existing basic credential verifier or FastAPI's HTTPBasic
utilities) and return "basic" only when credentials are valid; if neither
session nor basic auth succeed raise fastapi.HTTPException(status_code=401).
Update all call sites/dependencies to accept the async dependency if needed.
- Around line 236-244: The length check for the decoded cookie is off: the code
slices data up to data[24:56] (reading bytes 0–55) but currently requires
len(data) >= 58; change the guard to require at least 56 bytes instead of 58. In
the cookie-parsing block that decodes cookie_value with base64.b64decode and
unpacks created_at, user_id, nonce, and sig, replace the len(data) < 58 check
with len(data) < 56 so valid 56-byte payloads (used by created_at, user_id,
nonce, sig) are accepted.
- Around line 258-264: The HMAC is constructed with the wrong argument order so
SESSION_SECRET is never used; update the signature computation (sig) to call
hmac.new with the secret as the key and the packed message as the data (i.e.,
key=SESSION_SECRET, msg=msg, digestmod=hashlib.sha256), ensuring SESSION_SECRET
is a bytes object (encode if it's a string) and keep using msg, nonce, and
hashlib.sha256 as before; adjust any related variable names (msg, nonce,
SESSION_SECRET) accordingly so the generated sig uses the secret key.

In `@model/channel_global_settings.go`:
- Around line 54-64: GetChannelGlobalSetting currently discards
LoadChannelGlobalSettings errors and lets many concurrent callers trigger
reloads after expiry; fix it by introducing a single-flight guard around
LoadChannelGlobalSettings so only one goroutine performs the full-table reload
(use golang.org/x/sync/singleflight or an equivalent mutex+condition) and return
the result to waiters, stop discarding the returned error (propagate or at least
log it via processLogger or similar), and on any load attempt advance
globalSettingsLoaded (or set a short backoff timestamp) before/when calling
LoadChannelGlobalSettings to avoid per-request retry storms; update code paths
referencing globalSettingsLoaded, globalSettingsLock, GetChannelGlobalSetting,
and LoadChannelGlobalSettings accordingly.

---

Outside diff comments:
In `@docs/migrations/migration_v0.5-cjk-strip-global.sql`:
- Around line 1-42: The SQL migration uses PostgreSQL-only constructs
(EXTRACT(...)::bigint, ON CONFLICT, ::jsonb, jsonb_set, ? and ->> operators) and
must be replaced with a multi-DB safe approach: either split into DB-specific
SQL files (e.g., migration_v0.5-cjk-strip-global-postgres.sql and MySQL/SQLite
variants) or, preferably, convert this migration into a GORM-based migration
that runs at runtime and branches on DB type (use
common.UsingPostgreSQL/common.UsingMySQL/common.UsingSQLite) — implement
creation of the channel_global_settings record (`key='strip_cjk'`) and then
perform the channels settings updates by loading Channel rows via GORM, using
common.Unmarshal to parse settings, set use_global_strip_cjk=true for channels
with type=35 and for those with existing strip_cjk=true, then marshal and Save
back; reference table/key names: channel_global_settings, channels, settings,
strip_cjk, use_global_strip_cjk.

---

Nitpick comments:
In `@common/str.go`:
- Around line 22-26: cjkRegex currently omits several CJK Unicode blocks (e.g.,
CJK Compatibility Ideographs, Hangul Jamo/Compatibility Jamo, and
supplementary-plane CJK Extension B+) so characters from those ranges are not
stripped; update the implementation referenced by cjkRegex to include the
missing ranges (\x{f900}-\x{faff}, \x{1100}-\x{11ff}, \x{3130}-\x{318f}, and the
supplementary-plane range \x{20000}-\x{2fa1f}) or replace the regex with a
rune-based filter that uses unicode.RangeTable/unicode.In to reliably detect all
CJK blocks (ensuring handling of code points beyond the BMP). Ensure the chosen
approach correctly handles supplementary-plane code points supported by Go's
regexp or by iterating runes.

In `@integration/middleware/model_detailed_fastapi.py`:
- Around line 961-970: The branches treating response_content as non-bytes are
dead because response.content is always bytes; update the block around
response_content/strip_cjk_from_text to treat it as bytes only: decode
response_content to a string, call strip_cjk_from_text(decoded), then re-encode
the cleaned string back to bytes and assign to response_content (referencing the
response_content variable and strip_cjk_from_text function to locate the code),
removing the unreachable else branches.
- Around line 140-150: The code currently sets modified = True unconditionally
inside the loop, causing re-serialization even when text hasn't changed; in the
loop that processes each block (the dict named block, variable text) before
calling strip_cjk_from_text and the regex trimming, save the original_text, run
the existing transformations (regex and strip_cjk_from_text) into a new text
variable, then only set modified = True and update block["text"] when new_text
!= original_text; keep appending either the original block or the updated block
to new_content accordingly, and only replace data["content"] with new_content if
modified remains True so that json.dumps(...) / .encode("utf-8") is avoided when
the body is identical.
- Around line 867-904: The auth branches (provided_key,
get_session_cookie/validate_session_cookie, Basic auth via auth_header) are dead
because the handler unconditionally loads and returns load_curated_spec() at the
end; either delete the unused auth logic or enforce gating: after checking
provided_key, session_cookie/is_valid, and Basic auth
(DOCS_USERNAME/DOCS_PASSWORD) return the spec as you already do, otherwise raise
HTTPException(status_code=401) (or 403) instead of falling through to the final
public return; adjust code paths around provided_key, get_session_cookie,
validate_session_cookie, auth_header, load_curated_spec so that an
unauthenticated request does not reach the final JSONResponse when the intent is
to restrict access.
- Line 224: Move the scattered imports (e.g. the line importing hmac, hashlib,
base64, struct, time as _time) to the top of the module and remove duplicate
imports elsewhere so all imports are consolidated and follow PEP8 ordering;
locate uses of these modules (functions that call hmac, hashlib, base64, struct
or use _time) to ensure no name/alias changes break references when you
centralize them.

In `@model/channel_global_settings.go`:
- Line 22: Remove the invalid GORM tag on the UpdatedAt field in the
ChannelGlobalSettings struct (replace `UpdatedAt int64  `json:"updated_at"
gorm:"bigint"` with a plain field tag or only the json tag) and stop manually
setting UpdatedAt in the SetChannelGlobalSetting function so GORM can manage the
timestamp automatically; locate the UpdatedAt field in
model/channel_global_settings.go and the SetChannelGlobalSetting method where
UpdatedAt is being assigned and remove that manual assignment.
🪄 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: 1c4c863a-24c6-4ed9-8cd9-27798134bfa4

📥 Commits

Reviewing files that changed from the base of the PR and between a387c05 and 2f7ad9b.

📒 Files selected for processing (12)
  • .dockerignore
  • common/str.go
  • controller/channel_upstream_update.go
  • docs/migrations/migration_v0.5-cjk-strip-global.sql
  • dto/channel_settings.go
  • integration/middleware/model_detailed_fastapi.py
  • main.go
  • middleware/distributor.go
  • model/channel_global_settings.go
  • model/main.go
  • relay/channel/claude/relay-claude.go
  • relay/channel/openai/relay-openai.go
✅ Files skipped from review due to trivial changes (1)
  • .dockerignore

Comment on lines +1014 to +1040
func mergeChannelSettingsKeepingOthers(storedRaw string, newChannelOtherSettings dto.ChannelOtherSettings) string {
var storedMap map[string]interface{}
if storedRaw != "" {
if err := common.Unmarshal([]byte(storedRaw), &storedMap); err != nil {
common.SysLog(fmt.Sprintf("mergeChannelSettingsKeepingOthers: stored unmarshal failed: %v", err))
}
}
newBytes, err := common.Marshal(newChannelOtherSettings)
if err != nil {
return storedRaw
}
var newMap map[string]interface{}
if err := common.Unmarshal(newBytes, &newMap); err != nil {
return string(newBytes)
}
if storedMap == nil {
storedMap = map[string]interface{}{}
}
for k, v := range newMap {
storedMap[k] = v
}
out, err := common.Marshal(storedMap)
if err != nil {
return string(newBytes)
}
return string(out)
}

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 | 🟡 Minor | ⚡ Quick win

Minor: Potential data loss when stored JSON is corrupted.

If the stored settings JSON (storedRaw) is corrupted and unmarshal fails at line 1017, the function logs the error but continues with storedMap = nil. Line 1030 then initializes an empty map, and the final merge will contain only the canonical ChannelOtherSettings keys, silently dropping any unknown keys that existed in the corrupted JSON.

While this scenario is rare (requires database corruption), consider an additional fallback:

 func mergeChannelSettingsKeepingOthers(storedRaw string, newChannelOtherSettings dto.ChannelOtherSettings) string {
 	var storedMap map[string]interface{}
 	if storedRaw != "" {
 		if err := common.Unmarshal([]byte(storedRaw), &storedMap); err != nil {
 			common.SysLog(fmt.Sprintf("mergeChannelSettingsKeepingOthers: stored unmarshal failed: %v", err))
+			// If stored JSON is corrupted, return only the new struct to avoid
+			// silent data loss. Admin can recover unknown keys from DB backups.
+			newBytes, mErr := common.Marshal(newChannelOtherSettings)
+			if mErr != nil {
+				return storedRaw
+			}
+			return string(newBytes)
 		}
 	}

This makes the data-loss explicit: if stored JSON is corrupted, we return only the new canonical fields and log the issue.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func mergeChannelSettingsKeepingOthers(storedRaw string, newChannelOtherSettings dto.ChannelOtherSettings) string {
var storedMap map[string]interface{}
if storedRaw != "" {
if err := common.Unmarshal([]byte(storedRaw), &storedMap); err != nil {
common.SysLog(fmt.Sprintf("mergeChannelSettingsKeepingOthers: stored unmarshal failed: %v", err))
}
}
newBytes, err := common.Marshal(newChannelOtherSettings)
if err != nil {
return storedRaw
}
var newMap map[string]interface{}
if err := common.Unmarshal(newBytes, &newMap); err != nil {
return string(newBytes)
}
if storedMap == nil {
storedMap = map[string]interface{}{}
}
for k, v := range newMap {
storedMap[k] = v
}
out, err := common.Marshal(storedMap)
if err != nil {
return string(newBytes)
}
return string(out)
}
func mergeChannelSettingsKeepingOthers(storedRaw string, newChannelOtherSettings dto.ChannelOtherSettings) string {
var storedMap map[string]interface{}
if storedRaw != "" {
if err := common.Unmarshal([]byte(storedRaw), &storedMap); err != nil {
common.SysLog(fmt.Sprintf("mergeChannelSettingsKeepingOthers: stored unmarshal failed: %v", err))
// If stored JSON is corrupted, return only the new struct to avoid
// silent data loss. Admin can recover unknown keys from DB backups.
newBytes, mErr := common.Marshal(newChannelOtherSettings)
if mErr != nil {
return storedRaw
}
return string(newBytes)
}
}
newBytes, err := common.Marshal(newChannelOtherSettings)
if err != nil {
return storedRaw
}
var newMap map[string]interface{}
if err := common.Unmarshal(newBytes, &newMap); err != nil {
return string(newBytes)
}
if storedMap == nil {
storedMap = map[string]interface{}{}
}
for k, v := range newMap {
storedMap[k] = v
}
out, err := common.Marshal(storedMap)
if err != nil {
return string(newBytes)
}
return string(out)
}
🤖 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 `@controller/channel_upstream_update.go` around lines 1014 - 1040, The function
mergeChannelSettingsKeepingOthers currently logs but continues when Unmarshal of
storedRaw fails, causing silent loss of unknown keys; change the behavior in
mergeChannelSettingsKeepingOthers so that if common.Unmarshal into storedMap
returns an error (when storedRaw != ""), immediately log the error and return
string(newBytes) (i.e., the canonical new settings) instead of proceeding with a
nil storedMap—use the existing newBytes/newMap flow to produce the returned
canonical JSON and ensure the error is logged with context.

Comment on lines +30 to +31
THINK_CLOSE = "</final>"
THINK_OPEN = "<think>"

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 | 🔴 Critical | ⚡ Quick win

Critical: THINK_CLOSE constant doesn't match documented behavior.

THINK_CLOSE = "</final>" but the docstring (line 49) states the function "Finds the LAST closing </think> tag". This mismatch means strip_thinking_from_text() will never find </think> tags — it searches for </final> instead.

If the intent is to strip <think>...</think> blocks:

🐛 Proposed fix
-THINK_CLOSE = "</final>"
+THINK_CLOSE = "</think>"
 THINK_OPEN = "<think>"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
THINK_CLOSE = "</final>"
THINK_OPEN = "<think>"
THINK_CLOSE = "</think>"
THINK_OPEN = "<think>"
🤖 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 `@integration/middleware/model_detailed_fastapi.py` around lines 30 - 31, The
THINK_CLOSE constant is incorrect (set to "</final>") which prevents
strip_thinking_from_text from finding </think> tags; change THINK_CLOSE to
"</think>" so it matches THINK_OPEN ("<think>") and the docstring, and verify
the strip_thinking_from_text function and its docstring/reference use
THINK_OPEN/THINK_CLOSE symbols consistently (update any mismatched docstring
text if needed).

Comment on lines +236 to +244
try:
data = base64.b64decode(cookie_value)
if len(data) < 58:
return None
created_at = struct.unpack(">I", data[0:4])[0]
user_id = struct.unpack(">I", data[4:8])[0]
nonce = data[8:24]
sig = data[24:56]
return user_id, created_at, nonce

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 | 🟡 Minor | ⚡ Quick win

❓ Verification inconclusive

🏁 Script executed:

#!/bin/bash
# Search for session cookie encoding in Go backend
rg -n "session.*cookie|base64.*encode" --type=go -C 3 | head -50

Repository: QuantumNous/new-api

Length of output: 1989


Bounds check likely mismatched with cookie parsing (needs 56 bytes, not 58)

In integration/middleware/model_detailed_fastapi.py (lines 236-244), the parser reads up to data[24:56], so it only requires at least 56 bytes (0:4, 4:8, 8:24, 24:56). The guard len(data) < 58 would reject a valid 56-byte cookie unless the cookie format intentionally includes 2 extra trailing bytes/padding.

🐛 Proposed fix (if cookie payload is exactly 56 bytes)
-        if len(data) < 58:
+        if len(data) < 56:
             return None
🤖 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 `@integration/middleware/model_detailed_fastapi.py` around lines 236 - 244, The
length check for the decoded cookie is off: the code slices data up to
data[24:56] (reading bytes 0–55) but currently requires len(data) >= 58; change
the guard to require at least 56 bytes instead of 58. In the cookie-parsing
block that decodes cookie_value with base64.b64decode and unpacks created_at,
user_id, nonce, and sig, replace the len(data) < 58 check with len(data) < 56 so
valid 56-byte payloads (used by created_at, user_id, nonce, sig) are accepted.

Comment on lines +258 to +264
# Compute HMAC: HMAC-SHA256(key=SESSION_SECRET, data=binary(user_id+created_at), salt=nonce)
msg = struct.pack(">II", user_id, created_at)
sig = hmac.new(msg, nonce, hashlib.sha256).digest()

# Encode: user_id(4 bytes BE) + created_at(4 bytes BE) + nonce + sig
payload = struct.pack(">II", user_id, created_at) + nonce + sig
return base64.b64encode(payload).decode()

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 | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for New-Api-User header generation/validation in Go backend
rg -n "New-Api-User" --type=go -C 5

Repository: QuantumNous/new-api

Length of output: 1989


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="integration/middleware/model_detailed_fastapi.py"

# Show the suspected encode logic around the reported lines
echo "---- $FILE: lines 230-290 ----"
nl -ba "$FILE" | sed -n '230,290p'

# Search for all hmac.new usages in the repo
echo "---- rg hmac.new ----"
rg -n "hmac\.new" .

# Search for decode of New-Api-User / session cookie logic
echo "---- rg _decode_session_cookie / session cookie / new-api-user ----"
rg -n "_decode_session_cookie|session cookie|New-Api-User|New-Api-User" integration/middleware/model_detailed_fastapi.py

Repository: QuantumNous/new-api

Length of output: 1960


🏁 Script executed:

#!/bin/bash
set -euo pipefail
FILE="integration/middleware/model_detailed_fastapi.py"

echo "---- $FILE: lines 200-320 ----"
nl -ba "$FILE" | sed -n '200,320p'

echo "---- $FILE: where SESSION_SECRET is used ----"
rg -n "SESSION_SECRET" "$FILE"

echo "---- $FILE: hmac.new call(s) ----"
rg -n "hmac\.new" "$FILE" -n

echo "---- $FILE: decode expects lengths ----"
rg -n "len\\(data\\)|struct\\.unpack|nonce|sig" "$FILE" -C 2

Repository: QuantumNous/new-api

Length of output: 1960


Critical security bug: HMAC signature ignores SESSION_SECRET (wrong hmac.new args).

The code computes sig = hmac.new(msg, nonce, hashlib.sha256).digest(), but hmac.new(key, msg, digestmod) uses the first argument as the secret key—so SESSION_SECRET is never used, and the signature can be forged.

🔒 Proposed fix
     # Compute HMAC: HMAC-SHA256(key=SESSION_SECRET, data=binary(user_id+created_at), salt=nonce)
     msg = struct.pack(">II", user_id, created_at)
-    sig = hmac.new(msg, nonce, hashlib.sha256).digest()
+    key = SESSION_SECRET.encode() if isinstance(SESSION_SECRET, str) else SESSION_SECRET
+    sig = hmac.new(key, msg + nonce, hashlib.sha256).digest()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Compute HMAC: HMAC-SHA256(key=SESSION_SECRET, data=binary(user_id+created_at), salt=nonce)
msg = struct.pack(">II", user_id, created_at)
sig = hmac.new(msg, nonce, hashlib.sha256).digest()
# Encode: user_id(4 bytes BE) + created_at(4 bytes BE) + nonce + sig
payload = struct.pack(">II", user_id, created_at) + nonce + sig
return base64.b64encode(payload).decode()
# Compute HMAC: HMAC-SHA256(key=SESSION_SECRET, data=binary(user_id+created_at), salt=nonce)
msg = struct.pack(">II", user_id, created_at)
key = SESSION_SECRET.encode() if isinstance(SESSION_SECRET, str) else SESSION_SECRET
sig = hmac.new(key, msg + nonce, hashlib.sha256).digest()
# Encode: user_id(4 bytes BE) + created_at(4 bytes BE) + nonce + sig
payload = struct.pack(">II", user_id, created_at) + nonce + sig
return base64.b64encode(payload).decode()
🤖 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 `@integration/middleware/model_detailed_fastapi.py` around lines 258 - 264, The
HMAC is constructed with the wrong argument order so SESSION_SECRET is never
used; update the signature computation (sig) to call hmac.new with the secret as
the key and the packed message as the data (i.e., key=SESSION_SECRET, msg=msg,
digestmod=hashlib.sha256), ensuring SESSION_SECRET is a bytes object (encode if
it's a string) and keep using msg, nonce, and hashlib.sha256 as before; adjust
any related variable names (msg, nonce, SESSION_SECRET) accordingly so the
generated sig uses the secret key.

Comment on lines +301 to +339
def verify_session_or_basic_auth(
session_cookie: str | None = Cookie(None),
) -> str:
"""
Verify user via session cookie (New-API dashboard login) OR Basic Auth (fallback).

Session cookie takes priority — if valid, return "session".
If session invalid/missing, fall back to Basic Auth.
If neither works, raise 401.
"""
import asyncio

# Try session cookie first (async)
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

# Check if we can use session auth
if session_cookie:
# Run sync check in sync context
import concurrent.futures
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(
asyncio.run,
validate_session_cookie(session_cookie)
)
try:
is_valid = future.result(timeout=5)
except Exception:
is_valid = False

if is_valid:
return "session"

# Fall back to Basic Auth (not async-compatible in this context)
# Basic Auth is handled separately in each endpoint that needs it
return "basic"

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

Blocking async-in-sync anti-pattern and missing 401.

This synchronous function spawns a ThreadPoolExecutor to run asyncio.run() — an expensive and fragile pattern. Since FastAPI routes are async, this dependency should also be async.

Additionally, the docstring states "If neither works, raise 401" but the function always returns "basic" without verifying Basic Auth credentials, never raising an exception.

♻️ Proposed async refactor
-def verify_session_or_basic_auth(
-    session_cookie: str | None = Cookie(None),
-) -> str:
+async def verify_session_or_basic_auth(
+    request: Request,
+    credentials: HTTPBasicCredentials = Depends(security),
+) -> str:
     """
     Verify user via session cookie (New-API dashboard login) OR Basic Auth (fallback).
-    
-    Session cookie takes priority — if valid, return "session".
-    If session invalid/missing, fall back to Basic Auth.
-    If neither works, raise 401.
     """
-    import asyncio
-    
-    # Try session cookie first (async)
-    try:
-        loop = asyncio.get_event_loop()
-    except RuntimeError:
-        loop = asyncio.new_event_loop()
-        asyncio.set_event_loop(loop)
-    
-    # Check if we can use session auth
+    session_cookie = get_session_cookie(request)
     if session_cookie:
-        # Run sync check in sync context
-        import concurrent.futures
-        with concurrent.futures.ThreadPoolExecutor() as executor:
-            future = executor.submit(
-                asyncio.run,
-                validate_session_cookie(session_cookie)
-            )
-            try:
-                is_valid = future.result(timeout=5)
-            except Exception:
-                is_valid = False
-        
-        if is_valid:
+        if await validate_session_cookie(session_cookie):
             return "session"
     
-    # Fall back to Basic Auth (not async-compatible in this context)
-    # Basic Auth is handled separately in each endpoint that needs it
-    return "basic"
+    # Fall back to Basic Auth
+    if credentials and credentials.username == DOCS_USERNAME and credentials.password == DOCS_PASSWORD:
+        return "basic"
+    
+    raise HTTPException(status_code=401, detail="Not authenticated", headers={"WWW-Authenticate": "Basic"})
🤖 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 `@integration/middleware/model_detailed_fastapi.py` around lines 301 - 339, The
verify_session_or_basic_auth function should be converted to an async FastAPI
dependency (change signature to async def verify_session_or_basic_auth(...)) and
await the existing validate_session_cookie(session_cookie) instead of using
ThreadPoolExecutor/asyncio.run; if await validate_session_cookie(session_cookie)
returns True return "session". After that, perform an actual Basic Auth check
(use the project's existing basic credential verifier or FastAPI's HTTPBasic
utilities) and return "basic" only when credentials are valid; if neither
session nor basic auth succeed raise fastapi.HTTPException(status_code=401).
Update all call sites/dependencies to accept the async dependency if needed.

Comment on lines +54 to +64
func GetChannelGlobalSetting(key string) string {
globalSettingsLock.RLock()
if time.Since(globalSettingsLoaded) > 5*time.Minute {
globalSettingsLock.RUnlock()
_ = LoadChannelGlobalSettings()
globalSettingsLock.RLock()
}
val := globalSettingsCache[key]
globalSettingsLock.RUnlock()
return val
}

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 | 🟡 Minor | ⚡ Quick win

Stale-refresh path can hammer the DB on load failure and stampede on expiry.

Two reliability concerns in GetChannelGlobalSetting:

  1. On error, LoadChannelGlobalSettings() returns before updating globalSettingsLoaded (Line 48). The error is discarded here (_ =), so the timestamp stays stale and every subsequent Get will retry a full-table load — turning a transient DB outage into a per-request load storm.
  2. After the 5-minute window expires, concurrent callers all observe staleness and each trigger a full reload (thundering herd).

Since this runs on the relay hot path (per-request via the distributor middleware), consider a single-flight guard or advancing the timestamp on attempt to bound retries. At minimum, log the load error so a persistent failure is observable.

🤖 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 `@model/channel_global_settings.go` around lines 54 - 64,
GetChannelGlobalSetting currently discards LoadChannelGlobalSettings errors and
lets many concurrent callers trigger reloads after expiry; fix it by introducing
a single-flight guard around LoadChannelGlobalSettings so only one goroutine
performs the full-table reload (use golang.org/x/sync/singleflight or an
equivalent mutex+condition) and return the result to waiters, stop discarding
the returned error (propagate or at least log it via processLogger or similar),
and on any load attempt advance globalSettingsLoaded (or set a short backoff
timestamp) before/when calling LoadChannelGlobalSettings to avoid per-request
retry storms; update code paths referencing globalSettingsLoaded,
globalSettingsLock, GetChannelGlobalSetting, and LoadChannelGlobalSettings
accordingly.

… fallback test

The test setup had 'pt' alongside 'pt-BR' in supportedLngs, with a comment
claiming it exercised language normalization. The comment was misleading:
no test actually passed 'pt' as lng, so the entry was dead weight that
diverged from src/i18n/config.ts (production).

i18next's built-in fallback (nonExplicitSupportedLngs) maps 'pt' -> 'pt-BR'
when the 'pt-BR' resources entry exists. The correct test of this behavior
is to call changeLanguage('pt') and assert the language resolves to 'pt-BR'
— not to list 'pt' in supportedLngs (which would force it through the
explicit path and hide the fallback).

Changes:
- test/setup.ts: remove 'pt' from supportedLngs, align with config.ts.
- i18n/__tests__/pt-fallback.test.ts: new. Verifies that:
  * changeLanguage('pt') resolves to 'pt-BR' through the fallback
  * loadI18n('pt-BR') lands exactly on 'pt-BR' (no case folding)
  * changeLanguage('PT-br') (mixed case) also resolves to 'pt-BR'

Refs: CodeRabbit review on test/setup.ts.

Verified: 10/10 tests pass (3 new in pt-fallback, 6 normalize, 1 integration).
No new typecheck errors. Pre-existing failures in dropdown-menu.test.tsx
and usage-logs-mobile-card.tsx are unrelated to this change.

@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: 1

🤖 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 `@web/default/src/i18n/__tests__/pt-fallback.test.ts`:
- Around line 15-20: The test currently asserts i18n.language.toLowerCase()
which allows non-canonical casing; update the assertions to check the exact
canonical casing instead (e.g. expect(i18n.language).toBe('pt-BR')). Locate
tests using loadI18n(...) and i18n.changeLanguage('pt') (the test named
changeLanguage("pt") resolves to "pt-BR" and the similar assertion near line 31)
and replace the toLowerCase() based assertions with strict equality against
'pt-BR' using i18n.language.
🪄 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: ea455bb9-eea8-49a5-a68e-60b21c3e13ef

📥 Commits

Reviewing files that changed from the base of the PR and between 2f7ad9b and 5007453.

📒 Files selected for processing (2)
  • web/default/src/i18n/__tests__/pt-fallback.test.ts
  • web/default/src/test/setup.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • web/default/src/test/setup.ts

Comment on lines +15 to +20
test('changeLanguage("pt") resolves to "pt-BR" through the fallback', async () => {
const i18n = await loadI18n('en')
await i18n.changeLanguage('pt')
// i18next's fallback (nonExplicitSupportedLngs) maps 'pt' -> 'pt-BR'
// because the 'pt-BR' resources entry exists and is the best match.
expect(i18n.language.toLowerCase()).toBe('pt-br')

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 | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# 1) Show the test file contents with line numbers
echo "---- pt-fallback.test.ts ----"
nl -ba web/default/src/i18n/__tests__/pt-fallback.test.ts | sed -n '1,200p'

# 2) Find i18next resolution/canonicalization related assertions
echo "---- Search for resolvedLanguage usage ----"
rg -n "resolvedLanguage" web/default/src/i18n || true

# 3) Find where loadI18n is implemented and how i18next instance is created/configured
echo "---- Search for loadI18n implementation ----"
rg -n "function loadI18n|loadI18n\\(" web/default/src/i18n | head -n 50

# Print the loadI18n file (best match)
LOADI18N_FILE=$(rg -l "loadI18n" web/default/src/i18n | head -n 1 || true)
if [ -n "${LOADI18N_FILE}" ]; then
  echo "---- loadI18n file: $LOADI18N_FILE ----"
  nl -ba "$LOADI18N_FILE" | sed -n '1,220p'
fi

# 4) Search for existing tests asserting language vs resolvedLanguage
echo "---- Search for assertions on i18n.language ----"
rg -n "i18n\\.language\\b" web/default/src/i18n/__tests__ || true

echo "---- Search for assertions on i18n.resolvedLanguage ----"
rg -n "i18n\\.resolvedLanguage\\b" web/default/src/i18n/__tests__ || true

Repository: QuantumNous/new-api

Length of output: 154


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "---- pt-fallback.test.ts (first 200 lines) ----"
cat -n web/default/src/i18n/__tests__/pt-fallback.test.ts | sed -n '1,200p'

echo "---- Search for resolvedLanguage usage (i18n code) ----"
rg -n "resolvedLanguage" web/default/src/i18n || true

echo "---- Search for loadI18n implementation ----"
rg -n "function loadI18n|loadI18n\\(" web/default/src/i18n | head -n 50

LOADI18N_FILE=$(rg -l "loadI18n" web/default/src/i18n | head -n 1 || true)
if [ -n "${LOADI18N_FILE}" ]; then
  echo "---- loadI18n file: $LOADI18N_FILE (first 220 lines) ----"
  cat -n "$LOADI18N_FILE" | sed -n '1,220p'
fi

echo "---- Search for assertions on i18n.language (tests) ----"
rg -n "i18n\\.language\\b" web/default/src/i18n/__tests__ || true

echo "---- Search for assertions on i18n.resolvedLanguage (tests) ----"
rg -n "i18n\\.resolvedLanguage\\b" web/default/src/i18n/__tests__ || true

Repository: QuantumNous/new-api

Length of output: 4343


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "---- Search for loadI18n implementation across repo ----"
rg -n "export (async )?function loadI18n|const loadI18n|function loadI18n|loadI18n\s*=" -S . || true

echo "---- Show likely loadI18n setup file(s) ----"
# Find files named setup/index that may contain loadI18n
fd -t f -i "setup" web/default test src . 2>/dev/null || true

echo "---- Search for 'nonExplicitSupportedLngs' in repo ----"
rg -n "nonExplicitSupportedLngs" -S web/default . || true

echo "---- Search for i18next init config ----"
rg -n "i18next|init\\(|createInstance|supportedLngs|resources" -S web/default/src/i18n web/default/src test . || true

Repository: QuantumNous/new-api

Length of output: 50439


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "---- web/default/src/test/setup.ts (first 220) ----"
cat -n web/default/src/test/setup.ts | sed -n '1,220p'

echo "---- web/default/src/i18n/config.ts (first 200) ----"
cat -n web/default/src/i18n/config.ts | sed -n '1,200p'

echo "---- web/default/src/i18n/languages.ts (first 200) ----"
cat -n web/default/src/i18n/languages.ts | sed -n '1,200p'

echo "---- normalize-interface-language.test.ts (first 200) ----"
cat -n web/default/src/i18n/__tests__/normalize-interface-language.test.ts | sed -n '1,220p'

echo "---- Search for resolvedLanguage in relevant code ----"
rg -n "resolvedLanguage" web/default/src/i18n web/default/src/test || true

echo "---- Search for i18next language fallback options in config/setup ----"
rg -n "nonExplicitSupportedLngs|fallbackLng|supportedLngs|supportedLngs|explicitSupportedLngs" web/default/src/i18n/config.ts web/default/src/test/setup.ts || true

Repository: QuantumNous/new-api

Length of output: 9891


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "---- Search whole repo for resolvedLanguage ----"
rg -n "resolvedLanguage" . || true

echo "---- Search whole repo for normalizeInterfaceLanguage usage ----"
rg -n "normalizeInterfaceLanguage" web/default/src || true

echo "---- Search whole repo for changeLanguage( 'pt' or 'PT-br' patterns ----"
rg -n "changeLanguage\\(.*'pt|changeLanguage\\(.*\"pt" web/default/src/i18n web/default/src || true

Repository: QuantumNous/new-api

Length of output: 4080


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "---- language-preferences-card.tsx (first 120) ----"
cat -n web/default/src/features/profile/components/language-preferences-card.tsx | sed -n '1,140p'

echo "---- language-preferences-card integration test (first 120) ----"
cat -n web/default/src/features/profile/__tests__/language-preferences-card-integration.test.tsx | sed -n '1,200p'

echo "---- language-switcher.tsx (first 120) ----"
cat -n web/default/src/components/language-switcher.tsx | sed -n '1,140p'

Repository: QuantumNous/new-api

Length of output: 11663


Tighten pt fallback assertions to validate canonical casing

Lines 20 and 31 only verify i18n.language.toLowerCase(), so they’d still pass if i18next resolved to a non-canonical casing (e.g. pt-br/pt-Br). Since the test explicitly targets the canonical locale pt-BR, assert i18n.language equals 'pt-BR'.

Suggested change
-    expect(i18n.language.toLowerCase()).toBe('pt-br')
+    expect(i18n.language).toBe('pt-BR')
-    expect(i18n.language.toLowerCase()).toBe('pt-br')
+    expect(i18n.language).toBe('pt-BR')
🤖 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 `@web/default/src/i18n/__tests__/pt-fallback.test.ts` around lines 15 - 20, The
test currently asserts i18n.language.toLowerCase() which allows non-canonical
casing; update the assertions to check the exact canonical casing instead (e.g.
expect(i18n.language).toBe('pt-BR')). Locate tests using loadI18n(...) and
i18n.changeLanguage('pt') (the test named changeLanguage("pt") resolves to
"pt-BR" and the similar assertion near line 31) and replace the toLowerCase()
based assertions with strict equality against 'pt-BR' using i18n.language.

Giovanni Muniz and others added 7 commits June 2, 2026 02:03
Coverage gaps closed:
1. relay/channel/claude/relay-claude.go: ClaudeHandler (non-stream) and
   HandleStreamResponseData (stream) now strip CJK. Was 100% leak before.
2. integration/middleware/model_detailed_fastapi.py: CJK strip now applies
   to BOTH streaming and non-streaming responses (was gated on non-stream
   only). Thinking-block strip still requires non-stream (legit reason:
   blocks can span chunks), but CJK is per-chunk safe.
3. Regex extended to cover Hiragana (U+3040-U+309F), Katakana
   (U+30A0-U+30FF, U+31F0-U+31FF), and Hangul Syllables (U+AC00-U+D7AF).
   Was missing all Japanese kana and Korean.

Global key infrastructure:
- model/channel_global_settings.go: new table (key, value, updated_at)
  with in-memory cache (5min refresh) and convenience helpers
  (GlobalStripCJKEnabled, SetChannelGlobalSetting).
- model/main.go: AutoMigrate adds the new table.
- main.go: cache loaded at startup alongside InitChannelCache.
- dto/channel_settings.go: new UseGlobalStripCJK bool field.
- middleware/distributor.go: when channel has use_global_strip_cjk=true
  AND global strip_cjk=true, force channel's strip_cjk to true.

DB activation (migration v0.5):
- docs/migrations/migration_v0.5-cjk-strip-global.sql: creates table,
  inserts strip_cjk=true global, and opts channel type=35 (MiniMax)
  into use_global_strip_cjk. Idempotent.

Source of truth verified against:
- relay/channel/claude/relay-claude.go:789,895 (was 0 StripCJK calls)
- common/str.go:22-25 (regex)
- integration/middleware/model_detailed_fastapi.py:949 (was stream skip)
- dto/channel_settings.go:3-10 (struct)
…model update

The upstream model update task serializes ChannelOtherSettings back to
channel.settings, which silently overwrites any external keys (e.g.
use_global_strip_cjk) that aren't part of the typed struct.

Fix: capture pre-update raw JSON, then merge it with the new struct fields
via mergeChannelSettingsKeepingOthers. Keys present in both keep the new
value (managed); keys only in the stored map are preserved (external).

Without this fix, the upstream model update would wipe use_global_strip_cjk
on the MiniMax channel within the first 30 minutes of operation, defeating
the global strip_cjk key.
Zentrius is the new brand mark (Z + C monogram, dark green #174224 + gold
#C59B35, mid-weight strokes). Replaces the previous default logo
(a New API infinity mark).

Files:
- public/logo.png        (was 9.6K, now 16K Zentrius) — DEFAULT_LOGO path
- public/logo.atius.png  (backup of the old New-API mark)
- public/zentrius.svg    (vector source, 500x500 viewBox)
- public/zentrius.png    (rasterized @ 500dpi)
- public/zentrius-32.png (favicon size)
- public/zentrius-256.png (header/og size)
- public/favicon.ico     (= zentrius-256, browser tab icon)
- src/assets/logo.tsx    (inline SVG React component, mirrors zentrius.svg
  for offline/404 fallback in the React tree)

Canonical copies at ~/Imagens/zentrius.{svg,png} (+ zentrius-32.png,
zentrius-256.png) so the asset survives outside the repo.

DEFAULT_LOGO constant in src/lib/constants.ts is unchanged ('/logo.png')
— the new file at that path is the Zentrius raster.
SVG content matches the user's reference verbatim — no edits:
- Z (dark green #174224, stroke 65, miter join, square cap)
- C (gold #C59B35, stroke 40, square cap)
- H-line connector (dark green, stroke 6)

Renders at /logo.png (16K = zentrius-256), /favicon.ico, /zentrius.svg.
Single-line source format (matches the snippet exactly), not pretty-printed.
Re-renders produced identical bytes to the previous commit for the rasters
(svg source byte change doesn't change raster output at 32/256/500px).

The two prior commits (8e231e4 CJK + 709996e pt-fallback) were
already in the remote branch via the merge; this commit is the brand
change that got dropped during the reset/cherry-pick dance.
@giovannimnz giovannimnz closed this Jun 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant