Commit Graph

8 Commits

  • feat: add usage daily rollups, incremental auto-vacuum, and sync-aware backup
    - Add usage_daily_rollups table (schema v6) to aggregate proxy request
      logs into daily summaries, reducing query overhead for statistics
    - Add rollup_and_prune DAO that aggregates old detail logs (>N days)
      into rollup rows and deletes the originals
    - Update all usage stats queries to UNION detail logs with rollup data
    - Introduce incremental auto-vacuum for SQLite, with startup and
      periodic cleanup of old stream_check_logs and request log rollups
    - Split backup export/import into full vs sync variants: WebDAV sync
      now skips local-only table data (proxy_request_logs,
      stream_check_logs, provider_health, proxy_live_backup,
      usage_daily_rollups) while preserving them on import
    - Add enable_logging guard to skip request log writes when disabled
    - Apply cargo fmt formatting fixes across multiple modules
  • Feat/pricing config enhancement (#781)
    * feat(db): add pricing config fields to proxy_config table
    
    - Add default_cost_multiplier field per app type
    - Add pricing_model_source field (request/response)
    - Add request_model field to proxy_request_logs table
    - Implement schema migration v5
    
    * feat(api): add pricing config commands and provider meta fields
    
    - Add get/set commands for default cost multiplier
    - Add get/set commands for pricing model source
    - Extend ProviderMeta with cost_multiplier and pricing_model_source
    - Register new commands in Tauri invoke handler
    
    * fix(proxy): apply cost multiplier to total cost only
    
    - Move multiplier calculation from per-item to total cost
    - Add resolve_pricing_config for provider-level override
    - Include request_model and cost_multiplier in usage logs
    - Return new fields in get_request_logs API
    
    * feat(ui): add pricing config UI and usage log enhancements
    
    - Add pricing config section to provider advanced settings
    - Refactor PricingConfigPanel to compact table layout
    - Display all three apps (Claude/Codex/Gemini) in one view
    - Add multiplier column and request model display to logs
    - Add frontend API wrappers for pricing config
    
    * feat(i18n): add pricing config translations
    
    - Add zh/en/ja translations for pricing defaults config
    - Add translations for multiplier, requestModel, responseModel
    - Add provider pricing config translations
    
    * fix(pricing): align backfill cost calculation with real-time logic
    
    - Fix backfill to deduct cache_read_tokens from input (avoid double billing)
    - Apply multiplier only to total cost, not to each item
    - Add multiplier display in request detail panel with i18n support
    - Use AppError::localized for backend error messages
    - Fix init_proxy_config_rows to use per-app default values
    - Fix silent failure in set_default_cost_multiplier/set_pricing_model_source
    - Add clippy allow annotation for test mutex across await
    
    * style: format code with cargo fmt and prettier
    
    * fix(tests): correct error type assertions in proxy DAO tests
    
    The tests expected AppError::InvalidInput but the DAO functions use
    AppError::localized() which returns AppError::Localized variant.
    Updated assertions to match the correct error type with key validation.
    
    ---------
    
    Co-authored-by: Jason <farion1231@gmail.com>
  • Feat/provider individual config (#663)
    * refactor(ui): simplify UpdateBadge to minimal dot indicator
    
    * feat(provider): add individual test and proxy config for providers
    
    Add support for provider-specific model test and proxy configurations:
    
    - Add ProviderTestConfig and ProviderProxyConfig types in Rust and TypeScript
    - Create ProviderAdvancedConfig component with collapsible panels
    - Update stream_check service to merge provider config with global config
    - Proxy config UI follows global proxy style (single URL input)
    
    Provider-level configs stored in meta field, no database schema changes needed.
    
    * feat(ui): add failover toggle and improve proxy controls
    
    - Add FailoverToggle component with slide animation
    - Simplify ProxyToggle style to match FailoverToggle
    - Add usage statistics button when proxy is active
    - Fix i18n parameter passing for failover messages
    - Add missing failover translation keys (inQueue, addQueue, priority)
    - Replace AboutSection icon with app logo
    
    * fix(proxy): support system proxy fallback and provider-level proxy config
    
    - Remove no_proxy() calls in http_client.rs to allow system proxy fallback
    - Add get_for_provider() to build HTTP client with provider-specific proxy
    - Update forwarder.rs and stream_check.rs to use provider proxy config
    - Fix EditProviderDialog.tsx to include provider.meta in useMemo deps
    - Add useEffect in ProviderAdvancedConfig.tsx to sync expand state
    
    Fixes #636
    Fixes #583
    
    * fix(ui): sync toast theme with app setting
    
    * feat(settings): add log config management
    
    Fixes #612
    Fixes #514
    
    * fix(proxy): increase request body size limit to 200MB
    
    Fixes #666
    
    * docs(proxy): update timeout config descriptions and defaults
    
    Fixes #612
    
    * fix(proxy): filter x-goog-api-key header to prevent duplication
    
    * fix(proxy): prevent proxy recursion when system proxy points to localhost
    
    Detect if HTTP_PROXY, HTTPS_PROXY, or ALL_PROXY environment variables
    point to loopback addresses (localhost, 127.0.0.1), and bypass system
    proxy in such cases to avoid infinite request loops.
    
    * fix(i18n): add providerAdvanced i18n keys and fix failover toast parameter
    
    - Add providerAdvanced.* i18n keys to en.json, zh.json, and ja.json
    - Fix failover toggleFailed toast to pass detail parameter
    - Remove Chinese fallback text from UI for English/Japanese users
    
    * fix(tray): restore tray-provider events and enable Auto failover properly
    
    - Emit provider-switched event on tray provider click (backward compatibility)
    - Auto button now: starts proxy, takes over live config, enables failover
    
    * fix(log): enable dynamic log level and single file mode
    
    - Initialize log at Trace level for dynamic adjustment
    - Change rotation strategy to KeepSome(1) for single file
    - Set max file size to 1GB
    - Delete old log file on startup for clean start
    
    * fix(tray): fix clippy uninlined format args warning
    
    Use inline format arguments: {app_type_str} instead of {}
    
    * fix(provider): allow typing :// in endpoint URL inputs
    
    Change input type from "url" to "text" to prevent browser
    URL validation from blocking :// input.
    
    Closes #681
    
    * fix(stream-check): use Gemini native streaming API format
    
    - Change endpoint from OpenAI-compatible to native streamGenerateContent
    - Add alt=sse parameter for SSE format response
    - Use x-goog-api-key header instead of Bearer token
    - Convert request body to Gemini contents/parts format
    
    * feat(proxy): add request logging for debugging
    
    Add debug logs for outgoing requests including URL and body content
    with byte size, matching the existing response logging format.
    
    * fix(log): prevent usize underflow in KeepSome rotation strategy
    
    KeepSome(n) internally computes n-2, so n=1 causes underflow.
    Use KeepSome(2) as the minimum safe value.
  • Refactor/simplify proxy logs (#585)
    * refactor(proxy): simplify logging for better readability
    
    - Delete 17 verbose debug logs from handlers, streaming, and response_processor
    - Convert excessive INFO logs to DEBUG level for internal processing details
    - Add 2 critical INFO logs in forwarder.rs for failover scenarios:
      - Log when switching to next provider after failure
      - Log when all providers have been exhausted
    - Fix clippy uninlined_format_args warning
    
    This reduces log noise while maintaining visibility into key user-facing decisions.
    
    * fix: replace unsafe unwrap() calls with proper error handling
    
    - database/dao/mcp.rs: Use map_err for serde_json serialization
    - database/dao/providers.rs: Use map_err for settings_config and meta serialization
    - commands/misc.rs: Use expect() for compile-time regex pattern
    - services/prompt.rs: Use unwrap_or_default() for SystemTime
    - deeplink/provider.rs: Replace unwrap() with is_none_or pattern for Option checks
    
    Reduces potential panic points from 26 to 1 (static regex init, safe).
    
    * refactor(proxy): simplify verbose logging output
    
    - Remove response JSON full output logging in response_processor
    - Remove per-request INFO logs in provider_router (failover status, provider selection)
    - Change model mapping log from INFO to DEBUG
    - Change usage logging failure from INFO to WARN
    - Remove redundant debug logs for circuit breaker operations
    
    Reduces log noise significantly while preserving important warnings and errors.
    
    * feat(proxy): add structured log codes for i18n support
    
    Add error code system to proxy module logs for multi-language support:
    
    - CB-001~006: Circuit breaker state transitions and triggers
    - SRV-001~004: Proxy server lifecycle events
    - FWD-001~002: Request forwarding and failover
    - FO-001~005: Failover switch operations
    - USG-001~002: Usage logging errors
    
    Log format: [CODE] Chinese message
    Frontend/log tools can map codes to any language.
    
    New file: src/proxy/log_codes.rs - centralized code definitions
    
    * chore: bump version to 3.9.1
    
    * style: format code with prettier and rustfmt
    
    * fix(ui): allow number inputs to be fully cleared before saving
    
    - Convert numeric state to string type for controlled inputs
    - Use isNaN() check instead of || fallback to allow 0 values
    - Apply fix to ProxyPanel, CircuitBreakerConfigPanel,
      AutoFailoverConfigPanel, and ModelTestConfigPanel
    
    * feat(pricing): support @ separator in model name matching
    
    - Refactor model name cleaning into chained method calls
    - Add @ to - replacement (e.g., gpt-5.2-codex@low → gpt-5.2-codex-low)
    - Add test case for @ separator matching
    
    * fix(proxy): improve validation and error handling in proxy config panels
    
    - Add StopTimeout/StopFailed error types for proper stop() error reporting
    - Replace silent clamp with validation-and-block in config panels
    - Add listenAddress format validation in ProxyPanel
    - Use log_codes constants instead of hardcoded strings
    - Use once_cell::Lazy for regex precompilation
    
    * fix(proxy): harden error handling and input validation
    
    - Handle RwLock poisoning in settings.rs with unwrap_or_else
    - Add fallback for dirs::home_dir() in config modules
    - Normalize localhost to 127.0.0.1 in ProxyPanel
    - Format IPv6 addresses with brackets for valid URLs
    - Strict port validation with pure digit regex
    - Treat NaN as validation failure in config panels
    - Log warning on cost_multiplier parse failure
    - Align timeoutSeconds range to [0, 300] across all panels
  • Fix/Resolve panic issues in proxy-related code (#560)
    * fix(proxy): change default port from 5000 to 15721
    
    Port 5000 conflicts with AirPlay Receiver on macOS 12+.
    Also adds error handling for proxy toggle and i18n placeholder updates.
    
    * fix(proxy): replace unwrap/expect with graceful error handling
    
    - Handle HTTP client initialization failure with no_proxy fallback
    - Fix potential panic on Unicode slicing in API key preview
    - Add proper error handling for response body builder
    - Handle edge case where SystemTime is before UNIX_EPOCH
    
    * fix(proxy): handle UTF-8 char boundary when truncating request body log
    
    Rust strings are UTF-8 encoded, slicing at a fixed byte index may cut
    in the middle of a multi-byte character (e.g., Chinese, emoji), causing
    a panic. Use is_char_boundary() to find the nearest safe cut point.
    
    * fix(proxy): improve robustness and prevent panics
    
    - Add reqwest socks feature to support SOCKS proxy environments
    - Fix UTF-8 safety in masked_key/masked_access_token (use chars() instead of byte slicing)
    - Fix UTF-8 boundary check in usage_script HTTP response truncation
    - Add defensive checks for JSON operations in proxy service
    - Remove verbose debug logs that could trigger panic-prone code paths
  • Feat/usage improvements (#508)
    * i18n: update cache terminology across all languages
    
    - Change 'Cache Read' to 'Cache Hit' in all languages
    - Change 'Cache Write' to 'Cache Creation' in all languages
    - Update zh: 缓存读取 → 缓存命中, 缓存写入 → 缓存创建
    - Update en: Cache Read → Cache Hit, Cache Write → Cache Creation
    - Update ja: キャッシュ読取 → キャッシュヒット, キャッシュ書込 → キャッシュ作成
    
    Affected keys: cacheReadTokens, cacheCreationTokens, cacheReadCost,
    cacheWriteCost, cacheRead, cacheWrite
    
    * feat(usage): add cache metrics to trend chart
    
    - Add cache creation tokens visualization (orange line)
    - Add cache hit tokens visualization (purple line)
    - Add gradient definitions for new cache metrics
    - Include cache data in hourly aggregation
    - Display cache metrics alongside input/output tokens
    
    This provides better visibility into cache usage patterns over time.
    
    * fix(usage): fix timezone handling in datetime picker
    
    - Add timestampToLocalDatetime() to convert Unix timestamp to local datetime
    - Add localDatetimeToTimestamp() with validation for incomplete input
    - Fix issue where typing hours/minutes would jump to previous day
    - Validate datetime format completeness before conversion
    - Use local timezone instead of UTC for datetime-local input
    
    This resolves the issue where users couldn't fine-tune time selection
    and the input would jump unexpectedly when editing hours or minutes.
    
    * feat(usage): add auto-refresh for usage statistics
    
    - Add 30-second auto-refresh interval for all usage queries
    - Disable background refresh to save resources
    - Apply to: summary, trends, provider stats, model stats, request logs
    - Queries automatically update when tab is active
    - Pause refresh when user switches to another tab
    
    This keeps usage data fresh without manual refresh.
    
    * fix(proxy): improve usage logging and cache token parsing
    
    - Log requests even when usage parsing fails (with default values)
    - Add detailed debug logging for usage metrics
    - Support cache_read_input_tokens field in Codex responses
    - Fallback to input_tokens_details.cached_tokens if needed
    - Add test case for cached_tokens in input_tokens_details
    - Ensure all requests are tracked in database for analytics
    
    This fixes missing request logs when API responses lack usage data
    and improves cache token detection across different response formats.
    
    * style(rust): use inline format args in format! macros
    
    - Replace format!("...", var) with format!("...{var}")
    - Update universal provider ID formatting
    - Update error message formatting
    - Update config.toml generation in Codex provider
    
    Fixes clippy::uninlined_format_args warnings.
    
    * feat(proxy): enhance provider router logging
    
    - Add debug logs for failover queue provider count
    - Log circuit breaker state for each provider check
    - Add logs for missing current provider scenarios
    - Log when no current provider is configured
    - Use inline format args for better readability
    
    This improves debugging of provider selection and failover behavior.
    
    * feat(database): update model pricing data
    
    - Update Claude models to full version format (e.g. claude-opus-4-5-20251101)
    - Add GPT-5.2 series model pricing (10 models)
    - Add GPT-5.1 series model pricing (10 models)
    - Add GPT-5 series model pricing (12 models)
    - Add Gemini 3 series model pricing (2 models)
    - Update Gemini 2.5 series model ID format (use dot separator)
    - Unify display names by removing thinking level suffixes
    
    * fix(usage): correct Gemini output token calculation
    
    Fix Gemini API output token parsing to use totalTokenCount - promptTokenCount
    instead of candidatesTokenCount alone. This ensures thoughtsTokenCount is
    included in output statistics.
    
    - Update from_gemini_response to calculate output from total - input
    - Update from_gemini_stream_chunks with same logic for consistency
    - Fix from_codex_stream_events to use adjusted token calculation
    - Add test case for responses with thoughtsTokenCount
    - Update existing tests to match new calculation logic
    
    * fix(usage): correct cache token billing and add Codex format auto-detection
    
    - Avoid double-billing cache tokens by subtracting from input before calculation
    - Add smart Codex parser that auto-detects OpenAI vs Codex API format
    - Extract model name from Codex responses for accurate tracking
    
    * fix(proxy): improve takeover detection with live config check
    
    - Add live config takeover detection for hot-switch decision
    - Rebuild takeover when backup is missing or placeholder remains
    - Make detect_takeover_in_live_config_for_app public
    - Fix is_takeover_active to use actual takeover status
    
    * refactor(usage): simplify model pricing lookup by removing suffix fallback
    
    Replace complex suffix-stripping fallback with direct prefix/suffix cleanup.
    Model IDs are now cleaned by removing vendor prefix (before /) and colon
    suffix (after :), then matched exactly against pricing table.
    
    * feat(database): add Chinese AI model pricing data
    
    Add pricing for domestic AI models (CNY/1M tokens):
    - Doubao-Seed-Code (ByteDance)
    - DeepSeek V3/V3.1/V3.2
    - Kimi K2/K2-Thinking/K2-Turbo (Moonshot)
    - MiniMax M2/M2.1/M2.1-Lightning
    - GLM-4.6/4.7 (Zhipu)
    - Mimo V2 Flash (Xiaomi)
    
    Also fix test case to use correct model ID and remove invalid currency column.
    
    * refactor(proxy): improve header forwarding with blacklist approach
    
    Change from whitelist to blacklist mode for request header forwarding.
    Only skip headers that will be overridden (auth, host, content-length).
    This preserves client's original headers and improves compatibility.
    
    * fix(proxy): bypass timeout and retry configs when failover is disabled
    
    When auto_failover_enabled is false, timeout and retry configurations
    should not affect normal request flow. This change ensures:
    
    - create_forwarder: passes 0 for all timeout/retry params when failover
      is disabled, effectively bypassing these checks
    - streaming_timeout_config: returns 0 for both first_byte_timeout and
      idle_timeout when failover is disabled
    
    This prevents unnecessary timeout errors and retry attempts when users
    have explicitly disabled the failover feature.
    
    * fix(proxy): handle zero value input in failover config fields
    
    * refactor(proxy): remove retry logic and add enabled check for failover
    
    * refactor(proxy): distinguish circuit-open from no-provider errors
    
    * Align usage stats to sliding windows
    
    * feat(proxy): add body and header filtering for upstream requests
    
    * feat(proxy): enable transparent passthrough for headers
    
    - Passthrough anthropic-beta header as-is from client
    - Passthrough anthropic-version header from client
    - Passthrough client IP headers (x-forwarded-for, x-real-ip) by default
    - Filter private params (underscore-prefixed fields) from request body
    - No database changes required
    
    * feat(proxy): extract session ID from client requests for logging
    
    - Add SessionIdExtractor to parse session ID from Claude/Codex requests
    - Support extraction from metadata.user_id, headers, previous_response_id
    - Pass session_id through RequestContext to usage logger
    - Enable request correlation by session in proxy_request_logs
  • Feat/usage model extraction (#455)
    * feat(proxy): extract model name from API response for accurate usage tracking
    
    - Add model field extraction in TokenUsage parsing for Claude, OpenAI, and Codex
    - Prioritize response model over request model in usage logging
    - Update model extractors to use parsed usage.model first
    - Add tests for model extraction in stream and non-stream responses
    
    * feat(proxy): implement streaming timeout control with validation
    
    - Add first byte timeout (0 or 1-180s) for streaming requests
    - Add idle timeout (0 or 60-600s) for streaming data gaps
    - Add non-streaming timeout (0 or 60-1800s) for total request
    - Implement timeout logic in response processor
    - Add 1800s global timeout fallback when disabled
    - Add database schema migration for timeout fields
    - Add i18n translations for timeout settings
    
    * feat(proxy): add model mapping module for provider-based model substitution
    
    - Add model_mapper.rs with ModelMapping struct to extract model configs from Provider
    - Support ANTHROPIC_MODEL, ANTHROPIC_REASONING_MODEL, and default models for haiku/sonnet/opus
    - Implement thinking mode detection for reasoning model priority
    - Include comprehensive unit tests for all mapping scenarios
    
    * fix(proxy): bypass circuit breaker for single provider scenario
    
    When failover is disabled (single provider), circuit breaker open state
    would block all requests causing poor UX. Now bypasses circuit breaker
    check in this scenario. Also integrates model mapping into request flow.
    
    * feat(ui): add reasoning model field to Claude provider form
    
    Add ANTHROPIC_REASONING_MODEL configuration field for Claude providers,
    allowing users to specify a dedicated model for thinking/reasoning tasks.
    
    * feat(proxy): add openrouter_compat_mode for optional format conversion
    
    Add configurable OpenRouter compatibility mode that enables Anthropic to
    OpenAI format conversion. When enabled, rewrites endpoint to /v1/chat/completions
    and transforms request/response formats. Defaults to enabled for OpenRouter.
    
    * feat(ui): add OpenRouter compatibility mode toggle
    
    Add UI toggle for OpenRouter providers to enable/disable compatibility
    mode which uses OpenAI Chat Completions format with SSE conversion.
    
    * feat(stream-check): use provider-configured model for health checks
    
    Extract model from provider's settings_config (ANTHROPIC_MODEL, GEMINI_MODEL,
    or Codex config.toml) instead of always using default test models.
    
    * refactor(ui): remove timeout settings from AutoFailoverConfigPanel
    
    Remove streaming/non-streaming timeout configuration from failover panel
    as these settings have been moved to a dedicated location.
    
    * refactor(database): migrate proxy_config to per-app three-row structure
    
    Replace singleton proxy_config table with app_type primary key structure,
    allowing independent proxy settings for Claude, Codex, and Gemini.
    Add GlobalProxyConfig queries and per-app config management in DAO layer.
    
    * feat(proxy): add GlobalProxyConfig and AppProxyConfig types
    
    Add new type definitions for the refactored proxy configuration:
    - GlobalProxyConfig: shared settings (enabled, address, port, logging)
    - AppProxyConfig: per-app settings (failover, timeouts, circuit breaker)
    
    * refactor(proxy): update service layer for per-app config structure
    
    Adapt proxy service, handler context, and provider router to use
    the new per-app configuration model. Read enabled/timeout settings
    from proxy_config table instead of settings table.
    
    * feat(commands): add global and per-app proxy config commands
    
    Add new Tauri commands for the refactored proxy configuration:
    - get_global_proxy_config / update_global_proxy_config
    - get_proxy_config_for_app / update_proxy_config_for_app
    Update startup restore logic to read from proxy_config table.
    
    * feat(api): add frontend API and Query hooks for proxy config
    
    Add TypeScript wrappers and TanStack Query hooks for:
    - Global proxy config (address, port, logging)
    - Per-app proxy config (failover, timeouts, circuit breaker)
    - Proxy takeover status management
    
    * refactor(ui): redesign proxy panel with inline config controls
    
    Replace ProxySettingsDialog with inline controls in ProxyPanel.
    Add per-app takeover switches and global address/port settings.
    Simplify AutoFailoverConfigPanel by removing timeout settings.
    
    * feat(i18n): add proxy takeover translations and update types
    
    Add i18n strings for proxy takeover status in zh/en/ja.
    Update TypeScript types for GlobalProxyConfig and AppProxyConfig.
    
    * refactor(proxy): load circuit breaker config per-app instead of globally
    
    Extract app_type from router key and read circuit breaker settings
    from the corresponding proxy_config row for each application.
  • refactor(proxy): modularize handlers.rs to reduce code duplication
    Extract common request handling logic into dedicated modules:
    - handler_config.rs: Usage parser configurations for each API type
    - handler_context.rs: Request lifecycle context management
    - response_processor.rs: Unified streaming/non-streaming response handling
    
    Reduces handlers.rs from ~1130 lines to ~418 lines (-63%), eliminating
    repeated initialization and response processing patterns across the
    four API handlers (Claude, Codex Chat, Codex Responses, Gemini).