654 Commits

Author SHA1 Message Date
CaIon
9bb2b6a6ae feat: implement token key fetching and masking in API responses 2026-03-08 22:40:40 +08:00
CaIon
d796578880 fix: unify pricing labels and expand marketplace pricing display
Keep the model pricing editor wording aligned with the new price-based UI while exposing cache, image, and audio pricing in the marketplace so users can see the full configured pricing model.
2026-03-06 22:33:51 +08:00
Calcium-Ion
e593c11eab Merge pull request #3037 from RedwindA/fix/token-model-limits-length
fix: change token model_limits column from varchar(1024) to text
2026-03-02 22:00:21 +08:00
RedwindA
43e068c0c0 fix: enhance migrateTokenModelLimitsToText function to return errors and improve migration checks 2026-02-28 19:08:03 +08:00
RedwindA
52c29e7582 fix: migrate model_limits column from varchar(1024) to text for existing tables 2026-02-28 18:49:06 +08:00
Seefs
985189af23 fix: support vertex multi-key task fetch in content proxy 2026-02-27 17:07:10 +08:00
RedwindA
db8534b4a3 fix: change token model_limits column from varchar(1024) to text
Fixes #3033 — users with many model limits hit PostgreSQL's varchar
length constraint. The text type is supported across all three
databases (SQLite, MySQL, PostgreSQL) with no length restriction.
2026-02-27 14:47:20 +08:00
CaIon
0da0d80647 fix: handle nil setting in user retrieval from database 2026-02-24 23:46:46 +08:00
Calcium-Ion
6d03fc828d Merge pull request #2998 from seefs001/fix/pr-2900
Fix/pr 2900
2026-02-24 13:35:05 +08:00
Seefs
af31935102 fix: check oauthUser.Username length 2026-02-24 13:26:19 +08:00
Seefs
9a5f8222bd feat: move user bindings to dedicated management modal 2026-02-23 14:51:55 +08:00
CaIon
016812baa6 feat: implement caching for channel retrieval 2026-02-23 14:11:11 +08:00
CaIon
13ada6484a feat(task): introduce task timeout configuration and cleanup unfinished tasks
- Added TaskTimeoutMinutes constant to configure the timeout duration for asynchronous tasks.
- Implemented sweepTimedOutTasks function to identify and handle unfinished tasks that exceed the timeout limit, marking them as failed and processing refunds if applicable.
- Enhanced task polling loop to include the new timeout handling logic, ensuring timely cleanup of stale tasks.
2026-02-22 17:59:38 +08:00
CaIon
ec5c6b28ea feat(task): add model redirection, per-call billing, and multipart retry fix for async tasks
1. Async task model redirection (aligned with sync tasks):
   - Integrate ModelMappedHelper in RelayTaskSubmit after model name
     determination, populating OriginModelName / UpstreamModelName on RelayInfo.
   - All task adaptors now send UpstreamModelName to upstream providers:
     - Gemini & Vertex: BuildRequestURL uses UpstreamModelName.
     - Doubao & Ali: BuildRequestBody conditionally overwrites body.Model.
     - Vidu, Kling, Hailuo, Jimeng: convertToRequestPayload accepts RelayInfo
       and unconditionally uses info.UpstreamModelName.
     - Sora: BuildRequestBody parses JSON and multipart bodies to replace
       the "model" field with UpstreamModelName.
   - Frontend log visibility: LogTaskConsumption and taskBillingOther now
     emit is_model_mapped / upstream_model_name in the "other" JSON field.
   - Billing safety: RecalculateTaskQuotaByTokens reads model name from
     BillingContext.OriginModelName (via taskModelName) instead of
     task.Data["model"], preventing billing leaks from upstream model names.

2. Per-call billing (TaskPricePatches lifecycle):
   - Rename TaskBillingContext.ModelName → OriginModelName; add PerCallBilling
     bool field, populated from TaskPricePatches at submission time.
   - settleTaskBillingOnComplete short-circuits when PerCallBilling is true,
     skipping both adaptor adjustments and token-based recalculation.
   - Remove ModelName from TaskSubmitResult; use relayInfo.OriginModelName
     consistently in controller/relay.go for billing context and logging.

