mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-17 01:02:08 +08:00
Compare commits
32
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6accebab3a | ||
|
|
eacf138cc2 | ||
|
|
4c82a6cddb | ||
|
|
13bce76c51 | ||
|
|
65042b8887 | ||
|
|
d1649fcc8d | ||
|
|
368e41f48a | ||
|
|
11340794e1 | ||
|
|
578986fd24 | ||
|
|
b2689b4220 | ||
|
|
5321eb44b8 | ||
|
|
f0dd12dfb8 | ||
|
|
423b51e780 | ||
|
|
d59986182c | ||
|
|
41ad2d6d02 | ||
|
|
bab4cd14cb | ||
|
|
ca1e55d64e | ||
|
|
a0ce1cdadf | ||
|
|
d2e294ccce | ||
|
|
3c2ef1af00 | ||
|
|
c012a6cdf2 | ||
|
|
b3da333b56 | ||
|
|
8ca401a742 | ||
|
|
3cfef4a990 | ||
|
|
bbb0a0267f | ||
|
|
119ee86082 | ||
|
|
c2e36ab733 | ||
|
|
03d5c3715f | ||
|
|
b89d09e24e | ||
|
|
abd89a1457 | ||
|
|
2c60f55f45 | ||
|
|
b8c13c0370 |
@@ -1,2 +1,3 @@
|
|||||||
avoid-breaking-exported-api = true
|
avoid-breaking-exported-api = true
|
||||||
|
allow-unwrap-in-tests = true
|
||||||
cognitive-complexity-threshold = 25
|
cognitive-complexity-threshold = 25
|
||||||
|
|||||||
@@ -4,11 +4,11 @@
|
|||||||
|
|
||||||
"features": {
|
"features": {
|
||||||
"ghcr.io/devcontainers/features/node:2": {
|
"ghcr.io/devcontainers/features/node:2": {
|
||||||
"version": "26.13.0",
|
"version": "26.13.1",
|
||||||
"pnpmVersion": "12.18.0"
|
"pnpmVersion": "12.18.0"
|
||||||
},
|
},
|
||||||
"ghcr.io/devcontainers/features/rust:1": {
|
"ghcr.io/devcontainers/features/rust:1": {
|
||||||
"version": "1.99.1",
|
"version": "1.100.0",
|
||||||
"profile": "default"
|
"profile": "default"
|
||||||
},
|
},
|
||||||
"ghcr.io/devcontainers/features/git:1": {},
|
"ghcr.io/devcontainers/features/git:1": {},
|
||||||
|
|||||||
@@ -5,10 +5,10 @@
|
|||||||
"version": "v9.0.0",
|
"version": "v9.0.0",
|
||||||
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
|
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
|
||||||
},
|
},
|
||||||
"github/gh-aw-actions/setup@v1.2.2": {
|
"github/gh-aw-actions/setup@v1.3.0": {
|
||||||
"repo": "github/gh-aw-actions/setup",
|
"repo": "github/gh-aw-actions/setup",
|
||||||
"version": "v1.2.2",
|
"version": "v1.3.0",
|
||||||
"sha": "53d0749e19424a918acd82b4d140264ce48f2f14"
|
"sha": "8126d6cb07dea9221848de275af8a41474d839ca"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"containers": {
|
"containers": {
|
||||||
@@ -32,6 +32,16 @@
|
|||||||
"digest": "sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2",
|
"digest": "sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2",
|
||||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.28.23@sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2"
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.28.23@sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2"
|
||||||
},
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/agent:0.29.11": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/agent:0.29.11",
|
||||||
|
"digest": "sha256:8774a73c351395b41d2ad0af4ddb4689007c67de3cd08bd9f43bb8a0e300690e",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.11@sha256:8774a73c351395b41d2ad0af4ddb4689007c67de3cd08bd9f43bb8a0e300690e"
|
||||||
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/agent:0.29.14": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/agent:0.29.14",
|
||||||
|
"digest": "sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa"
|
||||||
|
},
|
||||||
"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13": {
|
"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13": {
|
||||||
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13",
|
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13",
|
||||||
"digest": "sha256:61f12dcff38eb008b645d87a5541763452f409d9040eb243718764944167b1a2",
|
"digest": "sha256:61f12dcff38eb008b645d87a5541763452f409d9040eb243718764944167b1a2",
|
||||||
@@ -52,6 +62,31 @@
|
|||||||
"digest": "sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64",
|
"digest": "sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64",
|
||||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.23@sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64"
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.23@sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64"
|
||||||
},
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.11": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.11",
|
||||||
|
"digest": "sha256:88d2d0e315a504d93fd4fb8847fd0f6b7f4469f41a6fc6047b3dc9654c56ab2c",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.11@sha256:88d2d0e315a504d93fd4fb8847fd0f6b7f4469f41a6fc6047b3dc9654c56ab2c"
|
||||||
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14",
|
||||||
|
"digest": "sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0"
|
||||||
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11",
|
||||||
|
"digest": "sha256:97782bc0d8ff7f80f19ae2fdc5e1668517aa732a6fa077e64b8d3919238496d2",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11@sha256:97782bc0d8ff7f80f19ae2fdc5e1668517aa732a6fa077e64b8d3919238496d2"
|
||||||
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14",
|
||||||
|
"digest": "sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14@sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12"
|
||||||
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/router:0.29.14": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.14",
|
||||||
|
"digest": "sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.14@sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0"
|
||||||
|
},
|
||||||
"ghcr.io/github/gh-aw-firewall/squid:0.28.13": {
|
"ghcr.io/github/gh-aw-firewall/squid:0.28.13": {
|
||||||
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13",
|
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13",
|
||||||
"digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56",
|
"digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56",
|
||||||
@@ -72,20 +107,30 @@
|
|||||||
"digest": "sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0",
|
"digest": "sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0",
|
||||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.28.23@sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0"
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.28.23@sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0"
|
||||||
},
|
},
|
||||||
"ghcr.io/github/gh-aw-mcpg:v0.4.25": {
|
"ghcr.io/github/gh-aw-firewall/squid:0.29.11": {
|
||||||
"image": "ghcr.io/github/gh-aw-mcpg:v0.4.25",
|
"image": "ghcr.io/github/gh-aw-firewall/squid:0.29.11",
|
||||||
"digest": "sha256:9be0a86220e807a0ecc89e53d7453468f7a53fbc6b3d1efd2299025ffe01d086",
|
"digest": "sha256:861739ecf924dd2db5e5fb652db2ad82aaafd1615623297ddabc8f41a36b2847",
|
||||||
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.4.25@sha256:9be0a86220e807a0ecc89e53d7453468f7a53fbc6b3d1efd2299025ffe01d086"
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.11@sha256:861739ecf924dd2db5e5fb652db2ad82aaafd1615623297ddabc8f41a36b2847"
|
||||||
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/squid:0.29.14": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/squid:0.29.14",
|
||||||
|
"digest": "sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.14@sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c"
|
||||||
|
},
|
||||||
|
"ghcr.io/github/gh-aw-mcpg:v0.5.10": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-mcpg:v0.5.10",
|
||||||
|
"digest": "sha256:629ddcd68a48ab02e7db8af527d2756c6db563b00c1d31d8aa8fcbac96f01c59",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.5.10@sha256:629ddcd68a48ab02e7db8af527d2756c6db563b00c1d31d8aa8fcbac96f01c59"
|
||||||
},
|
},
|
||||||
"ghcr.io/github/gh-aw-node": {
|
"ghcr.io/github/gh-aw-node": {
|
||||||
"image": "ghcr.io/github/gh-aw-node",
|
"image": "ghcr.io/github/gh-aw-node",
|
||||||
"digest": "sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e",
|
"digest": "sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f",
|
||||||
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e"
|
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f"
|
||||||
},
|
},
|
||||||
"ghcr.io/github/github-mcp-server:v1.12.2": {
|
"ghcr.io/github/github-mcp-server:v2.1.0": {
|
||||||
"image": "ghcr.io/github/github-mcp-server:v1.12.2",
|
"image": "ghcr.io/github/github-mcp-server:v2.1.0",
|
||||||
"digest": "sha256:508a0857ec762b1ab1cece29193345b501fab1dd9d1228a7b617062954cecac6",
|
"digest": "sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a",
|
||||||
"pinned_image": "ghcr.io/github/github-mcp-server:v1.12.2@sha256:508a0857ec762b1ab1cece29193345b501fab1dd9d1228a7b617062954cecac6"
|
"pinned_image": "ghcr.io/github/github-mcp-server:v2.1.0@sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ jobs:
|
|||||||
- name: Install Node
|
- name: Install Node
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: pnpm install --frozen-lockfile
|
run: pnpm install --frozen-lockfile
|
||||||
@@ -154,7 +154,7 @@ jobs:
|
|||||||
- name: Install Rust Stable
|
- name: Install Rust Stable
|
||||||
uses: dtolnay/rust-toolchain@master
|
uses: dtolnay/rust-toolchain@master
|
||||||
with:
|
with:
|
||||||
toolchain: '1.99.1'
|
toolchain: '1.100.0'
|
||||||
targets: ${{ matrix.target }}
|
targets: ${{ matrix.target }}
|
||||||
|
|
||||||
- name: Rust Cache
|
- name: Rust Cache
|
||||||
@@ -182,7 +182,7 @@ jobs:
|
|||||||
- name: Install Node
|
- name: Install Node
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
|
|
||||||
- name: Pnpm install and check
|
- name: Pnpm install and check
|
||||||
@@ -240,7 +240,7 @@ jobs:
|
|||||||
- name: Install Rust Stable
|
- name: Install Rust Stable
|
||||||
uses: dtolnay/rust-toolchain@master
|
uses: dtolnay/rust-toolchain@master
|
||||||
with:
|
with:
|
||||||
toolchain: '1.99.1'
|
toolchain: '1.100.0'
|
||||||
targets: ${{ matrix.target }}
|
targets: ${{ matrix.target }}
|
||||||
|
|
||||||
- name: Rust Cache
|
- name: Rust Cache
|
||||||
@@ -262,7 +262,7 @@ jobs:
|
|||||||
- name: Install Node
|
- name: Install Node
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
|
|
||||||
- name: Pnpm install and check
|
- name: Pnpm install and check
|
||||||
@@ -373,7 +373,7 @@ jobs:
|
|||||||
- name: Install Rust Stable
|
- name: Install Rust Stable
|
||||||
uses: dtolnay/rust-toolchain@master
|
uses: dtolnay/rust-toolchain@master
|
||||||
with:
|
with:
|
||||||
toolchain: '1.99.1'
|
toolchain: '1.100.0'
|
||||||
targets: ${{ matrix.target }}
|
targets: ${{ matrix.target }}
|
||||||
|
|
||||||
- name: Rust Cache
|
- name: Rust Cache
|
||||||
@@ -395,7 +395,7 @@ jobs:
|
|||||||
- name: Install Node
|
- name: Install Node
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
|
|
||||||
- name: Pnpm install and check
|
- name: Pnpm install and check
|
||||||
@@ -479,7 +479,7 @@ jobs:
|
|||||||
- name: Install Node
|
- name: Install Node
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
|
|
||||||
- uses: pnpm/action-setup@v6.1.1
|
- uses: pnpm/action-setup@v6.1.1
|
||||||
name: Install pnpm
|
name: Install pnpm
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-node@v7
|
- uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
|
|
||||||
- run: pnpm install --frozen-lockfile
|
- run: pnpm install --frozen-lockfile
|
||||||
|
|||||||
@@ -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@53d0749e19424a918acd82b4d140264ce48f2f14 # v1.2.2
|
uses: github/gh-aw-actions/setup-cli@8126d6cb07dea9221848de275af8a41474d839ca # v1.3.0
|
||||||
with:
|
with:
|
||||||
version: v1.0.1
|
version: v1.3.0
|
||||||
- name: Install Rust Stable
|
- name: Install Rust Stable
|
||||||
uses: dtolnay/rust-toolchain@stable
|
uses: dtolnay/rust-toolchain@stable
|
||||||
with:
|
with:
|
||||||
@@ -49,7 +49,7 @@ jobs:
|
|||||||
- name: Install Node.js
|
- name: Install Node.js
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
- name: Install frontend dependencies
|
- name: Install frontend dependencies
|
||||||
env:
|
env:
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ jobs:
|
|||||||
- name: Install Node
|
- name: Install Node
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
|
|
||||||
- uses: pnpm/action-setup@v6
|
- uses: pnpm/action-setup@v6
|
||||||
name: Install pnpm
|
name: Install pnpm
|
||||||
|
|||||||
@@ -74,7 +74,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Install Rust Stable
|
- name: Install Rust Stable
|
||||||
if: github.event.inputs[matrix.input] == 'true'
|
if: github.event.inputs[matrix.input] == 'true'
|
||||||
uses: dtolnay/rust-toolchain@1.99.1
|
uses: dtolnay/rust-toolchain@1.100.0
|
||||||
|
|
||||||
- name: Rust Cache
|
- name: Rust Cache
|
||||||
if: github.event.inputs[matrix.input] == 'true'
|
if: github.event.inputs[matrix.input] == 'true'
|
||||||
@@ -104,7 +104,7 @@ jobs:
|
|||||||
if: github.event.inputs[matrix.input] == 'true'
|
if: github.event.inputs[matrix.input] == 'true'
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
|
|
||||||
- name: Pnpm install and check
|
- name: Pnpm install and check
|
||||||
@@ -121,7 +121,7 @@ jobs:
|
|||||||
if: github.event.inputs[matrix.input] == 'true'
|
if: github.event.inputs[matrix.input] == 'true'
|
||||||
run: |
|
run: |
|
||||||
# Ensure cross target is installed for the pinned toolchain; fallback without explicit toolchain if needed
|
# Ensure cross target is installed for the pinned toolchain; fallback without explicit toolchain if needed
|
||||||
rustup target add ${{ matrix.target }} --toolchain 1.99.1 || rustup target add ${{ matrix.target }}
|
rustup target add ${{ matrix.target }} --toolchain 1.100.0 || rustup target add ${{ matrix.target }}
|
||||||
rustup target list --installed
|
rustup target list --installed
|
||||||
echo "Rust target ${{ matrix.target }} installed."
|
echo "Rust target ${{ matrix.target }} installed."
|
||||||
|
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-node@v7
|
- uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
|
|
||||||
- run: pnpm install --frozen-lockfile
|
- run: pnpm install --frozen-lockfile
|
||||||
|
|||||||
+112
-64
File diff suppressed because one or more lines are too long
Generated
+115
-66
File diff suppressed because one or more lines are too long
@@ -61,7 +61,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-node@v7
|
- uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
|
|
||||||
- uses: pnpm/action-setup@v6
|
- uses: pnpm/action-setup@v6
|
||||||
if: github.event.action != 'closed'
|
if: github.event.action != 'closed'
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ jobs:
|
|||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
- uses: actions/setup-node@v7
|
- uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
- name: Validate source and publish the approved snapshot
|
- name: Validate source and publish the approved snapshot
|
||||||
id: source
|
id: source
|
||||||
env:
|
env:
|
||||||
@@ -203,7 +203,7 @@ jobs:
|
|||||||
- name: Install Rust Stable
|
- name: Install Rust Stable
|
||||||
uses: dtolnay/rust-toolchain@master
|
uses: dtolnay/rust-toolchain@master
|
||||||
with:
|
with:
|
||||||
toolchain: '1.99.1'
|
toolchain: '1.100.0'
|
||||||
targets: ${{ matrix.target }}
|
targets: ${{ matrix.target }}
|
||||||
|
|
||||||
- name: Rust Cache
|
- name: Rust Cache
|
||||||
@@ -231,7 +231,7 @@ jobs:
|
|||||||
- name: Install Node
|
- name: Install Node
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
|
|
||||||
- name: Pnpm install and check
|
- name: Pnpm install and check
|
||||||
@@ -308,7 +308,7 @@ jobs:
|
|||||||
- name: Install Rust Stable
|
- name: Install Rust Stable
|
||||||
uses: dtolnay/rust-toolchain@master
|
uses: dtolnay/rust-toolchain@master
|
||||||
with:
|
with:
|
||||||
toolchain: '1.99.1'
|
toolchain: '1.100.0'
|
||||||
targets: ${{ matrix.target }}
|
targets: ${{ matrix.target }}
|
||||||
|
|
||||||
- name: Rust Cache
|
- name: Rust Cache
|
||||||
@@ -330,7 +330,7 @@ jobs:
|
|||||||
- name: Install Node
|
- name: Install Node
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
|
|
||||||
- name: Pnpm install and check
|
- name: Pnpm install and check
|
||||||
@@ -439,7 +439,7 @@ jobs:
|
|||||||
- name: Install Rust Stable
|
- name: Install Rust Stable
|
||||||
uses: dtolnay/rust-toolchain@master
|
uses: dtolnay/rust-toolchain@master
|
||||||
with:
|
with:
|
||||||
toolchain: '1.99.1'
|
toolchain: '1.100.0'
|
||||||
targets: ${{ matrix.target }}
|
targets: ${{ matrix.target }}
|
||||||
|
|
||||||
- name: Rust Cache
|
- name: Rust Cache
|
||||||
@@ -461,7 +461,7 @@ jobs:
|
|||||||
- name: Install Node
|
- name: Install Node
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
|
|
||||||
- name: Pnpm install and check
|
- name: Pnpm install and check
|
||||||
@@ -542,7 +542,7 @@ jobs:
|
|||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
- uses: actions/setup-node@v7
|
- uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
- uses: pnpm/action-setup@v6
|
- uses: pnpm/action-setup@v6
|
||||||
with:
|
with:
|
||||||
run_install: false
|
run_install: false
|
||||||
@@ -565,7 +565,7 @@ jobs:
|
|||||||
- name: Install Node
|
- name: Install Node
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
|
|
||||||
- uses: pnpm/action-setup@v6
|
- uses: pnpm/action-setup@v6
|
||||||
name: Install pnpm
|
name: Install pnpm
|
||||||
@@ -593,7 +593,7 @@ jobs:
|
|||||||
- name: Install Node
|
- name: Install Node
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
|
|
||||||
- uses: pnpm/action-setup@v6
|
- uses: pnpm/action-setup@v6
|
||||||
name: Install pnpm
|
name: Install pnpm
|
||||||
@@ -661,7 +661,7 @@ jobs:
|
|||||||
- name: Install Node
|
- name: Install Node
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
|
|
||||||
- uses: pnpm/action-setup@v6
|
- uses: pnpm/action-setup@v6
|
||||||
name: Install pnpm
|
name: Install pnpm
|
||||||
|
|||||||
+112
-64
File diff suppressed because one or more lines are too long
@@ -22,13 +22,13 @@ jobs:
|
|||||||
- name: Install Rust
|
- name: Install Rust
|
||||||
uses: dtolnay/rust-toolchain@master
|
uses: dtolnay/rust-toolchain@master
|
||||||
with:
|
with:
|
||||||
toolchain: '1.99.1'
|
toolchain: '1.100.0'
|
||||||
targets: x86_64-pc-windows-msvc
|
targets: x86_64-pc-windows-msvc
|
||||||
|
|
||||||
- name: Install Node
|
- name: Install Node
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
|
|
||||||
- name: Install pnpm
|
- name: Install pnpm
|
||||||
uses: pnpm/action-setup@v6
|
uses: pnpm/action-setup@v6
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
name: Sync Mihomo Changelog
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
dry_run:
|
||||||
|
description: Preview the Changelog diff without creating a PR
|
||||||
|
type: boolean
|
||||||
|
default: true
|
||||||
|
schedule:
|
||||||
|
# UTC+8 Monday 11:30
|
||||||
|
- cron: '30 3 * * 1'
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
pull-requests: write
|
||||||
|
issues: write
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: sync-mihomo-changelog
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
sync:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
ref: ${{ github.event.repository.default_branch }}
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
|
- uses: actions/setup-node@v7
|
||||||
|
with:
|
||||||
|
node-version: '26.13.1'
|
||||||
|
|
||||||
|
- name: Sync Mihomo version
|
||||||
|
id: sync
|
||||||
|
env:
|
||||||
|
DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}
|
||||||
|
run: |
|
||||||
|
args=()
|
||||||
|
if [[ "$DRY_RUN" == 'true' ]]; then args+=(--dry-run); fi
|
||||||
|
node scripts/sync-mihomo-version.mjs "${args[@]}"
|
||||||
|
|
||||||
|
- name: Create labeled PR and enqueue
|
||||||
|
if: steps.sync.outputs.changed == 'true' && !(github.event_name == 'workflow_dispatch' && inputs.dry_run)
|
||||||
|
uses: actions/github-script@v9
|
||||||
|
env:
|
||||||
|
MIHOMO_VERSION: ${{ steps.sync.outputs.version }}
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
const { readFileSync } = await import('node:fs');
|
||||||
|
const { execFileSync } = await import('node:child_process');
|
||||||
|
const { owner, repo } = context.repo;
|
||||||
|
const base = context.payload.repository.default_branch;
|
||||||
|
const version = process.env.MIHOMO_VERSION;
|
||||||
|
const appVersion = JSON.parse(readFileSync('package.json', 'utf8')).version;
|
||||||
|
const branch = `chore/sync-mihomo-${appVersion}-${version}`;
|
||||||
|
const title = `chore: sync Mihomo changelog to ${version}`;
|
||||||
|
const pulls = await github.rest.pulls.list({
|
||||||
|
owner, repo, base, head: `${owner}:${branch}`, state: 'all',
|
||||||
|
});
|
||||||
|
let pr = pulls.data[0];
|
||||||
|
if (pr && (pr.state !== 'open' || pr.user.login !== 'github-actions[bot]')) {
|
||||||
|
throw new Error(`Existing candidate needs maintainer attention: ${pr.html_url}`);
|
||||||
|
}
|
||||||
|
if (!pr) {
|
||||||
|
const sha = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
|
||||||
|
await github.rest.git.createRef({ owner, repo, ref: `refs/heads/${branch}`, sha });
|
||||||
|
await github.graphql(`mutation($input: CreateCommitOnBranchInput!) {
|
||||||
|
createCommitOnBranch(input: $input) { commit { oid } }
|
||||||
|
}`, {
|
||||||
|
input: {
|
||||||
|
branch: { repositoryNameWithOwner: `${owner}/${repo}`, branchName: branch },
|
||||||
|
expectedHeadOid: sha,
|
||||||
|
message: { headline: title },
|
||||||
|
fileChanges: { additions: [{
|
||||||
|
path: 'Changelog.md',
|
||||||
|
contents: readFileSync('Changelog.md').toString('base64'),
|
||||||
|
}] },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
({ data: pr } = await github.rest.pulls.create({
|
||||||
|
owner, repo, base, head: branch, title,
|
||||||
|
body: `## Problem\n\nChangelog.md needs to record the latest stable Mihomo version.\n\n` +
|
||||||
|
`## Approach\n\nRead the same upstream version.txt used by the core download script.\n\n` +
|
||||||
|
`## Scope\n\nOnly the Mihomo version line in Changelog.md changes to ${version}.`,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
for (let attempt = 0; attempt < 10; attempt++) {
|
||||||
|
({ data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: pr.number }));
|
||||||
|
if (pr.mergeable !== null) break;
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||||
|
}
|
||||||
|
if (!pr.mergeable) throw new Error(`Sync PR is not mergeable: ${pr.html_url}`);
|
||||||
|
const files = await github.paginate(github.rest.pulls.listFiles, {
|
||||||
|
owner, repo, pull_number: pr.number,
|
||||||
|
});
|
||||||
|
if (files.length !== 1 || files[0].filename !== 'Changelog.md') {
|
||||||
|
throw new Error('The sync PR must change only Changelog.md.');
|
||||||
|
}
|
||||||
|
await github.rest.issues.addLabels({
|
||||||
|
owner, repo, issue_number: pr.number, labels: ['dependencies', 'upstream'],
|
||||||
|
});
|
||||||
|
const result = await github.graphql(`query($id: ID!) {
|
||||||
|
node(id: $id) { ... on PullRequest { mergeQueueEntry { id } } }
|
||||||
|
}`, { id: pr.node_id });
|
||||||
|
if (!result.node.mergeQueueEntry) {
|
||||||
|
await github.graphql(`mutation($input: EnqueuePullRequestInput!) {
|
||||||
|
enqueuePullRequest(input: $input) { mergeQueueEntry { id } }
|
||||||
|
}`, { input: { pullRequestId: pr.node_id, expectedHeadOid: pr.head.sha } });
|
||||||
|
}
|
||||||
|
await core.summary.addRaw(`Queued Mihomo sync PR: ${pr.html_url}\n`).write();
|
||||||
@@ -34,7 +34,7 @@ jobs:
|
|||||||
- name: Install Node
|
- name: Install Node
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
|
|
||||||
- uses: pnpm/action-setup@v6
|
- uses: pnpm/action-setup@v6
|
||||||
name: Install pnpm
|
name: Install pnpm
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ jobs:
|
|||||||
- name: Install Node
|
- name: Install Node
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
|
|
||||||
- uses: pnpm/action-setup@v6
|
- uses: pnpm/action-setup@v6
|
||||||
name: Install pnpm
|
name: Install pnpm
|
||||||
@@ -39,7 +39,7 @@ jobs:
|
|||||||
- name: Install Node
|
- name: Install Node
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '26.13.0'
|
node-version: '26.13.1'
|
||||||
|
|
||||||
- uses: pnpm/action-setup@v6
|
- uses: pnpm/action-setup@v6
|
||||||
name: Install pnpm
|
name: Install pnpm
|
||||||
|
|||||||
+2
-2
@@ -1,3 +1,3 @@
|
|||||||
nodejs 26.13.0
|
nodejs 26.13.1
|
||||||
pnpm 12.18.0
|
pnpm 12.18.0
|
||||||
rust 1.99.1
|
rust 1.100.0
|
||||||
|
|||||||
@@ -68,6 +68,8 @@ the ownership evidence the AI-slop review evaluates (see
|
|||||||
- For code review and verification of review fixes, follow [REVIEW.md](REVIEW.md).
|
- For code review and verification of review fixes, follow [REVIEW.md](REVIEW.md).
|
||||||
Review is read-only unless changes are authorized; findings do not expand
|
Review is read-only unless changes are authorized; findings do not expand
|
||||||
that authorization to unrelated fixes, commits, pushes, or GitHub updates.
|
that authorization to unrelated fixes, commits, pushes, or GitHub updates.
|
||||||
|
- For macOS frontend performance or WebView memory investigations, follow
|
||||||
|
[scripts/perf/AGENTS.md](scripts/perf/AGENTS.md).
|
||||||
- When handing work between agents or review rounds, use the
|
- When handing work between agents or review rounds, use the
|
||||||
[AI context sharing guidance](REVIEW.md#ai-context-sharing).
|
[AI context sharing guidance](REVIEW.md#ai-context-sharing).
|
||||||
- Read the relevant sections and linked module rules, expanding only when the
|
- Read the relevant sections and linked module rules, expanding only when the
|
||||||
|
|||||||
Generated
+59
-46
@@ -912,7 +912,7 @@ checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"semver 1.0.28",
|
"semver 1.0.28",
|
||||||
"serde",
|
"serde",
|
||||||
"toml 1.1.6+spec-1.1.0",
|
"toml 1.2.1+spec-1.1.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1123,7 +1123,6 @@ dependencies = [
|
|||||||
"rfd 0.18.0",
|
"rfd 0.18.0",
|
||||||
"runas",
|
"runas",
|
||||||
"rustls",
|
"rustls",
|
||||||
"scopeguard",
|
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"serde_yaml_ng",
|
"serde_yaml_ng",
|
||||||
@@ -1224,8 +1223,8 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "clash_verge_service_ipc"
|
name = "clash_verge_service_ipc"
|
||||||
version = "2.7.7"
|
version = "2.8.1"
|
||||||
source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?tag=v2.7.7#3ed29700b093190b5e7addcaa892e77f172af544"
|
source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?tag=v2.8.1#9d4ea7d27fb3c43804bd18f3bb3b686528763239"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"kode-bridge",
|
"kode-bridge",
|
||||||
@@ -2203,7 +2202,7 @@ dependencies = [
|
|||||||
"cc",
|
"cc",
|
||||||
"memchr",
|
"memchr",
|
||||||
"rustc_version 0.4.1",
|
"rustc_version 0.4.1",
|
||||||
"toml 1.1.6+spec-1.1.0",
|
"toml 1.2.1+spec-1.1.0",
|
||||||
"vswhom",
|
"vswhom",
|
||||||
"winreg 0.55.0",
|
"winreg 0.55.0",
|
||||||
]
|
]
|
||||||
@@ -3878,16 +3877,16 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "kode-bridge"
|
name = "kode-bridge"
|
||||||
version = "0.5.2"
|
version = "0.6.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "cdb14ea1ba42eebb57b46bcdd67a20f11a3f076d846ddf772c68d7439f6c6eca"
|
checksum = "b17456ae84ba9c0da0f189bf00d13019805b89563ba846cd15ccd8c4bd6a2713"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytes",
|
"bytes",
|
||||||
"futures",
|
"futures",
|
||||||
"http",
|
"http",
|
||||||
"httparse",
|
"httparse",
|
||||||
"libc",
|
"libc",
|
||||||
"parking_lot 0.12.5",
|
"parking_lot 0.13.0",
|
||||||
"path-tree",
|
"path-tree",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
"rand 0.10.2",
|
"rand 0.10.2",
|
||||||
@@ -3897,7 +3896,7 @@ dependencies = [
|
|||||||
"tokio",
|
"tokio",
|
||||||
"tokio-stream",
|
"tokio-stream",
|
||||||
"tokio-util",
|
"tokio-util",
|
||||||
"toml 1.1.6+spec-1.1.0",
|
"toml 1.2.1+spec-1.1.0",
|
||||||
"tracing",
|
"tracing",
|
||||||
"url",
|
"url",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
@@ -4357,6 +4356,18 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "nix"
|
||||||
|
version = "0.32.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.13.2",
|
||||||
|
"cfg-if",
|
||||||
|
"cfg_aliases",
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "nohash-hasher"
|
name = "nohash-hasher"
|
||||||
version = "0.2.0"
|
version = "0.2.0"
|
||||||
@@ -4883,7 +4894,7 @@ checksum = "9cf20a545b305cf1da722b236b5155c9bb35f1d5ceb28c048bd96ca842f41b5b"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"android_system_properties",
|
"android_system_properties",
|
||||||
"log",
|
"log",
|
||||||
"nix",
|
"nix 0.31.3",
|
||||||
"objc2",
|
"objc2",
|
||||||
"objc2-foundation",
|
"objc2-foundation",
|
||||||
"objc2-ui-kit",
|
"objc2-ui-kit",
|
||||||
@@ -6522,9 +6533,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde_spanned"
|
name = "serde_spanned"
|
||||||
version = "1.1.1"
|
version = "1.1.3"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"
|
checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde_core",
|
"serde_core",
|
||||||
]
|
]
|
||||||
@@ -7073,9 +7084,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sysinfo"
|
name = "sysinfo"
|
||||||
version = "0.40.1"
|
version = "0.40.3"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0e8a3edbe0394ce115f3917a00349dd242be09eb5a091ed509eaf67b55cfb8a8"
|
checksum = "a86bac2f7d06e6384984118ad727f5694110f0ec44d924d05c8fdec3d030bee6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
"memchr",
|
"memchr",
|
||||||
@@ -7087,11 +7098,12 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sysproxy"
|
name = "sysproxy"
|
||||||
version = "0.7.1"
|
version = "0.7.2"
|
||||||
source = "git+https://github.com/clash-verge-rev/sysproxy-rs.git?branch=main#89ad876a0942c049ae72e1472f9fc3ed62023c5e"
|
source = "git+https://github.com/clash-verge-rev/sysproxy-rs.git?rev=2c9d0a538052aac6e44ad413156a6e848da262b9#2c9d0a538052aac6e44ad413156a6e848da262b9"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"iptools",
|
"iptools",
|
||||||
"log",
|
"log",
|
||||||
|
"serde",
|
||||||
"system-configuration",
|
"system-configuration",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.20",
|
||||||
"tokio",
|
"tokio",
|
||||||
@@ -7145,7 +7157,7 @@ dependencies = [
|
|||||||
"cfg-expr 0.20.9",
|
"cfg-expr 0.20.9",
|
||||||
"heck 0.5.0",
|
"heck 0.5.0",
|
||||||
"pkg-config",
|
"pkg-config",
|
||||||
"toml 1.1.6+spec-1.1.0",
|
"toml 1.2.1+spec-1.1.0",
|
||||||
"version-compare",
|
"version-compare",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -7499,7 +7511,7 @@ dependencies = [
|
|||||||
"tauri-plugin",
|
"tauri-plugin",
|
||||||
"tauri-utils",
|
"tauri-utils",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.20",
|
||||||
"toml 1.1.6+spec-1.1.0",
|
"toml 1.2.1+spec-1.1.0",
|
||||||
"url",
|
"url",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -7520,14 +7532,15 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-plugin-http"
|
name = "tauri-plugin-http"
|
||||||
version = "2.8.3"
|
version = "2.9.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2c57e3451553f95a1db3bfed6a358a77ce5080b6399a242c6eadac113f97abd2"
|
checksum = "c278945f30912c8c32728265c66d16ca1b139509c4874d00579f5c8c5276605a"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytes",
|
"bytes",
|
||||||
"cookie_store",
|
"cookie_store",
|
||||||
"data-url",
|
"data-url",
|
||||||
"http",
|
"http",
|
||||||
|
"percent-encoding",
|
||||||
"regex",
|
"regex",
|
||||||
"reqwest 0.12.28",
|
"reqwest 0.12.28",
|
||||||
"schemars 0.8.22",
|
"schemars 0.8.22",
|
||||||
@@ -7544,8 +7557,8 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-plugin-mihomo"
|
name = "tauri-plugin-mihomo"
|
||||||
version = "0.6.0"
|
version = "0.7.0"
|
||||||
source = "git+https://github.com/clash-verge-rev/tauri-plugin-mihomo?rev=7a03d16f4d39b1bb885b7babe66b9e153e34b615#7a03d16f4d39b1bb885b7babe66b9e153e34b615"
|
source = "git+https://github.com/clash-verge-rev/tauri-plugin-mihomo?rev=e49bbedcc67d60da2c10e81bc6433b0f8e8fa232#e49bbedcc67d60da2c10e81bc6433b0f8e8fa232"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"arc-swap",
|
"arc-swap",
|
||||||
"clashmap",
|
"clashmap",
|
||||||
@@ -7569,9 +7582,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-plugin-notification"
|
name = "tauri-plugin-notification"
|
||||||
version = "2.8.0"
|
version = "2.8.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "5bc6c194a95a535abdfbe3bc1af9a43935b8b9b29c216b8e71af8b59132703cf"
|
checksum = "14a226bfb8189ec4ab2c1936e66330ad06c44d9f6c54a674338208491dee177f"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"log",
|
"log",
|
||||||
"notify-rust",
|
"notify-rust",
|
||||||
@@ -7589,9 +7602,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-plugin-opener"
|
name = "tauri-plugin-opener"
|
||||||
version = "2.7.2"
|
version = "2.7.3"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "53810be1b4fed22bb6ac3f4cab5a2b80d9391d1af436bda145607532bc0bb219"
|
checksum = "54592c6718b42ab198bf11bda6a428a3553ca2f2f8e506df56f6a063ec328331"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"dunce",
|
"dunce",
|
||||||
"glob",
|
"glob",
|
||||||
@@ -7828,7 +7841,7 @@ dependencies = [
|
|||||||
"serde_with",
|
"serde_with",
|
||||||
"swift-rs",
|
"swift-rs",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.20",
|
||||||
"toml 1.1.6+spec-1.1.0",
|
"toml 1.2.1+spec-1.1.0",
|
||||||
"url",
|
"url",
|
||||||
"urlpattern",
|
"urlpattern",
|
||||||
"uuid",
|
"uuid",
|
||||||
@@ -7843,7 +7856,7 @@ checksum = "cc65d45c68858bfe420dd29e834b5d15dbecf8a07a8a16cf4d532c7b1f69d4b6"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"dunce",
|
"dunce",
|
||||||
"embed-resource",
|
"embed-resource",
|
||||||
"toml 1.1.6+spec-1.1.0",
|
"toml 1.2.1+spec-1.1.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -8209,14 +8222,14 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "toml"
|
name = "toml"
|
||||||
version = "1.1.6+spec-1.1.0"
|
version = "1.2.1+spec-1.1.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a"
|
checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"indexmap 2.14.0",
|
"indexmap 2.14.0",
|
||||||
"serde_core",
|
"serde_core",
|
||||||
"serde_spanned 1.1.1",
|
"serde_spanned 1.1.3",
|
||||||
"toml_datetime 1.1.1+spec-1.1.0",
|
"toml_datetime 1.1.3+spec-1.1.0",
|
||||||
"toml_parser",
|
"toml_parser",
|
||||||
"toml_writer",
|
"toml_writer",
|
||||||
"winnow 1.0.4",
|
"winnow 1.0.4",
|
||||||
@@ -8233,9 +8246,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "toml_datetime"
|
name = "toml_datetime"
|
||||||
version = "1.1.1+spec-1.1.0"
|
version = "1.1.3+spec-1.1.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
|
checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde_core",
|
"serde_core",
|
||||||
]
|
]
|
||||||
@@ -8283,16 +8296,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b"
|
checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"indexmap 2.14.0",
|
"indexmap 2.14.0",
|
||||||
"toml_datetime 1.1.1+spec-1.1.0",
|
"toml_datetime 1.1.3+spec-1.1.0",
|
||||||
"toml_parser",
|
"toml_parser",
|
||||||
"winnow 1.0.4",
|
"winnow 1.0.4",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "toml_parser"
|
name = "toml_parser"
|
||||||
version = "1.1.3+spec-1.1.0"
|
version = "1.1.5+spec-1.1.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"
|
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"winnow 1.0.4",
|
"winnow 1.0.4",
|
||||||
]
|
]
|
||||||
@@ -8305,9 +8318,9 @@ checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "toml_writer"
|
name = "toml_writer"
|
||||||
version = "1.1.2+spec-1.1.0"
|
version = "1.2.0+spec-1.1.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
|
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tonic"
|
name = "tonic"
|
||||||
@@ -8820,9 +8833,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "warp"
|
name = "warp"
|
||||||
version = "0.4.3"
|
version = "0.4.4"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c0a808122a8a77eecdabaefd88ddb1913c4be5ea1465399f63ba64c7aa705fea"
|
checksum = "c92be475cc42b6b3913eeac77f0cbc0dd8f6a1ad6400c0722dbe36ba0c3ee799"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytes",
|
"bytes",
|
||||||
"futures-channel",
|
"futures-channel",
|
||||||
@@ -9088,9 +9101,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "webpki-roots"
|
name = "webpki-roots"
|
||||||
version = "1.0.11"
|
version = "1.0.12"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171"
|
checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"rustls-pki-types",
|
"rustls-pki-types",
|
||||||
]
|
]
|
||||||
@@ -10126,9 +10139,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zip"
|
name = "zip"
|
||||||
version = "9.5.0"
|
version = "9.6.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0700e6c427aff64acdbf02e85fbfd946c2ee12319d1af013092f3a2178914ff8"
|
checksum = "80cc68510ea7553c30a69c732de5278e94183f68765af6c642dbccefd6ec777e"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes",
|
"aes",
|
||||||
"bzip2",
|
"bzip2",
|
||||||
@@ -10142,7 +10155,7 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
"lzma-rust2",
|
"lzma-rust2",
|
||||||
"memchr",
|
"memchr",
|
||||||
"nix",
|
"nix 0.32.0",
|
||||||
"pbkdf2",
|
"pbkdf2",
|
||||||
"ppmd-rust",
|
"ppmd-rust",
|
||||||
"sha1 0.11.0",
|
"sha1 0.11.0",
|
||||||
|
|||||||
@@ -132,6 +132,7 @@ large_const_arrays = "warn"
|
|||||||
large_futures = "deny"
|
large_futures = "deny"
|
||||||
large_stack_arrays = "warn"
|
large_stack_arrays = "warn"
|
||||||
large_types_passed_by_value = "deny"
|
large_types_passed_by_value = "deny"
|
||||||
|
map_unwrap_or = "deny"
|
||||||
missing_const_for_fn = "deny"
|
missing_const_for_fn = "deny"
|
||||||
mutex_atomic = "deny"
|
mutex_atomic = "deny"
|
||||||
mutex_integer = "deny"
|
mutex_integer = "deny"
|
||||||
|
|||||||
@@ -13,6 +13,8 @@
|
|||||||
first (Windows/macOS/Linux) when the change is platform-specific;
|
first (Windows/macOS/Linux) when the change is platform-specific;
|
||||||
merge sub-symptoms as 主题:症状、症状; full-width punctuation,
|
merge sub-symptoms as 主题:症状、症状; full-width punctuation,
|
||||||
「」 for UI labels, backticks for config keys and commands
|
「」 for UI labels, backticks for config keys and commands
|
||||||
|
- omit the redundant suffix 「的问题」; end with the concrete symptom
|
||||||
|
or outcome instead
|
||||||
- platform entries sit under their platform heading (bold, emoji
|
- platform entries sit under their platform heading (bold, emoji
|
||||||
prefixed, ordered Windows/macOS/Linux, combined for pairs like
|
prefixed, ordered Windows/macOS/Linux, combined for pairs like
|
||||||
macOS/Linux) at the end of their section;
|
macOS/Linux) at the end of their section;
|
||||||
@@ -21,6 +23,8 @@
|
|||||||
GitHub, so they never reach users. -->
|
GitHub, so they never reach users. -->
|
||||||
## v2.6.0
|
## v2.6.0
|
||||||
|
|
||||||
|
- **Mihomo 内核升级至 v1.19.34**
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary><strong> 🐞 修复问题 </strong></summary>
|
<summary><strong> 🐞 修复问题 </strong></summary>
|
||||||
|
|
||||||
@@ -29,17 +33,27 @@
|
|||||||
- 修复全局模式默认停在 `DIRECT` 或 `REJECT` 导致流量未经代理,现自动切换到第一个策略组
|
- 修复全局模式默认停在 `DIRECT` 或 `REJECT` 导致流量未经代理,现自动切换到第一个策略组
|
||||||
- 修复订阅中未加引号的 REALITY `short-id`(如 `1234e123`)被误读为数字,导致订阅无法启用
|
- 修复订阅中未加引号的 REALITY `short-id`(如 `1234e123`)被误读为数字,导致订阅无法启用
|
||||||
- 修复订阅中唯一的代理组名为 `GLOBAL` 或没有代理组时,规则模式下代理页面显示「未获取到代理信息」
|
- 修复订阅中唯一的代理组名为 `GLOBAL` 或没有代理组时,规则模式下代理页面显示「未获取到代理信息」
|
||||||
|
- 修复窗口较窄时,首页「当前节点」卡片中过长的节点名把延迟标签挤出卡片
|
||||||
|
- 修复断开链式代理时清空已选节点,导致再次连接需要重新选择
|
||||||
|
- 修复「连接」页表格排序时表头换行、标题位置跳动
|
||||||
|
- 修复「TUN 设置」未手动保存时,界面显示的默认 MTU 1500 未生效
|
||||||
|
|
||||||
**🍎 macOS**
|
**🍎 macOS**
|
||||||
|
|
||||||
- 修复 macOS TUN 模式下原有 DNS 被清除、关闭后 DNS 未恢复及联网后设置未生效
|
- 修复 macOS TUN 模式下原有 DNS 被清除、关闭后 DNS 未恢复及联网后设置未生效
|
||||||
- 修复 macOS 断网时误报代理已回退直连,恢复联网后自动重试系统代理
|
- 修复 macOS 断网时误报代理已回退直连,恢复联网后自动重试系统代理
|
||||||
|
- 修复 macOS 切换主题后标题栏保留原有深浅色
|
||||||
|
|
||||||
|
**🐧 Linux**
|
||||||
|
|
||||||
|
- 修复 Linux OpenRC 环境下服务安装失败
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary><strong> ✨ 新增功能 </strong></summary>
|
<summary><strong> ✨ 新增功能 </strong></summary>
|
||||||
|
|
||||||
|
- 新增连接页面按网络协议(TCP/UDP)筛选连接
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
|
|||||||
@@ -206,10 +206,10 @@ impl Logger {
|
|||||||
.map(|s| (*s).to_string())
|
.map(|s| (*s).to_string())
|
||||||
.or_else(|| info.payload().downcast_ref::<String>().cloned())
|
.or_else(|| info.payload().downcast_ref::<String>().cloned())
|
||||||
.unwrap_or_else(|| "Unknown panic payload".to_string());
|
.unwrap_or_else(|| "Unknown panic payload".to_string());
|
||||||
let location = info
|
let location = info.location().map_or_else(
|
||||||
.location()
|
|| "Unknown location".to_string(),
|
||||||
.map(|loc| format!("{}:{}", loc.file(), loc.line()))
|
|loc| format!("{}:{}", loc.file(), loc.line()),
|
||||||
.unwrap_or_else(|| "Unknown location".to_string());
|
);
|
||||||
logging!(error, Type::System, "Panic occurred at {}: {}", location, payload);
|
logging!(error, Type::System, "Panic occurred at {}: {}", location, payload);
|
||||||
Self::global().flush_logs();
|
Self::global().flush_logs();
|
||||||
std::thread::sleep(Duration::from_millis(100));
|
std::thread::sleep(Duration::from_millis(100));
|
||||||
|
|||||||
@@ -13,14 +13,13 @@ pub(super) async fn check_chatgpt(client: &Client) -> UnlockItem {
|
|||||||
|
|
||||||
let web_status = get_text(client, "https://api.openai.com/compliance/cookie_requirements")
|
let web_status = get_text(client, "https://api.openai.com/compliance/cookie_requirements")
|
||||||
.await
|
.await
|
||||||
.map(|body| {
|
.map_or("Failed", |body| {
|
||||||
if body.to_ascii_lowercase().contains("unsupported_country") {
|
if body.to_ascii_lowercase().contains("unsupported_country") {
|
||||||
"Unsupported Country/Region"
|
"Unsupported Country/Region"
|
||||||
} else {
|
} else {
|
||||||
"Yes"
|
"Yes"
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
.unwrap_or("Failed");
|
|
||||||
|
|
||||||
UnlockItem::checked(CHATGPT_WEB_NAME, web_status, region)
|
UnlockItem::checked(CHATGPT_WEB_NAME, web_status, region)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -157,11 +157,10 @@ async fn is_unavailable(client: &Client) -> bool {
|
|||||||
.get("https://disneyplus.com")
|
.get("https://disneyplus.com")
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.map(|response| {
|
.map_or(true, |response| {
|
||||||
let url = response.url().as_str();
|
let url = response.url().as_str();
|
||||||
url.contains("preview") || url.contains("unavailable")
|
url.contains("preview") || url.contains("unavailable")
|
||||||
})
|
})
|
||||||
.unwrap_or(true)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn fallback_region(client: &Client) -> Option<UnlockItem> {
|
async fn fallback_region(client: &Client) -> Option<UnlockItem> {
|
||||||
|
|||||||
@@ -114,11 +114,10 @@ async fn check_netflix_cdn(client: &Client) -> UnlockItem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
match response.json::<FastResponse>().await {
|
match response.json::<FastResponse>().await {
|
||||||
Ok(data) => data
|
Ok(data) => data.targets.first().map_or_else(
|
||||||
.targets
|
|| item("Unknown"),
|
||||||
.first()
|
|target| UnlockItem::checked_region(NETFLIX_NAME, "Yes", &target.location.country),
|
||||||
.map(|target| UnlockItem::checked_region(NETFLIX_NAME, "Yes", &target.location.country))
|
),
|
||||||
.unwrap_or_else(|| item("Unknown")),
|
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
logging!(error, Type::Network, "解析 Fast.com API 响应失败: {e}");
|
logging!(error, Type::Network, "解析 Fast.com API 响应失败: {e}");
|
||||||
item("Failed (解析错误)")
|
item("Failed (解析错误)")
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ parking_lot = { workspace = true }
|
|||||||
serde = { workspace = true, features = ["derive"] }
|
serde = { workspace = true, features = ["derive"] }
|
||||||
# sysinfo 0.38.2 conflicts with dark-light
|
# sysinfo 0.38.2 conflicts with dark-light
|
||||||
# see https://github.com/GuillaumeGomez/sysinfo/issues/1623
|
# see https://github.com/GuillaumeGomez/sysinfo/issues/1623
|
||||||
sysinfo = { version = "0.40.1", default-features = false, features = ["network", "system"] }
|
sysinfo = { version = "0.40.3", default-features = false, features = ["network", "system"] }
|
||||||
|
|
||||||
[target.'cfg(not(windows))'.dependencies]
|
[target.'cfg(not(windows))'.dependencies]
|
||||||
libc = "0.2.191"
|
libc = "0.2.191"
|
||||||
|
|||||||
@@ -118,8 +118,7 @@ fn is_binary_admin() -> bool {
|
|||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
Token::with_current_process()
|
Token::with_current_process()
|
||||||
.and_then(|token| token.privilege_level())
|
.and_then(|token| token.privilege_level())
|
||||||
.map(|level| level != PrivilegeLevel::NotPrivileged)
|
.is_ok_and(|level| level != PrivilegeLevel::NotPrivileged)
|
||||||
.unwrap_or(false)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
|
|||||||
@@ -14,7 +14,7 @@
|
|||||||
"duplicates",
|
"duplicates",
|
||||||
"cycles"
|
"cycles"
|
||||||
],
|
],
|
||||||
"ignoreBinaries": ["rustc", "cc"],
|
"ignoreBinaries": ["diff", "rustc"],
|
||||||
"ignoreDependencies": ["lint-staged"],
|
"ignoreDependencies": ["lint-staged"],
|
||||||
"ignoreIssues": {
|
"ignoreIssues": {
|
||||||
"src/types/generated/**": ["exports", "types"],
|
"src/types/generated/**": ["exports", "types"],
|
||||||
|
|||||||
+5
-12
@@ -36,11 +36,7 @@
|
|||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"test:watch": "vitest",
|
"test:watch": "vitest",
|
||||||
"knip:check": "knip",
|
"knip:check": "knip",
|
||||||
"knip:report": "knip --no-exit-code",
|
"knip:report": "knip --no-exit-code"
|
||||||
"perf:build": "node scripts/perf/build.mjs",
|
|
||||||
"perf:run": "node scripts/perf/run.mjs",
|
|
||||||
"perf:compare": "node scripts/perf/compare.mjs",
|
|
||||||
"perf:test": "node --test scripts/perf/report.test.mjs"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@dnd-kit/collision": "^0.5.0",
|
"@dnd-kit/collision": "^0.5.0",
|
||||||
@@ -58,8 +54,8 @@
|
|||||||
"@tauri-apps/plugin-clipboard-manager": "2.5.0",
|
"@tauri-apps/plugin-clipboard-manager": "2.5.0",
|
||||||
"@tauri-apps/plugin-dialog": "2.8.4",
|
"@tauri-apps/plugin-dialog": "2.8.4",
|
||||||
"@tauri-apps/plugin-fs": "2.7.1",
|
"@tauri-apps/plugin-fs": "2.7.1",
|
||||||
"@tauri-apps/plugin-http": "2.8.3",
|
"@tauri-apps/plugin-http": "2.9.0",
|
||||||
"@tauri-apps/plugin-opener": "2.7.2",
|
"@tauri-apps/plugin-opener": "2.7.3",
|
||||||
"@tauri-apps/plugin-updater": "2.14.1",
|
"@tauri-apps/plugin-updater": "2.14.1",
|
||||||
"ahooks": "^3.10.0",
|
"ahooks": "^3.10.0",
|
||||||
"cidr-block": "^2.3.0",
|
"cidr-block": "^2.3.0",
|
||||||
@@ -102,7 +98,6 @@
|
|||||||
"@types/validator": "^13.15.10",
|
"@types/validator": "^13.15.10",
|
||||||
"@vitejs/plugin-legacy": "^8.2.3",
|
"@vitejs/plugin-legacy": "^8.2.3",
|
||||||
"@vitejs/plugin-react": "^6.1.1",
|
"@vitejs/plugin-react": "^6.1.1",
|
||||||
"@wdio/tauri-service": "1.5.1",
|
|
||||||
"adm-zip": "^0.6.1",
|
"adm-zip": "^0.6.1",
|
||||||
"axios": "^1.20.0",
|
"axios": "^1.20.0",
|
||||||
"cli-color": "^2.0.4",
|
"cli-color": "^2.0.4",
|
||||||
@@ -121,7 +116,7 @@
|
|||||||
"https-proxy-agent": "^9.1.0",
|
"https-proxy-agent": "^9.1.0",
|
||||||
"husky": "^9.1.7",
|
"husky": "^9.1.7",
|
||||||
"jiti": "^2.7.0",
|
"jiti": "^2.7.0",
|
||||||
"knip": "6.44.2",
|
"knip": "6.45.1",
|
||||||
"lint-staged": "^17.5.1",
|
"lint-staged": "^17.5.1",
|
||||||
"sass": "^1.104.1",
|
"sass": "^1.104.1",
|
||||||
"tar": "^7.5.22",
|
"tar": "^7.5.22",
|
||||||
@@ -131,9 +126,7 @@
|
|||||||
"typescript-eslint": "^8.70.0",
|
"typescript-eslint": "^8.70.0",
|
||||||
"vite": "^8.3.0",
|
"vite": "^8.3.0",
|
||||||
"vite-plugin-svgr": "^5.2.0",
|
"vite-plugin-svgr": "^5.2.0",
|
||||||
"vitest": "^5.0.1",
|
"vitest": "^5.0.1"
|
||||||
"webdriverio": "10.2.0",
|
|
||||||
"ws": "8.22.2"
|
|
||||||
},
|
},
|
||||||
"lint-staged": {
|
"lint-staged": {
|
||||||
"*.{ts,tsx,js,mjs}": [
|
"*.{ts,tsx,js,mjs}": [
|
||||||
|
|||||||
Generated
+28
-1753
File diff suppressed because it is too large
Load Diff
+1
-6
@@ -50,12 +50,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"description": "Update Tauri npm packages and Cargo crates together so frontend and backend stay in sync",
|
"description": "Update Tauri npm packages and Cargo crates together so frontend and backend stay in sync",
|
||||||
"matchPackageNames": [
|
"matchPackageNames": ["@tauri-apps/**", "tauri", "tauri-*"],
|
||||||
"@tauri-apps/**",
|
|
||||||
"@wdio/tauri-service",
|
|
||||||
"tauri",
|
|
||||||
"tauri-*"
|
|
||||||
],
|
|
||||||
"groupName": "tauri",
|
"groupName": "tauri",
|
||||||
"addLabels": ["tauri"]
|
"addLabels": ["tauri"]
|
||||||
},
|
},
|
||||||
|
|||||||
+1
-1
@@ -1,3 +1,3 @@
|
|||||||
[toolchain]
|
[toolchain]
|
||||||
channel = "1.99.1"
|
channel = "1.100.0"
|
||||||
components = ["rustfmt", "clippy"]
|
components = ["rustfmt", "clippy"]
|
||||||
|
|||||||
@@ -46,8 +46,58 @@ function run(command, args, options = {}) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function checkDevelopmentServiceVersion() {
|
||||||
|
const [guiOutput, daemonOutput] = await Promise.all([
|
||||||
|
run(
|
||||||
|
'cargo',
|
||||||
|
[
|
||||||
|
'metadata',
|
||||||
|
'--locked',
|
||||||
|
'--format-version=1',
|
||||||
|
'--manifest-path',
|
||||||
|
join(repositoryRoot, 'Cargo.toml'),
|
||||||
|
],
|
||||||
|
{ stdio: ['inherit', 'pipe', 'inherit'] },
|
||||||
|
),
|
||||||
|
run(
|
||||||
|
'cargo',
|
||||||
|
[
|
||||||
|
'metadata',
|
||||||
|
'--locked',
|
||||||
|
'--no-deps',
|
||||||
|
'--format-version=1',
|
||||||
|
'--manifest-path',
|
||||||
|
serviceManifest,
|
||||||
|
],
|
||||||
|
{ stdio: ['inherit', 'pipe', 'inherit'] },
|
||||||
|
),
|
||||||
|
])
|
||||||
|
const gui = JSON.parse(guiOutput)
|
||||||
|
const daemon = JSON.parse(daemonOutput).packages.find(
|
||||||
|
(pkg) => resolve(pkg.manifest_path) === serviceManifest,
|
||||||
|
)
|
||||||
|
const app = gui.packages.find(
|
||||||
|
(pkg) =>
|
||||||
|
resolve(pkg.manifest_path) ===
|
||||||
|
join(repositoryRoot, 'src-tauri', 'Cargo.toml'),
|
||||||
|
)
|
||||||
|
const dependency = gui.resolve?.nodes
|
||||||
|
.find((node) => node.id === app?.id)
|
||||||
|
?.deps.find((dep) => dep.name === 'clash_verge_service_ipc')
|
||||||
|
const sdk = gui.packages.find((pkg) => pkg.id === dependency?.pkg)
|
||||||
|
if (!daemon || !sdk)
|
||||||
|
throw new Error('Cargo did not resolve the development Service and GUI SDK')
|
||||||
|
if (daemon.version !== sdk.version) {
|
||||||
|
throw new Error(
|
||||||
|
`Development Service ${daemon.version} does not match the resolved GUI SDK ${sdk.version} (${sdk.manifest_path}). ` +
|
||||||
|
'Align the GUI dependency explicitly before starting development. Building the sibling daemon does not update the SDK.',
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function prepareDevelopmentService() {
|
export async function prepareDevelopmentService() {
|
||||||
await access(serviceManifest)
|
await access(serviceManifest)
|
||||||
|
await checkDevelopmentServiceVersion()
|
||||||
const output = await run(
|
const output = await run(
|
||||||
'cargo',
|
'cargo',
|
||||||
[
|
[
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# Product Measurement Adapter Guidelines
|
||||||
|
|
||||||
|
[GUIDE.md](GUIDE.md) defines the product adapter boundary and explicit tool invocation.
|
||||||
|
Keep real component imports, initialization and the isolated native entry here,
|
||||||
|
using product frontend/native build dependencies. Do not copy components into the
|
||||||
|
tool. Preserve perf build gates; ordinary builds must not require the external tool.
|
||||||
|
|
||||||
|
The adapter must not load or modify daily configuration or control the daily app,
|
||||||
|
Core, Service, TUN, DNS or system proxy. Preserve loopback isolation, owned-process
|
||||||
|
PID/start attribution, nonactivation, visibility/occlusion and source continuity.
|
||||||
|
Do not weaken gates or substitute Chrome/Vite for native WebView evidence. Label
|
||||||
|
JavaScript adapters separately from native plugin/IPC paths. Expected startup errors
|
||||||
|
must use the owned app's normal nonzero exit, never panic through Tauri setup.
|
||||||
|
|
||||||
|
Review adapter source changes, including initialization and native/build configuration,
|
||||||
|
for changed measurement meaning. Matching interfaces alone do not prove equivalence;
|
||||||
|
an adapter review cannot waive other acceptance conditions.
|
||||||
|
|
||||||
|
For implementation changes, run scoped ESLint, both perf TypeScript projects
|
||||||
|
(`tsconfig.json` and `tsconfig.node.json`), formatting and relevant production checks,
|
||||||
|
including Rust checks for native changes. Run scoped Rust Clippy before freezing
|
||||||
|
the optimized artifact. Check ordinary-build exclusion and application-entry prerequisites.
|
||||||
|
|
||||||
|
Follow the external AGENTS.md's
|
||||||
|
[measurement-validation requirements](https://github.com/clash-verge-rev/clash-verge-rev-harness/blob/main/AGENTS.md)
|
||||||
|
and README's
|
||||||
|
[validation order](https://github.com/clash-verge-rev/clash-verge-rev-harness/blob/main/README.md#validate-before-freezing-a-build).
|
||||||
|
These govern affected native coverage, comparison, failure cleanup and evidence reuse.
|
||||||
+27
-132
@@ -1,140 +1,35 @@
|
|||||||
# macOS Traffic Performance Harness
|
# Product measurement adapter
|
||||||
|
|
||||||
This guide is the operating and maintenance contract for humans and coding agents.
|
This directory owns the isolated native entry, real Traffic/Logs/Connections
|
||||||
The only scenario is the production home traffic graph in a dedicated, optimized
|
imports, initialization, JavaScript socket adapter, replay receiver and minimal DOM
|
||||||
Tauri WKWebView. It measures foreground updates, native hide, then restoration.
|
layer. These evolve with product APIs and use the product's React/Tauri/Wry
|
||||||
It does not initialize the complete homepage or run Mihomo, Service or networking.
|
versions. Keep the explicit perf build gates; ordinary builds need no external tool.
|
||||||
|
|
||||||
## Build And Run
|
The external [clash-verge-rev-harness operating guide](https://github.com/clash-verge-rev/clash-verge-rev-harness/blob/main/README.md)
|
||||||
|
owns running, sampling, reports, comparison and owned cleanup. Follow its
|
||||||
Use this repository's pnpm, Rust and Xcode Command Line Tools on macOS. No global
|
[first setup and installation instructions](https://github.com/clash-verge-rev/clash-verge-rev-harness/blob/main/README.md#build-and-run),
|
||||||
WebDriver installation is needed. Keep each binary beside its generated manifest.
|
reusing an existing checkout. For subsequent calls, pass both absolute roots:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
pnpm install --frozen-lockfile
|
project=/absolute/path/to/clash-verge-rev
|
||||||
pnpm perf:build target/perf/baseline-build
|
harness=/absolute/path/to/clash-verge-rev-harness
|
||||||
caffeinate -di pnpm perf:run -- --binary target/perf/baseline-build/clash-verge --output target/perf/baseline --repeat 3 --seconds 20 --warmup 10
|
node "$harness/build.mjs" --project "$project" --output target/perf/build
|
||||||
pnpm perf:compare -- target/perf/baseline target/perf/baseline
|
caffeinate -di node "$harness/run.mjs" --project "$project" --binary target/perf/build/clash-verge --output target/perf/smoke --repeat 1 --seconds 5 --warmup 2
|
||||||
pnpm perf:test
|
node "$harness/compare.mjs" "$project/target/perf/smoke" "$project/target/perf/smoke"
|
||||||
```
|
```
|
||||||
|
|
||||||
`perf:build [directory]` uses release optimization, Vite `--mode perf` and the
|
JavaScript socket replacement does not measure native plugin IPC. DOM mutation/text
|
||||||
explicit Cargo `perf-harness` feature. It preserves the binary and records HEAD,
|
hashes show view-input delivery, not painting or cache ownership. Adapter changes
|
||||||
dirty state, compiled source, lockfile, frontend, build-settings and binary hashes.
|
require reviewing measurement meaning under the external validation requirements.
|
||||||
Source changes during compilation reject the manifest. Each run also hashes the
|
|
||||||
external collector and runner. Ordinary builds exclude the driver and measurement
|
|
||||||
entry; debug assertions are not the gate. Do not edit compiled inputs during builds.
|
|
||||||
|
|
||||||
Output directories must be new and Git ignored; use `target/perf/`. JSON/CSV keep
|
For virtual display mode, this adapter places only the hidden measurement window
|
||||||
raw process samples, observations, phase markers, attribution and cleanup evidence.
|
on the exact owned NSScreen, checks complete visibleFrame containment, mode/Space
|
||||||
`summary.json` and `report.md` provide distributions by independent run, phase and
|
flags and nonactivation, and exits on drift. The tool owns helper lifecycle and topology
|
||||||
process role. Failed runs exit nonzero and retain their evidence. The explicit
|
restoration; see its
|
||||||
`traffic-webview-v3` schema rejects older reports instead of silently migrating them.
|
[virtual display guide](https://github.com/clash-verge-rev/clash-verge-rev-harness/blob/main/README.md#optional-virtual-display).
|
||||||
|
|
||||||
## Isolation And Visibility
|
`isolation.json` owns the product configuration and process watch scope; keep it
|
||||||
|
aligned with product data directories and executable names. The tool owns
|
||||||
The dedicated measurement main bypasses normal initialization and shutdown. It
|
[command isolation snapshots](https://github.com/clash-verge-rev/clash-verge-rev-harness/blob/main/README.md#command-isolation-snapshots).
|
||||||
does not read or write daily configuration, subscriptions, proxy, TUN or Service.
|
The adapter must not load daily configuration or control Core, Service, TUN, DNS
|
||||||
It uses a distinct app identity and incognito WebView. Both automatic services
|
or system proxy.
|
||||||
bind loopback and are owned by the current run; never kill processes by name.
|
|
||||||
|
|
||||||
The measurement window stays above ordinary windows and covers part of the screen,
|
|
||||||
without activation or mouse capture: clicks pass through to the application behind it.
|
|
||||||
Native topmost and click-through states are verified, while native focus and application
|
|
||||||
activation must remain false. WebDriver uses the embedded WebView directly; DOM focus
|
|
||||||
is recorded but not required. Daily windows are unchanged; the topmost window exits
|
|
||||||
with its owned measurement instance. You may keep using another application.
|
|
||||||
The console must be unlocked. Lock state is checked before startup and recorded
|
|
||||||
at phase boundaries; unknown state fails and observed drift rejects comparison.
|
|
||||||
Boundary checks do not provide continuous lock monitoring or unlock the computer.
|
|
||||||
|
|
||||||
No focus does not mean no visibility: shown stages require `document.hidden=false`,
|
|
||||||
fresh Worker data, advancing Canvas draw timestamps and changed Canvas pixels.
|
|
||||||
Topmost placement avoids ordinary-window occlusion; system overlays or another Space
|
|
||||||
can still pause WebKit. Such a run fails; do not weaken Canvas assertions to make it
|
|
||||||
pass. `caffeinate -di` lasts only for the command and cannot prevent deliberate lock.
|
|
||||||
Hidden stages still require continuous input and Worker data.
|
|
||||||
|
|
||||||
## Fixed Workload
|
|
||||||
|
|
||||||
The native window is 1000 x 700 logical pixels. Verify driver dimensions against
|
|
||||||
DPR and record the actual CSS viewport; titlebar space is excluded. The graph is
|
|
||||||
920 x 360 with a ten-minute range, default bezier style and real data retention.
|
|
||||||
The measurement preload sets blur pause false without changing production defaults.
|
|
||||||
|
|
||||||
Deterministic loopback WebSocket replay enters the public traffic append boundary,
|
|
||||||
then the production Worker and Canvas. It does not cover Mihomo or network traffic.
|
|
||||||
There is no history prefill. Absolute 200 ms deadlines sustain 5 Hz without cumulative
|
|
||||||
timer drift or catch-up bursts; missing a complete period fails the source.
|
|
||||||
Warmup is at least the requested duration with a five-second readiness allowance.
|
|
||||||
Fixed input anchors reserve two seconds for each native transition; measured stages
|
|
||||||
retain their full duration. Readiness uses observable state and deadlines, not sleep.
|
|
||||||
Before the first show, wait for actual replay input and Worker data so the graph's
|
|
||||||
visibility listeners are installed; then require fresh Canvas output after showing.
|
|
||||||
Total replay, including allowances, must remain below ten minutes for raw history.
|
|
||||||
Two-input endpoint variation is 400 ms; larger differences reject comparison.
|
|
||||||
|
|
||||||
Worker snapshots are asynchronous. Count/latest-value checks verify deterministic
|
|
||||||
upload/download values at the retained point count, with a joint period of 60 and
|
|
||||||
received-minus-retained count below 60. This detects net missing/duplicate points,
|
|
||||||
not every historical element or exactly cancelling losses and duplicates.
|
|
||||||
Source age must be below 2500 ms, Worker age below 3500 ms and visible draw age below
|
|
||||||
2500 ms. Future timestamps, lost sequence, process changes and failed restore fail.
|
|
||||||
|
|
||||||
## Metrics And Comparison
|
|
||||||
|
|
||||||
The native command obtains the actual WKWebView process ID using the private
|
|
||||||
`_webProcessIdentifier` selector, with availability checking. External collection
|
|
||||||
verifies the canonical system WebContent executable and process start identity.
|
|
||||||
It handles PID reuse and exits; unsupported ownership fails closed. Main and WebView
|
|
||||||
remain separate. Mihomo is not started; shared GPU/network attribution is unavailable.
|
|
||||||
|
|
||||||
CPU is cumulative process time converted from Mach ticks; interval percentages use
|
|
||||||
adjacent valid samples, with one occupied core equal to 100%. The first difference
|
|
||||||
is unavailable. Memory is RSS bytes, not physical footprint or exclusive memory.
|
|
||||||
Reports include CPU mean/P50/P95/peak/seconds, RSS median/P95/peak/delta, sample count
|
|
||||||
and time coverage. Memory slope requires at least 60 seconds of continuous samples.
|
|
||||||
RSS growth is not proof of a leak; process statistics are not function profiles.
|
|
||||||
The embedded driver adds a 20 Hz macOS runloop timer and observation overhead.
|
|
||||||
|
|
||||||
For A/B, build the candidate separately and alternate independent instances:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
pnpm perf:build target/perf/candidate-build
|
|
||||||
for i in 1 2 3; do
|
|
||||||
caffeinate -di pnpm perf:run -- --binary target/perf/baseline-build/clash-verge --repeat 1 --output target/perf/ab-baseline/$i
|
|
||||||
caffeinate -di pnpm perf:run -- --binary target/perf/candidate-build/clash-verge --repeat 1 --output target/perf/ab-candidate/$i
|
|
||||||
done
|
|
||||||
pnpm perf:compare -- target/perf/ab-baseline target/perf/ab-candidate
|
|
||||||
pnpm perf:run -- --binary target/perf/candidate-build/clash-verge --repeat 1 --seconds 5 --warmup 2 --fail-phase hidden --output target/perf/failed
|
|
||||||
```
|
|
||||||
|
|
||||||
Comparison accepts summary files, run directories or groups of run directories.
|
|
||||||
Build mode, toolchain, platform, host, power, WebKit, viewport and workload must match.
|
|
||||||
Invalid and incomparable reports exit 2. A/A remains inconclusive. A/B compares
|
|
||||||
independent-run summaries, not adjacent time samples. An optional third numeric
|
|
||||||
argument is a percentage floor justified by baseline noise; there is no universal
|
|
||||||
pass threshold. Fewer than three runs per group, overlapping ranges or differences
|
|
||||||
within either group's range remain inconclusive. Background load limits inference.
|
|
||||||
|
|
||||||
## Automation Delivery Boundary
|
|
||||||
|
|
||||||
When the operator is a coding agent, the final change keeps only the
|
|
||||||
performance-optimization code. Harness additions introduced during the
|
|
||||||
work — measurement entries, configs, scripts, reports, manifests — must
|
|
||||||
stay untracked by Git and out of every commit; keep them on ignored
|
|
||||||
paths or remove them before delivery. Commits remain minimal and
|
|
||||||
necessary for the optimization itself. Track or commit harness files
|
|
||||||
only when a human explicitly requests it at the end.
|
|
||||||
|
|
||||||
## Maintenance And Acceptance
|
|
||||||
|
|
||||||
Keep measurement code behind the explicit build gates. Reuse the existing driver,
|
|
||||||
Worker, graph, attribution and cleanup; do not add mock IPC or replace real WebView
|
|
||||||
acceptance with Chrome/Vite. Preserve source/binary/report hashes and every failed run.
|
|
||||||
After changes, run scoped ESLint, both perf TypeScript projects, `pnpm perf:test`,
|
|
||||||
format checks and relevant production checks. Verify a real three-phase smoke,
|
|
||||||
three independent runs, A/A, invalid/incomparable reports and injected-failure cleanup.
|
|
||||||
Verify ordinary builds exclude measurement code and daily instance state is intact.
|
|
||||||
Changes to contracts require a schema bump and new reports. Use bounded WebKit CPU
|
|
||||||
or Allocation/Heap captures for deeper diagnosis; do not infer hotspots from counters.
|
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { MihomoWebSocket } from 'tauri-plugin-mihomo-api'
|
||||||
|
|
||||||
|
import { subscribe, scenario } from './replay'
|
||||||
|
|
||||||
|
// Only this perf entry replaces socket transport; the normal application never imports it.
|
||||||
|
export function installAdapter() {
|
||||||
|
const connect = async (kind: string) => {
|
||||||
|
const data = document.documentElement.dataset
|
||||||
|
data.perfSubscriptions = String(Number(data.perfSubscriptions || 0) + 1)
|
||||||
|
const callbacks = new Set<
|
||||||
|
(message: { type: 'Text'; data: string }) => void
|
||||||
|
>()
|
||||||
|
const unsubscribe = subscribe((frame) => {
|
||||||
|
const messages =
|
||||||
|
kind === 'logs'
|
||||||
|
? (frame.payload as ILogItem[])
|
||||||
|
: [
|
||||||
|
kind === 'traffic'
|
||||||
|
? { up: frame.sequence * 1000, down: frame.sequence * 5000 }
|
||||||
|
: frame.payload,
|
||||||
|
]
|
||||||
|
for (const payload of messages) {
|
||||||
|
const message = { type: 'Text' as const, data: JSON.stringify(payload) }
|
||||||
|
callbacks.forEach((callback) => {
|
||||||
|
callback(message)
|
||||||
|
data.perfDelivered = String(Number(data.perfDelivered || 0) + 1)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
addListener: (
|
||||||
|
callback: (message: { type: 'Text'; data: string }) => void,
|
||||||
|
) => {
|
||||||
|
callbacks.add(callback)
|
||||||
|
return () => callbacks.delete(callback)
|
||||||
|
},
|
||||||
|
close: async () => {
|
||||||
|
unsubscribe()
|
||||||
|
callbacks.clear()
|
||||||
|
data.perfSubscriptions = String(Number(data.perfSubscriptions) - 1)
|
||||||
|
},
|
||||||
|
} as unknown as MihomoWebSocket
|
||||||
|
}
|
||||||
|
MihomoWebSocket.connect_logs = async () => connect('logs')
|
||||||
|
MihomoWebSocket.connect_connections = async () => connect('connections')
|
||||||
|
MihomoWebSocket.connect_traffic = async () => connect('traffic')
|
||||||
|
if (scenario === 'logs')
|
||||||
|
localStorage.setItem(
|
||||||
|
'clash-log',
|
||||||
|
JSON.stringify({
|
||||||
|
enable: true,
|
||||||
|
logLevel: 'INFO',
|
||||||
|
logFilter: 'all',
|
||||||
|
logOrder: 'desc',
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
+227
-21
@@ -1,5 +1,136 @@
|
|||||||
use objc2::{class, msg_send, runtime::AnyObject, sel};
|
use objc2::{class, msg_send, runtime::AnyObject, sel};
|
||||||
use tauri::WebviewWindow;
|
use objc2_foundation::{NSPoint, NSRect, ns_string};
|
||||||
|
use tauri::{Manager as _, WebviewWindow};
|
||||||
|
|
||||||
|
#[link(name = "CoreGraphics", kind = "framework")]
|
||||||
|
unsafe extern "C" {
|
||||||
|
fn CGDisplayCopyDisplayMode(display: u32) -> *mut std::ffi::c_void;
|
||||||
|
fn CGDisplayModeGetRefreshRate(mode: *mut std::ffi::c_void) -> f64;
|
||||||
|
fn CGDisplayModeRelease(mode: *mut std::ffi::c_void);
|
||||||
|
fn CGMainDisplayID() -> u32;
|
||||||
|
fn CGDisplayIsInMirrorSet(display: u32) -> u32;
|
||||||
|
fn CGDisplayModeGetWidth(mode: *mut std::ffi::c_void) -> usize;
|
||||||
|
fn CGDisplayModeGetHeight(mode: *mut std::ffi::c_void) -> usize;
|
||||||
|
fn CGDisplayModeGetPixelWidth(mode: *mut std::ffi::c_void) -> usize;
|
||||||
|
fn CGDisplayModeGetPixelHeight(mode: *mut std::ffi::c_void) -> usize;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn expected_display() -> Result<Option<u32>, String> {
|
||||||
|
match std::env::var("PERF_DISPLAY_MODE").as_deref() {
|
||||||
|
Ok("physical") | Err(std::env::VarError::NotPresent) => Ok(None),
|
||||||
|
Ok("virtual") => {
|
||||||
|
let id = std::env::var("PERF_DISPLAY_ID")
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.parse::<u32>()
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
if id == 0 {
|
||||||
|
return Err("invalid owned display ID".into());
|
||||||
|
}
|
||||||
|
Ok(Some(id))
|
||||||
|
}
|
||||||
|
_ => Err("unknown measurement display mode".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const fn bounds(rect: NSRect) -> [f64; 4] {
|
||||||
|
[rect.origin.x, rect.origin.y, rect.size.width, rect.size.height]
|
||||||
|
}
|
||||||
|
fn contained(frame: NSRect, screen: NSRect) -> bool {
|
||||||
|
frame.origin.x >= screen.origin.x
|
||||||
|
&& frame.origin.y >= screen.origin.y
|
||||||
|
&& frame.origin.x + frame.size.width <= screen.origin.x + screen.size.width
|
||||||
|
&& frame.origin.y + frame.size.height <= screen.origin.y + screen.size.height
|
||||||
|
}
|
||||||
|
unsafe fn screen_id(screen: *mut AnyObject) -> u32 {
|
||||||
|
unsafe {
|
||||||
|
if screen.is_null() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
let dictionary: *mut AnyObject = msg_send![screen, deviceDescription];
|
||||||
|
let value: *mut AnyObject = msg_send![dictionary, objectForKey: ns_string!("NSScreenNumber")];
|
||||||
|
msg_send![value, unsignedIntValue]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unsafe fn display_state(native: &AnyObject) -> Result<Option<serde_json::Value>, String> {
|
||||||
|
let Some(wanted) = expected_display()? else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
unsafe {
|
||||||
|
let screen: *mut AnyObject = msg_send![native, screen];
|
||||||
|
let id = screen_id(screen);
|
||||||
|
if id == 0 || id != wanted || id == CGMainDisplayID() || CGDisplayIsInMirrorSet(id) != 0 {
|
||||||
|
return Err("owned virtual screen unavailable".into());
|
||||||
|
}
|
||||||
|
let frame: NSRect = msg_send![screen, frame];
|
||||||
|
let visible: NSRect = msg_send![screen, visibleFrame];
|
||||||
|
let window_frame: NSRect = msg_send![native, frame];
|
||||||
|
let scale: f64 = msg_send![screen, backingScaleFactor];
|
||||||
|
let behavior: usize = msg_send![native, collectionBehavior];
|
||||||
|
let mode = CGDisplayCopyDisplayMode(id);
|
||||||
|
if mode.is_null() {
|
||||||
|
return Err("owned display mode unavailable".into());
|
||||||
|
}
|
||||||
|
let rate = CGDisplayModeGetRefreshRate(mode);
|
||||||
|
let logical = [CGDisplayModeGetWidth(mode), CGDisplayModeGetHeight(mode)];
|
||||||
|
let pixels = [CGDisplayModeGetPixelWidth(mode), CGDisplayModeGetPixelHeight(mode)];
|
||||||
|
CGDisplayModeRelease(mode);
|
||||||
|
if logical != [1280, 900]
|
||||||
|
|| pixels != [2560, 1800]
|
||||||
|
|| scale != 2.0
|
||||||
|
|| (rate - 60.0).abs() > 0.01
|
||||||
|
|| frame.size.width != 1280.0
|
||||||
|
|| frame.size.height != 900.0
|
||||||
|
|| !contained(window_frame, visible)
|
||||||
|
|| behavior & 1 == 0
|
||||||
|
|| behavior & 2 != 0
|
||||||
|
{
|
||||||
|
return Err("owned virtual screen geometry/mode changed".into());
|
||||||
|
}
|
||||||
|
Ok(Some(
|
||||||
|
serde_json::json!({"id": id, "frame": bounds(frame), "visibleFrame": bounds(visible), "windowFrame": bounds(window_frame), "scale": scale, "refreshHz": rate, "collectionBehavior": behavior, "contained": true, "main": false, "mirrored": false, "logical": logical, "pixels": pixels}),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unsafe fn target_screen(wanted: u32) -> Result<*mut AnyObject, String> {
|
||||||
|
unsafe {
|
||||||
|
let screens: *mut AnyObject = msg_send![class!(NSScreen), screens];
|
||||||
|
let count: usize = msg_send![screens, count];
|
||||||
|
let mut target = std::ptr::null_mut::<AnyObject>();
|
||||||
|
for index in 0..count {
|
||||||
|
let screen: *mut AnyObject = msg_send![screens, objectAtIndex: index];
|
||||||
|
if screen_id(screen) == wanted {
|
||||||
|
target = screen;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if target.is_null() || wanted == CGMainDisplayID() {
|
||||||
|
return Err("exact owned virtual display missing".into());
|
||||||
|
}
|
||||||
|
Ok(target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unsafe fn place_virtual(window: &WebviewWindow) -> Result<(), String> {
|
||||||
|
unsafe {
|
||||||
|
let Some(wanted) = expected_display()? else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
let target = target_screen(wanted)?;
|
||||||
|
let native = &*(window.ns_window().map_err(|e| e.to_string())? as *const AnyObject);
|
||||||
|
let visible: NSRect = msg_send![target, visibleFrame];
|
||||||
|
let frame: NSRect = msg_send![native, frame];
|
||||||
|
if frame.size.width > visible.size.width || frame.size.height > visible.size.height {
|
||||||
|
return Err("owned window does not fit virtual visibleFrame".into());
|
||||||
|
}
|
||||||
|
let behavior: usize = msg_send![native, collectionBehavior];
|
||||||
|
let _: () = msg_send![native, setCollectionBehavior: (behavior & !2usize) | 1usize];
|
||||||
|
let origin = NSPoint::new(
|
||||||
|
visible.origin.x + (visible.size.width - frame.size.width) / 2.0,
|
||||||
|
visible.origin.y + (visible.size.height - frame.size.height) / 2.0,
|
||||||
|
);
|
||||||
|
let _: () = msg_send![native, setFrameOrigin: origin];
|
||||||
|
display_state(native)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
async fn perf_state(window: WebviewWindow, action: String) -> Result<serde_json::Value, String> {
|
async fn perf_state(window: WebviewWindow, action: String) -> Result<serde_json::Value, String> {
|
||||||
@@ -7,16 +138,28 @@ async fn perf_state(window: WebviewWindow, action: String) -> Result<serde_json:
|
|||||||
return Err("unknown measurement action".into());
|
return Err("unknown measurement action".into());
|
||||||
}
|
}
|
||||||
let (tx, rx) = std::sync::mpsc::channel();
|
let (tx, rx) = std::sync::mpsc::channel();
|
||||||
|
let fail_app = window.app_handle().clone();
|
||||||
window
|
window
|
||||||
.with_webview(move |view| unsafe {
|
.with_webview(move |view| unsafe {
|
||||||
let native = &*(view.ns_window() as *const AnyObject);
|
let native = &*(view.ns_window() as *const AnyObject);
|
||||||
let sender = std::ptr::null::<AnyObject>();
|
let sender = std::ptr::null::<AnyObject>();
|
||||||
|
let display = match display_state(native) {
|
||||||
|
Ok(state) => state,
|
||||||
|
Err(error) => {
|
||||||
|
let _: () = msg_send![native, orderOut: sender];
|
||||||
|
let _ = tx.send(Err(error));
|
||||||
|
fail_app.exit(2);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
if action == "show" {
|
if action == "show" {
|
||||||
let _: () = msg_send![native, orderBack: sender];
|
let _: () = msg_send![native, orderBack: sender];
|
||||||
} else if action == "hide" {
|
} else if action == "hide" {
|
||||||
let _: () = msg_send![native, orderOut: sender];
|
let _: () = msg_send![native, orderOut: sender];
|
||||||
}
|
}
|
||||||
let visible: bool = msg_send![native, isVisible];
|
let visible: bool = msg_send![native, isVisible];
|
||||||
|
let occlusion: usize = msg_send![native, occlusionState];
|
||||||
|
let active_space: bool = msg_send![native, isOnActiveSpace];
|
||||||
let focused: bool = msg_send![native, isKeyWindow];
|
let focused: bool = msg_send![native, isKeyWindow];
|
||||||
let click_through: bool = msg_send![native, ignoresMouseEvents];
|
let click_through: bool = msg_send![native, ignoresMouseEvents];
|
||||||
let app: *const AnyObject = msg_send![class!(NSApplication), sharedApplication];
|
let app: *const AnyObject = msg_send![class!(NSApplication), sharedApplication];
|
||||||
@@ -28,21 +171,41 @@ async fn perf_state(window: WebviewWindow, action: String) -> Result<serde_json:
|
|||||||
} else {
|
} else {
|
||||||
0
|
0
|
||||||
};
|
};
|
||||||
let _ = tx.send((pid, visible, focused, active, click_through));
|
let _ = tx.send(Ok((
|
||||||
|
pid,
|
||||||
|
visible,
|
||||||
|
focused,
|
||||||
|
active,
|
||||||
|
click_through,
|
||||||
|
occlusion & 2 == 0,
|
||||||
|
active_space,
|
||||||
|
display,
|
||||||
|
)));
|
||||||
})
|
})
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
let (pid, visible, focused, active, click_through) = rx
|
let (pid, visible, focused, active, click_through, occluded, active_space, display) = rx
|
||||||
.recv_timeout(std::time::Duration::from_secs(5))
|
.recv_timeout(std::time::Duration::from_secs(5))
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())??;
|
||||||
if pid <= 0 {
|
if pid <= 0 {
|
||||||
return Err("WKWebView process ownership unavailable".into());
|
return Err("WKWebView process ownership unavailable".into());
|
||||||
}
|
}
|
||||||
let top = window.is_always_on_top().map_err(|e| e.to_string())?;
|
let top = window.is_always_on_top().map_err(|e| e.to_string())?;
|
||||||
Ok(serde_json::json!({"main": std::process::id(), "webview": pid,
|
Ok(serde_json::json!({"main": std::process::id(), "webview": pid,
|
||||||
"visible": visible, "nativeFocused": focused, "appActive": active,
|
"visible": visible, "nativeFocused": focused, "appActive": active,
|
||||||
"top": top, "clickThrough": click_through,
|
"virtualScreen": display, "expectedDisplayID": expected_display()?,
|
||||||
|
"top": top, "occluded": occluded, "activeSpace": active_space, "clickThrough": click_through,
|
||||||
"token": std::env::var("PERF_TOKEN").map_err(|e| e.to_string())?}))
|
"token": std::env::var("PERF_TOKEN").map_err(|e| e.to_string())?}))
|
||||||
}
|
}
|
||||||
|
#[tauri::command]
|
||||||
|
const fn get_clash_logs() -> Vec<String> {
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn get_verge_config() -> serde_json::Value {
|
||||||
|
serde_json::json!({"language": "en", "theme_mode": "light"})
|
||||||
|
}
|
||||||
|
|
||||||
pub fn run() -> std::process::ExitCode {
|
pub fn run() -> std::process::ExitCode {
|
||||||
#[cfg(feature = "clippy")]
|
#[cfg(feature = "clippy")]
|
||||||
let context = tauri::test::mock_context(tauri::test::noop_assets());
|
let context = tauri::test::mock_context(tauri::test::noop_assets());
|
||||||
@@ -50,23 +213,66 @@ pub fn run() -> std::process::ExitCode {
|
|||||||
let context = tauri::generate_context!();
|
let context = tauri::generate_context!();
|
||||||
let result = tauri::Builder::default()
|
let result = tauri::Builder::default()
|
||||||
.plugin(tauri_plugin_wdio_webdriver::init())
|
.plugin(tauri_plugin_wdio_webdriver::init())
|
||||||
.invoke_handler(tauri::generate_handler![perf_state])
|
.invoke_handler(tauri::generate_handler![perf_state, get_clash_logs, get_verge_config])
|
||||||
.setup(|app| {
|
.setup(|app| {
|
||||||
app.handle().set_activation_policy(tauri::ActivationPolicy::Accessory)?;
|
let startup = (|| -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let port: u16 = std::env::var("PERF_REPLAY_PORT")?.parse()?;
|
app.handle()
|
||||||
tauri::WebviewWindowBuilder::new(
|
.set_activation_policy(tauri::ActivationPolicy::Prohibited)?;
|
||||||
app,
|
let scenario = std::env::var("PERF_SCENARIO").unwrap_or_else(|_| "traffic".into());
|
||||||
"perf",
|
let layer = std::env::var("PERF_LAYER").unwrap_or_else(|_| "component".into());
|
||||||
tauri::WebviewUrl::App(format!("index.html?port={port}").into()),
|
if !matches!(scenario.as_str(), "traffic" | "logs" | "connections")
|
||||||
)
|
|| !matches!(layer.as_str(), "page" | "component" | "dom")
|
||||||
.title("Clash Verge - performance replay")
|
{
|
||||||
.inner_size(1000., 700.)
|
return Err("invalid perf scene".into());
|
||||||
.visible(false)
|
}
|
||||||
.focused(false)
|
if let Some(wanted) = expected_display().map_err(std::io::Error::other)? {
|
||||||
.always_on_top(true)
|
unsafe {
|
||||||
.incognito(true)
|
target_screen(wanted).map_err(std::io::Error::other)?;
|
||||||
.build()?
|
}
|
||||||
.set_ignore_cursor_events(true)?;
|
}
|
||||||
|
let port: u16 = std::env::var("PERF_REPLAY_PORT")?.parse()?;
|
||||||
|
let window = tauri::WebviewWindowBuilder::new(
|
||||||
|
app,
|
||||||
|
"perf",
|
||||||
|
tauri::WebviewUrl::App(format!("index.html?port={port}&scenario={scenario}&layer={layer}").into()),
|
||||||
|
)
|
||||||
|
.title("Clash Verge - performance replay")
|
||||||
|
.inner_size(1000., 700.)
|
||||||
|
.visible(false)
|
||||||
|
.focused(false)
|
||||||
|
.focusable(false)
|
||||||
|
.always_on_top(true)
|
||||||
|
.incognito(true)
|
||||||
|
.build()?;
|
||||||
|
window.set_ignore_cursor_events(true)?;
|
||||||
|
unsafe {
|
||||||
|
place_virtual(&window).map_err(std::io::Error::other)?;
|
||||||
|
}
|
||||||
|
if expected_display().map_err(std::io::Error::other)?.is_some() {
|
||||||
|
let handle = app.handle().clone();
|
||||||
|
window.on_window_event(move |event| {
|
||||||
|
if matches!(
|
||||||
|
event,
|
||||||
|
tauri::WindowEvent::Moved(_) | tauri::WindowEvent::ScaleFactorChanged { .. }
|
||||||
|
) && let Some(window) = handle.get_webview_window("perf")
|
||||||
|
{
|
||||||
|
let valid = window
|
||||||
|
.ns_window()
|
||||||
|
.ok()
|
||||||
|
.is_some_and(|native| unsafe { display_state(&*(native as *const AnyObject)).is_ok() });
|
||||||
|
if !valid {
|
||||||
|
let _ = window.hide();
|
||||||
|
handle.exit(2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})();
|
||||||
|
if let Err(error) = startup {
|
||||||
|
eprintln!("Measurement startup failed: {error}");
|
||||||
|
app.handle().exit(1);
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
.build(context);
|
.build(context);
|
||||||
|
|||||||
@@ -1,107 +0,0 @@
|
|||||||
import { execFileSync } from 'node:child_process'
|
|
||||||
import { createHash } from 'node:crypto'
|
|
||||||
import {
|
|
||||||
copyFileSync,
|
|
||||||
existsSync,
|
|
||||||
mkdirSync,
|
|
||||||
readFileSync,
|
|
||||||
writeFileSync,
|
|
||||||
} from 'node:fs'
|
|
||||||
import { resolve } from 'node:path'
|
|
||||||
const output = resolve(process.argv[2] ?? 'target/perf/build')
|
|
||||||
const hash = (bytes) => createHash('sha256').update(bytes).digest('hex')
|
|
||||||
const command = (cmd, args) =>
|
|
||||||
execFileSync(cmd, args, { encoding: 'utf8' }).trim()
|
|
||||||
const source = () =>
|
|
||||||
command('git', ['ls-files', '-co', '--exclude-standard'])
|
|
||||||
.split('\n')
|
|
||||||
.filter(existsSync)
|
|
||||||
.filter(
|
|
||||||
(path) =>
|
|
||||||
!path.startsWith('scripts/perf/') ||
|
|
||||||
/\.(rs|tsx|html|mts|json)$/.test(path),
|
|
||||||
)
|
|
||||||
.sort()
|
|
||||||
.map((path) => `${path}\0${hash(readFileSync(path))}`)
|
|
||||||
.join('\n')
|
|
||||||
mkdirSync(output, { recursive: true })
|
|
||||||
const before = hash(source())
|
|
||||||
const buildSettingsSha256 = hash(
|
|
||||||
['Cargo.toml', '.cargo/config.toml']
|
|
||||||
.filter(existsSync)
|
|
||||||
.map((path) => `${path}\0${hash(readFileSync(path))}`)
|
|
||||||
.join('\n'),
|
|
||||||
)
|
|
||||||
execFileSync(
|
|
||||||
'pnpm',
|
|
||||||
[
|
|
||||||
'exec',
|
|
||||||
'vite',
|
|
||||||
'build',
|
|
||||||
'--mode',
|
|
||||||
'perf',
|
|
||||||
'--config',
|
|
||||||
'scripts/perf/vite.mts',
|
|
||||||
],
|
|
||||||
{ stdio: 'inherit' },
|
|
||||||
)
|
|
||||||
const mode = 'release + perf-harness (build settings hash recorded)'
|
|
||||||
const buildCommand =
|
|
||||||
'TAURI_CONFIG=<scripts/perf/tauri.json> cargo build -p clash-verge --release --features perf-harness --locked --target-dir target/perf/cargo'
|
|
||||||
execFileSync(
|
|
||||||
'cargo',
|
|
||||||
[
|
|
||||||
'build',
|
|
||||||
'-p',
|
|
||||||
'clash-verge',
|
|
||||||
'--release',
|
|
||||||
'--features',
|
|
||||||
'perf-harness',
|
|
||||||
'--locked',
|
|
||||||
'--target-dir',
|
|
||||||
'target/perf/cargo',
|
|
||||||
],
|
|
||||||
{
|
|
||||||
stdio: 'inherit',
|
|
||||||
env: {
|
|
||||||
...process.env,
|
|
||||||
TAURI_CONFIG: readFileSync('scripts/perf/tauri.json', 'utf8'),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
)
|
|
||||||
if (before !== hash(source()))
|
|
||||||
throw new Error('Source changed during build; refuse manifest')
|
|
||||||
const binary = `${output}/clash-verge`
|
|
||||||
copyFileSync('target/perf/cargo/release/clash-verge', binary)
|
|
||||||
const files = command('find', ['target/perf/dist', '-type', 'f'])
|
|
||||||
.split('\n')
|
|
||||||
.sort()
|
|
||||||
writeFileSync(
|
|
||||||
`${binary}.json`,
|
|
||||||
JSON.stringify(
|
|
||||||
{
|
|
||||||
head: command('git', ['rev-parse', 'HEAD']),
|
|
||||||
dirty: command('git', ['status', '--porcelain']),
|
|
||||||
sourceSha256: before,
|
|
||||||
binarySha256: hash(readFileSync(binary)),
|
|
||||||
frontendSha256: hash(
|
|
||||||
files.map((path) => `${path}\0${hash(readFileSync(path))}`).join('\n'),
|
|
||||||
),
|
|
||||||
mode,
|
|
||||||
buildSettingsSha256,
|
|
||||||
buildEnvironment: Object.fromEntries(
|
|
||||||
Object.entries(process.env).filter(([key]) =>
|
|
||||||
/^(RUSTFLAGS|CARGO_ENCODED_RUSTFLAGS|CARGO_PROFILE_|RUSTC_WRAPPER)/.test(
|
|
||||||
key,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
buildCommand,
|
|
||||||
binary,
|
|
||||||
toolchain: `${command('rustc', ['--version'])}; node ${process.version}; pnpm ${command('pnpm', ['--version'])}`,
|
|
||||||
},
|
|
||||||
null,
|
|
||||||
2,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
console.log(`Measurement binary and manifest: ${binary}`)
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
|
|
||||||
import { join } from 'node:path'
|
|
||||||
|
|
||||||
import { compare } from './report.mjs'
|
|
||||||
const args = process.argv.slice(2).filter((v) => v !== '--')
|
|
||||||
if (args.length < 2)
|
|
||||||
throw new Error(
|
|
||||||
'Usage: pnpm perf:compare -- baseline/summary.json candidate/summary.json [noise-threshold-percent]',
|
|
||||||
)
|
|
||||||
const threshold = args[2] === undefined ? null : Number(args[2])
|
|
||||||
if (threshold !== null && (!Number.isFinite(threshold) || threshold < 0))
|
|
||||||
throw new Error(
|
|
||||||
'threshold must be a nonnegative percentage justified by baseline noise',
|
|
||||||
)
|
|
||||||
function load(path) {
|
|
||||||
if (statSync(path).isFile()) return JSON.parse(readFileSync(path))
|
|
||||||
if (existsSync(join(path, 'summary.json')))
|
|
||||||
return load(join(path, 'summary.json'))
|
|
||||||
const reports = readdirSync(path)
|
|
||||||
.sort()
|
|
||||||
.map((name) => load(join(path, name)))
|
|
||||||
const first = reports[0]
|
|
||||||
if (
|
|
||||||
!first ||
|
|
||||||
reports.some(
|
|
||||||
(r) =>
|
|
||||||
r.build?.binarySha256 !== first.build?.binarySha256 ||
|
|
||||||
['invalid', 'incomparable'].includes(compare(first, r).verdict),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
throw new Error('group contains mixed builds, contracts, or invalid runs')
|
|
||||||
return { ...first, runs: reports.flatMap((r) => r.runs) }
|
|
||||||
}
|
|
||||||
let result
|
|
||||||
try {
|
|
||||||
result = compare(...args.slice(0, 2).map(load), threshold)
|
|
||||||
} catch (error) {
|
|
||||||
result = { verdict: 'invalid', reason: String(error) }
|
|
||||||
}
|
|
||||||
console.log(JSON.stringify(result, null, 2))
|
|
||||||
if (['invalid', 'incomparable'].includes(result.verdict)) process.exitCode = 2
|
|
||||||
+26
-49
@@ -1,52 +1,29 @@
|
|||||||
import { ThemeProvider, createTheme } from '@mui/material'
|
import { layer, scenario, startReplay } from './replay'
|
||||||
import { useEffect } from 'react'
|
|
||||||
import { createRoot } from 'react-dom/client'
|
|
||||||
import { SWRConfig } from 'swr'
|
|
||||||
|
|
||||||
import { EnhancedCanvasTrafficGraph } from '../../src/components/home/enhanced-canvas-traffic-graph'
|
if (scenario === 'traffic') {
|
||||||
import { useTrafficMonitorEnhanced } from '../../src/hooks/use-traffic-monitor'
|
await import('./traffic')
|
||||||
import { initializeLanguage } from '../../src/services/i18n'
|
} else {
|
||||||
import { setPreloadConfig } from '../../src/services/preload'
|
const root = document.getElementById('root')!
|
||||||
|
document.body.style.cssText = 'margin:0;font:14px -apple-system,sans-serif'
|
||||||
setPreloadConfig({
|
root.style.cssText = 'width:1000px;height:700px;overflow:hidden'
|
||||||
pause_render_traffic_stats_on_blur: false,
|
new MutationObserver(() => {
|
||||||
} as IVergeConfig)
|
document.documentElement.dataset.perfDraw = String(Date.now())
|
||||||
await initializeLanguage('en')
|
}).observe(root, { childList: true, characterData: true, subtree: true })
|
||||||
export function Replay() {
|
window.addEventListener('error', (event) => {
|
||||||
const {
|
document.documentElement.dataset.perfError = event.message
|
||||||
graphData: { appendData },
|
})
|
||||||
} = useTrafficMonitorEnhanced({ subscribe: false })
|
window.addEventListener('unhandledrejection', (event) => {
|
||||||
useEffect(() => {
|
document.documentElement.dataset.perfError = String(event.reason)
|
||||||
let received = 0,
|
})
|
||||||
previous = 0,
|
if (layer === 'dom') {
|
||||||
gaps = 0
|
const { mount } = await import('./minimal')
|
||||||
const socket = new WebSocket(
|
mount(root)
|
||||||
`ws://127.0.0.1:${new URLSearchParams(location.search).get('port')}`,
|
} else {
|
||||||
)
|
if (layer === 'page') {
|
||||||
socket.onmessage = ({ data }) => {
|
const { installAdapter } = await import('./adapter')
|
||||||
const point = JSON.parse(data)
|
installAdapter()
|
||||||
appendData(point)
|
|
||||||
if (previous && point.sequence !== previous + 1) gaps++
|
|
||||||
previous = point.sequence
|
|
||||||
document.documentElement.dataset.perfReceived = String(++received)
|
|
||||||
document.documentElement.dataset.perfGaps = String(gaps)
|
|
||||||
document.documentElement.dataset.perfSourceTime = String(point.timestamp)
|
|
||||||
}
|
}
|
||||||
return () => socket.close()
|
await import('./scenes')
|
||||||
}, [appendData])
|
}
|
||||||
return (
|
startReplay()
|
||||||
<main
|
|
||||||
aria-label="Home traffic graph replay"
|
|
||||||
style={{ width: 920, height: 360, margin: 32 }}
|
|
||||||
>
|
|
||||||
<EnhancedCanvasTrafficGraph />
|
|
||||||
</main>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
createRoot(document.getElementById('root')!).render(
|
|
||||||
<SWRConfig value={{ revalidateOnFocus: false, revalidateOnReconnect: false }}>
|
|
||||||
<ThemeProvider theme={createTheme()}>
|
|
||||||
<Replay />
|
|
||||||
</ThemeProvider>
|
|
||||||
</SWRConfig>,
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"configRoots": [
|
||||||
|
"Library/Application Support/io.github.clash-verge-rev.clash-verge-rev",
|
||||||
|
"Library/Application Support/io.github.clash-verge-rev.clash-verge-rev.dev"
|
||||||
|
],
|
||||||
|
"configDirectories": ["profiles"],
|
||||||
|
"configExtensions": [".yaml", ".yml", ".json", ".js"],
|
||||||
|
"processNames": {
|
||||||
|
"app": "clash-verge",
|
||||||
|
"core": "verge-mihomo",
|
||||||
|
"service": "clash-verge-service"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { scenario, subscribe } from './replay'
|
||||||
|
|
||||||
|
export function mount(root: HTMLElement) {
|
||||||
|
const rows = Array.from({ length: 20 }, () => {
|
||||||
|
const row = document.createElement('div')
|
||||||
|
row.style.cssText = 'height:32px;white-space:nowrap;overflow:hidden'
|
||||||
|
root.appendChild(row)
|
||||||
|
return row
|
||||||
|
})
|
||||||
|
subscribe(({ payload }) => {
|
||||||
|
const texts =
|
||||||
|
scenario === 'logs'
|
||||||
|
? (payload as ILogItem[]).map((log) => log.payload)
|
||||||
|
: (payload as IConnections).connections.map(
|
||||||
|
(connection) => connection.metadata.host,
|
||||||
|
)
|
||||||
|
rows.forEach((row, index) => {
|
||||||
|
row.textContent = texts[index % texts.length] ?? ''
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
export interface Frame {
|
||||||
|
sequence: number
|
||||||
|
timestamp: number
|
||||||
|
payload: ILogItem[] | IConnections
|
||||||
|
}
|
||||||
|
export const params = new URLSearchParams(location.search)
|
||||||
|
export const scenario = params.get('scenario') ?? 'traffic'
|
||||||
|
export const layer = params.get('layer') ?? 'component'
|
||||||
|
const listeners = new Set<(frame: Frame) => void>()
|
||||||
|
export const subscribe = (listener: (frame: Frame) => void) => {
|
||||||
|
listeners.add(listener)
|
||||||
|
return () => {
|
||||||
|
listeners.delete(listener)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export function startReplay() {
|
||||||
|
const data = document.documentElement.dataset
|
||||||
|
let previous = 0
|
||||||
|
data.perfReceived = '0'
|
||||||
|
data.perfGaps = '0'
|
||||||
|
const socket = new WebSocket(`ws://127.0.0.1:${params.get('port')}`)
|
||||||
|
socket.onmessage = ({ data: raw }) => {
|
||||||
|
const frame = JSON.parse(raw) as Frame
|
||||||
|
if (frame.sequence !== previous + 1)
|
||||||
|
data.perfGaps = String(Number(data.perfGaps) + 1)
|
||||||
|
previous = frame.sequence
|
||||||
|
data.perfReceived = String(previous)
|
||||||
|
data.perfSourceTime = String(frame.timestamp)
|
||||||
|
for (const listener of listeners) listener(frame)
|
||||||
|
}
|
||||||
|
socket.onerror = () => {
|
||||||
|
data.perfError = 'replay socket failed'
|
||||||
|
}
|
||||||
|
socket.onclose = () => {
|
||||||
|
data.perfError = 'replay socket closed'
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,443 +0,0 @@
|
|||||||
import { isDeepStrictEqual } from 'node:util'
|
|
||||||
|
|
||||||
export const SCHEMA = 'traffic-webview-v3'
|
|
||||||
export const phases = ['foreground', 'hidden', 'restored']
|
|
||||||
export const roles = ['webview', 'main']
|
|
||||||
export const quantile = (values, p) => {
|
|
||||||
const v = values.filter(Number.isFinite).sort((a, b) => a - b)
|
|
||||||
if (!v.length) return null
|
|
||||||
const index = (v.length - 1) * p
|
|
||||||
return (
|
|
||||||
v[Math.floor(index)] +
|
|
||||||
(v[Math.ceil(index)] - v[Math.floor(index)]) * (index % 1)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
export function delta(previous, next) {
|
|
||||||
if (
|
|
||||||
!previous ||
|
|
||||||
previous.pid !== next.pid ||
|
|
||||||
previous.start !== next.start ||
|
|
||||||
![previous.time, next.time, previous.cpu, next.cpu].every(
|
|
||||||
Number.isFinite,
|
|
||||||
) ||
|
|
||||||
next.time <= previous.time ||
|
|
||||||
next.cpu < previous.cpu
|
|
||||||
)
|
|
||||||
return null
|
|
||||||
return ((next.cpu - previous.cpu) / (next.time - previous.time)) * 100000
|
|
||||||
}
|
|
||||||
export function summarize(rows, seconds) {
|
|
||||||
const output = {}
|
|
||||||
for (const phase of phases)
|
|
||||||
for (const role of roles) {
|
|
||||||
const selected = rows.filter((r) => r.phase === phase && r.role === role)
|
|
||||||
const samples = selected.map((r, i) => ({
|
|
||||||
...r,
|
|
||||||
percent: delta(selected[i - 1], r),
|
|
||||||
cpuDelta: i ? r.cpu - selected[i - 1].cpu : null,
|
|
||||||
}))
|
|
||||||
const valid = samples.filter((r) => Number.isFinite(r.percent))
|
|
||||||
const memory = samples.map((r) => r.rss)
|
|
||||||
const span =
|
|
||||||
samples.length > 1 ? samples.at(-1).time - samples[0].time : 0
|
|
||||||
const continuous =
|
|
||||||
samples.length > 1 &&
|
|
||||||
samples.every(
|
|
||||||
(r) =>
|
|
||||||
[r.time, r.cpu, r.rss].every(Number.isFinite) &&
|
|
||||||
Number.isInteger(r.pid) &&
|
|
||||||
r.pid > 0 &&
|
|
||||||
/^\d+$/.test(r.start) &&
|
|
||||||
r.time >= 0 &&
|
|
||||||
r.cpu >= 0 &&
|
|
||||||
r.rss > 0,
|
|
||||||
) &&
|
|
||||||
samples.every(
|
|
||||||
(r, i) =>
|
|
||||||
!i ||
|
|
||||||
(r.time > samples[i - 1].time &&
|
|
||||||
r.time - samples[i - 1].time < 2500 &&
|
|
||||||
r.cpu >= samples[i - 1].cpu &&
|
|
||||||
r.pid === samples[i - 1].pid &&
|
|
||||||
r.start === samples[i - 1].start),
|
|
||||||
)
|
|
||||||
output[`${phase}/${role}`] = {
|
|
||||||
count: samples.length,
|
|
||||||
cpuCount: valid.length,
|
|
||||||
missing: Math.max(0, Math.floor(seconds) - samples.length),
|
|
||||||
coverage: Math.min(1, samples.length / seconds),
|
|
||||||
continuous,
|
|
||||||
observedSeconds: span / 1000,
|
|
||||||
intervalCoverage: Math.min(1, span / ((seconds - 1) * 1000)),
|
|
||||||
cpuMean: null,
|
|
||||||
cpuP50: quantile(
|
|
||||||
valid.map((r) => r.percent),
|
|
||||||
0.5,
|
|
||||||
),
|
|
||||||
cpuP95: quantile(
|
|
||||||
valid.map((r) => r.percent),
|
|
||||||
0.95,
|
|
||||||
),
|
|
||||||
cpuPeak: quantile(
|
|
||||||
valid.map((r) => r.percent),
|
|
||||||
1,
|
|
||||||
),
|
|
||||||
cpuSeconds: valid.length
|
|
||||||
? valid.reduce((sum, r) => sum + r.cpuDelta, 0)
|
|
||||||
: null,
|
|
||||||
rssP50: quantile(memory, 0.5),
|
|
||||||
rssP95: quantile(memory, 0.95),
|
|
||||||
rssPeak: quantile(memory, 1),
|
|
||||||
rssDelta: continuous ? samples.at(-1).rss - samples[0].rss : null,
|
|
||||||
rssSlopeBytesPerSecond:
|
|
||||||
span >= 60000 && continuous
|
|
||||||
? (samples.at(-1).rss - samples[0].rss) / (span / 1000)
|
|
||||||
: null,
|
|
||||||
}
|
|
||||||
output[`${phase}/${role}`].cpuMean =
|
|
||||||
valid.length && span > 0
|
|
||||||
? (output[`${phase}/${role}`].cpuSeconds / span) * 100000
|
|
||||||
: null
|
|
||||||
}
|
|
||||||
return output
|
|
||||||
}
|
|
||||||
export function replayValues(sequence) {
|
|
||||||
return {
|
|
||||||
up: 100000 + (sequence % 20) * 10000,
|
|
||||||
down: 500000 + (sequence % 30) * 20000,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
export const validVisibility = (s) =>
|
|
||||||
typeof s.hidden === 'boolean' &&
|
|
||||||
(s.phase === 'hidden'
|
|
||||||
? s.visible === false && s.hidden
|
|
||||||
: phases.includes(s.phase) && s.visible === true && !s.hidden)
|
|
||||||
export const validObservation = (s) =>
|
|
||||||
validWorkload(s) &&
|
|
||||||
validVisibility(s) &&
|
|
||||||
s.nativeFocused === false &&
|
|
||||||
s.appActive === false &&
|
|
||||||
s.top === true &&
|
|
||||||
s.clickThrough === true &&
|
|
||||||
[s.now, s.source, s.worker, s.draw].every(
|
|
||||||
(v) => Number.isFinite(v) && v > 0,
|
|
||||||
) &&
|
|
||||||
s.now >= s.source &&
|
|
||||||
s.now - s.source < 2500 &&
|
|
||||||
s.now >= s.worker &&
|
|
||||||
s.now - s.worker < 3500 &&
|
|
||||||
s.now >= s.draw &&
|
|
||||||
(s.phase === 'hidden' || s.now - s.draw < 2500)
|
|
||||||
export function validWorkload(s) {
|
|
||||||
if (!s) return false
|
|
||||||
const expected = replayValues(s.points)
|
|
||||||
return (
|
|
||||||
Number.isInteger(s.received) &&
|
|
||||||
Number.isInteger(s.points) &&
|
|
||||||
s.points > 0 &&
|
|
||||||
s.received >= s.points &&
|
|
||||||
s.received - s.points < 60 &&
|
|
||||||
s.lastUp === expected.up &&
|
|
||||||
s.lastDown === expected.down &&
|
|
||||||
s.gaps === 0
|
|
||||||
)
|
|
||||||
}
|
|
||||||
export function compare(a, b, threshold = null) {
|
|
||||||
const stats = new Map()
|
|
||||||
const text = (value) => typeof value === 'string' && value.length > 0
|
|
||||||
const object = (value) =>
|
|
||||||
value && typeof value === 'object' && !Array.isArray(value)
|
|
||||||
const expectedMarks = [
|
|
||||||
'ready',
|
|
||||||
...phases.flatMap((phase) => [phase, `${phase}:end`]),
|
|
||||||
]
|
|
||||||
const valid = (x) =>
|
|
||||||
x?.schema === SCHEMA &&
|
|
||||||
text(x?.harnessSha256) &&
|
|
||||||
[
|
|
||||||
'head',
|
|
||||||
'sourceSha256',
|
|
||||||
'binarySha256',
|
|
||||||
'frontendSha256',
|
|
||||||
'buildSettingsSha256',
|
|
||||||
'mode',
|
|
||||||
'buildCommand',
|
|
||||||
'binary',
|
|
||||||
'toolchain',
|
|
||||||
].every((key) => text(x.build?.[key])) &&
|
|
||||||
typeof x.build.dirty === 'string' &&
|
|
||||||
object(x.build.buildEnvironment) &&
|
|
||||||
[
|
|
||||||
'method',
|
|
||||||
'mode',
|
|
||||||
'toolchain',
|
|
||||||
'buildSettingsSha256',
|
|
||||||
'platform',
|
|
||||||
'machine',
|
|
||||||
'arch',
|
|
||||||
'host',
|
|
||||||
'hardware',
|
|
||||||
'power',
|
|
||||||
'powerSource',
|
|
||||||
'webkit',
|
|
||||||
'replay',
|
|
||||||
'automation',
|
|
||||||
].every((key) => text(x.contract?.[key])) &&
|
|
||||||
object(x.contract.buildEnvironment) &&
|
|
||||||
x.build.buildSettingsSha256 === x.contract.buildSettingsSha256 &&
|
|
||||||
[
|
|
||||||
'warmup',
|
|
||||||
'intervalMs',
|
|
||||||
'transitionSeconds',
|
|
||||||
'readinessAllowanceSeconds',
|
|
||||||
].every((key) => Number.isFinite(x.contract[key]) && x.contract[key] > 0) &&
|
|
||||||
x.contract.scenario === 'traffic' &&
|
|
||||||
typeof x.contract.consoleLocked === 'boolean' &&
|
|
||||||
x.contract.windowPolicy === 'nonactivating-top-click-through-v1' &&
|
|
||||||
x.contract.replayMs === 200 &&
|
|
||||||
x.contract.rangeMinutes === 10 &&
|
|
||||||
['window', 'viewport'].every(
|
|
||||||
(key) =>
|
|
||||||
Array.isArray(x.contract[key]) &&
|
|
||||||
x.contract[key].length === (key === 'window' ? 2 : 3) &&
|
|
||||||
x.contract[key].every((v) => Number.isFinite(v) && v > 0),
|
|
||||||
) &&
|
|
||||||
Number.isFinite(x.contract?.seconds) &&
|
|
||||||
x.contract.seconds >= 5 &&
|
|
||||||
Array.isArray(x.contract.phaseTargets) &&
|
|
||||||
x.contract.phaseTargets.length === phases.length &&
|
|
||||||
x.contract.phaseTargets.every((n) => Number.isInteger(n) && n > 0) &&
|
|
||||||
Array.isArray(x.runs) &&
|
|
||||||
x.runs.length &&
|
|
||||||
x.runs.every((r) => {
|
|
||||||
if (
|
|
||||||
!r?.ok ||
|
|
||||||
!Array.isArray(r.samples) ||
|
|
||||||
!r.samples.every(
|
|
||||||
(s) => s && roles.includes(s.role) && phases.includes(s.phase),
|
|
||||||
) ||
|
|
||||||
!Array.isArray(r.marks) ||
|
|
||||||
!r.marks.every((m) => m && typeof m.name === 'string')
|
|
||||||
)
|
|
||||||
return false
|
|
||||||
stats.set(r, summarize(r.samples, x.contract.seconds))
|
|
||||||
return (
|
|
||||||
r.cleanup?.mainExited &&
|
|
||||||
r.cleanup?.driverClosed &&
|
|
||||||
r.cleanup?.webviewExited &&
|
|
||||||
Array.isArray(r.consoleStates) &&
|
|
||||||
r.consoleStates.length === expectedMarks.length &&
|
|
||||||
r.consoleStates.every(
|
|
||||||
(s, i) =>
|
|
||||||
s &&
|
|
||||||
s.name === (i ? expectedMarks[i] : 'initial') &&
|
|
||||||
typeof s.locked === 'boolean' &&
|
|
||||||
Number.isFinite(s.time) &&
|
|
||||||
s.time > 0 &&
|
|
||||||
(!i || s.time >= r.consoleStates[i - 1].time),
|
|
||||||
) &&
|
|
||||||
Number.isInteger(r.replay?.sent) &&
|
|
||||||
r.replay.sent > 0 &&
|
|
||||||
Number.isFinite(r.replay.maxLateMs) &&
|
|
||||||
r.replay.maxLateMs >= 0 &&
|
|
||||||
r.replay.maxLateMs < x.contract.replayMs &&
|
|
||||||
!r.replay.error &&
|
|
||||||
r.actualWarmupMs >= x.contract.warmup * 1000 &&
|
|
||||||
Array.isArray(r.observations) &&
|
|
||||||
r.observations.length > 0 &&
|
|
||||||
r.observations.every(
|
|
||||||
(s, i) =>
|
|
||||||
validObservation(s) && (!i || s.now > r.observations[i - 1].now),
|
|
||||||
) &&
|
|
||||||
r.marks.length === expectedMarks.length &&
|
|
||||||
r.marks.every(
|
|
||||||
(m, i) =>
|
|
||||||
m.name === expectedMarks[i] &&
|
|
||||||
Number.isFinite(m.time) &&
|
|
||||||
m.time > 0 &&
|
|
||||||
(!i ||
|
|
||||||
(validObservation({ ...m, phase: m.name.split(':')[0] }) &&
|
|
||||||
/^[a-f0-9]{64}$/.test(m.pixelsSha256))) &&
|
|
||||||
(!phases.includes(m.name) ||
|
|
||||||
(m.target === x.contract.phaseTargets[phases.indexOf(m.name)] &&
|
|
||||||
m.received === m.target)) &&
|
|
||||||
(!i || m.time > r.marks[i - 1].time),
|
|
||||||
) &&
|
|
||||||
roles.every((role) =>
|
|
||||||
r.samples
|
|
||||||
.filter((s) => s.role === role)
|
|
||||||
.every(
|
|
||||||
(s, i, rows) =>
|
|
||||||
!i ||
|
|
||||||
(s.pid === rows[i - 1].pid &&
|
|
||||||
s.start === rows[i - 1].start &&
|
|
||||||
s.time > rows[i - 1].time &&
|
|
||||||
s.cpu >= rows[i - 1].cpu &&
|
|
||||||
phases.indexOf(s.phase) >= phases.indexOf(rows[i - 1].phase)),
|
|
||||||
),
|
|
||||||
) &&
|
|
||||||
validStats(stats.get(r)) &&
|
|
||||||
phases.every((phase) => {
|
|
||||||
const start = r.marks.find((m) => m.name === phase)
|
|
||||||
const end = r.marks.find((m) => m.name === `${phase}:end`)
|
|
||||||
const observed = r.observations.filter((s) => s.phase === phase)
|
|
||||||
return (
|
|
||||||
start &&
|
|
||||||
end &&
|
|
||||||
observed.length > 0 &&
|
|
||||||
[
|
|
||||||
start.deadlineIndex,
|
|
||||||
end.deadlineIndex,
|
|
||||||
start.senderSent,
|
|
||||||
end.senderSent,
|
|
||||||
].every((n) => Number.isInteger(n) && n >= 0) &&
|
|
||||||
end.deadlineIndex > start.deadlineIndex &&
|
|
||||||
end.senderSent >= start.senderSent &&
|
|
||||||
end.senderSent <= r.replay.sent &&
|
|
||||||
start.senderSent >= start.received &&
|
|
||||||
end.senderSent >= end.received &&
|
|
||||||
Math.abs(
|
|
||||||
end.received -
|
|
||||||
start.received -
|
|
||||||
(end.deadlineIndex - start.deadlineIndex),
|
|
||||||
) <= 2 &&
|
|
||||||
observed.every(
|
|
||||||
(s) =>
|
|
||||||
s.now >= start.now &&
|
|
||||||
s.now <= end.now &&
|
|
||||||
s.received >= start.received &&
|
|
||||||
s.received <= end.received,
|
|
||||||
) &&
|
|
||||||
end.worker > start.worker &&
|
|
||||||
(phase === 'hidden' ||
|
|
||||||
(end.draw > start.draw &&
|
|
||||||
end.pixelsSha256 !== start.pixelsSha256))
|
|
||||||
)
|
|
||||||
})
|
|
||||||
)
|
|
||||||
})
|
|
||||||
if (![a, b].every(valid))
|
|
||||||
return { verdict: 'invalid', reason: 'failed, malformed or missing runs' }
|
|
||||||
if (
|
|
||||||
[a, b].some((x) =>
|
|
||||||
x.runs.some((r) =>
|
|
||||||
r.consoleStates.some((s) => s.locked !== x.contract.consoleLocked),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
return {
|
|
||||||
verdict: 'incomparable',
|
|
||||||
reason: 'console lock state changed at observed boundaries',
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
!isDeepStrictEqual(a.contract, b.contract) ||
|
|
||||||
['mode', 'buildCommand', 'toolchain', 'buildEnvironment'].some(
|
|
||||||
(key) => !isDeepStrictEqual(a.build[key], b.build[key]),
|
|
||||||
) ||
|
|
||||||
a.harnessSha256 !== b.harnessSha256
|
|
||||||
)
|
|
||||||
return {
|
|
||||||
verdict: 'incomparable',
|
|
||||||
reason: 'harness, platform, build mode, workload or environment differ',
|
|
||||||
}
|
|
||||||
for (const phase of phases) {
|
|
||||||
for (const name of [phase, `${phase}:end`]) {
|
|
||||||
const sizes = [a, b].map((x) =>
|
|
||||||
x.runs.map((r) => r.marks.find((m) => m.name === name)?.received),
|
|
||||||
)
|
|
||||||
if (!sizes.flat().every(Number.isFinite))
|
|
||||||
return { verdict: 'invalid', reason: 'missing observed workload size' }
|
|
||||||
if (
|
|
||||||
Math.abs(quantile(sizes[0], 0.5) - quantile(sizes[1], 0.5)) > 2 ||
|
|
||||||
sizes.some((s) => Math.max(...s) - Math.min(...s) > 2)
|
|
||||||
)
|
|
||||||
return {
|
|
||||||
verdict: 'incomparable',
|
|
||||||
reason: `${name}: input size varies by more than two replay points`,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const same = a.build.binarySha256 === b.build.binarySha256
|
|
||||||
const enough = a.runs.length >= 3 && b.runs.length >= 3
|
|
||||||
const metrics = {}
|
|
||||||
for (const phase of phases)
|
|
||||||
for (const role of roles)
|
|
||||||
for (const metric of ['cpuMean', 'rssP50']) {
|
|
||||||
const key = `${phase}/${role}`
|
|
||||||
const av = a.runs.map((r) => stats.get(r)[key][metric])
|
|
||||||
const bv = b.runs.map((r) => stats.get(r)[key][metric])
|
|
||||||
const before = quantile(av, 0.5),
|
|
||||||
after = quantile(bv, 0.5)
|
|
||||||
const noise = Math.max(...av) - Math.min(...av)
|
|
||||||
const candidateRange = Math.max(...bv) - Math.min(...bv)
|
|
||||||
const overlap =
|
|
||||||
Math.max(...av) >= Math.min(...bv) &&
|
|
||||||
Math.max(...bv) >= Math.min(...av)
|
|
||||||
metrics[`${key}/${metric}`] = {
|
|
||||||
before,
|
|
||||||
after,
|
|
||||||
delta: after - before,
|
|
||||||
baselineRange: noise,
|
|
||||||
candidateRange,
|
|
||||||
verdict:
|
|
||||||
same ||
|
|
||||||
!enough ||
|
|
||||||
threshold === null ||
|
|
||||||
!av.every(Number.isFinite) ||
|
|
||||||
!bv.every(Number.isFinite) ||
|
|
||||||
overlap ||
|
|
||||||
Math.abs(after - before) <=
|
|
||||||
Math.max(
|
|
||||||
noise,
|
|
||||||
candidateRange,
|
|
||||||
(Math.abs(before) * threshold) / 100,
|
|
||||||
)
|
|
||||||
? 'inconclusive'
|
|
||||||
: after < before
|
|
||||||
? 'lower'
|
|
||||||
: 'higher',
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
verdict: 'inconclusive',
|
|
||||||
kind: same ? 'A/A' : 'A/B',
|
|
||||||
reason: same
|
|
||||||
? 'same binary; natural variation only'
|
|
||||||
: 'inspect independent-run metrics; no universal pass threshold',
|
|
||||||
metrics,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
export function markdown(report) {
|
|
||||||
const lines = [
|
|
||||||
'# Home traffic graph - replay measurement',
|
|
||||||
'',
|
|
||||||
`Success: ${report.runs.filter((r) => r.ok).length}/${report.runs.length}`,
|
|
||||||
'',
|
|
||||||
'CPU: one fully occupied core = 100%. Memory: process resident size bytes, not exclusive memory. Null = unavailable; first CPU observation has no delta. Slope requires 60 seconds of continuous observations.',
|
|
||||||
'',
|
|
||||||
'| Run / stage / role | CPU mean / P50 / P95 / peak (%) | CPU s | RSS P50 / P95 / peak / delta (bytes) | Samples / coverage |',
|
|
||||||
'|---|---|---|---|---|',
|
|
||||||
]
|
|
||||||
for (const [i, run] of report.runs.entries()) {
|
|
||||||
if (run.error) lines.push(`\nRun ${i + 1} failed: ${run.error}\n`)
|
|
||||||
for (const [key, s] of Object.entries(run.stats))
|
|
||||||
lines.push(
|
|
||||||
`| ${i + 1}/${key} | ${[s.cpuMean, s.cpuP50, s.cpuP95, s.cpuPeak].map((v) => v?.toFixed(2) ?? 'unavailable').join(' / ')} | ${s.cpuSeconds?.toFixed(3) ?? 'unavailable'} | ${[s.rssP50, s.rssP95, s.rssPeak, s.rssDelta].map((v) => v ?? 'unavailable').join(' / ')} | ${s.count} / ${(s.coverage * 100).toFixed(1)}% |`,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
lines.push(
|
|
||||||
'',
|
|
||||||
'Scope: loopback replay → public traffic append boundary → production Worker → homepage Canvas component. Mihomo and its network/subscription chain are not running. Shared GPU/network processes are unavailable and excluded. Process statistics do not identify function hotspots, component CPU or retained objects; memory growth is not proof of a leak.',
|
|
||||||
'',
|
|
||||||
'Next measurement: use WebKit CPU sampling for the highest-CPU foreground/restored phase; use Allocation/Heap captures for repeatable RSS growth. React Compiler is an untested local A/B candidate only.',
|
|
||||||
)
|
|
||||||
return lines.join('\n') + '\n'
|
|
||||||
}
|
|
||||||
export const validStats = (stats) =>
|
|
||||||
Object.values(stats).every(
|
|
||||||
(s) =>
|
|
||||||
s.continuous &&
|
|
||||||
s.coverage >= 0.8 &&
|
|
||||||
s.intervalCoverage >= 0.8 &&
|
|
||||||
s.cpuCount >= 3,
|
|
||||||
)
|
|
||||||
@@ -1,340 +0,0 @@
|
|||||||
import assert from 'node:assert/strict'
|
|
||||||
import { execFileSync } from 'node:child_process'
|
|
||||||
import { mkdirSync } from 'node:fs'
|
|
||||||
import { test } from 'node:test'
|
|
||||||
|
|
||||||
import {
|
|
||||||
compare,
|
|
||||||
delta,
|
|
||||||
phases,
|
|
||||||
roles,
|
|
||||||
quantile,
|
|
||||||
summarize,
|
|
||||||
validWorkload,
|
|
||||||
replayValues,
|
|
||||||
SCHEMA,
|
|
||||||
validVisibility,
|
|
||||||
} from './report.mjs'
|
|
||||||
const latest = (sequence) => {
|
|
||||||
const { up, down } = replayValues(sequence)
|
|
||||||
return { lastUp: up, lastDown: down }
|
|
||||||
}
|
|
||||||
const observation = (phase, now) => ({
|
|
||||||
phase,
|
|
||||||
now,
|
|
||||||
source: now - 100,
|
|
||||||
worker: now - 100,
|
|
||||||
draw: now - 100,
|
|
||||||
visible: phase !== 'hidden',
|
|
||||||
hidden: phase === 'hidden',
|
|
||||||
focused: false,
|
|
||||||
nativeFocused: false,
|
|
||||||
appActive: false,
|
|
||||||
top: true,
|
|
||||||
clickThrough: true,
|
|
||||||
})
|
|
||||||
const rows = phases.flatMap((phase, phaseIndex) =>
|
|
||||||
roles.flatMap((role) =>
|
|
||||||
Array.from({ length: 5 }, (_, i) => ({
|
|
||||||
phase,
|
|
||||||
role,
|
|
||||||
pid: role === 'main' ? 1 : 2,
|
|
||||||
start: '1',
|
|
||||||
time: (phaseIndex * 5 + i) * 1000,
|
|
||||||
cpu: (phaseIndex * 5 + i) / 10,
|
|
||||||
rss: 100 + i,
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
const run = {
|
|
||||||
ok: true,
|
|
||||||
samples: rows,
|
|
||||||
cleanup: { mainExited: true, driverClosed: true, webviewExited: true },
|
|
||||||
replay: { sent: 130, maxLateMs: 10 },
|
|
||||||
actualWarmupMs: 3000,
|
|
||||||
observations: phases.map((phase, i) => ({
|
|
||||||
...observation(phase, 2000 + i * 10000),
|
|
||||||
received: 35 + i * 35,
|
|
||||||
points: 34 + i * 35,
|
|
||||||
gaps: 0,
|
|
||||||
...latest(34 + i * 35),
|
|
||||||
})),
|
|
||||||
marks: [
|
|
||||||
{ name: 'ready', time: 1 },
|
|
||||||
...phases.flatMap((name, i) => [
|
|
||||||
{
|
|
||||||
name,
|
|
||||||
target: 35 + i * 35,
|
|
||||||
deadlineIndex: 35 + i * 35,
|
|
||||||
senderSent: 35 + i * 35,
|
|
||||||
received: 35 + i * 35,
|
|
||||||
points: 34 + i * 35,
|
|
||||||
...latest(34 + i * 35),
|
|
||||||
gaps: 0,
|
|
||||||
time: 1000 + i * 10000,
|
|
||||||
...observation(name, 1000 + i * 10000),
|
|
||||||
pixelsSha256: 'a'.repeat(64),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: `${name}:end`,
|
|
||||||
deadlineIndex: 60 + i * 35,
|
|
||||||
senderSent: 60 + i * 35,
|
|
||||||
received: 60 + i * 35,
|
|
||||||
points: 59 + i * 35,
|
|
||||||
...latest(59 + i * 35),
|
|
||||||
gaps: 0,
|
|
||||||
time: 6000 + i * 10000,
|
|
||||||
...observation(name, 6000 + i * 10000),
|
|
||||||
pixelsSha256: 'b'.repeat(64),
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
],
|
|
||||||
}
|
|
||||||
run.consoleStates = run.marks.map((m, i) => ({
|
|
||||||
name: i ? m.name : 'initial',
|
|
||||||
time: m.time,
|
|
||||||
locked: false,
|
|
||||||
}))
|
|
||||||
const baseline = {
|
|
||||||
schema: SCHEMA,
|
|
||||||
harnessSha256: 'fixture-harness',
|
|
||||||
build: {
|
|
||||||
head: 'fixture-head',
|
|
||||||
dirty: '',
|
|
||||||
sourceSha256: 'fixture-source',
|
|
||||||
binarySha256: 'same',
|
|
||||||
frontendSha256: 'fixture-assets',
|
|
||||||
buildSettingsSha256: 'fixture-settings',
|
|
||||||
mode: 'release',
|
|
||||||
buildCommand: 'fixture-build',
|
|
||||||
binary: '/fixture/app',
|
|
||||||
toolchain: 'fixture-tools',
|
|
||||||
buildEnvironment: {},
|
|
||||||
},
|
|
||||||
contract: {
|
|
||||||
scenario: 'traffic',
|
|
||||||
replayMs: 200,
|
|
||||||
consoleLocked: false,
|
|
||||||
windowPolicy: 'nonactivating-top-click-through-v1',
|
|
||||||
seconds: 5,
|
|
||||||
warmup: 2,
|
|
||||||
phaseTargets: [35, 70, 105],
|
|
||||||
transitionSeconds: 2,
|
|
||||||
readinessAllowanceSeconds: 5,
|
|
||||||
intervalMs: 1000,
|
|
||||||
rangeMinutes: 10,
|
|
||||||
window: [1000, 700],
|
|
||||||
viewport: [1000, 668, 2],
|
|
||||||
method: 'fixture-method',
|
|
||||||
mode: 'release',
|
|
||||||
toolchain: 'fixture-tools',
|
|
||||||
buildSettingsSha256: 'fixture-settings',
|
|
||||||
platform: 'macOS',
|
|
||||||
machine: 'fixture-model',
|
|
||||||
arch: 'arm64',
|
|
||||||
host: 'fixture-host',
|
|
||||||
hardware: 'fixture-hardware',
|
|
||||||
power: 'fixture-power',
|
|
||||||
powerSource: 'AC',
|
|
||||||
webkit: 'fixture-webkit',
|
|
||||||
replay: 'fixture-5Hz',
|
|
||||||
automation: 'fixture-wdio',
|
|
||||||
buildEnvironment: {},
|
|
||||||
},
|
|
||||||
runs: [run, run, run],
|
|
||||||
}
|
|
||||||
test('quantiles, CPU units, first observation and PID reuse', () => {
|
|
||||||
assert.equal(quantile([0, 10, 20], 0.95), 19)
|
|
||||||
assert.equal(delta(undefined, rows[0]), null)
|
|
||||||
assert.equal(delta(rows[0], rows[1]), 10)
|
|
||||||
assert.equal(delta(rows[0], { ...rows[1], start: '2' }), null)
|
|
||||||
assert.equal(delta(rows[0], { ...rows[1], time: NaN }), null)
|
|
||||||
assert.equal(summarize(rows, 5)['hidden/main'].cpuMean, 10)
|
|
||||||
assert.equal(summarize([], 5)['hidden/main'].cpuSeconds, null)
|
|
||||||
})
|
|
||||||
test('report schema: A/A, failed, incomparable and corrupt samples', () => {
|
|
||||||
assert.equal(compare(baseline, baseline).kind, 'A/A')
|
|
||||||
assert.equal(
|
|
||||||
compare(baseline, { ...baseline, schema: 'old' }).verdict,
|
|
||||||
'invalid',
|
|
||||||
)
|
|
||||||
for (const change of [
|
|
||||||
{ appActive: true },
|
|
||||||
{ nativeFocused: true },
|
|
||||||
{ top: false },
|
|
||||||
{ top: undefined },
|
|
||||||
{ clickThrough: false },
|
|
||||||
{ clickThrough: undefined },
|
|
||||||
{ hidden: true },
|
|
||||||
{ worker: 3000 },
|
|
||||||
{ now: 6000 },
|
|
||||||
{ draw: 3000 },
|
|
||||||
{ worker: null },
|
|
||||||
]) {
|
|
||||||
const invalid = structuredClone(baseline)
|
|
||||||
Object.assign(invalid.runs[0].observations[0], change)
|
|
||||||
assert.equal(compare(baseline, invalid).verdict, 'invalid')
|
|
||||||
}
|
|
||||||
for (const key of ['draw', 'pixelsSha256']) {
|
|
||||||
const stalled = structuredClone(baseline)
|
|
||||||
stalled.runs[0].marks[2][key] = stalled.runs[0].marks[1][key]
|
|
||||||
assert.equal(compare(baseline, stalled).verdict, 'invalid')
|
|
||||||
}
|
|
||||||
const missingPhase = structuredClone(baseline)
|
|
||||||
missingPhase.runs[0].observations.pop()
|
|
||||||
assert.equal(compare(baseline, missingPhase).verdict, 'invalid')
|
|
||||||
const consoleDrift = structuredClone(baseline)
|
|
||||||
consoleDrift.runs[0].consoleStates[3].locked = true
|
|
||||||
assert.equal(compare(baseline, consoleDrift).verdict, 'incomparable')
|
|
||||||
consoleDrift.runs[0].consoleStates[3].locked = null
|
|
||||||
assert.equal(compare(baseline, consoleDrift).verdict, 'invalid')
|
|
||||||
assert.equal(
|
|
||||||
validVisibility({ phase: 'restored', visible: true, hidden: true }),
|
|
||||||
false,
|
|
||||||
)
|
|
||||||
const missedPeriod = structuredClone(baseline)
|
|
||||||
missedPeriod.runs[0].replay.maxLateMs = 200
|
|
||||||
assert.equal(compare(baseline, missedPeriod).verdict, 'invalid')
|
|
||||||
const delayed = {
|
|
||||||
received: 100,
|
|
||||||
points: 97,
|
|
||||||
gaps: 0,
|
|
||||||
lastUp: 270000,
|
|
||||||
lastDown: 640000,
|
|
||||||
}
|
|
||||||
assert.equal(validWorkload(delayed), true)
|
|
||||||
assert.equal(validWorkload(null), false)
|
|
||||||
assert.equal(validWorkload({ ...delayed, points: 96 }), false)
|
|
||||||
assert.equal(validWorkload({ ...delayed, points: 98 }), false)
|
|
||||||
assert.equal(validWorkload({ ...delayed, received: 157 }), false)
|
|
||||||
assert.equal(validWorkload({ ...delayed, lastDown: 660000 }), false)
|
|
||||||
const missedAnchor = structuredClone(baseline)
|
|
||||||
missedAnchor.runs[0].marks[1].received++
|
|
||||||
assert.equal(compare(baseline, missedAnchor).verdict, 'invalid')
|
|
||||||
const droppedInputs = structuredClone(baseline)
|
|
||||||
const end = droppedInputs.runs[0].marks[2]
|
|
||||||
end.received -= 10
|
|
||||||
end.points -= 10
|
|
||||||
Object.assign(end, latest(end.points))
|
|
||||||
assert.equal(compare(droppedInputs, droppedInputs).verdict, 'invalid')
|
|
||||||
const workerLag = structuredClone(baseline)
|
|
||||||
workerLag.runs[0].observations[0].points -= 3
|
|
||||||
assert.equal(compare(baseline, workerLag).verdict, 'invalid')
|
|
||||||
const inputDrift = structuredClone(baseline)
|
|
||||||
inputDrift.runs = baseline.runs.map((r) => structuredClone(r))
|
|
||||||
inputDrift.runs[0].marks[2].received += 3
|
|
||||||
inputDrift.runs[0].marks[2].points += 3
|
|
||||||
inputDrift.runs[0].marks[2].deadlineIndex += 3
|
|
||||||
inputDrift.runs[0].marks[2].senderSent += 3
|
|
||||||
Object.assign(
|
|
||||||
inputDrift.runs[0].marks[2],
|
|
||||||
latest(inputDrift.runs[0].marks[2].points),
|
|
||||||
)
|
|
||||||
assert.equal(compare(baseline, inputDrift).verdict, 'incomparable')
|
|
||||||
const snapshotPhase = structuredClone(baseline)
|
|
||||||
snapshotPhase.runs[0].marks[2].points++
|
|
||||||
Object.assign(
|
|
||||||
snapshotPhase.runs[0].marks[2],
|
|
||||||
latest(snapshotPhase.runs[0].marks[2].points),
|
|
||||||
)
|
|
||||||
assert.equal(compare(baseline, snapshotPhase).kind, 'A/A')
|
|
||||||
const changedSettings = structuredClone(baseline)
|
|
||||||
changedSettings.build.buildSettingsSha256 =
|
|
||||||
changedSettings.contract.buildSettingsSha256 = 'changed-settings'
|
|
||||||
assert.equal(compare(baseline, changedSettings).verdict, 'incomparable')
|
|
||||||
assert.equal(
|
|
||||||
compare(baseline, { ...baseline, harnessSha256: 'changed' }).verdict,
|
|
||||||
'incomparable',
|
|
||||||
)
|
|
||||||
assert.equal(
|
|
||||||
compare(baseline, {
|
|
||||||
...baseline,
|
|
||||||
contract: { ...baseline.contract, seconds: 6 },
|
|
||||||
}).verdict,
|
|
||||||
'incomparable',
|
|
||||||
)
|
|
||||||
assert.equal(
|
|
||||||
compare(baseline, { ...baseline, runs: [{ ...run, ok: false }] }).verdict,
|
|
||||||
'invalid',
|
|
||||||
)
|
|
||||||
const corrupt = structuredClone(baseline)
|
|
||||||
corrupt.runs[0].samples[1].time = 0
|
|
||||||
assert.equal(compare(baseline, corrupt).verdict, 'invalid')
|
|
||||||
const shifted = structuredClone(baseline)
|
|
||||||
shifted.runs[0].samples
|
|
||||||
.filter((s) => s.phase === 'hidden')
|
|
||||||
.forEach((s) => {
|
|
||||||
s.time -= 5000
|
|
||||||
})
|
|
||||||
assert.equal(compare(baseline, shifted).verdict, 'invalid')
|
|
||||||
const badMarks = structuredClone(baseline)
|
|
||||||
badMarks.runs[0].marks.forEach((m) => {
|
|
||||||
m.time = -1
|
|
||||||
})
|
|
||||||
assert.equal(compare(baseline, badMarks).verdict, 'invalid')
|
|
||||||
const clustered = structuredClone(baseline)
|
|
||||||
clustered.runs[0].samples.forEach((s) => {
|
|
||||||
s.time /= 1000
|
|
||||||
})
|
|
||||||
assert.equal(compare(baseline, clustered).verdict, 'invalid')
|
|
||||||
for (const [section, key] of [
|
|
||||||
['contract', 'platform'],
|
|
||||||
['build', 'sourceSha256'],
|
|
||||||
]) {
|
|
||||||
const missing = structuredClone(baseline)
|
|
||||||
delete missing[section][key]
|
|
||||||
assert.equal(compare(missing, missing).verdict, 'invalid')
|
|
||||||
}
|
|
||||||
assert.equal(
|
|
||||||
compare(baseline, {
|
|
||||||
...baseline,
|
|
||||||
contract: { ...baseline.contract, platform: 'other-macOS' },
|
|
||||||
}).verdict,
|
|
||||||
'incomparable',
|
|
||||||
)
|
|
||||||
for (const malformed of [
|
|
||||||
null,
|
|
||||||
{},
|
|
||||||
{ runs: [null] },
|
|
||||||
{ ...baseline, runs: [{ ...run, samples: null }] },
|
|
||||||
])
|
|
||||||
assert.equal(compare(baseline, malformed).verdict, 'invalid')
|
|
||||||
const noisy = structuredClone(baseline)
|
|
||||||
noisy.runs = baseline.runs.map((r) => structuredClone(r))
|
|
||||||
noisy.build.binarySha256 = 'different'
|
|
||||||
noisy.runs.forEach((r, i) =>
|
|
||||||
r.samples.forEach((s) => {
|
|
||||||
s.cpu *= [0.1, 0.2, 10][i]
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
assert.equal(
|
|
||||||
compare(baseline, noisy, 5).metrics['foreground/webview/cpuMean'].verdict,
|
|
||||||
'inconclusive',
|
|
||||||
)
|
|
||||||
})
|
|
||||||
test('macOS collector agrees with process.cpuUsage on a busy owned process', {
|
|
||||||
skip: process.platform !== 'darwin',
|
|
||||||
}, () => {
|
|
||||||
mkdirSync('target/perf', { recursive: true })
|
|
||||||
execFileSync('cc', [
|
|
||||||
'-Wall',
|
|
||||||
'-Wextra',
|
|
||||||
'-Werror',
|
|
||||||
'scripts/perf/sample.c',
|
|
||||||
'-o',
|
|
||||||
'target/perf/test-sample',
|
|
||||||
])
|
|
||||||
const sample = () =>
|
|
||||||
Number(
|
|
||||||
execFileSync('target/perf/test-sample', [String(process.pid)], {
|
|
||||||
encoding: 'utf8',
|
|
||||||
}).split(' ')[2],
|
|
||||||
)
|
|
||||||
const first = sample(),
|
|
||||||
cpu = process.cpuUsage(),
|
|
||||||
start = performance.now()
|
|
||||||
while (performance.now() - start < 500) Math.sqrt(Math.random())
|
|
||||||
const used = process.cpuUsage(cpu),
|
|
||||||
measured = sample() - first
|
|
||||||
assert.ok(Math.abs(measured - (used.user + used.system) / 1e6) < 0.05)
|
|
||||||
})
|
|
||||||
@@ -1,674 +0,0 @@
|
|||||||
import { spawn, execFileSync } from 'node:child_process'
|
|
||||||
import { createHash, randomUUID } from 'node:crypto'
|
|
||||||
import {
|
|
||||||
mkdirSync,
|
|
||||||
readFileSync,
|
|
||||||
writeFileSync,
|
|
||||||
openSync,
|
|
||||||
closeSync,
|
|
||||||
realpathSync,
|
|
||||||
} from 'node:fs'
|
|
||||||
import { createServer } from 'node:net'
|
|
||||||
import { resolve, dirname } from 'node:path'
|
|
||||||
import { setTimeout as sleep } from 'node:timers/promises'
|
|
||||||
import { parseArgs } from 'node:util'
|
|
||||||
|
|
||||||
import { createTauriCapabilities } from '@wdio/tauri-service'
|
|
||||||
import { remote } from 'webdriverio'
|
|
||||||
import { WebSocketServer } from 'ws'
|
|
||||||
|
|
||||||
import {
|
|
||||||
delta,
|
|
||||||
summarize,
|
|
||||||
markdown,
|
|
||||||
phases,
|
|
||||||
roles,
|
|
||||||
validStats,
|
|
||||||
validWorkload,
|
|
||||||
replayValues,
|
|
||||||
SCHEMA,
|
|
||||||
validObservation,
|
|
||||||
validVisibility,
|
|
||||||
} from './report.mjs'
|
|
||||||
|
|
||||||
const { values } = parseArgs({
|
|
||||||
args: process.argv.slice(2).filter((v) => v !== '--'),
|
|
||||||
options: {
|
|
||||||
output: { type: 'string', default: `target/perf/runs/${Date.now()}` },
|
|
||||||
binary: { type: 'string', default: 'target/perf/build/clash-verge' },
|
|
||||||
repeat: { type: 'string', default: '3' },
|
|
||||||
seconds: { type: 'string', default: '20' },
|
|
||||||
warmup: { type: 'string', default: '10' },
|
|
||||||
'fail-phase': { type: 'string' },
|
|
||||||
},
|
|
||||||
})
|
|
||||||
const seconds = Number(values.seconds),
|
|
||||||
warmup = Number(values.warmup),
|
|
||||||
repeat = Number(values.repeat)
|
|
||||||
const replayMs = 200
|
|
||||||
if (process.platform !== 'darwin') throw new Error('macOS only')
|
|
||||||
function readConsole() {
|
|
||||||
const consoleState = JSON.parse(
|
|
||||||
execFileSync('/usr/bin/plutil', ['-convert', 'json', '-o', '-', '-'], {
|
|
||||||
input: execFileSync('/usr/sbin/ioreg', ['-n', 'Root', '-d1', '-a']),
|
|
||||||
encoding: 'utf8',
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
const locked = consoleState.IOConsoleLocked
|
|
||||||
if (typeof locked !== 'boolean')
|
|
||||||
throw new Error('Environment unavailable: unknown console lock state')
|
|
||||||
return locked
|
|
||||||
}
|
|
||||||
function checkConsole() {
|
|
||||||
const locked = readConsole()
|
|
||||||
if (locked)
|
|
||||||
throw new Error(
|
|
||||||
'Environment unavailable: an unlocked graphical session is required; window focus is not required',
|
|
||||||
)
|
|
||||||
return locked
|
|
||||||
}
|
|
||||||
const consoleLocked = checkConsole()
|
|
||||||
if (
|
|
||||||
![seconds, warmup, repeat].every(Number.isFinite) ||
|
|
||||||
seconds < 5 ||
|
|
||||||
warmup < 2 ||
|
|
||||||
repeat < 1 ||
|
|
||||||
!Number.isInteger(repeat)
|
|
||||||
)
|
|
||||||
throw new Error('Require seconds >= 5, warmup >= 2, integer repeat >= 1')
|
|
||||||
const phaseTargets = phases.map(
|
|
||||||
(_, i) =>
|
|
||||||
Math.ceil(((warmup + 5) * 1000) / replayMs) +
|
|
||||||
i * Math.ceil(((seconds + 2) * 1000) / replayMs),
|
|
||||||
)
|
|
||||||
if ((phaseTargets[2] * replayMs) / 1000 + seconds + 5 >= 600)
|
|
||||||
throw new Error(
|
|
||||||
'Total replay including transition allowance must be < 10 minutes',
|
|
||||||
)
|
|
||||||
const binary = realpathSync(values.binary),
|
|
||||||
output = resolve(values.output)
|
|
||||||
const webcontentBinary = realpathSync(
|
|
||||||
'/System/Library/Frameworks/WebKit.framework/Versions/A/XPCServices/com.apple.WebKit.WebContent.xpc/Contents/MacOS/com.apple.WebKit.WebContent',
|
|
||||||
)
|
|
||||||
const build = JSON.parse(readFileSync(`${binary}.json`))
|
|
||||||
const hash = (data) => createHash('sha256').update(data).digest('hex')
|
|
||||||
if (hash(readFileSync(binary)) !== build.binarySha256)
|
|
||||||
throw new Error('Binary does not match build manifest')
|
|
||||||
try {
|
|
||||||
execFileSync('git', ['check-ignore', '-q', '--no-index', output])
|
|
||||||
} catch {
|
|
||||||
throw new Error('Output directory must be Git ignored')
|
|
||||||
}
|
|
||||||
mkdirSync(dirname(output), { recursive: true })
|
|
||||||
mkdirSync(output)
|
|
||||||
execFileSync('cc', ['-O2', 'scripts/perf/sample.c', '-o', `${output}/sample`])
|
|
||||||
const command = (name, args) =>
|
|
||||||
execFileSync(name, args, { encoding: 'utf8' }).trim()
|
|
||||||
const report = {
|
|
||||||
schema: SCHEMA,
|
|
||||||
build,
|
|
||||||
contract: {
|
|
||||||
scenario: 'traffic',
|
|
||||||
replayMs,
|
|
||||||
consoleLocked,
|
|
||||||
method: 'mach-rusage-v0-seconds/rss-bytes-v1',
|
|
||||||
mode: build.mode,
|
|
||||||
buildSettingsSha256: build.buildSettingsSha256,
|
|
||||||
buildEnvironment: build.buildEnvironment,
|
|
||||||
toolchain: build.toolchain,
|
|
||||||
platform: command('sw_vers', []),
|
|
||||||
machine: command('sysctl', ['-n', 'hw.model']),
|
|
||||||
arch: process.arch,
|
|
||||||
host: hash(command('scutil', ['--get', 'LocalHostName'])),
|
|
||||||
hardware: command('sysctl', ['hw.ncpu', 'hw.memsize']),
|
|
||||||
power: command('pmset', ['-g', 'custom']),
|
|
||||||
powerSource: command('pmset', ['-g', 'batt']).split('\n')[0],
|
|
||||||
webkit: command('defaults', [
|
|
||||||
'read',
|
|
||||||
'/System/Library/Frameworks/WebKit.framework/Resources/Info',
|
|
||||||
'CFBundleVersion',
|
|
||||||
]),
|
|
||||||
seconds,
|
|
||||||
warmup,
|
|
||||||
phaseTargets,
|
|
||||||
transitionSeconds: 2,
|
|
||||||
readinessAllowanceSeconds: 5,
|
|
||||||
intervalMs: 1000,
|
|
||||||
window: [1000, 700],
|
|
||||||
windowPolicy: 'nonactivating-top-click-through-v1',
|
|
||||||
rangeMinutes: 10,
|
|
||||||
replay:
|
|
||||||
'deterministic-v1, 5Hz, no prefill, append boundary, default bezier, blur pause false',
|
|
||||||
automation:
|
|
||||||
'wdio plugin 1.3.0; 20Hz macOS runloop pump plus one WebDriver observation/second',
|
|
||||||
},
|
|
||||||
runs: [],
|
|
||||||
}
|
|
||||||
report.units = {
|
|
||||||
time: 'monotonic milliseconds',
|
|
||||||
cpu: 'cumulative CPU seconds',
|
|
||||||
percent: 'one CPU core = 100%',
|
|
||||||
rss: 'resident size bytes',
|
|
||||||
start: 'Mach process start ticks',
|
|
||||||
}
|
|
||||||
report.monotonicOriginEpochMs = performance.timeOrigin
|
|
||||||
report.harnessSha256 = hash(
|
|
||||||
['run.mjs', 'report.mjs', 'sample.c']
|
|
||||||
.map((p) => readFileSync(`scripts/perf/${p}`))
|
|
||||||
.join('\n'),
|
|
||||||
)
|
|
||||||
let interrupted = false
|
|
||||||
const abort = new AbortController()
|
|
||||||
const pause = (ms) => sleep(ms, undefined, { signal: abort.signal })
|
|
||||||
for (const signal of ['SIGINT', 'SIGTERM'])
|
|
||||||
process.on(signal, () => {
|
|
||||||
interrupted = true
|
|
||||||
abort.abort()
|
|
||||||
})
|
|
||||||
const assert = (value, reason) => {
|
|
||||||
if (!value) throw new Error(reason)
|
|
||||||
}
|
|
||||||
const drawn = (s) => s.now >= s.draw && s.now - s.draw < 2500
|
|
||||||
const marker = (s) => ({
|
|
||||||
...s,
|
|
||||||
pixelsSha256: hash(s.pixels),
|
|
||||||
pixels: undefined,
|
|
||||||
ua: undefined,
|
|
||||||
token: undefined,
|
|
||||||
})
|
|
||||||
async function freePort() {
|
|
||||||
const server = createServer()
|
|
||||||
await new Promise((done) => server.listen(0, '127.0.0.1', done))
|
|
||||||
const port = server.address().port
|
|
||||||
await new Promise((done) => server.close(done))
|
|
||||||
return port
|
|
||||||
}
|
|
||||||
for (let iteration = 0; iteration < repeat && !interrupted; iteration++) {
|
|
||||||
const initialLocked = checkConsole()
|
|
||||||
const token = randomUUID(),
|
|
||||||
port = await freePort()
|
|
||||||
const run = {
|
|
||||||
token,
|
|
||||||
ok: false,
|
|
||||||
samples: [],
|
|
||||||
observations: [],
|
|
||||||
consoleStates: [
|
|
||||||
{ name: 'initial', locked: initialLocked, time: Date.now() },
|
|
||||||
],
|
|
||||||
marks: [],
|
|
||||||
stats: {},
|
|
||||||
cleanup: {},
|
|
||||||
replay: { sent: 0, maxLateMs: 0 },
|
|
||||||
}
|
|
||||||
report.runs.push(run)
|
|
||||||
const replay = new WebSocketServer({ host: '127.0.0.1', port: 0 })
|
|
||||||
await new Promise((done) => replay.on('listening', done))
|
|
||||||
let sequence = 0,
|
|
||||||
replayStarted,
|
|
||||||
timer
|
|
||||||
replay.on('connection', () => {
|
|
||||||
if (replayStarted !== undefined) {
|
|
||||||
run.replay.error = 'unexpected replay reconnection'
|
|
||||||
clearTimeout(timer)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
replayStarted = performance.now()
|
|
||||||
timer = setTimeout(send, replayMs)
|
|
||||||
})
|
|
||||||
const deadlineIndex = () =>
|
|
||||||
Math.floor((performance.now() - replayStarted) / replayMs)
|
|
||||||
function send() {
|
|
||||||
const deadline = replayStarted + (sequence + 1) * replayMs
|
|
||||||
const late = performance.now() - deadline
|
|
||||||
if (late < 0) {
|
|
||||||
timer = setTimeout(send, Math.ceil(-late))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
run.replay.maxLateMs = Math.max(run.replay.maxLateMs, late)
|
|
||||||
if (late >= replayMs) {
|
|
||||||
run.replay.error = `replay source missed a complete ${replayMs} ms period`
|
|
||||||
return
|
|
||||||
}
|
|
||||||
sequence++
|
|
||||||
run.replay.sent = sequence
|
|
||||||
const timestamp = Date.now()
|
|
||||||
const point = JSON.stringify({
|
|
||||||
sequence,
|
|
||||||
timestamp,
|
|
||||||
...replayValues(sequence),
|
|
||||||
})
|
|
||||||
for (const socket of replay.clients)
|
|
||||||
if (socket.readyState === 1) socket.send(point)
|
|
||||||
timer = setTimeout(
|
|
||||||
send,
|
|
||||||
Math.max(
|
|
||||||
0,
|
|
||||||
replayStarted + (sequence + 1) * replayMs - performance.now(),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
const log = openSync(`${output}/${iteration + 1}.log`, 'w')
|
|
||||||
const child = spawn(binary, [], {
|
|
||||||
env: {
|
|
||||||
...process.env,
|
|
||||||
PERF_TOKEN: token,
|
|
||||||
PERF_REPLAY_PORT: String(replay.address().port),
|
|
||||||
TAURI_WEBDRIVER_PORT: String(port),
|
|
||||||
},
|
|
||||||
stdio: ['ignore', log, log],
|
|
||||||
})
|
|
||||||
closeSync(log)
|
|
||||||
let browser, childError, previous, mainStart
|
|
||||||
const identities = {}
|
|
||||||
child.on('error', (error) => {
|
|
||||||
childError = error
|
|
||||||
})
|
|
||||||
const exited = new Promise((done) => child.once('exit', done))
|
|
||||||
const alive = () =>
|
|
||||||
!childError && child.exitCode === null && child.signalCode === null
|
|
||||||
const collect = (pids) =>
|
|
||||||
command(`${output}/sample`, pids.map(String))
|
|
||||||
.split('\n')
|
|
||||||
.map((line) => {
|
|
||||||
const [pid, start, cpu, rss, ...path] = line.split(' ')
|
|
||||||
return {
|
|
||||||
pid: Number(pid),
|
|
||||||
start,
|
|
||||||
cpu: Number(cpu),
|
|
||||||
rss: Number(rss),
|
|
||||||
path: path.join(' '),
|
|
||||||
time: performance.now(),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
const identify = (role, row) => {
|
|
||||||
assert(
|
|
||||||
row.path === (role === 'main' ? binary : webcontentBinary),
|
|
||||||
`unexpected ${role} process executable: ${row.path}`,
|
|
||||||
)
|
|
||||||
assert(
|
|
||||||
BigInt(row.start) >= BigInt(mainStart),
|
|
||||||
'process predates owned application',
|
|
||||||
)
|
|
||||||
const identity = `${row.pid}/${row.start}`
|
|
||||||
assert(
|
|
||||||
!identities[role] || identities[role] === identity,
|
|
||||||
'process identity changed during scenario',
|
|
||||||
)
|
|
||||||
identities[role] = identity
|
|
||||||
}
|
|
||||||
const state = async (action = 'state', pixels = false) =>
|
|
||||||
browser.execute(
|
|
||||||
async (action, pixels) => {
|
|
||||||
const native = await window.__TAURI_INTERNALS__.invoke('perf_state', {
|
|
||||||
action,
|
|
||||||
})
|
|
||||||
const canvas = document.querySelector('canvas')
|
|
||||||
return {
|
|
||||||
...native,
|
|
||||||
now: Date.now(),
|
|
||||||
hidden: document.hidden,
|
|
||||||
focused: document.hasFocus(),
|
|
||||||
received: Number(document.documentElement.dataset.perfReceived),
|
|
||||||
source: Number(document.documentElement.dataset.perfSourceTime),
|
|
||||||
gaps: Number(document.documentElement.dataset.perfGaps),
|
|
||||||
worker: Number(document.documentElement.dataset.perfWorker),
|
|
||||||
points: Number(document.documentElement.dataset.perfPoints),
|
|
||||||
lastUp: Number(document.documentElement.dataset.perfLastUp),
|
|
||||||
lastDown: Number(document.documentElement.dataset.perfLastDown),
|
|
||||||
draw: Number(canvas?.dataset.perfDraw),
|
|
||||||
pixels: pixels ? canvas?.toDataURL() : null,
|
|
||||||
ua: navigator.userAgent,
|
|
||||||
}
|
|
||||||
},
|
|
||||||
action,
|
|
||||||
pixels,
|
|
||||||
)
|
|
||||||
const checked = async (action, pixels) => {
|
|
||||||
assert(!interrupted, 'interrupted')
|
|
||||||
assert(!run.replay.error, run.replay.error)
|
|
||||||
assert(
|
|
||||||
alive(),
|
|
||||||
`owned app exited: ${childError ?? child.exitCode ?? child.signalCode}`,
|
|
||||||
)
|
|
||||||
const value = await state(action, pixels)
|
|
||||||
assert(!run.replay.error, run.replay.error)
|
|
||||||
run.lastObservation = { ...value, pixels: undefined, ua: undefined }
|
|
||||||
assert(
|
|
||||||
value.token === token && value.main === child.pid,
|
|
||||||
'instance identity mismatch',
|
|
||||||
)
|
|
||||||
if (!identities.webview) {
|
|
||||||
run.initialAttribution = collect([value.webview])[0]
|
|
||||||
identify('webview', run.initialAttribution)
|
|
||||||
}
|
|
||||||
assert(
|
|
||||||
value.nativeFocused === false && value.appActive === false,
|
|
||||||
'measurement window unexpectedly activated',
|
|
||||||
)
|
|
||||||
assert(
|
|
||||||
value.top === true && value.clickThrough === true,
|
|
||||||
'measurement window must be natively topmost and click-through',
|
|
||||||
)
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
mainStart = collect([child.pid])[0].start
|
|
||||||
const deadline = Date.now() + 30000
|
|
||||||
while (true) {
|
|
||||||
assert(
|
|
||||||
Date.now() < deadline && !interrupted && alive(),
|
|
||||||
'embedded WebDriver readiness deadline or app exit',
|
|
||||||
)
|
|
||||||
try {
|
|
||||||
if (
|
|
||||||
(
|
|
||||||
await fetch(`http://127.0.0.1:${port}/status`, {
|
|
||||||
signal: AbortSignal.timeout(500),
|
|
||||||
})
|
|
||||||
).ok
|
|
||||||
)
|
|
||||||
break
|
|
||||||
} catch {}
|
|
||||||
await pause(100)
|
|
||||||
}
|
|
||||||
const listener = command('lsof', [
|
|
||||||
'-nP',
|
|
||||||
'-a',
|
|
||||||
'-p',
|
|
||||||
String(child.pid),
|
|
||||||
`-iTCP:${port}`,
|
|
||||||
'-sTCP:LISTEN',
|
|
||||||
])
|
|
||||||
assert(
|
|
||||||
listener.includes(`127.0.0.1:${port}`) && !listener.includes(`*:${port}`),
|
|
||||||
'driver must belong to this app and bind loopback',
|
|
||||||
)
|
|
||||||
const capabilities = createTauriCapabilities(binary)
|
|
||||||
delete capabilities['wdio:tauriServiceOptions']
|
|
||||||
browser = await remote({
|
|
||||||
hostname: '127.0.0.1',
|
|
||||||
port,
|
|
||||||
capabilities,
|
|
||||||
logLevel: 'error',
|
|
||||||
connectionRetryCount: 0,
|
|
||||||
connectionRetryTimeout: 5000,
|
|
||||||
})
|
|
||||||
const handles = await browser.getWindowHandles()
|
|
||||||
assert(handles.length === 1, 'expected exactly one measurement WebView')
|
|
||||||
await browser.switchToWindow(handles[0])
|
|
||||||
// Replay's parent effect starts the socket after the graph installs its listeners.
|
|
||||||
await browser.waitUntil(
|
|
||||||
async () => {
|
|
||||||
const s = await checked()
|
|
||||||
return (
|
|
||||||
validWorkload(s) &&
|
|
||||||
s.received >= 3 &&
|
|
||||||
s.now >= s.worker &&
|
|
||||||
s.now - s.worker < 2500
|
|
||||||
)
|
|
||||||
},
|
|
||||||
{
|
|
||||||
timeout: 15000,
|
|
||||||
interval: 100,
|
|
||||||
timeoutMsg: 'traffic effects/Worker not ready before show',
|
|
||||||
},
|
|
||||||
)
|
|
||||||
run.initialData = run.lastObservation
|
|
||||||
await checked('show')
|
|
||||||
await browser.waitUntil(
|
|
||||||
async () => {
|
|
||||||
const s = await checked()
|
|
||||||
return validObservation({ phase: 'foreground', ...s })
|
|
||||||
},
|
|
||||||
{
|
|
||||||
timeout: 15000,
|
|
||||||
interval: 250,
|
|
||||||
timeoutMsg: 'traffic data path/page not ready',
|
|
||||||
},
|
|
||||||
)
|
|
||||||
run.userAgent = (await checked()).ua
|
|
||||||
run.backgroundLoad = command('sysctl', ['-n', 'vm.loadavg'])
|
|
||||||
const viewport = await browser.execute(() => [
|
|
||||||
innerWidth,
|
|
||||||
innerHeight,
|
|
||||||
devicePixelRatio,
|
|
||||||
])
|
|
||||||
run.viewport = { dom: viewport, driver: await browser.getWindowRect() }
|
|
||||||
const driverScale = run.viewport.driver.width / 1000
|
|
||||||
assert(
|
|
||||||
viewport[0] === 1000 &&
|
|
||||||
viewport[1] > 0 &&
|
|
||||||
viewport[1] <= 700 &&
|
|
||||||
(driverScale === 1 || driverScale === viewport[2]) &&
|
|
||||||
run.viewport.driver.height / driverScale === 700,
|
|
||||||
`unexpected window dimensions: ${JSON.stringify(run.viewport)}`,
|
|
||||||
)
|
|
||||||
assert(
|
|
||||||
!report.contract.viewport ||
|
|
||||||
JSON.stringify(report.contract.viewport) === JSON.stringify(viewport),
|
|
||||||
'viewport changed between runs',
|
|
||||||
)
|
|
||||||
report.contract.viewport = viewport
|
|
||||||
run.marks.push({ name: 'ready', time: Date.now() })
|
|
||||||
const readyAt = performance.now()
|
|
||||||
assert(
|
|
||||||
phaseTargets[0] - (await checked()).received >=
|
|
||||||
(warmup * 1000) / replayMs,
|
|
||||||
'readiness exceeded fixed replay allowance',
|
|
||||||
)
|
|
||||||
for (const phase of phases) {
|
|
||||||
run.consoleStates.push({
|
|
||||||
name: phase,
|
|
||||||
locked: readConsole(),
|
|
||||||
time: Date.now(),
|
|
||||||
})
|
|
||||||
const operation = performance.now()
|
|
||||||
let s = await checked(phase === 'hidden' ? 'hide' : 'show', true)
|
|
||||||
assert(
|
|
||||||
s.visible === (phase !== 'hidden'),
|
|
||||||
`${phase}: native visibility mismatch`,
|
|
||||||
)
|
|
||||||
const beforeDraw = s.draw
|
|
||||||
await browser.waitUntil(
|
|
||||||
async () => {
|
|
||||||
s = await checked('state', true)
|
|
||||||
return (
|
|
||||||
validVisibility({ phase, ...s }) &&
|
|
||||||
(phase === 'hidden' || (s.draw > beforeDraw && drawn(s)))
|
|
||||||
)
|
|
||||||
},
|
|
||||||
{
|
|
||||||
timeout: 5000,
|
|
||||||
interval: 100,
|
|
||||||
timeoutMsg: `${phase}: window/Canvas readiness deadline`,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
const operationMs = performance.now() - operation
|
|
||||||
const target = phaseTargets[phases.indexOf(phase)]
|
|
||||||
await browser.waitUntil(
|
|
||||||
async () => {
|
|
||||||
s = await checked('state', true)
|
|
||||||
assert(
|
|
||||||
s.received <= target,
|
|
||||||
`${phase}: missed replay anchor ${target}`,
|
|
||||||
)
|
|
||||||
return s.received === target
|
|
||||||
},
|
|
||||||
{
|
|
||||||
timeout: Math.max(1000, (target - s.received) * replayMs + 1000),
|
|
||||||
interval: 50,
|
|
||||||
timeoutMsg: `${phase}: replay anchor deadline`,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
assert(
|
|
||||||
validObservation({ phase, ...s }),
|
|
||||||
`${phase}: invalid traffic observation`,
|
|
||||||
)
|
|
||||||
const first = s,
|
|
||||||
start = performance.now(),
|
|
||||||
firstIndex = deadlineIndex(),
|
|
||||||
phaseEpoch = Date.now()
|
|
||||||
if (phase === 'foreground') {
|
|
||||||
run.actualWarmupMs = start - readyAt
|
|
||||||
assert(
|
|
||||||
run.actualWarmupMs >= warmup * 1000,
|
|
||||||
'insufficient actual warmup',
|
|
||||||
)
|
|
||||||
}
|
|
||||||
run.marks.push({
|
|
||||||
name: phase,
|
|
||||||
time: phaseEpoch,
|
|
||||||
operationMs,
|
|
||||||
transitionMs: start - operation,
|
|
||||||
target,
|
|
||||||
...marker(s),
|
|
||||||
deadlineIndex: firstIndex,
|
|
||||||
senderSent: run.replay.sent,
|
|
||||||
})
|
|
||||||
previous = {}
|
|
||||||
if (values['fail-phase'] === phase)
|
|
||||||
throw new Error(`injected failure at ${phase}`)
|
|
||||||
while (performance.now() - start < seconds * 1000) {
|
|
||||||
const tick = performance.now()
|
|
||||||
s = await checked()
|
|
||||||
run.observations.push({ phase, ...run.lastObservation })
|
|
||||||
assert(
|
|
||||||
validObservation({ phase, ...s }),
|
|
||||||
`${phase}: invalid visibility, workload or freshness`,
|
|
||||||
)
|
|
||||||
assert(
|
|
||||||
performance.now() - replayStarted < 600000,
|
|
||||||
'replay exceeded raw history window',
|
|
||||||
)
|
|
||||||
const samples = collect(roles.map((role) => s[role]))
|
|
||||||
run.attribution = {
|
|
||||||
main: s.main,
|
|
||||||
webview: s.webview,
|
|
||||||
observed: samples,
|
|
||||||
}
|
|
||||||
for (let i = 0; i < roles.length; i++) {
|
|
||||||
const row = { ...samples[i], phase, role: roles[i] }
|
|
||||||
identify(row.role, row)
|
|
||||||
row.percent = delta(previous[row.role], row)
|
|
||||||
row.cpuDelta =
|
|
||||||
row.percent === null ? null : row.cpu - previous[row.role].cpu
|
|
||||||
run.samples.push(row)
|
|
||||||
previous[row.role] = row
|
|
||||||
}
|
|
||||||
await pause(Math.max(0, 1000 - (performance.now() - tick)))
|
|
||||||
}
|
|
||||||
s = await checked('state', true)
|
|
||||||
const endIndex = deadlineIndex()
|
|
||||||
const expected = endIndex - firstIndex
|
|
||||||
assert(
|
|
||||||
validObservation({ phase, ...s }) &&
|
|
||||||
s.worker > first.worker &&
|
|
||||||
Math.abs(s.received - first.received - expected) <= 2,
|
|
||||||
`${phase}: unstable or lost workload`,
|
|
||||||
)
|
|
||||||
if (phase !== 'hidden')
|
|
||||||
assert(
|
|
||||||
s.draw > first.draw && s.pixels !== first.pixels,
|
|
||||||
`${phase}: Canvas did not render fresh data`,
|
|
||||||
)
|
|
||||||
run.marks.push({
|
|
||||||
name: `${phase}:end`,
|
|
||||||
time: s.now,
|
|
||||||
...marker(s),
|
|
||||||
deadlineIndex: endIndex,
|
|
||||||
senderSent: run.replay.sent,
|
|
||||||
})
|
|
||||||
run.consoleStates.push({
|
|
||||||
name: `${phase}:end`,
|
|
||||||
locked: readConsole(),
|
|
||||||
time: Date.now(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
run.stats = summarize(run.samples, seconds)
|
|
||||||
assert(
|
|
||||||
validStats(run.stats),
|
|
||||||
'insufficient coverage or process discontinuity',
|
|
||||||
)
|
|
||||||
run.ok = true
|
|
||||||
} catch (error) {
|
|
||||||
run.error = String(error)
|
|
||||||
process.exitCode = 1
|
|
||||||
} finally {
|
|
||||||
await browser?.deleteSession().catch(() => {})
|
|
||||||
try {
|
|
||||||
if (alive() && collect([child.pid])[0].start === mainStart) {
|
|
||||||
child.kill('SIGTERM')
|
|
||||||
await Promise.race([exited, sleep(5000)])
|
|
||||||
if (alive() && collect([child.pid])[0].start === mainStart) {
|
|
||||||
child.kill('SIGKILL')
|
|
||||||
await Promise.race([exited, sleep(2000)])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
run.cleanup.error = String(error)
|
|
||||||
}
|
|
||||||
clearTimeout(timer)
|
|
||||||
for (const socket of replay.clients) socket.terminate()
|
|
||||||
await new Promise((done) => replay.close(done))
|
|
||||||
run.cleanup.mainExited =
|
|
||||||
child.exitCode !== null || child.signalCode !== null
|
|
||||||
if (identities.webview) {
|
|
||||||
const [pid, start] = identities.webview.split('/')
|
|
||||||
const remains = () => {
|
|
||||||
try {
|
|
||||||
return collect([pid])[0].start === start
|
|
||||||
} catch {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const deadline = Date.now() + 5000
|
|
||||||
while (remains() && Date.now() < deadline) await sleep(100)
|
|
||||||
run.cleanup.webviewExited = !remains()
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await fetch(`http://127.0.0.1:${port}/status`, {
|
|
||||||
signal: AbortSignal.timeout(500),
|
|
||||||
})
|
|
||||||
run.cleanup.driverClosed = false
|
|
||||||
} catch {
|
|
||||||
run.cleanup.driverClosed = true
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
!run.cleanup.mainExited ||
|
|
||||||
!run.cleanup.driverClosed ||
|
|
||||||
run.cleanup.webviewExited === false
|
|
||||||
) {
|
|
||||||
run.ok = false
|
|
||||||
run.error = `${run.error ?? ''} cleanup failed`
|
|
||||||
process.exitCode = 1
|
|
||||||
}
|
|
||||||
run.stats = summarize(run.samples, seconds)
|
|
||||||
writeFileSync(
|
|
||||||
`${output}/${iteration + 1}.json`,
|
|
||||||
JSON.stringify(run, null, 2),
|
|
||||||
)
|
|
||||||
const columns = [
|
|
||||||
'phase',
|
|
||||||
'role',
|
|
||||||
'time',
|
|
||||||
'pid',
|
|
||||||
'start',
|
|
||||||
'cpu',
|
|
||||||
'percent',
|
|
||||||
'rss',
|
|
||||||
]
|
|
||||||
writeFileSync(
|
|
||||||
`${output}/${iteration + 1}.csv`,
|
|
||||||
[
|
|
||||||
columns.join(','),
|
|
||||||
...run.samples.map((r) =>
|
|
||||||
columns.map((c) => r[c] ?? 'unavailable').join(','),
|
|
||||||
),
|
|
||||||
].join('\n'),
|
|
||||||
)
|
|
||||||
writeFileSync(`${output}/summary.json`, JSON.stringify(report, null, 2))
|
|
||||||
writeFileSync(`${output}/report.md`, markdown(report))
|
|
||||||
}
|
|
||||||
console.log(`Run ${iteration + 1}: ${run.ok ? 'passed' : run.error}`)
|
|
||||||
}
|
|
||||||
console.log(`Reports: ${output}`)
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
#include <libproc.h>
|
|
||||||
#include <mach/mach_time.h>
|
|
||||||
#include <stdio.h>
|
|
||||||
#include <stdlib.h>
|
|
||||||
#include <sys/resource.h>
|
|
||||||
|
|
||||||
int main(int argc, char **argv) {
|
|
||||||
mach_timebase_info_data_t timebase;
|
|
||||||
if (mach_timebase_info(&timebase) != KERN_SUCCESS) return 1;
|
|
||||||
for (int i = 1; i < argc; i++) {
|
|
||||||
int pid = atoi(argv[i]);
|
|
||||||
struct rusage_info_v0 r;
|
|
||||||
char path[PROC_PIDPATHINFO_MAXSIZE];
|
|
||||||
if (pid <= 0 || proc_pid_rusage(pid, RUSAGE_INFO_V0, (rusage_info_t *)&r)) return 1;
|
|
||||||
if (proc_pidpath(pid, path, sizeof(path)) <= 0) return 1;
|
|
||||||
printf("%d %llu %.9f %llu %s\n", pid, r.ri_proc_start_abstime,
|
|
||||||
((double)r.ri_user_time + r.ri_system_time) * timebase.numer / timebase.denom / 1e9, r.ri_resident_size, path);
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import { ThemeProvider, createTheme } from '@mui/material'
|
||||||
|
import dayjs from 'dayjs'
|
||||||
|
import relativeTime from 'dayjs/plugin/relativeTime'
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { createRoot } from 'react-dom/client'
|
||||||
|
import { SWRConfig } from 'swr'
|
||||||
|
|
||||||
|
import { VirtualList } from '../../src/components/base/virtual-list'
|
||||||
|
import { ConnectionRowItem } from '../../src/components/connection/connection-row-item'
|
||||||
|
import { useConnectionRowViews } from '../../src/components/connection/connection-row-view'
|
||||||
|
import LogItem from '../../src/components/log/log-item'
|
||||||
|
import { initializeLanguage } from '../../src/services/i18n'
|
||||||
|
import { setPreloadConfig } from '../../src/services/preload'
|
||||||
|
|
||||||
|
import { layer, scenario, subscribe } from './replay'
|
||||||
|
import '../../src/assets/styles/page.scss'
|
||||||
|
|
||||||
|
const searchState = {
|
||||||
|
text: '',
|
||||||
|
matchCase: false,
|
||||||
|
matchWholeWord: false,
|
||||||
|
useRegularExpression: false,
|
||||||
|
}
|
||||||
|
export function Components() {
|
||||||
|
const [logs, setLogs] = useState<ILogItem[]>([])
|
||||||
|
const [connections, setConnections] = useState<IConnectionsItem[]>([])
|
||||||
|
useEffect(
|
||||||
|
() =>
|
||||||
|
subscribe(({ payload }) => {
|
||||||
|
if (scenario === 'logs')
|
||||||
|
setLogs((previous) =>
|
||||||
|
previous.concat(payload as ILogItem[]).slice(-1000),
|
||||||
|
)
|
||||||
|
else setConnections((payload as IConnections).connections)
|
||||||
|
}),
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
const rows = useConnectionRowViews(connections)
|
||||||
|
return (
|
||||||
|
<VirtualList
|
||||||
|
count={scenario === 'logs' ? logs.length : rows.length}
|
||||||
|
estimateSize={scenario === 'logs' ? 50 : 56}
|
||||||
|
style={{ height: 640, margin: 24 }}
|
||||||
|
renderItem={(index) =>
|
||||||
|
scenario === 'logs' ? (
|
||||||
|
<LogItem
|
||||||
|
value={logs[logs.length - 1 - index]}
|
||||||
|
searchState={searchState}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<ConnectionRowItem
|
||||||
|
row={rows[index]}
|
||||||
|
closed={false}
|
||||||
|
onShowDetail={() => {}}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
dayjs.extend(relativeTime)
|
||||||
|
const root = document.getElementById('root')!
|
||||||
|
setPreloadConfig({
|
||||||
|
language: 'en',
|
||||||
|
theme_mode: 'light',
|
||||||
|
pause_render_traffic_stats_on_blur: false,
|
||||||
|
} as IVergeConfig)
|
||||||
|
await initializeLanguage('en')
|
||||||
|
const Scene =
|
||||||
|
layer === 'component'
|
||||||
|
? Components
|
||||||
|
: scenario === 'logs'
|
||||||
|
? (await import('../../src/pages/logs')).default
|
||||||
|
: (await import('../../src/pages/connections')).default
|
||||||
|
createRoot(root).render(
|
||||||
|
<SWRConfig value={{ revalidateOnFocus: false, revalidateOnReconnect: false }}>
|
||||||
|
<ThemeProvider theme={createTheme()}>
|
||||||
|
<Scene />
|
||||||
|
</ThemeProvider>
|
||||||
|
</SWRConfig>,
|
||||||
|
)
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { ThemeProvider, createTheme } from '@mui/material'
|
||||||
|
import { useEffect } from 'react'
|
||||||
|
import { createRoot } from 'react-dom/client'
|
||||||
|
import { SWRConfig } from 'swr'
|
||||||
|
|
||||||
|
import { EnhancedCanvasTrafficGraph } from '../../src/components/home/enhanced-canvas-traffic-graph'
|
||||||
|
import { useTrafficMonitorEnhanced } from '../../src/hooks/use-traffic-monitor'
|
||||||
|
import { initializeLanguage } from '../../src/services/i18n'
|
||||||
|
import { setPreloadConfig } from '../../src/services/preload'
|
||||||
|
|
||||||
|
setPreloadConfig({
|
||||||
|
pause_render_traffic_stats_on_blur: false,
|
||||||
|
} as IVergeConfig)
|
||||||
|
await initializeLanguage('en')
|
||||||
|
export function Replay() {
|
||||||
|
const {
|
||||||
|
graphData: { appendData },
|
||||||
|
} = useTrafficMonitorEnhanced({ subscribe: false })
|
||||||
|
useEffect(() => {
|
||||||
|
let received = 0,
|
||||||
|
previous = 0,
|
||||||
|
gaps = 0
|
||||||
|
const socket = new WebSocket(
|
||||||
|
`ws://127.0.0.1:${new URLSearchParams(location.search).get('port')}`,
|
||||||
|
)
|
||||||
|
socket.onmessage = ({ data }) => {
|
||||||
|
const point = JSON.parse(data)
|
||||||
|
appendData(point)
|
||||||
|
if (previous && point.sequence !== previous + 1) gaps++
|
||||||
|
previous = point.sequence
|
||||||
|
document.documentElement.dataset.perfReceived = String(++received)
|
||||||
|
document.documentElement.dataset.perfGaps = String(gaps)
|
||||||
|
document.documentElement.dataset.perfSourceTime = String(point.timestamp)
|
||||||
|
}
|
||||||
|
return () => socket.close()
|
||||||
|
}, [appendData])
|
||||||
|
return (
|
||||||
|
<main
|
||||||
|
aria-label="Home traffic graph replay"
|
||||||
|
style={{ width: 920, height: 360, margin: 32 }}
|
||||||
|
>
|
||||||
|
<EnhancedCanvasTrafficGraph />
|
||||||
|
</main>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
createRoot(document.getElementById('root')!).render(
|
||||||
|
<SWRConfig value={{ revalidateOnFocus: false, revalidateOnReconnect: false }}>
|
||||||
|
<ThemeProvider theme={createTheme()}>
|
||||||
|
<Replay />
|
||||||
|
</ThemeProvider>
|
||||||
|
</SWRConfig>,
|
||||||
|
)
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
{
|
{
|
||||||
"extends": "../../tsconfig.json",
|
"extends": "../../tsconfig.json",
|
||||||
"include": ["../../src", "./*.tsx"]
|
"include": ["../../src", "./*.tsx", "./*.ts"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { spawnSync } from 'node:child_process'
|
||||||
|
import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'
|
||||||
|
import { parseArgs } from 'node:util'
|
||||||
|
|
||||||
|
const { values } = parseArgs({
|
||||||
|
options: {
|
||||||
|
'dry-run': { type: 'boolean', default: false },
|
||||||
|
check: { type: 'boolean', default: false },
|
||||||
|
version: { type: 'string' },
|
||||||
|
file: { type: 'string', default: 'Changelog.md' },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
let version = values.version
|
||||||
|
if (!version) {
|
||||||
|
const response = await fetch(
|
||||||
|
'https://github.com/MetaCubeX/mihomo/releases/latest/download/version.txt',
|
||||||
|
{ signal: AbortSignal.timeout(30_000) },
|
||||||
|
)
|
||||||
|
if (!response.ok)
|
||||||
|
throw new Error(`Failed to fetch Mihomo version: ${response.status}`)
|
||||||
|
version = await response.text()
|
||||||
|
}
|
||||||
|
version = version.trim().replace(/^v?/, 'v')
|
||||||
|
if (!/^v\d+\.\d+\.\d+$/.test(version))
|
||||||
|
throw new Error(`Invalid stable Mihomo version: ${version}`)
|
||||||
|
|
||||||
|
const content = readFileSync(values.file, 'utf8')
|
||||||
|
const title = /^## .+$/m.exec(content)
|
||||||
|
if (!title) throw new Error('Could not find changelog title.')
|
||||||
|
const start = title.index + title[0].length
|
||||||
|
const end = content.indexOf('\n## ', start)
|
||||||
|
const section = content.slice(start, end === -1 ? undefined : end)
|
||||||
|
const line =
|
||||||
|
/^(\s*-\s*(?:\*\*)?\s*Mihomo(?:\(Meta\))?\s*内核升级至\s*)v?\d+(?:\.\d+)+(?:[-+][^\s*]+)?((?:\*\*)?[\t ]*)$/m
|
||||||
|
const nextSection = line.test(section)
|
||||||
|
? section.replace(line, `$1${version}$2`)
|
||||||
|
: `\n\n- **Mihomo 内核升级至 ${version}**${section.replace(/^\n*/, '\n\n')}`
|
||||||
|
const nextContent =
|
||||||
|
content.slice(0, start) +
|
||||||
|
nextSection +
|
||||||
|
(end === -1 ? '' : content.slice(end))
|
||||||
|
const changed = content !== nextContent
|
||||||
|
|
||||||
|
if (process.env.GITHUB_OUTPUT)
|
||||||
|
appendFileSync(
|
||||||
|
process.env.GITHUB_OUTPUT,
|
||||||
|
`version=${version}\nchanged=${changed}\n`,
|
||||||
|
)
|
||||||
|
if (!changed) {
|
||||||
|
console.log(`Mihomo version in changelog is already ${version}`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const diff = spawnSync(
|
||||||
|
'diff',
|
||||||
|
[
|
||||||
|
'-u',
|
||||||
|
'--label',
|
||||||
|
`a/${values.file}`,
|
||||||
|
'--label',
|
||||||
|
`b/${values.file}`,
|
||||||
|
values.file,
|
||||||
|
'-',
|
||||||
|
],
|
||||||
|
{ input: nextContent, encoding: 'utf8' },
|
||||||
|
)
|
||||||
|
if (diff.error) throw diff.error
|
||||||
|
if (diff.status !== 1)
|
||||||
|
throw new Error(diff.stderr || 'Could not preview changelog diff.')
|
||||||
|
process.stdout.write(diff.stdout)
|
||||||
|
if (process.env.GITHUB_STEP_SUMMARY)
|
||||||
|
appendFileSync(
|
||||||
|
process.env.GITHUB_STEP_SUMMARY,
|
||||||
|
`### Mihomo ${version}\n\n\`\`\`diff\n${diff.stdout}\`\`\`\n`,
|
||||||
|
)
|
||||||
|
if (values.check) {
|
||||||
|
process.exitCode = 1
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!values['dry-run']) writeFileSync(values.file, nextContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((error) => {
|
||||||
|
console.error('sync-mihomo-version failed:', error.message)
|
||||||
|
process.exitCode = 1
|
||||||
|
})
|
||||||
+11
-12
@@ -8,7 +8,7 @@ repository = "https://github.com/clash-verge-rev/clash-verge-rev.git"
|
|||||||
default-run = "clash-verge"
|
default-run = "clash-verge"
|
||||||
build = "build.rs"
|
build = "build.rs"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
rust-version = "1.99"
|
rust-version = "1.100"
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "app_lib"
|
name = "app_lib"
|
||||||
@@ -56,7 +56,7 @@ serde_json = { workspace = true }
|
|||||||
serde_yaml_ng = { workspace = true }
|
serde_yaml_ng = { workspace = true }
|
||||||
smartstring = { workspace = true, features = ["serde"] }
|
smartstring = { workspace = true, features = ["serde"] }
|
||||||
socket2 = { workspace = true }
|
socket2 = { workspace = true }
|
||||||
warp = { version = "0.4.3", features = ["server"] }
|
warp = { version = "0.4.4", features = ["server"] }
|
||||||
open = "5.4.5"
|
open = "5.4.5"
|
||||||
rfd = { version = "0.18.0", default-features = false, features = ["common-controls-v6", "xdg-portal"] }
|
rfd = { version = "0.18.0", default-features = false, features = ["common-controls-v6", "xdg-portal"] }
|
||||||
dirs = "7.0.0"
|
dirs = "7.0.0"
|
||||||
@@ -67,17 +67,17 @@ boa_engine = "0.22.0"
|
|||||||
http-body-util = "0.1.5"
|
http-body-util = "0.1.5"
|
||||||
percent-encoding = "2.3.2"
|
percent-encoding = "2.3.2"
|
||||||
reqwest = { workspace = true }
|
reqwest = { workspace = true }
|
||||||
sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs.git", branch = "main", features = [
|
sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs.git", rev = "2c9d0a538052aac6e44ad413156a6e848da262b9", version = "0.7.2", features = [
|
||||||
"guard",
|
"guard",
|
||||||
] }
|
] }
|
||||||
network-interface = { version = "2.0.5", features = ["serde"] }
|
network-interface = { version = "2.0.5", features = ["serde"] }
|
||||||
tauri-plugin-shell = "2.6.0"
|
tauri-plugin-shell = "2.6.0"
|
||||||
tauri-plugin-opener = "2.7.2"
|
tauri-plugin-opener = "2.7.3"
|
||||||
tauri-plugin-dialog = "2.8.4"
|
tauri-plugin-dialog = "2.8.4"
|
||||||
tauri-plugin-fs = "2.7.1"
|
tauri-plugin-fs = "2.7.1"
|
||||||
tauri-plugin-deep-link = "2.6.3"
|
tauri-plugin-deep-link = "2.6.3"
|
||||||
tauri-plugin-window-state = "2.5.0"
|
tauri-plugin-window-state = "2.5.0"
|
||||||
zip = "9.5.0"
|
zip = "9.6.0"
|
||||||
flate2 = "1.1.11"
|
flate2 = "1.1.11"
|
||||||
reqwest_dav = "0.3.3"
|
reqwest_dav = "0.3.3"
|
||||||
aes-gcm = { version = "0.11.1" }
|
aes-gcm = { version = "0.11.1" }
|
||||||
@@ -86,21 +86,20 @@ sha2 = "0.11.1"
|
|||||||
getrandom = "0.4.3"
|
getrandom = "0.4.3"
|
||||||
futures = "0.3.34"
|
futures = "0.3.34"
|
||||||
gethostname = "1.1.0"
|
gethostname = "1.1.0"
|
||||||
scopeguard = "1.2.0"
|
tauri-plugin-notification = "2.8.1"
|
||||||
tauri-plugin-notification = "2.8.0"
|
|
||||||
backon = { version = "1.6.0", features = ["tokio-sleep"] }
|
backon = { version = "1.6.0", features = ["tokio-sleep"] }
|
||||||
tauri-plugin-http = "2.8.3"
|
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 = "7a03d16f4d39b1bb885b7babe66b9e153e34b615" }
|
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "e49bbedcc67d60da2c10e81bc6433b0f8e8fa232" }
|
||||||
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.7.7", version = "2.7.7", 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",
|
||||||
] }
|
] }
|
||||||
arc-swap = "1.9.5"
|
arc-swap = "1.9.5"
|
||||||
tokio-rustls = "0.26.6"
|
tokio-rustls = "0.26.6"
|
||||||
rustls = { version = "0.23.46", features = ["ring"] }
|
rustls = { version = "0.23.46", features = ["ring"] }
|
||||||
webpki-roots = "1.0.11"
|
webpki-roots = "1.0.12"
|
||||||
dark-light = "3.0.0"
|
dark-light = "3.0.0"
|
||||||
bytes = "1.12.1"
|
bytes = "1.12.1"
|
||||||
tokio-util = { version = "0.7.20", features = ["time"] }
|
tokio-util = { version = "0.7.20", features = ["time"] }
|
||||||
@@ -154,7 +153,7 @@ tauri-plugin-updater = "2.14.1"
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tokio = { workspace = true, features = ["test-util"] }
|
tokio = { workspace = true, features = ["test-util"] }
|
||||||
warp = { version = "0.4.3", features = ["test"] }
|
warp = { version = "0.4.4", features = ["test"] }
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
|
|||||||
@@ -17,6 +17,8 @@
|
|||||||
"autostart:allow-disable",
|
"autostart:allow-disable",
|
||||||
"autostart:allow-is-enabled",
|
"autostart:allow-is-enabled",
|
||||||
"core:window:allow-set-theme",
|
"core:window:allow-set-theme",
|
||||||
|
"core:window:allow-set-background-color",
|
||||||
|
"core:webview:allow-set-webview-background-color",
|
||||||
"notification:default",
|
"notification:default",
|
||||||
"http:default",
|
"http:default",
|
||||||
"http:allow-fetch",
|
"http:allow-fetch",
|
||||||
|
|||||||
@@ -2,10 +2,10 @@
|
|||||||
// bundles (PR #8131), so this generator must stay an example, never a bin.
|
// bundles (PR #8131), so this generator must stay an example, never a bin.
|
||||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let mut args = std::env::args_os().skip(1);
|
let mut args = std::env::args_os().skip(1);
|
||||||
let output = args
|
let output = args.next().map_or_else(
|
||||||
.next()
|
|| std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../src/services/bindings.ts"),
|
||||||
.map(std::path::PathBuf::from)
|
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() {
|
if args.next().is_some() {
|
||||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "expected at most one output path").into());
|
return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "expected at most one output path").into());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,9 +18,11 @@ use crate::{
|
|||||||
};
|
};
|
||||||
use clash_verge_draft::{Draft, SharedDraft};
|
use clash_verge_draft::{Draft, SharedDraft};
|
||||||
use clash_verge_logging::{Type, logging, logging_error};
|
use clash_verge_logging::{Type, logging, logging_error};
|
||||||
use scopeguard::defer;
|
|
||||||
use smartstring::alias::String;
|
use smartstring::alias::String;
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::{
|
||||||
|
mem::DropGuard,
|
||||||
|
sync::atomic::{AtomicBool, Ordering},
|
||||||
|
};
|
||||||
|
|
||||||
static CURRENT_SWITCHING_PROFILE: AtomicBool = AtomicBool::new(false);
|
static CURRENT_SWITCHING_PROFILE: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
@@ -208,10 +210,10 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> {
|
async fn restore_previous_profile(prev_profile: &str) -> CmdResult<()> {
|
||||||
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
|
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
|
||||||
let restore_profiles = IProfiles {
|
let restore_profiles = IProfiles {
|
||||||
current: Some(prev_profile.to_owned()),
|
current: Some(prev_profile.into()),
|
||||||
items: None,
|
items: None,
|
||||||
};
|
};
|
||||||
Config::profiles()
|
Config::profiles()
|
||||||
@@ -400,9 +402,9 @@ pub async fn patch_profiles_config(profiles: ProfileSelection) -> CmdResult<Vali
|
|||||||
logging!(info, Type::Cmd, "当前正在切换配置,放弃请求");
|
logging!(info, Type::Cmd, "当前正在切换配置,放弃请求");
|
||||||
return Ok(ValidationOutcome::Busy);
|
return Ok(ValidationOutcome::Busy);
|
||||||
}
|
}
|
||||||
defer! {
|
let _switching_profile = DropGuard::new((), |()| {
|
||||||
CURRENT_SWITCHING_PROFILE.store(false, Ordering::Release);
|
CURRENT_SWITCHING_PROFILE.store(false, Ordering::Release);
|
||||||
}
|
});
|
||||||
let _profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
|
let _profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
|
||||||
|
|
||||||
let profiles = IProfiles {
|
let profiles = IProfiles {
|
||||||
|
|||||||
@@ -83,8 +83,7 @@ fn runtime_group_scopes(config: Option<&Mapping>) -> BTreeMap<String, GroupScope
|
|||||||
.get("exclude-type")
|
.get("exclude-type")
|
||||||
.and_then(|types| types.as_str())
|
.and_then(|types| types.as_str())
|
||||||
.filter(|types| !types.is_empty())
|
.filter(|types| !types.is_empty())
|
||||||
.map(|types| types.split('|').map(str::to_owned).collect())
|
.map_or_default(|types| types.split('|').map(str::to_owned).collect());
|
||||||
.unwrap_or_default();
|
|
||||||
Some((
|
Some((
|
||||||
name,
|
name,
|
||||||
GroupScope {
|
GroupScope {
|
||||||
|
|||||||
@@ -191,7 +191,7 @@ impl Config {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let error_msg = config_result.err().map(|err| err.to_string()).unwrap_or_default();
|
let error_msg = config_result.err().map_or_default(|err| err.to_string());
|
||||||
logging!(warn, Type::Config, "生成配置文件失败,使用默认配置: {error_msg}");
|
logging!(warn, Type::Config, "生成配置文件失败,使用默认配置: {error_msg}");
|
||||||
CoreManager::global()
|
CoreManager::global()
|
||||||
.use_default_config(NoticeStatus::ConfigValidateError, "")
|
.use_default_config(NoticeStatus::ConfigValidateError, "")
|
||||||
@@ -216,7 +216,7 @@ impl Config {
|
|||||||
.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 yaml_str = serde_yaml_ng::to_string(config)?;
|
||||||
Ok(format!("# Generated by Clash Verge\n\n{}", yaml_str))
|
Ok(yaml_str)
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.map_err(|join| anyhow!("runtime serialization task failed: {join}"))?
|
.map_err(|join| anyhow!("runtime serialization task failed: {join}"))?
|
||||||
@@ -224,7 +224,7 @@ impl Config {
|
|||||||
|
|
||||||
pub(crate) async fn write_runtime_file(yaml: &str) -> Result<PathBuf> {
|
pub(crate) async fn write_runtime_file(yaml: &str) -> Result<PathBuf> {
|
||||||
let path = dirs::app_home_dir()?.join(files::RUNTIME_CONFIG);
|
let path = dirs::app_home_dir()?.join(files::RUNTIME_CONFIG);
|
||||||
help::save_yaml_str(&path, yaml).await?;
|
help::save_yaml_str(&path, yaml, Some("# Generated by Clash Verge")).await?;
|
||||||
Ok(path)
|
Ok(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use crate::core::notify::NoticeStatus;
|
use crate::core::notify::NoticeStatus;
|
||||||
|
use crate::utils::help;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use clash_verge_draft::DraftTransaction;
|
use clash_verge_draft::DraftTransaction;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -49,9 +50,7 @@ pub(crate) fn dns_override_source(profile_uid: &str, config: &Mapping) -> Result
|
|||||||
digest.update(profile_uid.as_bytes());
|
digest.update(profile_uid.as_bytes());
|
||||||
digest.update([0]);
|
digest.update([0]);
|
||||||
digest.update(serde_json::to_vec(&canonical)?);
|
digest.update(serde_json::to_vec(&canonical)?);
|
||||||
Ok(Some(
|
Ok(Some(help::hex_encode(&digest.finalize()).into()))
|
||||||
digest.finalize().iter().map(|byte| format!("{byte:02x}")).collect(),
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ pub(super) fn normalize_profile_home_url(raw: &str) -> Option<String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
url.host_str()?;
|
url.host_str()?;
|
||||||
Some(url.to_string().into())
|
Some(url.as_str().into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)]
|
#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)]
|
||||||
@@ -371,9 +371,10 @@ impl PrfItem {
|
|||||||
|
|
||||||
let uid = help::get_uid("R").into();
|
let uid = help::get_uid("R").into();
|
||||||
let file = format!("{uid}.yaml").into();
|
let file = format!("{uid}.yaml").into();
|
||||||
let name = name
|
let name = name.map_or_else(
|
||||||
.map(|s| s.to_owned())
|
|| filename.map_or_else(|| "Remote File".into(), |s| s.into()),
|
||||||
.unwrap_or_else(|| filename.map(|s| s.into()).unwrap_or_else(|| "Remote File".into()));
|
|s| s.to_owned(),
|
||||||
|
);
|
||||||
let data = resp.text();
|
let data = resp.text();
|
||||||
|
|
||||||
let data = data.trim_start_matches('\u{feff}');
|
let data = data.trim_start_matches('\u{feff}');
|
||||||
|
|||||||
@@ -605,7 +605,7 @@ async fn fetch_proxies_with_timeout() -> Result<Proxies> {
|
|||||||
.map_err(Into::into)
|
.map_err(Into::into)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn select_node_with_timeout(group_name: &String, node: &String) -> Result<()> {
|
async fn select_node_with_timeout(group_name: &str, node: &str) -> Result<()> {
|
||||||
tokio::time::timeout(MIHOMO_OPERATION_TIMEOUT, async {
|
tokio::time::timeout(MIHOMO_OPERATION_TIMEOUT, async {
|
||||||
handle::Handle::mihomo().select_node_for_group(group_name, node).await
|
handle::Handle::mihomo().select_node_for_group(group_name, node).await
|
||||||
})
|
})
|
||||||
@@ -761,7 +761,7 @@ pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result
|
|||||||
return Ok((profiles, false));
|
return Ok((profiles, false));
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut selected = item.selected.clone().unwrap_or_default();
|
let selected = item.selected.get_or_insert_with(Vec::new);
|
||||||
match selected
|
match selected
|
||||||
.iter_mut()
|
.iter_mut()
|
||||||
.find(|entry| entry.name.as_ref() == Some(&group_name))
|
.find(|entry| entry.name.as_ref() == Some(&group_name))
|
||||||
@@ -770,14 +770,13 @@ pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result
|
|||||||
if entry.now.as_ref() == Some(&node) {
|
if entry.now.as_ref() == Some(&node) {
|
||||||
return Ok((profiles, false));
|
return Ok((profiles, false));
|
||||||
}
|
}
|
||||||
entry.now = Some(node);
|
entry.now = Some(node.clone());
|
||||||
}
|
}
|
||||||
None => selected.push(PrfSelected {
|
None => selected.push(PrfSelected {
|
||||||
name: Some(group_name),
|
name: Some(group_name),
|
||||||
now: Some(node),
|
now: Some(node),
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
item.selected = Some(selected);
|
|
||||||
profiles.save_file().await?;
|
profiles.save_file().await?;
|
||||||
Ok((profiles, true))
|
Ok((profiles, true))
|
||||||
})
|
})
|
||||||
@@ -796,12 +795,17 @@ pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
|
|||||||
return Ok((profiles, false));
|
return Ok((profiles, false));
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut selected = item.selected.clone().unwrap_or_default();
|
let Some(mut selected) = item.selected.take() else {
|
||||||
|
return Ok((profiles, false));
|
||||||
|
};
|
||||||
if !remove_selected_node(&mut selected, group_name) {
|
if !remove_selected_node(&mut selected, group_name) {
|
||||||
|
item.selected = Some(selected);
|
||||||
return Ok((profiles, false));
|
return Ok((profiles, false));
|
||||||
}
|
}
|
||||||
|
|
||||||
item.selected = (!selected.is_empty()).then_some(selected);
|
if !selected.is_empty() {
|
||||||
|
item.selected = Some(selected);
|
||||||
|
}
|
||||||
profiles.save_file().await?;
|
profiles.save_file().await?;
|
||||||
Ok((profiles, true))
|
Ok((profiles, true))
|
||||||
})
|
})
|
||||||
@@ -809,7 +813,7 @@ pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn persist_reconciled_selected(
|
async fn persist_reconciled_selected(
|
||||||
profile_uid: &String,
|
profile_uid: &str,
|
||||||
original_selected: &[PrfSelected],
|
original_selected: &[PrfSelected],
|
||||||
selected: Vec<PrfSelected>,
|
selected: Vec<PrfSelected>,
|
||||||
generation: u64,
|
generation: u64,
|
||||||
@@ -818,7 +822,7 @@ async fn persist_reconciled_selected(
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
let profile_uid = profile_uid.clone();
|
let profile_uid = String::from(profile_uid);
|
||||||
let original_selected = original_selected.to_vec();
|
let original_selected = original_selected.to_vec();
|
||||||
persist_selected_update(false, move |mut profiles| async move {
|
persist_selected_update(false, move |mut profiles| async move {
|
||||||
if !is_activation_current(generation) || profiles.current.as_ref() != Some(&profile_uid) {
|
if !is_activation_current(generation) || profiles.current.as_ref() != Some(&profile_uid) {
|
||||||
|
|||||||
@@ -70,6 +70,8 @@ pub mod files {
|
|||||||
pub mod tun {
|
pub mod tun {
|
||||||
pub const DEFAULT_STACK: &str = "mips";
|
pub const DEFAULT_STACK: &str = "mips";
|
||||||
|
|
||||||
|
pub const DEFAULT_MTU: u16 = 1500;
|
||||||
|
|
||||||
pub const DNS_HIJACK: &[&str] = &["any:53"];
|
pub const DNS_HIJACK: &[&str] = &["any:53"];
|
||||||
|
|
||||||
/// Saved dialog fields; `enable` belongs to the verge switch.
|
/// Saved dialog fields; `enable` belongs to the verge switch.
|
||||||
|
|||||||
@@ -279,8 +279,7 @@ async fn cleanup_auto_backups() -> Result<()> {
|
|||||||
.and_then(|meta| meta.modified())
|
.and_then(|meta| meta.modified())
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
|
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
|
||||||
.map(|dur| dur.as_secs())
|
.map_or(0, |dur| dur.as_secs());
|
||||||
.unwrap_or(0);
|
|
||||||
|
|
||||||
files.push((path, modified));
|
files.push((path, modified));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -539,18 +539,16 @@ fn bind_socket(claim: &BindClaim) -> io::Result<Socket> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn is_bind_conflict(error: &io::Error) -> bool {
|
fn is_bind_conflict(error: &io::Error) -> bool {
|
||||||
if error.kind() == io::ErrorKind::AddrInUse {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
{
|
{
|
||||||
use windows_sys::Win32::Networking::WinSock::WSAEACCES;
|
use windows_sys::Win32::Networking::WinSock::WSAEACCES;
|
||||||
|
|
||||||
error.raw_os_error() == Some(WSAEACCES)
|
error.kind() == io::ErrorKind::AddrInUse || error.raw_os_error() == Some(WSAEACCES)
|
||||||
}
|
}
|
||||||
#[cfg(not(windows))]
|
#[cfg(not(windows))]
|
||||||
false
|
{
|
||||||
|
error.kind() == io::ErrorKind::AddrInUse
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
|
|||||||
@@ -14,10 +14,10 @@ use anyhow::{Result, anyhow};
|
|||||||
use clash_verge_draft::DraftTransaction;
|
use clash_verge_draft::DraftTransaction;
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use clash_verge_service_ipc::StageRuntimeOutcome;
|
use clash_verge_service_ipc::StageRuntimeOutcome;
|
||||||
use scopeguard::defer;
|
|
||||||
use smartstring::alias::String;
|
use smartstring::alias::String;
|
||||||
use std::{
|
use std::{
|
||||||
collections::HashSet,
|
collections::HashSet,
|
||||||
|
mem::DropGuard,
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
sync::Arc,
|
sync::Arc,
|
||||||
time::{Duration, Instant},
|
time::{Duration, Instant},
|
||||||
@@ -191,9 +191,9 @@ impl CoreManager {
|
|||||||
logging!(debug, Type::Core, "Configuration update is already running");
|
logging!(debug, Type::Core, "Configuration update is already running");
|
||||||
return Ok(ValidationOutcome::Busy);
|
return Ok(ValidationOutcome::Busy);
|
||||||
}
|
}
|
||||||
defer! {
|
let _config_update = DropGuard::new((), |()| {
|
||||||
self.finish_config_update();
|
self.finish_config_update();
|
||||||
}
|
});
|
||||||
|
|
||||||
if !force && !self.should_update_config() {
|
if !force && !self.should_update_config() {
|
||||||
logging!(debug, Type::Core, "Skipping config update due to debounce");
|
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");
|
logging!(debug, Type::Core, "Configuration update is already running");
|
||||||
return Ok(ValidationOutcome::Busy);
|
return Ok(ValidationOutcome::Busy);
|
||||||
}
|
}
|
||||||
defer! {
|
let _config_update = DropGuard::new((), |()| {
|
||||||
self.finish_config_update();
|
self.finish_config_update();
|
||||||
}
|
});
|
||||||
|
|
||||||
let runtime = Config::runtime().await;
|
let runtime = Config::runtime().await;
|
||||||
let transaction = DraftTransaction::begin(vec![&runtime])?;
|
let transaction = DraftTransaction::begin(vec![&runtime])?;
|
||||||
|
|||||||
@@ -6,9 +6,8 @@ use crate::core::proxy_control::{self, SysproxyFailure};
|
|||||||
use crate::core::service::{SERVICE_MANAGER, ServiceStatus};
|
use crate::core::service::{SERVICE_MANAGER, ServiceStatus};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use scopeguard::defer;
|
|
||||||
use smartstring::alias::String;
|
use smartstring::alias::String;
|
||||||
use std::path::Path;
|
use std::{mem::DropGuard, path::Path};
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
use tauri_plugin_clash_verge_sysinfo::is_current_app_handle_admin;
|
use tauri_plugin_clash_verge_sysinfo::is_current_app_handle_admin;
|
||||||
|
|
||||||
@@ -356,9 +355,9 @@ impl CoreManager {
|
|||||||
if !self.try_start_config_update() {
|
if !self.try_start_config_update() {
|
||||||
anyhow::bail!("configuration update is already running");
|
anyhow::bail!("configuration update is already running");
|
||||||
}
|
}
|
||||||
defer! {
|
let _config_update = DropGuard::new((), |()| {
|
||||||
self.finish_config_update();
|
self.finish_config_update();
|
||||||
}
|
});
|
||||||
self.start_core_during_config_update().await
|
self.start_core_during_config_update().await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -383,9 +382,9 @@ impl CoreManager {
|
|||||||
service_rejection,
|
service_rejection,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
defer! {
|
let _config_update = DropGuard::new((), |()| {
|
||||||
self.finish_config_update();
|
self.finish_config_update();
|
||||||
}
|
});
|
||||||
// Lock order is config then lifecycle. disable_tun_and_persist commits the shared Verge
|
// 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.
|
// draft without claiming it, so without this it can commit another transaction's staged patch.
|
||||||
let config_write = Config::lock_config_write().await;
|
let config_write = Config::lock_config_write().await;
|
||||||
@@ -463,9 +462,9 @@ impl CoreManager {
|
|||||||
if !self.try_start_config_update() {
|
if !self.try_start_config_update() {
|
||||||
anyhow::bail!("configuration update is already running");
|
anyhow::bail!("configuration update is already running");
|
||||||
}
|
}
|
||||||
defer! {
|
let _config_update = DropGuard::new((), |()| {
|
||||||
self.finish_config_update();
|
self.finish_config_update();
|
||||||
}
|
});
|
||||||
// Lock order is config then lifecycle, for the unclaimed draft write below.
|
// Lock order is config then lifecycle, for the unclaimed draft write below.
|
||||||
let _config_write = Config::lock_config_write().await;
|
let _config_write = Config::lock_config_write().await;
|
||||||
let _life = self.lifecycle_lock.lock().await;
|
let _life = self.lifecycle_lock.lock().await;
|
||||||
@@ -795,9 +794,9 @@ impl CoreManager {
|
|||||||
if !self.try_start_config_update() {
|
if !self.try_start_config_update() {
|
||||||
anyhow::bail!("configuration update is already running");
|
anyhow::bail!("configuration update is already running");
|
||||||
}
|
}
|
||||||
defer! {
|
let _config_update = DropGuard::new((), |()| {
|
||||||
self.finish_config_update();
|
self.finish_config_update();
|
||||||
}
|
});
|
||||||
self.restart_core_during_config_update().await
|
self.restart_core_during_config_update().await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -966,9 +965,9 @@ impl CoreManager {
|
|||||||
if !self.try_start_config_update() {
|
if !self.try_start_config_update() {
|
||||||
return HandoffOutcome::NotReady;
|
return HandoffOutcome::NotReady;
|
||||||
}
|
}
|
||||||
defer! {
|
let _config_update = DropGuard::new((), |()| {
|
||||||
self.finish_config_update();
|
self.finish_config_update();
|
||||||
}
|
});
|
||||||
|
|
||||||
// Lock order is config then lifecycle.
|
// Lock order is config then lifecycle.
|
||||||
let _life = self.lifecycle_lock.lock().await;
|
let _life = self.lifecycle_lock.lock().await;
|
||||||
|
|||||||
@@ -42,9 +42,12 @@ pub async fn notify_event<'a>(event: NotificationEvent<'a>) {
|
|||||||
}
|
}
|
||||||
NotificationEvent::ClashModeChanged { mode } => {
|
NotificationEvent::ClashModeChanged { mode } => {
|
||||||
let title = clash_verge_i18n::t!("notifications.clashModeChanged.title");
|
let title = clash_verge_i18n::t!("notifications.clashModeChanged.title");
|
||||||
let body = clash_verge_i18n::t!("notifications.clashModeChanged.body")
|
let body = clash_verge_i18n::t!("notifications.clashModeChanged.body");
|
||||||
.replace("{mode}", mode)
|
let body = if body.contains("{mode}") {
|
||||||
.into();
|
body.replace("{mode}", mode).into()
|
||||||
|
} else {
|
||||||
|
body
|
||||||
|
};
|
||||||
notify(title, body);
|
notify(title, body);
|
||||||
}
|
}
|
||||||
NotificationEvent::SystemProxyToggled(enabled) => {
|
NotificationEvent::SystemProxyToggled(enabled) => {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
use super::NoticeStatus;
|
use super::NoticeStatus;
|
||||||
use crate::{APP_HANDLE, singleton};
|
use crate::{APP_HANDLE, singleton};
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
use smartstring::alias::String;
|
use smartstring::alias::String;
|
||||||
use std::sync::{
|
use std::sync::{
|
||||||
Arc,
|
Arc,
|
||||||
@@ -55,21 +56,21 @@ impl Handle {
|
|||||||
Self::send_event(FrontendEvent::RunStateChanged { state: state.clone() });
|
Self::send_event(FrontendEvent::RunStateChanged { state: state.clone() });
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn notify_profile_changed(profile_id: &String) {
|
pub fn notify_profile_changed(profile_id: &str) {
|
||||||
Self::send_event(FrontendEvent::ProfileChanged {
|
Self::send_event(FrontendEvent::ProfileChanged {
|
||||||
current_profile_id: profile_id,
|
current_profile_id: profile_id,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn notify_timer_updated(profile_index: &String) {
|
pub fn notify_timer_updated(profile_index: &str) {
|
||||||
Self::send_event(FrontendEvent::TimerUpdated { profile_index });
|
Self::send_event(FrontendEvent::TimerUpdated { profile_index });
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn notify_profile_update_started(uid: &String) {
|
pub fn notify_profile_update_started(uid: &str) {
|
||||||
Self::send_event(FrontendEvent::ProfileUpdateStarted { uid });
|
Self::send_event(FrontendEvent::ProfileUpdateStarted { uid });
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn notify_profile_update_completed(uid: &String) {
|
pub fn notify_profile_update_completed(uid: &str) {
|
||||||
Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid });
|
Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,16 +20,16 @@ pub enum FrontendEvent<'a> {
|
|||||||
message: Arc<str>,
|
message: Arc<str>,
|
||||||
},
|
},
|
||||||
ProfileChanged {
|
ProfileChanged {
|
||||||
current_profile_id: &'a String,
|
current_profile_id: &'a str,
|
||||||
},
|
},
|
||||||
TimerUpdated {
|
TimerUpdated {
|
||||||
profile_index: &'a String,
|
profile_index: &'a str,
|
||||||
},
|
},
|
||||||
ProfileUpdateStarted {
|
ProfileUpdateStarted {
|
||||||
uid: &'a String,
|
uid: &'a str,
|
||||||
},
|
},
|
||||||
ProfileUpdateCompleted {
|
ProfileUpdateCompleted {
|
||||||
uid: &'a String,
|
uid: &'a str,
|
||||||
},
|
},
|
||||||
RunStateChanged {
|
RunStateChanged {
|
||||||
state: crate::core::runstate::RunStateView,
|
state: crate::core::runstate::RunStateView,
|
||||||
@@ -369,7 +369,7 @@ mod wire_tests {
|
|||||||
|
|
||||||
/// One sample per `FrontendEvent` variant, paired with its wire name and payload.
|
/// One sample per `FrontendEvent` variant, paired with its wire name and payload.
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
fn sample_frontend_events(uid: &String) -> Vec<(FrontendEvent<'_>, &'static str, serde_json::Value)> {
|
fn sample_frontend_events(uid: &str) -> Vec<(FrontendEvent<'_>, &'static str, serde_json::Value)> {
|
||||||
let state = crate::core::runstate::RunState {
|
let state = crate::core::runstate::RunState {
|
||||||
health: Default::default(),
|
health: Default::default(),
|
||||||
pending: None,
|
pending: None,
|
||||||
|
|||||||
@@ -331,9 +331,7 @@ fn build_provider_records(
|
|||||||
providers: Option<ProxyProviders>,
|
providers: Option<ProxyProviders>,
|
||||||
records: &mut BTreeMap<String, ProxyNodeView>,
|
records: &mut BTreeMap<String, ProxyNodeView>,
|
||||||
) -> (Vec<ProxyProviderView>, ProviderCandidates) {
|
) -> (Vec<ProxyProviderView>, ProviderCandidates) {
|
||||||
let providers = providers
|
let providers = providers.map_or_default(|providers| providers.providers.into_iter().collect::<BTreeMap<_, _>>());
|
||||||
.map(|providers| providers.providers.into_iter().collect::<BTreeMap<_, _>>())
|
|
||||||
.unwrap_or_default();
|
|
||||||
let mut views = Vec::new();
|
let mut views = Vec::new();
|
||||||
let mut candidates = BTreeMap::new();
|
let mut candidates = BTreeMap::new();
|
||||||
|
|
||||||
|
|||||||
@@ -122,12 +122,11 @@ fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut Ha
|
|||||||
digest.update(destination.as_bytes());
|
digest.update(destination.as_bytes());
|
||||||
digest.update([0]);
|
digest.update([0]);
|
||||||
digest.update(url.as_bytes());
|
digest.update(url.as_bytes());
|
||||||
let digest: String = digest.finalize().iter().map(|byte| format!("{byte:02x}")).collect();
|
let digest: String = crate::utils::help::hex_encode(&digest.finalize());
|
||||||
let path = Path::new(destination);
|
let path = Path::new(destination);
|
||||||
let extension = path
|
let extension = path
|
||||||
.extension()
|
.extension()
|
||||||
.map(|ext| format!(".{}", ext.to_string_lossy()))
|
.map_or_default(|ext| format!(".{}", ext.to_string_lossy()));
|
||||||
.unwrap_or_default();
|
|
||||||
let mut suffix = String::new();
|
let mut suffix = String::new();
|
||||||
let mut sequence = 0;
|
let mut sequence = 0;
|
||||||
loop {
|
loop {
|
||||||
|
|||||||
@@ -334,6 +334,12 @@ pub(crate) fn service_stop_reason() -> Result<Option<&'static str>> {
|
|||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
pub(crate) fn trusted_service_evidence() -> Result<bool> {
|
pub(crate) fn trusted_service_evidence() -> Result<bool> {
|
||||||
|
// Without systemd, the installer registers an OpenRC script instead of a unit.
|
||||||
|
if !Path::new("/run/systemd/system").exists() && Path::new("/run/openrc").exists() {
|
||||||
|
return Ok(Path::new("/etc/init.d")
|
||||||
|
.join(clash_verge_service_ipc::SERVICE_SLUG)
|
||||||
|
.exists());
|
||||||
|
}
|
||||||
let unit = format!("{}.service", clash_verge_service_ipc::SERVICE_SLUG);
|
let unit = format!("{}.service", clash_verge_service_ipc::SERVICE_SLUG);
|
||||||
let output = StdCommand::new("systemctl")
|
let output = StdCommand::new("systemctl")
|
||||||
.args(["show", "--property=LoadState", "--value", &unit])
|
.args(["show", "--property=LoadState", "--value", &unit])
|
||||||
@@ -1470,10 +1476,7 @@ async fn create_sync_temp(target: &Path) -> Result<(PathBuf, tokio::fs::File)> {
|
|||||||
.await
|
.await
|
||||||
.with_context(|| format!("failed to create provider cache directory {}", parent.display()))?;
|
.with_context(|| format!("failed to create provider cache directory {}", parent.display()))?;
|
||||||
}
|
}
|
||||||
let name = target
|
let name = target.file_name().map_or_default(|name| name.to_string_lossy());
|
||||||
.file_name()
|
|
||||||
.map(|name| name.to_string_lossy())
|
|
||||||
.unwrap_or_default();
|
|
||||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||||
retry(
|
retry(
|
||||||
RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(7), std::time::Duration::ZERO),
|
RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(7), std::time::Duration::ZERO),
|
||||||
|
|||||||
@@ -7,9 +7,9 @@ use crate::{
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use parking_lot::RwLock;
|
use parking_lot::RwLock;
|
||||||
use scopeguard::defer;
|
|
||||||
use smartstring::alias::String;
|
use smartstring::alias::String;
|
||||||
use std::{
|
use std::{
|
||||||
|
mem::DropGuard,
|
||||||
sync::{
|
sync::{
|
||||||
Arc,
|
Arc,
|
||||||
atomic::{AtomicBool, Ordering},
|
atomic::{AtomicBool, Ordering},
|
||||||
@@ -541,9 +541,9 @@ impl Sysopt {
|
|||||||
{
|
{
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
defer! {
|
let _reset_sysproxy = DropGuard::new((), |()| {
|
||||||
self.reset_sysproxy.store(false, Ordering::SeqCst);
|
self.reset_sysproxy.store(false, Ordering::SeqCst);
|
||||||
}
|
});
|
||||||
let mut proxy_state = self.proxy_state_lock.lock().await;
|
let mut proxy_state = self.proxy_state_lock.lock().await;
|
||||||
let _guard_operation = self.guard_operation_lock.lock().await;
|
let _guard_operation = self.guard_operation_lock.lock().await;
|
||||||
let drained = self.stop_proxy_guard_locked().await;
|
let drained = self.stop_proxy_guard_locked().await;
|
||||||
|
|||||||
@@ -458,7 +458,7 @@ impl Timer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn emit_update_event(uid: &String, is_start: bool) {
|
fn emit_update_event(uid: &str, is_start: bool) {
|
||||||
if is_start {
|
if is_start {
|
||||||
super::handle::Handle::notify_profile_update_started(uid);
|
super::handle::Handle::notify_profile_update_started(uid);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -210,8 +210,7 @@ impl Tray {
|
|||||||
.latest_arc()
|
.latest_arc()
|
||||||
.0
|
.0
|
||||||
.get("mode")
|
.get("mode")
|
||||||
.map(|val| val.as_str().unwrap_or("rule"))
|
.map_or("rule", |val| val.as_str().unwrap_or("rule"))
|
||||||
.unwrap_or("rule")
|
|
||||||
.to_owned()
|
.to_owned()
|
||||||
};
|
};
|
||||||
let profiles_config = Config::profiles().await;
|
let profiles_config = Config::profiles().await;
|
||||||
@@ -343,9 +342,6 @@ impl Tray {
|
|||||||
let verge = Config::verge().await.data_arc();
|
let verge = Config::verge().await.data_arc();
|
||||||
let app_handle = handle::Handle::app_handle();
|
let app_handle = handle::Handle::app_handle();
|
||||||
self.update_menu_internal(app_handle, false).await?;
|
self.update_menu_internal(app_handle, false).await?;
|
||||||
AsyncHandler::spawn(|| async {
|
|
||||||
logging_error!(Type::Tray, Self::global().update_menu().await);
|
|
||||||
});
|
|
||||||
self.update_icon(&verge).await?;
|
self.update_icon(&verge).await?;
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
self.update_speed_task(verge.enable_tray_speed.unwrap_or(false));
|
self.update_speed_task(verge.enable_tray_speed.unwrap_or(false));
|
||||||
@@ -414,26 +410,23 @@ impl Tray {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn create_hotkeys(hotkeys: &Option<Vec<String>>) -> HashMap<&str, &str> {
|
fn create_hotkeys(hotkeys: &Option<Vec<String>>) -> HashMap<&str, &str> {
|
||||||
hotkeys
|
hotkeys.as_ref().map_or_default(|h| {
|
||||||
.as_ref()
|
h.iter()
|
||||||
.map(|h| {
|
.filter_map(|item| {
|
||||||
h.iter()
|
let mut parts = item.split(',');
|
||||||
.filter_map(|item| {
|
match (parts.next(), parts.next()) {
|
||||||
let mut parts = item.split(',');
|
(Some(func), Some(key)) => {
|
||||||
match (parts.next(), parts.next()) {
|
// 托盘菜单的 `accelerator` 在 Linux/Windows 下不支持小键盘按键,Windows 下也不支持 Win 键(前端上报为 `CMD`)
|
||||||
(Some(func), Some(key)) => {
|
let uppercase_key = key.to_uppercase();
|
||||||
// 托盘菜单的 `accelerator` 在 Linux/Windows 下不支持小键盘按键,Windows 下也不支持 Win 键(前端上报为 `CMD`)
|
let unsupported =
|
||||||
let uppercase_key = key.to_uppercase();
|
uppercase_key.contains("NUMPAD") || (cfg!(windows) && uppercase_key.contains("CMD"));
|
||||||
let unsupported =
|
if unsupported { None } else { Some((func, key)) }
|
||||||
uppercase_key.contains("NUMPAD") || (cfg!(windows) && uppercase_key.contains("CMD"));
|
|
||||||
if unsupported { None } else { Some((func, key)) }
|
|
||||||
}
|
|
||||||
_ => None,
|
|
||||||
}
|
}
|
||||||
})
|
_ => None,
|
||||||
.collect::<HashMap<&str, &str>>()
|
}
|
||||||
})
|
})
|
||||||
.unwrap_or_default()
|
.collect::<HashMap<&str, &str>>()
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_profile_menu_item(
|
fn create_profile_menu_item(
|
||||||
@@ -493,12 +486,14 @@ fn create_subcreate_proxy_menu_item(
|
|||||||
.proxies
|
.proxies
|
||||||
.get(proxy_str)
|
.get(proxy_str)
|
||||||
.and_then(|h| h.history.last())
|
.and_then(|h| h.history.last())
|
||||||
.map(|h| match h.delay {
|
.map_or_else(
|
||||||
0 => "-ms".into(),
|
|| "-ms".into(),
|
||||||
delay if delay >= 10000 => "-ms".into(),
|
|h| match h.delay {
|
||||||
_ => format!("{}ms", h.delay),
|
0 => "-ms".into(),
|
||||||
})
|
delay if delay >= 10000 => "-ms".into(),
|
||||||
.unwrap_or_else(|| "-ms".into());
|
_ => format!("{}ms", h.delay),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
let display_text = format!("{} | {}", proxy_str, delay_text);
|
let display_text = format!("{} | {}", proxy_str, delay_text);
|
||||||
|
|
||||||
@@ -611,7 +606,7 @@ async fn create_tray_menu(
|
|||||||
config
|
config
|
||||||
.get("proxy-groups")
|
.get("proxy-groups")
|
||||||
.and_then(|groups| groups.as_sequence())
|
.and_then(|groups| groups.as_sequence())
|
||||||
.map(|groups| {
|
.map_or_default(|groups| {
|
||||||
groups
|
groups
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|group| group.get("name"))
|
.filter_map(|group| group.get("name"))
|
||||||
@@ -620,7 +615,6 @@ async fn create_tray_menu(
|
|||||||
.map(|(index, name)| (name.into(), index))
|
.map(|(index, name)| (name.into(), index))
|
||||||
.collect::<HashMap<String, usize>>()
|
.collect::<HashMap<String, usize>>()
|
||||||
})
|
})
|
||||||
.unwrap_or_default()
|
|
||||||
});
|
});
|
||||||
|
|
||||||
(proxy_nodes_data, runtime_proxy_groups_order)
|
(proxy_nodes_data, runtime_proxy_groups_order)
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use scopeguard::defer;
|
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use smartstring::alias::String;
|
use smartstring::alias::String;
|
||||||
use std::{
|
use std::{
|
||||||
fmt,
|
fmt,
|
||||||
hash::{DefaultHasher, Hash as _, Hasher as _},
|
hash::{DefaultHasher, Hash as _, Hasher as _},
|
||||||
|
mem::DropGuard,
|
||||||
sync::LazyLock,
|
sync::LazyLock,
|
||||||
sync::atomic::{AtomicBool, Ordering},
|
sync::atomic::{AtomicBool, Ordering},
|
||||||
};
|
};
|
||||||
@@ -421,9 +421,9 @@ impl CoreConfigValidator {
|
|||||||
logging!(info, Type::Validate, "验证已在进行中,跳过新的验证请求");
|
logging!(info, Type::Validate, "验证已在进行中,跳过新的验证请求");
|
||||||
return Ok(ValidationOutcome::Busy);
|
return Ok(ValidationOutcome::Busy);
|
||||||
}
|
}
|
||||||
defer! {
|
let _validation = DropGuard::new((), |()| {
|
||||||
self.finish();
|
self.finish();
|
||||||
}
|
});
|
||||||
logging!(info, Type::Validate, "生成临时配置文件用于验证");
|
logging!(info, Type::Validate, "生成临时配置文件用于验证");
|
||||||
|
|
||||||
// The test run reads the app dir, which never sees updates made by a service core.
|
// The test run reads the app dir, which never sees updates made by a service core.
|
||||||
@@ -435,7 +435,7 @@ impl CoreConfigValidator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let check_path = dirs::app_home_dir()?.join(crate::constants::files::CHECK_CONFIG);
|
let check_path = dirs::app_home_dir()?.join(crate::constants::files::CHECK_CONFIG);
|
||||||
help::save_yaml_str(&check_path, yaml).await?;
|
help::save_yaml_str(&check_path, yaml, None).await?;
|
||||||
let outcome = Self::validate_config_internal_outcome(dirs::path_to_str(&check_path)?).await?;
|
let outcome = Self::validate_config_internal_outcome(dirs::path_to_str(&check_path)?).await?;
|
||||||
if outcome.is_valid() {
|
if outcome.is_valid() {
|
||||||
*LAST_VALIDATED.lock() = Some(fingerprint);
|
*LAST_VALIDATED.lock() = Some(fingerprint);
|
||||||
@@ -449,8 +449,7 @@ fn has_ext<P: AsRef<std::path::Path>>(path: P, ext: &str) -> bool {
|
|||||||
path.as_ref()
|
path.as_ref()
|
||||||
.extension()
|
.extension()
|
||||||
.and_then(|s| s.to_str())
|
.and_then(|s| s.to_str())
|
||||||
.map(|s| s.eq_ignore_ascii_case(ext))
|
.is_some_and(|s| s.eq_ignore_ascii_case(ext))
|
||||||
.unwrap_or(false)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn contains_any_keyword<'a>(buf: &'a [u8], keywords: &'a [&str]) -> bool {
|
fn contains_any_keyword<'a>(buf: &'a [u8], keywords: &'a [&str]) -> bool {
|
||||||
|
|||||||
@@ -24,12 +24,12 @@ fn lowercase_key(key: &str) -> Value {
|
|||||||
Value::from(key.as_str())
|
Value::from(key.as_str())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn use_lowercase(config: &Mapping) -> Mapping {
|
pub fn use_lowercase(config: Mapping) -> Mapping {
|
||||||
let mut lowercased = Mapping::new();
|
let mut lowercased = Mapping::new();
|
||||||
|
|
||||||
for (key, value) in config.iter() {
|
for (key, value) in config {
|
||||||
if let Some(key_str) = key.as_str() {
|
if let Some(key_str) = key.as_str() {
|
||||||
lowercased.insert(lowercase_key(key_str), value.clone());
|
lowercased.insert(lowercase_key(key_str), value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
lowercased
|
lowercased
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ fn deep_merge(a: &mut Value, b: Value) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn use_merge(merge: &Mapping, mut config: Mapping) -> Mapping {
|
pub fn use_merge(merge: Mapping, mut config: Mapping) -> Mapping {
|
||||||
for (key, value) in use_lowercase(merge) {
|
for (key, value) in use_lowercase(merge) {
|
||||||
match (config.get_mut(&key), value) {
|
match (config.get_mut(&key), value) {
|
||||||
(Some(Value::Mapping(existing)), Value::Mapping(overlay)) if key.as_str() == Some("dns") => {
|
(Some(Value::Mapping(existing)), Value::Mapping(overlay)) if key.as_str() == Some("dns") => {
|
||||||
@@ -79,7 +79,7 @@ fn test_merge() -> anyhow::Result<()> {
|
|||||||
let merge = serde_yaml_ng::from_str::<Mapping>(merge)?;
|
let merge = serde_yaml_ng::from_str::<Mapping>(merge)?;
|
||||||
let config = serde_yaml_ng::from_str::<Mapping>(config)?;
|
let config = serde_yaml_ng::from_str::<Mapping>(config)?;
|
||||||
|
|
||||||
let result = use_merge(&merge, config);
|
let result = use_merge(merge.clone(), config);
|
||||||
assert_eq!(result["dns"]["nameserver-policy"], merge["dns"]["nameserver-policy"]);
|
assert_eq!(result["dns"]["nameserver-policy"], merge["dns"]["nameserver-policy"]);
|
||||||
assert_eq!(result["dns"]["fallback-filter"], merge["dns"]["fallback-filter"]);
|
assert_eq!(result["dns"]["fallback-filter"], merge["dns"]["fallback-filter"]);
|
||||||
assert_eq!(result["hosts"], merge["hosts"]);
|
assert_eq!(result["hosts"], merge["hosts"]);
|
||||||
@@ -91,7 +91,7 @@ fn test_merge() -> anyhow::Result<()> {
|
|||||||
let cleared = serde_yaml_ng::from_str::<Mapping>(
|
let cleared = serde_yaml_ng::from_str::<Mapping>(
|
||||||
"dns: {enable: false, nameserver-policy: {}, fallback-filter: {}, nameserver: []}\nhosts: {}",
|
"dns: {enable: false, nameserver-policy: {}, fallback-filter: {}, nameserver: []}\nhosts: {}",
|
||||||
)?;
|
)?;
|
||||||
let result = use_merge(&cleared, result);
|
let result = use_merge(cleared.clone(), result);
|
||||||
assert_eq!(result["dns"], cleared["dns"]);
|
assert_eq!(result["dns"], cleared["dns"]);
|
||||||
assert_eq!(result["hosts"], cleared["hosts"]);
|
assert_eq!(result["hosts"], cleared["hosts"]);
|
||||||
|
|
||||||
|
|||||||
+103
-62
@@ -28,6 +28,7 @@ use parking_lot::Mutex;
|
|||||||
use serde_yaml_ng::{Mapping, Value};
|
use serde_yaml_ng::{Mapping, Value};
|
||||||
use smartstring::alias::String;
|
use smartstring::alias::String;
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
|
use std::hash::{Hash as _, Hasher as _};
|
||||||
use tokio::fs;
|
use tokio::fs;
|
||||||
|
|
||||||
type ResultLog = Vec<(String, String)>;
|
type ResultLog = Vec<(String, String)>;
|
||||||
@@ -236,13 +237,13 @@ async fn process_override_items(
|
|||||||
mut result_map: HashMap<String, ResultLog>,
|
mut result_map: HashMap<String, ResultLog>,
|
||||||
merge_item: ChainItem,
|
merge_item: ChainItem,
|
||||||
script_item: ChainItem,
|
script_item: ChainItem,
|
||||||
profile_name: &String,
|
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, config);
|
||||||
let notes: ResultLog = authoritative
|
let notes: ResultLog = authoritative
|
||||||
.overridden(&before, &authoritative.current(&config))
|
.overridden(&before, &authoritative.current(&config))
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -255,7 +256,7 @@ async fn process_override_items(
|
|||||||
|
|
||||||
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.clone()).await;
|
let (res_config, changed_keys, mut logs) = use_script(script, 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(
|
||||||
@@ -320,15 +321,45 @@ struct AuthoritativeFields {
|
|||||||
tun: Mapping,
|
tun: Mapping,
|
||||||
dns: Mapping,
|
dns: Mapping,
|
||||||
hosts: Option<Value>,
|
hosts: Option<Value>,
|
||||||
|
fingerprints: FieldFingerprints,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct FieldFingerprints {
|
||||||
|
control_plane: Vec<Option<u64>>,
|
||||||
|
tun: Vec<Option<u64>>,
|
||||||
|
dns: Vec<Option<u64>>,
|
||||||
|
hosts: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fingerprint(value: Option<&Value>) -> Option<u64> {
|
||||||
|
let value = value?;
|
||||||
|
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||||
|
value.hash(&mut hasher);
|
||||||
|
Some(hasher.finish())
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AuthoritativeFields {
|
impl AuthoritativeFields {
|
||||||
fn capture(config: &Mapping, gui_tun_keys: &[Value], mut dns_settings: Mapping) -> Self {
|
fn capture(config: &Mapping, gui_tun_keys: &[Value], mut dns_settings: Mapping) -> Self {
|
||||||
|
let control_plane = snapshot_control_plane(config);
|
||||||
|
let tun = snapshot_tun(config, gui_tun_keys);
|
||||||
|
let dns = take_mapping(&mut dns_settings, "dns");
|
||||||
|
let hosts = dns_settings.remove("hosts");
|
||||||
|
let fingerprints = FieldFingerprints {
|
||||||
|
control_plane: CONTROL_PLANE_KEYS
|
||||||
|
.iter()
|
||||||
|
.map(|&key| fingerprint(control_plane.get(Value::from(key))))
|
||||||
|
.collect(),
|
||||||
|
tun: tun.iter().map(|(_, value)| fingerprint(Some(value))).collect(),
|
||||||
|
dns: dns.iter().map(|(_, value)| fingerprint(Some(value))).collect(),
|
||||||
|
hosts: fingerprint(hosts.as_ref()),
|
||||||
|
};
|
||||||
Self {
|
Self {
|
||||||
control_plane: snapshot_control_plane(config),
|
control_plane,
|
||||||
tun: snapshot_tun(config, gui_tun_keys),
|
tun,
|
||||||
dns: take_mapping(&mut dns_settings, "dns"),
|
dns,
|
||||||
hosts: dns_settings.remove("hosts"),
|
hosts,
|
||||||
|
fingerprints,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -346,43 +377,50 @@ impl AuthoritativeFields {
|
|||||||
config
|
config
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The owned values as `config` holds them now, for diffing one override.
|
/// What `config` holds now, for diffing one override.
|
||||||
fn current(&self, config: &Mapping) -> Self {
|
fn current(&self, config: &Mapping) -> FieldFingerprints {
|
||||||
let tun_keys: Vec<Value> = self.tun.keys().cloned().collect();
|
let tun = config.get("tun").and_then(Value::as_mapping);
|
||||||
let dns = config.get("dns").and_then(Value::as_mapping);
|
let dns = config.get("dns").and_then(Value::as_mapping);
|
||||||
Self {
|
FieldFingerprints {
|
||||||
control_plane: snapshot_control_plane(config),
|
control_plane: CONTROL_PLANE_KEYS
|
||||||
tun: snapshot_tun(config, &tun_keys),
|
.iter()
|
||||||
|
.map(|&key| fingerprint(config.get(key)))
|
||||||
|
.collect(),
|
||||||
|
tun: self
|
||||||
|
.tun
|
||||||
|
.keys()
|
||||||
|
.map(|key| fingerprint(tun.and_then(|map| map.get(key))))
|
||||||
|
.collect(),
|
||||||
dns: self
|
dns: self
|
||||||
.dns
|
.dns
|
||||||
.keys()
|
.keys()
|
||||||
.filter_map(|key| Some((key.clone(), dns?.get(key)?.clone())))
|
.map(|key| fingerprint(dns.and_then(|map| map.get(key))))
|
||||||
.collect(),
|
.collect(),
|
||||||
hosts: self.hosts.as_ref().and_then(|_| config.get("hosts")).cloned(),
|
hosts: self.hosts.as_ref().and_then(|_| fingerprint(config.get("hosts"))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Owned keys an override moved off the app value; `enforce` discards those writes.
|
/// Owned keys an override moved off the app value; `enforce` discards those writes.
|
||||||
fn overridden(&self, before: &Self, after: &Self) -> Vec<String> {
|
fn overridden(&self, before: &FieldFingerprints, after: &FieldFingerprints) -> Vec<String> {
|
||||||
let mut keys = Vec::new();
|
let mut keys = Vec::new();
|
||||||
for &key in CONTROL_PLANE_KEYS {
|
for (index, &key) in CONTROL_PLANE_KEYS.iter().enumerate() {
|
||||||
if before.control_plane.get(key) != after.control_plane.get(key)
|
if before.control_plane[index] != after.control_plane[index]
|
||||||
&& after.control_plane.get(key) != self.control_plane.get(key)
|
&& after.control_plane[index] != self.fingerprints.control_plane[index]
|
||||||
{
|
{
|
||||||
keys.push(key.into());
|
keys.push(key.into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for key in self.tun.keys() {
|
for (index, key) in self.tun.keys().enumerate() {
|
||||||
if before.tun.get(key) != after.tun.get(key) && after.tun.get(key) != self.tun.get(key) {
|
if before.tun[index] != after.tun[index] && after.tun[index] != self.fingerprints.tun[index] {
|
||||||
keys.push(format!("tun.{}", key.as_str().unwrap_or_default()).into());
|
keys.push(format!("tun.{}", key.as_str().unwrap_or_default()).into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for key in self.dns.keys() {
|
for (index, key) in self.dns.keys().enumerate() {
|
||||||
if before.dns.get(key) != after.dns.get(key) && after.dns.get(key) != self.dns.get(key) {
|
if before.dns[index] != after.dns[index] && after.dns[index] != self.fingerprints.dns[index] {
|
||||||
keys.push(format!("dns.{}", key.as_str().unwrap_or_default()).into());
|
keys.push(format!("dns.{}", key.as_str().unwrap_or_default()).into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if self.hosts.is_some() && before.hosts != after.hosts && after.hosts != self.hosts {
|
if self.hosts.is_some() && before.hosts != after.hosts && after.hosts != self.fingerprints.hosts {
|
||||||
keys.push("hosts".into());
|
keys.push("hosts".into());
|
||||||
}
|
}
|
||||||
keys
|
keys
|
||||||
@@ -459,7 +497,7 @@ fn gui_tun_keys(clash_config: &Mapping) -> Vec<Value> {
|
|||||||
keys.extend(
|
keys.extend(
|
||||||
constants::tun::GUI_KEYS
|
constants::tun::GUI_KEYS
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|key| tun.contains_key(**key))
|
.filter(|key| tun.get(**key).is_some_and(|value| !value.is_null()))
|
||||||
.map(|key| Value::from(*key)),
|
.map(|key| Value::from(*key)),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -531,6 +569,16 @@ fn ensure_lan_bind_address(mut config: Mapping) -> Mapping {
|
|||||||
config
|
config
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn ensure_tun_default_mtu(mut config: Mapping) -> Mapping {
|
||||||
|
if let Some(Value::Mapping(tun)) = config.get_mut("tun")
|
||||||
|
&& matches!(tun.get("mtu"), None | Some(Value::Null))
|
||||||
|
{
|
||||||
|
tun.insert(Value::from("mtu"), Value::from(constants::tun::DEFAULT_MTU));
|
||||||
|
}
|
||||||
|
|
||||||
|
config
|
||||||
|
}
|
||||||
|
|
||||||
/// Merges the app's clash config over the profile; switches are parameters to keep it pure.
|
/// Merges the app's clash config over the profile; switches are parameters to keep it pure.
|
||||||
fn merge_default_config(
|
fn merge_default_config(
|
||||||
mut config: Mapping,
|
mut config: Mapping,
|
||||||
@@ -543,14 +591,15 @@ fn merge_default_config(
|
|||||||
) -> Mapping {
|
) -> Mapping {
|
||||||
for (key, value) in clash_config.into_iter() {
|
for (key, value) in clash_config.into_iter() {
|
||||||
if key.as_str() == Some("tun") {
|
if key.as_str() == Some("tun") {
|
||||||
let mut tun = config.get_mut("tun").map_or_else(Mapping::new, |val| {
|
if let Value::Mapping(patch_tun) = value {
|
||||||
val.as_mapping().cloned().unwrap_or_else(Mapping::new)
|
let mut tun = take_mapping(&mut config, "tun");
|
||||||
});
|
for (key, value) in patch_tun {
|
||||||
let patch_tun = value.as_mapping().cloned().unwrap_or_else(Mapping::new);
|
if !value.is_null() {
|
||||||
for (key, value) in patch_tun.into_iter() {
|
tun.insert(key, value);
|
||||||
tun.insert(key, value);
|
}
|
||||||
|
}
|
||||||
|
config.insert(Value::from("tun"), Value::Mapping(tun));
|
||||||
}
|
}
|
||||||
config.insert("tun".into(), tun.into());
|
|
||||||
} else {
|
} else {
|
||||||
if key.as_str() == Some("socks-port") && !socks_enabled {
|
if key.as_str() == Some("socks-port") && !socks_enabled {
|
||||||
config.remove("socks-port");
|
config.remove("socks-port");
|
||||||
@@ -605,7 +654,7 @@ fn merge_default_config(
|
|||||||
fn apply_builtin_scripts(mut config: Mapping, enable_builtin: bool) -> Mapping {
|
fn apply_builtin_scripts(mut config: Mapping, enable_builtin: bool) -> Mapping {
|
||||||
if enable_builtin {
|
if enable_builtin {
|
||||||
// The JS path saw a lowercased view; lowercase once, only when the builtin runs.
|
// The JS path saw a lowercased view; lowercase once, only when the builtin runs.
|
||||||
config = use_lowercase(&config);
|
config = use_lowercase(config);
|
||||||
logging!(debug, Type::Core, "run builtin script verge_hy_alpn");
|
logging!(debug, Type::Core, "run builtin script verge_hy_alpn");
|
||||||
config = builtin_hy_alpn(config);
|
config = builtin_hy_alpn(config);
|
||||||
}
|
}
|
||||||
@@ -634,24 +683,20 @@ fn cleanup_proxy_groups(mut config: Mapping) -> Mapping {
|
|||||||
let proxy_names = config
|
let proxy_names = config
|
||||||
.get("proxies")
|
.get("proxies")
|
||||||
.and_then(|v| v.as_sequence())
|
.and_then(|v| v.as_sequence())
|
||||||
.map(|seq| {
|
.map_or_default(|seq| {
|
||||||
seq.iter()
|
seq.iter()
|
||||||
.filter_map(|item| match item {
|
.filter_map(|item| match item {
|
||||||
Value::Mapping(map) => map
|
Value::Mapping(map) => map.get("name").and_then(Value::as_str).map(Into::into),
|
||||||
.get("name")
|
Value::String(name) => Some(name.as_str().into()),
|
||||||
.and_then(Value::as_str)
|
|
||||||
.map(|name| name.to_owned().into()),
|
|
||||||
Value::String(name) => Some(name.to_owned().into()),
|
|
||||||
_ => None,
|
_ => None,
|
||||||
})
|
})
|
||||||
.collect::<HashSet<String>>()
|
.collect::<HashSet<String>>()
|
||||||
})
|
});
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
let group_names = config
|
let group_names = config
|
||||||
.get("proxy-groups")
|
.get("proxy-groups")
|
||||||
.and_then(|v| v.as_sequence())
|
.and_then(|v| v.as_sequence())
|
||||||
.map(|seq| {
|
.map_or_default(|seq| {
|
||||||
seq.iter()
|
seq.iter()
|
||||||
.filter_map(|item| {
|
.filter_map(|item| {
|
||||||
item.as_mapping()
|
item.as_mapping()
|
||||||
@@ -660,19 +705,17 @@ fn cleanup_proxy_groups(mut config: Mapping) -> Mapping {
|
|||||||
.map(std::convert::Into::into)
|
.map(std::convert::Into::into)
|
||||||
})
|
})
|
||||||
.collect::<HashSet<String>>()
|
.collect::<HashSet<String>>()
|
||||||
})
|
});
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
let provider_names = config
|
let provider_names = config
|
||||||
.get("proxy-providers")
|
.get("proxy-providers")
|
||||||
.and_then(Value::as_mapping)
|
.and_then(Value::as_mapping)
|
||||||
.map(|map| {
|
.map_or_default(|map| {
|
||||||
map.keys()
|
map.keys()
|
||||||
.filter_map(Value::as_str)
|
.filter_map(Value::as_str)
|
||||||
.map(std::convert::Into::into)
|
.map(std::convert::Into::into)
|
||||||
.collect::<HashSet<String>>()
|
.collect::<HashSet<String>>()
|
||||||
})
|
});
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
let mut allowed_names = proxy_names;
|
let mut allowed_names = proxy_names;
|
||||||
allowed_names.extend(group_names);
|
allowed_names.extend(group_names);
|
||||||
@@ -716,15 +759,13 @@ fn ensure_fake_ip_range6(dns: &mut Mapping) {
|
|||||||
let is_fake_ip = dns
|
let is_fake_ip = dns
|
||||||
.get("enhanced-mode")
|
.get("enhanced-mode")
|
||||||
.and_then(|v| v.as_str())
|
.and_then(|v| v.as_str())
|
||||||
.map(|m| m == "fake-ip")
|
.is_none_or(|m| m == "fake-ip");
|
||||||
.unwrap_or(true);
|
|
||||||
|
|
||||||
// Hand-edited YAML may leave the key present but empty.
|
// Hand-edited YAML may leave the key present but empty.
|
||||||
let range6_missing = dns
|
let range6_missing = dns
|
||||||
.get("fake-ip-range6")
|
.get("fake-ip-range6")
|
||||||
.and_then(|v| v.as_str())
|
.and_then(|v| v.as_str())
|
||||||
.map(|s| s.trim().is_empty())
|
.is_none_or(|s| s.trim().is_empty());
|
||||||
.unwrap_or(true);
|
|
||||||
|
|
||||||
if ipv6_enabled && is_fake_ip && range6_missing {
|
if ipv6_enabled && is_fake_ip && range6_missing {
|
||||||
dns.insert(Value::from("fake-ip-range6"), Value::from("2001:2::0/64"));
|
dns.insert(Value::from("fake-ip-range6"), Value::from("2001:2::0/64"));
|
||||||
@@ -747,8 +788,7 @@ fn take_mapping(config: &mut Mapping, key: &str) -> Mapping {
|
|||||||
config
|
config
|
||||||
.get_mut(key)
|
.get_mut(key)
|
||||||
.and_then(Value::as_mapping_mut)
|
.and_then(Value::as_mapping_mut)
|
||||||
.map(std::mem::take)
|
.map_or_default(std::mem::take)
|
||||||
.unwrap_or_default()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn merge_dns_config(mut config: Mapping, mut dns_config: Mapping) -> (Mapping, Mapping) {
|
fn merge_dns_config(mut config: Mapping, mut dns_config: Mapping) -> (Mapping, Mapping) {
|
||||||
@@ -866,7 +906,7 @@ pub async fn enhance(
|
|||||||
result_map,
|
result_map,
|
||||||
global_merge,
|
global_merge,
|
||||||
global_script,
|
global_script,
|
||||||
&profile_name,
|
profile_name.as_str(),
|
||||||
&authoritative,
|
&authoritative,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
@@ -877,13 +917,14 @@ pub async fn enhance(
|
|||||||
result_map,
|
result_map,
|
||||||
merge_item,
|
merge_item,
|
||||||
script_item,
|
script_item,
|
||||||
&profile_name,
|
profile_name.as_str(),
|
||||||
&authoritative,
|
&authoritative,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
notify_discarded_keys(authoritative.overridden(&authoritative, &authoritative.current(&config)));
|
notify_discarded_keys(authoritative.overridden(&authoritative.fingerprints, &authoritative.current(&config)));
|
||||||
let config = authoritative.enforce(config);
|
let config = authoritative.enforce(config);
|
||||||
|
let config = ensure_tun_default_mtu(config);
|
||||||
let config = ensure_lan_bind_address(config);
|
let config = ensure_lan_bind_address(config);
|
||||||
|
|
||||||
let config = cleanup_proxy_groups(config);
|
let config = cleanup_proxy_groups(config);
|
||||||
@@ -1400,7 +1441,7 @@ mod tests {
|
|||||||
uid: uid.into(),
|
uid: uid.into(),
|
||||||
data: ChainType::Merge(merge.clone()),
|
data: ChainType::Merge(merge.clone()),
|
||||||
};
|
};
|
||||||
let profile_name = "test-profile".into();
|
let profile_name = "test-profile";
|
||||||
let (config, keys, logs) = process_override_items(
|
let (config, keys, logs) = process_override_items(
|
||||||
config,
|
config,
|
||||||
vec![],
|
vec![],
|
||||||
@@ -1410,7 +1451,7 @@ mod tests {
|
|||||||
uid: "global-script".into(),
|
uid: "global-script".into(),
|
||||||
data: ChainType::Script(script.into()),
|
data: ChainType::Script(script.into()),
|
||||||
},
|
},
|
||||||
&profile_name,
|
profile_name,
|
||||||
&authoritative,
|
&authoritative,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
@@ -1423,7 +1464,7 @@ mod tests {
|
|||||||
uid: "profile-script".into(),
|
uid: "profile-script".into(),
|
||||||
data: ChainType::Script(script.into()),
|
data: ChainType::Script(script.into()),
|
||||||
},
|
},
|
||||||
&profile_name,
|
profile_name,
|
||||||
&authoritative,
|
&authoritative,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
@@ -1499,7 +1540,7 @@ mod tests {
|
|||||||
),
|
),
|
||||||
};
|
};
|
||||||
|
|
||||||
let profile_name = "test-profile".into();
|
let profile_name = "test-profile";
|
||||||
let authoritative = AuthoritativeFields::capture(&config, &[], Mapping::new());
|
let authoritative = AuthoritativeFields::capture(&config, &[], Mapping::new());
|
||||||
let (config, exists_keys, result_map) = process_override_items(
|
let (config, exists_keys, result_map) = process_override_items(
|
||||||
config,
|
config,
|
||||||
@@ -1507,7 +1548,7 @@ mod tests {
|
|||||||
HashMap::new(),
|
HashMap::new(),
|
||||||
global_merge,
|
global_merge,
|
||||||
global_script,
|
global_script,
|
||||||
&profile_name,
|
profile_name,
|
||||||
&authoritative,
|
&authoritative,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
@@ -1517,7 +1558,7 @@ mod tests {
|
|||||||
result_map,
|
result_map,
|
||||||
profile_merge,
|
profile_merge,
|
||||||
profile_script,
|
profile_script,
|
||||||
&profile_name,
|
profile_name,
|
||||||
&authoritative,
|
&authoritative,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use crate::{process::AsyncHandler, utils::tmpl};
|
use crate::{process::AsyncHandler, utils::tmpl};
|
||||||
|
|
||||||
use super::field::use_lowercase;
|
use super::field::use_lowercase;
|
||||||
use anyhow::{Error, Result};
|
use anyhow::Result;
|
||||||
use boa_engine::{Context, JsString, JsValue, Source, js_string, native_function::NativeFunction, property::Attribute};
|
use boa_engine::{Context, JsString, JsValue, Source, js_string, native_function::NativeFunction, property::Attribute};
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
@@ -22,14 +22,26 @@ type EvalOutcome = (Result<Mapping, std::string::String>, Vec<(String, String)>)
|
|||||||
pub(super) async fn use_script(script: String, config: Mapping, name: String) -> ScriptResult {
|
pub(super) async fn use_script(script: String, config: Mapping, name: String) -> ScriptResult {
|
||||||
// The template is identity-plus-lowercasing; skip the Boa round-trip.
|
// The template is identity-plus-lowercasing; skip the Boa round-trip.
|
||||||
if script == tmpl::ITEM_SCRIPT {
|
if script == tmpl::ITEM_SCRIPT {
|
||||||
return (use_lowercase(&config), vec![], vec![]);
|
return (use_lowercase(config), vec![], vec![]);
|
||||||
}
|
}
|
||||||
|
|
||||||
let json = match serde_json::to_string(&use_lowercase(&config)) {
|
let json = match serde_json::to_value(&config) {
|
||||||
Ok(json) if json.len() <= MAX_JSON_SIZE => json,
|
Ok(mut json) => {
|
||||||
Ok(_) => {
|
if let Some(map) = json.as_object_mut() {
|
||||||
let message = "Configuration size exceeds maximum allowed size";
|
let mut lowered = serde_json::Map::with_capacity(map.len());
|
||||||
return (config, vec![], vec![("exception".into(), message.into())]);
|
for (key, value) in std::mem::take(map) {
|
||||||
|
let mut key = key;
|
||||||
|
key.make_ascii_lowercase();
|
||||||
|
lowered.insert(key, value);
|
||||||
|
}
|
||||||
|
*map = lowered;
|
||||||
|
}
|
||||||
|
if json_approx_size(&json) <= MAX_JSON_SIZE {
|
||||||
|
json
|
||||||
|
} else {
|
||||||
|
let message = "Configuration size exceeds maximum allowed size";
|
||||||
|
return (config, vec![], vec![("exception".into(), message.into())]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Err(err) => return (config, vec![], vec![("exception".into(), err.to_string().into())]),
|
Err(err) => return (config, vec![], vec![("exception".into(), err.to_string().into())]),
|
||||||
};
|
};
|
||||||
@@ -66,7 +78,7 @@ pub(super) async fn use_script(script: String, config: Mapping, name: String) ->
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Console logs survive every failure path.
|
/// Console logs survive every failure path.
|
||||||
fn eval_script(script: &str, config_json: &str, name: &String) -> EvalOutcome {
|
fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) -> EvalOutcome {
|
||||||
let mut context = Context::default();
|
let mut context = Context::default();
|
||||||
|
|
||||||
context
|
context
|
||||||
@@ -131,12 +143,11 @@ fn eval_script(script: &str, config_json: &str, name: &String) -> EvalOutcome {
|
|||||||
});"#,
|
});"#,
|
||||||
));
|
));
|
||||||
|
|
||||||
// Bind the JSON instead of embedding it in program source; Boa's parser never chews it.
|
let config_value = match JsValue::from_json(config_json, &mut context) {
|
||||||
if let Err(err) = context.register_global_property(
|
Ok(value) => value,
|
||||||
js_string!("__verge_config__"),
|
Err(err) => return bail(format!("failed to bind config for script: {err}")),
|
||||||
JsValue::from(JsString::from(config_json)),
|
};
|
||||||
Attribute::all(),
|
if let Err(err) = context.register_global_property(js_string!("__verge_config__"), config_value, Attribute::all()) {
|
||||||
) {
|
|
||||||
return bail(format!("failed to bind config for script: {err}"));
|
return bail(format!("failed to bind config for script: {err}"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,31 +160,61 @@ fn eval_script(script: &str, config_json: &str, name: &String) -> EvalOutcome {
|
|||||||
let code = format!(
|
let code = format!(
|
||||||
r"try{{
|
r"try{{
|
||||||
{script};
|
{script};
|
||||||
JSON.stringify(main(JSON.parse(globalThis.__verge_config__),'{safe_name}')||'')
|
main(globalThis.__verge_config__,'{safe_name}')
|
||||||
}} catch(err) {{
|
}} catch(err) {{
|
||||||
`__error_flag__ ${{err.toString()}}`
|
`__error_flag__ ${{err.toString()}}`
|
||||||
}}"
|
}}"
|
||||||
);
|
);
|
||||||
|
|
||||||
let result = match context.eval(Source::from_bytes(code.as_str())) {
|
let result = match context.eval(Source::from_bytes(code.as_str())) {
|
||||||
Ok(result) if result.is_string() => result,
|
|
||||||
_ => return bail("main function should return object".to_owned()),
|
|
||||||
};
|
|
||||||
let result = match result.to_string(&mut context) {
|
|
||||||
Ok(result) => result,
|
Ok(result) => result,
|
||||||
Err(e) => return bail(format!("Failed to convert JS result to string: {e}")),
|
Err(err) => {
|
||||||
|
logging!(
|
||||||
|
error,
|
||||||
|
Type::Config,
|
||||||
|
"Script execution error: {err}. Script name: {name}"
|
||||||
|
);
|
||||||
|
return bail("Script execution failed".to_owned());
|
||||||
|
}
|
||||||
};
|
};
|
||||||
let result = match result.to_std_string() {
|
// The JS wrapper funnels exceptions into a marker string; surface its text.
|
||||||
Ok(result) => result,
|
if result.is_string() {
|
||||||
Err(_) => return bail("Failed to convert JS string to std string".to_owned()),
|
let text = result
|
||||||
|
.to_string(&mut context)
|
||||||
|
.ok()
|
||||||
|
.and_then(|text| text.to_std_string().ok())
|
||||||
|
.unwrap_or_default();
|
||||||
|
if text.trim_start().starts_with("__error_flag__") {
|
||||||
|
logging!(
|
||||||
|
error,
|
||||||
|
Type::Config,
|
||||||
|
"Script execution error: {}. Script name: {name}",
|
||||||
|
text.trim_start()["__error_flag__".len()..].trim()
|
||||||
|
);
|
||||||
|
return bail("Script execution failed".to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !result.is_object() {
|
||||||
|
return bail("main function should return object".to_owned());
|
||||||
|
}
|
||||||
|
let result = match result.to_json(&mut context) {
|
||||||
|
Ok(Some(result)) => result,
|
||||||
|
Ok(None) => return bail("main function should return object".to_owned()),
|
||||||
|
Err(err) => {
|
||||||
|
logging!(
|
||||||
|
error,
|
||||||
|
Type::Config,
|
||||||
|
"Script execution error: {err}. Script name: {name}"
|
||||||
|
);
|
||||||
|
return bail("Script execution failed".to_owned());
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
if json_approx_size(&result) > MAX_JSON_SIZE {
|
||||||
if result.len() > MAX_JSON_SIZE {
|
|
||||||
return bail("Script result exceeds maximum allowed size".to_owned());
|
return bail("Script result exceeds maximum allowed size".to_owned());
|
||||||
}
|
}
|
||||||
|
|
||||||
match parse_json_safely(&result) {
|
match serde_json::from_value::<Mapping>(result) {
|
||||||
Ok(config) => (Ok(use_lowercase(&config)), outputs.lock().to_vec()),
|
Ok(config) => (Ok(use_lowercase(config)), outputs.lock().to_vec()),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
logging!(
|
logging!(
|
||||||
error,
|
error,
|
||||||
@@ -185,27 +226,17 @@ fn eval_script(script: &str, config_json: &str, name: &String) -> EvalOutcome {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_json_safely(json_str: &str) -> Result<Mapping, Error> {
|
/// Serialized-size estimate without building the serialized string; a DoS guard, not an exact byte count.
|
||||||
if json_str.len() > MAX_JSON_SIZE {
|
fn json_approx_size(value: &serde_json::Value) -> usize {
|
||||||
anyhow::bail!("JSON string too large");
|
match value {
|
||||||
}
|
serde_json::Value::String(s) => s.len() + 2,
|
||||||
|
serde_json::Value::Object(map) => map
|
||||||
let json_str = strip_outer_quotes(json_str);
|
.iter()
|
||||||
Ok(serde_json::from_str::<Mapping>(json_str)?)
|
.map(|(key, value)| key.len() + 4 + json_approx_size(value))
|
||||||
}
|
.sum(),
|
||||||
|
serde_json::Value::Array(items) => items.iter().map(json_approx_size).sum(),
|
||||||
// 安全地移除外层引号
|
serde_json::Value::Number(n) => n.to_string().len(),
|
||||||
fn strip_outer_quotes(s: &str) -> &str {
|
serde_json::Value::Bool(_) | serde_json::Value::Null => 4,
|
||||||
let s = s.trim();
|
|
||||||
|
|
||||||
if s.len() < 2 {
|
|
||||||
return s;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')) {
|
|
||||||
&s[1..s.len() - 1]
|
|
||||||
} else {
|
|
||||||
s
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,14 +20,10 @@ fn collect_proxy_names(seq: &Sequence) -> Vec<String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn is_selector_group(group_map: &Mapping) -> bool {
|
fn is_selector_group(group_map: &Mapping) -> bool {
|
||||||
group_map
|
group_map.get("type").and_then(Value::as_str).is_some_and(|value| {
|
||||||
.get("type")
|
let value = value.to_ascii_lowercase();
|
||||||
.and_then(Value::as_str)
|
value == "select" || value == "selector"
|
||||||
.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 {
|
pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping {
|
||||||
@@ -155,7 +151,6 @@ mod tests {
|
|||||||
use serde_yaml_ng::Value;
|
use serde_yaml_ng::Value;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[allow(clippy::unwrap_used)]
|
|
||||||
#[allow(clippy::expect_used)]
|
#[allow(clippy::expect_used)]
|
||||||
fn test_delete_proxy_and_references() {
|
fn test_delete_proxy_and_references() {
|
||||||
let config_str = r#"
|
let config_str = r#"
|
||||||
@@ -233,7 +228,6 @@ proxy-groups:
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[allow(clippy::unwrap_used)]
|
|
||||||
#[allow(clippy::expect_used)]
|
#[allow(clippy::expect_used)]
|
||||||
fn test_add_new_proxies_to_first_selector_group() {
|
fn test_add_new_proxies_to_first_selector_group() {
|
||||||
let config_str = r#"
|
let config_str = r#"
|
||||||
@@ -303,7 +297,6 @@ proxy-groups:
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[allow(clippy::unwrap_used)]
|
|
||||||
#[allow(clippy::expect_used)]
|
#[allow(clippy::expect_used)]
|
||||||
fn test_preserve_non_sequence_proxy_groups() {
|
fn test_preserve_non_sequence_proxy_groups() {
|
||||||
let config_str = r#"
|
let config_str = r#"
|
||||||
|
|||||||
@@ -8,18 +8,10 @@ macro_rules! revise {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
|
pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
|
||||||
let tun_key = Value::from("tun");
|
let mut tun_val = super::take_mapping(&mut config, "tun");
|
||||||
let tun_val = config.get(&tun_key);
|
|
||||||
let mut tun_val = tun_val.map_or_else(Mapping::new, |val| {
|
|
||||||
val.as_mapping().cloned().unwrap_or_else(Mapping::new)
|
|
||||||
});
|
|
||||||
|
|
||||||
if enable {
|
if enable {
|
||||||
let dns_key = Value::from("dns");
|
let mut dns_val = super::take_mapping(&mut config, "dns");
|
||||||
let dns_val = config.get(&dns_key);
|
|
||||||
let mut dns_val = dns_val.map_or_else(Mapping::new, |val| {
|
|
||||||
val.as_mapping().cloned().unwrap_or_else(Mapping::new)
|
|
||||||
});
|
|
||||||
let ipv6_key = Value::from("ipv6");
|
let ipv6_key = Value::from("ipv6");
|
||||||
let ipv6_val = config.get(&ipv6_key).and_then(|v| v.as_bool()).unwrap_or(false);
|
let ipv6_val = config.get(&ipv6_key).and_then(|v| v.as_bool()).unwrap_or(false);
|
||||||
|
|
||||||
|
|||||||
@@ -123,7 +123,7 @@ pub async fn list_wevdav_backup() -> Result<Vec<ListFile>> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn delete_webdav_backup(filename: String) -> Result<()> {
|
pub async fn delete_webdav_backup(filename: String) -> Result<()> {
|
||||||
let name = filename.to_string();
|
let name = filename.clone();
|
||||||
backup::WebDavClient::global().delete(filename).await.map_err(|err| {
|
backup::WebDavClient::global().delete(filename).await.map_err(|err| {
|
||||||
logging!(
|
logging!(
|
||||||
error,
|
error,
|
||||||
@@ -165,7 +165,7 @@ pub async fn restore_webdav_backup(filename: String) -> Result<()> {
|
|||||||
let backup_storage_path = app_home_dir()
|
let backup_storage_path = app_home_dir()
|
||||||
.map_err(|e| anyhow::anyhow!("Failed to get app home dir: {e}"))?
|
.map_err(|e| anyhow::anyhow!("Failed to get app home dir: {e}"))?
|
||||||
.join(filename.as_str());
|
.join(filename.as_str());
|
||||||
let name = filename.to_string();
|
let name = filename.clone();
|
||||||
backup::WebDavClient::global()
|
backup::WebDavClient::global()
|
||||||
.download(filename, backup_storage_path.clone())
|
.download(filename, backup_storage_path.clone())
|
||||||
.await
|
.await
|
||||||
@@ -235,8 +235,7 @@ pub async fn import_local_backup(source: String) -> Result<String> {
|
|||||||
let ext = source_path
|
let ext = source_path
|
||||||
.extension()
|
.extension()
|
||||||
.and_then(|ext| ext.to_str())
|
.and_then(|ext| ext.to_str())
|
||||||
.map(|ext| ext.to_ascii_lowercase())
|
.map_or_default(|ext| ext.to_ascii_lowercase());
|
||||||
.unwrap_or_default();
|
|
||||||
if ext != "zip" {
|
if ext != "zip" {
|
||||||
return Err(anyhow!("Only .zip backup files are supported"));
|
return Err(anyhow!("Only .zip backup files are supported"));
|
||||||
}
|
}
|
||||||
@@ -314,8 +313,7 @@ pub async fn list_local_backup() -> Result<Vec<LocalBackupFile>> {
|
|||||||
};
|
};
|
||||||
let last_modified = metadata
|
let last_modified = metadata
|
||||||
.modified()
|
.modified()
|
||||||
.map(|time| chrono::DateTime::<Utc>::from(time).to_rfc3339())
|
.map_or_default(|time| chrono::DateTime::<Utc>::from(time).to_rfc3339());
|
||||||
.unwrap_or_default();
|
|
||||||
backups.push(LocalBackupFile {
|
backups.push(LocalBackupFile {
|
||||||
filename: file_name.into(),
|
filename: file_name.into(),
|
||||||
path: path.to_string_lossy().into(),
|
path: path.to_string_lossy().into(),
|
||||||
|
|||||||
@@ -487,8 +487,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn package_urls_pin_the_resolved_version() {
|
fn package_urls_pin_the_resolved_version() {
|
||||||
let release = package_url(false, "v1.19.30").unwrap_or_default();
|
let release = package_url(false, "v1.19.30").unwrap();
|
||||||
let alpha = package_url(true, "alpha-c0e43eb").unwrap_or_default();
|
let alpha = package_url(true, "alpha-c0e43eb").unwrap();
|
||||||
assert!(release.contains("/releases/download/v1.19.30/"), "{release}");
|
assert!(release.contains("/releases/download/v1.19.30/"), "{release}");
|
||||||
assert!(
|
assert!(
|
||||||
release.ends_with("-v1.19.30.gz") || release.ends_with("-v1.19.30.zip"),
|
release.ends_with("-v1.19.30.gz") || release.ends_with("-v1.19.30.zip"),
|
||||||
|
|||||||
@@ -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 {
|
fn normalized_text_prefix(content: &[u8]) -> std::string::String {
|
||||||
let content = content.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(content);
|
let content = content.trim_prefix(&[0xEF, 0xBB, 0xBF]);
|
||||||
let start = content
|
let start = content
|
||||||
.iter()
|
.iter()
|
||||||
.position(|byte| !byte.is_ascii_whitespace())
|
.position(|byte| !byte.is_ascii_whitespace())
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ use crate::{
|
|||||||
use anyhow::{Context as _, Result, anyhow, bail};
|
use anyhow::{Context as _, Result, anyhow, bail};
|
||||||
use clash_verge_draft::DraftTransaction;
|
use clash_verge_draft::DraftTransaction;
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use scopeguard::{ScopeGuard, defer, guard};
|
use std::mem::DropGuard;
|
||||||
|
|
||||||
pub async fn probe_listener(request: ListenerProbe) -> Result<ListenerProbeOutcome> {
|
pub async fn probe_listener(request: ListenerProbe) -> Result<ListenerProbeOutcome> {
|
||||||
AsyncHandler::spawn_blocking(move || probe_listener_sync(&request))
|
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() {
|
if !manager.try_start_config_update() {
|
||||||
bail!("configuration update is already running");
|
bail!("configuration update is already running");
|
||||||
}
|
}
|
||||||
defer! {
|
let _config_update = DropGuard::new((), |()| {
|
||||||
manager.finish_config_update();
|
manager.finish_config_update();
|
||||||
}
|
});
|
||||||
|
|
||||||
// Read first because transaction rollback discards all claimed drafts.
|
// Read first because transaction rollback discards all claimed drafts.
|
||||||
let current = current_runtime_mapping().await?;
|
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.
|
// Hide PAC while the staged ports are not yet serving traffic.
|
||||||
manager.core_starting();
|
manager.core_starting();
|
||||||
// Recompute PAC state after every exit path.
|
// Recompute PAC state after every exit path.
|
||||||
defer! {
|
let _core_start = DropGuard::new((), |()| {
|
||||||
manager.core_start_settled();
|
manager.core_start_settled();
|
||||||
}
|
});
|
||||||
// A user-picked port ends the startup fallback, but only once the save lands: until then the
|
// 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
|
// 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.
|
// proxy and PAC point at a dead port. Declared after the PAC guard so it restores first.
|
||||||
let borrowed_port = guard(MixedPort::session_fallback(), restore_borrowed_port);
|
let borrowed_port = DropGuard::new(MixedPort::session_fallback(), restore_borrowed_port);
|
||||||
MixedPort::clear_session_fallback();
|
MixedPort::clear_session_fallback();
|
||||||
Config::generate()
|
Config::generate()
|
||||||
.await
|
.await
|
||||||
@@ -125,7 +125,7 @@ pub async fn save_proxy_ports(settings: ProxyPortSettings) -> Result<SaveProxyPo
|
|||||||
|
|
||||||
transaction.commit();
|
transaction.commit();
|
||||||
// The save landed, so the port the app had borrowed is now irrelevant.
|
// The save landed, so the port the app had borrowed is now irrelevant.
|
||||||
let _ = ScopeGuard::into_inner(borrowed_port);
|
let _ = DropGuard::dismiss(borrowed_port);
|
||||||
announce(Refresh::Clash);
|
announce(Refresh::Clash);
|
||||||
announce(Refresh::Verge);
|
announce(Refresh::Verge);
|
||||||
logging!(info, Type::Config, "Proxy port configuration applied and persisted");
|
logging!(info, Type::Config, "Proxy port configuration applied and persisted");
|
||||||
|
|||||||
@@ -103,7 +103,7 @@ pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool)
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn should_update_profile(uid: &String, 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>)>> {
|
||||||
let profiles = Config::profiles().await;
|
let profiles = Config::profiles().await;
|
||||||
let profiles = profiles.latest_arc();
|
let profiles = profiles.latest_arc();
|
||||||
let item = profiles.get_item(uid)?;
|
let item = profiles.get_item(uid)?;
|
||||||
@@ -138,8 +138,8 @@ async fn should_update_profile(uid: &String, ignore_auto_update: bool) -> Result
|
|||||||
|
|
||||||
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))]
|
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))]
|
||||||
async fn perform_profile_update(
|
async fn perform_profile_update(
|
||||||
uid: &String,
|
uid: &str,
|
||||||
url: &String,
|
url: &str,
|
||||||
opt: Option<&PrfOption>,
|
opt: Option<&PrfOption>,
|
||||||
option: Option<&PrfOption>,
|
option: Option<&PrfOption>,
|
||||||
is_mannual_trigger: bool,
|
is_mannual_trigger: bool,
|
||||||
@@ -234,7 +234,7 @@ async fn perform_profile_update(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_mannual_trigger))]
|
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_mannual_trigger))]
|
||||||
pub async fn update_profile(uid: &String, option: Option<&PrfOption>, is_mannual_trigger: bool) -> Result<()> {
|
pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_mannual_trigger: bool) -> Result<()> {
|
||||||
let url_opt = should_update_profile(uid, is_mannual_trigger).await?;
|
let url_opt = should_update_profile(uid, is_mannual_trigger).await?;
|
||||||
|
|
||||||
let profile_persisted = match url_opt {
|
let profile_persisted = match url_opt {
|
||||||
@@ -245,7 +245,7 @@ pub async fn update_profile(uid: &String, option: Option<&PrfOption>, is_mannual
|
|||||||
None => false,
|
None => false,
|
||||||
};
|
};
|
||||||
let profiles = Config::profiles().await;
|
let profiles = Config::profiles().await;
|
||||||
let is_current = profiles.latest_arc().current.as_ref() == Some(uid);
|
let is_current = profiles.latest_arc().current.as_deref() == Some(uid);
|
||||||
let should_refresh = is_current || (!profile_persisted && is_mannual_trigger);
|
let should_refresh = is_current || (!profile_persisted && is_mannual_trigger);
|
||||||
|
|
||||||
if should_refresh {
|
if should_refresh {
|
||||||
|
|||||||
@@ -2,10 +2,12 @@
|
|||||||
|
|
||||||
use crate::core::notify::NoticeStatus;
|
use crate::core::notify::NoticeStatus;
|
||||||
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::{
|
||||||
|
mem::DropGuard,
|
||||||
|
sync::atomic::{AtomicBool, Ordering},
|
||||||
|
};
|
||||||
|
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use scopeguard::defer;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{Config, IVerge},
|
config::{Config, IVerge},
|
||||||
@@ -61,9 +63,9 @@ pub async fn reconcile_tun_availability() {
|
|||||||
|
|
||||||
// The flag coalesces newly spawned tasks while the config lock serializes writers.
|
// The flag coalesces newly spawned tasks while the config lock serializes writers.
|
||||||
DISABLING_TUN.store(true, Ordering::Release);
|
DISABLING_TUN.store(true, Ordering::Release);
|
||||||
defer! {
|
let _disabling_tun = DropGuard::new((), |()| {
|
||||||
DISABLING_TUN.store(false, Ordering::Release);
|
DISABLING_TUN.store(false, Ordering::Release);
|
||||||
}
|
});
|
||||||
|
|
||||||
logging!(
|
logging!(
|
||||||
info,
|
info,
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ fn main() -> ExitCode {
|
|||||||
|
|
||||||
#[cfg(not(all(feature = "perf-harness", target_os = "macos")))]
|
#[cfg(not(all(feature = "perf-harness", target_os = "macos")))]
|
||||||
fn main() -> ExitCode {
|
fn main() -> ExitCode {
|
||||||
let default_parallelism = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
|
let default_parallelism = std::thread::available_parallelism().map_or(1, |n| n.get());
|
||||||
let worker_limit = std::cmp::min(default_parallelism, 4);
|
let worker_limit = std::cmp::min(default_parallelism, 4);
|
||||||
let blocking_limit = 2 * worker_limit;
|
let blocking_limit = 2 * worker_limit;
|
||||||
|
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ pub async fn connect_traffic_stream() -> Result<MihomoWsEventStream<TrafficSpeed
|
|||||||
.ws_traffic({
|
.ws_traffic({
|
||||||
let message_tx = message_tx.clone();
|
let message_tx = message_tx.clone();
|
||||||
move |message| {
|
move |message| {
|
||||||
if let Some(event) = parse_traffic_event(&message) {
|
if let Some(event) = parse_traffic_event(message.as_bytes()) {
|
||||||
try_send_internal_event(&message_tx, event);
|
try_send_internal_event(&message_tx, event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+25
-13
@@ -3,10 +3,10 @@ use crate::{config::with_encryption, process::AsyncHandler};
|
|||||||
use anyhow::{Context as _, Result, anyhow, bail};
|
use anyhow::{Context as _, Result, anyhow, bail};
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use nanoid::nanoid;
|
use nanoid::nanoid;
|
||||||
use scopeguard::{ScopeGuard, guard};
|
|
||||||
use serde::{Serialize, de::DeserializeOwned};
|
use serde::{Serialize, de::DeserializeOwned};
|
||||||
use serde_yaml_ng::{Mapping, Value};
|
use serde_yaml_ng::{Mapping, Value};
|
||||||
use std::{
|
use std::{
|
||||||
|
mem::DropGuard,
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
str::FromStr,
|
str::FromStr,
|
||||||
};
|
};
|
||||||
@@ -137,16 +137,11 @@ fn is_short_id(key: &Value) -> bool {
|
|||||||
pub async fn save_yaml<T: Serialize + Sync>(path: &Path, data: &T, prefix: Option<&str>) -> Result<()> {
|
pub async fn save_yaml<T: Serialize + Sync>(path: &Path, data: &T, prefix: Option<&str>) -> Result<()> {
|
||||||
let data_str = with_encryption(|| async { serde_yaml_ng::to_string(data) }).await?;
|
let data_str = with_encryption(|| async { serde_yaml_ng::to_string(data) }).await?;
|
||||||
|
|
||||||
let yaml_str = match prefix {
|
save_yaml_str(path, &data_str, prefix).await
|
||||||
Some(prefix) => format!("{prefix}\n\n{data_str}"),
|
|
||||||
None => data_str,
|
|
||||||
};
|
|
||||||
|
|
||||||
save_yaml_str(path, &yaml_str).await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Atomic replace with pre-serialized content; the payload must not need the encryption scope.
|
/// Atomic replace with pre-serialized content; the payload must not need the encryption scope.
|
||||||
pub async fn save_yaml_str(path: &Path, yaml_str: &str) -> Result<()> {
|
pub async fn save_yaml_str(path: &Path, yaml_str: &str, prefix: Option<&str>) -> Result<()> {
|
||||||
let (temporary, file) = loop {
|
let (temporary, file) = loop {
|
||||||
let temporary = path.with_extension(format!("tmp-{}-{}", std::process::id(), nanoid!()));
|
let temporary = path.with_extension(format!("tmp-{}-{}", std::process::id(), nanoid!()));
|
||||||
match std::fs::OpenOptions::new()
|
match std::fs::OpenOptions::new()
|
||||||
@@ -168,13 +163,20 @@ pub async fn save_yaml_str(path: &Path, yaml_str: &str) -> Result<()> {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let temporary = guard(temporary, |path| {
|
let temporary = DropGuard::new(temporary, |path| {
|
||||||
let _ = std::fs::remove_file(path);
|
let _ = std::fs::remove_file(path);
|
||||||
});
|
});
|
||||||
let mut file = tokio::fs::File::from_std(file);
|
let mut file = tokio::fs::File::from_std(file);
|
||||||
file.write_all(yaml_str.as_bytes())
|
async fn write_chunk(file: &mut tokio::fs::File, bytes: &[u8], path: &Path) -> Result<()> {
|
||||||
.await
|
file.write_all(bytes)
|
||||||
.with_context(|| format!("failed to write temporary file for \"{}\"", path.display()))?;
|
.await
|
||||||
|
.with_context(|| format!("failed to write temporary file for \"{}\"", path.display()))
|
||||||
|
}
|
||||||
|
if let Some(prefix) = prefix {
|
||||||
|
write_chunk(&mut file, prefix.as_bytes(), path).await?;
|
||||||
|
write_chunk(&mut file, b"\n\n", path).await?;
|
||||||
|
}
|
||||||
|
write_chunk(&mut file, yaml_str.as_bytes(), path).await?;
|
||||||
file.flush()
|
file.flush()
|
||||||
.await
|
.await
|
||||||
.with_context(|| format!("failed to flush temporary file for \"{}\"", path.display()))?;
|
.with_context(|| format!("failed to flush temporary file for \"{}\"", path.display()))?;
|
||||||
@@ -195,7 +197,7 @@ pub async fn save_yaml_str(path: &Path, yaml_str: &str) -> Result<()> {
|
|||||||
|
|
||||||
std::fs::rename(temporary.as_path(), path)
|
std::fs::rename(temporary.as_path(), path)
|
||||||
.with_context(|| format!("failed to replace file \"{}\"", path.display()))?;
|
.with_context(|| format!("failed to replace file \"{}\"", path.display()))?;
|
||||||
let _ = ScopeGuard::into_inner(temporary);
|
let _ = DropGuard::dismiss(temporary);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -220,6 +222,16 @@ pub fn parse_str<T: FromStr>(target: &str, key: &str) -> Option<T> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn hex_encode(bytes: &[u8]) -> String {
|
||||||
|
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||||
|
let mut out = String::with_capacity(bytes.len() * 2);
|
||||||
|
for &byte in bytes {
|
||||||
|
out.push(HEX[usize::from(byte >> 4)] as char);
|
||||||
|
out.push(HEX[usize::from(byte & 0x0f)] as char);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
/// Masks query values and token-like path segments for logging.
|
/// Masks query values and token-like path segments for logging.
|
||||||
pub fn mask_url(url: &str) -> String {
|
pub fn mask_url(url: &str) -> String {
|
||||||
let (path_part, query_part) = match url.find('?') {
|
let (path_part, query_part) = match url.find('?') {
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ fn extract_subscription_info(link_parsed: &Url) -> Option<(std::string::String,
|
|||||||
let name = link_parsed
|
let name = link_parsed
|
||||||
.query_pairs()
|
.query_pairs()
|
||||||
.find(|(key, _)| key == "name")
|
.find(|(key, _)| key == "name")
|
||||||
.map(|(_, value)| value.into_owned().into());
|
.map(|(_, value)| value.into());
|
||||||
let url = extract_subscription_url(link_parsed)?;
|
let url = extract_subscription_url(link_parsed)?;
|
||||||
Some((url, name))
|
Some((url, name))
|
||||||
}
|
}
|
||||||
@@ -123,7 +123,7 @@ async fn fetch_profile_item(url: &str, name: Option<&String>) -> Option<PrfItem>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn post_import_updates(uid: &String, had_current_profile: bool) {
|
async fn post_import_updates(uid: &str, had_current_profile: bool) {
|
||||||
handle::Handle::refresh_verge();
|
handle::Handle::refresh_verge();
|
||||||
handle::Handle::notify_profile_changed(uid);
|
handle::Handle::notify_profile_changed(uid);
|
||||||
|
|
||||||
@@ -131,7 +131,7 @@ async fn post_import_updates(uid: &String, had_current_profile: bool) {
|
|||||||
false
|
false
|
||||||
} else {
|
} else {
|
||||||
let profiles = Config::profiles().await;
|
let profiles = Config::profiles().await;
|
||||||
profiles.latest_arc().current.as_ref() == Some(uid)
|
profiles.latest_arc().current.as_deref() == Some(uid)
|
||||||
};
|
};
|
||||||
|
|
||||||
if should_update_core {
|
if should_update_core {
|
||||||
|
|||||||
@@ -234,15 +234,15 @@ impl WindowManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_main_window_visible(window: Option<&WebviewWindow<Wry>>) -> bool {
|
pub fn is_main_window_visible(window: Option<&WebviewWindow<Wry>>) -> bool {
|
||||||
window.map(|w| w.is_visible().unwrap_or(false)).unwrap_or(false)
|
window.is_some_and(|w| w.is_visible().unwrap_or(false))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_main_window_focused(window: Option<&WebviewWindow<Wry>>) -> bool {
|
pub fn is_main_window_focused(window: Option<&WebviewWindow<Wry>>) -> bool {
|
||||||
window.map(|w| w.is_focused().unwrap_or(false)).unwrap_or(false)
|
window.is_some_and(|w| w.is_focused().unwrap_or(false))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_main_window_minimized(window: Option<&WebviewWindow<Wry>>) -> bool {
|
fn is_main_window_minimized(window: Option<&WebviewWindow<Wry>>) -> bool {
|
||||||
window.map(|w| w.is_minimized().unwrap_or(false)).unwrap_or(false)
|
window.is_some_and(|w| w.is_minimized().unwrap_or(false))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Keep new windows hidden until the frontend overlay renders, avoiding a theme flash.
|
/// Keep new windows hidden until the frontend overlay renders, avoiding a theme flash.
|
||||||
|
|||||||
@@ -389,7 +389,7 @@ export const ConnectionTable = (props: Props) => {
|
|||||||
{
|
{
|
||||||
field: 'download',
|
field: 'download',
|
||||||
headerName: t('shared.labels.downloaded'),
|
headerName: t('shared.labels.downloaded'),
|
||||||
width: 76,
|
width: 96,
|
||||||
minWidth: 60,
|
minWidth: 60,
|
||||||
align: 'right',
|
align: 'right',
|
||||||
cell: (_, snapshot) => snapshot.downloadText,
|
cell: (_, snapshot) => snapshot.downloadText,
|
||||||
@@ -397,7 +397,7 @@ export const ConnectionTable = (props: Props) => {
|
|||||||
{
|
{
|
||||||
field: 'upload',
|
field: 'upload',
|
||||||
headerName: t('shared.labels.uploaded'),
|
headerName: t('shared.labels.uploaded'),
|
||||||
width: 76,
|
width: 96,
|
||||||
minWidth: 60,
|
minWidth: 60,
|
||||||
align: 'right',
|
align: 'right',
|
||||||
cell: (_, snapshot) => snapshot.uploadText,
|
cell: (_, snapshot) => snapshot.uploadText,
|
||||||
@@ -405,7 +405,7 @@ export const ConnectionTable = (props: Props) => {
|
|||||||
{
|
{
|
||||||
field: 'dlSpeed',
|
field: 'dlSpeed',
|
||||||
headerName: t('connections.components.fields.dlSpeed'),
|
headerName: t('connections.components.fields.dlSpeed'),
|
||||||
width: 76,
|
width: 96,
|
||||||
minWidth: 60,
|
minWidth: 60,
|
||||||
align: 'right',
|
align: 'right',
|
||||||
cell: (_, snapshot) => snapshot.downloadSpeedText,
|
cell: (_, snapshot) => snapshot.downloadSpeedText,
|
||||||
@@ -413,7 +413,7 @@ export const ConnectionTable = (props: Props) => {
|
|||||||
{
|
{
|
||||||
field: 'ulSpeed',
|
field: 'ulSpeed',
|
||||||
headerName: t('connections.components.fields.ulSpeed'),
|
headerName: t('connections.components.fields.ulSpeed'),
|
||||||
width: 76,
|
width: 96,
|
||||||
minWidth: 60,
|
minWidth: 60,
|
||||||
align: 'right',
|
align: 'right',
|
||||||
cell: (_, snapshot) => snapshot.uploadSpeedText,
|
cell: (_, snapshot) => snapshot.uploadSpeedText,
|
||||||
@@ -798,6 +798,7 @@ export const ConnectionTable = (props: Props) => {
|
|||||||
onClick={() => toggleSorting(column.field)}
|
onClick={() => toggleSorting(column.field)}
|
||||||
style={{
|
style={{
|
||||||
flex: 1,
|
flex: 1,
|
||||||
|
minWidth: 0,
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
justifyContent:
|
justifyContent:
|
||||||
@@ -809,15 +810,33 @@ export const ConnectionTable = (props: Props) => {
|
|||||||
color: 'inherit',
|
color: 'inherit',
|
||||||
font: 'inherit',
|
font: 'inherit',
|
||||||
textAlign: column.align === 'right' ? 'right' : 'left',
|
textAlign: column.align === 'right' ? 'right' : 'left',
|
||||||
|
whiteSpace: 'nowrap',
|
||||||
cursor: 'pointer',
|
cursor: 'pointer',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{column.headerName}
|
<span
|
||||||
{sorting?.id === column.field
|
style={{
|
||||||
? sorting.desc
|
minWidth: 0,
|
||||||
? '▼'
|
overflow: 'hidden',
|
||||||
: '▲'
|
textOverflow: 'ellipsis',
|
||||||
: null}
|
}}
|
||||||
|
>
|
||||||
|
{column.headerName}
|
||||||
|
</span>
|
||||||
|
{sorting?.id === column.field ? (
|
||||||
|
<span style={{ flexShrink: 0 }}>
|
||||||
|
{sorting.desc ? '▼' : '▲'}
|
||||||
|
</span>
|
||||||
|
) : column.align === 'right' ? (
|
||||||
|
// Reserve the indicator's space so right-aligned labels
|
||||||
|
// don't shift when sorting is toggled.
|
||||||
|
<span
|
||||||
|
aria-hidden
|
||||||
|
style={{ flexShrink: 0, visibility: 'hidden' }}
|
||||||
|
>
|
||||||
|
▲
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
</button>
|
</button>
|
||||||
<div
|
<div
|
||||||
onMouseDown={(event) =>
|
onMouseDown={(event) =>
|
||||||
|
|||||||
@@ -1008,8 +1008,13 @@ export const CurrentProxyCard = () => {
|
|||||||
border: `1px solid ${alpha(theme.palette.primary.main, 0.1)}`,
|
border: `1px solid ${alpha(theme.palette.primary.main, 0.1)}`,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Box>
|
<Box sx={{ minWidth: 0, flex: 1 }}>
|
||||||
<Typography variant="body1" sx={{ fontWeight: 'medium' }}>
|
<Typography
|
||||||
|
variant="body1"
|
||||||
|
noWrap
|
||||||
|
title={currentProxy?.name}
|
||||||
|
sx={{ fontWeight: 'medium' }}
|
||||||
|
>
|
||||||
{currentProxy?.name ??
|
{currentProxy?.name ??
|
||||||
t('home.components.currentProxy.labels.noActiveNode')}
|
t('home.components.currentProxy.labels.noActiveNode')}
|
||||||
</Typography>
|
</Typography>
|
||||||
@@ -1063,6 +1068,7 @@ export const CurrentProxyCard = () => {
|
|||||||
size="small"
|
size="small"
|
||||||
label={delayManager.formatDelay(currentDelay)}
|
label={delayManager.formatDelay(currentDelay)}
|
||||||
color={convertDelayColor(currentDelay)}
|
color={convertDelayColor(currentDelay)}
|
||||||
|
sx={{ flexShrink: 0, ml: 1 }}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
|
|||||||
@@ -1106,10 +1106,9 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
|
|
||||||
{tooltipData.visible && (
|
{tooltipData.visible && (
|
||||||
<Box
|
<Box
|
||||||
|
style={{ left: tooltipData.x + 8, top: tooltipData.y - 8 }}
|
||||||
sx={{
|
sx={{
|
||||||
position: 'absolute',
|
position: 'absolute',
|
||||||
left: tooltipData.x + 8,
|
|
||||||
top: tooltipData.y - 8,
|
|
||||||
bgcolor: theme.palette.background.paper,
|
bgcolor: theme.palette.background.paper,
|
||||||
border: 1,
|
border: 1,
|
||||||
borderColor: 'divider',
|
borderColor: 'divider',
|
||||||
|
|||||||
@@ -463,15 +463,12 @@ export const ProxyChain = ({
|
|||||||
|
|
||||||
localStorage.removeItem('proxy-chain-group')
|
localStorage.removeItem('proxy-chain-group')
|
||||||
localStorage.removeItem('proxy-chain-exit-node')
|
localStorage.removeItem('proxy-chain-exit-node')
|
||||||
localStorage.removeItem('proxy-chain-items')
|
|
||||||
|
|
||||||
await mutate(() => closeAllConnections(), {
|
await mutate(() => closeAllConnections(), {
|
||||||
id: 'close-all-connections',
|
id: 'close-all-connections',
|
||||||
errorNotice: false,
|
errorNotice: false,
|
||||||
})
|
})
|
||||||
await refreshProxy()
|
await refreshProxy()
|
||||||
|
|
||||||
onUpdateChain([])
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to disconnect from proxy chain:', error)
|
console.error('Failed to disconnect from proxy chain:', error)
|
||||||
alert(t('proxies.page.chain.disconnectFailed'))
|
alert(t('proxies.page.chain.disconnectFailed'))
|
||||||
@@ -550,7 +547,6 @@ export const ProxyChain = ({
|
|||||||
mode,
|
mode,
|
||||||
proxyView,
|
proxyView,
|
||||||
selectedGroup,
|
selectedGroup,
|
||||||
onUpdateChain,
|
|
||||||
recordSelection,
|
recordSelection,
|
||||||
])
|
])
|
||||||
|
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ export function TunViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
|||||||
autoDetectInterface: true,
|
autoDetectInterface: true,
|
||||||
dnsHijack: ['any:53'],
|
dnsHijack: ['any:53'],
|
||||||
strictRoute: false,
|
strictRoute: false,
|
||||||
mtu: 1500,
|
mtu: 1500 as number | undefined,
|
||||||
dnsMode: '',
|
dnsMode: '',
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -374,14 +374,15 @@ export function TunViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
|||||||
autoCapitalize="off"
|
autoCapitalize="off"
|
||||||
spellCheck="false"
|
spellCheck="false"
|
||||||
sx={{ width: 250 }}
|
sx={{ width: 250 }}
|
||||||
value={values.mtu}
|
value={values.mtu ?? ''}
|
||||||
placeholder="1500"
|
placeholder="1500"
|
||||||
onChange={(e) =>
|
onChange={(e) => {
|
||||||
|
const next = Number.parseInt(e.target.value, 10)
|
||||||
setValues((v) => ({
|
setValues((v) => ({
|
||||||
...v,
|
...v,
|
||||||
mtu: parseInt(e.target.value),
|
mtu: Number.isNaN(next) ? undefined : next,
|
||||||
}))
|
}))
|
||||||
}
|
}}
|
||||||
/>
|
/>
|
||||||
</ListItem>
|
</ListItem>
|
||||||
|
|
||||||
|
|||||||
@@ -363,6 +363,8 @@ const handleSummaryText = (messageData: string) => {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (connectionSummary.activeConnectionCount === (payload.count ?? 0)) return
|
||||||
|
|
||||||
connectionSummary = mergeConnectionSummary(payload)
|
connectionSummary = mergeConnectionSummary(payload)
|
||||||
notifySummaryListeners()
|
notifySummaryListeners()
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user