Skip to content

Conversation

@GofMan5
Copy link

@GofMan5 GofMan5 commented Feb 7, 2026

Summary

  • Sync the fork branch into upstream review with the latest production changes currently running in GofMan5/main.
  • Include proxy stability/security hardening, thinking-signature/session fixes, and OpenCode CLI sync integration (backend, web API routes, UI card, i18n).
  • Include the fork's architecture refactors and operational fixes accumulated after divergence, so upstream can review and cherry-pick/merge as needed.

Notes

  • Release tag v5.0.9 was published from this state in the fork.
  • If preferred, I can split this into smaller focused PRs after this umbrella PR is opened.

### Major Improvements
- **Traffic-Aware Load Balancing**: LEAST_CONNECTIONS strategy
- **Dynamic Smart Warmup**: Unlocked model list
- **Quota Timers**: Explicit reset countdowns in Accounts & Dashboard

### UX & Visuals
- **Drag & Drop**: Fixed visual offset and jumpiness
- **Layout**: Expanded email column, enabled text wrapping
- **Settings**: Polished header and save button layout

### Fixes
- **Version**: Bumped to 5.0.0 everywhere (including UI)
- **Stability**: Fixed broadcast channel panic
- **Proxy**: Optimized connection handling
…et cap

- fix: API endpoints order Sandbox → Daily → Prod (fixes 403 VALIDATION_REQUIRED)
- fix: Flash models thinking budget auto-cap 24576 (fixes 400 Bad Request)
- feat: dynamic User-Agent with version auto-detection
- feat: User-Agent override support in config
- feat: cache clearing module
- feat: version sync scripts (npm run version:*)
- chore: own signing keys for auto-updater
- chore: improved GitHub Actions release workflow
…rovements

## 🛡️ VALIDATION_REQUIRED (403) Handling
- Added temporary account blocking when receiving 403 VALIDATION_REQUIRED error
- Accounts are automatically blocked for configurable duration (default 10 minutes)
- Auto-unblock when block time expires during token pool reload
- New fields in Account: validation_blocked, validation_blocked_until, validation_blocked_reason
- Yellow animated badge with countdown timer in AccountRow/AccountCard
- Toast notification when account gets blocked
- Settings option: 'Validation Block Duration' in Advanced section
- Returns 503 Service Unavailable if all accounts are blocked

## 🔧 Debug Console
- New built-in debug console for real-time log viewing
- Tracing Layer integration (log_bridge.rs) captures all backend logs
- Zustand store for log management (useDebugConsole.ts)
- Slide panel UI with filtering, copying, and export functionality
- Toggle in Settings → Advanced → Debug Console
- Button in Navbar when enabled

## 🎨 UI Improvements
- Redesigned AddAccountDialog with glassmorphism style
- Framer Motion animations for tabs and content
- Gradient accents for buttons and icons
- Fixed click handling for Add Account button (pointer-events fix)
- Redesigned UpdateNotification in modern dark theme
- Fixed formatTimeRemaining validation for invalid dates
- Added 'SELECTED' badge toggle in Settings (show_proxy_selected_badge)
- Fixed Dashboard background to match Accounts page style
- Fixed model labels in SmartWarmup (Claude 4.5 instead of 3.5)
- Dynamic version display in About section

## 🗑️ Removed Features
- Removed Fixed Account Mode (preferred_account_id) - use Selected mode instead
- Removed Docker build jobs from CI/CD workflow

## 📦 Technical Changes
- Added parking_lot crate for synchronization
- Added single-instance feature flag
- New TypeScript types for validation_blocked fields
- Event listener for account-validation-blocked in App.tsx

Files changed: 35+ files across backend and frontend
…bout, FREE badge fix

Features:
- IP Security: blacklist/whitelist with CIDR matching, access logging
- Navbar: compact pill-navigation with dropdown menu
- Settings About: hero card with gradient border, info grid
- UpdateNotification: animated rocket icon, version comparison

Fixes:
- FREE badge now displays when subscription_tier is undefined
- Select dropdown z-index issue in Settings
- Removed unused imports (build errors)
## FSD Layer Structure (Feature-Sliced Design)