3. Multipart retry boundary mismatch fix:
   - Root cause: after Sora (or OpenAI audio) rebuilds a multipart body with a
     new boundary and overwrites c.Request.Header["Content-Type"], subsequent
     calls to ParseMultipartFormReusable on retry would parse the cached
     original body with the wrong boundary, causing "NextPart: EOF".
   - Fix: ParseMultipartFormReusable now caches the original Content-Type in
     gin context key "_original_multipart_ct" on first call and reuses it for
     all subsequent parses, making multipart parsing retry-safe globally.
   - Sora adaptor reverted to the standard pattern (direct header set/get),
     which is now safe thanks to the root fix.

4. Tests:
   - task_billing_test.go: update makeTask to use OriginModelName; add
     PerCallBilling settlement tests (skip adaptor adjust, skip token recalc);
     add non-per-call adaptor adjustment test with refund verification.
2026-02-22 16:33:00 +08:00
CaIon
9976b311ef refactor(task): enhance UpdateWithStatus for CAS updates and add integration tests
- Updated UpdateWithStatus method to use Model().Select("*").Updates() for conditional updates, preventing GORM's INSERT fallback.
- Introduced comprehensive integration tests for UpdateWithStatus, covering scenarios for winning and losing CAS updates, as well as concurrent updates.
- Added task_cas_test.go to validate the new behavior and ensure data integrity during concurrent state transitions.
2026-02-22 16:01:19 +08:00
CaIon
5ec4633cb8 refactor(task): add CAS-guarded updates to prevent concurrent billing conflicts
Replace all bare task.Update() (DB.Save) calls with UpdateWithStatus(),
which adds a WHERE status = ? guard to prevent concurrent processes from
overwriting each other's state transitions.

Key changes:

model/task.go:
- Add taskSnapshot struct with Equal() method for change detection
- Add Snapshot() method to capture pre-update state
- Add UpdateWithStatus(fromStatus) using DB.Where().Save() for CAS
  semantics with full-struct save (no explicit field listing needed)

model/midjourney.go:
- Add UpdateWithStatus(fromStatus string) with same CAS pattern

service/task_polling.go (updateVideoSingleTask):
- Snapshot before processing upstream response; skip DB write if unchanged
- Terminal transitions (SUCCESS/FAILURE) use UpdateWithStatus CAS:
  billing/refund only executes if this process wins the transition
- Non-terminal updates also use UpdateWithStatus to prevent overwriting
  a concurrent terminal transition back to IN_PROGRESS
- Defer settleTaskBillingOnComplete to after CAS check (shouldSettle flag)

relay/relay_task.go (tryRealtimeFetch):
- Add snapshot + change detection; use UpdateWithStatus for CAS safety

controller/midjourney.go (UpdateMidjourneyTaskBulk):
- Capture preStatus before mutations; use UpdateWithStatus CAS
- Gate refund (IncreaseUserQuota) on CAS success (won && shouldReturnQuota)

This prevents the multi-instance race condition where:
1. Instance A reads task (IN_PROGRESS), fetches upstream (still IN_PROGRESS)
2. Instance B reads same task, fetches upstream (now SUCCESS), writes SUCCESS
3. Instance A's bare Save() overwrites SUCCESS back to IN_PROGRESS
2026-02-22 16:01:19 +08:00
CaIon
809ba92089 refactor(logs): add refund logging for asynchronous tasks and update translations 2026-02-22 16:01:19 +08:00
CaIon
d6e11fd2e1 feat(task): add adaptor billing interface and async settlement framework
Add three billing lifecycle methods to the TaskAdaptor interface:
- EstimateBilling: compute OtherRatios from user request before pricing
- AdjustBillingOnSubmit: adjust ratios from upstream submit response
- AdjustBillingOnComplete: determine final quota at task terminal state

Introduce BaseBilling as embeddable no-op default for adaptors without
custom billing. Move Sora/Ali OtherRatios logic from shared validation
into per-adaptor EstimateBilling implementations.

Add TaskBillingContext to persist pricing params (model_price, group_ratio,
other_ratios) in task private data for async polling settlement.

