Compare commits

..
Author SHA1 Message Date
Slinetrac 2af44fab60 fix(windows): add a fallback when Auto Launch task registration is denied 2026-11-21 15:04:04 +08:00
wonfen 68ecad4ef7 fix(home): close the node card dropdowns after a pick
The delay test button still keeps an open list open.
2026-11-21 01:55:01 +08:00
wonfen 498648cca0 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.
2026-11-21 01:43:49 +08:00
wonfen e5e2cc8111 feat(home): anchor the node card on rule targets
The card lists the groups rules point at and walks the picked one down to the node carrying its traffic.
2026-11-21 01:27:21 +08:00
Fei Wenand❤是纱雾酱哟~ 22188f98c9 fix(home): route IP lookups through the live Clash mixed port (#8356)
* fix(home): route IP lookups through the live Clash mixed port

Assisted-by: MAI Code 2 (high)
Co-authored-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>

* fix: respects bind address and auth for IP check proxy

Assisted-by: Copilot Fusion (Standard) > GPT-6 Luna
Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>

---------

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
Co-authored-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
2026-11-20 12:48:04 +00:00
renovate[bot]andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> d3d91f3855 chore(deps): update tauri (#8698)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-20 08:28:19 +00:00
74 changed files with 1373 additions and 1242 deletions
Generated
+27 -17
View File
@@ -1118,6 +1118,7 @@ dependencies = [
"open",
"parking_lot 0.13.0",
"percent-encoding",
"quick-xml 0.42.0",
"reqwest 0.13.5",
"reqwest_dav",
"rfd 0.18.0",
@@ -5264,7 +5265,7 @@ checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85"
dependencies = [
"base64 0.22.1",
"indexmap 2.14.0",
"quick-xml",
"quick-xml 0.41.0",
"serde",
"time",
]
@@ -5534,6 +5535,15 @@ dependencies = [
"memchr",
]
[[package]]
name = "quick-xml"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
dependencies = [
"memchr",
]
[[package]]
name = "quinn"
version = "0.11.11"
@@ -7237,9 +7247,9 @@ checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
[[package]]
name = "tauri"
version = "2.12.5"
version = "2.12.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fb0244332cfb9cee7e2a568bf5da29a36ed8fdbd717f6f47a66b6b7b358c072"
checksum = "30fbfbb9dc9a2697b0e96d909ddc295fb18d2d82a58ed542ab8d9eba2edbe6da"
dependencies = [
"anyhow",
"bytes",
@@ -7292,9 +7302,9 @@ dependencies = [
[[package]]
name = "tauri-build"
version = "2.7.4"
version = "2.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adddb0e648752aaac5da9c3c3c6a68e1e87cab55e3b757b18a9441ef8c3ac614"
checksum = "73d80784e874fa117b9b00a6680cf2f9b8a51bbd14406bea980cf8f328b00646"
dependencies = [
"anyhow",
"cargo_toml",
@@ -7315,9 +7325,9 @@ dependencies = [
[[package]]
name = "tauri-codegen"
version = "2.7.4"
version = "2.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb37631cf71dab5e8ab55e1bdd701e18a52653d90b78e71d0e5598b1e0a61316"
checksum = "c5dc6caab4da5646f57648f39b794bae118f0dd4a4305eeb8c892966171f4852"
dependencies = [
"base64 0.23.1",
"brotli",
@@ -7330,7 +7340,7 @@ dependencies = [
"semver 1.0.28",
"serde",
"serde_json",
"sha2 0.10.9",
"sha2 0.11.1",
"syn 2.0.119",
"tauri-utils",
"thiserror 2.0.20",
@@ -7342,9 +7352,9 @@ dependencies = [
[[package]]
name = "tauri-macros"
version = "2.7.4"
version = "2.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cc38db58854c10fb5f91a887ed8bf82d3239bb92b5d8db86eda09e96d9963d1"
checksum = "2831c5da8603a96b1efc0b650c2cb6decc69b6cda257d815fe70c7f5be53818e"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -7717,9 +7727,9 @@ dependencies = [
[[package]]
name = "tauri-runtime"
version = "2.12.2"
version = "2.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c55766d99cea69055904d1735b93c2049302b2e09effd462120deb5581d78e9"
checksum = "60c2b14bd5265b63993cdc34ad526fb836e0fd0cf64a4634a895db0784844d5e"
dependencies = [
"cookie",
"dpi",
@@ -7742,9 +7752,9 @@ dependencies = [
[[package]]
name = "tauri-runtime-wry"
version = "2.12.3"
version = "2.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1aa9d8b7a120f879f44fdc1053f7b7dbf416bf0bbc6a72b714dec46b782b52f"
checksum = "b8c14a025255cc9816d401635035075b09b6cc9973b7b8fd7b8fcb8753f30f92"
dependencies = [
"gtk",
"http",
@@ -7800,9 +7810,9 @@ dependencies = [
[[package]]
name = "tauri-utils"
version = "2.10.2"
version = "2.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "362ab21cd4cc713f2a02b1a9b5688198b1541cfb6907c4281e9190e0f0ef4aa3"
checksum = "28d1d33d4453c5df0bf1672dbc7ada69d8ed74f56a4316d964a4aa73d4ecd3ad"
dependencies = [
"anyhow",
"brotli",
@@ -8998,7 +9008,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
dependencies = [
"proc-macro2",
"quick-xml",
"quick-xml 0.41.0",
"quote",
]
+1 -1
View File
@@ -61,7 +61,7 @@ tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", bra
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
tracing = "0.1.44"
tauri = { version = "2.12.5" }
tauri = { version = "2.12.7" }
tauri-plugin-clipboard-manager = "2.5.0"
parking_lot = "0.13.0"
anyhow = "1.0.104"
+7 -3
View File
@@ -39,6 +39,11 @@
- 修复「TUN 设置」未手动保存时,界面显示的默认 MTU 1500 未生效
- 修复「链式代理」节点列表按名称排序,未保持订阅中的节点顺序
- 修复规则模式下 Muse AI 解锁检测显示错误的出口地区
- 修复使用系统代理时 IP 信息显示直连地址
**🖥️ Windows**
- 修复 Windows 普通用户因权限不足无法开启「开机自启」
**🍎 macOS**
@@ -56,18 +61,17 @@
<summary><strong> ✨ 新增功能 </strong></summary>
- 新增连接页面按网络协议(TCP/UDP)筛选连接
- 新增规则模式下在 `url-test` 或 `fallback` 代理组选节点时,自动将首个包含该组的 `select` 代理组切换到该组,可在「杂项设置」关闭
- 新增规则模式下在规则流量未经过的代理组选节点时,自动将首个包含该组的 `select` 代理组切换到该组,可在「杂项设置」关闭
</details>
<details>
<summary><strong> 🚀 优化改进 </strong></summary>
- 优化首页流量图与代理、订阅、日志、设置页面的渲染效率,长列表滚动与实时刷新更流畅
- 优化连接、规则和日志筛选:切换页面后保留过滤条件
- 优化全局模式代理列表:仅显示 `GLOBAL` 节点,选中其中的策略组时才显示该组
- 优化设置页开关和选项所在行的鼠标悬停高亮,便于对应说明与控件
- 优化首页「当前节点」卡片:代理组列表加入 `fallback` 代理组,切换到 `url-test` 或 `fallback` 代理组时同样联动 `select` 代理组
- 优化首页「当前节点」卡片:按规则指向的代理组逐级显示和切换实际生效的节点,选中后下拉菜单自动收起
**🍎 macOS**
+2 -2
View File
@@ -50,7 +50,7 @@
"@mui/icons-material": "^9.4.0",
"@mui/material": "^9.4.0",
"@tanstack/react-virtual": "^3.14.13",
"@tauri-apps/api": "2.12.4",
"@tauri-apps/api": "2.12.5",
"@tauri-apps/plugin-clipboard-manager": "2.5.0",
"@tauri-apps/plugin-dialog": "2.8.4",
"@tauri-apps/plugin-fs": "2.7.1",
@@ -90,7 +90,7 @@
"@biomejs/biome": "^2.5.14",
"@eslint-react/eslint-plugin": "^5.20.5",
"@eslint/js": "^10.0.1",
"@tauri-apps/cli": "2.12.4",
"@tauri-apps/cli": "2.12.6",
"@types/lodash-es": "^4.17.12",
"@types/node": "^26.0.0",
"@types/react": "19.3.0",
+66 -66
View File
@@ -209,8 +209,8 @@ importers:
specifier: ^3.14.13
version: 3.14.13(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@tauri-apps/api':
specifier: 2.12.4
version: 2.12.4
specifier: 2.12.5
version: 2.12.5
'@tauri-apps/plugin-clipboard-manager':
specifier: 2.5.0
version: 2.5.0
@@ -303,7 +303,7 @@ importers:
version: 2.5.1(react@19.3.1)
tauri-plugin-mihomo-api:
specifier: github:clash-verge-rev/tauri-plugin-mihomo#main
version: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/e49bbedcc67d60da2c10e81bc6433b0f8e8fa232
version: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f
types-pac:
specifier: ^1.0.3
version: 1.0.3
@@ -324,8 +324,8 @@ importers:
specifier: ^10.0.1
version: 10.0.1(eslint@10.11.0(jiti@2.7.0)(supports-color@7.2.0))
'@tauri-apps/cli':
specifier: 2.12.4
version: 2.12.4
specifier: 2.12.6
version: 2.12.6
'@types/lodash-es':
specifier: ^4.17.12
version: 4.17.12
@@ -2072,82 +2072,82 @@ packages:
'@tanstack/virtual-core@3.17.11':
resolution: {integrity: sha512-+ILjvtHup6Y2hzQ6YzwMgX1Q+oQpxEGOXCEsCNaPoIP0VxMbizIBTmYTDtkerkIQS8/CbP1BRuyt8V/8BCsy1g==}
'@tauri-apps/api@2.12.4':
resolution: {integrity: sha512-pVmfis+4zT8H0Qhp3xPZx9Ju7kpzvA6rr/PSJPyuwfvucTQ8sVt61NYU9KMkK703UFlYadFmjKA4HhybOtN0gg==}
'@tauri-apps/api@2.12.5':
resolution: {integrity: sha512-G9QIMt5fzED+aS4QhVK3w1HWLKpLIwH/MnpCr9z1ugGEHnS2ORmqrLkc0uALOjRK4qXJy+4Yiw8LDl/KicC1Hg==}
'@tauri-apps/cli-darwin-arm64@2.12.4':
resolution: {integrity: sha512-OxqKSckIkoJ6vX2AjifIJpTasFC0Hbdoo7gEiCmAjauABO3U8m2MRsLWe+QTiBwDx1mIrvgA+rvI7tvDnbnHVg==}
'@tauri-apps/cli-darwin-arm64@2.12.6':
resolution: {integrity: sha512-Uokwk1hFfJoG54+kD8iU0St33jAIkNvojnjEfBZ6UbL5rnM10AiFwUS/2DHTJ9R4/Kba4U44v7djfMuWFTQgeg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [darwin]
'@tauri-apps/cli-darwin-x64@2.12.4':
resolution: {integrity: sha512-fz76/77wMMJOaaUN6n3CybRG0P/MTEjjqYk81mGPyhi9m6Ue5T+LWBnJP/AkPooNatBPI2vtulGqomyMJ44lCQ==}
'@tauri-apps/cli-darwin-x64@2.12.6':
resolution: {integrity: sha512-WhahqzcyHCpCzh4Taf0ZbBm6nGkvuOSh5ffrgOO7EdYaYe+RBQK8LOlFu+bbjul5v9cdLDi3kco+0+7IlZtTVA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [darwin]
'@tauri-apps/cli-linux-arm-gnueabihf@2.12.4':
resolution: {integrity: sha512-K0w8Bof6Lt8QKLAYhRy0yy36ZH5iA/35VuSOvnxyjvCUZ+A3JKsUTlALviH/sVgAlisaPzzmeJSH8XOn4Q2HBA==}
'@tauri-apps/cli-linux-arm-gnueabihf@2.12.6':
resolution: {integrity: sha512-GB6weN+iFHxiFZ9SOKW6fINis7gnxohoOldR7sryBe7uaavkFGaMCa0yQs5njeXPWvzlE9WTQ13z8oDjmqK+Ww==}
engines: {node: '>= 10'}
cpu: [arm]
os: [linux]
'@tauri-apps/cli-linux-arm64-gnu@2.12.4':
resolution: {integrity: sha512-j5rOnjmRUwWrm1oosf0zBYl4D+fqydgUROFCk0hvKZxvbTT8SOERes0QB7rBV/XWNy+kM6pCKzb3oSm2sRglzg==}
'@tauri-apps/cli-linux-arm64-gnu@2.12.6':
resolution: {integrity: sha512-mdHoUFYKfztUtPKE0C2hhGkEo7j6swXjg+5yRRKSD7A2gLkRPQFIXWD/DAYhiJdeAkyA8MCP6nvvKvg/4YryWQ==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@tauri-apps/cli-linux-arm64-musl@2.12.4':
resolution: {integrity: sha512-aOue3Fy6Jb7+oWcfAVUsVHfeTybSCt2CZoU06aO4jv4d2Ks/KnaTPwMAK3CLEduGOvBLY1lbBBrIyomqLLH5Sg==}
'@tauri-apps/cli-linux-arm64-musl@2.12.6':
resolution: {integrity: sha512-2BxB+9a3JRN0eJ0t0qGe8IKJfgBLOZDE8a499OXH+yg4J9bMpSK1oHXBxnHuSHFWhby4QnQ/t+sBf7tRC0UZeA==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@tauri-apps/cli-linux-riscv64-gnu@2.12.4':
resolution: {integrity: sha512-Fx6GShY/RvST+t6LMlTHAwd66+1tEaAAGrnU7cysVfaiRP1BKng5Vl6rVmO6rSLOA1Sp1dRzNYM4f0OWQGb7qA==}
'@tauri-apps/cli-linux-riscv64-gnu@2.12.6':
resolution: {integrity: sha512-sb58RsNHex9QVqHdN1cf9MMlamUWAtk1NzuxTZalUnBUHfblIbe71hfmdI6whDZ84MufgOdeg/bzvhrbZS1r0w==}
engines: {node: '>= 10'}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@tauri-apps/cli-linux-x64-gnu@2.12.4':
resolution: {integrity: sha512-tNzZSa79Z1nRpHxEpQ38lsAFpKlFlYvoXzjTV+lRRn/zSf3wrdUC3wnLcq2XEadchPu4ttK0zivhYzr+XGD19Q==}
'@tauri-apps/cli-linux-x64-gnu@2.12.6':
resolution: {integrity: sha512-ZAb4/CHRma3ErjL2RGfHjITTUBIs4zySf0hIli9BddOtEdSx0ze0hEgxl+HfBVc5OEW/QmbiZ2E2+CkkHc8Pcg==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@tauri-apps/cli-linux-x64-musl@2.12.4':
resolution: {integrity: sha512-jmZ1pr0xEqUhuEusWtt9Yt+GF6lCnGHUmIL+KIknpbjK/XQ2qkhDBhaxK/JMHM2A8dAacVXCxXJk2EXpwhQUfA==}
'@tauri-apps/cli-linux-x64-musl@2.12.6':
resolution: {integrity: sha512-ueSzM2Du6r4i1d/lby9kEvrhPnXw5zM/VYvcW1ldEWSpkUyVohsBXkmD+U7vMskEW5tXeCUenki7nYVxyGBGpQ==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [musl]
'@tauri-apps/cli-win32-arm64-msvc@2.12.4':
resolution: {integrity: sha512-fGo8pgEHZxdSYgZ/J98m1usJ7NHKmKbq7k6uT0x1rpOq6Bg2YVzzpaAblWk710f5LHYBJIL5QIFS5IrD+4gmTg==}
'@tauri-apps/cli-win32-arm64-msvc@2.12.6':
resolution: {integrity: sha512-6bmOt2BQSe0Bba+5CJcTKSML7VOYDxyiAKyBrjo86VxMdC1usIQmklu3Xc83s3QoK1rOMwwbANlPF6i5R2mvIg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [win32]
'@tauri-apps/cli-win32-ia32-msvc@2.12.4':
resolution: {integrity: sha512-ezl8sQIcjYsye3TUnTH5VcWmWzccZASlQm7hlZt0dYyj1XD0qpVW47u2xYVrIKui0F8uQv/7QGZixdWiClBsbg==}
'@tauri-apps/cli-win32-ia32-msvc@2.12.6':
resolution: {integrity: sha512-9q9ZFNuFreBczwyJuhhlrEOBzGClwWUYirQ2GBl66Y6EaNl17IdLH8TRqoY9wYB1LnctNBi+Fa/WMGtFA4BtFQ==}
engines: {node: '>= 10'}
cpu: [ia32]
os: [win32]
'@tauri-apps/cli-win32-x64-msvc@2.12.4':
resolution: {integrity: sha512-DJhDeCqjLDNMWYFy7ZS8cfeAHX2RK0RbQMLiA3bMVVkXRDJ4NBYiHriGqsUhsr9iG41aTb+dJGkFPmPw1gWwVw==}
'@tauri-apps/cli-win32-x64-msvc@2.12.6':
resolution: {integrity: sha512-ion7Chbj21ROxMRpjQ7G8rz5sIOaI7IoBQum1oq5sl1V5zGWyc/oYnCrQhVqO2TxK/lBDWxt648BzLi02SY3Xg==}
engines: {node: '>= 10'}
cpu: [x64]
os: [win32]
'@tauri-apps/cli@2.12.4':
resolution: {integrity: sha512-JI9bHfudSRJikGOrjbXEm6RjzzvmKuLc+JixB1NE8hNzQkNlCCIC3pTES3uypkR9lxHrsbxzcnSwhI2IxBQphw==}
'@tauri-apps/cli@2.12.6':
resolution: {integrity: sha512-/cOeQgqq8PBDPODOjjT0YHs4qxKCHcQMWMiBm4rLM3JNr9mZE+PHNKOK4zAkhIUtYMNL/0fweW48VNvzD1AbqA==}
engines: {node: '>= 10'}
hasBin: true
@@ -4015,9 +4015,9 @@ packages:
resolution: {integrity: sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==}
engines: {node: '>=18'}
tauri-plugin-mihomo-api@https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/e49bbedcc67d60da2c10e81bc6433b0f8e8fa232:
resolution: {gitHosted: true, integrity: sha512-fy5wxkEBj+L3c1ZefPpU6F9Wmhsx9iLJI3xBeYlvpGg7Iqzo6+qR2KcWpGilgHbpJWcPb6c22QMxyLR369vkeQ==, tarball: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/e49bbedcc67d60da2c10e81bc6433b0f8e8fa232}
version: 0.7.0
tauri-plugin-mihomo-api@https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f:
resolution: {gitHosted: true, integrity: sha512-4nRJ9eBOdd+mT9KaqEhUNya8bh/zaHHAJMBRgFR62KxSZ0S77mcjkB6Bz2xmHqPdYrhbi58aD6UcybEp4a6UyA==, tarball: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f}
version: 0.7.1
terser@5.51.2:
resolution: {integrity: sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==}
@@ -5970,78 +5970,78 @@ snapshots:
'@tanstack/virtual-core@3.17.11': {}
'@tauri-apps/api@2.12.4': {}
'@tauri-apps/api@2.12.5': {}
'@tauri-apps/cli-darwin-arm64@2.12.4':
'@tauri-apps/cli-darwin-arm64@2.12.6':
optional: true
'@tauri-apps/cli-darwin-x64@2.12.4':
'@tauri-apps/cli-darwin-x64@2.12.6':
optional: true
'@tauri-apps/cli-linux-arm-gnueabihf@2.12.4':
'@tauri-apps/cli-linux-arm-gnueabihf@2.12.6':
optional: true
'@tauri-apps/cli-linux-arm64-gnu@2.12.4':
'@tauri-apps/cli-linux-arm64-gnu@2.12.6':
optional: true
'@tauri-apps/cli-linux-arm64-musl@2.12.4':
'@tauri-apps/cli-linux-arm64-musl@2.12.6':
optional: true
'@tauri-apps/cli-linux-riscv64-gnu@2.12.4':
'@tauri-apps/cli-linux-riscv64-gnu@2.12.6':
optional: true
'@tauri-apps/cli-linux-x64-gnu@2.12.4':
'@tauri-apps/cli-linux-x64-gnu@2.12.6':
optional: true
'@tauri-apps/cli-linux-x64-musl@2.12.4':
'@tauri-apps/cli-linux-x64-musl@2.12.6':
optional: true
'@tauri-apps/cli-win32-arm64-msvc@2.12.4':
'@tauri-apps/cli-win32-arm64-msvc@2.12.6':
optional: true
'@tauri-apps/cli-win32-ia32-msvc@2.12.4':
'@tauri-apps/cli-win32-ia32-msvc@2.12.6':
optional: true
'@tauri-apps/cli-win32-x64-msvc@2.12.4':
'@tauri-apps/cli-win32-x64-msvc@2.12.6':
optional: true
'@tauri-apps/cli@2.12.4':
'@tauri-apps/cli@2.12.6':
optionalDependencies:
'@tauri-apps/cli-darwin-arm64': 2.12.4
'@tauri-apps/cli-darwin-x64': 2.12.4
'@tauri-apps/cli-linux-arm-gnueabihf': 2.12.4
'@tauri-apps/cli-linux-arm64-gnu': 2.12.4
'@tauri-apps/cli-linux-arm64-musl': 2.12.4
'@tauri-apps/cli-linux-riscv64-gnu': 2.12.4
'@tauri-apps/cli-linux-x64-gnu': 2.12.4
'@tauri-apps/cli-linux-x64-musl': 2.12.4
'@tauri-apps/cli-win32-arm64-msvc': 2.12.4
'@tauri-apps/cli-win32-ia32-msvc': 2.12.4
'@tauri-apps/cli-win32-x64-msvc': 2.12.4
'@tauri-apps/cli-darwin-arm64': 2.12.6
'@tauri-apps/cli-darwin-x64': 2.12.6
'@tauri-apps/cli-linux-arm-gnueabihf': 2.12.6
'@tauri-apps/cli-linux-arm64-gnu': 2.12.6
'@tauri-apps/cli-linux-arm64-musl': 2.12.6
'@tauri-apps/cli-linux-riscv64-gnu': 2.12.6
'@tauri-apps/cli-linux-x64-gnu': 2.12.6
'@tauri-apps/cli-linux-x64-musl': 2.12.6
'@tauri-apps/cli-win32-arm64-msvc': 2.12.6
'@tauri-apps/cli-win32-ia32-msvc': 2.12.6
'@tauri-apps/cli-win32-x64-msvc': 2.12.6
'@tauri-apps/plugin-clipboard-manager@2.5.0':
dependencies:
'@tauri-apps/api': 2.12.4
'@tauri-apps/api': 2.12.5
'@tauri-apps/plugin-dialog@2.8.4':
dependencies:
'@tauri-apps/api': 2.12.4
'@tauri-apps/api': 2.12.5
'@tauri-apps/plugin-fs@2.7.1':
dependencies:
'@tauri-apps/api': 2.12.4
'@tauri-apps/api': 2.12.5
'@tauri-apps/plugin-http@2.9.0':
dependencies:
'@tauri-apps/api': 2.12.4
'@tauri-apps/api': 2.12.5
'@tauri-apps/plugin-opener@2.7.3':
dependencies:
'@tauri-apps/api': 2.12.4
'@tauri-apps/api': 2.12.5
'@tauri-apps/plugin-updater@2.14.1':
dependencies:
'@tauri-apps/api': 2.12.4
'@tauri-apps/api': 2.12.5
'@tsrs/darwin-arm64@0.20.0-ts7.1.0-beta':
optional: true
@@ -8120,9 +8120,9 @@ snapshots:
minizlib: 3.1.0
yallist: 5.0.0
tauri-plugin-mihomo-api@https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/e49bbedcc67d60da2c10e81bc6433b0f8e8fa232:
tauri-plugin-mihomo-api@https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f:
dependencies:
'@tauri-apps/api': 2.12.4
'@tauri-apps/api': 2.12.5
terser@5.51.2:
dependencies:
+8 -2
View File
@@ -29,7 +29,7 @@ perf-harness = ["dep:tauri-plugin-wdio-webdriver"]
identifier = "io.github.clash-verge-rev.clash-verge-rev"
[build-dependencies]
tauri-build = { version = "2.7.4", features = [] }
tauri-build = { version = "2.7.6", features = [] }
[dependencies]
clash-verge-draft = { workspace = true }
@@ -140,10 +140,16 @@ objc2-app-kit = { version = "0.3.2", features = [
[target.'cfg(windows)'.dependencies]
deelevate = { workspace = true }
quick-xml = "0.42.0"
runas = "=1.2.0"
winreg = "0.56.0"
windows-service = "0.8.1"
windows = { version = "0.62.2", features = ["Win32_Globalization"] }
windows = { version = "0.62.2", features = [
"Win32_System_Com",
"Win32_System_Ole",
"Win32_System_TaskScheduler",
"Win32_System_Variant",
] }
windows-sys.workspace = true
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
+28
View File
@@ -70,6 +70,7 @@ ${StrLoc}
Var PassiveMode
Var UpdateMode
Var KeepAutoLaunch
Var NoShortcutMode
Var WixMode
Var OldMainBinaryName
@@ -333,6 +334,9 @@ Function PageLeaveReinstall
${EndIf}
reinst_uninstall:
${If} $R0 = 1
StrCpy $KeepAutoLaunch 1
${EndIf}
!insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}"
HideWindow
@@ -345,6 +349,7 @@ Function PageLeaveReinstall
ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" ""
ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"
${IfThen} $UpdateMode = 1 ${|} StrCpy $R1 "$R1 /UPDATE" ${|} ; append /UPDATE
${IfThen} $KeepAutoLaunch = 1 ${|} StrCpy $R1 "$R1 /KEEPAUTOLAUNCH" ${|}
${IfThen} $PassiveMode = 1 ${|} StrCpy $R1 "$R1 /P" ${|} ; append /P
StrCpy $R1 "$R1 _?=$4" ; append uninstall directory
ExecWait '$R1' $0
@@ -1098,6 +1103,11 @@ Function un.onInit
${IfNot} ${Errors}
StrCpy $UpdateMode 1
${EndIf}
${GetOptions} $CMDLINE "/KEEPAUTOLAUNCH" $KeepAutoLaunch
${IfNot} ${Errors}
StrCpy $KeepAutoLaunch 1
${EndIf}
FunctionEnd
Section Uninstall
@@ -1291,6 +1301,24 @@ Section Uninstall
DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${PRODUCTNAME}"
${EndIf}
${If} $UpdateMode <> 1
${AndIf} $KeepAutoLaunch <> 1
; UAC can run the uninstaller under a different account from the desktop user.
StrCpy $R0 0
${Do}
EnumRegKey $R1 HKU "" $R0
${If} $R1 == ""
${ExitDo}
${EndIf}
StrCpy $R3 "$R1\Software\Microsoft\Windows\CurrentVersion\Run"
ReadRegStr $R2 HKU "$R3" "Clash Verge Auto Launch"
${If} $R2 == "$\"$INSTDIR\${MAINBINARYNAME}.exe$\""
DeleteRegValue HKU "$R3" "Clash Verge Auto Launch"
${EndIf}
IntOp $R0 $R0 + 1
${Loop}
${EndIf}
; Delete app data if the checkbox is selected
; and if not updating
${If} $DeleteAppDataCheckboxState = 1
-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();
+18 -21
View File
@@ -1,34 +1,31 @@
#[cfg(target_os = "windows")]
use crate::utils::schtasks;
use crate::{config::Config, core::handle::Handle};
use anyhow::Result;
#[cfg(not(target_os = "windows"))]
use clash_verge_logging::logging_error;
use clash_verge_logging::{Type, logging};
#[cfg(not(target_os = "windows"))]
use tauri_plugin_autostart::ManagerExt as _;
#[cfg(target_os = "windows")]
use tauri_plugin_clash_verge_sysinfo::is_current_app_handle_admin;
pub async fn update_launch() -> Result<()> {
let enable_auto_launch = { Config::verge().await.latest_arc().enable_auto_launch };
let is_enable = enable_auto_launch.unwrap_or(false);
logging!(info, Type::System, "Setting auto-launch enabled state to: {is_enable}");
#[cfg(target_os = "windows")]
{
let is_admin = is_current_app_handle_admin(Handle::app_handle());
schtasks::set_auto_launch(is_enable, is_admin).await?;
}
let app_handle = Handle::app_handle();
cfg_select! {
target_os = "windows" => {
use crate::utils::schtasks;
use tauri_plugin_clash_verge_sysinfo::is_current_app_handle_admin;
#[cfg(not(target_os = "windows"))]
{
let app_handle = Handle::app_handle();
let autostart_manager = app_handle.autolaunch();
if is_enable {
logging_error!(Type::System, "{:?}", autostart_manager.enable());
} else {
logging_error!(Type::System, "{:?}", autostart_manager.disable());
let is_admin = is_current_app_handle_admin(app_handle);
schtasks::set_auto_launch(is_enable, is_admin).await?;
}
_ => {
use clash_verge_logging::logging_error;
use tauri_plugin_autostart::ManagerExt as _;
let autostart_manager = app_handle.autolaunch();
if is_enable {
logging_error!(Type::System, "{:?}", autostart_manager.enable());
} else {
logging_error!(Type::System, "{:?}", autostart_manager.disable());
}
}
}
+50 -8
View File
@@ -48,10 +48,13 @@ fn windows_owner_credentials(app_data_root: &Path) -> Result<(OwnerIdentity, Opt
#[cfg(windows)]
fn windows_current_identity() -> Result<OwnerIdentity> {
Ok(OwnerIdentity::Windows {
sid: windows_owner::current_sid()?,
sid: current_user_sid()?,
})
}
#[cfg(windows)]
pub(crate) use windows_owner::{account_sid, current_sid as current_user_sid};
#[cfg(windows)]
pub(crate) fn create_private_current_user_file(path: &Path) -> Result<std::fs::File> {
windows_owner::create_private_file(path)
@@ -93,8 +96,8 @@ mod windows_owner {
use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _};
use std::path::Path;
use windows_sys::Win32::Foundation::{
CloseHandle, ERROR_ACCESS_DENIED, ERROR_FILE_EXISTS, ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND, GENERIC_READ,
GENERIC_WRITE, GetLastError, INVALID_HANDLE_VALUE, LocalFree,
CloseHandle, ERROR_ACCESS_DENIED, ERROR_FILE_EXISTS, ERROR_FILE_NOT_FOUND, ERROR_INSUFFICIENT_BUFFER,
ERROR_PATH_NOT_FOUND, GENERIC_READ, GENERIC_WRITE, GetLastError, INVALID_HANDLE_VALUE, LocalFree,
};
use windows_sys::Win32::Security::Authorization::{
ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, GetSecurityInfo, SDDL_REVISION_1,
@@ -103,8 +106,9 @@ mod windows_owner {
use windows_sys::Win32::Security::{
ACCESS_ALLOWED_ACE, ACL, DACL_SECURITY_INFORMATION, EqualSid, GetAce, GetSecurityDescriptorControl,
GetSecurityDescriptorDacl, GetSecurityDescriptorOwner, GetTokenInformation, IsValidSid, IsWellKnownSid,
OWNER_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID, SE_DACL_PROTECTED,
SECURITY_ATTRIBUTES, TOKEN_QUERY, TOKEN_USER, TokenUser, WinBuiltinAdministratorsSid, WinLocalSystemSid,
LookupAccountNameW, OWNER_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR,
PSID, SE_DACL_PROTECTED, SECURITY_ATTRIBUTES, TOKEN_QUERY, TOKEN_USER, TokenUser, WinBuiltinAdministratorsSid,
WinLocalSystemSid,
};
use windows_sys::Win32::Storage::FileSystem::{
BY_HANDLE_FILE_INFORMATION, CREATE_NEW, CreateFileW, FILE_ALL_ACCESS, FILE_ATTRIBUTE_DIRECTORY,
@@ -123,7 +127,7 @@ mod windows_owner {
crate::utils::server::INSTANCE_LOCK_FILE,
];
pub(super) fn current_sid() -> Result<String> {
pub(crate) fn current_sid() -> Result<String> {
let mut token = std::ptr::null_mut();
if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
return Err(std::io::Error::last_os_error()).context("failed to open process token");
@@ -145,6 +149,44 @@ mod windows_owner {
sid_to_string(token_user.User.Sid)
}
pub(crate) fn account_sid(account: &str) -> Result<String> {
let wide_account: Vec<_> = account.encode_utf16().chain([0]).collect();
let mut sid_size = 0;
let mut domain_len = 0;
let mut account_type = 0;
unsafe {
LookupAccountNameW(
std::ptr::null(),
wide_account.as_ptr(),
std::ptr::null_mut(),
&mut sid_size,
std::ptr::null_mut(),
&mut domain_len,
&mut account_type,
);
}
if unsafe { GetLastError() } != ERROR_INSUFFICIENT_BUFFER {
return Err(std::io::Error::last_os_error()).context("failed to size account SID buffer");
}
let mut sid = vec![0_usize; (sid_size as usize).div_ceil(std::mem::size_of::<usize>())];
let mut domain = vec![0_u16; domain_len as usize];
if unsafe {
LookupAccountNameW(
std::ptr::null(),
wide_account.as_ptr(),
sid.as_mut_ptr().cast(),
&mut sid_size,
domain.as_mut_ptr(),
&mut domain_len,
&mut account_type,
)
} == 0
{
return Err(std::io::Error::last_os_error()).context("failed to look up account SID");
}
sid_to_string(sid.as_mut_ptr().cast())
}
pub(super) fn load_or_create_token(app_data_root: &Path, sid: &str) -> Result<String> {
let token_path = app_data_root.join(OWNER_TOKEN_FILE_NAME);
let descriptor = LocalSecurityDescriptor::from_sid(sid)?;
@@ -640,12 +682,12 @@ mod windows_owner {
fn sid_to_string(sid: PSID) -> Result<String> {
let mut value = std::ptr::null_mut();
if unsafe { ConvertSidToStringSidW(sid, &mut value) } == 0 || value.is_null() {
return Err(std::io::Error::last_os_error()).context("failed to format process SID");
return Err(std::io::Error::last_os_error()).context("failed to format Windows SID");
}
let value = LocalWideString(value);
let length = (0..).take_while(|index| unsafe { *value.0.add(*index) } != 0).count();
String::from_utf16(unsafe { std::slice::from_raw_parts(value.0, length) })
.context("process SID is not valid UTF-16")
.context("Windows SID is not valid UTF-16")
}
fn encode_token(token: &[u8; TOKEN_BYTES]) -> String {
+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,
+269 -264
View File
@@ -1,21 +1,38 @@
use crate::utils::dirs::{self, PathBufExec as _};
use anyhow::{Context as _, Result, anyhow};
use crate::{
core::owner_identity::{account_sid, current_user_sid},
utils::dirs::PathBufExec as _,
};
use anyhow::{Context as _, Result, anyhow, bail, ensure};
use clash_verge_logging::{Type, logging};
use std::fs;
use std::os::windows::process::CommandExt as _;
use quick_xml::escape::escape;
use std::ffi::OsString;
use std::io::ErrorKind;
use std::os::windows::ffi::OsStrExt as _;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use windows::Win32::Globalization::{GetACP, GetOEMCP, MULTI_BYTE_TO_WIDE_CHAR_FLAGS, MultiByteToWideChar};
use windows::{
Win32::{
Foundation::{E_ACCESSDENIED, ERROR_FILE_NOT_FOUND},
System::{
Com::{CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize},
TaskScheduler::{
ITaskFolder, ITaskService, TASK_CREATE, TASK_CREATION, TASK_LOGON_INTERACTIVE_TOKEN, TASK_UPDATE,
TaskScheduler,
},
Variant::VARIANT,
},
},
core::{BSTR, Error as WindowsError},
};
use winreg::{
RegKey,
enums::{HKEY_CURRENT_USER, KEY_QUERY_VALUE, KEY_SET_VALUE},
};
const CREATE_NO_WINDOW: u32 = 0x08000000;
const TASK_NAME_USER: &str = "Clash Verge";
const TASK_NAME_ADMIN: &str = "Clash Verge (Admin)";
const TASK_XML_DIR: &str = "tasks";
const TASK_XML_USER: &str = "clash-verge-task-user.xml";
const TASK_XML_ADMIN: &str = "clash-verge-task-admin.xml";
const RUN_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
const RUN_VALUE: &str = "Clash Verge Auto Launch";
#[derive(Clone, Copy)]
pub enum TaskMode {
#[derive(Clone, Copy, PartialEq, Eq)]
enum TaskMode {
User,
Admin,
}
@@ -23,15 +40,8 @@ pub enum TaskMode {
impl TaskMode {
const fn name(self) -> &'static str {
match self {
Self::User => TASK_NAME_USER,
Self::Admin => TASK_NAME_ADMIN,
}
}
const fn label(self) -> &'static str {
match self {
Self::User => "user",
Self::Admin => "admin",
Self::User => "Clash Verge",
Self::Admin => "Clash Verge (Admin)",
}
}
@@ -41,42 +51,6 @@ impl TaskMode {
Self::Admin => "HighestAvailable",
}
}
const fn xml_file_name(self) -> &'static str {
match self {
Self::User => TASK_XML_USER,
Self::Admin => TASK_XML_ADMIN,
}
}
}
fn get_exe_path() -> Result<PathBuf> {
let exe_path = std::env::current_exe().map_err(|e| anyhow!("failed to get exe path: {}", e))?;
Ok(exe_path)
}
fn get_task_user_id() -> Result<String> {
let username = std::env::var_os("USERNAME")
.or_else(|| std::env::var_os("USER"))
.ok_or_else(|| anyhow!("failed to get current user name"))?;
let username = username.to_string_lossy();
let username = username.trim();
if username.is_empty() {
return Err(anyhow!("current user name is empty"));
}
let domain = std::env::var_os("USERDOMAIN")
.or_else(|| std::env::var_os("COMPUTERNAME"))
.map(|value| value.to_string_lossy().to_string());
if let Some(domain) = domain {
let domain = domain.trim();
if !domain.is_empty() {
return Ok(format!("{domain}\\{username}"));
}
}
Ok(username.to_string())
}
fn get_startup_dir() -> Result<PathBuf> {
@@ -111,45 +85,23 @@ async fn cleanup_legacy_shortcuts() -> Result<()> {
Ok(())
}
fn task_xml_path(mode: TaskMode) -> Result<PathBuf> {
let dir = dirs::app_home_dir()?.join(TASK_XML_DIR);
fs::create_dir_all(&dir).map_err(|e| anyhow!("failed to create task xml dir: {}", e))?;
Ok(dir.join(mode.xml_file_name()))
}
fn xml_escape(value: &str) -> String {
let mut escaped = String::with_capacity(value.len());
for ch in value.chars() {
match ch {
'&' => escaped.push_str("&amp;"),
'<' => escaped.push_str("&lt;"),
'>' => escaped.push_str("&gt;"),
'"' => escaped.push_str("&quot;"),
'\'' => escaped.push_str("&apos;"),
_ => escaped.push(ch),
}
}
escaped
}
fn build_task_xml(mode: TaskMode) -> Result<String> {
let exe_path = get_exe_path()?.to_string_lossy().to_string();
let exe_path = xml_escape(&exe_path);
let user_id = xml_escape(&get_task_user_id()?);
Ok(format!(
fn build_task_xml(mode: TaskMode, user_sid: &str, exe: &Path) -> String {
let exe_path = escape(exe.to_string_lossy());
let run_level = mode.xml_run_level();
format!(
r#"<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<Triggers>
<LogonTrigger>
<Enabled>true</Enabled>
<UserId>{}</UserId>
<UserId>{user_sid}</UserId>
</LogonTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>{}</UserId>
<UserId>{user_sid}</UserId>
<LogonType>InteractiveToken</LogonType>
<RunLevel>{}</RunLevel>
<RunLevel>{run_level}</RunLevel>
</Principal>
</Principals>
<Settings>
@@ -173,209 +125,262 @@ fn build_task_xml(mode: TaskMode) -> Result<String> {
</Settings>
<Actions Context="Author">
<Exec>
<Command>{}</Command>
<Command>{exe_path}</Command>
</Exec>
</Actions>
</Task>
"#,
user_id,
user_id,
mode.xml_run_level(),
exe_path
))
"#
)
}
fn encode_utf16le_with_bom(content: &str) -> Vec<u8> {
let mut bytes = Vec::with_capacity(2 + content.len() * 2);
bytes.extend_from_slice(&[0xFF, 0xFE]);
for unit in content.encode_utf16() {
bytes.extend_from_slice(&unit.to_le_bytes());
}
bytes
}
struct ComApartment;
fn write_task_xml(mode: TaskMode) -> Result<PathBuf> {
let task_xml = build_task_xml(mode)?;
let task_xml_path = task_xml_path(mode)?;
let encoded = encode_utf16le_with_bom(&task_xml);
fs::write(&task_xml_path, encoded).map_err(|e| anyhow!("failed to write task xml: {}", e))?;
Ok(task_xml_path)
}
fn decode_with_code_page(bytes: &[u8], code_page: u32) -> Option<String> {
if bytes.is_empty() {
return Some(String::new());
}
let len = bytes.len();
if len > i32::MAX as usize {
return None;
}
let required = unsafe { MultiByteToWideChar(code_page, MULTI_BYTE_TO_WIDE_CHAR_FLAGS(0), bytes, None) };
if required <= 0 {
return None;
}
let mut wide = vec![0u16; required as usize];
let written = unsafe { MultiByteToWideChar(code_page, MULTI_BYTE_TO_WIDE_CHAR_FLAGS(0), bytes, Some(&mut wide)) };
if written <= 0 {
return None;
}
wide.truncate(written as usize);
Some(String::from_utf16_lossy(&wide))
}
fn decode_console_output(bytes: &[u8]) -> String {
if let Ok(text) = std::str::from_utf8(bytes) {
return text.to_string();
}
let oem = unsafe { GetOEMCP() };
if let Some(text) = decode_with_code_page(bytes, oem) {
return text;
}
let acp = unsafe { GetACP() };
if let Some(text) = decode_with_code_page(bytes, acp) {
return text;
}
String::from_utf8_lossy(bytes).to_string()
}
fn output_message(output: &Output) -> String {
let stdout = decode_console_output(&output.stdout);
let stderr = decode_console_output(&output.stderr);
let stdout = stdout.trim();
let stderr = stderr.trim();
match (stdout.is_empty(), stderr.is_empty()) {
(true, true) => "unknown error".to_string(),
(false, true) => stdout.to_string(),
(true, false) => stderr.to_string(),
(false, false) => format!("{stdout} | {stderr}"),
impl ComApartment {
fn initialize() -> Result<Self> {
unsafe { CoInitializeEx(None, COINIT_MULTITHREADED).ok() }.context("failed to initialize COM")?;
Ok(Self)
}
}
fn schtasks_output(mut cmd: Command) -> Result<Output> {
cmd.creation_flags(CREATE_NO_WINDOW)
.output()
.map_err(|e| anyhow!("failed to execute schtasks: {}", e))
impl Drop for ComApartment {
fn drop(&mut self) {
unsafe { CoUninitialize() };
}
}
pub fn is_task_enabled(mode: TaskMode) -> Result<bool> {
let output = schtasks_output({
let mut cmd = Command::new("schtasks");
cmd.args(["/Query", "/TN", mode.name()]);
cmd
})?;
Ok(output.status.success())
#[derive(Clone, Copy, PartialEq, Eq)]
enum TaskOwner {
Missing,
CurrentUser,
OtherUser,
}
pub fn create_task(mode: TaskMode) -> Result<()> {
let task_xml_path = write_task_xml(mode)?;
let output = schtasks_output({
let mut cmd = Command::new("schtasks");
cmd.args(["/Create", "/TN", mode.name(), "/XML"]);
cmd.arg(&task_xml_path);
cmd.arg("/F");
cmd
})?;
if !output.status.success() {
return Err(anyhow!(
"failed to create {} task: {}",
mode.label(),
output_message(&output)
));
}
logging!(info, Type::Setup, "Created {} auto-launch task", mode.label());
Ok(())
struct ScheduledTasks {
folder: ITaskFolder,
user_sid: String,
// Drop the COM interface before uninitializing the apartment.
_com: ComApartment,
}
pub fn remove_task(mode: TaskMode) -> Result<()> {
let output = schtasks_output({
let mut cmd = Command::new("schtasks");
cmd.args(["/Delete", "/TN", mode.name(), "/F"]);
cmd
})?;
if output.status.success() {
logging!(info, Type::Setup, "Removed {} auto-launch task", mode.label());
return Ok(());
impl ScheduledTasks {
fn connect() -> Result<Self> {
let com = ComApartment::initialize()?;
let service: ITaskService = unsafe { CoCreateInstance(&TaskScheduler, None, CLSCTX_INPROC_SERVER) }
.context("failed to open Task Scheduler")?;
let empty = VARIANT::default();
unsafe { service.Connect(&empty, &empty, &empty, &empty) }.context("failed to connect to Task Scheduler")?;
let folder =
unsafe { service.GetFolder(&BSTR::from(r"\")) }.context("failed to open the Task Scheduler root folder")?;
Ok(Self {
folder,
user_sid: current_user_sid()?,
_com: com,
})
}
if !is_task_enabled(mode)? {
logging!(
info,
Type::Setup,
"{} auto-launch task not found, skipping removal",
mode.label()
);
return Ok(());
}
Err(anyhow!(
"failed to remove {} task: {}",
mode.label(),
output_message(&output)
))
}
pub async fn set_auto_launch(is_enable: bool, is_admin: bool) -> Result<()> {
let target = if is_admin { TaskMode::Admin } else { TaskMode::User };
let other = if is_admin { TaskMode::User } else { TaskMode::Admin };
if let Err(err) = cleanup_legacy_shortcuts().await {
logging!(warn, Type::Setup, "Failed to cleanup legacy startup shortcuts: {err:#}");
}
if is_enable {
if is_admin {
create_task(target)?;
if let Err(err) = remove_task(other) {
let _ = remove_task(target);
return Err(err);
fn owner(&self, mode: TaskMode) -> Result<TaskOwner> {
let task = match unsafe { self.folder.GetTask(&BSTR::from(mode.name())) } {
Ok(task) => task,
Err(error) if task_missing(&error) => return Ok(TaskOwner::Missing),
Err(error) => return Err(error).with_context(|| format!("failed to find the {} task", mode.name())),
};
let principal_sid = (|| {
let principal = unsafe { task.Definition()?.Principal()? };
let mut user = BSTR::new();
unsafe { principal.UserId(&mut user)? };
let user = String::try_from(&user)?;
if user.starts_with("S-1-") {
return Ok(user);
}
account_sid(&user)
})()
.with_context(|| format!("failed to identify the owner of the {} task", mode.name()))?;
Ok(if principal_sid == self.user_sid {
TaskOwner::CurrentUser
} else {
if is_task_enabled(other)? {
return Err(anyhow!(
"admin auto-launch task exists; run the app as administrator to remove it before creating a user task"
));
TaskOwner::OtherUser
})
}
fn has_current_user_task(&self) -> Result<bool> {
let user_task = self.owner(TaskMode::User)?;
let admin_task = self.owner(TaskMode::Admin)?;
Ok(user_task == TaskOwner::CurrentUser || admin_task == TaskOwner::CurrentUser)
}
fn register(&self, mode: TaskMode, exe: &Path, flags: TASK_CREATION) -> windows::core::Result<()> {
let xml = BSTR::from(build_task_xml(mode, &self.user_sid, exe));
let empty = VARIANT::default();
unsafe {
self.folder.RegisterTask(
&BSTR::from(mode.name()),
&xml,
flags.0,
&empty,
&empty,
TASK_LOGON_INTERACTIVE_TOKEN,
&empty,
)
}
.map(drop)
}
fn remove(&self, mode: TaskMode) -> Result<()> {
match unsafe { self.folder.DeleteTask(&BSTR::from(mode.name()), 0) } {
Ok(()) => {
logging!(info, Type::Setup, "Removed the {} auto-launch task", mode.name());
Ok(())
}
create_task(target)?;
Err(error) if task_missing(&error) => Ok(()),
Err(error) => Err(error).with_context(|| format!("failed to remove the {} task", mode.name())),
}
return Ok(());
}
}
if is_admin {
let mut errors = Vec::new();
if let Err(err) = remove_task(TaskMode::User) {
errors.push(err);
}
if let Err(err) = remove_task(TaskMode::Admin) {
errors.push(err);
}
fn task_missing(error: &WindowsError) -> bool {
error.code() == ERROR_FILE_NOT_FOUND.to_hresult()
}
if let Some(err) = errors.into_iter().next() {
return Err(err);
}
fn write_startup_entry(exe: &Path) -> Result<()> {
let mut command = OsString::from("\"");
command.push(exe);
command.push("\"");
ensure!(
command.encode_wide().count() <= 260,
"the startup command exceeds the Windows Run entry limit"
);
return Ok(());
let (key, _) = RegKey::predef(HKEY_CURRENT_USER)
.create_subkey_with_flags(RUN_KEY, KEY_SET_VALUE)
.context("failed to open the current user's Run key for writing")?;
key.set_value(RUN_VALUE, &command)
.context("failed to write the per-user startup entry")
}
fn startup_entry_for_removal() -> Result<Option<RegKey>> {
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let entry = hkcu
.open_subkey_with_flags(RUN_KEY, KEY_QUERY_VALUE)
.and_then(|key| key.get_raw_value(RUN_VALUE));
match entry {
Ok(_) => hkcu
.open_subkey_with_flags(RUN_KEY, KEY_SET_VALUE)
.map(Some)
.context("failed to open the current user's Run key for cleanup"),
Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
Err(error) => Err(error).context("failed to inspect the per-user startup entry"),
}
}
remove_task(TaskMode::User)?;
if is_task_enabled(TaskMode::Admin)? {
return Err(anyhow!(
"admin auto-launch task exists; run the app as administrator to remove it"
));
fn remove_startup_entry(key: Option<RegKey>) -> Result<()> {
if let Some(key) = key {
match key.delete_value(RUN_VALUE) {
Ok(()) => (),
Err(error) if error.kind() == ErrorKind::NotFound => (),
Err(error) => return Err(error).context("failed to remove the per-user startup entry"),
}
}
Ok(())
}
fn enable_auto_launch(
tasks: &ScheduledTasks,
mode: TaskMode,
user_task: TaskOwner,
admin_task: TaskOwner,
) -> Result<()> {
let target = match mode {
TaskMode::User => user_task,
TaskMode::Admin => admin_task,
};
ensure!(
target != TaskOwner::OtherUser,
"the {} auto-launch task belongs to another Windows account",
mode.name()
);
let exe = std::env::current_exe().context("failed to get the app executable path")?;
let exe = dunce::simplified(&exe);
let fallback = startup_entry_for_removal()?;
let is_new_task = target == TaskOwner::Missing;
let flags = if is_new_task { TASK_CREATE } else { TASK_UPDATE };
if let Err(error) = tasks.register(mode, exe, flags) {
let can_fallback = mode == TaskMode::User && is_new_task && error.code() == E_ACCESSDENIED;
// A task could have appeared after the first lookup and may already launch the app.
if can_fallback && !tasks.has_current_user_task()? {
write_startup_entry(exe).with_context(|| format!("Task Scheduler denied registration ({error})"))?;
logging!(
info,
Type::Setup,
"Using the per-user startup entry after Task Scheduler denied registration"
);
return Ok(());
}
return Err(error).with_context(|| format!("failed to register the {} task", mode.name()));
}
let cleanup = (|| {
if mode == TaskMode::Admin && user_task == TaskOwner::CurrentUser {
tasks.remove(TaskMode::User)?;
}
remove_startup_entry(fallback)
})();
if let Err(error) = cleanup {
if is_new_task && let Err(rollback) = tasks.remove(mode) {
return Err(error.context(format!(
"failed to roll back the new {} task: {rollback:#}",
mode.name()
)));
}
return Err(error);
}
logging!(info, Type::Setup, "Registered the {} auto-launch task", mode.name());
Ok(())
}
fn configure_auto_launch(enabled: bool, mode: TaskMode) -> Result<()> {
let tasks = ScheduledTasks::connect()?;
let admin_task = tasks.owner(TaskMode::Admin)?;
if mode == TaskMode::User && admin_task == TaskOwner::CurrentUser {
bail!("run Clash Verge as administrator to manage its existing elevated auto-launch task");
}
let user_task = tasks.owner(TaskMode::User)?;
if enabled {
return enable_auto_launch(&tasks, mode, user_task, admin_task);
}
let fallback = startup_entry_for_removal()?;
if admin_task == TaskOwner::CurrentUser {
tasks.remove(TaskMode::Admin)?;
}
if user_task == TaskOwner::CurrentUser {
tasks.remove(TaskMode::User)?;
}
remove_startup_entry(fallback)
}
pub async fn set_auto_launch(enabled: bool, is_admin: bool) -> Result<()> {
let mode = if is_admin { TaskMode::Admin } else { TaskMode::User };
let result = tokio::task::spawn_blocking(move || configure_auto_launch(enabled, mode)).await?;
result.map_err(|error| {
if mode == TaskMode::User
&& error
.downcast_ref::<WindowsError>()
.is_some_and(|error| error.code() == E_ACCESSDENIED)
{
error.context("run Clash Verge as administrator to manage its scheduled auto-launch tasks")
} else {
error
}
})?;
if let Err(error) = cleanup_legacy_shortcuts().await {
logging!(
warn,
Type::Setup,
"Failed to clean up legacy startup shortcuts: {error:#}"
);
}
Ok(())
}
+283 -204
View File
@@ -54,8 +54,8 @@ import {
useClashConfigData,
useCoreDataStatus,
useProxiesData,
useRulesData,
} from '@/providers/app-data-context'
import { followProxyGroup } from '@/services/cmds'
import delayManager from '@/services/delay'
import {
findCurrentGroupMember,
@@ -63,7 +63,9 @@ import {
isInteractableMember,
memberDetails,
resolveMember,
type InteractableProxyMemberOccurrence,
type ProxyGroupView,
type ProxyViewV1,
type ResolvedProxyMember,
} from '@/types/proxy-view'
import { debugLog } from '@/utils/debug'
@@ -118,7 +120,37 @@ interface ProxyOption {
disabled: boolean
}
type OpenSelect = 'group' | 'proxy' | null
interface RuleEntry {
group: ProxyGroupView
ruleCount: number
isDefault: boolean
}
interface ChainLevel {
group: Pick<ProxyGroupView, 'name' | 'members' | 'fixed'>
current?: InteractableProxyMemberOccurrence
}
const SELECTABLE_GROUP_TYPES = ['Selector', 'URLTest', 'Fallback']
const ENTRY_SELECT = 'entry'
const levelSelect = (groupName: string) => `level:${groupName}`
const resolveChain = (view: ProxyViewV1, entry: ProxyGroupView) => {
const levels: ChainLevel[] = []
let group: ProxyGroupView | undefined = entry
while (group) {
const current = findCurrentGroupMember(view, group)
levels.push({ group, current })
// A load-balance member has no single active node, so the chain ends on it.
group =
current?.member.kind === 'group' &&
SELECTABLE_GROUP_TYPES.includes(current.member.group.type)
? current.member.group
: undefined
}
return levels
}
function convertDelayColor(
delayValue: number,
@@ -411,6 +443,13 @@ const PersistentSelect = ({
role="listbox"
aria-labelledby={labelId}
variant="selectedMenu"
onClick={(event) => {
// A disabled option passes its click to the list itself.
if (!(event.target as Element).closest('[role="option"]'))
return
onOpenChange(false)
anchorRef.current?.focus({ preventScroll: true })
}}
>
{open && renderOptions()}
</MenuList>
@@ -423,13 +462,11 @@ const PersistentSelect = ({
interface PersistentProxySelectProps
extends Omit<PersistentSelectProps, 'displayValue' | 'renderOptions'> {
value: string
selectedName: string
groupName: string
fixed?: string | null
selectedDelay: number
options: ProxyOption[]
onChange: (value: string) => void
view: ProxyViewV1
level: ChainLevel
sortType: ProxySortType
latencyTimeout?: number
onChange: (groupName: string, proxyName: string, fixed?: string) => void
}
const ProxyMenuOption = memo(function ProxyMenuOption({
@@ -445,7 +482,7 @@ const ProxyMenuOption = memo(function ProxyMenuOption({
isFixed: boolean
fixedProxyInUsed: boolean
delay: number
onChange: (value: string) => void
onChange: (proxyName: string) => void
}) {
return (
<MenuItem
@@ -454,7 +491,7 @@ const ProxyMenuOption = memo(function ProxyMenuOption({
selected={selected}
disabled={option.disabled}
onClick={() => {
if (!option.disabled) onChange(option.value)
if (!option.disabled) onChange(option.name)
}}
sx={{
display: 'flex',
@@ -499,17 +536,49 @@ const ProxyMenuOption = memo(function ProxyMenuOption({
})
const PersistentProxySelect = ({
groupName,
fixed,
selectedName,
selectedDelay,
options,
value,
view,
level: { group, current },
sortType,
latencyTimeout,
onChange,
...props
}: PersistentProxySelectProps) => {
const groupName = group.name
const fixed = group.fixed
const selectedName = current?.member.ref.name ?? ''
const value = current ? optionValue(current.memberIndex, current.member) : ''
const fixedProxyInUsed = selectedName === fixed
const delays = useGroupDelays(groupName, current?.member, props.open)
const selectedDelay =
typeof delays === 'number'
? delays
: current
? delays.of(current.member)
: -1
const options = useMemo(() => {
if (typeof delays === 'number') return []
const unsorted = group.members.map((memberRef, memberIndex) => {
const member = resolveMember(view, memberRef)
return {
memberIndex,
member,
value: optionValue(memberIndex, member),
name: member.ref.name,
disabled: !isInteractableMember(member),
}
})
return sortType === 2
? unsorted.sort((a, b) => a.name.localeCompare(b.name))
: sortProxyOptions(unsorted, sortType, delays.of, latencyTimeout)
}, [delays, group.members, latencyTimeout, sortType, view])
const handleChange = useCallback(
(proxyName: string) => onChange(groupName, proxyName, fixed),
[fixed, groupName, onChange],
)
return (
<PersistentSelect
{...props}
@@ -557,7 +626,7 @@ const PersistentProxySelect = ({
isFixed={isFixed}
fixedProxyInUsed={fixedProxyInUsed}
delay={delay}
onChange={onChange}
onChange={handleChange}
/>
)
})
@@ -571,6 +640,7 @@ export const CurrentProxyCard = () => {
const navigate = useNavigate()
const theme = useTheme()
const { proxyView } = useProxiesData()
const { rules } = useRulesData()
const { clashConfig } = useClashConfigData()
const { refreshProxy } = useAppRefreshers()
const { isCoreDataPending } = useCoreDataStatus()
@@ -649,8 +719,8 @@ export const CurrentProxyCard = () => {
return savedSortType ? (Number(savedSortType) as ProxySortType) : 0
})
const [lastGroupName, setLastGroupName] = useState('')
const [openSelect, setOpenSelect] = useState<OpenSelect>(null)
const [pickedGroupName, setPickedGroupName] = useState('')
const [openSelect, setOpenSelect] = useState<string | null>(null)
const [openSelectMode, setOpenSelectMode] = useState(mode)
if (openSelectMode !== mode) {
setOpenSelectMode(mode)
@@ -661,151 +731,130 @@ export const CurrentProxyCard = () => {
const autoCheckInProgressRef = useRef(false)
const selectableGroups = useMemo(() => {
const entries = useMemo<RuleEntry[]>(() => {
if (!proxyView) return []
return proxyView.groups.filter(
(group) =>
!group.hidden &&
['Selector', 'URLTest', 'Fallback'].includes(group.type),
)
}, [proxyView])
const isSelectable = (group: ProxyGroupView) =>
!group.hidden && SELECTABLE_GROUP_TYPES.includes(group.type)
const ruleCounts = new Map<string, number>()
for (const { proxy } of rules) {
ruleCounts.set(proxy, (ruleCounts.get(proxy) ?? 0) + 1)
}
const matchTarget = rules.find(({ type }) => type === 'Match')?.proxy
// The view keeps GLOBAL out of `groups`, yet rules may name it.
const ruleEntries = [
...proxyView.groups,
...(proxyView.global ? [proxyView.global] : []),
]
.filter(isSelectable)
.flatMap((group) => {
const ruleCount = ruleCounts.get(group.name)
return ruleCount
? [{ group, ruleCount, isDefault: group.name === matchTarget }]
: []
})
// Rules that failed to load, or that name no selectable group, leave nothing to anchor on.
return ruleEntries.length > 0
? ruleEntries
: proxyView.groups.filter(isSelectable).map((group) => ({
group,
ruleCount: 0,
isDefault: false,
}))
}, [proxyView, rules])
const selectedGroupName = useMemo(() => {
if (isDirectMode) return 'DIRECT'
if (!proxyView) return lastGroupName
if (!proxyView) return ''
if (isGlobalMode) return proxyView.global?.name ?? 'GLOBAL'
const hasGroup = (name: string | null) =>
!!name && selectableGroups.some((group) => group.name === name)
if (hasGroup(lastGroupName)) return lastGroupName
const hasEntry = (name: string | null) =>
!!name && entries.some(({ group }) => group.name === name)
if (hasEntry(pickedGroupName)) return pickedGroupName
const savedGroup = readProfileScopedItem(STORAGE_KEY_GROUP)
if (hasGroup(savedGroup)) return savedGroup!
if (hasEntry(savedGroup)) return savedGroup!
const primaryKeywords = ['auto', 'select', 'proxy', '节点选择', '自动选择']
const primaryGroup =
selectableGroups.find((group) =>
primaryKeywords.some((keyword) =>
group.name.toLowerCase().includes(keyword.toLowerCase()),
),
) ?? selectableGroups[0]
return primaryGroup?.name ?? ''
const defaultEntry =
entries.find(({ isDefault }) => isDefault) ??
entries.reduce<RuleEntry | undefined>(
(most, entry) =>
most && most.ruleCount >= entry.ruleCount ? most : entry,
undefined,
)
return defaultEntry?.group.name ?? ''
}, [
entries,
isDirectMode,
isGlobalMode,
lastGroupName,
pickedGroupName,
proxyView,
readProfileScopedItem,
selectableGroups,
])
// Keep the shown group, auto picks included, until it leaves the profile.
if (proxyView && lastGroupName !== selectedGroupName) {
setLastGroupName(selectedGroupName)
}
const selectedGroup = useMemo<ProxyGroupView | null>(() => {
if (!proxyView || isDirectMode) return null
if (isGlobalMode) return proxyView.global
return (
selectableGroups.find(({ name }) => name === selectedGroupName) ?? null
)
}, [
isDirectMode,
isGlobalMode,
proxyView,
selectableGroups,
selectedGroupName,
])
const optionsForGroup = useCallback(
(group: ProxyGroupView | null): ProxyOption[] =>
proxyView && group
? group.members.map((memberRef, memberIndex) => {
const member = resolveMember(proxyView, memberRef)
return {
memberIndex,
member,
value: optionValue(memberIndex, member),
name: member.ref.name,
disabled: !isInteractableMember(member),
}
})
: [],
[proxyView],
)
const selectedEntry =
isGlobalMode || isDirectMode
? undefined
: entries.find(({ group }) => group.name === selectedGroupName)
const selectedGroup = isGlobalMode ? proxyView?.global : selectedEntry?.group
const unsortedProxyOptions = useMemo(
() => optionsForGroup(selectedGroup),
[optionsForGroup, selectedGroup],
)
const currentOption = useMemo(() => {
if (!proxyView) return undefined
const levels = useMemo<ChainLevel[]>(() => {
if (!proxyView) return []
if (isDirectMode) {
const node =
proxyView.direct == null
? undefined
: getRecord(proxyView, proxyView.direct)
return node
? ({
memberIndex: 0,
member: {
kind: 'node',
ref: { kind: 'node', name: node.name, recordId: node.recordId },
node,
? [
{
group: { name: 'DIRECT', members: [] },
current: {
memberIndex: 0,
member: {
kind: 'node',
ref: {
kind: 'node',
name: node.name,
recordId: node.recordId,
},
node,
},
},
},
} satisfies Pick<ProxyOption, 'memberIndex' | 'member'>)
: undefined
]
: []
}
return selectedGroup
? findCurrentGroupMember(proxyView, selectedGroup)
: undefined
return selectedGroup ? resolveChain(proxyView, selectedGroup) : []
}, [isDirectMode, proxyView, selectedGroup])
// A chain deeper than two groups shares one row above the node list so the card stays three rows tall.
const levelRows =
levels.length > 2
? [levels.slice(0, -1), levels.slice(-1)]
: levels.map((level) => [level])
const leafLevel = levels.at(-1)
const leafGroupName = leafLevel?.group.name ?? ''
const handleGroupChange = useCallback(
(newGroupName: string) => {
if (isGlobalMode || isDirectMode) return
setLastGroupName(newGroupName)
setPickedGroupName(newGroupName)
writeProfileScopedItem(STORAGE_KEY_GROUP, newGroupName)
void followProxyGroup(newGroupName)
},
[isDirectMode, isGlobalMode, writeProfileScopedItem],
)
const handleProxyChange = useCallback(
(value: string) => {
if (isDirectMode) return
const option = unsortedProxyOptions.find(
(candidate) => candidate.value === value,
)
if (!selectedGroup || !option || !isInteractableMember(option.member)) {
return
}
const nextName = option.member.ref.name
// The profile selection is the durable source across core restarts and run modes.
select(selectedGroup.name, nextName, selectedGroup.fixed!)
},
[isDirectMode, select, selectedGroup, unsortedProxyOptions],
)
const goToProxies = useCallback(() => {
navigate('/proxies')
}, [navigate])
const currentMember = currentOption?.member
const currentMember = leafLevel?.current?.member
const currentProxy = currentMember ? memberDetails(currentMember) : undefined
const selectedProxyName = currentMember?.ref.name ?? ''
const delays = useGroupDelays(
selectedGroupName,
const currentDelay = useGroupDelays(
leafGroupName,
currentMember,
openSelect === 'proxy',
)
const currentDelay =
typeof delays === 'number'
? delays
: currentMember
? delays.of(currentMember)
: -1
false,
) as number
const signalInfo =
currentProxy && selectedGroupName
@@ -820,18 +869,11 @@ export const CurrentProxyCard = () => {
if (autoCheckInProgressRef.current) return
if (isDirectMode) return
const groupName = selectedGroupName
const groupName = leafGroupName
const proxyName = selectedProxyName
const proxyMember = currentMember
if (!groupName || !proxyName) return
const proxyMember = currentOption?.member
if (!proxyMember || !isInteractableMember(proxyMember)) {
debugLog(
`[CurrentProxyCard] 自动延迟检测跳过,组: ${groupName}, 节点: ${proxyName} 未找到`,
)
return
}
if (!groupName || !proxyMember) return
autoCheckInProgressRef.current = true
@@ -856,7 +898,7 @@ export const CurrentProxyCard = () => {
useEffect(() => {
if (isDirectMode) return
if (!autoDelayEnabled) return
if (!selectedGroupName || !selectedProxyName) return
if (!leafGroupName || !selectedProxyName) return
let disposed = false
let intervalTimer: ReturnType<typeof setTimeout> | null = null
@@ -883,7 +925,7 @@ export const CurrentProxyCard = () => {
}, [
autoDelayIntervalMs,
isDirectMode,
selectedGroupName,
leafGroupName,
selectedProxyName,
autoDelayEnabled,
])
@@ -894,16 +936,21 @@ export const CurrentProxyCard = () => {
localStorage.setItem(STORAGE_KEY_SORT_TYPE, newSortType.toString())
}, [sortType])
// The button keeps an open list open, so it tests the list being looked at.
const delayLevel =
levels.find(({ group }) => openSelect === levelSelect(group.name)) ??
leafLevel
const handleCheckDelay = useLockFn(async () => {
const groupName = selectedGroupName
if (!groupName || isDirectMode) return
if (!proxyView || !delayLevel || isDirectMode) return
const groupName = delayLevel.group.name
debugLog(`[CurrentProxyCard] 开始测试所有延迟,组: ${groupName}`)
const timeout = verge?.default_latency_timeout || 10000
const interactable = unsortedProxyOptions
.map(({ member }) => member)
const interactable = delayLevel.group.members
.map((member) => resolveMember(proxyView, member))
.filter(isInteractableMember)
.filter(({ ref }) => ref.name !== 'DIRECT' && ref.name !== 'REJECT')
@@ -925,35 +972,14 @@ export const CurrentProxyCard = () => {
refreshProxy()
})
const nameSortedProxyOptions = useMemo(
() =>
!isDirectMode && openSelect === 'proxy' && sortType === 2
? [...unsortedProxyOptions].sort((a, b) => a.name.localeCompare(b.name))
: unsortedProxyOptions,
[isDirectMode, openSelect, sortType, unsortedProxyOptions],
)
const proxyOptions = useMemo(
() =>
isDirectMode || openSelect !== 'proxy' || typeof delays === 'number'
? []
: sortType === 2
? nameSortedProxyOptions
: sortProxyOptions(
unsortedProxyOptions,
sortType,
delays.of,
defaultLatencyTimeout!,
),
[
delays,
nameSortedProxyOptions,
isDirectMode,
openSelect,
unsortedProxyOptions,
sortType,
defaultLatencyTimeout,
],
)
const entrySummary = ({ ruleCount, isDefault }: RuleEntry) => {
const count = t('home.components.currentProxy.labels.ruleCount', {
count: ruleCount,
})
return isDefault
? `${t('home.components.currentProxy.labels.defaultRoute')} · ${count}`
: count
}
const getSortIcon = (): React.ReactElement => {
switch (sortType) {
@@ -1007,7 +1033,7 @@ export const CurrentProxyCard = () => {
size="small"
color="inherit"
onClick={handleCheckDelay}
disabled={isDirectMode || unsortedProxyOptions.length === 0}
disabled={isDirectMode || !delayLevel?.group.members.length}
aria-label={t(
'home.components.currentProxy.actions.refreshDelay',
)}
@@ -1117,48 +1143,101 @@ export const CurrentProxyCard = () => {
/>
)}
</Box>
<Box sx={{ mb: 1.5 }}>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}>
<PersistentSelect
label={t('home.components.currentProxy.labels.group')}
displayValue={<Typography noWrap>{selectedGroupName}</Typography>}
open={openSelect === 'group'}
label={t(
selectedEntry?.ruleCount
? 'home.components.currentProxy.labels.ruleTarget'
: 'home.components.currentProxy.labels.group',
)}
displayValue={
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Typography noWrap sx={{ minWidth: 0, flex: 1 }}>
{selectedGroupName}
</Typography>
{!!selectedEntry?.ruleCount && (
<Typography
variant="caption"
sx={{ flexShrink: 0, color: 'text.secondary' }}
>
{entrySummary(selectedEntry)}
</Typography>
)}
</Box>
}
open={openSelect === ENTRY_SELECT}
disabled={isGlobalMode || isDirectMode}
keepOpenRef={delayButtonRef}
onOpenChange={(open) => setOpenSelect(open ? 'group' : null)}
onOpenChange={(open) => setOpenSelect(open ? ENTRY_SELECT : null)}
renderOptions={() =>
selectableGroups.map((group) => (
<MenuItem
key={group.name}
role="option"
aria-selected={group.name === selectedGroupName}
selected={group.name === selectedGroupName}
onClick={() => handleGroupChange(group.name)}
>
<Typography noWrap>{group.name}</Typography>
</MenuItem>
))
entries.map((entry) => {
const { group, ruleCount } = entry
const activeName = resolveChain(proxyView!, group).at(-1)
?.current?.member.ref.name
return (
<MenuItem
key={group.name}
role="option"
aria-selected={group.name === selectedGroupName}
selected={group.name === selectedGroupName}
onClick={() => handleGroupChange(group.name)}
sx={{ gap: 1 }}
>
<Box sx={{ minWidth: 0, flex: 1 }}>
<Typography noWrap>{group.name}</Typography>
{activeName && (
<Typography
noWrap
component="div"
variant="caption"
sx={{ color: 'text.secondary' }}
>
→ {activeName}
</Typography>
)}
</Box>
{ruleCount > 0 && (
<Typography
variant="caption"
sx={{ flexShrink: 0, color: 'text.secondary' }}
>
{entrySummary(entry)}
</Typography>
)}
</MenuItem>
)
})
}
/>
{levelRows.map((row) => (
<Box key={row[0].group.name} sx={{ display: 'flex', gap: 1 }}>
{row.map((level) => (
<Box key={level.group.name} sx={{ minWidth: 0, flex: 1 }}>
<PersistentProxySelect
label={t(
level === leafLevel
? 'home.components.currentProxy.labels.proxy'
: 'home.components.currentProxy.labels.group',
)}
view={proxyView!}
level={level}
sortType={sortType}
latencyTimeout={defaultLatencyTimeout ?? undefined}
open={openSelect === levelSelect(level.group.name)}
disabled={isDirectMode}
keepOpenRef={delayButtonRef}
onOpenChange={(open) =>
setOpenSelect(
open ? levelSelect(level.group.name) : null,
)
}
onChange={select}
/>
</Box>
))}
</Box>
))}
</Box>
<PersistentProxySelect
label={t('home.components.currentProxy.labels.proxy')}
groupName={selectedGroupName}
fixed={selectedGroup?.fixed}
value={
currentOption
? optionValue(currentOption.memberIndex, currentOption.member)
: ''
}
selectedName={selectedProxyName}
selectedDelay={currentDelay}
options={proxyOptions}
open={openSelect === 'proxy'}
disabled={isDirectMode}
keepOpenRef={delayButtonRef}
onOpenChange={(open) => setOpenSelect(open ? 'proxy' : null)}
onChange={handleProxyChange}
/>
</Box>
) : (
<Box sx={{ textAlign: 'center', py: 4 }}>
+1 -1
View File
@@ -79,7 +79,7 @@ export const SystemInfoCard = () => {
try {
await patchVerge({ enable_auto_launch: !verge.enable_auto_launch })
} catch (err) {
console.error('切换开机自启动状态失败:', err)
showNotice.error(err)
}
}, [verge, patchVerge])
+6 -6
View File
@@ -87,18 +87,18 @@ export const TestCard = () => {
x.uid === uid ? { ...x, ...patch } : x,
)
mutateVerge((prev) => ({ ...prev, test_list: newList }))
mutateVerge({ ...verge, test_list: newList })
},
[testList, mutateVerge],
[testList, verge, mutateVerge],
)
const onDeleteTestListItem = useCallback(
(uid: string) => {
const newList = testList.filter((x) => x.uid !== uid)
patchVerge({ test_list: newList })
mutateVerge((prev) => ({ ...prev, test_list: newList }))
mutateVerge({ ...verge, test_list: newList })
},
[testList, patchVerge, mutateVerge],
[testList, verge, patchVerge, mutateVerge],
)
const onDragEnd = useCallback(
@@ -129,7 +129,7 @@ export const TestCard = () => {
newList.splice(newIndex, 0, removed)
// 优化:先本地更新,再异步 patch,避免UI卡死
mutateVerge((prev) => ({ ...prev, test_list: newList }))
mutateVerge({ ...verge, test_list: newList })
const patchFn = () => {
try {
patchVerge({ test_list: newList })
@@ -141,7 +141,7 @@ export const TestCard = () => {
setTimeout(patchFn, 0)
}
},
[testList, mutateVerge, patchVerge],
[testList, verge, mutateVerge, patchVerge],
)
// 仅在verge首次加载时初始化测试列表
+11 -23
View File
@@ -176,10 +176,7 @@ export const GroupsEditorViewer = (props: Props) => {
},
})
const [groupList, setGroupList] = useState<IProxyGroupConfig[]>([])
const [originPolicy, setOriginPolicy] = useState<{
proxyNames: string[]
groupNames: string[]
}>({ proxyNames: [], groupNames: [] })
const [proxyPolicyList, setProxyPolicyList] = useState<string[]>([])
const [proxyProviderList, setProxyProviderList] = useState<string[]>([])
const [prependSeq, setPrependSeq] = useState<IProxyGroupConfig[]>([])
const [appendSeq, setAppendSeq] = useState<IProxyGroupConfig[]>([])
@@ -356,9 +353,6 @@ export const GroupsEditorViewer = (props: Props) => {
}
}, [prependSeq, appendSeq, deleteSeq])
// Origin policy names come from profile files that this dialog never
// rewrites while open, so they are read once per open; the live seq states
// are folded in by the derived proxyPolicyList below.
const fetchProxyPolicy = useCallback(async () => {
const data = await readProfileFile(profileUid)
const proxiesData = await readProfileFile(proxiesUid)
@@ -394,13 +388,17 @@ export const GroupsEditorViewer = (props: Props) => {
(name): name is string => typeof name === 'string' && name.length > 0,
)
setOriginPolicy({
const computedPolicyList = builtinProxyPolicies.concat(
prependSeq.map((group: IProxyGroupConfig) => group.name),
(originGroupsObj?.['proxy-groups'] || [])
.map((group: IProxyGroupConfig) => group.name)
.filter((name) => !deleteSeq.includes(name)),
appendSeq.map((group: IProxyGroupConfig) => group.name),
proxyNames,
groupNames: (originGroupsObj?.['proxy-groups'] || []).map(
(group) => group.name,
),
})
}, [profileUid, proxiesUid])
)
setProxyPolicyList(Array.from(new Set(computedPolicyList)))
}, [appendSeq, deleteSeq, prependSeq, profileUid, proxiesUid])
const fetchProfile = useCallback(async () => {
const data = await readProfileFile(profileUid)
const mergeData = await readProfileFile(mergeUid)
@@ -444,16 +442,6 @@ export const GroupsEditorViewer = (props: Props) => {
fetchProxyPolicy()
}, [fetchProxyPolicy, open])
const proxyPolicyList = useMemo(() => {
const computedPolicyList = builtinProxyPolicies.concat(
prependSeq.map((group) => group.name),
originPolicy.groupNames.filter((name) => !deleteSeq.includes(name)),
appendSeq.map((group) => group.name),
originPolicy.proxyNames,
)
return Array.from(new Set(computedPolicyList))
}, [appendSeq, deleteSeq, originPolicy, prependSeq])
useEffect(() => {
if (!open) return
fetchContent()
+186 -194
View File
@@ -61,31 +61,6 @@ const round = keyframes`
to { transform: rotate(360deg); }
`
type ContextMenuItem = {
label: string
handler: () => void
disabled: boolean
}
const menuLabels: Record<string, TranslationKey> = {
home: 'profiles.components.menu.home',
select: 'profiles.components.menu.select',
shareQrCode: 'profiles.components.menu.shareQrCode',
editInfo: 'profiles.components.menu.editInfo',
editFile: 'profiles.components.menu.editFile',
editRules: 'profiles.components.menu.editRules',
editProxies: 'profiles.components.menu.editProxies',
editGroups: 'profiles.components.menu.editGroups',
extendConfig: 'profiles.components.menu.extendConfig',
extendScript: 'profiles.components.menu.extendScript',
openFile: 'profiles.components.menu.openFile',
update: 'profiles.components.menu.update',
updateViaProxy: 'profiles.components.menu.updateViaProxy',
delete: 'shared.actions.delete',
} as const
const EMPTY_CONTEXT_MENU: ContextMenuItem[] = []
export interface ProfileItemProps {
id: string
index: number
@@ -93,13 +68,13 @@ export interface ProfileItemProps {
activating: boolean
itemData: IProfileItem
mutateProfiles: () => Promise<void>
onSelect: (uid: string, force: boolean) => void
onEdit: (item: IProfileItem) => void
onSave?: (uid: string, prev?: string, curr?: string) => void
onDelete: (uid: string) => void
onSelect: (force: boolean) => void
onEdit: () => void
onSave?: (prev?: string, curr?: string) => void
onDelete: () => void
batchMode?: boolean
isSelected?: boolean
onSelectionChange?: (uid: string) => void
onSelectionChange?: () => void
timerUpdateRevision: number
completedUpdateRevision: number
}
@@ -347,7 +322,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const onEditInfo = () => {
setAnchorEl(null)
onEdit(itemData)
onEdit()
}
const onShareQrCode = () => {
@@ -387,7 +362,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const onForceSelect = () => {
setAnchorEl(null)
onSelect(id, true)
onSelect(true)
}
const onOpenFile = useLockFn(async () => {
@@ -437,158 +412,175 @@ const ProfileItemBase = (props: ProfileItemProps) => {
}
})
// The context menu is closed on almost every render; building its items
// only while open keeps the idle path allocation-free.
const menuItems: ContextMenuItem[] =
anchorEl === null
? EMPTY_CONTEXT_MENU
: hasUrl
? [
...(hasHome
? [
{
label: menuLabels.home,
handler: onOpenHome,
disabled: false,
} satisfies ContextMenuItem,
]
: []),
{
label: menuLabels.select,
handler: onForceSelect,
disabled: false,
},
{
label: menuLabels.shareQrCode,
handler: onShareQrCode,
disabled: false,
},
{
label: menuLabels.editInfo,
handler: onEditInfo,
disabled: false,
},
{
label: menuLabels.editFile,
handler: onEditFile,
disabled: false,
},
{
label: menuLabels.editRules,
handler: onEditRules,
disabled: !option?.rules,
},
{
label: menuLabels.editProxies,
handler: onEditProxies,
disabled: !option?.proxies,
},
{
label: menuLabels.editGroups,
handler: onEditGroups,
disabled: !option?.groups,
},
{
label: menuLabels.extendConfig,
handler: onEditMerge,
disabled: !option?.merge,
},
{
label: menuLabels.extendScript,
handler: onEditScript,
disabled: !option?.script,
},
{
label: menuLabels.openFile,
handler: onOpenFile,
disabled: false,
},
{
label: menuLabels.update,
handler: () => onUpdate(0),
disabled: false,
},
{
label: menuLabels.updateViaProxy,
handler: () => onUpdate(2),
disabled: false,
},
{
label: menuLabels.delete,
handler: () => {
setAnchorEl(null)
if (batchMode) {
if (onSelectionChange) {
onSelectionChange(id)
}
} else {
setConfirmOpen(true)
}
},
disabled: false,
},
]
: [
{
label: menuLabels.select,
handler: onForceSelect,
disabled: false,
},
{
label: menuLabels.editInfo,
handler: onEditInfo,
disabled: false,
},
{
label: menuLabels.editFile,
handler: onEditFile,
disabled: false,
},
{
label: menuLabels.editRules,
handler: onEditRules,
disabled: !option?.rules,
},
{
label: menuLabels.editProxies,
handler: onEditProxies,
disabled: !option?.proxies,
},
{
label: menuLabels.editGroups,
handler: onEditGroups,
disabled: !option?.groups,
},
{
label: menuLabels.extendConfig,
handler: onEditMerge,
disabled: !option?.merge,
},
{
label: menuLabels.extendScript,
handler: onEditScript,
disabled: !option?.script,
},
{
label: menuLabels.openFile,
handler: onOpenFile,
disabled: false,
},
{
label: menuLabels.delete,
handler: () => {
setAnchorEl(null)
if (batchMode) {
if (onSelectionChange) {
onSelectionChange(id)
}
} else {
setConfirmOpen(true)
}
},
disabled: false,
},
]
type ContextMenuItem = {
label: string
handler: () => void
disabled: boolean
}
const menuLabels: Record<string, TranslationKey> = {
home: 'profiles.components.menu.home',
select: 'profiles.components.menu.select',
shareQrCode: 'profiles.components.menu.shareQrCode',
editInfo: 'profiles.components.menu.editInfo',
editFile: 'profiles.components.menu.editFile',
editRules: 'profiles.components.menu.editRules',
editProxies: 'profiles.components.menu.editProxies',
editGroups: 'profiles.components.menu.editGroups',
extendConfig: 'profiles.components.menu.extendConfig',
extendScript: 'profiles.components.menu.extendScript',
openFile: 'profiles.components.menu.openFile',
update: 'profiles.components.menu.update',
updateViaProxy: 'profiles.components.menu.updateViaProxy',
delete: 'shared.actions.delete',
} as const
const urlModeMenu: ContextMenuItem[] = [
...(hasHome
? [
{
label: menuLabels.home,
handler: onOpenHome,
disabled: false,
} satisfies ContextMenuItem,
]
: []),
{
label: menuLabels.select,
handler: onForceSelect,
disabled: false,
},
{
label: menuLabels.shareQrCode,
handler: onShareQrCode,
disabled: false,
},
{
label: menuLabels.editInfo,
handler: onEditInfo,
disabled: false,
},
{
label: menuLabels.editFile,
handler: onEditFile,
disabled: false,
},
{
label: menuLabels.editRules,
handler: onEditRules,
disabled: !option?.rules,
},
{
label: menuLabels.editProxies,
handler: onEditProxies,
disabled: !option?.proxies,
},
{
label: menuLabels.editGroups,
handler: onEditGroups,
disabled: !option?.groups,
},
{
label: menuLabels.extendConfig,
handler: onEditMerge,
disabled: !option?.merge,
},
{
label: menuLabels.extendScript,
handler: onEditScript,
disabled: !option?.script,
},
{
label: menuLabels.openFile,
handler: onOpenFile,
disabled: false,
},
{
label: menuLabels.update,
handler: () => onUpdate(0),
disabled: false,
},
{
label: menuLabels.updateViaProxy,
handler: () => onUpdate(2),
disabled: false,
},
{
label: menuLabels.delete,
handler: () => {
setAnchorEl(null)
if (batchMode) {
if (onSelectionChange) {
onSelectionChange()
}
} else {
setConfirmOpen(true)
}
},
disabled: false,
},
]
const fileModeMenu: ContextMenuItem[] = [
{
label: menuLabels.select,
handler: onForceSelect,
disabled: false,
},
{
label: menuLabels.editInfo,
handler: onEditInfo,
disabled: false,
},
{
label: menuLabels.editFile,
handler: onEditFile,
disabled: false,
},
{
label: menuLabels.editRules,
handler: onEditRules,
disabled: !option?.rules,
},
{
label: menuLabels.editProxies,
handler: onEditProxies,
disabled: !option?.proxies,
},
{
label: menuLabels.editGroups,
handler: onEditGroups,
disabled: !option?.groups,
},
{
label: menuLabels.extendConfig,
handler: onEditMerge,
disabled: !option?.merge,
},
{
label: menuLabels.extendScript,
handler: onEditScript,
disabled: !option?.script,
},
{
label: menuLabels.openFile,
handler: onOpenFile,
disabled: false,
},
{
label: menuLabels.delete,
handler: () => {
setAnchorEl(null)
if (batchMode) {
if (onSelectionChange) {
onSelectionChange()
}
} else {
setConfirmOpen(true)
}
},
disabled: false,
},
]
const boxStyle = {
height: 26,
@@ -607,7 +599,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
await profileDocument.reload()
return
}
onSave?.(id, profileDocument.savedValue, currentValue)
onSave?.(profileDocument.savedValue, currentValue)
profileDocument.markSaved(currentValue)
})
@@ -622,7 +614,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
await mergeDocument.reload()
return
}
onSave?.(id, mergeDocument.savedValue, currentValue)
onSave?.(mergeDocument.savedValue, currentValue)
mergeDocument.markSaved(currentValue)
})
@@ -640,7 +632,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
await scriptDocument.reload()
return
}
onSave?.(id, scriptDocument.savedValue, currentValue)
onSave?.(scriptDocument.savedValue, currentValue)
scriptDocument.markSaved(currentValue)
})
@@ -654,7 +646,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
e.stopPropagation()
return
}
onSelect(id, false)
onSelect(false)
}}
onContextMenu={(event) => {
const { clientX, clientY } = event
@@ -695,7 +687,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
onClick={(e) => {
e.stopPropagation()
if (onSelectionChange) {
onSelectionChange(id)
onSelectionChange()
}
}}
>
@@ -861,7 +853,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
e.preventDefault()
}}
>
{menuItems.map((item) => (
{(hasUrl ? urlModeMenu : fileModeMenu).map((item) => (
<MenuItem
key={item.label}
onClick={item.handler}
@@ -905,7 +897,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
profileUid={uid!}
property={option?.rules ?? ''}
open={true}
onSave={(prev, curr) => onSave?.(id, prev, curr)}
onSave={onSave}
onClose={() => setRulesOpen(false)}
/>
)}
@@ -914,7 +906,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
profileUid={uid!}
property={option?.proxies ?? ''}
open={true}
onSave={(prev, curr) => onSave?.(id, prev, curr)}
onSave={onSave}
onClose={() => setProxiesOpen(false)}
/>
)}
@@ -925,7 +917,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
profileUid={uid!}
property={option?.groups ?? ''}
open={true}
onSave={(prev, curr) => onSave?.(id, prev, curr)}
onSave={onSave}
onClose={() => {
setGroupsOpen(false)
}}
@@ -971,7 +963,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
onCancel={() => setConfirmOpen(false)}
onClose={() => setConfirmOpen(false)}
onOk={() => {
onDelete(id)
onDelete()
setConfirmOpen(false)
}}
>
@@ -180,7 +180,7 @@ export const ProxiesEditorViewer = (props: Props) => {
// 优化:异步分片解析,避免主线程阻塞,解析完成后批量setState
const handleParseAsync = (cb: (proxies: IProxyConfig[]) => void) => {
const proxies: IProxyConfig[] = []
const names = new Set<string>()
const names: string[] = []
let uris: string
try {
uris = atob(proxyUri)
@@ -198,9 +198,9 @@ export const ProxiesEditorViewer = (props: Props) => {
const uri = lines[idx]
try {
const proxy = parseUri(uri.trim())
if (!names.has(proxy.name)) {
if (!names.includes(proxy.name)) {
proxies.push(proxy)
names.add(proxy.name)
names.push(proxy.name)
}
} catch (err) {
console.warn(
+6 -32
View File
@@ -3,7 +3,6 @@ import * as yaml from 'js-yaml'
import {
getRecord,
rebindNode,
sameSource,
type ProxyNodeView,
type ProxyViewV1,
} from '@/types/proxy-view'
@@ -21,47 +20,22 @@ export const rebindProxyChainItems = (
items: readonly ProxyChainItem[],
candidates: readonly ProxyNodeView[],
proxyView: ProxyViewV1,
): ProxyChainItem[] => {
// The proxy view refreshes on a fixed cadence; reusing item and array
// identities while the rebound values are equal keeps persistence effects
// and memoized chain rows from reprocessing identical content.
let reboundItems: ProxyChainItem[] | undefined
items.forEach((item, index) => {
): ProxyChainItem[] =>
items.map((item) => {
const rebound = rebindNode(candidates, {
name: item.name,
source: item.source,
})
const record =
rebound === undefined ? undefined : getRecord(proxyView, rebound.recordId)
const source = rebound?.source ?? item.source
const type = rebound?.type ?? item.type
const delay = record?.history.at(-1)?.delay
const sourceReused =
item.source === source ||
(item.source !== undefined &&
source !== undefined &&
sameSource(item.source, source))
if (
item.recordId === rebound?.recordId &&
sourceReused &&
item.type === type &&
item.delay === delay
) {
return
}
reboundItems ??= [...items]
reboundItems[index] = {
return {
...item,
recordId: rebound?.recordId,
source,
type,
delay,
source: rebound?.source ?? item.source,
type: rebound?.type ?? item.type,
delay: record?.history.at(-1)?.delay,
}
})
return reboundItems ?? (items as ProxyChainItem[])
}
interface ParsedChainConfig {
proxies?: Array<{
+17 -19
View File
@@ -31,9 +31,9 @@ interface Props {
url?: string
groupName: string
headState: HeadState
onLocation: (groupName: string) => void
onCheckDelay: (groupName: string) => void
onHeadState: (groupName: string, val: Partial<HeadState>) => void
onLocation: () => void
onCheckDelay: () => void
onHeadState: (val: Partial<HeadState>) => void
}
export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
@@ -76,7 +76,7 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
// 因此对写入 headState 的动作做防抖,避免每输入一个字符就过滤一次。
const { run: applyFilter, flush: flushFilter } = useDebounceFn(
(state: SearchState) => {
onHeadState(groupName, {
onHeadState({
filterText: state.text,
filterMatchCase: state.matchCase,
filterMatchWholeWord: state.matchWholeWord,
@@ -125,7 +125,7 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.preventDefault()
e.stopPropagation()
}}
onChange={(e) => onHeadState(groupName, { testUrl: e.target.value })}
onChange={(e) => onHeadState({ testUrl: e.target.value })}
sx={{ flex: '1 1 auto', input: { py: 0.65, px: 1 } }}
/>
)}
@@ -155,8 +155,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation()
if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState(groupName, { open: true }))
onLocation(groupName)
flushSync(() => onHeadState({ open: true }))
onLocation()
}}
>
<MyLocationRounded fontSize="inherit" />
@@ -171,16 +171,16 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation()
if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState(groupName, { open: true }))
flushSync(() => onHeadState({ open: true }))
// Remind the user that it is custom test url
if (testUrl?.trim() && textState !== 'filter') {
onHeadState(groupName, { textState: 'url' })
onHeadState({ textState: 'url' })
}
if (testUrl?.trim() && !isValidUrl(testUrl)) {
showNotice.warning('proxies.feedback.warnings.invalidTestUrl')
return
}
onCheckDelay(groupName)
onCheckDelay()
}}
>
<NetworkCheckRounded fontSize="inherit" />
@@ -201,8 +201,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation()
if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState(groupName, { open: true }))
onHeadState(groupName, {
flushSync(() => onHeadState({ open: true }))
onHeadState({
sortType: ((sortType + 1) % 3) as ProxySortType,
})
}}
@@ -219,7 +219,7 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
onHeadState(groupName, {
onHeadState({
textState: textState === 'url' ? null : 'url',
})
setTimeout(() => inputRef.current?.focus())
@@ -245,8 +245,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation()
if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState(groupName, { open: true }))
onHeadState(groupName, { showType: !showType })
flushSync(() => onHeadState({ open: true }))
onHeadState({ showType: !showType })
}}
>
{showType ? (
@@ -265,10 +265,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation()
if (!headState.open && textState !== 'filter')
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState(groupName, { open: true }))
onHeadState(groupName, {
textState: textState === 'filter' ? null : 'filter',
})
flushSync(() => onHeadState({ open: true }))
onHeadState({ textState: textState === 'filter' ? null : 'filter' })
setTimeout(() => inputRef.current?.focus())
}}
>
+2 -2
View File
@@ -93,7 +93,7 @@ interface ProxyGroupsChainProps {
// Shared callbacks
onCheckAll: (groupName: string) => void
onHeadState: (groupName: string, patch: Partial<HeadState>) => void
onLocation: (groupName: string) => void
onLocation: (group: any) => void
onGroupSelect: (groupName: string) => void
onScrollToTop: () => void
}
@@ -245,7 +245,7 @@ function ProxyVirtualList({
activeStickyIndex: number | null
isChainMode?: boolean
measureElement: (node: Element | null) => void
onLocation: (groupName: string) => void
onLocation: (group: any) => void
onCheckAll: (groupName: string) => void
onHeadState: (groupName: string, patch: Partial<HeadState>) => void
onChangeProxy: (group: ProxyGroupView, member: ResolvedProxyMember) => void
+26 -33
View File
@@ -324,20 +324,16 @@ function ChainProxyGroups(props: {
scrollTopRef.current = 0
}, [])
const handleLocation = useStableCallback((groupName: string) => {
// Flat (type 1) headers such as GLOBAL carry the same live group.
const headerIndex = renderList.findIndex(
(e) => (e.type === 0 || e.type === 1) && e.group?.name === groupName,
)
const now = renderList[headerIndex]?.group?.now
if (!now) return
const handleLocation = useStableCallback((group: ProxyGroupView) => {
if (!group) return
const { name, now } = group
const index = renderList.findIndex(
(e) =>
e.group?.name === groupName &&
((e.type === 2 && e.member?.member.ref.name === now) ||
(e.type === 4 &&
e.memberCol?.some(({ member }) => member.ref.name === now))),
(item) =>
item.group?.name === name &&
((item.type === 2 && item.member?.member.ref.name === now) ||
(item.type === 4 &&
item.memberCol?.some(({ member }) => member.ref.name === now))),
)
if (index >= 0) {
@@ -500,17 +496,13 @@ function NormalProxyGroups(props: { mode: string }) {
[globalGroupName, select, setHeadState],
)
const handleLocation = useStableCallback((groupName: string) => {
// Flat (type 1) headers such as GLOBAL carry the same live group.
const headerIndex = renderList.findIndex(
(e) => (e.type === 0 || e.type === 1) && e.group?.name === groupName,
)
const now = renderList[headerIndex]?.group?.now
if (!now) return
const handleLocation = useStableCallback((group: ProxyGroupView) => {
if (!group) return
const { name, now } = group
const index = renderList.findIndex(
(e) =>
e.group?.name === groupName &&
e.group?.name === name &&
((e.type === 2 && e.member?.member.ref.name === now) ||
(e.type === 4 &&
e.memberCol?.some(({ member }) => member.ref.name === now))),
@@ -524,20 +516,21 @@ function NormalProxyGroups(props: { mode: string }) {
}
})
// Stable identity: this feeds the sticky-header render callback; a
// [renderList] dep would re-create it on every list rebuild.
const handleGroupLocationByName = useStableCallback((groupName: string) => {
const index = renderList.findIndex(
(item) => item.type === 0 && item.group?.name === groupName,
)
const handleGroupLocationByName = useCallback(
(groupName: string) => {
const index = renderList.findIndex(
(item) => item.type === 0 && item.group?.name === groupName,
)
if (index >= 0) {
stickyListRef.current?.scrollToIndex(index, {
align: 'start',
behavior: 'smooth',
})
}
})
if (index >= 0) {
stickyListRef.current?.scrollToIndex(index, {
align: 'start',
behavior: 'smooth',
})
}
},
[renderList],
)
const proxyGroupNames = useMemo(() => {
const names = renderList
+12 -18
View File
@@ -30,9 +30,9 @@ interface Props {
url?: string
groupName: string
headState: HeadState
onLocation: (groupName: string) => void
onCheckDelay: (groupName: string) => void
onHeadState: (groupName: string, val: Partial<HeadState>) => void
onLocation: () => void
onCheckDelay: () => void
onHeadState: (val: Partial<HeadState>) => void
}
const defaultSx: SxProps = {}
@@ -81,7 +81,7 @@ export const ProxyHead = ({
size="small"
color="inherit"
title={t('proxies.page.tooltips.locate')}
onClick={() => onLocation(groupName)}
onClick={onLocation}
>
<MyLocationRounded />
</IconButton>
@@ -95,13 +95,13 @@ export const ProxyHead = ({
// Remind the user that it is custom test url
if (testUrl?.trim() && textState !== 'filter') {
debugLog(`[ProxyHead] 使用自定义测试URL: ${testUrl}`)
onHeadState(groupName, { textState: 'url' })
onHeadState({ textState: 'url' })
}
if (testUrl?.trim() && !isValidUrl(testUrl)) {
showNotice.warning('proxies.feedback.warnings.invalidTestUrl')
return
}
onCheckDelay(groupName)
onCheckDelay()
}}
>
<NetworkCheckRounded />
@@ -118,9 +118,7 @@ export const ProxyHead = ({
][sortType]
}
onClick={() =>
onHeadState(groupName, {
sortType: ((sortType + 1) % 3) as ProxySortType,
})
onHeadState({ sortType: ((sortType + 1) % 3) as ProxySortType })
}
>
{sortType !== 1 && sortType !== 2 && <SortRounded />}
@@ -133,9 +131,7 @@ export const ProxyHead = ({
color="inherit"
title={t('proxies.page.tooltips.delayCheckUrl')}
onClick={() =>
onHeadState(groupName, {
textState: textState === 'url' ? null : 'url',
})
onHeadState({ textState: textState === 'url' ? null : 'url' })
}
>
{textState === 'url' ? (
@@ -153,7 +149,7 @@ export const ProxyHead = ({
? t('proxies.page.tooltips.showBasic')
: t('proxies.page.tooltips.showDetail')
}
onClick={() => onHeadState(groupName, { showType: !showType })}
onClick={() => onHeadState({ showType: !showType })}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
@@ -163,9 +159,7 @@ export const ProxyHead = ({
color="inherit"
title={t('proxies.page.tooltips.filter')}
onClick={() =>
onHeadState(groupName, {
textState: textState === 'filter' ? null : 'filter',
})
onHeadState({ textState: textState === 'filter' ? null : 'filter' })
}
>
{textState === 'filter' ? <SearchOffRounded /> : <SearchRounded />}
@@ -182,7 +176,7 @@ export const ProxyHead = ({
useRegularExpression: filterUseRegularExpression,
}}
onSearch={(_, state) =>
onHeadState(groupName, {
onHeadState({
filterText: state.text,
filterMatchCase: state.matchCase,
filterMatchWholeWord: state.matchWholeWord,
@@ -203,7 +197,7 @@ export const ProxyHead = ({
size="small"
variant="outlined"
placeholder={t('proxies.page.placeholders.delayCheckUrl')}
onChange={(e) => onHeadState(groupName, { testUrl: e.target.value })}
onChange={(e) => onHeadState({ testUrl: e.target.value })}
sx={{ ml: 0.5, flex: '1 1 auto', input: { py: 0.65, px: 1 } }}
/>
)}
+7 -7
View File
@@ -33,7 +33,7 @@ interface RenderProps {
item: IRenderItem
stickyed?: boolean
isChainMode?: boolean
onLocation: (groupName: string) => void
onLocation: (group: IRenderItem['group']) => void
onCheckAll: (groupName: string) => void
onHeadState: (groupName: string, patch: Partial<HeadState>) => void
onChangeProxy: (
@@ -179,9 +179,9 @@ const ProxyGroupHeader = (props: RenderProps) => {
url={group.testUrl!}
groupName={group.name}
headState={headState!}
onLocation={onLocation}
onCheckDelay={onCheckAll}
onHeadState={onHeadState}
onLocation={() => onLocation(group)}
onCheckDelay={() => onCheckAll(group.name)}
onHeadState={(p) => onHeadState(group.name, p)}
/>
{!toolsOnLeft && proxyCount}
</ProxyGroupHeaderBlock>
@@ -270,9 +270,9 @@ export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
url={group.testUrl!}
groupName={group.name}
headState={headState!}
onLocation={onLocation}
onCheckDelay={onCheckAll}
onHeadState={onHeadState}
onLocation={() => onLocation(group)}
onCheckDelay={() => onCheckAll(group.name)}
onHeadState={(p) => onHeadState(group.name, p)}
/>
)
}
+9 -13
View File
@@ -175,19 +175,15 @@ export const useRenderList = (
chainOccurrencesRef.current = chainOccurrences
const chainDelayGroup =
mode === 'rule' && selectedGroup ? selectedGroup : CHAIN_DELAY_GROUP
const chainDelayKey = useMemo(
() =>
chainOccurrences
.map(({ member }) => {
if (member.kind !== 'node') return `${member.kind}:${member.ref.name}`
const source = member.node.source
return source.kind === 'provider'
? `provider:${source.providerName}:${source.proxyName}`
: `core:${source.proxyName}`
})
.join('\u0000'),
[chainOccurrences],
)
const chainDelayKey = chainOccurrences
.map(({ member }) => {
if (member.kind !== 'node') return `${member.kind}:${member.ref.name}`
const source = member.node.source
return source.kind === 'provider'
? `provider:${source.providerName}:${source.proxyName}`
: `core:${source.proxyName}`
})
.join('\u0000')
useEffect(() => {
if (!isChainMode || !chainDelayKey) return
+23 -35
View File
@@ -51,25 +51,6 @@ const Item = styled(ListItem)(() => ({
},
}))
// Static editor settings; a per-render object would re-trigger Monaco's
// updateOptions and listener resubscription on every keystroke. The minimap
// depends on the live window width and is applied at editor mount instead.
const MONACO_OPTIONS = {
tabSize: 2,
mouseWheelZoom: true,
quickSuggestions: {
strings: true,
comments: true,
other: true,
},
padding: {
top: 33,
},
fontFamily: MONACO_FONT_FAMILY,
fontLigatures: false,
smoothScrolling: true,
} as const
type NameserverPolicy = Record<string, any>
function parseNameserverPolicy(str: string): NameserverPolicy {
@@ -539,21 +520,9 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
}
})
const handleYamlChange = useCallback((value?: string) => {
const handleYamlChange = (value?: string) => {
setYamlContent(value || '')
}, [])
const handleEditorMount = useCallback(
(editorInstance: MonacoEditorInstance) => {
editorRef.current = editorInstance
editorInstance.updateOptions({
minimap: {
enabled: document.documentElement.clientWidth >= 1500,
},
})
},
[],
)
}
const handleChange = (field: string) => (event: any) => {
const value =
@@ -1083,8 +1052,27 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
value={yamlContent}
theme={themeMode === 'light' ? 'light' : 'vs-dark'}
className="flex-grow"
onMount={handleEditorMount}
options={MONACO_OPTIONS}
onMount={(editorInstance) => {
editorRef.current = editorInstance
}}
options={{
tabSize: 2,
minimap: {
enabled: document.documentElement.clientWidth >= 1500,
},
mouseWheelZoom: true,
quickSuggestions: {
strings: true,
comments: true,
other: true,
},
padding: {
top: 33,
},
fontFamily: MONACO_FONT_FAMILY,
fontLigatures: false,
smoothScrolling: true,
}}
onChange={handleYamlChange}
/>
)}
@@ -109,7 +109,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
showNotice.error(err)
}
const onChangeData = (patch: Partial<IVergeConfig>) => {
mutateVerge((prev) => ({ ...prev, ...patch }))
mutateVerge({ ...verge, ...patch })
}
return (
@@ -326,7 +326,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
Promise.resolve().then(async () => {
try {
if (Object.keys(patch).length > 0) {
mutateVerge((prev) => ({ ...prev, ...patch }))
mutateVerge({ ...verge, ...patch })
}
if (Object.keys(patch).length > 0) {
await patchVerge(patch)
+83 -82
View File
@@ -114,84 +114,6 @@ const getAlertTypeFromClassName = (
return match?.[1] as GitHubAlertType | null
}
const openUrlWithNotice = (url: string) => {
void openExternalUrl(url).catch(showNotice.error)
}
// Renderer map is static; a per-render identity would remount every link and
// blockquote subtree while download progress re-renders the dialog.
const MARKDOWN_COMPONENTS: ReactMarkdownOptions['components'] = {
a: ({ href, children, ...props }) => {
const isFragment = href?.startsWith('#') ?? false
const renderedHref = isFragment
? `#${UPDATE_MARKDOWN_ID_PREFIX}${href?.slice(1)}`
: href
? '#'
: undefined
return (
<a
{...props}
href={renderedHref}
target={undefined}
rel={undefined}
onClick={(event) => {
if (isFragment) return
event.preventDefault()
if (!href) return
openUrlWithNotice(href)
}}
onAuxClick={(event) => {
if (isFragment) return
event.preventDefault()
if (event.button === 1 && href) {
openUrlWithNotice(href)
}
}}
>
{children}
</a>
)
},
blockquote: ({ className, children }) => {
const alertType = getAlertTypeFromClassName(className)
if (!alertType) {
return <blockquote className={className}>{children}</blockquote>
}
return (
<Box
component="blockquote"
className={className}
sx={(theme) => {
const color = GITHUB_ALERTS[alertType].color
return {
m: '12px 0 18px',
px: 2,
py: 1,
borderLeft: `4px solid ${color}`,
borderRadius: 1,
bgcolor: alpha(color, theme.palette.mode === 'dark' ? 0.16 : 0.08),
'& p': {
my: 0.75,
},
'& .markdown-alert-title': {
display: 'flex',
alignItems: 'center',
gap: 0.75,
fontWeight: 700,
lineHeight: 1.4,
},
}
}}
>
{children}
</Box>
)
},
}
const findFirstTextNode = (node: MarkdownNode): MarkdownNode | null => {
if (node.type === 'text') return node
for (const child of node.children ?? []) {
@@ -263,6 +185,10 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
})
const { downloaded, total } = download
const openUrlWithNotice = (url: string) => {
void openExternalUrl(url).catch(showNotice.error)
}
const progress = useMemo(() => {
if (total <= 0) return 0
return Math.min((downloaded / total) * 100, 100)
@@ -286,8 +212,8 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
) as Record<GitHubAlertType, string>,
[t],
)
const remarkPlugins = useMemo(
() => [() => remarkGitHubAlerts(githubAlertLabels)],
const remarkGitHubAlertsPlugin = useMemo(
() => () => remarkGitHubAlerts(githubAlertLabels),
[githubAlertLabels],
)
@@ -549,8 +475,83 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
{open && (
<Suspense fallback={<LinearProgress />}>
<LazyReactMarkdown
remarkPlugins={remarkPlugins}
components={MARKDOWN_COMPONENTS}
remarkPlugins={[remarkGitHubAlertsPlugin]}
components={{
a: ({ href, children, ...props }) => {
const isFragment = href?.startsWith('#') ?? false
const renderedHref = isFragment
? `#${UPDATE_MARKDOWN_ID_PREFIX}${href?.slice(1)}`
: href
? '#'
: undefined
return (
<a
{...props}
href={renderedHref}
target={undefined}
rel={undefined}
onClick={(event) => {
if (isFragment) return
event.preventDefault()
if (!href) return
openUrlWithNotice(href)
}}
onAuxClick={(event) => {
if (isFragment) return
event.preventDefault()
if (event.button === 1 && href) {
openUrlWithNotice(href)
}
}}
>
{children}
</a>
)
},
blockquote: ({ className, children }) => {
const alertType = getAlertTypeFromClassName(className)
if (!alertType) {
return (
<blockquote className={className}>{children}</blockquote>
)
}
return (
<Box
component="blockquote"
className={className}
sx={(theme) => {
const color = GITHUB_ALERTS[alertType].color
return {
m: '12px 0 18px',
px: 2,
py: 1,
borderLeft: `4px solid ${color}`,
borderRadius: 1,
bgcolor: alpha(
color,
theme.palette.mode === 'dark' ? 0.16 : 0.08,
),
'& p': {
my: 0.75,
},
'& .markdown-alert-title': {
display: 'flex',
alignItems: 'center',
gap: 0.75,
fontWeight: 700,
lineHeight: 1.4,
},
}
}}
>
{children}
</Box>
)
},
}}
>
{markdownContent}
</LazyReactMarkdown>
+1 -1
View File
@@ -25,7 +25,7 @@ const SettingSystem = ({ onError }: Props) => {
value: boolean,
) => value
const onChangeData = (patch: Partial<IVergeConfig>) => {
mutateVerge((prev) => ({ ...prev, ...patch }))
mutateVerge({ ...verge, ...patch })
}
return (
@@ -72,7 +72,7 @@ const SettingVergeBasic = ({ onError }: Props) => {
const backupRef = useRef<DialogRef>(null)
const onChangeData = (patch: any) => {
mutateVerge((prev) => ({ ...prev, ...patch }))
mutateVerge({ ...verge, ...patch })
}
const onCopyClashEnv = useCallback(async () => {
+6 -15
View File
@@ -10,7 +10,7 @@ import {
TextField,
Typography,
} from '@mui/material'
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { useEffect, useRef, useState, type ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
import getSystem from '@/utils/get-system'
@@ -21,9 +21,6 @@ import {
type SearchDialog,
} from './settings-search-context'
// Constant for the runtime; module-level like the other getSystem() callers.
const OS = getSystem()
export function SettingsSearch({
children,
}: {
@@ -43,17 +40,11 @@ export function SettingsSearch({
const originalScrollRef = useRef(0)
const resultScrollRef = useRef(0)
const cancelLocateRef = useRef<() => void>(() => {})
// The catalog scan touches every entry with translations; memoizing keeps
// unrelated state (arrow-key selection) from re-running it.
const results = useMemo(
() =>
searchSettings(
query,
OS,
(key) => t(key),
(key) => t(key, { lng: 'en' }),
),
[query, t],
const results = searchSettings(
query,
getSystem(),
(key) => t(key),
(key) => t(key, { lng: 'en' }),
)
const searching = !!query.trim()
const scroller = () =>
@@ -163,7 +163,7 @@ const ProxyControlSwitches = ({
})
return false
}
mutateVerge((prev) => ({ ...prev, enable_tun_mode: value }))
mutateVerge({ ...verge, enable_tun_mode: value })
await patchVerge({ enable_tun_mode: value })
}
+1 -4
View File
@@ -12,9 +12,6 @@ const FLUSH_DELAY_MS = 50
type LogType = ILogItem['type']
const DEFAULT_LOG_TYPES: LogType[] = ['debug', 'info', 'warning', 'error']
// Shared empty fallback: a fresh [] would give `refresh` a new identity on
// every render and re-run the snapshot effect while logs stream.
const EMPTY_LOGS: ILogItem[] = []
const LOG_LEVEL_FILTERS: Record<LogLevel, LogType[]> = {
DEBUG: DEFAULT_LOG_TYPES,
INFO: ['info', 'warning', 'error'],
@@ -58,7 +55,7 @@ export const useLogData = () => {
const { response, refresh, setData } = useMihomoWsSubscription<ILogItem[]>({
subscriptionKey: enableLog ? 'getClashLog' : null,
fallbackData: EMPTY_LOGS,
fallbackData: [],
connect: () => MihomoWebSocket.connect_logs(logLevel),
setupHandlers: ({ next, scheduleReconnect, isMounted }) => {
let flushTimer: ReturnType<typeof setTimeout> | null = null
+1 -1
View File
@@ -61,7 +61,7 @@ export function useProxyDelayState(
}
const cachedUpdate = delayManager.getDelayUpdate(name, groupName)
if (cachedUpdate) {
setDelayState(cachedUpdate)
setDelayState({ ...cachedUpdate })
return
}
+19 -25
View File
@@ -3,16 +3,12 @@ import { useCallback } from 'react'
import { getVergeConfig, patchVergeConfig } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { getPreloadConfig, setPreloadConfig } from '@/services/preload'
import {
revalidateQuery,
setCacheData,
useQuery,
} from '@/services/query-client'
import { setCacheData, useQuery } from '@/services/query-client'
export const useVerge = () => {
const initialVergeConfig = getPreloadConfig()
const { data: verge } = useQuery({
const { data: verge, refetch } = useQuery({
queryKey: ['getVergeConfig'],
queryFn: async () => {
const config = await getVergeConfig()
@@ -24,25 +20,23 @@ export const useVerge = () => {
staleTime: 5000,
})
// Stable identity: many consumers list mutateVerge in their own callback
// deps, so a per-render closure here would churn their memoization too.
// The updater receives the live cache value (preload snapshot when the
// cache is still empty) instead of a render-time snapshot, so an older
// render cannot clobber a newer cache write.
const mutateVerge = useCallback(
(
updater?: (prev: IVergeConfig | undefined) => IVergeConfig | undefined,
) => {
if (updater === undefined) {
void revalidateQuery(['getVergeConfig'])
return
}
void setCacheData<IVergeConfig>(['getVergeConfig'], (current) =>
updater(current ?? getPreloadConfig() ?? undefined),
)
},
[],
)
const mutateVerge = (
updaterOrData?:
| IVergeConfig
| ((prev: IVergeConfig | undefined) => IVergeConfig | undefined)
| undefined,
) => {
if (updaterOrData === undefined) {
void refetch()
return
}
void setCacheData<IVergeConfig>(
['getVergeConfig'],
typeof updaterOrData === 'function'
? (current) => updaterOrData(current ?? verge)
: updaterOrData,
)
}
// Callers own the error toast (GuardState onCatch / page onError), so the
// funnel must not add a second one.
+3
View File
@@ -98,6 +98,9 @@
"directMode": "الوضع المباشر",
"group": "Group",
"proxy": "Proxy",
"ruleTarget": "Rule Target",
"defaultRoute": "Default",
"ruleCount": "{{count}} rules",
"noActiveNode": "No active proxy node"
},
"status": {
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "إنهاء الاتصالات القائمة عند تغيير اختيار مجموعة الوكيل أو وضع الوكيل",
"autoSwitchSelectorGroup": "في وضع القواعد، عند اختيار عقدة في مجموعة url-test أو fallback يتم أيضًا تحويل أول مجموعة select تحتوي عليها إلى تلك المجموعة",
"autoSwitchSelectorGroup": "في وضع القواعد، عند اختيار عقدة في مجموعة لا تمر بها حركة القواعد يتم أيضًا تحويل أول مجموعة select تحتوي عليها إلى تلك المجموعة",
"enableBuiltinEnhanced": "معالجة توافق ملف التكوين",
"autoDelayDetection": "يختبر زمن استجابة العقدة الحالية على نحو دوري في الخلفية",
"defaultLatencyTest": "يُستخدم فقط لاختبار طلب HTTP العميل. لن يؤثر على ملف التكوين"
+3
View File
@@ -98,6 +98,9 @@
"directMode": "Direktmodus",
"group": "Proxy-Gruppe",
"proxy": "Knoten",
"ruleTarget": "Regelziel",
"defaultRoute": "Standard",
"ruleCount": "{{count}} Regeln",
"noActiveNode": "Kein aktiver Proxy-Knoten"
},
"status": {
+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."
+3
View File
@@ -98,6 +98,9 @@
"directMode": "Direct Mode",
"group": "Group",
"proxy": "Proxy",
"ruleTarget": "Rule Target",
"defaultRoute": "Default",
"ruleCount": "{{count}} rules",
"noActiveNode": "No active proxy node"
},
"status": {
+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"
+3
View File
@@ -98,6 +98,9 @@
"directMode": "Direct Mode",
"group": "Grupo de proxy",
"proxy": "Nodo",
"ruleTarget": "Destino de reglas",
"defaultRoute": "Predeterminado",
"ruleCount": "{{count}} reglas",
"noActiveNode": "No hay nodos de proxy activos"
},
"status": {
+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."
+3
View File
@@ -98,6 +98,9 @@
"directMode": "حالت مستقیم",
"group": "Group",
"proxy": "Proxy",
"ruleTarget": "Rule Target",
"defaultRoute": "Default",
"ruleCount": "{{count}} rules",
"noActiveNode": "No active proxy node"
},
"status": {
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "اتصالات برقرار شده را هنگام تغییر انتخاب گروه پروکسی یا حالت پروکسی خاتمه دهید",
"autoSwitchSelectorGroup": "در حالت قانون، با انتخاب یک گره در گروه url-test یا fallback، اولین گروه select شامل آن نیز به همان گروه تغییر می‌کند",
"autoSwitchSelectorGroup": "در حالت قانون، با انتخاب یک گره در گروهی که ترافیک قوانین از آن عبور نمی‌کند، اولین گروه select شامل آن نیز به همان گروه تغییر می‌کند",
"enableBuiltinEnhanced": "مدیریت سازگاری برای فایل پیکربندی",
"autoDelayDetection": "به‌صورت دوره‌ای تأخیر گره فعلی را در پس‌زمینه آزمایش می‌کند",
"defaultLatencyTest": "فقط برای تست درخواست‌های کلاینت HTTP استفاده می‌شود و بر فایل پیکربندی تأثیری نخواهد داشت"
+3
View File
@@ -98,6 +98,9 @@
"directMode": "Mode Langsung",
"group": "Group",
"proxy": "Proxy",
"ruleTarget": "Rule Target",
"defaultRoute": "Default",
"ruleCount": "{{count}} rules",
"noActiveNode": "No active proxy node"
},
"status": {
+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"
+3
View File
@@ -98,6 +98,9 @@
"directMode": "直接接続モード",
"group": "プロキシグループ",
"proxy": "ノード",
"ruleTarget": "ルールの宛先",
"defaultRoute": "デフォルト",
"ruleCount": "{{count}} 件のルール",
"noActiveNode": "アクティブなプロキシノードがありません。"
},
"status": {
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "プロキシグループで選択されたノードまたはプロキシモードが変更されたときに、既存の接続を閉じます。",
"autoSwitchSelectorGroup": "ルールモードで url-test または fallback グループのノードを選択すると、そのグループを含む最初の select グループも当該グループに切り替えます。",
"autoSwitchSelectorGroup": "ルールモードで、ルールの通信が通らないグループのノードを選択すると、そのグループを含む最初の select グループも当該グループに切り替えます。",
"enableBuiltinEnhanced": "設定ファイルの互換性処理",
"autoDelayDetection": "バックグラウンドで現在のノードのレイテンシーを定期的にテストします",
"defaultLatencyTest": "HTTPクライアントリクエストテストにのみ使用され、設定ファイルには影響しません。"
+3
View File
@@ -98,6 +98,9 @@
"directMode": "직접 모드",
"group": "그룹",
"proxy": "프록시",
"ruleTarget": "규칙 대상",
"defaultRoute": "기본",
"ruleCount": "규칙 {{count}}개",
"noActiveNode": "활성 프록시 노드 없음"
},
"status": {
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "프록시 그룹 선택 또는 프록시 모드 변경 시 기존 연결을 종료합니다",
"autoSwitchSelectorGroup": "규칙 모드에서 url-test 또는 fallback 그룹의 노드를 선택하면 해당 그룹을 포함하는 첫 번째 select 그룹도 그 그룹으로 전환합니다",
"autoSwitchSelectorGroup": "규칙 모드에서 규칙 트래픽이 지나지 않는 그룹의 노드를 선택하면 해당 그룹을 포함하는 첫 번째 select 그룹도 그 그룹으로 전환합니다",
"enableBuiltinEnhanced": "구성 파일에 대한 호환성 처리를 수행합니다",
"autoDelayDetection": "백그라운드에서 현재 노드의 지연을 주기적으로 검사합니다",
"defaultLatencyTest": "HTTP 클라이언트 요청 테스트에만 사용되며 구성 파일에는 영향을 주지 않습니다"
+3
View File
@@ -98,6 +98,9 @@
"directMode": "Modo direto",
"group": "Grupo",
"proxy": "Proxy",
"ruleTarget": "Destino das regras",
"defaultRoute": "Padrão",
"ruleCount": "{{count}} regras",
"noActiveNode": "Nenhum nó de proxy ativo"
},
"status": {
+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"
+3
View File
@@ -98,6 +98,9 @@
"directMode": "Прямой режим",
"group": "Группа",
"proxy": "Прокси",
"ruleTarget": "Цель правил",
"defaultRoute": "По умолчанию",
"ruleCount": "Правил: {{count}}",
"noActiveNode": "Нет активного прокси"
},
"status": {
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "Закрывать установленные соединения при изменении выбора группы прокси или режима прокси",
"autoSwitchSelectorGroup": "В режиме правил при выборе узла в группе url-test или fallback первая группа select, содержащая эту группу, также переключается на неё",
"autoSwitchSelectorGroup": "В режиме правил при выборе узла в группе, через которую не идёт трафик правил, первая группа select, содержащая эту группу, также переключается на неё",
"enableBuiltinEnhanced": "Обработка совместимости для файла конфигурации",
"autoDelayDetection": "Периодически проверяет задержку текущего узла в фоновом режиме",
"defaultLatencyTest": "Используется только для тестирования HTTP-запросов клиента и не влияет на файл конфигурации"
+3
View File
@@ -98,6 +98,9 @@
"directMode": "Doğrudan Mod",
"group": "Grup",
"proxy": "Vekil",
"ruleTarget": "Kural Hedefi",
"defaultRoute": "Varsayılan",
"ruleCount": "{{count}} kural",
"noActiveNode": "Aktif vekil düğümü yok"
},
"status": {
+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"
+3
View File
@@ -98,6 +98,9 @@
"directMode": "Туры режим",
"group": "Group",
"proxy": "Proxy",
"ruleTarget": "Rule Target",
"defaultRoute": "Default",
"ruleCount": "{{count}} rules",
"noActiveNode": "No active proxy node"
},
"status": {
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "Прокси төркеме яисә режимын үзгәрткәндә актив тоташуларны өзү",
"autoSwitchSelectorGroup": "Кагыйдәләр режимында url-test яки fallback төркемендә төен сайлаганда, аны эченә алган беренче select төркеме дә шул төркемгә күчә",
"autoSwitchSelectorGroup": "Кагыйдәләр режимында кагыйдәләр трафигы үтми торган төркемдә төен сайлаганда, аны эченә алган беренче select төркеме дә шул төркемгә күчә",
"enableBuiltinEnhanced": "Конфигурация файлы белән туры килә торган өстәмә оптимизация",
"autoDelayDetection": "Фон режимында хәзерге төен тоткарлыгын периодик тикшерә",
"defaultLatencyTest": "Бу фәкать клиентның HTTP сораулары тесты өчен кулланыла, конфигурация файлына йогынты ясамый"
+3
View File
@@ -98,6 +98,9 @@
"directMode": "直连模式",
"group": "代理组",
"proxy": "节点",
"ruleTarget": "规则入口",
"defaultRoute": "默认",
"ruleCount": "{{count}} 条规则",
"noActiveNode": "暂无激活的代理节点"
},
"status": {
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "当代理组选中节点或代理模式变动时,关闭已建立的连接",
"autoSwitchSelectorGroup": "规则模式下,在 url-test 或 fallback 代理组中选择节点时,将首个包含该组的 select 代理组切换到该组",
"autoSwitchSelectorGroup": "规则模式下,在规则流量未经过的代理组中选择节点时,将首个包含该组的 select 代理组切换到该组",
"enableBuiltinEnhanced": "配置文件的兼容性处理",
"autoDelayDetection": "后台定时检测当前节点延迟",
"defaultLatencyTest": "仅用于 HTTP 客户端请求测试,不会对配置文件产生影响"
+3
View File
@@ -98,6 +98,9 @@
"directMode": "直連模式",
"group": "代理組",
"proxy": "節點",
"ruleTarget": "規則入口",
"defaultRoute": "預設",
"ruleCount": "{{count}} 條規則",
"noActiveNode": "暫無作用中的代理節點"
},
"status": {
+1 -1
View File
@@ -423,7 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "當代理組選中節點或代理模式變動時,關閉已建立的連線",
"autoSwitchSelectorGroup": "規則模式下,在 url-test 或 fallback 代理組中選擇節點時,將首個包含該組的 select 代理組切換到該組",
"autoSwitchSelectorGroup": "規則模式下,在規則流量未經過的代理組中選擇節點時,將首個包含該組的 select 代理組切換到該組",
"enableBuiltinEnhanced": "配置檔案的相容性處理",
"autoDelayDetection": "在背景定時偵測目前節點延遲",
"defaultLatencyTest": "僅用於 HTTP 客戶端請求測試,不會對配置檔案產生影響"
+20 -46
View File
@@ -462,12 +462,9 @@ const ProfilePage = () => {
[runProfileSwitchQueue],
)
const onSelect = useCallback(
async (profile: string, force: boolean) => {
await activateProfile(profile, true, force)
},
[activateProfile],
)
const onSelect = async (profile: string, force: boolean) => {
await activateProfile(profile, true, force)
}
useEffect(() => {
let cancelled = false
@@ -597,7 +594,7 @@ const ProfilePage = () => {
}
}
const toggleProfileSelection = useCallback((uid: string) => {
const toggleProfileSelection = (uid: string) => {
setSelectedProfiles((prev) => {
const newSet = new Set(prev)
if (newSet.has(uid)) {
@@ -607,40 +604,7 @@ const ProfilePage = () => {
}
return newSet
})
}, [])
// Item-grid callbacks stay identity-stable so ProfileItem's memo holds
// across unrelated page state (URL input keystrokes, switch spinners).
// onEnhance/onDelete are useLockFn wrappers whose identity changes every
// render, so they are read through refs here.
const onEnhanceRef = useRef(onEnhance)
onEnhanceRef.current = onEnhance
const onDeleteRef = useRef(onDelete)
onDeleteRef.current = onDelete
const handleItemEdit = useCallback((item: IProfileItem) => {
viewerRef.current?.edit(item)
}, [])
const handleItemSave = useCallback(
async (uid: string, prev?: string, curr?: string) => {
if (prev !== curr && profiles.current === uid) {
await onEnhanceRef.current(false)
}
},
[profiles],
)
const handleItemDelete = useCallback(
(uid: string) => {
if (batchMode) {
toggleProfileSelection(uid)
} else {
onDeleteRef.current(uid)
}
},
[batchMode, toggleProfileSelection],
)
}
const selectAllProfiles = () => {
setSelectedProfiles(new Set(profileItems.map((item) => item.uid!)))
@@ -944,13 +908,23 @@ const ProfilePage = () => {
completedUpdateRevisions.get(item.uid!) ?? 0
}
mutateProfiles={mutateProfiles}
onSelect={onSelect}
onEdit={handleItemEdit}
onSave={handleItemSave}
onDelete={handleItemDelete}
onSelect={(f) => onSelect(item.uid!, f)}
onEdit={() => viewerRef.current?.edit(item)}
onSave={async (prev, curr) => {
if (prev !== curr && profiles.current === item.uid) {
await onEnhance(false)
}
}}
onDelete={() => {
if (batchMode) {
toggleProfileSelection(item.uid!)
} else {
onDelete(item.uid!)
}
}}
batchMode={batchMode}
isSelected={selectedProfiles.has(item.uid!)}
onSelectionChange={toggleProfileSelection}
onSelectionChange={() => toggleProfileSelection(item.uid!)}
/>
))}
</Box>
+47
View File
@@ -4,6 +4,7 @@ import { asyncRetry } from 'foxts/async-retry'
import { extractErrorMessage } from 'foxts/extract-error-message'
import { once } from 'foxts/once'
import i18n from 'i18next'
import { getBaseConfig } from 'tauri-plugin-mihomo-api'
import { debugLog } from '@/utils/debug'
@@ -137,6 +138,29 @@ const IP_CHECK_SERVICES: ServiceConfig[] = [
},
]
const getProxyHost = (allowLan: boolean, bindAddress: string) => {
const address = bindAddress.trim().replace(/^\[|\]$/g, '')
const normalizedAddress = address.toLowerCase()
const isIpv6 = normalizedAddress.includes(':')
const isIpv6Wildcard =
isIpv6 &&
normalizedAddress
.split(':')
.every((part) => part === '' || /^0+$/.test(part))
const isWildcard =
normalizedAddress === '*' ||
normalizedAddress === '0.0.0.0' ||
isIpv6Wildcard
if (!allowLan) return '127.0.0.1'
if (!address || isWildcard || normalizedAddress === 'localhost') {
return isIpv6Wildcard ? '[::1]' : '127.0.0.1'
}
return isIpv6 ? `[${address}]` : address
}
// 获取当前IP和地理位置信息
export const getIpInfo = async (): Promise<
IpInfo & { lastFetchTs: number }
@@ -150,6 +174,28 @@ export const getIpInfo = async (): Promise<
)
let lastError: unknown | null = null
const userAgent = await getUserAgentPromise()
const { mixedPort, allowLan, bindAddress, authentication } =
await getBaseConfig()
const proxyUrl = `http://${getProxyHost(allowLan, bindAddress)}:${mixedPort}`
const proxyAuthentication = authentication?.[0]
const authSeparator = proxyAuthentication?.indexOf(':') ?? -1
if (proxyAuthentication !== undefined && authSeparator < 0) {
throw new Error('Invalid mixed proxy authentication configuration')
}
const proxy = {
all:
proxyAuthentication === undefined
? proxyUrl
: {
url: proxyUrl,
basicAuth: {
username: proxyAuthentication.slice(0, authSeparator),
password: proxyAuthentication.slice(authSeparator + 1),
},
},
}
console.debug('User-Agent for IP detection:', userAgent)
for (const service of shuffledServices) {
@@ -168,6 +214,7 @@ export const getIpInfo = async (): Promise<
try {
const response = await fetch(service.url, {
method: 'GET',
proxy,
signal: timeoutController.signal,
connectTimeout: serviceTimeout,
headers: {
-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) {
+1 -3
View File
@@ -237,9 +237,7 @@ class DelayManager {
return undefined
}
// Entries are replaced, never mutated, so the cached object is shared
// directly; readers treat it as immutable.
return entry
return { ...entry }
}
getDelay(name: string, group: string) {
+3
View File
@@ -82,6 +82,9 @@ export const translationKeys = [
'home.components.currentProxy.labels.directMode',
'home.components.currentProxy.labels.group',
'home.components.currentProxy.labels.proxy',
'home.components.currentProxy.labels.ruleTarget',
'home.components.currentProxy.labels.defaultRoute',
'home.components.currentProxy.labels.ruleCount',
'home.components.currentProxy.labels.noActiveNode',
'home.components.currentProxy.status.testing',
'home.components.currentProxy.status.untested',
+3
View File
@@ -69,11 +69,14 @@ export interface TranslationResources {
refreshDelay: string
}
labels: {
defaultRoute: string
directMode: string
globalMode: string
group: string
noActiveNode: string
proxy: string
ruleCount: string
ruleTarget: string
}
status: {
error: string
+1 -1
View File
@@ -156,7 +156,7 @@ export const selectRuleChainMembers = (
})
}
export const sameSource = (
const sameSource = (
left: ProxyNodeView['source'],
right: ProxyNodeView['source'],
) =>
+13 -34
View File
@@ -124,10 +124,10 @@ export class TrafficDataSampler {
) {
rawStart++
}
const rawCount = this.rawBuffer.length - rawStart
const rawData = this.rawBuffer.slice(rawStart)
if (minutes <= this.config.rawDataMinutes) {
return this.rawBuffer.slice(rawStart)
return rawData
}
const compressedCutoffUpper =
@@ -140,40 +140,19 @@ export class TrafficDataSampler {
) {
compressedStart++
}
let compressedEnd = compressedStart
while (
compressedEnd < this.compressedBuffer.length &&
this.compressedBuffer[compressedEnd].timestamp <= compressedCutoffUpper
) {
compressedEnd++
}
// Single preallocated result; raw entries keep their stored identity.
const compressedCount = compressedEnd - compressedStart
const result: ITrafficDataPoint[] = new Array(compressedCount + rawCount)
for (let i = 0; i < compressedCount; i++) {
const point = this.compressedBuffer[compressedStart + i]
result[i] = {
up: point.up,
down: point.down,
timestamp: point.timestamp,
}
}
for (let i = 0; i < rawCount; i++) {
result[compressedCount + i] = this.rawBuffer[rawStart + i]
}
const compressedData = this.compressedBuffer
.slice(compressedStart)
.filter((p) => p.timestamp <= compressedCutoffUpper)
.map((p) => ({
up: p.up,
down: p.down,
timestamp: p.timestamp,
}))
// Compressed points precede raw ones except across the trim boundary;
// sort only when the two ranges actually interleave.
if (
compressedCount > 0 &&
rawCount > 0 &&
this.compressedBuffer[compressedEnd - 1].timestamp >
this.rawBuffer[rawStart].timestamp
) {
result.sort((a, b) => a.timestamp - b.timestamp)
}
return result
return [...compressedData, ...rawData].sort(
(a, b) => a.timestamp - b.timestamp,
)
}
getStats(): ISamplerStats {