### New FSD Layers Created:
- src/shared/api/ - invoke wrapper, query-client
- src/shared/lib/ - utils, format, clipboard, env, cn
- src/shared/ui/ - 10 reusable UI components (badge, button, card, input, label, progress, select, skeleton, switch, tooltip)
- src/shared/i18n/ - i18n configuration
- src/entities/account/ - Account, QuotaData, DeviceProfile types
- src/entities/config/ - AppConfig types
- src/features/accounts/api/ - 30+ React Query hooks (queries, mutations, keys)
- src/features/proxy/ - proxy feature hooks
- src/features/settings/ - settings feature hooks
- src/features/security/ - security feature hooks
- src/features/stats/ - token stats feature hooks
- src/widgets/layout/ - MainLayout widget
- src/widgets/debug-console/ - DebugConsole widget
- src/widgets/update-notification/ - UpdateNotification widget
- src/app/providers/ - QueryProvider, I18nProvider
- src/app/router/ - routes configuration
- src/app/App.tsx - main App component

### Deleted Legacy Files:
- src/App.tsx (replaced by src/app/App.tsx)
- src/stores/useAccountStore.ts (replaced by FSD hooks)
- src/services/accountService.ts (replaced by FSD mutations)
- src/services/configService.ts (replaced by invoke calls)
- src/hooks/queries/useAccounts.ts (moved to features)
- src/hooks/queries/useCurrentAccount.ts (moved to features)

### Updated Components (FSD imports):
- All 7 pages updated to use FSD imports
- ~25 components migrated to FSD patterns
- UI components now use @/shared/lib/cn

### Bug Fixes:
- Fixed Rust axum ConnectInfo middleware error (made optional)
- Fixed Drag & Drop reorder with pagination (allAccounts prop)
- Fixed DeviceFingerprintDialog openDeviceFolder call

### Configuration:
- tsconfig.json: Added @/ path alias
- vite.config.ts: Added @/ path resolution
- Version bumped to 5.0.4 in package.json, Cargo.toml, tauri.conf.json

