Commit Graph
3794 Commits
Author SHA1 Message Date
erio d19e8385fa refactor: align Antigravity/ClaudeMax/Sora code with upstream main
- Restore 14 Antigravity/model-mapping files to upstream/main versions
  - Remove fork-specific credits pre-check and degraded retry logic
  - Revert sonnet 4.5→4.6 model mapping back to upstream defaults
  - Remove accountUsageService dependency from AntigravityGatewayService
  - Restore original applyThinkingModelSuffix behavior
- Delete 6 fork-only migration files:
  - 056/057 (Antigravity model mapping)
  - 060 (Claude Max simulation)
  - 070 (Sora tasks table)
  - 077/078 (sonnet rollback/migration)
- Fix wire_gen.go to match updated constructor signature
2026-04-14 21:28:20 +08:00
erio 3be0321bfe fix: Stripe payment type matching in load balancer
Checkout page aggregates Stripe sub-types (card,link,alipay,wxpay) under
"stripe", but SelectInstance matched against supported_types literally,
which doesn't contain "stripe". Now matches by provider_key for Stripe.
2026-04-14 09:50:12 +08:00
erio 8084565d81 test: add unit tests for billing, websearch, and notify systems
Billing (25 tests):
- CalculateCostUnified: nil resolver fallback, token/per_request/image modes
- GetModelPricingWithChannel: nil/partial/full channel overrides
- resolveAccountStatsCost: four-level priority chain integration tests

