feat(proxy): follow node picks along the rule chain

A pick in any group rules do not reach switches the first select group that lists it, and the node card drops its own follow command.
This commit is contained in:
wonfen
2026-11-21 01:43:49 +08:00
parent e5e2cc8111
commit 498648cca0
21 changed files with 62 additions and 56 deletions
+2 -2
View File
@@ -57,7 +57,7 @@
<summary><strong> ✨ 新增功能 </strong></summary>
- 新增连接页面按网络协议(TCP/UDP)筛选连接
- 新增规则模式下在 `url-test` 或 `fallback` 代理组选节点时,自动将首个包含该组的 `select` 代理组切换到该组,可在「杂项设置」关闭
- 新增规则模式下在规则流量未经过的代理组选节点时,自动将首个包含该组的 `select` 代理组切换到该组,可在「杂项设置」关闭
</details>
@@ -67,7 +67,7 @@
- 优化连接、规则和日志筛选:切换页面后保留过滤条件
- 优化全局模式代理列表:仅显示 `GLOBAL` 节点,选中其中的策略组时才显示该组
- 优化设置页开关和选项所在行的鼠标悬停高亮,便于对应说明与控件
- 优化首页「当前节点」卡片:按规则指向的代理组逐级显示和切换实际生效的节点,切换到 `url-test` 或 `fallback` 代理组时同样联动 `select` 代理组
- 优化首页「当前节点」卡片:按规则指向的代理组逐级显示和切换实际生效的节点
**🍎 macOS**
-6
View File
@@ -27,12 +27,6 @@ pub async fn switch_proxy_node(group_name: String, proxy_name: String, unfix: bo
.stringify_err()
}
#[tauri::command]
#[specta::specta]
pub async fn follow_proxy_group(group_name: String) {
crate::feat::follow_proxy_group(&group_name).await;
}
fn runtime_group_order(config: Option<&Mapping>) -> Vec<String> {
let mut seen = HashSet::new();
+46 -25
View File
@@ -9,7 +9,8 @@ use crate::{
};
use anyhow::{Result, bail};
use clash_verge_logging::{Type, logging};
use tauri_plugin_mihomo::models::ProxyType;
use std::collections::{HashMap, HashSet};
use tauri_plugin_mihomo::models::{Proxy, ProxyType, Rule};
use tristr::alias::String;
/// Toggle proxy profile
@@ -23,13 +24,9 @@ pub async fn toggle_proxy_profile(profile_index: String) {
}
}
/// First `select` group in config order that lists `group_name`, when that group is `url-test` or `fallback`.
/// First `select` group in config order that lists `group_name`.
fn parent_selector<'a>(groups: &'a [serde_yaml_ng::Value], group_name: &str) -> Option<&'a str> {
let field = |group: &'a serde_yaml_ng::Value, key: &str| group.get(key)?.as_str();
let group = groups.iter().find(|group| field(group, "name") == Some(group_name))?;
if !matches!(field(group, "type"), Some("url-test" | "fallback")) {
return None;
}
groups
.iter()
.filter(|group| field(group, "type") == Some("select"))
@@ -43,9 +40,24 @@ fn parent_selector<'a>(groups: &'a [serde_yaml_ng::Value], group_name: &str) ->
.find(|name| *name != "GLOBAL")
}
/// Rule traffic enters through `select` groups, so a pick inside a `url-test`/`fallback` group only
/// carries traffic once the first `select` group listing that group points at it.
/// Returns the node that group left.
/// Whether rule traffic passes through `group_name`, following each group's current selection.
fn rules_reach(groups: &[Proxy], rules: &[Rule], group_name: &str) -> bool {
let by_name: HashMap<&str, &Proxy> = groups.iter().map(|group| (group.name.as_str(), group)).collect();
let mut seen = HashSet::new();
rules.iter().any(|rule| {
let mut hop = by_name.get(rule.proxy.as_str()).copied();
while let Some(group) = hop.filter(|group| seen.insert(group.name.as_str())) {
if group.name == group_name {
return true;
}
hop = group.now.as_deref().and_then(|now| by_name.get(now).copied());
}
false
})
}
/// A pick in a group no rule reaches only carries traffic once the first `select` group listing that group
/// points at it. Returns that `select` group, whose connections are then stale.
async fn follow_group_selection(group_name: &str) -> Option<std::string::String> {
if !Config::verge()
.await
@@ -70,13 +82,15 @@ async fn follow_group_selection(group_name: &str) -> Option<std::string::String>
};
let mihomo = handle::Handle::mihomo();
let current = mihomo.get_proxy_by_name(&selector).await.ok()?;
let groups = mihomo.get_groups().await.ok()?.proxies;
let current = groups.iter().find(|group| group.name == selector)?;
// The runtime config can lag the core, which alone knows what this group is now.
if current.proxy_type != ProxyType::Selector {
return None;
}
let previous = current.now?;
if previous == group_name {
if current.now.as_deref() == Some(group_name)
|| rules_reach(&groups, &mihomo.get_rules().await.ok()?.rules, group_name)
{
return None;
}
if let Err(err) = mihomo.select_node_for_group(&selector, group_name).await {
@@ -90,7 +104,7 @@ async fn follow_group_selection(group_name: &str) -> Option<std::string::String>
"Failed to persist proxy selection for {selector}: {error:#}"
);
}
Some(previous)
Some(selector)
}
pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool) -> Result<()> {
@@ -132,24 +146,15 @@ pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool)
}
let mut stale_proxies: Vec<_> = previous_proxy.into_iter().collect();
if !unfix
&& let Some(left) = follow_group_selection(group_name).await
&& let Some(followed) = follow_group_selection(group_name).await
&& auto_close
{
stale_proxies.push(left);
stale_proxies.push(followed);
}
finish_proxy_switch(stale_proxies).await;
Ok(())
}
/// Lets a `url-test`/`fallback` group carry rule traffic without fixing a node in it.
pub async fn follow_proxy_group(group_name: &str) {
let Some(left) = follow_group_selection(group_name).await else {
return;
};
let auto_close = Config::verge().await.data_arc().auto_close_connection.unwrap_or(false);
finish_proxy_switch(auto_close.then_some(left).into_iter().collect()).await;
}
async fn finish_proxy_switch(stale_proxies: Vec<std::string::String>) {
let mihomo = handle::Handle::mihomo();
announce(Refresh::Proxies);
@@ -379,7 +384,7 @@ mod tests {
use super::*;
#[test]
fn only_the_first_select_group_follows_an_auto_group() -> Result<()> {
fn only_the_first_select_group_follows_a_group() -> Result<()> {
let groups: Vec<serde_yaml_ng::Value> = serde_yaml_ng::from_str(
"
- { name: GLOBAL, type: select, proxies: [Auto, Proxy, Direct] }
@@ -393,4 +398,20 @@ mod tests {
assert_eq!(parent_selector(&groups, "Proxy"), None);
Ok(())
}
#[test]
fn rules_reach_the_groups_on_their_current_path() -> Result<()> {
let groups: Vec<Proxy> = serde_yaml_ng::from_str(
"
- { name: Proxy, type: Selector, now: Auto }
- { name: Auto, type: URLTest, now: Node }
- { name: Spare, type: Selector, now: Node }
",
)?;
let rules: Vec<Rule> = serde_yaml_ng::from_str("[{ proxy: DIRECT }, { proxy: Proxy }]")?;
assert!(rules_reach(&groups, &rules, "Auto"));
assert!(!rules_reach(&groups, &rules, "Spare"));
Ok(())
}
}
-1
View File
@@ -47,7 +47,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
cmd::copy_clash_env,
cmd::record_selected_node,
cmd::switch_proxy_node,
cmd::follow_proxy_group,
cmd::save_dns_config,
cmd::apply_dns_config,
cmd::set_dns_override,
@@ -56,7 +56,6 @@ import {
useProxiesData,
useRulesData,
} from '@/providers/app-data-context'
import { followProxyGroup } from '@/services/cmds'
import delayManager from '@/services/delay'
import {
findCurrentGroupMember,
@@ -832,7 +831,6 @@ export const CurrentProxyCard = () => {
if (isGlobalMode || isDirectMode) return
setPickedGroupName(newGroupName)
writeProfileScopedItem(STORAGE_KEY_GROUP, newGroupName)
void followProxyGroup(newGroupName)
},
[isDirectMode, isGlobalMode, writeProfileScopedItem],
)
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "إنهاء الاتصالات القائمة عند تغيير اختيار مجموعة الوكيل أو وضع الوكيل",
"autoSwitchSelectorGroup": "في وضع القواعد، عند اختيار عقدة في مجموعة url-test أو fallback يتم أيضًا تحويل أول مجموعة select تحتوي عليها إلى تلك المجموعة",
"autoSwitchSelectorGroup": "في وضع القواعد، عند اختيار عقدة في مجموعة لا تمر بها حركة القواعد يتم أيضًا تحويل أول مجموعة select تحتوي عليها إلى تلك المجموعة",
"enableBuiltinEnhanced": "معالجة توافق ملف التكوين",
"autoDelayDetection": "يختبر زمن استجابة العقدة الحالية على نحو دوري في الخلفية",
"defaultLatencyTest": "يُستخدم فقط لاختبار طلب HTTP العميل. لن يؤثر على ملف التكوين"
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "Wenn der ausgewählte Knoten in der Proxy-Gruppe oder der Proxy-Modus geändert wird, werden die bestehenden Verbindungen geschlossen.",
"autoSwitchSelectorGroup": "Wird im Regelmodus ein Knoten in einer url-test- oder fallback-Gruppe gewählt, wechselt auch die erste select-Gruppe, die diese Gruppe enthält, auf diese Gruppe.",
"autoSwitchSelectorGroup": "Wird im Regelmodus ein Knoten in einer Gruppe gewählt, die kein Regelverkehr erreicht, wechselt auch die erste select-Gruppe, die diese Gruppe enthält, auf diese Gruppe.",
"enableBuiltinEnhanced": "Kompatibilitätsbehandlung der Konfigurationsdatei",
"autoDelayDetection": "Überprüft regelmäßig im Hintergrund die Latenz des aktuellen Knotens",
"defaultLatencyTest": "Dies wird nur für HTTP-Client-Anfragentests verwendet und hat keine Auswirkungen auf die Konfigurationsdatei."
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "Terminate established connections when the proxy group selection or proxy mode changes",
"autoSwitchSelectorGroup": "In rule mode, selecting a node in a url-test or fallback group also switches the first select group containing it to that group",
"autoSwitchSelectorGroup": "In rule mode, selecting a node in a group that rule traffic does not reach also switches the first select group containing it to that group",
"enableBuiltinEnhanced": "Compatibility handling for the configuration file",
"autoDelayDetection": "Periodically test the current node latency in the background",
"defaultLatencyTest": "Used for HTTP client request testing only and won't make a difference to the configuration file"
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "Cierra las conexiones establecidas cuando se cambia el nodo seleccionado en el grupo de proxy o el modo de proxy.",
"autoSwitchSelectorGroup": "En modo de reglas, al elegir un nodo en un grupo url-test o fallback, el primer grupo select que lo contiene también cambia a ese grupo.",
"autoSwitchSelectorGroup": "En modo de reglas, al elegir un nodo en un grupo al que no llega tráfico de reglas, el primer grupo select que lo contiene también cambia a ese grupo.",
"enableBuiltinEnhanced": "Procesamiento de compatibilidad de archivos de configuración",
"autoDelayDetection": "Prueba periódicamente la latencia del nodo actual en segundo plano",
"defaultLatencyTest": "Solo se utiliza para pruebas de solicitudes de clientes HTTP y no afectará al archivo de configuración."
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "اتصالات برقرار شده را هنگام تغییر انتخاب گروه پروکسی یا حالت پروکسی خاتمه دهید",
"autoSwitchSelectorGroup": "در حالت قانون، با انتخاب یک گره در گروه url-test یا fallback، اولین گروه select شامل آن نیز به همان گروه تغییر می‌کند",
"autoSwitchSelectorGroup": "در حالت قانون، با انتخاب یک گره در گروهی که ترافیک قوانین از آن عبور نمی‌کند، اولین گروه select شامل آن نیز به همان گروه تغییر می‌کند",
"enableBuiltinEnhanced": "مدیریت سازگاری برای فایل پیکربندی",
"autoDelayDetection": "به‌صورت دوره‌ای تأخیر گره فعلی را در پس‌زمینه آزمایش می‌کند",
"defaultLatencyTest": "فقط برای تست درخواست‌های کلاینت HTTP استفاده می‌شود و بر فایل پیکربندی تأثیری نخواهد داشت"
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "Hentikan koneksi yang sudah ada saat pemilihan grup proksi atau mode proksi berubah",
"autoSwitchSelectorGroup": "Dalam mode aturan, memilih node di grup url-test atau fallback juga mengalihkan grup select pertama yang memuatnya ke grup tersebut",
"autoSwitchSelectorGroup": "Dalam mode aturan, memilih node di grup yang tidak dilalui lalu lintas aturan juga mengalihkan grup select pertama yang memuatnya ke grup tersebut",
"enableBuiltinEnhanced": "Penanganan kompatibilitas untuk file konfigurasi",
"autoDelayDetection": "Secara berkala menguji latensi node saat ini di latar belakang",
"defaultLatencyTest": "Digunakan hanya untuk pengujian permintaan klien HTTP dan tidak akan mempengaruhi file konfigurasi"
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "プロキシグループで選択されたノードまたはプロキシモードが変更されたときに、既存の接続を閉じます。",
"autoSwitchSelectorGroup": "ルールモードで url-test または fallback グループのノードを選択すると、そのグループを含む最初の select グループも当該グループに切り替えます。",
"autoSwitchSelectorGroup": "ルールモードで、ルールの通信が通らないグループのノードを選択すると、そのグループを含む最初の select グループも当該グループに切り替えます。",
"enableBuiltinEnhanced": "設定ファイルの互換性処理",
"autoDelayDetection": "バックグラウンドで現在のノードのレイテンシーを定期的にテストします",
"defaultLatencyTest": "HTTPクライアントリクエストテストにのみ使用され、設定ファイルには影響しません。"
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "프록시 그룹 선택 또는 프록시 모드 변경 시 기존 연결을 종료합니다",
"autoSwitchSelectorGroup": "규칙 모드에서 url-test 또는 fallback 그룹의 노드를 선택하면 해당 그룹을 포함하는 첫 번째 select 그룹도 그 그룹으로 전환합니다",
"autoSwitchSelectorGroup": "규칙 모드에서 규칙 트래픽이 지나지 않는 그룹의 노드를 선택하면 해당 그룹을 포함하는 첫 번째 select 그룹도 그 그룹으로 전환합니다",
"enableBuiltinEnhanced": "구성 파일에 대한 호환성 처리를 수행합니다",
"autoDelayDetection": "백그라운드에서 현재 노드의 지연을 주기적으로 검사합니다",
"defaultLatencyTest": "HTTP 클라이언트 요청 테스트에만 사용되며 구성 파일에는 영향을 주지 않습니다"
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "Encerra as conexões estabelecidas quando a seleção do grupo de proxy ou o modo de proxy muda",
"autoSwitchSelectorGroup": "No modo de regras, ao escolher um nó em um grupo url-test ou fallback, o primeiro grupo select que o contém também muda para esse grupo",
"autoSwitchSelectorGroup": "No modo de regras, ao escolher um nó em um grupo que o tráfego das regras não alcança, o primeiro grupo select que o contém também muda para esse grupo",
"enableBuiltinEnhanced": "Tratamento de compatibilidade para o arquivo de configuração",
"autoDelayDetection": "Testa periodicamente a latência do nó atual em segundo plano",
"defaultLatencyTest": "Usado apenas para testes de requisição do cliente HTTP e não afeta o arquivo de configuração"
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "Закрывать установленные соединения при изменении выбора группы прокси или режима прокси",
"autoSwitchSelectorGroup": "В режиме правил при выборе узла в группе url-test или fallback первая группа select, содержащая эту группу, также переключается на неё",
"autoSwitchSelectorGroup": "В режиме правил при выборе узла в группе, через которую не идёт трафик правил, первая группа select, содержащая эту группу, также переключается на неё",
"enableBuiltinEnhanced": "Обработка совместимости для файла конфигурации",
"autoDelayDetection": "Периодически проверяет задержку текущего узла в фоновом режиме",
"defaultLatencyTest": "Используется только для тестирования HTTP-запросов клиента и не влияет на файл конфигурации"
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "Vekil grup seçimi veya vekil modu değiştiğinde kurulan bağlantıları sonlandır",
"autoSwitchSelectorGroup": "Kural modunda url-test veya fallback grubunda bir düğüm seçildiğinde, bu grubu içeren ilk select grubu da o gruba geçer",
"autoSwitchSelectorGroup": "Kural modunda, kural trafiğinin ulaşmadığı bir grupta düğüm seçildiğinde, bu grubu içeren ilk select grubu da o gruba geçer",
"enableBuiltinEnhanced": "Yapılandırma dosyası için uyumluluk işleme",
"autoDelayDetection": "Arka planda mevcut düğümün gecikmesini periyodik olarak test eder",
"defaultLatencyTest": "Yalnızca HTTP istemci isteği testi için kullanılır ve yapılandırma dosyasında bir fark yaratmaz"
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "Прокси төркеме яисә режимын үзгәрткәндә актив тоташуларны өзү",
"autoSwitchSelectorGroup": "Кагыйдәләр режимында url-test яки fallback төркемендә төен сайлаганда, аны эченә алган беренче select төркеме дә шул төркемгә күчә",
"autoSwitchSelectorGroup": "Кагыйдәләр режимында кагыйдәләр трафигы үтми торган төркемдә төен сайлаганда, аны эченә алган беренче select төркеме дә шул төркемгә күчә",
"enableBuiltinEnhanced": "Конфигурация файлы белән туры килә торган өстәмә оптимизация",
"autoDelayDetection": "Фон режимында хәзерге төен тоткарлыгын периодик тикшерә",
"defaultLatencyTest": "Бу фәкать клиентның HTTP сораулары тесты өчен кулланыла, конфигурация файлына йогынты ясамый"
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "当代理组选中节点或代理模式变动时,关闭已建立的连接",
"autoSwitchSelectorGroup": "规则模式下,在 url-test 或 fallback 代理组中选择节点时,将首个包含该组的 select 代理组切换到该组",
"autoSwitchSelectorGroup": "规则模式下,在规则流量未经过的代理组中选择节点时,将首个包含该组的 select 代理组切换到该组",
"enableBuiltinEnhanced": "配置文件的兼容性处理",
"autoDelayDetection": "后台定时检测当前节点延迟",
"defaultLatencyTest": "仅用于 HTTP 客户端请求测试,不会对配置文件产生影响"
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "當代理組選中節點或代理模式變動時,關閉已建立的連線",
"autoSwitchSelectorGroup": "規則模式下,在 url-test 或 fallback 代理組中選擇節點時,將首個包含該組的 select 代理組切換到該組",
"autoSwitchSelectorGroup": "規則模式下,在規則流量未經過的代理組中選擇節點時,將首個包含該組的 select 代理組切換到該組",
"enableBuiltinEnhanced": "配置檔案的相容性處理",
"autoDelayDetection": "在背景定時偵測目前節點延遲",
"defaultLatencyTest": "僅用於 HTTP 客戶端請求測試,不會對配置檔案產生影響"
-2
View File
@@ -83,8 +83,6 @@ export const commands = {
__TAURI_INVOKE<null>('record_selected_node', { groupName, node }),
switchProxyNode: (groupName: string, proxyName: string, unfix: boolean) =>
__TAURI_INVOKE<null>('switch_proxy_node', { groupName, proxyName, unfix }),
followProxyGroup: (groupName: string) =>
__TAURI_INVOKE<void>('follow_proxy_group', { groupName }),
saveDnsConfig: (dnsConfig: YamlMapping) =>
__TAURI_INVOKE<null>('save_dns_config', { dnsConfig }),
applyDnsConfig: (apply: boolean) =>
-4
View File
@@ -165,10 +165,6 @@ export async function switchProxyNode(
return commands.switchProxyNode(groupName, proxyName, unfix)
}
export async function followProxyGroup(groupName: string) {
return commands.followProxyGroup(groupName)
}
export async function getProxyView(): Promise<ProxyViewV1> {
const view = await commands.getProxyView()
if (view.schemaVersion !== 1) {