1. 23 Apr, 2026 1 commit
    • erio's avatar
      sync: bring over remaining release/custom-0.1.115 changes · 748a84d8
      erio authored
      - Extract PublicSettingsInjectionPayload named struct with drift test
      - Add channel_monitor_default_interval_seconds to SSR injection
      - Add image_output_price to SupportedModelChip
      - Simplify AppSidebar buildSelfNavItems (admins see available channels)
      - Add gateway WARN logs for 503 no-available-accounts branches
      - Wire ChannelMonitorRunner into provideCleanup for graceful shutdown
      - Add migrations 130/131 (CC template userid fix + mimicry field cleanup)
      - Clean up fork-only features (sora, claude max simulation, client affinity)
      - Remove ~320 obsolete i18n keys
      - Add codexUsage utility, WechatServiceButton, BulkEditAccountModal
      - Tidy go.sum
      748a84d8
  2. 22 Apr, 2026 1 commit
    • erio's avatar
      fix(channels): supported models = mapping ∪ pricing with global LiteLLM fallback · 6cd7c605
      erio authored
      Why: channels with model pricing entries but no model mapping (e.g. azcc with
      3 priced claude models, no mapping) were rendering as 未配置模型 in the
      'Available Channels' page. The algorithm only iterated ModelMapping and
      silently dropped any platform without a mapping entry.
      
      Changes:
      - channel.go: SupportedModels now unions mapping + pricing entries.
        For exact mapping src → target, pricing is looked up by target (the actually
        billed name), not by src.
      - channel_available.go: ListAvailable enriches each entry with nil pricing
        via PricingService.GetModelPricing (global LiteLLM fallback) so the popover
        always shows a price.
      - channel_service.go: NewChannelService takes *PricingService as 4th param.
      - channel_test.go: rewrote 4 tests that froze the old mapping-only semantics;
        added pricing-only / mapping-target / target-missing coverage.
      6cd7c605
  3. 21 Apr, 2026 2 commits
    • erio's avatar
      feat(channels): gate available channels behind feature switch (backend) · 9ba42aa5
      erio authored
      Add a DB-backed soft switch "available_channels_enabled" controlling
      the user-facing /channels/available endpoint and sidebar entry. Default
      to false (opt-in) — the feature stays invisible until an admin enables
      it under Admin Settings > Features.
      
      - domain_constants: SettingKeyAvailableChannelsEnabled
      - settings_view: AllSettings/PublicSettings + AvailableChannelsEnabled
      - setting_service: public+all read/write, seed default "false",
        GetAvailableChannelsRuntime helper (fail-closed on read error)
      - admin setting_handler: UpdateSettingsRequest *bool + update branch
        + audit diff entry
      - public setting_handler: expose via GET /api/v1/settings
      - available_channel_handler: featureEnabled() guard — returns empty
        list after auth when disabled (401 precedes the feature check to
        preserve existing behavior)
      9ba42aa5
    • erio's avatar
      chore(channels): drop admin-side available channels view · 59290e39
      erio authored
      Remove the admin-side "Available Channels" aggregate view — admins
      already see full channel configuration (groups, pricing, model
      mappings) in the channel edit dialog, making a read-only admin
      aggregate view redundant. The user-side "可用渠道" remains.
      
      Backend:
      - Delete handler/admin/available_channel_handler.go (+ test)
      - Drop AdminHandlers.AvailableChannel field and wire injection
      - Remove /admin/channels/available route
      
      Frontend:
      - Delete views/admin/AvailableChannelsView.vue
      - Drop /admin/available-channels router entry
      - Strip AvailableChannel types + listAvailable from api/admin/channels.ts
      59290e39
  4. 20 Apr, 2026 1 commit
    • erio's avatar
      feat(channels): add "Available Channels" aggregate view · 654cfb64
      erio authored
      Add a read-only aggregate view per channel: its linked groups and a
      deterministic wildcard-free supported-model list with pricing details.
      
      Backend
      - service.Channel.SupportedModels(): combine ModelMapping keys with
        same-platform ModelPricing.Models; trailing "*" keys expand via
        pricing prefix match; platforms without a mapping produce no
        entries (intentional "no mapping = not shown" rule).
      - Extract splitWildcardSuffix() shared with toModelEntry.
      - Build a per-call pricing lookup map (platform+lowerName -> *pricing)
        to avoid O(N*M) scans in SupportedModels.
      - ChannelService.ListAvailable() aggregates channels + active groups;
        filters out group IDs no longer active.
      - Admin route GET /api/v1/admin/channels/available returns the full
        DTO (id, status, billing_model_source, restrict_models, groups,
        supported_models).
      - User route GET /api/v1/channels/available applies three filters:
        Status==active, visible-group intersection, and platform filter
        on supported_models (prevents cross-platform leak when a channel
        links to both a user-accessible group and an inaccessible one on
        another platform). Response is a plain array (matches the
        /groups/available sibling shape). Field whitelist omits
        billing_model_source, restrict_models, ids, status, sort_order.
      
      Frontend
      - New /admin/available-channels and /available-channels views backed
        by a shared AvailableChannelsTable component (admin adds status +
        billing-source columns via slots).
      - PricingRow extracted to its own SFC; SupportedModelChip references
        shared billing-mode constants in constants/channel.ts.
      - Sidebar: new entry above "渠道管理" for admin; matching entry in
        user nav.
      - i18n: zh + en coverage for both namespaces.
      
      Tests
      - SupportedModels: wildcard-only pricing skipped, prefix-matches-
        nothing, cross-platform bleed, case-insensitive dedup, empty
        platform mapping.
      - ListAvailable: nil groupRepo, inactive-group-ID dropped, stable
        case-insensitive name sort.
      - User handler: 401 on unauthenticated, visible-group intersection,
        platform filter on supported_models, JSON whitelist.
      - Admin handler: full DTO including default BillingModelSource
        fallback.
      
      Refs: issue #1729
      654cfb64
  5. 21 Apr, 2026 2 commits
    • erio's avatar
      feat(channel-monitor): request templates with snapshot apply + headers/body override · a2964259
      erio authored
      Problem:
      Upstream channels can reject monitor probes based on client fingerprint
      (e.g. "only Claude Code clients allowed"). The monitor had no way to
      customize the outgoing request to bypass such restrictions.
      
      Solution:
      Introduce reusable request templates that carry extra_headers plus an
      optional body override; monitors reference a template and receive a
      snapshot copy on apply. Template edits do NOT auto-propagate — users
      must click "apply to associated monitors" to refresh snapshots, so a
      bad template edit cannot instantly break all production monitors.
      
      Data model (migration 112):
      - channel_monitor_request_templates: id, name, provider, description,
        extra_headers jsonb, body_override_mode ('off'|'merge'|'replace'),
        body_override jsonb. Unique (provider, name).
      - channel_monitors: +template_id (FK, ON DELETE SET NULL), +extra_headers,
        +body_override_mode, +body_override (the three runtime snapshot fields).
      
      Checker (channel_monitor_checker.go):
      - callProvider + runCheckForModel accept a CheckOptions carrying the
        snapshot fields. mergeHeaders applies user headers on top of adapter
        defaults (forbidden list: Host / Content-Length / Transfer-Encoding /
        Connection / Content-Encoding).
      - buildRequestBody:
          off     -> adapter default body
          merge   -> shallow-merge over default; per-provider deny list
                     (model/messages/contents) protects the challenge contract
          replace -> user body verbatim
      - Replace mode skips challenge validation; instead HTTP 2xx + non-empty
        extracted response text = operational, empty = failed.
      - 4 new unit tests cover all three modes + replace/empty-response case.
      
      Admin API:
      - /admin/channel-monitor-templates CRUD + /:id/apply (overwrite snapshot
        on all template_id=id monitors, returns affected count).
      - channel_monitor request/response DTOs gain the 4 new fields.
      
      Frontend:
      - channelMonitorTemplate.ts API client.
      - MonitorAdvancedRequestConfig.vue shared component for headers textarea
        + body mode radio + body JSON editor; used by both template and monitor
        forms.
      - MonitorTemplateManagerDialog.vue: provider tabs, list/create/edit/
        delete/apply, live "associated monitors" count per row.
      - MonitorFiltersBar: new 模板管理 button next to 新增监控.
      - MonitorFormDialog: collapsible 高级 section with template dropdown
        (filtered by form.provider, clears on provider change) + embedded
        AdvancedRequestConfig. Picking a template copies its fields into the
        form (snapshot semantics mirrored on the client).
      - i18n zh/en entries for all new copy.
      
      chore: bump version to 0.1.114.32
      a2964259
    • erio's avatar
      feat(channel-monitor): aggregate history to daily rollups + soft delete · 8cf83c98
      erio authored
      明细只保留 1 天,超过 1 天聚合到新表 channel_monitor_daily_rollups(按
      monitor_id/model/bucket_date 维度),聚合保留 30 天。两张表都用 SoftDeleteMixin
      软删除(DELETE 自动改为 UPDATE deleted_at = NOW())。
      
      聚合 + 清理任务由 OpsCleanupService 的 cron 统一调度,与运维监控的清理共享
      schedule(默认 0 2 * * *)和 leader lock。ChannelMonitorRunner 的 cleanupLoop
      被移除,只保留 dueCheckLoop。
      
      读取路径 ComputeAvailability* 改为 UNION 明细(今天 deleted_at IS NULL)+
      聚合(过去 windowDays 天 deleted_at IS NULL),SUM(ok)/SUM(total) 自然加权
      计算可用率,AVG latency 用 SUM(sum_latency_ms)/SUM(count_latency)。
      
      watermark 表 channel_monitor_aggregation_watermark 单行(id=1),记录
      last_aggregated_date,重启后从该日期 +1 继续聚合,首次为 nil 则从
      today - 30d 开始回填,单次最多 35 天上限避免长事务。
      
      raw SQL 的 ListLatestPerModel / ListLatestForMonitorIDs / ListRecentHistoryForMonitors
      都补上 deleted_at IS NULL 过滤(SoftDeleteMixin interceptor 只对 ent query 生效)。
      
      bump version to 0.1.114.28
      
      GroupBadge 在 MonitorKeyPickerDialog 中复用平台主题色 + 倍率/专属倍率
      (顺手优化)。
      8cf83c98
  6. 20 Apr, 2026 2 commits
    • erio's avatar
      feat(channel-monitor): add feature switch settings + fix extra_models save · 7da51240
      erio authored
      Settings:
      - New "功能开关" tab between 通用设置 and 安全与认证
      - ChannelMonitorEnabled toggle: runner skips scheduling when false,
        user-facing list returns empty
      - ChannelMonitorDefaultIntervalSeconds (15-3600): pre-fills interval
        when creating a new monitor; each monitor can still override
      
      Bug fix:
      - ModelTagInput now commits pending input on blur, not just Enter/Tab.
        Previously clicking "save" with an un-Enter'd extra model would drop
        the value (DB stored extra_models=[] even when user typed entries).
      
      Backend:
      - domain_constants: SettingKeyChannelMonitor{Enabled,DefaultIntervalSeconds}
      - SettingService.GetChannelMonitorRuntime: lightweight getter used by
        runner tick + user handler per-request (fail-open on DB error)
      - Runner tickDueChecks: bails early when feature disabled
      - ChannelMonitorUserHandler: checks feature flag before serving
      - Comment on runner doc: scheduler state is implicit (every tick re-reads
        ListEnabled from DB), so CRUD ops on monitors self-maintain the schedule
      
      Bump VERSION to 0.1.114.25
      7da51240
    • erio's avatar
      feat(monitor): admin channel monitor MVP with SSRF protection and batch aggregation · 20a4e418
      erio authored
      新增 admin「渠道监控」模块(参考 BingZi-233/check-cx),独立于现有 Channel 体系。
      admin 配置 + 后台定时调用上游 LLM chat completions 健康检查 + 所有登录用户只读可见。
      
      后端:
      - ent: channel_monitor + channel_monitor_history(AES-256-GCM 加密 api_key)
      - service 按职责拆分:service/aggregator/validate/checker/runner/ssrf
      - provider strategy map 替代 switch(openai/anthropic/gemini)
      - repository batch 聚合(ListLatestForMonitorIDs + ComputeAvailabilityForMonitors)消除 N+1
      - runner: ticker(5s) + pond worker pool(5) + inFlight 防并发 + TrySubmit 防雪崩
        + 凌晨 3 点 cron 清理 30 天历史
      - SSRF 防护:强制 https + 私网/loopback/云元数据 IP 拒绝(127/8、10/8、172.16/12、
        192.168/16、169.254/16、100.64/10、::1、fc00::/7、fe80::/10)+ DialContext
        在 socket 层防 DNS rebinding
      - API key sanitize:擦除 url.Error 与上游响应 body 中的 sk-/sk-ant-/AIza/JWT 模式
      - APIKeyDecryptFailed 标志位 + 单 monitor 路径检测,避免空 key 调用上游
      
      handler:
      - admin: CRUD + 手动触发 + 历史接口(api_key 脱敏)
      - user: 只读列表 + 状态详情(去除 api_key/endpoint)
      - ParseChannelMonitorID 共用 + dto.ChannelMonitorExtraModelStatus 共用
      
      前端:
      - 路由 /admin/channels/{pricing,monitor} + /monitor(用户只读)
      - AppSidebar 父项 expandOnly 支持
      - ChannelMonitorView 拆为 8 个子组件 + ChannelStatusView 拆出 detail dialog
      - composables/useChannelMonitorFormat + constants/channelMonitor 共享
      - i18n monitorCommon namespace 消除 admin/user 两 view 重复
      
      合规:所有文件符合 CLAUDE.md(Go ≤ 500 行 / Vue ≤ 300 行 / 函数 ≤ 30 行)
      CI: go build / gofmt / golangci-lint(0 issues) / make test-unit / pnpm build 全绿
      20a4e418
  7. 22 Apr, 2026 1 commit
  8. 21 Apr, 2026 1 commit
  9. 17 Apr, 2026 1 commit
  10. 15 Apr, 2026 1 commit
  11. 14 Apr, 2026 27 commits
    • erio's avatar
      fix: update wire_gen.go to use ProvideSchedulerCache with config injection · 3d202722
      erio authored
      wire_gen.go was calling NewSchedulerCache(redisClient) but wire.go had
      been updated to register ProvideSchedulerCache(redisClient, config),
      which reads SnapshotMGetChunkSize and SnapshotWriteChunkSize from config.
      Without this fix, those config values were silently ignored.
      3d202722
    • erio's avatar
      fix: merge 30 general improvements from release branch · 6ac8ccde
      erio authored
      Bug fixes:
      - Detached context for GetAccountConcurrencyBatch (prevent all-zero on request cancel)
      - Filter soft-deleted users in GetByGroupID
      - Stripe CSP policy (allow Stripe.js in script-src and frame-src)
      - WebSearch API key validation on save
      - RECHARGING status in payment result success check
      - Windows test fixes (logger Sync deadlock, config path escaping)
      
      Feature enhancements:
      - Webhook multi-instance dispatch (extractOutTradeNo + GetWebhookProvider)
      - EasyPay mobile H5 payment (device param + PayURL2)
      - SSE error propagation in WebSearch emulation
      - AccountStatsCost DTO field for admin usage logs
      - Plans sort by sort_order instead of created_at
      - UsageMapHook for streaming response usage data
      - apicompat Instructions field passthrough
      - EffectiveLoadFactor for ops concurrency/metrics
      - Usage billing RETURNING balance for notify system
      - BulkUpdate mixed channel warning with details
      - println to slog migration in auth cache
      - Wire ProviderSet cleanup
      - CI cache-dependency-path optimization
      
      Frontend:
      - Refund eligibility check per provider (canRequestRefund)
      - Plan sort_order editing
      - Dead code cleanup (simulate_claude_max, client_affinity)
      - GroupsView platform switch guard
      - channels features_config API type
      - UsageView account_stats_cost export
      6ac8ccde
    • erio's avatar
      fix: restore resolveOpenAIMessagesDispatchMappedModel and reset VERSION · 24e16b7f
      erio authored
      - Restore function deleted during cherry-pick conflict resolution
      - Reset VERSION to upstream 0.1.112
      24e16b7f
    • erio's avatar
      fix: resolve cherry-pick conflicts and restore compilation · d6965b06
      erio authored
      - Restore gateway_cache.go to upstream (no lua embeds)
      - Restore payment_order.go to upstream (use out_trade_no lookup)
      - Restore payment_fulfillment.go to upstream (same reason)
      - Add FeaturesConfig field and IsWebSearchEmulationEnabled to Channel
      - Add applyAccountStatsCost wrapper function
      - Add SettingKeyWebSearchEmulationConfig constant
      - Add WebSearchEmulationEnabled to SystemSettings
      - Add notify code rate limiting methods to EmailCache interface
      - Remove AllowUserRefund references (ent schema not present)
      - Fix duplicate import in payment_handler.go
      - Fix wire_gen.go argument mismatches
      d6965b06
    • erio's avatar
      feat: websearch quota enhancements and balance notify hint · 7c729293
      erio authored
      - 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
      7c729293
    • erio's avatar
      fix: show websearch API key visibility/copy buttons for saved providers · 9e0d12d3
      erio authored
      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).
      9e0d12d3
    • erio's avatar
      refactor: M5 useQuotaNotifyState composable + H14 Vue file splits · 1b7c2951
      erio authored
      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)
      1b7c2951
    • erio's avatar
      refactor: batch 3 — decompose CheckBalanceAfterDeduction, merge crossing... · 594f0d17
      erio authored
      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
      594f0d17
    • erio's avatar
      fix: batch 2 audit fixes — diffSettings notify fields, slog migration, frontend constants · 9d319cfa
      erio authored
      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
      9d319cfa
    • erio's avatar
      fix: batch 1 audit fixes — quota SQL fixed mode, public recharge URL,... · ed8a9d97
      erio authored
      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
      ed8a9d97
    • erio's avatar
      fix(accounts): unify modal width, add notify props to create, fix quota layout · a43da622
      erio authored
      - 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
      a43da622
    • erio's avatar
      6e9146e7
    • erio's avatar
      f571d8ff
    • erio's avatar
    • erio's avatar
      feat(notify): add platform/ID to quota alert email, add recharge URL to balance alert · c1eb79e4
      erio authored
      - 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
      c1eb79e4
    • erio's avatar
    • erio's avatar
      fix: change quota notify threshold semantics to "remaining quota" · 216bda58
      erio authored
      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
      216bda58
    • erio's avatar
      fix(frontend): place quota notify toggle inline with limit input · 7141dcee
      erio authored
      Move QuotaNotifyToggle to the same row as the limit $ input for all
      three dimensions (daily/weekly/total), significantly reducing card height.
      7141dcee
    • erio's avatar
      fix(frontend): collapsible quota card and compact notify layout · ac554432
      erio authored
      - QuotaLimitCard: add collapse/expand toggle (chevron icon + click header)
      - QuotaNotifyToggle: show $ or % suffix in threshold input
      - Reduce vertical spacing between reset mode hint and notify toggle
      ac554432
    • erio's avatar
      fix(frontend): quota notify UI improvements · 2066c478
      erio authored
      - QuotaNotifyToggle: add $ or % suffix to threshold input based on type
      - QuotaLimitCard: combine reset mode and notify toggle on same row
        to reduce vertical height for daily/weekly sections
      - Remove redundant ml-4 indentation from QuotaNotifyToggle
      2066c478
    • erio's avatar
      fix: correct account stats pricing priority order · 98c9d517
      erio authored
      Priority was wrong:
      - Before: custom rules → LiteLLM (when ApplyPricingToAccountStats) → nil
      - After:  custom rules → totalCost (when ApplyPricingToAccountStats) → LiteLLM → nil
      
      When ApplyPricingToAccountStats is enabled, use the request's actual
      client billing cost (before multiplier) as account_stats_cost, instead
      of recalculating from LiteLLM per-token prices which produced incorrect
      values for per-request billing mode.
      
      LiteLLM model pricing is now the final fallback (priority 3), used only
      when neither custom rules nor ApplyPricingToAccountStats apply.
      98c9d517
    • erio's avatar
      fix: add missing AccountQuotaNotifyEnabled to admin settings API · 42f8ef33
      erio authored
      The field was present in SystemSettings response DTO and service layer
      but missing from:
      - UpdateSettingsRequest (admin handler) - saves were silently ignored
      - GET/PUT response mapping in admin handler
      - UpdateSettingsRequest (non-admin dto)
      
      This caused the toggle to always revert to off after saving.
      42f8ef33
    • erio's avatar
      fix(frontend): hide quota notify toggle when global setting is disabled · 48e8efe3
      erio authored
      QuotaLimitCard now requires quotaNotifyGlobalEnabled prop to control
      visibility of QuotaNotifyToggle components. When the global account
      quota notification is disabled in admin settings, per-account threshold
      toggles are hidden in both Edit and Create account modals.
      48e8efe3
    • erio's avatar
      fix: round 3 audit fixes - SMTP header sanitization and goroutine safety · b1875f0b
      erio authored
      - Move sanitizeEmailHeader to SendEmailWithConfig entry point, covering all
        email senders (verify code, password reset, ops alerts, notifications)
      - Add panic recovery to UpdateBalance goroutine
      - Fix stale comment in getAccountQuotaNotifyEmails (email="" no longer used)
      - Log error instead of silently discarding verifyNotifyCode cache update failure
      b1875f0b
    • erio's avatar
      fix: audit fixes for websearch, notifications, and channel pricing · b7fb2e43
      erio authored
      P0: fix wildcard matching test assertion (config order, not longest prefix)
      P0: add TotalRecharged to auth cache snapshot (v5) for percentage threshold
      P1: move pricing rules into per-platform sections in ChannelsView
      P1: populate account name cache when editing existing channel rules
      P1: sanitize email subject headers to prevent SMTP injection
      P1: make Redis INCR+EXPIRE idempotent for rate limiting
      P1: deep copy FeaturesConfig in Channel.Clone()
      P2: clean up stale email="" placeholder comments
      P2: replace log.Printf with slog in email_service.go
      b7fb2e43
    • erio's avatar
      feat: WebSearch tri-state, account stats pricing fix, quota cache fix, usage tooltip · 1262654d
      erio authored
      WebSearch tri-state switch:
      - Account-level web_search_emulation changed from bool to tri-state
        string: "default" (follow channel) / "enabled" / "disabled"
      - shouldEmulateWebSearch checks channel config when account is "default"
      - SQL migration converts old bool values
      - Frontend select replaces toggle in Edit/CreateAccountModal
      
      Account stats pricing:
      - resolveAccountStatsCost uses upstream model (post-mapping) for matching
      - Priority: custom rules → model pricing file (when toggle on) → default
      - Custom rules always configurable, independent of toggle
      - Account ID field changed to searchable selector filtered by platform
      - Description updated to reflect new behavior
      
      Quota notification cache fix:
      - CheckAccountQuotaAfterIncrement fetches real-time account from DB
      - Reconstructs pre-increment usage for accurate threshold crossing detection
      - New AccountQuotaReader interface (minimal: GetByID only)
      
      Usage tooltip:
      - Per-request/image billing shows per-request price instead of $0 token price
      - Token billing continues to show input/output price per million tokens
      1262654d
    • erio's avatar
      fix(websearch): improve settings UI and hide config when globally disabled · 889b5b4f
      erio authored
      - API Key show/copy buttons moved inside input field (inline icons)
      - Proxy selector and test button on same row to save vertical space
      - Test opens a dialog modal instead of inline display
      - Hide all websearch config in channels/accounts when global toggle is off
      889b5b4f