Compare commits

..
Author SHA1 Message Date
Tunglies 4969630f57 test(perf): add proxy scroll scene to the perf adapter
Adds a proxy page scenario to the measurement adapter: a core-module
shim serves synthetic proxy/clash/run-state data at the invoke seam
(active only for the proxy scenario; other scenarios stay
byte-identical), and a sawtooth scroll driver keeps the virtualizer
measuring and the throttled scroll-position save running. Running the
scene additionally requires the harness-side scenario contract and
schema v10 from the clash-verge-rev-harness repository.
2026-11-19 10:16:06 +08:00
Tunglies 50fd66925a perf(proxy): reuse the parsed scroll-position snapshot and drop per-frame copies
The sticky-index lookup copied and reversed its array per range
extraction and every throttled save re-read and re-parsed the same
localStorage payload; the reverse scan is now allocation-free and the
parse goes through one read-through snapshot.
2026-11-19 10:09:59 +08:00
Tunglies 5d2e69ba6c perf(log): compile the highlight regex once per search state
Each visible row recompiled (and re-escaped) the same regex three times
per render while logs stream in; the compiled regex is now cached per
search state identity.
2026-11-19 10:09:57 +08:00
Tunglies 71444c9815 perf(ui): hoist static icons and style identities in traffic widgets
Stat-card icons were rebuilt per parsed-data update, defeating the
memoized card comparison, and the layout traffic widget reallocated its
style objects (with a redundant double sx spread) on every tick.
2026-11-19 10:09:55 +08:00
Tunglies 02a1998b8d perf(home): draw the traffic graph from refs instead of per-snapshot state
Worker snapshots re-rendered the whole graph tree per update and the
sampler sliced its full buffer every second just to compare for
equality. Snapshots now feed display data and the y-scale through refs
(React state only tracks the diagnostics badge inputs, skipped while
hidden), the draw callback chain is identity-stable, per-draw axis
ticks/labels and gradient strings go through pooled buffers and bounded
caches, and the sampler version counter plus an oldest-point age check
let the idle poll skip unchanged slices.
2026-11-19 10:09:44 +08:00
星海and❤是纱雾酱哟~ 3f7af9ab02 fix(media-unlock): avoid misleading region for Muse AI in Rule mode (#8685)
* fix(media-unlock): avoid misleading region from cloudflare trace for Muse AI

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>

* chore(changelog): append missing statements

- Simply express what has changed in `Changelog.md`

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

---------

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
Co-authored-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
2026-11-19 01:24:54 +00:00
wonfen 7b7a5947b9 feat(home): follow url-test/fallback groups picked on the node card
The card lists fallback groups again, and switching it to a url-test or
fallback group points the first select group at it without fixing a node.
2026-11-19 01:57:09 +08:00
wonfen 54119cb187 feat(proxy): follow url-test/fallback picks with the first select group
In rule mode, picking a node in a url-test or fallback group also points the first select group listing it at that group. Toggle in Misc settings, on by default.
2026-11-19 01:57:08 +08:00
renovate[bot]renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>❤是纱雾酱哟~
2e786bf2c9 chore(deps): update github/gh-aw-actions action to v1.3.1 (#8686)
* chore(deps): update github/gh-aw-actions action to v1.3.1

* chore(deps): update gh-aw extension version to v1.3.1

- Also bump version value of `with.version`

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>

* chore: update gh-aw to version 1.3.1

- Updated `gh-aw` version from `1.3.0` to `1.3.1` in workflow configuration

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>

* chore(gh-aw): update allowed network identifiers for better maintainability

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>

* feat(gh-aw): update model routing logic

Rather than judging auto-routing standard by GitHub Copilot itself, explicitly set the cost level to "economy" to
reduce AI Credits costs of one collaborator's classic PAT.

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>

---------

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
2026-11-18 15:21:01 +00:00
❤是纱雾酱哟~andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 4890f8eaa7 chore(deps): update dependency pnpm to v12.21.0 (#8687)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-18 14:31:52 +00:00
HowGeGe 60456a2c84 fix(settings): highlight control rows on hover (#8313) 2026-11-18 13:59:08 +00:00
Tunglies 7d8fec7314 chore(lint): inherit workspace lints in draft and logging crates
clash-verge-draft and clash-verge-logging did not inherit
[workspace.lints], so cargo's missing_lints_inheritance warned and the
strict clippy set never applied to them. Inheriting the lints surfaced
six errors, now fixed:

- draft: drop the data lock before cloning the snapshot and before
  returning in with_data_modify (significant_drop_tightening)
- draft: require T: Send + Sync on acquire_data_modify_permit so its
  future is Send (future_not_send)
- draft bench: scope an allow for the runtime-init panic
- logging: make Logger::new const (missing_const_for_fn)
- logging: return the builder directly from generate_file_log_writer,
  which never failed (unnecessary_wraps)

The three unused-dependency warnings that remain under
--all-features are cfg artifacts, not dead deps: tauri-build is only
called when the clippy feature is off, tauri-plugin-devtools is
compiled out when tokio-trace is enabled alongside tauri-dev, and
clash-verge-logging in clash-verge-signal is only referenced by the
Linux-only body of that crate.
2026-11-18 09:45:36 +08:00
Tunglies 16667137a7 perf(backend): cache chain items and guard runtime yaml re-serialization (#8676)
* perf(enhance): cache chain items by file identity

Every config generation re-read and re-parsed all seven chain files.
Cache the parsed ChainItem keyed by (path, mtime, length) and clone on
hit: measured 486us -> 20us per generation (-95.9%) on a seven-file
chain set (merge/script/rules fixtures). Profile saves go through
tmp+rename so mtime always changes.

* perf(config): guard runtime yaml re-serialization

runtime_config_yaml re-serialized the multi-megabyte runtime Mapping on
every call even when unchanged. Hash the Mapping tree (Value: Hash) and
return the cached Arc<String> handle on hit: 4.10ms -> ~0.39ms (hash
290us, ~-90%) for a 3000-node config on the unchanged path, and the
handle keeps both hit and miss at a refcount clone instead of copying
the yaml body. The 64-bit SipHash key is sound here: a birthday
collision needs ~2^32 distinct config states at a volume of a few
hundred generations per day, and a colliding pair only serves one stale
yaml until the next config change re-hashes.

* build(deps): bump tauri-plugin-mihomo to 0.7.1

Pins the revision that derives Clone on ProxyType and DelayHistory,
which the upcoming proxy-view cache needs to return cached views
without changing the IPC contract.

* refactor(backend): right-size the new caches' storage

The chain cache never shares its stored ChainItem -- every hit
deep-clones it -- so its Arc wrapper only added indirection; store it
directly and const-shape it behind a LazyLock static instead of a
OnceLock accessor. The yaml cache keeps Arc<String> because callers
receive the stored handle, making hit and miss clones O(1).

* style(config): hoist the runtime yaml cache to module scope

Match the module-level placement of the chain cache and the other
named statics; the closure-local declaration shadowed nothing but read
worse and forced rustfmt to split the line.
2026-11-18 09:45:36 +08:00
66 changed files with 1380 additions and 795 deletions
+1 -1
View File
@@ -5,7 +5,7 @@
"features": { "features": {
"ghcr.io/devcontainers/features/node:2": { "ghcr.io/devcontainers/features/node:2": {
"version": "26.13.1", "version": "26.13.1",
"pnpmVersion": "12.18.0" "pnpmVersion": "12.21.0"
}, },
"ghcr.io/devcontainers/features/rust:1": { "ghcr.io/devcontainers/features/rust:1": {
"version": "1.100.0", "version": "1.100.0",
+3 -3
View File
@@ -5,10 +5,10 @@
"version": "v9.0.0", "version": "v9.0.0",
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3" "sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
}, },
"github/gh-aw-actions/setup@v1.3.0": { "github/gh-aw-actions/setup@v1.3.1": {
"repo": "github/gh-aw-actions/setup", "repo": "github/gh-aw-actions/setup",
"version": "v1.3.0", "version": "v1.3.1",
"sha": "8126d6cb07dea9221848de275af8a41474d839ca" "sha": "dfe97a19c8249d41e2adfc95f92db2b8facea58f"
} }
}, },
"containers": { "containers": {
+2 -2
View File
@@ -31,9 +31,9 @@ jobs:
with: with:
persist-credentials: false persist-credentials: false
- name: Install gh-aw extension - name: Install gh-aw extension
uses: github/gh-aw-actions/setup-cli@8126d6cb07dea9221848de275af8a41474d839ca # v1.3.0 uses: github/gh-aw-actions/setup-cli@dfe97a19c8249d41e2adfc95f92db2b8facea58f # v1.3.1
with: with:
version: v1.3.0 version: v1.3.1
- name: Install Rust Stable - name: Install Rust Stable
uses: dtolnay/rust-toolchain@stable uses: dtolnay/rust-toolchain@stable
with: with:
File diff suppressed because one or more lines are too long
+4
View File
@@ -30,6 +30,10 @@ max-ai-credits: 60
max-turns: 12 max-turns: 12
max-daily-ai-credits: 5000 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: permissions:
issues: read issues: read
pull-requests: read pull-requests: read
File diff suppressed because one or more lines are too long
+3
View File
@@ -26,6 +26,9 @@ imports:
max-ai-credits: 60 max-ai-credits: 60
max-turns: 12 max-turns: 12
max-daily-ai-credits: 500 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: permissions:
contents: read contents: read
issues: read issues: read
File diff suppressed because one or more lines are too long
+6 -1
View File
@@ -32,8 +32,13 @@ permissions:
max-ai-credits: 60 max-ai-credits: 60
max-turns: 12 max-turns: 12
max-daily-ai-credits: 500 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: network:
allowed: [github, docs.rs, doc.rust-lang.org, nodejs.org, www.typescriptlang.org] # 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]
steps: steps:
- name: Load trusted metadata parser - name: Load trusted metadata parser
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+1 -1
View File
@@ -1,3 +1,3 @@
nodejs 26.13.1 nodejs 26.13.1
pnpm 12.18.0 pnpm 12.21.0
rust 1.100.0 rust 1.100.0
Generated
+2 -2
View File
@@ -7545,8 +7545,8 @@ dependencies = [
[[package]] [[package]]
name = "tauri-plugin-mihomo" name = "tauri-plugin-mihomo"
version = "0.7.0" version = "0.7.1"
source = "git+https://github.com/clash-verge-rev/tauri-plugin-mihomo?rev=e49bbedcc67d60da2c10e81bc6433b0f8e8fa232#e49bbedcc67d60da2c10e81bc6433b0f8e8fa232" source = "git+https://github.com/clash-verge-rev/tauri-plugin-mihomo?rev=7e4fa8642cf6c394ed88b5a969420d8eab60087f#7e4fa8642cf6c394ed88b5a969420d8eab60087f"
dependencies = [ dependencies = [
"arc-swap", "arc-swap",
"clashmap", "clashmap",
+5
View File
@@ -38,6 +38,7 @@
- 修复「连接」页表格排序时表头换行、标题位置跳动 - 修复「连接」页表格排序时表头换行、标题位置跳动
- 修复「TUN 设置」未手动保存时,界面显示的默认 MTU 1500 未生效 - 修复「TUN 设置」未手动保存时,界面显示的默认 MTU 1500 未生效
- 修复「链式代理」节点列表按名称排序,未保持订阅中的节点顺序 - 修复「链式代理」节点列表按名称排序,未保持订阅中的节点顺序
- 修复规则模式下 Muse AI 解锁检测显示错误的出口地区
**🍎 macOS** **🍎 macOS**
@@ -55,6 +56,7 @@
<summary><strong> ✨ 新增功能 </strong></summary> <summary><strong> ✨ 新增功能 </strong></summary>
- 新增连接页面按网络协议(TCP/UDP)筛选连接 - 新增连接页面按网络协议(TCP/UDP)筛选连接
- 新增规则模式下在 `url-test` 或 `fallback` 代理组选节点时,自动将首个包含该组的 `select` 代理组切换到该组,可在「杂项设置」关闭
</details> </details>
@@ -63,6 +65,9 @@
- 优化连接、规则和日志筛选:切换页面后保留过滤条件 - 优化连接、规则和日志筛选:切换页面后保留过滤条件
- 优化全局模式代理列表:仅显示 `GLOBAL` 节点,选中其中的策略组时才显示该组 - 优化全局模式代理列表:仅显示 `GLOBAL` 节点,选中其中的策略组时才显示该组
- 优化设置页开关和选项所在行的鼠标悬停高亮,便于对应说明与控件
- 优化首页「当前节点」卡片:代理组列表加入 `fallback` 代理组,切换到 `url-test` 或 `fallback` 代理组时同样联动 `select` 代理组
- 优化主页流量图表与日志、代理列表的实时刷新和滚动占用,降低高频更新时的 CPU 负载
**🍎 macOS** **🍎 macOS**
+3
View File
@@ -15,3 +15,6 @@ tokio = { workspace = true }
[dev-dependencies] [dev-dependencies]
criterion = { workspace = true } criterion = { workspace = true }
[lints]
workspace = true
@@ -19,6 +19,7 @@ fn make_draft() -> Draft<IVerge> {
} }
pub fn bench_draft(c: &mut Criterion) { pub fn bench_draft(c: &mut Criterion) {
#[allow(clippy::panic, reason = "bench setup cannot proceed without a runtime")]
let rt = Runtime::new().unwrap_or_else(|e| panic!("Tokio runtime init failed: {e}")); let rt = Runtime::new().unwrap_or_else(|e| panic!("Tokio runtime init failed: {e}"));
let mut group = c.benchmark_group("draft"); let mut group = c.benchmark_group("draft");
+6 -1
View File
@@ -102,6 +102,7 @@ impl<T: Clone> Draft<T> {
let (local, original_arc) = { let (local, original_arc) = {
let guard = self.inner.data.lock(); let guard = self.inner.data.lock();
let arc = Arc::clone(&guard.0); let arc = Arc::clone(&guard.0);
drop(guard);
((**arc).clone(), arc) ((**arc).clone(), arc)
}; };
let (new_local, res) = f(local).await?; let (new_local, res) = f(local).await?;
@@ -112,6 +113,7 @@ impl<T: Clone> Draft<T> {
)); ));
} }
guard.0 = Arc::new(Box::new(new_local)); guard.0 = Arc::new(Box::new(new_local));
drop(guard);
Ok(res) Ok(res)
} }
@@ -125,7 +127,10 @@ impl<T: Clone> Draft<T> {
} }
#[inline] #[inline]
async fn acquire_data_modify_permit(&self) -> DataModifyPermit<'_> { async fn acquire_data_modify_permit(&self) -> DataModifyPermit<'_>
where
T: Send + Sync,
{
for _ in 0..DATA_MODIFY_FAST_RETRY_YIELDS { for _ in 0..DATA_MODIFY_FAST_RETRY_YIELDS {
if let Some(permit) = self.try_acquire_data_modify_permit() { if let Some(permit) = self.try_acquire_data_modify_permit() {
return permit; return permit;
+3
View File
@@ -15,3 +15,6 @@ default = []
tokio-trace = ["tracing-estuary/tokio-trace"] tokio-trace = ["tracing-estuary/tokio-trace"]
chrome-trace = ["tracing-estuary/chrome-trace"] chrome-trace = ["tracing-estuary/chrome-trace"]
color = ["tracing-estuary/color"] color = ["tracing-estuary/color"]
[lints]
workspace = true
+6 -7
View File
@@ -160,7 +160,7 @@ pub struct Logger {
static LOGGER: OnceLock<Logger> = OnceLock::new(); static LOGGER: OnceLock<Logger> = OnceLock::new();
impl Logger { impl Logger {
fn new() -> Self { const fn new() -> Self {
Self { Self {
pipeline: OnceLock::new(), pipeline: OnceLock::new(),
sidecar_file_writer: RwLock::new(None), sidecar_file_writer: RwLock::new(None),
@@ -185,7 +185,7 @@ impl Logger {
self.store_config(cfg); self.store_config(cfg);
let pipeline = tracing_estuary::PipelineBuilder::new() let pipeline = tracing_estuary::PipelineBuilder::new()
.default_level(log_level) .default_level(log_level)
.file_writer(self.generate_file_log_writer()?) .file_writer(self.generate_file_log_writer())
.init()?; .init()?;
self.pipeline.set(pipeline).ok(); self.pipeline.set(pipeline).ok();
Ok(()) Ok(())
@@ -225,11 +225,11 @@ impl Logger {
self.log_max_count.store(cfg.max_count, Ordering::SeqCst); self.log_max_count.store(cfg.max_count, Ordering::SeqCst);
} }
fn generate_file_log_writer(&self) -> Result<FileLogWriterBuilder> { fn generate_file_log_writer(&self) -> FileLogWriterBuilder {
let log_dir = self.log_dir.get().cloned().unwrap_or_default(); let log_dir = self.log_dir.get().cloned().unwrap_or_default();
let log_max_size = self.log_max_size.load(Ordering::SeqCst); let log_max_size = self.log_max_size.load(Ordering::SeqCst);
let log_max_count = self.log_max_count.load(Ordering::SeqCst); let log_max_count = self.log_max_count.load(Ordering::SeqCst);
let flwb = FileLogWriter::builder(FileSpec::default().directory(log_dir).basename("")) FileLogWriter::builder(FileSpec::default().directory(log_dir).basename(""))
.format(tracing_estuary::file_format_with_level) .format(tracing_estuary::file_format_with_level)
.write_mode(flexi_logger::WriteMode::BufferAndFlushWith( .write_mode(flexi_logger::WriteMode::BufferAndFlushWith(
WRITE_BUFFER_CAPACITY, WRITE_BUFFER_CAPACITY,
@@ -239,8 +239,7 @@ impl Logger {
Criterion::Size(log_max_size * 1024), Criterion::Size(log_max_size * 1024),
ROTATE_NAMING, ROTATE_NAMING,
Cleanup::KeepLogFiles(log_max_count), Cleanup::KeepLogFiles(log_max_count),
); )
Ok(flwb)
} }
/// Ensures the sidecar writer exists and points at `builder`'s config: /// Ensures the sidecar writer exists and points at `builder`'s config:
@@ -311,7 +310,7 @@ impl Logger {
self.log_max_size.store(log_max_size, Ordering::SeqCst); self.log_max_size.store(log_max_size, Ordering::SeqCst);
self.log_max_count.store(log_max_count, Ordering::SeqCst); self.log_max_count.store(log_max_count, Ordering::SeqCst);
if let Some(pipeline) = self.pipeline.get() { if let Some(pipeline) = self.pipeline.get() {
let log_file_writer = self.generate_file_log_writer()?; let log_file_writer = self.generate_file_log_writer();
if let Some(sink) = pipeline.sink.as_ref() { if let Some(sink) = pipeline.sink.as_ref() {
sink.reset(log_file_writer) sink.reset(log_file_writer)
.map_err(|error| anyhow::anyhow!("failed to reset log writer: {error}"))?; .map_err(|error| anyhow::anyhow!("failed to reset log writer: {error}"))?;
+6 -11
View File
@@ -1,28 +1,23 @@
use reqwest::Client; use reqwest::Client;
use crate::utils::{classify_restricted_status, get_trace_location}; use crate::utils::classify_restricted_status;
use super::UnlockItem; use super::UnlockItem;
pub(crate) const MUSE_AI_NAME: &str = "Muse AI"; pub(crate) const MUSE_AI_NAME: &str = "Muse AI";
const MUSE_URL: &str = "https://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 // The aymh ("Are You a Human") gateway answers plain HTTP requests with a
// generic Meta error page that always contains the Facebook logo asset. // 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"]; const AYMH_ERROR_MARKERS: &[&str] = &["Sorry, something went wrong", "static.facebook.com/images/logos"];
pub(super) async fn check_muse_ai(client: &Client) -> UnlockItem { pub(super) async fn check_muse_ai(client: &Client) -> UnlockItem {
// muse.ai itself is served by Vercel, so resolve the exit region through // muse.ai is served by Vercel and does not expose a service-specific region trace endpoint.
// the generic Cloudflare trace endpoint instead of a service-specific one. // Querying a generic third-party domain (e.g. www.cloudflare.com/cdn-cgi/trace) would report
let region = get_trace_location(client, CLOUDFLARE_TRACE_URL) // that domain's proxy group rather than muse.ai's actual exit in Rule mode, so leave region as None.
.await
.map(|code| code.trim().to_ascii_uppercase())
.map(|code| UnlockItem::region_label(&code));
let Ok(response) = client.get(MUSE_URL).send().await else { let Ok(response) = client.get(MUSE_URL).send().await else {
return UnlockItem::checked(MUSE_AI_NAME, "Failed (Network Connection)", region); return UnlockItem::checked(MUSE_AI_NAME, "Failed (Network Connection)", None);
}; };
let status = response.status(); let status = response.status();
@@ -44,5 +39,5 @@ pub(super) async fn check_muse_ai(client: &Client) -> UnlockItem {
classify_restricted_status(status).unwrap_or("Failed") classify_restricted_status(status).unwrap_or("Failed")
}; };
UnlockItem::checked(MUSE_AI_NAME, result, region) UnlockItem::checked(MUSE_AI_NAME, result, None)
} }
+2 -2
View File
@@ -75,7 +75,7 @@
"react-dom": "19.3.1", "react-dom": "19.3.1",
"react-error-boundary": "6.1.6", "react-error-boundary": "6.1.6",
"react-hook-form": "^7.88.0", "react-hook-form": "^7.88.0",
"react-i18next": "18.0.2", "react-i18next": "18.0.1",
"react-markdown": "10.1.0", "react-markdown": "10.1.0",
"react-router": "^8.4.0", "react-router": "^8.4.0",
"rehype-raw": "^7.0.0", "rehype-raw": "^7.0.0",
@@ -138,5 +138,5 @@
] ]
}, },
"type": "module", "type": "module",
"packageManager": "pnpm@12.18.0" "packageManager": "pnpm@12.21.0"
} }
+75 -66
View File
@@ -7,153 +7,162 @@ importers:
configDependencies: {} configDependencies: {}
packageManagerDependencies: packageManagerDependencies:
pnpm: pnpm:
specifier: 12.18.0 specifier: 12.21.0
version: 12.18.0 version: 12.21.0
packages: packages:
'@pnpm/exe.android-arm64@12.18.0': '@pnpm/exe.android-arm64@12.21.0':
resolution: {integrity: sha512-fOF6IwgvnUKEmVedGqiAsNPfN2Ry8GvaqzSQOiF3RJFbpBfPKO/6YT54s1GjToyYinRxw9preHHPe4y2N3SzhA==} resolution: {integrity: sha512-iaWidxR5B9NUBpwMznCQu1yUpKB6BjTY5BYX2lORj76VsfINdj8Z8XWSzSNrGI8qlxa28Jzdp5fiaspzOaJZlA==}
cpu: [arm64] cpu: [arm64]
os: [android] os: [android]
'@pnpm/exe.android-x64@12.18.0': '@pnpm/exe.android-x64@12.21.0':
resolution: {integrity: sha512-6OiolnaCsB3/GcJ9XNrenbUH3zFHRJ+5QynrMUUEyThbgnnCzWxa199hpQlOmxN4rAXuYQ0IYgWFNUZxyzg31Q==} resolution: {integrity: sha512-35e5v3wlwjIYxDywq+R6/z8CE4gLOEgRxt18yqz1tMRLmx2mnW+CFJI2Q8+srTNjn7gykXUC0x1k195JNikC5A==}
cpu: [x64] cpu: [x64]
os: [android] os: [android]
'@pnpm/exe.darwin-arm64@12.18.0': '@pnpm/exe.darwin-arm64@12.21.0':
resolution: {integrity: sha512-zkq+4YzVIX39ETYLyC3W7LY7MpHEU/J3nRhHl4i2yPld2Cf2+rEKRh3ejJ4AmaQ77HHJLCktY4Z3jq0fpcxFXg==} resolution: {integrity: sha512-F5OyMX/6zLSowpTZEQRojbCmPS1Pq+fyRaIinslsIe6Glh3qbyQ52u+Fe0eEzSaRuIbWZkXmAAXSWh6Q5Wrlgg==}
cpu: [arm64] cpu: [arm64]
os: [darwin] os: [darwin]
'@pnpm/exe.darwin-x64@12.18.0': '@pnpm/exe.darwin-x64@12.21.0':
resolution: {integrity: sha512-qMsL9qx92unOTa6hgkfiTJv8ceZaTx0IQg7InhYDVX2ZrTECujaVEEVypnJK5m3eGUsP1KD7Y4qIgleCwfRsYw==} resolution: {integrity: sha512-EzpvcsaE6hrrgYeEiAFYd2rSgFybYyxXhkAY7K3y6Hg3loVfcyJ81hHczpFzi8lW5RXtUlFECRPZ8ZAMRFQYYg==}
cpu: [x64] cpu: [x64]
os: [darwin] os: [darwin]
'@pnpm/exe.freebsd-x64@12.18.0': '@pnpm/exe.freebsd-x64@12.21.0':
resolution: {integrity: sha512-/9vy/4ms52cU4MjZ5NhHd6N2d9L9W0kARf5/ff2tweAHu0VeUzs/0qp/7ZHFuddm2Wa/m0AKQoPum9AVUCqKsw==} resolution: {integrity: sha512-wNjuEnmdLks4aayPu/QZWQ5tQM9Jn+odUp/vwQM8BXRYoulkTZhtZTHoD60N6mUdLWef1hgUeUh8llNGEUsimw==}
cpu: [x64] cpu: [x64]
os: [freebsd] os: [freebsd]
'@pnpm/exe.linux-arm64-musl@12.18.0': '@pnpm/exe.linux-arm64-musl@12.21.0':
resolution: {integrity: sha512-Vp+TIMPPyackVCXkOdEKH/RmAn/r07EcIyrgZYQK7VrkksqZOie0GnWIx+85mPqeFEYCRtXIZAFJ9L4ceTndDg==} resolution: {integrity: sha512-Ceit9zn4g5ZqCJtx1fV8eJE7p8aeXMrGZ+Dc01vRqZLIUNgNeI+Ur0ruyqxtsnJx6rGADyXzohumxPLHjaJ5AQ==}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
libc: [musl] libc: [musl]
'@pnpm/exe.linux-arm64@12.18.0': '@pnpm/exe.linux-arm64@12.21.0':
resolution: {integrity: sha512-2dpyVBCHT+FfpuQh9i+7MXAqNWYLCvD5vYr5p6Eimxoga8USLnjbUgyj72AOrO0hjc5ri3TEFP3jiyBHjkSZpQ==} resolution: {integrity: sha512-4Oj/iF2TDCe2lcH0n4TupPR5sSdrNLclJB6xBElLMPCUOAvBhdf2rRlSaO5M4erJ6g4Fyy7YTXTpcmfFsKyxEA==}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@pnpm/exe.linux-ppc64@12.18.0': '@pnpm/exe.linux-ppc64@12.21.0':
resolution: {integrity: sha512-BBOOOfNJ2QwIIya3eKqOjiN4WNTszfRz7HCvw9XggcT7+ftMjNP8XJ/GfW+ltCBeUFR9d8WBVsr2m/NLjX2CZQ==} resolution: {integrity: sha512-s2o7rdSDeUTBFsNqxptpZXlTgT6cojmMVUOvTQvFNSv6Easian02ha4tR32fwwD97Au4YzIIjMCwywCF4D82Sw==}
cpu: [ppc64] cpu: [ppc64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@pnpm/exe.linux-riscv64@12.18.0': '@pnpm/exe.linux-riscv64@12.21.0':
resolution: {integrity: sha512-7kMN77xSOYJX8GPSH5RbNAc5oM61LMmcSUukDDUwllnZPXm8GRPskCNsTWy8SCw01Kr1FB+5SwGNMiTdiziLNQ==} resolution: {integrity: sha512-EYv3GzxeBTITCuM3yGHHbpRFpUvyulkXpQ6LsjKAQNL3iaba1E6h9iDmlouLb3Io4AMMsfdk0/uG6poQ41uewA==}
cpu: [riscv64] cpu: [riscv64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@pnpm/exe.linux-s390x@12.18.0': '@pnpm/exe.linux-s390x@12.21.0':
resolution: {integrity: sha512-htuSCpEcmDzhKoJqXbPkvfr176dBHU0QIF5mWcRiqxRXAB/1JoYiMYotfjWpk+ztgpB9qlx4XnWlLFAf7gzc6g==} resolution: {integrity: sha512-8VXGNGVNEfs7pL9GTZOzFxjFEnMt4WL3rLOADR5/kPQ7ROTV9GfpVI2DPO/zArXFSkvfc9Zad/WypHLbvzoaTQ==}
cpu: [s390x] cpu: [s390x]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@pnpm/exe.linux-x64-musl@12.18.0': '@pnpm/exe.linux-x64-musl@12.21.0':
resolution: {integrity: sha512-Uj+vzfIQ62kDP10x36yHZIXVs5ohdNtiPYwn5FhCLlNScHPo0OAI+ShGDtLofiBXKE7umu71Jmjm7N8a8zVcDw==} resolution: {integrity: sha512-MnC5vpIXYubhDZCgCwlfJMg7Cg6HupN2IuouT9gD/tUmOfVdQYqeyYccWbthyo/Jeto8de1oQlxeRN1+1Hl2DQ==}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
libc: [musl] libc: [musl]
'@pnpm/exe.linux-x64@12.18.0': '@pnpm/exe.linux-x64@12.21.0':
resolution: {integrity: sha512-OJ+X2wcraldCwj75pCIerWARQSRpdfj0eBTs/2ODyhfeW46ylOnjTIE/GKra6Mn6E72/gBmXS8igrUioa+F9fQ==} resolution: {integrity: sha512-8eufCjHXspKbNS/kh8q4Q0gqJoOuvC4Q5pgos6XS8By/nAMtP+jf8F1Cw9er840kfAX+PJ/ts+A9qnLE91rvXQ==}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@pnpm/exe.win32-arm64@12.18.0': '@pnpm/exe.netbsd-x64@12.21.0':
resolution: {integrity: sha512-wEY6jiACGcbhhi5yD59doHqNTndS7AaujaPmtWAu1DKkHru2hy5fJ9yUGecW72Ypaw2/I3BEprfMOopap2NQtw==} resolution: {integrity: sha512-eyh1M8hQZCkLWxuva7S/fc1SbFbgqg0/5di0dgWmyiuc2Io3dbWVihDun8X+XM8zsR5uhIDvvZpbS9aZQbCovg==}
cpu: [x64]
os: [netbsd]
'@pnpm/exe.win32-arm64@12.21.0':
resolution: {integrity: sha512-7xTxxUXo/grRLivSeIl6B21gnsz7ooe5EMPcJmQqwxc8WLJVReN8MzrlHru8bqXfVr4X3+6ZGZscntKenlCBqQ==}
cpu: [arm64] cpu: [arm64]
os: [win32] os: [win32]
'@pnpm/exe.win32-x64@12.18.0': '@pnpm/exe.win32-x64@12.21.0':
resolution: {integrity: sha512-5FJkghO7RLRkQpWxeVEygW9XsmnNuxzPfXbgwFWCHsFyFhpDn/vOdL88ToQEM0Kt5igdW5s6U0/IDH8Dvkt3pg==} resolution: {integrity: sha512-9TpkJemVApxJ1Z1w0ZFGN+AuSx4nJOqXSJUqMqDvaXTYwGOzvBiiWdFP9GN0ketiWCQS1Q0/pza2E7I3pP0OBQ==}
cpu: [x64] cpu: [x64]
os: [win32] os: [win32]
pnpm@12.18.0: pnpm@12.21.0:
resolution: {integrity: sha512-nXiC1dyCFH7PxOBiqjSDTgrQKWcQoYN6ERWuASEn02txCeMhrBWYod0KZVl2gbHpmRfhLtDXSerpEYeUM2O+sw==} resolution: {integrity: sha512-Zv2CeO4ok1zpUXktNDZ/869cQyonVkRYIwKVM4NbjaUpu+C+UTCv1W7QcT+4eJ5Hutgtk71a4v5UsVVi1idu8A==}
engines: {node: '>=18'} engines: {node: '>=18'}
hasBin: true hasBin: true
snapshots: snapshots:
'@pnpm/exe.android-arm64@12.18.0': '@pnpm/exe.android-arm64@12.21.0':
optional: true optional: true
'@pnpm/exe.android-x64@12.18.0': '@pnpm/exe.android-x64@12.21.0':
optional: true optional: true
'@pnpm/exe.darwin-arm64@12.18.0': '@pnpm/exe.darwin-arm64@12.21.0':
optional: true optional: true
'@pnpm/exe.darwin-x64@12.18.0': '@pnpm/exe.darwin-x64@12.21.0':
optional: true optional: true
'@pnpm/exe.freebsd-x64@12.18.0': '@pnpm/exe.freebsd-x64@12.21.0':
optional: true optional: true
'@pnpm/exe.linux-arm64-musl@12.18.0': '@pnpm/exe.linux-arm64-musl@12.21.0':
optional: true optional: true
'@pnpm/exe.linux-arm64@12.18.0': '@pnpm/exe.linux-arm64@12.21.0':
optional: true optional: true
'@pnpm/exe.linux-ppc64@12.18.0': '@pnpm/exe.linux-ppc64@12.21.0':
optional: true optional: true
'@pnpm/exe.linux-riscv64@12.18.0': '@pnpm/exe.linux-riscv64@12.21.0':
optional: true optional: true
'@pnpm/exe.linux-s390x@12.18.0': '@pnpm/exe.linux-s390x@12.21.0':
optional: true optional: true
'@pnpm/exe.linux-x64-musl@12.18.0': '@pnpm/exe.linux-x64-musl@12.21.0':
optional: true optional: true
'@pnpm/exe.linux-x64@12.18.0': '@pnpm/exe.linux-x64@12.21.0':
optional: true optional: true
'@pnpm/exe.win32-arm64@12.18.0': '@pnpm/exe.netbsd-x64@12.21.0':
optional: true optional: true
'@pnpm/exe.win32-x64@12.18.0': '@pnpm/exe.win32-arm64@12.21.0':
optional: true optional: true
pnpm@12.18.0: '@pnpm/exe.win32-x64@12.21.0':
optional: true
pnpm@12.21.0:
optionalDependencies: optionalDependencies:
'@pnpm/exe.android-arm64': 12.18.0 '@pnpm/exe.android-arm64': 12.21.0
'@pnpm/exe.android-x64': 12.18.0 '@pnpm/exe.android-x64': 12.21.0
'@pnpm/exe.darwin-arm64': 12.18.0 '@pnpm/exe.darwin-arm64': 12.21.0
'@pnpm/exe.darwin-x64': 12.18.0 '@pnpm/exe.darwin-x64': 12.21.0
'@pnpm/exe.freebsd-x64': 12.18.0 '@pnpm/exe.freebsd-x64': 12.21.0
'@pnpm/exe.linux-arm64': 12.18.0 '@pnpm/exe.linux-arm64': 12.21.0
'@pnpm/exe.linux-arm64-musl': 12.18.0 '@pnpm/exe.linux-arm64-musl': 12.21.0
'@pnpm/exe.linux-ppc64': 12.18.0 '@pnpm/exe.linux-ppc64': 12.21.0
'@pnpm/exe.linux-riscv64': 12.18.0 '@pnpm/exe.linux-riscv64': 12.21.0
'@pnpm/exe.linux-s390x': 12.18.0 '@pnpm/exe.linux-s390x': 12.21.0
'@pnpm/exe.linux-x64': 12.18.0 '@pnpm/exe.linux-x64': 12.21.0
'@pnpm/exe.linux-x64-musl': 12.18.0 '@pnpm/exe.linux-x64-musl': 12.21.0
'@pnpm/exe.win32-arm64': 12.18.0 '@pnpm/exe.netbsd-x64': 12.21.0
'@pnpm/exe.win32-x64': 12.18.0 '@pnpm/exe.win32-arm64': 12.21.0
'@pnpm/exe.win32-x64': 12.21.0
--- ---
lockfileVersion: '9.0' lockfileVersion: '9.0'
@@ -275,8 +284,8 @@ importers:
specifier: ^7.88.0 specifier: ^7.88.0
version: 7.88.0(react@19.3.1) version: 7.88.0(react@19.3.1)
react-i18next: react-i18next:
specifier: 18.0.2 specifier: 18.0.1
version: 18.0.2(@types/react@19.3.0)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3) version: 18.0.1(@types/react@19.3.0)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3)
react-markdown: react-markdown:
specifier: 10.1.0 specifier: 10.1.0
version: 10.1.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0) version: 10.1.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
@@ -3783,8 +3792,8 @@ packages:
peerDependencies: peerDependencies:
react: ^16.8.0 || ^17 || ^18 || ^19 react: ^16.8.0 || ^17 || ^18 || ^19
react-i18next@18.0.2: react-i18next@18.0.1:
resolution: {integrity: sha512-g7YfBxTDC9dYdEsb3F7o0pRr6jg14f08U5G6N3DTUqSgGt/nq7AYf279ESRjE3Dy+Q/YG7OGVd7vtiylxTfV4w==} resolution: {integrity: sha512-kPWXI0E/lrPj3+/umcKNzYZVnWmEedLiamMzDIHfbs+5ANf6yzvlZsjKou8f7kaGkfMMDLIZBejV+4aSN1CyBw==}
engines: {node: '>=22'} engines: {node: '>=22'}
peerDependencies: peerDependencies:
'@types/react': '*' '@types/react': '*'
@@ -7874,7 +7883,7 @@ snapshots:
dependencies: dependencies:
react: 19.3.1 react: 19.3.1
react-i18next@18.0.2(@types/react@19.3.0)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3): react-i18next@18.0.1(@types/react@19.3.0)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3):
dependencies: dependencies:
html-parse-stringify: 4.0.1 html-parse-stringify: 4.0.1
i18next: 27.0.1(typescript@6.0.3) i18next: 27.0.1(typescript@6.0.3)
+1 -1
View File
@@ -220,7 +220,7 @@ pub fn run() -> std::process::ExitCode {
.set_activation_policy(tauri::ActivationPolicy::Prohibited)?; .set_activation_policy(tauri::ActivationPolicy::Prohibited)?;
let scenario = std::env::var("PERF_SCENARIO").unwrap_or_else(|_| "traffic".into()); let scenario = std::env::var("PERF_SCENARIO").unwrap_or_else(|_| "traffic".into());
let layer = std::env::var("PERF_LAYER").unwrap_or_else(|_| "component".into()); let layer = std::env::var("PERF_LAYER").unwrap_or_else(|_| "component".into());
if !matches!(scenario.as_str(), "traffic" | "logs" | "connections") if !matches!(scenario.as_str(), "traffic" | "logs" | "connections" | "proxy")
|| !matches!(layer.as_str(), "page" | "component" | "dom") || !matches!(layer.as_str(), "page" | "component" | "dom")
{ {
return Err("invalid perf scene".into()); return Err("invalid perf scene".into());
+2
View File
@@ -2,6 +2,8 @@ import { layer, scenario, startReplay } from './replay'
if (scenario === 'traffic') { if (scenario === 'traffic') {
await import('./traffic') await import('./traffic')
} else if (scenario === 'proxy') {
await import('./proxy')
} else { } else {
const root = document.getElementById('root')! const root = document.getElementById('root')!
document.body.style.cssText = 'margin:0;font:14px -apple-system,sans-serif' document.body.style.cssText = 'margin:0;font:14px -apple-system,sans-serif'
+137
View File
@@ -0,0 +1,137 @@
// 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
@@ -0,0 +1,93 @@
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
@@ -0,0 +1,17 @@
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
@@ -0,0 +1,30 @@
// 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,5 +6,11 @@ export default mergeConfig(
defineConfig({ defineConfig({
root: 'scripts/perf', root: 'scripts/perf',
build: { outDir: '../../target/perf/dist', target: 'safari16' }, 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
@@ -91,7 +91,7 @@ backon = { version = "1.6.0", features = ["tokio-sleep"] }
tauri-plugin-http = "2.9.0" tauri-plugin-http = "2.9.0"
tracing = { workspace = true } tracing = { workspace = true }
tauri-plugin-devtools = { version = "2.2.3", optional = true } tauri-plugin-devtools = { version = "2.2.3", optional = true }
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "e49bbedcc67d60da2c10e81bc6433b0f8e8fa232" } tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "7e4fa8642cf6c394ed88b5a969420d8eab60087f" }
async-trait = "0.1.92" async-trait = "0.1.92"
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", tag = "v2.8.1", version = "2.8.1", features = [ clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", tag = "v2.8.1", version = "2.8.1", features = [
"client", "client",
+6
View File
@@ -27,6 +27,12 @@ pub async fn switch_proxy_node(group_name: String, proxy_name: String, unfix: bo
.stringify_err() .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> { fn runtime_group_order(config: Option<&Mapping>) -> Vec<String> {
let mut seen = HashSet::new(); let mut seen = HashSet::new();
+14 -2
View File
@@ -34,6 +34,9 @@ pub(crate) struct Config {
static CONFIG_WRITE_LOCK: Mutex<()> = Mutex::const_new(()); static CONFIG_WRITE_LOCK: Mutex<()> = Mutex::const_new(());
static RUNTIME_YAML_CACHE: parking_lot::Mutex<Option<(u64, std::sync::Arc<std::string::String>)>> =
parking_lot::Mutex::new(None);
impl Config { impl Config {
async fn global() -> &'static Self { async fn global() -> &'static Self {
static CONFIG: OnceCell<Config> = OnceCell::const_new(); static CONFIG: OnceCell<Config> = OnceCell::const_new();
@@ -205,7 +208,7 @@ impl Config {
Self::write_runtime_file(&yaml).await Self::write_runtime_file(&yaml).await
} }
pub(crate) async fn runtime_config_yaml() -> Result<std::string::String> { pub(crate) async fn runtime_config_yaml() -> Result<std::sync::Arc<std::string::String>> {
let runtime = Self::runtime().await; let runtime = Self::runtime().await;
AsyncHandler::spawn_blocking(move || { AsyncHandler::spawn_blocking(move || {
let runtime_lastest = runtime.latest_arc(); let runtime_lastest = runtime.latest_arc();
@@ -215,7 +218,16 @@ impl Config {
.as_ref() .as_ref()
.or_else(|| runtime_data.config.as_ref()) .or_else(|| runtime_data.config.as_ref())
.ok_or_else(|| anyhow!("failed to generate runtime config, might need to restart application"))?; .ok_or_else(|| anyhow!("failed to generate runtime config, might need to restart application"))?;
let yaml_str = serde_yaml_ng::to_string(config)?; let mut hasher = std::collections::hash_map::DefaultHasher::new();
std::hash::Hash::hash(config, &mut hasher);
let key = std::hash::Hasher::finish(&hasher);
if let Some((cached_key, cached)) = RUNTIME_YAML_CACHE.lock().as_ref()
&& *cached_key == key
{
return Ok(std::sync::Arc::clone(cached));
}
let yaml_str = std::sync::Arc::new(serde_yaml_ng::to_string(config)?);
*RUNTIME_YAML_CACHE.lock() = Some((key, std::sync::Arc::clone(&yaml_str)));
Ok(yaml_str) Ok(yaml_str)
}) })
.await .await
+4
View File
@@ -109,6 +109,8 @@ pub struct IVerge {
pub auto_close_connection: Option<bool>, pub auto_close_connection: Option<bool>,
pub auto_switch_selector_group: Option<bool>,
pub auto_check_update: Option<bool>, pub auto_check_update: Option<bool>,
pub default_latency_test: Option<String>, pub default_latency_test: Option<String>,
@@ -368,6 +370,7 @@ impl IVerge {
use_default_bypass: Some(true), use_default_bypass: Some(true),
proxy_guard_duration: Some(30), proxy_guard_duration: Some(30),
auto_close_connection: Some(true), auto_close_connection: Some(true),
auto_switch_selector_group: Some(true),
auto_check_update: Some(true), auto_check_update: Some(true),
enable_builtin_enhanced: Some(true), enable_builtin_enhanced: Some(true),
auto_log_clean: Some(2), // 1: 1天, 2: 7天, 3: 30天, 4: 90天 auto_log_clean: Some(2), // 1: 1天, 2: 7天, 3: 30天, 4: 90天
@@ -456,6 +459,7 @@ impl IVerge {
patch_opt_field!(self, patch, enable_global_hotkey); patch_opt_field!(self, patch, enable_global_hotkey);
patch_opt_field!(self, patch, auto_close_connection); 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, auto_check_update);
patch_opt_field!(self, patch, default_latency_test); patch_opt_field!(self, patch, default_latency_test);
patch_opt_field!(self, patch, default_latency_timeout); patch_opt_field!(self, patch, default_latency_timeout);
+39 -11
View File
@@ -3,17 +3,22 @@ use crate::{
config::PrfItem, config::PrfItem,
utils::{dirs, help}, utils::{dirs, help},
}; };
use parking_lot::Mutex;
use serde_yaml_ng::Mapping; use serde_yaml_ng::Mapping;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, LazyLock};
use std::time::SystemTime;
use tokio::fs; use tokio::fs;
use tristr::alias::String; use tristr::alias::String;
#[derive(Debug, Clone)] #[derive(Debug)]
pub struct ChainItem { pub struct ChainItem {
pub uid: String, pub uid: String,
pub data: ChainType, pub data: ChainType,
} }
#[derive(Debug, Clone)] #[derive(Debug)]
pub enum ChainType { pub enum ChainType {
Merge(Mapping), Merge(Mapping),
Script(String), Script(String),
@@ -22,26 +27,39 @@ pub enum ChainType {
Groups(SeqMap), Groups(SeqMap),
} }
// Helper trait to allow async conversion struct CachedChain {
pub trait AsyncChainItemFrom { mtime: SystemTime,
async fn from_async(item: &PrfItem) -> Option<ChainItem>; len: u64,
item: Arc<ChainItem>,
} }
impl AsyncChainItemFrom for Option<ChainItem> { static CHAIN_CACHE: LazyLock<Mutex<HashMap<PathBuf, CachedChain>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
// Helper trait to allow async conversion
pub trait AsyncChainItemFrom {
async fn from_async(item: &PrfItem) -> Option<Arc<ChainItem>>;
}
impl AsyncChainItemFrom for Option<Arc<ChainItem>> {
async fn from_async(item: &PrfItem) -> Self { async fn from_async(item: &PrfItem) -> Self {
let itype = item.itype.as_ref()?.as_str(); let itype = item.itype.as_ref()?.as_str();
let file = item.file.clone()?; let file = item.file.clone()?;
let uid = item.uid.clone().unwrap_or_else(|| "".into()); let uid = item.uid.clone().unwrap_or_else(|| "".into());
let path = dirs::app_profiles_dir().ok()?.join(file.as_str()); let path = dirs::app_profiles_dir().ok()?.join(file.as_str());
if !path.exists() { let meta = fs::metadata(&path).await.ok()?;
return None; let (mtime, len) = (meta.modified().ok()?, meta.len());
if let Some(cached) = CHAIN_CACHE.lock().get(&path)
&& cached.mtime == mtime
&& cached.len == len
{
return Some(Arc::clone(&cached.item));
} }
match itype { let loaded = Arc::new(match itype {
"script" => Some(ChainItem { "script" => Some(ChainItem {
uid, uid,
data: ChainType::Script(fs::read_to_string(path).await.ok()?.into()), data: ChainType::Script(fs::read_to_string(&path).await.ok()?.as_str().into()),
}), }),
"merge" => Some(ChainItem { "merge" => Some(ChainItem {
uid, uid,
@@ -57,6 +75,16 @@ impl AsyncChainItemFrom for Option<ChainItem> {
Some(ChainItem { uid, data }) Some(ChainItem { uid, data })
} }
_ => None, _ => None,
} }?);
CHAIN_CACHE.lock().insert(
path,
CachedChain {
mtime,
len,
item: Arc::clone(&loaded),
},
);
Some(loaded)
} }
} }
+65 -56
View File
@@ -28,6 +28,7 @@ use parking_lot::Mutex;
use serde_yaml_ng::{Mapping, Value}; use serde_yaml_ng::{Mapping, Value};
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::hash::{Hash as _, Hasher as _}; use std::hash::{Hash as _, Hasher as _};
use std::sync::Arc;
use tokio::fs; use tokio::fs;
use tristr::alias::String; use tristr::alias::String;
@@ -51,13 +52,13 @@ struct ConfigValues {
#[derive(Debug)] #[derive(Debug)]
struct ProfileItems { struct ProfileItems {
config: Mapping, config: Mapping,
merge_item: ChainItem, merge_item: Arc<ChainItem>,
script_item: ChainItem, script_item: Arc<ChainItem>,
rules_item: ChainItem, rules_item: Arc<ChainItem>,
proxies_item: ChainItem, proxies_item: Arc<ChainItem>,
groups_item: ChainItem, groups_item: Arc<ChainItem>,
global_merge: ChainItem, global_merge: Arc<ChainItem>,
global_script: ChainItem, global_script: Arc<ChainItem>,
profile_name: String, profile_name: String,
} }
@@ -66,41 +67,46 @@ impl Default for ProfileItems {
Self { Self {
config: Default::default(), config: Default::default(),
profile_name: Default::default(), profile_name: Default::default(),
merge_item: ChainItem { merge_item: Arc::new(ChainItem {
uid: "".into(), uid: "".into(),
data: ChainType::Merge(Mapping::new()), data: ChainType::Merge(Mapping::new()),
}, }),
script_item: ChainItem { script_item: Arc::new(ChainItem {
uid: "".into(), uid: "".into(),
data: ChainType::Script(tmpl::ITEM_SCRIPT.into()), data: ChainType::Script(tmpl::ITEM_SCRIPT.into()),
}, }),
rules_item: ChainItem { rules_item: Arc::new(ChainItem {
uid: "".into(), uid: "".into(),
data: ChainType::Rules(SeqMap::default()), data: ChainType::Rules(SeqMap::default()),
}, }),
proxies_item: ChainItem { proxies_item: Arc::new(ChainItem {
uid: "".into(), uid: "".into(),
data: ChainType::Proxies(SeqMap::default()), data: ChainType::Proxies(SeqMap::default()),
}, }),
groups_item: ChainItem { groups_item: Arc::new(ChainItem {
uid: "".into(), uid: "".into(),
data: ChainType::Groups(SeqMap::default()), data: ChainType::Groups(SeqMap::default()),
}, }),
global_merge: ChainItem { global_merge: Arc::new(ChainItem {
uid: "Merge".into(), uid: "Merge".into(),
data: ChainType::Merge(Mapping::new()), data: ChainType::Merge(Mapping::new()),
}, }),
global_script: ChainItem { global_script: Arc::new(ChainItem {
uid: "Script".into(), uid: "Script".into(),
data: ChainType::Script(tmpl::ITEM_SCRIPT.into()), data: ChainType::Script(tmpl::ITEM_SCRIPT.into()),
}, }),
} }
} }
} }
async fn chain_item_or_default(item: Option<&PrfItem>, default_item: impl FnOnce() -> ChainItem) -> ChainItem { async fn chain_item_or_default(
item: Option<&PrfItem>,
default_item: impl FnOnce() -> Arc<ChainItem>,
) -> Arc<ChainItem> {
if let Some(item) = item { if let Some(item) = item {
<Option<ChainItem>>::from_async(item).await.unwrap_or_else(default_item) <Option<Arc<ChainItem>>>::from_async(item)
.await
.unwrap_or_else(default_item)
} else { } else {
default_item() default_item()
} }
@@ -235,28 +241,28 @@ async fn process_override_items(
mut config: Mapping, mut config: Mapping,
mut exists_keys: Vec<String>, mut exists_keys: Vec<String>,
mut result_map: HashMap<String, ResultLog>, mut result_map: HashMap<String, ResultLog>,
merge_item: ChainItem, merge_item: Arc<ChainItem>,
script_item: ChainItem, script_item: Arc<ChainItem>,
profile_name: &str, profile_name: &str,
authoritative: &AuthoritativeFields, authoritative: &AuthoritativeFields,
) -> (Mapping, Vec<String>, HashMap<String, ResultLog>) { ) -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
if let ChainType::Merge(merge) = merge_item.data { if let ChainType::Merge(merge) = &merge_item.data {
exists_keys.extend(use_keys(&merge)); exists_keys.extend(use_keys(merge));
let before = authoritative.current(&config); let before = authoritative.current(&config);
config = use_merge(merge, config); config = use_merge(merge.clone(), config);
let notes: ResultLog = authoritative let notes: ResultLog = authoritative
.overridden(&before, &authoritative.current(&config)) .overridden(&before, &authoritative.current(&config))
.into_iter() .into_iter()
.map(discarded_note) .map(discarded_note)
.collect(); .collect();
if !notes.is_empty() { if !notes.is_empty() {
result_map.entry(merge_item.uid).or_default().extend(notes); result_map.entry(merge_item.uid.clone()).or_default().extend(notes);
} }
} }
if let ChainType::Script(script) = script_item.data { if let ChainType::Script(script) = &script_item.data {
let before = authoritative.current(&config); let before = authoritative.current(&config);
let (res_config, changed_keys, mut logs) = use_script(script, config, profile_name.into()).await; let (res_config, changed_keys, mut logs) = use_script(script.clone(), config, profile_name.into()).await;
exists_keys.extend(changed_keys); exists_keys.extend(changed_keys);
config = res_config; config = res_config;
logs.extend( logs.extend(
@@ -265,7 +271,7 @@ async fn process_override_items(
.into_iter() .into_iter()
.map(discarded_note), .map(discarded_note),
); );
result_map.insert(script_item.uid, logs); result_map.insert(script_item.uid.clone(), logs);
} }
(config, exists_keys, result_map) (config, exists_keys, result_map)
@@ -273,20 +279,20 @@ async fn process_override_items(
fn process_seq_items( fn process_seq_items(
mut config: Mapping, mut config: Mapping,
rules_item: ChainItem, rules_item: Arc<ChainItem>,
proxies_item: ChainItem, proxies_item: Arc<ChainItem>,
groups_item: ChainItem, groups_item: Arc<ChainItem>,
) -> Mapping { ) -> Mapping {
if let ChainType::Rules(rules) = rules_item.data { if let ChainType::Rules(rules) = &rules_item.data {
config = use_seq(rules, config, "rules"); config = use_seq(rules.clone(), config, "rules");
} }
if let ChainType::Proxies(proxies) = proxies_item.data { if let ChainType::Proxies(proxies) = &proxies_item.data {
config = use_seq(proxies, config, "proxies"); config = use_seq(proxies.clone(), config, "proxies");
} }
if let ChainType::Groups(groups) = groups_item.data { if let ChainType::Groups(groups) = &groups_item.data {
config = use_seq(groups, config, "proxy-groups"); config = use_seq(groups.clone(), config, "proxy-groups");
} }
config config
@@ -1397,6 +1403,7 @@ mod tests {
process_override_items, use_keys, process_override_items, use_keys,
}; };
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::Arc;
fn mapping(yaml: &str) -> serde_yaml_ng::Mapping { fn mapping(yaml: &str) -> serde_yaml_ng::Mapping {
serde_yaml_ng::from_str(yaml).expect("test config should be valid") serde_yaml_ng::from_str(yaml).expect("test config should be valid")
@@ -1437,9 +1444,11 @@ mod tests {
(profile.clone(), Mapping::new()) (profile.clone(), Mapping::new())
}; };
let authoritative = AuthoritativeFields::capture(&config, &[], dns_settings); let authoritative = AuthoritativeFields::capture(&config, &[], dns_settings);
let merge_item = |uid: &str| ChainItem { let merge_item = |uid: &str| {
uid: uid.into(), Arc::new(ChainItem {
data: ChainType::Merge(merge.clone()), uid: uid.into(),
data: ChainType::Merge(merge.clone()),
})
}; };
let profile_name = "test-profile"; let profile_name = "test-profile";
let (config, keys, logs) = process_override_items( let (config, keys, logs) = process_override_items(
@@ -1447,10 +1456,10 @@ mod tests {
vec![], vec![],
HashMap::new(), HashMap::new(),
merge_item("global-merge"), merge_item("global-merge"),
ChainItem { Arc::new(ChainItem {
uid: "global-script".into(), uid: "global-script".into(),
data: ChainType::Script(script.into()), data: ChainType::Script(script.into()),
}, }),
profile_name, profile_name,
&authoritative, &authoritative,
) )
@@ -1460,10 +1469,10 @@ mod tests {
keys, keys,
logs, logs,
merge_item("profile-merge"), merge_item("profile-merge"),
ChainItem { Arc::new(ChainItem {
uid: "profile-script".into(), uid: "profile-script".into(),
data: ChainType::Script(script.into()), data: ChainType::Script(script.into()),
}, }),
profile_name, profile_name,
&authoritative, &authoritative,
) )
@@ -1500,15 +1509,15 @@ mod tests {
let exists_keys = use_keys(&config).collect(); let exists_keys = use_keys(&config).collect();
config.insert("application-only".into(), true.into()); config.insert("application-only".into(), true.into());
let global_merge = ChainItem { let global_merge = Arc::new(ChainItem {
uid: "Merge".into(), uid: "Merge".into(),
data: ChainType::Merge(mapping( data: ChainType::Merge(mapping(
r"{global-merge-wins: global-merge, global-script-wins: global-merge, r"{global-merge-wins: global-merge, global-script-wins: global-merge,
profile-merge-wins: global-merge, profile-script-wins: global-merge, profile-merge-wins: global-merge, profile-script-wins: global-merge,
nested: {winner: global-merge}, dns: {enable: false}, tun: {enable: false}}", nested: {winner: global-merge}, dns: {enable: false}, tun: {enable: false}}",
)), )),
}; });
let global_script = ChainItem { let global_script = Arc::new(ChainItem {
uid: "Script".into(), uid: "Script".into(),
data: ChainType::Script( data: ChainType::Script(
r#"function main(config) { r#"function main(config) {
@@ -1520,15 +1529,15 @@ mod tests {
}"# }"#
.into(), .into(),
), ),
}; });
let profile_merge = ChainItem { let profile_merge = Arc::new(ChainItem {
uid: "profile-merge".into(), uid: "profile-merge".into(),
data: ChainType::Merge(mapping( data: ChainType::Merge(mapping(
r"{profile-merge-wins: profile-merge, profile-script-wins: profile-merge, r"{profile-merge-wins: profile-merge, profile-script-wins: profile-merge,
nested: {winner: profile-merge}}", nested: {winner: profile-merge}}",
)), )),
}; });
let profile_script = ChainItem { let profile_script = Arc::new(ChainItem {
uid: "profile-script".into(), uid: "profile-script".into(),
data: ChainType::Script( data: ChainType::Script(
r#"function main(config) { r#"function main(config) {
@@ -1538,7 +1547,7 @@ mod tests {
}"# }"#
.into(), .into(),
), ),
}; });
let profile_name = "test-profile"; let profile_name = "test-profile";
let authoritative = AuthoritativeFields::capture(&config, &[], Mapping::new()); let authoritative = AuthoritativeFields::capture(&config, &[], Mapping::new());
+1
View File
@@ -90,6 +90,7 @@ verge_registry! {
enable_global_hotkey => NoEffect; enable_global_hotkey => NoEffect;
home_cards => NoEffect; home_cards => NoEffect;
auto_close_connection => NoEffect; auto_close_connection => NoEffect;
auto_switch_selector_group => NoEffect;
auto_check_update => NoEffect; auto_check_update => NoEffect;
default_latency_test => NoEffect; default_latency_test => NoEffect;
default_latency_timeout => NoEffect; default_latency_timeout => NoEffect;
+118 -4
View File
@@ -9,6 +9,7 @@ use crate::{
}; };
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use tauri_plugin_mihomo::models::ProxyType;
use tristr::alias::String; use tristr::alias::String;
/// Toggle proxy profile /// Toggle proxy profile
@@ -22,9 +23,80 @@ 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<()> { pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool) -> Result<()> {
let mihomo = handle::Handle::mihomo(); let mihomo = handle::Handle::mihomo();
let previous_proxy = if Config::verge().await.data_arc().auto_close_connection.unwrap_or(false) { let auto_close = Config::verge().await.data_arc().auto_close_connection.unwrap_or(false);
let previous_proxy = if auto_close {
match mihomo.get_proxy_by_name(group_name).await { match mihomo.get_proxy_by_name(group_name).await {
Ok(group) => group.now.filter(|name| !name.is_empty()), Ok(group) => group.now.filter(|name| !name.is_empty()),
Err(err) => { Err(err) => {
@@ -58,9 +130,31 @@ pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool)
"Failed to persist proxy selection for {group_name}: {error:#}" "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); announce(Refresh::Proxies);
if let Some(previous_proxy) = previous_proxy { if !stale_proxies.is_empty() {
AsyncHandler::spawn(move || async move { AsyncHandler::spawn(move || async move {
let connections = match mihomo.get_connections().await { let connections = match mihomo.get_connections().await {
Ok(connections) => connections, Ok(connections) => connections,
@@ -78,7 +172,7 @@ pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool)
.connections .connections
.unwrap_or_default() .unwrap_or_default()
.into_iter() .into_iter()
.filter(|connection| connection.chains.contains(&previous_proxy)) .filter(|connection| stale_proxies.iter().any(|proxy| connection.chains.contains(proxy)))
.map(|connection| async move { .map(|connection| async move {
if let Err(err) = mihomo.close_connection(&connection.id).await { if let Err(err) = mihomo.close_connection(&connection.id).await {
logging!( logging!(
@@ -100,7 +194,6 @@ pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool)
"Failed to refresh tray after switching proxy: {err:#}" "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>)>> { async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
@@ -280,3 +373,24 @@ pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_mannual_tr
pub async fn enhance_profiles() -> Result<ValidationOutcome> { pub async fn enhance_profiles() -> Result<ValidationOutcome> {
CoreManager::global().update_config_forced().await 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,6 +47,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
cmd::copy_clash_env, cmd::copy_clash_env,
cmd::record_selected_node, cmd::record_selected_node,
cmd::switch_proxy_node, cmd::switch_proxy_node,
cmd::follow_proxy_group,
cmd::save_dns_config, cmd::save_dns_config,
cmd::apply_dns_config, cmd::apply_dns_config,
cmd::set_dns_override, cmd::set_dns_override,
+3 -1
View File
@@ -55,6 +55,7 @@ import {
useCoreDataStatus, useCoreDataStatus,
useProxiesData, useProxiesData,
} from '@/providers/app-data-context' } from '@/providers/app-data-context'
import { followProxyGroup } from '@/services/cmds'
import delayManager from '@/services/delay' import delayManager from '@/services/delay'
import { import {
findCurrentGroupMember, findCurrentGroupMember,
@@ -665,7 +666,7 @@ export const CurrentProxyCard = () => {
return proxyView.groups.filter( return proxyView.groups.filter(
(group) => (group) =>
!group.hidden && !group.hidden &&
(group.type === 'Selector' || group.type === 'URLTest'), ['Selector', 'URLTest', 'Fallback'].includes(group.type),
) )
}, [proxyView]) }, [proxyView])
@@ -765,6 +766,7 @@ export const CurrentProxyCard = () => {
if (isGlobalMode || isDirectMode) return if (isGlobalMode || isDirectMode) return
setLastGroupName(newGroupName) setLastGroupName(newGroupName)
writeProfileScopedItem(STORAGE_KEY_GROUP, newGroupName) writeProfileScopedItem(STORAGE_KEY_GROUP, newGroupName)
void followProxyGroup(newGroupName)
}, },
[isDirectMode, isGlobalMode, writeProfileScopedItem], [isDirectMode, isGlobalMode, writeProfileScopedItem],
) )
@@ -7,7 +7,6 @@ import {
useEffectEvent, useEffectEvent,
useImperativeHandle, useImperativeHandle,
useMemo, useMemo,
useReducer,
useRef, useRef,
useState, useState,
} from 'react' } from 'react'
@@ -20,7 +19,6 @@ import {
formatTrafficHourMinute, formatTrafficHourMinute,
formatTrafficMinuteSecond, formatTrafficMinuteSecond,
formatTrafficName, formatTrafficName,
isSameTrafficData,
} from '@/utils/traffic-sampler' } from '@/utils/traffic-sampler'
export interface EnhancedCanvasTrafficGraphRef { export interface EnhancedCanvasTrafficGraphRef {
@@ -74,16 +72,200 @@ const GRAPH_CONFIG = {
const STALE_DATA_THRESHOLD = 2500 // ms without fresh data => drop FPS 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 { interface EnhancedCanvasTrafficGraphProps {
ref?: Ref<EnhancedCanvasTrafficGraphRef> ref?: Ref<EnhancedCanvasTrafficGraphRef>
} }
const displayDataReducer = (
current: ITrafficDataPoint[],
payload: ITrafficDataPoint[],
): ITrafficDataPoint[] =>
isSameTrafficData(current, payload) ? current : payload
export const EnhancedCanvasTrafficGraph = memo( export const EnhancedCanvasTrafficGraph = memo(
function EnhancedCanvasTrafficGraph({ function EnhancedCanvasTrafficGraph({
ref, ref,
@@ -94,11 +276,9 @@ export const EnhancedCanvasTrafficGraph = memo(
const pause_render_traffic_stats_on_blur = const pause_render_traffic_stats_on_blur =
verge.verge?.pause_render_traffic_stats_on_blur ?? true verge.verge?.pause_render_traffic_stats_on_blur ?? true
const { dataPoints, requestRange, samplerStats } =
useTrafficGraphDataEnhanced()
const [timeRange, setTimeRange] = useState<TimeRange>(10) const [timeRange, setTimeRange] = useState<TimeRange>(10)
const [chartStyle, setChartStyle] = useState<'bezier' | 'line'>('bezier') const [chartStyle, setChartStyle] = useState<'bezier' | 'line'>('bezier')
const [badgeStats, setBadgeStats] = useState({ points: 0, compressed: 0 })
const initialFocusState = const initialFocusState =
typeof document !== 'undefined' ? !document.hidden : true typeof document !== 'undefined' ? !document.hidden : true
@@ -129,66 +309,49 @@ export const EnhancedCanvasTrafficGraph = memo(
const lastDataTimestampRef = useRef<number>(0) const lastDataTimestampRef = useRef<number>(0)
const dataStaleRef = useRef<boolean>(false) const dataStaleRef = useRef<boolean>(false)
const [displayData, dispatchDisplayData] = useReducer( // Live snapshot data for the rAF draw path; React state only tracks the
displayDataReducer, // diagnostics badge inputs so steady-state snapshots stop re-rendering.
[], const displayDataRef = useRef<ITrafficDataPoint[]>([])
) const yScaleRef = useRef<{ topValue: number; bottomValue: number }>({
const debounceTimeoutRef = useRef<number | null>(null) topValue: 1024,
bottomValue: 0,
})
const colors = useMemo( const colors = useMemo(() => {
() => ({ const base = {
up: theme.palette.secondary.main, up: theme.palette.secondary.main,
down: theme.palette.primary.main, down: theme.palette.primary.main,
grid: theme.palette.divider, grid: theme.palette.divider,
text: theme.palette.text.secondary, text: theme.palette.text.secondary,
background: theme.palette.background.paper, 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',
},
}), }),
[theme], [colors],
) )
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) => { const handleFocusStateChange = useEffectEvent((focused: boolean) => {
isWindowFocusedRef.current = focused isWindowFocusedRef.current = focused
@@ -270,14 +433,9 @@ export const EnhancedCanvasTrafficGraph = memo(
[], [],
) )
const yScale = useMemo(
() => computeYScale(displayData),
[computeYScale, displayData],
)
const handleMouseMove = useCallback( const handleMouseMove = useCallback(
(event: React.MouseEvent<HTMLElement>) => { (event: React.MouseEvent<HTMLElement>) => {
if (displayData.length === 0) return if (displayDataRef.current.length === 0) return
pendingMousePositionRef.current = { pendingMousePositionRef.current = {
clientX: event.clientX, clientX: event.clientX,
@@ -294,7 +452,8 @@ export const EnhancedCanvasTrafficGraph = memo(
if (!pendingMousePosition) return if (!pendingMousePosition) return
const canvas = canvasRef.current const canvas = canvasRef.current
if (!canvas || displayData.length === 0) return const data = displayDataRef.current
if (!canvas || data.length === 0) return
const rect = canvas.getBoundingClientRect() const rect = canvas.getBoundingClientRect()
const mouseX = pendingMousePosition.clientX - rect.left const mouseX = pendingMousePosition.clientX - rect.left
@@ -309,11 +468,11 @@ export const EnhancedCanvasTrafficGraph = memo(
0, 0,
Math.min(1, relativeMouseX / effectiveWidth), Math.min(1, relativeMouseX / effectiveWidth),
) )
const dataIndex = Math.round(ratio * (displayData.length - 1)) const dataIndex = Math.round(ratio * (data.length - 1))
if (dataIndex < 0 || dataIndex >= displayData.length) return if (dataIndex < 0 || dataIndex >= data.length) return
const dataPoint = displayData[dataIndex] const dataPoint = data[dataIndex]
const [upValue, upUnit] = parseTraffic(dataPoint.up) const [upValue, upUnit] = parseTraffic(dataPoint.up)
const [downValue, downUnit] = parseTraffic(dataPoint.down) const [downValue, downUnit] = parseTraffic(dataPoint.down)
@@ -322,7 +481,7 @@ export const EnhancedCanvasTrafficGraph = memo(
? formatTrafficName(dataPoint.timestamp) ? formatTrafficName(dataPoint.timestamp)
: t('home.components.traffic.unknownTime') : t('home.components.traffic.unknownTime')
const { topValue: tvH, bottomValue: bvH } = yScale const { topValue: tvH, bottomValue: bvH } = yScaleRef.current
const upY = calculateY(dataPoint.up, rect.height, tvH, bvH) const upY = calculateY(dataPoint.up, rect.height, tvH, bvH)
const downY = calculateY(dataPoint.down, rect.height, tvH, bvH) const downY = calculateY(dataPoint.down, rect.height, tvH, bvH)
const highlightY = const highlightY =
@@ -359,7 +518,7 @@ export const EnhancedCanvasTrafficGraph = memo(
}) })
}) })
}, },
[displayData, calculateY, yScale, t], [calculateY, t],
) )
const handleMouseLeave = useCallback(() => { const handleMouseLeave = useCallback(() => {
@@ -375,45 +534,6 @@ 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( const drawYAxis = useCallback(
( (
ctx: CanvasRenderingContext2D, ctx: CanvasRenderingContext2D,
@@ -425,8 +545,6 @@ export const EnhancedCanvasTrafficGraph = memo(
const padding = GRAPH_CONFIG.padding const padding = GRAPH_CONFIG.padding
const ticks = getYAxisTicks(topValue, bottomValue, height) const ticks = getYAxisTicks(topValue, bottomValue, height)
if (ticks.length === 0) return
ctx.save() ctx.save()
ticks.forEach((tick, index) => { ticks.forEach((tick, index) => {
@@ -470,37 +588,7 @@ export const EnhancedCanvasTrafficGraph = memo(
ctx.restore() ctx.restore()
}, },
[colors.grid, colors.text, colors.background, getYAxisTicks], [colors.grid, colors.text, colors.background],
)
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( const drawTimeAxis = useCallback(
@@ -516,7 +604,7 @@ export const EnhancedCanvasTrafficGraph = memo(
const effectiveWidth = width - padding.left - padding.right const effectiveWidth = width - padding.left - padding.right
const timeAxisY = height - padding.bottom + 14 const timeAxisY = height - padding.bottom + 14
const strategy = getTimeDisplayStrategy(timeRange) const strategy = TIME_DISPLAY_STRATEGIES[timeRange]
ctx.save() ctx.save()
ctx.fillStyle = colors.text ctx.fillStyle = colors.text
@@ -533,15 +621,13 @@ export const EnhancedCanvasTrafficGraph = memo(
Math.ceil((data.length * minPixelDistance) / effectiveWidth), Math.ceil((data.length * minPixelDistance) / effectiveWidth),
) )
const timePoints: Array<{ index: number; x: number; label: string }> = resetTimeAxisPoints()
[]
if (data.length > 0 && data[0].timestamp) { if (data.length > 0 && data[0].timestamp) {
timePoints.push({ pushTimeAxisPoint(
index: 0, padding.left,
x: padding.left, strategy.formatTime(data[0].timestamp),
label: strategy.formatTime(data[0].timestamp), )
})
} }
for ( for (
@@ -553,41 +639,37 @@ export const EnhancedCanvasTrafficGraph = memo(
if (!point.timestamp) continue if (!point.timestamp) continue
const x = padding.left + (i / (data.length - 1)) * effectiveWidth const x = padding.left + (i / (data.length - 1)) * effectiveWidth
timePoints.push({ pushTimeAxisPoint(x, strategy.formatTime(point.timestamp))
index: i,
x,
label: strategy.formatTime(point.timestamp),
})
} }
if (data.length > 1 && data[data.length - 1].timestamp) { if (data.length > 1 && data[data.length - 1].timestamp) {
const lastX = width - padding.right const lastX = width - padding.right
const lastPoint = timePoints[timePoints.length - 1] const lastPoint = timeAxisPoints[timeAxisPoints.length - 1]
if (!lastPoint || lastX - lastPoint.x >= minPixelDistance) { if (!lastPoint || lastX - lastPoint.x >= minPixelDistance) {
timePoints.push({ pushTimeAxisPoint(
index: data.length - 1, lastX,
x: lastX, strategy.formatTime(data[data.length - 1].timestamp),
label: strategy.formatTime(data[data.length - 1].timestamp), )
})
} }
} }
timePoints.forEach((point, index) => { for (let i = 0; i < timeAxisPoints.length; i++) {
if (index === 0) { const point = timeAxisPoints[i]
if (i === 0) {
ctx.textAlign = 'left' ctx.textAlign = 'left'
} else if (index === timePoints.length - 1) { } else if (i === timeAxisPoints.length - 1) {
ctx.textAlign = 'right' ctx.textAlign = 'right'
} else { } else {
ctx.textAlign = 'center' ctx.textAlign = 'center'
} }
ctx.fillText(point.label, point.x, timeAxisY) ctx.fillText(point.label, point.x, timeAxisY)
}) }
ctx.restore() ctx.restore()
}, },
[colors.text, timeRange, getTimeDisplayStrategy], [colors.text, timeRange],
) )
const drawGrid = useCallback( const drawGrid = useCallback(
@@ -632,6 +714,7 @@ export const EnhancedCanvasTrafficGraph = memo(
width: number, width: number,
height: number, height: number,
color: string, color: string,
gradientStops: { start: string; end: string },
withGradient = false, withGradient = false,
topValue: number, topValue: number,
bottomValue: number, bottomValue: number,
@@ -655,13 +738,8 @@ export const EnhancedCanvasTrafficGraph = memo(
0, 0,
height - padding.bottom, height - padding.bottom,
) )
gradient.addColorStop( gradient.addColorStop(0, gradientStops.start)
0, gradient.addColorStop(1, gradientStops.end)
`${color}${Math.round(GRAPH_CONFIG.alpha.gradient * 255)
.toString(16)
.padStart(2, '0')}`,
)
gradient.addColorStop(1, `${color}00`)
ctx.beginPath() ctx.beginPath()
ctx.moveTo(getX(0), getY(0)) ctx.moveTo(getX(0), getY(0))
@@ -752,6 +830,7 @@ export const EnhancedCanvasTrafficGraph = memo(
const drawGraph = useCallback(() => { const drawGraph = useCallback(() => {
const canvas = canvasRef.current const canvas = canvasRef.current
const displayData = displayDataRef.current
if (!canvas || displayData.length === 0) { if (!canvas || displayData.length === 0) {
clearCanvas(canvasRef.current) clearCanvas(canvasRef.current)
clearCanvas(hoverCanvasRef.current) clearCanvas(hoverCanvasRef.current)
@@ -765,7 +844,7 @@ export const EnhancedCanvasTrafficGraph = memo(
// Clear using CSS dimensions; context is already scaled by DPR. // Clear using CSS dimensions; context is already scaled by DPR.
ctx.clearRect(0, 0, cssWidth, cssHeight) ctx.clearRect(0, 0, cssWidth, cssHeight)
const { topValue, bottomValue } = yScale const { topValue, bottomValue } = yScaleRef.current
drawYAxis(ctx, cssWidth, cssHeight, topValue, bottomValue) drawYAxis(ctx, cssWidth, cssHeight, topValue, bottomValue)
@@ -780,6 +859,7 @@ export const EnhancedCanvasTrafficGraph = memo(
cssWidth, cssWidth,
cssHeight, cssHeight,
colors.down, colors.down,
colors.gradient.down,
true, true,
topValue, topValue,
bottomValue, bottomValue,
@@ -792,6 +872,7 @@ export const EnhancedCanvasTrafficGraph = memo(
cssWidth, cssWidth,
cssHeight, cssHeight,
colors.up, colors.up,
colors.gradient.up,
true, true,
topValue, topValue,
bottomValue, bottomValue,
@@ -804,9 +885,7 @@ export const EnhancedCanvasTrafficGraph = memo(
) )
canvas.dataset.perfDraw = String(displayData.at(-1)?.timestamp ?? 0) canvas.dataset.perfDraw = String(displayData.at(-1)?.timestamp ?? 0)
}, [ }, [
displayData,
colors, colors,
yScale,
drawYAxis, drawYAxis,
drawGrid, drawGrid,
drawTimeAxis, drawTimeAxis,
@@ -817,6 +896,7 @@ export const EnhancedCanvasTrafficGraph = memo(
const drawHoverOverlay = useCallback(() => { const drawHoverOverlay = useCallback(() => {
const canvas = hoverCanvasRef.current const canvas = hoverCanvasRef.current
const displayData = displayDataRef.current
if (!canvas || displayData.length < 2) { if (!canvas || displayData.length < 2) {
clearCanvas(canvas) clearCanvas(canvas)
return return
@@ -854,7 +934,7 @@ export const EnhancedCanvasTrafficGraph = memo(
ctx.restore() ctx.restore()
} }
}, [displayData, colors, syncCanvasSize, clearCanvas]) }, [colors, syncCanvasSize, clearCanvas])
const shouldSkipGraphDraw = useCallback(() => { const shouldSkipGraphDraw = useCallback(() => {
if (!isDocumentVisibleRef.current) return true if (!isDocumentVisibleRef.current) return true
@@ -897,6 +977,55 @@ export const EnhancedCanvasTrafficGraph = memo(
}) })
}, [drawGraph, drawHoverOverlay, shouldSkipGraphDraw]) }, [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(() => { useEffect(() => {
tooltipDataRef.current = tooltipData tooltipDataRef.current = tooltipData
scheduleHoverDraw() scheduleHoverDraw()
@@ -966,119 +1095,36 @@ export const EnhancedCanvasTrafficGraph = memo(
return ( return (
<Box <Box
sx={{ sx={rootSx}
width: '100%',
height: '100%',
position: 'relative',
bgcolor: 'action.hover',
borderRadius: 1,
cursor: 'pointer',
overflow: 'hidden',
}}
onClick={toggleStyle} onClick={toggleStyle}
onMouseMove={handleMouseMove} onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave} onMouseLeave={handleMouseLeave}
> >
<canvas <canvas ref={canvasRef} style={canvasStyle} onClick={toggleStyle} />
ref={canvasRef}
style={{
width: '100%',
height: '100%',
display: 'block',
}}
onClick={toggleStyle}
/>
{tooltipData.visible && ( {tooltipData.visible && (
<canvas <canvas ref={hoverCanvasRef} style={hoverCanvasStyle} />
ref={hoverCanvasRef}
style={{
position: 'absolute',
inset: 0,
width: '100%',
height: '100%',
display: 'block',
pointerEvents: 'none',
}}
/>
)} )}
<Box <Box sx={overlaySx}>
sx={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
pointerEvents: 'none',
}}
>
<Box <Box
component="div" component="div"
onClick={handleTimeRangeClick} onClick={handleTimeRangeClick}
sx={{ sx={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)',
},
}}
> >
{getTimeRangeText()} {getTimeRangeText()}
</Box> </Box>
<Box <Box sx={legendsSx}>
sx={{ <Box sx={legendSx.up}>
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')} {t('home.components.traffic.legends.upload')}
</Box> </Box>
<Box <Box sx={legendSx.down}>
sx={{
fontSize: '11px',
fontWeight: 'bold',
color: colors.down,
textAlign: 'right',
}}
>
{t('home.components.traffic.legends.download')} {t('home.components.traffic.legends.download')}
</Box> </Box>
</Box> </Box>
<Box <Box sx={chartStyleHintSx}>
sx={{
position: 'absolute',
bottom: 6,
right: 8,
fontSize: '10px',
color: 'text.disabled',
opacity: 0.7,
}}
>
{t( {t(
chartStyle === 'bezier' chartStyle === 'bezier'
? 'home.components.traffic.chartStyles.smooth' ? 'home.components.traffic.chartStyles.smooth'
@@ -1086,20 +1132,10 @@ export const EnhancedCanvasTrafficGraph = memo(
)} )}
</Box> </Box>
<Box <Box sx={diagnosticsSx}>
sx={{
position: 'absolute',
bottom: 6,
left: 8,
fontSize: '9px',
color: 'text.disabled',
opacity: 0.6,
lineHeight: 1.2,
}}
>
{t('home.components.traffic.diagnostics', { {t('home.components.traffic.diagnostics', {
points: displayData.length, points: badgeStats.points,
compressed: samplerStats.compressedBufferSize, compressed: badgeStats.compressed,
fps: GRAPH_CONFIG.targetFPS, fps: GRAPH_CONFIG.targetFPS,
})} })}
</Box> </Box>
@@ -1127,15 +1163,9 @@ export const EnhancedCanvasTrafficGraph = memo(
whiteSpace: 'nowrap', whiteSpace: 'nowrap',
}} }}
> >
<Box sx={{ color: 'text.secondary', mb: 0.2 }}> <Box sx={tooltipTimeSx}>{tooltipData.timestamp}</Box>
{tooltipData.timestamp} <Box sx={tooltipUpSx}>↑ {tooltipData.upSpeed}</Box>
</Box> <Box sx={tooltipDownSx}>↓ {tooltipData.downSpeed}</Box>
<Box sx={{ color: 'secondary.main', fontWeight: 500 }}>
↑ {tooltipData.upSpeed}
</Box>
<Box sx={{ color: 'primary.main', fontWeight: 500 }}>
↓ {tooltipData.downSpeed}
</Box>
</Box> </Box>
)} )}
</Box> </Box>
+15 -6
View File
@@ -131,6 +131,15 @@ const CompactStatCard = memo(
// 添加显示名称 // 添加显示名称
CompactStatCard.displayName = 'CompactStatCard' 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 = { const fallbackSx = {
p: 2, p: 2,
minHeight: 200, minHeight: 200,
@@ -252,35 +261,35 @@ export const EnhancedTrafficStats = () => {
const statCards = useMemo(() => { const statCards = useMemo(() => {
const cards: StatCardProps[] = [ const cards: StatCardProps[] = [
{ {
icon: <ArrowUpwardRounded fontSize="small" />, icon: uploadSpeedIcon,
title: t('home.components.traffic.metrics.uploadSpeed'), title: t('home.components.traffic.metrics.uploadSpeed'),
value: parsedData.up, value: parsedData.up,
unit: `${parsedData.upUnit}/s`, unit: `${parsedData.upUnit}/s`,
color: 'secondary' as const, color: 'secondary' as const,
}, },
{ {
icon: <ArrowDownwardRounded fontSize="small" />, icon: downloadSpeedIcon,
title: t('home.components.traffic.metrics.downloadSpeed'), title: t('home.components.traffic.metrics.downloadSpeed'),
value: parsedData.down, value: parsedData.down,
unit: `${parsedData.downUnit}/s`, unit: `${parsedData.downUnit}/s`,
color: 'primary' as const, color: 'primary' as const,
}, },
{ {
icon: <LinkRounded fontSize="small" />, icon: activeConnectionsIcon,
title: t('home.components.traffic.metrics.activeConnections'), title: t('home.components.traffic.metrics.activeConnections'),
value: parsedData.connectionsCount, value: parsedData.connectionsCount,
unit: '', unit: '',
color: 'success' as const, color: 'success' as const,
}, },
{ {
icon: <CloudUploadRounded fontSize="small" />, icon: uploadedIcon,
title: t('shared.labels.uploaded'), title: t('shared.labels.uploaded'),
value: parsedData.uploadTotal, value: parsedData.uploadTotal,
unit: parsedData.uploadTotalUnit, unit: parsedData.uploadTotalUnit,
color: 'secondary' as const, color: 'secondary' as const,
}, },
{ {
icon: <CloudDownloadRounded fontSize="small" />, icon: downloadedIcon,
title: t('shared.labels.downloaded'), title: t('shared.labels.downloaded'),
value: parsedData.downloadTotal, value: parsedData.downloadTotal,
unit: parsedData.downloadTotalUnit, unit: parsedData.downloadTotalUnit,
@@ -290,7 +299,7 @@ export const EnhancedTrafficStats = () => {
if (displayMemory) { if (displayMemory) {
cards.push({ cards.push({
icon: <MemoryRounded fontSize="small" />, icon: memoryUsageIcon,
title: t('home.components.traffic.metrics.memoryUsage'), title: t('home.components.traffic.metrics.memoryUsage'),
value: parsedData.inuse, value: parsedData.inuse,
unit: parsedData.inuseUnit, unit: parsedData.inuseUnit,
+34 -36
View File
@@ -42,6 +42,39 @@ 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 = () => { export const LayoutTraffic = () => {
const { t } = useTranslation() const { t } = useTranslation()
const { verge } = useVerge() const { verge } = useVerge()
@@ -74,31 +107,6 @@ export const LayoutTraffic = () => {
const [down, downUnit] = parseTraffic(traffic?.down || 0) const [down, downUnit] = parseTraffic(traffic?.down || 0)
const [inuse, inuseUnit] = parseTraffic(memory?.inuse || 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 ( return (
<ErrorBoundary <ErrorBoundary
FallbackComponent={TrafficUnavailableFallback} FallbackComponent={TrafficUnavailableFallback}
@@ -120,9 +128,6 @@ export const LayoutTraffic = () => {
<Box <Box
title={`${t('home.components.traffic.metrics.uploadSpeed')}`} title={`${t('home.components.traffic.metrics.uploadSpeed')}`}
{...boxStyle} {...boxStyle}
sx={{
...boxStyle.sx,
}}
> >
<ArrowUpwardRounded <ArrowUpwardRounded
{...iconStyle} {...iconStyle}
@@ -137,9 +142,6 @@ export const LayoutTraffic = () => {
<Box <Box
title={`${t('home.components.traffic.metrics.downloadSpeed')}`} title={`${t('home.components.traffic.metrics.downloadSpeed')}`}
{...boxStyle} {...boxStyle}
sx={{
...boxStyle.sx,
}}
> >
<ArrowDownwardRounded <ArrowDownwardRounded
{...iconStyle} {...iconStyle}
@@ -154,11 +156,7 @@ export const LayoutTraffic = () => {
{displayMemory && ( {displayMemory && (
<Box <Box
title={`${t('home.components.traffic.metrics.memoryUsage')} `} title={`${t('home.components.traffic.metrics.memoryUsage')} `}
{...boxStyle} {...memoryBoxStyle}
sx={{
...boxStyle.sx,
cursor: 'auto',
}}
color={'disabled'} color={'disabled'}
> >
<MemoryRounded {...iconStyle} /> <MemoryRounded {...iconStyle} />
+58 -45
View File
@@ -2,6 +2,7 @@ import { styled, Box } from '@mui/material'
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import type { SearchState } from '@/components/base' import type { SearchState } from '@/components/base'
import { buildRegex } from '@/utils/search-matcher'
const Item = styled(Box)(({ theme: { palette, typography } }) => ({ const Item = styled(Box)(({ theme: { palette, typography } }) => ({
padding: '8px 0', padding: '8px 0',
@@ -47,62 +48,74 @@ interface Props {
searchState?: SearchState 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 LogItem = ({ value, searchState }: Props) => {
const renderHighlightText = (text: string) => { const renderHighlightText = (text: string) => {
if (!searchState?.text.trim()) return text if (!searchState?.text.trim()) return text
try { const regex = getHighlightRegex(searchState)
const searchText = searchState.text if (!regex) return text
let pattern: string
if (searchState.useRegularExpression) { const elements: ReactNode[] = []
try { let lastIndex = 0
new RegExp(searchText) let match: RegExpExecArray | null
pattern = searchText
} catch { while ((match = regex.exec(text)) !== null) {
pattern = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') const start = match.index
} const matchText = match[0]
} else {
const escaped = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') if (matchText === '') {
pattern = searchState.matchWholeWord ? `\\b${escaped}\\b` : escaped regex.lastIndex += 1
continue
} }
const flags = searchState.matchCase ? 'g' : 'gi' if (start > lastIndex) {
const regex = new RegExp(pattern, flags) elements.push(text.slice(lastIndex, start))
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
} }
if (lastIndex < text.length) { elements.push(
elements.push(text.slice(lastIndex)) <span key={`highlight-${start}`} className="highlight">
} {matchText}
</span>,
)
return elements.length ? elements : text lastIndex = start + matchText.length
} catch {
return text
} }
if (lastIndex < text.length) {
elements.push(text.slice(lastIndex))
}
return elements.length ? elements : text
} }
return ( return (
+31 -16
View File
@@ -60,6 +60,23 @@ 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 { function useStableCallback<T extends (...args: any[]) => any>(fn: T): T {
const ref = useRef(fn) const ref = useRef(fn)
ref.current = fn ref.current = fn
@@ -150,13 +167,12 @@ function useProxyRenderState(
const saveScrollPosition = useCallback( const saveScrollPosition = useCallback(
(scrollTop: number) => { (scrollTop: number) => {
const scrollPositions = localStorage.getItem('proxy-scroll-positions') const scrollPositions = readScrollPositions() ?? {}
? JSON.parse(localStorage.getItem('proxy-scroll-positions') ?? '{}')
: {}
scrollPositions[scrollPositionKey] = scrollTop scrollPositions[scrollPositionKey] = scrollTop
scrollPositionsCache = scrollPositions
try { try {
localStorage.setItem( localStorage.setItem(
'proxy-scroll-positions', SCROLL_POSITIONS_KEY,
JSON.stringify(scrollPositions), JSON.stringify(scrollPositions),
) )
} catch (e) { } catch (e) {
@@ -167,15 +183,10 @@ function useProxyRenderState(
) )
const getScrollPosition = useCallback(() => { const getScrollPosition = useCallback(() => {
try { const savedPositions = readScrollPositions()
const savedPositions = localStorage.getItem('proxy-scroll-positions') if (savedPositions) {
if (savedPositions) { const savedPosition = savedPositions[scrollPositionKey]
const positions = JSON.parse(savedPositions) return savedPosition ?? 0
const savedPosition = positions[scrollPositionKey]
return savedPosition ?? 0
}
} catch (e) {
console.error('Error restoring scroll position:', e)
} }
}, [scrollPositionKey]) }, [scrollPositionKey])
@@ -240,9 +251,13 @@ function ChainProxyGroups(props: {
const rangeExtractor = useCallback( const rangeExtractor = useCallback(
(range: Parameters<typeof defaultRangeExtractor>[0]) => { (range: Parameters<typeof defaultRangeExtractor>[0]) => {
const activeStickyIndex = [...stickyGroupIndexes] let activeStickyIndex: number | undefined
.reverse() for (let i = stickyGroupIndexes.length - 1; i >= 0; i--) {
.find((index) => index <= range.startIndex) if (stickyGroupIndexes[i] <= range.startIndex) {
activeStickyIndex = stickyGroupIndexes[i]
break
}
}
activeStickyIndexRef.current = activeStickyIndex ?? null activeStickyIndexRef.current = activeStickyIndex ?? null
const indexes = defaultRangeExtractor(range) const indexes = defaultRangeExtractor(range)
@@ -22,6 +22,7 @@ const buildInitialValues = (verge?: IVergeConfig | null) => ({
appLogMaxSize: verge?.app_log_max_size ?? 128, appLogMaxSize: verge?.app_log_max_size ?? 128,
appLogMaxCount: verge?.app_log_max_count ?? 8, appLogMaxCount: verge?.app_log_max_count ?? 8,
autoCloseConnection: verge?.auto_close_connection ?? true, autoCloseConnection: verge?.auto_close_connection ?? true,
autoSwitchSelectorGroup: verge?.auto_switch_selector_group ?? true,
autoCheckUpdate: verge?.auto_check_update ?? true, autoCheckUpdate: verge?.auto_check_update ?? true,
enableBuiltinEnhanced: verge?.enable_builtin_enhanced ?? true, enableBuiltinEnhanced: verge?.enable_builtin_enhanced ?? true,
proxyLayoutColumn: verge?.proxy_layout_column || 6, proxyLayoutColumn: verge?.proxy_layout_column || 6,
@@ -55,6 +56,7 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
app_log_max_size: values.appLogMaxSize, app_log_max_size: values.appLogMaxSize,
app_log_max_count: values.appLogMaxCount, app_log_max_count: values.appLogMaxCount,
auto_close_connection: values.autoCloseConnection, auto_close_connection: values.autoCloseConnection,
auto_switch_selector_group: values.autoSwitchSelectorGroup,
auto_check_update: values.autoCheckUpdate, auto_check_update: values.autoCheckUpdate,
enable_builtin_enhanced: values.enableBuiltinEnhanced, enable_builtin_enhanced: values.enableBuiltinEnhanced,
proxy_layout_column: values.proxyLayoutColumn, proxy_layout_column: values.proxyLayoutColumn,
@@ -202,6 +204,28 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
/> />
</ListItem> </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 <ListItem
data-setting-target="settings.modals.misc.fields.autoCheckUpdate" data-setting-target="settings.modals.misc.fields.autoCheckUpdate"
sx={{ padding: '5px 2px' }} sx={{ padding: '5px 2px' }}
+8 -1
View File
@@ -62,7 +62,14 @@ export const SettingItem: React.FC<ItemProps> = ({
</ListItemButton> </ListItemButton>
</ListItem> </ListItem>
) : ( ) : (
<ListItem data-setting-target={searchTarget} sx={{ pt: '5px', pb: '5px' }}> <ListItem
data-setting-target={searchTarget}
sx={{
pt: '5px',
pb: '5px',
'&:hover': { bgcolor: 'action.hover' },
}}
>
<ListItemText primary={primary} secondary={secondary} /> <ListItemText primary={primary} secondary={secondary} />
{children} {children}
</ListItem> </ListItem>
@@ -480,6 +480,8 @@ const settingsCatalog: readonly SettingEntry[] = [
'settings.modals.misc.fields.appLogMaxCount': 'app log max count', 'settings.modals.misc.fields.appLogMaxCount': 'app log max count',
'settings.modals.misc.fields.autoCloseConnections': 'settings.modals.misc.fields.autoCloseConnections':
'auto close connections', 'auto close connections',
'settings.modals.misc.fields.autoSwitchSelectorGroup':
'auto switch select group',
'settings.modals.misc.fields.autoCheckUpdate': 'auto check update', 'settings.modals.misc.fields.autoCheckUpdate': 'auto check update',
'settings.modals.misc.fields.enableBuiltinEnhanced': 'settings.modals.misc.fields.enableBuiltinEnhanced':
'enable builtin enhanced', 'enable builtin enhanced',
+18 -7
View File
@@ -158,9 +158,11 @@ const EMPTY_DATA: ITrafficDataPoint[] = []
export const useTrafficMonitorEnhanced = (options?: { export const useTrafficMonitorEnhanced = (options?: {
subscribe?: boolean subscribe?: boolean
enabled?: boolean enabled?: boolean
onSnapshot?: (message: ITrafficWorkerSnapshotMessage) => void
}) => { }) => {
const subscribeToSnapshots = options?.subscribe ?? true const subscribeToSnapshots = options?.subscribe ?? true
const enabled = options?.enabled ?? true const enabled = options?.enabled ?? true
const onSnapshot = options?.onSnapshot
const isVisible = useVisibility() const isVisible = useVisibility()
const [latestSnapshot, setLatestSnapshot] = useState<{ const [latestSnapshot, setLatestSnapshot] = useState<{
dataPoints: ITrafficDataPoint[] dataPoints: ITrafficDataPoint[]
@@ -174,6 +176,8 @@ export const useTrafficMonitorEnhanced = (options?: {
const currentRangeRef = useRef<number>(WORKER_CONFIG.defaultRangeMinutes) const currentRangeRef = useRef<number>(WORKER_CONFIG.defaultRangeMinutes)
const isVisibleRef = useRef(isVisible) const isVisibleRef = useRef(isVisible)
isVisibleRef.current = isVisible isVisibleRef.current = isVisible
const onSnapshotRef = useRef(onSnapshot)
onSnapshotRef.current = onSnapshot
// 注册引用计数与Worker生命周期 // 注册引用计数与Worker生命周期
useEffect(() => { useEffect(() => {
@@ -186,9 +190,12 @@ export const useTrafficMonitorEnhanced = (options?: {
client.start(currentRangeRef.current) client.start(currentRangeRef.current)
let unsubscribe: (() => void) | undefined let unsubscribe: (() => void) | undefined
if (subscribeToSnapshots) { if (subscribeToSnapshots || onSnapshot) {
unsubscribe = client.onSnapshot((message) => { unsubscribe = client.onSnapshot((message) => {
if (!isVisibleRef.current) return // 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
setLatestSnapshot({ setLatestSnapshot({
dataPoints: message.dataPoints, dataPoints: message.dataPoints,
samplerStats: message.samplerStats, samplerStats: message.samplerStats,
@@ -203,14 +210,14 @@ export const useTrafficMonitorEnhanced = (options?: {
client.stop() client.stop()
} }
} }
}, [enabled, subscribeToSnapshots]) }, [enabled, subscribeToSnapshots, onSnapshot])
// Re-prime snapshot ingestion after every visible transition // Re-prime snapshot ingestion after every visible transition
useEffect(() => { useEffect(() => {
if (enabled && subscribeToSnapshots && isVisible) { if (enabled && isVisible && (subscribeToSnapshots || onSnapshot)) {
clientRef.current?.requestSnapshot() clientRef.current?.requestSnapshot()
} }
}, [enabled, subscribeToSnapshots, isVisible]) }, [enabled, subscribeToSnapshots, onSnapshot, isVisible])
// 添加流量数据 // 添加流量数据
const appendData = useCallback( const appendData = useCallback(
@@ -244,8 +251,12 @@ export const useTrafficMonitorEnhanced = (options?: {
/** /**
* 图表数据Hook * 图表数据Hook
*/ */
export const useTrafficGraphDataEnhanced = () => { export const useTrafficGraphDataEnhanced = (options?: {
const { graphData, samplerStats } = useTrafficMonitorEnhanced() subscribe?: boolean
enabled?: boolean
onSnapshot?: (message: ITrafficWorkerSnapshotMessage) => void
}) => {
const { graphData, samplerStats } = useTrafficMonitorEnhanced(options)
return { return {
...graphData, ...graphData,
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "App Log Max Size", "appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count", "appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "إغلاق الاتصالات تلقائيًا", "autoCloseConnections": "إغلاق الاتصالات تلقائيًا",
"autoSwitchSelectorGroup": "تبديل مجموعة select تلقائيًا",
"autoCheckUpdate": "فحص التحديث تلقائيًا", "autoCheckUpdate": "فحص التحديث تلقائيًا",
"enableBuiltinEnhanced": "تفعيل التحسين المدمج", "enableBuiltinEnhanced": "تفعيل التحسين المدمج",
"proxyLayoutColumns": "أعمدة عرض الوكيل", "proxyLayoutColumns": "أعمدة عرض الوكيل",
@@ -422,6 +423,7 @@
}, },
"tooltips": { "tooltips": {
"autoCloseConnections": "إنهاء الاتصالات القائمة عند تغيير اختيار مجموعة الوكيل أو وضع الوكيل", "autoCloseConnections": "إنهاء الاتصالات القائمة عند تغيير اختيار مجموعة الوكيل أو وضع الوكيل",
"autoSwitchSelectorGroup": "في وضع القواعد، عند اختيار عقدة في مجموعة url-test أو fallback يتم أيضًا تحويل أول مجموعة select تحتوي عليها إلى تلك المجموعة",
"enableBuiltinEnhanced": "معالجة توافق ملف التكوين", "enableBuiltinEnhanced": "معالجة توافق ملف التكوين",
"autoDelayDetection": "يختبر زمن استجابة العقدة الحالية على نحو دوري في الخلفية", "autoDelayDetection": "يختبر زمن استجابة العقدة الحالية على نحو دوري في الخلفية",
"defaultLatencyTest": "يُستخدم فقط لاختبار طلب HTTP العميل. لن يؤثر على ملف التكوين" "defaultLatencyTest": "يُستخدم فقط لاختبار طلب HTTP العميل. لن يؤثر على ملف التكوين"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "Maximale Größe des Anwendungsprotokolls", "appLogMaxSize": "Maximale Größe des Anwendungsprotokolls",
"appLogMaxCount": "Maximale Anzahl der Anwendungsprotokolle", "appLogMaxCount": "Maximale Anzahl der Anwendungsprotokolle",
"autoCloseConnections": "Verbindungen automatisch schließen", "autoCloseConnections": "Verbindungen automatisch schließen",
"autoSwitchSelectorGroup": "Select-Gruppe automatisch umschalten",
"autoCheckUpdate": "Automatisch auf Updates prüfen", "autoCheckUpdate": "Automatisch auf Updates prüfen",
"enableBuiltinEnhanced": "Eingebaute Verbesserungen aktivieren", "enableBuiltinEnhanced": "Eingebaute Verbesserungen aktivieren",
"proxyLayoutColumns": "Anzahl der Spalten im Proxy-Layout", "proxyLayoutColumns": "Anzahl der Spalten im Proxy-Layout",
@@ -422,6 +423,7 @@
}, },
"tooltips": { "tooltips": {
"autoCloseConnections": "Wenn der ausgewählte Knoten in der Proxy-Gruppe oder der Proxy-Modus geändert wird, werden die bestehenden Verbindungen geschlossen.", "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", "enableBuiltinEnhanced": "Kompatibilitätsbehandlung der Konfigurationsdatei",
"autoDelayDetection": "Überprüft regelmäßig im Hintergrund die Latenz des aktuellen Knotens", "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." "defaultLatencyTest": "Dies wird nur für HTTP-Client-Anfragentests verwendet und hat keine Auswirkungen auf die Konfigurationsdatei."
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "App Log Max Size", "appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count", "appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "Auto Close Connections", "autoCloseConnections": "Auto Close Connections",
"autoSwitchSelectorGroup": "Auto Switch Select Group",
"autoCheckUpdate": "Auto Check Update", "autoCheckUpdate": "Auto Check Update",
"enableBuiltinEnhanced": "Enable Builtin Enhanced", "enableBuiltinEnhanced": "Enable Builtin Enhanced",
"proxyLayoutColumns": "Proxy Layout Columns", "proxyLayoutColumns": "Proxy Layout Columns",
@@ -422,6 +423,7 @@
}, },
"tooltips": { "tooltips": {
"autoCloseConnections": "Terminate established connections when the proxy group selection or proxy mode changes", "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", "enableBuiltinEnhanced": "Compatibility handling for the configuration file",
"autoDelayDetection": "Periodically test the current node latency in the background", "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" "defaultLatencyTest": "Used for HTTP client request testing only and won't make a difference to the configuration file"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "App Log Max Size", "appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count", "appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "Cerrar conexiones automáticamente", "autoCloseConnections": "Cerrar conexiones automáticamente",
"autoSwitchSelectorGroup": "Cambiar grupo select automáticamente",
"autoCheckUpdate": "Comprobar actualizaciones automáticamente", "autoCheckUpdate": "Comprobar actualizaciones automáticamente",
"enableBuiltinEnhanced": "Habilitar funciones mejoradas integradas", "enableBuiltinEnhanced": "Habilitar funciones mejoradas integradas",
"proxyLayoutColumns": "Número de columnas en la disposición de la página de proxy", "proxyLayoutColumns": "Número de columnas en la disposición de la página de proxy",
@@ -422,6 +423,7 @@
}, },
"tooltips": { "tooltips": {
"autoCloseConnections": "Cierra las conexiones establecidas cuando se cambia el nodo seleccionado en el grupo de proxy o el modo de proxy.", "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", "enableBuiltinEnhanced": "Procesamiento de compatibilidad de archivos de configuración",
"autoDelayDetection": "Prueba periódicamente la latencia del nodo actual en segundo plano", "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." "defaultLatencyTest": "Solo se utiliza para pruebas de solicitudes de clientes HTTP y no afectará al archivo de configuración."
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "App Log Max Size", "appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count", "appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "بستن خودکار اتصالات", "autoCloseConnections": "بستن خودکار اتصالات",
"autoSwitchSelectorGroup": "تغییر خودکار گروه select",
"autoCheckUpdate": "بررسی خودکار به‌روزرسانی", "autoCheckUpdate": "بررسی خودکار به‌روزرسانی",
"enableBuiltinEnhanced": "فعال کردن تقویت داخلی", "enableBuiltinEnhanced": "فعال کردن تقویت داخلی",
"proxyLayoutColumns": "ستون چیدمان پراکسی", "proxyLayoutColumns": "ستون چیدمان پراکسی",
@@ -422,6 +423,7 @@
}, },
"tooltips": { "tooltips": {
"autoCloseConnections": "اتصالات برقرار شده را هنگام تغییر انتخاب گروه پروکسی یا حالت پروکسی خاتمه دهید", "autoCloseConnections": "اتصالات برقرار شده را هنگام تغییر انتخاب گروه پروکسی یا حالت پروکسی خاتمه دهید",
"autoSwitchSelectorGroup": "در حالت قانون، با انتخاب یک گره در گروه url-test یا fallback، اولین گروه select شامل آن نیز به همان گروه تغییر می‌کند",
"enableBuiltinEnhanced": "مدیریت سازگاری برای فایل پیکربندی", "enableBuiltinEnhanced": "مدیریت سازگاری برای فایل پیکربندی",
"autoDelayDetection": "به‌صورت دوره‌ای تأخیر گره فعلی را در پس‌زمینه آزمایش می‌کند", "autoDelayDetection": "به‌صورت دوره‌ای تأخیر گره فعلی را در پس‌زمینه آزمایش می‌کند",
"defaultLatencyTest": "فقط برای تست درخواست‌های کلاینت HTTP استفاده می‌شود و بر فایل پیکربندی تأثیری نخواهد داشت" "defaultLatencyTest": "فقط برای تست درخواست‌های کلاینت HTTP استفاده می‌شود و بر فایل پیکربندی تأثیری نخواهد داشت"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "App Log Max Size", "appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count", "appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "Tutup Koneksi Otomatis", "autoCloseConnections": "Tutup Koneksi Otomatis",
"autoSwitchSelectorGroup": "Alihkan Grup Select Otomatis",
"autoCheckUpdate": "Periksa Pembaruan Otomatis", "autoCheckUpdate": "Periksa Pembaruan Otomatis",
"enableBuiltinEnhanced": "Aktifkan Peningkatan Bawaan", "enableBuiltinEnhanced": "Aktifkan Peningkatan Bawaan",
"proxyLayoutColumns": "Kolom Tata Letak Proksi", "proxyLayoutColumns": "Kolom Tata Letak Proksi",
@@ -422,6 +423,7 @@
}, },
"tooltips": { "tooltips": {
"autoCloseConnections": "Hentikan koneksi yang sudah ada saat pemilihan grup proksi atau mode proksi berubah", "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", "enableBuiltinEnhanced": "Penanganan kompatibilitas untuk file konfigurasi",
"autoDelayDetection": "Secara berkala menguji latensi node saat ini di latar belakang", "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" "defaultLatencyTest": "Digunakan hanya untuk pengujian permintaan klien HTTP dan tidak akan mempengaruhi file konfigurasi"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "App Log Max Size", "appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count", "appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "接続を自動的に閉じる", "autoCloseConnections": "接続を自動的に閉じる",
"autoSwitchSelectorGroup": "ノード選択時にグループを連動",
"autoCheckUpdate": "自動更新チェック", "autoCheckUpdate": "自動更新チェック",
"enableBuiltinEnhanced": "組み込み拡張機能を有効にする", "enableBuiltinEnhanced": "組み込み拡張機能を有効にする",
"proxyLayoutColumns": "プロキシページのレイアウト列数", "proxyLayoutColumns": "プロキシページのレイアウト列数",
@@ -422,6 +423,7 @@
}, },
"tooltips": { "tooltips": {
"autoCloseConnections": "プロキシグループで選択されたノードまたはプロキシモードが変更されたときに、既存の接続を閉じます。", "autoCloseConnections": "プロキシグループで選択されたノードまたはプロキシモードが変更されたときに、既存の接続を閉じます。",
"autoSwitchSelectorGroup": "ルールモードで url-test または fallback グループのノードを選択すると、そのグループを含む最初の select グループも当該グループに切り替えます。",
"enableBuiltinEnhanced": "設定ファイルの互換性処理", "enableBuiltinEnhanced": "設定ファイルの互換性処理",
"autoDelayDetection": "バックグラウンドで現在のノードのレイテンシーを定期的にテストします", "autoDelayDetection": "バックグラウンドで現在のノードのレイテンシーを定期的にテストします",
"defaultLatencyTest": "HTTPクライアントリクエストテストにのみ使用され、設定ファイルには影響しません。" "defaultLatencyTest": "HTTPクライアントリクエストテストにのみ使用され、設定ファイルには影響しません。"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "앱 로그 최대 크기", "appLogMaxSize": "앱 로그 최대 크기",
"appLogMaxCount": "앱 로그 최대 개수", "appLogMaxCount": "앱 로그 최대 개수",
"autoCloseConnections": "연결 자동 종료", "autoCloseConnections": "연결 자동 종료",
"autoSwitchSelectorGroup": "노드 선택 시 그룹 연동",
"autoCheckUpdate": "업데이트 자동 확인", "autoCheckUpdate": "업데이트 자동 확인",
"enableBuiltinEnhanced": "내장 향상 기능 사용", "enableBuiltinEnhanced": "내장 향상 기능 사용",
"proxyLayoutColumns": "프록시 레이아웃 열 수", "proxyLayoutColumns": "프록시 레이아웃 열 수",
@@ -422,6 +423,7 @@
}, },
"tooltips": { "tooltips": {
"autoCloseConnections": "프록시 그룹 선택 또는 프록시 모드 변경 시 기존 연결을 종료합니다", "autoCloseConnections": "프록시 그룹 선택 또는 프록시 모드 변경 시 기존 연결을 종료합니다",
"autoSwitchSelectorGroup": "규칙 모드에서 url-test 또는 fallback 그룹의 노드를 선택하면 해당 그룹을 포함하는 첫 번째 select 그룹도 그 그룹으로 전환합니다",
"enableBuiltinEnhanced": "구성 파일에 대한 호환성 처리를 수행합니다", "enableBuiltinEnhanced": "구성 파일에 대한 호환성 처리를 수행합니다",
"autoDelayDetection": "백그라운드에서 현재 노드의 지연을 주기적으로 검사합니다", "autoDelayDetection": "백그라운드에서 현재 노드의 지연을 주기적으로 검사합니다",
"defaultLatencyTest": "HTTP 클라이언트 요청 테스트에만 사용되며 구성 파일에는 영향을 주지 않습니다" "defaultLatencyTest": "HTTP 클라이언트 요청 테스트에만 사용되며 구성 파일에는 영향을 주지 않습니다"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "Tamanho Máximo do Log do Aplicativo", "appLogMaxSize": "Tamanho Máximo do Log do Aplicativo",
"appLogMaxCount": "Quantidade Máxima de Logs do Aplicativo", "appLogMaxCount": "Quantidade Máxima de Logs do Aplicativo",
"autoCloseConnections": "Fechar Conexões Automaticamente", "autoCloseConnections": "Fechar Conexões Automaticamente",
"autoSwitchSelectorGroup": "Alternar Grupo Select Automaticamente",
"autoCheckUpdate": "Verificar Atualizações Automaticamente", "autoCheckUpdate": "Verificar Atualizações Automaticamente",
"enableBuiltinEnhanced": "Ativar Aprimoramento Integrado", "enableBuiltinEnhanced": "Ativar Aprimoramento Integrado",
"proxyLayoutColumns": "Colunas do Layout de Proxy", "proxyLayoutColumns": "Colunas do Layout de Proxy",
@@ -422,6 +423,7 @@
}, },
"tooltips": { "tooltips": {
"autoCloseConnections": "Encerra as conexões estabelecidas quando a seleção do grupo de proxy ou o modo de proxy muda", "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", "enableBuiltinEnhanced": "Tratamento de compatibilidade para o arquivo de configuração",
"autoDelayDetection": "Testa periodicamente a latência do nó atual em segundo plano", "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" "defaultLatencyTest": "Usado apenas para testes de requisição do cliente HTTP e não afeta o arquivo de configuração"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "Максимальный размер журнала приложения", "appLogMaxSize": "Максимальный размер журнала приложения",
"appLogMaxCount": "Максимальное количество файлов журнала", "appLogMaxCount": "Максимальное количество файлов журнала",
"autoCloseConnections": "Автоматическое закрытие соединений", "autoCloseConnections": "Автоматическое закрытие соединений",
"autoSwitchSelectorGroup": "Автопереключение группы select",
"autoCheckUpdate": "Автоматическая проверка обновлений", "autoCheckUpdate": "Автоматическая проверка обновлений",
"enableBuiltinEnhanced": "Включить встроенные улучшения", "enableBuiltinEnhanced": "Включить встроенные улучшения",
"proxyLayoutColumns": "Количество столбцов в макете прокси", "proxyLayoutColumns": "Количество столбцов в макете прокси",
@@ -422,6 +423,7 @@
}, },
"tooltips": { "tooltips": {
"autoCloseConnections": "Закрывать установленные соединения при изменении выбора группы прокси или режима прокси", "autoCloseConnections": "Закрывать установленные соединения при изменении выбора группы прокси или режима прокси",
"autoSwitchSelectorGroup": "В режиме правил при выборе узла в группе url-test или fallback первая группа select, содержащая эту группу, также переключается на неё",
"enableBuiltinEnhanced": "Обработка совместимости для файла конфигурации", "enableBuiltinEnhanced": "Обработка совместимости для файла конфигурации",
"autoDelayDetection": "Периодически проверяет задержку текущего узла в фоновом режиме", "autoDelayDetection": "Периодически проверяет задержку текущего узла в фоновом режиме",
"defaultLatencyTest": "Используется только для тестирования HTTP-запросов клиента и не влияет на файл конфигурации" "defaultLatencyTest": "Используется только для тестирования HTTP-запросов клиента и не влияет на файл конфигурации"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "Uygulama Günlüğü En Büyük Boyutu", "appLogMaxSize": "Uygulama Günlüğü En Büyük Boyutu",
"appLogMaxCount": "Uygulama Günlüğü En Fazla Dosya Sayısı", "appLogMaxCount": "Uygulama Günlüğü En Fazla Dosya Sayısı",
"autoCloseConnections": "Bağlantıları Otomatik Kapat", "autoCloseConnections": "Bağlantıları Otomatik Kapat",
"autoSwitchSelectorGroup": "Select Grubunu Otomatik Değiştir",
"autoCheckUpdate": "Otomatik Güncelleme Kontrolü", "autoCheckUpdate": "Otomatik Güncelleme Kontrolü",
"enableBuiltinEnhanced": "Yerleşik Geliştirilmiş Modu Etkinleştir", "enableBuiltinEnhanced": "Yerleşik Geliştirilmiş Modu Etkinleştir",
"proxyLayoutColumns": "Vekil Düzeni Sütunları", "proxyLayoutColumns": "Vekil Düzeni Sütunları",
@@ -422,6 +423,7 @@
}, },
"tooltips": { "tooltips": {
"autoCloseConnections": "Vekil grup seçimi veya vekil modu değiştiğinde kurulan bağlantıları sonlandır", "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", "enableBuiltinEnhanced": "Yapılandırma dosyası için uyumluluk işleme",
"autoDelayDetection": "Arka planda mevcut düğümün gecikmesini periyodik olarak test eder", "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" "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,6 +411,7 @@
"appLogMaxSize": "App Log Max Size", "appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count", "appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "Тоташуларны автоматик ябу", "autoCloseConnections": "Тоташуларны автоматик ябу",
"autoSwitchSelectorGroup": "Select төркемен автоматик күчерү",
"autoCheckUpdate": "Яңартуларны автоматик тикшерү", "autoCheckUpdate": "Яңартуларны автоматик тикшерү",
"enableBuiltinEnhanced": "Эчке камилләштерүне кабызу", "enableBuiltinEnhanced": "Эчке камилләштерүне кабызу",
"proxyLayoutColumns": "Прокси күрсәтү баганалары саны", "proxyLayoutColumns": "Прокси күрсәтү баганалары саны",
@@ -422,6 +423,7 @@
}, },
"tooltips": { "tooltips": {
"autoCloseConnections": "Прокси төркеме яисә режимын үзгәрткәндә актив тоташуларны өзү", "autoCloseConnections": "Прокси төркеме яисә режимын үзгәрткәндә актив тоташуларны өзү",
"autoSwitchSelectorGroup": "Кагыйдәләр режимында url-test яки fallback төркемендә төен сайлаганда, аны эченә алган беренче select төркеме дә шул төркемгә күчә",
"enableBuiltinEnhanced": "Конфигурация файлы белән туры килә торган өстәмә оптимизация", "enableBuiltinEnhanced": "Конфигурация файлы белән туры килә торган өстәмә оптимизация",
"autoDelayDetection": "Фон режимында хәзерге төен тоткарлыгын периодик тикшерә", "autoDelayDetection": "Фон режимында хәзерге төен тоткарлыгын периодик тикшерә",
"defaultLatencyTest": "Бу фәкать клиентның HTTP сораулары тесты өчен кулланыла, конфигурация файлына йогынты ясамый" "defaultLatencyTest": "Бу фәкать клиентның HTTP сораулары тесты өчен кулланыла, конфигурация файлына йогынты ясамый"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "应用日志最大大小", "appLogMaxSize": "应用日志最大大小",
"appLogMaxCount": "应用日志最大数量", "appLogMaxCount": "应用日志最大数量",
"autoCloseConnections": "自动关闭连接", "autoCloseConnections": "自动关闭连接",
"autoSwitchSelectorGroup": "选择节点时联动代理组",
"autoCheckUpdate": "自动检查更新", "autoCheckUpdate": "自动检查更新",
"enableBuiltinEnhanced": "内置增强功能", "enableBuiltinEnhanced": "内置增强功能",
"proxyLayoutColumns": "代理页布局列数", "proxyLayoutColumns": "代理页布局列数",
@@ -422,6 +423,7 @@
}, },
"tooltips": { "tooltips": {
"autoCloseConnections": "当代理组选中节点或代理模式变动时,关闭已建立的连接", "autoCloseConnections": "当代理组选中节点或代理模式变动时,关闭已建立的连接",
"autoSwitchSelectorGroup": "规则模式下,在 url-test 或 fallback 代理组中选择节点时,将首个包含该组的 select 代理组切换到该组",
"enableBuiltinEnhanced": "配置文件的兼容性处理", "enableBuiltinEnhanced": "配置文件的兼容性处理",
"autoDelayDetection": "后台定时检测当前节点延迟", "autoDelayDetection": "后台定时检测当前节点延迟",
"defaultLatencyTest": "仅用于 HTTP 客户端请求测试,不会对配置文件产生影响" "defaultLatencyTest": "仅用于 HTTP 客户端请求测试,不会对配置文件产生影响"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "應用程式日誌最大大小", "appLogMaxSize": "應用程式日誌最大大小",
"appLogMaxCount": "應用程式日誌最大數量", "appLogMaxCount": "應用程式日誌最大數量",
"autoCloseConnections": "自動關閉連線", "autoCloseConnections": "自動關閉連線",
"autoSwitchSelectorGroup": "選擇節點時聯動代理組",
"autoCheckUpdate": "自動檢查更新", "autoCheckUpdate": "自動檢查更新",
"enableBuiltinEnhanced": "內建增強功能", "enableBuiltinEnhanced": "內建增強功能",
"proxyLayoutColumns": "代理頁面欄數", "proxyLayoutColumns": "代理頁面欄數",
@@ -422,6 +423,7 @@
}, },
"tooltips": { "tooltips": {
"autoCloseConnections": "當代理組選中節點或代理模式變動時,關閉已建立的連線", "autoCloseConnections": "當代理組選中節點或代理模式變動時,關閉已建立的連線",
"autoSwitchSelectorGroup": "規則模式下,在 url-test 或 fallback 代理組中選擇節點時,將首個包含該組的 select 代理組切換到該組",
"enableBuiltinEnhanced": "配置檔案的相容性處理", "enableBuiltinEnhanced": "配置檔案的相容性處理",
"autoDelayDetection": "在背景定時偵測目前節點延遲", "autoDelayDetection": "在背景定時偵測目前節點延遲",
"defaultLatencyTest": "僅用於 HTTP 客戶端請求測試,不會對配置檔案產生影響" "defaultLatencyTest": "僅用於 HTTP 客戶端請求測試,不會對配置檔案產生影響"
+4
View File
@@ -83,6 +83,8 @@ export const commands = {
__TAURI_INVOKE<null>('record_selected_node', { groupName, node }), __TAURI_INVOKE<null>('record_selected_node', { groupName, node }),
switchProxyNode: (groupName: string, proxyName: string, unfix: boolean) => switchProxyNode: (groupName: string, proxyName: string, unfix: boolean) =>
__TAURI_INVOKE<null>('switch_proxy_node', { groupName, proxyName, unfix }), __TAURI_INVOKE<null>('switch_proxy_node', { groupName, proxyName, unfix }),
followProxyGroup: (groupName: string) =>
__TAURI_INVOKE<void>('follow_proxy_group', { groupName }),
saveDnsConfig: (dnsConfig: YamlMapping) => saveDnsConfig: (dnsConfig: YamlMapping) =>
__TAURI_INVOKE<null>('save_dns_config', { dnsConfig }), __TAURI_INVOKE<null>('save_dns_config', { dnsConfig }),
applyDnsConfig: (apply: boolean) => applyDnsConfig: (apply: boolean) =>
@@ -416,6 +418,7 @@ export type IVerge_Deserialize = {
enable_global_hotkey?: boolean | null enable_global_hotkey?: boolean | null
home_cards?: JsonValue | null home_cards?: JsonValue | null
auto_close_connection?: boolean | null auto_close_connection?: boolean | null
auto_switch_selector_group?: boolean | null
auto_check_update?: boolean | null auto_check_update?: boolean | null
default_latency_test?: string | null default_latency_test?: string | null
default_latency_timeout?: number | null default_latency_timeout?: number | null
@@ -506,6 +509,7 @@ export type IVerge_Serialize = {
enable_global_hotkey: boolean | null enable_global_hotkey: boolean | null
home_cards: JsonValue | null home_cards: JsonValue | null
auto_close_connection: boolean | null auto_close_connection: boolean | null
auto_switch_selector_group: boolean | null
auto_check_update: boolean | null auto_check_update: boolean | null
default_latency_test: string | null default_latency_test: string | null
default_latency_timeout: number | null default_latency_timeout: number | null
+4
View File
@@ -165,6 +165,10 @@ export async function switchProxyNode(
return commands.switchProxyNode(groupName, proxyName, unfix) return commands.switchProxyNode(groupName, proxyName, unfix)
} }
export async function followProxyGroup(groupName: string) {
return commands.followProxyGroup(groupName)
}
export async function getProxyView(): Promise<ProxyViewV1> { export async function getProxyView(): Promise<ProxyViewV1> {
const view = await commands.getProxyView() const view = await commands.getProxyView()
if (view.schemaVersion !== 1) { if (view.schemaVersion !== 1) {
+17
View File
@@ -19,6 +19,13 @@ let currentRangeMinutes!: number
let throttleTimer: ReturnType<typeof setTimeout> | null = null let throttleTimer: ReturnType<typeof setTimeout> | null = null
let lastTimestamp: number | undefined let lastTimestamp: number | undefined
let lastBroadcast: ITrafficDataPoint[] = [] 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 broadcastSnapshot = () => {
const dataPoints = sampler.getDataForTimeRange(currentRangeMinutes) const dataPoints = sampler.getDataForTimeRange(currentRangeMinutes)
@@ -33,6 +40,7 @@ const broadcastSnapshot = () => {
ctx.postMessage(message) ctx.postMessage(message)
lastBroadcast = dataPoints lastBroadcast = dataPoints
lastSamplerVersion = sampler.getVersion()
} }
const scheduleSnapshot = () => { const scheduleSnapshot = () => {
@@ -55,9 +63,18 @@ ctx.onmessage = (event: MessageEvent<TrafficWorkerRequestMessage>) => {
// no handle needed, worker teardown (terminate) drops pending timers // no handle needed, worker teardown (terminate) drops pending timers
ctx.setInterval(() => { ctx.setInterval(() => {
if (throttleTimer !== null) return if (throttleTimer !== null) return
const version = sampler.getVersion()
if (
version === lastSamplerVersion &&
!agedPastRange(lastBroadcast, currentRangeMinutes)
) {
return
}
const slice = sampler.getDataForTimeRange(currentRangeMinutes) const slice = sampler.getDataForTimeRange(currentRangeMinutes)
if (!isSameTrafficData(lastBroadcast, slice)) { if (!isSameTrafficData(lastBroadcast, slice)) {
broadcastSnapshot() broadcastSnapshot()
} else {
lastSamplerVersion = version
} }
}, 1000) }, 1000)
broadcastSnapshot() broadcastSnapshot()
+2
View File
@@ -652,6 +652,7 @@ export const translationKeys = [
'settings.modals.misc.fields.appLogMaxSize', 'settings.modals.misc.fields.appLogMaxSize',
'settings.modals.misc.fields.appLogMaxCount', 'settings.modals.misc.fields.appLogMaxCount',
'settings.modals.misc.fields.autoCloseConnections', 'settings.modals.misc.fields.autoCloseConnections',
'settings.modals.misc.fields.autoSwitchSelectorGroup',
'settings.modals.misc.fields.autoCheckUpdate', 'settings.modals.misc.fields.autoCheckUpdate',
'settings.modals.misc.fields.enableBuiltinEnhanced', 'settings.modals.misc.fields.enableBuiltinEnhanced',
'settings.modals.misc.fields.proxyLayoutColumns', 'settings.modals.misc.fields.proxyLayoutColumns',
@@ -661,6 +662,7 @@ export const translationKeys = [
'settings.modals.misc.fields.defaultLatencyTest', 'settings.modals.misc.fields.defaultLatencyTest',
'settings.modals.misc.fields.defaultLatencyTimeout', 'settings.modals.misc.fields.defaultLatencyTimeout',
'settings.modals.misc.tooltips.autoCloseConnections', 'settings.modals.misc.tooltips.autoCloseConnections',
'settings.modals.misc.tooltips.autoSwitchSelectorGroup',
'settings.modals.misc.tooltips.enableBuiltinEnhanced', 'settings.modals.misc.tooltips.enableBuiltinEnhanced',
'settings.modals.misc.tooltips.autoDelayDetection', 'settings.modals.misc.tooltips.autoDelayDetection',
'settings.modals.misc.tooltips.defaultLatencyTest', 'settings.modals.misc.tooltips.defaultLatencyTest',
+2
View File
@@ -1123,6 +1123,7 @@ export interface TranslationResources {
autoDelayDetection: string autoDelayDetection: string
autoDelayDetectionInterval: string autoDelayDetectionInterval: string
autoLogClean: string autoLogClean: string
autoSwitchSelectorGroup: string
defaultLatencyTest: string defaultLatencyTest: string
defaultLatencyTimeout: string defaultLatencyTimeout: string
enableBuiltinEnhanced: string enableBuiltinEnhanced: string
@@ -1141,6 +1142,7 @@ export interface TranslationResources {
tooltips: { tooltips: {
autoCloseConnections: string autoCloseConnections: string
autoDelayDetection: string autoDelayDetection: string
autoSwitchSelectorGroup: string
defaultLatencyTest: string defaultLatencyTest: string
enableBuiltinEnhanced: string enableBuiltinEnhanced: string
} }
+29 -2
View File
@@ -7,14 +7,33 @@ interface ICompressedDataPoint {
const pad2 = (value: number) => value.toString().padStart(2, '0') 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) => { export const formatTrafficHourMinute = (timestamp: number) => {
const cached = hourMinuteLabels.get(timestamp)
if (cached !== undefined) return cached
const date = new Date(timestamp) const date = new Date(timestamp)
return `${pad2(date.getHours())}:${pad2(date.getMinutes())}` const label = `${pad2(date.getHours())}:${pad2(date.getMinutes())}`
if (hourMinuteLabels.size >= TIME_LABEL_CACHE_LIMIT) hourMinuteLabels.clear()
hourMinuteLabels.set(timestamp, label)
return label
} }
export const formatTrafficMinuteSecond = (timestamp: number) => { export const formatTrafficMinuteSecond = (timestamp: number) => {
const cached = minuteSecondLabels.get(timestamp)
if (cached !== undefined) return cached
const date = new Date(timestamp) const date = new Date(timestamp)
return `${pad2(date.getMinutes())}:${pad2(date.getSeconds())}` const label = `${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`
if (minuteSecondLabels.size >= TIME_LABEL_CACHE_LIMIT)
minuteSecondLabels.clear()
minuteSecondLabels.set(timestamp, label)
return label
} }
export const formatTrafficName = (timestamp: number) => { export const formatTrafficName = (timestamp: number) => {
@@ -53,10 +72,12 @@ export class TrafficDataSampler {
private compressedBuffer: ICompressedDataPoint[] = [] private compressedBuffer: ICompressedDataPoint[] = []
private compressedHead = 0 private compressedHead = 0
private compressionQueue: ITrafficDataPoint[] = [] private compressionQueue: ITrafficDataPoint[] = []
private version = 0
constructor(private config: ISamplingConfig) {} constructor(private config: ISamplingConfig) {}
addDataPoint(point: ITrafficDataPoint) { addDataPoint(point: ITrafficDataPoint) {
this.version++
this.rawBuffer.push(point) this.rawBuffer.push(point)
const rawCutoff = Date.now() - this.config.rawDataMinutes * 60 * 1000 const rawCutoff = Date.now() - this.config.rawDataMinutes * 60 * 1000
@@ -167,7 +188,13 @@ export class TrafficDataSampler {
} }
} }
/** Bumped by every mutation (added points, compression, aging trims, clear). */
getVersion(): number {
return this.version
}
clear() { clear() {
this.version++
this.rawBuffer = [] this.rawBuffer = []
this.rawHead = 0 this.rawHead = 0
this.compressedBuffer = [] this.compressedBuffer = []