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.
This commit is contained in:
wonfen
2026-08-14 23:52:37 +08:00
committed by GitHub
parent 0844ed30a8
commit 22947632c0
93 changed files with 5208 additions and 337 deletions
+5 -1
View File
@@ -1,6 +1,6 @@
use crate::{
config::{Config, IClashTemp, IProfiles, IVerge},
core::backup,
core::{backup, proxy_control::SystemProxyStateUnknown},
process::AsyncHandler,
utils::{
dirs::{PathBufExec as _, app_home_dir, local_backup_dir, verge_path},
@@ -63,6 +63,10 @@ async fn finalize_restored_verge_config(
// Use not_save_file = true to avoid extra I/O (we already persisted the restored file).
if let Err(err) = super::patch_verge(&restored, true).await {
logging!(error, Type::Backup, "Failed to apply restored verge config: {err:#?}");
// Propagate unknown proxy state; ordinary side-effect failures stay logged.
if SystemProxyStateUnknown::is_in(&err) {
return Err(err);
}
}
Ok(())
}
+2 -2
View File
@@ -31,8 +31,8 @@ pub async fn restart_clash_core() {
handle::Handle::notice_message("set_config::ok", "ok");
}
Err(err) => {
handle::Handle::notice_message("set_config::error", format!("{err}"));
logging!(error, Type::Core, "{err}");
handle::Handle::notice_message("set_config::error", format!("{err:#}"));
logging!(error, Type::Core, "{err:#}");
}
}
}
+80 -5
View File
@@ -1,6 +1,6 @@
use crate::{
config::{Config, IVerge},
core::{CoreManager, autostart, handle, hotkey, logger::Logger, tray},
core::{CoreManager, autostart, handle, hotkey, logger::Logger, proxy_control::SystemProxyStateUnknown, tray},
module::{auto_backup::AutoBackupManager, lightweight},
};
use anyhow::Result;
@@ -211,9 +211,6 @@ async fn process_terminated_flags(update_flags: UpdateFlags, patch: &IVerge) ->
CoreManager::global().update_config_checked().await?;
handle::Handle::refresh_clash();
}
if update_flags.contains(UpdateFlags::VERGE_CONFIG) {
handle::Handle::refresh_verge();
}
if update_flags.contains(UpdateFlags::LAUNCH) {
autostart::update_launch().await?;
}
@@ -306,8 +303,25 @@ pub(super) async fn apply_verge_patch(patch: &IVerge, not_save_file: bool) -> Re
let update_flags = determine_update_flags(patch);
logging!(debug, Type::Setup, "Determined update flags: {:?}", update_flags);
process_terminated_flags(update_flags, patch).await?;
if let Err(error) = process_terminated_flags(update_flags, patch).await {
if !may_commit_system_proxy_disabled(patch, &error) {
return Err(error);
}
// Commit the safe state after a user-requested proxy patch partly lands.
verge.edit_draft(|d| d.enable_system_proxy = Some(false));
transaction.commit();
announce_verge_change();
// Persist the forced-off value even when the original patch was pre-saved.
let unsaved = verge.data_arc().save_file().await.err();
return Err(match unsaved {
Some(save) => error.context(format!(
"the system proxy state became unknown and the disabled safety value could not be saved: {save:#}"
)),
None => error,
});
}
transaction.commit();
announce_verge_change();
logging_error!(Type::Backup, AutoBackupManager::global().refresh_settings().await);
if !not_save_file {
@@ -319,8 +333,69 @@ pub(super) async fn apply_verge_patch(patch: &IVerge, not_save_file: bool) -> Re
Ok(())
}
fn announce_verge_change() {
handle::Handle::refresh_verge();
}
/// Whether a user proxy patch may commit disabled after a partial write.
fn may_commit_system_proxy_disabled(patch: &IVerge, error: &anyhow::Error) -> bool {
patch.enable_system_proxy.is_some() && SystemProxyStateUnknown::is_in(error)
}
pub async fn fetch_verge_config() -> Result<SharedDraft<IVerge>> {
let draft = Config::verge().await;
let data = draft.data_arc();
Ok(data)
}
#[cfg(test)]
mod tests {
use super::{IVerge, SystemProxyStateUnknown, may_commit_system_proxy_disabled};
fn state_unknown() -> anyhow::Error {
anyhow::anyhow!("networksetup refused")
.context(SystemProxyStateUnknown)
.context("failed to apply the system proxy")
}
#[test]
fn the_user_turning_the_proxy_on_gets_it_committed_as_off_when_the_os_ended_up_unknown() {
let patch = IVerge {
enable_system_proxy: Some(true),
..IVerge::default()
};
assert!(may_commit_system_proxy_disabled(&patch, &state_unknown()));
}
#[test]
fn a_patch_about_something_else_never_rewrites_the_proxy_setting() {
let patch = IVerge {
enable_tun_mode: Some(true),
..IVerge::default()
};
assert!(!may_commit_system_proxy_disabled(&patch, &state_unknown()));
}
#[test]
fn nothing_is_committed_when_nothing_is_known_to_have_been_written() {
let patch = IVerge {
enable_system_proxy: Some(true),
..IVerge::default()
};
let refused = anyhow::anyhow!("networksetup refused").context("failed to apply the system proxy");
assert!(!may_commit_system_proxy_disabled(&patch, &refused));
}
#[test]
fn turning_the_proxy_off_and_failing_that_way_still_commits_off() {
let patch = IVerge {
enable_system_proxy: Some(false),
..IVerge::default()
};
assert!(may_commit_system_proxy_disabled(&patch, &state_unknown()));
}
}
+8 -12
View File
@@ -11,6 +11,7 @@ use crate::{
probe_listener as probe_listener_sync, probe_proxy_port_change,
},
manager::RunningMode,
proxy_control::rollback_failure,
validate::CoreConfigValidator,
},
process::AsyncHandler,
@@ -87,17 +88,15 @@ pub async fn save_proxy_ports(settings: ProxyPortSettings) -> Result<SaveProxyPo
transaction.rollback();
return match restore_files(&snapshots).await {
Ok(()) => Err(error).context("failed to persist candidate Runtime Configuration"),
Err(rollback_error) => Err(anyhow!("{error:#}; configuration rollback failed: {rollback_error:#}")),
Err(rollback_error) => Err(rollback_failure(error, rollback_error)),
};
}
if was_running && let Err(activation_error) = manager.restart_core_during_config_update().await {
transaction.rollback();
if let Err(rollback_error) = rollback_proxy_ports(&snapshots, was_running).await {
return Err(anyhow!(
"failed to activate proxy port configuration: {activation_error:#}; \
configuration rollback failed: {rollback_error:#}"
));
return Err(rollback_failure(activation_error, rollback_error)
.context("failed to activate the proxy port configuration"));
}
let post_failure_assessment = probe_proxy_ports(current, candidate, was_running).await?;
@@ -116,9 +115,7 @@ pub async fn save_proxy_ports(settings: ProxyPortSettings) -> Result<SaveProxyPo
transaction.rollback();
return match rollback_proxy_ports(&snapshots, was_running).await {
Ok(()) => Err(persist_error),
Err(rollback_error) => Err(anyhow!(
"{persist_error:#}; configuration rollback failed: {rollback_error:#}"
)),
Err(rollback_error) => Err(rollback_failure(persist_error, rollback_error)),
};
}
@@ -245,9 +242,8 @@ async fn rollback_proxy_ports(snapshots: &[FileSnapshot], was_running: bool) ->
(Ok(()), Ok(())) => Ok(()),
(Err(file_error), Ok(())) => Err(file_error),
(Ok(()), Err(lifecycle_error)) => Err(lifecycle_error).context("failed to restore the previous core"),
(Err(file_error), Err(lifecycle_error)) => Err(anyhow!(
"failed to restore configuration files: {file_error:#}; \
failed to restore the previous core: {lifecycle_error:#}"
)),
(Err(file_error), Err(lifecycle_error)) => Err(lifecycle_error
.context(format!("failed to restore configuration files: {file_error:#}"))
.context("failed to restore the previous core")),
}
}
+55 -16
View File
@@ -1,13 +1,21 @@
use crate::{
config::{Config, IVerge, MixedPort},
core::handle,
core::{
handle,
notification::{self, FailedOperation},
proxy_control,
},
utils::{
notification::{NotificationEvent, needs_system_notification, notify_event},
window_manager::WindowManager,
},
};
use clash_verge_logging::{Type, logging};
use std::env;
use tauri_plugin_clipboard_manager::ClipboardExt as _;
/// Toggle system proxy on/off
pub async fn toggle_system_proxy() -> bool {
/// Toggle system proxy, returning `None` when it does not change.
pub async fn toggle_system_proxy() -> Option<bool> {
let verge = Config::verge().await;
let current = verge.latest_arc().enable_system_proxy.unwrap_or(false);
let auto_close_connection = verge.latest_arc().auto_close_connection.unwrap_or(false);
@@ -21,27 +29,46 @@ pub async fn toggle_system_proxy() -> bool {
}
let requested = !current;
let patch_result = super::patch_verge(
&IVerge {
enable_system_proxy: Some(requested),
..IVerge::default()
},
false,
let patch_result = notification::asking_for(
toggle_operation(requested),
Box::pin(super::patch_verge(
&IVerge {
enable_system_proxy: Some(requested),
..IVerge::default()
},
false,
)),
)
.await;
match patch_result {
Ok(_) => {
handle::Handle::refresh_verge();
requested
}
// Patch processing refreshes every caller.
Ok(_) => Some(requested),
Err(err) => {
logging!(error, Type::ProxyMode, "{err}");
current
logging!(error, Type::ProxyMode, "{err:#}");
report_toggle_failure(&err).await;
None
}
}
}
/// Notify only when a classified failure remains pending.
async fn report_toggle_failure(error: &anyhow::Error) {
let recorded = proxy_control::is_reportable(error);
if recorded && needs_system_notification(WindowManager::get_main_window_state()) {
notify_event(NotificationEvent::SystemProxyFailed).await;
}
}
const fn toggle_operation(requested: bool) -> FailedOperation {
if requested {
FailedOperation::SystemProxyEnable
} else {
FailedOperation::SystemProxyDisable
}
}
/// Toggle TUN mode on/off
/// Returns the updated toggle state
pub async fn toggle_tun_mode(not_save_file: Option<bool>) -> bool {
@@ -67,7 +94,7 @@ pub async fn toggle_tun_mode(not_save_file: Option<bool>) -> bool {
Config::verge().await.latest_arc().enable_tun_mode.unwrap_or(false)
}
Err(err) => {
logging!(error, Type::ProxyMode, "{err}");
logging!(error, Type::ProxyMode, "{err:#}");
current
}
}
@@ -123,3 +150,15 @@ pub async fn copy_clash_env() {
logging!(error, Type::ProxyMode, "Failed to write to clipboard");
}
}
#[cfg(test)]
mod tests {
use super::toggle_operation;
use crate::core::notification::FailedOperation;
#[test]
fn a_failed_toggle_records_which_way_the_user_was_asking() {
assert_eq!(toggle_operation(true), FailedOperation::SystemProxyEnable);
assert_eq!(toggle_operation(false), FailedOperation::SystemProxyDisable);
}
}