### Metrics:
- ~65 new FSD files created
- ~70+ React Query hooks
- 347 lines added, 1023 lines removed (net -676 lines)
- Build time: 8.36s
- Dashboard: 8 FSD files (model/useDashboard, ui/DashboardPage, etc.)
- Accounts: 8 FSD files (model/useAccounts, ui/AccountsPage, etc.)
- Settings: 15 FSD files (model/useSettings, ui/tabs/*, etc.)
- ApiProxy: 15 FSD files (model/useApiProxy, ui/ProxyConfigCard, etc.)
- Security: 12 FSD files (model/useSecurity, ui/BlacklistTab, etc.)
- TokenStats: 8 FSD files (model/useTokenStats, ui/TokenStatsHeader, etc.)
- Monitor: 3 FSD files (ui/MonitorPage)

Total: ~69 new FSD files, 7 monoliths removed (~5161 lines)
Build: OK (3812 modules, 8.34s)
- Updated StatsRow with clean cards without blur

- Enhanced CurrentAccount with Gemini image and quota-level colors

- Improved BestAccounts with compact cards (max 3)

- Changed Add Account button to subtle outline style

- Consistent page background with Accounts page
- Fix FREE accounts count calculation (was excluding accounts without tier)
- Fix FREE filter to include accounts without pro/ultra subscription
- Add useEffect for dropdown menu click-outside to close on background click
- Add fallback for filterCounts display (nullish coalescing)
…cleanup

- Migrate Debug Console to FSD structure (src/widgets/debug-console/)
- Add checkEnabled() call on app start to restore debug console state
- Redesign Security page: single card layout, unified styles
- Redesign Settings page: remove sidebar, add horizontal tabs
- Unify all Settings tabs styling (GeneralTab, AccountTab, ProxyTab, etc.)
- Remove decorative blur elements from SettingsCard and AboutTab
- Add Switch toggle for Validation Block in AdvancedTab
- Remove unused 'Show SELECTED badge' option
- Fix imports: components/ui -> shared/ui
- Delete dead code: AccountRow, StatCard, StatsCard, IpListTable, NetworkMonitor
- Delete duplicate UI components (src/components/ui/) - use shared/ui
- Delete old debug console files (src/components/debug/, src/stores/useDebugConsole.ts)
- Delete unused navbar components (LanguageSelector, NavLink)
- Create SettingsHeader and SettingsTabs components
- Update DebugConsoleButton styling for light/dark mode
- Create Toast and ToastContainer in src/shared/ui/toast/
- Export showToast, ToastContainer, Toast from shared/ui
- Update 19 files to import from @/shared/ui instead of components/common/
- Delete old Toast files from components/common/
- Fix ToastContainer import (named export)
…ared/ui/)

- Create Pagination component in src/shared/ui/pagination/
- Create ModalDialog component in src/shared/ui/modal-dialog/
- Create HelpTooltip component in src/shared/ui/help-tooltip/
- Update exports in src/shared/ui/index.ts
- Update imports in 10 files to use @/shared/ui
- Delete old components from src/components/common/
- Unified styling with zinc color palette
## 🏗️ Feature-Sliced Design (FSD) Migration

This commit completes the full migration to FSD architecture, organizing
the codebase into proper layers: app, pages, widgets, features, entities, shared.

### 📁 New Structure

```
src/
├── app/           # App initialization, router, providers, styles
├── pages/         # Page components with model/ui/lib slices
├── widgets/       # Composite UI blocks (accounts, dashboard, stats, etc.)
├── features/      # Business features (accounts, security, settings, proxy)
├── entities/      # Domain entities (account, security, config)
└── shared/        # Reusable code (api, lib, hooks, config, ui)
```

### ✨ Changes

#### Entities Layer (NEW)
- `entities/account/` - Account domain types
- `entities/security/` - Security domain types (IP lists, access logs, etc.)
- `entities/config/model/store.ts` - Zustand config store (moved from stores/)

#### Shared Layer
- `shared/hooks/useProxyModels.ts` - Proxy models hook
- `shared/config/i18n/` - i18n configuration with all locales
- `shared/ui/debounced-slider/` - DebouncedSlider component
- `shared/ui/grouped-select/` - GroupedSelect component

#### App Layer
- `app/styles/global.css` - Global styles (moved from App.css)
- `app/providers/` - AdminAuthGuard, BackgroundTaskRunner, ThemeManager

#### Widgets Layer
- `widgets/accounts/` - AccountCard, AccountTable, AccountGrid
- `widgets/dashboard/` - BestAccounts, CurrentAccount, StatsRow, Skeleton
- `widgets/proxy/` - ProxyMonitor
- `widgets/stats/` - StatsCharts, StatsSummary, RequestHealthCards

#### Features Layer
- `features/accounts/ui/` - AddAccountDialog, AccountDetailsDialog, DeviceFingerprintDialog
- `features/proxy/ui/` - CliSyncCard
- `features/security/ui/` - AddIpDialog
- `features/settings/ui/` - CircuitBreaker, QuotaProtection, SchedulingSettings, SmartWarmup, PinnedQuotaModels

### 🗑️ Removed (migrated to FSD)
- `src/components/` - All components moved to widgets/features
- `src/stores/` - Moved to entities/config/model
- `src/types/` - Moved to entities/
- `src/utils/` - Moved to shared/lib/
- `src/lib/` - Moved to shared/lib/ and shared/api/
- `src/hooks/` - Moved to shared/hooks/
- `src/locales/` - Moved to shared/config/i18n/locales/
- `src/i18n.ts` - Moved to shared/config/i18n/
- `src/App.css` - Moved to app/styles/global.css

### 🔧 Updated Imports (21 files)
All imports updated to use FSD paths:
- `@/stores/useConfigStore` → `@/entities/config`
- `@/types/security` → `@/entities/security`
- `@/utils/format` → `@/shared/lib`
- `@/hooks/useProxyModels` → `@/shared/hooks`
- `@/shared/i18n` → `@/shared/config/i18n`

### 🦀 Rust Backend
- Updated `src-tauri/src/modules/i18n.rs` to use new locales path

### 📊 Stats
- 92 files changed
- ~17,000 lines reorganized
- 100% FSD compliance
- Redesign AccountDetailsDialog with unified project style (zinc palette, Framer Motion)
- Restore DeviceFingerprintDialog from original (DeviceProfile with machine_id, history, confirm dialog)
- Fix drag-and-drop reorder lag (optimistic update in useReorderAccounts)
- Add smart menu positioning (up/down based on row position)
- Make action menu more compact to prevent overflow
- Remove empty space below accounts list
- Increase email column width (240px -> 280px), actions (44px -> 64px)
- Add missing i18n keys (common.switch, accounts.toggle_proxy)
- Add light/dark mode support for all dialogs
- Toast: Framer Motion animations, progress bar with hover pause, bottom-right position
- Toast: Color-coded left bar and icon backgrounds (emerald/rose/amber/indigo)
- Toast: AnimatePresence for smooth removal, stack from bottom up
- ModalDialog: Framer Motion animations (scale + fade)
- ModalDialog: Escape key to close, unified color scheme
- ModalDialog: Removed backdrop blur, reduced shadow (shadow-lg)
- ModalDialog: Compact icon size, border for dark mode visibility
- Split 800-line commands/mod.rs into 8 focused modules:
  - account.rs: Account CRUD operations
  - device.rs: Device fingerprint management
  - oauth.rs: OAuth authentication flow
  - import.rs: Import/migration commands
  - quota.rs: Quota management and warmup
  - config.rs: Configuration management
  - stats.rs: Token statistics
  - system.rs: File ops, windows, updates

- Enhanced error.rs with comprehensive AppError enum:
  - Added 20+ error variants (Validation, RateLimit, Proxy, etc.)
  - Structured JSON serialization for frontend
  - Helper methods and ResultExt trait for migration

- Added shared/db_pool.rs for SQLite connection pooling:
  - r2d2 integration for rusqlite
  - Pool registry with lazy initialization
  - Eliminates 'Too many open files' issues

- Updated lib.rs invoke_handler with full module paths
- Fixed proxy/server.rs to use new command paths

Dependencies added: r2d2 0.8, r2d2_sqlite 0.25
- Extract types and response structs to server/types.rs
- Split admin handlers into server/admin/ submodules:
  - accounts.rs: Account CRUD, OAuth, device binding, warmup
  - proxy.rs: Proxy control, logs, cloudflared, CLI sync
  - stats.rs: Token statistics endpoints
  - system.rs: Configuration, updates, file operations
  - import.rs: Import/migration handlers
- Move OAuth callback to server/oauth.rs
- Create server/routes.rs with route definitions
- Main server logic remains in server/mod.rs

Breaking down 2070-line god-file into ~10 focused modules
for better maintainability and code navigation.
- Extract handle_chat_completions to openai/chat.rs
- Extract handle_completions to openai/completions.rs
- Extract handle_images_* to openai/images.rs
- Extract handle_list_models to openai/models.rs
- Update handlers/mod.rs to reference directory module

Original: 2020 lines -> 4 focused modules (~30-520 lines each)
- Extract handle_messages to claude/messages.rs
- Extract handle_list_models to claude/models.rs
- Extract handle_count_tokens to claude/tokens.rs
- Extract warmup detection to claude/warmup.rs
- Extract background task detection to claude/background.rs
- Extract Layer 3 compression to claude/compression.rs
- Update handlers/mod.rs to reference directory module

Original: 1748 lines -> 6 focused modules (~30-750 lines each)
New features:
- Add StatsTab.tsx with full security statistics dashboard
- 5 stat cards: Total Requests, Unique IPs, Blocked, Blacklisted, Whitelisted
- IP Token Usage table with progress bars (Top 15 IPs)
- Time range selector (1h/24h/7d/30d)
- Top Blocked IPs display
- Auto-refresh every 30s/60s

API updates:
- Add useSecurityStats() hook -> security_get_stats
- Add useIpTokenStats(hours) hook -> security_get_ip_token_stats
- Add IpTokenStats type to entities/security
- Add stats/ipTokenStats query keys

UI updates:
- Add Stats tab as first tab in SecurityTabs
- Hide toolbar for Stats tab (has its own controls)
- Update SecurityPage to render StatsTab
- Modern glassmorphism design with gradients and animations
- Use createPortal to render modal to document.body
- Add proper z-index (100) and flex centering
- Add Escape key handler and body scroll lock
- Match ModalDialog design patterns (light/dark mode support)
- Compact duration presets (10m/1h/24h/7d/30d/∞)
- Use project color tokens (rose, emerald, zinc)
- Add Tauri drag region for window dragging
- Consistent border radius, padding, and typography
Phase 1 - Server Stability Improvements:
- Replace std::sync::RwLock with DashSet for pending account reloads (non-blocking)
- Add Semaphore for connection limiting (10K max, configurable via ABV_MAX_CONNECTIONS)
- Add HTTP/2 support via hyper-util auto-detection with HTTP/1.1 fallback
- Increase upstream connection pool from 16 to 64 (configurable via ABV_POOL_SIZE)
- Track active connections count for monitoring
- Graceful rejection when connection limit reached
Phase 2 - Selection Logic Improvements:
- Fix timeout message to show actual 5s instead of incorrect 120s
- Implement strict_selected logic with fallback to all accounts when disabled
- Fix optimistic reset to only clear expired/near-expired rate limits (5s buffer)
  instead of clearing ALL records which caused cascade 429 errors
- Fix race condition in round-robin index with safe modulo operation
- Replace blocking std::fs::write with async tokio::fs::write in quota.rs
- Remove duplicate config loading (quota_protection_enabled)
- Add clear_expired_with_buffer() method for safer optimistic reset
Phase 3 - Quality & Features:
- Add P2C (Power-of-2-Choices) scheduling mode to reduce hot-spot issues
  Randomly picks 2 accounts, selects the one with higher quota
- Hide max_wait_seconds for Selected mode (only used in CacheFirst)
- Fix model normalization consistency in quota protection (trigger/restore)
- Make selected_models and strict_selected required in TypeScript types
- Add graceful connection draining on server shutdown (30s max wait)
- Add Shuffle icon for P2C mode in UI
- Fix compilation errors
load_accounts() now validates account files against account_index.json
before loading. Orphaned files (deleted from index but still on disk)
are skipped, preventing race conditions where background operations
could resurrect deleted accounts.
- New /logs page with FSD architecture (pages/logs/)
- Real-time updates via Tauri events + 3s polling
- Auto-refresh toggle button in header
- Compact table design with zebra stripes
- Protocol badges (OpenAI/Claude/Gemini)
- Duration color coding (red >5s, yellow >2s)
- Token display inline (input/output)
- Quick filters: All/Errors/Chat/Gemini/Claude/Images
- Account filter dropdown
- Clear logs with confirmation dialog
- Log detail modal with request/response payloads
- Fixed .gitignore to allow src/pages/logs directory
Auto-update via Tauri updater was unreliable, now opens
GitHub releases page in browser instead. Simplified UI
with single 'Download from GitHub' button.
- Split 1026-line monolith into 6 focused modules
- selection/mod.rs: main get_token logic
- selection/scoring.rs: sort_tokens by priority
- selection/sticky.rs: sticky session handling
- selection/round_robin.rs: round-robin selection
- selection/token_ops.rs: token refresh + project ID
- selection/p2c.rs: P2C algorithm + availability check
- Public API unchanged (get_token, has_available_account)
- Split 723-line monolith into 7 focused modules
- commands/proxy/types.rs: ProxyStatus, ProxyServiceState, instances
- commands/proxy/lifecycle.rs: start/stop/ensure_admin_server
- commands/proxy/status.rs: get_status, get_stats, monitoring
- commands/proxy/logs.rs: paginated logs, filtering, export
- commands/proxy/config.rs: api_key, model_mapping, scheduling
- commands/proxy/external.rs: z.ai fetch_models
- commands/proxy/accounts.rs: reload, preferred account, rate limits
- All Tauri commands unchanged (public API preserved)
… refactor rate_limit module

- Add remaining_quota <= 0 check in filter_tokens() to exclude accounts with zero quota
- Fix P2C mode: pre-filter rate limited accounts before selection (was missing)
- Refactor rate_limit.rs into modular structure (types.rs, parsing.rs, mod.rs)
- Remove blocking is_rate_limited_sync() from filter_tokens() to prevent deadlock
- Bump version to 5.0.6
- lifecycle.rs: Reuse existing TokenManager from AxumServer instead of creating orphaned instance
- selection/mod.rs: Fix overly aggressive fuzzy matching that blocked claude-opus-4-5-thinking when claude-opus-4 had 0% quota
- useApiProxy.ts: Add sync of scheduling config to running proxy service
@ZaneL1u
Copy link
Contributor

ZaneL1u commented Feb 7, 2026

image

The scope of this PR is quite large, which can make reviewing and tracking potential issues harder.
Breaking it down into smaller, focused PRs could make the review and merge process smoother. Just a suggestion.


这么大规模的变更可能会增加 review 和回归风险。 一般将改动拆分为多个小 PR 会更容易 Review 和定位问题,供参考。

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.

2 participants