mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-17 17:32:15 +08:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e3084cd34 | ||
|
|
dc71c11ef2 | ||
|
|
1b212f9a28 | ||
|
|
9f7b390cd4 | ||
|
|
0c2de711bc | ||
|
|
6a202e8d00 | ||
|
|
d7ac6b5bca | ||
|
|
65042b8887 | ||
|
|
d1649fcc8d | ||
|
|
368e41f48a |
@@ -0,0 +1,31 @@
|
|||||||
|
# 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,3 +1,29 @@
|
|||||||
|
<!--
|
||||||
|
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
|
||||||
@@ -14,4 +40,6 @@ Why this change solves the problem — the reasoning behind the approach, not a
|
|||||||
|
|
||||||
## Scope
|
## Scope
|
||||||
|
|
||||||
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.
|
Optional: explain necessary changes outside the core fix, PR dependencies, or
|
||||||
|
why added tests are needed. Otherwise remove this section. New tests are not
|
||||||
|
expected by default.
|
||||||
|
|||||||
@@ -5,10 +5,10 @@
|
|||||||
"version": "v9.0.0",
|
"version": "v9.0.0",
|
||||||
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
|
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
|
||||||
},
|
},
|
||||||
"github/gh-aw-actions/setup@v1.2.2": {
|
"github/gh-aw-actions/setup@v1.3.0": {
|
||||||
"repo": "github/gh-aw-actions/setup",
|
"repo": "github/gh-aw-actions/setup",
|
||||||
"version": "v1.2.2",
|
"version": "v1.3.0",
|
||||||
"sha": "53d0749e19424a918acd82b4d140264ce48f2f14"
|
"sha": "8126d6cb07dea9221848de275af8a41474d839ca"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"containers": {
|
"containers": {
|
||||||
@@ -32,6 +32,16 @@
|
|||||||
"digest": "sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2",
|
"digest": "sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2",
|
||||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.28.23@sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2"
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.28.23@sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2"
|
||||||
},
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/agent:0.29.11": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/agent:0.29.11",
|
||||||
|
"digest": "sha256:8774a73c351395b41d2ad0af4ddb4689007c67de3cd08bd9f43bb8a0e300690e",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.11@sha256:8774a73c351395b41d2ad0af4ddb4689007c67de3cd08bd9f43bb8a0e300690e"
|
||||||
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/agent:0.29.14": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/agent:0.29.14",
|
||||||
|
"digest": "sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa"
|
||||||
|
},
|
||||||
"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13": {
|
"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13": {
|
||||||
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13",
|
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13",
|
||||||
"digest": "sha256:61f12dcff38eb008b645d87a5541763452f409d9040eb243718764944167b1a2",
|
"digest": "sha256:61f12dcff38eb008b645d87a5541763452f409d9040eb243718764944167b1a2",
|
||||||
@@ -52,6 +62,31 @@
|
|||||||
"digest": "sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64",
|
"digest": "sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64",
|
||||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.23@sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64"
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.23@sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64"
|
||||||
},
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.11": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.11",
|
||||||
|
"digest": "sha256:88d2d0e315a504d93fd4fb8847fd0f6b7f4469f41a6fc6047b3dc9654c56ab2c",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.11@sha256:88d2d0e315a504d93fd4fb8847fd0f6b7f4469f41a6fc6047b3dc9654c56ab2c"
|
||||||
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14",
|
||||||
|
"digest": "sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0"
|
||||||
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11",
|
||||||
|
"digest": "sha256:97782bc0d8ff7f80f19ae2fdc5e1668517aa732a6fa077e64b8d3919238496d2",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11@sha256:97782bc0d8ff7f80f19ae2fdc5e1668517aa732a6fa077e64b8d3919238496d2"
|
||||||
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14",
|
||||||
|
"digest": "sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14@sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12"
|
||||||
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/router:0.29.14": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.14",
|
||||||
|
"digest": "sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.14@sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0"
|
||||||
|
},
|
||||||
"ghcr.io/github/gh-aw-firewall/squid:0.28.13": {
|
"ghcr.io/github/gh-aw-firewall/squid:0.28.13": {
|
||||||
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13",
|
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13",
|
||||||
"digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56",
|
"digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56",
|
||||||
@@ -72,20 +107,30 @@
|
|||||||
"digest": "sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0",
|
"digest": "sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0",
|
||||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.28.23@sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0"
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.28.23@sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0"
|
||||||
},
|
},
|
||||||
"ghcr.io/github/gh-aw-mcpg:v0.4.25": {
|
"ghcr.io/github/gh-aw-firewall/squid:0.29.11": {
|
||||||
"image": "ghcr.io/github/gh-aw-mcpg:v0.4.25",
|
"image": "ghcr.io/github/gh-aw-firewall/squid:0.29.11",
|
||||||
"digest": "sha256:9be0a86220e807a0ecc89e53d7453468f7a53fbc6b3d1efd2299025ffe01d086",
|
"digest": "sha256:861739ecf924dd2db5e5fb652db2ad82aaafd1615623297ddabc8f41a36b2847",
|
||||||
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.4.25@sha256:9be0a86220e807a0ecc89e53d7453468f7a53fbc6b3d1efd2299025ffe01d086"
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.11@sha256:861739ecf924dd2db5e5fb652db2ad82aaafd1615623297ddabc8f41a36b2847"
|
||||||
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/squid:0.29.14": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/squid:0.29.14",
|
||||||
|
"digest": "sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.14@sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c"
|
||||||
|
},
|
||||||
|
"ghcr.io/github/gh-aw-mcpg:v0.5.10": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-mcpg:v0.5.10",
|
||||||
|
"digest": "sha256:629ddcd68a48ab02e7db8af527d2756c6db563b00c1d31d8aa8fcbac96f01c59",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.5.10@sha256:629ddcd68a48ab02e7db8af527d2756c6db563b00c1d31d8aa8fcbac96f01c59"
|
||||||
},
|
},
|
||||||
"ghcr.io/github/gh-aw-node": {
|
"ghcr.io/github/gh-aw-node": {
|
||||||
"image": "ghcr.io/github/gh-aw-node",
|
"image": "ghcr.io/github/gh-aw-node",
|
||||||
"digest": "sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e",
|
"digest": "sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f",
|
||||||
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e"
|
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f"
|
||||||
},
|
},
|
||||||
"ghcr.io/github/github-mcp-server:v1.12.2": {
|
"ghcr.io/github/github-mcp-server:v2.1.0": {
|
||||||
"image": "ghcr.io/github/github-mcp-server:v1.12.2",
|
"image": "ghcr.io/github/github-mcp-server:v2.1.0",
|
||||||
"digest": "sha256:508a0857ec762b1ab1cece29193345b501fab1dd9d1228a7b617062954cecac6",
|
"digest": "sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a",
|
||||||
"pinned_image": "ghcr.io/github/github-mcp-server:v1.12.2@sha256:508a0857ec762b1ab1cece29193345b501fab1dd9d1228a7b617062954cecac6"
|
"pinned_image": "ghcr.io/github/github-mcp-server:v2.1.0@sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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@862164f9ffbcce2e24e5397da938e3b19f839dce # v1.2.3
|
uses: github/gh-aw-actions/setup-cli@8126d6cb07dea9221848de275af8a41474d839ca # v1.3.0
|
||||||
with:
|
with:
|
||||||
version: v1.2.2
|
version: v1.3.0
|
||||||
- name: Install Rust Stable
|
- name: Install Rust Stable
|
||||||
uses: dtolnay/rust-toolchain@stable
|
uses: dtolnay/rust-toolchain@stable
|
||||||
with:
|
with:
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ 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
|
||||||
@@ -30,6 +31,7 @@ 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
|
||||||
@@ -57,7 +59,8 @@ 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 'Disclose AI automation'
|
check AGENTS.md '(.github/AGENTS.md)'
|
||||||
|
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)'
|
||||||
@@ -84,7 +87,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/ISSUE_GUIDELINES.md",
|
"src/AGENTS.md", "src-tauri/AGENTS.md", ".github/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",
|
||||||
|
|||||||
+112
-64
File diff suppressed because one or more lines are too long
Generated
+115
-66
File diff suppressed because one or more lines are too long
+112
-64
File diff suppressed because one or more lines are too long
@@ -48,16 +48,11 @@ 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. **Disclose AI automation.** When an agent creates or co-creates a PR or Issue,
|
9. **Compiled workflows.** Agentic workflow Markdown, including the
|
||||||
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.
|
||||||
11. **Changelog.** Entries follow the rules in
|
10. **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.
|
||||||
|
|
||||||
@@ -78,8 +73,5 @@ the ownership evidence the AI-slop review evaluates (see
|
|||||||
|
|
||||||
## Issue and PR Workflows
|
## Issue and PR Workflows
|
||||||
|
|
||||||
When drafting, triaging, splitting, or implementing from a community issue, use
|
For Issue and PR work, read [`.github/AGENTS.md`](.github/AGENTS.md), including
|
||||||
the conditional checklist in [`.github/ISSUE_GUIDELINES.md`](.github/ISSUE_GUIDELINES.md).
|
when using `gh` or an API without editing files under `.github/`.
|
||||||
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.
|
|
||||||
|
|||||||
+4
-3
@@ -168,9 +168,10 @@ 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. Report
|
local review. Keep command-level results in the working conversation. For PR
|
||||||
the command or interaction, observed result, and material gaps in the existing
|
descriptions, follow the [PR template](.github/PULL_REQUEST_TEMPLATE.md): include
|
||||||
conversation or PR; no separate verification report is required. Static checks,
|
behavioral evidence and material gaps relevant to review, omitting routine check
|
||||||
|
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
+41
-32
@@ -1127,7 +1127,6 @@ 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",
|
||||||
@@ -1155,6 +1154,7 @@ 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",
|
||||||
@@ -4356,6 +4356,18 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "nix"
|
||||||
|
version = "0.32.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.13.2",
|
||||||
|
"cfg-if",
|
||||||
|
"cfg_aliases",
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "nohash-hasher"
|
name = "nohash-hasher"
|
||||||
version = "0.2.0"
|
version = "0.2.0"
|
||||||
@@ -4882,7 +4894,7 @@ checksum = "9cf20a545b305cf1da722b236b5155c9bb35f1d5ceb28c048bd96ca842f41b5b"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"android_system_properties",
|
"android_system_properties",
|
||||||
"log",
|
"log",
|
||||||
"nix",
|
"nix 0.31.3",
|
||||||
"objc2",
|
"objc2",
|
||||||
"objc2-foundation",
|
"objc2-foundation",
|
||||||
"objc2-ui-kit",
|
"objc2-ui-kit",
|
||||||
@@ -6789,18 +6801,6 @@ 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"
|
||||||
@@ -7237,9 +7237,9 @@ checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri"
|
name = "tauri"
|
||||||
version = "2.12.6"
|
version = "2.12.5"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9c2a5cad3827d1fa46c206a6bcaee8ca14203e9b0aaabe447dd4acef33ecd065"
|
checksum = "5fb0244332cfb9cee7e2a568bf5da29a36ed8fdbd717f6f47a66b6b7b358c072"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"bytes",
|
"bytes",
|
||||||
@@ -7292,9 +7292,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-build"
|
name = "tauri-build"
|
||||||
version = "2.7.5"
|
version = "2.7.4"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "3e03658bfc9cb60f96a05b7d07a7f7cdfbf4c30b1bbfcb5cf6b5342cc2c9e0bc"
|
checksum = "adddb0e648752aaac5da9c3c3c6a68e1e87cab55e3b757b18a9441ef8c3ac614"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"cargo_toml",
|
"cargo_toml",
|
||||||
@@ -7315,9 +7315,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-codegen"
|
name = "tauri-codegen"
|
||||||
version = "2.7.5"
|
version = "2.7.4"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "7c454a15120b885bf57d0cb9ab218c01e12bc672f793452cb6527b460db883aa"
|
checksum = "fb37631cf71dab5e8ab55e1bdd701e18a52653d90b78e71d0e5598b1e0a61316"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.23.1",
|
"base64 0.23.1",
|
||||||
"brotli",
|
"brotli",
|
||||||
@@ -7330,7 +7330,7 @@ dependencies = [
|
|||||||
"semver 1.0.28",
|
"semver 1.0.28",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sha2 0.11.1",
|
"sha2 0.10.9",
|
||||||
"syn 2.0.119",
|
"syn 2.0.119",
|
||||||
"tauri-utils",
|
"tauri-utils",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.20",
|
||||||
@@ -7342,9 +7342,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-macros"
|
name = "tauri-macros"
|
||||||
version = "2.7.5"
|
version = "2.7.4"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f8f7513896f637528ec27ff76effd90638b1cdfa77499fae3db078043aed7ecb"
|
checksum = "0cc38db58854c10fb5f91a887ed8bf82d3239bb92b5d8db86eda09e96d9963d1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"heck 0.5.0",
|
"heck 0.5.0",
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
@@ -7717,9 +7717,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-runtime"
|
name = "tauri-runtime"
|
||||||
version = "2.12.3"
|
version = "2.12.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "3c4b2a71c4bf51cde5cdcf1b45d7943282c7c669d3d26f7a324cce25f1b53e75"
|
checksum = "7c55766d99cea69055904d1735b93c2049302b2e09effd462120deb5581d78e9"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cookie",
|
"cookie",
|
||||||
"dpi",
|
"dpi",
|
||||||
@@ -7742,9 +7742,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-runtime-wry"
|
name = "tauri-runtime-wry"
|
||||||
version = "2.12.4"
|
version = "2.12.3"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0d9be5e7af9560a4a60cdd441389a066cdd3e7c5d464a006ae34cb276cc78abd"
|
checksum = "e1aa9d8b7a120f879f44fdc1053f7b7dbf416bf0bbc6a72b714dec46b782b52f"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"gtk",
|
"gtk",
|
||||||
"http",
|
"http",
|
||||||
@@ -7800,9 +7800,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-utils"
|
name = "tauri-utils"
|
||||||
version = "2.10.3"
|
version = "2.10.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d6bf649f12d6fb11e1867214973cd37d89786ae2c0904f79b787b1db4fdcd14c"
|
checksum = "362ab21cd4cc713f2a02b1a9b5688198b1541cfb6907c4281e9190e0f0ef4aa3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"brotli",
|
"brotli",
|
||||||
@@ -8565,6 +8565,15 @@ 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"
|
||||||
@@ -10127,9 +10136,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zip"
|
name = "zip"
|
||||||
version = "9.5.1"
|
version = "9.6.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e3476fd497ac8af5b1ec7b51acab7bef380f7e8dd8e0487595bafd839417a302"
|
checksum = "80cc68510ea7553c30a69c732de5278e94183f68765af6c642dbccefd6ec777e"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes",
|
"aes",
|
||||||
"bzip2",
|
"bzip2",
|
||||||
@@ -10143,7 +10152,7 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
"lzma-rust2",
|
"lzma-rust2",
|
||||||
"memchr",
|
"memchr",
|
||||||
"nix",
|
"nix 0.32.0",
|
||||||
"pbkdf2",
|
"pbkdf2",
|
||||||
"ppmd-rust",
|
"ppmd-rust",
|
||||||
"sha1 0.11.0",
|
"sha1 0.11.0",
|
||||||
|
|||||||
+2
-3
@@ -61,7 +61,7 @@ tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", bra
|
|||||||
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
|
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
|
||||||
tracing = "0.1.44"
|
tracing = "0.1.44"
|
||||||
|
|
||||||
tauri = { version = "2.12.6" }
|
tauri = { version = "2.12.5" }
|
||||||
tauri-plugin-clipboard-manager = "2.5.0"
|
tauri-plugin-clipboard-manager = "2.5.0"
|
||||||
parking_lot = "0.13.0"
|
parking_lot = "0.13.0"
|
||||||
anyhow = "1.0.104"
|
anyhow = "1.0.104"
|
||||||
@@ -84,9 +84,8 @@ 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"
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ perf-harness = ["dep:tauri-plugin-wdio-webdriver"]
|
|||||||
identifier = "io.github.clash-verge-rev.clash-verge-rev"
|
identifier = "io.github.clash-verge-rev.clash-verge-rev"
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
tauri-build = { version = "2.7.5", features = [] }
|
tauri-build = { version = "2.7.4", features = [] }
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
clash-verge-draft = { workspace = true }
|
clash-verge-draft = { workspace = true }
|
||||||
@@ -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 }
|
||||||
smartstring = { workspace = true, features = ["serde"] }
|
tristr = { workspace = true }
|
||||||
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"
|
||||||
@@ -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.5.1"
|
zip = "9.6.0"
|
||||||
flate2 = "1.1.11"
|
flate2 = "1.1.11"
|
||||||
reqwest_dav = "0.3.3"
|
reqwest_dav = "0.3.3"
|
||||||
aes-gcm = { version = "0.11.1" }
|
aes-gcm = { version = "0.11.1" }
|
||||||
|
|||||||
@@ -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,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 smartstring::alias::String;
|
use tristr::alias::String;
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
|
|||||||
@@ -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,5 +1,5 @@
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use smartstring::alias::String;
|
use tristr::alias::String;
|
||||||
|
|
||||||
pub type CmdResult<T = ()> = Result<T, CommandFailure>;
|
pub type CmdResult<T = ()> = Result<T, CommandFailure>;
|
||||||
|
|
||||||
|
|||||||
@@ -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: &String) -> CmdResult<()> {
|
async fn restore_previous_profile(prev_profile: &str) -> CmdResult<()> {
|
||||||
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
|
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
|
||||||
let restore_profiles = IProfiles {
|
let restore_profiles = IProfiles {
|
||||||
current: Some(prev_profile.to_owned()),
|
current: Some(prev_profile.into()),
|
||||||
items: None,
|
items: None,
|
||||||
};
|
};
|
||||||
Config::profiles()
|
Config::profiles()
|
||||||
@@ -322,7 +322,6 @@ 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>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -330,13 +329,9 @@ 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>,
|
||||||
}
|
}
|
||||||
@@ -358,15 +353,10 @@ 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>,
|
||||||
|
|||||||
@@ -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,10 +36,7 @@ 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(
|
pub struct RuntimeLogs(HashMap<String, Vec<(String, String)>>);
|
||||||
#[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]
|
||||||
|
|||||||
@@ -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]
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use crate::{
|
|||||||
config::{Config, IVerge},
|
config::{Config, IVerge},
|
||||||
core, feat,
|
core, feat,
|
||||||
};
|
};
|
||||||
use smartstring::alias::String;
|
use tristr::alias::String;
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
|
|||||||
@@ -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>,
|
||||||
@@ -216,7 +216,7 @@ impl Config {
|
|||||||
.or_else(|| runtime_data.config.as_ref())
|
.or_else(|| runtime_data.config.as_ref())
|
||||||
.ok_or_else(|| anyhow!("failed to generate runtime config, might need to restart application"))?;
|
.ok_or_else(|| anyhow!("failed to generate runtime config, might need to restart application"))?;
|
||||||
let yaml_str = serde_yaml_ng::to_string(config)?;
|
let yaml_str = serde_yaml_ng::to_string(config)?;
|
||||||
Ok(format!("# Generated by Clash Verge\n\n{}", yaml_str))
|
Ok(yaml_str)
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.map_err(|join| anyhow!("runtime serialization task failed: {join}"))?
|
.map_err(|join| anyhow!("runtime serialization task failed: {join}"))?
|
||||||
@@ -224,7 +224,7 @@ impl Config {
|
|||||||
|
|
||||||
pub(crate) async fn write_runtime_file(yaml: &str) -> Result<PathBuf> {
|
pub(crate) async fn write_runtime_file(yaml: &str) -> Result<PathBuf> {
|
||||||
let path = dirs::app_home_dir()?.join(files::RUNTIME_CONFIG);
|
let path = dirs::app_home_dir()?.join(files::RUNTIME_CONFIG);
|
||||||
help::save_yaml_str(&path, yaml).await?;
|
help::save_yaml_str(&path, yaml, Some("# Generated by Clash Verge")).await?;
|
||||||
Ok(path)
|
Ok(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
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;
|
||||||
@@ -49,9 +50,7 @@ pub(crate) fn dns_override_source(profile_uid: &str, config: &Mapping) -> Result
|
|||||||
digest.update(profile_uid.as_bytes());
|
digest.update(profile_uid.as_bytes());
|
||||||
digest.update([0]);
|
digest.update([0]);
|
||||||
digest.update(serde_json::to_vec(&canonical)?);
|
digest.update(serde_json::to_vec(&canonical)?);
|
||||||
Ok(Some(
|
Ok(Some(help::hex_encode(&digest.finalize()).into()))
|
||||||
digest.finalize().iter().map(|byte| format!("{byte:02x}")).collect(),
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -110,7 +109,6 @@ 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>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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,30 +26,24 @@ pub(super) fn normalize_profile_home_url(raw: &str) -> Option<String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
url.host_str()?;
|
url.host_str()?;
|
||||||
Some(url.to_string().into())
|
Some(url.as_str().into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)]
|
#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)]
|
||||||
#[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")]
|
||||||
@@ -64,20 +58,16 @@ 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>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,7 +83,6 @@ 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")]
|
||||||
@@ -116,15 +105,10 @@ 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>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ 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},
|
||||||
@@ -30,6 +29,7 @@ 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,7 +51,6 @@ 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>>,
|
||||||
@@ -605,7 +604,7 @@ async fn fetch_proxies_with_timeout() -> Result<Proxies> {
|
|||||||
.map_err(Into::into)
|
.map_err(Into::into)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn select_node_with_timeout(group_name: &String, node: &String) -> Result<()> {
|
async fn select_node_with_timeout(group_name: &str, node: &str) -> Result<()> {
|
||||||
tokio::time::timeout(MIHOMO_OPERATION_TIMEOUT, async {
|
tokio::time::timeout(MIHOMO_OPERATION_TIMEOUT, async {
|
||||||
handle::Handle::mihomo().select_node_for_group(group_name, node).await
|
handle::Handle::mihomo().select_node_for_group(group_name, node).await
|
||||||
})
|
})
|
||||||
@@ -761,7 +760,7 @@ pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result
|
|||||||
return Ok((profiles, false));
|
return Ok((profiles, false));
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut selected = item.selected.clone().unwrap_or_default();
|
let selected = item.selected.get_or_insert_with(Vec::new);
|
||||||
match selected
|
match selected
|
||||||
.iter_mut()
|
.iter_mut()
|
||||||
.find(|entry| entry.name.as_ref() == Some(&group_name))
|
.find(|entry| entry.name.as_ref() == Some(&group_name))
|
||||||
@@ -770,14 +769,13 @@ pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result
|
|||||||
if entry.now.as_ref() == Some(&node) {
|
if entry.now.as_ref() == Some(&node) {
|
||||||
return Ok((profiles, false));
|
return Ok((profiles, false));
|
||||||
}
|
}
|
||||||
entry.now = Some(node);
|
entry.now = Some(node.clone());
|
||||||
}
|
}
|
||||||
None => selected.push(PrfSelected {
|
None => selected.push(PrfSelected {
|
||||||
name: Some(group_name),
|
name: Some(group_name),
|
||||||
now: Some(node),
|
now: Some(node),
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
item.selected = Some(selected);
|
|
||||||
profiles.save_file().await?;
|
profiles.save_file().await?;
|
||||||
Ok((profiles, true))
|
Ok((profiles, true))
|
||||||
})
|
})
|
||||||
@@ -796,12 +794,17 @@ pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
|
|||||||
return Ok((profiles, false));
|
return Ok((profiles, false));
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut selected = item.selected.clone().unwrap_or_default();
|
let Some(mut selected) = item.selected.take() else {
|
||||||
|
return Ok((profiles, false));
|
||||||
|
};
|
||||||
if !remove_selected_node(&mut selected, group_name) {
|
if !remove_selected_node(&mut selected, group_name) {
|
||||||
|
item.selected = Some(selected);
|
||||||
return Ok((profiles, false));
|
return Ok((profiles, false));
|
||||||
}
|
}
|
||||||
|
|
||||||
item.selected = (!selected.is_empty()).then_some(selected);
|
if !selected.is_empty() {
|
||||||
|
item.selected = Some(selected);
|
||||||
|
}
|
||||||
profiles.save_file().await?;
|
profiles.save_file().await?;
|
||||||
Ok((profiles, true))
|
Ok((profiles, true))
|
||||||
})
|
})
|
||||||
@@ -809,7 +812,7 @@ pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn persist_reconciled_selected(
|
async fn persist_reconciled_selected(
|
||||||
profile_uid: &String,
|
profile_uid: &str,
|
||||||
original_selected: &[PrfSelected],
|
original_selected: &[PrfSelected],
|
||||||
selected: Vec<PrfSelected>,
|
selected: Vec<PrfSelected>,
|
||||||
generation: u64,
|
generation: u64,
|
||||||
@@ -818,7 +821,7 @@ async fn persist_reconciled_selected(
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
let profile_uid = profile_uid.clone();
|
let profile_uid = String::from(profile_uid);
|
||||||
let original_selected = original_selected.to_vec();
|
let original_selected = original_selected.to_vec();
|
||||||
persist_selected_update(false, move |mut profiles| async move {
|
persist_selected_update(false, move |mut profiles| async move {
|
||||||
if !is_activation_current(generation) || profiles.current.as_ref() != Some(&profile_uid) {
|
if !is_activation_current(generation) || profiles.current.as_ref() != Some(&profile_uid) {
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|
||||||
|
|||||||
@@ -8,33 +8,26 @@ 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 smartstring::alias::String;
|
use tristr::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>,
|
||||||
@@ -52,23 +45,18 @@ 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>,
|
||||||
@@ -93,32 +81,25 @@ 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>,
|
||||||
@@ -129,7 +110,6 @@ pub struct IVerge {
|
|||||||
pub auto_close_connection: Option<bool>,
|
pub auto_close_connection: 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>,
|
||||||
@@ -209,7 +189,6 @@ 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>,
|
||||||
|
|
||||||
@@ -229,38 +208,24 @@ 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>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ 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},
|
||||||
@@ -15,6 +14,7 @@ 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");
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ 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,
|
||||||
@@ -18,6 +17,7 @@ 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)]
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ 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,
|
||||||
@@ -23,6 +22,7 @@ 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)]
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -42,9 +42,12 @@ pub async fn notify_event<'a>(event: NotificationEvent<'a>) {
|
|||||||
}
|
}
|
||||||
NotificationEvent::ClashModeChanged { mode } => {
|
NotificationEvent::ClashModeChanged { mode } => {
|
||||||
let title = clash_verge_i18n::t!("notifications.clashModeChanged.title");
|
let title = clash_verge_i18n::t!("notifications.clashModeChanged.title");
|
||||||
let body = clash_verge_i18n::t!("notifications.clashModeChanged.body")
|
let body = clash_verge_i18n::t!("notifications.clashModeChanged.body");
|
||||||
.replace("{mode}", mode)
|
let body = if body.contains("{mode}") {
|
||||||
.into();
|
body.replace("{mode}", mode).into()
|
||||||
|
} else {
|
||||||
|
body
|
||||||
|
};
|
||||||
notify(title, body);
|
notify(title, body);
|
||||||
}
|
}
|
||||||
NotificationEvent::SystemProxyToggled(enabled) => {
|
NotificationEvent::SystemProxyToggled(enabled) => {
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
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};
|
||||||
|
|
||||||
@@ -55,21 +56,21 @@ impl Handle {
|
|||||||
Self::send_event(FrontendEvent::RunStateChanged { state: state.clone() });
|
Self::send_event(FrontendEvent::RunStateChanged { state: state.clone() });
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn notify_profile_changed(profile_id: &String) {
|
pub fn notify_profile_changed(profile_id: &str) {
|
||||||
Self::send_event(FrontendEvent::ProfileChanged {
|
Self::send_event(FrontendEvent::ProfileChanged {
|
||||||
current_profile_id: profile_id,
|
current_profile_id: profile_id,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn notify_timer_updated(profile_index: &String) {
|
pub fn notify_timer_updated(profile_index: &str) {
|
||||||
Self::send_event(FrontendEvent::TimerUpdated { profile_index });
|
Self::send_event(FrontendEvent::TimerUpdated { profile_index });
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn notify_profile_update_started(uid: &String) {
|
pub fn notify_profile_update_started(uid: &str) {
|
||||||
Self::send_event(FrontendEvent::ProfileUpdateStarted { uid });
|
Self::send_event(FrontendEvent::ProfileUpdateStarted { uid });
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn notify_profile_update_completed(uid: &String) {
|
pub fn notify_profile_update_completed(uid: &str) {
|
||||||
Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid });
|
Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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 String,
|
current_profile_id: &'a str,
|
||||||
},
|
},
|
||||||
TimerUpdated {
|
TimerUpdated {
|
||||||
profile_index: &'a String,
|
profile_index: &'a str,
|
||||||
},
|
},
|
||||||
ProfileUpdateStarted {
|
ProfileUpdateStarted {
|
||||||
uid: &'a String,
|
uid: &'a str,
|
||||||
},
|
},
|
||||||
ProfileUpdateCompleted {
|
ProfileUpdateCompleted {
|
||||||
uid: &'a String,
|
uid: &'a str,
|
||||||
},
|
},
|
||||||
RunStateChanged {
|
RunStateChanged {
|
||||||
state: crate::core::runstate::RunStateView,
|
state: crate::core::runstate::RunStateView,
|
||||||
@@ -77,10 +77,8 @@ 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.
|
||||||
@@ -247,7 +245,6 @@ 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>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -369,7 +366,7 @@ mod wire_tests {
|
|||||||
|
|
||||||
/// One sample per `FrontendEvent` variant, paired with its wire name and payload.
|
/// One sample per `FrontendEvent` variant, paired with its wire name and payload.
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
fn sample_frontend_events(uid: &String) -> Vec<(FrontendEvent<'_>, &'static str, serde_json::Value)> {
|
fn sample_frontend_events(uid: &str) -> Vec<(FrontendEvent<'_>, &'static str, serde_json::Value)> {
|
||||||
let state = crate::core::runstate::RunState {
|
let state = crate::core::runstate::RunState {
|
||||||
health: Default::default(),
|
health: Default::default(),
|
||||||
pending: None,
|
pending: None,
|
||||||
|
|||||||
@@ -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 = digest.finalize().iter().map(|byte| format!("{byte:02x}")).collect();
|
let digest: String = crate::utils::help::hex_encode(&digest.finalize());
|
||||||
let path = Path::new(destination);
|
let path = Path::new(destination);
|
||||||
let extension = path
|
let extension = path
|
||||||
.extension()
|
.extension()
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ 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::{
|
||||||
@@ -18,6 +17,7 @@ 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 {
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ 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::{
|
||||||
@@ -23,6 +22,7 @@ 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: &String, is_start: bool) {
|
fn emit_update_event(uid: &str, is_start: bool) {
|
||||||
if is_start {
|
if is_start {
|
||||||
super::handle::Handle::notify_profile_update_started(uid);
|
super::handle::Handle::notify_profile_update_started(uid);
|
||||||
} else {
|
} else {
|
||||||
@@ -503,7 +503,6 @@ 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::{
|
||||||
@@ -515,6 +514,7 @@ 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>,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::config::{IProfilePreview, IVerge};
|
use crate::config::{IProfilePreview, IProfiles, 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,7 +19,6 @@ 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;
|
||||||
@@ -27,6 +26,7 @@ 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,7 +41,10 @@ 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 {
|
struct TrayMenuOptions<'a> {
|
||||||
|
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,
|
||||||
}
|
}
|
||||||
@@ -201,9 +204,8 @@ impl Tray {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let verge = Config::verge().await.latest_arc();
|
let verge = Config::verge().await.latest_arc();
|
||||||
let system_proxy = verge.enable_system_proxy.as_ref().unwrap_or(&false);
|
let system_proxy = verge.enable_system_proxy.unwrap_or(false);
|
||||||
let tun_mode = verge.enable_tun_mode.as_ref().unwrap_or(&false);
|
let tun_mode = verge.enable_tun_mode.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
|
||||||
@@ -213,29 +215,72 @@ 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();
|
||||||
|
|
||||||
logging_error!(
|
let fetch_proxy_groups =
|
||||||
Type::Tray,
|
include_proxy_groups && verge.tray_proxy_groups_display_mode.as_deref() != Some("disable");
|
||||||
tray.set_menu(Some(
|
|
||||||
create_tray_menu(
|
// TODO: should update tray menu again when it was timeout error
|
||||||
app_handle,
|
let (proxy_nodes_data, runtime_proxy_groups_order) = if fetch_proxy_groups {
|
||||||
Some(mode.as_str()),
|
let proxy_nodes_data =
|
||||||
*system_proxy,
|
tokio::time::timeout(Duration::from_millis(1000), handle::Handle::mihomo().get_proxies())
|
||||||
*tun_mode,
|
.await
|
||||||
tun_mode_available,
|
.map_or(None, |res| res.ok());
|
||||||
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,
|
||||||
.await?,
|
&profiles,
|
||||||
))
|
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(())
|
||||||
@@ -342,9 +387,6 @@ impl Tray {
|
|||||||
let verge = Config::verge().await.data_arc();
|
let verge = Config::verge().await.data_arc();
|
||||||
let app_handle = handle::Handle::app_handle();
|
let app_handle = handle::Handle::app_handle();
|
||||||
self.update_menu_internal(app_handle, false).await?;
|
self.update_menu_internal(app_handle, false).await?;
|
||||||
AsyncHandler::spawn(|| async {
|
|
||||||
logging_error!(Type::Tray, Self::global().update_menu().await);
|
|
||||||
});
|
|
||||||
self.update_icon(&verge).await?;
|
self.update_icon(&verge).await?;
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
self.update_speed_task(verge.enable_tray_speed.unwrap_or(false));
|
self.update_speed_task(verge.enable_tray_speed.unwrap_or(false));
|
||||||
@@ -582,52 +624,16 @@ fn create_proxy_menu_item(
|
|||||||
Ok((proxies_submenu, inline_proxy_items))
|
Ok((proxies_submenu, inline_proxy_items))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn create_tray_menu(
|
fn build_tray_menu(
|
||||||
app_handle: &AppHandle,
|
app_handle: &AppHandle,
|
||||||
mode: Option<&str>,
|
options: TrayMenuOptions<'_>,
|
||||||
system_proxy_enabled: bool,
|
verge_settings: &IVerge,
|
||||||
tun_mode_enabled: bool,
|
profiles_config: &IProfiles,
|
||||||
tun_mode_available: bool,
|
proxy_group_order_map: Option<HashMap<String, usize>>,
|
||||||
profiles_preview: Vec<IProfilePreview<'_>>,
|
proxy_nodes_data: Option<Proxies>,
|
||||||
options: TrayMenuOptions,
|
|
||||||
) -> Result<tauri::menu::Menu<Wry>> {
|
) -> Result<tauri::menu::Menu<Wry>> {
|
||||||
let current_proxy_mode = mode.unwrap_or("");
|
let current_proxy_mode = options.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
|
||||||
@@ -636,15 +642,14 @@ async fn create_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>> = create_profile_menu_item(app_handle, profiles_preview)?;
|
let profile_menu_items: Vec<CheckMenuItem<Wry>> =
|
||||||
|
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
|
||||||
@@ -735,7 +740,7 @@ async fn create_tray_menu(
|
|||||||
MenuIds::SYSTEM_PROXY,
|
MenuIds::SYSTEM_PROXY,
|
||||||
&texts.system_proxy,
|
&texts.system_proxy,
|
||||||
true,
|
true,
|
||||||
system_proxy_enabled,
|
options.system_proxy_enabled,
|
||||||
hotkeys.get("toggle_system_proxy").copied(),
|
hotkeys.get("toggle_system_proxy").copied(),
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
@@ -744,7 +749,7 @@ async fn create_tray_menu(
|
|||||||
MenuIds::TUN_MODE,
|
MenuIds::TUN_MODE,
|
||||||
&texts.tun_mode,
|
&texts.tun_mode,
|
||||||
tun_mode_available,
|
tun_mode_available,
|
||||||
tun_mode_enabled,
|
options.tun_mode_enabled,
|
||||||
hotkeys.get("toggle_tun_mode").copied(),
|
hotkeys.get("toggle_tun_mode").copied(),
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
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 _},
|
||||||
@@ -10,6 +9,7 @@ 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,14 +114,8 @@ 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 {
|
Invalid { kind: ValidationErrorKind, message: String },
|
||||||
kind: ValidationErrorKind,
|
Skipped { reason: ValidationSkipReason },
|
||||||
#[specta(type = std::string::String)]
|
|
||||||
message: String,
|
|
||||||
},
|
|
||||||
Skipped {
|
|
||||||
reason: ValidationSkipReason,
|
|
||||||
},
|
|
||||||
Busy,
|
Busy,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -435,7 +429,7 @@ impl CoreConfigValidator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let check_path = dirs::app_home_dir()?.join(crate::constants::files::CHECK_CONFIG);
|
let check_path = dirs::app_home_dir()?.join(crate::constants::files::CHECK_CONFIG);
|
||||||
help::save_yaml_str(&check_path, yaml).await?;
|
help::save_yaml_str(&check_path, yaml, None).await?;
|
||||||
let outcome = Self::validate_config_internal_outcome(dirs::path_to_str(&check_path)?).await?;
|
let outcome = Self::validate_config_internal_outcome(dirs::path_to_str(&check_path)?).await?;
|
||||||
if outcome.is_valid() {
|
if outcome.is_valid() {
|
||||||
*LAST_VALIDATED.lock() = Some(fingerprint);
|
*LAST_VALIDATED.lock() = Some(fingerprint);
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ use crate::{
|
|||||||
utils::{dirs, help},
|
utils::{dirs, help},
|
||||||
};
|
};
|
||||||
use serde_yaml_ng::Mapping;
|
use serde_yaml_ng::Mapping;
|
||||||
use smartstring::alias::String;
|
|
||||||
use tokio::fs;
|
use tokio::fs;
|
||||||
|
use tristr::alias::String;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct ChainItem {
|
pub struct ChainItem {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use serde_yaml_ng::{Mapping, Value};
|
use serde_yaml_ng::{Mapping, Value};
|
||||||
use smartstring::alias::String;
|
use tristr::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.iter() {
|
for (key, value) in config {
|
||||||
if let Some(key_str) = key.as_str() {
|
if let Some(key_str) = key.as_str() {
|
||||||
lowercased.insert(lowercase_key(key_str), value.clone());
|
lowercased.insert(lowercase_key(key_str), value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
lowercased
|
lowercased
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ fn deep_merge(a: &mut Value, b: Value) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn use_merge(merge: &Mapping, mut config: Mapping) -> Mapping {
|
pub fn use_merge(merge: Mapping, mut config: Mapping) -> Mapping {
|
||||||
for (key, value) in use_lowercase(merge) {
|
for (key, value) in use_lowercase(merge) {
|
||||||
match (config.get_mut(&key), value) {
|
match (config.get_mut(&key), value) {
|
||||||
(Some(Value::Mapping(existing)), Value::Mapping(overlay)) if key.as_str() == Some("dns") => {
|
(Some(Value::Mapping(existing)), Value::Mapping(overlay)) if key.as_str() == Some("dns") => {
|
||||||
@@ -79,7 +79,7 @@ fn test_merge() -> anyhow::Result<()> {
|
|||||||
let merge = serde_yaml_ng::from_str::<Mapping>(merge)?;
|
let merge = serde_yaml_ng::from_str::<Mapping>(merge)?;
|
||||||
let config = serde_yaml_ng::from_str::<Mapping>(config)?;
|
let config = serde_yaml_ng::from_str::<Mapping>(config)?;
|
||||||
|
|
||||||
let result = use_merge(&merge, config);
|
let result = use_merge(merge.clone(), config);
|
||||||
assert_eq!(result["dns"]["nameserver-policy"], merge["dns"]["nameserver-policy"]);
|
assert_eq!(result["dns"]["nameserver-policy"], merge["dns"]["nameserver-policy"]);
|
||||||
assert_eq!(result["dns"]["fallback-filter"], merge["dns"]["fallback-filter"]);
|
assert_eq!(result["dns"]["fallback-filter"], merge["dns"]["fallback-filter"]);
|
||||||
assert_eq!(result["hosts"], merge["hosts"]);
|
assert_eq!(result["hosts"], merge["hosts"]);
|
||||||
@@ -91,7 +91,7 @@ fn test_merge() -> anyhow::Result<()> {
|
|||||||
let cleared = serde_yaml_ng::from_str::<Mapping>(
|
let cleared = serde_yaml_ng::from_str::<Mapping>(
|
||||||
"dns: {enable: false, nameserver-policy: {}, fallback-filter: {}, nameserver: []}\nhosts: {}",
|
"dns: {enable: false, nameserver-policy: {}, fallback-filter: {}, nameserver: []}\nhosts: {}",
|
||||||
)?;
|
)?;
|
||||||
let result = use_merge(&cleared, result);
|
let result = use_merge(cleared.clone(), result);
|
||||||
assert_eq!(result["dns"], cleared["dns"]);
|
assert_eq!(result["dns"], cleared["dns"]);
|
||||||
assert_eq!(result["hosts"], cleared["hosts"]);
|
assert_eq!(result["hosts"], cleared["hosts"]);
|
||||||
|
|
||||||
|
|||||||
@@ -26,9 +26,10 @@ 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 tokio::fs;
|
use tokio::fs;
|
||||||
|
use tristr::alias::String;
|
||||||
|
|
||||||
type ResultLog = Vec<(String, String)>;
|
type ResultLog = Vec<(String, String)>;
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -236,13 +237,13 @@ async fn process_override_items(
|
|||||||
mut result_map: HashMap<String, ResultLog>,
|
mut result_map: HashMap<String, ResultLog>,
|
||||||
merge_item: ChainItem,
|
merge_item: ChainItem,
|
||||||
script_item: ChainItem,
|
script_item: ChainItem,
|
||||||
profile_name: &String,
|
profile_name: &str,
|
||||||
authoritative: &AuthoritativeFields,
|
authoritative: &AuthoritativeFields,
|
||||||
) -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
|
) -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
|
||||||
if let ChainType::Merge(merge) = merge_item.data {
|
if let ChainType::Merge(merge) = merge_item.data {
|
||||||
exists_keys.extend(use_keys(&merge));
|
exists_keys.extend(use_keys(&merge));
|
||||||
let before = authoritative.current(&config);
|
let before = authoritative.current(&config);
|
||||||
config = use_merge(&merge, config);
|
config = use_merge(merge, config);
|
||||||
let notes: ResultLog = authoritative
|
let notes: ResultLog = authoritative
|
||||||
.overridden(&before, &authoritative.current(&config))
|
.overridden(&before, &authoritative.current(&config))
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -255,7 +256,7 @@ async fn process_override_items(
|
|||||||
|
|
||||||
if let ChainType::Script(script) = script_item.data {
|
if let ChainType::Script(script) = script_item.data {
|
||||||
let before = authoritative.current(&config);
|
let before = authoritative.current(&config);
|
||||||
let (res_config, changed_keys, mut logs) = use_script(script, config, profile_name.clone()).await;
|
let (res_config, changed_keys, mut logs) = use_script(script, config, profile_name.into()).await;
|
||||||
exists_keys.extend(changed_keys);
|
exists_keys.extend(changed_keys);
|
||||||
config = res_config;
|
config = res_config;
|
||||||
logs.extend(
|
logs.extend(
|
||||||
@@ -320,15 +321,45 @@ struct AuthoritativeFields {
|
|||||||
tun: Mapping,
|
tun: Mapping,
|
||||||
dns: Mapping,
|
dns: Mapping,
|
||||||
hosts: Option<Value>,
|
hosts: Option<Value>,
|
||||||
|
fingerprints: FieldFingerprints,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct FieldFingerprints {
|
||||||
|
control_plane: Vec<Option<u64>>,
|
||||||
|
tun: Vec<Option<u64>>,
|
||||||
|
dns: Vec<Option<u64>>,
|
||||||
|
hosts: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fingerprint(value: Option<&Value>) -> Option<u64> {
|
||||||
|
let value = value?;
|
||||||
|
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||||
|
value.hash(&mut hasher);
|
||||||
|
Some(hasher.finish())
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AuthoritativeFields {
|
impl AuthoritativeFields {
|
||||||
fn capture(config: &Mapping, gui_tun_keys: &[Value], mut dns_settings: Mapping) -> Self {
|
fn capture(config: &Mapping, gui_tun_keys: &[Value], mut dns_settings: Mapping) -> Self {
|
||||||
|
let control_plane = snapshot_control_plane(config);
|
||||||
|
let tun = snapshot_tun(config, gui_tun_keys);
|
||||||
|
let dns = take_mapping(&mut dns_settings, "dns");
|
||||||
|
let hosts = dns_settings.remove("hosts");
|
||||||
|
let fingerprints = FieldFingerprints {
|
||||||
|
control_plane: CONTROL_PLANE_KEYS
|
||||||
|
.iter()
|
||||||
|
.map(|&key| fingerprint(control_plane.get(Value::from(key))))
|
||||||
|
.collect(),
|
||||||
|
tun: tun.iter().map(|(_, value)| fingerprint(Some(value))).collect(),
|
||||||
|
dns: dns.iter().map(|(_, value)| fingerprint(Some(value))).collect(),
|
||||||
|
hosts: fingerprint(hosts.as_ref()),
|
||||||
|
};
|
||||||
Self {
|
Self {
|
||||||
control_plane: snapshot_control_plane(config),
|
control_plane,
|
||||||
tun: snapshot_tun(config, gui_tun_keys),
|
tun,
|
||||||
dns: take_mapping(&mut dns_settings, "dns"),
|
dns,
|
||||||
hosts: dns_settings.remove("hosts"),
|
hosts,
|
||||||
|
fingerprints,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -346,43 +377,50 @@ impl AuthoritativeFields {
|
|||||||
config
|
config
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The owned values as `config` holds them now, for diffing one override.
|
/// What `config` holds now, for diffing one override.
|
||||||
fn current(&self, config: &Mapping) -> Self {
|
fn current(&self, config: &Mapping) -> FieldFingerprints {
|
||||||
let tun_keys: Vec<Value> = self.tun.keys().cloned().collect();
|
let tun = config.get("tun").and_then(Value::as_mapping);
|
||||||
let dns = config.get("dns").and_then(Value::as_mapping);
|
let dns = config.get("dns").and_then(Value::as_mapping);
|
||||||
Self {
|
FieldFingerprints {
|
||||||
control_plane: snapshot_control_plane(config),
|
control_plane: CONTROL_PLANE_KEYS
|
||||||
tun: snapshot_tun(config, &tun_keys),
|
.iter()
|
||||||
|
.map(|&key| fingerprint(config.get(key)))
|
||||||
|
.collect(),
|
||||||
|
tun: self
|
||||||
|
.tun
|
||||||
|
.keys()
|
||||||
|
.map(|key| fingerprint(tun.and_then(|map| map.get(key))))
|
||||||
|
.collect(),
|
||||||
dns: self
|
dns: self
|
||||||
.dns
|
.dns
|
||||||
.keys()
|
.keys()
|
||||||
.filter_map(|key| Some((key.clone(), dns?.get(key)?.clone())))
|
.map(|key| fingerprint(dns.and_then(|map| map.get(key))))
|
||||||
.collect(),
|
.collect(),
|
||||||
hosts: self.hosts.as_ref().and_then(|_| config.get("hosts")).cloned(),
|
hosts: self.hosts.as_ref().and_then(|_| fingerprint(config.get("hosts"))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Owned keys an override moved off the app value; `enforce` discards those writes.
|
/// Owned keys an override moved off the app value; `enforce` discards those writes.
|
||||||
fn overridden(&self, before: &Self, after: &Self) -> Vec<String> {
|
fn overridden(&self, before: &FieldFingerprints, after: &FieldFingerprints) -> Vec<String> {
|
||||||
let mut keys = Vec::new();
|
let mut keys = Vec::new();
|
||||||
for &key in CONTROL_PLANE_KEYS {
|
for (index, &key) in CONTROL_PLANE_KEYS.iter().enumerate() {
|
||||||
if before.control_plane.get(key) != after.control_plane.get(key)
|
if before.control_plane[index] != after.control_plane[index]
|
||||||
&& after.control_plane.get(key) != self.control_plane.get(key)
|
&& after.control_plane[index] != self.fingerprints.control_plane[index]
|
||||||
{
|
{
|
||||||
keys.push(key.into());
|
keys.push(key.into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for key in self.tun.keys() {
|
for (index, key) in self.tun.keys().enumerate() {
|
||||||
if before.tun.get(key) != after.tun.get(key) && after.tun.get(key) != self.tun.get(key) {
|
if before.tun[index] != after.tun[index] && after.tun[index] != self.fingerprints.tun[index] {
|
||||||
keys.push(format!("tun.{}", key.as_str().unwrap_or_default()).into());
|
keys.push(format!("tun.{}", key.as_str().unwrap_or_default()).into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for key in self.dns.keys() {
|
for (index, key) in self.dns.keys().enumerate() {
|
||||||
if before.dns.get(key) != after.dns.get(key) && after.dns.get(key) != self.dns.get(key) {
|
if before.dns[index] != after.dns[index] && after.dns[index] != self.fingerprints.dns[index] {
|
||||||
keys.push(format!("dns.{}", key.as_str().unwrap_or_default()).into());
|
keys.push(format!("dns.{}", key.as_str().unwrap_or_default()).into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if self.hosts.is_some() && before.hosts != after.hosts && after.hosts != self.hosts {
|
if self.hosts.is_some() && before.hosts != after.hosts && after.hosts != self.fingerprints.hosts {
|
||||||
keys.push("hosts".into());
|
keys.push("hosts".into());
|
||||||
}
|
}
|
||||||
keys
|
keys
|
||||||
@@ -553,16 +591,15 @@ fn merge_default_config(
|
|||||||
) -> Mapping {
|
) -> Mapping {
|
||||||
for (key, value) in clash_config.into_iter() {
|
for (key, value) in clash_config.into_iter() {
|
||||||
if key.as_str() == Some("tun") {
|
if key.as_str() == Some("tun") {
|
||||||
let mut tun = config.get_mut("tun").map_or_else(Mapping::new, |val| {
|
if let Value::Mapping(patch_tun) = value {
|
||||||
val.as_mapping().cloned().unwrap_or_else(Mapping::new)
|
let mut tun = take_mapping(&mut config, "tun");
|
||||||
});
|
for (key, value) in patch_tun {
|
||||||
let patch_tun = value.as_mapping().cloned().unwrap_or_else(Mapping::new);
|
|
||||||
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("tun".into(), tun.into());
|
config.insert(Value::from("tun"), Value::Mapping(tun));
|
||||||
|
}
|
||||||
} 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");
|
||||||
@@ -617,7 +654,7 @@ fn merge_default_config(
|
|||||||
fn apply_builtin_scripts(mut config: Mapping, enable_builtin: bool) -> Mapping {
|
fn apply_builtin_scripts(mut config: Mapping, enable_builtin: bool) -> Mapping {
|
||||||
if enable_builtin {
|
if enable_builtin {
|
||||||
// The JS path saw a lowercased view; lowercase once, only when the builtin runs.
|
// The JS path saw a lowercased view; lowercase once, only when the builtin runs.
|
||||||
config = use_lowercase(&config);
|
config = use_lowercase(config);
|
||||||
logging!(debug, Type::Core, "run builtin script verge_hy_alpn");
|
logging!(debug, Type::Core, "run builtin script verge_hy_alpn");
|
||||||
config = builtin_hy_alpn(config);
|
config = builtin_hy_alpn(config);
|
||||||
}
|
}
|
||||||
@@ -649,11 +686,8 @@ 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
|
Value::Mapping(map) => map.get("name").and_then(Value::as_str).map(Into::into),
|
||||||
.get("name")
|
Value::String(name) => Some(name.as_str().into()),
|
||||||
.and_then(Value::as_str)
|
|
||||||
.map(|name| name.to_owned().into()),
|
|
||||||
Value::String(name) => Some(name.to_owned().into()),
|
|
||||||
_ => None,
|
_ => None,
|
||||||
})
|
})
|
||||||
.collect::<HashSet<String>>()
|
.collect::<HashSet<String>>()
|
||||||
@@ -872,7 +906,7 @@ pub async fn enhance(
|
|||||||
result_map,
|
result_map,
|
||||||
global_merge,
|
global_merge,
|
||||||
global_script,
|
global_script,
|
||||||
&profile_name,
|
profile_name.as_str(),
|
||||||
&authoritative,
|
&authoritative,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
@@ -883,12 +917,12 @@ pub async fn enhance(
|
|||||||
result_map,
|
result_map,
|
||||||
merge_item,
|
merge_item,
|
||||||
script_item,
|
script_item,
|
||||||
&profile_name,
|
profile_name.as_str(),
|
||||||
&authoritative,
|
&authoritative,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
notify_discarded_keys(authoritative.overridden(&authoritative, &authoritative.current(&config)));
|
notify_discarded_keys(authoritative.overridden(&authoritative.fingerprints, &authoritative.current(&config)));
|
||||||
let config = authoritative.enforce(config);
|
let config = authoritative.enforce(config);
|
||||||
let config = ensure_tun_default_mtu(config);
|
let config = ensure_tun_default_mtu(config);
|
||||||
let config = ensure_lan_bind_address(config);
|
let config = ensure_lan_bind_address(config);
|
||||||
@@ -1407,7 +1441,7 @@ mod tests {
|
|||||||
uid: uid.into(),
|
uid: uid.into(),
|
||||||
data: ChainType::Merge(merge.clone()),
|
data: ChainType::Merge(merge.clone()),
|
||||||
};
|
};
|
||||||
let profile_name = "test-profile".into();
|
let profile_name = "test-profile";
|
||||||
let (config, keys, logs) = process_override_items(
|
let (config, keys, logs) = process_override_items(
|
||||||
config,
|
config,
|
||||||
vec![],
|
vec![],
|
||||||
@@ -1417,7 +1451,7 @@ mod tests {
|
|||||||
uid: "global-script".into(),
|
uid: "global-script".into(),
|
||||||
data: ChainType::Script(script.into()),
|
data: ChainType::Script(script.into()),
|
||||||
},
|
},
|
||||||
&profile_name,
|
profile_name,
|
||||||
&authoritative,
|
&authoritative,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
@@ -1430,7 +1464,7 @@ mod tests {
|
|||||||
uid: "profile-script".into(),
|
uid: "profile-script".into(),
|
||||||
data: ChainType::Script(script.into()),
|
data: ChainType::Script(script.into()),
|
||||||
},
|
},
|
||||||
&profile_name,
|
profile_name,
|
||||||
&authoritative,
|
&authoritative,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
@@ -1506,7 +1540,7 @@ mod tests {
|
|||||||
),
|
),
|
||||||
};
|
};
|
||||||
|
|
||||||
let profile_name = "test-profile".into();
|
let profile_name = "test-profile";
|
||||||
let authoritative = AuthoritativeFields::capture(&config, &[], Mapping::new());
|
let authoritative = AuthoritativeFields::capture(&config, &[], Mapping::new());
|
||||||
let (config, exists_keys, result_map) = process_override_items(
|
let (config, exists_keys, result_map) = process_override_items(
|
||||||
config,
|
config,
|
||||||
@@ -1514,7 +1548,7 @@ mod tests {
|
|||||||
HashMap::new(),
|
HashMap::new(),
|
||||||
global_merge,
|
global_merge,
|
||||||
global_script,
|
global_script,
|
||||||
&profile_name,
|
profile_name,
|
||||||
&authoritative,
|
&authoritative,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
@@ -1524,7 +1558,7 @@ mod tests {
|
|||||||
result_map,
|
result_map,
|
||||||
profile_merge,
|
profile_merge,
|
||||||
profile_script,
|
profile_script,
|
||||||
&profile_name,
|
profile_name,
|
||||||
&authoritative,
|
&authoritative,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|||||||
@@ -1,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::{Error, Result};
|
use anyhow::Result;
|
||||||
use boa_engine::{Context, JsString, JsValue, Source, js_string, native_function::NativeFunction, property::Attribute};
|
use boa_engine::{Context, JsString, JsValue, Source, js_string, native_function::NativeFunction, property::Attribute};
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
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,15 +22,27 @@ type EvalOutcome = (Result<Mapping, std::string::String>, Vec<(String, String)>)
|
|||||||
pub(super) async fn use_script(script: String, config: Mapping, name: String) -> ScriptResult {
|
pub(super) async fn use_script(script: String, config: Mapping, name: String) -> ScriptResult {
|
||||||
// The template is identity-plus-lowercasing; skip the Boa round-trip.
|
// The template is identity-plus-lowercasing; skip the Boa round-trip.
|
||||||
if script == tmpl::ITEM_SCRIPT {
|
if script == tmpl::ITEM_SCRIPT {
|
||||||
return (use_lowercase(&config), vec![], vec![]);
|
return (use_lowercase(config), vec![], vec![]);
|
||||||
}
|
}
|
||||||
|
|
||||||
let json = match serde_json::to_string(&use_lowercase(&config)) {
|
let json = match serde_json::to_value(&config) {
|
||||||
Ok(json) if json.len() <= MAX_JSON_SIZE => json,
|
Ok(mut json) => {
|
||||||
Ok(_) => {
|
if let Some(map) = json.as_object_mut() {
|
||||||
|
let 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())]),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -66,7 +78,7 @@ pub(super) async fn use_script(script: String, config: Mapping, name: String) ->
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Console logs survive every failure path.
|
/// Console logs survive every failure path.
|
||||||
fn eval_script(script: &str, config_json: &str, name: &String) -> EvalOutcome {
|
fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) -> EvalOutcome {
|
||||||
let mut context = Context::default();
|
let mut context = Context::default();
|
||||||
|
|
||||||
context
|
context
|
||||||
@@ -131,12 +143,11 @@ fn eval_script(script: &str, config_json: &str, name: &String) -> EvalOutcome {
|
|||||||
});"#,
|
});"#,
|
||||||
));
|
));
|
||||||
|
|
||||||
// Bind the JSON instead of embedding it in program source; Boa's parser never chews it.
|
let config_value = match JsValue::from_json(config_json, &mut context) {
|
||||||
if let Err(err) = context.register_global_property(
|
Ok(value) => value,
|
||||||
js_string!("__verge_config__"),
|
Err(err) => return bail(format!("failed to bind config for script: {err}")),
|
||||||
JsValue::from(JsString::from(config_json)),
|
};
|
||||||
Attribute::all(),
|
if let Err(err) = context.register_global_property(js_string!("__verge_config__"), config_value, Attribute::all()) {
|
||||||
) {
|
|
||||||
return bail(format!("failed to bind config for script: {err}"));
|
return bail(format!("failed to bind config for script: {err}"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,31 +160,61 @@ fn eval_script(script: &str, config_json: &str, name: &String) -> EvalOutcome {
|
|||||||
let code = format!(
|
let code = format!(
|
||||||
r"try{{
|
r"try{{
|
||||||
{script};
|
{script};
|
||||||
JSON.stringify(main(JSON.parse(globalThis.__verge_config__),'{safe_name}')||'')
|
main(globalThis.__verge_config__,'{safe_name}')
|
||||||
}} catch(err) {{
|
}} catch(err) {{
|
||||||
`__error_flag__ ${{err.toString()}}`
|
`__error_flag__ ${{err.toString()}}`
|
||||||
}}"
|
}}"
|
||||||
);
|
);
|
||||||
|
|
||||||
let result = match context.eval(Source::from_bytes(code.as_str())) {
|
let result = match context.eval(Source::from_bytes(code.as_str())) {
|
||||||
Ok(result) if result.is_string() => result,
|
|
||||||
_ => return bail("main function should return object".to_owned()),
|
|
||||||
};
|
|
||||||
let result = match result.to_string(&mut context) {
|
|
||||||
Ok(result) => result,
|
Ok(result) => result,
|
||||||
Err(e) => return bail(format!("Failed to convert JS result to string: {e}")),
|
Err(err) => {
|
||||||
|
logging!(
|
||||||
|
error,
|
||||||
|
Type::Config,
|
||||||
|
"Script execution error: {err}. Script name: {name}"
|
||||||
|
);
|
||||||
|
return bail("Script execution failed".to_owned());
|
||||||
|
}
|
||||||
};
|
};
|
||||||
let result = match result.to_std_string() {
|
// The JS wrapper funnels exceptions into a marker string; surface its text.
|
||||||
Ok(result) => result,
|
if result.is_string() {
|
||||||
Err(_) => return bail("Failed to convert JS string to std string".to_owned()),
|
let text = result
|
||||||
|
.to_string(&mut context)
|
||||||
|
.ok()
|
||||||
|
.and_then(|text| text.to_std_string().ok())
|
||||||
|
.unwrap_or_default();
|
||||||
|
if text.trim_start().starts_with("__error_flag__") {
|
||||||
|
logging!(
|
||||||
|
error,
|
||||||
|
Type::Config,
|
||||||
|
"Script execution error: {}. Script name: {name}",
|
||||||
|
text.trim_start()["__error_flag__".len()..].trim()
|
||||||
|
);
|
||||||
|
return bail("Script execution failed".to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !result.is_object() {
|
||||||
|
return bail("main function should return object".to_owned());
|
||||||
|
}
|
||||||
|
let result = match result.to_json(&mut context) {
|
||||||
|
Ok(Some(result)) => result,
|
||||||
|
Ok(None) => return bail("main function should return object".to_owned()),
|
||||||
|
Err(err) => {
|
||||||
|
logging!(
|
||||||
|
error,
|
||||||
|
Type::Config,
|
||||||
|
"Script execution error: {err}. Script name: {name}"
|
||||||
|
);
|
||||||
|
return bail("Script execution failed".to_owned());
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
if json_approx_size(&result) > MAX_JSON_SIZE {
|
||||||
if result.len() > MAX_JSON_SIZE {
|
|
||||||
return bail("Script result exceeds maximum allowed size".to_owned());
|
return bail("Script result exceeds maximum allowed size".to_owned());
|
||||||
}
|
}
|
||||||
|
|
||||||
match parse_json_safely(&result) {
|
match serde_json::from_value::<Mapping>(result) {
|
||||||
Ok(config) => (Ok(use_lowercase(&config)), outputs.lock().to_vec()),
|
Ok(config) => (Ok(use_lowercase(config)), outputs.lock().to_vec()),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
logging!(
|
logging!(
|
||||||
error,
|
error,
|
||||||
@@ -185,27 +226,17 @@ fn eval_script(script: &str, config_json: &str, name: &String) -> EvalOutcome {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_json_safely(json_str: &str) -> Result<Mapping, Error> {
|
/// Serialized-size estimate without building the serialized string; a DoS guard, not an exact byte count.
|
||||||
if json_str.len() > MAX_JSON_SIZE {
|
fn json_approx_size(value: &serde_json::Value) -> usize {
|
||||||
anyhow::bail!("JSON string too large");
|
match value {
|
||||||
}
|
serde_json::Value::String(s) => s.len() + 2,
|
||||||
|
serde_json::Value::Object(map) => map
|
||||||
let json_str = strip_outer_quotes(json_str);
|
.iter()
|
||||||
Ok(serde_json::from_str::<Mapping>(json_str)?)
|
.map(|(key, value)| key.len() + 4 + json_approx_size(value))
|
||||||
}
|
.sum(),
|
||||||
|
serde_json::Value::Array(items) => items.iter().map(json_approx_size).sum(),
|
||||||
// 安全地移除外层引号
|
serde_json::Value::Number(n) => n.to_string().len(),
|
||||||
fn strip_outer_quotes(s: &str) -> &str {
|
serde_json::Value::Bool(_) | serde_json::Value::Null => 4,
|
||||||
let s = s.trim();
|
|
||||||
|
|
||||||
if s.len() < 2 {
|
|
||||||
return s;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')) {
|
|
||||||
&s[1..s.len() - 1]
|
|
||||||
} else {
|
|
||||||
s
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,18 +8,10 @@ macro_rules! revise {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
|
pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
|
||||||
let tun_key = Value::from("tun");
|
let mut tun_val = super::take_mapping(&mut config, "tun");
|
||||||
let tun_val = config.get(&tun_key);
|
|
||||||
let mut tun_val = tun_val.map_or_else(Mapping::new, |val| {
|
|
||||||
val.as_mapping().cloned().unwrap_or_else(Mapping::new)
|
|
||||||
});
|
|
||||||
|
|
||||||
if enable {
|
if enable {
|
||||||
let dns_key = Value::from("dns");
|
let mut dns_val = super::take_mapping(&mut config, "dns");
|
||||||
let dns_val = config.get(&dns_key);
|
|
||||||
let mut dns_val = dns_val.map_or_else(Mapping::new, |val| {
|
|
||||||
val.as_mapping().cloned().unwrap_or_else(Mapping::new)
|
|
||||||
});
|
|
||||||
let ipv6_key = Value::from("ipv6");
|
let ipv6_key = Value::from("ipv6");
|
||||||
let ipv6_val = config.get(&ipv6_key).and_then(|v| v.as_bool()).unwrap_or(false);
|
let ipv6_val = config.get(&ipv6_key).and_then(|v| v.as_bool()).unwrap_or(false);
|
||||||
|
|
||||||
|
|||||||
@@ -12,17 +12,14 @@ 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,
|
||||||
}
|
}
|
||||||
@@ -123,7 +120,7 @@ pub async fn list_wevdav_backup() -> Result<Vec<ListFile>> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn delete_webdav_backup(filename: String) -> Result<()> {
|
pub async fn delete_webdav_backup(filename: String) -> Result<()> {
|
||||||
let name = filename.to_string();
|
let name = filename.clone();
|
||||||
backup::WebDavClient::global().delete(filename).await.map_err(|err| {
|
backup::WebDavClient::global().delete(filename).await.map_err(|err| {
|
||||||
logging!(
|
logging!(
|
||||||
error,
|
error,
|
||||||
@@ -165,7 +162,7 @@ pub async fn restore_webdav_backup(filename: String) -> Result<()> {
|
|||||||
let backup_storage_path = app_home_dir()
|
let backup_storage_path = app_home_dir()
|
||||||
.map_err(|e| anyhow::anyhow!("Failed to get app home dir: {e}"))?
|
.map_err(|e| anyhow::anyhow!("Failed to get app home dir: {e}"))?
|
||||||
.join(filename.as_str());
|
.join(filename.as_str());
|
||||||
let name = filename.to_string();
|
let name = filename.clone();
|
||||||
backup::WebDavClient::global()
|
backup::WebDavClient::global()
|
||||||
.download(filename, backup_storage_path.clone())
|
.download(filename, backup_storage_path.clone())
|
||||||
.await
|
.await
|
||||||
|
|||||||
@@ -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>> =
|
||||||
|
|||||||
@@ -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 smartstring::alias::String;
|
use tristr::alias::String;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{
|
config::{
|
||||||
@@ -19,10 +19,7 @@ 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 {
|
ConfirmationRequired { source: String },
|
||||||
#[specta(type = std::string::String)]
|
|
||||||
source: String,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn set_dns_override(
|
pub async fn set_dns_override(
|
||||||
|
|||||||
@@ -3,18 +3,15 @@ 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,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +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 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) {
|
||||||
@@ -103,7 +103,7 @@ pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool)
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn should_update_profile(uid: &String, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
|
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
|
||||||
let profiles = Config::profiles().await;
|
let profiles = Config::profiles().await;
|
||||||
let profiles = profiles.latest_arc();
|
let profiles = profiles.latest_arc();
|
||||||
let item = profiles.get_item(uid)?;
|
let item = profiles.get_item(uid)?;
|
||||||
@@ -138,8 +138,8 @@ async fn should_update_profile(uid: &String, ignore_auto_update: bool) -> Result
|
|||||||
|
|
||||||
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))]
|
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))]
|
||||||
async fn perform_profile_update(
|
async fn perform_profile_update(
|
||||||
uid: &String,
|
uid: &str,
|
||||||
url: &String,
|
url: &str,
|
||||||
opt: Option<&PrfOption>,
|
opt: Option<&PrfOption>,
|
||||||
option: Option<&PrfOption>,
|
option: Option<&PrfOption>,
|
||||||
is_mannual_trigger: bool,
|
is_mannual_trigger: bool,
|
||||||
@@ -234,7 +234,7 @@ async fn perform_profile_update(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_mannual_trigger))]
|
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_mannual_trigger))]
|
||||||
pub async fn update_profile(uid: &String, option: Option<&PrfOption>, is_mannual_trigger: bool) -> Result<()> {
|
pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_mannual_trigger: bool) -> Result<()> {
|
||||||
let url_opt = should_update_profile(uid, is_mannual_trigger).await?;
|
let url_opt = should_update_profile(uid, is_mannual_trigger).await?;
|
||||||
|
|
||||||
let profile_persisted = match url_opt {
|
let profile_persisted = match url_opt {
|
||||||
@@ -245,7 +245,7 @@ pub async fn update_profile(uid: &String, option: Option<&PrfOption>, is_mannual
|
|||||||
None => false,
|
None => false,
|
||||||
};
|
};
|
||||||
let profiles = Config::profiles().await;
|
let profiles = Config::profiles().await;
|
||||||
let is_current = profiles.latest_arc().current.as_ref() == Some(uid);
|
let is_current = profiles.latest_arc().current.as_deref() == Some(uid);
|
||||||
let should_refresh = is_current || (!profile_persisted && is_mannual_trigger);
|
let should_refresh = is_current || (!profile_persisted && is_mannual_trigger);
|
||||||
|
|
||||||
if should_refresh {
|
if should_refresh {
|
||||||
|
|||||||
@@ -137,16 +137,11 @@ fn is_short_id(key: &Value) -> bool {
|
|||||||
pub async fn save_yaml<T: Serialize + Sync>(path: &Path, data: &T, prefix: Option<&str>) -> Result<()> {
|
pub async fn save_yaml<T: Serialize + Sync>(path: &Path, data: &T, prefix: Option<&str>) -> Result<()> {
|
||||||
let data_str = with_encryption(|| async { serde_yaml_ng::to_string(data) }).await?;
|
let data_str = with_encryption(|| async { serde_yaml_ng::to_string(data) }).await?;
|
||||||
|
|
||||||
let yaml_str = match prefix {
|
save_yaml_str(path, &data_str, prefix).await
|
||||||
Some(prefix) => format!("{prefix}\n\n{data_str}"),
|
|
||||||
None => data_str,
|
|
||||||
};
|
|
||||||
|
|
||||||
save_yaml_str(path, &yaml_str).await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Atomic replace with pre-serialized content; the payload must not need the encryption scope.
|
/// Atomic replace with pre-serialized content; the payload must not need the encryption scope.
|
||||||
pub async fn save_yaml_str(path: &Path, yaml_str: &str) -> Result<()> {
|
pub async fn save_yaml_str(path: &Path, yaml_str: &str, prefix: Option<&str>) -> Result<()> {
|
||||||
let (temporary, file) = loop {
|
let (temporary, file) = loop {
|
||||||
let temporary = path.with_extension(format!("tmp-{}-{}", std::process::id(), nanoid!()));
|
let temporary = path.with_extension(format!("tmp-{}-{}", std::process::id(), nanoid!()));
|
||||||
match std::fs::OpenOptions::new()
|
match std::fs::OpenOptions::new()
|
||||||
@@ -172,9 +167,16 @@ pub async fn save_yaml_str(path: &Path, yaml_str: &str) -> Result<()> {
|
|||||||
let _ = std::fs::remove_file(path);
|
let _ = std::fs::remove_file(path);
|
||||||
});
|
});
|
||||||
let mut file = tokio::fs::File::from_std(file);
|
let mut file = tokio::fs::File::from_std(file);
|
||||||
file.write_all(yaml_str.as_bytes())
|
async fn write_chunk(file: &mut tokio::fs::File, bytes: &[u8], path: &Path) -> Result<()> {
|
||||||
|
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()))?;
|
||||||
@@ -220,6 +222,16 @@ pub fn parse_str<T: FromStr>(target: &str, key: &str) -> Option<T> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn hex_encode(bytes: &[u8]) -> String {
|
||||||
|
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||||
|
let mut out = String::with_capacity(bytes.len() * 2);
|
||||||
|
for &byte in bytes {
|
||||||
|
out.push(HEX[usize::from(byte >> 4)] as char);
|
||||||
|
out.push(HEX[usize::from(byte & 0x0f)] as char);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
/// Masks query values and token-like path segments for logging.
|
/// Masks query values and token-like path segments for logging.
|
||||||
pub fn mask_url(url: &str) -> String {
|
pub fn mask_url(url: &str) -> String {
|
||||||
let (path_part, query_part) = match url.find('?') {
|
let (path_part, query_part) = match url.find('?') {
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -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_owned().into());
|
.map(|(_, value)| value.into());
|
||||||
let url = extract_subscription_url(link_parsed)?;
|
let url = extract_subscription_url(link_parsed)?;
|
||||||
Some((url, name))
|
Some((url, name))
|
||||||
}
|
}
|
||||||
@@ -123,7 +123,7 @@ async fn fetch_profile_item(url: &str, name: Option<&String>) -> Option<PrfItem>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn post_import_updates(uid: &String, had_current_profile: bool) {
|
async fn post_import_updates(uid: &str, had_current_profile: bool) {
|
||||||
handle::Handle::refresh_verge();
|
handle::Handle::refresh_verge();
|
||||||
handle::Handle::notify_profile_changed(uid);
|
handle::Handle::notify_profile_changed(uid);
|
||||||
|
|
||||||
@@ -131,7 +131,7 @@ async fn post_import_updates(uid: &String, had_current_profile: bool) {
|
|||||||
false
|
false
|
||||||
} else {
|
} else {
|
||||||
let profiles = Config::profiles().await;
|
let profiles = Config::profiles().await;
|
||||||
profiles.latest_arc().current.as_ref() == Some(uid)
|
profiles.latest_arc().current.as_deref() == Some(uid)
|
||||||
};
|
};
|
||||||
|
|
||||||
if should_update_core {
|
if should_update_core {
|
||||||
|
|||||||
@@ -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) return
|
if (timerId !== null || document.hidden || listeners.size === 0) return
|
||||||
|
|
||||||
currentTime = Date.now()
|
currentTime = Date.now()
|
||||||
timerId = window.setInterval(() => {
|
timerId = window.setInterval(() => {
|
||||||
@@ -18,19 +18,34 @@ const startTimer = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const stopTimer = () => {
|
const stopTimer = () => {
|
||||||
if (listeners.size > 0 || timerId === null) return
|
if (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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -223,6 +223,16 @@ 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))
|
||||||
|
|
||||||
@@ -491,6 +501,8 @@ 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
|
||||||
@@ -664,6 +676,7 @@ 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,
|
||||||
@@ -686,8 +699,10 @@ 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 })
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import {
|
|||||||
} from '@mui/material'
|
} from '@mui/material'
|
||||||
import { useLockFn } from 'ahooks'
|
import { useLockFn } from 'ahooks'
|
||||||
import {
|
import {
|
||||||
|
memo,
|
||||||
useCallback,
|
useCallback,
|
||||||
useEffect,
|
useEffect,
|
||||||
useEffectEvent,
|
useEffectEvent,
|
||||||
@@ -204,14 +205,11 @@ const optionValue = (memberIndex: number, member: ResolvedProxyMember) =>
|
|||||||
|
|
||||||
const sortProxyOptions = (
|
const sortProxyOptions = (
|
||||||
options: ProxyOption[],
|
options: ProxyOption[],
|
||||||
sortType: ProxySortType,
|
sortType: 0 | 1,
|
||||||
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
|
||||||
@@ -433,6 +431,72 @@ 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,
|
||||||
@@ -485,54 +549,15 @@ const PersistentProxySelect = ({
|
|||||||
: delayManager.getDelayFix(option.member, groupName)
|
: delayManager.getDelayFix(option.member, groupName)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<MenuItem
|
<ProxyMenuOption
|
||||||
key={option.value}
|
key={option.value}
|
||||||
role="option"
|
option={option}
|
||||||
aria-selected={selected}
|
|
||||||
selected={selected}
|
selected={selected}
|
||||||
disabled={option.disabled}
|
isFixed={isFixed}
|
||||||
onClick={() => {
|
fixedProxyInUsed={fixedProxyInUsed}
|
||||||
if (!option.disabled) onChange(option.value)
|
delay={delay}
|
||||||
}}
|
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>
|
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -605,12 +630,14 @@ export const CurrentProxyCard = () => {
|
|||||||
[getProfileStorageKey],
|
[getProfileStorageKey],
|
||||||
)
|
)
|
||||||
|
|
||||||
const { select } = useProxySelection({
|
const onSelectionError = useCallback(
|
||||||
onError: (error) => {
|
(error: unknown) => {
|
||||||
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'
|
||||||
@@ -673,7 +700,6 @@ 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
|
||||||
@@ -767,9 +793,16 @@ 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 =
|
||||||
currentMember && selectedGroupName
|
typeof delays === 'number'
|
||||||
? delayManager.getDelayFix(currentMember, selectedGroupName)
|
? delays
|
||||||
|
: currentMember
|
||||||
|
? delays.of(currentMember)
|
||||||
: -1
|
: -1
|
||||||
|
|
||||||
const signalInfo =
|
const signalInfo =
|
||||||
@@ -890,10 +923,19 @@ 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'
|
isDirectMode || openSelect !== 'proxy' || typeof delays === 'number'
|
||||||
? []
|
? []
|
||||||
|
: sortType === 2
|
||||||
|
? nameSortedProxyOptions
|
||||||
: sortProxyOptions(
|
: sortProxyOptions(
|
||||||
unsortedProxyOptions,
|
unsortedProxyOptions,
|
||||||
sortType,
|
sortType,
|
||||||
@@ -902,6 +944,7 @@ export const CurrentProxyCard = () => {
|
|||||||
),
|
),
|
||||||
[
|
[
|
||||||
delays,
|
delays,
|
||||||
|
nameSortedProxyOptions,
|
||||||
isDirectMode,
|
isDirectMode,
|
||||||
openSelect,
|
openSelect,
|
||||||
unsortedProxyOptions,
|
unsortedProxyOptions,
|
||||||
|
|||||||
@@ -469,12 +469,14 @@ function NormalProxyGroups(props: { mode: string }) {
|
|||||||
}
|
}
|
||||||
}, [handleScroll])
|
}, [handleScroll])
|
||||||
|
|
||||||
const { select } = useProxySelection({
|
const onSelectionError = useCallback(
|
||||||
onError: (error) => {
|
(error: unknown) => {
|
||||||
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) => {
|
||||||
@@ -569,6 +571,17 @@ 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
|
||||||
@@ -576,13 +589,7 @@ function NormalProxyGroups(props: { mode: string }) {
|
|||||||
stickyed={stickyed}
|
stickyed={stickyed}
|
||||||
onLocation={handleLocation}
|
onLocation={handleLocation}
|
||||||
onCheckAll={handleCheckAll}
|
onCheckAll={handleCheckAll}
|
||||||
onHeadState={async (groupName, patch) => {
|
onHeadState={stickyed ? onStickyHeadState : onHeadState}
|
||||||
if (stickyed && patch.filterText !== undefined) {
|
|
||||||
handleGroupLocationByName(groupName)
|
|
||||||
await stickyListRef.current?.waitForScrollEnd()
|
|
||||||
}
|
|
||||||
onHeadState(groupName, patch)
|
|
||||||
}}
|
|
||||||
onChangeProxy={handleChangeProxy}
|
onChangeProxy={handleChangeProxy}
|
||||||
onGroupToggle={handleGroupToggle}
|
onGroupToggle={handleGroupToggle}
|
||||||
/>
|
/>
|
||||||
@@ -593,7 +600,7 @@ function NormalProxyGroups(props: { mode: string }) {
|
|||||||
onHeadState,
|
onHeadState,
|
||||||
handleLocation,
|
handleLocation,
|
||||||
handleGroupToggle,
|
handleGroupToggle,
|
||||||
handleGroupLocationByName,
|
onStickyHeadState,
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ interface RenderProps {
|
|||||||
onGroupToggle?: (group: IRenderItem['group']) => void
|
onGroupToggle?: (group: IRenderItem['group']) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
|
const ProxyGroupHeader = (props: RenderProps) => {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
const {
|
const {
|
||||||
item,
|
item,
|
||||||
@@ -51,11 +51,9 @@ export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
|
|||||||
onLocation,
|
onLocation,
|
||||||
onCheckAll,
|
onCheckAll,
|
||||||
onHeadState,
|
onHeadState,
|
||||||
onChangeProxy,
|
|
||||||
onGroupToggle,
|
onGroupToggle,
|
||||||
isChainMode: _ = false,
|
|
||||||
} = props
|
} = props
|
||||||
const { type, group, headState, member, memberCol } = item
|
const { group, headState } = 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'
|
||||||
@@ -69,25 +67,6 @@ export const ProxyRender = memo(function ProxyRender(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"
|
||||||
@@ -175,8 +154,7 @@ export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
|
|||||||
label={`${group.members.length}`}
|
label={`${group.members.length}`}
|
||||||
sx={{
|
sx={{
|
||||||
mr: toolsOnLeft ? 0 : 1,
|
mr: toolsOnLeft ? 0 : 1,
|
||||||
backgroundColor: (theme) =>
|
backgroundColor: (theme) => alpha(theme.palette.primary.main, 0.1),
|
||||||
alpha(theme.palette.primary.main, 0.1),
|
|
||||||
color: (theme) => theme.palette.primary.main,
|
color: (theme) => theme.palette.primary.main,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
@@ -241,7 +219,49 @@ export const ProxyRender = memo(function ProxyRender(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 (
|
||||||
@@ -271,23 +291,7 @@ export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (type === 3) {
|
if (type === 3) {
|
||||||
return (
|
return <ProxyEmptyRow />
|
||||||
<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) {
|
||||||
|
|||||||
@@ -29,6 +29,9 @@ 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,
|
||||||
|
|||||||
@@ -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 } from './use-filter-sort'
|
import { filterSort, isDelayFilter } from './use-filter-sort'
|
||||||
import {
|
import {
|
||||||
DEFAULT_STATE,
|
DEFAULT_STATE,
|
||||||
useHeadStateNew,
|
useHeadStateNew,
|
||||||
@@ -60,14 +60,15 @@ 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 = {
|
||||||
now: string | undefined
|
group: ProxyGroupView
|
||||||
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[]
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -222,19 +223,55 @@ export const useRenderList = (
|
|||||||
return current?.kind === 'group' ? [global, current.group] : [global]
|
return current?.kind === 'group' ? [global, current.group] : [global]
|
||||||
}, [mode, proxyView])
|
}, [mode, proxyView])
|
||||||
|
|
||||||
// Every group this list draws, so a test settling in any of them re-sorts that group.
|
const repeatedNameGroups = useMemo(() => {
|
||||||
|
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) return []
|
if (!proxyView || isChainMode) return []
|
||||||
if (isChainMode)
|
return renderGroups
|
||||||
return selectedGroup ? [selectedGroup] : [CHAIN_DELAY_GROUP]
|
.filter((group) => {
|
||||||
return renderGroups.map(({ name }) => name)
|
const state = headStates[group.name] || DEFAULT_STATE
|
||||||
}, [isChainMode, proxyView, renderGroups, selectedGroup])
|
return (
|
||||||
|
(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>>(new Map())
|
const groupCacheRef = useRef<Map<string, GroupCache> | null>(null)
|
||||||
|
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) {
|
||||||
@@ -269,16 +306,13 @@ export const useRenderList = (
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
const cache = groupCacheRef.current
|
const groupItems = renderGroups.map((group) => {
|
||||||
|
|
||||||
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.now === group.now &&
|
cached.group === group &&
|
||||||
cached.members === group.members &&
|
|
||||||
cached.headState === headState &&
|
cached.headState === headState &&
|
||||||
cached.col === col &&
|
cached.col === col &&
|
||||||
cached.latencyTimeout === latencyTimeout &&
|
cached.latencyTimeout === latencyTimeout &&
|
||||||
@@ -287,6 +321,51 @@ 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 }
|
||||||
@@ -299,20 +378,8 @@ export const useRenderList = (
|
|||||||
testUrl: group.testUrl!,
|
testUrl: group.testUrl!,
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
if (projected) {
|
||||||
if (headState.open || isFlat) {
|
const occurrences = projected
|
||||||
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) {
|
||||||
@@ -340,17 +407,30 @@ export const useRenderList = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
cache.set(group.name, {
|
cache.set(group.name, {
|
||||||
now: group.now!,
|
group,
|
||||||
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 (
|
||||||
@@ -371,6 +451,7 @@ export const useRenderList = (
|
|||||||
mode,
|
mode,
|
||||||
proxyView,
|
proxyView,
|
||||||
renderGroups,
|
renderGroups,
|
||||||
|
repeatedNameGroups,
|
||||||
selectedGroup,
|
selectedGroup,
|
||||||
])
|
])
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,8 @@ const COLOR = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
value: Rule & { lineNo: number }
|
value: Rule
|
||||||
|
lineNo: number
|
||||||
}
|
}
|
||||||
|
|
||||||
const parseColor = (text: string) => {
|
const parseColor = (text: string) => {
|
||||||
@@ -31,7 +32,7 @@ const parseColor = (text: string) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const RuleItem = (props: Props) => {
|
const RuleItem = (props: Props) => {
|
||||||
const { value } = props
|
const { value, lineNo } = props
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Item sx={{ borderBottom: '1px solid var(--divider-color)' }}>
|
<Item sx={{ borderBottom: '1px solid var(--divider-color)' }}>
|
||||||
@@ -40,7 +41,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' }}
|
||||||
>
|
>
|
||||||
{value.lineNo}
|
{lineNo}
|
||||||
</Typography>
|
</Typography>
|
||||||
|
|
||||||
<Box sx={{ userSelect: 'text' }}>
|
<Box sx={{ userSelect: 'text' }}>
|
||||||
|
|||||||
@@ -150,25 +150,49 @@ 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 previousActiveById = new Map<string, IConnectionsItem>()
|
const sameOrder =
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
const activeConnections: IConnectionsItem[] = []
|
|
||||||
for (let i = 0; i < nextConnections.length; i++) {
|
|
||||||
const connection = nextConnections[i]
|
|
||||||
const previousConnection = previousActiveById.get(connection.id)
|
|
||||||
if (previousConnection) previousActiveById.delete(connection.id)
|
|
||||||
activeConnections.push(normalizeConnection(connection, previousConnection))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (previousActiveById.size === 0) {
|
let activeConnections = sameOrder ? previousActive : []
|
||||||
|
for (let i = 0; i < nextConnections.length; i++) {
|
||||||
|
const connection = nextConnections[i]
|
||||||
|
const previousConnection = sameOrder
|
||||||
|
? previousActive[i]
|
||||||
|
: previousActiveById?.get(connection.id)
|
||||||
|
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
|
||||||
|
const downloadTotal = payload.downloadTotal ?? 0
|
||||||
|
if (!previousActiveById?.size) {
|
||||||
|
if (
|
||||||
|
activeConnections === previousActive &&
|
||||||
|
uploadTotal === previous.uploadTotal &&
|
||||||
|
downloadTotal === previous.downloadTotal
|
||||||
|
) {
|
||||||
|
return previous
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
uploadTotal: payload.uploadTotal ?? 0,
|
uploadTotal,
|
||||||
downloadTotal: payload.downloadTotal ?? 0,
|
downloadTotal,
|
||||||
activeConnections,
|
activeConnections,
|
||||||
closedConnections: previousClosed,
|
closedConnections: previousClosed,
|
||||||
}
|
}
|
||||||
@@ -198,8 +222,8 @@ const mergeConnectionSnapshot = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
uploadTotal: payload.uploadTotal ?? 0,
|
uploadTotal,
|
||||||
downloadTotal: payload.downloadTotal ?? 0,
|
downloadTotal,
|
||||||
activeConnections,
|
activeConnections,
|
||||||
closedConnections,
|
closedConnections,
|
||||||
}
|
}
|
||||||
@@ -227,7 +251,9 @@ const flushPendingMessage = () => {
|
|||||||
|
|
||||||
lastFlushAt = Date.now()
|
lastFlushAt = Date.now()
|
||||||
|
|
||||||
connectionData = mergeConnectionSnapshot(payload, connectionData)
|
const nextData = mergeConnectionSnapshot(payload, connectionData)
|
||||||
|
if (nextData === connectionData) return
|
||||||
|
connectionData = nextData
|
||||||
notifyConnectionListeners()
|
notifyConnectionListeners()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,19 +1,27 @@
|
|||||||
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'
|
||||||
|
|
||||||
const NO_DELAYS: DelaySnapshot = { of: () => -1 }
|
/** A closed menu observes only its current member, not every settled group delay. */
|
||||||
|
export const useGroupDelays = (
|
||||||
/** Exposes the external delay store to React, updating sort order only after a test settles. */
|
group: string | null,
|
||||||
export const useGroupDelays = (group: string | null): DelaySnapshot => {
|
member: ResolvedProxyMember | undefined,
|
||||||
|
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],
|
group && menuOpen
|
||||||
|
? delayManager.groupDelays(group)
|
||||||
|
: group && member
|
||||||
|
? delayManager.getDelayFix(member, group)
|
||||||
|
: -1,
|
||||||
|
[group, member, menuOpen],
|
||||||
)
|
)
|
||||||
|
|
||||||
return useSyncExternalStore(subscribe, read, read)
|
return useSyncExternalStore(subscribe, read, read)
|
||||||
@@ -23,12 +31,12 @@ export const useGroupDelays = (group: string | null): DelaySnapshot => {
|
|||||||
export const useGroupsDelays = (
|
export const useGroupsDelays = (
|
||||||
groups: readonly string[],
|
groups: readonly string[],
|
||||||
): ReadonlyMap<string, DelaySnapshot> => {
|
): ReadonlyMap<string, DelaySnapshot> => {
|
||||||
// Subscribe by group membership; callers rebuild the array on every render.
|
// Group membership must remain unambiguous when names contain spaces.
|
||||||
const groupKey = groups.join(' ')
|
const groupKey = JSON.stringify(groups)
|
||||||
|
|
||||||
const subscribe = useCallback(
|
const subscribe = useCallback(
|
||||||
(onSettle: () => void) => {
|
(onSettle: () => void) => {
|
||||||
const names = groupKey ? groupKey.split(' ') : []
|
const names: string[] = JSON.parse(groupKey)
|
||||||
const unsubscribes = names.map((name) =>
|
const unsubscribes = names.map((name) =>
|
||||||
delayManager.addGroupListener(name, onSettle),
|
delayManager.addGroupListener(name, onSettle),
|
||||||
)
|
)
|
||||||
|
|||||||
+11
-8
@@ -34,13 +34,11 @@ const RulesPage = () => {
|
|||||||
}, [refreshRules, refreshRuleProviders, pageVisible])
|
}, [refreshRules, refreshRuleProviders, pageVisible])
|
||||||
|
|
||||||
const filteredRules = useMemo(() => {
|
const filteredRules = useMemo(() => {
|
||||||
const rulesWithLineNo = rules.map((item, index) => ({
|
const indices: number[] = []
|
||||||
...item,
|
for (let i = 0; i < rules.length; i++) {
|
||||||
// UI-only derived data; keep app context/SWR data immutable
|
if (match(rules[i].payload ?? '')) indices.push(i)
|
||||||
lineNo: index + 1,
|
}
|
||||||
}))
|
return indices
|
||||||
|
|
||||||
return rulesWithLineNo.filter((item) => match(item.payload ?? ''))
|
|
||||||
}, [rules, match])
|
}, [rules, match])
|
||||||
|
|
||||||
const handleScroll = useCallback((e: Event) => {
|
const handleScroll = useCallback((e: Event) => {
|
||||||
@@ -90,7 +88,12 @@ const RulesPage = () => {
|
|||||||
ref={virtuosoRef}
|
ref={virtuosoRef}
|
||||||
count={filteredRules.length}
|
count={filteredRules.length}
|
||||||
estimateSize={40}
|
estimateSize={40}
|
||||||
renderItem={(i) => <RuleItem value={filteredRules[i]} />}
|
renderItem={(i) => (
|
||||||
|
<RuleItem
|
||||||
|
value={rules[filteredRules[i]]}
|
||||||
|
lineNo={filteredRules[i] + 1}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
style={{ flex: 1 }}
|
style={{ flex: 1 }}
|
||||||
onScroll={handleScroll}
|
onScroll={handleScroll}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -132,7 +132,7 @@ class DelayManager {
|
|||||||
const cached = this.groupSetSnapshots.get(groupKey)
|
const cached = this.groupSetSnapshots.get(groupKey)
|
||||||
if (cached) return cached
|
if (cached) return cached
|
||||||
|
|
||||||
const names = groupKey ? groupKey.split(' ') : []
|
const names: string[] = JSON.parse(groupKey)
|
||||||
const snapshots = new Map(
|
const snapshots = new Map(
|
||||||
names.map((name) => [name, this.groupDelays(name)]),
|
names.map((name) => [name, this.groupDelays(name)]),
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in New Issue
Block a user