WebSearch (18 tests):
- PopulateWebSearchUsage: nil input, manager states, QuotaLimit nil/*int64
- ResetWebSearchUsage: nil manager error
- Manager.ResetUsage: nil Redis
- shouldEmulateWebSearch: full decision chain (8 scenarios)

Notify (36 tests):
- ParseNotifyEmails/MarshalNotifyEmails: old/new format, roundtrip
- crossedDownward: boundary values, threshold semantics
- checkQuotaDimCrossings: mixed dimensions, disabled/zero skip
2026-04-14 08:42:28 +08:00
erio 9f9c3a9384 feat: websearch quota enhancements and balance notify hint
- QuotaLimit changed to *int64 (null=unlimited, >0=limited)
- Add reset-usage endpoint (POST /admin/settings/web-search-emulation/reset-usage)
- Show quota usage in header always (collapsed and expanded)
- Add reset quota button in expanded provider view
- Quota input: empty=unlimited with ∞ placeholder, must be >0 if set
- Add email verification hint on balance notify card
2026-04-14 08:07:29 +08:00
erio 63ae7365d6 fix: gofmt formatting across all Go source files 2026-04-14 07:43:08 +08:00
erio 9a820a1749 fix: show websearch API key visibility/copy buttons for saved providers
The buttons were hidden because v-if only checked provider.api_key,
which is always empty for saved providers (backend sanitizes it).
Now also checks api_key_configured. Copy button is disabled when
no actual key is available (only configured placeholder shown).
2026-04-14 07:35:24 +08:00
erio 0104ff55c8 chore: bump version to 0.1.112.2 2026-04-14 07:01:29 +08:00
erio a232407486 fix: resolve remaining test failures after v0.1.112 merge
- Add missing balanceNotifyService param to NewGatewayService in warmup test
- Fix config_test YAML path escaping on Windows (use filepath.ToSlash)
- Update pricingRequestToService test: empty platform no longer defaults
2026-04-14 06:56:58 +08:00
erio 33a0ad767c fix: post-merge fixes for upstream v0.1.112 integration
- Fix AccountUsageCell loadUsage() parameter type mismatch (string→object)
- Add missing i18n keys for openaiMessages family mapping (en/zh, 17 keys)
- Remove duplicate payment provider declarations in wire.go
- Add sort_order field to PlanEditDialog.vue
- Remove 10 duplicate upstream-renumbered migration files
- Fix NewUserService call signatures in test files (missing 4th param)
- Update api_contract_test.go snapshots for new balance_notify fields
2026-04-14 02:57:24 +08:00
erio 54e55e8da0 Merge upstream v0.1.112
Merge upstream v0.1.112 into release/custom-0.1.112.
Resolved conflicts preserving our customizations (allow_user_refund,
balance/quota notify, web search emulation) while adopting upstream
improvements (BySortOrder for plans, CSS sidebar collapse animation,
mobile lazy-load optimization, Anthropic empty output fix).
2026-04-14 02:00:02 +08:00
erio 63315cb7db chore: bump version to 0.1.110.56 2026-04-14 01:39:06 +08:00
erio 3fdb63e2b6 fix: add opportunistic STARTTLS to sendMailPlain for 587 port compatibility
smtp.SendMail automatically upgrades to STARTTLS when the server
supports it. Our replacement sendMailPlain skipped this, causing
credentials to be sent in plaintext on port 587. Add STARTTLS
negotiation before Auth to restore the original security behavior.
2026-04-14 01:38:42 +08:00
erio 325d8eb2ae chore: bump version to 0.1.110.55 2026-04-14 01:11:13 +08:00
erio 541dd3b467 fix: audit round-3 — proxy safety, intervals persistence, SMTP timeout, sort fix
- Skip websearch provider when ProxyID is set but proxy not found (prevent
  silent direct connection bypass)
- Fix sortByStableRandomWeight: pair factors with items so sort.Slice swap
  keeps weights aligned
- Allow empty platform in account_stats_pricing_rules (wildcard matching),
  only force anthropic default for main model_pricing
- Add channel_account_stats_pricing_intervals table and repo layer support
  for interval-based pricing in account stats rules
- calculateTokenStatsCost now uses interval pricing when available
- Replace smtp.SendMail/tls.Dial with net.Dialer timeout (10s dial, 20s IO)
  to prevent goroutine leak on SMTP hang
- Fix gofmt formatting issues
- Web Search label: black text with red warning hint
2026-04-14 01:10:46 +08:00
erio b1c64dcdda chore: bump version to 0.1.110.54 2026-04-14 00:43:09 +08:00
erio 6d61455232 fix: websearch features_config cleanup and pricing rules validation
- Fix web_search_emulation toggle: explicitly write false for disabled
  platforms instead of leaving stale true from cloned features_config
- Extract validatePricingEntries from validateChannelConfig for reuse
- Validate account_stats_pricing_rules[].pricing in both Create and
  Update paths (negative prices, bad intervals, missing per_request price)
2026-04-14 00:42:40 +08:00
erio 61f702ddab chore: bump version to 0.1.110.53 2026-04-14 00:26:49 +08:00
erio e5e26d73d6 fix: round-2 audit fixes — security, code quality, and UI improvements
Security (HIGH):
- Normalize all Redis cache keys to lowercase (verifyCode, passwordReset)
- Fix verify code TTL renewal on failed attempts: use remaining TTL via
  ExpiresAt field instead of resetting to full 15-minute window
- Add 3 missing fields to diffSettings audit log (promo_code, invitation_code,
  custom_endpoints)

Code quality (MEDIUM):
- Extract filterVerifiedEmails shared helper (balance_notify_service.go)
- Add Pricing array non-empty validation for channel pricing rules
- Add platform token semantics comment in gateway_service.go
- Complete validatePlanPatch test coverage (+10 test cases)
- Replace string types with QuotaThresholdType/QuotaResetMode across frontend
- Remove duplicate getPlatformTextColor/getRateBadgeClass in ChannelsView
- Return EMAIL_NOT_FOUND error on RemoveNotifyEmail miss

UI improvements:
- Reorder cost tooltip: user billing above separator, account billing below
- Add NaN guard to accountBilled function
- Move timezone selector inline into reset-mode row (no longer standalone)
2026-04-14 00:26:20 +08:00
erio b3a2611d67 chore: bump version to 0.1.110.52 2026-04-13 23:36:27 +08:00
erio 931fcb50f8 fix: address audit findings for websearch, email verification, and pricing
- Fix websearch provider failover: proxy error from provider-specific proxy
  now continues to next provider instead of aborting the entire loop
- Fix SMTP failure locking users out: send email first, then write cache
  and increment rate counter
- Fix notify email cache key case sensitivity: normalize to lowercase
- Add OriginalPrice validation to validatePlanPatch and validatePlanRequired
- Add empty scope validation for channel pricing rules (group_ids/account_ids)
- Add platform color to account search dropdown in channel pricing rules
2026-04-13 23:35:59 +08:00
shaw f9f57e9505 fix(migrations): add 097 to restore settings.updated_at default
Legacy instances created the settings table via ent auto-migration,
which emits Go-level defaults only. Migration 005 uses CREATE TABLE
IF NOT EXISTS, so the missing SQL DEFAULT was never backfilled. This
caused 098's raw INSERT to fail with a NOT NULL violation on
updated_at. The new migration is idempotent and safe for fresh
installs (no-op) and historical instances (backfills the default).
2026-04-13 23:09:26 +08:00
erio c664e67018 refactor: M5 useQuotaNotifyState composable + H14 Vue file splits
M5: New composable frontend/src/composables/useQuotaNotifyState.ts
  - Replaces 9 individual refs in both Create/Edit modals with reactive state
  - Provides loadFromExtra/writeToExtra/reset helpers
  - Eliminates ~120 lines of duplicated code across the two modals

H14: Vue file length violations fixed
  - AdminPaymentPlansView.vue: 325 → 183 lines (extracted PlanEditDialog.vue)
  - QuotaLimitCard.vue: 327 → 268 lines (extracted QuotaDimensionRow.vue)
  - PlanEditDialog.vue: 181 lines (new, plan create/edit form)
  - QuotaDimensionRow.vue: 108 lines (new, single quota dimension row)
2026-04-13 22:35:24 +08:00
shaw 92f4a6bb94 chore: update readme 2026-04-13 22:28:44 +08:00
erio 7a5ec1a17a refactor: M6 extract applyAccountStatsCost helper, M11 fix postUsageBilling double-queue
M6: New applyAccountStatsCost() helper in account_stats_pricing.go replaces
    identical upstream-model-fallback + resolveAccountStatsCost() call sites
    in both gateway_service.go and openai_gateway_service.go

M11: postUsageBilling legacy path no longer calls finalizePostUsageBilling,
    fixing the double-queue bug (QueueDeductBalance was called twice if the
    fallback path was ever reached). Added NOTE comment documenting the split.
2026-04-13 22:22:05 +08:00
Wesley Liddick 66bea2b5ed Merge pull request #1624 from KnowSky404/fix-issue-1613-version-dropdown
fix(sidebar): prevent version update dropdown clipping
2026-04-13 22:03:02 +08:00
Wesley Liddick ad6c328135 Merge pull request #1575 from shuanbao0/fix/cursor-responses-body-compat
fix(gateway): 兼容 Cursor /v1/chat/completions 的 Responses API body
2026-04-13 22:02:44 +08:00
erio 4213688485 refactor: batch 3 — decompose CheckBalanceAfterDeduction, merge crossing checks, add QuotaNotifyConfig
M1: CheckBalanceAfterDeduction (63→18 lines) decomposed into:
    canNotifyBalance, resolveUserEffectiveThreshold, crossedDownward, dispatchBalanceLowEmail
M3: New Account.QuotaNotifyConfig(dim) method replaces 9 hardcoded getters
    (getters kept as thin wrappers for backward compatibility)
M4: checkQuotaDimCrossings + checkQuotaDimCrossingsFromState merged into one
    function taking pre-built []quotaDim; caller builds dims conditionally
2026-04-13 22:02:18 +08:00
erio 939902f998 fix: batch 2 audit fixes — diffSettings notify fields, slog migration, frontend constants
H5: diffSettings now tracks 5 balance/quota notify fields in audit log
M15: log.Printf audit log migrated to slog.Info, removed "log" import
M14: New frontend/src/constants/account.ts with shared constants
     QuotaNotifyToggle.vue uses QUOTA_THRESHOLD_TYPE_FIXED/PERCENTAGE
L2: UsageTable.vue uses BILLING_MODE_TOKEN/IMAGE from billingMode.ts
2026-04-13 21:54:01 +08:00
Wesley Liddick d949acb1f2 Merge pull request #1603 from Zqysl/qingyu/fix-datatable-mobile-double-render
fix(frontend): reduce account usage request fan-out on pagination
2026-04-13 21:48:00 +08:00
Wesley Liddick 759088002d Merge pull request #1612 from touwaeriol/fix/qrcode-density
fix(frontend): lower QR code error correction level to reduce density
2026-04-13 21:44:38 +08:00
Wesley Liddick 7d80b5ad28 Merge pull request #1610 from touwaeriol/fix/alipay-wxpay-type-mapping
fix(payment): register Alipay/Wxpay providers for base payment types
2026-04-13 21:44:19 +08:00
erio 563339dedb fix: batch 1 audit fixes — quota SQL fixed mode, public recharge URL, WebSearch bool fallback, UpdatePlan validation
H1: incrementUsageBillingAccountQuota now uses shared dailyExpiredExpr/weeklyExpiredExpr
    constants (supporting fixed reset mode) instead of hardcoded '24 hours'/'168 hours'
H4: public settings endpoint now maps balance_low_notify_recharge_url
H6: GetWebSearchEmulationMode tolerates legacy bool values (true→enabled)
H7: UpdatePlan validates non-nil patch fields (rejects negative price, empty name, etc.)
H8: UsageTable accountBilled() helper with total_cost ?? 0 null guard
H9: AdminUsageLog TS type adds channel_id + billing_tier
M2: account.go "fixed" literals replaced with thresholdTypeFixed constant
M13: SystemSettings TS type adds web_search_emulation_enabled
UI: QuotaLimitCard title labels now use flex-1 to align with flex-1 input boxes
2026-04-13 21:41:02 +08:00
Wesley Liddick e70812f03f Merge pull request #1623 from sakurawztlt/fix/anthropic-buffered-empty-output
fix: anthropic 非流式路径丢失 delta 内容(镜像 b2e379cf)
2026-04-13 21:11:48 +08:00
erio 66ccd17492 fix(quota-card): balance input widths, inline reset hint, timezone GMT offset
- Limit input and notify threshold now share flex-1 equally (was w-28 fixed)
- Reset schedule hint text moved inline after the selectors (same row)
- Timezone dropdown shows GMT offset, e.g. "Asia/Shanghai (GMT+8)"
2026-04-13 20:45:12 +08:00
erio 69971098af fix(channels): apply platform color to rule group/account chips
In "custom account stats pricing rule" section, group checkbox labels and
selected account chips now use the platform text color (matching the top
"associated groups" header), making it visually consistent across the modal.
2026-04-13 20:39:06 +08:00
erio 1701b32e2c test: add 66 unit tests for balance/quota notify + plan validation
balance_notify_service_test.go (27 tests):
- resolveBalanceThreshold: fixed/percentage/zero recharged/empty type
- quotaDim.resolvedThreshold: fixed normal/exceed/equal limit, percentage 0/30/100/>100, zero/negative limit
- sanitizeEmailHeader: CRLF/CR/LF/clean/empty/multiple newlines
- buildQuotaDims / buildQuotaDimsFromState: all dimensions, empty extra, state-vs-account precedence
- collectBalanceNotifyRecipients: empty, filter disabled/unverified, case-insensitive dedup, skip empty, trim

balance_notify_check_test.go (16 tests):
- CheckBalanceAfterDeduction guard clauses: nil user/disabled/global-off/threshold=0/user-override/no-crossing
- CheckAccountQuotaAfterIncrement guards: nil account/zero cost/negative cost/global-disabled
- getBalanceNotifyConfig: all fields, disabled, invalid threshold
- isAccountQuotaNotifyEnabled: missing/false/true
- getSiteName: default fallback + configured

balance_notify_email_body_test.go (10 tests):
- Guards against fmt.Sprintf arg-count mismatches in email templates
- Verifies HTML escaping of recharge URL
- Verifies CSS %% escape produces literal % in output
- Verifies unlimited/percentage/over-quota display branches

payment_config_plans_validation_test.go (13 tests):
- validatePlanRequired: all 5 validation branches + whitespace handling
2026-04-13 20:35:38 +08:00
erio fea35fbfb2 fix(accounts): unify modal width, add notify props to create, fix quota layout
- EditAccountModal width changed from "normal" to "wide" (match CreateAccountModal)
- CreateAccountModal now passes all quota notify props to QuotaLimitCard
- QuotaLimitCard: when global notify disabled, hide title row, input takes full width
- Quota alert email: show remaining quota + threshold (fixed/$, percentage/%) instead of usage trigger point
2026-04-13 20:01:25 +08:00
erio b0305fef11 fix: audit findings - PUT response rechargeURL, NaN guard, debug logs
- Add BalanceLowNotifyRechargeURL to admin PUT response (fixes save-then-stale)
- Add ?? 1 guard for account_rate_multiplier in UsageTable else branch
- Downgrade high-frequency notify logs from Info to Debug
- Extract "Sub2API" magic string to defaultSiteName constant
2026-04-13 19:45:45 +08:00
knowsky404 b9b52e74c6 fix(sidebar): prevent version dropdown clipping 2026-04-13 19:24:33 +08:00
erio 6307aff1d3 fix(notify): add recharge URL to admin settings GET response 2026-04-13 19:02:40 +08:00
erio 1621f8ae9e fix(notify): write back auto-filled recharge URL to form on save 2026-04-13 18:52:02 +08:00
sakurawztlt a1e299a355 fix: Anthropic 非流式路径在上游终态事件 output 为空时从 delta 事件重建响应内容
b2e379cf 引入的 BufferedResponseAccumulator 已修复了 chat_completions
非流式路径和 responses OAuth 非流式路径,但遗漏了 Anthropic /v1/messages
非流式路径 (handleAnthropicBufferedStreamingResponse)。

当客户端请求 stream=false 且模型开启思考时,上游 response.completed
终态事件的 output 字段可能为空,实际 message 内容通过
response.output_text.delta 增量事件下发。旧代码只读终态事件的 Response,
导致客户端收到的 content 字段为空 ([{"type":"text"}])。

本 commit 将 b2e379cf 的相同修复模式镜像到 Anthropic 路径:在 SSE 扫描
过程中用 BufferedResponseAccumulator 累积 delta 内容,终态 output 为空
时通过 SupplementResponseOutput 补充重建。

同时修复 handleAnthropicBufferedStreamingResponse 遗漏 response.done
事件类型的问题,与 chat completions 路径保持一致,避免上游发送
response.done 时 handler 认不出终态事件、最终返回 502 的潜在问题。

BufferedResponseAccumulator 已在 chatcompletions_responses_test.go 有
完整单元测试覆盖(TextOnly/ToolCalls/Reasoning/Mixed/SupplementEmpty/
NoSupplementWhenOutputExists/EmptyDeltas/IgnoresNonFunctionCallItems),
本次复用相同累加器无需新增测试。
2026-04-13 18:51:49 +08:00
erio 1d13c2d2ba fix(notify): auto-fill recharge URL with current origin when empty 2026-04-13 18:46:56 +08:00
erio 6c2c17d17e feat(notify): add platform/ID to quota alert email, add recharge URL to balance alert
- Quota alert email now shows account ID and platform
- Balance low email includes a "Top Up Now" button when recharge URL is configured
- New setting: balance_low_notify_recharge_url in admin settings
2026-04-13 18:39:45 +08:00
erio 78df126437 fix(ui): widen notify type dropdown to show % fully, align quota input widths 2026-04-13 18:23:20 +08:00
erio d6fe6da831 fix(plans): frontend validation for price > 0 and validity_days >= 1 2026-04-13 18:18:29 +08:00
erio f5e386e330 fix(plans): require price > 0 for subscription plans 2026-04-13 18:12:57 +08:00
erio 5277f33155 fix(plans): subscription plan page validation, sorting, and toFixed error
- Fix toFixed crash when price is undefined
- Remove sort_order field, order by created_at instead
- Fix group selector showing blank when nothing selected
- Add required field markers (*) and backend validation
- Add i18n groupRequired key for both zh/en
2026-04-13 18:08:06 +08:00
erio d96cbe4f21 chore: bump version to 0.1.110.34 2026-04-13 17:38:34 +08:00
erio a03ffc8c99 fix: change quota notify threshold semantics to "remaining quota"
Threshold now represents remaining quota instead of usage amount:
- Fixed ($): threshold=400, limit=1000 → alert when remaining drops to $400
  (i.e., usage reaches $600)
- Percentage (%): threshold=30%, limit=1000 → alert when remaining drops
  to 30% (i.e., usage reaches $700)

Also:
- Rename 告警阈值 → 提醒阈值 in i18n
- Widen type dropdown to w-16 for proper $ / % display
2026-04-13 17:38:33 +08:00