Compare commits

..
Author SHA1 Message Date
renovate[bot] 257a75c5ca chore(deps): update tauri 2026-11-18 14:12:24 +00:00
58 changed files with 793 additions and 1310 deletions
+1 -1
View File
@@ -5,7 +5,7 @@
"features": {
"ghcr.io/devcontainers/features/node:2": {
"version": "26.13.1",
"pnpmVersion": "12.21.0"
"pnpmVersion": "12.18.0"
},
"ghcr.io/devcontainers/features/rust:1": {
"version": "1.100.0",
+3 -3
View File
@@ -5,10 +5,10 @@
"version": "v9.0.0",
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
},
"github/gh-aw-actions/setup@v1.3.1": {
"github/gh-aw-actions/setup@v1.3.0": {
"repo": "github/gh-aw-actions/setup",
"version": "v1.3.1",
"sha": "dfe97a19c8249d41e2adfc95f92db2b8facea58f"
"version": "v1.3.0",
"sha": "8126d6cb07dea9221848de275af8a41474d839ca"
}
},
"containers": {
+2 -2
View File
@@ -31,9 +31,9 @@ jobs:
with:
persist-credentials: false
- name: Install gh-aw extension
uses: github/gh-aw-actions/setup-cli@dfe97a19c8249d41e2adfc95f92db2b8facea58f # v1.3.1
uses: github/gh-aw-actions/setup-cli@8126d6cb07dea9221848de275af8a41474d839ca # v1.3.0
with:
version: v1.3.1
version: v1.3.0
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@stable
with:
File diff suppressed because one or more lines are too long
-4
View File
@@ -30,10 +30,6 @@ max-ai-credits: 60
max-turns: 12
max-daily-ai-credits: 5000
# Routine, low-risk tasks such as triage, labeling, and summaries.
# See https://github.github.com/gh-aw/reference/model-routing/#setting-the-level-yourself
model: router/economy
permissions:
issues: read
pull-requests: read
File diff suppressed because one or more lines are too long
-3
View File
@@ -26,9 +26,6 @@ imports:
max-ai-credits: 60
max-turns: 12
max-daily-ai-credits: 500
# Routine, low-risk tasks such as triage, labeling, and summaries.
# See https://github.github.com/gh-aw/reference/model-routing/#setting-the-level-yourself
model: router/economy
permissions:
contents: read
issues: read
File diff suppressed because one or more lines are too long
+1 -6
View File
@@ -32,13 +32,8 @@ permissions:
max-ai-credits: 60
max-turns: 12
max-daily-ai-credits: 500
# Routine, low-risk tasks such as triage, labeling, and summaries.
# See https://github.github.com/gh-aw/reference/model-routing/#setting-the-level-yourself
model: router/economy
network:
# GitHub CLI recommend using ecosystem identifiers instead of individual domain names for better maintainability,
# hence "node" is prefer than "nodejs.org"
allowed: [github, docs.rs, doc.rust-lang.org, node, www.typescriptlang.org]
allowed: [github, docs.rs, doc.rust-lang.org, nodejs.org, www.typescriptlang.org]
steps:
- name: Load trusted metadata parser
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+1 -1
View File
@@ -1,3 +1,3 @@
nodejs 26.13.1
pnpm 12.21.0
pnpm 12.18.0
rust 1.100.0
Generated
+15 -15
View File
@@ -7237,9 +7237,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 +7292,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 +7315,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 +7330,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 +7342,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 +7717,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 +7742,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 +7800,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",
+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"
-4
View File
@@ -38,7 +38,6 @@
- 修复「连接」页表格排序时表头换行、标题位置跳动
- 修复「TUN 设置」未手动保存时,界面显示的默认 MTU 1500 未生效
- 修复「链式代理」节点列表按名称排序,未保持订阅中的节点顺序
- 修复规则模式下 Muse AI 解锁检测显示错误的出口地区
**🍎 macOS**
@@ -56,7 +55,6 @@
<summary><strong> ✨ 新增功能 </strong></summary>
- 新增连接页面按网络协议(TCP/UDP)筛选连接
- 新增规则模式下在 `url-test` 或 `fallback` 代理组选节点时,自动将首个包含该组的 `select` 代理组切换到该组,可在「杂项设置」关闭
</details>
@@ -66,8 +64,6 @@
- 优化连接、规则和日志筛选:切换页面后保留过滤条件
- 优化全局模式代理列表:仅显示 `GLOBAL` 节点,选中其中的策略组时才显示该组
- 优化设置页开关和选项所在行的鼠标悬停高亮,便于对应说明与控件
- 优化首页「当前节点」卡片:代理组列表加入 `fallback` 代理组,切换到 `url-test` 或 `fallback` 代理组时同样联动 `select` 代理组
- 优化主页流量图表与日志、代理列表的实时刷新和滚动占用,降低高频更新时的 CPU 负载
**🍎 macOS**
+11 -6
View File
@@ -1,23 +1,28 @@
use reqwest::Client;
use crate::utils::classify_restricted_status;
use crate::utils::{classify_restricted_status, get_trace_location};
use super::UnlockItem;
pub(crate) const MUSE_AI_NAME: &str = "Muse AI";
const MUSE_URL: &str = "https://muse.ai";
const CLOUDFLARE_TRACE_URL: &str = "https://www.cloudflare.com/cdn-cgi/trace";
// The aymh ("Are You a Human") gateway answers plain HTTP requests with a
// generic Meta error page that always contains the Facebook logo asset.
const AYMH_ERROR_MARKERS: &[&str] = &["Sorry, something went wrong", "static.facebook.com/images/logos"];
pub(super) async fn check_muse_ai(client: &Client) -> UnlockItem {
// muse.ai is served by Vercel and does not expose a service-specific region trace endpoint.
// Querying a generic third-party domain (e.g. www.cloudflare.com/cdn-cgi/trace) would report
// that domain's proxy group rather than muse.ai's actual exit in Rule mode, so leave region as None.
// muse.ai itself is served by Vercel, so resolve the exit region through
// the generic Cloudflare trace endpoint instead of a service-specific one.
let region = get_trace_location(client, CLOUDFLARE_TRACE_URL)
.await
.map(|code| code.trim().to_ascii_uppercase())
.map(|code| UnlockItem::region_label(&code));
let Ok(response) = client.get(MUSE_URL).send().await else {
return UnlockItem::checked(MUSE_AI_NAME, "Failed (Network Connection)", None);
return UnlockItem::checked(MUSE_AI_NAME, "Failed (Network Connection)", region);
};
let status = response.status();
@@ -39,5 +44,5 @@ pub(super) async fn check_muse_ai(client: &Client) -> UnlockItem {
classify_restricted_status(status).unwrap_or("Failed")
};
UnlockItem::checked(MUSE_AI_NAME, result, None)
UnlockItem::checked(MUSE_AI_NAME, result, region)
}
+3 -3
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.5",
"@types/lodash-es": "^4.17.12",
"@types/node": "^26.0.0",
"@types/react": "19.3.0",
@@ -138,5 +138,5 @@
]
},
"type": "module",
"packageManager": "pnpm@12.21.0"
"packageManager": "pnpm@12.18.0"
}
+127 -136
View File
@@ -7,162 +7,153 @@ importers:
configDependencies: {}
packageManagerDependencies:
pnpm:
specifier: 12.21.0
version: 12.21.0
specifier: 12.18.0
version: 12.18.0
packages:
'@pnpm/exe.android-arm64@12.21.0':
resolution: {integrity: sha512-iaWidxR5B9NUBpwMznCQu1yUpKB6BjTY5BYX2lORj76VsfINdj8Z8XWSzSNrGI8qlxa28Jzdp5fiaspzOaJZlA==}
'@pnpm/exe.android-arm64@12.18.0':
resolution: {integrity: sha512-fOF6IwgvnUKEmVedGqiAsNPfN2Ry8GvaqzSQOiF3RJFbpBfPKO/6YT54s1GjToyYinRxw9preHHPe4y2N3SzhA==}
cpu: [arm64]
os: [android]
'@pnpm/exe.android-x64@12.21.0':
resolution: {integrity: sha512-35e5v3wlwjIYxDywq+R6/z8CE4gLOEgRxt18yqz1tMRLmx2mnW+CFJI2Q8+srTNjn7gykXUC0x1k195JNikC5A==}
'@pnpm/exe.android-x64@12.18.0':
resolution: {integrity: sha512-6OiolnaCsB3/GcJ9XNrenbUH3zFHRJ+5QynrMUUEyThbgnnCzWxa199hpQlOmxN4rAXuYQ0IYgWFNUZxyzg31Q==}
cpu: [x64]
os: [android]
'@pnpm/exe.darwin-arm64@12.21.0':
resolution: {integrity: sha512-F5OyMX/6zLSowpTZEQRojbCmPS1Pq+fyRaIinslsIe6Glh3qbyQ52u+Fe0eEzSaRuIbWZkXmAAXSWh6Q5Wrlgg==}
'@pnpm/exe.darwin-arm64@12.18.0':
resolution: {integrity: sha512-zkq+4YzVIX39ETYLyC3W7LY7MpHEU/J3nRhHl4i2yPld2Cf2+rEKRh3ejJ4AmaQ77HHJLCktY4Z3jq0fpcxFXg==}
cpu: [arm64]
os: [darwin]
'@pnpm/exe.darwin-x64@12.21.0':
resolution: {integrity: sha512-EzpvcsaE6hrrgYeEiAFYd2rSgFybYyxXhkAY7K3y6Hg3loVfcyJ81hHczpFzi8lW5RXtUlFECRPZ8ZAMRFQYYg==}
'@pnpm/exe.darwin-x64@12.18.0':
resolution: {integrity: sha512-qMsL9qx92unOTa6hgkfiTJv8ceZaTx0IQg7InhYDVX2ZrTECujaVEEVypnJK5m3eGUsP1KD7Y4qIgleCwfRsYw==}
cpu: [x64]
os: [darwin]
'@pnpm/exe.freebsd-x64@12.21.0':
resolution: {integrity: sha512-wNjuEnmdLks4aayPu/QZWQ5tQM9Jn+odUp/vwQM8BXRYoulkTZhtZTHoD60N6mUdLWef1hgUeUh8llNGEUsimw==}
'@pnpm/exe.freebsd-x64@12.18.0':
resolution: {integrity: sha512-/9vy/4ms52cU4MjZ5NhHd6N2d9L9W0kARf5/ff2tweAHu0VeUzs/0qp/7ZHFuddm2Wa/m0AKQoPum9AVUCqKsw==}
cpu: [x64]
os: [freebsd]
'@pnpm/exe.linux-arm64-musl@12.21.0':
resolution: {integrity: sha512-Ceit9zn4g5ZqCJtx1fV8eJE7p8aeXMrGZ+Dc01vRqZLIUNgNeI+Ur0ruyqxtsnJx6rGADyXzohumxPLHjaJ5AQ==}
'@pnpm/exe.linux-arm64-musl@12.18.0':
resolution: {integrity: sha512-Vp+TIMPPyackVCXkOdEKH/RmAn/r07EcIyrgZYQK7VrkksqZOie0GnWIx+85mPqeFEYCRtXIZAFJ9L4ceTndDg==}
cpu: [arm64]
os: [linux]
libc: [musl]
'@pnpm/exe.linux-arm64@12.21.0':
resolution: {integrity: sha512-4Oj/iF2TDCe2lcH0n4TupPR5sSdrNLclJB6xBElLMPCUOAvBhdf2rRlSaO5M4erJ6g4Fyy7YTXTpcmfFsKyxEA==}
'@pnpm/exe.linux-arm64@12.18.0':
resolution: {integrity: sha512-2dpyVBCHT+FfpuQh9i+7MXAqNWYLCvD5vYr5p6Eimxoga8USLnjbUgyj72AOrO0hjc5ri3TEFP3jiyBHjkSZpQ==}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@pnpm/exe.linux-ppc64@12.21.0':
resolution: {integrity: sha512-s2o7rdSDeUTBFsNqxptpZXlTgT6cojmMVUOvTQvFNSv6Easian02ha4tR32fwwD97Au4YzIIjMCwywCF4D82Sw==}
'@pnpm/exe.linux-ppc64@12.18.0':
resolution: {integrity: sha512-BBOOOfNJ2QwIIya3eKqOjiN4WNTszfRz7HCvw9XggcT7+ftMjNP8XJ/GfW+ltCBeUFR9d8WBVsr2m/NLjX2CZQ==}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@pnpm/exe.linux-riscv64@12.21.0':
resolution: {integrity: sha512-EYv3GzxeBTITCuM3yGHHbpRFpUvyulkXpQ6LsjKAQNL3iaba1E6h9iDmlouLb3Io4AMMsfdk0/uG6poQ41uewA==}
'@pnpm/exe.linux-riscv64@12.18.0':
resolution: {integrity: sha512-7kMN77xSOYJX8GPSH5RbNAc5oM61LMmcSUukDDUwllnZPXm8GRPskCNsTWy8SCw01Kr1FB+5SwGNMiTdiziLNQ==}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@pnpm/exe.linux-s390x@12.21.0':
resolution: {integrity: sha512-8VXGNGVNEfs7pL9GTZOzFxjFEnMt4WL3rLOADR5/kPQ7ROTV9GfpVI2DPO/zArXFSkvfc9Zad/WypHLbvzoaTQ==}
'@pnpm/exe.linux-s390x@12.18.0':
resolution: {integrity: sha512-htuSCpEcmDzhKoJqXbPkvfr176dBHU0QIF5mWcRiqxRXAB/1JoYiMYotfjWpk+ztgpB9qlx4XnWlLFAf7gzc6g==}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@pnpm/exe.linux-x64-musl@12.21.0':
resolution: {integrity: sha512-MnC5vpIXYubhDZCgCwlfJMg7Cg6HupN2IuouT9gD/tUmOfVdQYqeyYccWbthyo/Jeto8de1oQlxeRN1+1Hl2DQ==}
'@pnpm/exe.linux-x64-musl@12.18.0':
resolution: {integrity: sha512-Uj+vzfIQ62kDP10x36yHZIXVs5ohdNtiPYwn5FhCLlNScHPo0OAI+ShGDtLofiBXKE7umu71Jmjm7N8a8zVcDw==}
cpu: [x64]
os: [linux]
libc: [musl]
'@pnpm/exe.linux-x64@12.21.0':
resolution: {integrity: sha512-8eufCjHXspKbNS/kh8q4Q0gqJoOuvC4Q5pgos6XS8By/nAMtP+jf8F1Cw9er840kfAX+PJ/ts+A9qnLE91rvXQ==}
'@pnpm/exe.linux-x64@12.18.0':
resolution: {integrity: sha512-OJ+X2wcraldCwj75pCIerWARQSRpdfj0eBTs/2ODyhfeW46ylOnjTIE/GKra6Mn6E72/gBmXS8igrUioa+F9fQ==}
cpu: [x64]
os: [linux]
libc: [glibc]
'@pnpm/exe.netbsd-x64@12.21.0':
resolution: {integrity: sha512-eyh1M8hQZCkLWxuva7S/fc1SbFbgqg0/5di0dgWmyiuc2Io3dbWVihDun8X+XM8zsR5uhIDvvZpbS9aZQbCovg==}
cpu: [x64]
os: [netbsd]
'@pnpm/exe.win32-arm64@12.21.0':
resolution: {integrity: sha512-7xTxxUXo/grRLivSeIl6B21gnsz7ooe5EMPcJmQqwxc8WLJVReN8MzrlHru8bqXfVr4X3+6ZGZscntKenlCBqQ==}
'@pnpm/exe.win32-arm64@12.18.0':
resolution: {integrity: sha512-wEY6jiACGcbhhi5yD59doHqNTndS7AaujaPmtWAu1DKkHru2hy5fJ9yUGecW72Ypaw2/I3BEprfMOopap2NQtw==}
cpu: [arm64]
os: [win32]
'@pnpm/exe.win32-x64@12.21.0':
resolution: {integrity: sha512-9TpkJemVApxJ1Z1w0ZFGN+AuSx4nJOqXSJUqMqDvaXTYwGOzvBiiWdFP9GN0ketiWCQS1Q0/pza2E7I3pP0OBQ==}
'@pnpm/exe.win32-x64@12.18.0':
resolution: {integrity: sha512-5FJkghO7RLRkQpWxeVEygW9XsmnNuxzPfXbgwFWCHsFyFhpDn/vOdL88ToQEM0Kt5igdW5s6U0/IDH8Dvkt3pg==}
cpu: [x64]
os: [win32]
pnpm@12.21.0:
resolution: {integrity: sha512-Zv2CeO4ok1zpUXktNDZ/869cQyonVkRYIwKVM4NbjaUpu+C+UTCv1W7QcT+4eJ5Hutgtk71a4v5UsVVi1idu8A==}
pnpm@12.18.0:
resolution: {integrity: sha512-nXiC1dyCFH7PxOBiqjSDTgrQKWcQoYN6ERWuASEn02txCeMhrBWYod0KZVl2gbHpmRfhLtDXSerpEYeUM2O+sw==}
engines: {node: '>=18'}
hasBin: true
snapshots:
'@pnpm/exe.android-arm64@12.21.0':
'@pnpm/exe.android-arm64@12.18.0':
optional: true
'@pnpm/exe.android-x64@12.21.0':
'@pnpm/exe.android-x64@12.18.0':
optional: true
'@pnpm/exe.darwin-arm64@12.21.0':
'@pnpm/exe.darwin-arm64@12.18.0':
optional: true
'@pnpm/exe.darwin-x64@12.21.0':
'@pnpm/exe.darwin-x64@12.18.0':
optional: true
'@pnpm/exe.freebsd-x64@12.21.0':
'@pnpm/exe.freebsd-x64@12.18.0':
optional: true
'@pnpm/exe.linux-arm64-musl@12.21.0':
'@pnpm/exe.linux-arm64-musl@12.18.0':
optional: true
'@pnpm/exe.linux-arm64@12.21.0':
'@pnpm/exe.linux-arm64@12.18.0':
optional: true
'@pnpm/exe.linux-ppc64@12.21.0':
'@pnpm/exe.linux-ppc64@12.18.0':
optional: true
'@pnpm/exe.linux-riscv64@12.21.0':
'@pnpm/exe.linux-riscv64@12.18.0':
optional: true
'@pnpm/exe.linux-s390x@12.21.0':
'@pnpm/exe.linux-s390x@12.18.0':
optional: true
'@pnpm/exe.linux-x64-musl@12.21.0':
'@pnpm/exe.linux-x64-musl@12.18.0':
optional: true
'@pnpm/exe.linux-x64@12.21.0':
'@pnpm/exe.linux-x64@12.18.0':
optional: true
'@pnpm/exe.netbsd-x64@12.21.0':
'@pnpm/exe.win32-arm64@12.18.0':
optional: true
'@pnpm/exe.win32-arm64@12.21.0':
'@pnpm/exe.win32-x64@12.18.0':
optional: true
'@pnpm/exe.win32-x64@12.21.0':
optional: true
pnpm@12.21.0:
pnpm@12.18.0:
optionalDependencies:
'@pnpm/exe.android-arm64': 12.21.0
'@pnpm/exe.android-x64': 12.21.0
'@pnpm/exe.darwin-arm64': 12.21.0
'@pnpm/exe.darwin-x64': 12.21.0
'@pnpm/exe.freebsd-x64': 12.21.0
'@pnpm/exe.linux-arm64': 12.21.0
'@pnpm/exe.linux-arm64-musl': 12.21.0
'@pnpm/exe.linux-ppc64': 12.21.0
'@pnpm/exe.linux-riscv64': 12.21.0
'@pnpm/exe.linux-s390x': 12.21.0
'@pnpm/exe.linux-x64': 12.21.0
'@pnpm/exe.linux-x64-musl': 12.21.0
'@pnpm/exe.netbsd-x64': 12.21.0
'@pnpm/exe.win32-arm64': 12.21.0
'@pnpm/exe.win32-x64': 12.21.0
'@pnpm/exe.android-arm64': 12.18.0
'@pnpm/exe.android-x64': 12.18.0
'@pnpm/exe.darwin-arm64': 12.18.0
'@pnpm/exe.darwin-x64': 12.18.0
'@pnpm/exe.freebsd-x64': 12.18.0
'@pnpm/exe.linux-arm64': 12.18.0
'@pnpm/exe.linux-arm64-musl': 12.18.0
'@pnpm/exe.linux-ppc64': 12.18.0
'@pnpm/exe.linux-riscv64': 12.18.0
'@pnpm/exe.linux-s390x': 12.18.0
'@pnpm/exe.linux-x64': 12.18.0
'@pnpm/exe.linux-x64-musl': 12.18.0
'@pnpm/exe.win32-arm64': 12.18.0
'@pnpm/exe.win32-x64': 12.18.0
---
lockfileVersion: '9.0'
@@ -209,8 +200,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 +294,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 +315,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.5
version: 2.12.5
'@types/lodash-es':
specifier: ^4.17.12
version: 4.17.12
@@ -2072,82 +2063,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.5':
resolution: {integrity: sha512-VVvBRBdTFF7BP7RqGeItp9yDiyXj0DI1laRCEN2q6GLrNkw4wrHeWAxHp23PwtQtn/XET+yTN1jOKrq+Yor5PQ==}
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.5':
resolution: {integrity: sha512-A84QYNj93kaG06N2mIFBRZM/X3lf9TyAVQeQwOmP2AJZ2wCt1WLDJgHRCvjeJmwJjJ5Ud0jUbIKbXg8NEGvsVQ==}
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.5':
resolution: {integrity: sha512-tb/5xG5HV6CJR9AZBmTyI2GCi05vcH8XUjUIjBquAx7x+AE4f1vMWngvq7JW2AqYK8nNl79LJH1GR9Hf5QQc5g==}
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.5':
resolution: {integrity: sha512-Vb7SlbIWlmIqekfsGYT64wH1cQNg5MET8XFyT6pUlVJ7Y/z6LsOIh4MUal0Z5FCPL83GMuEUNxpYUHpt36teHQ==}
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.5':
resolution: {integrity: sha512-b/YfVGueoTOtENQHY1STBF9XlU4uZDtOiMUErp2Nao/YrDWCKggjxxBZU3ycbeDWUYxl8U8M9seE4HYag1xjiQ==}
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.5':
resolution: {integrity: sha512-/EXbTfE9FM9GKSSRL9YTRHcMglTVNzbcwegXM0MBR3ozVgoE+pFq46Ej/InJBs1l+sjSpu6jyi38MZ+xyU/3NQ==}
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.5':
resolution: {integrity: sha512-OIun574QsULxaZ5SmPDX4D8bO95RBmYJshu8yGFy0RSyCMKEs/y+o3BThot4fbCv4ttC1Tq6Hzt0QRHXCIgp7w==}
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.5':
resolution: {integrity: sha512-GDzWcb/6OzJrHnVGQ/n3XndLan67bZ7cu4zJN9+zFmV10nBgKz5jDDm8sRQO4sGb7bu6Ztiy+Al2XY2ptRY0RQ==}
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.5':
resolution: {integrity: sha512-61KCX5vo0vex7P/P7sbXdfFhHqs+rFaG+UXK/UBwz/VlLveDx6vgpHkF+rfUIfCqj0VvLArpxR3+rQIzRwxKgw==}
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.5':
resolution: {integrity: sha512-mGujjR/MlXwJiQcue4wlXrBYlIEdDCoap0g+GNPlLCb75ilSbWMC8qTsXVuGcLIMumIJvc2v+veDnCHnels/Zg==}
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.5':
resolution: {integrity: sha512-o1+EOjvi/nFwKx5XamCXSr+GUr2ko8TH7+0wnWuZjE+lZwE+/VWCbE49HPHa3/V59M3bJ0dlK1yhogGQ15OVPg==}
engines: {node: '>= 10'}
cpu: [x64]
os: [win32]
'@tauri-apps/cli@2.12.4':
resolution: {integrity: sha512-JI9bHfudSRJikGOrjbXEm6RjzzvmKuLc+JixB1NE8hNzQkNlCCIC3pTES3uypkR9lxHrsbxzcnSwhI2IxBQphw==}
'@tauri-apps/cli@2.12.5':
resolution: {integrity: sha512-Dm8s/4aiE52HsBh+Gz3uSrh+fEykRICA1VoAnQA80IqHoTRncPg+q4rGvuhmyNsHUPg3QrPjUrTUSfWmXLVVEw==}
engines: {node: '>= 10'}
hasBin: true
@@ -4015,9 +4006,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 +5961,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.5':
optional: true
'@tauri-apps/cli-darwin-x64@2.12.4':
'@tauri-apps/cli-darwin-x64@2.12.5':
optional: true
'@tauri-apps/cli-linux-arm-gnueabihf@2.12.4':
'@tauri-apps/cli-linux-arm-gnueabihf@2.12.5':
optional: true
'@tauri-apps/cli-linux-arm64-gnu@2.12.4':
'@tauri-apps/cli-linux-arm64-gnu@2.12.5':
optional: true
'@tauri-apps/cli-linux-arm64-musl@2.12.4':
'@tauri-apps/cli-linux-arm64-musl@2.12.5':
optional: true
'@tauri-apps/cli-linux-riscv64-gnu@2.12.4':
'@tauri-apps/cli-linux-riscv64-gnu@2.12.5':
optional: true
'@tauri-apps/cli-linux-x64-gnu@2.12.4':
'@tauri-apps/cli-linux-x64-gnu@2.12.5':
optional: true
'@tauri-apps/cli-linux-x64-musl@2.12.4':
'@tauri-apps/cli-linux-x64-musl@2.12.5':
optional: true
'@tauri-apps/cli-win32-arm64-msvc@2.12.4':
'@tauri-apps/cli-win32-arm64-msvc@2.12.5':
optional: true
'@tauri-apps/cli-win32-ia32-msvc@2.12.4':
'@tauri-apps/cli-win32-ia32-msvc@2.12.5':
optional: true
'@tauri-apps/cli-win32-x64-msvc@2.12.4':
'@tauri-apps/cli-win32-x64-msvc@2.12.5':
optional: true
'@tauri-apps/cli@2.12.4':
'@tauri-apps/cli@2.12.5':
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.5
'@tauri-apps/cli-darwin-x64': 2.12.5
'@tauri-apps/cli-linux-arm-gnueabihf': 2.12.5
'@tauri-apps/cli-linux-arm64-gnu': 2.12.5
'@tauri-apps/cli-linux-arm64-musl': 2.12.5
'@tauri-apps/cli-linux-riscv64-gnu': 2.12.5
'@tauri-apps/cli-linux-x64-gnu': 2.12.5
'@tauri-apps/cli-linux-x64-musl': 2.12.5
'@tauri-apps/cli-win32-arm64-msvc': 2.12.5
'@tauri-apps/cli-win32-ia32-msvc': 2.12.5
'@tauri-apps/cli-win32-x64-msvc': 2.12.5
'@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 +8111,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:
+1 -1
View File
@@ -220,7 +220,7 @@ pub fn run() -> std::process::ExitCode {
.set_activation_policy(tauri::ActivationPolicy::Prohibited)?;
let scenario = std::env::var("PERF_SCENARIO").unwrap_or_else(|_| "traffic".into());
let layer = std::env::var("PERF_LAYER").unwrap_or_else(|_| "component".into());
if !matches!(scenario.as_str(), "traffic" | "logs" | "connections" | "proxy")
if !matches!(scenario.as_str(), "traffic" | "logs" | "connections")
|| !matches!(layer.as_str(), "page" | "component" | "dom")
{
return Err("invalid perf scene".into());
-2
View File
@@ -2,8 +2,6 @@ import { layer, scenario, startReplay } from './replay'
if (scenario === 'traffic') {
await import('./traffic')
} else if (scenario === 'proxy') {
await import('./proxy')
} else {
const root = document.getElementById('root')!
document.body.style.cssText = 'margin:0;font:14px -apple-system,sans-serif'
-137
View File
@@ -1,137 +0,0 @@
// Only this perf build aliases '@tauri-apps/api/core' to a shim that serves
// these responses for the proxy scenario; the normal application never
// imports it. The runtime-injected __TAURI_INTERNALS__ is read-only, so
// interception happens at import resolution instead. Unknown commands pass
// through to the real backend (perf_state, event plugin), keeping harness
// ownership probes and lifecycle commands working. The proxy scenario is
// therefore a JavaScript invoke adapter, not native plugin IPC.
const GROUP_COUNT = 40
const NODES_PER_GROUP = 24
const capabilities = {
udp: true,
xudp: false,
tfo: false,
mptcp: false,
smux: false,
}
const history = (delay: number) => [{ time: '2026-11-19T00:00:00Z', delay }]
const buildProxyView = () => {
const records: Record<string, unknown> = {}
const groups: {
name: string
type: string
now: string
hidden: boolean
history: { time: string; delay: number }[]
members: unknown[]
}[] = []
for (let g = 0; g < GROUP_COUNT; g++) {
const members: unknown[] = []
for (let n = 0; n < NODES_PER_GROUP; n++) {
const name = `node-${g}-${n}`
const recordId = `record-${g}-${n}`
records[recordId] = {
recordId,
name,
type: n % 3 === 0 ? 'Shadowsocks' : n % 3 === 1 ? 'Vmess' : 'Trojan',
history: history(30 + ((g * 7 + n * 13) % 40) * 10),
source: { kind: 'core', proxyName: name },
...capabilities,
}
members.push({ kind: 'node', name, recordId })
}
groups.push({
name: `group-${String(g).padStart(2, '0')}`,
type: g % 2 === 0 ? 'Selector' : 'URLTest',
now: `node-${g}-0`,
hidden: false,
history: history(20),
members,
})
}
return {
schemaVersion: 1,
orderSource: 'runtime',
providerState: 'ready',
global: {
name: 'GLOBAL',
type: 'Selector',
now: 'group-00',
hidden: true,
history: [],
members: groups.map((group) => ({ kind: 'group', name: group.name })),
...capabilities,
},
direct: 'DIRECT',
groups: groups.map((group) => ({ ...group, ...capabilities })),
records,
standalone: [],
providers: [],
}
}
const handlers: Record<string, () => unknown> = {
get_proxy_view: buildProxyView,
get_verge_config: () => ({
language: 'en',
theme_mode: 'light',
proxy_layout_column: 2,
default_latency_timeout: 10000,
enable_hover_jump_navigator: true,
hover_jump_navigator_delay: 200,
pause_render_traffic_stats_on_blur: false,
}),
get_profiles: () => ({
current: 'perf-profile',
items: [
{
uid: 'perf-profile',
type: 'remote',
name: 'Perf Profile',
desc: '',
url: '',
selected: true,
extra: {},
option: { update_interval: 0 },
},
],
}),
get_clash_info: () => ({
mixed_port: 7897,
socks_port: 0,
port: 0,
server: '127.0.0.1:9097',
secret: null,
}),
get_runtime_config: () => null,
get_sys_proxy: () => ({ enable: false, bypass: '', pac_file: '' }),
get_runtime_state: () => ({
mode: 'Sidecar',
service: 'ready',
serviceUnavailableReason: null,
pendingAction: null,
sidecarAllowed: true,
isAdmin: false,
opInFlight: false,
serviceUsable: true,
tunCapable: false,
serviceNeedsAttention: false,
}),
get_sidecar_failure: () => null,
get_pending_failures: () => [],
'plugin:mihomo|get_configs': () => ({ mode: 'rule', 'mixed-port': 7897 }),
'plugin:mihomo|get_rule_providers': () => ({ providers: {} }),
'plugin:mihomo|get_rules': () => ({ rules: [] }),
}
/** Returns the mocked response, or undefined to pass through to the backend. */
export const mockCommand = (cmd: string): unknown => {
const handler = handlers[cmd]
return handler ? handler() : undefined
}
-93
View File
@@ -1,93 +0,0 @@
import { ThemeProvider, createTheme } from '@mui/material'
import { useEffect } from 'react'
import { createRoot } from 'react-dom/client'
import { SWRConfig } from 'swr'
import { AppDataProvider } from '../../src/providers/app-data-provider'
import { initializeLanguage } from '../../src/services/i18n'
import { setPreloadConfig } from '../../src/services/preload'
import { swrConfig } from '../../src/services/query-client'
import { AppStoreProvider } from '../../src/store/app-store'
import '../../src/assets/styles/page.scss'
const root = document.getElementById('root')!
document.body.style.cssText = 'margin:0;font:14px -apple-system,sans-serif'
root.style.cssText = 'width:1000px;height:700px;overflow:hidden'
new MutationObserver(() => {
document.documentElement.dataset.perfDraw = String(Date.now())
}).observe(root, { childList: true, characterData: true, subtree: true })
setPreloadConfig({
language: 'en',
theme_mode: 'light',
pause_render_traffic_stats_on_blur: false,
} as IVergeConfig)
await initializeLanguage('en')
const ProxyPage = (await import('../../src/pages/proxies')).default
const findScroller = () => {
const elements = document.querySelectorAll<HTMLElement>('#root *')
for (const element of elements) {
const { overflowY } = getComputedStyle(element)
if (
(overflowY === 'auto' || overflowY === 'scroll') &&
element.scrollHeight > element.clientHeight
) {
return element
}
}
return null
}
// Deterministic sawtooth scrolling keeps the virtualizer measuring, the
// throttled scroll-position save running and the DOM mutating so the perfDraw
// marker tracks view-input delivery. Each applied scroll step counts as one
// delivered view input; the interval keeps delivering (throttled by the
// browser) while the window is hidden and rAF is suspended.
export const ScrollDriver = () => {
useEffect(() => {
const data = document.documentElement.dataset
let stopped = false
const step = () => {
const scroller = findScroller()
if (scroller) {
const max = scroller.scrollHeight - scroller.clientHeight
if (max > 0) {
const next =
scroller.scrollTop + 36 > max - 36 ? 0 : scroller.scrollTop + 36
scroller.scrollTop = next
data.perfScroll = String(Number(data.perfScroll || 0) + 1)
data.perfDelivered = String(Number(data.perfDelivered || 0) + 1)
}
}
}
const drive = () => {
if (stopped) return
step()
requestAnimationFrame(drive)
}
const handle = requestAnimationFrame(drive)
const timer = window.setInterval(step, 250)
return () => {
stopped = true
cancelAnimationFrame(handle)
window.clearInterval(timer)
}
}, [])
return null
}
createRoot(root).render(
<SWRConfig value={swrConfig}>
<ThemeProvider theme={createTheme()}>
<AppStoreProvider>
<AppDataProvider>
<ProxyPage />
<ScrollDriver />
</AppDataProvider>
</AppStoreProvider>
</ThemeProvider>
</SWRConfig>,
)
-17
View File
@@ -1,17 +0,0 @@
import { startReplay } from './replay'
// Thin loader: error handlers must precede scene module evaluation so any
// startup failure surfaces in perfError.
const data = document.documentElement.dataset
window.addEventListener('error', (event) => {
data.perfError = event.message
})
window.addEventListener('unhandledrejection', (event) => {
data.perfError = String(event.reason)
})
data.perfStage = 'loader'
await import('./proxy-scene')
data.perfStage = 'scene'
startReplay()
data.perfStage = 'replay'
-30
View File
@@ -1,30 +0,0 @@
// Aliased in place of '@tauri-apps/api/core' only by the perf build. The
// direct relative import keeps the original module outside the alias so this
// shim can forward to it. Invocation stays byte-identical for every scenario
// except proxy, which needs the JavaScript invoke adapter.
import {
Channel,
convertFileSrc,
invoke as realInvoke,
type InvokeArgs,
type InvokeOptions,
} from '../../node_modules/@tauri-apps/api/core.js'
import { mockCommand } from './invoke-mock'
import { scenario } from './replay'
const proxied = scenario === 'proxy'
export const invoke = async <T>(
cmd: string,
args?: InvokeArgs,
options?: InvokeOptions,
): Promise<T> => {
if (proxied) {
const mocked = mockCommand(cmd)
if (mocked !== undefined) return mocked as T
}
return realInvoke(cmd, args, options)
}
export { Channel, convertFileSrc }
-6
View File
@@ -6,11 +6,5 @@ export default mergeConfig(
defineConfig({
root: 'scripts/perf',
build: { outDir: '../../target/perf/dist', target: 'safari16' },
resolve: {
alias: {
'@tauri-apps/api/core': new URL('./tauri-core-shim.ts', import.meta.url)
.pathname,
},
},
}),
)
+1 -1
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 }
-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();
-4
View File
@@ -109,8 +109,6 @@ pub struct IVerge {
pub auto_close_connection: Option<bool>,
pub auto_switch_selector_group: Option<bool>,
pub auto_check_update: Option<bool>,
pub default_latency_test: Option<String>,
@@ -370,7 +368,6 @@ impl IVerge {
use_default_bypass: Some(true),
proxy_guard_duration: Some(30),
auto_close_connection: Some(true),
auto_switch_selector_group: Some(true),
auto_check_update: Some(true),
enable_builtin_enhanced: Some(true),
auto_log_clean: Some(2), // 1: 1天, 2: 7天, 3: 30天, 4: 90天
@@ -459,7 +456,6 @@ impl IVerge {
patch_opt_field!(self, patch, enable_global_hotkey);
patch_opt_field!(self, patch, auto_close_connection);
patch_opt_field!(self, patch, auto_switch_selector_group);
patch_opt_field!(self, patch, auto_check_update);
patch_opt_field!(self, patch, default_latency_test);
patch_opt_field!(self, patch, default_latency_timeout);
-1
View File
@@ -90,7 +90,6 @@ verge_registry! {
enable_global_hotkey => NoEffect;
home_cards => NoEffect;
auto_close_connection => NoEffect;
auto_switch_selector_group => NoEffect;
auto_check_update => NoEffect;
default_latency_test => NoEffect;
default_latency_timeout => NoEffect;
+4 -118
View File
@@ -9,7 +9,6 @@ use crate::{
};
use anyhow::{Result, bail};
use clash_verge_logging::{Type, logging};
use tauri_plugin_mihomo::models::ProxyType;
use tristr::alias::String;
/// Toggle proxy profile
@@ -23,80 +22,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`.
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"))
.filter(|group| {
group
.get("proxies")
.and_then(|members| members.as_sequence())
.is_some_and(|members| members.iter().any(|member| member.as_str() == Some(group_name)))
})
.filter_map(|group| field(group, "name"))
.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.
async fn follow_group_selection(group_name: &str) -> Option<std::string::String> {
if !Config::verge()
.await
.data_arc()
.auto_switch_selector_group
.unwrap_or(true)
{
return None;
}
if Config::clash()
.await
.data_arc()
.get_mode()
.is_some_and(|mode| mode != "rule")
{
return None;
}
let selector = {
let runtime = Config::runtime().await.latest_arc();
let groups = runtime.config.as_ref()?.get("proxy-groups")?.as_sequence()?;
parent_selector(groups, group_name)?.to_owned()
};
let mihomo = handle::Handle::mihomo();
let current = mihomo.get_proxy_by_name(&selector).await.ok()?;
// 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 {
return None;
}
if let Err(err) = mihomo.select_node_for_group(&selector, group_name).await {
logging!(warn, Type::Core, "Failed to point {selector} at {group_name}: {err:#}");
return None;
}
if let Err(error) = crate::config::profiles::record_selected_node(&selector, group_name).await {
logging!(
warn,
Type::Config,
"Failed to persist proxy selection for {selector}: {error:#}"
);
}
Some(previous)
}
pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool) -> Result<()> {
let mihomo = handle::Handle::mihomo();
let auto_close = Config::verge().await.data_arc().auto_close_connection.unwrap_or(false);
let previous_proxy = if auto_close {
let previous_proxy = if Config::verge().await.data_arc().auto_close_connection.unwrap_or(false) {
match mihomo.get_proxy_by_name(group_name).await {
Ok(group) => group.now.filter(|name| !name.is_empty()),
Err(err) => {
@@ -130,31 +58,9 @@ pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool)
"Failed to persist proxy selection for {group_name}: {error:#}"
);
}
let mut stale_proxies: Vec<_> = previous_proxy.into_iter().collect();
if !unfix
&& let Some(left) = follow_group_selection(group_name).await
&& auto_close
{
stale_proxies.push(left);
}
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);
if !stale_proxies.is_empty() {
if let Some(previous_proxy) = previous_proxy {
AsyncHandler::spawn(move || async move {
let connections = match mihomo.get_connections().await {
Ok(connections) => connections,
@@ -172,7 +78,7 @@ async fn finish_proxy_switch(stale_proxies: Vec<std::string::String>) {
.connections
.unwrap_or_default()
.into_iter()
.filter(|connection| stale_proxies.iter().any(|proxy| connection.chains.contains(proxy)))
.filter(|connection| connection.chains.contains(&previous_proxy))
.map(|connection| async move {
if let Err(err) = mihomo.close_connection(&connection.id).await {
logging!(
@@ -194,6 +100,7 @@ async fn finish_proxy_switch(stale_proxies: Vec<std::string::String>) {
"Failed to refresh tray after switching proxy: {err:#}"
);
}
Ok(())
}
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
@@ -373,24 +280,3 @@ pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_mannual_tr
pub async fn enhance_profiles() -> Result<ValidationOutcome> {
CoreManager::global().update_config_forced().await
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_first_select_group_follows_an_auto_group() -> Result<()> {
let groups: Vec<serde_yaml_ng::Value> = serde_yaml_ng::from_str(
"
- { name: GLOBAL, type: select, proxies: [Auto, Proxy, Direct] }
- { name: Auto, type: url-test, proxies: [Node] }
- { name: Proxy, type: select, proxies: [Auto, Node] }
- { name: Direct, type: select, proxies: [DIRECT, Auto] }
",
)?;
assert_eq!(parent_selector(&groups, "Auto"), Some("Proxy"));
assert_eq!(parent_selector(&groups, "Proxy"), None);
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,
+1 -3
View File
@@ -55,7 +55,6 @@ import {
useCoreDataStatus,
useProxiesData,
} from '@/providers/app-data-context'
import { followProxyGroup } from '@/services/cmds'
import delayManager from '@/services/delay'
import {
findCurrentGroupMember,
@@ -666,7 +665,7 @@ export const CurrentProxyCard = () => {
return proxyView.groups.filter(
(group) =>
!group.hidden &&
['Selector', 'URLTest', 'Fallback'].includes(group.type),
(group.type === 'Selector' || group.type === 'URLTest'),
)
}, [proxyView])
@@ -766,7 +765,6 @@ export const CurrentProxyCard = () => {
if (isGlobalMode || isDirectMode) return
setLastGroupName(newGroupName)
writeProfileScopedItem(STORAGE_KEY_GROUP, newGroupName)
void followProxyGroup(newGroupName)
},
[isDirectMode, isGlobalMode, writeProfileScopedItem],
)
@@ -7,6 +7,7 @@ import {
useEffectEvent,
useImperativeHandle,
useMemo,
useReducer,
useRef,
useState,
} from 'react'
@@ -19,6 +20,7 @@ import {
formatTrafficHourMinute,
formatTrafficMinuteSecond,
formatTrafficName,
isSameTrafficData,
} from '@/utils/traffic-sampler'
export interface EnhancedCanvasTrafficGraphRef {
@@ -72,200 +74,16 @@ const GRAPH_CONFIG = {
const STALE_DATA_THRESHOLD = 2500 // ms without fresh data => drop FPS
// Static sx/style identities keep the emotion cache effective; the remaining
// dynamic props (tooltip position, legend colors) stay inline or memoized.
const rootSx = {
width: '100%',
height: '100%',
position: 'relative',
bgcolor: 'action.hover',
borderRadius: 1,
cursor: 'pointer',
overflow: 'hidden',
}
const canvasStyle = {
width: '100%',
height: '100%',
display: 'block',
} as const
const hoverCanvasStyle = {
position: 'absolute',
inset: 0,
width: '100%',
height: '100%',
display: 'block',
pointerEvents: 'none',
} as const
const overlaySx = {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
pointerEvents: 'none',
}
const timeRangeBadgeSx = {
position: 'absolute',
top: 6,
left: 40,
fontSize: '11px',
fontWeight: 'bold',
color: 'text.secondary',
cursor: 'pointer',
pointerEvents: 'all',
px: 1,
py: 0.5,
borderRadius: 0.5,
bgcolor: 'rgba(0,0,0,0.05)',
'&:hover': {
bgcolor: 'rgba(0,0,0,0.1)',
},
}
const legendsSx = {
position: 'absolute',
top: 6,
right: 8,
display: 'flex',
flexDirection: 'column',
gap: 0.5,
}
const chartStyleHintSx = {
position: 'absolute',
bottom: 6,
right: 8,
fontSize: '10px',
color: 'text.disabled',
opacity: 0.7,
}
const diagnosticsSx = {
position: 'absolute',
bottom: 6,
left: 8,
fontSize: '9px',
color: 'text.disabled',
opacity: 0.6,
lineHeight: 1.2,
}
const tooltipTimeSx = { color: 'text.secondary', mb: 0.2 }
const tooltipUpSx = { color: 'secondary.main', fontWeight: 500 }
const tooltipDownSx = { color: 'primary.main', fontWeight: 500 }
interface TimeDisplayStrategy {
maxLabels: number
formatTime: (timestamp: number) => string
intervalSeconds: number
minPixelDistance: number
}
const TIME_DISPLAY_STRATEGIES: Record<TimeRange, TimeDisplayStrategy> = {
1: {
maxLabels: 6,
formatTime: formatTrafficMinuteSecond,
intervalSeconds: 10,
minPixelDistance: 35,
},
5: {
maxLabels: 6,
formatTime: formatTrafficHourMinute,
intervalSeconds: 30,
minPixelDistance: 38,
},
10: {
maxLabels: 8,
formatTime: formatTrafficHourMinute,
intervalSeconds: 60,
minPixelDistance: 40,
},
}
// Per-draw buffers live at module scope: drawing runs synchronously on the
// main thread, so slots never overlap a concurrent reader.
const yAxisTicks = [
{ label: '', y: 0 },
{ label: '', y: 0 },
{ label: '', y: 0 },
]
const yAxisTickLabels = new Map<number, string>()
const formatYAxisTickLabel = (bytes: number): string => {
const cached = yAxisTickLabels.get(bytes)
if (cached !== undefined) return cached
const label =
bytes === 0
? '0'
: bytes < 1024
? `${Math.round(bytes)}B`
: bytes < 1024 * 1024
? `${Math.round(bytes / 1024)}KB`
: `${(bytes / (1024 * 1024)).toFixed(1)}MB`
if (yAxisTickLabels.size >= 256) yAxisTickLabels.clear()
yAxisTickLabels.set(bytes, label)
return label
}
const getYAxisTicks = (
topValue: number,
bottomValue: number,
height: number,
) => {
const padding = GRAPH_CONFIG.padding
const topY = padding.top + 10
const bottomY = height - padding.bottom - 5
const middleY = (topY + bottomY) / 2
const middleValue = (bottomValue + topValue) / 2
const [bottomTick, middleTick, topTick] = yAxisTicks
bottomTick.label = formatYAxisTickLabel(bottomValue)
bottomTick.y = bottomY
middleTick.label = formatYAxisTickLabel(middleValue)
middleTick.y = middleY
topTick.label = formatYAxisTickLabel(topValue)
topTick.y = topY
return yAxisTicks
}
interface TimeAxisPoint {
x: number
label: string
}
const timeAxisPoints: TimeAxisPoint[] = []
const resetTimeAxisPoints = () => {
timeAxisPoints.length = 0
}
const pushTimeAxisPoint = (x: number, label: string) => {
let slot = timeAxisPoints[timeAxisPoints.length]
if (!slot) {
slot = { x: 0, label: '' }
timeAxisPoints.push(slot)
}
slot.x = x
slot.label = label
}
// Gradient stop strings are pure functions of the theme color; the colors
// memo builds them once per theme.
const GRADIENT_ALPHA_HEX = Math.round(GRAPH_CONFIG.alpha.gradient * 255)
.toString(16)
.padStart(2, '0')
const makeGradientStops = (color: string) => ({
start: `${color}${GRADIENT_ALPHA_HEX}`,
end: `${color}00`,
})
interface EnhancedCanvasTrafficGraphProps {
ref?: Ref<EnhancedCanvasTrafficGraphRef>
}
const displayDataReducer = (
current: ITrafficDataPoint[],
payload: ITrafficDataPoint[],
): ITrafficDataPoint[] =>
isSameTrafficData(current, payload) ? current : payload
export const EnhancedCanvasTrafficGraph = memo(
function EnhancedCanvasTrafficGraph({
ref,
@@ -276,9 +94,11 @@ export const EnhancedCanvasTrafficGraph = memo(
const pause_render_traffic_stats_on_blur =
verge.verge?.pause_render_traffic_stats_on_blur ?? true
const { dataPoints, requestRange, samplerStats } =
useTrafficGraphDataEnhanced()
const [timeRange, setTimeRange] = useState<TimeRange>(10)
const [chartStyle, setChartStyle] = useState<'bezier' | 'line'>('bezier')
const [badgeStats, setBadgeStats] = useState({ points: 0, compressed: 0 })
const initialFocusState =
typeof document !== 'undefined' ? !document.hidden : true
@@ -309,49 +129,66 @@ export const EnhancedCanvasTrafficGraph = memo(
const lastDataTimestampRef = useRef<number>(0)
const dataStaleRef = useRef<boolean>(false)
// Live snapshot data for the rAF draw path; React state only tracks the
// diagnostics badge inputs so steady-state snapshots stop re-rendering.
const displayDataRef = useRef<ITrafficDataPoint[]>([])
const yScaleRef = useRef<{ topValue: number; bottomValue: number }>({
topValue: 1024,
bottomValue: 0,
})
const [displayData, dispatchDisplayData] = useReducer(
displayDataReducer,
[],
)
const debounceTimeoutRef = useRef<number | null>(null)
const colors = useMemo(() => {
const base = {
const colors = useMemo(
() => ({
up: theme.palette.secondary.main,
down: theme.palette.primary.main,
grid: theme.palette.divider,
text: theme.palette.text.secondary,
background: theme.palette.background.paper,
}
return {
...base,
gradient: {
up: makeGradientStops(base.up),
down: makeGradientStops(base.down),
},
}
}, [theme])
const legendSx = useMemo(
() => ({
up: {
fontSize: '11px',
fontWeight: 'bold',
color: colors.up,
textAlign: 'right',
},
down: {
fontSize: '11px',
fontWeight: 'bold',
color: colors.down,
textAlign: 'right',
},
}),
[colors],
[theme],
)
const updateDisplayData = useCallback((newData: ITrafficDataPoint[]) => {
if (debounceTimeoutRef.current !== null) {
window.clearTimeout(debounceTimeoutRef.current)
}
debounceTimeoutRef.current = window.setTimeout(() => {
dispatchDisplayData(newData)
}, 50)
}, [])
useEffect(() => {
updateDisplayData(dataPoints)
return () => {
if (debounceTimeoutRef.current !== null) {
window.clearTimeout(debounceTimeoutRef.current)
debounceTimeoutRef.current = null
}
}
}, [dataPoints, updateDisplayData])
useEffect(() => {
requestRange(timeRange)
}, [requestRange, timeRange])
useEffect(() => {
if (displayData.length === 0) {
lastDataTimestampRef.current = 0
dataStaleRef.current = false
return
}
const latestTimestamp =
displayData[displayData.length - 1]?.timestamp ?? null
if (latestTimestamp) {
lastDataTimestampRef.current = latestTimestamp
const age = Date.now() - latestTimestamp
const stale = age > STALE_DATA_THRESHOLD
dataStaleRef.current = stale
} else {
dataStaleRef.current = false
}
}, [displayData])
const handleFocusStateChange = useEffectEvent((focused: boolean) => {
isWindowFocusedRef.current = focused
@@ -433,9 +270,14 @@ export const EnhancedCanvasTrafficGraph = memo(
[],
)
const yScale = useMemo(
() => computeYScale(displayData),
[computeYScale, displayData],
)
const handleMouseMove = useCallback(
(event: React.MouseEvent<HTMLElement>) => {
if (displayDataRef.current.length === 0) return
if (displayData.length === 0) return
pendingMousePositionRef.current = {
clientX: event.clientX,
@@ -452,8 +294,7 @@ export const EnhancedCanvasTrafficGraph = memo(
if (!pendingMousePosition) return
const canvas = canvasRef.current
const data = displayDataRef.current
if (!canvas || data.length === 0) return
if (!canvas || displayData.length === 0) return
const rect = canvas.getBoundingClientRect()
const mouseX = pendingMousePosition.clientX - rect.left
@@ -468,11 +309,11 @@ export const EnhancedCanvasTrafficGraph = memo(
0,
Math.min(1, relativeMouseX / effectiveWidth),
)
const dataIndex = Math.round(ratio * (data.length - 1))
const dataIndex = Math.round(ratio * (displayData.length - 1))
if (dataIndex < 0 || dataIndex >= data.length) return
if (dataIndex < 0 || dataIndex >= displayData.length) return
const dataPoint = data[dataIndex]
const dataPoint = displayData[dataIndex]
const [upValue, upUnit] = parseTraffic(dataPoint.up)
const [downValue, downUnit] = parseTraffic(dataPoint.down)
@@ -481,7 +322,7 @@ export const EnhancedCanvasTrafficGraph = memo(
? formatTrafficName(dataPoint.timestamp)
: t('home.components.traffic.unknownTime')
const { topValue: tvH, bottomValue: bvH } = yScaleRef.current
const { topValue: tvH, bottomValue: bvH } = yScale
const upY = calculateY(dataPoint.up, rect.height, tvH, bvH)
const downY = calculateY(dataPoint.down, rect.height, tvH, bvH)
const highlightY =
@@ -518,7 +359,7 @@ export const EnhancedCanvasTrafficGraph = memo(
})
})
},
[calculateY, t],
[displayData, calculateY, yScale, t],
)
const handleMouseLeave = useCallback(() => {
@@ -534,6 +375,45 @@ export const EnhancedCanvasTrafficGraph = memo(
)
}, [])
const getYAxisTicks = useCallback(
(topValue: number, bottomValue: number, height: number) => {
const formatTrafficValue = (bytes: number): string => {
if (bytes === 0) return '0'
if (bytes < 1024) return `${Math.round(bytes)}B`
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)}KB`
return `${(bytes / (1024 * 1024)).toFixed(1)}MB`
}
const padding = GRAPH_CONFIG.padding
const topY = padding.top + 10
const bottomY = height - padding.bottom - 5
const middleY = (topY + bottomY) / 2
const middleValue = (bottomValue + topValue) / 2
const ticks = [
{
value: bottomValue,
label: formatTrafficValue(bottomValue),
y: bottomY,
},
{
value: middleValue,
label: formatTrafficValue(middleValue),
y: middleY,
},
{
value: topValue,
label: formatTrafficValue(topValue),
y: topY,
},
]
return ticks
},
[],
)
const drawYAxis = useCallback(
(
ctx: CanvasRenderingContext2D,
@@ -545,6 +425,8 @@ export const EnhancedCanvasTrafficGraph = memo(
const padding = GRAPH_CONFIG.padding
const ticks = getYAxisTicks(topValue, bottomValue, height)
if (ticks.length === 0) return
ctx.save()
ticks.forEach((tick, index) => {
@@ -588,7 +470,37 @@ export const EnhancedCanvasTrafficGraph = memo(
ctx.restore()
},
[colors.grid, colors.text, colors.background],
[colors.grid, colors.text, colors.background, getYAxisTicks],
)
const getTimeDisplayStrategy = useCallback(
(timeRangeMinutes: TimeRange) => {
switch (timeRangeMinutes) {
case 1:
return {
maxLabels: 6,
formatTime: formatTrafficMinuteSecond,
intervalSeconds: 10,
minPixelDistance: 35,
}
case 5:
return {
maxLabels: 6,
formatTime: formatTrafficHourMinute,
intervalSeconds: 30,
minPixelDistance: 38,
}
case 10:
default:
return {
maxLabels: 8,
formatTime: formatTrafficHourMinute,
intervalSeconds: 60,
minPixelDistance: 40,
}
}
},
[],
)
const drawTimeAxis = useCallback(
@@ -604,7 +516,7 @@ export const EnhancedCanvasTrafficGraph = memo(
const effectiveWidth = width - padding.left - padding.right
const timeAxisY = height - padding.bottom + 14
const strategy = TIME_DISPLAY_STRATEGIES[timeRange]
const strategy = getTimeDisplayStrategy(timeRange)
ctx.save()
ctx.fillStyle = colors.text
@@ -621,13 +533,15 @@ export const EnhancedCanvasTrafficGraph = memo(
Math.ceil((data.length * minPixelDistance) / effectiveWidth),
)
resetTimeAxisPoints()
const timePoints: Array<{ index: number; x: number; label: string }> =
[]
if (data.length > 0 && data[0].timestamp) {
pushTimeAxisPoint(
padding.left,
strategy.formatTime(data[0].timestamp),
)
timePoints.push({
index: 0,
x: padding.left,
label: strategy.formatTime(data[0].timestamp),
})
}
for (
@@ -639,37 +553,41 @@ export const EnhancedCanvasTrafficGraph = memo(
if (!point.timestamp) continue
const x = padding.left + (i / (data.length - 1)) * effectiveWidth
pushTimeAxisPoint(x, strategy.formatTime(point.timestamp))
timePoints.push({
index: i,
x,
label: strategy.formatTime(point.timestamp),
})
}
if (data.length > 1 && data[data.length - 1].timestamp) {
const lastX = width - padding.right
const lastPoint = timeAxisPoints[timeAxisPoints.length - 1]
const lastPoint = timePoints[timePoints.length - 1]
if (!lastPoint || lastX - lastPoint.x >= minPixelDistance) {
pushTimeAxisPoint(
lastX,
strategy.formatTime(data[data.length - 1].timestamp),
)
timePoints.push({
index: data.length - 1,
x: lastX,
label: strategy.formatTime(data[data.length - 1].timestamp),
})
}
}
for (let i = 0; i < timeAxisPoints.length; i++) {
const point = timeAxisPoints[i]
if (i === 0) {
timePoints.forEach((point, index) => {
if (index === 0) {
ctx.textAlign = 'left'
} else if (i === timeAxisPoints.length - 1) {
} else if (index === timePoints.length - 1) {
ctx.textAlign = 'right'
} else {
ctx.textAlign = 'center'
}
ctx.fillText(point.label, point.x, timeAxisY)
}
})
ctx.restore()
},
[colors.text, timeRange],
[colors.text, timeRange, getTimeDisplayStrategy],
)
const drawGrid = useCallback(
@@ -714,7 +632,6 @@ export const EnhancedCanvasTrafficGraph = memo(
width: number,
height: number,
color: string,
gradientStops: { start: string; end: string },
withGradient = false,
topValue: number,
bottomValue: number,
@@ -738,8 +655,13 @@ export const EnhancedCanvasTrafficGraph = memo(
0,
height - padding.bottom,
)
gradient.addColorStop(0, gradientStops.start)
gradient.addColorStop(1, gradientStops.end)
gradient.addColorStop(
0,
`${color}${Math.round(GRAPH_CONFIG.alpha.gradient * 255)
.toString(16)
.padStart(2, '0')}`,
)
gradient.addColorStop(1, `${color}00`)
ctx.beginPath()
ctx.moveTo(getX(0), getY(0))
@@ -830,7 +752,6 @@ export const EnhancedCanvasTrafficGraph = memo(
const drawGraph = useCallback(() => {
const canvas = canvasRef.current
const displayData = displayDataRef.current
if (!canvas || displayData.length === 0) {
clearCanvas(canvasRef.current)
clearCanvas(hoverCanvasRef.current)
@@ -844,7 +765,7 @@ export const EnhancedCanvasTrafficGraph = memo(
// Clear using CSS dimensions; context is already scaled by DPR.
ctx.clearRect(0, 0, cssWidth, cssHeight)
const { topValue, bottomValue } = yScaleRef.current
const { topValue, bottomValue } = yScale
drawYAxis(ctx, cssWidth, cssHeight, topValue, bottomValue)
@@ -859,7 +780,6 @@ export const EnhancedCanvasTrafficGraph = memo(
cssWidth,
cssHeight,
colors.down,
colors.gradient.down,
true,
topValue,
bottomValue,
@@ -872,7 +792,6 @@ export const EnhancedCanvasTrafficGraph = memo(
cssWidth,
cssHeight,
colors.up,
colors.gradient.up,
true,
topValue,
bottomValue,
@@ -885,7 +804,9 @@ export const EnhancedCanvasTrafficGraph = memo(
)
canvas.dataset.perfDraw = String(displayData.at(-1)?.timestamp ?? 0)
}, [
displayData,
colors,
yScale,
drawYAxis,
drawGrid,
drawTimeAxis,
@@ -896,7 +817,6 @@ export const EnhancedCanvasTrafficGraph = memo(
const drawHoverOverlay = useCallback(() => {
const canvas = hoverCanvasRef.current
const displayData = displayDataRef.current
if (!canvas || displayData.length < 2) {
clearCanvas(canvas)
return
@@ -934,7 +854,7 @@ export const EnhancedCanvasTrafficGraph = memo(
ctx.restore()
}
}, [colors, syncCanvasSize, clearCanvas])
}, [displayData, colors, syncCanvasSize, clearCanvas])
const shouldSkipGraphDraw = useCallback(() => {
if (!isDocumentVisibleRef.current) return true
@@ -977,55 +897,6 @@ export const EnhancedCanvasTrafficGraph = memo(
})
}, [drawGraph, drawHoverOverlay, shouldSkipGraphDraw])
const handleSnapshot = useCallback(
(message: ITrafficWorkerSnapshotMessage) => {
const data = message.dataPoints
displayDataRef.current = data
yScaleRef.current = computeYScale(data)
if (data.length === 0) {
lastDataTimestampRef.current = 0
dataStaleRef.current = false
} else {
const latestTimestamp = data[data.length - 1]?.timestamp ?? null
if (latestTimestamp) {
lastDataTimestampRef.current = latestTimestamp
const age = Date.now() - latestTimestamp
const stale = age > STALE_DATA_THRESHOLD
dataStaleRef.current = stale
} else {
dataStaleRef.current = false
}
}
scheduleDrawGraph()
// The badge is the only snapshot content that still renders; keeping
// its state here confines re-renders to actual badge changes, and the
// visibility gate skips hidden-phase renders — the re-prime snapshot
// on regaining visibility refreshes it.
if (!isDocumentVisibleRef.current) return
setBadgeStats((prev) =>
prev.points === data.length &&
prev.compressed === message.samplerStats.compressedBufferSize
? prev
: {
points: data.length,
compressed: message.samplerStats.compressedBufferSize,
},
)
},
[computeYScale, scheduleDrawGraph],
)
const { requestRange } = useTrafficGraphDataEnhanced({
subscribe: false,
onSnapshot: handleSnapshot,
})
useEffect(() => {
requestRange(timeRange)
}, [requestRange, timeRange])
useEffect(() => {
tooltipDataRef.current = tooltipData
scheduleHoverDraw()
@@ -1095,36 +966,119 @@ export const EnhancedCanvasTrafficGraph = memo(
return (
<Box
sx={rootSx}
sx={{
width: '100%',
height: '100%',
position: 'relative',
bgcolor: 'action.hover',
borderRadius: 1,
cursor: 'pointer',
overflow: 'hidden',
}}
onClick={toggleStyle}
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
>
<canvas ref={canvasRef} style={canvasStyle} onClick={toggleStyle} />
<canvas
ref={canvasRef}
style={{
width: '100%',
height: '100%',
display: 'block',
}}
onClick={toggleStyle}
/>
{tooltipData.visible && (
<canvas ref={hoverCanvasRef} style={hoverCanvasStyle} />
<canvas
ref={hoverCanvasRef}
style={{
position: 'absolute',
inset: 0,
width: '100%',
height: '100%',
display: 'block',
pointerEvents: 'none',
}}
/>
)}
<Box sx={overlaySx}>
<Box
sx={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
pointerEvents: 'none',
}}
>
<Box
component="div"
onClick={handleTimeRangeClick}
sx={timeRangeBadgeSx}
sx={{
position: 'absolute',
top: 6,
left: 40,
fontSize: '11px',
fontWeight: 'bold',
color: 'text.secondary',
cursor: 'pointer',
pointerEvents: 'all',
px: 1,
py: 0.5,
borderRadius: 0.5,
bgcolor: 'rgba(0,0,0,0.05)',
'&:hover': {
bgcolor: 'rgba(0,0,0,0.1)',
},
}}
>
{getTimeRangeText()}
</Box>
<Box sx={legendsSx}>
<Box sx={legendSx.up}>
<Box
sx={{
position: 'absolute',
top: 6,
right: 8,
display: 'flex',
flexDirection: 'column',
gap: 0.5,
}}
>
<Box
sx={{
fontSize: '11px',
fontWeight: 'bold',
color: colors.up,
textAlign: 'right',
}}
>
{t('home.components.traffic.legends.upload')}
</Box>
<Box sx={legendSx.down}>
<Box
sx={{
fontSize: '11px',
fontWeight: 'bold',
color: colors.down,
textAlign: 'right',
}}
>
{t('home.components.traffic.legends.download')}
</Box>
</Box>
<Box sx={chartStyleHintSx}>
<Box
sx={{
position: 'absolute',
bottom: 6,
right: 8,
fontSize: '10px',
color: 'text.disabled',
opacity: 0.7,
}}
>
{t(
chartStyle === 'bezier'
? 'home.components.traffic.chartStyles.smooth'
@@ -1132,10 +1086,20 @@ export const EnhancedCanvasTrafficGraph = memo(
)}
</Box>
<Box sx={diagnosticsSx}>
<Box
sx={{
position: 'absolute',
bottom: 6,
left: 8,
fontSize: '9px',
color: 'text.disabled',
opacity: 0.6,
lineHeight: 1.2,
}}
>
{t('home.components.traffic.diagnostics', {
points: badgeStats.points,
compressed: badgeStats.compressed,
points: displayData.length,
compressed: samplerStats.compressedBufferSize,
fps: GRAPH_CONFIG.targetFPS,
})}
</Box>
@@ -1163,9 +1127,15 @@ export const EnhancedCanvasTrafficGraph = memo(
whiteSpace: 'nowrap',
}}
>
<Box sx={tooltipTimeSx}>{tooltipData.timestamp}</Box>
<Box sx={tooltipUpSx}>↑ {tooltipData.upSpeed}</Box>
<Box sx={tooltipDownSx}>↓ {tooltipData.downSpeed}</Box>
<Box sx={{ color: 'text.secondary', mb: 0.2 }}>
{tooltipData.timestamp}
</Box>
<Box sx={{ color: 'secondary.main', fontWeight: 500 }}>
↑ {tooltipData.upSpeed}
</Box>
<Box sx={{ color: 'primary.main', fontWeight: 500 }}>
↓ {tooltipData.downSpeed}
</Box>
</Box>
)}
</Box>
+6 -15
View File
@@ -131,15 +131,6 @@ const CompactStatCard = memo(
// 添加显示名称
CompactStatCard.displayName = 'CompactStatCard'
// Element identity is stable, so CompactStatCard's memo comparison holds
// across per-second parsedData updates.
const uploadSpeedIcon = <ArrowUpwardRounded fontSize="small" />
const downloadSpeedIcon = <ArrowDownwardRounded fontSize="small" />
const activeConnectionsIcon = <LinkRounded fontSize="small" />
const uploadedIcon = <CloudUploadRounded fontSize="small" />
const downloadedIcon = <CloudDownloadRounded fontSize="small" />
const memoryUsageIcon = <MemoryRounded fontSize="small" />
const fallbackSx = {
p: 2,
minHeight: 200,
@@ -261,35 +252,35 @@ export const EnhancedTrafficStats = () => {
const statCards = useMemo(() => {
const cards: StatCardProps[] = [
{
icon: uploadSpeedIcon,
icon: <ArrowUpwardRounded fontSize="small" />,
title: t('home.components.traffic.metrics.uploadSpeed'),
value: parsedData.up,
unit: `${parsedData.upUnit}/s`,
color: 'secondary' as const,
},
{
icon: downloadSpeedIcon,
icon: <ArrowDownwardRounded fontSize="small" />,
title: t('home.components.traffic.metrics.downloadSpeed'),
value: parsedData.down,
unit: `${parsedData.downUnit}/s`,
color: 'primary' as const,
},
{
icon: activeConnectionsIcon,
icon: <LinkRounded fontSize="small" />,
title: t('home.components.traffic.metrics.activeConnections'),
value: parsedData.connectionsCount,
unit: '',
color: 'success' as const,
},
{
icon: uploadedIcon,
icon: <CloudUploadRounded fontSize="small" />,
title: t('shared.labels.uploaded'),
value: parsedData.uploadTotal,
unit: parsedData.uploadTotalUnit,
color: 'secondary' as const,
},
{
icon: downloadedIcon,
icon: <CloudDownloadRounded fontSize="small" />,
title: t('shared.labels.downloaded'),
value: parsedData.downloadTotal,
unit: parsedData.downloadTotalUnit,
@@ -299,7 +290,7 @@ export const EnhancedTrafficStats = () => {
if (displayMemory) {
cards.push({
icon: memoryUsageIcon,
icon: <MemoryRounded fontSize="small" />,
title: t('home.components.traffic.metrics.memoryUsage'),
value: parsedData.inuse,
unit: parsedData.inuseUnit,
+36 -34
View File
@@ -42,39 +42,6 @@ const TrafficUnavailableFallback = () => {
)
}
// Stable identities keep the emotion sx cache effective across the ~1Hz
// traffic-driven re-renders of LayoutTraffic.
const boxStyle: Pick<BoxProps, 'sx'> = {
sx: {
display: 'flex',
alignItems: 'center',
whiteSpace: 'nowrap',
},
}
const memoryBoxStyle: Pick<BoxProps, 'sx'> = {
sx: {
...boxStyle.sx,
cursor: 'auto',
},
}
const iconStyle: Pick<SvgIconProps, 'sx'> = {
sx: { mr: '8px', fontSize: 16 },
}
const valStyle: Pick<TypographyProps, 'component' | 'sx'> = {
component: 'span',
sx: { flex: '1 1 56px', userSelect: 'none', textAlign: 'center' },
}
const unitStyle: Pick<TypographyProps, 'component' | 'color' | 'sx'> = {
component: 'span',
color: 'grey.500',
sx: {
flex: '0 1 27px',
userSelect: 'none',
fontSize: '12px',
textAlign: 'right',
},
}
export const LayoutTraffic = () => {
const { t } = useTranslation()
const { verge } = useVerge()
@@ -107,6 +74,31 @@ export const LayoutTraffic = () => {
const [down, downUnit] = parseTraffic(traffic?.down || 0)
const [inuse, inuseUnit] = parseTraffic(memory?.inuse || 0)
const boxStyle: Pick<BoxProps, 'sx'> = {
sx: {
display: 'flex',
alignItems: 'center',
whiteSpace: 'nowrap',
},
}
const iconStyle: Pick<SvgIconProps, 'sx'> = {
sx: { mr: '8px', fontSize: 16 },
}
const valStyle: Pick<TypographyProps, 'component' | 'sx'> = {
component: 'span',
sx: { flex: '1 1 56px', userSelect: 'none', textAlign: 'center' },
}
const unitStyle: Pick<TypographyProps, 'component' | 'color' | 'sx'> = {
component: 'span',
color: 'grey.500',
sx: {
flex: '0 1 27px',
userSelect: 'none',
fontSize: '12px',
textAlign: 'right',
},
}
return (
<ErrorBoundary
FallbackComponent={TrafficUnavailableFallback}
@@ -128,6 +120,9 @@ export const LayoutTraffic = () => {
<Box
title={`${t('home.components.traffic.metrics.uploadSpeed')}`}
{...boxStyle}
sx={{
...boxStyle.sx,
}}
>
<ArrowUpwardRounded
{...iconStyle}
@@ -142,6 +137,9 @@ export const LayoutTraffic = () => {
<Box
title={`${t('home.components.traffic.metrics.downloadSpeed')}`}
{...boxStyle}
sx={{
...boxStyle.sx,
}}
>
<ArrowDownwardRounded
{...iconStyle}
@@ -156,7 +154,11 @@ export const LayoutTraffic = () => {
{displayMemory && (
<Box
title={`${t('home.components.traffic.metrics.memoryUsage')} `}
{...memoryBoxStyle}
{...boxStyle}
sx={{
...boxStyle.sx,
cursor: 'auto',
}}
color={'disabled'}
>
<MemoryRounded {...iconStyle} />
+45 -58
View File
@@ -2,7 +2,6 @@ import { styled, Box } from '@mui/material'
import type { ReactNode } from 'react'
import type { SearchState } from '@/components/base'
import { buildRegex } from '@/utils/search-matcher'
const Item = styled(Box)(({ theme: { palette, typography } }) => ({
padding: '8px 0',
@@ -48,74 +47,62 @@ interface Props {
searchState?: SearchState
}
// Compiling per row multiplied by high-frequency log appends; searchState is
// React state, so identity reuse is safe until the search inputs change.
let highlightRegexCache: { state: SearchState; regex: RegExp | null } | null =
null
const getHighlightRegex = (searchState: SearchState): RegExp | null => {
if (highlightRegexCache?.state === searchState)
return highlightRegexCache.regex
const searchText = searchState.text
let pattern: string
if (searchState.useRegularExpression) {
try {
new RegExp(searchText)
pattern = searchText
} catch {
pattern = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
} else {
const escaped = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
pattern = searchState.matchWholeWord ? `\\b${escaped}\\b` : escaped
}
const flags = searchState.matchCase ? 'g' : 'gi'
const regex = buildRegex(pattern, flags)
highlightRegexCache = { state: searchState, regex }
return regex
}
const LogItem = ({ value, searchState }: Props) => {
const renderHighlightText = (text: string) => {
if (!searchState?.text.trim()) return text
const regex = getHighlightRegex(searchState)
if (!regex) return text
try {
const searchText = searchState.text
let pattern: string
const elements: ReactNode[] = []
let lastIndex = 0
let match: RegExpExecArray | null
while ((match = regex.exec(text)) !== null) {
const start = match.index
const matchText = match[0]
if (matchText === '') {
regex.lastIndex += 1
continue
if (searchState.useRegularExpression) {
try {
new RegExp(searchText)
pattern = searchText
} catch {
pattern = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
} else {
const escaped = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
pattern = searchState.matchWholeWord ? `\\b${escaped}\\b` : escaped
}
if (start > lastIndex) {
elements.push(text.slice(lastIndex, start))
const flags = searchState.matchCase ? 'g' : 'gi'
const regex = new RegExp(pattern, flags)
const elements: ReactNode[] = []
let lastIndex = 0
let match: RegExpExecArray | null
while ((match = regex.exec(text)) !== null) {
const start = match.index
const matchText = match[0]
if (matchText === '') {
regex.lastIndex += 1
continue
}
if (start > lastIndex) {
elements.push(text.slice(lastIndex, start))
}
elements.push(
<span key={`highlight-${start}`} className="highlight">
{matchText}
</span>,
)
lastIndex = start + matchText.length
}
elements.push(
<span key={`highlight-${start}`} className="highlight">
{matchText}
</span>,
)
if (lastIndex < text.length) {
elements.push(text.slice(lastIndex))
}
lastIndex = start + matchText.length
return elements.length ? elements : text
} catch {
return text
}
if (lastIndex < text.length) {
elements.push(text.slice(lastIndex))
}
return elements.length ? elements : text
}
return (
+16 -31
View File
@@ -60,23 +60,6 @@ const ProxyGroupsChain = lazy(() =>
})),
)
const SCROLL_POSITIONS_KEY = 'proxy-scroll-positions'
type ScrollPositions = Record<string, number>
let scrollPositionsCache: ScrollPositions | undefined
// Scroll handling runs per frame and is throttled to 500ms writes; keep the
// parsed object so saves do not re-read and re-parse localStorage each time.
const readScrollPositions = (): ScrollPositions | undefined => {
if (scrollPositionsCache) return scrollPositionsCache
try {
const raw = localStorage.getItem(SCROLL_POSITIONS_KEY)
if (raw) scrollPositionsCache = JSON.parse(raw) as ScrollPositions
} catch (e) {
console.error('Error restoring scroll position:', e)
}
return scrollPositionsCache
}
function useStableCallback<T extends (...args: any[]) => any>(fn: T): T {
const ref = useRef(fn)
ref.current = fn
@@ -167,12 +150,13 @@ function useProxyRenderState(
const saveScrollPosition = useCallback(
(scrollTop: number) => {
const scrollPositions = readScrollPositions() ?? {}
const scrollPositions = localStorage.getItem('proxy-scroll-positions')
? JSON.parse(localStorage.getItem('proxy-scroll-positions') ?? '{}')
: {}
scrollPositions[scrollPositionKey] = scrollTop
scrollPositionsCache = scrollPositions
try {
localStorage.setItem(
SCROLL_POSITIONS_KEY,
'proxy-scroll-positions',
JSON.stringify(scrollPositions),
)
} catch (e) {
@@ -183,10 +167,15 @@ function useProxyRenderState(
)
const getScrollPosition = useCallback(() => {
const savedPositions = readScrollPositions()
if (savedPositions) {
const savedPosition = savedPositions[scrollPositionKey]
return savedPosition ?? 0
try {
const savedPositions = localStorage.getItem('proxy-scroll-positions')
if (savedPositions) {
const positions = JSON.parse(savedPositions)
const savedPosition = positions[scrollPositionKey]
return savedPosition ?? 0
}
} catch (e) {
console.error('Error restoring scroll position:', e)
}
}, [scrollPositionKey])
@@ -251,13 +240,9 @@ function ChainProxyGroups(props: {
const rangeExtractor = useCallback(
(range: Parameters<typeof defaultRangeExtractor>[0]) => {
let activeStickyIndex: number | undefined
for (let i = stickyGroupIndexes.length - 1; i >= 0; i--) {
if (stickyGroupIndexes[i] <= range.startIndex) {
activeStickyIndex = stickyGroupIndexes[i]
break
}
}
const activeStickyIndex = [...stickyGroupIndexes]
.reverse()
.find((index) => index <= range.startIndex)
activeStickyIndexRef.current = activeStickyIndex ?? null
const indexes = defaultRangeExtractor(range)
@@ -22,7 +22,6 @@ const buildInitialValues = (verge?: IVergeConfig | null) => ({
appLogMaxSize: verge?.app_log_max_size ?? 128,
appLogMaxCount: verge?.app_log_max_count ?? 8,
autoCloseConnection: verge?.auto_close_connection ?? true,
autoSwitchSelectorGroup: verge?.auto_switch_selector_group ?? true,
autoCheckUpdate: verge?.auto_check_update ?? true,
enableBuiltinEnhanced: verge?.enable_builtin_enhanced ?? true,
proxyLayoutColumn: verge?.proxy_layout_column || 6,
@@ -56,7 +55,6 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
app_log_max_size: values.appLogMaxSize,
app_log_max_count: values.appLogMaxCount,
auto_close_connection: values.autoCloseConnection,
auto_switch_selector_group: values.autoSwitchSelectorGroup,
auto_check_update: values.autoCheckUpdate,
enable_builtin_enhanced: values.enableBuiltinEnhanced,
proxy_layout_column: values.proxyLayoutColumn,
@@ -204,28 +202,6 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
/>
</ListItem>
<ListItem
data-setting-target="settings.modals.misc.fields.autoSwitchSelectorGroup"
sx={{ padding: '5px 2px' }}
>
<ListItemText
primary={t('settings.modals.misc.fields.autoSwitchSelectorGroup')}
sx={{ maxWidth: 'fit-content' }}
/>
<TooltipIcon
title={t('settings.modals.misc.tooltips.autoSwitchSelectorGroup')}
sx={{ opacity: '0.7' }}
/>
<Switch
edge="end"
checked={values.autoSwitchSelectorGroup}
onChange={(_, c) =>
setValues((v) => ({ ...v, autoSwitchSelectorGroup: c }))
}
sx={{ marginLeft: 'auto' }}
/>
</ListItem>
<ListItem
data-setting-target="settings.modals.misc.fields.autoCheckUpdate"
sx={{ padding: '5px 2px' }}
@@ -480,8 +480,6 @@ const settingsCatalog: readonly SettingEntry[] = [
'settings.modals.misc.fields.appLogMaxCount': 'app log max count',
'settings.modals.misc.fields.autoCloseConnections':
'auto close connections',
'settings.modals.misc.fields.autoSwitchSelectorGroup':
'auto switch select group',
'settings.modals.misc.fields.autoCheckUpdate': 'auto check update',
'settings.modals.misc.fields.enableBuiltinEnhanced':
'enable builtin enhanced',
+7 -18
View File
@@ -158,11 +158,9 @@ const EMPTY_DATA: ITrafficDataPoint[] = []
export const useTrafficMonitorEnhanced = (options?: {
subscribe?: boolean
enabled?: boolean
onSnapshot?: (message: ITrafficWorkerSnapshotMessage) => void
}) => {
const subscribeToSnapshots = options?.subscribe ?? true
const enabled = options?.enabled ?? true
const onSnapshot = options?.onSnapshot
const isVisible = useVisibility()
const [latestSnapshot, setLatestSnapshot] = useState<{
dataPoints: ITrafficDataPoint[]
@@ -176,8 +174,6 @@ export const useTrafficMonitorEnhanced = (options?: {
const currentRangeRef = useRef<number>(WORKER_CONFIG.defaultRangeMinutes)
const isVisibleRef = useRef(isVisible)
isVisibleRef.current = isVisible
const onSnapshotRef = useRef(onSnapshot)
onSnapshotRef.current = onSnapshot
// 注册引用计数与Worker生命周期
useEffect(() => {
@@ -190,12 +186,9 @@ export const useTrafficMonitorEnhanced = (options?: {
client.start(currentRangeRef.current)
let unsubscribe: (() => void) | undefined
if (subscribeToSnapshots || onSnapshot) {
if (subscribeToSnapshots) {
unsubscribe = client.onSnapshot((message) => {
// onSnapshot is the always-live channel (ignores visibility); the
// state mirror below keeps its original always-latest contract.
onSnapshotRef.current?.(message)
if (!subscribeToSnapshots || !isVisibleRef.current) return
if (!isVisibleRef.current) return
setLatestSnapshot({
dataPoints: message.dataPoints,
samplerStats: message.samplerStats,
@@ -210,14 +203,14 @@ export const useTrafficMonitorEnhanced = (options?: {
client.stop()
}
}
}, [enabled, subscribeToSnapshots, onSnapshot])
}, [enabled, subscribeToSnapshots])
// Re-prime snapshot ingestion after every visible transition
useEffect(() => {
if (enabled && isVisible && (subscribeToSnapshots || onSnapshot)) {
if (enabled && subscribeToSnapshots && isVisible) {
clientRef.current?.requestSnapshot()
}
}, [enabled, subscribeToSnapshots, onSnapshot, isVisible])
}, [enabled, subscribeToSnapshots, isVisible])
// 添加流量数据
const appendData = useCallback(
@@ -251,12 +244,8 @@ export const useTrafficMonitorEnhanced = (options?: {
/**
* 图表数据Hook
*/
export const useTrafficGraphDataEnhanced = (options?: {
subscribe?: boolean
enabled?: boolean
onSnapshot?: (message: ITrafficWorkerSnapshotMessage) => void
}) => {
const { graphData, samplerStats } = useTrafficMonitorEnhanced(options)
export const useTrafficGraphDataEnhanced = () => {
const { graphData, samplerStats } = useTrafficMonitorEnhanced()
return {
...graphData,
-2
View File
@@ -411,7 +411,6 @@
"appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "إغلاق الاتصالات تلقائيًا",
"autoSwitchSelectorGroup": "تبديل مجموعة select تلقائيًا",
"autoCheckUpdate": "فحص التحديث تلقائيًا",
"enableBuiltinEnhanced": "تفعيل التحسين المدمج",
"proxyLayoutColumns": "أعمدة عرض الوكيل",
@@ -423,7 +422,6 @@
},
"tooltips": {
"autoCloseConnections": "إنهاء الاتصالات القائمة عند تغيير اختيار مجموعة الوكيل أو وضع الوكيل",
"autoSwitchSelectorGroup": "في وضع القواعد، عند اختيار عقدة في مجموعة url-test أو fallback يتم أيضًا تحويل أول مجموعة select تحتوي عليها إلى تلك المجموعة",
"enableBuiltinEnhanced": "معالجة توافق ملف التكوين",
"autoDelayDetection": "يختبر زمن استجابة العقدة الحالية على نحو دوري في الخلفية",
"defaultLatencyTest": "يُستخدم فقط لاختبار طلب HTTP العميل. لن يؤثر على ملف التكوين"
-2
View File
@@ -411,7 +411,6 @@
"appLogMaxSize": "Maximale Größe des Anwendungsprotokolls",
"appLogMaxCount": "Maximale Anzahl der Anwendungsprotokolle",
"autoCloseConnections": "Verbindungen automatisch schließen",
"autoSwitchSelectorGroup": "Select-Gruppe automatisch umschalten",
"autoCheckUpdate": "Automatisch auf Updates prüfen",
"enableBuiltinEnhanced": "Eingebaute Verbesserungen aktivieren",
"proxyLayoutColumns": "Anzahl der Spalten im Proxy-Layout",
@@ -423,7 +422,6 @@
},
"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.",
"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."
-2
View File
@@ -411,7 +411,6 @@
"appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "Auto Close Connections",
"autoSwitchSelectorGroup": "Auto Switch Select Group",
"autoCheckUpdate": "Auto Check Update",
"enableBuiltinEnhanced": "Enable Builtin Enhanced",
"proxyLayoutColumns": "Proxy Layout Columns",
@@ -423,7 +422,6 @@
},
"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",
"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"
-2
View File
@@ -411,7 +411,6 @@
"appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "Cerrar conexiones automáticamente",
"autoSwitchSelectorGroup": "Cambiar grupo select automáticamente",
"autoCheckUpdate": "Comprobar actualizaciones automáticamente",
"enableBuiltinEnhanced": "Habilitar funciones mejoradas integradas",
"proxyLayoutColumns": "Número de columnas en la disposición de la página de proxy",
@@ -423,7 +422,6 @@
},
"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.",
"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."
-2
View File
@@ -411,7 +411,6 @@
"appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "بستن خودکار اتصالات",
"autoSwitchSelectorGroup": "تغییر خودکار گروه select",
"autoCheckUpdate": "بررسی خودکار به‌روزرسانی",
"enableBuiltinEnhanced": "فعال کردن تقویت داخلی",
"proxyLayoutColumns": "ستون چیدمان پراکسی",
@@ -423,7 +422,6 @@
},
"tooltips": {
"autoCloseConnections": "اتصالات برقرار شده را هنگام تغییر انتخاب گروه پروکسی یا حالت پروکسی خاتمه دهید",
"autoSwitchSelectorGroup": "در حالت قانون، با انتخاب یک گره در گروه url-test یا fallback، اولین گروه select شامل آن نیز به همان گروه تغییر می‌کند",
"enableBuiltinEnhanced": "مدیریت سازگاری برای فایل پیکربندی",
"autoDelayDetection": "به‌صورت دوره‌ای تأخیر گره فعلی را در پس‌زمینه آزمایش می‌کند",
"defaultLatencyTest": "فقط برای تست درخواست‌های کلاینت HTTP استفاده می‌شود و بر فایل پیکربندی تأثیری نخواهد داشت"
-2
View File
@@ -411,7 +411,6 @@
"appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "Tutup Koneksi Otomatis",
"autoSwitchSelectorGroup": "Alihkan Grup Select Otomatis",
"autoCheckUpdate": "Periksa Pembaruan Otomatis",
"enableBuiltinEnhanced": "Aktifkan Peningkatan Bawaan",
"proxyLayoutColumns": "Kolom Tata Letak Proksi",
@@ -423,7 +422,6 @@
},
"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",
"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"
-2
View File
@@ -411,7 +411,6 @@
"appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "接続を自動的に閉じる",
"autoSwitchSelectorGroup": "ノード選択時にグループを連動",
"autoCheckUpdate": "自動更新チェック",
"enableBuiltinEnhanced": "組み込み拡張機能を有効にする",
"proxyLayoutColumns": "プロキシページのレイアウト列数",
@@ -423,7 +422,6 @@
},
"tooltips": {
"autoCloseConnections": "プロキシグループで選択されたノードまたはプロキシモードが変更されたときに、既存の接続を閉じます。",
"autoSwitchSelectorGroup": "ルールモードで url-test または fallback グループのノードを選択すると、そのグループを含む最初の select グループも当該グループに切り替えます。",
"enableBuiltinEnhanced": "設定ファイルの互換性処理",
"autoDelayDetection": "バックグラウンドで現在のノードのレイテンシーを定期的にテストします",
"defaultLatencyTest": "HTTPクライアントリクエストテストにのみ使用され、設定ファイルには影響しません。"
-2
View File
@@ -411,7 +411,6 @@
"appLogMaxSize": "앱 로그 최대 크기",
"appLogMaxCount": "앱 로그 최대 개수",
"autoCloseConnections": "연결 자동 종료",
"autoSwitchSelectorGroup": "노드 선택 시 그룹 연동",
"autoCheckUpdate": "업데이트 자동 확인",
"enableBuiltinEnhanced": "내장 향상 기능 사용",
"proxyLayoutColumns": "프록시 레이아웃 열 수",
@@ -423,7 +422,6 @@
},
"tooltips": {
"autoCloseConnections": "프록시 그룹 선택 또는 프록시 모드 변경 시 기존 연결을 종료합니다",
"autoSwitchSelectorGroup": "규칙 모드에서 url-test 또는 fallback 그룹의 노드를 선택하면 해당 그룹을 포함하는 첫 번째 select 그룹도 그 그룹으로 전환합니다",
"enableBuiltinEnhanced": "구성 파일에 대한 호환성 처리를 수행합니다",
"autoDelayDetection": "백그라운드에서 현재 노드의 지연을 주기적으로 검사합니다",
"defaultLatencyTest": "HTTP 클라이언트 요청 테스트에만 사용되며 구성 파일에는 영향을 주지 않습니다"
-2
View File
@@ -411,7 +411,6 @@
"appLogMaxSize": "Tamanho Máximo do Log do Aplicativo",
"appLogMaxCount": "Quantidade Máxima de Logs do Aplicativo",
"autoCloseConnections": "Fechar Conexões Automaticamente",
"autoSwitchSelectorGroup": "Alternar Grupo Select Automaticamente",
"autoCheckUpdate": "Verificar Atualizações Automaticamente",
"enableBuiltinEnhanced": "Ativar Aprimoramento Integrado",
"proxyLayoutColumns": "Colunas do Layout de Proxy",
@@ -423,7 +422,6 @@
},
"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",
"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"
-2
View File
@@ -411,7 +411,6 @@
"appLogMaxSize": "Максимальный размер журнала приложения",
"appLogMaxCount": "Максимальное количество файлов журнала",
"autoCloseConnections": "Автоматическое закрытие соединений",
"autoSwitchSelectorGroup": "Автопереключение группы select",
"autoCheckUpdate": "Автоматическая проверка обновлений",
"enableBuiltinEnhanced": "Включить встроенные улучшения",
"proxyLayoutColumns": "Количество столбцов в макете прокси",
@@ -423,7 +422,6 @@
},
"tooltips": {
"autoCloseConnections": "Закрывать установленные соединения при изменении выбора группы прокси или режима прокси",
"autoSwitchSelectorGroup": "В режиме правил при выборе узла в группе url-test или fallback первая группа select, содержащая эту группу, также переключается на неё",
"enableBuiltinEnhanced": "Обработка совместимости для файла конфигурации",
"autoDelayDetection": "Периодически проверяет задержку текущего узла в фоновом режиме",
"defaultLatencyTest": "Используется только для тестирования HTTP-запросов клиента и не влияет на файл конфигурации"
-2
View File
@@ -411,7 +411,6 @@
"appLogMaxSize": "Uygulama Günlüğü En Büyük Boyutu",
"appLogMaxCount": "Uygulama Günlüğü En Fazla Dosya Sayısı",
"autoCloseConnections": "Bağlantıları Otomatik Kapat",
"autoSwitchSelectorGroup": "Select Grubunu Otomatik Değiştir",
"autoCheckUpdate": "Otomatik Güncelleme Kontrolü",
"enableBuiltinEnhanced": "Yerleşik Geliştirilmiş Modu Etkinleştir",
"proxyLayoutColumns": "Vekil Düzeni Sütunları",
@@ -423,7 +422,6 @@
},
"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",
"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"
-2
View File
@@ -411,7 +411,6 @@
"appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "Тоташуларны автоматик ябу",
"autoSwitchSelectorGroup": "Select төркемен автоматик күчерү",
"autoCheckUpdate": "Яңартуларны автоматик тикшерү",
"enableBuiltinEnhanced": "Эчке камилләштерүне кабызу",
"proxyLayoutColumns": "Прокси күрсәтү баганалары саны",
@@ -423,7 +422,6 @@
},
"tooltips": {
"autoCloseConnections": "Прокси төркеме яисә режимын үзгәрткәндә актив тоташуларны өзү",
"autoSwitchSelectorGroup": "Кагыйдәләр режимында url-test яки fallback төркемендә төен сайлаганда, аны эченә алган беренче select төркеме дә шул төркемгә күчә",
"enableBuiltinEnhanced": "Конфигурация файлы белән туры килә торган өстәмә оптимизация",
"autoDelayDetection": "Фон режимында хәзерге төен тоткарлыгын периодик тикшерә",
"defaultLatencyTest": "Бу фәкать клиентның HTTP сораулары тесты өчен кулланыла, конфигурация файлына йогынты ясамый"
-2
View File
@@ -411,7 +411,6 @@
"appLogMaxSize": "应用日志最大大小",
"appLogMaxCount": "应用日志最大数量",
"autoCloseConnections": "自动关闭连接",
"autoSwitchSelectorGroup": "选择节点时联动代理组",
"autoCheckUpdate": "自动检查更新",
"enableBuiltinEnhanced": "内置增强功能",
"proxyLayoutColumns": "代理页布局列数",
@@ -423,7 +422,6 @@
},
"tooltips": {
"autoCloseConnections": "当代理组选中节点或代理模式变动时,关闭已建立的连接",
"autoSwitchSelectorGroup": "规则模式下,在 url-test 或 fallback 代理组中选择节点时,将首个包含该组的 select 代理组切换到该组",
"enableBuiltinEnhanced": "配置文件的兼容性处理",
"autoDelayDetection": "后台定时检测当前节点延迟",
"defaultLatencyTest": "仅用于 HTTP 客户端请求测试,不会对配置文件产生影响"
-2
View File
@@ -411,7 +411,6 @@
"appLogMaxSize": "應用程式日誌最大大小",
"appLogMaxCount": "應用程式日誌最大數量",
"autoCloseConnections": "自動關閉連線",
"autoSwitchSelectorGroup": "選擇節點時聯動代理組",
"autoCheckUpdate": "自動檢查更新",
"enableBuiltinEnhanced": "內建增強功能",
"proxyLayoutColumns": "代理頁面欄數",
@@ -423,7 +422,6 @@
},
"tooltips": {
"autoCloseConnections": "當代理組選中節點或代理模式變動時,關閉已建立的連線",
"autoSwitchSelectorGroup": "規則模式下,在 url-test 或 fallback 代理組中選擇節點時,將首個包含該組的 select 代理組切換到該組",
"enableBuiltinEnhanced": "配置檔案的相容性處理",
"autoDelayDetection": "在背景定時偵測目前節點延遲",
"defaultLatencyTest": "僅用於 HTTP 客戶端請求測試,不會對配置檔案產生影響"
-4
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) =>
@@ -418,7 +416,6 @@ export type IVerge_Deserialize = {
enable_global_hotkey?: boolean | null
home_cards?: JsonValue | null
auto_close_connection?: boolean | null
auto_switch_selector_group?: boolean | null
auto_check_update?: boolean | null
default_latency_test?: string | null
default_latency_timeout?: number | null
@@ -509,7 +506,6 @@ export type IVerge_Serialize = {
enable_global_hotkey: boolean | null
home_cards: JsonValue | null
auto_close_connection: boolean | null
auto_switch_selector_group: boolean | null
auto_check_update: boolean | null
default_latency_test: string | null
default_latency_timeout: number | null
-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) {
-17
View File
@@ -19,13 +19,6 @@ let currentRangeMinutes!: number
let throttleTimer: ReturnType<typeof setTimeout> | null = null
let lastTimestamp: number | undefined
let lastBroadcast: ITrafficDataPoint[] = []
let lastSamplerVersion = 0
// The slice for `minutes` can only change without new samples when its oldest
// point ages past the range cutoff.
const agedPastRange = (reference: ITrafficDataPoint[], minutes: number) =>
reference.length > 0 &&
Date.now() - reference[0].timestamp >= minutes * 60 * 1000
const broadcastSnapshot = () => {
const dataPoints = sampler.getDataForTimeRange(currentRangeMinutes)
@@ -40,7 +33,6 @@ const broadcastSnapshot = () => {
ctx.postMessage(message)
lastBroadcast = dataPoints
lastSamplerVersion = sampler.getVersion()
}
const scheduleSnapshot = () => {
@@ -63,18 +55,9 @@ ctx.onmessage = (event: MessageEvent<TrafficWorkerRequestMessage>) => {
// no handle needed, worker teardown (terminate) drops pending timers
ctx.setInterval(() => {
if (throttleTimer !== null) return
const version = sampler.getVersion()
if (
version === lastSamplerVersion &&
!agedPastRange(lastBroadcast, currentRangeMinutes)
) {
return
}
const slice = sampler.getDataForTimeRange(currentRangeMinutes)
if (!isSameTrafficData(lastBroadcast, slice)) {
broadcastSnapshot()
} else {
lastSamplerVersion = version
}
}, 1000)
broadcastSnapshot()
-2
View File
@@ -652,7 +652,6 @@ export const translationKeys = [
'settings.modals.misc.fields.appLogMaxSize',
'settings.modals.misc.fields.appLogMaxCount',
'settings.modals.misc.fields.autoCloseConnections',
'settings.modals.misc.fields.autoSwitchSelectorGroup',
'settings.modals.misc.fields.autoCheckUpdate',
'settings.modals.misc.fields.enableBuiltinEnhanced',
'settings.modals.misc.fields.proxyLayoutColumns',
@@ -662,7 +661,6 @@ export const translationKeys = [
'settings.modals.misc.fields.defaultLatencyTest',
'settings.modals.misc.fields.defaultLatencyTimeout',
'settings.modals.misc.tooltips.autoCloseConnections',
'settings.modals.misc.tooltips.autoSwitchSelectorGroup',
'settings.modals.misc.tooltips.enableBuiltinEnhanced',
'settings.modals.misc.tooltips.autoDelayDetection',
'settings.modals.misc.tooltips.defaultLatencyTest',
-2
View File
@@ -1123,7 +1123,6 @@ export interface TranslationResources {
autoDelayDetection: string
autoDelayDetectionInterval: string
autoLogClean: string
autoSwitchSelectorGroup: string
defaultLatencyTest: string
defaultLatencyTimeout: string
enableBuiltinEnhanced: string
@@ -1142,7 +1141,6 @@ export interface TranslationResources {
tooltips: {
autoCloseConnections: string
autoDelayDetection: string
autoSwitchSelectorGroup: string
defaultLatencyTest: string
enableBuiltinEnhanced: string
}
+2 -29
View File
@@ -7,33 +7,14 @@ interface ICompressedDataPoint {
const pad2 = (value: number) => value.toString().padStart(2, '0')
// Time labels are derived once per 1Hz timestamp and redrawn several times per
// second; the bounded cache keeps axis drawing allocation-free in steady state.
const TIME_LABEL_CACHE_LIMIT = 1024
const hourMinuteLabels = new Map<number, string>()
const minuteSecondLabels = new Map<number, string>()
export const formatTrafficHourMinute = (timestamp: number) => {
const cached = hourMinuteLabels.get(timestamp)
if (cached !== undefined) return cached
const date = new Date(timestamp)
const label = `${pad2(date.getHours())}:${pad2(date.getMinutes())}`
if (hourMinuteLabels.size >= TIME_LABEL_CACHE_LIMIT) hourMinuteLabels.clear()
hourMinuteLabels.set(timestamp, label)
return label
return `${pad2(date.getHours())}:${pad2(date.getMinutes())}`
}
export const formatTrafficMinuteSecond = (timestamp: number) => {
const cached = minuteSecondLabels.get(timestamp)
if (cached !== undefined) return cached
const date = new Date(timestamp)
const label = `${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`
if (minuteSecondLabels.size >= TIME_LABEL_CACHE_LIMIT)
minuteSecondLabels.clear()
minuteSecondLabels.set(timestamp, label)
return label
return `${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`
}
export const formatTrafficName = (timestamp: number) => {
@@ -72,12 +53,10 @@ export class TrafficDataSampler {
private compressedBuffer: ICompressedDataPoint[] = []
private compressedHead = 0
private compressionQueue: ITrafficDataPoint[] = []
private version = 0
constructor(private config: ISamplingConfig) {}
addDataPoint(point: ITrafficDataPoint) {
this.version++
this.rawBuffer.push(point)
const rawCutoff = Date.now() - this.config.rawDataMinutes * 60 * 1000
@@ -188,13 +167,7 @@ export class TrafficDataSampler {
}
}
/** Bumped by every mutation (added points, compression, aging trims, clear). */
getVersion(): number {
return this.version
}
clear() {
this.version++
this.rawBuffer = []
this.rawHead = 0
this.compressedBuffer = []