Compare commits

..
139 changed files with 3101 additions and 2789 deletions
+1 -1
View File
@@ -5,7 +5,7 @@
"features": { "features": {
"ghcr.io/devcontainers/features/node:2": { "ghcr.io/devcontainers/features/node:2": {
"version": "26.13.1", "version": "26.13.1",
"pnpmVersion": "12.21.0" "pnpmVersion": "12.18.0"
}, },
"ghcr.io/devcontainers/features/rust:1": { "ghcr.io/devcontainers/features/rust:1": {
"version": "1.100.0", "version": "1.100.0",
-31
View File
@@ -1,31 +0,0 @@
# Issue and PR Guidelines
These rules apply to Issue and PR work, including operations through `gh` or an
API. The root [AGENTS.md](../AGENTS.md) defines the repository-wide contract.
## Issues
When creating, drafting, triaging, splitting, or implementing from a community
issue, follow [ISSUE_GUIDELINES.md](ISSUE_GUIDELINES.md). Do not create or modify
GitHub issues without explicit authorization.
## PR Descriptions
When creating or updating a PR body, follow the
[PR template](PULL_REQUEST_TEMPLATE.md). Describe the final change; replace stale
text instead of appending work history. Omit routine check-pass declarations,
including Clippy, lint, and local tests. Keep only evidence and limitations that
help reviewers assess the change; the template defines what belongs in the body
and when Scope is needed.
Before publishing or updating a PR body, remove repetition, self-evaluation, and
details already clear from the diff. Keep only sentences that help review the
change.
## AI Disclosure
When an agent creates or co-creates a PR or Issue, append a final body line with
the model and effort used (e.g. `Assisted by: GPT-5.6 High`). Effort may be omitted
when the runtime does not report it. Human contributors are not asked to disclose
AI assistance. Disclosure is transparency only and carries no positive or
negative weight.
+1 -29
View File
@@ -1,29 +1,3 @@
<!--
Describe the final problem, approach, and evidence needed to review this change.
When updating the body, replace stale text instead of appending implementation
history or review-round summaries.
State each fact once. Omit details already clear from the diff unless they
explain a non-obvious constraint or trade-off. Describe concrete behavior instead
of self-evaluation or unsupported assurances such as "more robust" or "seamless".
Mention unchanged behavior or excluded areas only when they matter to review.
Before publishing, remove any sentence whose deletion loses no information
needed to understand the problem, approach, evidence, or material limitations.
Omit file-by-file diff summaries, internal planning scores, agent handoffs, and
routine check results such as "Clippy passed", "lint passed", or "local tests
passed". Do not add a Validation/Testing section for a command checklist.
Include concrete before/after behavior or measurements when they support the
change, and retain limitations that affect review. Link reviewer-accessible
details when needed; do not paste full scripts, logs, or test matrices into the
body, including collapsed sections.
Keep Scope only when explaining necessary changes outside the core fix, PR
dependencies, or why added tests are needed. Do not repeat Approach there.
For small changes, Problem and Approach may be combined into one short paragraph;
remove unnecessary headings instead of adding text to fill them.
-->
## Problem ## Problem
What breaks or what is missing. Product bug fixes and features require a What breaks or what is missing. Product bug fixes and features require a
@@ -40,6 +14,4 @@ Why this change solves the problem — the reasoning behind the approach, not a
## Scope ## Scope
Optional: explain necessary changes outside the core fix, PR dependencies, or What changed. If anything outside the core fix was touched, explain why it was necessary. New tests are not expected by default — if any were added, justify why each is needed.
why added tests are needed. Otherwise remove this section. New tests are not
expected by default.
+13 -58
View File
@@ -5,10 +5,10 @@
"version": "v9.0.0", "version": "v9.0.0",
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3" "sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
}, },
"github/gh-aw-actions/setup@v1.3.1": { "github/gh-aw-actions/setup@v1.2.2": {
"repo": "github/gh-aw-actions/setup", "repo": "github/gh-aw-actions/setup",
"version": "v1.3.1", "version": "v1.2.2",
"sha": "dfe97a19c8249d41e2adfc95f92db2b8facea58f" "sha": "53d0749e19424a918acd82b4d140264ce48f2f14"
} }
}, },
"containers": { "containers": {
@@ -32,16 +32,6 @@
"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",
@@ -62,31 +52,6 @@
"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",
@@ -107,30 +72,20 @@
"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-firewall/squid:0.29.11": { "ghcr.io/github/gh-aw-mcpg:v0.4.25": {
"image": "ghcr.io/github/gh-aw-firewall/squid:0.29.11", "image": "ghcr.io/github/gh-aw-mcpg:v0.4.25",
"digest": "sha256:861739ecf924dd2db5e5fb652db2ad82aaafd1615623297ddabc8f41a36b2847", "digest": "sha256:9be0a86220e807a0ecc89e53d7453468f7a53fbc6b3d1efd2299025ffe01d086",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.11@sha256:861739ecf924dd2db5e5fb652db2ad82aaafd1615623297ddabc8f41a36b2847" "pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.4.25@sha256:9be0a86220e807a0ecc89e53d7453468f7a53fbc6b3d1efd2299025ffe01d086"
},
"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:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f", "digest": "sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e",
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f" "pinned_image": "ghcr.io/github/gh-aw-node@sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e"
}, },
"ghcr.io/github/github-mcp-server:v2.1.0": { "ghcr.io/github/github-mcp-server:v1.12.2": {
"image": "ghcr.io/github/github-mcp-server:v2.1.0", "image": "ghcr.io/github/github-mcp-server:v1.12.2",
"digest": "sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a", "digest": "sha256:508a0857ec762b1ab1cece29193345b501fab1dd9d1228a7b617062954cecac6",
"pinned_image": "ghcr.io/github/github-mcp-server:v2.1.0@sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a" "pinned_image": "ghcr.io/github/github-mcp-server:v1.12.2@sha256:508a0857ec762b1ab1cece29193345b501fab1dd9d1228a7b617062954cecac6"
} }
} }
} }
+2 -2
View File
@@ -31,9 +31,9 @@ jobs:
with: with:
persist-credentials: false persist-credentials: false
- name: Install gh-aw extension - name: Install gh-aw extension
uses: github/gh-aw-actions/setup-cli@dfe97a19c8249d41e2adfc95f92db2b8facea58f # v1.3.1 uses: github/gh-aw-actions/setup-cli@862164f9ffbcce2e24e5397da938e3b19f839dce # v1.2.3
with: with:
version: v1.3.1 version: v1.2.2
- name: Install Rust Stable - name: Install Rust Stable
uses: dtolnay/rust-toolchain@stable uses: dtolnay/rust-toolchain@stable
with: with:
+2 -5
View File
@@ -12,7 +12,6 @@ on:
- REVIEW.md - REVIEW.md
- src/AGENTS.md - src/AGENTS.md
- src-tauri/AGENTS.md - src-tauri/AGENTS.md
- .github/AGENTS.md
- .github/ISSUE_GUIDELINES.md - .github/ISSUE_GUIDELINES.md
- .github/agents/agentic-workflows.md - .github/agents/agentic-workflows.md
- .github/skills/agentic-workflows/SKILL.md - .github/skills/agentic-workflows/SKILL.md
@@ -31,7 +30,6 @@ on:
- REVIEW.md - REVIEW.md
- src/AGENTS.md - src/AGENTS.md
- src-tauri/AGENTS.md - src-tauri/AGENTS.md
- .github/AGENTS.md
- .github/ISSUE_GUIDELINES.md - .github/ISSUE_GUIDELINES.md
- .github/agents/agentic-workflows.md - .github/agents/agentic-workflows.md
- .github/skills/agentic-workflows/SKILL.md - .github/skills/agentic-workflows/SKILL.md
@@ -59,8 +57,7 @@ jobs:
check AGENTS.md 'Issue first' check AGENTS.md 'Issue first'
check AGENTS.md 'Author accountability' check AGENTS.md 'Author accountability'
check AGENTS.md 'pr-ai-slop-review' check AGENTS.md 'pr-ai-slop-review'
check AGENTS.md '(.github/AGENTS.md)' check AGENTS.md 'Disclose AI automation'
check .github/AGENTS.md '## AI Disclosure'
check CONTRIBUTING.md 'Assisted by:' check CONTRIBUTING.md 'Assisted by:'
check .github/workflows/pr-ai-slop-review.md '(../../CONTRIBUTING.md)' check .github/workflows/pr-ai-slop-review.md '(../../CONTRIBUTING.md)'
check .github/workflows/pr-ai-slop-review.md '(../../AGENTS.md)' check .github/workflows/pr-ai-slop-review.md '(../../AGENTS.md)'
@@ -87,7 +84,7 @@ jobs:
sources = [ sources = [
"AGENTS.md", "CONTRIBUTING.md", "REVIEW.md", "CLAUDE.md", "GEMINI.md", "AGENTS.md", "CONTRIBUTING.md", "REVIEW.md", "CLAUDE.md", "GEMINI.md",
"src/AGENTS.md", "src-tauri/AGENTS.md", ".github/AGENTS.md", ".github/ISSUE_GUIDELINES.md", "src/AGENTS.md", "src-tauri/AGENTS.md", ".github/ISSUE_GUIDELINES.md",
".github/PULL_REQUEST_TEMPLATE.md", ".github/workflows/pr-ai-slop-review.md", ".github/PULL_REQUEST_TEMPLATE.md", ".github/workflows/pr-ai-slop-review.md",
".github/workflows/pr-verify-fix.md", ".github/workflows/pr-verify-fix.md",
".github/agents/agentic-workflows.md", ".github/skills/agentic-workflows/SKILL.md", ".github/agents/agentic-workflows.md", ".github/skills/agentic-workflows/SKILL.md",
File diff suppressed because one or more lines are too long
-4
View File
@@ -30,10 +30,6 @@ max-ai-credits: 60
max-turns: 12 max-turns: 12
max-daily-ai-credits: 5000 max-daily-ai-credits: 5000
# Routine, low-risk tasks such as triage, labeling, and summaries.
# See https://github.github.com/gh-aw/reference/model-routing/#setting-the-level-yourself
model: router/economy
permissions: permissions:
issues: read issues: read
pull-requests: read pull-requests: read
+101 -116
View File
File diff suppressed because one or more lines are too long
-3
View File
@@ -26,9 +26,6 @@ imports:
max-ai-credits: 60 max-ai-credits: 60
max-turns: 12 max-turns: 12
max-daily-ai-credits: 500 max-daily-ai-credits: 500
# Routine, low-risk tasks such as triage, labeling, and summaries.
# See https://github.github.com/gh-aw/reference/model-routing/#setting-the-level-yourself
model: router/economy
permissions: permissions:
contents: read contents: read
issues: read issues: read
File diff suppressed because one or more lines are too long
+1 -6
View File
@@ -32,13 +32,8 @@ permissions:
max-ai-credits: 60 max-ai-credits: 60
max-turns: 12 max-turns: 12
max-daily-ai-credits: 500 max-daily-ai-credits: 500
# Routine, low-risk tasks such as triage, labeling, and summaries.
# See https://github.github.com/gh-aw/reference/model-routing/#setting-the-level-yourself
model: router/economy
network: network:
# GitHub CLI recommend using ecosystem identifiers instead of individual domain names for better maintainability, allowed: [github, docs.rs, doc.rust-lang.org, nodejs.org, www.typescriptlang.org]
# hence "node" is prefer than "nodejs.org"
allowed: [github, docs.rs, doc.rust-lang.org, node, www.typescriptlang.org]
steps: steps:
- name: Load trusted metadata parser - name: Load trusted metadata parser
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+1 -1
View File
@@ -1,3 +1,3 @@
nodejs 26.13.1 nodejs 26.13.1
pnpm 12.21.0 pnpm 12.18.0
rust 1.100.0 rust 1.100.0
+12 -4
View File
@@ -48,11 +48,16 @@ the ownership evidence the AI-slop review evaluates (see
8. **Minimal diffs.** Match the surrounding code's style, naming, and comment 8. **Minimal diffs.** Match the surrounding code's style, naming, and comment
density. Do not introduce new dependencies or restructure working code unless density. Do not introduce new dependencies or restructure working code unless
the linked issue or stated task demands it. the linked issue or stated task demands it.
9. **Compiled workflows.** Agentic workflow Markdown, including the 9. **Disclose AI automation.** When an agent creates or co-creates a PR or Issue,
append a final body line with the model and effort used (e.g.
`Assisted by: GPT-5.6 High`). Effort may be omitted when the runtime does not
report it. Human contributors are not asked to disclose AI assistance.
Disclosure is transparency only and carries no positive or negative weight.
10. **Compiled workflows.** Agentic workflow Markdown, including the
[AI-slop policy](.github/workflows/pr-ai-slop-review.md) and shared imports, [AI-slop policy](.github/workflows/pr-ai-slop-review.md) and shared imports,
is compiled: after editing it, run `gh aw compile` and commit the affected is compiled: after editing it, run `gh aw compile` and commit the affected
`.lock.yml` files. Never edit lock files directly. `.lock.yml` files. Never edit lock files directly.
10. **Changelog.** Entries follow the rules in 11. **Changelog.** Entries follow the rules in
[`template/Changelog.md`](template/Changelog.md): one line per [`template/Changelog.md`](template/Changelog.md): one line per
user-visible change, no internals. user-visible change, no internals.
@@ -73,5 +78,8 @@ the ownership evidence the AI-slop review evaluates (see
## Issue and PR Workflows ## Issue and PR Workflows
For Issue and PR work, read [`.github/AGENTS.md`](.github/AGENTS.md), including When drafting, triaging, splitting, or implementing from a community issue, use
when using `gh` or an API without editing files under `.github/`. the conditional checklist in [`.github/ISSUE_GUIDELINES.md`](.github/ISSUE_GUIDELINES.md).
Do not make GitHub issue changes without explicit authorization. For PRs, follow
the directly loaded [PR template](.github/PULL_REQUEST_TEMPLATE.md); do not
duplicate its prompts here.
+3 -4
View File
@@ -168,10 +168,9 @@ to run every command for every change. Run commands from the repository root.
Tie results to the code reviewed: identify the base/head commits for branch Tie results to the code reviewed: identify the base/head commits for branch
comparisons and include task-relevant staged, unstaged, and untracked files in a comparisons and include task-relevant staged, unstaged, and untracked files in a
local review. Keep command-level results in the working conversation. For PR local review. Report
descriptions, follow the [PR template](.github/PULL_REQUEST_TEMPLATE.md): include the command or interaction, observed result, and material gaps in the existing
behavioral evidence and material gaps relevant to review, omitting routine check conversation or PR; no separate verification report is required. Static checks,
pass lists. No separate verification report is required. Static checks,
mocks, browser previews, native runs, and remote CI establish different things. mocks, browser previews, native runs, and remote CI establish different things.
When code changes after verification, repeat affected checks. Attribute a failure When code changes after verification, repeat affected checks. Attribute a failure
to the baseline only after comparing the same check on the base revision. to the baseline only after comparing the same check on the base revision.
Generated
+46 -56
View File
@@ -912,7 +912,7 @@ checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9"
dependencies = [ dependencies = [
"semver 1.0.28", "semver 1.0.28",
"serde", "serde",
"toml 1.2.1+spec-1.1.0", "toml 1.1.6+spec-1.1.0",
] ]
[[package]] [[package]]
@@ -1127,6 +1127,7 @@ dependencies = [
"serde_json", "serde_json",
"serde_yaml_ng", "serde_yaml_ng",
"sha2 0.11.1", "sha2 0.11.1",
"smartstring",
"socket2", "socket2",
"specta", "specta",
"specta-typescript", "specta-typescript",
@@ -1154,7 +1155,6 @@ dependencies = [
"tokio-rustls", "tokio-rustls",
"tokio-util", "tokio-util",
"tracing", "tracing",
"tristr",
"warp", "warp",
"webpki-roots", "webpki-roots",
"windows 0.62.2", "windows 0.62.2",
@@ -1223,8 +1223,8 @@ dependencies = [
[[package]] [[package]]
name = "clash_verge_service_ipc" name = "clash_verge_service_ipc"
version = "2.8.1" version = "2.7.7"
source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?tag=v2.8.1#9d4ea7d27fb3c43804bd18f3bb3b686528763239" source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?tag=v2.7.7#3ed29700b093190b5e7addcaa892e77f172af544"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"kode-bridge", "kode-bridge",
@@ -2202,7 +2202,7 @@ dependencies = [
"cc", "cc",
"memchr", "memchr",
"rustc_version 0.4.1", "rustc_version 0.4.1",
"toml 1.2.1+spec-1.1.0", "toml 1.1.6+spec-1.1.0",
"vswhom", "vswhom",
"winreg 0.55.0", "winreg 0.55.0",
] ]
@@ -3877,16 +3877,16 @@ dependencies = [
[[package]] [[package]]
name = "kode-bridge" name = "kode-bridge"
version = "0.6.0" version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b17456ae84ba9c0da0f189bf00d13019805b89563ba846cd15ccd8c4bd6a2713" checksum = "cdb14ea1ba42eebb57b46bcdd67a20f11a3f076d846ddf772c68d7439f6c6eca"
dependencies = [ dependencies = [
"bytes", "bytes",
"futures", "futures",
"http", "http",
"httparse", "httparse",
"libc", "libc",
"parking_lot 0.13.0", "parking_lot 0.12.5",
"path-tree", "path-tree",
"pin-project-lite", "pin-project-lite",
"rand 0.10.2", "rand 0.10.2",
@@ -3896,7 +3896,7 @@ dependencies = [
"tokio", "tokio",
"tokio-stream", "tokio-stream",
"tokio-util", "tokio-util",
"toml 1.2.1+spec-1.1.0", "toml 1.1.6+spec-1.1.0",
"tracing", "tracing",
"url", "url",
"windows-sys 0.61.2", "windows-sys 0.61.2",
@@ -4356,18 +4356,6 @@ 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"
@@ -4894,7 +4882,7 @@ checksum = "9cf20a545b305cf1da722b236b5155c9bb35f1d5ceb28c048bd96ca842f41b5b"
dependencies = [ dependencies = [
"android_system_properties", "android_system_properties",
"log", "log",
"nix 0.31.3", "nix",
"objc2", "objc2",
"objc2-foundation", "objc2-foundation",
"objc2-ui-kit", "objc2-ui-kit",
@@ -6533,9 +6521,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_spanned" name = "serde_spanned"
version = "1.1.3" version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"
dependencies = [ dependencies = [
"serde_core", "serde_core",
] ]
@@ -6801,6 +6789,18 @@ dependencies = [
"thiserror 2.0.20", "thiserror 2.0.20",
] ]
[[package]]
name = "smartstring"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a155190f9c039a1e9b6e92efbfa50ae68daad98a0fd6d5521a5a09ef782383e8"
dependencies = [
"autocfg",
"serde",
"static_assertions",
"version_check",
]
[[package]] [[package]]
name = "socket2" name = "socket2"
version = "0.6.5" version = "0.6.5"
@@ -7086,12 +7086,11 @@ dependencies = [
[[package]] [[package]]
name = "sysproxy" name = "sysproxy"
version = "0.7.2" version = "0.7.1"
source = "git+https://github.com/clash-verge-rev/sysproxy-rs.git?rev=2c9d0a538052aac6e44ad413156a6e848da262b9#2c9d0a538052aac6e44ad413156a6e848da262b9" source = "git+https://github.com/clash-verge-rev/sysproxy-rs.git?branch=main#89ad876a0942c049ae72e1472f9fc3ed62023c5e"
dependencies = [ dependencies = [
"iptools", "iptools",
"log", "log",
"serde",
"system-configuration", "system-configuration",
"thiserror 2.0.20", "thiserror 2.0.20",
"tokio", "tokio",
@@ -7145,7 +7144,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.2.1+spec-1.1.0", "toml 1.1.6+spec-1.1.0",
"version-compare", "version-compare",
] ]
@@ -7499,7 +7498,7 @@ dependencies = [
"tauri-plugin", "tauri-plugin",
"tauri-utils", "tauri-utils",
"thiserror 2.0.20", "thiserror 2.0.20",
"toml 1.2.1+spec-1.1.0", "toml 1.1.6+spec-1.1.0",
"url", "url",
] ]
@@ -7545,8 +7544,8 @@ dependencies = [
[[package]] [[package]]
name = "tauri-plugin-mihomo" name = "tauri-plugin-mihomo"
version = "0.7.1" version = "0.7.0"
source = "git+https://github.com/clash-verge-rev/tauri-plugin-mihomo?rev=7e4fa8642cf6c394ed88b5a969420d8eab60087f#7e4fa8642cf6c394ed88b5a969420d8eab60087f" source = "git+https://github.com/clash-verge-rev/tauri-plugin-mihomo?rev=e49bbedcc67d60da2c10e81bc6433b0f8e8fa232#e49bbedcc67d60da2c10e81bc6433b0f8e8fa232"
dependencies = [ dependencies = [
"arc-swap", "arc-swap",
"clashmap", "clashmap",
@@ -7829,7 +7828,7 @@ dependencies = [
"serde_with", "serde_with",
"swift-rs", "swift-rs",
"thiserror 2.0.20", "thiserror 2.0.20",
"toml 1.2.1+spec-1.1.0", "toml 1.1.6+spec-1.1.0",
"url", "url",
"urlpattern", "urlpattern",
"uuid", "uuid",
@@ -7844,7 +7843,7 @@ checksum = "cc65d45c68858bfe420dd29e834b5d15dbecf8a07a8a16cf4d532c7b1f69d4b6"
dependencies = [ dependencies = [
"dunce", "dunce",
"embed-resource", "embed-resource",
"toml 1.2.1+spec-1.1.0", "toml 1.1.6+spec-1.1.0",
] ]
[[package]] [[package]]
@@ -8210,14 +8209,14 @@ dependencies = [
[[package]] [[package]]
name = "toml" name = "toml"
version = "1.2.1+spec-1.1.0" version = "1.1.6+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 = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a"
dependencies = [ dependencies = [
"indexmap 2.14.0", "indexmap 2.14.0",
"serde_core", "serde_core",
"serde_spanned 1.1.3", "serde_spanned 1.1.1",
"toml_datetime 1.1.3+spec-1.1.0", "toml_datetime 1.1.1+spec-1.1.0",
"toml_parser", "toml_parser",
"toml_writer", "toml_writer",
"winnow 1.0.4", "winnow 1.0.4",
@@ -8234,9 +8233,9 @@ dependencies = [
[[package]] [[package]]
name = "toml_datetime" name = "toml_datetime"
version = "1.1.3+spec-1.1.0" version = "1.1.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 = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
dependencies = [ dependencies = [
"serde_core", "serde_core",
] ]
@@ -8284,16 +8283,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.3+spec-1.1.0", "toml_datetime 1.1.1+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.5+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 = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"
dependencies = [ dependencies = [
"winnow 1.0.4", "winnow 1.0.4",
] ]
@@ -8306,9 +8305,9 @@ checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
[[package]] [[package]]
name = "toml_writer" name = "toml_writer"
version = "1.2.0+spec-1.1.0" version = "1.1.2+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 = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
[[package]] [[package]]
name = "tonic" name = "tonic"
@@ -8565,15 +8564,6 @@ dependencies = [
"stable_deref_trait", "stable_deref_trait",
] ]
[[package]]
name = "tristr"
version = "0.1.0"
source = "git+https://github.com/Tunglies/tristr?rev=3738d8c5785d609674c5f4f05def26b94724200c#3738d8c5785d609674c5f4f05def26b94724200c"
dependencies = [
"serde",
"specta",
]
[[package]] [[package]]
name = "try-lock" name = "try-lock"
version = "0.2.5" version = "0.2.5"
@@ -10136,9 +10126,9 @@ dependencies = [
[[package]] [[package]]
name = "zip" name = "zip"
version = "9.6.0" version = "9.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80cc68510ea7553c30a69c732de5278e94183f68765af6c642dbccefd6ec777e" checksum = "e3476fd497ac8af5b1ec7b51acab7bef380f7e8dd8e0487595bafd839417a302"
dependencies = [ dependencies = [
"aes", "aes",
"bzip2", "bzip2",
@@ -10152,7 +10142,7 @@ dependencies = [
"libc", "libc",
"lzma-rust2", "lzma-rust2",
"memchr", "memchr",
"nix 0.32.0", "nix",
"pbkdf2", "pbkdf2",
"ppmd-rust", "ppmd-rust",
"sha1 0.11.0", "sha1 0.11.0",
+2 -1
View File
@@ -84,8 +84,9 @@ reqwest = { version = "0.13.5", features = [
] } ] }
rust_iso3166 = "0.2.0" rust_iso3166 = "0.2.0"
smartstring = { version = "2.0.0" }
serde = { version = "1.0.229" } serde = { version = "1.0.229" }
tristr = { git = "https://github.com/Tunglies/tristr", rev = "3738d8c5785d609674c5f4f05def26b94724200c", default-features = false, features = ["serde", "specta"] }
serde_json = { version = "1.0.154" } serde_json = { version = "1.0.154" }
serde_yaml_ng = { version = "0.10.0" } serde_yaml_ng = { version = "0.10.0" }
socket2 = "0.6.5" socket2 = "0.6.5"
+2 -10
View File
@@ -37,8 +37,7 @@
- 修复断开链式代理时清空已选节点,导致再次连接需要重新选择 - 修复断开链式代理时清空已选节点,导致再次连接需要重新选择
- 修复「连接」页表格排序时表头换行、标题位置跳动 - 修复「连接」页表格排序时表头换行、标题位置跳动
- 修复「TUN 设置」未手动保存时,界面显示的默认 MTU 1500 未生效 - 修复「TUN 设置」未手动保存时,界面显示的默认 MTU 1500 未生效
- 修复「链式代理」节点列表按名称排序,未保持订阅中的节点顺序 - 修复连接详情较窄时操作按钮偏离右侧
- 修复规则模式下 Muse AI 解锁检测显示错误的出口地区
**🍎 macOS** **🍎 macOS**
@@ -46,17 +45,13 @@
- 修复 macOS 断网时误报代理已回退直连,恢复联网后自动重试系统代理 - 修复 macOS 断网时误报代理已回退直连,恢复联网后自动重试系统代理
- 修复 macOS 切换主题后标题栏保留原有深浅色 - 修复 macOS 切换主题后标题栏保留原有深浅色
**🐧 Linux**
- 修复 Linux OpenRC 环境下服务安装失败
</details> </details>
<details> <details>
<summary><strong> ✨ 新增功能 </strong></summary> <summary><strong> ✨ 新增功能 </strong></summary>
- 新增连接页面按网络协议(TCP/UDP)筛选连接 - 新增连接页面按网络协议(TCP/UDP)筛选连接
- 新增规则模式下在 `url-test` 或 `fallback` 代理组选节点时,自动将首个包含该组的 `select` 代理组切换到该组,可在「杂项设置」关闭 - 新增从连接详情设置域名、进程或源/目标 IP 规则,支持识别主域、匹配子域、自定义 IP 网段及修改已有规则
</details> </details>
@@ -65,9 +60,6 @@
- 优化连接、规则和日志筛选:切换页面后保留过滤条件 - 优化连接、规则和日志筛选:切换页面后保留过滤条件
- 优化全局模式代理列表:仅显示 `GLOBAL` 节点,选中其中的策略组时才显示该组 - 优化全局模式代理列表:仅显示 `GLOBAL` 节点,选中其中的策略组时才显示该组
- 优化设置页开关和选项所在行的鼠标悬停高亮,便于对应说明与控件
- 优化首页「当前节点」卡片:代理组列表加入 `fallback` 代理组,切换到 `url-test` 或 `fallback` 代理组时同样联动 `select` 代理组
- 优化主页流量图表与日志、代理列表的实时刷新和滚动占用,降低高频更新时的 CPU 负载
**🍎 macOS** **🍎 macOS**
-3
View File
@@ -15,6 +15,3 @@ tokio = { workspace = true }
[dev-dependencies] [dev-dependencies]
criterion = { workspace = true } criterion = { workspace = true }
[lints]
workspace = true
@@ -19,7 +19,6 @@ fn make_draft() -> Draft<IVerge> {
} }
pub fn bench_draft(c: &mut Criterion) { pub fn bench_draft(c: &mut Criterion) {
#[allow(clippy::panic, reason = "bench setup cannot proceed without a runtime")]
let rt = Runtime::new().unwrap_or_else(|e| panic!("Tokio runtime init failed: {e}")); let rt = Runtime::new().unwrap_or_else(|e| panic!("Tokio runtime init failed: {e}"));
let mut group = c.benchmark_group("draft"); let mut group = c.benchmark_group("draft");
+1 -6
View File
@@ -102,7 +102,6 @@ impl<T: Clone> Draft<T> {
let (local, original_arc) = { let (local, original_arc) = {
let guard = self.inner.data.lock(); let guard = self.inner.data.lock();
let arc = Arc::clone(&guard.0); let arc = Arc::clone(&guard.0);
drop(guard);
((**arc).clone(), arc) ((**arc).clone(), arc)
}; };
let (new_local, res) = f(local).await?; let (new_local, res) = f(local).await?;
@@ -113,7 +112,6 @@ impl<T: Clone> Draft<T> {
)); ));
} }
guard.0 = Arc::new(Box::new(new_local)); guard.0 = Arc::new(Box::new(new_local));
drop(guard);
Ok(res) Ok(res)
} }
@@ -127,10 +125,7 @@ impl<T: Clone> Draft<T> {
} }
#[inline] #[inline]
async fn acquire_data_modify_permit(&self) -> DataModifyPermit<'_> async fn acquire_data_modify_permit(&self) -> DataModifyPermit<'_> {
where
T: Send + Sync,
{
for _ in 0..DATA_MODIFY_FAST_RETRY_YIELDS { for _ in 0..DATA_MODIFY_FAST_RETRY_YIELDS {
if let Some(permit) = self.try_acquire_data_modify_permit() { if let Some(permit) = self.try_acquire_data_modify_permit() {
return permit; return permit;
-3
View File
@@ -15,6 +15,3 @@ default = []
tokio-trace = ["tracing-estuary/tokio-trace"] tokio-trace = ["tracing-estuary/tokio-trace"]
chrome-trace = ["tracing-estuary/chrome-trace"] chrome-trace = ["tracing-estuary/chrome-trace"]
color = ["tracing-estuary/color"] color = ["tracing-estuary/color"]
[lints]
workspace = true
+7 -6
View File
@@ -160,7 +160,7 @@ pub struct Logger {
static LOGGER: OnceLock<Logger> = OnceLock::new(); static LOGGER: OnceLock<Logger> = OnceLock::new();
impl Logger { impl Logger {
const fn new() -> Self { fn new() -> Self {
Self { Self {
pipeline: OnceLock::new(), pipeline: OnceLock::new(),
sidecar_file_writer: RwLock::new(None), sidecar_file_writer: RwLock::new(None),
@@ -185,7 +185,7 @@ impl Logger {
self.store_config(cfg); self.store_config(cfg);
let pipeline = tracing_estuary::PipelineBuilder::new() let pipeline = tracing_estuary::PipelineBuilder::new()
.default_level(log_level) .default_level(log_level)
.file_writer(self.generate_file_log_writer()) .file_writer(self.generate_file_log_writer()?)
.init()?; .init()?;
self.pipeline.set(pipeline).ok(); self.pipeline.set(pipeline).ok();
Ok(()) Ok(())
@@ -225,11 +225,11 @@ impl Logger {
self.log_max_count.store(cfg.max_count, Ordering::SeqCst); self.log_max_count.store(cfg.max_count, Ordering::SeqCst);
} }
fn generate_file_log_writer(&self) -> FileLogWriterBuilder { fn generate_file_log_writer(&self) -> Result<FileLogWriterBuilder> {
let log_dir = self.log_dir.get().cloned().unwrap_or_default(); let log_dir = self.log_dir.get().cloned().unwrap_or_default();
let log_max_size = self.log_max_size.load(Ordering::SeqCst); let log_max_size = self.log_max_size.load(Ordering::SeqCst);
let log_max_count = self.log_max_count.load(Ordering::SeqCst); let log_max_count = self.log_max_count.load(Ordering::SeqCst);
FileLogWriter::builder(FileSpec::default().directory(log_dir).basename("")) let flwb = FileLogWriter::builder(FileSpec::default().directory(log_dir).basename(""))
.format(tracing_estuary::file_format_with_level) .format(tracing_estuary::file_format_with_level)
.write_mode(flexi_logger::WriteMode::BufferAndFlushWith( .write_mode(flexi_logger::WriteMode::BufferAndFlushWith(
WRITE_BUFFER_CAPACITY, WRITE_BUFFER_CAPACITY,
@@ -239,7 +239,8 @@ impl Logger {
Criterion::Size(log_max_size * 1024), Criterion::Size(log_max_size * 1024),
ROTATE_NAMING, ROTATE_NAMING,
Cleanup::KeepLogFiles(log_max_count), Cleanup::KeepLogFiles(log_max_count),
) );
Ok(flwb)
} }
/// Ensures the sidecar writer exists and points at `builder`'s config: /// Ensures the sidecar writer exists and points at `builder`'s config:
@@ -310,7 +311,7 @@ impl Logger {
self.log_max_size.store(log_max_size, Ordering::SeqCst); self.log_max_size.store(log_max_size, Ordering::SeqCst);
self.log_max_count.store(log_max_count, Ordering::SeqCst); self.log_max_count.store(log_max_count, Ordering::SeqCst);
if let Some(pipeline) = self.pipeline.get() { if let Some(pipeline) = self.pipeline.get() {
let log_file_writer = self.generate_file_log_writer(); let log_file_writer = self.generate_file_log_writer()?;
if let Some(sink) = pipeline.sink.as_ref() { if let Some(sink) = pipeline.sink.as_ref() {
sink.reset(log_file_writer) sink.reset(log_file_writer)
.map_err(|error| anyhow::anyhow!("failed to reset log writer: {error}"))?; .map_err(|error| anyhow::anyhow!("failed to reset log writer: {error}"))?;
+11 -6
View File
@@ -1,23 +1,28 @@
use reqwest::Client; use reqwest::Client;
use crate::utils::classify_restricted_status; use crate::utils::{classify_restricted_status, get_trace_location};
use super::UnlockItem; use super::UnlockItem;
pub(crate) const MUSE_AI_NAME: &str = "Muse AI"; pub(crate) const MUSE_AI_NAME: &str = "Muse AI";
const MUSE_URL: &str = "https://muse.ai"; const MUSE_URL: &str = "https://muse.ai";
const CLOUDFLARE_TRACE_URL: &str = "https://www.cloudflare.com/cdn-cgi/trace";
// The aymh ("Are You a Human") gateway answers plain HTTP requests with a // The aymh ("Are You a Human") gateway answers plain HTTP requests with a
// generic Meta error page that always contains the Facebook logo asset. // generic Meta error page that always contains the Facebook logo asset.
const AYMH_ERROR_MARKERS: &[&str] = &["Sorry, something went wrong", "static.facebook.com/images/logos"]; const AYMH_ERROR_MARKERS: &[&str] = &["Sorry, something went wrong", "static.facebook.com/images/logos"];
pub(super) async fn check_muse_ai(client: &Client) -> UnlockItem { pub(super) async fn check_muse_ai(client: &Client) -> UnlockItem {
// muse.ai is served by Vercel and does not expose a service-specific region trace endpoint. // muse.ai itself is served by Vercel, so resolve the exit region through
// Querying a generic third-party domain (e.g. www.cloudflare.com/cdn-cgi/trace) would report // the generic Cloudflare trace endpoint instead of a service-specific one.
// that domain's proxy group rather than muse.ai's actual exit in Rule mode, so leave region as None. let region = get_trace_location(client, CLOUDFLARE_TRACE_URL)
.await
.map(|code| code.trim().to_ascii_uppercase())
.map(|code| UnlockItem::region_label(&code));
let Ok(response) = client.get(MUSE_URL).send().await else { let Ok(response) = client.get(MUSE_URL).send().await else {
return UnlockItem::checked(MUSE_AI_NAME, "Failed (Network Connection)", None); return UnlockItem::checked(MUSE_AI_NAME, "Failed (Network Connection)", region);
}; };
let status = response.status(); let status = response.status();
@@ -39,5 +44,5 @@ pub(super) async fn check_muse_ai(client: &Client) -> UnlockItem {
classify_restricted_status(status).unwrap_or("Failed") classify_restricted_status(status).unwrap_or("Failed")
}; };
UnlockItem::checked(MUSE_AI_NAME, result, None) UnlockItem::checked(MUSE_AI_NAME, result, region)
} }
+2 -1
View File
@@ -82,6 +82,7 @@
"rehype-sanitize": "^6.0.0", "rehype-sanitize": "^6.0.0",
"swr": "^2.5.1", "swr": "^2.5.1",
"tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#main", "tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#main",
"tldts": "7.4.19",
"types-pac": "^1.0.3", "types-pac": "^1.0.3",
"validator": "^13.15.35" "validator": "^13.15.35"
}, },
@@ -138,5 +139,5 @@
] ]
}, },
"type": "module", "type": "module",
"packageManager": "pnpm@12.21.0" "packageManager": "pnpm@12.18.0"
} }
+77 -70
View File
@@ -7,162 +7,153 @@ importers:
configDependencies: {} configDependencies: {}
packageManagerDependencies: packageManagerDependencies:
pnpm: pnpm:
specifier: 12.21.0 specifier: 12.18.0
version: 12.21.0 version: 12.18.0
packages: packages:
'@pnpm/exe.android-arm64@12.21.0': '@pnpm/exe.android-arm64@12.18.0':
resolution: {integrity: sha512-iaWidxR5B9NUBpwMznCQu1yUpKB6BjTY5BYX2lORj76VsfINdj8Z8XWSzSNrGI8qlxa28Jzdp5fiaspzOaJZlA==} resolution: {integrity: sha512-fOF6IwgvnUKEmVedGqiAsNPfN2Ry8GvaqzSQOiF3RJFbpBfPKO/6YT54s1GjToyYinRxw9preHHPe4y2N3SzhA==}
cpu: [arm64] cpu: [arm64]
os: [android] os: [android]
'@pnpm/exe.android-x64@12.21.0': '@pnpm/exe.android-x64@12.18.0':
resolution: {integrity: sha512-35e5v3wlwjIYxDywq+R6/z8CE4gLOEgRxt18yqz1tMRLmx2mnW+CFJI2Q8+srTNjn7gykXUC0x1k195JNikC5A==} resolution: {integrity: sha512-6OiolnaCsB3/GcJ9XNrenbUH3zFHRJ+5QynrMUUEyThbgnnCzWxa199hpQlOmxN4rAXuYQ0IYgWFNUZxyzg31Q==}
cpu: [x64] cpu: [x64]
os: [android] os: [android]
'@pnpm/exe.darwin-arm64@12.21.0': '@pnpm/exe.darwin-arm64@12.18.0':
resolution: {integrity: sha512-F5OyMX/6zLSowpTZEQRojbCmPS1Pq+fyRaIinslsIe6Glh3qbyQ52u+Fe0eEzSaRuIbWZkXmAAXSWh6Q5Wrlgg==} resolution: {integrity: sha512-zkq+4YzVIX39ETYLyC3W7LY7MpHEU/J3nRhHl4i2yPld2Cf2+rEKRh3ejJ4AmaQ77HHJLCktY4Z3jq0fpcxFXg==}
cpu: [arm64] cpu: [arm64]
os: [darwin] os: [darwin]
'@pnpm/exe.darwin-x64@12.21.0': '@pnpm/exe.darwin-x64@12.18.0':
resolution: {integrity: sha512-EzpvcsaE6hrrgYeEiAFYd2rSgFybYyxXhkAY7K3y6Hg3loVfcyJ81hHczpFzi8lW5RXtUlFECRPZ8ZAMRFQYYg==} resolution: {integrity: sha512-qMsL9qx92unOTa6hgkfiTJv8ceZaTx0IQg7InhYDVX2ZrTECujaVEEVypnJK5m3eGUsP1KD7Y4qIgleCwfRsYw==}
cpu: [x64] cpu: [x64]
os: [darwin] os: [darwin]
'@pnpm/exe.freebsd-x64@12.21.0': '@pnpm/exe.freebsd-x64@12.18.0':
resolution: {integrity: sha512-wNjuEnmdLks4aayPu/QZWQ5tQM9Jn+odUp/vwQM8BXRYoulkTZhtZTHoD60N6mUdLWef1hgUeUh8llNGEUsimw==} resolution: {integrity: sha512-/9vy/4ms52cU4MjZ5NhHd6N2d9L9W0kARf5/ff2tweAHu0VeUzs/0qp/7ZHFuddm2Wa/m0AKQoPum9AVUCqKsw==}
cpu: [x64] cpu: [x64]
os: [freebsd] os: [freebsd]
'@pnpm/exe.linux-arm64-musl@12.21.0': '@pnpm/exe.linux-arm64-musl@12.18.0':
resolution: {integrity: sha512-Ceit9zn4g5ZqCJtx1fV8eJE7p8aeXMrGZ+Dc01vRqZLIUNgNeI+Ur0ruyqxtsnJx6rGADyXzohumxPLHjaJ5AQ==} resolution: {integrity: sha512-Vp+TIMPPyackVCXkOdEKH/RmAn/r07EcIyrgZYQK7VrkksqZOie0GnWIx+85mPqeFEYCRtXIZAFJ9L4ceTndDg==}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
libc: [musl] libc: [musl]
'@pnpm/exe.linux-arm64@12.21.0': '@pnpm/exe.linux-arm64@12.18.0':
resolution: {integrity: sha512-4Oj/iF2TDCe2lcH0n4TupPR5sSdrNLclJB6xBElLMPCUOAvBhdf2rRlSaO5M4erJ6g4Fyy7YTXTpcmfFsKyxEA==} resolution: {integrity: sha512-2dpyVBCHT+FfpuQh9i+7MXAqNWYLCvD5vYr5p6Eimxoga8USLnjbUgyj72AOrO0hjc5ri3TEFP3jiyBHjkSZpQ==}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@pnpm/exe.linux-ppc64@12.21.0': '@pnpm/exe.linux-ppc64@12.18.0':
resolution: {integrity: sha512-s2o7rdSDeUTBFsNqxptpZXlTgT6cojmMVUOvTQvFNSv6Easian02ha4tR32fwwD97Au4YzIIjMCwywCF4D82Sw==} resolution: {integrity: sha512-BBOOOfNJ2QwIIya3eKqOjiN4WNTszfRz7HCvw9XggcT7+ftMjNP8XJ/GfW+ltCBeUFR9d8WBVsr2m/NLjX2CZQ==}
cpu: [ppc64] cpu: [ppc64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@pnpm/exe.linux-riscv64@12.21.0': '@pnpm/exe.linux-riscv64@12.18.0':
resolution: {integrity: sha512-EYv3GzxeBTITCuM3yGHHbpRFpUvyulkXpQ6LsjKAQNL3iaba1E6h9iDmlouLb3Io4AMMsfdk0/uG6poQ41uewA==} resolution: {integrity: sha512-7kMN77xSOYJX8GPSH5RbNAc5oM61LMmcSUukDDUwllnZPXm8GRPskCNsTWy8SCw01Kr1FB+5SwGNMiTdiziLNQ==}
cpu: [riscv64] cpu: [riscv64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@pnpm/exe.linux-s390x@12.21.0': '@pnpm/exe.linux-s390x@12.18.0':
resolution: {integrity: sha512-8VXGNGVNEfs7pL9GTZOzFxjFEnMt4WL3rLOADR5/kPQ7ROTV9GfpVI2DPO/zArXFSkvfc9Zad/WypHLbvzoaTQ==} resolution: {integrity: sha512-htuSCpEcmDzhKoJqXbPkvfr176dBHU0QIF5mWcRiqxRXAB/1JoYiMYotfjWpk+ztgpB9qlx4XnWlLFAf7gzc6g==}
cpu: [s390x] cpu: [s390x]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@pnpm/exe.linux-x64-musl@12.21.0': '@pnpm/exe.linux-x64-musl@12.18.0':
resolution: {integrity: sha512-MnC5vpIXYubhDZCgCwlfJMg7Cg6HupN2IuouT9gD/tUmOfVdQYqeyYccWbthyo/Jeto8de1oQlxeRN1+1Hl2DQ==} resolution: {integrity: sha512-Uj+vzfIQ62kDP10x36yHZIXVs5ohdNtiPYwn5FhCLlNScHPo0OAI+ShGDtLofiBXKE7umu71Jmjm7N8a8zVcDw==}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
libc: [musl] libc: [musl]
'@pnpm/exe.linux-x64@12.21.0': '@pnpm/exe.linux-x64@12.18.0':
resolution: {integrity: sha512-8eufCjHXspKbNS/kh8q4Q0gqJoOuvC4Q5pgos6XS8By/nAMtP+jf8F1Cw9er840kfAX+PJ/ts+A9qnLE91rvXQ==} resolution: {integrity: sha512-OJ+X2wcraldCwj75pCIerWARQSRpdfj0eBTs/2ODyhfeW46ylOnjTIE/GKra6Mn6E72/gBmXS8igrUioa+F9fQ==}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@pnpm/exe.netbsd-x64@12.21.0': '@pnpm/exe.win32-arm64@12.18.0':
resolution: {integrity: sha512-eyh1M8hQZCkLWxuva7S/fc1SbFbgqg0/5di0dgWmyiuc2Io3dbWVihDun8X+XM8zsR5uhIDvvZpbS9aZQbCovg==} resolution: {integrity: sha512-wEY6jiACGcbhhi5yD59doHqNTndS7AaujaPmtWAu1DKkHru2hy5fJ9yUGecW72Ypaw2/I3BEprfMOopap2NQtw==}
cpu: [x64]
os: [netbsd]
'@pnpm/exe.win32-arm64@12.21.0':
resolution: {integrity: sha512-7xTxxUXo/grRLivSeIl6B21gnsz7ooe5EMPcJmQqwxc8WLJVReN8MzrlHru8bqXfVr4X3+6ZGZscntKenlCBqQ==}
cpu: [arm64] cpu: [arm64]
os: [win32] os: [win32]
'@pnpm/exe.win32-x64@12.21.0': '@pnpm/exe.win32-x64@12.18.0':
resolution: {integrity: sha512-9TpkJemVApxJ1Z1w0ZFGN+AuSx4nJOqXSJUqMqDvaXTYwGOzvBiiWdFP9GN0ketiWCQS1Q0/pza2E7I3pP0OBQ==} resolution: {integrity: sha512-5FJkghO7RLRkQpWxeVEygW9XsmnNuxzPfXbgwFWCHsFyFhpDn/vOdL88ToQEM0Kt5igdW5s6U0/IDH8Dvkt3pg==}
cpu: [x64] cpu: [x64]
os: [win32] os: [win32]
pnpm@12.21.0: pnpm@12.18.0:
resolution: {integrity: sha512-Zv2CeO4ok1zpUXktNDZ/869cQyonVkRYIwKVM4NbjaUpu+C+UTCv1W7QcT+4eJ5Hutgtk71a4v5UsVVi1idu8A==} resolution: {integrity: sha512-nXiC1dyCFH7PxOBiqjSDTgrQKWcQoYN6ERWuASEn02txCeMhrBWYod0KZVl2gbHpmRfhLtDXSerpEYeUM2O+sw==}
engines: {node: '>=18'} engines: {node: '>=18'}
hasBin: true hasBin: true
snapshots: snapshots:
'@pnpm/exe.android-arm64@12.21.0': '@pnpm/exe.android-arm64@12.18.0':
optional: true optional: true
'@pnpm/exe.android-x64@12.21.0': '@pnpm/exe.android-x64@12.18.0':
optional: true optional: true
'@pnpm/exe.darwin-arm64@12.21.0': '@pnpm/exe.darwin-arm64@12.18.0':
optional: true optional: true
'@pnpm/exe.darwin-x64@12.21.0': '@pnpm/exe.darwin-x64@12.18.0':
optional: true optional: true
'@pnpm/exe.freebsd-x64@12.21.0': '@pnpm/exe.freebsd-x64@12.18.0':
optional: true optional: true
'@pnpm/exe.linux-arm64-musl@12.21.0': '@pnpm/exe.linux-arm64-musl@12.18.0':
optional: true optional: true
'@pnpm/exe.linux-arm64@12.21.0': '@pnpm/exe.linux-arm64@12.18.0':
optional: true optional: true
'@pnpm/exe.linux-ppc64@12.21.0': '@pnpm/exe.linux-ppc64@12.18.0':
optional: true optional: true
'@pnpm/exe.linux-riscv64@12.21.0': '@pnpm/exe.linux-riscv64@12.18.0':
optional: true optional: true
'@pnpm/exe.linux-s390x@12.21.0': '@pnpm/exe.linux-s390x@12.18.0':
optional: true optional: true
'@pnpm/exe.linux-x64-musl@12.21.0': '@pnpm/exe.linux-x64-musl@12.18.0':
optional: true optional: true
'@pnpm/exe.linux-x64@12.21.0': '@pnpm/exe.linux-x64@12.18.0':
optional: true optional: true
'@pnpm/exe.netbsd-x64@12.21.0': '@pnpm/exe.win32-arm64@12.18.0':
optional: true optional: true
'@pnpm/exe.win32-arm64@12.21.0': '@pnpm/exe.win32-x64@12.18.0':
optional: true optional: true
'@pnpm/exe.win32-x64@12.21.0': pnpm@12.18.0:
optional: true
pnpm@12.21.0:
optionalDependencies: optionalDependencies:
'@pnpm/exe.android-arm64': 12.21.0 '@pnpm/exe.android-arm64': 12.18.0
'@pnpm/exe.android-x64': 12.21.0 '@pnpm/exe.android-x64': 12.18.0
'@pnpm/exe.darwin-arm64': 12.21.0 '@pnpm/exe.darwin-arm64': 12.18.0
'@pnpm/exe.darwin-x64': 12.21.0 '@pnpm/exe.darwin-x64': 12.18.0
'@pnpm/exe.freebsd-x64': 12.21.0 '@pnpm/exe.freebsd-x64': 12.18.0
'@pnpm/exe.linux-arm64': 12.21.0 '@pnpm/exe.linux-arm64': 12.18.0
'@pnpm/exe.linux-arm64-musl': 12.21.0 '@pnpm/exe.linux-arm64-musl': 12.18.0
'@pnpm/exe.linux-ppc64': 12.21.0 '@pnpm/exe.linux-ppc64': 12.18.0
'@pnpm/exe.linux-riscv64': 12.21.0 '@pnpm/exe.linux-riscv64': 12.18.0
'@pnpm/exe.linux-s390x': 12.21.0 '@pnpm/exe.linux-s390x': 12.18.0
'@pnpm/exe.linux-x64': 12.21.0 '@pnpm/exe.linux-x64': 12.18.0
'@pnpm/exe.linux-x64-musl': 12.21.0 '@pnpm/exe.linux-x64-musl': 12.18.0
'@pnpm/exe.netbsd-x64': 12.21.0 '@pnpm/exe.win32-arm64': 12.18.0
'@pnpm/exe.win32-arm64': 12.21.0 '@pnpm/exe.win32-x64': 12.18.0
'@pnpm/exe.win32-x64': 12.21.0
--- ---
lockfileVersion: '9.0' lockfileVersion: '9.0'
@@ -304,6 +295,9 @@ importers:
tauri-plugin-mihomo-api: tauri-plugin-mihomo-api:
specifier: github:clash-verge-rev/tauri-plugin-mihomo#main specifier: github:clash-verge-rev/tauri-plugin-mihomo#main
version: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/e49bbedcc67d60da2c10e81bc6433b0f8e8fa232 version: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/e49bbedcc67d60da2c10e81bc6433b0f8e8fa232
tldts:
specifier: 7.4.19
version: 7.4.19
types-pac: types-pac:
specifier: ^1.0.3 specifier: ^1.0.3
version: 1.0.3 version: 1.0.3
@@ -4044,6 +4038,13 @@ packages:
resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
engines: {node: '>=12.0.0'} engines: {node: '>=12.0.0'}
tldts-core@7.5.2:
resolution: {integrity: sha512-8W1topazDwhMKbm2I83IPa57Ow5VUxFgLbXv42+vSILnv8FY5OHvdEY/tS6WoWeMbxkHZQhra5cmeFHriKptSQ==}
tldts@7.4.19:
resolution: {integrity: sha512-48dH6aSpQnpbzDUc4vIQZ1VjB8tkK+e8c1yx05/SZK+rkssgjEOlxDd/yU8/a4vGYQ9vRgJr9dwMq9TJ0b3X2Q==}
hasBin: true
trim-lines@3.0.1: trim-lines@3.0.1:
resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==} resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}
@@ -8147,6 +8148,12 @@ snapshots:
fdir: 6.5.0(picomatch@4.0.7) fdir: 6.5.0(picomatch@4.0.7)
picomatch: 4.0.7 picomatch: 4.0.7
tldts-core@7.5.2: {}
tldts@7.4.19:
dependencies:
tldts-core: 7.5.2
trim-lines@3.0.1: {} trim-lines@3.0.1: {}
trough@2.2.0: {} trough@2.2.0: {}
-50
View File
@@ -46,58 +46,8 @@ 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',
[ [
+1 -1
View File
@@ -220,7 +220,7 @@ pub fn run() -> std::process::ExitCode {
.set_activation_policy(tauri::ActivationPolicy::Prohibited)?; .set_activation_policy(tauri::ActivationPolicy::Prohibited)?;
let scenario = std::env::var("PERF_SCENARIO").unwrap_or_else(|_| "traffic".into()); let scenario = std::env::var("PERF_SCENARIO").unwrap_or_else(|_| "traffic".into());
let layer = std::env::var("PERF_LAYER").unwrap_or_else(|_| "component".into()); let layer = std::env::var("PERF_LAYER").unwrap_or_else(|_| "component".into());
if !matches!(scenario.as_str(), "traffic" | "logs" | "connections" | "proxy") if !matches!(scenario.as_str(), "traffic" | "logs" | "connections")
|| !matches!(layer.as_str(), "page" | "component" | "dom") || !matches!(layer.as_str(), "page" | "component" | "dom")
{ {
return Err("invalid perf scene".into()); return Err("invalid perf scene".into());
-2
View File
@@ -2,8 +2,6 @@ import { layer, scenario, startReplay } from './replay'
if (scenario === 'traffic') { if (scenario === 'traffic') {
await import('./traffic') await import('./traffic')
} else if (scenario === 'proxy') {
await import('./proxy')
} else { } else {
const root = document.getElementById('root')! const root = document.getElementById('root')!
document.body.style.cssText = 'margin:0;font:14px -apple-system,sans-serif' document.body.style.cssText = 'margin:0;font:14px -apple-system,sans-serif'
-137
View File
@@ -1,137 +0,0 @@
// Only this perf build aliases '@tauri-apps/api/core' to a shim that serves
// these responses for the proxy scenario; the normal application never
// imports it. The runtime-injected __TAURI_INTERNALS__ is read-only, so
// interception happens at import resolution instead. Unknown commands pass
// through to the real backend (perf_state, event plugin), keeping harness
// ownership probes and lifecycle commands working. The proxy scenario is
// therefore a JavaScript invoke adapter, not native plugin IPC.
const GROUP_COUNT = 40
const NODES_PER_GROUP = 24
const capabilities = {
udp: true,
xudp: false,
tfo: false,
mptcp: false,
smux: false,
}
const history = (delay: number) => [{ time: '2026-11-19T00:00:00Z', delay }]
const buildProxyView = () => {
const records: Record<string, unknown> = {}
const groups: {
name: string
type: string
now: string
hidden: boolean
history: { time: string; delay: number }[]
members: unknown[]
}[] = []
for (let g = 0; g < GROUP_COUNT; g++) {
const members: unknown[] = []
for (let n = 0; n < NODES_PER_GROUP; n++) {
const name = `node-${g}-${n}`
const recordId = `record-${g}-${n}`
records[recordId] = {
recordId,
name,
type: n % 3 === 0 ? 'Shadowsocks' : n % 3 === 1 ? 'Vmess' : 'Trojan',
history: history(30 + ((g * 7 + n * 13) % 40) * 10),
source: { kind: 'core', proxyName: name },
...capabilities,
}
members.push({ kind: 'node', name, recordId })
}
groups.push({
name: `group-${String(g).padStart(2, '0')}`,
type: g % 2 === 0 ? 'Selector' : 'URLTest',
now: `node-${g}-0`,
hidden: false,
history: history(20),
members,
})
}
return {
schemaVersion: 1,
orderSource: 'runtime',
providerState: 'ready',
global: {
name: 'GLOBAL',
type: 'Selector',
now: 'group-00',
hidden: true,
history: [],
members: groups.map((group) => ({ kind: 'group', name: group.name })),
...capabilities,
},
direct: 'DIRECT',
groups: groups.map((group) => ({ ...group, ...capabilities })),
records,
standalone: [],
providers: [],
}
}
const handlers: Record<string, () => unknown> = {
get_proxy_view: buildProxyView,
get_verge_config: () => ({
language: 'en',
theme_mode: 'light',
proxy_layout_column: 2,
default_latency_timeout: 10000,
enable_hover_jump_navigator: true,
hover_jump_navigator_delay: 200,
pause_render_traffic_stats_on_blur: false,
}),
get_profiles: () => ({
current: 'perf-profile',
items: [
{
uid: 'perf-profile',
type: 'remote',
name: 'Perf Profile',
desc: '',
url: '',
selected: true,
extra: {},
option: { update_interval: 0 },
},
],
}),
get_clash_info: () => ({
mixed_port: 7897,
socks_port: 0,
port: 0,
server: '127.0.0.1:9097',
secret: null,
}),
get_runtime_config: () => null,
get_sys_proxy: () => ({ enable: false, bypass: '', pac_file: '' }),
get_runtime_state: () => ({
mode: 'Sidecar',
service: 'ready',
serviceUnavailableReason: null,
pendingAction: null,
sidecarAllowed: true,
isAdmin: false,
opInFlight: false,
serviceUsable: true,
tunCapable: false,
serviceNeedsAttention: false,
}),
get_sidecar_failure: () => null,
get_pending_failures: () => [],
'plugin:mihomo|get_configs': () => ({ mode: 'rule', 'mixed-port': 7897 }),
'plugin:mihomo|get_rule_providers': () => ({ providers: {} }),
'plugin:mihomo|get_rules': () => ({ rules: [] }),
}
/** Returns the mocked response, or undefined to pass through to the backend. */
export const mockCommand = (cmd: string): unknown => {
const handler = handlers[cmd]
return handler ? handler() : undefined
}
-93
View File
@@ -1,93 +0,0 @@
import { ThemeProvider, createTheme } from '@mui/material'
import { useEffect } from 'react'
import { createRoot } from 'react-dom/client'
import { SWRConfig } from 'swr'
import { AppDataProvider } from '../../src/providers/app-data-provider'
import { initializeLanguage } from '../../src/services/i18n'
import { setPreloadConfig } from '../../src/services/preload'
import { swrConfig } from '../../src/services/query-client'
import { AppStoreProvider } from '../../src/store/app-store'
import '../../src/assets/styles/page.scss'
const root = document.getElementById('root')!
document.body.style.cssText = 'margin:0;font:14px -apple-system,sans-serif'
root.style.cssText = 'width:1000px;height:700px;overflow:hidden'
new MutationObserver(() => {
document.documentElement.dataset.perfDraw = String(Date.now())
}).observe(root, { childList: true, characterData: true, subtree: true })
setPreloadConfig({
language: 'en',
theme_mode: 'light',
pause_render_traffic_stats_on_blur: false,
} as IVergeConfig)
await initializeLanguage('en')
const ProxyPage = (await import('../../src/pages/proxies')).default
const findScroller = () => {
const elements = document.querySelectorAll<HTMLElement>('#root *')
for (const element of elements) {
const { overflowY } = getComputedStyle(element)
if (
(overflowY === 'auto' || overflowY === 'scroll') &&
element.scrollHeight > element.clientHeight
) {
return element
}
}
return null
}
// Deterministic sawtooth scrolling keeps the virtualizer measuring, the
// throttled scroll-position save running and the DOM mutating so the perfDraw
// marker tracks view-input delivery. Each applied scroll step counts as one
// delivered view input; the interval keeps delivering (throttled by the
// browser) while the window is hidden and rAF is suspended.
export const ScrollDriver = () => {
useEffect(() => {
const data = document.documentElement.dataset
let stopped = false
const step = () => {
const scroller = findScroller()
if (scroller) {
const max = scroller.scrollHeight - scroller.clientHeight
if (max > 0) {
const next =
scroller.scrollTop + 36 > max - 36 ? 0 : scroller.scrollTop + 36
scroller.scrollTop = next
data.perfScroll = String(Number(data.perfScroll || 0) + 1)
data.perfDelivered = String(Number(data.perfDelivered || 0) + 1)
}
}
}
const drive = () => {
if (stopped) return
step()
requestAnimationFrame(drive)
}
const handle = requestAnimationFrame(drive)
const timer = window.setInterval(step, 250)
return () => {
stopped = true
cancelAnimationFrame(handle)
window.clearInterval(timer)
}
}, [])
return null
}
createRoot(root).render(
<SWRConfig value={swrConfig}>
<ThemeProvider theme={createTheme()}>
<AppStoreProvider>
<AppDataProvider>
<ProxyPage />
<ScrollDriver />
</AppDataProvider>
</AppStoreProvider>
</ThemeProvider>
</SWRConfig>,
)
-17
View File
@@ -1,17 +0,0 @@
import { startReplay } from './replay'
// Thin loader: error handlers must precede scene module evaluation so any
// startup failure surfaces in perfError.
const data = document.documentElement.dataset
window.addEventListener('error', (event) => {
data.perfError = event.message
})
window.addEventListener('unhandledrejection', (event) => {
data.perfError = String(event.reason)
})
data.perfStage = 'loader'
await import('./proxy-scene')
data.perfStage = 'scene'
startReplay()
data.perfStage = 'replay'
-30
View File
@@ -1,30 +0,0 @@
// Aliased in place of '@tauri-apps/api/core' only by the perf build. The
// direct relative import keeps the original module outside the alias so this
// shim can forward to it. Invocation stays byte-identical for every scenario
// except proxy, which needs the JavaScript invoke adapter.
import {
Channel,
convertFileSrc,
invoke as realInvoke,
type InvokeArgs,
type InvokeOptions,
} from '../../node_modules/@tauri-apps/api/core.js'
import { mockCommand } from './invoke-mock'
import { scenario } from './replay'
const proxied = scenario === 'proxy'
export const invoke = async <T>(
cmd: string,
args?: InvokeArgs,
options?: InvokeOptions,
): Promise<T> => {
if (proxied) {
const mocked = mockCommand(cmd)
if (mocked !== undefined) return mocked as T
}
return realInvoke(cmd, args, options)
}
export { Channel, convertFileSrc }
-6
View File
@@ -6,11 +6,5 @@ export default mergeConfig(
defineConfig({ defineConfig({
root: 'scripts/perf', root: 'scripts/perf',
build: { outDir: '../../target/perf/dist', target: 'safari16' }, build: { outDir: '../../target/perf/dist', target: 'safari16' },
resolve: {
alias: {
'@tauri-apps/api/core': new URL('./tauri-core-shim.ts', import.meta.url)
.pathname,
},
},
}), }),
) )
+5 -5
View File
@@ -54,7 +54,7 @@ log = { workspace = true }
serde = { workspace = true, features = ["derive"] } serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true } serde_json = { workspace = true }
serde_yaml_ng = { workspace = true } serde_yaml_ng = { workspace = true }
tristr = { workspace = true } smartstring = { workspace = true, features = ["serde"] }
socket2 = { workspace = true } socket2 = { workspace = true }
warp = { version = "0.4.4", features = ["server"] } warp = { version = "0.4.4", features = ["server"] }
open = "5.4.5" open = "5.4.5"
@@ -67,7 +67,7 @@ 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", rev = "2c9d0a538052aac6e44ad413156a6e848da262b9", version = "0.7.2", features = [ sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs.git", branch = "main", features = [
"guard", "guard",
] } ] }
network-interface = { version = "2.0.5", features = ["serde"] } network-interface = { version = "2.0.5", features = ["serde"] }
@@ -77,7 +77,7 @@ 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.6.0" zip = "9.5.1"
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" }
@@ -91,9 +91,9 @@ backon = { version = "1.6.0", features = ["tokio-sleep"] }
tauri-plugin-http = "2.9.0" tauri-plugin-http = "2.9.0"
tracing = { workspace = true } tracing = { workspace = true }
tauri-plugin-devtools = { version = "2.2.3", optional = true } tauri-plugin-devtools = { version = "2.2.3", optional = true }
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "7e4fa8642cf6c394ed88b5a969420d8eab60087f" } 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.8.1", version = "2.8.1", features = [ clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", tag = "v2.7.7", version = "2.7.7", features = [
"client", "client",
] } ] }
arc-swap = "1.9.5" arc-swap = "1.9.5"
+1 -1
View File
@@ -8,8 +8,8 @@ use crate::{
feat, feat,
utils::dirs, utils::dirs,
}; };
use smartstring::alias::String;
use tauri::{AppHandle, Manager as _, ipc::Channel}; use tauri::{AppHandle, Manager as _, ipc::Channel};
use tristr::alias::String;
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
+1 -1
View File
@@ -1,7 +1,7 @@
use super::CmdResult; use super::CmdResult;
use crate::{cmd::StringifyErr as _, feat}; use crate::{cmd::StringifyErr as _, feat};
use feat::LocalBackupFile; use feat::LocalBackupFile;
use tristr::alias::String; use smartstring::alias::String;
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
+1 -1
View File
@@ -12,8 +12,8 @@ use crate::{
}, },
}; };
use clash_verge_logging::{Type, logging, logging_error}; use clash_verge_logging::{Type, logging, logging_error};
use smartstring::alias::String;
use tokio::fs; use tokio::fs;
use tristr::alias::String;
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
+1 -1
View File
@@ -1,5 +1,5 @@
use anyhow::Result; use anyhow::Result;
use tristr::alias::String; use smartstring::alias::String;
pub type CmdResult<T = ()> = Result<T, CommandFailure>; pub type CmdResult<T = ()> = Result<T, CommandFailure>;
+13 -3
View File
@@ -18,11 +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 smartstring::alias::String;
use std::{ use std::{
mem::DropGuard, mem::DropGuard,
sync::atomic::{AtomicBool, Ordering}, sync::atomic::{AtomicBool, Ordering},
}; };
use tristr::alias::String;
static CURRENT_SWITCHING_PROFILE: AtomicBool = AtomicBool::new(false); static CURRENT_SWITCHING_PROFILE: AtomicBool = AtomicBool::new(false);
@@ -210,10 +210,10 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
Ok(()) Ok(())
} }
async fn restore_previous_profile(prev_profile: &str) -> CmdResult<()> { async fn restore_previous_profile(prev_profile: &String) -> 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.into()), current: Some(prev_profile.to_owned()),
items: None, items: None,
}; };
Config::profiles() Config::profiles()
@@ -322,6 +322,7 @@ async fn perform_config_update(
#[derive(Default, serde::Deserialize, specta::Type)] #[derive(Default, serde::Deserialize, specta::Type)]
#[serde(default)] #[serde(default)]
pub struct ProfileSelection { pub struct ProfileSelection {
#[specta(type = Option<std::string::String>)]
pub current: Option<String>, pub current: Option<String>,
} }
@@ -329,9 +330,13 @@ pub struct ProfileSelection {
#[serde(default)] #[serde(default)]
pub struct ProfileCreate { pub struct ProfileCreate {
#[serde(rename = "type")] #[serde(rename = "type")]
#[specta(type = Option<std::string::String>)]
pub itype: Option<String>, pub itype: Option<String>,
#[specta(type = Option<std::string::String>)]
pub name: Option<String>, pub name: Option<String>,
#[specta(type = Option<std::string::String>)]
pub desc: Option<String>, pub desc: Option<String>,
#[specta(type = Option<std::string::String>)]
pub url: Option<String>, pub url: Option<String>,
pub option: Option<PrfOption>, pub option: Option<PrfOption>,
} }
@@ -353,10 +358,15 @@ impl From<ProfileCreate> for PrfItem {
#[serde(default)] #[serde(default)]
pub struct ProfilePatch { pub struct ProfilePatch {
#[serde(rename = "type")] #[serde(rename = "type")]
#[specta(type = Option<std::string::String>)]
pub itype: Option<String>, pub itype: Option<String>,
#[specta(type = Option<std::string::String>)]
pub name: Option<String>, pub name: Option<String>,
#[specta(type = Option<std::string::String>)]
pub desc: Option<String>, pub desc: Option<String>,
#[specta(type = Option<std::string::String>)]
pub file: Option<String>, pub file: Option<String>,
#[specta(type = Option<std::string::String>)]
pub url: Option<String>, pub url: Option<String>,
pub selected: Option<Vec<crate::config::PrfSelected>>, pub selected: Option<Vec<crate::config::PrfSelected>>,
pub extra: Option<crate::config::PrfExtra>, pub extra: Option<crate::config::PrfExtra>,
-6
View File
@@ -27,12 +27,6 @@ pub async fn switch_proxy_node(group_name: String, proxy_name: String, unfix: bo
.stringify_err() .stringify_err()
} }
#[tauri::command]
#[specta::specta]
pub async fn follow_proxy_group(group_name: String) {
crate::feat::follow_proxy_group(&group_name).await;
}
fn runtime_group_order(config: Option<&Mapping>) -> Vec<String> { fn runtime_group_order(config: Option<&Mapping>) -> Vec<String> {
let mut seen = HashSet::new(); let mut seen = HashSet::new();
+5 -2
View File
@@ -1,8 +1,8 @@
use super::CmdResult; use super::CmdResult;
use crate::{cmd::StringifyErr as _, config::Config, core::CoreManager, utils::yaml_emitter}; use crate::{cmd::StringifyErr as _, config::Config, core::CoreManager, utils::yaml_emitter};
use anyhow::{Context as _, anyhow}; use anyhow::{Context as _, anyhow};
use smartstring::alias::String;
use std::collections::HashMap; use std::collections::HashMap;
use tristr::alias::String;
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
@@ -36,7 +36,10 @@ pub async fn get_runtime_logs() -> CmdResult<RuntimeLogs> {
#[derive(serde::Serialize, specta::Type)] #[derive(serde::Serialize, specta::Type)]
#[serde(transparent)] #[serde(transparent)]
pub struct RuntimeLogs(HashMap<String, Vec<(String, String)>>); pub struct RuntimeLogs(
#[specta(type = HashMap<std::string::String, Vec<(std::string::String, std::string::String)>>)]
HashMap<String, Vec<(String, String)>>,
);
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
+1 -1
View File
@@ -11,8 +11,8 @@ use crate::{
utils::dirs, utils::dirs,
}; };
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use smartstring::alias::String;
use tokio::fs; use tokio::fs;
use tristr::alias::String;
/// 保存profiles的配置 /// 保存profiles的配置
#[tauri::command] #[tauri::command]
+1 -1
View File
@@ -4,7 +4,7 @@ use crate::{
config::{Config, IVerge}, config::{Config, IVerge},
core, feat, core, feat,
}; };
use tristr::alias::String; use smartstring::alias::String;
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
+5 -17
View File
@@ -20,10 +20,10 @@ use backon::{ExponentialBuilder, Retryable as _};
use clash_verge_draft::Draft; use clash_verge_draft::Draft;
use clash_verge_logging::{Type, logging, logging_error}; use clash_verge_logging::{Type, logging, logging_error};
use serde_yaml_ng::{Mapping, Value}; use serde_yaml_ng::{Mapping, Value};
use smartstring::alias::String;
use std::{collections::HashSet, path::PathBuf}; use std::{collections::HashSet, path::PathBuf};
use tokio::sync::{Mutex, MutexGuard, OnceCell}; use tokio::sync::{Mutex, MutexGuard, OnceCell};
use tokio::time::sleep; use tokio::time::sleep;
use tristr::alias::String;
pub(crate) struct Config { pub(crate) struct Config {
clash_config: Draft<IClashTemp>, clash_config: Draft<IClashTemp>,
@@ -34,9 +34,6 @@ pub(crate) struct Config {
static CONFIG_WRITE_LOCK: Mutex<()> = Mutex::const_new(()); static CONFIG_WRITE_LOCK: Mutex<()> = Mutex::const_new(());
static RUNTIME_YAML_CACHE: parking_lot::Mutex<Option<(u64, std::sync::Arc<std::string::String>)>> =
parking_lot::Mutex::new(None);
impl Config { impl Config {
async fn global() -> &'static Self { async fn global() -> &'static Self {
static CONFIG: OnceCell<Config> = OnceCell::const_new(); static CONFIG: OnceCell<Config> = OnceCell::const_new();
@@ -208,7 +205,7 @@ impl Config {
Self::write_runtime_file(&yaml).await Self::write_runtime_file(&yaml).await
} }
pub(crate) async fn runtime_config_yaml() -> Result<std::sync::Arc<std::string::String>> { pub(crate) async fn runtime_config_yaml() -> Result<std::string::String> {
let runtime = Self::runtime().await; let runtime = Self::runtime().await;
AsyncHandler::spawn_blocking(move || { AsyncHandler::spawn_blocking(move || {
let runtime_lastest = runtime.latest_arc(); let runtime_lastest = runtime.latest_arc();
@@ -218,17 +215,8 @@ impl Config {
.as_ref() .as_ref()
.or_else(|| runtime_data.config.as_ref()) .or_else(|| runtime_data.config.as_ref())
.ok_or_else(|| anyhow!("failed to generate runtime config, might need to restart application"))?; .ok_or_else(|| anyhow!("failed to generate runtime config, might need to restart application"))?;
let mut hasher = std::collections::hash_map::DefaultHasher::new(); let yaml_str = serde_yaml_ng::to_string(config)?;
std::hash::Hash::hash(config, &mut hasher); Ok(format!("# Generated by Clash Verge\n\n{}", yaml_str))
let key = std::hash::Hasher::finish(&hasher);
if let Some((cached_key, cached)) = RUNTIME_YAML_CACHE.lock().as_ref()
&& *cached_key == key
{
return Ok(std::sync::Arc::clone(cached));
}
let yaml_str = std::sync::Arc::new(serde_yaml_ng::to_string(config)?);
*RUNTIME_YAML_CACHE.lock() = Some((key, std::sync::Arc::clone(&yaml_str)));
Ok(yaml_str)
}) })
.await .await
.map_err(|join| anyhow!("runtime serialization task failed: {join}"))? .map_err(|join| anyhow!("runtime serialization task failed: {join}"))?
@@ -236,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, Some("# Generated by Clash Verge")).await?; help::save_yaml_str(&path, yaml).await?;
Ok(path) Ok(path)
} }
+5 -3
View File
@@ -1,12 +1,11 @@
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};
use serde_yaml_ng::{Mapping, Value}; use serde_yaml_ng::{Mapping, Value};
use sha2::{Digest as _, Sha256}; use sha2::{Digest as _, Sha256};
use smartstring::alias::String;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use tristr::alias::String;
use super::{Config, IVerge}; use super::{Config, IVerge};
use crate::core::handle::Handle; use crate::core::handle::Handle;
@@ -50,7 +49,9 @@ 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(help::hex_encode(&digest.finalize()).into())) Ok(Some(
digest.finalize().iter().map(|byte| format!("{byte:02x}")).collect(),
))
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@@ -109,6 +110,7 @@ impl DnsOverrideState {
pub struct ProfileDnsSettings { pub struct ProfileDnsSettings {
pub enabled: bool, pub enabled: bool,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(type = Option<std::string::String>)]
pub confirmation: Option<String>, pub confirmation: Option<String>,
} }
+18 -2
View File
@@ -11,9 +11,9 @@ use crate::{
use anyhow::{Context as _, Result, bail}; use anyhow::{Context as _, Result, bail};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_yaml_ng::Mapping; use serde_yaml_ng::Mapping;
use smartstring::alias::String;
use std::time::Duration; use std::time::Duration;
use tokio::fs; use tokio::fs;
use tristr::alias::String;
// TODO, use other re-export // TODO, use other re-export
use reqwest_dav::re_exports::url::form_urlencoded; use reqwest_dav::re_exports::url::form_urlencoded;
use tauri::Url; use tauri::Url;
@@ -26,24 +26,30 @@ pub(super) fn normalize_profile_home_url(raw: &str) -> Option<String> {
} }
url.host_str()?; url.host_str()?;
Some(url.as_str().into()) Some(url.to_string().into())
} }
#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)] #[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)]
#[serde(default)] #[serde(default)]
pub struct PrfItem { pub struct PrfItem {
#[specta(type = Option<std::string::String>)]
pub uid: Option<String>, pub uid: Option<String>,
/// enum value: remote | local | script | merge /// enum value: remote | local | script | merge
#[serde(rename = "type")] #[serde(rename = "type")]
#[specta(type = Option<std::string::String>)]
pub itype: Option<String>, pub itype: Option<String>,
#[specta(type = Option<std::string::String>)]
pub name: Option<String>, pub name: Option<String>,
#[specta(type = Option<std::string::String>)]
pub file: Option<String>, pub file: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
#[specta(type = Option<std::string::String>)]
pub desc: Option<String>, pub desc: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
#[specta(type = Option<std::string::String>)]
pub url: Option<String>, pub url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
@@ -58,16 +64,20 @@ pub struct PrfItem {
pub option: Option<PrfOption>, pub option: Option<PrfOption>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
#[specta(type = Option<std::string::String>)]
pub home: Option<String>, pub home: Option<String>,
#[serde(skip)] #[serde(skip)]
#[specta(type = Option<std::string::String>)]
pub file_data: Option<String>, pub file_data: Option<String>,
} }
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)] #[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)]
#[serde(default)] #[serde(default)]
pub struct PrfSelected { pub struct PrfSelected {
#[specta(type = Option<std::string::String>)]
pub name: Option<String>, pub name: Option<String>,
#[specta(type = Option<std::string::String>)]
pub now: Option<String>, pub now: Option<String>,
} }
@@ -83,6 +93,7 @@ pub struct PrfExtra {
#[serde(default)] #[serde(default)]
pub struct PrfOption { pub struct PrfOption {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
#[specta(type = Option<std::string::String>)]
pub user_agent: Option<String>, pub user_agent: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
@@ -105,10 +116,15 @@ pub struct PrfOption {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub allow_auto_update: Option<bool>, pub allow_auto_update: Option<bool>,
#[specta(type = Option<std::string::String>)]
pub merge: Option<String>, pub merge: Option<String>,
#[specta(type = Option<std::string::String>)]
pub script: Option<String>, pub script: Option<String>,
#[specta(type = Option<std::string::String>)]
pub rules: Option<String>, pub rules: Option<String>,
#[specta(type = Option<std::string::String>)]
pub proxies: Option<String>, pub proxies: Option<String>,
#[specta(type = Option<std::string::String>)]
pub groups: Option<String>, pub groups: Option<String>,
} }
+10 -13
View File
@@ -17,6 +17,7 @@ use clash_verge_logging::{Type, logging};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_yaml_ng::Mapping; use serde_yaml_ng::Mapping;
use smartstring::alias::String;
use std::num::NonZeroUsize; use std::num::NonZeroUsize;
use std::{ use std::{
collections::{HashMap, HashSet}, collections::{HashMap, HashSet},
@@ -29,7 +30,6 @@ use std::{
}; };
use tauri_plugin_mihomo::models::{Proxies, ProxyType}; use tauri_plugin_mihomo::models::{Proxies, ProxyType};
use tokio::{fs, task::JoinHandle}; use tokio::{fs, task::JoinHandle};
use tristr::alias::String;
pub(crate) static PROFILE_WRITE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); pub(crate) static PROFILE_WRITE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
@@ -51,6 +51,7 @@ const SELECTED_NODES_FIRST_PASS_BUDGET: Duration = Duration::from_secs(3);
#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)] #[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)]
#[serde(default)] #[serde(default)]
pub struct IProfiles { pub struct IProfiles {
#[specta(type = Option<std::string::String>)]
pub current: Option<String>, pub current: Option<String>,
pub items: Option<Vec<PrfItem>>, pub items: Option<Vec<PrfItem>>,
@@ -604,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: &str, node: &str) -> Result<()> { async fn select_node_with_timeout(group_name: &String, node: &String) -> 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
}) })
@@ -760,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 selected = item.selected.get_or_insert_with(Vec::new); let mut selected = item.selected.clone().unwrap_or_default();
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))
@@ -769,13 +770,14 @@ 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.clone()); entry.now = Some(node);
} }
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))
}) })
@@ -794,17 +796,12 @@ pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
return Ok((profiles, false)); return Ok((profiles, false));
}; };
let Some(mut selected) = item.selected.take() else { let mut selected = item.selected.clone().unwrap_or_default();
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));
} }
if !selected.is_empty() { item.selected = (!selected.is_empty()).then_some(selected);
item.selected = Some(selected);
}
profiles.save_file().await?; profiles.save_file().await?;
Ok((profiles, true)) Ok((profiles, true))
}) })
@@ -812,7 +809,7 @@ pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
} }
async fn persist_reconciled_selected( async fn persist_reconciled_selected(
profile_uid: &str, profile_uid: &String,
original_selected: &[PrfSelected], original_selected: &[PrfSelected],
selected: Vec<PrfSelected>, selected: Vec<PrfSelected>,
generation: u64, generation: u64,
@@ -821,7 +818,7 @@ async fn persist_reconciled_selected(
return Ok(()); return Ok(());
} }
let profile_uid = String::from(profile_uid); let profile_uid = profile_uid.clone();
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) {
+1 -1
View File
@@ -1,6 +1,6 @@
use serde_yaml_ng::{Mapping, Value}; use serde_yaml_ng::{Mapping, Value};
use smartstring::alias::String;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use tristr::alias::String;
use crate::enhance::field::use_keys; use crate::enhance::field::use_keys;
+36 -5
View File
@@ -8,26 +8,33 @@ use anyhow::Result;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use log::LevelFilter; use log::LevelFilter;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tristr::alias::String; use smartstring::alias::String;
/// ### `verge.yaml` schema /// ### `verge.yaml` schema
#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)] #[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)]
#[serde(default)] #[serde(default)]
pub struct IVerge { pub struct IVerge {
/// silent | error | warn | info | debug | trace /// silent | error | warn | info | debug | trace
#[specta(type = Option<std::string::String>)]
pub app_log_level: Option<String>, pub app_log_level: Option<String>,
/// Maximum app log size in KiB. /// Maximum app log size in KiB.
pub app_log_max_size: Option<u64>, pub app_log_max_size: Option<u64>,
pub app_log_max_count: Option<usize>, pub app_log_max_count: Option<usize>,
#[specta(type = Option<std::string::String>)]
pub language: Option<String>, pub language: Option<String>,
/// `light` or `dark` or `system` /// `light` or `dark` or `system`
#[specta(type = Option<std::string::String>)]
pub theme_mode: Option<String>, pub theme_mode: Option<String>,
#[specta(type = Option<std::string::String>)]
pub tray_event: Option<String>, pub tray_event: Option<String>,
#[specta(type = Option<std::string::String>)]
pub env_type: Option<String>, pub env_type: Option<String>,
#[specta(type = Option<std::string::String>)]
pub start_page: Option<String>, pub start_page: Option<String>,
#[specta(type = Option<std::string::String>)]
pub startup_script: Option<String>, pub startup_script: Option<String>,
pub traffic_graph: Option<bool>, pub traffic_graph: Option<bool>,
@@ -45,18 +52,23 @@ pub struct IVerge {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
#[specta(type = Option<std::string::String>)]
pub tray_icon: Option<String>, pub tray_icon: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
#[specta(type = Option<std::string::String>)]
pub menu_icon: Option<String>, pub menu_icon: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
#[specta(type = Option<Vec<std::string::String>>)]
pub menu_order: Option<Vec<String>>, pub menu_order: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
#[specta(type = Option<std::string::String>)]
pub proxy_group_tools_position: Option<String>, pub proxy_group_tools_position: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
#[specta(type = Option<std::string::String>)]
pub notice_position: Option<String>, pub notice_position: Option<String>,
pub collapse_navbar: Option<bool>, pub collapse_navbar: Option<bool>,
@@ -81,25 +93,32 @@ pub struct IVerge {
pub enable_dns_settings: Option<bool>, pub enable_dns_settings: Option<bool>,
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
#[specta(type = std::collections::BTreeMap<std::string::String, super::dns::ProfileDnsSettings>)]
pub profile_dns_settings: std::collections::BTreeMap<String, super::dns::ProfileDnsSettings>, pub profile_dns_settings: std::collections::BTreeMap<String, super::dns::ProfileDnsSettings>,
pub use_default_bypass: Option<bool>, pub use_default_bypass: Option<bool>,
#[specta(type = Option<std::string::String>)]
pub system_proxy_bypass: Option<String>, pub system_proxy_bypass: Option<String>,
pub proxy_guard_duration: Option<u64>, pub proxy_guard_duration: Option<u64>,
pub proxy_auto_config: Option<bool>, pub proxy_auto_config: Option<bool>,
#[specta(type = Option<std::string::String>)]
pub pac_file_content: Option<String>, pub pac_file_content: Option<String>,
#[specta(type = Option<std::string::String>)]
pub proxy_host: Option<String>, pub proxy_host: Option<String>,
pub theme_setting: Option<IVergeTheme>, pub theme_setting: Option<IVergeTheme>,
#[specta(type = Option<Vec<std::string::String>>)]
pub web_ui_list: Option<Vec<String>>, pub web_ui_list: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
#[specta(type = Option<std::string::String>)]
pub clash_core: Option<String>, pub clash_core: Option<String>,
/// format: {func},{key} /// format: {func},{key}
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
#[specta(type = Option<Vec<std::string::String>>)]
pub hotkeys: Option<Vec<String>>, pub hotkeys: Option<Vec<String>>,
pub enable_global_hotkey: Option<bool>, pub enable_global_hotkey: Option<bool>,
@@ -109,9 +128,8 @@ pub struct IVerge {
pub auto_close_connection: Option<bool>, pub auto_close_connection: Option<bool>,
pub auto_switch_selector_group: Option<bool>,
pub auto_check_update: Option<bool>, pub auto_check_update: Option<bool>,
#[specta(type = Option<std::string::String>)]
pub default_latency_test: Option<String>, pub default_latency_test: Option<String>,
pub default_latency_timeout: Option<i16>, pub default_latency_timeout: Option<i16>,
@@ -191,6 +209,7 @@ pub struct IVerge {
pub enable_tray_speed: Option<bool>, pub enable_tray_speed: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
#[specta(type = Option<std::string::String>)]
pub tray_proxy_groups_display_mode: Option<String>, pub tray_proxy_groups_display_mode: Option<String>,
pub tray_inline_outbound_modes: Option<bool>, pub tray_inline_outbound_modes: Option<bool>,
@@ -210,24 +229,38 @@ pub struct IVerge {
#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)] #[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)]
#[serde(default)] #[serde(default)]
pub struct IVergeTestItem { pub struct IVergeTestItem {
#[specta(type = Option<std::string::String>)]
pub uid: Option<String>, pub uid: Option<String>,
#[specta(type = Option<std::string::String>)]
pub name: Option<String>, pub name: Option<String>,
#[specta(type = Option<std::string::String>)]
pub icon: Option<String>, pub icon: Option<String>,
#[specta(type = Option<std::string::String>)]
pub url: Option<String>, pub url: Option<String>,
} }
#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)] #[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)]
#[serde(default)] #[serde(default)]
pub struct IVergeTheme { pub struct IVergeTheme {
#[specta(type = Option<std::string::String>)]
pub primary_color: Option<String>, pub primary_color: Option<String>,
#[specta(type = Option<std::string::String>)]
pub secondary_color: Option<String>, pub secondary_color: Option<String>,
#[specta(type = Option<std::string::String>)]
pub primary_text: Option<String>, pub primary_text: Option<String>,
#[specta(type = Option<std::string::String>)]
pub secondary_text: Option<String>, pub secondary_text: Option<String>,
#[specta(type = Option<std::string::String>)]
pub info_color: Option<String>, pub info_color: Option<String>,
#[specta(type = Option<std::string::String>)]
pub error_color: Option<String>, pub error_color: Option<String>,
#[specta(type = Option<std::string::String>)]
pub warning_color: Option<String>, pub warning_color: Option<String>,
#[specta(type = Option<std::string::String>)]
pub success_color: Option<String>, pub success_color: Option<String>,
#[specta(type = Option<std::string::String>)]
pub font_family: Option<String>, pub font_family: Option<String>,
#[specta(type = Option<std::string::String>)]
pub css_injection: Option<String>, pub css_injection: Option<String>,
} }
@@ -370,7 +403,6 @@ impl IVerge {
use_default_bypass: Some(true), use_default_bypass: Some(true),
proxy_guard_duration: Some(30), proxy_guard_duration: Some(30),
auto_close_connection: Some(true), auto_close_connection: Some(true),
auto_switch_selector_group: Some(true),
auto_check_update: Some(true), auto_check_update: Some(true),
enable_builtin_enhanced: Some(true), enable_builtin_enhanced: Some(true),
auto_log_clean: Some(2), // 1: 1天, 2: 7天, 3: 30天, 4: 90天 auto_log_clean: Some(2), // 1: 1天, 2: 7天, 3: 30天, 4: 90天
@@ -459,7 +491,6 @@ impl IVerge {
patch_opt_field!(self, patch, enable_global_hotkey); patch_opt_field!(self, patch, enable_global_hotkey);
patch_opt_field!(self, patch, auto_close_connection); patch_opt_field!(self, patch, auto_close_connection);
patch_opt_field!(self, patch, auto_switch_selector_group);
patch_opt_field!(self, patch, auto_check_update); patch_opt_field!(self, patch, auto_check_update);
patch_opt_field!(self, patch, default_latency_test); patch_opt_field!(self, patch, default_latency_test);
patch_opt_field!(self, patch, default_latency_timeout); patch_opt_field!(self, patch, default_latency_timeout);
+1 -1
View File
@@ -5,6 +5,7 @@ use arc_swap::{ArcSwap, ArcSwapOption};
use backon::{ConstantBuilder, Retryable as _}; use backon::{ConstantBuilder, Retryable as _};
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use reqwest_dav::list_cmd::{ListEntity, ListFile, ListMultiStatus}; use reqwest_dav::list_cmd::{ListEntity, ListFile, ListMultiStatus};
use smartstring::alias::String;
use std::{ use std::{
collections::HashMap, collections::HashMap,
env::{consts::OS, temp_dir}, env::{consts::OS, temp_dir},
@@ -14,7 +15,6 @@ use std::{
time::Duration, time::Duration,
}; };
use tokio::{fs, time::timeout}; use tokio::{fs, time::timeout};
use tristr::alias::String;
use zip::write::SimpleFileOptions; use zip::write::SimpleFileOptions;
const APP_VERSION: &str = env!("CARGO_PKG_VERSION"); const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
+1 -1
View File
@@ -7,6 +7,7 @@ use crate::{config::Config, core::handle, core::lightweight::entry_lightweight_m
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use arc_swap::ArcSwap; use arc_swap::ArcSwap;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use smartstring::alias::String;
use std::{ use std::{
collections::HashMap, collections::HashMap,
fmt, fmt,
@@ -17,7 +18,6 @@ use std::{
}, },
}; };
use tauri_plugin_global_shortcut::{Code, GlobalShortcutExt as _, ShortcutState}; use tauri_plugin_global_shortcut::{Code, GlobalShortcutExt as _, ShortcutState};
use tristr::alias::String;
/// Enum representing all available hotkey functions /// Enum representing all available hotkey functions
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+1 -1
View File
@@ -14,6 +14,7 @@ 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 smartstring::alias::String;
use std::{ use std::{
collections::HashSet, collections::HashSet,
mem::DropGuard, mem::DropGuard,
@@ -22,7 +23,6 @@ use std::{
time::{Duration, Instant}, time::{Duration, Instant},
}; };
use tauri_plugin_mihomo::Error as MihomoError; use tauri_plugin_mihomo::Error as MihomoError;
use tristr::alias::String;
/// A staging result separated from the policy that acts on it. /// A staging result separated from the policy that acts on it.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
+1 -1
View File
@@ -6,10 +6,10 @@ 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 smartstring::alias::String;
use std::{mem::DropGuard, 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;
use tristr::alias::String;
#[cfg(any(target_os = "windows", test))] #[cfg(any(target_os = "windows", test))]
const fn should_wait_for_service(tun_enabled: bool, service_ready: bool, is_admin: bool) -> bool { const fn should_wait_for_service(tun_enabled: bool, service_ready: bool, is_admin: bool) -> bool {
+3 -6
View File
@@ -42,12 +42,9 @@ 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")
let body = if body.contains("{mode}") { .replace("{mode}", mode)
body.replace("{mode}", mode).into() .into();
} else {
body
};
notify(title, body); notify(title, body);
} }
NotificationEvent::SystemProxyToggled(enabled) => { NotificationEvent::SystemProxyToggled(enabled) => {
+5 -6
View File
@@ -1,13 +1,12 @@
use super::NoticeStatus; use super::NoticeStatus;
use crate::{APP_HANDLE, singleton}; use crate::{APP_HANDLE, singleton};
use smartstring::alias::String;
use std::sync::{ use std::sync::{
Arc, Arc,
atomic::{AtomicBool, Ordering}, atomic::{AtomicBool, Ordering},
}; };
use tauri::AppHandle; use tauri::AppHandle;
use tauri_plugin_mihomo::{Mihomo, MihomoExt as _}; use tauri_plugin_mihomo::{Mihomo, MihomoExt as _};
#[cfg(target_os = "macos")]
use tristr::alias::String;
use super::notification::{FrontendEvent, NotificationSystem}; use super::notification::{FrontendEvent, NotificationSystem};
@@ -56,21 +55,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: &str) { pub fn notify_profile_changed(profile_id: &String) {
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: &str) { pub fn notify_timer_updated(profile_index: &String) {
Self::send_event(FrontendEvent::TimerUpdated { profile_index }); Self::send_event(FrontendEvent::TimerUpdated { profile_index });
} }
pub fn notify_profile_update_started(uid: &str) { pub fn notify_profile_update_started(uid: &String) {
Self::send_event(FrontendEvent::ProfileUpdateStarted { uid }); Self::send_event(FrontendEvent::ProfileUpdateStarted { uid });
} }
pub fn notify_profile_update_completed(uid: &str) { pub fn notify_profile_update_completed(uid: &String) {
Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid }); Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid });
} }
+9 -6
View File
@@ -3,11 +3,11 @@ use clash_verge_logging::{Type, logging};
use parking_lot::Mutex; use parking_lot::Mutex;
#[cfg(test)] #[cfg(test)]
use serde_json::json; use serde_json::json;
use smartstring::alias::String;
use std::sync::Arc; use std::sync::Arc;
use std::sync::LazyLock; use std::sync::LazyLock;
use std::{collections::HashMap, future::Future}; use std::{collections::HashMap, future::Future};
use tauri::{AppHandle, Emitter as _, Manager as _, WebviewWindow}; use tauri::{AppHandle, Emitter as _, Manager as _, WebviewWindow};
use tristr::alias::String;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum FrontendEvent<'a> { pub enum FrontendEvent<'a> {
@@ -20,16 +20,16 @@ pub enum FrontendEvent<'a> {
message: Arc<str>, message: Arc<str>,
}, },
ProfileChanged { ProfileChanged {
current_profile_id: &'a str, current_profile_id: &'a String,
}, },
TimerUpdated { TimerUpdated {
profile_index: &'a str, profile_index: &'a String,
}, },
ProfileUpdateStarted { ProfileUpdateStarted {
uid: &'a str, uid: &'a String,
}, },
ProfileUpdateCompleted { ProfileUpdateCompleted {
uid: &'a str, uid: &'a String,
}, },
RunStateChanged { RunStateChanged {
state: crate::core::runstate::RunStateView, state: crate::core::runstate::RunStateView,
@@ -77,8 +77,10 @@ impl FailedOperation {
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct PendingFailure { pub struct PendingFailure {
/// Stable code used as the table key. /// Stable code used as the table key.
#[specta(type = std::string::String)]
pub code: String, pub code: String,
/// Full diagnostic context chain. /// Full diagnostic context chain.
#[specta(type = std::string::String)]
pub detail: String, pub detail: String,
pub operation: FailedOperation, pub operation: FailedOperation,
/// Monotonic identity for repeated failures under the same code. /// Monotonic identity for repeated failures under the same code.
@@ -245,6 +247,7 @@ static PENDING_FAILURES: LazyLock<FailureTable> = LazyLock::new(FailureTable::de
#[derive(Debug, Default, Clone, serde::Serialize, specta::Type)] #[derive(Debug, Default, Clone, serde::Serialize, specta::Type)]
pub struct SidecarFailureSnapshot { pub struct SidecarFailureSnapshot {
pub revision: u64, pub revision: u64,
#[specta(type = Option<std::string::String>)]
pub detail: Option<String>, pub detail: Option<String>,
} }
@@ -366,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: &str) -> Vec<(FrontendEvent<'_>, &'static str, serde_json::Value)> { fn sample_frontend_events(uid: &String) -> 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,
+1 -1
View File
@@ -122,7 +122,7 @@ 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 = crate::utils::help::hex_encode(&digest.finalize()); let digest: String = digest.finalize().iter().map(|byte| format!("{byte:02x}")).collect();
let path = Path::new(destination); let path = Path::new(destination);
let extension = path let extension = path
.extension() .extension()
-6
View File
@@ -334,12 +334,6 @@ 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])
+1 -1
View File
@@ -7,6 +7,7 @@ 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 smartstring::alias::String;
use std::{ use std::{
mem::DropGuard, mem::DropGuard,
sync::{ sync::{
@@ -17,7 +18,6 @@ use std::{
}; };
use sysproxy::{Autoproxy, GuardMonitor, GuardType, Sysproxy}; use sysproxy::{Autoproxy, GuardMonitor, GuardType, Sysproxy};
use tokio::sync::Mutex as TokioMutex; use tokio::sync::Mutex as TokioMutex;
use tristr::alias::String;
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ProxyApplyStep { enum ProxyApplyStep {
+3 -3
View File
@@ -9,6 +9,7 @@ use anyhow::Result;
use clash_verge_logging::{Type, logging, logging_error}; use clash_verge_logging::{Type, logging, logging_error};
use futures::StreamExt as _; use futures::StreamExt as _;
use parking_lot::{Mutex, RwLock}; use parking_lot::{Mutex, RwLock};
use smartstring::alias::String;
use std::{ use std::{
collections::HashMap, collections::HashMap,
sync::{ sync::{
@@ -22,7 +23,6 @@ use tokio::{
time::{sleep, timeout}, time::{sleep, timeout},
}; };
use tokio_util::time::{DelayQueue, delay_queue::Key}; use tokio_util::time::{DelayQueue, delay_queue::Key};
use tristr::alias::String;
enum TimerCommand { enum TimerCommand {
Apply(HashMap<String, TaskSchedule>), Apply(HashMap<String, TaskSchedule>),
@@ -458,7 +458,7 @@ impl Timer {
} }
} }
fn emit_update_event(uid: &str, is_start: bool) { fn emit_update_event(uid: &String, 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 {
@@ -503,6 +503,7 @@ mod tests {
use crate::config::{PrfItem, PrfOption}; use crate::config::{PrfItem, PrfOption};
use futures::StreamExt as _; use futures::StreamExt as _;
use parking_lot::Mutex; use parking_lot::Mutex;
use smartstring::alias::String;
use std::collections::HashMap; use std::collections::HashMap;
use std::{ use std::{
sync::{ sync::{
@@ -514,7 +515,6 @@ mod tests {
}; };
use tokio::sync::Barrier; use tokio::sync::Barrier;
use tokio_util::time::DelayQueue; use tokio_util::time::DelayQueue;
use tristr::alias::String;
struct CancellationProbe { struct CancellationProbe {
cancelled: Arc<AtomicBool>, cancelled: Arc<AtomicBool>,
+75 -80
View File
@@ -1,4 +1,4 @@
use crate::config::{IProfilePreview, IProfiles, IVerge}; use crate::config::{IProfilePreview, IVerge};
use crate::core::lightweight; use crate::core::lightweight;
use crate::core::tray::menu_def::TrayAction; use crate::core::tray::menu_def::TrayAction;
use crate::process::AsyncHandler; use crate::process::AsyncHandler;
@@ -19,6 +19,7 @@ use tokio::fs;
use super::handle; use super::handle;
use anyhow::Result; use anyhow::Result;
use smartstring::alias::String;
use std::borrow::Cow; use std::borrow::Cow;
use std::collections::HashMap; use std::collections::HashMap;
use std::time::Duration; use std::time::Duration;
@@ -26,7 +27,6 @@ use tauri::{
AppHandle, Wry, AppHandle, Wry,
menu::{CheckMenuItem, IsMenuItem, MenuEvent, MenuItem, PredefinedMenuItem, Submenu}, menu::{CheckMenuItem, IsMenuItem, MenuEvent, MenuItem, PredefinedMenuItem, Submenu},
}; };
use tristr::alias::String;
mod menu_def; mod menu_def;
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
@@ -41,10 +41,7 @@ const TRAY_CLICK_DEBOUNCE_MS: u64 = 300;
pub const TRAY_ID: &str = "clash-verge-rev-tray"; pub const TRAY_ID: &str = "clash-verge-rev-tray";
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
struct TrayMenuOptions<'a> { struct TrayMenuOptions {
mode: Option<&'a str>,
system_proxy_enabled: bool,
tun_mode_enabled: bool,
is_lightweight_mode: bool, is_lightweight_mode: bool,
include_proxy_groups: bool, include_proxy_groups: bool,
} }
@@ -204,8 +201,9 @@ impl Tray {
}; };
let verge = Config::verge().await.latest_arc(); let verge = Config::verge().await.latest_arc();
let system_proxy = verge.enable_system_proxy.unwrap_or(false); let system_proxy = verge.enable_system_proxy.as_ref().unwrap_or(&false);
let tun_mode = verge.enable_tun_mode.unwrap_or(false); let tun_mode = verge.enable_tun_mode.as_ref().unwrap_or(&false);
let tun_mode_available = crate::core::runstate::RUN_STATE.state().tun_capable();
let mode = { let mode = {
Config::clash() Config::clash()
.await .await
@@ -215,72 +213,29 @@ impl Tray {
.map_or("rule", |val| val.as_str().unwrap_or("rule")) .map_or("rule", |val| val.as_str().unwrap_or("rule"))
.to_owned() .to_owned()
}; };
let profiles_config = Config::profiles().await;
let profiles_arc = profiles_config.latest_arc();
let profiles_preview = profiles_arc.profiles_preview().unwrap_or_default();
let is_lightweight_mode = is_in_lightweight_mode(); let is_lightweight_mode = is_in_lightweight_mode();
let fetch_proxy_groups = logging_error!(
include_proxy_groups && verge.tray_proxy_groups_display_mode.as_deref() != Some("disable"); Type::Tray,
tray.set_menu(Some(
// TODO: should update tray menu again when it was timeout error create_tray_menu(
let (proxy_nodes_data, runtime_proxy_groups_order) = if fetch_proxy_groups { app_handle,
let proxy_nodes_data = Some(mode.as_str()),
tokio::time::timeout(Duration::from_millis(1000), handle::Handle::mihomo().get_proxies()) *system_proxy,
.await *tun_mode,
.map_or(None, |res| res.ok()); tun_mode_available,
profiles_preview,
let runtime = Config::runtime().await.latest_arc();
let runtime_proxy_groups_order = runtime.config.as_ref().map(|config| {
config
.get("proxy-groups")
.and_then(|groups| groups.as_sequence())
.map_or_default(|groups| {
groups
.iter()
.filter_map(|group| group.get("name"))
.filter_map(|name| name.as_str())
.enumerate()
.map(|(index, name)| (name.into(), index))
.collect::<HashMap<String, usize>>()
})
});
(proxy_nodes_data, runtime_proxy_groups_order)
} else {
(None, None)
};
let verge = if fetch_proxy_groups {
Config::verge().await.latest_arc()
} else {
verge
};
let profiles = Config::profiles().await.latest_arc();
let (tx, rx) = tokio::sync::oneshot::channel();
let dispatch_handle = app_handle.clone();
app_handle
.run_on_main_thread(move || {
let _ = tx.send((|| -> Result<()> {
let menu = build_tray_menu(
&dispatch_handle,
TrayMenuOptions { TrayMenuOptions {
mode: Some(mode.as_str()),
system_proxy_enabled: system_proxy,
tun_mode_enabled: tun_mode,
is_lightweight_mode, is_lightweight_mode,
include_proxy_groups, include_proxy_groups,
}, },
&verge, )
&profiles, .await?,
runtime_proxy_groups_order, ))
proxy_nodes_data, );
)?;
logging_error!(Type::Tray, tray.set_menu(Some(menu)));
Ok(())
})());
})
.map_err(|e| anyhow::anyhow!("Failed to dispatch tray menu update: {e}"))?;
rx.await
.map_err(|_| anyhow::anyhow!("Tray menu update returned no result"))??;
logging!(debug, Type::Tray, "托盘菜单更新成功"); logging!(debug, Type::Tray, "托盘菜单更新成功");
Ok(()) Ok(())
@@ -387,6 +342,9 @@ 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));
@@ -624,16 +582,52 @@ fn create_proxy_menu_item(
Ok((proxies_submenu, inline_proxy_items)) Ok((proxies_submenu, inline_proxy_items))
} }
fn build_tray_menu( async fn create_tray_menu(
app_handle: &AppHandle, app_handle: &AppHandle,
options: TrayMenuOptions<'_>, mode: Option<&str>,
verge_settings: &IVerge, system_proxy_enabled: bool,
profiles_config: &IProfiles, tun_mode_enabled: bool,
proxy_group_order_map: Option<HashMap<String, usize>>, tun_mode_available: bool,
proxy_nodes_data: Option<Proxies>, profiles_preview: Vec<IProfilePreview<'_>>,
options: TrayMenuOptions,
) -> Result<tauri::menu::Menu<Wry>> { ) -> Result<tauri::menu::Menu<Wry>> {
let current_proxy_mode = options.mode.unwrap_or(""); let current_proxy_mode = mode.unwrap_or("");
let tun_mode_available = crate::core::runstate::RUN_STATE.state().tun_capable();
let mut verge_settings = Config::verge().await.latest_arc();
let fetch_proxy_groups =
options.include_proxy_groups && verge_settings.tray_proxy_groups_display_mode.as_deref() != Some("disable");
// TODO: should update tray menu again when it was timeout error
let (proxy_nodes_data, runtime_proxy_groups_order) = if fetch_proxy_groups {
let proxy_nodes_data =
tokio::time::timeout(Duration::from_millis(1000), handle::Handle::mihomo().get_proxies())
.await
.map_or(None, |res| res.ok());
let runtime = Config::runtime().await.latest_arc();
let runtime_proxy_groups_order = runtime.config.as_ref().map(|config| {
config
.get("proxy-groups")
.and_then(|groups| groups.as_sequence())
.map_or_default(|groups| {
groups
.iter()
.filter_map(|group| group.get("name"))
.filter_map(|name| name.as_str())
.enumerate()
.map(|(index, name)| (name.into(), index))
.collect::<HashMap<String, usize>>()
})
});
(proxy_nodes_data, runtime_proxy_groups_order)
} else {
(None, None)
};
if fetch_proxy_groups {
verge_settings = Config::verge().await.latest_arc();
}
let tray_proxy_groups_display_mode = verge_settings let tray_proxy_groups_display_mode = verge_settings
.tray_proxy_groups_display_mode .tray_proxy_groups_display_mode
@@ -642,14 +636,15 @@ fn build_tray_menu(
let include_proxy_groups = let include_proxy_groups =
options.include_proxy_groups && verge_settings.tray_proxy_groups_display_mode.as_deref() != Some("disable"); options.include_proxy_groups && verge_settings.tray_proxy_groups_display_mode.as_deref() != Some("disable");
let proxy_group_order_map = runtime_proxy_groups_order;
let show_outbound_modes_inline = verge_settings.tray_inline_outbound_modes.unwrap_or(false); let show_outbound_modes_inline = verge_settings.tray_inline_outbound_modes.unwrap_or(false);
let version = env!("CARGO_PKG_VERSION"); let version = env!("CARGO_PKG_VERSION");
let hotkeys = create_hotkeys(&verge_settings.hotkeys); let hotkeys = create_hotkeys(&verge_settings.hotkeys);
let profile_menu_items: Vec<CheckMenuItem<Wry>> = let profile_menu_items: Vec<CheckMenuItem<Wry>> = create_profile_menu_item(app_handle, profiles_preview)?;
create_profile_menu_item(app_handle, profiles_config.profiles_preview().unwrap_or_default())?;
let texts = MenuTexts::new(); let texts = MenuTexts::new();
let profile_menu_items_refs: Vec<&dyn IsMenuItem<Wry>> = profile_menu_items let profile_menu_items_refs: Vec<&dyn IsMenuItem<Wry>> = profile_menu_items
@@ -740,7 +735,7 @@ fn build_tray_menu(
MenuIds::SYSTEM_PROXY, MenuIds::SYSTEM_PROXY,
&texts.system_proxy, &texts.system_proxy,
true, true,
options.system_proxy_enabled, system_proxy_enabled,
hotkeys.get("toggle_system_proxy").copied(), hotkeys.get("toggle_system_proxy").copied(),
)?; )?;
@@ -749,7 +744,7 @@ fn build_tray_menu(
MenuIds::TUN_MODE, MenuIds::TUN_MODE,
&texts.tun_mode, &texts.tun_mode,
tun_mode_available, tun_mode_available,
options.tun_mode_enabled, tun_mode_enabled,
hotkeys.get("toggle_tun_mode").copied(), hotkeys.get("toggle_tun_mode").copied(),
)?; )?;
+10 -4
View File
@@ -1,5 +1,6 @@
use anyhow::Result; use anyhow::Result;
use serde::Serialize; use serde::Serialize;
use smartstring::alias::String;
use std::{ use std::{
fmt, fmt,
hash::{DefaultHasher, Hash as _, Hasher as _}, hash::{DefaultHasher, Hash as _, Hasher as _},
@@ -9,7 +10,6 @@ use std::{
}; };
use tauri_plugin_shell::ShellExt as _; use tauri_plugin_shell::ShellExt as _;
use tokio::fs; use tokio::fs;
use tristr::alias::String;
use crate::config::Config; use crate::config::Config;
use crate::core::handle; use crate::core::handle;
@@ -114,8 +114,14 @@ impl fmt::Display for ValidationSkipReason {
#[serde(tag = "status", rename_all = "camelCase")] #[serde(tag = "status", rename_all = "camelCase")]
pub enum ValidationOutcome { pub enum ValidationOutcome {
Valid, Valid,
Invalid { kind: ValidationErrorKind, message: String }, Invalid {
Skipped { reason: ValidationSkipReason }, kind: ValidationErrorKind,
#[specta(type = std::string::String)]
message: String,
},
Skipped {
reason: ValidationSkipReason,
},
Busy, Busy,
} }
@@ -429,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, None).await?; help::save_yaml_str(&check_path, yaml).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);
+10 -38
View File
@@ -3,22 +3,17 @@ use crate::{
config::PrfItem, config::PrfItem,
utils::{dirs, help}, utils::{dirs, help},
}; };
use parking_lot::Mutex;
use serde_yaml_ng::Mapping; use serde_yaml_ng::Mapping;
use std::collections::HashMap; use smartstring::alias::String;
use std::path::PathBuf;
use std::sync::{Arc, LazyLock};
use std::time::SystemTime;
use tokio::fs; use tokio::fs;
use tristr::alias::String;
#[derive(Debug)] #[derive(Debug, Clone)]
pub struct ChainItem { pub struct ChainItem {
pub uid: String, pub uid: String,
pub data: ChainType, pub data: ChainType,
} }
#[derive(Debug)] #[derive(Debug, Clone)]
pub enum ChainType { pub enum ChainType {
Merge(Mapping), Merge(Mapping),
Script(String), Script(String),
@@ -27,39 +22,26 @@ pub enum ChainType {
Groups(SeqMap), Groups(SeqMap),
} }
struct CachedChain {
mtime: SystemTime,
len: u64,
item: Arc<ChainItem>,
}
static CHAIN_CACHE: LazyLock<Mutex<HashMap<PathBuf, CachedChain>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
// Helper trait to allow async conversion // Helper trait to allow async conversion
pub trait AsyncChainItemFrom { pub trait AsyncChainItemFrom {
async fn from_async(item: &PrfItem) -> Option<Arc<ChainItem>>; async fn from_async(item: &PrfItem) -> Option<ChainItem>;
} }
impl AsyncChainItemFrom for Option<Arc<ChainItem>> { impl AsyncChainItemFrom for Option<ChainItem> {
async fn from_async(item: &PrfItem) -> Self { async fn from_async(item: &PrfItem) -> Self {
let itype = item.itype.as_ref()?.as_str(); let itype = item.itype.as_ref()?.as_str();
let file = item.file.clone()?; let file = item.file.clone()?;
let uid = item.uid.clone().unwrap_or_else(|| "".into()); let uid = item.uid.clone().unwrap_or_else(|| "".into());
let path = dirs::app_profiles_dir().ok()?.join(file.as_str()); let path = dirs::app_profiles_dir().ok()?.join(file.as_str());
let meta = fs::metadata(&path).await.ok()?; if !path.exists() {
let (mtime, len) = (meta.modified().ok()?, meta.len()); return None;
if let Some(cached) = CHAIN_CACHE.lock().get(&path)
&& cached.mtime == mtime
&& cached.len == len
{
return Some(Arc::clone(&cached.item));
} }
let loaded = Arc::new(match itype { match itype {
"script" => Some(ChainItem { "script" => Some(ChainItem {
uid, uid,
data: ChainType::Script(fs::read_to_string(&path).await.ok()?.as_str().into()), data: ChainType::Script(fs::read_to_string(path).await.ok()?.into()),
}), }),
"merge" => Some(ChainItem { "merge" => Some(ChainItem {
uid, uid,
@@ -75,16 +57,6 @@ impl AsyncChainItemFrom for Option<Arc<ChainItem>> {
Some(ChainItem { uid, data }) Some(ChainItem { uid, data })
} }
_ => None, _ => None,
}?); }
CHAIN_CACHE.lock().insert(
path,
CachedChain {
mtime,
len,
item: Arc::clone(&loaded),
},
);
Some(loaded)
} }
} }
+4 -4
View File
@@ -1,5 +1,5 @@
use serde_yaml_ng::{Mapping, Value}; use serde_yaml_ng::{Mapping, Value};
use tristr::alias::String; use smartstring::alias::String;
pub const HANDLE_FIELDS: [&str; 12] = [ pub const HANDLE_FIELDS: [&str; 12] = [
"mode", "mode",
@@ -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 { for (key, value) in config.iter() {
if let Some(key_str) = key.as_str() { if let Some(key_str) = key.as_str() {
lowercased.insert(lowercase_key(key_str), value); lowercased.insert(lowercase_key(key_str), value.clone());
} }
} }
lowercased lowercased
+3 -3
View File
@@ -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.clone(), config); let result = use_merge(&merge, 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.clone(), result); let result = use_merge(&cleared, 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"]);
+98 -141
View File
@@ -26,11 +26,9 @@ use anyhow::{Context as _, Result};
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde_yaml_ng::{Mapping, Value}; use serde_yaml_ng::{Mapping, Value};
use smartstring::alias::String;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::hash::{Hash as _, Hasher as _};
use std::sync::Arc;
use tokio::fs; use tokio::fs;
use tristr::alias::String;
type ResultLog = Vec<(String, String)>; type ResultLog = Vec<(String, String)>;
#[derive(Debug)] #[derive(Debug)]
@@ -52,13 +50,13 @@ struct ConfigValues {
#[derive(Debug)] #[derive(Debug)]
struct ProfileItems { struct ProfileItems {
config: Mapping, config: Mapping,
merge_item: Arc<ChainItem>, merge_item: ChainItem,
script_item: Arc<ChainItem>, script_item: ChainItem,
rules_item: Arc<ChainItem>, rules_item: ChainItem,
proxies_item: Arc<ChainItem>, proxies_item: ChainItem,
groups_item: Arc<ChainItem>, groups_item: ChainItem,
global_merge: Arc<ChainItem>, global_merge: ChainItem,
global_script: Arc<ChainItem>, global_script: ChainItem,
profile_name: String, profile_name: String,
} }
@@ -67,46 +65,41 @@ impl Default for ProfileItems {
Self { Self {
config: Default::default(), config: Default::default(),
profile_name: Default::default(), profile_name: Default::default(),
merge_item: Arc::new(ChainItem { merge_item: ChainItem {
uid: "".into(), uid: "".into(),
data: ChainType::Merge(Mapping::new()), data: ChainType::Merge(Mapping::new()),
}), },
script_item: Arc::new(ChainItem { script_item: ChainItem {
uid: "".into(), uid: "".into(),
data: ChainType::Script(tmpl::ITEM_SCRIPT.into()), data: ChainType::Script(tmpl::ITEM_SCRIPT.into()),
}), },
rules_item: Arc::new(ChainItem { rules_item: ChainItem {
uid: "".into(), uid: "".into(),
data: ChainType::Rules(SeqMap::default()), data: ChainType::Rules(SeqMap::default()),
}), },
proxies_item: Arc::new(ChainItem { proxies_item: ChainItem {
uid: "".into(), uid: "".into(),
data: ChainType::Proxies(SeqMap::default()), data: ChainType::Proxies(SeqMap::default()),
}), },
groups_item: Arc::new(ChainItem { groups_item: ChainItem {
uid: "".into(), uid: "".into(),
data: ChainType::Groups(SeqMap::default()), data: ChainType::Groups(SeqMap::default()),
}), },
global_merge: Arc::new(ChainItem { global_merge: ChainItem {
uid: "Merge".into(), uid: "Merge".into(),
data: ChainType::Merge(Mapping::new()), data: ChainType::Merge(Mapping::new()),
}), },
global_script: Arc::new(ChainItem { global_script: ChainItem {
uid: "Script".into(), uid: "Script".into(),
data: ChainType::Script(tmpl::ITEM_SCRIPT.into()), data: ChainType::Script(tmpl::ITEM_SCRIPT.into()),
}), },
} }
} }
} }
async fn chain_item_or_default( async fn chain_item_or_default(item: Option<&PrfItem>, default_item: impl FnOnce() -> ChainItem) -> ChainItem {
item: Option<&PrfItem>,
default_item: impl FnOnce() -> Arc<ChainItem>,
) -> Arc<ChainItem> {
if let Some(item) = item { if let Some(item) = item {
<Option<Arc<ChainItem>>>::from_async(item) <Option<ChainItem>>::from_async(item).await.unwrap_or_else(default_item)
.await
.unwrap_or_else(default_item)
} else { } else {
default_item() default_item()
} }
@@ -241,28 +234,28 @@ async fn process_override_items(
mut config: Mapping, mut config: Mapping,
mut exists_keys: Vec<String>, mut exists_keys: Vec<String>,
mut result_map: HashMap<String, ResultLog>, mut result_map: HashMap<String, ResultLog>,
merge_item: Arc<ChainItem>, merge_item: ChainItem,
script_item: Arc<ChainItem>, script_item: ChainItem,
profile_name: &str, profile_name: &String,
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.clone(), 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()
.map(discarded_note) .map(discarded_note)
.collect(); .collect();
if !notes.is_empty() { if !notes.is_empty() {
result_map.entry(merge_item.uid.clone()).or_default().extend(notes); result_map.entry(merge_item.uid).or_default().extend(notes);
} }
} }
if let ChainType::Script(script) = &script_item.data { if let ChainType::Script(script) = script_item.data {
let before = authoritative.current(&config); let before = authoritative.current(&config);
let (res_config, changed_keys, mut logs) = use_script(script.clone(), config, profile_name.into()).await; let (res_config, changed_keys, mut logs) = use_script(script, config, profile_name.clone()).await;
exists_keys.extend(changed_keys); exists_keys.extend(changed_keys);
config = res_config; config = res_config;
logs.extend( logs.extend(
@@ -271,7 +264,7 @@ async fn process_override_items(
.into_iter() .into_iter()
.map(discarded_note), .map(discarded_note),
); );
result_map.insert(script_item.uid.clone(), logs); result_map.insert(script_item.uid, logs);
} }
(config, exists_keys, result_map) (config, exists_keys, result_map)
@@ -279,20 +272,20 @@ async fn process_override_items(
fn process_seq_items( fn process_seq_items(
mut config: Mapping, mut config: Mapping,
rules_item: Arc<ChainItem>, rules_item: ChainItem,
proxies_item: Arc<ChainItem>, proxies_item: ChainItem,
groups_item: Arc<ChainItem>, groups_item: ChainItem,
) -> Mapping { ) -> Mapping {
if let ChainType::Rules(rules) = &rules_item.data { if let ChainType::Rules(rules) = rules_item.data {
config = use_seq(rules.clone(), config, "rules"); config = use_seq(rules, config, "rules");
} }
if let ChainType::Proxies(proxies) = &proxies_item.data { if let ChainType::Proxies(proxies) = proxies_item.data {
config = use_seq(proxies.clone(), config, "proxies"); config = use_seq(proxies, config, "proxies");
} }
if let ChainType::Groups(groups) = &groups_item.data { if let ChainType::Groups(groups) = groups_item.data {
config = use_seq(groups.clone(), config, "proxy-groups"); config = use_seq(groups, config, "proxy-groups");
} }
config config
@@ -327,45 +320,15 @@ 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, control_plane: snapshot_control_plane(config),
tun, tun: snapshot_tun(config, gui_tun_keys),
dns, dns: take_mapping(&mut dns_settings, "dns"),
hosts, hosts: dns_settings.remove("hosts"),
fingerprints,
} }
} }
@@ -383,50 +346,43 @@ impl AuthoritativeFields {
config config
} }
/// What `config` holds now, for diffing one override. /// The owned values as `config` holds them now, for diffing one override.
fn current(&self, config: &Mapping) -> FieldFingerprints { fn current(&self, config: &Mapping) -> Self {
let tun = config.get("tun").and_then(Value::as_mapping); let tun_keys: Vec<Value> = self.tun.keys().cloned().collect();
let dns = config.get("dns").and_then(Value::as_mapping); let dns = config.get("dns").and_then(Value::as_mapping);
FieldFingerprints { Self {
control_plane: CONTROL_PLANE_KEYS control_plane: snapshot_control_plane(config),
.iter() tun: snapshot_tun(config, &tun_keys),
.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()
.map(|key| fingerprint(dns.and_then(|map| map.get(key)))) .filter_map(|key| Some((key.clone(), dns?.get(key)?.clone())))
.collect(), .collect(),
hosts: self.hosts.as_ref().and_then(|_| fingerprint(config.get("hosts"))), hosts: self.hosts.as_ref().and_then(|_| config.get("hosts")).cloned(),
} }
} }
/// 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: &FieldFingerprints, after: &FieldFingerprints) -> Vec<String> { fn overridden(&self, before: &Self, after: &Self) -> Vec<String> {
let mut keys = Vec::new(); let mut keys = Vec::new();
for (index, &key) in CONTROL_PLANE_KEYS.iter().enumerate() { for &key in CONTROL_PLANE_KEYS {
if before.control_plane[index] != after.control_plane[index] if before.control_plane.get(key) != after.control_plane.get(key)
&& after.control_plane[index] != self.fingerprints.control_plane[index] && after.control_plane.get(key) != self.control_plane.get(key)
{ {
keys.push(key.into()); keys.push(key.into());
} }
} }
for (index, key) in self.tun.keys().enumerate() { for key in self.tun.keys() {
if before.tun[index] != after.tun[index] && after.tun[index] != self.fingerprints.tun[index] { if before.tun.get(key) != after.tun.get(key) && after.tun.get(key) != self.tun.get(key) {
keys.push(format!("tun.{}", key.as_str().unwrap_or_default()).into()); keys.push(format!("tun.{}", key.as_str().unwrap_or_default()).into());
} }
} }
for (index, key) in self.dns.keys().enumerate() { for key in self.dns.keys() {
if before.dns[index] != after.dns[index] && after.dns[index] != self.fingerprints.dns[index] { if before.dns.get(key) != after.dns.get(key) && after.dns.get(key) != self.dns.get(key) {
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.fingerprints.hosts { if self.hosts.is_some() && before.hosts != after.hosts && after.hosts != self.hosts {
keys.push("hosts".into()); keys.push("hosts".into());
} }
keys keys
@@ -597,15 +553,16 @@ 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") {
if let Value::Mapping(patch_tun) = value { let mut tun = config.get_mut("tun").map_or_else(Mapping::new, |val| {
let mut tun = take_mapping(&mut config, "tun"); val.as_mapping().cloned().unwrap_or_else(Mapping::new)
for (key, value) in patch_tun { });
let patch_tun = value.as_mapping().cloned().unwrap_or_else(Mapping::new);
for (key, value) in patch_tun.into_iter() {
if !value.is_null() { if !value.is_null() {
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");
@@ -660,7 +617,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);
} }
@@ -692,8 +649,11 @@ fn cleanup_proxy_groups(mut config: Mapping) -> Mapping {
.map_or_default(|seq| { .map_or_default(|seq| {
seq.iter() seq.iter()
.filter_map(|item| match item { .filter_map(|item| match item {
Value::Mapping(map) => map.get("name").and_then(Value::as_str).map(Into::into), Value::Mapping(map) => map
Value::String(name) => Some(name.as_str().into()), .get("name")
.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>>()
@@ -912,7 +872,7 @@ pub async fn enhance(
result_map, result_map,
global_merge, global_merge,
global_script, global_script,
profile_name.as_str(), &profile_name,
&authoritative, &authoritative,
) )
.await; .await;
@@ -923,12 +883,12 @@ pub async fn enhance(
result_map, result_map,
merge_item, merge_item,
script_item, script_item,
profile_name.as_str(), &profile_name,
&authoritative, &authoritative,
) )
.await; .await;
notify_discarded_keys(authoritative.overridden(&authoritative.fingerprints, &authoritative.current(&config))); notify_discarded_keys(authoritative.overridden(&authoritative, &authoritative.current(&config)));
let config = authoritative.enforce(config); let config = authoritative.enforce(config);
let config = ensure_tun_default_mtu(config); let config = ensure_tun_default_mtu(config);
let config = ensure_lan_bind_address(config); let config = ensure_lan_bind_address(config);
@@ -1403,7 +1363,6 @@ mod tests {
process_override_items, use_keys, process_override_items, use_keys,
}; };
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::Arc;
fn mapping(yaml: &str) -> serde_yaml_ng::Mapping { fn mapping(yaml: &str) -> serde_yaml_ng::Mapping {
serde_yaml_ng::from_str(yaml).expect("test config should be valid") serde_yaml_ng::from_str(yaml).expect("test config should be valid")
@@ -1444,23 +1403,21 @@ mod tests {
(profile.clone(), Mapping::new()) (profile.clone(), Mapping::new())
}; };
let authoritative = AuthoritativeFields::capture(&config, &[], dns_settings); let authoritative = AuthoritativeFields::capture(&config, &[], dns_settings);
let merge_item = |uid: &str| { let merge_item = |uid: &str| ChainItem {
Arc::new(ChainItem {
uid: uid.into(), uid: uid.into(),
data: ChainType::Merge(merge.clone()), data: ChainType::Merge(merge.clone()),
})
}; };
let profile_name = "test-profile"; let profile_name = "test-profile".into();
let (config, keys, logs) = process_override_items( let (config, keys, logs) = process_override_items(
config, config,
vec![], vec![],
HashMap::new(), HashMap::new(),
merge_item("global-merge"), merge_item("global-merge"),
Arc::new(ChainItem { ChainItem {
uid: "global-script".into(), uid: "global-script".into(),
data: ChainType::Script(script.into()), data: ChainType::Script(script.into()),
}), },
profile_name, &profile_name,
&authoritative, &authoritative,
) )
.await; .await;
@@ -1469,11 +1426,11 @@ mod tests {
keys, keys,
logs, logs,
merge_item("profile-merge"), merge_item("profile-merge"),
Arc::new(ChainItem { ChainItem {
uid: "profile-script".into(), uid: "profile-script".into(),
data: ChainType::Script(script.into()), data: ChainType::Script(script.into()),
}), },
profile_name, &profile_name,
&authoritative, &authoritative,
) )
.await; .await;
@@ -1509,15 +1466,15 @@ mod tests {
let exists_keys = use_keys(&config).collect(); let exists_keys = use_keys(&config).collect();
config.insert("application-only".into(), true.into()); config.insert("application-only".into(), true.into());
let global_merge = Arc::new(ChainItem { let global_merge = ChainItem {
uid: "Merge".into(), uid: "Merge".into(),
data: ChainType::Merge(mapping( data: ChainType::Merge(mapping(
r"{global-merge-wins: global-merge, global-script-wins: global-merge, r"{global-merge-wins: global-merge, global-script-wins: global-merge,
profile-merge-wins: global-merge, profile-script-wins: global-merge, profile-merge-wins: global-merge, profile-script-wins: global-merge,
nested: {winner: global-merge}, dns: {enable: false}, tun: {enable: false}}", nested: {winner: global-merge}, dns: {enable: false}, tun: {enable: false}}",
)), )),
}); };
let global_script = Arc::new(ChainItem { let global_script = ChainItem {
uid: "Script".into(), uid: "Script".into(),
data: ChainType::Script( data: ChainType::Script(
r#"function main(config) { r#"function main(config) {
@@ -1529,15 +1486,15 @@ mod tests {
}"# }"#
.into(), .into(),
), ),
}); };
let profile_merge = Arc::new(ChainItem { let profile_merge = ChainItem {
uid: "profile-merge".into(), uid: "profile-merge".into(),
data: ChainType::Merge(mapping( data: ChainType::Merge(mapping(
r"{profile-merge-wins: profile-merge, profile-script-wins: profile-merge, r"{profile-merge-wins: profile-merge, profile-script-wins: profile-merge,
nested: {winner: profile-merge}}", nested: {winner: profile-merge}}",
)), )),
}); };
let profile_script = Arc::new(ChainItem { let profile_script = ChainItem {
uid: "profile-script".into(), uid: "profile-script".into(),
data: ChainType::Script( data: ChainType::Script(
r#"function main(config) { r#"function main(config) {
@@ -1547,9 +1504,9 @@ mod tests {
}"# }"#
.into(), .into(),
), ),
}); };
let profile_name = "test-profile"; let profile_name = "test-profile".into();
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,
@@ -1557,7 +1514,7 @@ mod tests {
HashMap::new(), HashMap::new(),
global_merge, global_merge,
global_script, global_script,
profile_name, &profile_name,
&authoritative, &authoritative,
) )
.await; .await;
@@ -1567,7 +1524,7 @@ mod tests {
result_map, result_map,
profile_merge, profile_merge,
profile_script, profile_script,
profile_name, &profile_name,
&authoritative, &authoritative,
) )
.await; .await;
+47 -78
View File
@@ -1,13 +1,13 @@
use crate::{process::AsyncHandler, utils::tmpl}; use crate::{process::AsyncHandler, utils::tmpl};
use super::field::use_lowercase; use super::field::use_lowercase;
use anyhow::Result; use anyhow::{Error, 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;
use serde_yaml_ng::Mapping; use serde_yaml_ng::Mapping;
use smartstring::alias::String;
use std::sync::Arc; use std::sync::Arc;
use tristr::alias::String;
const MAX_OUTPUTS: usize = 1000; const MAX_OUTPUTS: usize = 1000;
const MAX_OUTPUT_SIZE: usize = 1024 * 1024; // 1MB const MAX_OUTPUT_SIZE: usize = 1024 * 1024; // 1MB
@@ -22,27 +22,15 @@ 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_value(&config) { let json = match serde_json::to_string(&use_lowercase(&config)) {
Ok(mut json) => { Ok(json) if json.len() <= MAX_JSON_SIZE => json,
if let Some(map) = json.as_object_mut() { Ok(_) => {
let mut lowered = serde_json::Map::with_capacity(map.len());
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"; let message = "Configuration size exceeds maximum allowed size";
return (config, vec![], vec![("exception".into(), message.into())]); 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())]),
}; };
@@ -78,7 +66,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: &serde_json::Value, name: &String) -> EvalOutcome { fn eval_script(script: &str, config_json: &str, name: &String) -> EvalOutcome {
let mut context = Context::default(); let mut context = Context::default();
context context
@@ -143,11 +131,12 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
});"#, });"#,
)); ));
let config_value = match JsValue::from_json(config_json, &mut context) { // Bind the JSON instead of embedding it in program source; Boa's parser never chews it.
Ok(value) => value, if let Err(err) = context.register_global_property(
Err(err) => return bail(format!("failed to bind config for script: {err}")), js_string!("__verge_config__"),
}; JsValue::from(JsString::from(config_json)),
if let Err(err) = context.register_global_property(js_string!("__verge_config__"), config_value, Attribute::all()) { Attribute::all(),
) {
return bail(format!("failed to bind config for script: {err}")); return bail(format!("failed to bind config for script: {err}"));
} }
@@ -160,61 +149,31 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
let code = format!( let code = format!(
r"try{{ r"try{{
{script}; {script};
main(globalThis.__verge_config__,'{safe_name}') JSON.stringify(main(JSON.parse(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(err) => { Err(e) => return bail(format!("Failed to convert JS result to string: {e}")),
logging!(
error,
Type::Config,
"Script execution error: {err}. Script name: {name}"
);
return bail("Script execution failed".to_owned());
}
}; };
// The JS wrapper funnels exceptions into a marker string; surface its text. let result = match result.to_std_string() {
if result.is_string() { Ok(result) => result,
let text = result Err(_) => return bail("Failed to convert JS string to std string".to_owned()),
.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 serde_json::from_value::<Mapping>(result) { match parse_json_safely(&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,
@@ -226,17 +185,27 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
} }
} }
/// Serialized-size estimate without building the serialized string; a DoS guard, not an exact byte count. fn parse_json_safely(json_str: &str) -> Result<Mapping, Error> {
fn json_approx_size(value: &serde_json::Value) -> usize { if json_str.len() > MAX_JSON_SIZE {
match value { anyhow::bail!("JSON string too large");
serde_json::Value::String(s) => s.len() + 2, }
serde_json::Value::Object(map) => map
.iter() let json_str = strip_outer_quotes(json_str);
.map(|(key, value)| key.len() + 4 + json_approx_size(value)) Ok(serde_json::from_str::<Mapping>(json_str)?)
.sum(), }
serde_json::Value::Array(items) => items.iter().map(json_approx_size).sum(),
serde_json::Value::Number(n) => n.to_string().len(), // 安全地移除外层引号
serde_json::Value::Bool(_) | serde_json::Value::Null => 4, fn strip_outer_quotes(s: &str) -> &str {
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
} }
} }
+10 -2
View File
@@ -8,10 +8,18 @@ macro_rules! revise {
} }
pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping { pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
let mut tun_val = super::take_mapping(&mut config, "tun"); let tun_key = Value::from("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 mut dns_val = super::take_mapping(&mut config, "dns"); let dns_key = Value::from("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);
+6 -3
View File
@@ -12,14 +12,17 @@ use chrono::Utc;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use reqwest_dav::list_cmd::ListFile; use reqwest_dav::list_cmd::ListFile;
use serde::Serialize; use serde::Serialize;
use smartstring::alias::String;
use std::path::PathBuf; use std::path::PathBuf;
use tokio::fs; use tokio::fs;
use tristr::alias::String;
#[derive(Debug, Serialize, specta::Type)] #[derive(Debug, Serialize, specta::Type)]
pub struct LocalBackupFile { pub struct LocalBackupFile {
#[specta(type = std::string::String)]
pub filename: String, pub filename: String,
#[specta(type = std::string::String)]
pub path: String, pub path: String,
#[specta(type = std::string::String)]
pub last_modified: String, pub last_modified: String,
pub content_length: u64, pub content_length: u64,
} }
@@ -120,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.clone(); let name = filename.to_string();
backup::WebDavClient::global().delete(filename).await.map_err(|err| { backup::WebDavClient::global().delete(filename).await.map_err(|err| {
logging!( logging!(
error, error,
@@ -162,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.clone(); let name = filename.to_string();
backup::WebDavClient::global() backup::WebDavClient::global()
.download(filename, backup_storage_path.clone()) .download(filename, backup_storage_path.clone())
.await .await
+1 -1
View File
@@ -10,8 +10,8 @@ use crate::{
use bytes::BytesMut; use bytes::BytesMut;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use serde_yaml_ng::{Mapping, Value}; use serde_yaml_ng::{Mapping, Value};
use smartstring::alias::String;
use std::sync::{Arc, LazyLock}; use std::sync::{Arc, LazyLock};
use tristr::alias::String;
#[allow(clippy::expect_used)] #[allow(clippy::expect_used)]
static TLS_CONFIG: LazyLock<Arc<rustls::ClientConfig>> = static TLS_CONFIG: LazyLock<Arc<rustls::ClientConfig>> =
+5 -2
View File
@@ -2,7 +2,7 @@ use crate::core::notify::{Refresh, announce};
use anyhow::{Result, ensure}; use anyhow::{Result, ensure};
use clash_verge_draft::DraftTransaction; use clash_verge_draft::DraftTransaction;
use serde::Serialize; use serde::Serialize;
use tristr::alias::String; use smartstring::alias::String;
use crate::{ use crate::{
config::{ config::{
@@ -19,7 +19,10 @@ use crate::{
#[serde(tag = "status", rename_all = "snake_case")] #[serde(tag = "status", rename_all = "snake_case")]
pub enum DnsOverrideOutcome { pub enum DnsOverrideOutcome {
Applied, Applied,
ConfirmationRequired { source: String }, ConfirmationRequired {
#[specta(type = std::string::String)]
source: String,
},
} }
pub async fn set_dns_override( pub async fn set_dns_override(
-1
View File
@@ -90,7 +90,6 @@ verge_registry! {
enable_global_hotkey => NoEffect; enable_global_hotkey => NoEffect;
home_cards => NoEffect; home_cards => NoEffect;
auto_close_connection => NoEffect; auto_close_connection => NoEffect;
auto_switch_selector_group => NoEffect;
auto_check_update => NoEffect; auto_check_update => NoEffect;
default_latency_test => NoEffect; default_latency_test => NoEffect;
default_latency_timeout => NoEffect; default_latency_timeout => NoEffect;
+4 -1
View File
@@ -3,15 +3,18 @@ use crate::{
utils::dirs::{self, PathBufExec as _}, utils::dirs::{self, PathBufExec as _},
}; };
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use smartstring::alias::String;
use std::path::{Component, Path, PathBuf}; use std::path::{Component, Path, PathBuf};
use tokio::fs; use tokio::fs;
use tokio::io::AsyncWriteExt as _; use tokio::io::AsyncWriteExt as _;
use tristr::alias::String;
#[derive(Debug, serde::Serialize, serde::Deserialize, specta::Type)] #[derive(Debug, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct IconInfo { pub struct IconInfo {
#[specta(type = std::string::String)]
name: String, name: String,
#[specta(type = std::string::String)]
previous_t: String, previous_t: String,
#[specta(type = std::string::String)]
current_t: String, current_t: String,
} }
+10 -124
View File
@@ -9,8 +9,7 @@ use crate::{
}; };
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use tauri_plugin_mihomo::models::ProxyType; use smartstring::alias::String;
use tristr::alias::String;
/// Toggle proxy profile /// Toggle proxy profile
pub async fn toggle_proxy_profile(profile_index: String) { pub async fn toggle_proxy_profile(profile_index: String) {
@@ -23,80 +22,9 @@ pub async fn toggle_proxy_profile(profile_index: String) {
} }
} }
/// First `select` group in config order that lists `group_name`, when that group is `url-test` or `fallback`.
fn parent_selector<'a>(groups: &'a [serde_yaml_ng::Value], group_name: &str) -> Option<&'a str> {
let field = |group: &'a serde_yaml_ng::Value, key: &str| group.get(key)?.as_str();
let group = groups.iter().find(|group| field(group, "name") == Some(group_name))?;
if !matches!(field(group, "type"), Some("url-test" | "fallback")) {
return None;
}
groups
.iter()
.filter(|group| field(group, "type") == Some("select"))
.filter(|group| {
group
.get("proxies")
.and_then(|members| members.as_sequence())
.is_some_and(|members| members.iter().any(|member| member.as_str() == Some(group_name)))
})
.filter_map(|group| field(group, "name"))
.find(|name| *name != "GLOBAL")
}
/// Rule traffic enters through `select` groups, so a pick inside a `url-test`/`fallback` group only
/// carries traffic once the first `select` group listing that group points at it.
/// Returns the node that group left.
async fn follow_group_selection(group_name: &str) -> Option<std::string::String> {
if !Config::verge()
.await
.data_arc()
.auto_switch_selector_group
.unwrap_or(true)
{
return None;
}
if Config::clash()
.await
.data_arc()
.get_mode()
.is_some_and(|mode| mode != "rule")
{
return None;
}
let selector = {
let runtime = Config::runtime().await.latest_arc();
let groups = runtime.config.as_ref()?.get("proxy-groups")?.as_sequence()?;
parent_selector(groups, group_name)?.to_owned()
};
let mihomo = handle::Handle::mihomo();
let current = mihomo.get_proxy_by_name(&selector).await.ok()?;
// The runtime config can lag the core, which alone knows what this group is now.
if current.proxy_type != ProxyType::Selector {
return None;
}
let previous = current.now?;
if previous == group_name {
return None;
}
if let Err(err) = mihomo.select_node_for_group(&selector, group_name).await {
logging!(warn, Type::Core, "Failed to point {selector} at {group_name}: {err:#}");
return None;
}
if let Err(error) = crate::config::profiles::record_selected_node(&selector, group_name).await {
logging!(
warn,
Type::Config,
"Failed to persist proxy selection for {selector}: {error:#}"
);
}
Some(previous)
}
pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool) -> Result<()> { pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool) -> Result<()> {
let mihomo = handle::Handle::mihomo(); let mihomo = handle::Handle::mihomo();
let auto_close = Config::verge().await.data_arc().auto_close_connection.unwrap_or(false); let previous_proxy = if Config::verge().await.data_arc().auto_close_connection.unwrap_or(false) {
let previous_proxy = if auto_close {
match mihomo.get_proxy_by_name(group_name).await { match mihomo.get_proxy_by_name(group_name).await {
Ok(group) => group.now.filter(|name| !name.is_empty()), Ok(group) => group.now.filter(|name| !name.is_empty()),
Err(err) => { Err(err) => {
@@ -130,31 +58,9 @@ pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool)
"Failed to persist proxy selection for {group_name}: {error:#}" "Failed to persist proxy selection for {group_name}: {error:#}"
); );
} }
let mut stale_proxies: Vec<_> = previous_proxy.into_iter().collect();
if !unfix
&& let Some(left) = follow_group_selection(group_name).await
&& auto_close
{
stale_proxies.push(left);
}
finish_proxy_switch(stale_proxies).await;
Ok(())
}
/// Lets a `url-test`/`fallback` group carry rule traffic without fixing a node in it.
pub async fn follow_proxy_group(group_name: &str) {
let Some(left) = follow_group_selection(group_name).await else {
return;
};
let auto_close = Config::verge().await.data_arc().auto_close_connection.unwrap_or(false);
finish_proxy_switch(auto_close.then_some(left).into_iter().collect()).await;
}
async fn finish_proxy_switch(stale_proxies: Vec<std::string::String>) {
let mihomo = handle::Handle::mihomo();
announce(Refresh::Proxies); announce(Refresh::Proxies);
if !stale_proxies.is_empty() { if let Some(previous_proxy) = previous_proxy {
AsyncHandler::spawn(move || async move { AsyncHandler::spawn(move || async move {
let connections = match mihomo.get_connections().await { let connections = match mihomo.get_connections().await {
Ok(connections) => connections, Ok(connections) => connections,
@@ -172,7 +78,7 @@ async fn finish_proxy_switch(stale_proxies: Vec<std::string::String>) {
.connections .connections
.unwrap_or_default() .unwrap_or_default()
.into_iter() .into_iter()
.filter(|connection| stale_proxies.iter().any(|proxy| connection.chains.contains(proxy))) .filter(|connection| connection.chains.contains(&previous_proxy))
.map(|connection| async move { .map(|connection| async move {
if let Err(err) = mihomo.close_connection(&connection.id).await { if let Err(err) = mihomo.close_connection(&connection.id).await {
logging!( logging!(
@@ -194,9 +100,10 @@ async fn finish_proxy_switch(stale_proxies: Vec<std::string::String>) {
"Failed to refresh tray after switching proxy: {err:#}" "Failed to refresh tray after switching proxy: {err:#}"
); );
} }
Ok(())
} }
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> { async fn should_update_profile(uid: &String, 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)?;
@@ -231,8 +138,8 @@ async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Op
#[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: &str, uid: &String,
url: &str, url: &String,
opt: Option<&PrfOption>, opt: Option<&PrfOption>,
option: Option<&PrfOption>, option: Option<&PrfOption>,
is_mannual_trigger: bool, is_mannual_trigger: bool,
@@ -327,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: &str, option: Option<&PrfOption>, is_mannual_trigger: bool) -> Result<()> { pub async fn update_profile(uid: &String, 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 {
@@ -338,7 +245,7 @@ pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_mannual_tr
None => false, None => false,
}; };
let profiles = Config::profiles().await; let profiles = Config::profiles().await;
let is_current = profiles.latest_arc().current.as_deref() == Some(uid); let is_current = profiles.latest_arc().current.as_ref() == 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 {
@@ -373,24 +280,3 @@ pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_mannual_tr
pub async fn enhance_profiles() -> Result<ValidationOutcome> { pub async fn enhance_profiles() -> Result<ValidationOutcome> {
CoreManager::global().update_config_forced().await CoreManager::global().update_config_forced().await
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_first_select_group_follows_an_auto_group() -> Result<()> {
let groups: Vec<serde_yaml_ng::Value> = serde_yaml_ng::from_str(
"
- { name: GLOBAL, type: select, proxies: [Auto, Proxy, Direct] }
- { name: Auto, type: url-test, proxies: [Node] }
- { name: Proxy, type: select, proxies: [Auto, Node] }
- { name: Direct, type: select, proxies: [DIRECT, Auto] }
",
)?;
assert_eq!(parent_selector(&groups, "Auto"), Some("Proxy"));
assert_eq!(parent_selector(&groups, "Proxy"), None);
Ok(())
}
}
-1
View File
@@ -47,7 +47,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
cmd::copy_clash_env, cmd::copy_clash_env,
cmd::record_selected_node, cmd::record_selected_node,
cmd::switch_proxy_node, cmd::switch_proxy_node,
cmd::follow_proxy_group,
cmd::save_dns_config, cmd::save_dns_config,
cmd::apply_dns_config, cmd::apply_dns_config,
cmd::set_dns_override, cmd::set_dns_override,
+9 -21
View File
@@ -137,11 +137,16 @@ 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?;
save_yaml_str(path, &data_str, prefix).await let yaml_str = match prefix {
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, prefix: Option<&str>) -> Result<()> { pub async fn save_yaml_str(path: &Path, yaml_str: &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()
@@ -167,16 +172,9 @@ pub async fn save_yaml_str(path: &Path, yaml_str: &str, prefix: Option<&str>) ->
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);
async fn write_chunk(file: &mut tokio::fs::File, bytes: &[u8], path: &Path) -> Result<()> { file.write_all(yaml_str.as_bytes())
file.write_all(bytes)
.await .await
.with_context(|| format!("failed to write temporary file for \"{}\"", path.display())) .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()))?;
@@ -222,16 +220,6 @@ 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('?') {
+1 -1
View File
@@ -5,10 +5,10 @@ use reqwest::{
Client, Proxy, StatusCode, Client, Proxy, StatusCode,
header::{HeaderMap, HeaderValue, USER_AGENT}, header::{HeaderMap, HeaderValue, USER_AGENT},
}; };
use smartstring::alias::String;
use std::{sync::Arc, time::Duration}; use std::{sync::Arc, time::Duration};
use sysproxy::Sysproxy; use sysproxy::Sysproxy;
use tauri::Url; use tauri::Url;
use tristr::alias::String;
#[derive(Debug)] #[derive(Debug)]
pub struct HttpResponse { pub struct HttpResponse {
+4 -4
View File
@@ -1,8 +1,8 @@
use crate::core::notify::NoticeStatus; use crate::core::notify::NoticeStatus;
use anyhow::Result; use anyhow::Result;
use percent_encoding::percent_decode_str; use percent_encoding::percent_decode_str;
use smartstring::alias::String;
use tauri::Url; use tauri::Url;
use tristr::alias::String;
use crate::{ use crate::{
config::{Config, PrfItem, profiles}, config::{Config, PrfItem, profiles},
@@ -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()); .map(|(_, value)| value.into_owned().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: &str, had_current_profile: bool) { async fn post_import_updates(uid: &String, 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: &str, had_current_profile: bool) {
false false
} else { } else {
let profiles = Config::profiles().await; let profiles = Config::profiles().await;
profiles.latest_arc().current.as_deref() == Some(uid) profiles.latest_arc().current.as_ref() == Some(uid)
}; };
if should_update_core { if should_update_core {
+108 -7
View File
@@ -5,10 +5,24 @@ import { useCallback, useImperativeHandle, useState, type Ref } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { closeConnection } from 'tauri-plugin-mihomo-api' import { closeConnection } from 'tauri-plugin-mihomo-api'
import { useProfiles } from '@/hooks/use-profiles'
import parseTraffic from '@/utils/parse-traffic' import parseTraffic from '@/utils/parse-traffic'
import {
getConnectionRuleTargets,
type ConnectionRuleKind,
} from './connection-rule'
import {
ConnectionRuleDialog,
type ConnectionRuleTarget,
} from './connection-rule-dialog'
export interface ConnectionDetailRef { export interface ConnectionDetailRef {
open: (detail: IConnectionsItem, closed: boolean) => void open: (
detail: IConnectionsItem,
closed: boolean,
preferredKind?: ConnectionRuleKind,
) => void
close: () => void close: () => void
} }
@@ -16,7 +30,12 @@ export function ConnectionDetail({ ref }: { ref?: Ref<ConnectionDetailRef> }) {
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
const [detail, setDetail] = useState<IConnectionsItem | null>(null) const [detail, setDetail] = useState<IConnectionsItem | null>(null)
const [closed, setClosed] = useState(false) const [closed, setClosed] = useState(false)
const [preferredKind, setPreferredKind] =
useState<ConnectionRuleKind>('domain')
const theme = useTheme() const theme = useTheme()
const [ruleTarget, setRuleTarget] = useState<ConnectionRuleTarget | null>(
null,
)
const onClose = useCallback(() => { const onClose = useCallback(() => {
setOpen(false) setOpen(false)
@@ -25,51 +44,90 @@ export function ConnectionDetail({ ref }: { ref?: Ref<ConnectionDetailRef> }) {
}, []) }, [])
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
open: (detail: IConnectionsItem, closed: boolean) => { open: (
detail: IConnectionsItem,
closed: boolean,
preferredKind = 'domain',
) => {
if (open) return if (open) return
setOpen(true) setOpen(true)
setDetail(detail) setDetail(detail)
setClosed(closed) setClosed(closed)
setPreferredKind(preferredKind)
}, },
close: onClose, close: onClose,
})) }))
return ( return (
<>
<Snackbar <Snackbar
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
open={open} open={open}
onClose={onClose} onClose={onClose}
sx={{ sx={{
'.MuiSnackbarContent-root': { '.MuiSnackbarContent-root': {
maxWidth: '520px', width: '520px',
maxWidth: 'calc(100vw - 32px)',
boxSizing: 'border-box',
maxHeight: '480px', maxHeight: '480px',
overflowY: 'auto', overflowY: 'auto',
backgroundColor: theme.palette.background.paper, backgroundColor: theme.palette.background.paper,
color: theme.palette.text.primary, color: theme.palette.text.primary,
}, },
'.MuiSnackbarContent-message': { width: '100%', minWidth: 0 },
}} }}
message={ message={
detail ? ( detail ? (
<InnerConnectionDetail <InnerConnectionDetail
data={detail} data={detail}
closed={closed} closed={closed}
preferredKind={preferredKind}
onClose={onClose} onClose={onClose}
onAddRule={(target) => {
setRuleTarget(target)
onClose()
}}
/> />
) : null ) : null
} }
/> />
{ruleTarget && (
<ConnectionRuleDialog
target={ruleTarget}
onClose={() => setRuleTarget(null)}
/>
)}
</>
) )
} }
interface InnerProps { interface InnerProps {
data: IConnectionsItem data: IConnectionsItem
closed: boolean closed: boolean
preferredKind: ConnectionRuleKind
onClose?: () => void onClose?: () => void
onAddRule: (target: ConnectionRuleTarget) => void
} }
const InnerConnectionDetail = ({ data, closed, onClose }: InnerProps) => { const InnerConnectionDetail = ({
data,
closed,
preferredKind,
onClose,
onAddRule,
}: InnerProps) => {
const { t } = useTranslation() const { t } = useTranslation()
const { current } = useProfiles()
const { metadata, rulePayload } = data const { metadata, rulePayload } = data
const targets = getConnectionRuleTargets(metadata)
const canAddRule = Boolean(
current?.uid &&
current.option?.rules &&
(targets.domain ||
targets.process ||
targets.source ||
targets.destination),
)
const theme = useTheme() const theme = useTheme()
const chains = [...data.chains].reverse().join(' / ') const chains = [...data.chains].reverse().join(' / ')
const rule = rulePayload ? `${data.rule}(${rulePayload})` : data.rule const rule = rulePayload ? `${data.rule}(${rulePayload})` : data.rule
@@ -105,7 +163,7 @@ const InnerConnectionDetail = ({ data, closed, onClose }: InnerProps) => {
{ label: t('connections.components.fields.rule'), value: rule }, { label: t('connections.components.fields.rule'), value: rule },
{ {
label: t('connections.components.fields.process'), label: t('connections.components.fields.process'),
value: `${metadata.process}${metadata.processPath ? `(${metadata.processPath})` : ''}`, value: `${metadata.process ?? ''}${metadata.processPath ? `(${metadata.processPath})` : ''}`,
}, },
{ {
label: t('connections.components.fields.time'), label: t('connections.components.fields.time'),
@@ -132,7 +190,14 @@ const InnerConnectionDetail = ({ data, closed, onClose }: InnerProps) => {
const onDelete = useLockFn(async () => closeConnection(data.id)) const onDelete = useLockFn(async () => closeConnection(data.id))
return ( return (
<Box sx={{ userSelect: 'text', color: theme.palette.text.secondary }}> <Box
sx={{
width: '100%',
minWidth: 0,
userSelect: 'text',
color: theme.palette.text.secondary,
}}
>
{information.map((each) => ( {information.map((each) => (
<div key={each.label}> <div key={each.label}>
<b>{each.label}</b> <b>{each.label}</b>
@@ -147,8 +212,32 @@ const InnerConnectionDetail = ({ data, closed, onClose }: InnerProps) => {
</div> </div>
))} ))}
<Box
sx={{
display: 'flex',
justifyContent: 'flex-end',
gap: 1,
flexWrap: 'wrap',
mt: 1,
}}
>
<Button
variant="outlined"
disabled={!canAddRule}
onClick={() => {
if (!current?.uid || !current.option?.rules) return
onAddRule({
metadata: { ...metadata },
profileUid: current.uid,
profileName: current.name || current.uid,
rulesUid: current.option.rules,
preferredKind,
})
}}
>
{t('connections.ruleDialog.entry')}
</Button>
{!closed && ( {!closed && (
<Box sx={{ textAlign: 'right' }}>
<Button <Button
variant="contained" variant="contained"
title={t('connections.components.actions.closeConnection')} title={t('connections.components.actions.closeConnection')}
@@ -159,6 +248,18 @@ const InnerConnectionDetail = ({ data, closed, onClose }: InnerProps) => {
> >
{t('connections.components.actions.closeConnection')} {t('connections.components.actions.closeConnection')}
</Button> </Button>
)}
</Box>
{!canAddRule && (
<Box sx={{ mt: 1, typography: 'caption' }}>
{t(
targets.domain ||
targets.process ||
targets.source ||
targets.destination
? 'connections.ruleDialog.noProfile'
: 'connections.ruleDialog.noMetadata',
)}
</Box> </Box>
)} )}
</Box> </Box>
@@ -8,7 +8,7 @@ let timerId: number | null = null
const listeners = new Set<RelativeTimeListener>() const listeners = new Set<RelativeTimeListener>()
const startTimer = () => { const startTimer = () => {
if (timerId !== null || document.hidden || listeners.size === 0) return if (timerId !== null) return
currentTime = Date.now() currentTime = Date.now()
timerId = window.setInterval(() => { timerId = window.setInterval(() => {
@@ -18,34 +18,19 @@ const startTimer = () => {
} }
const stopTimer = () => { const stopTimer = () => {
if (timerId === null) return if (listeners.size > 0 || timerId === null) return
window.clearInterval(timerId) window.clearInterval(timerId)
timerId = null timerId = null
} }
const handleVisibilityChange = () => {
if (document.hidden) {
stopTimer()
} else {
startTimer()
listeners.forEach((listener) => listener())
}
}
const subscribeRelativeTime = (listener: RelativeTimeListener) => { const subscribeRelativeTime = (listener: RelativeTimeListener) => {
listeners.add(listener) listeners.add(listener)
if (listeners.size === 1) {
document.addEventListener('visibilitychange', handleVisibilityChange)
}
startTimer() startTimer()
return () => { return () => {
listeners.delete(listener) listeners.delete(listener)
if (listeners.size === 0) {
stopTimer() stopTimer()
document.removeEventListener('visibilitychange', handleVisibilityChange)
}
} }
} }
@@ -7,11 +7,12 @@ import { closeConnection } from 'tauri-plugin-mihomo-api'
import { RelativeTime } from './connection-relative-time' import { RelativeTime } from './connection-relative-time'
import type { ConnectionRowView } from './connection-row-view' import type { ConnectionRowView } from './connection-row-view'
import type { ConnectionRuleKind } from './connection-rule'
interface Props { interface Props {
row: ConnectionRowView row: ConnectionRowView
closed: boolean closed: boolean
onShowDetail: (id: string) => void onShowDetail: (id: string, preferredKind?: ConnectionRuleKind) => void
} }
const tagStyle = { const tagStyle = {
@@ -86,7 +87,17 @@ export const ConnectionRowItem = memo(
<div style={tagsStyle}> <div style={tagsStyle}>
<span style={tagStyle}>{row.network}</span> <span style={tagStyle}>{row.network}</span>
<span style={tagStyle}>{row.type}</span> <span style={tagStyle}>{row.type}</span>
{row.process && <span style={tagStyle}>{row.process}</span>} {row.process && (
<span
style={tagStyle}
onClick={(event) => {
event.stopPropagation()
onShowDetail(row.id, 'process')
}}
>
{row.process}
</span>
)}
{row.chains && <span style={tagStyle}>{row.chains}</span>} {row.chains && <span style={tagStyle}>{row.chains}</span>}
<span style={tagStyle}> <span style={tagStyle}>
<RelativeTime start={row.time} /> <RelativeTime start={row.time} />
@@ -0,0 +1,525 @@
import {
Alert,
Autocomplete,
Box,
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
FormControlLabel,
MenuItem,
Radio,
RadioGroup,
TextField,
Typography,
} from '@mui/material'
import { useLockFn } from 'ahooks'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
useClashConfigData,
useProxiesData,
} from '@/providers/app-data-context'
import { getProfiles, readProfileFile, saveProfileFile } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import {
getConnectionIPRule,
getConnectionRuleTargets,
getConnectionRules,
getConnectionRootDomain,
isConnectionRuleDomain,
findConnectionRule,
saveConnectionRule,
type ConnectionRuleKind,
} from './connection-rule'
export interface ConnectionRuleTarget {
metadata: IConnectionsItem['metadata']
profileUid: string
profileName: string
rulesUid: string
preferredKind: ConnectionRuleKind
}
type DomainScope = 'DOMAIN' | 'DOMAIN-SUFFIX' | 'ROOT-DOMAIN'
function getInitialKind(target: ConnectionRuleTarget) {
const targets = getConnectionRuleTargets(target.metadata)
return targets[target.preferredKind]
? target.preferredKind
: ((['domain', 'process', 'source', 'destination'] as const).find(
(kind) => targets[kind],
) ?? 'domain')
}
export function ConnectionRuleDialog({
target,
onClose,
}: {
target: ConnectionRuleTarget
onClose: () => void
}) {
const { t } = useTranslation()
const { proxyView } = useProxiesData()
const { clashConfig } = useClashConfigData()
const targets = getConnectionRuleTargets(target.metadata)
const [rootDomain, setRootDomain] = useState<string>()
const [kind, setKind] = useState<ConnectionRuleKind>(() =>
getInitialKind(target),
)
const [policy, setPolicy] = useState<string | null>(null)
const [scope, setScope] = useState<DomainScope>('DOMAIN')
const [matchingInput, setMatchingInput] = useState(
() => targets[getInitialKind(target)]?.value ?? '',
)
const [rules, setRules] = useState<string[] | null>(null)
const [loadAttempt, setLoadAttempt] = useState(0)
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
const selected = targets[kind]
const matchingRoot = kind === 'domain' && scope === 'ROOT-DOMAIN'
const editingDomain = kind === 'domain' && scope === 'DOMAIN-SUFFIX'
const editingIP = kind === 'source' || kind === 'destination'
const matchingValue = matchingRoot
? (rootDomain ?? '')
: editingDomain || editingIP
? matchingInput
: (selected?.value ?? '')
const invalidDomain =
editingDomain &&
!isConnectionRuleDomain(matchingInput, targets.domain?.value ?? '')
const ipRule = editingIP
? getConnectionIPRule(matchingInput, kind === 'source')
: undefined
const invalidIP = editingIP && !ipRule
const invalidValue = invalidDomain || invalidIP
const condition = editingIP
? ipRule
: selected
? {
type:
kind === 'domain' && scope !== 'DOMAIN'
? 'DOMAIN-SUFFIX'
: selected.type,
value: kind === 'domain' ? matchingValue.trim() : selected.value,
}
: undefined
const existing =
rules && condition && !invalidValue
? findConnectionRule(rules, condition)
: undefined
const modifying = Boolean(existing)
const groups = proxyView
? proxyView.groups.length || !proxyView.global
? proxyView.groups
: [proxyView.global]
: []
const policies = [
...new Set(['DIRECT', 'REJECT', ...groups.map((group) => group.name)]),
]
const kindLabels = {
domain: t('connections.ruleDialog.domain'),
process: t('connections.components.fields.process'),
source: t('connections.ruleDialog.sourceIp'),
destination: t('connections.ruleDialog.destinationIp'),
}
const unavailablePolicy = Boolean(policy && !policies.includes(policy))
const blocked = loading || saving || rules === null
useEffect(() => {
let cancelled = false
const ruleTargets = getConnectionRuleTargets(target.metadata)
Promise.all([
readProfileFile(target.rulesUid),
ruleTargets.domain
? getConnectionRootDomain(ruleTargets.domain.value)
: undefined,
])
.then(([content, root]) => {
const loadedRules = getConnectionRules(content)
const initialKind = getInitialKind(target)
const selectedTarget = ruleTargets[initialKind]
const initial = selectedTarget
? (findConnectionRule(loadedRules, selectedTarget) ??
(initialKind === 'domain'
? findConnectionRule(loadedRules, {
...selectedTarget,
type: 'DOMAIN-SUFFIX',
})
: undefined))
: undefined
if (cancelled) return
setRootDomain(root)
setRules(loadedRules)
setPolicy(initial?.policy ?? null)
setScope(initial?.type === 'DOMAIN-SUFFIX' ? 'DOMAIN-SUFFIX' : 'DOMAIN')
})
.catch((err: unknown) => {
if (!cancelled)
setError(err instanceof Error ? err.message : String(err))
})
.finally(() => {
if (!cancelled) setLoading(false)
})
return () => {
cancelled = true
}
}, [target, loadAttempt])
const handleSave = useLockFn(async () => {
if (
blocked ||
!condition ||
invalidValue ||
!policy ||
!policies.includes(policy)
)
return
if (/[\r\n,]/u.test(condition.value) || /[\r\n,]/u.test(policy)) {
setError(t('connections.ruleDialog.unsupportedValue'))
return
}
setSaving(true)
setError('')
try {
const result = await mutate(
async () => {
const checkProfile = async () => {
const profiles = await getProfiles()
const current = profiles.items?.find(
(item) => item.uid === profiles.current,
)
if (
profiles.current !== target.profileUid ||
current?.option?.rules !== target.rulesUid
) {
throw new Error(t('connections.ruleDialog.profileChanged'))
}
}
await checkProfile()
const content = await readProfileFile(target.rulesUid)
const updated = saveConnectionRule(content, condition, policy)
await checkProfile()
return saveProfileFile(target.rulesUid, updated)
},
{ id: `save-profile-file:${target.rulesUid}`, errorNotice: false },
)
if (!result.ok || !result.value) {
setError(t('connections.ruleDialog.applyFailed'))
return
}
showNotice.success('connections.ruleDialog.saved')
onClose()
} catch (err) {
setError(err instanceof Error ? err.message : String(err))
} finally {
setSaving(false)
}
})
return (
<Dialog open onClose={saving ? undefined : onClose} fullWidth maxWidth="sm">
<DialogTitle>
{t(
modifying
? 'connections.ruleDialog.modifyTitle'
: 'connections.ruleDialog.title',
)}
</DialogTitle>
<DialogContent>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 1 }}>
<TextField
select
fullWidth
size="small"
label={t('connections.ruleDialog.matchBy')}
value={kind}
disabled={blocked}
onChange={(event) => {
const next = event.target.value as ConnectionRuleKind
const nextTarget = targets[next]
const rule =
rules && nextTarget
? (findConnectionRule(rules, nextTarget) ??
(next === 'domain'
? findConnectionRule(rules, {
...nextTarget,
type: 'DOMAIN-SUFFIX',
})
: undefined))
: undefined
setMatchingInput(nextTarget?.value ?? '')
setKind(next)
setPolicy(rule?.policy ?? null)
setScope(
rule?.type === 'DOMAIN-SUFFIX' ? 'DOMAIN-SUFFIX' : 'DOMAIN',
)
}}
>
{(['domain', 'process', 'source', 'destination'] as const).map(
(option) => (
<MenuItem
key={option}
value={option}
disabled={!targets[option]}
>
{kindLabels[option]}
{!targets[option] &&
` · ${t('connections.ruleDialog.unavailable')}`}
</MenuItem>
),
)}
</TextField>
{kind === 'process' ? (
<>
{target.metadata.process?.trim() && (
<TextField
fullWidth
size="small"
label={kindLabels.process}
value={target.metadata.process}
slotProps={{
input: { readOnly: true },
htmlInput: { title: target.metadata.process },
}}
/>
)}
{selected?.type === 'PROCESS-PATH' && (
<TextField
fullWidth
size="small"
label={t('connections.ruleDialog.fullPath')}
value={selected.value}
slotProps={{
input: { readOnly: true },
htmlInput: { title: selected.value },
}}
/>
)}
</>
) : (
<TextField
fullWidth
size="small"
label={
editingDomain || matchingRoot
? t('connections.ruleDialog.matchingDomain')
: kindLabels[kind]
}
value={matchingValue}
disabled={(editingDomain || editingIP) && blocked}
onChange={(event) => {
const value = event.target.value
setMatchingInput(value)
const nextCondition = editingIP
? getConnectionIPRule(value, kind === 'source')
: isConnectionRuleDomain(value, targets.domain?.value ?? '')
? { type: 'DOMAIN-SUFFIX', value: value.trim() }
: undefined
const match =
rules && nextCondition
? findConnectionRule(rules, nextCondition)
: undefined
if (match) setPolicy(match.policy)
}}
error={invalidValue}
helperText={
editingDomain || matchingRoot ? (
<>
{t('connections.ruleDialog.connectionHost', {
host: targets.domain?.value,
})}
{invalidDomain && (
<>
<br />
{t('connections.ruleDialog.invalidDomain')}
</>
)}
</>
) : invalidIP ? (
t('connections.ruleDialog.invalidIp')
) : undefined
}
slotProps={{
input: { readOnly: !editingDomain && !editingIP },
htmlInput: {
title: condition?.value,
},
}}
/>
)}
</Box>
{kind === 'domain' && (
<RadioGroup
row
aria-label={t('connections.ruleDialog.domainScope')}
value={scope}
onChange={(_, value) => {
const nextScope = value as DomainScope
setScope(nextScope)
setMatchingInput(targets.domain?.value ?? '')
const match =
rules && targets.domain
? findConnectionRule(rules, {
type: nextScope === 'DOMAIN' ? 'DOMAIN' : 'DOMAIN-SUFFIX',
value:
nextScope === 'ROOT-DOMAIN'
? (rootDomain ?? '')
: targets.domain.value,
})
: undefined
setPolicy(match?.policy ?? null)
}}
sx={{ mt: 0.5 }}
>
<FormControlLabel
value="DOMAIN"
control={<Radio size="small" />}
disabled={blocked}
label={t('connections.ruleDialog.exactDomain')}
/>
<FormControlLabel
value="DOMAIN-SUFFIX"
control={<Radio size="small" />}
disabled={blocked}
label={t('connections.ruleDialog.allSubdomains')}
/>
{rootDomain &&
rootDomain.toLowerCase() !==
targets.domain?.value.toLowerCase() && (
<FormControlLabel
value="ROOT-DOMAIN"
control={<Radio size="small" />}
disabled={blocked}
label={t('connections.ruleDialog.rootDomain', {
domain: rootDomain,
})}
/>
)}
</RadioGroup>
)}
{(kind === 'source' || kind === 'destination') && (
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
{t(
kind === 'source'
? 'connections.ruleDialog.sourceHint'
: 'connections.ruleDialog.destinationHint',
)}
</Typography>
)}
{kind === 'process' && (
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
{selected?.type === 'PROCESS-PATH'
? t('connections.ruleDialog.processPathHint')
: t('connections.ruleDialog.processNameHint')}
</Typography>
)}
<Autocomplete
size="small"
options={
unavailablePolicy && policy ? [policy, ...policies] : policies
}
getOptionLabel={(value) =>
value === 'DIRECT'
? t('proxies.components.enums.policies.DIRECT')
: value === 'REJECT'
? t('proxies.components.enums.policies.REJECT')
: value
}
getOptionDisabled={(value) => !policies.includes(value)}
value={policy}
onChange={(_, value) => setPolicy(value)}
disabled={blocked}
loading={loading}
renderInput={(params) => (
<TextField
{...params}
label={t('rules.modals.editor.form.labels.proxyPolicy')}
margin="normal"
error={unavailablePolicy}
helperText={
unavailablePolicy
? t('connections.ruleDialog.policyUnavailable')
: undefined
}
/>
)}
/>
{clashConfig && clashConfig.mode !== 'rule' && (
<Alert severity="info" sx={{ mt: 2 }}>
{t('connections.ruleDialog.ruleModeHint')}
</Alert>
)}
{error && (
<Box sx={{ mt: 2 }}>
<Alert severity="error">
{error}
{rules === null && (
<Button
onClick={() => {
setLoading(true)
setError('')
setLoadAttempt((attempt) => attempt + 1)
}}
>
{t('shared.actions.retry')}
</Button>
)}
</Alert>
</Box>
)}
<Typography
variant="caption"
color="text.secondary"
sx={{ display: 'block', mt: 2, overflowWrap: 'anywhere' }}
>
{t(
modifying
? 'connections.ruleDialog.editDestination'
: 'connections.ruleDialog.destination',
{
name: target.profileName,
},
)}
</Typography>
<Typography
variant="caption"
color="text.secondary"
sx={{ display: 'block' }}
>
{t('connections.ruleDialog.newConnections')}
</Typography>
</DialogContent>
<DialogActions>
<Button disabled={saving} onClick={onClose}>
{t('shared.actions.cancel')}
</Button>
<Button
variant="contained"
loading={saving}
disabled={
blocked ||
!condition ||
invalidValue ||
!policy ||
!policies.includes(policy)
}
onClick={handleSave}
>
{t(
modifying
? 'connections.ruleDialog.saveAndApply'
: 'connections.ruleDialog.addAndApply',
)}
</Button>
</DialogActions>
</Dialog>
)
}
@@ -0,0 +1,163 @@
import { dump, loadAll } from 'js-yaml'
import isFQDN from 'validator/es/lib/isFQDN'
import isIP from 'validator/es/lib/isIP'
import isIPRange from 'validator/es/lib/isIPRange'
export type ConnectionRuleKind = 'domain' | 'process' | 'source' | 'destination'
function getAddressRule(address: string | undefined, source: boolean) {
const ip = address?.trim()
if (!ip || !isIP(ip)) return undefined
return getConnectionIPRule(`${ip}/${isIP(ip, 4) ? 32 : 128}`, source)
}
export function getConnectionIPRule(value: string, source: boolean) {
const cidr = value.trim()
if (cidr.includes('%') || !isIPRange(cidr)) return undefined
const ipv4 = isIP(cidr.split('/')[0], 4)
return {
type: source ? 'SRC-IP-CIDR' : ipv4 ? 'IP-CIDR' : 'IP-CIDR6',
value: cidr,
}
}
export function getConnectionRuleTargets(
metadata: Pick<
IConnectionsItem['metadata'],
| 'host'
| 'process'
| 'processPath'
| 'sourceIP'
| 'destinationIP'
| 'remoteDestination'
>,
) {
const host = metadata.host?.trim() ?? ''
const path = metadata.processPath
const name = metadata.process
const domain =
host && !isIP(host) && isFQDN(host, { require_tld: false })
? { type: 'DOMAIN', value: host }
: undefined
const process = path?.trim()
? { type: 'PROCESS-PATH', value: path }
: name?.trim()
? { type: 'PROCESS-NAME', value: name }
: undefined
const source = getAddressRule(metadata.sourceIP, true)
const destination =
getAddressRule(metadata.destinationIP, false) ??
getAddressRule(metadata.remoteDestination, false)
return { domain, process, source, destination }
}
export function isConnectionRuleDomain(value: string, host: string) {
const domain = value.trim()
if (!domain || isIP(domain) || !isFQDN(domain, { require_tld: false }))
return false
const normalized = domain.toLowerCase()
const current = host.toLowerCase()
return (
normalized === current ||
(domain.split('.').length >= 2 && current.endsWith(`.${normalized}`))
)
}
export async function getConnectionRootDomain(host: string) {
const { parse } = await import('tldts')
const { domain, isIcann, isPrivate } = parse(host, {
allowPrivateDomains: true,
})
return domain && (isIcann || isPrivate) ? domain : undefined
}
function parseRuleExtension(content: string) {
const documents = loadAll(content)
if (documents.length > 1) {
throw new Error('The rule extension must contain a single YAML document.')
}
const parsed = documents[0]
if (
parsed !== undefined &&
parsed !== null &&
(typeof parsed !== 'object' ||
Array.isArray(parsed) ||
Object.getPrototypeOf(parsed) !== Object.prototype)
) {
throw new Error('The rule extension must be a YAML mapping.')
}
const config = (parsed ?? {}) as Record<string, unknown>
for (const key of ['prepend', 'append', 'delete']) {
const sequence = config[key]
if (
sequence != null &&
(!Array.isArray(sequence) ||
sequence.some((item) => typeof item !== 'string'))
) {
throw new Error('The rule extension contains an invalid rule list.')
}
}
return config
}
interface RuleCondition {
type: string
value: string
}
function matchesConnectionRule(raw: string, target: RuleCondition) {
const parts = raw.split(',').map((part) => part.trim())
const hasNoResolve =
(target.type === 'IP-CIDR' || target.type === 'IP-CIDR6') &&
parts.length === 4 &&
parts[3] === 'no-resolve'
if (parts.length !== 3 && !hasNoResolve) return false
if (target.type === 'DOMAIN' || target.type === 'DOMAIN-SUFFIX') {
return (
parts[0] === target.type &&
parts[1].toLowerCase() === target.value.toLowerCase()
)
}
return parts[0] === target.type && parts[1] === target.value
}
export function getConnectionRules(content: string): string[] {
const config = parseRuleExtension(content)
return [
...((config.prepend ?? []) as string[]),
...((config.append ?? []) as string[]),
]
}
export function findConnectionRule(rules: string[], target: RuleCondition) {
for (const raw of rules) {
if (matchesConnectionRule(raw, target)) {
const [type, , policy] = raw.split(',').map((part) => part.trim())
return { type, policy }
}
}
return undefined
}
export function saveConnectionRule(
content: string,
target: RuleCondition,
policy: string,
): string {
const config = parseRuleExtension(content)
const rule = `${target.type},${target.value},${policy}`
let replaced = false
for (const key of ['prepend', 'append']) {
if (!Array.isArray(config[key])) continue
config[key] = (config[key] as string[]).flatMap((raw) => {
if (!matchesConnectionRule(raw, target)) return [raw]
if (replaced) return []
replaced = true
return [raw.split(',').length === 4 ? `${rule},no-resolve` : rule]
})
}
if (!replaced) {
config.prepend = [rule, ...((config.prepend ?? []) as string[])]
}
return dump(config, { forceQuotes: true })
}
+22 -19
View File
@@ -29,6 +29,7 @@ import {
getConnectionStartTime, getConnectionStartTime,
getConnectionTypeLabel, getConnectionTypeLabel,
} from './connection-row-view' } from './connection-row-view'
import type { ConnectionRuleKind } from './connection-rule'
const ROW_HEIGHT = 40 const ROW_HEIGHT = 40
const RESIZE_HANDLE_WIDTH = 6 const RESIZE_HANDLE_WIDTH = 6
@@ -223,16 +224,6 @@ const compareConnectionCellValue = (
right: IConnectionsItem, right: IConnectionsItem,
getSnapshot: (row: IConnectionsItem) => TableRowSnapshot, getSnapshot: (row: IConnectionsItem) => TableRowSnapshot,
) => { ) => {
switch (field) {
case 'download':
return (left.download ?? 0) - (right.download ?? 0)
case 'upload':
return (left.upload ?? 0) - (right.upload ?? 0)
case 'dlSpeed':
return (left.curDownload ?? 0) - (right.curDownload ?? 0)
case 'ulSpeed':
return (left.curUpload ?? 0) - (right.curUpload ?? 0)
}
const leftValue = getConnectionCellValue(field, getSnapshot(left)) const leftValue = getConnectionCellValue(field, getSnapshot(left))
const rightValue = getConnectionCellValue(field, getSnapshot(right)) const rightValue = getConnectionCellValue(field, getSnapshot(right))
@@ -257,7 +248,7 @@ const renderCell = (
interface RowComponentProps { interface RowComponentProps {
row: IConnectionsItem row: IConnectionsItem
columns: DisplayColumn[] columns: DisplayColumn[]
onShowDetail: (id: string) => void onShowDetail: (id: string, preferredKind?: ConnectionRuleKind) => void
getSnapshot: (row: IConnectionsItem) => TableRowSnapshot getSnapshot: (row: IConnectionsItem) => TableRowSnapshot
borderColor: string borderColor: string
virtualTop: number virtualTop: number
@@ -273,7 +264,22 @@ const RowComponent = memo(
virtualTop, virtualTop,
}: RowComponentProps) { }: RowComponentProps) {
const handleClick = useCallback( const handleClick = useCallback(
() => onShowDetail(row.id), (event: ReactMouseEvent<HTMLDivElement>) => {
const field =
event.target instanceof Element
? event.target.closest<HTMLElement>('[data-connection-field]')
?.dataset.connectionField
: undefined
const preferredKind =
field === 'process'
? 'process'
: field === 'source'
? 'source'
: field === 'remoteDestination'
? 'destination'
: 'domain'
onShowDetail(row.id, preferredKind)
},
[onShowDetail, row.id], [onShowDetail, row.id],
) )
const snapshot = getSnapshot(row) const snapshot = getSnapshot(row)
@@ -295,6 +301,7 @@ const RowComponent = memo(
{columns.map((column) => ( {columns.map((column) => (
<div <div
key={column.field} key={column.field}
data-connection-field={column.field}
style={{ style={{
boxSizing: 'border-box', boxSizing: 'border-box',
flex: `0 0 ${column.size}px`, flex: `0 0 ${column.size}px`,
@@ -328,7 +335,7 @@ const RowComponent = memo(
interface Props { interface Props {
connections: IConnectionsItem[] connections: IConnectionsItem[]
onShowDetail: (id: string) => void onShowDetail: (id: string, preferredKind?: ConnectionRuleKind) => void
columnManagerOpen: boolean columnManagerOpen: boolean
onCloseColumnManager: () => void onCloseColumnManager: () => void
} }
@@ -343,7 +350,8 @@ export const ConnectionTable = (props: Props) => {
const onShowDetailRef = useRef(rawOnShowDetail) const onShowDetailRef = useRef(rawOnShowDetail)
onShowDetailRef.current = rawOnShowDetail onShowDetailRef.current = rawOnShowDetail
const onShowDetail = useCallback( const onShowDetail = useCallback(
(id: string) => onShowDetailRef.current(id), (id: string, preferredKind?: ConnectionRuleKind) =>
onShowDetailRef.current(id, preferredKind),
[], [],
) )
const { t } = useTranslation() const { t } = useTranslation()
@@ -501,8 +509,6 @@ export const ConnectionTable = (props: Props) => {
const [sorting, setSorting] = useState<SortingState | null>(null) const [sorting, setSorting] = useState<SortingState | null>(null)
const [viewport, setViewport] = useState({ scrollTop: 0, height: 0 }) const [viewport, setViewport] = useState({ scrollTop: 0, height: 0 })
const scrollContainerRef = useRef<HTMLDivElement | null>(null) const scrollContainerRef = useRef<HTMLDivElement | null>(null)
const resizeCleanupRef = useRef<(() => void) | null>(null)
useEffect(() => () => resizeCleanupRef.current?.(), [])
const rowSnapshotCacheRef = useRef(new Map<string, TableRowSnapshot>()) const rowSnapshotCacheRef = useRef(new Map<string, TableRowSnapshot>())
const getRowSnapshot = useCallback((row: IConnectionsItem) => { const getRowSnapshot = useCallback((row: IConnectionsItem) => {
const cache = rowSnapshotCacheRef.current const cache = rowSnapshotCacheRef.current
@@ -676,7 +682,6 @@ export const ConnectionTable = (props: Props) => {
minWidth: number, minWidth: number,
maxWidth: number | undefined, maxWidth: number | undefined,
) => { ) => {
resizeCleanupRef.current?.()
const handleMove = (clientX: number) => { const handleMove = (clientX: number) => {
const nextWidth = Math.max( const nextWidth = Math.max(
minWidth, minWidth,
@@ -699,10 +704,8 @@ export const ConnectionTable = (props: Props) => {
window.removeEventListener('touchmove', handleTouchMove) window.removeEventListener('touchmove', handleTouchMove)
window.removeEventListener('touchend', cleanup) window.removeEventListener('touchend', cleanup)
window.removeEventListener('touchcancel', cleanup) window.removeEventListener('touchcancel', cleanup)
resizeCleanupRef.current = null
} }
resizeCleanupRef.current = cleanup
window.addEventListener('mousemove', handleMouseMove) window.addEventListener('mousemove', handleMouseMove)
window.addEventListener('mouseup', cleanup) window.addEventListener('mouseup', cleanup)
window.addEventListener('touchmove', handleTouchMove, { passive: true }) window.addEventListener('touchmove', handleTouchMove, { passive: true })
+57 -102
View File
@@ -31,7 +31,6 @@ import {
} from '@mui/material' } from '@mui/material'
import { useLockFn } from 'ahooks' import { useLockFn } from 'ahooks'
import { import {
memo,
useCallback, useCallback,
useEffect, useEffect,
useEffectEvent, useEffectEvent,
@@ -55,7 +54,6 @@ import {
useCoreDataStatus, useCoreDataStatus,
useProxiesData, useProxiesData,
} from '@/providers/app-data-context' } from '@/providers/app-data-context'
import { followProxyGroup } from '@/services/cmds'
import delayManager from '@/services/delay' import delayManager from '@/services/delay'
import { import {
findCurrentGroupMember, findCurrentGroupMember,
@@ -206,11 +204,14 @@ const optionValue = (memberIndex: number, member: ResolvedProxyMember) =>
const sortProxyOptions = ( const sortProxyOptions = (
options: ProxyOption[], options: ProxyOption[],
sortType: 0 | 1, sortType: ProxySortType,
delayOf: (member: ResolvedProxyMember) => number, delayOf: (member: ResolvedProxyMember) => number,
latencyTimeout?: number, latencyTimeout?: number,
) => { ) => {
if (sortType === 0) return options if (sortType === 0) return options
if (sortType === 2) {
return [...options].sort((a, b) => a.name.localeCompare(b.name))
}
const effectiveTimeout = const effectiveTimeout =
typeof latencyTimeout === 'number' && latencyTimeout > 0 typeof latencyTimeout === 'number' && latencyTimeout > 0
@@ -432,72 +433,6 @@ interface PersistentProxySelectProps
onChange: (value: string) => void onChange: (value: string) => void
} }
const ProxyMenuOption = memo(function ProxyMenuOption({
option,
selected,
isFixed,
fixedProxyInUsed,
delay,
onChange,
}: {
option: ProxyOption
selected: boolean
isFixed: boolean
fixedProxyInUsed: boolean
delay: number
onChange: (value: string) => void
}) {
return (
<MenuItem
role="option"
aria-selected={selected}
selected={selected}
disabled={option.disabled}
onClick={() => {
if (!option.disabled) onChange(option.value)
}}
sx={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
width: '100%',
pr: 1,
}}
>
{isFixed && (
<span
style={{
position: 'absolute',
fontSize: '12px',
top: '-5px',
right: '5px',
...(!fixedProxyInUsed && {
filter: 'grayscale(1)',
}),
}}
>
📌
</span>
)}
<Typography noWrap sx={{ flex: 1, mr: 1 }}>
{option.name}
</Typography>
{!option.disabled && (
<Chip
size="small"
label={delayManager.formatDelay(delay)}
color={convertDelayColor(delay)}
sx={{
minWidth: '60px',
height: '22px',
flexShrink: 0,
}}
/>
)}
</MenuItem>
)
})
const PersistentProxySelect = ({ const PersistentProxySelect = ({
groupName, groupName,
fixed, fixed,
@@ -550,15 +485,54 @@ const PersistentProxySelect = ({
: delayManager.getDelayFix(option.member, groupName) : delayManager.getDelayFix(option.member, groupName)
return ( return (
<ProxyMenuOption <MenuItem
key={option.value} key={option.value}
option={option} role="option"
aria-selected={selected}
selected={selected} selected={selected}
isFixed={isFixed} disabled={option.disabled}
fixedProxyInUsed={fixedProxyInUsed} onClick={() => {
delay={delay} if (!option.disabled) onChange(option.value)
onChange={onChange} }}
sx={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
width: '100%',
pr: 1,
}}
>
{isFixed && (
<span
style={{
position: 'absolute',
fontSize: '12px',
top: '-5px',
right: '5px',
...(!fixedProxyInUsed && {
filter: 'grayscale(1)',
}),
}}
>
📌
</span>
)}
<Typography noWrap sx={{ flex: 1, mr: 1 }}>
{option.name}
</Typography>
{!option.disabled && (
<Chip
size="small"
label={delayManager.formatDelay(delay)}
color={convertDelayColor(delay)}
sx={{
minWidth: '60px',
height: '22px',
flexShrink: 0,
}}
/> />
)}
</MenuItem>
) )
}) })
} }
@@ -631,14 +605,12 @@ export const CurrentProxyCard = () => {
[getProfileStorageKey], [getProfileStorageKey],
) )
const onSelectionError = useCallback( const { select } = useProxySelection({
(error: unknown) => { onError: (error) => {
console.error('代理切换失败', error) console.error('代理切换失败', error)
refreshProxy() refreshProxy()
}, },
[refreshProxy], })
)
const { select } = useProxySelection({ onError: onSelectionError })
const mode = clashConfig?.mode?.toLowerCase() || 'rule' const mode = clashConfig?.mode?.toLowerCase() || 'rule'
const isGlobalMode = mode === 'global' const isGlobalMode = mode === 'global'
@@ -666,7 +638,7 @@ export const CurrentProxyCard = () => {
return proxyView.groups.filter( return proxyView.groups.filter(
(group) => (group) =>
!group.hidden && !group.hidden &&
['Selector', 'URLTest', 'Fallback'].includes(group.type), (group.type === 'Selector' || group.type === 'URLTest'),
) )
}, [proxyView]) }, [proxyView])
@@ -701,6 +673,7 @@ export const CurrentProxyCard = () => {
if (proxyView && lastGroupName !== selectedGroupName) { if (proxyView && lastGroupName !== selectedGroupName) {
setLastGroupName(selectedGroupName) setLastGroupName(selectedGroupName)
} }
const delays = useGroupDelays(selectedGroupName || null)
const selectedGroup = useMemo<ProxyGroupView | null>(() => { const selectedGroup = useMemo<ProxyGroupView | null>(() => {
if (!proxyView || isDirectMode) return null if (!proxyView || isDirectMode) return null
@@ -766,7 +739,6 @@ export const CurrentProxyCard = () => {
if (isGlobalMode || isDirectMode) return if (isGlobalMode || isDirectMode) return
setLastGroupName(newGroupName) setLastGroupName(newGroupName)
writeProfileScopedItem(STORAGE_KEY_GROUP, newGroupName) writeProfileScopedItem(STORAGE_KEY_GROUP, newGroupName)
void followProxyGroup(newGroupName)
}, },
[isDirectMode, isGlobalMode, writeProfileScopedItem], [isDirectMode, isGlobalMode, writeProfileScopedItem],
) )
@@ -795,16 +767,9 @@ export const CurrentProxyCard = () => {
const currentProxy = currentMember ? memberDetails(currentMember) : undefined const currentProxy = currentMember ? memberDetails(currentMember) : undefined
const selectedProxyName = currentMember?.ref.name ?? '' const selectedProxyName = currentMember?.ref.name ?? ''
const delays = useGroupDelays(
selectedGroupName,
currentMember,
openSelect === 'proxy',
)
const currentDelay = const currentDelay =
typeof delays === 'number' currentMember && selectedGroupName
? delays ? delayManager.getDelayFix(currentMember, selectedGroupName)
: currentMember
? delays.of(currentMember)
: -1 : -1
const signalInfo = const signalInfo =
@@ -925,19 +890,10 @@ export const CurrentProxyCard = () => {
refreshProxy() refreshProxy()
}) })
const nameSortedProxyOptions = useMemo(
() =>
!isDirectMode && openSelect === 'proxy' && sortType === 2
? [...unsortedProxyOptions].sort((a, b) => a.name.localeCompare(b.name))
: unsortedProxyOptions,
[isDirectMode, openSelect, sortType, unsortedProxyOptions],
)
const proxyOptions = useMemo( const proxyOptions = useMemo(
() => () =>
isDirectMode || openSelect !== 'proxy' || typeof delays === 'number' isDirectMode || openSelect !== 'proxy'
? [] ? []
: sortType === 2
? nameSortedProxyOptions
: sortProxyOptions( : sortProxyOptions(
unsortedProxyOptions, unsortedProxyOptions,
sortType, sortType,
@@ -946,7 +902,6 @@ export const CurrentProxyCard = () => {
), ),
[ [
delays, delays,
nameSortedProxyOptions,
isDirectMode, isDirectMode,
openSelect, openSelect,
unsortedProxyOptions, unsortedProxyOptions,
@@ -7,6 +7,7 @@ import {
useEffectEvent, useEffectEvent,
useImperativeHandle, useImperativeHandle,
useMemo, useMemo,
useReducer,
useRef, useRef,
useState, useState,
} from 'react' } from 'react'
@@ -19,6 +20,7 @@ import {
formatTrafficHourMinute, formatTrafficHourMinute,
formatTrafficMinuteSecond, formatTrafficMinuteSecond,
formatTrafficName, formatTrafficName,
isSameTrafficData,
} from '@/utils/traffic-sampler' } from '@/utils/traffic-sampler'
export interface EnhancedCanvasTrafficGraphRef { export interface EnhancedCanvasTrafficGraphRef {
@@ -72,200 +74,16 @@ const GRAPH_CONFIG = {
const STALE_DATA_THRESHOLD = 2500 // ms without fresh data => drop FPS const STALE_DATA_THRESHOLD = 2500 // ms without fresh data => drop FPS
// Static sx/style identities keep the emotion cache effective; the remaining
// dynamic props (tooltip position, legend colors) stay inline or memoized.
const rootSx = {
width: '100%',
height: '100%',
position: 'relative',
bgcolor: 'action.hover',
borderRadius: 1,
cursor: 'pointer',
overflow: 'hidden',
}
const canvasStyle = {
width: '100%',
height: '100%',
display: 'block',
} as const
const hoverCanvasStyle = {
position: 'absolute',
inset: 0,
width: '100%',
height: '100%',
display: 'block',
pointerEvents: 'none',
} as const
const overlaySx = {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
pointerEvents: 'none',
}
const timeRangeBadgeSx = {
position: 'absolute',
top: 6,
left: 40,
fontSize: '11px',
fontWeight: 'bold',
color: 'text.secondary',
cursor: 'pointer',
pointerEvents: 'all',
px: 1,
py: 0.5,
borderRadius: 0.5,
bgcolor: 'rgba(0,0,0,0.05)',
'&:hover': {
bgcolor: 'rgba(0,0,0,0.1)',
},
}
const legendsSx = {
position: 'absolute',
top: 6,
right: 8,
display: 'flex',
flexDirection: 'column',
gap: 0.5,
}
const chartStyleHintSx = {
position: 'absolute',
bottom: 6,
right: 8,
fontSize: '10px',
color: 'text.disabled',
opacity: 0.7,
}
const diagnosticsSx = {
position: 'absolute',
bottom: 6,
left: 8,
fontSize: '9px',
color: 'text.disabled',
opacity: 0.6,
lineHeight: 1.2,
}
const tooltipTimeSx = { color: 'text.secondary', mb: 0.2 }
const tooltipUpSx = { color: 'secondary.main', fontWeight: 500 }
const tooltipDownSx = { color: 'primary.main', fontWeight: 500 }
interface TimeDisplayStrategy {
maxLabels: number
formatTime: (timestamp: number) => string
intervalSeconds: number
minPixelDistance: number
}
const TIME_DISPLAY_STRATEGIES: Record<TimeRange, TimeDisplayStrategy> = {
1: {
maxLabels: 6,
formatTime: formatTrafficMinuteSecond,
intervalSeconds: 10,
minPixelDistance: 35,
},
5: {
maxLabels: 6,
formatTime: formatTrafficHourMinute,
intervalSeconds: 30,
minPixelDistance: 38,
},
10: {
maxLabels: 8,
formatTime: formatTrafficHourMinute,
intervalSeconds: 60,
minPixelDistance: 40,
},
}
// Per-draw buffers live at module scope: drawing runs synchronously on the
// main thread, so slots never overlap a concurrent reader.
const yAxisTicks = [
{ label: '', y: 0 },
{ label: '', y: 0 },
{ label: '', y: 0 },
]
const yAxisTickLabels = new Map<number, string>()
const formatYAxisTickLabel = (bytes: number): string => {
const cached = yAxisTickLabels.get(bytes)
if (cached !== undefined) return cached
const label =
bytes === 0
? '0'
: bytes < 1024
? `${Math.round(bytes)}B`
: bytes < 1024 * 1024
? `${Math.round(bytes / 1024)}KB`
: `${(bytes / (1024 * 1024)).toFixed(1)}MB`
if (yAxisTickLabels.size >= 256) yAxisTickLabels.clear()
yAxisTickLabels.set(bytes, label)
return label
}
const getYAxisTicks = (
topValue: number,
bottomValue: number,
height: number,
) => {
const padding = GRAPH_CONFIG.padding
const topY = padding.top + 10
const bottomY = height - padding.bottom - 5
const middleY = (topY + bottomY) / 2
const middleValue = (bottomValue + topValue) / 2
const [bottomTick, middleTick, topTick] = yAxisTicks
bottomTick.label = formatYAxisTickLabel(bottomValue)
bottomTick.y = bottomY
middleTick.label = formatYAxisTickLabel(middleValue)
middleTick.y = middleY
topTick.label = formatYAxisTickLabel(topValue)
topTick.y = topY
return yAxisTicks
}
interface TimeAxisPoint {
x: number
label: string
}
const timeAxisPoints: TimeAxisPoint[] = []
const resetTimeAxisPoints = () => {
timeAxisPoints.length = 0
}
const pushTimeAxisPoint = (x: number, label: string) => {
let slot = timeAxisPoints[timeAxisPoints.length]
if (!slot) {
slot = { x: 0, label: '' }
timeAxisPoints.push(slot)
}
slot.x = x
slot.label = label
}
// Gradient stop strings are pure functions of the theme color; the colors
// memo builds them once per theme.
const GRADIENT_ALPHA_HEX = Math.round(GRAPH_CONFIG.alpha.gradient * 255)
.toString(16)
.padStart(2, '0')
const makeGradientStops = (color: string) => ({
start: `${color}${GRADIENT_ALPHA_HEX}`,
end: `${color}00`,
})
interface EnhancedCanvasTrafficGraphProps { interface EnhancedCanvasTrafficGraphProps {
ref?: Ref<EnhancedCanvasTrafficGraphRef> ref?: Ref<EnhancedCanvasTrafficGraphRef>
} }
const displayDataReducer = (
current: ITrafficDataPoint[],
payload: ITrafficDataPoint[],
): ITrafficDataPoint[] =>
isSameTrafficData(current, payload) ? current : payload
export const EnhancedCanvasTrafficGraph = memo( export const EnhancedCanvasTrafficGraph = memo(
function EnhancedCanvasTrafficGraph({ function EnhancedCanvasTrafficGraph({
ref, ref,
@@ -276,9 +94,11 @@ export const EnhancedCanvasTrafficGraph = memo(
const pause_render_traffic_stats_on_blur = const pause_render_traffic_stats_on_blur =
verge.verge?.pause_render_traffic_stats_on_blur ?? true verge.verge?.pause_render_traffic_stats_on_blur ?? true
const { dataPoints, requestRange, samplerStats } =
useTrafficGraphDataEnhanced()
const [timeRange, setTimeRange] = useState<TimeRange>(10) const [timeRange, setTimeRange] = useState<TimeRange>(10)
const [chartStyle, setChartStyle] = useState<'bezier' | 'line'>('bezier') const [chartStyle, setChartStyle] = useState<'bezier' | 'line'>('bezier')
const [badgeStats, setBadgeStats] = useState({ points: 0, compressed: 0 })
const initialFocusState = const initialFocusState =
typeof document !== 'undefined' ? !document.hidden : true typeof document !== 'undefined' ? !document.hidden : true
@@ -309,49 +129,66 @@ export const EnhancedCanvasTrafficGraph = memo(
const lastDataTimestampRef = useRef<number>(0) const lastDataTimestampRef = useRef<number>(0)
const dataStaleRef = useRef<boolean>(false) const dataStaleRef = useRef<boolean>(false)
// Live snapshot data for the rAF draw path; React state only tracks the const [displayData, dispatchDisplayData] = useReducer(
// diagnostics badge inputs so steady-state snapshots stop re-rendering. displayDataReducer,
const displayDataRef = useRef<ITrafficDataPoint[]>([]) [],
const yScaleRef = useRef<{ topValue: number; bottomValue: number }>({ )
topValue: 1024, const debounceTimeoutRef = useRef<number | null>(null)
bottomValue: 0,
})
const colors = useMemo(() => { const colors = useMemo(
const base = { () => ({
up: theme.palette.secondary.main, up: theme.palette.secondary.main,
down: theme.palette.primary.main, down: theme.palette.primary.main,
grid: theme.palette.divider, grid: theme.palette.divider,
text: theme.palette.text.secondary, text: theme.palette.text.secondary,
background: theme.palette.background.paper, background: theme.palette.background.paper,
}
return {
...base,
gradient: {
up: makeGradientStops(base.up),
down: makeGradientStops(base.down),
},
}
}, [theme])
const legendSx = useMemo(
() => ({
up: {
fontSize: '11px',
fontWeight: 'bold',
color: colors.up,
textAlign: 'right',
},
down: {
fontSize: '11px',
fontWeight: 'bold',
color: colors.down,
textAlign: 'right',
},
}), }),
[colors], [theme],
) )
const updateDisplayData = useCallback((newData: ITrafficDataPoint[]) => {
if (debounceTimeoutRef.current !== null) {
window.clearTimeout(debounceTimeoutRef.current)
}
debounceTimeoutRef.current = window.setTimeout(() => {
dispatchDisplayData(newData)
}, 50)
}, [])
useEffect(() => {
updateDisplayData(dataPoints)
return () => {
if (debounceTimeoutRef.current !== null) {
window.clearTimeout(debounceTimeoutRef.current)
debounceTimeoutRef.current = null
}
}
}, [dataPoints, updateDisplayData])
useEffect(() => {
requestRange(timeRange)
}, [requestRange, timeRange])
useEffect(() => {
if (displayData.length === 0) {
lastDataTimestampRef.current = 0
dataStaleRef.current = false
return
}
const latestTimestamp =
displayData[displayData.length - 1]?.timestamp ?? null
if (latestTimestamp) {
lastDataTimestampRef.current = latestTimestamp
const age = Date.now() - latestTimestamp
const stale = age > STALE_DATA_THRESHOLD
dataStaleRef.current = stale
} else {
dataStaleRef.current = false
}
}, [displayData])
const handleFocusStateChange = useEffectEvent((focused: boolean) => { const handleFocusStateChange = useEffectEvent((focused: boolean) => {
isWindowFocusedRef.current = focused isWindowFocusedRef.current = focused
@@ -433,9 +270,14 @@ export const EnhancedCanvasTrafficGraph = memo(
[], [],
) )
const yScale = useMemo(
() => computeYScale(displayData),
[computeYScale, displayData],
)
const handleMouseMove = useCallback( const handleMouseMove = useCallback(
(event: React.MouseEvent<HTMLElement>) => { (event: React.MouseEvent<HTMLElement>) => {
if (displayDataRef.current.length === 0) return if (displayData.length === 0) return
pendingMousePositionRef.current = { pendingMousePositionRef.current = {
clientX: event.clientX, clientX: event.clientX,
@@ -452,8 +294,7 @@ export const EnhancedCanvasTrafficGraph = memo(
if (!pendingMousePosition) return if (!pendingMousePosition) return
const canvas = canvasRef.current const canvas = canvasRef.current
const data = displayDataRef.current if (!canvas || displayData.length === 0) return
if (!canvas || data.length === 0) return
const rect = canvas.getBoundingClientRect() const rect = canvas.getBoundingClientRect()
const mouseX = pendingMousePosition.clientX - rect.left const mouseX = pendingMousePosition.clientX - rect.left
@@ -468,11 +309,11 @@ export const EnhancedCanvasTrafficGraph = memo(
0, 0,
Math.min(1, relativeMouseX / effectiveWidth), Math.min(1, relativeMouseX / effectiveWidth),
) )
const dataIndex = Math.round(ratio * (data.length - 1)) const dataIndex = Math.round(ratio * (displayData.length - 1))
if (dataIndex < 0 || dataIndex >= data.length) return if (dataIndex < 0 || dataIndex >= displayData.length) return
const dataPoint = data[dataIndex] const dataPoint = displayData[dataIndex]
const [upValue, upUnit] = parseTraffic(dataPoint.up) const [upValue, upUnit] = parseTraffic(dataPoint.up)
const [downValue, downUnit] = parseTraffic(dataPoint.down) const [downValue, downUnit] = parseTraffic(dataPoint.down)
@@ -481,7 +322,7 @@ export const EnhancedCanvasTrafficGraph = memo(
? formatTrafficName(dataPoint.timestamp) ? formatTrafficName(dataPoint.timestamp)
: t('home.components.traffic.unknownTime') : t('home.components.traffic.unknownTime')
const { topValue: tvH, bottomValue: bvH } = yScaleRef.current const { topValue: tvH, bottomValue: bvH } = yScale
const upY = calculateY(dataPoint.up, rect.height, tvH, bvH) const upY = calculateY(dataPoint.up, rect.height, tvH, bvH)
const downY = calculateY(dataPoint.down, rect.height, tvH, bvH) const downY = calculateY(dataPoint.down, rect.height, tvH, bvH)
const highlightY = const highlightY =
@@ -518,7 +359,7 @@ export const EnhancedCanvasTrafficGraph = memo(
}) })
}) })
}, },
[calculateY, t], [displayData, calculateY, yScale, t],
) )
const handleMouseLeave = useCallback(() => { const handleMouseLeave = useCallback(() => {
@@ -534,6 +375,45 @@ export const EnhancedCanvasTrafficGraph = memo(
) )
}, []) }, [])
const getYAxisTicks = useCallback(
(topValue: number, bottomValue: number, height: number) => {
const formatTrafficValue = (bytes: number): string => {
if (bytes === 0) return '0'
if (bytes < 1024) return `${Math.round(bytes)}B`
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)}KB`
return `${(bytes / (1024 * 1024)).toFixed(1)}MB`
}
const padding = GRAPH_CONFIG.padding
const topY = padding.top + 10
const bottomY = height - padding.bottom - 5
const middleY = (topY + bottomY) / 2
const middleValue = (bottomValue + topValue) / 2
const ticks = [
{
value: bottomValue,
label: formatTrafficValue(bottomValue),
y: bottomY,
},
{
value: middleValue,
label: formatTrafficValue(middleValue),
y: middleY,
},
{
value: topValue,
label: formatTrafficValue(topValue),
y: topY,
},
]
return ticks
},
[],
)
const drawYAxis = useCallback( const drawYAxis = useCallback(
( (
ctx: CanvasRenderingContext2D, ctx: CanvasRenderingContext2D,
@@ -545,6 +425,8 @@ export const EnhancedCanvasTrafficGraph = memo(
const padding = GRAPH_CONFIG.padding const padding = GRAPH_CONFIG.padding
const ticks = getYAxisTicks(topValue, bottomValue, height) const ticks = getYAxisTicks(topValue, bottomValue, height)
if (ticks.length === 0) return
ctx.save() ctx.save()
ticks.forEach((tick, index) => { ticks.forEach((tick, index) => {
@@ -588,7 +470,37 @@ export const EnhancedCanvasTrafficGraph = memo(
ctx.restore() ctx.restore()
}, },
[colors.grid, colors.text, colors.background], [colors.grid, colors.text, colors.background, getYAxisTicks],
)
const getTimeDisplayStrategy = useCallback(
(timeRangeMinutes: TimeRange) => {
switch (timeRangeMinutes) {
case 1:
return {
maxLabels: 6,
formatTime: formatTrafficMinuteSecond,
intervalSeconds: 10,
minPixelDistance: 35,
}
case 5:
return {
maxLabels: 6,
formatTime: formatTrafficHourMinute,
intervalSeconds: 30,
minPixelDistance: 38,
}
case 10:
default:
return {
maxLabels: 8,
formatTime: formatTrafficHourMinute,
intervalSeconds: 60,
minPixelDistance: 40,
}
}
},
[],
) )
const drawTimeAxis = useCallback( const drawTimeAxis = useCallback(
@@ -604,7 +516,7 @@ export const EnhancedCanvasTrafficGraph = memo(
const effectiveWidth = width - padding.left - padding.right const effectiveWidth = width - padding.left - padding.right
const timeAxisY = height - padding.bottom + 14 const timeAxisY = height - padding.bottom + 14
const strategy = TIME_DISPLAY_STRATEGIES[timeRange] const strategy = getTimeDisplayStrategy(timeRange)
ctx.save() ctx.save()
ctx.fillStyle = colors.text ctx.fillStyle = colors.text
@@ -621,13 +533,15 @@ export const EnhancedCanvasTrafficGraph = memo(
Math.ceil((data.length * minPixelDistance) / effectiveWidth), Math.ceil((data.length * minPixelDistance) / effectiveWidth),
) )
resetTimeAxisPoints() const timePoints: Array<{ index: number; x: number; label: string }> =
[]
if (data.length > 0 && data[0].timestamp) { if (data.length > 0 && data[0].timestamp) {
pushTimeAxisPoint( timePoints.push({
padding.left, index: 0,
strategy.formatTime(data[0].timestamp), x: padding.left,
) label: strategy.formatTime(data[0].timestamp),
})
} }
for ( for (
@@ -639,37 +553,41 @@ export const EnhancedCanvasTrafficGraph = memo(
if (!point.timestamp) continue if (!point.timestamp) continue
const x = padding.left + (i / (data.length - 1)) * effectiveWidth const x = padding.left + (i / (data.length - 1)) * effectiveWidth
pushTimeAxisPoint(x, strategy.formatTime(point.timestamp)) timePoints.push({
index: i,
x,
label: strategy.formatTime(point.timestamp),
})
} }
if (data.length > 1 && data[data.length - 1].timestamp) { if (data.length > 1 && data[data.length - 1].timestamp) {
const lastX = width - padding.right const lastX = width - padding.right
const lastPoint = timeAxisPoints[timeAxisPoints.length - 1] const lastPoint = timePoints[timePoints.length - 1]
if (!lastPoint || lastX - lastPoint.x >= minPixelDistance) { if (!lastPoint || lastX - lastPoint.x >= minPixelDistance) {
pushTimeAxisPoint( timePoints.push({
lastX, index: data.length - 1,
strategy.formatTime(data[data.length - 1].timestamp), x: lastX,
) label: strategy.formatTime(data[data.length - 1].timestamp),
})
} }
} }
for (let i = 0; i < timeAxisPoints.length; i++) { timePoints.forEach((point, index) => {
const point = timeAxisPoints[i] if (index === 0) {
if (i === 0) {
ctx.textAlign = 'left' ctx.textAlign = 'left'
} else if (i === timeAxisPoints.length - 1) { } else if (index === timePoints.length - 1) {
ctx.textAlign = 'right' ctx.textAlign = 'right'
} else { } else {
ctx.textAlign = 'center' ctx.textAlign = 'center'
} }
ctx.fillText(point.label, point.x, timeAxisY) ctx.fillText(point.label, point.x, timeAxisY)
} })
ctx.restore() ctx.restore()
}, },
[colors.text, timeRange], [colors.text, timeRange, getTimeDisplayStrategy],
) )
const drawGrid = useCallback( const drawGrid = useCallback(
@@ -714,7 +632,6 @@ export const EnhancedCanvasTrafficGraph = memo(
width: number, width: number,
height: number, height: number,
color: string, color: string,
gradientStops: { start: string; end: string },
withGradient = false, withGradient = false,
topValue: number, topValue: number,
bottomValue: number, bottomValue: number,
@@ -738,8 +655,13 @@ export const EnhancedCanvasTrafficGraph = memo(
0, 0,
height - padding.bottom, height - padding.bottom,
) )
gradient.addColorStop(0, gradientStops.start) gradient.addColorStop(
gradient.addColorStop(1, gradientStops.end) 0,
`${color}${Math.round(GRAPH_CONFIG.alpha.gradient * 255)
.toString(16)
.padStart(2, '0')}`,
)
gradient.addColorStop(1, `${color}00`)
ctx.beginPath() ctx.beginPath()
ctx.moveTo(getX(0), getY(0)) ctx.moveTo(getX(0), getY(0))
@@ -830,7 +752,6 @@ export const EnhancedCanvasTrafficGraph = memo(
const drawGraph = useCallback(() => { const drawGraph = useCallback(() => {
const canvas = canvasRef.current const canvas = canvasRef.current
const displayData = displayDataRef.current
if (!canvas || displayData.length === 0) { if (!canvas || displayData.length === 0) {
clearCanvas(canvasRef.current) clearCanvas(canvasRef.current)
clearCanvas(hoverCanvasRef.current) clearCanvas(hoverCanvasRef.current)
@@ -844,7 +765,7 @@ export const EnhancedCanvasTrafficGraph = memo(
// Clear using CSS dimensions; context is already scaled by DPR. // Clear using CSS dimensions; context is already scaled by DPR.
ctx.clearRect(0, 0, cssWidth, cssHeight) ctx.clearRect(0, 0, cssWidth, cssHeight)
const { topValue, bottomValue } = yScaleRef.current const { topValue, bottomValue } = yScale
drawYAxis(ctx, cssWidth, cssHeight, topValue, bottomValue) drawYAxis(ctx, cssWidth, cssHeight, topValue, bottomValue)
@@ -859,7 +780,6 @@ export const EnhancedCanvasTrafficGraph = memo(
cssWidth, cssWidth,
cssHeight, cssHeight,
colors.down, colors.down,
colors.gradient.down,
true, true,
topValue, topValue,
bottomValue, bottomValue,
@@ -872,7 +792,6 @@ export const EnhancedCanvasTrafficGraph = memo(
cssWidth, cssWidth,
cssHeight, cssHeight,
colors.up, colors.up,
colors.gradient.up,
true, true,
topValue, topValue,
bottomValue, bottomValue,
@@ -885,7 +804,9 @@ export const EnhancedCanvasTrafficGraph = memo(
) )
canvas.dataset.perfDraw = String(displayData.at(-1)?.timestamp ?? 0) canvas.dataset.perfDraw = String(displayData.at(-1)?.timestamp ?? 0)
}, [ }, [
displayData,
colors, colors,
yScale,
drawYAxis, drawYAxis,
drawGrid, drawGrid,
drawTimeAxis, drawTimeAxis,
@@ -896,7 +817,6 @@ export const EnhancedCanvasTrafficGraph = memo(
const drawHoverOverlay = useCallback(() => { const drawHoverOverlay = useCallback(() => {
const canvas = hoverCanvasRef.current const canvas = hoverCanvasRef.current
const displayData = displayDataRef.current
if (!canvas || displayData.length < 2) { if (!canvas || displayData.length < 2) {
clearCanvas(canvas) clearCanvas(canvas)
return return
@@ -934,7 +854,7 @@ export const EnhancedCanvasTrafficGraph = memo(
ctx.restore() ctx.restore()
} }
}, [colors, syncCanvasSize, clearCanvas]) }, [displayData, colors, syncCanvasSize, clearCanvas])
const shouldSkipGraphDraw = useCallback(() => { const shouldSkipGraphDraw = useCallback(() => {
if (!isDocumentVisibleRef.current) return true if (!isDocumentVisibleRef.current) return true
@@ -977,55 +897,6 @@ export const EnhancedCanvasTrafficGraph = memo(
}) })
}, [drawGraph, drawHoverOverlay, shouldSkipGraphDraw]) }, [drawGraph, drawHoverOverlay, shouldSkipGraphDraw])
const handleSnapshot = useCallback(
(message: ITrafficWorkerSnapshotMessage) => {
const data = message.dataPoints
displayDataRef.current = data
yScaleRef.current = computeYScale(data)
if (data.length === 0) {
lastDataTimestampRef.current = 0
dataStaleRef.current = false
} else {
const latestTimestamp = data[data.length - 1]?.timestamp ?? null
if (latestTimestamp) {
lastDataTimestampRef.current = latestTimestamp
const age = Date.now() - latestTimestamp
const stale = age > STALE_DATA_THRESHOLD
dataStaleRef.current = stale
} else {
dataStaleRef.current = false
}
}
scheduleDrawGraph()
// The badge is the only snapshot content that still renders; keeping
// its state here confines re-renders to actual badge changes, and the
// visibility gate skips hidden-phase renders — the re-prime snapshot
// on regaining visibility refreshes it.
if (!isDocumentVisibleRef.current) return
setBadgeStats((prev) =>
prev.points === data.length &&
prev.compressed === message.samplerStats.compressedBufferSize
? prev
: {
points: data.length,
compressed: message.samplerStats.compressedBufferSize,
},
)
},
[computeYScale, scheduleDrawGraph],
)
const { requestRange } = useTrafficGraphDataEnhanced({
subscribe: false,
onSnapshot: handleSnapshot,
})
useEffect(() => {
requestRange(timeRange)
}, [requestRange, timeRange])
useEffect(() => { useEffect(() => {
tooltipDataRef.current = tooltipData tooltipDataRef.current = tooltipData
scheduleHoverDraw() scheduleHoverDraw()
@@ -1095,36 +966,119 @@ export const EnhancedCanvasTrafficGraph = memo(
return ( return (
<Box <Box
sx={rootSx} sx={{
width: '100%',
height: '100%',
position: 'relative',
bgcolor: 'action.hover',
borderRadius: 1,
cursor: 'pointer',
overflow: 'hidden',
}}
onClick={toggleStyle} onClick={toggleStyle}
onMouseMove={handleMouseMove} onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave} onMouseLeave={handleMouseLeave}
> >
<canvas ref={canvasRef} style={canvasStyle} onClick={toggleStyle} /> <canvas
ref={canvasRef}
style={{
width: '100%',
height: '100%',
display: 'block',
}}
onClick={toggleStyle}
/>
{tooltipData.visible && ( {tooltipData.visible && (
<canvas ref={hoverCanvasRef} style={hoverCanvasStyle} /> <canvas
ref={hoverCanvasRef}
style={{
position: 'absolute',
inset: 0,
width: '100%',
height: '100%',
display: 'block',
pointerEvents: 'none',
}}
/>
)} )}
<Box sx={overlaySx}> <Box
sx={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
pointerEvents: 'none',
}}
>
<Box <Box
component="div" component="div"
onClick={handleTimeRangeClick} onClick={handleTimeRangeClick}
sx={timeRangeBadgeSx} sx={{
position: 'absolute',
top: 6,
left: 40,
fontSize: '11px',
fontWeight: 'bold',
color: 'text.secondary',
cursor: 'pointer',
pointerEvents: 'all',
px: 1,
py: 0.5,
borderRadius: 0.5,
bgcolor: 'rgba(0,0,0,0.05)',
'&:hover': {
bgcolor: 'rgba(0,0,0,0.1)',
},
}}
> >
{getTimeRangeText()} {getTimeRangeText()}
</Box> </Box>
<Box sx={legendsSx}> <Box
<Box sx={legendSx.up}> sx={{
position: 'absolute',
top: 6,
right: 8,
display: 'flex',
flexDirection: 'column',
gap: 0.5,
}}
>
<Box
sx={{
fontSize: '11px',
fontWeight: 'bold',
color: colors.up,
textAlign: 'right',
}}
>
{t('home.components.traffic.legends.upload')} {t('home.components.traffic.legends.upload')}
</Box> </Box>
<Box sx={legendSx.down}> <Box
sx={{
fontSize: '11px',
fontWeight: 'bold',
color: colors.down,
textAlign: 'right',
}}
>
{t('home.components.traffic.legends.download')} {t('home.components.traffic.legends.download')}
</Box> </Box>
</Box> </Box>
<Box sx={chartStyleHintSx}> <Box
sx={{
position: 'absolute',
bottom: 6,
right: 8,
fontSize: '10px',
color: 'text.disabled',
opacity: 0.7,
}}
>
{t( {t(
chartStyle === 'bezier' chartStyle === 'bezier'
? 'home.components.traffic.chartStyles.smooth' ? 'home.components.traffic.chartStyles.smooth'
@@ -1132,10 +1086,20 @@ export const EnhancedCanvasTrafficGraph = memo(
)} )}
</Box> </Box>
<Box sx={diagnosticsSx}> <Box
sx={{
position: 'absolute',
bottom: 6,
left: 8,
fontSize: '9px',
color: 'text.disabled',
opacity: 0.6,
lineHeight: 1.2,
}}
>
{t('home.components.traffic.diagnostics', { {t('home.components.traffic.diagnostics', {
points: badgeStats.points, points: displayData.length,
compressed: badgeStats.compressed, compressed: samplerStats.compressedBufferSize,
fps: GRAPH_CONFIG.targetFPS, fps: GRAPH_CONFIG.targetFPS,
})} })}
</Box> </Box>
@@ -1163,9 +1127,15 @@ export const EnhancedCanvasTrafficGraph = memo(
whiteSpace: 'nowrap', whiteSpace: 'nowrap',
}} }}
> >
<Box sx={tooltipTimeSx}>{tooltipData.timestamp}</Box> <Box sx={{ color: 'text.secondary', mb: 0.2 }}>
<Box sx={tooltipUpSx}>↑ {tooltipData.upSpeed}</Box> {tooltipData.timestamp}
<Box sx={tooltipDownSx}>↓ {tooltipData.downSpeed}</Box> </Box>
<Box sx={{ color: 'secondary.main', fontWeight: 500 }}>
↑ {tooltipData.upSpeed}
</Box>
<Box sx={{ color: 'primary.main', fontWeight: 500 }}>
↓ {tooltipData.downSpeed}
</Box>
</Box> </Box>
)} )}
</Box> </Box>
+6 -15
View File
@@ -131,15 +131,6 @@ const CompactStatCard = memo(
// 添加显示名称 // 添加显示名称
CompactStatCard.displayName = 'CompactStatCard' CompactStatCard.displayName = 'CompactStatCard'
// Element identity is stable, so CompactStatCard's memo comparison holds
// across per-second parsedData updates.
const uploadSpeedIcon = <ArrowUpwardRounded fontSize="small" />
const downloadSpeedIcon = <ArrowDownwardRounded fontSize="small" />
const activeConnectionsIcon = <LinkRounded fontSize="small" />
const uploadedIcon = <CloudUploadRounded fontSize="small" />
const downloadedIcon = <CloudDownloadRounded fontSize="small" />
const memoryUsageIcon = <MemoryRounded fontSize="small" />
const fallbackSx = { const fallbackSx = {
p: 2, p: 2,
minHeight: 200, minHeight: 200,
@@ -261,35 +252,35 @@ export const EnhancedTrafficStats = () => {
const statCards = useMemo(() => { const statCards = useMemo(() => {
const cards: StatCardProps[] = [ const cards: StatCardProps[] = [
{ {
icon: uploadSpeedIcon, icon: <ArrowUpwardRounded fontSize="small" />,
title: t('home.components.traffic.metrics.uploadSpeed'), title: t('home.components.traffic.metrics.uploadSpeed'),
value: parsedData.up, value: parsedData.up,
unit: `${parsedData.upUnit}/s`, unit: `${parsedData.upUnit}/s`,
color: 'secondary' as const, color: 'secondary' as const,
}, },
{ {
icon: downloadSpeedIcon, icon: <ArrowDownwardRounded fontSize="small" />,
title: t('home.components.traffic.metrics.downloadSpeed'), title: t('home.components.traffic.metrics.downloadSpeed'),
value: parsedData.down, value: parsedData.down,
unit: `${parsedData.downUnit}/s`, unit: `${parsedData.downUnit}/s`,
color: 'primary' as const, color: 'primary' as const,
}, },
{ {
icon: activeConnectionsIcon, icon: <LinkRounded fontSize="small" />,
title: t('home.components.traffic.metrics.activeConnections'), title: t('home.components.traffic.metrics.activeConnections'),
value: parsedData.connectionsCount, value: parsedData.connectionsCount,
unit: '', unit: '',
color: 'success' as const, color: 'success' as const,
}, },
{ {
icon: uploadedIcon, icon: <CloudUploadRounded fontSize="small" />,
title: t('shared.labels.uploaded'), title: t('shared.labels.uploaded'),
value: parsedData.uploadTotal, value: parsedData.uploadTotal,
unit: parsedData.uploadTotalUnit, unit: parsedData.uploadTotalUnit,
color: 'secondary' as const, color: 'secondary' as const,
}, },
{ {
icon: downloadedIcon, icon: <CloudDownloadRounded fontSize="small" />,
title: t('shared.labels.downloaded'), title: t('shared.labels.downloaded'),
value: parsedData.downloadTotal, value: parsedData.downloadTotal,
unit: parsedData.downloadTotalUnit, unit: parsedData.downloadTotalUnit,
@@ -299,7 +290,7 @@ export const EnhancedTrafficStats = () => {
if (displayMemory) { if (displayMemory) {
cards.push({ cards.push({
icon: memoryUsageIcon, icon: <MemoryRounded fontSize="small" />,
title: t('home.components.traffic.metrics.memoryUsage'), title: t('home.components.traffic.metrics.memoryUsage'),
value: parsedData.inuse, value: parsedData.inuse,
unit: parsedData.inuseUnit, unit: parsedData.inuseUnit,
+36 -34
View File
@@ -42,39 +42,6 @@ const TrafficUnavailableFallback = () => {
) )
} }
// Stable identities keep the emotion sx cache effective across the ~1Hz
// traffic-driven re-renders of LayoutTraffic.
const boxStyle: Pick<BoxProps, 'sx'> = {
sx: {
display: 'flex',
alignItems: 'center',
whiteSpace: 'nowrap',
},
}
const memoryBoxStyle: Pick<BoxProps, 'sx'> = {
sx: {
...boxStyle.sx,
cursor: 'auto',
},
}
const iconStyle: Pick<SvgIconProps, 'sx'> = {
sx: { mr: '8px', fontSize: 16 },
}
const valStyle: Pick<TypographyProps, 'component' | 'sx'> = {
component: 'span',
sx: { flex: '1 1 56px', userSelect: 'none', textAlign: 'center' },
}
const unitStyle: Pick<TypographyProps, 'component' | 'color' | 'sx'> = {
component: 'span',
color: 'grey.500',
sx: {
flex: '0 1 27px',
userSelect: 'none',
fontSize: '12px',
textAlign: 'right',
},
}
export const LayoutTraffic = () => { export const LayoutTraffic = () => {
const { t } = useTranslation() const { t } = useTranslation()
const { verge } = useVerge() const { verge } = useVerge()
@@ -107,6 +74,31 @@ export const LayoutTraffic = () => {
const [down, downUnit] = parseTraffic(traffic?.down || 0) const [down, downUnit] = parseTraffic(traffic?.down || 0)
const [inuse, inuseUnit] = parseTraffic(memory?.inuse || 0) const [inuse, inuseUnit] = parseTraffic(memory?.inuse || 0)
const boxStyle: Pick<BoxProps, 'sx'> = {
sx: {
display: 'flex',
alignItems: 'center',
whiteSpace: 'nowrap',
},
}
const iconStyle: Pick<SvgIconProps, 'sx'> = {
sx: { mr: '8px', fontSize: 16 },
}
const valStyle: Pick<TypographyProps, 'component' | 'sx'> = {
component: 'span',
sx: { flex: '1 1 56px', userSelect: 'none', textAlign: 'center' },
}
const unitStyle: Pick<TypographyProps, 'component' | 'color' | 'sx'> = {
component: 'span',
color: 'grey.500',
sx: {
flex: '0 1 27px',
userSelect: 'none',
fontSize: '12px',
textAlign: 'right',
},
}
return ( return (
<ErrorBoundary <ErrorBoundary
FallbackComponent={TrafficUnavailableFallback} FallbackComponent={TrafficUnavailableFallback}
@@ -128,6 +120,9 @@ export const LayoutTraffic = () => {
<Box <Box
title={`${t('home.components.traffic.metrics.uploadSpeed')}`} title={`${t('home.components.traffic.metrics.uploadSpeed')}`}
{...boxStyle} {...boxStyle}
sx={{
...boxStyle.sx,
}}
> >
<ArrowUpwardRounded <ArrowUpwardRounded
{...iconStyle} {...iconStyle}
@@ -142,6 +137,9 @@ export const LayoutTraffic = () => {
<Box <Box
title={`${t('home.components.traffic.metrics.downloadSpeed')}`} title={`${t('home.components.traffic.metrics.downloadSpeed')}`}
{...boxStyle} {...boxStyle}
sx={{
...boxStyle.sx,
}}
> >
<ArrowDownwardRounded <ArrowDownwardRounded
{...iconStyle} {...iconStyle}
@@ -156,7 +154,11 @@ export const LayoutTraffic = () => {
{displayMemory && ( {displayMemory && (
<Box <Box
title={`${t('home.components.traffic.metrics.memoryUsage')} `} title={`${t('home.components.traffic.metrics.memoryUsage')} `}
{...memoryBoxStyle} {...boxStyle}
sx={{
...boxStyle.sx,
cursor: 'auto',
}}
color={'disabled'} color={'disabled'}
> >
<MemoryRounded {...iconStyle} /> <MemoryRounded {...iconStyle} />
+8 -21
View File
@@ -2,7 +2,6 @@ import { styled, Box } from '@mui/material'
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import type { SearchState } from '@/components/base' import type { SearchState } from '@/components/base'
import { buildRegex } from '@/utils/search-matcher'
const Item = styled(Box)(({ theme: { palette, typography } }) => ({ const Item = styled(Box)(({ theme: { palette, typography } }) => ({
padding: '8px 0', padding: '8px 0',
@@ -48,15 +47,11 @@ interface Props {
searchState?: SearchState searchState?: SearchState
} }
// Compiling per row multiplied by high-frequency log appends; searchState is const LogItem = ({ value, searchState }: Props) => {
// React state, so identity reuse is safe until the search inputs change. const renderHighlightText = (text: string) => {
let highlightRegexCache: { state: SearchState; regex: RegExp | null } | null = if (!searchState?.text.trim()) return text
null
const getHighlightRegex = (searchState: SearchState): RegExp | null => {
if (highlightRegexCache?.state === searchState)
return highlightRegexCache.regex
try {
const searchText = searchState.text const searchText = searchState.text
let pattern: string let pattern: string
@@ -73,18 +68,7 @@ const getHighlightRegex = (searchState: SearchState): RegExp | null => {
} }
const flags = searchState.matchCase ? 'g' : 'gi' const flags = searchState.matchCase ? 'g' : 'gi'
const regex = buildRegex(pattern, flags) const regex = new RegExp(pattern, flags)
highlightRegexCache = { state: searchState, regex }
return regex
}
const LogItem = ({ value, searchState }: Props) => {
const renderHighlightText = (text: string) => {
if (!searchState?.text.trim()) return text
const regex = getHighlightRegex(searchState)
if (!regex) return text
const elements: ReactNode[] = [] const elements: ReactNode[] = []
let lastIndex = 0 let lastIndex = 0
let match: RegExpExecArray | null let match: RegExpExecArray | null
@@ -116,6 +100,9 @@ const LogItem = ({ value, searchState }: Props) => {
} }
return elements.length ? elements : text return elements.length ? elements : text
} catch {
return text
}
} }
return ( return (
+25 -47
View File
@@ -60,23 +60,6 @@ const ProxyGroupsChain = lazy(() =>
})), })),
) )
const SCROLL_POSITIONS_KEY = 'proxy-scroll-positions'
type ScrollPositions = Record<string, number>
let scrollPositionsCache: ScrollPositions | undefined
// Scroll handling runs per frame and is throttled to 500ms writes; keep the
// parsed object so saves do not re-read and re-parse localStorage each time.
const readScrollPositions = (): ScrollPositions | undefined => {
if (scrollPositionsCache) return scrollPositionsCache
try {
const raw = localStorage.getItem(SCROLL_POSITIONS_KEY)
if (raw) scrollPositionsCache = JSON.parse(raw) as ScrollPositions
} catch (e) {
console.error('Error restoring scroll position:', e)
}
return scrollPositionsCache
}
function useStableCallback<T extends (...args: any[]) => any>(fn: T): T { function useStableCallback<T extends (...args: any[]) => any>(fn: T): T {
const ref = useRef(fn) const ref = useRef(fn)
ref.current = fn ref.current = fn
@@ -167,12 +150,13 @@ function useProxyRenderState(
const saveScrollPosition = useCallback( const saveScrollPosition = useCallback(
(scrollTop: number) => { (scrollTop: number) => {
const scrollPositions = readScrollPositions() ?? {} const scrollPositions = localStorage.getItem('proxy-scroll-positions')
? JSON.parse(localStorage.getItem('proxy-scroll-positions') ?? '{}')
: {}
scrollPositions[scrollPositionKey] = scrollTop scrollPositions[scrollPositionKey] = scrollTop
scrollPositionsCache = scrollPositions
try { try {
localStorage.setItem( localStorage.setItem(
SCROLL_POSITIONS_KEY, 'proxy-scroll-positions',
JSON.stringify(scrollPositions), JSON.stringify(scrollPositions),
) )
} catch (e) { } catch (e) {
@@ -183,11 +167,16 @@ function useProxyRenderState(
) )
const getScrollPosition = useCallback(() => { const getScrollPosition = useCallback(() => {
const savedPositions = readScrollPositions() try {
const savedPositions = localStorage.getItem('proxy-scroll-positions')
if (savedPositions) { if (savedPositions) {
const savedPosition = savedPositions[scrollPositionKey] const positions = JSON.parse(savedPositions)
const savedPosition = positions[scrollPositionKey]
return savedPosition ?? 0 return savedPosition ?? 0
} }
} catch (e) {
console.error('Error restoring scroll position:', e)
}
}, [scrollPositionKey]) }, [scrollPositionKey])
return { return {
@@ -251,13 +240,9 @@ function ChainProxyGroups(props: {
const rangeExtractor = useCallback( const rangeExtractor = useCallback(
(range: Parameters<typeof defaultRangeExtractor>[0]) => { (range: Parameters<typeof defaultRangeExtractor>[0]) => {
let activeStickyIndex: number | undefined const activeStickyIndex = [...stickyGroupIndexes]
for (let i = stickyGroupIndexes.length - 1; i >= 0; i--) { .reverse()
if (stickyGroupIndexes[i] <= range.startIndex) { .find((index) => index <= range.startIndex)
activeStickyIndex = stickyGroupIndexes[i]
break
}
}
activeStickyIndexRef.current = activeStickyIndex ?? null activeStickyIndexRef.current = activeStickyIndex ?? null
const indexes = defaultRangeExtractor(range) const indexes = defaultRangeExtractor(range)
@@ -484,14 +469,12 @@ function NormalProxyGroups(props: { mode: string }) {
} }
}, [handleScroll]) }, [handleScroll])
const onSelectionError = useCallback( const { select } = useProxySelection({
(error: unknown) => { onError: (error) => {
console.error('代理切换失败', error) console.error('代理切换失败', error)
onProxies() onProxies()
}, },
[onProxies], })
)
const { select } = useProxySelection({ onError: onSelectionError })
const handleChangeProxy = useCallback( const handleChangeProxy = useCallback(
(group: ProxyGroupView, member: ResolvedProxyMember) => { (group: ProxyGroupView, member: ResolvedProxyMember) => {
@@ -586,17 +569,6 @@ function NormalProxyGroups(props: { mode: string }) {
[renderList], [renderList],
) )
const onStickyHeadState = useCallback(
async (groupName: string, patch: Partial<HeadState>) => {
if (patch.filterText !== undefined) {
handleGroupLocationByName(groupName)
await stickyListRef.current?.waitForScrollEnd()
}
onHeadState(groupName, patch)
},
[handleGroupLocationByName, onHeadState],
)
const renderGroupItem = useCallback( const renderGroupItem = useCallback(
(item: IRenderItem, _index: number, stickyed: boolean) => ( (item: IRenderItem, _index: number, stickyed: boolean) => (
<ProxyRender <ProxyRender
@@ -604,7 +576,13 @@ function NormalProxyGroups(props: { mode: string }) {
stickyed={stickyed} stickyed={stickyed}
onLocation={handleLocation} onLocation={handleLocation}
onCheckAll={handleCheckAll} onCheckAll={handleCheckAll}
onHeadState={stickyed ? onStickyHeadState : onHeadState} onHeadState={async (groupName, patch) => {
if (stickyed && patch.filterText !== undefined) {
handleGroupLocationByName(groupName)
await stickyListRef.current?.waitForScrollEnd()
}
onHeadState(groupName, patch)
}}
onChangeProxy={handleChangeProxy} onChangeProxy={handleChangeProxy}
onGroupToggle={handleGroupToggle} onGroupToggle={handleGroupToggle}
/> />
@@ -615,7 +593,7 @@ function NormalProxyGroups(props: { mode: string }) {
onHeadState, onHeadState,
handleLocation, handleLocation,
handleGroupToggle, handleGroupToggle,
onStickyHeadState, handleGroupLocationByName,
], ],
) )
+43 -47
View File
@@ -43,7 +43,7 @@ interface RenderProps {
onGroupToggle?: (group: IRenderItem['group']) => void onGroupToggle?: (group: IRenderItem['group']) => void
} }
const ProxyGroupHeader = (props: RenderProps) => { export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
const { t } = useTranslation() const { t } = useTranslation()
const { const {
item, item,
@@ -51,9 +51,11 @@ const ProxyGroupHeader = (props: RenderProps) => {
onLocation, onLocation,
onCheckAll, onCheckAll,
onHeadState, onHeadState,
onChangeProxy,
onGroupToggle, onGroupToggle,
isChainMode: _ = false,
} = props } = props
const { group, headState } = item const { type, group, headState, member, memberCol } = item
const { verge } = useVerge() const { verge } = useVerge()
const enable_group_icon = verge?.enable_group_icon ?? true const enable_group_icon = verge?.enable_group_icon ?? true
const toolsOnLeft = verge?.proxy_group_tools_position === 'left' const toolsOnLeft = verge?.proxy_group_tools_position === 'left'
@@ -67,6 +69,25 @@ const ProxyGroupHeader = (props: RenderProps) => {
enabled: enable_group_icon, enabled: enable_group_icon,
}) })
const showType = headState?.showType
const memberColItemsMemo = useMemo(() => {
if (type !== 4 || !memberCol) {
return null
}
return memberCol.map((occurrence) => (
<ProxyItemMini
key={`${item.key}-${occurrence.memberIndex}`}
group={group}
member={occurrence.member}
selected={group.now === occurrence.member.ref.name}
showType={showType}
onClick={(nextMember) => onChangeProxy(group, nextMember)}
/>
))
}, [type, memberCol, item.key, group, showType, onChangeProxy])
if (type === 0) {
const nameBlock = ( const nameBlock = (
<ProxyGroupHeaderBlock <ProxyGroupHeaderBlock
key="name" key="name"
@@ -154,7 +175,8 @@ const ProxyGroupHeader = (props: RenderProps) => {
label={`${group.members.length}`} label={`${group.members.length}`}
sx={{ sx={{
mr: toolsOnLeft ? 0 : 1, mr: toolsOnLeft ? 0 : 1,
backgroundColor: (theme) => alpha(theme.palette.primary.main, 0.1), backgroundColor: (theme) =>
alpha(theme.palette.primary.main, 0.1),
color: (theme) => theme.palette.primary.main, color: (theme) => theme.palette.primary.main,
}} }}
/> />
@@ -219,49 +241,7 @@ const ProxyGroupHeader = (props: RenderProps) => {
</ListItemButton> </ListItemButton>
</div> </div>
) )
} }
const ProxyEmptyRow = () => {
const { t } = useTranslation()
return (
<Box
sx={{
py: 2,
pl: 0,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
}}
>
<InboxRounded sx={{ fontSize: '2.5em', color: 'inherit' }} />
<Typography sx={{ color: 'inherit' }}>
{t('proxies.page.empty.noProxies')}
</Typography>
</Box>
)
}
export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
const { item, onLocation, onCheckAll, onHeadState, onChangeProxy } = props
const { type, group, headState, member, memberCol } = item
const showType = headState?.showType
const memberColItemsMemo = useMemo(() => {
if (type !== 4 || !memberCol) return null
return memberCol.map((occurrence) => (
<ProxyItemMini
key={`${item.key}-${occurrence.memberIndex}`}
group={group}
member={occurrence.member}
selected={group.now === occurrence.member.ref.name}
showType={showType}
onClick={(nextMember) => onChangeProxy(group, nextMember)}
/>
))
}, [type, memberCol, item.key, group, showType, onChangeProxy])
if (type === 0) return <ProxyGroupHeader {...props} />
if (type === 1) { if (type === 1) {
return ( return (
@@ -291,7 +271,23 @@ export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
} }
if (type === 3) { if (type === 3) {
return <ProxyEmptyRow /> return (
<Box
sx={{
py: 2,
pl: 0,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
}}
>
<InboxRounded sx={{ fontSize: '2.5em', color: 'inherit' }} />
<Typography sx={{ color: 'inherit' }}>
{t('proxies.page.empty.noProxies')}
</Typography>
</Box>
)
} }
if (type === 4) { if (type === 4) {
-3
View File
@@ -29,9 +29,6 @@ export function filterSort(
const regex1 = /delay([=<>])(\d+|timeout|error)/i const regex1 = /delay([=<>])(\d+|timeout|error)/i
const regex2 = /type=(.*)/i const regex2 = /type=(.*)/i
export const isDelayFilter = (filterText: string) =>
regex1.test(filterText.trim())
function filterProxies( function filterProxies(
proxies: ResolvedMemberOccurrence[], proxies: ResolvedMemberOccurrence[],
groupName: string, groupName: string,
+31 -112
View File
@@ -17,7 +17,7 @@ import {
} from '@/types/proxy-view' } from '@/types/proxy-view'
import { debugLog } from '@/utils/debug' import { debugLog } from '@/utils/debug'
import { filterSort, isDelayFilter } from './use-filter-sort' import { filterSort } from './use-filter-sort'
import { import {
DEFAULT_STATE, DEFAULT_STATE,
useHeadStateNew, useHeadStateNew,
@@ -60,15 +60,14 @@ export const hasRenderableItems = (
): boolean => renderList.some((item) => item.type !== 0 || !item.group.hidden) ): boolean => renderList.some((item) => item.type !== 0 || !item.group.hidden)
type GroupCache = { type GroupCache = {
group: ProxyGroupView now: string | undefined
members: ProxyGroupView['members']
headState: HeadState headState: HeadState
col: number col: number
latencyTimeout: number | undefined latencyTimeout: number | undefined
/// This group's own delays. Compared by identity so that a test settling in one group /// This group's own delays. Compared by identity so that a test settling in one group
/// does not throw away every other group's sorted order. /// does not throw away every other group's sorted order.
delays: DelaySnapshot | undefined delays: DelaySnapshot | undefined
occurrences: ResolvedMemberOccurrence[] | undefined
projected: ResolvedMemberOccurrence[] | undefined
items: IRenderItem[] items: IRenderItem[]
} }
@@ -223,55 +222,19 @@ export const useRenderList = (
return current?.kind === 'group' ? [global, current.group] : [global] return current?.kind === 'group' ? [global, current.group] : [global]
}, [mode, proxyView]) }, [mode, proxyView])
const repeatedNameGroups = useMemo(() => { // Every group this list draws, so a test settling in any of them re-sorts that group.
const repeated = new Set<string>()
if (isChainMode) return repeated
for (const group of renderGroups) {
const names = new Set<string>()
if (
group.members.some(({ name }) => {
if (names.has(name)) return true
names.add(name)
return false
})
) {
repeated.add(group.name)
}
}
return repeated
}, [isChainMode, renderGroups])
// Rows own delay updates unless repeated names share the current item listener.
const renderedGroupNames = useMemo(() => { const renderedGroupNames = useMemo(() => {
if (!proxyView || isChainMode) return [] if (!proxyView) return []
return renderGroups if (isChainMode)
.filter((group) => { return selectedGroup ? [selectedGroup] : [CHAIN_DELAY_GROUP]
const state = headStates[group.name] || DEFAULT_STATE return renderGroups.map(({ name }) => name)
return ( }, [isChainMode, proxyView, renderGroups, selectedGroup])
(state.open || group === proxyView.global) &&
(state.sortType === 1 ||
isDelayFilter(state.filterText) ||
repeatedNameGroups.has(group.name))
)
})
.map(({ name }) => name)
}, [headStates, isChainMode, proxyView, renderGroups, repeatedNameGroups])
const groupDelays = useGroupsDelays(renderedGroupNames) const groupDelays = useGroupsDelays(renderedGroupNames)
const groupCacheRef = useRef<Map<string, GroupCache> | null>(null) const groupCacheRef = useRef<Map<string, GroupCache>>(new Map())
const cachedViewRef = useRef(proxyView)
const prevListRef = useRef<IRenderItem[]>([]) const prevListRef = useRef<IRenderItem[]>([])
const prevGroupItemsRef = useRef<IRenderItem[][]>([])
const prevModeRef = useRef(mode)
const renderList = useMemo<IRenderItem[]>(() => { const renderList = useMemo<IRenderItem[]>(() => {
const cache = (groupCacheRef.current ??= new Map())
if (cachedViewRef.current !== proxyView) {
cache.clear()
prevGroupItemsRef.current = []
prevListRef.current = []
cachedViewRef.current = proxyView
}
if (!proxyView) return [] if (!proxyView) return []
if (isChainMode) { if (isChainMode) {
@@ -306,13 +269,16 @@ export const useRenderList = (
})) }))
} }
const groupItems = renderGroups.map((group) => { const cache = groupCacheRef.current
const retList = renderGroups.flatMap((group) => {
const isFlat = group === proxyView.global const isFlat = group === proxyView.global
const headState = headStates[group.name] || DEFAULT_STATE const headState = headStates[group.name] || DEFAULT_STATE
const cached = cache.get(group.name) const cached = cache.get(group.name)
if ( if (
cached && cached &&
cached.group === group && cached.now === group.now &&
cached.members === group.members &&
cached.headState === headState && cached.headState === headState &&
cached.col === col && cached.col === col &&
cached.latencyTimeout === latencyTimeout && cached.latencyTimeout === latencyTimeout &&
@@ -321,51 +287,6 @@ export const useRenderList = (
return cached.items return cached.items
} }
// Duplicate names share one item listener until the delay-store fix lands.
const refreshRepeated =
repeatedNameGroups.has(group.name) &&
cached?.delays !== groupDelays.get(group.name)
let resolved =
cached?.group === group && !refreshRepeated
? cached.occurrences
: undefined
let projected: ResolvedMemberOccurrence[] | undefined
if (headState.open || isFlat) {
resolved ??= resolveOccurrences(proxyView, group)
projected = filterSort(
resolved,
group.name,
headState.filterText,
headState.sortType,
latencyTimeout!,
{
matchCase: headState.filterMatchCase,
matchWholeWord: headState.filterMatchWholeWord,
useRegularExpression: headState.filterUseRegularExpression,
},
)
// Repeated names still need new member props while item listeners share a key.
if (
!refreshRepeated &&
cached?.group === group &&
cached.headState === headState &&
cached.col === col &&
cached.projected?.length === projected.length &&
projected.every(
(member, index) => member === cached.projected?.[index],
)
) {
cache.set(group.name, {
...cached,
latencyTimeout,
delays: groupDelays.get(group.name),
})
return cached.items
}
} else {
resolved = undefined
}
const ret: IRenderItem[] = [ const ret: IRenderItem[] = [
isFlat isFlat
? { type: 1, key: `head-${group.name}`, group, headState } ? { type: 1, key: `head-${group.name}`, group, headState }
@@ -378,8 +299,20 @@ export const useRenderList = (
testUrl: group.testUrl!, testUrl: group.testUrl!,
}, },
] ]
if (projected) {
const occurrences = projected if (headState.open || isFlat) {
const occurrences = filterSort(
resolveOccurrences(proxyView, group),
group.name,
headState.filterText,
headState.sortType,
latencyTimeout!,
{
matchCase: headState.filterMatchCase,
matchWholeWord: headState.filterMatchWholeWord,
useRegularExpression: headState.filterUseRegularExpression,
},
)
if (occurrences.length === 0) { if (occurrences.length === 0) {
ret.push({ type: 3, key: `empty-${group.name}`, group, headState }) ret.push({ type: 3, key: `empty-${group.name}`, group, headState })
} else if (col > 1) { } else if (col > 1) {
@@ -407,30 +340,17 @@ export const useRenderList = (
} }
cache.set(group.name, { cache.set(group.name, {
group, now: group.now!,
members: group.members,
headState, headState,
col, col,
latencyTimeout: latencyTimeout!, latencyTimeout: latencyTimeout!,
delays: groupDelays.get(group.name), delays: groupDelays.get(group.name),
occurrences: resolved,
projected,
items: ret, items: ret,
}) })
return ret return ret
}) })
if (
prevModeRef.current === mode &&
prevGroupItemsRef.current.length === groupItems.length &&
groupItems.every(
(items, index) => items === prevGroupItemsRef.current[index],
)
) {
return prevListRef.current
}
prevModeRef.current = mode
prevGroupItemsRef.current = groupItems
const retList = groupItems.flat()
const filtered = const filtered =
mode === 'rule' ? retList.filter((item) => !item.group.hidden) : retList mode === 'rule' ? retList.filter((item) => !item.group.hidden) : retList
if ( if (
@@ -451,7 +371,6 @@ export const useRenderList = (
mode, mode,
proxyView, proxyView,
renderGroups, renderGroups,
repeatedNameGroups,
selectedGroup, selectedGroup,
]) ])
+3 -4
View File
@@ -16,8 +16,7 @@ const COLOR = [
] ]
interface Props { interface Props {
value: Rule value: Rule & { lineNo: number }
lineNo: number
} }
const parseColor = (text: string) => { const parseColor = (text: string) => {
@@ -32,7 +31,7 @@ const parseColor = (text: string) => {
} }
const RuleItem = (props: Props) => { const RuleItem = (props: Props) => {
const { value, lineNo } = props const { value } = props
return ( return (
<Item sx={{ borderBottom: '1px solid var(--divider-color)' }}> <Item sx={{ borderBottom: '1px solid var(--divider-color)' }}>
@@ -41,7 +40,7 @@ const RuleItem = (props: Props) => {
variant="body2" variant="body2"
sx={{ lineHeight: 2, minWidth: 30, mr: 2.25, textAlign: 'center' }} sx={{ lineHeight: 2, minWidth: 30, mr: 2.25, textAlign: 'center' }}
> >
{lineNo} {value.lineNo}
</Typography> </Typography>
<Box sx={{ userSelect: 'text' }}> <Box sx={{ userSelect: 'text' }}>
@@ -22,7 +22,6 @@ const buildInitialValues = (verge?: IVergeConfig | null) => ({
appLogMaxSize: verge?.app_log_max_size ?? 128, appLogMaxSize: verge?.app_log_max_size ?? 128,
appLogMaxCount: verge?.app_log_max_count ?? 8, appLogMaxCount: verge?.app_log_max_count ?? 8,
autoCloseConnection: verge?.auto_close_connection ?? true, autoCloseConnection: verge?.auto_close_connection ?? true,
autoSwitchSelectorGroup: verge?.auto_switch_selector_group ?? true,
autoCheckUpdate: verge?.auto_check_update ?? true, autoCheckUpdate: verge?.auto_check_update ?? true,
enableBuiltinEnhanced: verge?.enable_builtin_enhanced ?? true, enableBuiltinEnhanced: verge?.enable_builtin_enhanced ?? true,
proxyLayoutColumn: verge?.proxy_layout_column || 6, proxyLayoutColumn: verge?.proxy_layout_column || 6,
@@ -56,7 +55,6 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
app_log_max_size: values.appLogMaxSize, app_log_max_size: values.appLogMaxSize,
app_log_max_count: values.appLogMaxCount, app_log_max_count: values.appLogMaxCount,
auto_close_connection: values.autoCloseConnection, auto_close_connection: values.autoCloseConnection,
auto_switch_selector_group: values.autoSwitchSelectorGroup,
auto_check_update: values.autoCheckUpdate, auto_check_update: values.autoCheckUpdate,
enable_builtin_enhanced: values.enableBuiltinEnhanced, enable_builtin_enhanced: values.enableBuiltinEnhanced,
proxy_layout_column: values.proxyLayoutColumn, proxy_layout_column: values.proxyLayoutColumn,
@@ -204,28 +202,6 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
/> />
</ListItem> </ListItem>
<ListItem
data-setting-target="settings.modals.misc.fields.autoSwitchSelectorGroup"
sx={{ padding: '5px 2px' }}
>
<ListItemText
primary={t('settings.modals.misc.fields.autoSwitchSelectorGroup')}
sx={{ maxWidth: 'fit-content' }}
/>
<TooltipIcon
title={t('settings.modals.misc.tooltips.autoSwitchSelectorGroup')}
sx={{ opacity: '0.7' }}
/>
<Switch
edge="end"
checked={values.autoSwitchSelectorGroup}
onChange={(_, c) =>
setValues((v) => ({ ...v, autoSwitchSelectorGroup: c }))
}
sx={{ marginLeft: 'auto' }}
/>
</ListItem>
<ListItem <ListItem
data-setting-target="settings.modals.misc.fields.autoCheckUpdate" data-setting-target="settings.modals.misc.fields.autoCheckUpdate"
sx={{ padding: '5px 2px' }} sx={{ padding: '5px 2px' }}
+1 -8
View File
@@ -62,14 +62,7 @@ export const SettingItem: React.FC<ItemProps> = ({
</ListItemButton> </ListItemButton>
</ListItem> </ListItem>
) : ( ) : (
<ListItem <ListItem data-setting-target={searchTarget} sx={{ pt: '5px', pb: '5px' }}>
data-setting-target={searchTarget}
sx={{
pt: '5px',
pb: '5px',
'&:hover': { bgcolor: 'action.hover' },
}}
>
<ListItemText primary={primary} secondary={secondary} /> <ListItemText primary={primary} secondary={secondary} />
{children} {children}
</ListItem> </ListItem>
@@ -480,8 +480,6 @@ const settingsCatalog: readonly SettingEntry[] = [
'settings.modals.misc.fields.appLogMaxCount': 'app log max count', 'settings.modals.misc.fields.appLogMaxCount': 'app log max count',
'settings.modals.misc.fields.autoCloseConnections': 'settings.modals.misc.fields.autoCloseConnections':
'auto close connections', 'auto close connections',
'settings.modals.misc.fields.autoSwitchSelectorGroup':
'auto switch select group',
'settings.modals.misc.fields.autoCheckUpdate': 'auto check update', 'settings.modals.misc.fields.autoCheckUpdate': 'auto check update',
'settings.modals.misc.fields.enableBuiltinEnhanced': 'settings.modals.misc.fields.enableBuiltinEnhanced':
'enable builtin enhanced', 'enable builtin enhanced',
+11 -37
View File
@@ -150,49 +150,25 @@ const mergeConnectionSnapshot = (
const nextConnections = payload.connections ?? [] const nextConnections = payload.connections ?? []
const previousActive = previous.activeConnections ?? [] const previousActive = previous.activeConnections ?? []
const previousClosed = previous.closedConnections ?? [] const previousClosed = previous.closedConnections ?? []
const sameOrder = const previousActiveById = new Map<string, IConnectionsItem>()
nextConnections.length === previousActive.length &&
nextConnections.every(
(connection, i) => connection.id === previousActive[i].id,
)
let previousActiveById: Map<string, IConnectionsItem> | undefined
if (!sameOrder) {
previousActiveById = new Map()
for (let i = 0; i < previousActive.length; i++) { for (let i = 0; i < previousActive.length; i++) {
const previousConnection = previousActive[i] const previousConnection = previousActive[i]
previousActiveById.set(previousConnection.id, previousConnection) previousActiveById.set(previousConnection.id, previousConnection)
} }
}
let activeConnections = sameOrder ? previousActive : [] const activeConnections: IConnectionsItem[] = []
for (let i = 0; i < nextConnections.length; i++) { for (let i = 0; i < nextConnections.length; i++) {
const connection = nextConnections[i] const connection = nextConnections[i]
const previousConnection = sameOrder const previousConnection = previousActiveById.get(connection.id)
? previousActive[i] if (previousConnection) previousActiveById.delete(connection.id)
: previousActiveById?.get(connection.id) activeConnections.push(normalizeConnection(connection, previousConnection))
previousActiveById?.delete(connection.id)
const normalized = normalizeConnection(connection, previousConnection)
if (activeConnections[i] === normalized) continue
if (activeConnections === previousActive) {
activeConnections = previousActive.slice()
}
activeConnections[i] = normalized
} }
const uploadTotal = payload.uploadTotal ?? 0 if (previousActiveById.size === 0) {
const downloadTotal = payload.downloadTotal ?? 0
if (!previousActiveById?.size) {
if (
activeConnections === previousActive &&
uploadTotal === previous.uploadTotal &&
downloadTotal === previous.downloadTotal
) {
return previous
}
return { return {
uploadTotal, uploadTotal: payload.uploadTotal ?? 0,
downloadTotal, downloadTotal: payload.downloadTotal ?? 0,
activeConnections, activeConnections,
closedConnections: previousClosed, closedConnections: previousClosed,
} }
@@ -222,8 +198,8 @@ const mergeConnectionSnapshot = (
} }
return { return {
uploadTotal, uploadTotal: payload.uploadTotal ?? 0,
downloadTotal, downloadTotal: payload.downloadTotal ?? 0,
activeConnections, activeConnections,
closedConnections, closedConnections,
} }
@@ -251,9 +227,7 @@ const flushPendingMessage = () => {
lastFlushAt = Date.now() lastFlushAt = Date.now()
const nextData = mergeConnectionSnapshot(payload, connectionData) connectionData = mergeConnectionSnapshot(payload, connectionData)
if (nextData === connectionData) return
connectionData = nextData
notifyConnectionListeners() notifyConnectionListeners()
} }
+9 -17
View File
@@ -1,27 +1,19 @@
import { useCallback, useSyncExternalStore } from 'react' import { useCallback, useSyncExternalStore } from 'react'
import delayManager, { type DelaySnapshot } from '@/services/delay' import delayManager, { type DelaySnapshot } from '@/services/delay'
import type { ResolvedProxyMember } from '@/types/proxy-view'
/** A closed menu observes only its current member, not every settled group delay. */ const NO_DELAYS: DelaySnapshot = { of: () => -1 }
export const useGroupDelays = (
group: string | null, /** Exposes the external delay store to React, updating sort order only after a test settles. */
member: ResolvedProxyMember | undefined, export const useGroupDelays = (group: string | null): DelaySnapshot => {
menuOpen: boolean,
): DelaySnapshot | number => {
const subscribe = useCallback( const subscribe = useCallback(
(onSettle: () => void) => (onSettle: () => void) =>
group ? delayManager.addGroupListener(group, onSettle) : () => {}, group ? delayManager.addGroupListener(group, onSettle) : () => {},
[group], [group],
) )
const read = useCallback( const read = useCallback(
() => () => (group ? delayManager.groupDelays(group) : NO_DELAYS),
group && menuOpen [group],
? delayManager.groupDelays(group)
: group && member
? delayManager.getDelayFix(member, group)
: -1,
[group, member, menuOpen],
) )
return useSyncExternalStore(subscribe, read, read) return useSyncExternalStore(subscribe, read, read)
@@ -31,12 +23,12 @@ export const useGroupDelays = (
export const useGroupsDelays = ( export const useGroupsDelays = (
groups: readonly string[], groups: readonly string[],
): ReadonlyMap<string, DelaySnapshot> => { ): ReadonlyMap<string, DelaySnapshot> => {
// Group membership must remain unambiguous when names contain spaces. // Subscribe by group membership; callers rebuild the array on every render.
const groupKey = JSON.stringify(groups) const groupKey = groups.join(' ')
const subscribe = useCallback( const subscribe = useCallback(
(onSettle: () => void) => { (onSettle: () => void) => {
const names: string[] = JSON.parse(groupKey) const names = groupKey ? groupKey.split(' ') : []
const unsubscribes = names.map((name) => const unsubscribes = names.map((name) =>
delayManager.addGroupListener(name, onSettle), delayManager.addGroupListener(name, onSettle),
) )

Some files were not shown because too many files have changed in this diff Show More