mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-10-24 04:32:07 +08:00
db024c5ddb8ea3b27c5eeea23ac1e2793ae37f56
129
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
84312a5cd1 |
fix(sysproxy): bypass *.local by default on Windows (#8054)
Hostnames such as mi13.local are resolved by mDNS on the local network, which the proxy core cannot do, so they failed with 'couldn't find ip' while the system proxy was on. The macOS default already bypasses *.local. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
a640010bc3 |
fix(clippy): Restrict 2 imports to macOS only (#7858)
* fix(clippy): Remove 2 unused imports - Drop 2 unused imports according to clippy suggestions * fix(clippy): Re-add 2 imports and limit to macOS - Those "unused imports" are only for Windows and Linux - macOS environment requires those identifiers |
||
|
|
ef042ddf82 | fix(sysproxy): stop turning a missing network service into a hard failure | ||
|
|
0d3f141f20 | test: remove redundant backend coverage | ||
|
|
b80bca01da | fix: unblock pre-push checks | ||
|
|
349c635de0 |
fix(sysproxy): use platform-specific bypass separator (#7559)
* fix(sysproxy): use platform bypass separator * refactor: squash conditional compilation logic - Share a single `BYPASS_SEPERATOR` definition between both Linux and macOS --------- Co-authored-by: Ayanami <ay@nami.ltd> Co-authored-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com> Co-authored-by: oomeow <oomeow@outlook.com> |
||
|
|
9b9feb9a39 | fix: handle proxy cleanup failures during app exit | ||
|
|
22947632c0 |
refactor: Rewrite and improve sysproxy logic (#7744)
* fix(cmd): preserve anyhow context in coded errors Use alternate error formatting so coded failures retain the full anyhow context chain without changing their wire format. * fix(macos): skip redundant proxy disable writes When both proxy modes are off, read macOS state first and skip networksetup if the OS is already clean. Update the guard target only after a successful write. * feat(proxy): classify system proxy failures Attach stable, actionable proxy failure codes to anyhow chains while preserving the original diagnostic causes. * feat(cmd): return structured command failures Replace encoded error strings with serializable code and detail fields, and update frontend notice consumers to handle the structured shape. * fix(scripts): use the js-yaml namespace import Import js-yaml through its ESM namespace so the i18n cleanup script can access load and dump. * feat(proxy): localize classified proxy failures Map privilege and direct-fallback codes to localized explanations, and let mapped causes outrank generic operation keys in notices. * fix(ui): bound notice text and render failure details Limit resolved notice text without truncating clipboard content, and normalize structured failures embedded in translation parameters. * feat(proxy): persist unseen proxy failures Store unresolved classified failures by code, notify the frontend when the table changes, and show each failure sequence once when a visible window can receive it. * feat(proxy): report tray and hotkey toggle failures Record classified failures from tray and hotkey proxy toggles so they appear when a visible window is available. * fix(ui): restore the proxy switch after failed toggles Refresh frontend proxy state after a failed toggle so the switch reflects the rolled-back configuration. * feat(proxy): stop the guard after repeated failures Report guard outcomes, stop after the failure threshold, and persist the classified failure for the frontend. * fix(macos): preserve proxy during service handoff Stop a sidecar being handed to the service without clearing proxy state that the new owner must inherit. * feat(macos): classify misplaced sidecar state Distinguish a refused sidecar proxy write from a machine that still needs the privileged service installed. * feat(ui): recover misplaced sidecar notices Offer a restart action for macOS proxy failures caused by a ready service while the core still runs as a sidecar. * feat(ui): install the service from proxy notices Let privilege notices install the macOS service, restart the core, and report the runtime mode that was actually reached. * feat(cmd): attach requested proxy operations Carry the requested proxy direction with structured command failures when the originating command knows it. * feat(sysproxy): drain guards before OS access Wait for the local proxy guard to stop before OS reads, service handoff, or final writes, and refuse transitions when it does not drain. * feat(sysproxy): recover partial proxy writes Use write progress to choose whether to restore the old guard or compensate with a disabled proxy state, while preserving actionable errors. * feat(sysproxy): skip already-applied proxy writes Compare macOS proxy snapshots with global, PAC, and disabled targets so matching state avoids redundant privileged writes. * feat(proxy): report background proxy failures Persist and surface classified proxy failures from lifecycle paths that have no direct caller awaiting the result. * feat(ui): move proxy recovery into a dialog Guide users through installing or switching to the service after a refused proxy write, and suppress duplicate toast reports. * fix(ui): close proxy dialog after service recovery Dismiss the recovery dialog once the core reaches service mode, even when the original proxy request remains pending. * feat(ui): retry proxy request after service recovery Replay the requested proxy direction after the core reaches service mode, while leaving incidental restores unchanged. * fix(proxy): refresh state after successful apply Publish the proxy refresh from the shared apply path after releasing the lifecycle lock, and remove the tray-specific duplicate. * feat(ui): show proxy recovery progress Display installation, restart, and proxy-apply stages while keeping the primary action spinner visible during recovery. * feat(ui): route unavailable TUN through service recovery Let the TUN switch request service recovery and restore its requested state after the core restarts in service mode. * fix(ui): avoid duplicate TUN recovery errors Roll back deferred TUN toggles without reporting an error, and publish configuration refreshes from the transaction commit path. * chore: update changelog & pinlock * fix(core): resolve platform-specific clippy warnings * fix(core): detect Windows wildcard TCP conflicts Windows permits a specific exclusive bind beside an existing non-exclusive wildcard listener. Consult the system TCP listener table so the probe reports that overlap as a conflict. |
||
|
|
c90de1355e |
refactor: core runstate (#7602)
* refactor(core): introduce core::runstate as the owner of Run State
"Is the Service available?" had five caches and three predicates, and
prepare_startup consulted all three within thirty lines. This lands the
foundation for collapsing that, with no behaviour change: the old owners
now delegate into one store.
The state model splits observation from intent. Five of ServiceStatus's
ten variants were never observations — cmd/service.rs passed
ServiceStatus::InstallRequired as the "which operation do you want"
argument — which is why narrowing to ServiceInstallState had to be lossy.
ServiceHealth now records what we saw, PendingAction records what the
session asked for, and ServiceStatus::from_run_state flattens the pair
for call sites that still expect the single slot.
Reads differ only in freshness: state() is cached, settled() waits for an
in-flight privileged operation, probe() forces IPC. What an answer means
lives on the snapshot (service_usable, tun_capable), so callers stop
writing their own formulas — the tray now asks tun_capable() instead of
recomputing "admin or ready".
Effects sit behind RunStateEnv with two adapters, RealEnv and FakeEnv.
That retires the seven tests that hand-built a private ServiceManager
struct literal, and makes the probe and detection paths testable for the
first time.
Two distinctions are now explicit rather than incidental:
- A single failed probe is not an observation and leaves confirmed
health intact; exhausting a poll's whole retry budget is one and
records unavailable. Both are tested, protecting
|
||
|
|
23dda47641 |
feat: add launch guard and secure multi-user service ownership (#7569)
* feat(service): isolate macOS launch and owner runtime * ci(windows): run owner security tests * chore(deps): use kode-bridge v0.4.1 tag * fix(macos): classify installed service state * fix(macos): classify marked unavailable service * fix(macos): gate core startup on service migration * fix(macos): scope service init to supported platforms * feat(macos): prompt before migrating installed service * fix(macos): shorten sidecar IPC path * build(service): pin helper protocol and artifacts * fix(core): require confirmed service and sidecar readiness * fix(macos): harden launch roots and singleton state * fix(ui): refresh migration state before restart * fix(macos): linearize service migration lifecycle * fix(ui): keep service migration state fresh * feat(service): track authenticated owner sessions * fix(service): preserve newer owner sessions * feat(macos): route service proxy changes through helper * fix(macos): serialize service proxy guard * fix(macos): close service proxy owner lifecycle * fix(macos): close remaining proxy stop races * fix(app): do not cancel controlled service stop * fix(lifecycle): keep controlled updates cancellation-safe * fix(macos): stage dev core for service * test(macos): exercise staged core cleanup * fix(dev): await controlled macOS exit * chore: update changelog * fix(macos): recover sidecar after service install failure Allow the existing sidecar to continue when service installation leaves the manager in InstallRequired, then settle the session state as SidecarAllowed. Show neutral status text while the migration dialog waits for its final state. * fix(macos): stage dev service tools before elevation * fix(macos): localize launch guard prompts * fix(service): address cross-platform integration issues * feat: support seamless service migration * fix: pass Windows service installer path safely * fix(prebuild): derive service release from Cargo dependency * fix(dev): preserve service installation state * fix: resolve clippy warnings in service lifecycle |
||
|
|
761209bbbc |
refactor: backend (#7102)
* refactor(tray): move tray log opening to utils helper * refactor(enhance): move owned config through pipeline * refactor(enhance): move sequence values in use_seq * refactor(enhance): move values while sorting fields * refactor(enhance): move values when lowercasing owned config * refactor(backend): move owned config values in utilities * refactor(tray): borrow hotkey accelerators * refactor(core): borrow proxy config strings * fix(backend): preserve config patch semantics * refactor(enhance): clarify config transform names |
||
|
|
09e491885f |
fix: stop disabled system proxy guard
close #7004 |
||
|
|
20808c0c11 | fix(sysproxy): preserve global proxy apply order #6760, #6832, #6790, #6793, #6801 | ||
|
|
4d408a8c1a | fix: serialize OS state reads with in-progress update_sysproxy | ||
|
|
ca8e350694 |
fix(proxy): resolve system proxy toggle stuck and state desync (#6614) (#6657)
* fix(proxy): resolve system proxy toggle stuck and state desync (#6614) Backend: replace hand-rolled AtomicBool lock in update_sysproxy() with tokio::sync::Mutex so concurrent calls wait instead of being silently dropped, ensuring the latest config is always applied. Move blocking OS calls (networksetup on macOS) to spawn_blocking so they no longer stall the tokio worker thread pool. Frontend: release SwitchRow pendingRef in .finally() so the UI always re-syncs with the actual OS proxy state, and rollback checked on error. Closes #6614 * fix(changelog): add note for macOS proxy toggle freeze issue |
||
|
|
77fa721119 | fix(sysproxy): fully clear PAC when disabling system proxy (#6591) | ||
|
|
fe60649718 | refactor(core): move autostart logic out of sysopt and clean up naming (#6429) | ||
|
|
65b4d8713d |
refactor: windows autostart (#5941)
* refactor(windows-autostart): switch to scheduled tasks with user/admin split * fix(schtasks): decode stdout/stderr using Windows OEM/ANSI code pages * refactor(ui): remove admin auto-launch warning and clean i18n * feat(windows): user-level auto-launch via task XML * docs: Changelog.md |
||
|
|
9713343323 |
refactor: use sysproxy-rs to set system proxy on windows (#5846)
* refactor: use sysproxy-rs to set system proxy on windows * fix: remove download sysproxy.exe task * chore: unified processing system proxy reset * docs: update Changelog.md |
||
|
|
2ca8e6716d | style: adjust rustfmt max_width to 120 | ||
|
|
a0fd24bb90 | refactor(sysopt): replace Mutex with RwLock for inner_proxy management | ||
|
|
6456c597ed |
perf: spawn clean task (#5595)
* perf: spawn task * perf: spawn task to save draft date * perf: store proxy client * chore: update * perf: reduce handle quit on macOS * chore: clippy * docs: update Changelog.md * chore: update |
||
|
|
871881c460 | fix(resolve): implement resolve_done state management and refactor timer logic | ||
|
|
687530a9cd |
fix(sysproxy): remove redundant 172.29.0.0/16 entry #4351
Closes #4351 |
||
|
|
d8090277af | refactor: replace singleton_lazy with singleton macro across multiple modules | ||
|
|
0866b93175 |
feat(logging): introduce clash-verge-logging crate for management (#5486)
* feat(logging): introduce clash-verge-logging crate for management - Added a new crate `clash-verge-logging` with dependencies on `log`, `tokio`, `compact_str`, and `flexi_logger`. - Implemented logging types and macros for structured logging across the application. - Replaced existing logging imports with the new `clash_verge_logging` crate in various modules. - Updated logging functionality to support different logging types and error handling. - Refactored code to improve logging consistency and maintainability. * fix(logging): update import paths for clash_verge_logging in linux.rs and dns.rs * fix(logging): update import statement for clash_verge_logging in windows.rs |
||
|
|
8654bad6b0 |
refactor: migrate proxy setting guard to sysproxy-rs crate (#5287)
* Refactor proxy management: Remove EventDrivenProxyManager and async_proxy_query - Removed the EventDrivenProxyManager and its related event-driven proxy management logic. - Replaced usages of AsyncProxyQuery with direct calls to sysproxy for fetching system and auto proxy configurations. - Cleaned up constants by removing unused default proxy host. - Updated sysopt to eliminate calls to the removed EventDrivenProxyManager. - Adjusted logging and proxy state management to reflect the removal of event-driven architecture. - Simplified the core module structure by removing unnecessary module imports. * refactor: remove bypass module for cleaner network configuration * feat: update sysproxy to version 0.4.0 and add guard feature; refactor sysopt for improved proxy management * feat(windows/sysproxy): unify guard-type handling and auto-restore drift * refactor(config): remove commented-out code for SysProxy update flag --------- Co-authored-by: Slinetrac <realakayuki@gmail.com> |
||
|
|
a6cb903fe6 | refactor: simplify function return types and remove unnecessary wraps | ||
|
|
0dcdd7fed6 | fix: clippy lint | ||
|
|
4eeb883464 | refactor: update imports to use as _ for unused identifiers across multiple files | ||
|
|
671ac2ebed | refactor: replace type references with Self in various structs and methods for consistency | ||
|
|
2287ea5f0b |
Refactor configuration access to use latest_arc() instead of latest_ref()
- Updated multiple instances in the codebase to replace calls to latest_ref() with latest_arc() for improved performance and memory management. - This change affects various modules including validate, enhance, feat (backup, clash, config, profile, proxy, window), utils (draft, i18n, init, network, resolve, server). - Ensured that all references to configuration data are now using the new arc-based approach to enhance concurrency and reduce cloning overhead. refactor: update imports to explicitly include ClashInfo and Config in command files |
||
|
|
34cac0fa3a | feat: improve subscription update method and enhance error handling for profile updates | ||
|
|
fb260fb33d |
Refactor logging to use a centralized logging utility across the application (#5277)
- Replaced direct log calls with a new logging macro that includes a logging type for better categorization. - Updated logging in various modules including `merge.rs`, `mod.rs`, `tun.rs`, `clash.rs`, `profile.rs`, `proxy.rs`, `window.rs`, `lightweight.rs`, `guard.rs`, `autostart.rs`, `dirs.rs`, `dns.rs`, `scheme.rs`, `server.rs`, and `window_manager.rs`. - Introduced logging types such as `Core`, `Network`, `ProxyMode`, `Window`, `Lightweight`, `Service`, and `File` to enhance log clarity and filtering. |
||
|
|
9ea9704bbf | refactor(sysopt): replace Arc<TokioMutex> with AtomicBool for sysproxy state management | ||
|
|
a05ea64bcd |
perf: utilize smartstring for string handling (#5149)
* perf: utilize smartstring for string handling - Updated various modules to replace standard String with smartstring::alias::String for improved performance and memory efficiency. - Adjusted string manipulations and conversions throughout the codebase to ensure compatibility with the new smartstring type. - Enhanced readability and maintainability by using `.into()` for conversions where applicable. - Ensured that all instances of string handling in configuration, logging, and network management leverage the benefits of smartstring. * fix: replace wrap_err with stringify_err for better error handling in UWP tool invocation * refactor: update import path for StringifyErr and adjust string handling in sysopt * fix: correct import path for CmdResult in UWP module * fix: update argument type for execute_sysproxy_command to use std::string::String * fix: add missing CmdResult import in UWP platform module * fix: improve string handling and error messaging across multiple files * style: format code for improved readability and consistency across multiple files * fix: remove unused file |
||
|
|
a5c00ecb12 | fix: faile to reset sysproxy (#5139) | ||
|
|
7c71d07ad2 |
refactor: convert synchronous file operations to asynchronous for improved performance (#5059)
* refactor: convert synchronous file operations to asynchronous for improved performance * fix: update copy_icon_file to use asynchronous directory creation * refactor: remove unnecessary variable assignments in shortcut management functions |
||
|
|
924e7d1022 |
Refactor string handling to use into() instead of to_string() for improved performance and consistency across the codebase. This change affects various modules including app.rs, clash.rs, config.rs, core.rs, service.rs, and others, ensuring that string conversions are streamlined and more idiomatic.
|
||
|
|
8c0af66ca9 |
Refactor logging macros to remove print control parameter
- Updated logging macros to eliminate the boolean parameter for print control, simplifying the logging calls throughout the codebase. - Adjusted all logging calls in various modules (lib.rs, lightweight.rs, help.rs, init.rs, logging.rs, resolve/mod.rs, resolve/scheme.rs, resolve/ui.rs, resolve/window.rs, server.rs, singleton.rs, window_manager.rs) to reflect the new macro structure. - Ensured consistent logging behavior across the application by standardizing the logging format. |
||
|
|
7fc238c27b |
refactor: invock mihomo api by use tauri-plugin-mihomo (#4926)
* feat: add tauri-plugin-mihomo
* refactor: invock mihomo api by use tauri-plugin-mihomo
* chore: todo
* chore: update
* chore: update
* chore: update
* chore: update
* fix: incorrect delay status and update pretty config
* chore: update
* chore: remove cache
* chore: update
* chore: update
* fix: app freezed when change group proxy
* chore: update
* chore: update
* chore: add rustfmt.toml to tauri-plugin-mihomo
* chore: happy clippy
* refactor: connect mihomo websocket
* chore: update
* chore: update
* fix: parse bigint to number
* chore: update
* Revert "fix: parse bigint to number"
This reverts commit
|
||
|
|
dbcad24093 | refactor: Uses tokio Command with CREATE_NO_WINDOW flag to avoid DLL initialization issues during shutdown | ||
|
|
251678493c |
edition 2024 (#4702)
* feat: update Cargo.toml for 2024 edition and optimize release profiles * feat: refactor environment variable settings for Linux and improve code organization * Refactor conditional statements to use `&&` for improved readability - Updated multiple files to combine nested `if let` statements using `&&` for better clarity and conciseness. - This change enhances the readability of the code by reducing indentation levels and making the conditions more straightforward. - Affected files include: media_unlock_checker.rs, profile.rs, clash.rs, profiles.rs, async_proxy_query.rs, core.rs, handle.rs, hotkey.rs, service.rs, timer.rs, tray/mod.rs, merge.rs, seq.rs, config.rs, proxy.rs, window.rs, general.rs, dirs.rs, i18n.rs, init.rs, network.rs, and window.rs in the resolve module. * refactor: streamline conditional checks using `&&` for improved readability * fix: update release profile settings for panic behavior and optimization * fix: adjust optimization level in Cargo.toml and reorder imports in lightweight.rs |
||
|
|
55b95a1985 |
Revert "feat: update Cargo.toml for 2024 edition and optimize release profiles (#4681)"
This reverts commit
|
||
|
|
31e3104c7f |
feat: update Cargo.toml for 2024 edition and optimize release profiles (#4681)
* feat: update Cargo.toml for 2024 edition and optimize release profiles * feat: refactor environment variable settings for Linux and improve code organization * Refactor conditional statements to use `&&` for improved readability - Updated multiple files to combine nested `if let` statements using `&&` for better clarity and conciseness. - This change enhances the readability of the code by reducing indentation levels and making the conditions more straightforward. - Affected files include: media_unlock_checker.rs, profile.rs, clash.rs, profiles.rs, async_proxy_query.rs, core.rs, handle.rs, hotkey.rs, service.rs, timer.rs, tray/mod.rs, merge.rs, seq.rs, config.rs, proxy.rs, window.rs, general.rs, dirs.rs, i18n.rs, init.rs, network.rs, and window.rs in the resolve module. * refactor: streamline conditional checks using `&&` for improved readability |
||
|
|
355a18e5eb |
refactor(async): migrate from sync-blocking async execution to true async with unified AsyncHandler::spawn (#4502)
* feat: replace all tokio::spawn with unified AsyncHandler::spawn - 🚀 Core Improvements: * Replace all tokio::spawn calls with AsyncHandler::spawn for unified Tauri async task management * Prioritize converting sync functions to async functions to reduce spawn usage * Use .await directly in async contexts instead of spawn - 🔧 Major Changes: * core/hotkey.rs: Use AsyncHandler::spawn for hotkey callback functions * module/lightweight.rs: Async lightweight mode switching * feat/window.rs: Convert window operation functions to async, use .await internally * feat/proxy.rs, feat/clash.rs: Async proxy and mode switching functions * lib.rs: Window focus handling with AsyncHandler::spawn * core/tray/mod.rs: Complete async tray event handling - ✨ Technical Advantages: * Unified task tracking and debugging capabilities (via tokio-trace feature) * Better error handling and task management * Consistency with Tauri runtime * Reduced async boundaries for better performance - 🧪 Verification: * Compilation successful with 0 errors, 0 warnings * Maintains complete original functionality * Optimized async execution flow * feat: complete tokio fs migration and replace tokio::spawn with AsyncHandler 🚀 Major achievements: - Migrate 8 core modules from std::fs to tokio::fs - Create 6 Send-safe wrapper functions using spawn_blocking pattern - Replace all tokio::spawn calls with AsyncHandler::spawn for unified async task management - Solve all 19 Send trait compilation errors through innovative spawn_blocking architecture 🔧 Core changes: - config/profiles.rs: Add profiles_*_safe functions to handle Send trait constraints - cmd/profile.rs: Update all Tauri commands to use Send-safe operations - config/prfitem.rs: Replace append_item calls with profiles_append_item_safe - utils/help.rs: Convert YAML operations to async (read_yaml, save_yaml) - Multiple modules: Replace tokio::task::spawn_blocking with AsyncHandler::spawn_blocking ✅ Technical innovations: - spawn_blocking wrapper pattern resolves parking_lot RwLock Send trait conflicts - Maintain parking_lot performance while achieving Tauri async command compatibility - Preserve backwards compatibility with gradual migration strategy 🎯 Results: - Zero compilation errors - Zero warnings - All async file operations working correctly - Complete Send trait compliance for Tauri commands * feat: refactor app handle and command functions to use async/await for improved performance * feat: update async handling in profiles and logging functions for improved error handling and performance * fix: update TRACE_MINI_SIZE constant to improve task logging threshold * fix(windows): convert service management functions to async for improved performance * fix: convert service management functions to async for improved responsiveness * fix(ubuntu): convert install and reinstall service functions to async for improved performance * fix(linux): convert uninstall_service function to async for improved performance * fix: convert uninstall_service call to async for improved performance * fix: convert file and directory creation calls to async for improved performance * fix: convert hotkey functions to async for improved responsiveness * chore: update UPDATELOG.md for v2.4.1 with major improvements and performance optimizations |
||
|
|
537d27d10b |
fix: clippy errors with new config (#4428)
* refactor: improve code quality with clippy fixes and standardized logging
- Replace dangerous unwrap()/expect() calls with proper error handling
- Standardize logging from log:: to logging\! macro with Type:: classifications
- Fix app handle panics with graceful fallback patterns
- Improve error resilience across 35+ modules without breaking functionality
- Reduce clippy warnings from 300+ to 0 in main library code
* chore: update Cargo.toml configuration
* refactor: resolve all clippy warnings
- Fix Arc clone warnings using explicit Arc::clone syntax across 9 files
- Add #[allow(clippy::expect_used)] to test functions for appropriate expect usage
- Remove no-effect statements from debug code cleanup
- Apply clippy auto-fixes for dbg\! macro removals and path statements
- Achieve zero clippy warnings on all targets with -D warnings flag
* chore: update Cargo.toml clippy configuration
* refactor: simplify macOS job configuration and improve caching
* refactor: remove unnecessary async/await from service and proxy functions
* refactor: streamline pnpm installation in CI configuration
* refactor: simplify error handling and remove unnecessary else statements
* refactor: replace async/await with synchronous locks for core management
* refactor: add workflow_dispatch trigger to clippy job
* refactor: convert async functions to synchronous for service management
* refactor: convert async functions to synchronous for UWP tool invocation
* fix: change wrong logging
* refactor: convert proxy restoration functions to async
* Revert "refactor: convert proxy restoration functions to async"
This reverts commit
|
||
|
|
b1e2940db6 |
refactor: optimize singleton macro usage with Default trait implementations (#4279)
* refactor: implement DRY principle improvements across backend
Major DRY violations identified and addressed:
1. **IPC Stream Monitor Pattern**:
- Created `utils/ipc_monitor.rs` with generic `IpcStreamMonitor` trait
- Added `IpcMonitorManager` for common async task management patterns
- Eliminates duplication across traffic.rs, memory.rs, and logs.rs
2. **Singleton Pattern Duplication**:
- Created `utils/singleton.rs` with `singleton\!` and `singleton_with_logging\!` macros
- Replaces 16+ duplicate singleton implementations across codebase
- Provides consistent, tested patterns for global instances
3. **macOS Activation Policy Refactoring**:
- Consolidated 3 duplicate methods into single parameterized `set_activation_policy()`
- Eliminated code duplication while maintaining backward compatibility
- Reduced maintenance burden for macOS-specific functionality
These improvements enhance maintainability, reduce bug potential, and ensure consistent patterns across the backend codebase.
* fix: resolve test failures and clippy warnings
- Fix doctest in singleton.rs by using rust,ignore syntax and proper code examples
- Remove unused time::Instant import from ipc_monitor.rs
- Add #[allow(dead_code)] attributes to future-use utility modules
- All 11 unit tests now pass successfully
- All clippy checks pass with -D warnings strict mode
- Documentation tests properly ignore example code that requires full context
* refactor: migrate code to use new utility tools (partial)
Progress on systematic migration to use created utility tools:
1. **Reorganized IPC Monitor**:
- Moved ipc_monitor.rs to src-tauri/src/ipc/monitor.rs for better organization
- Updated module structure to emphasize IPC relationship
2. **IpcManager Singleton Migration**:
- Replaced manual OnceLock singleton pattern with singleton_with_logging\! macro
- Simplified initialization code and added consistent logging
- Removed unused imports (OnceLock, logging::Type)
3. **ProxyRequestCache Singleton Migration**:
- Migrated from once_cell::sync::OnceCell to singleton\! macro
- Cleaner, more maintainable singleton pattern
- Consistent with project-wide singleton approach
These migrations demonstrate the utility and effectiveness of the created tools:
- Less boilerplate code
- Consistent patterns across codebase
- Easier maintenance and debugging
* feat: complete migration to new utility tools - phase 1
Successfully migrated core components to use the created utility tools:
- Moved `ipc_monitor.rs` to `src-tauri/src/ipc/monitor.rs`
- Better organization emphasizing IPC relationship
- Updated module exports and imports
- **IpcManager**: Migrated to `singleton_with_logging\!` macro
- **ProxyRequestCache**: Migrated to `singleton\!` macro
- Eliminated ~30 lines of boilerplate singleton code
- Consistent logging and initialization patterns
- Removed unused imports (OnceLock, once_cell, logging::Type)
- Cleaner, more maintainable code structure
- All 11 unit tests pass successfully
- Zero compilation warnings
- **Lines of code reduced**: ~50+ lines of boilerplate
- **Consistency improved**: Unified singleton patterns
- **Maintainability enhanced**: Centralized utility functions
- **Test coverage maintained**: 100% test pass rate
Remaining complex monitors (traffic, memory, logs) will be migrated to use the shared IPC monitoring patterns in the next phase, which requires careful refactoring of their streaming logic.
* refactor: complete singleton pattern migration to utility macros
Migrate remaining singleton patterns across the backend to use standardized
utility macros, achieving significant code reduction and consistency improvements.
- **LogsMonitor** (ipc/logs.rs): `OnceLock` → `singleton_with_logging\!`
- **Sysopt** (core/sysopt.rs): `OnceCell` → `singleton_lazy\!`
- **Tray** (core/tray/mod.rs): Complex `OnceCell` → `singleton_lazy\!`
- **Handle** (core/handle.rs): `OnceCell` → `singleton\!`
- **CoreManager** (core/core.rs): `OnceCell` → `singleton_lazy\!`
- **TrafficMonitor** (ipc/traffic.rs): `OnceLock` → `singleton_lazy_with_logging\!`
- **MemoryMonitor** (ipc/memory.rs): `OnceLock` → `singleton_lazy_with_logging\!`
- `singleton_lazy\!` - For complex initialization patterns
- `singleton_lazy_with_logging\!` - For complex initialization with logging
- **Code Reduction**: -33 lines of boilerplate singleton code
- **DRY Compliance**: Eliminated duplicate initialization patterns
- **Consistency**: Unified singleton approach across codebase
- **Maintainability**: Centralized singleton logic in utility macros
- **Zero Breaking Changes**: All existing APIs remain compatible
All tests pass and clippy warnings resolved.
* refactor: optimize singleton macros using Default trait implementation
Simplify singleton macro usage by implementing Default trait for complex
initialization patterns, significantly improving code readability and maintainability.
- **MemoryMonitor**: Move IPC client initialization to Default impl
- **TrafficMonitor**: Move IPC client initialization to Default impl
- **Sysopt**: Move Arc<Mutex> initialization to Default impl
- **Tray**: Move struct field initialization to Default impl
- **CoreManager**: Move Arc<Mutex> initialization to Default impl
```rust
singleton_lazy_with_logging\!(MemoryMonitor, INSTANCE, "MemoryMonitor", || {
let ipc_path_buf = ipc_path().unwrap();
let ipc_path = ipc_path_buf.to_str().unwrap_or_default();
let client = IpcStreamClient::new(ipc_path).unwrap();
MemoryMonitor::new(client)
});
```
```rust
impl Default for MemoryMonitor { /* initialization logic */ }
singleton_lazy_with_logging\!(MemoryMonitor, INSTANCE, "MemoryMonitor", MemoryMonitor::default);
```
- **Code Reduction**: -17 lines of macro closure code (80%+ simplification)
- **Separation of Concerns**: Initialization logic moved to proper Default impl
- **Readability**: Single-line macro calls vs multi-line closures
- **Testability**: Default implementations can be tested independently
- **Rust Idioms**: Using standard Default trait pattern
- **Performance**: Function calls more efficient than closures
All tests pass and clippy warnings resolved.
* refactor: implement MonitorData and StreamingParser traits for IPC monitors
* refactor: add timeout and retry_interval fields to IpcStreamMonitor; update TrafficMonitorState to derive Default
* refactor: migrate AppHandleManager to unified singleton control
- Replace manual singleton implementation with singleton_with_logging\! macro
- Remove std::sync::Once dependency in favor of OnceLock-based pattern
- Improve error handling for macOS activation policy methods
- Maintain thread safety with parking_lot::Mutex for AppHandle storage
- Add proper initialization check to prevent duplicate handle assignment
- Enhance logging consistency across AppHandleManager operations
* refactor: improve hotkey management with enum-based operations
- Add HotkeyFunction enum for type-safe function selection
- Add SystemHotkey enum for predefined system shortcuts
- Implement Display and FromStr traits for type conversions
- Replace string-based hotkey registration with enum methods
- Add register_system_hotkey() and unregister_system_hotkey() methods
- Maintain backward compatibility with string-based register() method
- Migrate singleton pattern to use singleton_with_logging\! macro
- Extract hotkey function execution logic into centralized execute_function()
- Update lib.rs to use new enum-based SystemHotkey operations
- Improve type safety and reduce string manipulation errors
Benefits:
- Type safety prevents invalid hotkey function names
- Centralized function execution reduces code duplication
- Enum-based API provides better IDE autocomplete support
- Maintains full backward compatibility with existing configurations
* fix: resolve LightWeightState initialization order panic
- Modify with_lightweight_status() to safely handle unmanaged state using try_state()
- Return Option<R> instead of R to gracefully handle state unavailability
- Update is_in_lightweight_mode() to use unwrap_or(false) for safe defaults
- Add state availability check in auto_lightweight_mode_init() before access
- Maintain singleton check priority while preventing early state access panics
- Fix clippy warnings for redundant pattern matching
Resolves runtime panic: "state() called before manage() for LightWeightState"
* refactor: add unreachable patterns for non-macOS in hotkey handling
* refactor: simplify SystemHotkey enum by removing redundant cfg attributes
* refactor: add macOS conditional compilation for system hotkey registration methods
* refactor: streamline hotkey unregistration and error logging for macOS
|
||
|
|
764ef48fd1 |
refactor(Draft): Replace latest() with latest_ref() and data() with data_mut() in multiple files for improved mutability handling and consistency across the codebase (#3987)
* feat: add benchmarking for draft operations and new draft management structure * Refactor Config Access: Replace `latest()` with `latest_ref()` and `data()` with `data_mut()` in multiple files for improved mutability handling and consistency across the codebase. * refactor: remove DraftNew implementation and related benchmarks for cleaner codebase |
||
|
|
7b5afb7afe |
Add cors (#3909)
* add external `cors` control panel
* optimize format
* fix-script.rs
* fix-service.rs
* fix-rs
async_proxy_query.rs
event_driven_proxy.rs
service_ipc.rs
service.rs
sysopt.rs
* lower the prettier version number to 3.5.3
* Revert "lower the prettier version number to 3.5.3"
This reverts commit
|