Extract RecalculateTaskQuota as a general-purpose delta settlement
function and unify polling billing via settleTaskBillingOnComplete
(adaptor-first, then token-based fallback).
2026-02-22 16:00:27 +08:00
CaIon
9e3954428d refactor(task): extract billing and polling logic from controller to service layer
Restructure the task relay system for better separation of concerns:
- Extract task billing into service/task_billing.go with unified settlement flow
- Move task polling loop from controller to service/task_polling.go (supports Suno + video platforms)
- Split RelayTask into fetch/submit paths with dedicated retry logic (taskSubmitWithRetry)
- Add TaskDto, TaskResponse generics, and FetchReq to dto/task.go
- Add taskcommon/helpers.go for shared task adaptor utilities
- Remove controller/task_video.go (logic consolidated into service layer)
- Update all task adaptors (ali, doubao, gemini, hailuo, jimeng, kling, sora, suno, vertex, vidu)
- Simplify frontend task logs to use new TaskDto response format
2026-02-22 16:00:27 +08:00
Seefs
e0a6ee1cb8 imporve oauth provider UI/UX (#2983)
* feat: imporve UI/UX

* fix: stabilize provider enabled toggle and polish custom OAuth settings UX

* fix: add access policy/message templates and persist advanced fields reliably

* fix: move template fill actions below fields and keep advanced form flow cleaner
2026-02-22 15:41:29 +08:00
Calcium-Ion
61a5fa39dd Merge pull request #2928 from RedwindA/fix/token-Search
fix(token-search): use TrimPrefix for sk- token normalization
2026-02-12 15:19:34 +08:00
RedwindA
091a7611b1 fix(token-search): use TrimPrefix for sk- token normalization 2026-02-12 15:12:49 +08:00
skynono
30da5bbd08 优化: 任务日志查询速度并显示用户详情 (#2905)
* perf: task log show userinfo

* feat: add Tooltip component to TaskLogsColumnDefs
2026-02-12 14:49:38 +08:00
CaIon
eca4eff5f0 feat: Improve backend multilingual support 2026-02-12 14:29:56 +08:00
Seefs
2c0db08f32 Merge pull request #2815 from wans10/main
fix: 修复模型管理"参与官方同步"与"状态"开关无法保存的问题
2026-02-08 19:56:16 +08:00
Seefs
4950db666f fix: 如果模型管理有自定义配置则不合并默认配置 2026-02-08 19:42:52 +08:00
Calcium-Ion
7a146a11f5 Merge pull request #2870 from seefs001/feature/cache-creation-configurable
feat: make 5m cache-creation ratio configurable
2026-02-08 00:28:42 +08:00
Calcium-Ion
8e1a990b45 Merge pull request #2857 from QuantumNous/feat/custom-oauth
feat(oauth): implement custom OAuth provider
2026-02-08 00:13:20 +08:00
CaIon
0837090fa9 🔧 refactor: Enhance Log struct indexing for improved query performance 2026-02-07 23:20:43 +08:00
CaIon
c8aee5e487 🔧 refactor: Update formatUserLogs function to accept start index
Modified the formatUserLogs function to include a startIdx parameter, allowing for more flexible log ID assignment. Updated calls to this function in GetLogByTokenId and GetUserLogs to pass the appropriate starting index.
2026-02-07 22:51:26 +08:00
t0ng7u
1cc6bf1b45 chore: Improve subscription billing fallback and UI states
Add a lightweight active-subscription check to skip subscription pre-consume when none exist, reducing unnecessary transactions and locks. In the subscription UI, disable subscription-first options when no active plan is available, show the effective fallback to wallet with a clear notice, and distinguish “invalidated” from “expired” states. Update i18n strings across supported locales to reflect the new messages and status labels.
2026-02-07 00:57:36 +08:00
CaIon
d814d62e2f refactor: enhance API security with read-only token authentication and improved rate limiting 2026-02-06 21:26:26 +08:00
CaIon
04dd761880 fix: update LIKE pattern sanitization for token search
- Change ESCAPE character from '\' to '!' for compatibility with MySQL/PostgreSQL/SQLite
- Adjust sanitization logic to escape '!' and '_' correctly, improving input validation for search queries
2026-02-06 19:52:35 +08:00
Seefs
50ee4361d0 feat: make 5m cache-creation ratio configurable 2026-02-06 19:46:59 +08:00
Calcium-Ion
053699fa98 Merge commit from fork
fix: harden token search with pagination, rate limiting and input validation
2026-02-06 17:54:40 +08:00
CaIon
3e1be18310 fix: harden token search with pagination, rate limiting and input validation
- Add configurable per-user token creation limit (max_user_tokens)
- Sanitize search input patterns to prevent expensive queries
- Add per-user search rate limiting (by user ID)
- Add pagination to search endpoint with strict page size cap
- Skip empty search fields instead of matching nothing
- Hide internal errors from API responses
- Fix Interface2String float64 formatting causing config parse failures
- Add float-string fallback in config system for int/uint fields
2026-02-06 17:52:19 +08:00
CaIon
2567cff6c8 fix(oauth): enhance error handling and transaction management for OAuth user creation and binding
- Improve error handling in DeleteCustomOAuthProvider to log and return errors when fetching binding counts.
- Refactor user creation and OAuth binding logic to use transactions for atomic operations, ensuring data integrity.
- Add unique constraints to UserOAuthBinding model to prevent duplicate bindings.
- Enhance GitHub OAuth provider error logging for non-200 responses.
- Update AccountManagement component to provide clearer error messages on API failures.
2026-02-05 21:48:05 +08:00
CaIon
af54ea85d2 feat(oauth): implement custom OAuth provider management #1106
- Add support for custom OAuth providers, including creation, retrieval, updating, and deletion.
- Introduce new model and controller for managing custom OAuth providers.
- Enhance existing OAuth logic to accommodate custom providers.
- Update API routes for custom OAuth provider management.
- Include i18n support for custom OAuth-related messages.
2026-02-05 21:18:43 +08:00
CaIon
632baadb57 feat(oauth): migrate GitHub user identification from login to numeric ID 2026-02-05 20:30:48 +08:00
Calcium-Ion
3c7687f952 Merge pull request #2842 from QuantumNous/feat/backend-i18n
feat: backend i18n
2026-02-05 01:57:44 +08:00
CaIon
67613e0642 fix(i18n): prioritize user settings over Accept-Language header
The i18n middleware runs before UserAuth, so user settings weren't
available when language was detected. Now GetLangFromContext checks
user settings first (set by UserAuth) before falling back to the
language set by middleware or Accept-Language header.
2026-02-05 00:37:18 +08:00
CaIon
42b5aeaae4 fix(i18n): add missing translations and improve language fallback
- Change default language fallback to English instead of Chinese
- Add ErrRedeemFailed typed error for model layer translation
- Migrate remaining hardcoded messages in controller/user.go
- Add translation keys: redeem.failed, user.create_default_token_error, common.uuid_duplicate, common.invalid_input
2026-02-05 00:16:17 +08:00
Calcium-Ion
ca91d6992e Merge pull request #2635 from feitianbubu/pr/1a2a0dbd92384bfe886b93606003f6753fcb4e9d
feat: task log show username
2026-02-04 23:39:41 +08:00
CaIon
9ef7740fe7 feat(file): unify file handling with a new FileSource abstraction for URL and base64 data 2026-02-04 18:23:17 +08:00
Calcium-Ion
89b2782675 Merge pull request #2825 from seefs001/feature/request-id-log-column
feat: log search field request_id && conversion_path display
2026-02-04 15:13:06 +08:00
Seefs
bb54ed91dc feat: capture request_id, filter by request_id, show request_conversion 2026-02-04 14:47:42 +08:00
Seefs
d8d1f141c2 The conversion path is displayed to users by default. 2026-02-04 02:17:30 +08:00
Seefs
dd467ed592 feat: log search field request_id 2026-02-04 02:12:18 +08:00
CaIon
f1e6c1bf77 feat(subscription): implement SQLite support for SubscriptionPlan table creation and migration
#2823
2026-02-04 01:42:55 +08:00
CaIon
6a9522ac5b feat(subscription): validate price amount and migrate database column type
- Add validation to ensure subscription plan price amount is non-negative and does not exceed 9999.
- Migrate the price_amount column from float/double to decimal(10,6) in the database for improved precision.
- Update SubscriptionPlan model to reflect the new decimal type for price_amount.
2026-02-03 18:58:28 +08:00