Compare commits

..
Author SHA1 Message Date
Tunglies 62666b5e27 fix(proxies): derive mounted delays from shared snapshots
Remove mirrored item delay state so profile cache invalidation cannot leave reused rows blank until remount. Read current node history when the shared cache is empty and preserve snapshot identity for React subscriptions.
2026-11-11 05:47:22 +08:00
Tunglies 2db9da5d06 test(proxies): narrow delay regressions to reported failures
Remove global fake timers and deferred request scaffolding. Keep only profile-switch cache isolation and shared-key listener cleanup regressions.
2026-11-10 12:15:39 +08:00
Tunglies 371ca6e907 test(proxies): keep focused delay regression coverage
Reduce added delay coverage to profile-switch isolation and shared-key subscriptions. Append the changelog entry after existing general fixes.
2026-11-10 05:58:17 +08:00
Tunglies b02fb26c0c fix(proxies): retain independent delay listeners
Notify every mounted occurrence sharing a delay key and scope cleanup to its registered listener. Cover pending results, profile reset, and either occurrence unmounting without restoring direct unfenced updates.
2026-11-10 05:55:28 +08:00
Tunglies a2d875cebd fix(proxies): invalidate delays when switching profiles
Clear cached delays and fence old measurements when the active profile changes. Refresh proxy history on page entry without forcing automatic measurements or expanding groups.
2026-11-10 05:50:55 +08:00
70 changed files with 763 additions and 1234 deletions
-1
View File
@@ -1,3 +1,2 @@
avoid-breaking-exported-api = true
allow-unwrap-in-tests = true
cognitive-complexity-threshold = 25
+2 -2
View File
@@ -4,11 +4,11 @@
"features": {
"ghcr.io/devcontainers/features/node:2": {
"version": "26.13.1",
"version": "26.13.0",
"pnpmVersion": "12.18.0"
},
"ghcr.io/devcontainers/features/rust:1": {
"version": "1.100.0",
"version": "1.99.1",
"profile": "default"
},
"ghcr.io/devcontainers/features/git:1": {},
+3 -3
View File
@@ -5,10 +5,10 @@
"version": "v9.0.0",
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
},
"github/gh-aw-actions/setup@v1.2.2": {
"github/gh-aw-actions/setup@v1.0.1": {
"repo": "github/gh-aw-actions/setup",
"version": "v1.2.2",
"sha": "53d0749e19424a918acd82b4d140264ce48f2f14"
"version": "v1.0.1",
"sha": "221ba4f4319de6b8e809d1a15528b3ae6a818aa5"
}
},
"containers": {
+8 -8
View File
@@ -51,7 +51,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
- name: Install dependencies
run: pnpm install --frozen-lockfile
@@ -154,7 +154,7 @@ jobs:
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@master
with:
toolchain: '1.100.0'
toolchain: '1.99.1'
targets: ${{ matrix.target }}
- name: Rust Cache
@@ -182,7 +182,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -240,7 +240,7 @@ jobs:
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@master
with:
toolchain: '1.100.0'
toolchain: '1.99.1'
targets: ${{ matrix.target }}
- name: Rust Cache
@@ -262,7 +262,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -373,7 +373,7 @@ jobs:
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@master
with:
toolchain: '1.100.0'
toolchain: '1.99.1'
targets: ${{ matrix.target }}
- name: Rust Cache
@@ -395,7 +395,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -479,7 +479,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
- uses: pnpm/action-setup@v6.1.1
name: Install pnpm
+1 -1
View File
@@ -63,7 +63,7 @@ jobs:
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
+3 -3
View File
@@ -31,9 +31,9 @@ jobs:
with:
persist-credentials: false
- name: Install gh-aw extension
uses: github/gh-aw-actions/setup-cli@53d0749e19424a918acd82b4d140264ce48f2f14 # v1.2.2
uses: github/gh-aw-actions/setup-cli@406c7719e31d7fe354224d4bb8fe3d4aeb47da1c # v1.2.1
with:
version: v1.2.2
version: v1.0.1
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@stable
with:
@@ -49,7 +49,7 @@ jobs:
- name: Install Node.js
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
cache: 'pnpm'
- name: Install frontend dependencies
env:
+1 -1
View File
@@ -43,7 +43,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
+3 -3
View File
@@ -74,7 +74,7 @@ jobs:
- name: Install Rust Stable
if: github.event.inputs[matrix.input] == 'true'
uses: dtolnay/rust-toolchain@1.100.0
uses: dtolnay/rust-toolchain@1.99.1
- name: Rust Cache
if: github.event.inputs[matrix.input] == 'true'
@@ -104,7 +104,7 @@ jobs:
if: github.event.inputs[matrix.input] == 'true'
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -121,7 +121,7 @@ jobs:
if: github.event.inputs[matrix.input] == 'true'
run: |
# Ensure cross target is installed for the pinned toolchain; fallback without explicit toolchain if needed
rustup target add ${{ matrix.target }} --toolchain 1.100.0 || rustup target add ${{ matrix.target }}
rustup target add ${{ matrix.target }} --toolchain 1.99.1 || rustup target add ${{ matrix.target }}
rustup target list --installed
echo "Rust target ${{ matrix.target }} installed."
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
File diff suppressed because one or more lines are too long
-1
View File
@@ -33,7 +33,6 @@ max-daily-ai-credits: 5000
permissions:
issues: read
pull-requests: read
copilot-requests: none
pre-agent-steps:
- name: Make Copilot quota exhaustion non-blocking
+107 -288
View File
File diff suppressed because one or more lines are too long
-1
View File
@@ -30,7 +30,6 @@ permissions:
contents: read
issues: read
pull-requests: read
copilot-requests: none
steps:
- name: Load review rules from the base revision
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
+1 -1
View File
@@ -61,7 +61,7 @@ jobs:
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
- uses: pnpm/action-setup@v6
if: github.event.action != 'closed'
+11 -11
View File
@@ -46,7 +46,7 @@ jobs:
fetch-depth: 0
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
- name: Validate source and publish the approved snapshot
id: source
env:
@@ -203,7 +203,7 @@ jobs:
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@master
with:
toolchain: '1.100.0'
toolchain: '1.99.1'
targets: ${{ matrix.target }}
- name: Rust Cache
@@ -231,7 +231,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -308,7 +308,7 @@ jobs:
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@master
with:
toolchain: '1.100.0'
toolchain: '1.99.1'
targets: ${{ matrix.target }}
- name: Rust Cache
@@ -330,7 +330,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -439,7 +439,7 @@ jobs:
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@master
with:
toolchain: '1.100.0'
toolchain: '1.99.1'
targets: ${{ matrix.target }}
- name: Rust Cache
@@ -461,7 +461,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -542,7 +542,7 @@ jobs:
fetch-depth: 0
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
- uses: pnpm/action-setup@v6
with:
run_install: false
@@ -565,7 +565,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
@@ -593,7 +593,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
@@ -661,7 +661,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
File diff suppressed because one or more lines are too long
@@ -28,7 +28,6 @@ permissions:
contents: read
issues: read
pull-requests: read
copilot-requests: none
max-ai-credits: 60
max-turns: 12
max-daily-ai-credits: 500
+2 -2
View File
@@ -22,13 +22,13 @@ jobs:
- name: Install Rust
uses: dtolnay/rust-toolchain@master
with:
toolchain: '1.100.0'
toolchain: '1.99.1'
targets: x86_64-pc-windows-msvc
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
- name: Install pnpm
uses: pnpm/action-setup@v6
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
+2 -2
View File
@@ -15,7 +15,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
@@ -39,7 +39,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.13.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
+2 -2
View File
@@ -1,3 +1,3 @@
nodejs 26.13.1
nodejs 26.13.0
pnpm 12.18.0
rust 1.100.0
rust 1.99.1
Generated
+9 -8
View File
@@ -159,9 +159,9 @@ dependencies = [
[[package]]
name = "arc-swap"
version = "1.9.5"
version = "1.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84a22b5d51209f6de83d37a0b33d320acb8da88823e42a94c075140708f032a5"
checksum = "db4c94f57a570fce5d381be3289b3f79aef6332d72948fe82ab5772e423ccf92"
dependencies = [
"rustversion",
]
@@ -1123,6 +1123,7 @@ dependencies = [
"rfd 0.18.0",
"runas",
"rustls",
"scopeguard",
"serde",
"serde_json",
"serde_yaml_ng",
@@ -7072,9 +7073,9 @@ dependencies = [
[[package]]
name = "sysinfo"
version = "0.40.3"
version = "0.40.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a86bac2f7d06e6384984118ad727f5694110f0ec44d924d05c8fdec3d030bee6"
checksum = "0e8a3edbe0394ce115f3917a00349dd242be09eb5a091ed509eaf67b55cfb8a8"
dependencies = [
"libc",
"memchr",
@@ -9087,9 +9088,9 @@ dependencies = [
[[package]]
name = "webpki-roots"
version = "1.0.12"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297"
checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171"
dependencies = [
"rustls-pki-types",
]
@@ -10125,9 +10126,9 @@ dependencies = [
[[package]]
name = "zip"
version = "9.5.1"
version = "9.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3476fd497ac8af5b1ec7b51acab7bef380f7e8dd8e0487595bafd839417a302"
checksum = "df3845f734baabdd02de353a20580e30ceccd03897def44a4eb8e9654992e294"
dependencies = [
"aes",
"bzip2",
-1
View File
@@ -132,7 +132,6 @@ large_const_arrays = "warn"
large_futures = "deny"
large_stack_arrays = "warn"
large_types_passed_by_value = "deny"
map_unwrap_or = "deny"
missing_const_for_fn = "deny"
mutex_atomic = "deny"
mutex_integer = "deny"
+1 -3
View File
@@ -29,20 +29,18 @@
- 修复全局模式默认停在 `DIRECT` 或 `REJECT` 导致流量未经代理,现自动切换到第一个策略组
- 修复订阅中未加引号的 REALITY `short-id`(如 `1234e123`)被误读为数字,导致订阅无法启用
- 修复订阅中唯一的代理组名为 `GLOBAL` 或没有代理组时,规则模式下代理页面显示「未获取到代理信息」
- 修复窗口较窄时,首页「当前节点」卡片中过长的节点名把延迟标签挤出卡片
- 修复切换订阅后节点延迟显示旧订阅结果,进入代理页面时主动刷新延迟记录
**🍎 macOS**
- 修复 macOS TUN 模式下原有 DNS 被清除、关闭后 DNS 未恢复及联网后设置未生效
- 修复 macOS 断网时误报代理已回退直连,恢复联网后自动重试系统代理
- 修复 macOS 切换主题后标题栏保留原有深浅色
</details>
<details>
<summary><strong> ✨ 新增功能 </strong></summary>
- 新增连接页面按网络协议(TCP/UDP)筛选连接
</details>
+4 -4
View File
@@ -206,10 +206,10 @@ impl Logger {
.map(|s| (*s).to_string())
.or_else(|| info.payload().downcast_ref::<String>().cloned())
.unwrap_or_else(|| "Unknown panic payload".to_string());
let location = info.location().map_or_else(
|| "Unknown location".to_string(),
|loc| format!("{}:{}", loc.file(), loc.line()),
);
let location = info
.location()
.map(|loc| format!("{}:{}", loc.file(), loc.line()))
.unwrap_or_else(|| "Unknown location".to_string());
logging!(error, Type::System, "Panic occurred at {}: {}", location, payload);
Self::global().flush_logs();
std::thread::sleep(Duration::from_millis(100));
@@ -13,13 +13,14 @@ pub(super) async fn check_chatgpt(client: &Client) -> UnlockItem {
let web_status = get_text(client, "https://api.openai.com/compliance/cookie_requirements")
.await
.map_or("Failed", |body| {
.map(|body| {
if body.to_ascii_lowercase().contains("unsupported_country") {
"Unsupported Country/Region"
} else {
"Yes"
}
});
})
.unwrap_or("Failed");
UnlockItem::checked(CHATGPT_WEB_NAME, web_status, region)
}
@@ -157,10 +157,11 @@ async fn is_unavailable(client: &Client) -> bool {
.get("https://disneyplus.com")
.send()
.await
.map_or(true, |response| {
.map(|response| {
let url = response.url().as_str();
url.contains("preview") || url.contains("unavailable")
})
.unwrap_or(true)
}
async fn fallback_region(client: &Client) -> Option<UnlockItem> {
@@ -114,10 +114,11 @@ async fn check_netflix_cdn(client: &Client) -> UnlockItem {
}
match response.json::<FastResponse>().await {
Ok(data) => data.targets.first().map_or_else(
|| item("Unknown"),
|target| UnlockItem::checked_region(NETFLIX_NAME, "Yes", &target.location.country),
),
Ok(data) => data
.targets
.first()
.map(|target| UnlockItem::checked_region(NETFLIX_NAME, "Yes", &target.location.country))
.unwrap_or_else(|| item("Unknown")),
Err(e) => {
logging!(error, Type::Network, "解析 Fast.com API 响应失败: {e}");
item("Failed (解析错误)")
@@ -12,7 +12,7 @@ parking_lot = { workspace = true }
serde = { workspace = true, features = ["derive"] }
# sysinfo 0.38.2 conflicts with dark-light
# see https://github.com/GuillaumeGomez/sysinfo/issues/1623
sysinfo = { version = "0.40.3", default-features = false, features = ["network", "system"] }
sysinfo = { version = "0.40.1", default-features = false, features = ["network", "system"] }
[target.'cfg(not(windows))'.dependencies]
libc = "0.2.191"
@@ -118,7 +118,8 @@ fn is_binary_admin() -> bool {
#[cfg(windows)]
Token::with_current_process()
.and_then(|token| token.privilege_level())
.is_ok_and(|level| level != PrivilegeLevel::NotPrivileged)
.map(|level| level != PrivilegeLevel::NotPrivileged)
.unwrap_or(false)
}
#[inline]
+3 -3
View File
@@ -67,7 +67,7 @@
"dayjs": "1.11.23",
"foxact": "^0.3.12",
"foxts": "^5.9.1",
"i18next": "^27.0.0",
"i18next": "^26.4.2",
"js-yaml": "^5.4.2",
"lodash-es": "^4.18.1",
"meta-json-schema": "^1.19.31",
@@ -79,7 +79,7 @@
"react-dom": "19.3.1",
"react-error-boundary": "6.1.6",
"react-hook-form": "^7.88.0",
"react-i18next": "18.0.1",
"react-i18next": "17.1.13",
"react-markdown": "10.1.0",
"react-router": "^8.4.0",
"rehype-raw": "^7.0.0",
@@ -121,7 +121,7 @@
"https-proxy-agent": "^9.1.0",
"husky": "^9.1.7",
"jiti": "^2.7.0",
"knip": "6.45.1",
"knip": "6.44.2",
"lint-staged": "^17.5.1",
"sass": "^1.104.1",
"tar": "^7.5.22",
+31 -27
View File
@@ -239,8 +239,8 @@ importers:
specifier: ^5.9.1
version: 5.9.1
i18next:
specifier: ^27.0.0
version: 27.0.1(typescript@6.0.3)
specifier: ^26.4.2
version: 26.4.2(typescript@6.0.3)
js-yaml:
specifier: ^5.4.2
version: 5.4.2
@@ -275,8 +275,8 @@ importers:
specifier: ^7.88.0
version: 7.88.0(react@19.3.1)
react-i18next:
specifier: 18.0.1
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)
specifier: 17.1.13
version: 17.1.13(i18next@26.4.2(typescript@6.0.3))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(typescript@6.0.3)
react-markdown:
specifier: 10.1.0
version: 10.1.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
@@ -396,8 +396,8 @@ importers:
specifier: ^2.7.0
version: 2.7.0
knip:
specifier: 6.45.1
version: 6.45.1
specifier: 6.44.2
version: 6.44.2
lint-staged:
specifier: ^17.5.1
version: 17.5.1
@@ -3689,9 +3689,8 @@ packages:
engines: {node: '>=18'}
hasBin: true
i18next@27.0.1:
resolution: {integrity: sha512-KaE5ozP8UUeVpOJIwMVbbnpRKpyYQuxd9ZbseJoDzezE3nvLnZZQn20pkzyIJwPI2Uet/Qs3WzPTG812f6F/Eg==}
engines: {node: '>=22'}
i18next@26.4.2:
resolution: {integrity: sha512-RX+R0VLg13IbvRuJSxnqykUFS9vQZTl8wYpWPCIUDWVrSGjsQywB5Y+pjzrkboxGAuYfJZVH1InFTdgBdxq6ug==}
peerDependencies:
typescript: ^5 || ^6 || ^7
peerDependenciesMeta:
@@ -3856,8 +3855,8 @@ packages:
keyv@5.6.0:
resolution: {integrity: sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==}
knip@6.45.1:
resolution: {integrity: sha512-zp3zXKy2cZWiIttdlWU5fisKxVQaLSU6471ej0KGz1GdHdaHxpzTAO/LIyFNc3gU3v1W7LJaqvYumoO3l/u+6A==}
knip@6.44.2:
resolution: {integrity: sha512-6URO7pnqtOnyvSsXfW6+8C9j1lfcicxUCysXO0RgMtHTZ96HqCXh29op8iabeQW5JeIc8dJWwzSdJVWDokeScQ==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
@@ -4397,16 +4396,18 @@ packages:
peerDependencies:
react: ^16.8.0 || ^17 || ^18 || ^19
react-i18next@18.0.1:
resolution: {integrity: sha512-kPWXI0E/lrPj3+/umcKNzYZVnWmEedLiamMzDIHfbs+5ANf6yzvlZsjKou8f7kaGkfMMDLIZBejV+4aSN1CyBw==}
engines: {node: '>=22'}
react-i18next@17.1.13:
resolution: {integrity: sha512-ZxhOSlyKSKPtbUNPLwYMmE3w3bhoc0jaZJZ6bc7wGOT6cLbrbs//6m01HxCLtFdSjHvFpwFwoPhxxzIlHSs9cw==}
peerDependencies:
'@types/react': '*'
i18next: '>= 27.0.1'
react: '>= 18.0.0'
i18next: '>= 26.2.0'
react: '>= 16.8.0'
react-dom: '*'
react-native: '*'
typescript: ^5 || ^6 || ^7
peerDependenciesMeta:
'@types/react':
react-dom:
optional: true
react-native:
optional: true
typescript:
optional: true
@@ -4804,8 +4805,8 @@ packages:
engines: {node: '>=14.17'}
hasBin: true
unbash@6.0.4:
resolution: {integrity: sha512-t3OptUArewg9OpYGDskTSlxhyLDahfmZ4d36hE44Efb1y3HRLLpzsVqwH+AwBVymP4t7pP71xN+nnduudn2awA==}
unbash@6.0.1:
resolution: {integrity: sha512-0db9eS5iqybux41zLkX69nk90KTci7F7eZ+gXzEG/Q7E0tAqEBhRh5fkZvk1N7jT7QkGWqq34i8SFGPFEe1V8A==}
engines: {node: '>=14'}
undici-types@6.21.0:
@@ -8532,7 +8533,7 @@ snapshots:
husky@9.1.7: {}
i18next@27.0.1(typescript@6.0.3):
i18next@26.4.2(typescript@6.0.3):
optionalDependencies:
typescript: 6.0.3
@@ -8684,7 +8685,7 @@ snapshots:
dependencies:
'@keyv/serialize': 1.1.1
knip@6.45.1:
knip@6.44.2:
dependencies:
formatly: 0.11.4
get-tsconfig: 4.14.3
@@ -8695,8 +8696,9 @@ snapshots:
smol-toml: 1.9.1
strip-json-comments: 5.0.3
tinyglobby: 0.2.17
unbash: 6.0.4
unbash: 6.0.1
yaml: 2.9.1
zod: 4.6.5
lazystream@1.0.1:
dependencies:
@@ -9355,13 +9357,15 @@ snapshots:
dependencies:
react: 19.3.1
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):
react-i18next@17.1.13(i18next@26.4.2(typescript@6.0.3))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(typescript@6.0.3):
dependencies:
'@babel/runtime': 7.29.7
html-parse-stringify: 4.0.1
i18next: 27.0.1(typescript@6.0.3)
i18next: 26.4.2(typescript@6.0.3)
react: 19.3.1
use-sync-external-store: 1.7.0(react@19.3.1)
optionalDependencies:
'@types/react': 19.3.0
react-dom: 19.3.1(react@19.3.1)
typescript: 6.0.3
react-is@16.13.1: {}
@@ -9786,7 +9790,7 @@ snapshots:
typescript@6.0.3: {}
unbash@6.0.4: {}
unbash@6.0.1: {}
undici-types@6.21.0: {}
+1 -1
View File
@@ -1,3 +1,3 @@
[toolchain]
channel = "1.100.0"
channel = "1.99.1"
components = ["rustfmt", "clippy"]
+5 -4
View File
@@ -8,7 +8,7 @@ repository = "https://github.com/clash-verge-rev/clash-verge-rev.git"
default-run = "clash-verge"
build = "build.rs"
edition = "2024"
rust-version = "1.100"
rust-version = "1.99"
[lib]
name = "app_lib"
@@ -77,7 +77,7 @@ tauri-plugin-dialog = "2.8.4"
tauri-plugin-fs = "2.7.1"
tauri-plugin-deep-link = "2.6.3"
tauri-plugin-window-state = "2.5.0"
zip = "9.5.1"
zip = "9.4.2"
flate2 = "1.1.11"
reqwest_dav = "0.3.3"
aes-gcm = { version = "0.11.1" }
@@ -86,6 +86,7 @@ sha2 = "0.11.1"
getrandom = "0.4.3"
futures = "0.3.34"
gethostname = "1.1.0"
scopeguard = "1.2.0"
tauri-plugin-notification = "2.8.0"
backon = { version = "1.6.0", features = ["tokio-sleep"] }
tauri-plugin-http = "2.8.3"
@@ -96,10 +97,10 @@ async-trait = "0.1.92"
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", tag = "v2.7.7", version = "2.7.7", features = [
"client",
] }
arc-swap = "1.9.5"
arc-swap = "1.9.4"
tokio-rustls = "0.26.6"
rustls = { version = "0.23.46", features = ["ring"] }
webpki-roots = "1.0.12"
webpki-roots = "1.0.11"
dark-light = "3.0.0"
bytes = "1.12.1"
tokio-util = { version = "0.7.20", features = ["time"] }
-2
View File
@@ -17,8 +17,6 @@
"autostart:allow-disable",
"autostart:allow-is-enabled",
"core:window:allow-set-theme",
"core:window:allow-set-background-color",
"core:webview:allow-set-webview-background-color",
"notification:default",
"http:default",
"http:allow-fetch",
+4 -4
View File
@@ -2,10 +2,10 @@
// bundles (PR #8131), so this generator must stay an example, never a bin.
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args_os().skip(1);
let output = args.next().map_or_else(
|| std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../src/services/bindings.ts"),
std::path::PathBuf::from,
);
let output = args
.next()
.map(std::path::PathBuf::from)
.unwrap_or_else(|| std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../src/services/bindings.ts"));
if args.next().is_some() {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "expected at most one output path").into());
}
+4 -6
View File
@@ -18,11 +18,9 @@ use crate::{
};
use clash_verge_draft::{Draft, SharedDraft};
use clash_verge_logging::{Type, logging, logging_error};
use scopeguard::defer;
use smartstring::alias::String;
use std::{
mem::DropGuard,
sync::atomic::{AtomicBool, Ordering},
};
use std::sync::atomic::{AtomicBool, Ordering};
static CURRENT_SWITCHING_PROFILE: AtomicBool = AtomicBool::new(false);
@@ -402,9 +400,9 @@ pub async fn patch_profiles_config(profiles: ProfileSelection) -> CmdResult<Vali
logging!(info, Type::Cmd, "当前正在切换配置,放弃请求");
return Ok(ValidationOutcome::Busy);
}
let _switching_profile = DropGuard::new((), |()| {
defer! {
CURRENT_SWITCHING_PROFILE.store(false, Ordering::Release);
});
}
let _profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
let profiles = IProfiles {
+2 -1
View File
@@ -83,7 +83,8 @@ fn runtime_group_scopes(config: Option<&Mapping>) -> BTreeMap<String, GroupScope
.get("exclude-type")
.and_then(|types| types.as_str())
.filter(|types| !types.is_empty())
.map_or_default(|types| types.split('|').map(str::to_owned).collect());
.map(|types| types.split('|').map(str::to_owned).collect())
.unwrap_or_default();
Some((
name,
GroupScope {
+1 -1
View File
@@ -191,7 +191,7 @@ impl Config {
}
}
} else {
let error_msg = config_result.err().map_or_default(|err| err.to_string());
let error_msg = config_result.err().map(|err| err.to_string()).unwrap_or_default();
logging!(warn, Type::Config, "生成配置文件失败,使用默认配置: {error_msg}");
CoreManager::global()
.use_default_config(NoticeStatus::ConfigValidateError, "")
+3 -4
View File
@@ -371,10 +371,9 @@ impl PrfItem {
let uid = help::get_uid("R").into();
let file = format!("{uid}.yaml").into();
let name = name.map_or_else(
|| filename.map_or_else(|| "Remote File".into(), |s| s.into()),
|s| s.to_owned(),
);
let name = name
.map(|s| s.to_owned())
.unwrap_or_else(|| filename.map(|s| s.into()).unwrap_or_else(|| "Remote File".into()));
let data = resp.text();
let data = data.trim_start_matches('\u{feff}');
+2 -1
View File
@@ -279,7 +279,8 @@ async fn cleanup_auto_backups() -> Result<()> {
.and_then(|meta| meta.modified())
.ok()
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
.map_or(0, |dur| dur.as_secs());
.map(|dur| dur.as_secs())
.unwrap_or(0);
files.push((path, modified));
}
+6 -4
View File
@@ -539,16 +539,18 @@ fn bind_socket(claim: &BindClaim) -> io::Result<Socket> {
}
fn is_bind_conflict(error: &io::Error) -> bool {
if error.kind() == io::ErrorKind::AddrInUse {
return true;
}
#[cfg(windows)]
{
use windows_sys::Win32::Networking::WinSock::WSAEACCES;
error.kind() == io::ErrorKind::AddrInUse || error.raw_os_error() == Some(WSAEACCES)
error.raw_os_error() == Some(WSAEACCES)
}
#[cfg(not(windows))]
{
error.kind() == io::ErrorKind::AddrInUse
}
false
}
#[cfg(windows)]
+5 -5
View File
@@ -14,10 +14,10 @@ use anyhow::{Result, anyhow};
use clash_verge_draft::DraftTransaction;
use clash_verge_logging::{Type, logging};
use clash_verge_service_ipc::StageRuntimeOutcome;
use scopeguard::defer;
use smartstring::alias::String;
use std::{
collections::HashSet,
mem::DropGuard,
path::PathBuf,
sync::Arc,
time::{Duration, Instant},
@@ -191,9 +191,9 @@ impl CoreManager {
logging!(debug, Type::Core, "Configuration update is already running");
return Ok(ValidationOutcome::Busy);
}
let _config_update = DropGuard::new((), |()| {
defer! {
self.finish_config_update();
});
}
if !force && !self.should_update_config() {
logging!(debug, Type::Core, "Skipping config update due to debounce");
@@ -314,9 +314,9 @@ impl CoreManager {
logging!(debug, Type::Core, "Configuration update is already running");
return Ok(ValidationOutcome::Busy);
}
let _config_update = DropGuard::new((), |()| {
defer! {
self.finish_config_update();
});
}
let runtime = Config::runtime().await;
let transaction = DraftTransaction::begin(vec![&runtime])?;
+12 -11
View File
@@ -6,8 +6,9 @@ use crate::core::proxy_control::{self, SysproxyFailure};
use crate::core::service::{SERVICE_MANAGER, ServiceStatus};
use anyhow::Result;
use clash_verge_logging::{Type, logging};
use scopeguard::defer;
use smartstring::alias::String;
use std::{mem::DropGuard, path::Path};
use std::path::Path;
#[cfg(target_os = "windows")]
use tauri_plugin_clash_verge_sysinfo::is_current_app_handle_admin;
@@ -355,9 +356,9 @@ impl CoreManager {
if !self.try_start_config_update() {
anyhow::bail!("configuration update is already running");
}
let _config_update = DropGuard::new((), |()| {
defer! {
self.finish_config_update();
});
}
self.start_core_during_config_update().await
}
@@ -382,9 +383,9 @@ impl CoreManager {
service_rejection,
));
}
let _config_update = DropGuard::new((), |()| {
defer! {
self.finish_config_update();
});
}
// Lock order is config then lifecycle. disable_tun_and_persist commits the shared Verge
// draft without claiming it, so without this it can commit another transaction's staged patch.
let config_write = Config::lock_config_write().await;
@@ -462,9 +463,9 @@ impl CoreManager {
if !self.try_start_config_update() {
anyhow::bail!("configuration update is already running");
}
let _config_update = DropGuard::new((), |()| {
defer! {
self.finish_config_update();
});
}
// Lock order is config then lifecycle, for the unclaimed draft write below.
let _config_write = Config::lock_config_write().await;
let _life = self.lifecycle_lock.lock().await;
@@ -794,9 +795,9 @@ impl CoreManager {
if !self.try_start_config_update() {
anyhow::bail!("configuration update is already running");
}
let _config_update = DropGuard::new((), |()| {
defer! {
self.finish_config_update();
});
}
self.restart_core_during_config_update().await
}
@@ -965,9 +966,9 @@ impl CoreManager {
if !self.try_start_config_update() {
return HandoffOutcome::NotReady;
}
let _config_update = DropGuard::new((), |()| {
defer! {
self.finish_config_update();
});
}
// Lock order is config then lifecycle.
let _life = self.lifecycle_lock.lock().await;
+3 -1
View File
@@ -331,7 +331,9 @@ fn build_provider_records(
providers: Option<ProxyProviders>,
records: &mut BTreeMap<String, ProxyNodeView>,
) -> (Vec<ProxyProviderView>, ProviderCandidates) {
let providers = providers.map_or_default(|providers| providers.providers.into_iter().collect::<BTreeMap<_, _>>());
let providers = providers
.map(|providers| providers.providers.into_iter().collect::<BTreeMap<_, _>>())
.unwrap_or_default();
let mut views = Vec::new();
let mut candidates = BTreeMap::new();
+2 -1
View File
@@ -126,7 +126,8 @@ fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut Ha
let path = Path::new(destination);
let extension = path
.extension()
.map_or_default(|ext| format!(".{}", ext.to_string_lossy()));
.map(|ext| format!(".{}", ext.to_string_lossy()))
.unwrap_or_default();
let mut suffix = String::new();
let mut sequence = 0;
loop {
+4 -1
View File
@@ -1470,7 +1470,10 @@ async fn create_sync_temp(target: &Path) -> Result<(PathBuf, tokio::fs::File)> {
.await
.with_context(|| format!("failed to create provider cache directory {}", parent.display()))?;
}
let name = target.file_name().map_or_default(|name| name.to_string_lossy());
let name = target
.file_name()
.map(|name| name.to_string_lossy())
.unwrap_or_default();
use crate::utils::retry::{RetryError, RetryPolicy, retry};
retry(
RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(7), std::time::Duration::ZERO),
+3 -3
View File
@@ -7,9 +7,9 @@ use crate::{
use anyhow::Result;
use clash_verge_logging::{Type, logging};
use parking_lot::RwLock;
use scopeguard::defer;
use smartstring::alias::String;
use std::{
mem::DropGuard,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
@@ -541,9 +541,9 @@ impl Sysopt {
{
return Ok(());
}
let _reset_sysproxy = DropGuard::new((), |()| {
defer! {
self.reset_sysproxy.store(false, Ordering::SeqCst);
});
}
let mut proxy_state = self.proxy_state_lock.lock().await;
let _guard_operation = self.guard_operation_lock.lock().await;
let drained = self.stop_proxy_guard_locked().await;
+29 -26
View File
@@ -210,7 +210,8 @@ impl Tray {
.latest_arc()
.0
.get("mode")
.map_or("rule", |val| val.as_str().unwrap_or("rule"))
.map(|val| val.as_str().unwrap_or("rule"))
.unwrap_or("rule")
.to_owned()
};
let profiles_config = Config::profiles().await;
@@ -413,23 +414,26 @@ impl Tray {
}
fn create_hotkeys(hotkeys: &Option<Vec<String>>) -> HashMap<&str, &str> {
hotkeys.as_ref().map_or_default(|h| {
h.iter()
.filter_map(|item| {
let mut parts = item.split(',');
match (parts.next(), parts.next()) {
(Some(func), Some(key)) => {
// 托盘菜单的 `accelerator` 在 Linux/Windows 下不支持小键盘按键,Windows 下也不支持 Win 键(前端上报为 `CMD`)
let uppercase_key = key.to_uppercase();
let unsupported =
uppercase_key.contains("NUMPAD") || (cfg!(windows) && uppercase_key.contains("CMD"));
if unsupported { None } else { Some((func, key)) }
hotkeys
.as_ref()
.map(|h| {
h.iter()
.filter_map(|item| {
let mut parts = item.split(',');
match (parts.next(), parts.next()) {
(Some(func), Some(key)) => {
// 托盘菜单的 `accelerator` 在 Linux/Windows 下不支持小键盘按键,Windows 下也不支持 Win 键(前端上报为 `CMD`)
let uppercase_key = key.to_uppercase();
let unsupported =
uppercase_key.contains("NUMPAD") || (cfg!(windows) && uppercase_key.contains("CMD"));
if unsupported { None } else { Some((func, key)) }
}
_ => None,
}
_ => None,
}
})
.collect::<HashMap<&str, &str>>()
})
})
.collect::<HashMap<&str, &str>>()
})
.unwrap_or_default()
}
fn create_profile_menu_item(
@@ -489,14 +493,12 @@ fn create_subcreate_proxy_menu_item(
.proxies
.get(proxy_str)
.and_then(|h| h.history.last())
.map_or_else(
|| "-ms".into(),
|h| match h.delay {
0 => "-ms".into(),
delay if delay >= 10000 => "-ms".into(),
_ => format!("{}ms", h.delay),
},
);
.map(|h| match h.delay {
0 => "-ms".into(),
delay if delay >= 10000 => "-ms".into(),
_ => format!("{}ms", h.delay),
})
.unwrap_or_else(|| "-ms".into());
let display_text = format!("{} | {}", proxy_str, delay_text);
@@ -609,7 +611,7 @@ async fn create_tray_menu(
config
.get("proxy-groups")
.and_then(|groups| groups.as_sequence())
.map_or_default(|groups| {
.map(|groups| {
groups
.iter()
.filter_map(|group| group.get("name"))
@@ -618,6 +620,7 @@ async fn create_tray_menu(
.map(|(index, name)| (name.into(), index))
.collect::<HashMap<String, usize>>()
})
.unwrap_or_default()
});
(proxy_nodes_data, runtime_proxy_groups_order)
+5 -4
View File
@@ -1,10 +1,10 @@
use anyhow::Result;
use scopeguard::defer;
use serde::Serialize;
use smartstring::alias::String;
use std::{
fmt,
hash::{DefaultHasher, Hash as _, Hasher as _},
mem::DropGuard,
sync::LazyLock,
sync::atomic::{AtomicBool, Ordering},
};
@@ -421,9 +421,9 @@ impl CoreConfigValidator {
logging!(info, Type::Validate, "验证已在进行中,跳过新的验证请求");
return Ok(ValidationOutcome::Busy);
}
let _validation = DropGuard::new((), |()| {
defer! {
self.finish();
});
}
logging!(info, Type::Validate, "生成临时配置文件用于验证");
// The test run reads the app dir, which never sees updates made by a service core.
@@ -449,7 +449,8 @@ fn has_ext<P: AsRef<std::path::Path>>(path: P, ext: &str) -> bool {
path.as_ref()
.extension()
.and_then(|s| s.to_str())
.is_some_and(|s| s.eq_ignore_ascii_case(ext))
.map(|s| s.eq_ignore_ascii_case(ext))
.unwrap_or(false)
}
fn contains_any_keyword<'a>(buf: &'a [u8], keywords: &'a [&str]) -> bool {
+15 -9
View File
@@ -634,7 +634,7 @@ fn cleanup_proxy_groups(mut config: Mapping) -> Mapping {
let proxy_names = config
.get("proxies")
.and_then(|v| v.as_sequence())
.map_or_default(|seq| {
.map(|seq| {
seq.iter()
.filter_map(|item| match item {
Value::Mapping(map) => map
@@ -645,12 +645,13 @@ fn cleanup_proxy_groups(mut config: Mapping) -> Mapping {
_ => None,
})
.collect::<HashSet<String>>()
});
})
.unwrap_or_default();
let group_names = config
.get("proxy-groups")
.and_then(|v| v.as_sequence())
.map_or_default(|seq| {
.map(|seq| {
seq.iter()
.filter_map(|item| {
item.as_mapping()
@@ -659,17 +660,19 @@ fn cleanup_proxy_groups(mut config: Mapping) -> Mapping {
.map(std::convert::Into::into)
})
.collect::<HashSet<String>>()
});
})
.unwrap_or_default();
let provider_names = config
.get("proxy-providers")
.and_then(Value::as_mapping)
.map_or_default(|map| {
.map(|map| {
map.keys()
.filter_map(Value::as_str)
.map(std::convert::Into::into)
.collect::<HashSet<String>>()
});
})
.unwrap_or_default();
let mut allowed_names = proxy_names;
allowed_names.extend(group_names);
@@ -713,13 +716,15 @@ fn ensure_fake_ip_range6(dns: &mut Mapping) {
let is_fake_ip = dns
.get("enhanced-mode")
.and_then(|v| v.as_str())
.is_none_or(|m| m == "fake-ip");
.map(|m| m == "fake-ip")
.unwrap_or(true);
// Hand-edited YAML may leave the key present but empty.
let range6_missing = dns
.get("fake-ip-range6")
.and_then(|v| v.as_str())
.is_none_or(|s| s.trim().is_empty());
.map(|s| s.trim().is_empty())
.unwrap_or(true);
if ipv6_enabled && is_fake_ip && range6_missing {
dns.insert(Value::from("fake-ip-range6"), Value::from("2001:2::0/64"));
@@ -742,7 +747,8 @@ fn take_mapping(config: &mut Mapping, key: &str) -> Mapping {
config
.get_mut(key)
.and_then(Value::as_mapping_mut)
.map_or_default(std::mem::take)
.map(std::mem::take)
.unwrap_or_default()
}
fn merge_dns_config(mut config: Mapping, mut dns_config: Mapping) -> (Mapping, Mapping) {
+11 -4
View File
@@ -20,10 +20,14 @@ fn collect_proxy_names(seq: &Sequence) -> Vec<String> {
}
fn is_selector_group(group_map: &Mapping) -> bool {
group_map.get("type").and_then(Value::as_str).is_some_and(|value| {
let value = value.to_ascii_lowercase();
value == "select" || value == "selector"
})
group_map
.get("type")
.and_then(Value::as_str)
.map(|value| {
let value = value.to_ascii_lowercase();
value == "select" || value == "selector"
})
.unwrap_or(false)
}
pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping {
@@ -151,6 +155,7 @@ mod tests {
use serde_yaml_ng::Value;
#[test]
#[allow(clippy::unwrap_used)]
#[allow(clippy::expect_used)]
fn test_delete_proxy_and_references() {
let config_str = r#"
@@ -228,6 +233,7 @@ proxy-groups:
}
#[test]
#[allow(clippy::unwrap_used)]
#[allow(clippy::expect_used)]
fn test_add_new_proxies_to_first_selector_group() {
let config_str = r#"
@@ -297,6 +303,7 @@ proxy-groups:
}
#[test]
#[allow(clippy::unwrap_used)]
#[allow(clippy::expect_used)]
fn test_preserve_non_sequence_proxy_groups() {
let config_str = r#"
+4 -2
View File
@@ -235,7 +235,8 @@ pub async fn import_local_backup(source: String) -> Result<String> {
let ext = source_path
.extension()
.and_then(|ext| ext.to_str())
.map_or_default(|ext| ext.to_ascii_lowercase());
.map(|ext| ext.to_ascii_lowercase())
.unwrap_or_default();
if ext != "zip" {
return Err(anyhow!("Only .zip backup files are supported"));
}
@@ -313,7 +314,8 @@ pub async fn list_local_backup() -> Result<Vec<LocalBackupFile>> {
};
let last_modified = metadata
.modified()
.map_or_default(|time| chrono::DateTime::<Utc>::from(time).to_rfc3339());
.map(|time| chrono::DateTime::<Utc>::from(time).to_rfc3339())
.unwrap_or_default();
backups.push(LocalBackupFile {
filename: file_name.into(),
path: path.to_string_lossy().into(),
+2 -2
View File
@@ -487,8 +487,8 @@ mod tests {
#[test]
fn package_urls_pin_the_resolved_version() {
let release = package_url(false, "v1.19.30").unwrap();
let alpha = package_url(true, "alpha-c0e43eb").unwrap();
let release = package_url(false, "v1.19.30").unwrap_or_default();
let alpha = package_url(true, "alpha-c0e43eb").unwrap_or_default();
assert!(release.contains("/releases/download/v1.19.30/"), "{release}");
assert!(
release.ends_with("-v1.19.30.gz") || release.ends_with("-v1.19.30.zip"),
+1 -1
View File
@@ -44,7 +44,7 @@ fn ensure_icon_cache_target(icon_cache_dir: &Path, file_name: &str) -> CmdResult
}
fn normalized_text_prefix(content: &[u8]) -> std::string::String {
let content = content.trim_prefix(&[0xEF, 0xBB, 0xBF]);
let content = content.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(content);
let start = content
.iter()
.position(|byte| !byte.is_ascii_whitespace())
+7 -7
View File
@@ -19,7 +19,7 @@ use crate::{
use anyhow::{Context as _, Result, anyhow, bail};
use clash_verge_draft::DraftTransaction;
use clash_verge_logging::{Type, logging};
use std::mem::DropGuard;
use scopeguard::{ScopeGuard, defer, guard};
pub async fn probe_listener(request: ListenerProbe) -> Result<ListenerProbeOutcome> {
AsyncHandler::spawn_blocking(move || probe_listener_sync(&request))
@@ -35,9 +35,9 @@ pub async fn save_proxy_ports(settings: ProxyPortSettings) -> Result<SaveProxyPo
if !manager.try_start_config_update() {
bail!("configuration update is already running");
}
let _config_update = DropGuard::new((), |()| {
defer! {
manager.finish_config_update();
});
}
// Read first because transaction rollback discards all claimed drafts.
let current = current_runtime_mapping().await?;
@@ -52,13 +52,13 @@ pub async fn save_proxy_ports(settings: ProxyPortSettings) -> Result<SaveProxyPo
// Hide PAC while the staged ports are not yet serving traffic.
manager.core_starting();
// Recompute PAC state after every exit path.
let _core_start = DropGuard::new((), |()| {
defer! {
manager.core_start_settled();
});
}
// A user-picked port ends the startup fallback, but only once the save lands: until then the
// Core still serves the borrowed port, so every failing exit must put it back or the system
// proxy and PAC point at a dead port. Declared after the PAC guard so it restores first.
let borrowed_port = DropGuard::new(MixedPort::session_fallback(), restore_borrowed_port);
let borrowed_port = guard(MixedPort::session_fallback(), restore_borrowed_port);
MixedPort::clear_session_fallback();
Config::generate()
.await
@@ -125,7 +125,7 @@ pub async fn save_proxy_ports(settings: ProxyPortSettings) -> Result<SaveProxyPo
transaction.commit();
// The save landed, so the port the app had borrowed is now irrelevant.
let _ = DropGuard::dismiss(borrowed_port);
let _ = ScopeGuard::into_inner(borrowed_port);
announce(Refresh::Clash);
announce(Refresh::Verge);
logging!(info, Type::Config, "Proxy port configuration applied and persisted");
+4 -6
View File
@@ -2,12 +2,10 @@
use crate::core::notify::NoticeStatus;
use std::{
mem::DropGuard,
sync::atomic::{AtomicBool, Ordering},
};
use std::sync::atomic::{AtomicBool, Ordering};
use clash_verge_logging::{Type, logging};
use scopeguard::defer;
use crate::{
config::{Config, IVerge},
@@ -63,9 +61,9 @@ pub async fn reconcile_tun_availability() {
// The flag coalesces newly spawned tasks while the config lock serializes writers.
DISABLING_TUN.store(true, Ordering::Release);
let _disabling_tun = DropGuard::new((), |()| {
defer! {
DISABLING_TUN.store(false, Ordering::Release);
});
}
logging!(
info,
+1 -1
View File
@@ -15,7 +15,7 @@ fn main() -> ExitCode {
#[cfg(not(all(feature = "perf-harness", target_os = "macos")))]
fn main() -> ExitCode {
let default_parallelism = std::thread::available_parallelism().map_or(1, |n| n.get());
let default_parallelism = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
let worker_limit = std::cmp::min(default_parallelism, 4);
let blocking_limit = 2 * worker_limit;
+3 -3
View File
@@ -3,10 +3,10 @@ use crate::{config::with_encryption, process::AsyncHandler};
use anyhow::{Context as _, Result, anyhow, bail};
use clash_verge_logging::{Type, logging};
use nanoid::nanoid;
use scopeguard::{ScopeGuard, guard};
use serde::{Serialize, de::DeserializeOwned};
use serde_yaml_ng::{Mapping, Value};
use std::{
mem::DropGuard,
path::{Path, PathBuf},
str::FromStr,
};
@@ -168,7 +168,7 @@ pub async fn save_yaml_str(path: &Path, yaml_str: &str) -> Result<()> {
}
};
let temporary = DropGuard::new(temporary, |path| {
let temporary = guard(temporary, |path| {
let _ = std::fs::remove_file(path);
});
let mut file = tokio::fs::File::from_std(file);
@@ -195,7 +195,7 @@ pub async fn save_yaml_str(path: &Path, yaml_str: &str) -> Result<()> {
std::fs::rename(temporary.as_path(), path)
.with_context(|| format!("failed to replace file \"{}\"", path.display()))?;
let _ = DropGuard::dismiss(temporary);
let _ = ScopeGuard::into_inner(temporary);
Ok(())
}
+3 -3
View File
@@ -234,15 +234,15 @@ impl WindowManager {
}
pub fn is_main_window_visible(window: Option<&WebviewWindow<Wry>>) -> bool {
window.is_some_and(|w| w.is_visible().unwrap_or(false))
window.map(|w| w.is_visible().unwrap_or(false)).unwrap_or(false)
}
pub fn is_main_window_focused(window: Option<&WebviewWindow<Wry>>) -> bool {
window.is_some_and(|w| w.is_focused().unwrap_or(false))
window.map(|w| w.is_focused().unwrap_or(false)).unwrap_or(false)
}
fn is_main_window_minimized(window: Option<&WebviewWindow<Wry>>) -> bool {
window.is_some_and(|w| w.is_minimized().unwrap_or(false))
window.map(|w| w.is_minimized().unwrap_or(false)).unwrap_or(false)
}
/// Keep new windows hidden until the frontend overlay renders, avoiding a theme flash.
+2 -8
View File
@@ -1008,13 +1008,8 @@ export const CurrentProxyCard = () => {
border: `1px solid ${alpha(theme.palette.primary.main, 0.1)}`,
}}
>
<Box sx={{ minWidth: 0, flex: 1 }}>
<Typography
variant="body1"
noWrap
title={currentProxy?.name}
sx={{ fontWeight: 'medium' }}
>
<Box>
<Typography variant="body1" sx={{ fontWeight: 'medium' }}>
{currentProxy?.name ??
t('home.components.currentProxy.labels.noActiveNode')}
</Typography>
@@ -1068,7 +1063,6 @@ export const CurrentProxyCard = () => {
size="small"
label={delayManager.formatDelay(currentDelay)}
color={convertDelayColor(currentDelay)}
sx={{ flexShrink: 0, ml: 1 }}
/>
)}
</Box>
@@ -1106,9 +1106,10 @@ export const EnhancedCanvasTrafficGraph = memo(
{tooltipData.visible && (
<Box
style={{ left: tooltipData.x + 8, top: tooltipData.y - 8 }}
sx={{
position: 'absolute',
left: tooltipData.x + 8,
top: tooltipData.y - 8,
bgcolor: theme.palette.background.paper,
border: 1,
borderColor: 'divider',
+25 -51
View File
@@ -1,5 +1,5 @@
import { useLockFn } from 'ahooks'
import { useCallback, useEffect, useReducer } from 'react'
import { useCallback, useSyncExternalStore } from 'react'
import { useVerge } from '@/hooks/use-verge'
import delayManager, { type DelayUpdate } from '@/services/delay'
@@ -17,13 +17,6 @@ const PRESET_PROXY_NAMES = [
'COMPATIBLE',
]
const identity = (previous: DelayUpdate, next: DelayUpdate): DelayUpdate =>
previous.delay === next.delay &&
previous.elapsed === next.elapsed &&
previous.updatedAt === next.updatedAt
? previous
: next
const INITIAL_DELAY: DelayUpdate = { delay: -1, updatedAt: 0 }
export interface UseProxyDelayState {
@@ -42,56 +35,37 @@ export function useProxyDelayState(
const details = memberDetails(member)
const unresolved = member.kind === 'unresolved'
const isPreset = unresolved || PRESET_PROXY_NAMES.includes(name)
const [delayState, setDelayState] = useReducer(identity, INITIAL_DELAY)
const { verge } = useVerge()
const timeout = verge?.default_latency_timeout || 10000
useEffect(() => {
if (isPreset) return
delayManager.setListener(name, groupName, setDelayState)
return () => {
delayManager.removeListener(name, groupName)
}
}, [name, groupName, isPreset])
const subscribe = useCallback(
(onChange: () => void) =>
isPreset ? () => {} : delayManager.addListener(name, groupName, onChange),
[name, groupName, isPreset],
)
const read = useCallback(
() =>
unresolved ? undefined : delayManager.getDelayUpdate(name, groupName),
[name, groupName, unresolved],
)
const cachedUpdate = useSyncExternalStore(subscribe, read, read)
const updateDelay = useCallback(() => {
if (unresolved) {
setDelayState(INITIAL_DELAY)
return
}
const cachedUpdate = delayManager.getDelayUpdate(name, groupName)
if (cachedUpdate) {
setDelayState({ ...cachedUpdate })
return
}
const fallbackDelay = delayManager.getDelayFix(member, groupName)
if (fallbackDelay === -1) {
setDelayState({ delay: -1, updatedAt: 0 })
return
}
let updatedAt = 0
const history = details?.history
if (history && history.length > 0) {
const lastRecord = history[history.length - 1]
const parsed = Date.parse(lastRecord.time)
if (!Number.isNaN(parsed)) {
updatedAt = parsed
}
}
setDelayState({ delay: fallbackDelay, updatedAt })
}, [details?.history, groupName, member, name, unresolved])
useEffect(() => {
updateDelay()
}, [updateDelay])
const fallbackDelay = delayManager.getDelayFix(member, groupName)
const history = details?.history
const lastRecord = history?.[history.length - 1]
const parsed = lastRecord ? Date.parse(lastRecord.time) : NaN
const delayState =
cachedUpdate ??
(fallbackDelay === -1
? INITIAL_DELAY
: {
delay: fallbackDelay,
updatedAt: Number.isNaN(parsed) ? 0 : parsed,
})
const onDelay = useLockFn(async () => {
if (!isInteractableMember(member)) return
setDelayState({ delay: -2, updatedAt: Date.now() })
setDelayState(await delayManager.checkDelay(member, groupName, timeout))
await delayManager.checkDelay(member, groupName, timeout)
})
return {
@@ -9,7 +9,6 @@ import { useEffect, useMemo } from 'react'
import { useVerge } from '@/hooks/use-verge'
import { defaultDarkTheme, defaultTheme } from '@/pages/_theme'
import { useSetThemeMode, useThemeMode } from '@/services/states'
import getSystem from '@/utils/get-system'
const CSS_INJECTION_SCOPE_ROOT = '[data-css-injection-root]'
const CSS_INJECTION_SCOPE_LIMIT =
@@ -140,12 +139,6 @@ export const useCustomTheme = () => {
console.error(`Failed to set window theme to ${mode}:`, err)
})
}
if (getSystem() === 'macos' && mode) {
const background = mode === 'light' ? defaultTheme : defaultDarkTheme
appWindow.setBackgroundColor(background.background_color).catch((err) => {
console.error('Failed to set window background:', err)
})
}
}, [mode, appWindow, theme_mode])
const theme = useMemo(() => {
+5 -42
View File
@@ -71,10 +71,6 @@ const ORDER_OPTIONS = [
type OrderKey = (typeof ORDER_OPTIONS)[number]['id']
type NetworkFilter = 'all' | 'tcp' | 'udp'
let savedNetworkFilter: NetworkFilter = 'all'
const orderFunctionMap = ORDER_OPTIONS.reduce<Record<OrderKey, OrderFunc>>(
(acc, option) => {
acc[option.id] = option.fn
@@ -90,9 +86,6 @@ const ConnectionsPage = () => {
const { searchState, match, onSearch } = usePageSearch('connections')
const hasSearch = searchState.text.length > 0
const [curOrderOpt, setCurOrderOpt] = useState<OrderKey>('default')
const [networkFilter, setNetworkFilter] =
useState<NetworkFilter>(savedNetworkFilter)
const hasFilter = networkFilter !== 'all'
const [connectionsType, setConnectionsType] = useState<'active' | 'closed'>(
'active',
)
@@ -119,30 +112,18 @@ const ConnectionsPage = () => {
const filterConn = useMemo(() => {
const orderFunc = orderFunctionMap[curOrderOpt]
if (isTableLayout && !hasSearch && !hasFilter) return selectedConnections
if (!hasSearch && !hasFilter) return orderFunc([...selectedConnections])
if (isTableLayout && !hasSearch) return selectedConnections
if (!hasSearch) return orderFunc([...selectedConnections])
const matchConns = selectedConnections.filter((conn) => {
const { host, destinationIP, process, network } = conn.metadata
if (networkFilter !== 'all' && network !== networkFilter) return false
const { host, destinationIP, process } = conn.metadata
return (
!hasSearch ||
match(host || '') ||
match(destinationIP || '') ||
match(process || '')
match(host || '') || match(destinationIP || '') || match(process || '')
)
})
return orderFunc ? orderFunc(matchConns) : matchConns
}, [
selectedConnections,
isTableLayout,
hasSearch,
hasFilter,
networkFilter,
match,
curOrderOpt,
])
}, [selectedConnections, isTableLayout, hasSearch, match, curOrderOpt])
const displayRows = useConnectionRowViews(
isTableLayout ? EMPTY_CONNECTIONS : filterConn,
@@ -274,24 +255,6 @@ const ConnectionsPage = () => {
))}
</BaseStyledSelect>
)}
<BaseStyledSelect
style={{ width: 80 }}
value={networkFilter}
onChange={(e) => {
savedNetworkFilter = e.target.value as NetworkFilter
setNetworkFilter(savedNetworkFilter)
}}
>
<MenuItem value="all">
<span style={{ fontSize: 14 }}>All</span>
</MenuItem>
<MenuItem value="tcp">
<span style={{ fontSize: 14 }}>TCP</span>
</MenuItem>
<MenuItem value="udp">
<span style={{ fontSize: 14 }}>UDP</span>
</MenuItem>
</BaseStyledSelect>
<Box
sx={{
flex: 1,
+11 -8
View File
@@ -39,18 +39,21 @@ const LogPage = () => {
return []
}
const hasSearch = searchState.text.length > 0
if (!hasSearch && logState === 'all') return logData
// Server-side filtering handles level filtering via query parameters
// We only need to apply search filtering here
return logData.filter((data) => {
if (logState !== 'all' && !data.type.includes(logState)) return false
if (!hasSearch) return true
// 构建完整的搜索文本,包含时间、类型和内容
const searchText =
`${data.time || ''} ${data.type} ${data.payload}`.toLowerCase()
return match(searchText)
const matchesSearch = match(searchText)
return (
(logState == 'all' ? true : data.type.includes(logState)) &&
matchesSearch
)
})
}, [logData, logState, match, searchState.text])
}, [logData, logState, match])
const filteredLogs = useMemo(
() => (isDescending ? [...filterLogs].reverse() : filterLogs),
+5 -1
View File
@@ -49,7 +49,11 @@ const ProxyPage = () => {
>(null)
const { clashConfig } = useClashConfigData()
const { refreshClashConfig } = useAppRefreshers()
const { refreshClashConfig, refreshProxy } = useAppRefreshers()
useEffect(() => {
refreshProxy().catch((error) => showNotice.error(error))
}, [refreshProxy])
const normalizedMode = clashConfig?.mode?.toLowerCase()
const curMode = isMode(normalizedMode) ? normalizedMode : undefined
+11 -1
View File
@@ -1,4 +1,4 @@
import React, { useCallback, useMemo, useRef } from 'react'
import React, { useCallback, useEffect, useMemo, useRef } from 'react'
import {
getBaseConfig,
getRuleProviders,
@@ -6,8 +6,10 @@ import {
} from 'tauri-plugin-mihomo-api'
import { useClashInfo, useRuntimeConfig } from '@/hooks/use-clash'
import { useProfiles } from '@/hooks/use-profiles'
import { useVerge } from '@/hooks/use-verge'
import { getProxyView, getSystemProxy } from '@/services/cmds'
import delayManager from '@/services/delay'
import { useQuery } from '@/services/query-client'
import { useRunState } from '@/store/app-store-context'
import { resolveDisplayedMixedPort } from '@/utils/mixed-port'
@@ -53,6 +55,8 @@ export const AppDataProvider = ({
const { verge } = useVerge()
const { data: runtimeConfig } = useRuntimeConfig()
const { clashInfo } = useClashInfo()
const { profiles } = useProfiles()
const currentProfile = profiles?.current
const {
data: proxyView,
@@ -102,6 +106,12 @@ export const AppDataProvider = ({
const runningMode = runState?.mode
const refreshProxy = useStableFn(_refetchProxyView)
useEffect(() => {
if (currentProfile === undefined) return
delayManager.setProfile(currentProfile)
void refreshProxy()
}, [currentProfile, refreshProxy])
const refreshClashConfig = useStableFn(_refetchClashConfig)
const refreshRules = useStableFn(_refetchRules)
const refreshSysproxy = useStableFn(_refetchSysproxy)
+66 -16
View File
@@ -5,26 +5,32 @@ vi.mock('tauri-plugin-mihomo-api', () => ({
healthcheckNodeInProvider: vi.fn(async () => ({ delay: 120 })),
}))
import type { ResolvedProxyMember } from '@/types/proxy-view'
import type { InteractableProxyMember } from '@/types/proxy-view'
import delayManager from './delay'
const node = (name: string) =>
({
kind: 'node',
ref: { kind: 'node', name, recordId: `r:${name}` },
node: {
recordId: `r:${name}`,
name,
history: [],
source: { kind: 'core', proxyName: name },
},
}) as unknown as ResolvedProxyMember
const flush = () => new Promise((resolve) => setTimeout(resolve, 0))
const node = (
name: string,
): Extract<InteractableProxyMember, { kind: 'node' }> => ({
kind: 'node',
ref: { kind: 'node', name, recordId: `r:${name}` },
node: {
recordId: `r:${name}`,
name,
type: 'Shadowsocks',
history: [],
source: { kind: 'core', proxyName: name },
udp: false,
xudp: false,
tfo: false,
mptcp: false,
smux: false,
},
})
let settles = 0
let unsubscribe: () => void
const flush = () => new Promise((resolve) => setTimeout(resolve, 0))
beforeEach(() => {
settles = 0
@@ -39,7 +45,7 @@ describe('group delay completion', () => {
test('notifies once after a batch settles', async () => {
const proxies = Array.from({ length: 6 }, (_, index) => node(`n${index}`))
await delayManager.checkListDelay(proxies as never, 'g', 5000, 2)
await delayManager.checkListDelay(proxies, 'g', 5000, 2)
await flush()
expect(settles).toBe(1)
@@ -51,7 +57,7 @@ describe('group delay completion', () => {
other += 1
})
await delayManager.checkDelay(node('a') as never, 'g', 5000)
await delayManager.checkDelay(node('a'), 'g', 5000)
await flush()
expect(settles).toBe(1)
@@ -59,3 +65,47 @@ describe('group delay completion', () => {
stop()
})
})
describe('profile delay isolation', () => {
test('notifies both shared-key occurrences and preserves the surviving subscription', async () => {
const first = vi.fn()
const second = vi.fn()
const stopFirst = delayManager.addListener('a', 'g', first)
const stopSecond = delayManager.addListener('a', 'g', second)
try {
delayManager.setDelay('a', 'g', -2)
const pending = delayManager.getDelayUpdate('a', 'g')
expect(delayManager.getDelayUpdate('a', 'g')).toBe(pending)
await flush()
stopFirst()
delayManager.setDelay('a', 'g', 120)
expect(delayManager.getDelayUpdate('a', 'g')).not.toBe(pending)
await flush()
expect(first.mock.calls.map(([update]) => update.delay)).toEqual([-2])
expect(second.mock.calls.map(([update]) => update.delay)).toEqual([
-2, 120,
])
} finally {
stopFirst()
stopSecond()
}
})
test('clears cached delays and fences an old batch across a profile switch', async () => {
delayManager.setProfile('initial')
delayManager.setDelay('cached', 'g', 900)
const oldBatch = delayManager.checkListDelay(
[node('a'), node('not-started')],
'g',
5000,
1,
)
delayManager.setProfile('next')
expect(delayManager.getDelayUpdate('cached', 'g')).toBeUndefined()
delayManager.setDelay('a', 'g', 42)
await oldBatch
await flush()
expect(delayManager.getDelay('a', 'g')).toBe(42)
expect(delayManager.getDelayUpdate('not-started', 'g')).toBeUndefined()
})
})
+83 -33
View File
@@ -29,10 +29,12 @@ export interface DelayUpdate {
const CACHE_TTL = 30 * 60 * 1000
class DelayManager {
private profile: string | null = null
private generation = 0
private cache = new Map<string, DelayUpdate>()
private urlMap = new Map<string, string>()
private listenerMap = new Map<string, (update: DelayUpdate) => void>()
private listenerMap = new Map<string, Set<(update: DelayUpdate) => void>>()
private groupListenerMap = new Map<string, Set<() => void>>()
// Consumers compare snapshot identity; replace it only when the group settles.
@@ -49,6 +51,35 @@ class DelayManager {
private itemFlushScheduled = false
private groupFlushScheduled = false
setProfile(profile: string | null) {
if (this.profile === profile) return
this.profile = profile
this.generation += 1
this.cache.clear()
this.activeBatches.clear()
this.pendingItemUpdates.clear()
this.pendingGroupUpdates.clear()
this.groupSnapshots.clear()
this.groupSetSnapshots.clear()
// Reset before a refreshed proxy snapshot can publish newer history.
for (const [key, listeners] of this.listenerMap) {
for (const listener of [...listeners]) {
try {
listener({ delay: -1, updatedAt: 0 })
} catch (error) {
console.error(
`[DelayManager] Failed to reset delay listener: ${key}`,
error,
)
}
}
}
for (const group of this.groupListenerMap.keys()) {
this.queueGroupNotification(group)
}
}
private scheduleOnNextFrame(run: () => void): void {
if (typeof window !== 'undefined') {
if (typeof window.requestAnimationFrame === 'function') {
@@ -74,17 +105,19 @@ class DelayManager {
this.pendingItemUpdates = new Map()
updates.forEach((queue, key) => {
const listener = this.listenerMap.get(key)
if (!listener) return
const listeners = this.listenerMap.get(key)
if (!listeners) return
queue.forEach((update) => {
try {
listener(update)
} catch (error) {
console.error(
`[DelayManager] 通知节点延迟监听器失败: ${key}`,
error,
)
for (const listener of [...listeners]) {
try {
listener(update)
} catch (error) {
console.error(
`[DelayManager] 通知节点延迟监听器失败: ${key}`,
error,
)
}
}
})
})
@@ -170,18 +203,22 @@ class DelayManager {
return url || 'http://cp.cloudflare.com/generate_204'
}
setListener(
addListener(
name: string,
group: string,
listener: (update: DelayUpdate) => void,
) {
): () => void {
const key = hashKey(name, group)
this.listenerMap.set(key, listener)
}
const listeners = this.listenerMap.get(key) ?? new Set()
listeners.add(listener)
this.listenerMap.set(key, listeners)
removeListener(name: string, group: string) {
const key = hashKey(name, group)
this.listenerMap.delete(key)
return () => {
const current = this.listenerMap.get(key)
if (!current) return
current.delete(listener)
if (current.size === 0) this.listenerMap.delete(key)
}
}
/** Multiple views may subscribe independently; notifications occur only after settle. */
@@ -237,7 +274,8 @@ class DelayManager {
return undefined
}
return { ...entry }
// React's external-store reads must retain identity until the value changes.
return entry
}
getDelay(name: string, group: string) {
@@ -276,19 +314,21 @@ class DelayManager {
member: InteractableProxyMember,
group: string,
timeout: number,
): Promise<DelayUpdate> {
): Promise<void> {
const generation = this.generation
// Entry points own the pending mark; measureDelay only writes results.
this.setDelay(member.ref.name, group, -2)
const update = await this.measureDelay(member, group, timeout)
this.queueGroupNotification(group)
return update
await this.measureDelay(member, group, timeout, generation)
if (generation === this.generation) this.queueGroupNotification(group)
}
private async measureDelay(
member: InteractableProxyMember,
group: string,
timeout: number,
): Promise<DelayUpdate> {
generation: number,
): Promise<void> {
if (generation !== this.generation) return
const name = member.ref.name
const providerName =
member.kind === 'node' ? providerNameOf(member.node) : undefined
@@ -324,14 +364,18 @@ class DelayManager {
const elapsed = elapsedTime
debugLog(`[DelayManager] 延迟测试完成,代理: ${name}, 结果: ${delay}ms`)
return this.setDelay(name, group, delay, { elapsed })
if (generation === this.generation) {
this.setDelay(name, group, delay, { elapsed })
}
} catch (error) {
await new Promise((resolve) => setTimeout(resolve, 500))
console.error(`[DelayManager] 延迟测试出错,代理: ${name}`, error)
const delay = 1e6 // error
const elapsed = Date.now() - startTime
return this.setDelay(name, group, delay, { elapsed })
if (generation === this.generation) {
this.setDelay(name, group, delay, { elapsed })
}
}
}
@@ -341,6 +385,7 @@ class DelayManager {
timeout: number,
concurrency = 36,
) {
const generation = this.generation
debugLog(
`[DelayManager] 批量测试延迟开始,组: ${group}, 数量: ${proxies.length}, 并发数: ${concurrency}`,
)
@@ -354,6 +399,7 @@ class DelayManager {
const startTime = Date.now()
const help = async (): Promise<void> => {
if (generation !== this.generation) return
const currMember = proxies[index++]
if (!currMember) return
const currName = currMember.ref.name
@@ -367,13 +413,15 @@ class DelayManager {
}
// Do not reorder a list around the pointer while batch results are arriving.
await this.measureDelay(currMember, group, timeout)
await this.measureDelay(currMember, group, timeout, generation)
} catch (error) {
console.error(
`[DelayManager] 批量测试单个代理出错,代理: ${currName}`,
error,
)
this.setDelay(currName, group, 1e6)
if (generation === this.generation) {
this.setDelay(currName, group, 1e6)
}
}
return help()
@@ -391,12 +439,14 @@ class DelayManager {
await Promise.all(promiseList)
} finally {
// Always release the batch and notify; otherwise failures leave stale sort state.
const remaining = (this.activeBatches.get(group) ?? 1) - 1
if (remaining > 0) {
this.activeBatches.set(group, remaining)
} else {
this.activeBatches.delete(group)
this.queueGroupNotification(group)
if (generation === this.generation) {
const remaining = (this.activeBatches.get(group) ?? 1) - 1
if (remaining > 0) {
this.activeBatches.set(group, remaining)
} else {
this.activeBatches.delete(group)
this.queueGroupNotification(group)
}
}
}
const totalTime = Date.now() - startTime