Compare commits

..
1 Commits
Author SHA1 Message Date
renovate[bot] ac88fa91d8 chore(deps): update cargo dependencies 2026-10-09 03:06:41 +00:00
114 changed files with 2090 additions and 3429 deletions
+1 -1
View File
@@ -5,7 +5,7 @@
"features": { "features": {
"ghcr.io/devcontainers/features/node:2": { "ghcr.io/devcontainers/features/node:2": {
"version": "24.21.0", "version": "24.21.0",
"pnpmVersion": "12.11.2" "pnpmVersion": "12.10.0"
}, },
"ghcr.io/devcontainers/features/rust:1": { "ghcr.io/devcontainers/features/rust:1": {
"version": "1.99.0", "version": "1.99.0",
+12 -4
View File
@@ -6,7 +6,6 @@ on:
permissions: permissions:
contents: read contents: read
pull-requests: read
env: env:
HUSKY: 0 HUSKY: 0
@@ -100,7 +99,14 @@ jobs:
id: check_inputs id: check_inputs
uses: dorny/paths-filter@v4 uses: dorny/paths-filter@v4
with: with:
filters: scripts/contract-inputs.json filters: |
contract:
- 'src/services/contract.ts'
- 'scripts/gen-contract.mjs'
- 'src-tauri/src/core/notify/**'
- 'src-tauri/src/bin/**'
- 'src-tauri/src/lib.rs'
- '.github/workflows/frontend-check.yml'
- name: Skip if contract inputs unchanged - name: Skip if contract inputs unchanged
if: steps.check_inputs.outputs.contract != 'true' if: steps.check_inputs.outputs.contract != 'true'
@@ -153,6 +159,8 @@ jobs:
touch "src-tauri/sidecar/${bin}-x86_64-unknown-linux-gnu" touch "src-tauri/sidecar/${bin}-x86_64-unknown-linux-gnu"
done done
- name: Check generated contract without changing the checkout - name: Regenerate contract and require empty diff
if: steps.check_inputs.outputs.contract == 'true' if: steps.check_inputs.outputs.contract == 'true'
run: pnpm gen:contract --check run: |
pnpm gen:contract
git diff --exit-code -- src/services/contract.ts
+2 -2
View File
@@ -1,4 +1,4 @@
# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"8296ef86aad04ad225d29c7fe51dd18dfa50f258c46e8bd24e443193cc6f80fc","body_hash":"e7b165b458a07108c2e6bfe6f4ed61f5659ce81512691dda091165d5966ee732","compiler_version":"v0.89.21","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.87"}} # gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"ff92739239d50701d56d10eb77fff5083a556fe471496674aa066c4f73b6b6d2","body_hash":"e7b165b458a07108c2e6bfe6f4ed61f5659ce81512691dda091165d5966ee732","compiler_version":"v0.89.21","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.87"}}
# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_DEFAULT_OTLP_ENDPOINT","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"820762786026740c76f36085b0efc47a31fe5020","version":"v7.0.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"924af5fdc64061cfbf66fb584c8b07e2ac230c60","version":"v0.89.21"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.28.23","digest":"sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.28.23@sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.23","digest":"sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.23@sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.28.23","digest":"sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.28.23@sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.25","digest":"sha256:9be0a86220e807a0ecc89e53d7453468f7a53fbc6b3d1efd2299025ffe01d086","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.25@sha256:9be0a86220e807a0ecc89e53d7453468f7a53fbc6b3d1efd2299025ffe01d086"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e","pinned_image":"ghcr.io/github/gh-aw-node@sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e"},{"image":"ghcr.io/github/github-mcp-server:v1.12.2","digest":"sha256:508a0857ec762b1ab1cece29193345b501fab1dd9d1228a7b617062954cecac6","pinned_image":"ghcr.io/github/github-mcp-server:v1.12.2@sha256:508a0857ec762b1ab1cece29193345b501fab1dd9d1228a7b617062954cecac6"}],"has_pull_request_target":true,"mcp_servers":[{"name":"github","tools":["get_pull_request","get_pull_request_comments","get_pull_request_diff","get_pull_request_files","get_pull_request_review_comments","get_pull_request_reviews","get_pull_request_status","issue_read","list_issue_types","list_issues","list_pull_requests","pull_request_read","search_issues","search_pull_requests"]},{"name":"safeoutputs","tools":["add_comment","add_labels","missing_data","missing_tool","noop","remove_labels"]}]} # gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_DEFAULT_OTLP_ENDPOINT","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"820762786026740c76f36085b0efc47a31fe5020","version":"v7.0.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"924af5fdc64061cfbf66fb584c8b07e2ac230c60","version":"v0.89.21"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.28.23","digest":"sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.28.23@sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.23","digest":"sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.23@sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.28.23","digest":"sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.28.23@sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.25","digest":"sha256:9be0a86220e807a0ecc89e53d7453468f7a53fbc6b3d1efd2299025ffe01d086","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.25@sha256:9be0a86220e807a0ecc89e53d7453468f7a53fbc6b3d1efd2299025ffe01d086"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e","pinned_image":"ghcr.io/github/gh-aw-node@sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e"},{"image":"ghcr.io/github/github-mcp-server:v1.12.2","digest":"sha256:508a0857ec762b1ab1cece29193345b501fab1dd9d1228a7b617062954cecac6","pinned_image":"ghcr.io/github/github-mcp-server:v1.12.2@sha256:508a0857ec762b1ab1cece29193345b501fab1dd9d1228a7b617062954cecac6"}],"has_pull_request_target":true,"mcp_servers":[{"name":"github","tools":["get_pull_request","get_pull_request_comments","get_pull_request_diff","get_pull_request_files","get_pull_request_review_comments","get_pull_request_reviews","get_pull_request_status","issue_read","list_issue_types","list_issues","list_pull_requests","pull_request_read","search_issues","search_pull_requests"]},{"name":"safeoutputs","tools":["add_comment","add_labels","missing_data","missing_tool","noop","remove_labels"]}]}
# This file was automatically generated by gh-aw (v0.89.21). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md # This file was automatically generated by gh-aw (v0.89.21). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md
# #
@@ -541,7 +541,7 @@ jobs:
GH_AW_SKILL_DIR: ".github/skills" GH_AW_SKILL_DIR: ".github/skills"
run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh"
- name: Make Copilot quota exhaustion non-blocking - name: Make Copilot quota exhaustion non-blocking
run: "node <<'NODE'\nconst fs = require('fs');\nconst harnessPath = `${process.env.RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs`;\nconst harness = fs.readFileSync(harnessPath, 'utf8');\nconst quotaBranch = [\n ' if (isQuotaExceeded) {',\n ' log(`attempt ${attempt + 1}: Copilot quota exceeded — not retrying`);',\n ' return { action: \"stop\" };',\n ' }',\n].join('\\n');\nconst nonBlockingQuotaBranch = [\n ' let quotaErrorMsg = null;',\n ' if (isQuotaExceeded) {',\n ' log(`attempt ${attempt + 1}: Copilot quota exceeded — not retrying`);',\n ' quotaErrorMsg = { action: \"stop\" };',\n ' }',\n ' if (/\\\\b429\\\\b|Too Many Requests/i.test(result.output)) {',\n ' log(`attempt ${attempt + 1}: Copilot quota unavailable — exiting 0`);',\n ' quotaErrorMsg = { action: \"stop\", exitCode: 0 };',\n ' }',\n ' if (quotaErrorMsg) {',\n ' return quotaErrorMsg;',\n ' }',\n].join('\\n');\n\nif (harness.split(quotaBranch).length !== 2) {\n throw new Error('Unexpected Copilot quota branch; re-audit the gh-aw upgrade');\n}\nfs.writeFileSync(harnessPath, harness.replace(quotaBranch, nonBlockingQuotaBranch));\nNODE" run: "node <<'NODE'\nconst fs = require('fs');\nconst harnessPath = `${process.env.RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs`;\nconst harness = fs.readFileSync(harnessPath, 'utf8');\nconst quotaBranch = [\n ' if (isQuotaExceeded) {',\n ' log(`attempt ${attempt + 1}: Copilot quota exceeded — not retrying`);',\n ' return { action: \"stop\" };',\n ' }',\n].join('\\n');\nconst nonBlockingQuotaBranch = [\n ' if (isQuotaExceeded) {',\n ' log(`attempt ${attempt + 1}: Copilot quota exceeded — not retrying`);',\n ' if (/\\\\b429\\\\b|Too Many Requests/i.test(result.output)) {',\n ' log(`attempt ${attempt + 1}: Copilot quota unavailable — exiting 0`);',\n ' return { action: \"stop\", exitCode: 0 };',\n ' }',\n ' return { action: \"stop\" };',\n ' }',\n].join('\\n');\n\nif (harness.split(quotaBranch).length !== 2) {\n throw new Error('Unexpected Copilot quota branch; re-audit the gh-aw upgrade');\n}\nfs.writeFileSync(harnessPath, harness.replace(quotaBranch, nonBlockingQuotaBranch));\nNODE"
- name: Download container images - name: Download container images
run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.28.23@sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2 ghcr.io/github/gh-aw-firewall/api-proxy:0.28.23@sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64 ghcr.io/github/gh-aw-firewall/squid:0.28.23@sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0 ghcr.io/github/gh-aw-mcpg:v0.4.25@sha256:9be0a86220e807a0ecc89e53d7453468f7a53fbc6b3d1efd2299025ffe01d086 ghcr.io/github/gh-aw-node@sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e ghcr.io/github/github-mcp-server:v1.12.2@sha256:508a0857ec762b1ab1cece29193345b501fab1dd9d1228a7b617062954cecac6 run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.28.23@sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2 ghcr.io/github/gh-aw-firewall/api-proxy:0.28.23@sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64 ghcr.io/github/gh-aw-firewall/squid:0.28.23@sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0 ghcr.io/github/gh-aw-mcpg:v0.4.25@sha256:9be0a86220e807a0ecc89e53d7453468f7a53fbc6b3d1efd2299025ffe01d086 ghcr.io/github/gh-aw-node@sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e ghcr.io/github/github-mcp-server:v1.12.2@sha256:508a0857ec762b1ab1cece29193345b501fab1dd9d1228a7b617062954cecac6
+5 -9
View File
@@ -41,17 +41,13 @@ pre-agent-steps:
' }', ' }',
].join('\n'); ].join('\n');
const nonBlockingQuotaBranch = [ const nonBlockingQuotaBranch = [
' let quotaErrorMsg = null;',
' if (isQuotaExceeded) {', ' if (isQuotaExceeded) {',
' log(`attempt ${attempt + 1}: Copilot quota exceeded — not retrying`);', ' log(`attempt ${attempt + 1}: Copilot quota exceeded — not retrying`);',
' quotaErrorMsg = { action: "stop" };', ' if (/\\b429\\b|Too Many Requests/i.test(result.output)) {',
' }', ' log(`attempt ${attempt + 1}: Copilot quota unavailable — exiting 0`);',
' if (/\\b429\\b|Too Many Requests/i.test(result.output)) {', ' return { action: "stop", exitCode: 0 };',
' log(`attempt ${attempt + 1}: Copilot quota unavailable — exiting 0`);', ' }',
' quotaErrorMsg = { action: "stop", exitCode: 0 };', ' return { action: "stop" };',
' }',
' if (quotaErrorMsg) {',
' return quotaErrorMsg;',
' }', ' }',
].join('\n'); ].join('\n');
-90
View File
@@ -1,90 +0,0 @@
name: SignPath Test
on:
workflow_dispatch:
permissions:
contents: read
actions: read
env:
CARGO_INCREMENTAL: 0
HUSKY: 0
jobs:
sign-windows:
runs-on: windows-latest
timeout-minutes: 90
steps:
- name: Checkout repository
uses: actions/checkout@v7
- name: Install Rust
uses: dtolnay/rust-toolchain@master
with:
toolchain: '1.99.0'
targets: x86_64-pc-windows-msvc
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '24.21.0'
- name: Install pnpm
uses: pnpm/action-setup@v6
with:
run_install: false
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Prepare build resources
run: pnpm run prebuild x86_64-pc-windows-msvc
- name: Build test installer
shell: pwsh
env:
NODE_OPTIONS: '--max-old-space-size=4096'
run: |
$configPath = Join-Path $env:RUNNER_TEMP 'signpath-test.json'
'{"bundle":{"createUpdaterArtifacts":false}}' |
Set-Content -LiteralPath $configPath -Encoding utf8
pnpm exec tauri build --target x86_64-pc-windows-msvc --bundles nsis --config $configPath
- name: Upload unsigned installer
id: unsigned
uses: actions/upload-artifact@v7
with:
name: windows-x64-unsigned
path: target/x86_64-pc-windows-msvc/release/bundle/nsis/*-setup.exe
if-no-files-found: error
- name: Sign with SignPath test certificate
uses: signpath/github-action-submit-signing-request@v3
with:
api-token: ${{ secrets.SIGNPATH_API_TOKEN }}
organization-id: '5b298f4d-010d-4bae-b665-70551a58839c'
project-slug: 'clash-verge-rev'
signing-policy-slug: 'test-signing'
artifact-configuration-slug: 'initial'
github-artifact-id: ${{ steps.unsigned.outputs.artifact-id }}
wait-for-completion: true
output-artifact-directory: signed
- name: Inspect installer signature
shell: pwsh
run: |
Get-ChildItem -Path signed/*-setup.exe | ForEach-Object {
$signature = Get-AuthenticodeSignature -LiteralPath $_.FullName
if (-not $signature.SignerCertificate) {
throw "No Authenticode signer certificate found for $($_.Name)"
}
$signature | Format-List Path, Status, StatusMessage, SignerCertificate
}
- name: Upload signed test installer
uses: actions/upload-artifact@v7
with:
name: windows-x64-test-signed
path: signed/*-setup.exe
if-no-files-found: error
-1
View File
@@ -5,5 +5,4 @@ if ! command -v "cargo-make" >/dev/null 2>&1; then
cargo install --force cargo-make cargo install --force cargo-make
fi fi
node scripts/check-contract-changes.mjs --push "$1" || exit $?
cargo make pre-push cargo make pre-push
+1 -1
View File
@@ -1,3 +1,3 @@
nodejs 24.21.0 nodejs 24.21.0
pnpm 12.11.2 pnpm 12.10.0
rust 1.99.0 rust 1.99.0
Generated
+431 -362
View File
File diff suppressed because it is too large Load Diff
+8 -12
View File
@@ -49,15 +49,12 @@ split-debuginfo = "unpacked"
[patch.crates-io] [patch.crates-io]
# Backport Windows menu command ID recycling on the muda 0.20 compatibility branch. # Backport Windows menu command ID recycling on the muda 0.20 compatibility branch.
muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdfa785f20f3c7ece8468e2" } muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdfa785f20f3c7ece8468e2" }
# tauri-specta has no tauri 3 release yet; ride the tauri team's port and the
# unpublished specta rc.26 line it pins. Drop all six entries once both ship # macOS Golden Gate fix for tray-icon click reentrancy issue
# on crates.io. # Remove the following patch once the fix is merged upstream(tauri)
tauri-specta = { git = "https://github.com/tauri-apps/tauri-specta", branch = "tauri-v3" } # https://github.com/tauri-apps/tray-icon/pull/365
specta = { git = "https://github.com/specta-rs/specta.git", rev = "2757fa8899926dce7da999780c7edf2dc08a732a" } tray-icon = { git = "https://github.com/Tunglies/tray-icon.git", branch = "fix/macos-27-click-reentrancy" }
specta-macros = { git = "https://github.com/specta-rs/specta.git", rev = "2757fa8899926dce7da999780c7edf2dc08a732a" }
specta-serde = { git = "https://github.com/specta-rs/specta.git", rev = "2757fa8899926dce7da999780c7edf2dc08a732a" }
specta-typescript = { git = "https://github.com/specta-rs/specta.git", rev = "2757fa8899926dce7da999780c7edf2dc08a732a" }
specta-util = { git = "https://github.com/specta-rs/specta.git", rev = "2757fa8899926dce7da999780c7edf2dc08a732a" }
[workspace.dependencies] [workspace.dependencies]
clash-verge-draft = { path = "crates/clash-verge-draft" } clash-verge-draft = { path = "crates/clash-verge-draft" }
clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" } clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" }
@@ -69,9 +66,8 @@ 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 = "3.0.0-alpha.4" } tauri = { version = "2.12.2" }
tauri-runtime-wry = "3.0.0-alpha.4" tauri-plugin-clipboard-manager = "2.4.1"
tauri-plugin-clipboard-manager = "3.0.0-alpha.2"
parking_lot = { version = "0.12.5", features = ["hardware-lock-elision"] } parking_lot = { version = "0.12.5", features = ["hardware-lock-elision"] }
anyhow = "1.0.104" anyhow = "1.0.104"
chrono = "0.4.45" chrono = "0.4.45"
+30 -3
View File
@@ -1,24 +1,51 @@
## v2.5.9 ## v2.5.8
<details> <details>
<summary><strong> 🐞 修复问题 </strong></summary> <summary><strong> 🐞 修复问题 </strong></summary>
- 修复通过 URL 导入订阅时,即使导入的订阅并非当前使用的订阅,也会重新加载当前配置的问题 - 修复系统托盘代理组行不显示延迟、超时项与未测过项无法区分的问题
- 修复不同订阅源的同名节点测速和延迟显示指向错误节点的问题
- 修复端口设置混淆保存值与运行值、输入无效时缺少提示的问题
- 修复已有内核进程阻止启动时缺少多语言说明和处理建议的问题
- 修复从开始菜单再次打开应用后,窗口反复弹出并提示启动失败的问题
- 修复多个代理集合包含同名节点时,代理组中的节点变灰并显示 ambiguous、无法选择的问题
- 修复手动更新时重复下载后台已下载的安装包、启动时选「稍后」后每次启动都重新下载的问题
- 修复下载更新时镜像缓慢或卡住不会切换下载地址、点击「取消」无法中止下载的问题
- 修复关闭「自动检查更新」后,启动时仍弹出已下载更新的安装提示的问题
- 修复从 Dock 退出、注销或关机时,应用可能长时间卡住无法退出的问题
- 修复宽窗口下「订阅」页每行显示过多卡片,导致配置名称被截断的问题
**🖥️ Windows**
- 修复 Windows 升级后因文件权限异常无法启动、需要手动清理配置的问题
- 修复 Windows 服务启动类型被改为手动后,软件启动卡住约两分钟的问题,并提供一键修复
- 修复 Windows 长时间运行后,托盘菜单点击无响应的问题
**🍎 macOS**
- 修复 macOS 关闭 TUN 或退出后,系统 DNS 仍停留在 `114.114.114.114` 导致无法解析域名的问题
**🖥️/🍎 Windows/macOS**
- 修复 Windows/macOS 打开系统托盘菜单时,节点延迟与自动选择状态未刷新的问题
</details> </details>
<details> <details>
<summary><strong> ✨ 新增功能 </strong></summary> <summary><strong> ✨ 新增功能 </strong></summary>
- 新增系统托盘代理组中的「测试延迟」菜单项
</details> </details>
<details> <details>
<summary><strong> 🚀 优化改进 </strong></summary> <summary><strong> 🚀 优化改进 </strong></summary>
- 优化端口设置窗口的实现,精简重复代码
- 优化侧边栏流量图表的 CPU 占用
**🖥️ Windows** **🖥️ Windows**
- Windows 系统代理默认绕过 `*.local` 域名,访问局域网设备的 `.local` 主机名时不再经过代理 - 优化 Windows 服务安全检查未通过时的提示:启动、安装或修复服务时说明原因与内核占用,并提供处理方法
</details> </details>
-2
View File
@@ -70,8 +70,6 @@ tray:
global: Global global: Global
profiles: Perfis profiles: Perfis
proxies: Proxies proxies: Proxies
testLatency: Test Latency
testingLatency: Testing latency…
systemProxy: Proxy do sistema systemProxy: Proxy do sistema
tunMode: Modo TUN tunMode: Modo TUN
closeAllConnections: Fechar todas as conexões closeAllConnections: Fechar todas as conexões
@@ -4,7 +4,6 @@ version = "0.1.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
specta = { version = "=2.0.0-rc.26", features = ["derive", "function"] }
clash-verge-logging = { workspace = true } clash-verge-logging = { workspace = true }
chrono = { workspace = true } chrono = { workspace = true }
log = { workspace = true } log = { workspace = true }
+1 -1
View File
@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
use super::utils::{country_code_to_emoji, get_local_date_string}; use super::utils::{country_code_to_emoji, get_local_date_string};
#[derive(Debug, Clone, Serialize, Deserialize, specta::Type)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnlockItem { pub struct UnlockItem {
pub name: String, pub name: String,
pub status: String, pub status: String,
@@ -5,7 +5,6 @@ edition = "2024"
rust-version = "1.91" rust-version = "1.91"
[dependencies] [dependencies]
specta = { version = "=2.0.0-rc.26", features = ["derive", "function"] }
tauri = { workspace = true } tauri = { workspace = true }
tauri-plugin-clipboard-manager = { workspace = true } tauri-plugin-clipboard-manager = { workspace = true }
parking_lot = { workspace = true } parking_lot = { workspace = true }
@@ -1,46 +1,53 @@
use parking_lot::RwLock; use parking_lot::RwLock;
use serde::Serialize; use serde::Serialize;
use tauri::{AppHandle, Runtime, State, command}; use tauri::{AppHandle, Runtime, State, command};
use tauri_plugin_clipboard_manager::ClipboardExt as _; use tauri_plugin_clipboard_manager::{ClipboardExt as _, Error};
use crate::Platform; use crate::Platform;
#[derive(Serialize, specta::Type)] #[derive(Serialize)]
pub struct SystemInfo { pub struct SystemInfo {
pub system_name: String, pub system_name: String,
pub system_version: String, pub system_version: String,
pub system_kernel_version: String,
pub system_arch: String,
pub app_version: String,
pub app_core_mode: String,
pub app_is_admin: bool,
} }
impl From<&Platform> for SystemInfo { impl From<Platform> for SystemInfo {
fn from(platform: &Platform) -> Self { fn from(platform: Platform) -> Self {
Self { Self {
system_name: platform.sysinfo.system_name.clone(), system_name: platform.sysinfo.system_name,
system_version: platform.sysinfo.system_version.clone(), system_version: platform.sysinfo.system_version,
system_kernel_version: platform.sysinfo.system_kernel_version,
system_arch: platform.sysinfo.system_arch,
app_version: platform.appinfo.app_version,
app_core_mode: platform.appinfo.app_core_mode,
app_is_admin: platform.appinfo.app_is_admin,
} }
} }
} }
#[command] #[command]
#[specta::specta] pub fn get_system_info(state: State<'_, RwLock<Platform>>) -> Result<SystemInfo, Error> {
pub fn get_system_info(state: State<'_, RwLock<Platform>>) -> Result<SystemInfo, String> {
let platform = state.inner().read(); let platform = state.inner().read();
Ok(SystemInfo::from(&*platform)) Ok(SystemInfo::from(platform.clone()))
} }
/// 获取应用的运行时间(毫秒) /// 获取应用的运行时间(毫秒)
#[command] #[command]
#[specta::specta] pub fn get_app_uptime(state: State<'_, RwLock<Platform>>) -> Result<u128, Error> {
pub fn get_app_uptime(state: State<'_, RwLock<Platform>>) -> Result<u128, String> {
Ok(state.inner().read().appinfo.app_startup_time.elapsed().as_millis()) Ok(state.inner().read().appinfo.app_startup_time.elapsed().as_millis())
} }
#[command] #[command]
#[specta::specta]
pub fn export_diagnostic_info<R: Runtime>( pub fn export_diagnostic_info<R: Runtime>(
app_handle: AppHandle<R>, app_handle: AppHandle<R>,
state: State<'_, RwLock<Platform>>, state: State<'_, RwLock<Platform>>,
) -> Result<(), String> { ) -> Result<(), Error> {
let info = state.inner().read().to_string(); let info = state.inner().read().to_string();
let clipboard = app_handle.clipboard(); let clipboard = app_handle.clipboard();
clipboard.write_text(info).map_err(|error| error.to_string()) clipboard.write_text(info)
} }
-52
View File
@@ -1,55 +1,3 @@
## v2.5.8
<details>
<summary><strong> 🐞 修复问题 </strong></summary>
- 修复系统托盘代理组行不显示延迟、超时项与未测过项无法区分的问题
- 修复不同订阅源的同名节点测速和延迟显示指向错误节点的问题
- 修复端口设置混淆保存值与运行值、输入无效时缺少提示的问题
- 修复已有内核进程阻止启动时缺少多语言说明和处理建议的问题
- 修复从开始菜单再次打开应用后,窗口反复弹出并提示启动失败的问题
- 修复多个代理集合包含同名节点时,代理组中的节点变灰并显示 ambiguous、无法选择的问题
- 修复手动更新时重复下载后台已下载的安装包、启动时选「稍后」后每次启动都重新下载的问题
- 修复下载更新时镜像缓慢或卡住不会切换下载地址、点击「取消」无法中止下载的问题
- 修复关闭「自动检查更新」后,启动时仍弹出已下载更新的安装提示的问题
- 修复从 Dock 退出、注销或关机时,应用可能长时间卡住无法退出的问题
- 修复宽窗口下「订阅」页每行显示过多卡片,导致配置名称被截断的问题
**🖥️ Windows**
- 修复 Windows 升级后因文件权限异常无法启动、需要手动清理配置的问题
- 修复 Windows 服务启动类型被改为手动后,软件启动卡住约两分钟的问题,并提供一键修复
- 修复 Windows 长时间运行后,托盘菜单点击无响应的问题
**🍎 macOS**
- 修复 macOS 关闭 TUN 或退出后,系统 DNS 仍停留在 `114.114.114.114` 导致无法解析域名的问题
**🖥️/🍎 Windows/macOS**
- 修复 Windows/macOS 打开系统托盘菜单时,节点延迟与自动选择状态未刷新的问题
</details>
<details>
<summary><strong> ✨ 新增功能 </strong></summary>
- 新增系统托盘代理组中的「测试延迟」菜单项
</details>
<details>
<summary><strong> 🚀 优化改进 </strong></summary>
- 优化端口设置窗口的实现,精简重复代码
- 优化侧边栏流量图表的 CPU 占用
**🖥️ Windows**
- 优化 Windows 服务安全检查未通过时的提示:启动、安装或修复服务时说明原因与内核占用,并提供处理方法
</details>
## v2.5.7 ## v2.5.7
<details> <details>
-115
View File
@@ -12,92 +12,6 @@ import pluginUnusedImports from 'eslint-plugin-unused-imports'
import globals from 'globals' import globals from 'globals'
import tseslint from 'typescript-eslint' import tseslint from 'typescript-eslint'
const ipcBoundaryRules = ({
allowCommands = false,
allowInvoke = false,
allowEvents = false,
} = {}) => {
const paths = [
...(!allowInvoke
? [
{
name: '@tauri-apps/api/core',
importNames: ['invoke'],
allowTypeImports: true,
message: 'Invoke backend commands through services/cmds.',
},
]
: []),
...(!allowEvents
? [
{
name: '@tauri-apps/api/event',
importNames: ['listen', 'emit', 'emitTo', 'once'],
allowTypeImports: true,
message:
'The event bus owns Tauri event subscriptions and emissions.',
},
]
: []),
]
const patterns = allowCommands
? []
: [
{
regex: '(^|/)bindings(\\.ts)?$',
importNames: ['commands'],
allowTypeImports: true,
message:
'Only services/cmds may import generated command implementations.',
},
]
const modules = [
...(!allowInvoke ? ['@tauri-apps/api/core'] : []),
...(!allowEvents ? ['@tauri-apps/api/event'] : []),
]
const syntax = modules.flatMap((name) => [
{
selector: `ImportExpression[source.value='${name}']`,
message:
'Use the owned IPC service boundary instead of dynamically importing Tauri APIs.',
},
{
selector: `CallExpression[callee.name='require'][arguments.0.value='${name}']`,
message:
'Use the owned IPC service boundary instead of requiring Tauri APIs.',
},
{
selector: `TSImportEqualsDeclaration[moduleReference.expression.value='${name}']`,
message: 'Use the owned IPC service boundary for Tauri APIs.',
},
])
if (!allowCommands) {
syntax.push(
{
selector: 'ImportExpression[source.value=/bindings(\\.ts)?$/]',
message:
'Only services/cmds may load generated command implementations.',
},
{
selector:
"CallExpression[callee.name='require'][arguments.0.value=/bindings(\\.ts)?$/]",
message:
'Only services/cmds may load generated command implementations.',
},
{
selector:
'TSImportEqualsDeclaration[moduleReference.expression.value=/bindings(\\.ts)?$/]',
message:
'Only services/cmds may load generated command implementations.',
},
)
}
return {
'no-restricted-imports': ['error', { paths, patterns }],
'no-restricted-syntax': ['error', ...syntax],
}
}
export default defineConfig([ export default defineConfig([
pluginESx.configs['flat/restrict-to-es2022'], pluginESx.configs['flat/restrict-to-es2022'],
{ {
@@ -248,33 +162,4 @@ export default defineConfig([
}, },
}, },
}, },
{
files: ['src/**/*.{ts,tsx,js,jsx,mts,mjs}'],
rules: ipcBoundaryRules(),
},
{
files: ['src/services/cmds.ts'],
rules: ipcBoundaryRules({ allowCommands: true }),
},
{
files: ['src/services/bindings.ts'],
rules: ipcBoundaryRules({ allowCommands: true, allowInvoke: true }),
},
{
files: ['src/services/bus/**/*.{ts,tsx}'],
rules: ipcBoundaryRules({ allowEvents: true }),
},
{
files: [
'src/components/proxy/proxy-chain.tsx',
'src/components/proxy/proxy-groups-chain.tsx',
'src/pages/proxies.tsx',
],
rules: {
'@typescript-eslint/no-floating-promises': [
'error',
{ ignoreVoid: false },
],
},
},
]) ])
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"$schema": "https://unpkg.com/knip@6/schema.json", "$schema": "https://unpkg.com/knip@6/schema.json",
"entry": ["src/polyfills/*.js!", "scripts/check-contract-changes.mjs!"], "entry": ["src/polyfills/*.js!"],
"project": ["src/**/*.{js,jsx,ts,tsx,sass,scss}!", "scripts/**/*.{js,mjs}!"], "project": ["src/**/*.{js,jsx,ts,tsx,sass,scss}!", "scripts/**/*.{js,mjs}!"],
"include": [ "include": [
"files", "files",
@@ -18,7 +18,7 @@
"ignoreDependencies": ["lint-staged"], "ignoreDependencies": ["lint-staged"],
"ignoreIssues": { "ignoreIssues": {
"src/types/generated/**": ["exports", "types"], "src/types/generated/**": ["exports", "types"],
"src/services/bindings.ts": ["types"] "src/services/contract.ts": ["exports", "types"]
}, },
"cycles": { "cycles": {
"dynamicImports": true "dynamicImports": true
+10 -10
View File
@@ -1,6 +1,6 @@
{ {
"name": "clash-verge", "name": "clash-verge",
"version": "2.5.9", "version": "2.5.8",
"license": "GPL-3.0-only", "license": "GPL-3.0-only",
"scripts": { "scripts": {
"prepare": "husky || true", "prepare": "husky || true",
@@ -54,13 +54,13 @@
"@mui/icons-material": "^9.4.0", "@mui/icons-material": "^9.4.0",
"@mui/material": "^9.4.0", "@mui/material": "^9.4.0",
"@tanstack/react-virtual": "^3.14.13", "@tanstack/react-virtual": "^3.14.13",
"@tauri-apps/api": "3.0.0-alpha.2", "@tauri-apps/api": "2.12.1",
"@tauri-apps/plugin-clipboard-manager": "^3.0.0-alpha.2", "@tauri-apps/plugin-clipboard-manager": "2.4.0",
"@tauri-apps/plugin-dialog": "^3.0.0-alpha.3", "@tauri-apps/plugin-dialog": "2.8.0",
"@tauri-apps/plugin-fs": "^3.0.0-alpha.2", "@tauri-apps/plugin-fs": "2.6.0",
"@tauri-apps/plugin-http": "~3.0.0-alpha.2", "@tauri-apps/plugin-http": "2.8.0",
"@tauri-apps/plugin-opener": "3.0.0-alpha.2", "@tauri-apps/plugin-opener": "2.7.0",
"@tauri-apps/plugin-updater": "3.0.0-alpha.2", "@tauri-apps/plugin-updater": "2.13.1",
"ahooks": "^3.10.0", "ahooks": "^3.10.0",
"cidr-block": "^2.3.0", "cidr-block": "^2.3.0",
"compare-versions": "^6.1.1", "compare-versions": "^6.1.1",
@@ -95,7 +95,7 @@
"@biomejs/biome": "^2.5.14", "@biomejs/biome": "^2.5.14",
"@eslint-react/eslint-plugin": "^5.20.5", "@eslint-react/eslint-plugin": "^5.20.5",
"@eslint/js": "^10.0.1", "@eslint/js": "^10.0.1",
"@tauri-apps/cli": "3.0.0-alpha.4", "@tauri-apps/cli": "2.12.1",
"@types/lodash-es": "^4.17.12", "@types/lodash-es": "^4.17.12",
"@types/node": "^24.13.6", "@types/node": "^24.13.6",
"@types/react": "19.3.0", "@types/react": "19.3.0",
@@ -146,5 +146,5 @@
] ]
}, },
"type": "module", "type": "module",
"packageManager": "pnpm@12.11.2" "packageManager": "pnpm@12.10.0"
} }
+148 -153
View File
@@ -7,153 +7,153 @@ importers:
configDependencies: {} configDependencies: {}
packageManagerDependencies: packageManagerDependencies:
pnpm: pnpm:
specifier: 12.11.2 specifier: 12.10.0
version: 12.11.2 version: 12.10.0
packages: packages:
'@pnpm/exe.android-arm64@12.11.2': '@pnpm/exe.android-arm64@12.10.0':
resolution: {integrity: sha512-owLw13OfPkEoY+hLBNeeG+dCFhywr7q2d/EHPz4mNL2RhKnv8gNwMARkjkiDQu234aItVwFNDeGnmQXm+ikkAg==} resolution: {integrity: sha512-QMMRzOI/7CU4xLbKY6O2BZn3VI4+a8LLyim18H7it8llBWuBPMqDqUURE8045k+7lI8/lI2/tElhyKptEviKDQ==}
cpu: [arm64] cpu: [arm64]
os: [android] os: [android]
'@pnpm/exe.android-x64@12.11.2': '@pnpm/exe.android-x64@12.10.0':
resolution: {integrity: sha512-GYPkVebl4iokOA/4MPSpGoUVfFlsth7uqOCe1XiaiM23LAdvUOMJBObqHJijr89ZqjwHm9pO6vO45GRwJ2U2qA==} resolution: {integrity: sha512-41zwlROW+t523Nfqo4rWp8IPiSK5vnAWrnCey26Je45rX1SMNc4ABY7OFmPw41/t+Y0CE+4tjTj+0s9YGqPM5w==}
cpu: [x64] cpu: [x64]
os: [android] os: [android]
'@pnpm/exe.darwin-arm64@12.11.2': '@pnpm/exe.darwin-arm64@12.10.0':
resolution: {integrity: sha512-n9M4On66y8FDxUAKgMO1FXt0qihyG4e+56p3/F0uo8Bx9KplW8BwKVnXigzCJ8aNM6sVVPkOE6M9XXbeVIxnZA==} resolution: {integrity: sha512-L+r7AD8Fjf8Vcc4ZRJl+Pjzc27CIeQ/FiRwPmOluFO2UcXubmGHdW+OuMUxrU0vkoXiGR61Ft0RtaPwTRY4W/g==}
cpu: [arm64] cpu: [arm64]
os: [darwin] os: [darwin]
'@pnpm/exe.darwin-x64@12.11.2': '@pnpm/exe.darwin-x64@12.10.0':
resolution: {integrity: sha512-oSW7n3sBT0c0cyk4kj10T2Y6Mpm+OFEiCAWozgX039tdoI6yqJF1uaFD3sw7ugLdu6VV3+uY0pa1TUZIPdxDWA==} resolution: {integrity: sha512-/TCF1K6E+4PnbkLgqGS1Iqlf5bHp6FDzuXgu6++PMMAFkF7Yk5EF3BcfG1gYYjpkvlJBccvVMsRBnWFbSyqu1w==}
cpu: [x64] cpu: [x64]
os: [darwin] os: [darwin]
'@pnpm/exe.freebsd-x64@12.11.2': '@pnpm/exe.freebsd-x64@12.10.0':
resolution: {integrity: sha512-qbzc3KoDpa/Lkf8vs3jnDe6dUUbso+6eLIyssYFMiliLpYNxn8dirk11YoNnOQcdHVB50v5RFls1Yid6ttT5pg==} resolution: {integrity: sha512-k7/WFA91E2qhnR/2EOEv402U8bjP758y2pybbdiB5Hrd4KhgviVOJp5cFrXpKgd8HZJs/RZN7cdmMvU2Q2BVgg==}
cpu: [x64] cpu: [x64]
os: [freebsd] os: [freebsd]
'@pnpm/exe.linux-arm64-musl@12.11.2': '@pnpm/exe.linux-arm64-musl@12.10.0':
resolution: {integrity: sha512-uMEYDwKRktGwANubQ+kYCwmhNwg3Ik6qK89ahsbQ5cP30R/5FVJb/T99vr9XRUBC/A7mZI6eeT92oyVas9ACyg==} resolution: {integrity: sha512-ChD8bN0lRCRaL+CMOaMUgZQ4WHzEkDXmDHrZgXgdoo6yymQKKzr66Ic7Sl/D7Ky1cVUcFEzHjlq4fGDJwt6Lqg==}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
libc: [musl] libc: [musl]
'@pnpm/exe.linux-arm64@12.11.2': '@pnpm/exe.linux-arm64@12.10.0':
resolution: {integrity: sha512-6e8ZAQUwFXAWHHHv5FesWqf/kEK04wuitBv5f/gxzkC0DiBfaixr+f+6JQede8SF4Ji5LcMwVFJbzAtffpWxEg==} resolution: {integrity: sha512-egl5RUSQFh7kETBdmMhaTuaQKP1pjH6Cxq370zgpFFKJXF+GGkIzK+jLNazrjX9pKIWF3iqn7kUeyP6yKxzBoA==}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@pnpm/exe.linux-ppc64@12.11.2': '@pnpm/exe.linux-ppc64@12.10.0':
resolution: {integrity: sha512-Ui8A4nepkVupx2VpuFfysEluMvWK6gTB5rgVts7Ss/+8dj0RD28x3F/seNeH/zSypgC6yKdV6qsKVQh/uffTuQ==} resolution: {integrity: sha512-YJ6bEZ+stPpv71CGfGQQeyIpMx/zSMEcAXQzG+rjBtzVfyNsxYciRevhJ+PE9b2qKqN78Mh/1tOMmx9ly4VXGw==}
cpu: [ppc64] cpu: [ppc64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@pnpm/exe.linux-riscv64@12.11.2': '@pnpm/exe.linux-riscv64@12.10.0':
resolution: {integrity: sha512-i1yLdQ5bu+wjQ+srtFoJAaY2gN/+oXHFdjul4llCeoDxHE0rTIG3R41NhHfCjyFPW4+CpbBT58933CL9sMOCnA==} resolution: {integrity: sha512-njfd4euctC1zH1nVBbm6+r1c+0y/TtgqN523rk/KMSxqItpV5QAVa9Yz48Rt5DOIKmuLq7xXOhsQodBlbTk3pw==}
cpu: [riscv64] cpu: [riscv64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@pnpm/exe.linux-s390x@12.11.2': '@pnpm/exe.linux-s390x@12.10.0':
resolution: {integrity: sha512-YS1/lhPjjTsN4QL50VaFZKRa3Uc/bDnhE8eKbJMFvuX06UuFS5YaiDg04APoZdfVSGqTfX27QAg7rfLMSWaqxA==} resolution: {integrity: sha512-4JI2F8pYGMcsG6ny61OiBSvZeDozc64TbPozbTU2X5uCsaFCsCvcpr/WwyypwCv+/mNjcIhaKhlxpwJYsnteIg==}
cpu: [s390x] cpu: [s390x]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@pnpm/exe.linux-x64-musl@12.11.2': '@pnpm/exe.linux-x64-musl@12.10.0':
resolution: {integrity: sha512-7eIxQR05fvJxCujUSKp5KTtehJ7QqrgqP/HD1+BcB/SaV2Be4XI1PEHiOgA1zxsiMIeMvTF6E4G4dYHrFjeXRg==} resolution: {integrity: sha512-xayd2iG8ugdvjlGeOvsfm+iSe0bFu9RTX3/8HWOLAQmHdbLKi4hPbxP0S4c9tj8pNej/IxVBQLJksRXFlhNjPw==}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
libc: [musl] libc: [musl]
'@pnpm/exe.linux-x64@12.11.2': '@pnpm/exe.linux-x64@12.10.0':
resolution: {integrity: sha512-FK7QKe24AYgppJwO3mpooYptduuvIGqKJPi5ac7MdnWkjUy46JBfYhCW0grnkWKC8YOf0x+vGviuQqJEj3SpQQ==} resolution: {integrity: sha512-PFkzWEghFLKuocxMHtn57mlJ59f5aBbqjX6FCUtiunEHqxTxOibSduQPs3Llm6VWbAXBjD3VrX29Z+bjU1Dpyw==}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@pnpm/exe.win32-arm64@12.11.2': '@pnpm/exe.win32-arm64@12.10.0':
resolution: {integrity: sha512-PCTjVDdJb6VvraZxrEeFv6EqEA0hhIsAySx28e95J2Tqpi88hLpgOXgNqV0vpxq9A+b8GLQfyk/D+1UlJPv/YQ==} resolution: {integrity: sha512-0HtTS+TLONWd/dNSczyOkK0UeZ36cbdhC/2ljZ61DPhvc4jTb7ur0yU47On0in7Im3yXwzTY4vtF8ykrDwc+NQ==}
cpu: [arm64] cpu: [arm64]
os: [win32] os: [win32]
'@pnpm/exe.win32-x64@12.11.2': '@pnpm/exe.win32-x64@12.10.0':
resolution: {integrity: sha512-8sgX86OvRjJ3yZs/TvGR2L31wH9ScPZ+f+geKI3ikuB0RRiK3i4LlTRO8OXN6pdRqj8epMde4312MCjj7JsJdA==} resolution: {integrity: sha512-IcW3rehTGzJ7YnmHEWnbnJakjbBmnH0r29qiajK9+6b9psMF9IjocFr0dyitRVSfXxyW/FI5PIK3mOswGoyFTg==}
cpu: [x64] cpu: [x64]
os: [win32] os: [win32]
pnpm@12.11.2: pnpm@12.10.0:
resolution: {integrity: sha512-JaUWUqGWeFr18ovabf6NxYLr76SsHRgCIc4TkCMcX7dmN4IupLbkYzznSs3LCnf3Ja8RutOBd/3t2u6BipVcuQ==} resolution: {integrity: sha512-Eip7bd+dQCaLwNsal4CJm5Xk+out/Ke9RQYVrYz3wmWfX1acIO18U4hrx7CNDVClT0rVBwaEf1aC7GxQSEFlOQ==}
engines: {node: '>=18.*'} engines: {node: '>=18.*'}
hasBin: true hasBin: true
snapshots: snapshots:
'@pnpm/exe.android-arm64@12.11.2': '@pnpm/exe.android-arm64@12.10.0':
optional: true optional: true
'@pnpm/exe.android-x64@12.11.2': '@pnpm/exe.android-x64@12.10.0':
optional: true optional: true
'@pnpm/exe.darwin-arm64@12.11.2': '@pnpm/exe.darwin-arm64@12.10.0':
optional: true optional: true
'@pnpm/exe.darwin-x64@12.11.2': '@pnpm/exe.darwin-x64@12.10.0':
optional: true optional: true
'@pnpm/exe.freebsd-x64@12.11.2': '@pnpm/exe.freebsd-x64@12.10.0':
optional: true optional: true
'@pnpm/exe.linux-arm64-musl@12.11.2': '@pnpm/exe.linux-arm64-musl@12.10.0':
optional: true optional: true
'@pnpm/exe.linux-arm64@12.11.2': '@pnpm/exe.linux-arm64@12.10.0':
optional: true optional: true
'@pnpm/exe.linux-ppc64@12.11.2': '@pnpm/exe.linux-ppc64@12.10.0':
optional: true optional: true
'@pnpm/exe.linux-riscv64@12.11.2': '@pnpm/exe.linux-riscv64@12.10.0':
optional: true optional: true
'@pnpm/exe.linux-s390x@12.11.2': '@pnpm/exe.linux-s390x@12.10.0':
optional: true optional: true
'@pnpm/exe.linux-x64-musl@12.11.2': '@pnpm/exe.linux-x64-musl@12.10.0':
optional: true optional: true
'@pnpm/exe.linux-x64@12.11.2': '@pnpm/exe.linux-x64@12.10.0':
optional: true optional: true
'@pnpm/exe.win32-arm64@12.11.2': '@pnpm/exe.win32-arm64@12.10.0':
optional: true optional: true
'@pnpm/exe.win32-x64@12.11.2': '@pnpm/exe.win32-x64@12.10.0':
optional: true optional: true
pnpm@12.11.2: pnpm@12.10.0:
optionalDependencies: optionalDependencies:
'@pnpm/exe.android-arm64': 12.11.2 '@pnpm/exe.android-arm64': 12.10.0
'@pnpm/exe.android-x64': 12.11.2 '@pnpm/exe.android-x64': 12.10.0
'@pnpm/exe.darwin-arm64': 12.11.2 '@pnpm/exe.darwin-arm64': 12.10.0
'@pnpm/exe.darwin-x64': 12.11.2 '@pnpm/exe.darwin-x64': 12.10.0
'@pnpm/exe.freebsd-x64': 12.11.2 '@pnpm/exe.freebsd-x64': 12.10.0
'@pnpm/exe.linux-arm64': 12.11.2 '@pnpm/exe.linux-arm64': 12.10.0
'@pnpm/exe.linux-arm64-musl': 12.11.2 '@pnpm/exe.linux-arm64-musl': 12.10.0
'@pnpm/exe.linux-ppc64': 12.11.2 '@pnpm/exe.linux-ppc64': 12.10.0
'@pnpm/exe.linux-riscv64': 12.11.2 '@pnpm/exe.linux-riscv64': 12.10.0
'@pnpm/exe.linux-s390x': 12.11.2 '@pnpm/exe.linux-s390x': 12.10.0
'@pnpm/exe.linux-x64': 12.11.2 '@pnpm/exe.linux-x64': 12.10.0
'@pnpm/exe.linux-x64-musl': 12.11.2 '@pnpm/exe.linux-x64-musl': 12.10.0
'@pnpm/exe.win32-arm64': 12.11.2 '@pnpm/exe.win32-arm64': 12.10.0
'@pnpm/exe.win32-x64': 12.11.2 '@pnpm/exe.win32-x64': 12.10.0
--- ---
lockfileVersion: '9.0' lockfileVersion: '9.0'
@@ -200,26 +200,26 @@ importers:
specifier: ^3.14.13 specifier: ^3.14.13
version: 3.14.13(react-dom@19.3.0(react@19.3.0))(react@19.3.0) version: 3.14.13(react-dom@19.3.0(react@19.3.0))(react@19.3.0)
'@tauri-apps/api': '@tauri-apps/api':
specifier: 3.0.0-alpha.2 specifier: 2.12.1
version: 3.0.0-alpha.2 version: 2.12.1
'@tauri-apps/plugin-clipboard-manager': '@tauri-apps/plugin-clipboard-manager':
specifier: ^3.0.0-alpha.2 specifier: 2.4.0
version: 3.0.0-alpha.2 version: 2.4.0
'@tauri-apps/plugin-dialog': '@tauri-apps/plugin-dialog':
specifier: ^3.0.0-alpha.3 specifier: 2.8.0
version: 3.0.0-alpha.3 version: 2.8.0
'@tauri-apps/plugin-fs': '@tauri-apps/plugin-fs':
specifier: ^3.0.0-alpha.2 specifier: 2.6.0
version: 3.0.0-alpha.2 version: 2.6.0
'@tauri-apps/plugin-http': '@tauri-apps/plugin-http':
specifier: ~3.0.0-alpha.2 specifier: 2.8.0
version: 3.0.0-alpha.2 version: 2.8.0
'@tauri-apps/plugin-opener': '@tauri-apps/plugin-opener':
specifier: 3.0.0-alpha.2 specifier: 2.7.0
version: 3.0.0-alpha.2 version: 2.7.0
'@tauri-apps/plugin-updater': '@tauri-apps/plugin-updater':
specifier: 3.0.0-alpha.2 specifier: 2.13.1
version: 3.0.0-alpha.2 version: 2.13.1
ahooks: ahooks:
specifier: ^3.10.0 specifier: ^3.10.0
version: 3.10.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0) version: 3.10.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0)
@@ -318,8 +318,8 @@ importers:
specifier: ^10.0.1 specifier: ^10.0.1
version: 10.0.1(eslint@10.11.0(jiti@2.7.0)(supports-color@7.2.0)) version: 10.0.1(eslint@10.11.0(jiti@2.7.0)(supports-color@7.2.0))
'@tauri-apps/cli': '@tauri-apps/cli':
specifier: 3.0.0-alpha.4 specifier: 2.12.1
version: 3.0.0-alpha.4 version: 2.12.1
'@types/lodash-es': '@types/lodash-es':
specifier: ^4.17.12 specifier: ^4.17.12
version: 4.17.12 version: 4.17.12
@@ -2129,102 +2129,99 @@ packages:
'@tauri-apps/api@2.12.1': '@tauri-apps/api@2.12.1':
resolution: {integrity: sha512-DeyFHa3wynpyoqTDikDEDGTJIq4LQ5USfolQGRmGIWT6JMADyxZBTDa5cAdT3tDg73rUXufPaCwN7aXBos4OnQ==} resolution: {integrity: sha512-DeyFHa3wynpyoqTDikDEDGTJIq4LQ5USfolQGRmGIWT6JMADyxZBTDa5cAdT3tDg73rUXufPaCwN7aXBos4OnQ==}
'@tauri-apps/api@3.0.0-alpha.2': '@tauri-apps/cli-darwin-arm64@2.12.1':
resolution: {integrity: sha512-W5MTTRAsbNqxSO5hf6U6gHwtTfW0ZnEyIWkmn9L6XYWFcSi0n1JtVQAIsJ6EZHLpJkchGEFwSeVBy+IcrtXl4g==} resolution: {integrity: sha512-8bMnbpJ2jKO/ufrOPL65EMHC3ptw7fzeraoQkwibyfGLqIl+UCWsC0152kmNbW6r9NvVQduXqAZF5mH1QgTWhw==}
'@tauri-apps/cli-darwin-arm64@3.0.0-alpha.4':
resolution: {integrity: sha512-QSySr8o6f8nD/6e8BG9QYQTExlAhsiM2c6ewNti3kzcVzDh7WvM/Jya93mKhQrSjKumq7bUa/jlgmFB24P2oNA==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [arm64] cpu: [arm64]
os: [darwin] os: [darwin]
'@tauri-apps/cli-darwin-x64@3.0.0-alpha.4': '@tauri-apps/cli-darwin-x64@2.12.1':
resolution: {integrity: sha512-sx0fxH4CEWdWeB8THKzB4mF8P0ZXi1UXO/gVM4dzLjFpHcZbvMJ7B2cBeHNH3ED16aVKbbCGVYLDFVLh56x1Kg==} resolution: {integrity: sha512-G+2qte8GNqNlEZ9ftd21rbu/APVkl3r/nzNDI7LVxEoqJWVNe9GbEgQUMH1r4PHT20Z2UxR3KjCkltIb0e/Wjg==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [x64] cpu: [x64]
os: [darwin] os: [darwin]
'@tauri-apps/cli-linux-arm-gnueabihf@3.0.0-alpha.4': '@tauri-apps/cli-linux-arm-gnueabihf@2.12.1':
resolution: {integrity: sha512-eyABwsj3vJiyipJERTJCMYJfguXCxiL94Ux8SP9rwBao7cOEFgonhX2uG57/K4RekmZPFMekcfHp8JMXf88VCQ==} resolution: {integrity: sha512-5b3n4DaTW+A1Zntnh4Yn44VyLrlPEpB8kMOBRfWkzNnzolBk+AYhKIfKjCLmoC8Mob3ETodxAEOMkE2YPKEWzQ==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [arm] cpu: [arm]
os: [linux] os: [linux]
'@tauri-apps/cli-linux-arm64-gnu@3.0.0-alpha.4': '@tauri-apps/cli-linux-arm64-gnu@2.12.1':
resolution: {integrity: sha512-HmYCfjTlpn3mwMh5A2PeZud6QBZJbstTQDRCbs6ikd8t9GurSGTJINVbONrauNKUXYd37c8h5eEERRrkzqpK+w==} resolution: {integrity: sha512-APArHhDu+8pXSCkCQmvaz1nD3d8WTmlCoSS/oG475TJ6AATBvyQOAmf5qELgsQ4s2+8MOsop0Zd699RKELF1Cw==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@tauri-apps/cli-linux-arm64-musl@3.0.0-alpha.4': '@tauri-apps/cli-linux-arm64-musl@2.12.1':
resolution: {integrity: sha512-BgD2YHYkOLKJ8qIpiwnYmq1xMKhxwGEOeX+HRjyrtIb4Eonf4/qGKfH7AoN88MUjpUfm+Zn3AZ82bQBAFDhV9Q==} resolution: {integrity: sha512-JaCxcLoV0oGtllVkLr4UAHWG/wTfkEunnUqnsEsGYOp0VRxnUwHg63wFBD0jU2ul5eFfSLIDS4RF2gfzsSo5Jg==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
libc: [musl] libc: [musl]
'@tauri-apps/cli-linux-riscv64-gnu@3.0.0-alpha.4': '@tauri-apps/cli-linux-riscv64-gnu@2.12.1':
resolution: {integrity: sha512-AHl6DFQEtNDaI2YuIqNeSm7G3RWlHSz2R23+j1woFMXZjR48Dd7xSxthWybnxgy09Qw//8OeE5LX0u9oaC07ew==} resolution: {integrity: sha512-K5+VXM7+SGVDwZleA2+lMgvbTVuA5e1tkiVEawu1Yxj26ZyEfO8h8xTC1rBdRX2xgJDSwCk6vPUBCS6i+Z5slQ==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [riscv64] cpu: [riscv64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@tauri-apps/cli-linux-x64-gnu@3.0.0-alpha.4': '@tauri-apps/cli-linux-x64-gnu@2.12.1':
resolution: {integrity: sha512-sfLIf/Dr3fio2gGAIXvjDdhESeQDyVKTTuhXfKV361gcTcx+/OkkctVw1FBKgdtRqDP0JVQI9y8sXdhuL0F61A==} resolution: {integrity: sha512-Z1QGPr49HJZMktu+Spu6Q1b/f9ANadXvqZZZt2645ua1x1ev6prOgp85eiGv2jRzohFEMLo6aJyaLjLUX5KIvA==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@tauri-apps/cli-linux-x64-musl@3.0.0-alpha.4': '@tauri-apps/cli-linux-x64-musl@2.12.1':
resolution: {integrity: sha512-3aY8+4mvts+dia8VXfGhJYxhhU57fdcbL7IxKLrTt4ASrsXwCDspVf+yVfa0GKpsUWPIxsGA7dYt9oaviv8gkg==} resolution: {integrity: sha512-nHuEhRPOMSJ/8RRhtMRxB9B9lVr7xxpe4DapBz8x1GIau3vdzjHHJ1hAfmw+PyayPLZ6XoaVIHPgI17rX6ii8w==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
libc: [musl] libc: [musl]
'@tauri-apps/cli-win32-arm64-msvc@3.0.0-alpha.4': '@tauri-apps/cli-win32-arm64-msvc@2.12.1':
resolution: {integrity: sha512-m3hVaoWavJBGHrKPGjhyCVW+IIbXMTP2CvqqG7Ak6yoVJLEYYTwkwfEq/dMHpX9Spw9iQE5pONK1vTatcJ/jPQ==} resolution: {integrity: sha512-I0oPk2uGh86R8dAs2X5OxSP+/GqSc8jh1Px3l8EqrocSNivsRHDTh2k3PVOqdv163dlV6PIVvmhZAbH/lPfZrA==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [arm64] cpu: [arm64]
os: [win32] os: [win32]
'@tauri-apps/cli-win32-ia32-msvc@3.0.0-alpha.4': '@tauri-apps/cli-win32-ia32-msvc@2.12.1':
resolution: {integrity: sha512-v8J3IgwgFsOiuDPLCScYGAQjQZKj+46o1mMRVcx4gYo1JV9P6o/hblJX5nMT/oTTGdsAgao5PZNxUlX8WJGMFA==} resolution: {integrity: sha512-baNZRBfepAJ5qNFRMwzgBk94xQmkcmTZrNDjZjnzrq2vAaTC3NAhallb/zo3hyoCGQlMS13sdovktrg46NZz6Q==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [ia32] cpu: [ia32]
os: [win32] os: [win32]
'@tauri-apps/cli-win32-x64-msvc@3.0.0-alpha.4': '@tauri-apps/cli-win32-x64-msvc@2.12.1':
resolution: {integrity: sha512-BfEHaKBdNImxb9KOVji9hROEVnPWl2ImshQmV9ASC61jraX2/xCJ+YNdaAi7yA18qAyQVb/CszsfhFWJHT+YbA==} resolution: {integrity: sha512-dIFaKslrzcbesb+bBh+E1R9km241pHyj32w6D9FPtvQeYpRUFbiCLEa/2S+S0UnIytfxepp4P+X8IerGqnXeYg==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [x64] cpu: [x64]
os: [win32] os: [win32]
'@tauri-apps/cli@3.0.0-alpha.4': '@tauri-apps/cli@2.12.1':
resolution: {integrity: sha512-hu2CcWxH6yeo5CfLkEYvDOHW5aKdh0gY5DobR5UK+psBInfsc/qKetD0HA+Z41WvVQZsHJXk2uvPMUZP2ckAJg==} resolution: {integrity: sha512-kEDEiGzG+yAc5FeLxtXpES/VN+F2C8H0r4gDVtfRLKxT9np9101d9REG/Kgo2lr0hKi0IpDsODiHnU3+naOmLg==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
hasBin: true hasBin: true
'@tauri-apps/plugin-clipboard-manager@3.0.0-alpha.2': '@tauri-apps/plugin-clipboard-manager@2.4.0':
resolution: {integrity: sha512-87oq7PUtHZk0PZgvIp5KWsXWOIJtUz3qEiL+PFvV/dC4T4EByi+dx4/hZ+/BMiX7lchknPmA6WTmmx+530Xjgw==} resolution: {integrity: sha512-yAuTffXc/sm+4oYnrwxbUkaJXQMTesPJ9dim0ADcA31rpboyhAN2TGQqs9VCcPIpb60LFOeePkvhpP2I3xhejg==}
'@tauri-apps/plugin-dialog@3.0.0-alpha.3': '@tauri-apps/plugin-dialog@2.8.0':
resolution: {integrity: sha512-LjP/CwCaQ/uVhIjFbMG1JM9MY9+gvNchoRsQoOQpm1+y8dWKCb4/VFFXv+RuH6XbR11eIU6G+yL34hggc7iw2Q==} resolution: {integrity: sha512-HSSD5C8UFE9ijD1wue84F7jjaIReFmj8AAPtS+xyjYRltJafIc4BiWHY7SJ6vbbew6u+YljEJHfyNfy5VwywXg==}
'@tauri-apps/plugin-fs@3.0.0-alpha.2': '@tauri-apps/plugin-fs@2.6.0':
resolution: {integrity: sha512-w/pmQ5swWqEgQhWMabreK5eMIiAHXHFKdb/SWGrZF4tTpVky/dUAyScFl7XiFRKpfr5cHSDiZAP/dsg0Ud9p9w==} resolution: {integrity: sha512-MhBAZ4rryd+h9fijd/GWDfArqiAeGI0ZNduV4wuRyUVI6wDZ+oDBY7atqtoXKDwlTUVSvpvmWJAY0ehQd/v6Uw==}
'@tauri-apps/plugin-http@3.0.0-alpha.2': '@tauri-apps/plugin-http@2.8.0':
resolution: {integrity: sha512-imgCIw601u03ahDFu+ifiOKMAU6zab0taYp6h6Z7O9TcsU1SRqgXxbVcO84iLQ4bjELiFdAtUp0xqiNx+r8fvg==} resolution: {integrity: sha512-cPvZvfUSaBkqGxef/dgbh/iEl6T3jQfSJyypi9OdcWr1VcuTt4ZRlk9DLAHEHF2q2NML+0UOkjyXRPNo6Cky6g==}
'@tauri-apps/plugin-opener@3.0.0-alpha.2': '@tauri-apps/plugin-opener@2.7.0':
resolution: {integrity: sha512-T3Y7Y/m+XybZqB2cI6SZD8St47GBONPTbFp+hSYFLHy5Lh0eNh0sv9TRyi7MElzUtUx0NWZltAOHuHzeo2UfWA==} resolution: {integrity: sha512-mBorYfVKh9Lt7s4ZFtKbMUTxBw+Y/sVmSlKCtkkoBgMTC/DIbt/kaPm67L/2djAUqDI1wbixy5OHHVmipjuGMw==}
'@tauri-apps/plugin-updater@3.0.0-alpha.2': '@tauri-apps/plugin-updater@2.13.1':
resolution: {integrity: sha512-WHRIi50gV9M2JDx9VZLxlpcuA3gvd7eABaqfNQEQTdKUSuIWyS/gQcbH5LpiuSWSkCTMMInUUBmost2LdZnnkA==} resolution: {integrity: sha512-+STDzJ0sdQLImjc63zkv6Nncimqeo6jyCWoTQtbSwgGLNj1qbP9I6LC4p5R5ocBk3gNKAZs6i/AJz0jxysytiw==}
'@tybys/wasm-util@0.10.4': '@tybys/wasm-util@0.10.4':
resolution: {integrity: sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==} resolution: {integrity: sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==}
@@ -6910,78 +6907,76 @@ snapshots:
'@tauri-apps/api@2.12.1': {} '@tauri-apps/api@2.12.1': {}
'@tauri-apps/api@3.0.0-alpha.2': {} '@tauri-apps/cli-darwin-arm64@2.12.1':
'@tauri-apps/cli-darwin-arm64@3.0.0-alpha.4':
optional: true optional: true
'@tauri-apps/cli-darwin-x64@3.0.0-alpha.4': '@tauri-apps/cli-darwin-x64@2.12.1':
optional: true optional: true
'@tauri-apps/cli-linux-arm-gnueabihf@3.0.0-alpha.4': '@tauri-apps/cli-linux-arm-gnueabihf@2.12.1':
optional: true optional: true
'@tauri-apps/cli-linux-arm64-gnu@3.0.0-alpha.4': '@tauri-apps/cli-linux-arm64-gnu@2.12.1':
optional: true optional: true
'@tauri-apps/cli-linux-arm64-musl@3.0.0-alpha.4': '@tauri-apps/cli-linux-arm64-musl@2.12.1':
optional: true optional: true
'@tauri-apps/cli-linux-riscv64-gnu@3.0.0-alpha.4': '@tauri-apps/cli-linux-riscv64-gnu@2.12.1':
optional: true optional: true
'@tauri-apps/cli-linux-x64-gnu@3.0.0-alpha.4': '@tauri-apps/cli-linux-x64-gnu@2.12.1':
optional: true optional: true
'@tauri-apps/cli-linux-x64-musl@3.0.0-alpha.4': '@tauri-apps/cli-linux-x64-musl@2.12.1':
optional: true optional: true
'@tauri-apps/cli-win32-arm64-msvc@3.0.0-alpha.4': '@tauri-apps/cli-win32-arm64-msvc@2.12.1':
optional: true optional: true
'@tauri-apps/cli-win32-ia32-msvc@3.0.0-alpha.4': '@tauri-apps/cli-win32-ia32-msvc@2.12.1':
optional: true optional: true
'@tauri-apps/cli-win32-x64-msvc@3.0.0-alpha.4': '@tauri-apps/cli-win32-x64-msvc@2.12.1':
optional: true optional: true
'@tauri-apps/cli@3.0.0-alpha.4': '@tauri-apps/cli@2.12.1':
optionalDependencies: optionalDependencies:
'@tauri-apps/cli-darwin-arm64': 3.0.0-alpha.4 '@tauri-apps/cli-darwin-arm64': 2.12.1
'@tauri-apps/cli-darwin-x64': 3.0.0-alpha.4 '@tauri-apps/cli-darwin-x64': 2.12.1
'@tauri-apps/cli-linux-arm-gnueabihf': 3.0.0-alpha.4 '@tauri-apps/cli-linux-arm-gnueabihf': 2.12.1
'@tauri-apps/cli-linux-arm64-gnu': 3.0.0-alpha.4 '@tauri-apps/cli-linux-arm64-gnu': 2.12.1
'@tauri-apps/cli-linux-arm64-musl': 3.0.0-alpha.4 '@tauri-apps/cli-linux-arm64-musl': 2.12.1
'@tauri-apps/cli-linux-riscv64-gnu': 3.0.0-alpha.4 '@tauri-apps/cli-linux-riscv64-gnu': 2.12.1
'@tauri-apps/cli-linux-x64-gnu': 3.0.0-alpha.4 '@tauri-apps/cli-linux-x64-gnu': 2.12.1
'@tauri-apps/cli-linux-x64-musl': 3.0.0-alpha.4 '@tauri-apps/cli-linux-x64-musl': 2.12.1
'@tauri-apps/cli-win32-arm64-msvc': 3.0.0-alpha.4 '@tauri-apps/cli-win32-arm64-msvc': 2.12.1
'@tauri-apps/cli-win32-ia32-msvc': 3.0.0-alpha.4 '@tauri-apps/cli-win32-ia32-msvc': 2.12.1
'@tauri-apps/cli-win32-x64-msvc': 3.0.0-alpha.4 '@tauri-apps/cli-win32-x64-msvc': 2.12.1
'@tauri-apps/plugin-clipboard-manager@3.0.0-alpha.2': '@tauri-apps/plugin-clipboard-manager@2.4.0':
dependencies: dependencies:
'@tauri-apps/api': 3.0.0-alpha.2 '@tauri-apps/api': 2.12.1
'@tauri-apps/plugin-dialog@3.0.0-alpha.3': '@tauri-apps/plugin-dialog@2.8.0':
dependencies: dependencies:
'@tauri-apps/api': 3.0.0-alpha.2 '@tauri-apps/api': 2.12.1
'@tauri-apps/plugin-fs@3.0.0-alpha.2': '@tauri-apps/plugin-fs@2.6.0':
dependencies: dependencies:
'@tauri-apps/api': 3.0.0-alpha.2 '@tauri-apps/api': 2.12.1
'@tauri-apps/plugin-http@3.0.0-alpha.2': '@tauri-apps/plugin-http@2.8.0':
dependencies: dependencies:
'@tauri-apps/api': 3.0.0-alpha.2 '@tauri-apps/api': 2.12.1
'@tauri-apps/plugin-opener@3.0.0-alpha.2': '@tauri-apps/plugin-opener@2.7.0':
dependencies: dependencies:
'@tauri-apps/api': 3.0.0-alpha.2 '@tauri-apps/api': 2.12.1
'@tauri-apps/plugin-updater@3.0.0-alpha.2': '@tauri-apps/plugin-updater@2.13.1':
dependencies: dependencies:
'@tauri-apps/api': 3.0.0-alpha.2 '@tauri-apps/api': 2.12.1
'@tybys/wasm-util@0.10.4': '@tybys/wasm-util@0.10.4':
dependencies: dependencies:
-12
View File
@@ -10,15 +10,3 @@ allowBuilds:
unrs-resolver: true unrs-resolver: true
minimumReleaseAgeExclude: minimumReleaseAgeExclude:
- dayjs@1.11.21 - dayjs@1.11.21
- '@tauri-apps/cli-darwin-arm64@3.0.0-alpha.4'
- '@tauri-apps/cli-darwin-x64@3.0.0-alpha.4'
- '@tauri-apps/cli-linux-arm-gnueabihf@3.0.0-alpha.4'
- '@tauri-apps/cli-linux-arm64-gnu@3.0.0-alpha.4'
- '@tauri-apps/cli-linux-arm64-musl@3.0.0-alpha.4'
- '@tauri-apps/cli-linux-riscv64-gnu@3.0.0-alpha.4'
- '@tauri-apps/cli-linux-x64-gnu@3.0.0-alpha.4'
- '@tauri-apps/cli-linux-x64-musl@3.0.0-alpha.4'
- '@tauri-apps/cli-win32-arm64-msvc@3.0.0-alpha.4'
- '@tauri-apps/cli-win32-ia32-msvc@3.0.0-alpha.4'
- '@tauri-apps/cli-win32-x64-msvc@3.0.0-alpha.4'
- '@tauri-apps/cli@3.0.0-alpha.4'
+75 -25
View File
@@ -1,34 +1,84 @@
import fs from 'node:fs'
import path from 'node:path' import path from 'node:path'
import { ESLint } from 'eslint' /**
* Architecture grep gates for the frontend contract flow. Select gates via
* argv:
*
* node scripts/check-architecture.mjs listen emit invoke
*
* - listen/emit: the Tauri event API may only be used under src/services/bus/**
* (the event bus). Detected as a bare `listen(`/`emit(` call (member calls
* like `this.emit(` are unrelated class methods) or as importing the name
* from '@tauri-apps/api/event'.
* - invoke: `invoke(` calls may exist only under src/services/**.
*/
const ROOT = path.resolve(import.meta.dirname, '..') const ROOT = path.resolve(import.meta.dirname, '..')
const gates = process.argv.slice(2) const SRC = path.join(ROOT, 'src')
if (
!gates.length || const tauriEventImport = (name) =>
gates.some((gate) => !['listen', 'emit', 'invoke'].includes(gate)) new RegExp(
) { `import\\s*\\{[^}]*\\b${name}\\b[^}]*\\}\\s*from\\s*'@tauri-apps/api/event'`,
)
const GATES = {
listen: {
patterns: [/(?<![.\w])listen\(/, tauriEventImport('listen')],
allowed: (file) => file.startsWith('src/services/bus/'),
description: 'Tauri listen outside the event bus (src/services/bus)',
},
emit: {
patterns: [/(?<![.\w])emit\(/, tauriEventImport('emit')],
allowed: (file) => file.startsWith('src/services/bus/'),
description: 'Tauri emit outside the event bus (src/services/bus)',
},
invoke: {
patterns: [/\binvoke\(/],
allowed: (file) => file.startsWith('src/services/'),
description: 'invoke( outside the services layer (src/services)',
},
}
const walk = (dir) => {
const entries = fs.readdirSync(dir, { withFileTypes: true })
return entries.flatMap((entry) => {
const full = path.join(dir, entry.name)
if (entry.isDirectory()) return walk(full)
return /\.(ts|tsx|js|jsx|mts|mjs)$/.test(entry.name) ? [full] : []
})
}
const selected = process.argv.slice(2)
if (selected.length === 0) {
console.error('usage: check-architecture.mjs <gate>... (listen|emit|invoke)') console.error('usage: check-architecture.mjs <gate>... (listen|emit|invoke)')
process.exit(2) process.exit(2)
} }
// All IPC boundaries use the lint configuration, including when callers request a legacy gate. let violations = 0
const eslint = new ESLint({ cwd: ROOT, allowInlineConfig: false }) for (const gate of selected) {
const results = await eslint.lintFiles(['src']) const rule = GATES[gate]
const boundaryRules = new Set([ if (!rule) {
'no-restricted-imports', console.error(`unknown gate: ${gate}`)
'no-restricted-syntax', process.exit(2)
'@typescript-eslint/no-floating-promises', }
]) for (const file of walk(SRC)) {
const violations = results.flatMap((result) => const relative = path.relative(ROOT, file).replaceAll('\\', '/')
result.messages if (rule.allowed(relative)) continue
.filter((message) => message.fatal || boundaryRules.has(message.ruleId)) const lines = fs.readFileSync(file, 'utf8').split('\n')
.map((message) => ({ file: result.filePath, ...message })), lines.forEach((line, index) => {
) if (rule.patterns.some((pattern) => pattern.test(line))) {
for (const violation of violations) { violations += 1
console.error( console.error(
`[arch] ${path.relative(ROOT, violation.file)}:${violation.line}: ${violation.message}`, `[arch] ${rule.description}: ${relative}:${index + 1}: ${line.trim()}`,
) )
}
})
}
} }
if (violations.length) process.exitCode = 1
else console.log('[arch] no violations') if (violations > 0) {
console.error(`[arch] ${violations} violation(s) found`)
process.exit(1)
}
console.log('[arch] no violations')
-69
View File
@@ -1,69 +0,0 @@
import { execFileSync } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
const ROOT = path.resolve(import.meta.dirname, '..')
const git = (...args) =>
execFileSync('git', args, { cwd: ROOT, encoding: 'utf8' }).trim()
const { contract } = JSON.parse(
fs.readFileSync(path.join(ROOT, 'scripts/contract-inputs.json'), 'utf8'),
)
const inputs = contract.map((pattern) => `:(glob)${pattern}`)
const args = process.argv.slice(2)
if (args.length !== 2 || args[0] !== '--push') {
console.error('usage: check-contract-changes.mjs --push <remote>')
process.exit(2)
}
const hasChanges = (...range) =>
git('diff', '--name-only', ...range, '--', ...inputs) !== ''
const assertCleanInputs = (...range) => {
if (
hasChanges(...range) ||
git('ls-files', '--others', '--exclude-standard', '--', ...inputs)
) {
throw new Error(
'Contract inputs differ from the pushed commit. Commit those changes before pushing.',
)
}
}
let relevant = false
const head = git('rev-parse', 'HEAD')
for (const line of fs
.readFileSync(0, 'utf8')
.trim()
.split('\n')
.filter(Boolean)) {
const fields = line.trim().split(/\s+/)
if (
fields.length !== 4 ||
![fields[1], fields[3]].every((sha) => /^[a-f0-9]{40,64}$/.test(sha))
) {
throw new Error('Invalid pre-push ref update')
}
const [, local, , remote] = fields
if (/^0+$/.test(local) || local === remote) continue
// A new remote branch has no upstream; use its fork point with the remote default branch.
const base = /^0+$/.test(remote)
? git('merge-base', local, `refs/remotes/${args[1]}/HEAD`)
: remote
if (!hasChanges(base, local)) continue
const commit = git('rev-parse', `${local}^{commit}`)
if (commit !== head)
throw new Error(
'Check out the pushed commit before validating its changed IPC contract.',
)
assertCleanInputs('HEAD')
relevant = true
}
if (relevant) {
execFileSync(
process.execPath,
[path.join(ROOT, 'scripts/gen-contract.mjs'), '--check'],
{
cwd: ROOT,
stdio: 'inherit',
},
)
} else {
console.log('[contract] inputs unchanged; skipping Rust generation')
}
-23
View File
@@ -1,23 +0,0 @@
{
"contract": [
"src-tauri/**/*.rs",
"crates/**/*.rs",
"Cargo.toml",
"Cargo.lock",
"src-tauri/Cargo.toml",
"crates/**/Cargo.toml",
"rust-toolchain.toml",
"src-tauri/tauri.conf*.json",
"src/services/bindings.ts",
"scripts/gen-contract.mjs",
"scripts/check-contract-changes.mjs",
"biome.json",
"biome.jsonc",
"package.json",
"pnpm-lock.yaml",
"pnpm-workspace.yaml",
"scripts/contract-inputs.json",
".github/workflows/frontend-check.yml",
".husky/pre-push"
]
}
+83 -47
View File
@@ -1,55 +1,91 @@
import { execFileSync } from 'node:child_process' import { execFileSync } from 'node:child_process'
import fs from 'node:fs' import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path' import path from 'node:path'
/**
* Regenerates src/services/contract.ts from the backend wire contract.
* Source of truth: `cargo run -p clash-verge --bin frontend-contract` inside
* src-tauri, which serializes the same enum variants and event payloads the
* app emits at runtime. CI reruns this and fails on a non-empty diff.
*/
const ROOT = path.resolve(import.meta.dirname, '..') const ROOT = path.resolve(import.meta.dirname, '..')
const BINDINGS = path.join(ROOT, 'src/services/bindings.ts') const OUT = path.join(ROOT, 'src/services/contract.ts')
const args = process.argv.slice(2)
if (args.length > 1 || (args.length === 1 && args[0] !== '--check')) { const contract = JSON.parse(
console.error('usage: gen-contract.mjs [--check]')
process.exit(2)
}
const check = args[0] === '--check'
const temporary = check
? fs.mkdtempSync(path.join(os.tmpdir(), 'verge-contract-'))
: null
const output = temporary ? path.join(temporary, 'bindings.ts') : BINDINGS
try {
execFileSync( execFileSync(
'cargo', 'cargo',
[ ['run', '-p', 'clash-verge', '--bin', 'frontend-contract', '-q'],
'run', {
'-p', cwd: path.join(ROOT, 'src-tauri'),
'clash-verge', encoding: 'utf8',
'--bin', maxBuffer: 16 * 1024 * 1024,
'frontend-contract', },
'--locked', ),
'-q', )
...(check ? ['--', output] : []),
], if (contract.version !== 1) {
{ cwd: ROOT, stdio: 'inherit' }, throw new Error(`unsupported wire contract version: ${contract.version}`)
)
const formatted = execFileSync(
process.execPath,
[
path.join(ROOT, 'node_modules/@biomejs/biome/bin/biome'),
'format',
'--stdin-file-path',
BINDINGS,
],
{ cwd: ROOT, input: fs.readFileSync(output) },
)
if (check) {
if (!formatted.equals(fs.readFileSync(BINDINGS))) {
console.error(
'IPC bindings are out of date. Run pnpm gen:contract and commit the generated file.',
)
process.exitCode = 1
}
} else {
fs.writeFileSync(BINDINGS, formatted)
}
} finally {
if (temporary) fs.rmSync(temporary, { recursive: true, force: true })
} }
/** TS type per event, derived from the serialized sample payload's JSON shape. */
const payloadType = (name, sample) => {
if (sample === null) return 'null'
if (typeof sample === 'string') return 'string'
if (Array.isArray(sample)) {
if (name === 'verge://notice-message') return '[NoticeStatus, string]'
throw new Error(`unexpected array payload for ${name}`)
}
if (typeof sample === 'object') {
const keys = Object.keys(sample)
if (keys.length === 1 && keys[0] === 'uid') return '{ uid: string }'
if (name === 'verge://run-state-changed') return 'RunState'
throw new Error(`unexpected object payload for ${name}: ${keys.join(',')}`)
}
throw new Error(`unexpected payload for ${name}`)
}
const needsRunState = contract.events.some(
(e) => e.name === 'verge://run-state-changed',
)
if (!needsRunState)
throw new Error('run-state-changed event missing from contract')
const lines = []
lines.push(
'// @generated by scripts/gen-contract.mjs from the backend wire contract. DO NOT EDIT.',
)
lines.push('// Regen: pnpm gen:contract')
lines.push('')
lines.push("import type { RunState } from './cmds'")
lines.push('')
lines.push(
'/** Wire status strings from NoticeStatus; keep in sync via `pnpm gen:contract`. */',
)
lines.push('export type NoticeStatus =')
for (const status of contract.noticeStatuses) {
lines.push(` | ${JSON.stringify(status)}`)
}
lines.push('')
lines.push('/** Event name → payload type for every backend-emitted event. */')
lines.push('export interface VergeEventPayloads {')
for (const event of contract.events) {
const key = JSON.stringify(event.name)
lines.push(` ${key}: ${payloadType(event.name, event.sample)}`)
}
lines.push('}')
lines.push('')
const content = `${lines.join('\n')}\n`
fs.writeFileSync(OUT, content)
// Match the repo's biome style so CI parity (`git diff --exit-code`) is stable.
execFileSync(
process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm',
['exec', 'biome', 'format', '--write', path.relative(ROOT, OUT)],
{ cwd: ROOT, stdio: 'ignore' },
)
console.log(
`[gen-contract] wrote ${path.relative(ROOT, OUT)}: ${contract.events.length} events, ${contract.noticeStatuses.length} statuses`,
)
+21 -25
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "clash-verge" name = "clash-verge"
version = "2.5.9" version = "2.5.8"
description = "clash verge" description = "clash verge"
authors = ["zzzgydi", "Tunglies", "wonfen", "MystiPanda"] authors = ["zzzgydi", "Tunglies", "wonfen", "MystiPanda"]
license = "GPL-3.0-only" license = "GPL-3.0-only"
@@ -23,15 +23,13 @@ tauri-dev = ["dep:tauri-plugin-devtools"]
tokio-trace = ["clash-verge-logging/tokio-trace"] tokio-trace = ["clash-verge-logging/tokio-trace"]
chrome-trace = ["clash-verge-logging/chrome-trace"] chrome-trace = ["clash-verge-logging/chrome-trace"]
clippy = ["tauri/test"] clippy = ["tauri/test"]
# The perf-harness feature and its main.rs wiring are parked until perf-harness = ["dep:tauri-plugin-wdio-webdriver"]
# tauri-plugin-wdio-webdriver publishes a tauri 3 release; restore both
# from git history together with the crate dependency.
[package.metadata.bundle] [package.metadata.bundle]
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 = "3.0.0-alpha.3", features = [] } tauri-build = { version = "2.7.1", features = [] }
[dependencies] [dependencies]
clash-verge-draft = { workspace = true } clash-verge-draft = { workspace = true }
@@ -44,12 +42,12 @@ tauri-plugin-clash-verge-sysinfo = { workspace = true }
tauri-plugin-clipboard-manager = { workspace = true } tauri-plugin-clipboard-manager = { workspace = true }
tauri = { workspace = true, features = [ tauri = { workspace = true, features = [
"protocol-asset", "protocol-asset",
"devtools",
"tracing", "tracing",
"tray-icon", "tray-icon",
"image-ico", "image-ico",
"image-png", "image-png",
] } ] }
tauri-runtime-wry = { workspace = true, features = ["devtools"] }
parking_lot = { workspace = true } parking_lot = { workspace = true }
anyhow = { workspace = true } anyhow = { workspace = true }
tokio = { workspace = true } tokio = { workspace = true }
@@ -62,7 +60,7 @@ bitflags = { workspace = true }
socket2 = { workspace = true } socket2 = { workspace = true }
warp = { version = "0.4.3", features = ["server"] } warp = { version = "0.4.3", features = ["server"] }
open = "5.4.4" open = "5.4.4"
rfd = { version = "0.16.0", default-features = false, features = ["common-controls-v6"] } rfd = { version = "0.17.2", default-features = false, features = ["common-controls-v6"] }
dirs = "7.0.0" dirs = "7.0.0"
dunce = "1.0.5" dunce = "1.0.5"
nanoid = "0.5" nanoid = "0.5"
@@ -75,14 +73,14 @@ sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs.git", branch
"guard", "guard",
] } ] }
network-interface = { version = "2.0.5", features = ["serde"] } network-interface = { version = "2.0.5", features = ["serde"] }
tauri-plugin-shell = "3.0.0-alpha.2" tauri-plugin-shell = "2.4.1"
tauri-plugin-opener = "3.0.0-alpha.2" tauri-plugin-opener = "2.7.0"
tauri-plugin-dialog = "3.0.0-alpha.3" tauri-plugin-dialog = "2.8.1"
tauri-plugin-fs = "3.0.0-alpha.2" tauri-plugin-fs = "2.6.0"
tauri-plugin-process = "3.0.0-alpha.2" tauri-plugin-process = "2.4.0"
tauri-plugin-deep-link = "3.0.0-alpha.2" tauri-plugin-deep-link = "2.6.1"
tauri-plugin-window-state = "3.0.0-alpha.2" tauri-plugin-window-state = "2.5.0"
zip = "9.0.1" zip = "8.6.0"
flate2 = "1.1.10" flate2 = "1.1.10"
reqwest_dav = "0.3.3" reqwest_dav = "0.3.3"
aes-gcm = { version = "0.11.1" } aes-gcm = { version = "0.11.1" }
@@ -93,13 +91,13 @@ getrandom = "0.4.3"
futures = "0.3.34" futures = "0.3.34"
gethostname = "1.1.0" gethostname = "1.1.0"
scopeguard = "1.2.0" scopeguard = "1.2.0"
tauri-plugin-notification = "3.0.0-alpha.2" tauri-plugin-notification = "2.5.1"
tokio-stream = "0.1.19" tokio-stream = "0.1.19"
backon = { version = "1.6.0", features = ["tokio-sleep"] } backon = { version = "1.6.0", features = ["tokio-sleep"] }
tauri-plugin-http = "3.0.0-alpha.2" tauri-plugin-http = "2.8.1"
tracing = { workspace = true } tracing = { workspace = true }
tauri-plugin-devtools = { version = "3.0.0-alpha.0", optional = true } tauri-plugin-devtools = { version = "2.2.2", optional = true }
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", branch = "feat/tauri-v3" } tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", branch = "main" }
async-trait = "0.1.92" async-trait = "0.1.92"
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", tag = "v2.7.6", version = "2.7.6", features = [ clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", tag = "v2.7.6", version = "2.7.6", features = [
"client", "client",
@@ -111,14 +109,12 @@ webpki-roots = "1.0.9"
dark-light = "3.0.0" dark-light = "3.0.0"
bytes = "1.12.1" bytes = "1.12.1"
tokio-util = { version = "0.7.19", features = ["time"] } tokio-util = { version = "0.7.19", features = ["time"] }
specta = { version = "=2.0.0-rc.26", features = ["derive", "function", "serde_json"] }
tauri-specta = { version = "=2.0.0-rc.25", features = ["derive", "typescript"] }
specta-typescript = "=0.0.13"
[target.'cfg(unix)'.dependencies] [target.'cfg(unix)'.dependencies]
libc = "0.2.190" libc = "0.2.190"
[target.'cfg(target_os = "macos")'.dependencies] [target.'cfg(target_os = "macos")'.dependencies]
tauri-plugin-wdio-webdriver = { version = "=1.5.0", optional = true }
objc2 = "0.6.5" objc2 = "0.6.5"
objc2-foundation = { version = "0.3.2", features = [ objc2-foundation = { version = "0.3.2", features = [
"NSString", "NSString",
@@ -150,9 +146,9 @@ windows = { version = "0.62.2", features = ["Win32_Globalization"] }
windows-sys.workspace = true windows-sys.workspace = true
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies] [target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
tauri-plugin-autostart = "3.0.0-alpha.2" tauri-plugin-autostart = "2.7.0"
tauri-plugin-global-shortcut = "3.0.0-alpha.2" tauri-plugin-global-shortcut = "2.4.0"
tauri-plugin-updater = "3.0.0-alpha.2" tauri-plugin-updater = "2.13.2"
[dev-dependencies] [dev-dependencies]
criterion = { workspace = true } criterion = { workspace = true }
+1
View File
@@ -70,6 +70,7 @@
"dialog:allow-open", "dialog:allow-open",
"global-shortcut:allow-is-registered", "global-shortcut:allow-is-registered",
"global-shortcut:allow-register", "global-shortcut:allow-register",
"global-shortcut:allow-register-all",
"global-shortcut:allow-unregister", "global-shortcut:allow-unregister",
"global-shortcut:allow-unregister-all", "global-shortcut:allow-unregister-all",
"process:allow-exit", "process:allow-exit",
+7 -11
View File
@@ -1,12 +1,8 @@
fn main() -> Result<(), Box<dyn std::error::Error>> { //! Prints the frontend wire contract as JSON to stdout. Zero new dependencies:
let mut args = std::env::args_os().skip(1); //! the payload is derived from the same serializers the app uses at runtime.
let output = args //! Consumed by scripts/gen-contract.mjs; CI regenerates and diffs the committed
.next() //! TypeScript artifact.
.map(std::path::PathBuf::from)
.unwrap_or_else(|| std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../src/services/bindings.ts")); fn main() {
if args.next().is_some() { println!("{}", app_lib::frontend_wire_contract());
return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "expected at most one output path").into());
}
app_lib::ipc::builder().export(specta_typescript::Typescript::default(), output)?;
Ok(())
} }
+6 -24
View File
@@ -9,14 +9,12 @@ use smartstring::alias::String;
use tauri::{AppHandle, Manager as _, ipc::Channel}; use tauri::{AppHandle, Manager as _, ipc::Channel};
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn open_app_dir() -> CmdResult<()> { pub async fn open_app_dir() -> CmdResult<()> {
let app_dir = dirs::app_home_dir().stringify_err()?; let app_dir = dirs::app_home_dir().stringify_err()?;
open::that(app_dir).stringify_err() open::that(app_dir).stringify_err()
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn open_core_dir() -> CmdResult<()> { pub async fn open_core_dir() -> CmdResult<()> {
let core_dir = tauri::utils::platform::current_exe().stringify_err()?; let core_dir = tauri::utils::platform::current_exe().stringify_err()?;
let core_dir = core_dir.parent().ok_or("failed to get core dir")?; let core_dir = core_dir.parent().ok_or("failed to get core dir")?;
@@ -24,14 +22,12 @@ pub async fn open_core_dir() -> CmdResult<()> {
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn open_logs_dir() -> CmdResult<()> { pub async fn open_logs_dir() -> CmdResult<()> {
let log_dir = dirs::app_logs_dir().stringify_err()?; let log_dir = dirs::app_logs_dir().stringify_err()?;
open::that(log_dir).stringify_err() open::that(log_dir).stringify_err()
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub fn open_devtools(app_handle: AppHandle) { pub fn open_devtools(app_handle: AppHandle) {
if let Some(window) = app_handle.get_webview_window("main") { if let Some(window) = app_handle.get_webview_window("main") {
if !window.is_devtools_open() { if !window.is_devtools_open() {
@@ -43,26 +39,22 @@ pub fn open_devtools(app_handle: AppHandle) {
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn exit_app() { pub async fn exit_app() {
feat::quit().await; feat::quit().await;
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn restart_app() -> CmdResult<()> { pub async fn restart_app() -> CmdResult<()> {
feat::restart_app().await; feat::restart_app().await;
Ok(()) Ok(())
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn install_update( pub async fn install_update(
app_handle: AppHandle, app_handle: AppHandle,
version: std::string::String, version: String,
on_event: Channel<DownloadEvent>, on_event: Channel<DownloadEvent>,
) -> CmdResult<bool> { ) -> CmdResult<bool> {
let version: String = version.into();
SilentUpdater::global() SilentUpdater::global()
.install_update(&app_handle, &version, |event| { .install_update(&app_handle, &version, |event| {
let _ = on_event.send(event); let _ = on_event.send(event);
@@ -72,32 +64,22 @@ pub async fn install_update(
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub fn cancel_update_download() { pub fn cancel_update_download() {
SilentUpdater::global().cancel_download(); SilentUpdater::global().cancel_download();
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub fn get_app_dir() -> CmdResult<String> {
pub fn get_app_dir() -> CmdResult<std::string::String> {
let app_home_dir = dirs::app_home_dir().stringify_err()?.to_string_lossy().into(); let app_home_dir = dirs::app_home_dir().stringify_err()?.to_string_lossy().into();
Ok(app_home_dir) Ok(app_home_dir)
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn download_icon_cache(url: String, name: String) -> CmdResult<String> {
pub async fn download_icon_cache( feat::download_icon_cache(url, name).await
url: std::string::String,
name: std::string::String,
) -> CmdResult<std::string::String> {
let url: String = url.into();
let name: String = name.into();
feat::download_icon_cache(url, name).await.map(Into::into)
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn copy_icon_file(path: String, icon_info: feat::IconInfo) -> CmdResult<String> {
pub async fn copy_icon_file(path: std::string::String, icon_info: feat::IconInfo) -> CmdResult<std::string::String> { feat::copy_icon_file(path, icon_info).await
let path: String = path.into();
feat::copy_icon_file(path, icon_info).await.map(Into::into)
} }
+5 -16
View File
@@ -4,44 +4,33 @@ use feat::LocalBackupFile;
use smartstring::alias::String; use smartstring::alias::String;
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn create_local_backup() -> CmdResult<()> { pub async fn create_local_backup() -> CmdResult<()> {
feat::create_local_backup().await.stringify_err() feat::create_local_backup().await.stringify_err()
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn list_local_backup() -> CmdResult<Vec<LocalBackupFile>> { pub async fn list_local_backup() -> CmdResult<Vec<LocalBackupFile>> {
feat::list_local_backup().await.stringify_err() feat::list_local_backup().await.stringify_err()
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn delete_local_backup(filename: String) -> CmdResult<()> {
pub async fn delete_local_backup(filename: std::string::String) -> CmdResult<()> {
let filename: String = filename.into();
feat::delete_local_backup(filename).await.stringify_err() feat::delete_local_backup(filename).await.stringify_err()
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn restore_local_backup(filename: String) -> CmdResult<()> {
pub async fn restore_local_backup(filename: std::string::String) -> CmdResult<()> {
let filename: String = filename.into();
feat::restore_local_backup(filename) feat::restore_local_backup(filename)
.await .await
.map_err(|error| super::proxy_aware_error(&error)) .map_err(|error| super::proxy_aware_error(&error))
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn import_local_backup(source: String) -> CmdResult<String> {
pub async fn import_local_backup(source: std::string::String) -> CmdResult<std::string::String> { feat::import_local_backup(source).await.stringify_err()
let source: String = source.into();
feat::import_local_backup(source).await.map(Into::into).stringify_err()
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn export_local_backup(filename: String, destination: String) -> CmdResult<()> {
pub async fn export_local_backup(filename: std::string::String, destination: std::string::String) -> CmdResult<()> {
let filename: String = filename.into();
let destination: String = destination.into();
feat::export_local_backup(filename, destination).await.stringify_err() feat::export_local_backup(filename, destination).await.stringify_err()
} }
+24 -36
View File
@@ -12,33 +12,30 @@ use crate::{
}, },
}; };
use clash_verge_logging::{Type, logging, logging_error}; use clash_verge_logging::{Type, logging, logging_error};
use serde_yaml_ng::Mapping;
use smartstring::alias::String; use smartstring::alias::String;
use tokio::fs; use tokio::fs;
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn copy_clash_env() -> CmdResult { pub async fn copy_clash_env() -> CmdResult {
feat::copy_clash_env().await.stringify_err() feat::copy_clash_env().await;
Ok(())
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn get_clash_info() -> CmdResult<ClashInfo> { pub async fn get_clash_info() -> CmdResult<ClashInfo> {
Ok(Config::clash().await.data_arc().get_client_info()) Ok(Config::clash().await.data_arc().get_client_info())
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn patch_clash_config(payload: Mapping) -> CmdResult {
pub async fn patch_clash_config(payload: crate::ipc::YamlMapping) -> CmdResult { feat::patch_clash(&payload)
feat::patch_clash(&payload.0)
.await .await
.map_err(|error| proxy_aware_coded_error(&error, "CLASH_CONFIG_UPDATE_FAILED")) .map_err(|error| proxy_aware_coded_error(&error, "CLASH_CONFIG_UPDATE_FAILED"))
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn patch_clash_mode(payload: String) -> CmdResult {
pub async fn patch_clash_mode(payload: std::string::String) -> CmdResult {
let payload: String = payload.into();
feat::change_clash_mode(payload) feat::change_clash_mode(payload)
.await .await
.with_error_code("CLASH_MODE_UPDATE_FAILED") .with_error_code("CLASH_MODE_UPDATE_FAILED")
@@ -46,15 +43,12 @@ pub async fn patch_clash_mode(payload: std::string::String) -> CmdResult {
/// Reads the saved mode without depending on strict mihomo `/configs` deserialization. /// Reads the saved mode without depending on strict mihomo `/configs` deserialization.
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn get_clash_mode() -> CmdResult<Option<String>> {
pub async fn get_clash_mode() -> CmdResult<Option<std::string::String>> { Ok(Config::clash().await.data_arc().get_mode().map(Into::into))
Ok(Config::clash().await.data_arc().get_mode())
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn change_clash_core(clash_core: String) -> CmdResult<Option<CommandFailure>> {
pub async fn change_clash_core(clash_core: std::string::String) -> CmdResult<Option<CommandFailure>> {
let clash_core: String = clash_core.into();
logging!(info, Type::Config, "changing core to {clash_core}"); logging!(info, Type::Config, "changing core to {clash_core}");
match CoreManager::global().change_core(&clash_core).await { match CoreManager::global().change_core(&clash_core).await {
@@ -86,7 +80,6 @@ pub async fn change_clash_core(clash_core: std::string::String) -> CmdResult<Opt
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn restart_core() -> CmdResult { pub async fn restart_core() -> CmdResult {
logging_error!(Type::Core, profiles_save_file_safe().await); logging_error!(Type::Core, profiles_save_file_safe().await);
let result = CoreManager::global() let result = CoreManager::global()
@@ -101,7 +94,6 @@ pub async fn restart_core() -> CmdResult {
/// Replaces the managed core binary atomically instead of letting mihomo overwrite itself. /// Replaces the managed core binary atomically instead of letting mihomo overwrite itself.
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn upgrade_clash_core(force: bool) -> CmdResult<feat::CoreUpgradeReport> { pub async fn upgrade_clash_core(force: bool) -> CmdResult<feat::CoreUpgradeReport> {
let report = feat::upgrade_core(force).await.with_error_code("CORE_UPGRADE_FAILED")?; let report = feat::upgrade_core(force).await.with_error_code("CORE_UPGRADE_FAILED")?;
if report.upgraded { if report.upgraded {
@@ -111,9 +103,7 @@ pub async fn upgrade_clash_core(force: bool) -> CmdResult<feat::CoreUpgradeRepor
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn test_delay(url: String) -> CmdResult<u32> {
pub async fn test_delay(url: std::string::String) -> CmdResult<u32> {
let url: String = url.into();
let result = match feat::test_delay(url).await { let result = match feat::test_delay(url).await {
Ok(delay) => delay, Ok(delay) => delay,
Err(e) => { Err(e) => {
@@ -125,14 +115,13 @@ pub async fn test_delay(url: std::string::String) -> CmdResult<u32> {
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn save_dns_config(dns_config: Mapping) -> CmdResult {
pub async fn save_dns_config(dns_config: crate::ipc::YamlMapping) -> CmdResult {
use crate::utils::dirs; use crate::utils::dirs;
use tokio::fs; use tokio::fs;
let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG); let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG);
let yaml_str = yaml_emitter::to_mihomo_config_string(&dns_config.0).stringify_err()?; let yaml_str = yaml_emitter::to_mihomo_config_string(&dns_config).stringify_err()?;
fs::write(&dns_path, yaml_str).await.stringify_err()?; fs::write(&dns_path, yaml_str).await.stringify_err()?;
logging!(info, Type::Config, "DNS config saved to {dns_path:?}"); logging!(info, Type::Config, "DNS config saved to {dns_path:?}");
@@ -140,27 +129,22 @@ pub async fn save_dns_config(dns_config: crate::ipc::YamlMapping) -> CmdResult {
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub fn take_dns_override_notice() -> bool { pub fn take_dns_override_notice() -> bool {
crate::config::dns::take_dns_override_notice() crate::config::dns::take_dns_override_notice()
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn set_dns_override( pub async fn set_dns_override(
profile_uid: std::string::String, profile_uid: String,
enabled: bool, enabled: bool,
confirmation: Option<std::string::String>, confirmation: Option<String>,
) -> CmdResult<feat::DnsOverrideOutcome> { ) -> CmdResult<feat::DnsOverrideOutcome> {
let profile_uid: String = profile_uid.into();
let confirmation = confirmation.map(String::from);
feat::set_dns_override(profile_uid, enabled, confirmation) feat::set_dns_override(profile_uid, enabled, confirmation)
.await .await
.map_err(|error| proxy_aware_coded_error(&error, "DNS_OVERRIDE_UPDATE_FAILED")) .map_err(|error| proxy_aware_coded_error(&error, "DNS_OVERRIDE_UPDATE_FAILED"))
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn apply_dns_config(apply: bool) -> CmdResult { pub async fn apply_dns_config(apply: bool) -> CmdResult {
if apply { if apply {
let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG); let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG);
@@ -179,7 +163,7 @@ pub async fn apply_dns_config(apply: bool) -> CmdResult {
); );
})?; })?;
serde_yaml_ng::from_str::<serde_yaml_ng::Mapping>(&dns_yaml).stringify_err_log(|e| { let patch_config = serde_yaml_ng::from_str::<serde_yaml_ng::Mapping>(&dns_yaml).stringify_err_log(|e| {
logging!( logging!(
error, error,
Type::Config, Type::Config,
@@ -188,6 +172,13 @@ pub async fn apply_dns_config(apply: bool) -> CmdResult {
); );
})?; })?;
let mut patch = serde_yaml_ng::Mapping::new();
patch.insert("dns".into(), patch_config.into());
Config::runtime().await.edit_draft(|d| {
d.patch_config(&patch);
});
CoreManager::global().update_config_checked().await.map_err(|error| { CoreManager::global().update_config_checked().await.map_err(|error| {
logging!(error, Type::Config, "failed to apply the config with DNS: {error:#}"); logging!(error, Type::Config, "failed to apply the config with DNS: {error:#}");
proxy_aware_error(&error) proxy_aware_error(&error)
@@ -211,22 +202,20 @@ pub async fn apply_dns_config(apply: bool) -> CmdResult {
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn get_dns_config_content() -> CmdResult<Option<String>> {
pub async fn get_dns_config_content() -> CmdResult<Option<std::string::String>> {
use crate::utils::dirs; use crate::utils::dirs;
use tokio::fs; use tokio::fs;
let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG); let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG);
match fs::read_to_string(&dns_path).await { match fs::read_to_string(&dns_path).await {
Ok(content) => Ok(Some(content)), Ok(content) => Ok(Some(content.into())),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(CommandFailure::plain(error)), Err(error) => Err(CommandFailure::plain(error)),
} }
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn validate_dns_config() -> CmdResult<ValidationOutcome> { pub async fn validate_dns_config() -> CmdResult<ValidationOutcome> {
let app_dir = dirs::app_home_dir().stringify_err()?; let app_dir = dirs::app_home_dir().stringify_err()?;
let dns_path = app_dir.join(constants::files::DNS_CONFIG); let dns_path = app_dir.join(constants::files::DNS_CONFIG);
@@ -243,7 +232,6 @@ pub async fn validate_dns_config() -> CmdResult<ValidationOutcome> {
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn get_clash_logs() -> CmdResult<Vec<std::string::String>> { pub async fn get_clash_logs() -> CmdResult<Vec<std::string::String>> {
let logs = CoreManager::global().get_clash_logs().await.unwrap_or_default(); let logs = CoreManager::global().get_clash_logs().await.unwrap_or_default();
Ok(logs) Ok(logs)
-1
View File
@@ -3,7 +3,6 @@ use crate::core::lightweight;
use super::CmdResult; use super::CmdResult;
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn entry_lightweight_mode() -> CmdResult { pub async fn entry_lightweight_mode() -> CmdResult {
lightweight::entry_lightweight_mode().await; lightweight::entry_lightweight_mode().await;
Ok(()) Ok(())
-2
View File
@@ -5,13 +5,11 @@ use crate::{
}; };
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn probe_listener(request: ListenerProbe) -> CmdResult<ListenerProbeOutcome> { pub async fn probe_listener(request: ListenerProbe) -> CmdResult<ListenerProbeOutcome> {
feat::probe_listener(request).await.stringify_err() feat::probe_listener(request).await.stringify_err()
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn save_proxy_ports(settings: ProxyPortSettings) -> CmdResult<SaveProxyPortsOutcome> { pub async fn save_proxy_ports(settings: ProxyPortSettings) -> CmdResult<SaveProxyPortsOutcome> {
feat::save_proxy_ports(settings) feat::save_proxy_ports(settings)
.await .await
@@ -4,7 +4,6 @@ use std::time::Duration;
use tauri::{command, ipc::Channel}; use tauri::{command, ipc::Channel};
#[command] #[command]
#[specta::specta]
pub fn get_unlock_items() -> Vec<UnlockItem> { pub fn get_unlock_items() -> Vec<UnlockItem> {
clash_verge_media_unlock::default_unlock_items() clash_verge_media_unlock::default_unlock_items()
} }
@@ -27,7 +26,6 @@ async fn create_client() -> Result<Client, String> {
} }
#[command] #[command]
#[specta::specta]
pub async fn check_media_unlock(on_complete: Channel<UnlockItem>) -> Result<Vec<UnlockItem>, String> { pub async fn check_media_unlock(on_complete: Channel<UnlockItem>) -> Result<Vec<UnlockItem>, String> {
let client = create_client().await?; let client = create_client().await?;
Ok(clash_verge_media_unlock::check_media_unlock(&client, |item| { Ok(clash_verge_media_unlock::check_media_unlock(&client, |item| {
@@ -37,7 +35,6 @@ pub async fn check_media_unlock(on_complete: Channel<UnlockItem>) -> Result<Vec<
} }
#[command] #[command]
#[specta::specta]
pub async fn check_media_unlock_item(name: String) -> Result<UnlockItem, String> { pub async fn check_media_unlock_item(name: String) -> Result<UnlockItem, String> {
let client = create_client().await?; let client = create_client().await?;
clash_verge_media_unlock::check_media_unlock_item(&client, &name).await clash_verge_media_unlock::check_media_unlock_item(&client, &name).await
+1 -1
View File
@@ -4,7 +4,7 @@ use smartstring::alias::String;
pub type CmdResult<T = ()> = Result<T, CommandFailure>; pub type CmdResult<T = ()> = Result<T, CommandFailure>;
/// Structured command failure returned to the frontend. /// Structured command failure returned to the frontend.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, specta::Type)] #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct CommandFailure { pub struct CommandFailure {
/// Stable frontend identifier, when classified. /// Stable frontend identifier, when classified.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
+20 -34
View File
@@ -3,12 +3,13 @@ use crate::cmd::StringifyErr as _;
use crate::core::{proxy_control, sysopt::Sysopt}; use crate::core::{proxy_control, sysopt::Sysopt};
use gethostname::gethostname; use gethostname::gethostname;
use network_interface::NetworkInterface;
use serde_yaml_ng::Mapping;
use sysproxy::{Autoproxy, Sysproxy}; use sysproxy::{Autoproxy, Sysproxy};
use tauri_plugin_clash_verge_sysinfo; use tauri_plugin_clash_verge_sysinfo;
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn get_sys_proxy() -> CmdResult<Mapping> {
pub async fn get_sys_proxy() -> CmdResult<SystemProxy> {
Sysopt::global().wait_idle().await; Sysopt::global().wait_idle().await;
// With no network service there is no proxy configured anywhere, which reads as disabled. // With no network service there is no proxy configured anywhere, which reads as disabled.
let sys_proxy = match Sysproxy::get_system_proxy() { let sys_proxy = match Sysproxy::get_system_proxy() {
@@ -16,40 +17,40 @@ pub async fn get_sys_proxy() -> CmdResult<SystemProxy> {
other => other.stringify_err()?, other => other.stringify_err()?,
}; };
let Sysproxy { let Sysproxy {
host, ref host,
bypass, ref bypass,
port, ref port,
enable, ref enable,
} = sys_proxy; } = sys_proxy;
Ok(SystemProxy { let mut map = Mapping::new();
enable, map.insert("enable".into(), (*enable).into());
server: format!("{host}:{port}"), map.insert("server".into(), format!("{}:{}", host, port).into());
bypass, map.insert("bypass".into(), bypass.as_str().into());
}) Ok(map)
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn get_auto_proxy() -> CmdResult<Mapping> {
pub async fn get_auto_proxy() -> CmdResult<AutoProxy> {
Sysopt::global().wait_idle().await; Sysopt::global().wait_idle().await;
let auto_proxy = match Autoproxy::get_auto_proxy() { let auto_proxy = match Autoproxy::get_auto_proxy() {
Err(error) if proxy_control::is_missing_network_service(&error) => Autoproxy::default(), Err(error) if proxy_control::is_missing_network_service(&error) => Autoproxy::default(),
other => other.stringify_err()?, other => other.stringify_err()?,
}; };
let Autoproxy { enable, url } = auto_proxy; let Autoproxy { ref enable, ref url } = auto_proxy;
Ok(AutoProxy { enable, url }) let mut map = Mapping::new();
map.insert("enable".into(), (*enable).into());
map.insert("url".into(), url.as_str().into());
Ok(map)
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub fn get_embedded_server_port() -> CmdResult<u16> { pub fn get_embedded_server_port() -> CmdResult<u16> {
crate::utils::server::embedded_server_port().stringify_err() crate::utils::server::embedded_server_port().stringify_err()
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub fn get_system_hostname() -> String { pub fn get_system_hostname() -> String {
match gethostname().into_string() { match gethostname().into_string() {
Ok(name) => name, Ok(name) => name,
@@ -61,14 +62,12 @@ pub fn get_system_hostname() -> String {
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub fn get_network_interfaces() -> Vec<String> { pub fn get_network_interfaces() -> Vec<String> {
tauri_plugin_clash_verge_sysinfo::list_network_interfaces() tauri_plugin_clash_verge_sysinfo::list_network_interfaces()
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub fn get_network_interfaces_info() -> CmdResult<Vec<NetworkInterface>> {
pub fn get_network_interfaces_info() -> CmdResult<Vec<crate::ipc::NetworkInterfaceView>> {
use network_interface::{NetworkInterface, NetworkInterfaceConfig as _}; use network_interface::{NetworkInterface, NetworkInterfaceConfig as _};
let names = get_network_interfaces(); let names = get_network_interfaces();
@@ -78,22 +77,9 @@ pub fn get_network_interfaces_info() -> CmdResult<Vec<crate::ipc::NetworkInterfa
for interface in interfaces { for interface in interfaces {
if names.contains(&interface.name) { if names.contains(&interface.name) {
result.push(interface.into()); result.push(interface);
} }
} }
Ok(result) Ok(result)
} }
#[derive(serde::Serialize, specta::Type)]
pub struct SystemProxy {
pub enable: bool,
pub server: String,
pub bypass: String,
}
#[derive(serde::Serialize, specta::Type)]
pub struct AutoProxy {
pub enable: bool,
pub url: String,
}
+17 -114
View File
@@ -33,7 +33,6 @@ fn profile_import_error(err: &anyhow::Error) -> std::string::String {
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn get_profiles() -> CmdResult<SharedDraft<IProfiles>> { pub async fn get_profiles() -> CmdResult<SharedDraft<IProfiles>> {
let draft = Config::profiles().await; let draft = Config::profiles().await;
let data = draft.data_arc(); let data = draft.data_arc();
@@ -41,7 +40,6 @@ pub async fn get_profiles() -> CmdResult<SharedDraft<IProfiles>> {
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn enhance_profiles() -> CmdResult<ValidationOutcome> { pub async fn enhance_profiles() -> CmdResult<ValidationOutcome> {
match feat::enhance_profiles().await { match feat::enhance_profiles().await {
Ok(outcome) if outcome.is_valid() => { Ok(outcome) if outcome.is_valid() => {
@@ -67,7 +65,6 @@ pub async fn enhance_profiles() -> CmdResult<ValidationOutcome> {
#[tauri::command] #[tauri::command]
#[tracing::instrument(skip_all, level = "info", fields(url = %help::mask_url(&url), uid = tracing::field::Empty))] #[tracing::instrument(skip_all, level = "info", fields(url = %help::mask_url(&url), uid = tracing::field::Empty))]
#[specta::specta]
pub async fn import_profile(url: std::string::String, option: Option<PrfOption>) -> CmdResult { pub async fn import_profile(url: std::string::String, option: Option<PrfOption>) -> CmdResult {
let item = &mut match PrfItem::from_url(&url, None, None, option.as_ref()).await { let item = &mut match PrfItem::from_url(&url, None, None, option.as_ref()).await {
Ok(it) => it, Ok(it) => it,
@@ -97,10 +94,7 @@ pub async fn import_profile(url: std::string::String, option: Option<PrfOption>)
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn reorder_profile(active_id: String, over_id: String) -> CmdResult {
pub async fn reorder_profile(active_id: std::string::String, over_id: std::string::String) -> CmdResult {
let active_id: String = active_id.into();
let over_id: String = over_id.into();
match profiles_reorder_safe(&active_id, &over_id).await { match profiles_reorder_safe(&active_id, &over_id).await {
Ok(_) => { Ok(_) => {
logging!(info, Type::Cmd, "重新排序配置文件: {} -> {}", active_id, over_id); logging!(info, Type::Cmd, "重新排序配置文件: {} -> {}", active_id, over_id);
@@ -120,16 +114,16 @@ pub async fn reorder_profile(active_id: std::string::String, over_id: std::strin
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn create_profile(item: PrfItem, file_data: Option<String>) -> CmdResult {
pub async fn create_profile(item: ProfileCreate, file_data: Option<std::string::String>) -> CmdResult {
let item: PrfItem = item.into();
let file_data = file_data.map(String::from);
match profiles_append_item_with_filedata_safe(&item, file_data).await { match profiles_append_item_with_filedata_safe(&item, file_data).await {
Ok(_) => { Ok(_) => {
profiles_save_file_safe() profiles_save_file_safe()
.await .await
.with_error_code("PROFILE_CREATE_FAILED")?; .with_error_code("PROFILE_CREATE_FAILED")?;
logging_error!(Type::Timer, Timer::global().refresh().await); logging_error!(Type::Timer, Timer::global().refresh().await);
if let Some(uid) = &item.uid {
handle::Handle::notify_profile_changed(uid);
}
Ok(()) Ok(())
} }
Err(err) => Err(coded_error("PROFILE_CREATE_FAILED", err)), Err(err) => Err(coded_error("PROFILE_CREATE_FAILED", err)),
@@ -137,9 +131,7 @@ pub async fn create_profile(item: ProfileCreate, file_data: Option<std::string::
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn update_profile(index: String, option: Option<PrfOption>) -> CmdResult {
pub async fn update_profile(index: std::string::String, option: Option<PrfOption>) -> CmdResult {
let index: String = index.into();
match feat::update_profile(&index, option.as_ref(), true).await { match feat::update_profile(&index, option.as_ref(), true).await {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(e) => { Err(e) => {
@@ -150,9 +142,7 @@ pub async fn update_profile(index: std::string::String, option: Option<PrfOption
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn delete_profile(index: String) -> CmdResult {
pub async fn delete_profile(index: std::string::String) -> CmdResult {
let index: String = index.into();
let profile_write_guard = PROFILE_WRITE_LOCK.lock().await; let profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
let profiles = Config::profiles().await; let profiles = Config::profiles().await;
@@ -323,85 +313,9 @@ async fn perform_config_update(
} }
} }
#[derive(Default, serde::Deserialize, specta::Type)]
#[serde(default)]
pub struct ProfileSelection {
#[specta(type = Option<std::string::String>)]
pub current: Option<String>,
}
#[derive(Default, serde::Deserialize, specta::Type)]
#[serde(default)]
pub struct ProfileCreate {
#[serde(rename = "type")]
#[specta(type = Option<std::string::String>)]
pub itype: Option<String>,
#[specta(type = Option<std::string::String>)]
pub name: Option<String>,
#[specta(type = Option<std::string::String>)]
pub desc: Option<String>,
#[specta(type = Option<std::string::String>)]
pub url: Option<String>,
pub option: Option<PrfOption>,
}
impl From<ProfileCreate> for PrfItem {
fn from(item: ProfileCreate) -> Self {
Self {
itype: item.itype,
name: item.name,
desc: item.desc,
url: item.url,
option: item.option,
..Self::default()
}
}
}
#[derive(Default, serde::Deserialize, specta::Type)]
#[serde(default)]
pub struct ProfilePatch {
#[serde(rename = "type")]
#[specta(type = Option<std::string::String>)]
pub itype: Option<String>,
#[specta(type = Option<std::string::String>)]
pub name: Option<String>,
#[specta(type = Option<std::string::String>)]
pub desc: Option<String>,
#[specta(type = Option<std::string::String>)]
pub file: Option<String>,
#[specta(type = Option<std::string::String>)]
pub url: Option<String>,
pub selected: Option<Vec<crate::config::PrfSelected>>,
#[specta(type = Option<std::collections::BTreeMap<std::string::String, std::string::String>>)]
pub latency_test_urls: Option<std::collections::BTreeMap<String, String>>,
pub extra: Option<crate::config::PrfExtra>,
pub updated: Option<usize>,
pub option: Option<PrfOption>,
}
impl From<ProfilePatch> for PrfItem {
fn from(patch: ProfilePatch) -> Self {
Self {
itype: patch.itype,
name: patch.name,
desc: patch.desc,
file: patch.file,
url: patch.url,
selected: patch.selected,
latency_test_urls: patch.latency_test_urls,
extra: patch.extra,
updated: patch.updated,
option: patch.option,
..Self::default()
}
}
}
#[tauri::command] #[tauri::command]
#[tracing::instrument(skip_all, level = "info", fields(target = ?profiles.current))] #[tracing::instrument(skip_all, level = "info", fields(target = ?profiles.current))]
#[specta::specta] pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<ValidationOutcome> {
pub async fn patch_profiles_config(profiles: ProfileSelection) -> CmdResult<ValidationOutcome> {
if CURRENT_SWITCHING_PROFILE if CURRENT_SWITCHING_PROFILE
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_err() .is_err()
@@ -411,17 +325,11 @@ pub async fn patch_profiles_config(profiles: ProfileSelection) -> CmdResult<Vali
} }
let _profile_write_guard = PROFILE_WRITE_LOCK.lock().await; let _profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
let profiles = IProfiles {
current: profiles.current,
items: None,
};
let target_profile = profiles.current.as_ref(); let target_profile = profiles.current.as_ref();
let previous_profile = Config::profiles().await.data_arc().current.clone(); let previous_profile = Config::profiles().await.data_arc().current.clone();
Config::profiles().await.edit_draft(|d| { Config::profiles().await.edit_draft(|d| d.patch_config(&profiles));
d.patch_config(&profiles);
});
perform_config_update(target_profile, previous_profile.as_ref()) perform_config_update(target_profile, previous_profile.as_ref())
.await .await
@@ -429,17 +337,15 @@ pub async fn patch_profiles_config(profiles: ProfileSelection) -> CmdResult<Vali
} }
pub async fn patch_profiles_config_by_profile_index(profile_index: String) -> CmdResult<ValidationOutcome> { pub async fn patch_profiles_config_by_profile_index(profile_index: String) -> CmdResult<ValidationOutcome> {
let profiles = ProfileSelection { let profiles = IProfiles {
current: Some(profile_index), current: Some(profile_index),
items: None,
}; };
patch_profiles_config(profiles).await patch_profiles_config(profiles).await
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn patch_profile(index: String, profile: PrfItem) -> CmdResult {
pub async fn patch_profile(index: std::string::String, profile: ProfilePatch) -> CmdResult {
let profile: PrfItem = profile.into();
let index: String = index.into();
let profiles = Config::profiles().await; let profiles = Config::profiles().await;
let should_refresh_timer = if let Ok(old_profile) = profiles.latest_arc().get_item(&index) let should_refresh_timer = if let Ok(old_profile) = profiles.latest_arc().get_item(&index)
&& let Some(new_option) = profile.option.as_ref() && let Some(new_option) = profile.option.as_ref()
@@ -479,8 +385,7 @@ pub async fn patch_profile(index: std::string::String, profile: ProfilePatch) ->
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn view_profile(index: String) -> CmdResult {
pub async fn view_profile(index: std::string::String) -> CmdResult {
let profiles = Config::profiles().await; let profiles = Config::profiles().await;
let profiles_ref = profiles.latest_arc(); let profiles_ref = profiles.latest_arc();
let file = profiles_ref let file = profiles_ref
@@ -504,8 +409,7 @@ pub async fn view_profile(index: std::string::String) -> CmdResult {
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn read_profile_file(index: String) -> CmdResult<String> {
pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::string::String> {
let item = { let item = {
let profiles = Config::profiles().await; let profiles = Config::profiles().await;
let profiles_ref = profiles.latest_arc(); let profiles_ref = profiles.latest_arc();
@@ -525,7 +429,7 @@ pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::str
.join(file.as_str()); .join(file.as_str());
match tokio::fs::try_exists(&path).await { match tokio::fs::try_exists(&path).await {
Ok(true) => {} Ok(true) => {}
Ok(false) => return Ok(std::string::String::new()), Ok(false) => return Ok(String::new()),
Err(err) => { Err(err) => {
return Err(coded_error( return Err(coded_error(
"PROFILE_READ_FAILED", "PROFILE_READ_FAILED",
@@ -536,12 +440,11 @@ pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::str
} }
let data = item.read_file().await.with_error_code("PROFILE_READ_FAILED")?; let data = item.read_file().await.with_error_code("PROFILE_READ_FAILED")?;
Ok(data.into()) Ok(data)
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn get_next_update_time(uid: String) -> CmdResult<Option<i64>> {
pub async fn get_next_update_time(uid: std::string::String) -> CmdResult<Option<i64>> {
let timer = Timer::global(); let timer = Timer::global();
let next_time = timer.get_next_update_time(&uid).await; let next_time = timer.get_next_update_time(&uid).await;
Ok(next_time) Ok(next_time)
-4
View File
@@ -18,7 +18,6 @@ use std::{
/// Merges one selection pair into fresh backend state to avoid stale-list overwrites. /// Merges one selection pair into fresh backend state to avoid stale-list overwrites.
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn record_selected_node(group_name: String, node: String) -> CmdResult<()> { pub async fn record_selected_node(group_name: String, node: String) -> CmdResult<()> {
crate::config::profiles::record_selected_node(&group_name, &node) crate::config::profiles::record_selected_node(&group_name, &node)
.await .await
@@ -26,7 +25,6 @@ pub async fn record_selected_node(group_name: String, node: String) -> CmdResult
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn forget_selected_node(group_name: String) -> CmdResult<()> { pub async fn forget_selected_node(group_name: String) -> CmdResult<()> {
crate::config::profiles::forget_selected_node(&group_name) crate::config::profiles::forget_selected_node(&group_name)
.await .await
@@ -106,7 +104,6 @@ fn runtime_group_scopes(config: Option<&Mapping>) -> BTreeMap<String, GroupScope
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn get_proxy_view() -> CmdResult<ProxyViewV1> { pub async fn get_proxy_view() -> CmdResult<ProxyViewV1> {
proxy_view(None).await proxy_view(None).await
} }
@@ -138,7 +135,6 @@ pub(crate) async fn proxy_view(provider_timeout: Option<std::time::Duration>) ->
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn sync_tray_proxy_selection() -> CmdResult<()> { pub async fn sync_tray_proxy_selection() -> CmdResult<()> {
if TRAY_SYNC_RUNNING if TRAY_SYNC_RUNNING
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
+36 -41
View File
@@ -1,57 +1,44 @@
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 clash_verge_logging::{Type, logging};
use serde_yaml_ng::Mapping;
use smartstring::alias::String; use smartstring::alias::String;
use std::collections::HashMap; use std::collections::HashMap;
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn get_runtime_config() -> CmdResult<Option<Mapping>> {
pub async fn get_runtime_config() -> CmdResult<Option<crate::ipc::YamlMapping>> { Ok(Config::runtime().await.latest_arc().config.clone())
Ok(Config::runtime()
.await
.latest_arc()
.config
.clone()
.map(crate::ipc::YamlMapping))
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn get_runtime_yaml() -> CmdResult<String> {
pub async fn get_runtime_yaml() -> CmdResult<std::string::String> {
let runtime = Config::runtime().await; let runtime = Config::runtime().await;
let runtime = runtime.latest_arc(); let runtime = runtime.latest_arc();
let config = runtime.config.as_ref(); let config = runtime.config.as_ref();
config config
.ok_or_else(|| anyhow!("failed to parse config to yaml file")) .ok_or_else(|| anyhow!("failed to parse config to yaml file"))
.and_then(|config| yaml_emitter::to_mihomo_config_string(config).context("failed to convert config to yaml")) .and_then(|config| {
yaml_emitter::to_mihomo_config_string(config)
.context("failed to convert config to yaml")
.map(|s| s.into())
})
.stringify_err() .stringify_err()
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn get_runtime_logs() -> CmdResult<HashMap<String, Vec<(String, String)>>> {
pub async fn get_runtime_logs() -> CmdResult<RuntimeLogs> { Ok(Config::runtime().await.latest_arc().chain_logs.clone())
Ok(RuntimeLogs(Config::runtime().await.latest_arc().chain_logs.clone()))
}
#[derive(serde::Serialize, specta::Type)]
#[serde(transparent)]
pub struct RuntimeLogs(
#[specta(type = HashMap<std::string::String, Vec<(std::string::String, std::string::String)>>)]
HashMap<String, Vec<(String, String)>>,
);
#[tauri::command]
#[specta::specta]
pub fn take_discarded_keys_notice() -> Option<std::string::String> {
crate::enhance::take_discarded_keys_notice().map(Into::into)
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub fn take_discarded_keys_notice() -> Option<String> {
pub async fn get_runtime_proxy_chain_config( crate::enhance::take_discarded_keys_notice()
proxy_chain_exit_node: std::string::String, }
) -> CmdResult<std::string::String> {
#[tauri::command]
pub async fn get_runtime_proxy_chain_config(proxy_chain_exit_node: String) -> CmdResult<String> {
let runtime = Config::runtime().await; let runtime = Config::runtime().await;
let runtime = runtime.latest_arc(); let runtime = runtime.latest_arc();
@@ -72,7 +59,7 @@ pub async fn get_runtime_proxy_chain_config(
false false
} }
}) { }) {
proxies_chain.push(proxy); proxies_chain.push(proxy.to_owned());
proxy_name = proxy.get("dialer-proxy").map(|x| x.as_str()); proxy_name = proxy.get("dialer-proxy").map(|x| x.as_str());
} }
@@ -81,17 +68,18 @@ pub async fn get_runtime_proxy_chain_config(
.find(|proxy| proxy.get("name").map(|x| x.as_str()) == proxy_name) .find(|proxy| proxy.get("name").map(|x| x.as_str()) == proxy_name)
&& !proxies_chain.is_empty() && !proxies_chain.is_empty()
{ {
proxies_chain.push(entry_proxy); proxies_chain.push(entry_proxy.to_owned());
} }
proxies_chain.reverse(); proxies_chain.reverse();
let mut config: HashMap<String, Vec<&serde_yaml_ng::Value>> = HashMap::new(); let mut config: HashMap<String, Vec<serde_yaml_ng::Value>> = HashMap::new();
config.insert("proxies".into(), proxies_chain); config.insert("proxies".into(), proxies_chain);
yaml_emitter::to_mihomo_config_string(&config) yaml_emitter::to_mihomo_config_string(&config)
.context("YAML generation failed") .context("YAML generation failed")
.map(|s| s.into())
.stringify_err() .stringify_err()
} else { } else {
Err("failed to get proxies or proxy-groups".into()) Err("failed to get proxies or proxy-groups".into())
@@ -99,13 +87,20 @@ pub async fn get_runtime_proxy_chain_config(
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn update_proxy_chain_config_in_runtime(proxy_chain_config: Option<serde_yaml_ng::Value>) -> CmdResult<()> {
pub async fn update_proxy_chain_config_in_runtime( match CoreManager::global()
proxy_chain_config: Option<crate::ipc::YamlValue>,
) -> CmdResult<crate::core::validate::ValidationOutcome> {
let proxy_chain_config = proxy_chain_config.map(|value| value.0);
CoreManager::global()
.update_runtime_config(|d| d.update_proxy_chain_config(proxy_chain_config)) .update_runtime_config(|d| d.update_proxy_chain_config(proxy_chain_config))
.await .await
.stringify_err() {
Ok(outcome) if outcome.is_valid() => {}
Ok(outcome) => logging!(
warn,
Type::Core,
"Failed to apply runtime proxy chain config: {}",
outcome
),
Err(err) => logging!(error, Type::Core, "Failed to apply runtime proxy chain config: {err:#}"),
}
Ok(())
} }
+1 -7
View File
@@ -16,13 +16,7 @@ use tokio::fs;
/// 保存profiles的配置 /// 保存profiles的配置
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn save_profile_file(index: String, file_data: Option<String>) -> CmdResult<ValidationOutcome> {
pub async fn save_profile_file(
index: std::string::String,
file_data: Option<std::string::String>,
) -> CmdResult<ValidationOutcome> {
let index: String = index.into();
let file_data = file_data.map(String::from);
let file_data = match file_data { let file_data = match file_data {
Some(d) => d, Some(d) => d,
None => return Ok(ValidationOutcome::Valid), None => return Ok(ValidationOutcome::Valid),
+2 -13
View File
@@ -8,11 +8,11 @@ use crate::{
}, },
}; };
#[derive(Debug, PartialEq, Eq, serde::Serialize, specta::Type)] #[derive(Debug, PartialEq, Eq, serde::Serialize)]
#[serde(tag = "status", rename_all = "camelCase")] #[serde(tag = "status", rename_all = "camelCase")]
pub enum ServiceInstallOutcome { pub enum ServiceInstallOutcome {
Installed, Installed,
#[cfg_attr(not(any(windows, test)), allow(dead_code))] #[cfg(any(windows, test))]
Sidecar { Sidecar {
reason: String, reason: String,
}, },
@@ -82,13 +82,11 @@ where
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn install_service() -> CmdResult<ServiceInstallOutcome> { pub async fn install_service() -> CmdResult<ServiceInstallOutcome> {
execute_service_operation_sync(ServiceStatus::InstallRequired, "SERVICE_INSTALL_FAILED").await execute_service_operation_sync(ServiceStatus::InstallRequired, "SERVICE_INSTALL_FAILED").await
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn uninstall_service() -> CmdResult { pub async fn uninstall_service() -> CmdResult {
CoreManager::global() CoreManager::global()
.uninstall_service_and_start_sidecar() .uninstall_service_and_start_sidecar()
@@ -97,19 +95,16 @@ pub async fn uninstall_service() -> CmdResult {
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn reinstall_service() -> CmdResult<ServiceInstallOutcome> { pub async fn reinstall_service() -> CmdResult<ServiceInstallOutcome> {
execute_service_operation_sync(ServiceStatus::ReinstallRequired, "SERVICE_REINSTALL_FAILED").await execute_service_operation_sync(ServiceStatus::ReinstallRequired, "SERVICE_REINSTALL_FAILED").await
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn repair_service() -> CmdResult<ServiceInstallOutcome> { pub async fn repair_service() -> CmdResult<ServiceInstallOutcome> {
execute_service_operation_sync(ServiceStatus::ForceReinstallRequired, "SERVICE_REPAIR_FAILED").await execute_service_operation_sync(ServiceStatus::ForceReinstallRequired, "SERVICE_REPAIR_FAILED").await
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn continue_with_sidecar() -> CmdResult { pub async fn continue_with_sidecar() -> CmdResult {
crate::core::CoreManager::global() crate::core::CoreManager::global()
.continue_with_sidecar(None) .continue_with_sidecar(None)
@@ -118,37 +113,31 @@ pub async fn continue_with_sidecar() -> CmdResult {
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub fn get_sidecar_failure() -> crate::core::notification::SidecarFailureSnapshot { pub fn get_sidecar_failure() -> crate::core::notification::SidecarFailureSnapshot {
crate::core::notification::sidecar_failure_snapshot() crate::core::notification::sidecar_failure_snapshot()
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub fn take_service_fallback_notice() -> Option<crate::core::service::ServiceFallbackNotice> { pub fn take_service_fallback_notice() -> Option<crate::core::service::ServiceFallbackNotice> {
crate::core::service::take_service_fallback_notice() crate::core::service::take_service_fallback_notice()
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub fn get_core_startup_error() -> Option<crate::core::manager::CoreFailure> { pub fn get_core_startup_error() -> Option<crate::core::manager::CoreFailure> {
crate::core::CoreManager::global().get_startup_error() crate::core::CoreManager::global().get_startup_error()
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub fn take_service_repair_notice() -> bool { pub fn take_service_repair_notice() -> bool {
crate::core::service::take_service_repair_notice() crate::core::service::take_service_repair_notice()
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub fn take_service_owner_notice() -> Option<String> { pub fn take_service_owner_notice() -> Option<String> {
crate::core::service::take_service_owner_notice() crate::core::service::take_service_owner_notice()
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub fn sync_runtime_providers() { pub fn sync_runtime_providers() {
if matches!(*CoreManager::global().get_running_mode(), RunningMode::Service) { if matches!(*CoreManager::global().get_running_mode(), RunningMode::Service) {
request_runtime_provider_sync(timing::RUNTIME_PROVIDER_SETTLE); request_runtime_provider_sync(timing::RUNTIME_PROVIDER_SETTLE);
-2
View File
@@ -5,13 +5,11 @@ use crate::core::{
/// Returns one coherent core/service snapshot instead of independently refreshed state. /// Returns one coherent core/service snapshot instead of independently refreshed state.
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn get_runtime_state() -> Result<RunStateView, String> { pub async fn get_runtime_state() -> Result<RunStateView, String> {
Ok(RUN_STATE.settled().await.to_view()) Ok(RUN_STATE.settled().await.to_view())
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn get_pending_failures() -> Vec<PendingFailure> { pub async fn get_pending_failures() -> Vec<PendingFailure> {
notification::pending_failures() notification::pending_failures()
} }
-1
View File
@@ -22,7 +22,6 @@ mod platform {
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn invoke_uwp_tool() -> CmdResult { pub async fn invoke_uwp_tool() -> CmdResult {
platform::invoke_uwp_tool() platform::invoke_uwp_tool()
} }
-2
View File
@@ -9,14 +9,12 @@ use clash_verge_draft::SharedDraft;
/// 获取Verge配置 /// 获取Verge配置
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn get_verge_config() -> CmdResult<SharedDraft<IVerge>> { pub async fn get_verge_config() -> CmdResult<SharedDraft<IVerge>> {
feat::fetch_verge_config().await.stringify_err() feat::fetch_verge_config().await.stringify_err()
} }
/// 修改Verge配置 /// 修改Verge配置
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn patch_verge_config(payload: IVerge) -> CmdResult { pub async fn patch_verge_config(payload: IVerge) -> CmdResult {
let operation = system_proxy_operation(&payload); let operation = system_proxy_operation(&payload);
let result = match operation { let result = match operation {
+6 -22
View File
@@ -4,18 +4,11 @@ use crate::{
config::{Config, IVerge}, config::{Config, IVerge},
core, feat, core, feat,
}; };
use reqwest_dav::list_cmd::ListFile;
use smartstring::alias::String; use smartstring::alias::String;
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn save_webdav_config(url: String, username: String, password: String) -> CmdResult<()> {
pub async fn save_webdav_config(
url: std::string::String,
username: std::string::String,
password: std::string::String,
) -> CmdResult<()> {
let url: String = url.into();
let username: String = username.into();
let password: String = password.into();
let patch = IVerge { let patch = IVerge {
webdav_url: Some(url), webdav_url: Some(url),
webdav_username: Some(username), webdav_username: Some(username),
@@ -32,31 +25,22 @@ pub async fn save_webdav_config(
} }
#[tauri::command] #[tauri::command]
#[specta::specta]
pub async fn create_webdav_backup() -> CmdResult<()> { pub async fn create_webdav_backup() -> CmdResult<()> {
feat::create_backup_and_upload_webdav().await.stringify_err() feat::create_backup_and_upload_webdav().await.stringify_err()
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn list_webdav_backup() -> CmdResult<Vec<ListFile>> {
pub async fn list_webdav_backup() -> CmdResult<Vec<crate::ipc::WebDavFile>> { feat::list_wevdav_backup().await.stringify_err()
feat::list_wevdav_backup()
.await
.map(|files| files.into_iter().map(Into::into).collect())
.stringify_err()
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn delete_webdav_backup(filename: String) -> CmdResult<()> {
pub async fn delete_webdav_backup(filename: std::string::String) -> CmdResult<()> {
let filename: String = filename.into();
feat::delete_webdav_backup(filename).await.stringify_err() feat::delete_webdav_backup(filename).await.stringify_err()
} }
#[tauri::command] #[tauri::command]
#[specta::specta] pub async fn restore_webdav_backup(filename: String) -> CmdResult<()> {
pub async fn restore_webdav_backup(filename: std::string::String) -> CmdResult<()> {
let filename: String = filename.into();
feat::restore_webdav_backup(filename) feat::restore_webdav_backup(filename)
.await .await
.map_err(|error| super::proxy_aware_error(&error)) .map_err(|error| super::proxy_aware_error(&error))
+6 -6
View File
@@ -308,7 +308,7 @@ impl IClashTemp {
} }
} }
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)] #[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct ClashInfo { pub struct ClashInfo {
/// clash core port /// clash core port
pub mixed_port: u16, pub mixed_port: u16,
@@ -364,14 +364,14 @@ fn test_clash_info() {
assert_eq!(get_case(8888, "192.168.1.1:80800"), get_result(8888, "127.0.0.1:9097")); assert_eq!(get_case(8888, "192.168.1.1:80800"), get_result(8888, "127.0.0.1:9097"));
} }
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)] #[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct IClashExternalControllerCors { pub struct IClashExternalControllerCors {
pub allow_origins: Option<Vec<String>>, pub allow_origins: Option<Vec<String>>,
pub allow_private_network: Option<bool>, pub allow_private_network: Option<bool>,
} }
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)] #[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct IClash { pub struct IClash {
pub mixed_port: Option<u16>, pub mixed_port: Option<u16>,
@@ -387,7 +387,7 @@ pub struct IClash {
pub external_controller_cors: Option<IClashExternalControllerCors>, pub external_controller_cors: Option<IClashExternalControllerCors>,
} }
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)] #[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct IClashTUN { pub struct IClashTUN {
pub enable: Option<bool>, pub enable: Option<bool>,
@@ -397,7 +397,7 @@ pub struct IClashTUN {
pub dns_hijack: Option<Vec<String>>, pub dns_hijack: Option<Vec<String>>,
} }
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)] #[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct IClashDNS { pub struct IClashDNS {
pub enable: Option<bool>, pub enable: Option<bool>,
@@ -414,7 +414,7 @@ pub struct IClashDNS {
pub nameserver_policy: Option<Vec<String>>, pub nameserver_policy: Option<Vec<String>>,
} }
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)] #[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct IClashFallbackFilter { pub struct IClashFallbackFilter {
pub geoip: Option<bool>, pub geoip: Option<bool>,
+1 -2
View File
@@ -106,11 +106,10 @@ impl DnsOverrideState {
} }
} }
#[derive(Debug, Clone, Default, Deserialize, Serialize, specta::Type)] #[derive(Debug, Clone, Default, Deserialize, Serialize)]
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 -24
View File
@@ -27,34 +27,28 @@ pub(super) fn normalize_profile_home_url(raw: &str) -> Option<String> {
Some(url.to_string().into()) Some(url.to_string().into())
} }
#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)] #[derive(Debug, Clone, Deserialize, Serialize, 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")]
pub selected: Option<Vec<PrfSelected>>, pub selected: Option<Vec<PrfSelected>>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
#[specta(type = Option<std::collections::BTreeMap<std::string::String, std::string::String>>)]
pub latency_test_urls: Option<std::collections::BTreeMap<String, String>>, pub latency_test_urls: Option<std::collections::BTreeMap<String, String>>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
@@ -66,24 +60,19 @@ 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)]
#[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>,
} }
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize, specta::Type)] #[derive(Default, Debug, Clone, Copy, Deserialize, Serialize)]
pub struct PrfExtra { pub struct PrfExtra {
pub upload: u64, pub upload: u64,
pub download: u64, pub download: u64,
@@ -91,11 +80,9 @@ pub struct PrfExtra {
pub expire: u64, pub expire: u64,
} }
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)] #[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[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")]
@@ -118,15 +105,15 @@ pub struct PrfOption {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub allow_auto_update: Option<bool>, pub allow_auto_update: Option<bool>,
#[specta(type = Option<std::string::String>)]
pub merge: Option<String>, pub merge: Option<String>,
#[specta(type = Option<std::string::String>)]
pub script: Option<String>, pub script: Option<String>,
#[specta(type = Option<std::string::String>)]
pub rules: Option<String>, pub rules: Option<String>,
#[specta(type = Option<std::string::String>)]
pub proxies: Option<String>, pub proxies: Option<String>,
#[specta(type = Option<std::string::String>)]
pub groups: Option<String>, pub groups: Option<String>,
} }
+1 -3
View File
@@ -48,10 +48,8 @@ const SELECTED_NODES_SETTLE_INTERVAL: Duration = Duration::from_secs(1);
const SELECTED_NODES_FIRST_PASS_BUDGET: Duration = Duration::from_secs(3); const SELECTED_NODES_FIRST_PASS_BUDGET: Duration = Duration::from_secs(3);
/// Define the `profiles.yaml` schema /// Define the `profiles.yaml` schema
#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)] #[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[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>>,
+14 -45
View File
@@ -11,30 +11,26 @@ use serde::{Deserialize, Serialize};
use smartstring::alias::String; use smartstring::alias::String;
/// ### `verge.yaml` schema /// ### `verge.yaml` schema
#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)] #[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[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 +48,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,43 +84,39 @@ 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>,
#[specta(type = Option<crate::ipc::JsonValue>)]
pub home_cards: Option<serde_json::Value>, pub home_cards: Option<serde_json::Value>,
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>,
@@ -184,7 +171,6 @@ pub struct IVerge {
skip_serializing_if = "Option::is_none", skip_serializing_if = "Option::is_none",
default default
)] )]
#[specta(type = Option<std::string::String>)]
pub webdav_url: Option<String>, pub webdav_url: Option<String>,
#[serde( #[serde(
@@ -193,7 +179,6 @@ pub struct IVerge {
skip_serializing_if = "Option::is_none", skip_serializing_if = "Option::is_none",
default default
)] )]
#[specta(type = Option<std::string::String>)]
pub webdav_username: Option<String>, pub webdav_username: Option<String>,
#[serde( #[serde(
@@ -202,14 +187,12 @@ pub struct IVerge {
skip_serializing_if = "Option::is_none", skip_serializing_if = "Option::is_none",
default default
)] )]
#[specta(type = Option<std::string::String>)]
pub webdav_password: Option<String>, pub webdav_password: Option<String>,
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
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>,
@@ -226,41 +209,27 @@ pub struct IVerge {
pub enable_external_controller: Option<bool>, pub enable_external_controller: Option<bool>,
} }
#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)] #[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[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)]
#[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>,
} }
+1 -1
View File
@@ -24,7 +24,7 @@ pub async fn update_launch() -> Result<()> {
#[cfg(not(target_os = "windows"))] #[cfg(not(target_os = "windows"))]
{ {
let app_handle = Handle::app_handle(); let app_handle = Handle::app_handle();
let autostart_manager = app_handle.autostart(); let autostart_manager = app_handle.autolaunch();
if is_enable { if is_enable {
logging_error!(Type::System, "{:?}", autostart_manager.enable()); logging_error!(Type::System, "{:?}", autostart_manager.enable());
} else { } else {
+6 -6
View File
@@ -38,7 +38,7 @@ pub(crate) fn proxy_listener_keys() -> impl Iterator<Item = &'static str> {
PROXY_LISTENERS.iter().map(|(key, _, _)| *key) PROXY_LISTENERS.iter().map(|(key, _, _)| *key)
} }
#[derive(Debug, Deserialize, specta::Type)] #[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct ProxyPortSettings { pub struct ProxyPortSettings {
pub mixed_port: u16, pub mixed_port: u16,
@@ -48,27 +48,27 @@ pub struct ProxyPortSettings {
pub tproxy: ToggleableProxyPort, pub tproxy: ToggleableProxyPort,
} }
#[derive(Clone, Copy, Debug, Deserialize, specta::Type)] #[derive(Clone, Copy, Debug, Deserialize)]
pub struct ToggleableProxyPort { pub struct ToggleableProxyPort {
pub enabled: bool, pub enabled: bool,
pub port: u16, pub port: u16,
} }
#[derive(Debug, Deserialize, specta::Type)] #[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct ListenerProbe { pub struct ListenerProbe {
pub address: String, pub address: String,
pub transports: Vec<ListenerTransport>, pub transports: Vec<ListenerTransport>,
} }
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Hash, Serialize, specta::Type)] #[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "lowercase")] #[serde(rename_all = "lowercase")]
pub enum ListenerTransport { pub enum ListenerTransport {
Tcp, Tcp,
Udp, Udp,
} }
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)] #[derive(Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "status", rename_all = "camelCase")] #[serde(tag = "status", rename_all = "camelCase")]
pub enum ListenerProbeOutcome { pub enum ListenerProbeOutcome {
Available, Available,
@@ -77,7 +77,7 @@ pub enum ListenerProbeOutcome {
Indeterminate { message: String }, Indeterminate { message: String },
} }
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)] #[derive(Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "status", rename_all = "camelCase")] #[serde(tag = "status", rename_all = "camelCase")]
pub enum SaveProxyPortsOutcome { pub enum SaveProxyPortsOutcome {
Saved, Saved,
+2 -2
View File
@@ -57,7 +57,7 @@ fn claim_core_readiness_generation(state: &AtomicU64, captured_generation: u64)
.is_ok() .is_ok()
} }
#[derive(Clone, Copy, Debug, serde::Serialize, PartialEq, Eq, specta::Type)] #[derive(Clone, Copy, Debug, serde::Serialize, PartialEq, Eq)]
pub enum RunningMode { pub enum RunningMode {
Service, Service,
Sidecar, Sidecar,
@@ -75,7 +75,7 @@ impl fmt::Display for RunningMode {
} }
/// Why the Core is not running, kept until a Core starts again. /// Why the Core is not running, kept until a Core starts again.
#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, specta::Type)] #[derive(Clone, Debug, serde::Serialize, PartialEq, Eq)]
#[serde(tag = "kind", content = "detail", rename_all = "camelCase")] #[serde(tag = "kind", content = "detail", rename_all = "camelCase")]
pub enum CoreFailure { pub enum CoreFailure {
StartFailed(String), StartFailed(String),
+4 -1
View File
@@ -52,7 +52,10 @@ impl Handle {
/// Sent on every transition, so the frontend does not have to poll to notice that the Core /// Sent on every transition, so the frontend does not have to poll to notice that the Core
/// stopped or that the Service came back. /// stopped or that the Service came back.
pub fn notify_run_state(state: &crate::core::runstate::RunStateView) { pub fn notify_run_state(state: &crate::core::runstate::RunStateView) {
Self::send_event(FrontendEvent::RunStateChanged { state: state.clone() }); let Ok(state) = serde_json::to_value(state) else {
return;
};
Self::send_event(FrontendEvent::RunStateChanged { state });
} }
pub fn notify_profile_changed(profile_id: &String) { pub fn notify_profile_changed(profile_id: &String) {
+2 -2
View File
@@ -3,8 +3,9 @@ pub use announce::{Refresh, announce};
pub mod desktop; pub mod desktop;
pub mod handle; pub mod handle;
pub mod notification; pub mod notification;
pub use notification::frontend_wire_contract;
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, specta::Type)] #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub enum NoticeStatus { pub enum NoticeStatus {
#[serde(rename = "info")] #[serde(rename = "info")]
Info, Info,
@@ -82,7 +83,6 @@ impl NoticeStatus {
/// Every variant in golden order. The wire-contract export and the golden /// Every variant in golden order. The wire-contract export and the golden
/// test both derive their variant list from here; expected strings stay /// test both derive their variant list from here; expected strings stay
/// hand-written in the test so renames cannot slip through. /// hand-written in the test so renames cannot slip through.
#[cfg(test)]
pub const ALL: [Self; 34] = [ pub const ALL: [Self; 34] = [
Self::Info, Self::Info,
Self::ImportSubUrlOk, Self::ImportSubUrlOk,
+58 -61
View File
@@ -1,7 +1,6 @@
use super::NoticeStatus; use super::NoticeStatus;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use parking_lot::Mutex; use parking_lot::Mutex;
#[cfg(test)]
use serde_json::json; use serde_json::json;
use smartstring::alias::String; use smartstring::alias::String;
use std::sync::Arc; use std::sync::Arc;
@@ -32,7 +31,7 @@ pub enum FrontendEvent<'a> {
uid: &'a String, uid: &'a String,
}, },
RunStateChanged { RunStateChanged {
state: crate::core::runstate::RunStateView, state: serde_json::Value,
}, },
PendingFailuresChanged, PendingFailuresChanged,
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
@@ -43,7 +42,7 @@ pub enum FrontendEvent<'a> {
/// Operation associated with a pending failure. /// Operation associated with a pending failure.
#[allow(clippy::enum_variant_names)] #[allow(clippy::enum_variant_names)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, specta::Type)] #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub enum FailedOperation { pub enum FailedOperation {
SystemProxyEnable, SystemProxyEnable,
@@ -73,14 +72,12 @@ impl FailedOperation {
} }
/// Latest unresolved failure for one stable code. /// Latest unresolved failure for one stable code.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, specta::Type)] #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[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.
@@ -244,10 +241,9 @@ pub fn what_was_asked() -> FailedOperation {
static PENDING_FAILURES: LazyLock<FailureTable> = LazyLock::new(FailureTable::default); static PENDING_FAILURES: LazyLock<FailureTable> = LazyLock::new(FailureTable::default);
/// A removal has a revision too, so a delayed read cannot restore a resolved failure. /// A removal has a revision too, so a delayed read cannot restore a resolved failure.
#[derive(Debug, Default, Clone, serde::Serialize, specta::Type)] #[derive(Debug, Default, Clone, serde::Serialize)]
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>,
} }
@@ -331,7 +327,24 @@ impl NotificationSystem {
} }
fn serialize_event(event: FrontendEvent) -> (&'static str, Result<serde_json::Value, serde_json::Error>) { fn serialize_event(event: FrontendEvent) -> (&'static str, Result<serde_json::Value, serde_json::Error>) {
serialize_frontend_event(event) match event {
FrontendEvent::RefreshClash => ("verge://refresh-clash-config", Ok(json!("yes"))),
FrontendEvent::RefreshVerge => ("verge://refresh-verge-config", Ok(json!("yes"))),
FrontendEvent::RefreshProfiles => ("verge://refresh-profiles", Ok(json!("yes"))),
FrontendEvent::RefreshProxyConfig => ("verge://refresh-proxy-config", Ok(serde_json::Value::Null)),
FrontendEvent::NoticeMessage { status, message } => (
"verge://notice-message",
serde_json::to_value((status, message.as_ref())),
),
FrontendEvent::ProfileChanged { current_profile_id } => ("profile-changed", Ok(json!(current_profile_id))),
FrontendEvent::TimerUpdated { profile_index } => ("verge://timer-updated", Ok(json!(profile_index))),
FrontendEvent::ProfileUpdateStarted { uid } => ("profile-update-started", Ok(json!({ "uid": uid }))),
FrontendEvent::ProfileUpdateCompleted { uid } => ("profile-update-completed", Ok(json!({ "uid": uid }))),
FrontendEvent::RunStateChanged { state } => ("verge://run-state-changed", Ok(state)),
FrontendEvent::PendingFailuresChanged => ("verge://pending-failures-changed", Ok(serde_json::Value::Null)),
#[cfg(target_os = "linux")]
FrontendEvent::ThemeChanged { theme } => ("tauri://theme-changed", serde_json::to_value(theme)),
}
} }
pub(crate) fn send_event(app_handle: AppHandle, event: FrontendEvent) { pub(crate) fn send_event(app_handle: AppHandle, event: FrontendEvent) {
@@ -368,21 +381,20 @@ 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)] /// Shared by the wire golden test and the contract export so the two cannot drift.
fn sample_frontend_events(uid: &String) -> Vec<(FrontendEvent<'_>, &'static str, serde_json::Value)> { fn sample_frontend_events(uid: &String) -> Vec<(FrontendEvent<'_>, &'static str, serde_json::Value)> {
let state = crate::core::runstate::RunState {
health: Default::default(),
pending: None,
sidecar_allowed: false,
mode: crate::core::manager::RunningMode::NotRunning,
is_admin: false,
op_in_flight: false,
}
.to_view();
vec![ vec![
(FrontendEvent::RefreshClash, "verge://refresh-clash-config", json!(null)), (
(FrontendEvent::RefreshVerge, "verge://refresh-verge-config", json!(null)), FrontendEvent::RefreshClash,
(FrontendEvent::RefreshProfiles, "verge://refresh-profiles", json!(null)), "verge://refresh-clash-config",
json!("yes"),
),
(
FrontendEvent::RefreshVerge,
"verge://refresh-verge-config",
json!("yes"),
),
(FrontendEvent::RefreshProfiles, "verge://refresh-profiles", json!("yes")),
( (
FrontendEvent::RefreshProxyConfig, FrontendEvent::RefreshProxyConfig,
"verge://refresh-proxy-config", "verge://refresh-proxy-config",
@@ -402,9 +414,11 @@ fn sample_frontend_events(uid: &String) -> Vec<(FrontendEvent<'_>, &'static str,
json!("profile"), json!("profile"),
), ),
( (
FrontendEvent::RunStateChanged { state: state.clone() }, FrontendEvent::RunStateChanged {
state: json!({"running": true}),
},
"verge://run-state-changed", "verge://run-state-changed",
serde_json::to_value(state).unwrap_or(serde_json::Value::Null), json!({"running": true}),
), ),
( (
FrontendEvent::PendingFailuresChanged, FrontendEvent::PendingFailuresChanged,
@@ -431,41 +445,24 @@ fn sample_frontend_events(uid: &String) -> Vec<(FrontendEvent<'_>, &'static str,
] ]
} }
macro_rules! frontend_events { /// Machine-readable form of the frontend wire contract: every event name with a
($( $field:ident: $payload:ty = $name:literal, $pattern:pat => $value:expr; )*) => { /// serialized sample payload, plus every notice status string. The sample
#[derive(serde::Serialize, specta::Type)] /// payload's JSON shape (string / null / array / object) is what the frontend
pub struct VergeEventPayloads { /// generator maps to TypeScript types. `ThemeChanged` is a Tauri built-in
$(#[serde(rename = $name)] pub $field: $payload,)* /// linux-only window event, not part of this contract.
} pub fn frontend_wire_contract() -> serde_json::Value {
let uid = String::from("sample");
fn serialize_frontend_event(event: FrontendEvent) -> (&'static str, Result<serde_json::Value, serde_json::Error>) { let events: Vec<_> = sample_frontend_events(&uid)
match event { .into_iter()
$($pattern => { .map(|(event, _, _)| {
let payload: $payload = $value; let (name, payload) = NotificationSystem::serialize_event(event);
($name, serde_json::to_value(payload)) json!({ "name": name, "sample": payload.unwrap_or(serde_json::Value::Null) })
},)* })
#[cfg(target_os = "linux")] .collect();
FrontendEvent::ThemeChanged { theme } => ("tauri://theme-changed", serde_json::to_value(theme)), let statuses: Vec<_> = NoticeStatus::ALL
} .iter()
} // A unit variant with a string rename cannot fail to serialize.
}; .filter_map(|status| serde_json::to_value(status).ok())
} .collect();
json!({ "version": 1, "events": events, "noticeStatuses": statuses })
frontend_events! {
refresh_clash: () = "verge://refresh-clash-config", FrontendEvent::RefreshClash => ();
refresh_verge: () = "verge://refresh-verge-config", FrontendEvent::RefreshVerge => ();
refresh_profiles: () = "verge://refresh-profiles", FrontendEvent::RefreshProfiles => ();
refresh_proxy: () = "verge://refresh-proxy-config", FrontendEvent::RefreshProxyConfig => ();
notice: (NoticeStatus, std::string::String) = "verge://notice-message", FrontendEvent::NoticeMessage { status, ref message } => (status, message.to_string());
profile_changed: std::string::String = "profile-changed", FrontendEvent::ProfileChanged { current_profile_id } => current_profile_id.to_string();
timer_updated: std::string::String = "verge://timer-updated", FrontendEvent::TimerUpdated { profile_index } => profile_index.to_string();
profile_started: ProfileUpdatePayload = "profile-update-started", FrontendEvent::ProfileUpdateStarted { uid } => ProfileUpdatePayload { uid: uid.to_string() };
profile_completed: ProfileUpdatePayload = "profile-update-completed", FrontendEvent::ProfileUpdateCompleted { uid } => ProfileUpdatePayload { uid: uid.to_string() };
run_state: crate::core::runstate::RunStateView = "verge://run-state-changed", FrontendEvent::RunStateChanged { state } => state;
pending_failures: () = "verge://pending-failures-changed", FrontendEvent::PendingFailuresChanged => ();
}
#[derive(serde::Serialize, specta::Type)]
pub struct ProfileUpdatePayload {
pub uid: std::string::String,
} }
+19 -43
View File
@@ -1,6 +1,6 @@
use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::collections::{BTreeMap, BTreeSet, HashMap};
use serde::{Serialize, Serializer, ser::SerializeMap as _}; use serde::Serialize;
use tauri_plugin_mihomo::models::{ use tauri_plugin_mihomo::models::{
DelayHistory, Extra, Proxies, Proxy, ProxyProvider, ProxyProviders, ProxyType, VehicleType, DelayHistory, Extra, Proxies, Proxy, ProxyProvider, ProxyProviders, ProxyType, VehicleType,
}; };
@@ -20,7 +20,7 @@ pub struct GroupScope {
pub struct ProxyViewBuilder; pub struct ProxyViewBuilder;
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)] #[derive(Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct ProxyViewV1 { pub struct ProxyViewV1 {
pub schema_version: u8, pub schema_version: u8,
@@ -34,21 +34,21 @@ pub struct ProxyViewV1 {
pub providers: Vec<ProxyProviderView>, pub providers: Vec<ProxyProviderView>,
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, specta::Type)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")] #[serde(rename_all = "lowercase")]
pub enum ProxyViewOrderSource { pub enum ProxyViewOrderSource {
Runtime, Runtime,
Fallback, Fallback,
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, specta::Type)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")] #[serde(rename_all = "lowercase")]
pub enum ProxyViewProviderState { pub enum ProxyViewProviderState {
Ready, Ready,
Unavailable, Unavailable,
} }
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)] #[derive(Debug, PartialEq, Eq, Serialize)]
pub struct ProxyCapabilities { pub struct ProxyCapabilities {
pub udp: bool, pub udp: bool,
pub xudp: bool, pub xudp: bool,
@@ -57,35 +57,13 @@ pub struct ProxyCapabilities {
pub smux: bool, pub smux: bool,
} }
#[derive(Serialize, specta::Type)] #[derive(Debug, PartialEq, Eq, Serialize)]
struct ProxyLatencyHistory<'a> {
#[specta(type = Vec<crate::ipc::DelayHistory>)]
history: &'a [DelayHistory],
}
fn serialize_proxy_latency_history<S: Serializer>(
extra: &HashMap<String, Extra>,
serializer: S,
) -> Result<S::Ok, S::Error> {
let mut map = serializer.serialize_map(Some(extra.len()))?;
for (url, extra) in extra {
map.serialize_entry(
url,
&ProxyLatencyHistory {
history: &extra.history,
},
)?;
}
map.end()
}
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct ProxyGroupView { pub struct ProxyGroupView {
pub name: String, pub name: String,
#[serde(rename = "type")] #[serde(rename = "type")]
#[specta(type = String)]
pub proxy_type: ProxyType, pub proxy_type: ProxyType,
pub alive: bool,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub now: Option<String>, pub now: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
@@ -96,28 +74,22 @@ pub struct ProxyGroupView {
pub icon: Option<String>, pub icon: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub test_url: Option<String>, pub test_url: Option<String>,
#[specta(type = Vec<crate::ipc::DelayHistory>)]
pub history: Vec<DelayHistory>, pub history: Vec<DelayHistory>,
#[serde(serialize_with = "serialize_proxy_latency_history")]
#[specta(type = HashMap<String, ProxyLatencyHistory<'static>>)]
pub extra: HashMap<String, Extra>, pub extra: HashMap<String, Extra>,
#[serde(flatten)] #[serde(flatten)]
pub capabilities: ProxyCapabilities, pub capabilities: ProxyCapabilities,
pub members: Vec<ProxyMemberRef>, pub members: Vec<ProxyMemberRef>,
} }
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)] #[derive(Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct ProxyNodeView { pub struct ProxyNodeView {
pub record_id: String, pub record_id: String,
pub name: String, pub name: String,
#[serde(rename = "type")] #[serde(rename = "type")]
#[specta(type = String)]
pub proxy_type: ProxyType, pub proxy_type: ProxyType,
#[specta(type = Vec<crate::ipc::DelayHistory>)] pub alive: bool,
pub history: Vec<DelayHistory>, pub history: Vec<DelayHistory>,
#[serde(serialize_with = "serialize_proxy_latency_history")]
#[specta(type = HashMap<String, ProxyLatencyHistory<'static>>)]
pub extra: HashMap<String, Extra>, pub extra: HashMap<String, Extra>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>, pub id: Option<String>,
@@ -132,7 +104,7 @@ pub struct ProxyNodeView {
pub source: ProxyNodeSource, pub source: ProxyNodeSource,
} }
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)] #[derive(Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "camelCase")] #[serde(tag = "kind", rename_all = "camelCase")]
pub enum ProxyNodeSource { pub enum ProxyNodeSource {
Core { Core {
@@ -147,7 +119,7 @@ pub enum ProxyNodeSource {
}, },
} }
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)] #[derive(Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "camelCase")] #[serde(tag = "kind", rename_all = "camelCase")]
pub enum ProxyMemberRef { pub enum ProxyMemberRef {
Group { Group {
@@ -164,7 +136,7 @@ pub enum ProxyMemberRef {
}, },
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, specta::Type)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub enum ProxyMemberUnresolvedReason { pub enum ProxyMemberUnresolvedReason {
#[serde(rename = "missing")] #[serde(rename = "missing")]
Missing, Missing,
@@ -174,7 +146,7 @@ pub enum ProxyMemberUnresolvedReason {
ProviderUnavailable, ProviderUnavailable,
} }
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)] #[derive(Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct ProxyProviderView { pub struct ProxyProviderView {
pub name: String, pub name: String,
@@ -186,7 +158,7 @@ pub struct ProxyProviderView {
pub proxy_record_ids: Vec<String>, pub proxy_record_ids: Vec<String>,
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, specta::Type)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub enum ProxyProviderVehicleType { pub enum ProxyProviderVehicleType {
#[serde(rename = "HTTP")] #[serde(rename = "HTTP")]
Http, Http,
@@ -196,7 +168,7 @@ pub enum ProxyProviderVehicleType {
Inline, Inline,
} }
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)] #[derive(Debug, PartialEq, Eq, Serialize)]
pub struct ProxySubscriptionInfo { pub struct ProxySubscriptionInfo {
pub upload: i64, pub upload: i64,
pub download: i64, pub download: i64,
@@ -430,6 +402,7 @@ fn build_group(name: String, proxy: Proxy, resolver: &MemberResolver<'_>) -> Pro
icon, icon,
now, now,
test_url, test_url,
alive,
history, history,
extra, extra,
udp, udp,
@@ -458,6 +431,7 @@ fn build_group(name: String, proxy: Proxy, resolver: &MemberResolver<'_>) -> Pro
ProxyGroupView { ProxyGroupView {
name, name,
proxy_type, proxy_type,
alive,
now, now,
fixed, fixed,
hidden, hidden,
@@ -482,6 +456,7 @@ fn build_node(record_id: String, name: String, proxy: Proxy, source: ProxyNodeSo
hidden, hidden,
icon, icon,
test_url, test_url,
alive,
history, history,
extra, extra,
udp, udp,
@@ -497,6 +472,7 @@ fn build_node(record_id: String, name: String, proxy: Proxy, source: ProxyNodeSo
record_id, record_id,
name, name,
proxy_type, proxy_type,
alive,
history, history,
extra, extra,
id, id,
+11 -21
View File
@@ -14,13 +14,13 @@ pub enum ServiceHealth {
} }
impl ServiceHealth { impl ServiceHealth {
const fn kind(&self) -> ServiceHealthKind { const fn kind(&self) -> &'static str {
match self { match self {
Self::Unknown => ServiceHealthKind::Unknown, Self::Unknown => "unknown",
Self::Ready => ServiceHealthKind::Ready, Self::Ready => "ready",
Self::NotInstalled => ServiceHealthKind::NotInstalled, Self::NotInstalled => "notInstalled",
Self::VersionMismatch => ServiceHealthKind::VersionMismatch, Self::VersionMismatch => "versionMismatch",
Self::Unavailable(_) => ServiceHealthKind::Unavailable, Self::Unavailable(_) => "unavailable",
} }
} }
@@ -32,7 +32,7 @@ impl ServiceHealth {
} }
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, specta::Type)] #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub enum PendingAction { pub enum PendingAction {
Install, Install,
@@ -118,11 +118,11 @@ impl RunState {
} }
} }
#[derive(Debug, Clone, serde::Serialize, specta::Type)] #[derive(Debug, Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct RunStateView { pub struct RunStateView {
pub mode: RunningMode, pub mode: RunningMode,
pub service: ServiceHealthKind, pub service: &'static str,
pub service_unavailable_reason: Option<String>, pub service_unavailable_reason: Option<String>,
pub pending_action: Option<PendingAction>, pub pending_action: Option<PendingAction>,
pub sidecar_allowed: bool, pub sidecar_allowed: bool,
@@ -232,7 +232,7 @@ mod tests {
let view = run_state.to_view(); let view = run_state.to_view();
assert_eq!(view.service, ServiceHealthKind::Unavailable); assert_eq!(view.service, "unavailable");
assert_eq!(view.service_unavailable_reason.as_deref(), Some("socket refused")); assert_eq!(view.service_unavailable_reason.as_deref(), Some("socket refused"));
assert_eq!(view.pending_action, Some(PendingAction::Reinstall)); assert_eq!(view.pending_action, Some(PendingAction::Reinstall));
assert!(view.tun_capable, "elevation alone makes TUN possible"); assert!(view.tun_capable, "elevation alone makes TUN possible");
@@ -244,7 +244,7 @@ mod tests {
fn a_healthy_view_reports_no_unavailable_reason() { fn a_healthy_view_reports_no_unavailable_reason() {
let view = state(ServiceHealth::Ready, false, false).to_view(); let view = state(ServiceHealth::Ready, false, false).to_view();
assert_eq!(view.service, ServiceHealthKind::Ready); assert_eq!(view.service, "ready");
assert_eq!(view.service_unavailable_reason, None); assert_eq!(view.service_unavailable_reason, None);
assert!(view.service_usable); assert!(view.service_usable);
assert!(!view.service_needs_attention); assert!(!view.service_needs_attention);
@@ -350,13 +350,3 @@ mod tests {
assert!(settled.tun_should_be_disabled(true)); assert!(settled.tun_should_be_disabled(true));
} }
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub enum ServiceHealthKind {
Unknown,
Ready,
NotInstalled,
VersionMismatch,
Unavailable,
}
+1 -1
View File
@@ -44,7 +44,7 @@ static PENDING_SERVICE_REPAIR_NOTICE: AtomicBool = AtomicBool::new(false);
static PENDING_SERVICE_OWNER_NOTICE: Mutex<Option<String>> = Mutex::new(None); static PENDING_SERVICE_OWNER_NOTICE: Mutex<Option<String>> = Mutex::new(None);
/// Why the Service was unavailable when the core fell back to Sidecar. /// Why the Service was unavailable when the core fell back to Sidecar.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, specta::Type)] #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[serde(tag = "kind", content = "reason", rename_all = "camelCase")] #[serde(tag = "kind", content = "reason", rename_all = "camelCase")]
pub enum ServiceFallbackNotice { pub enum ServiceFallbackNotice {
Unavailable, Unavailable,
+1 -1
View File
@@ -261,7 +261,7 @@ impl Default for Sysopt {
} }
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
static DEFAULT_BYPASS: &str = "localhost;127.*;192.168.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;*.local;<local>"; static DEFAULT_BYPASS: &str = "localhost;127.*;192.168.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;<local>";
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
static BYPASS_SEPARATOR: &str = ";"; static BYPASS_SEPARATOR: &str = ";";
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
+31 -43
View File
@@ -23,9 +23,8 @@ 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;
use tauri::Manager as _;
use tauri::{ use tauri::{
AppHandle, DynRuntime, AppHandle, Wry,
menu::{CheckMenuItem, IsMenuItem, MenuEvent, MenuItem, PredefinedMenuItem, Submenu}, menu::{CheckMenuItem, IsMenuItem, MenuEvent, MenuItem, PredefinedMenuItem, Submenu},
}; };
@@ -37,7 +36,7 @@ use menu_def::{MenuIds, MenuTexts};
// TODO: 是否需要将可变菜单抽离存储起来,后续直接更新对应菜单实例,无需重新创建菜单(待考虑) // TODO: 是否需要将可变菜单抽离存储起来,后续直接更新对应菜单实例,无需重新创建菜单(待考虑)
type ProxyMenuItem = (Option<Submenu<DynRuntime>>, Vec<Box<dyn IsMenuItem<DynRuntime>>>); type ProxyMenuItem = (Option<Submenu<Wry>>, Vec<Box<dyn IsMenuItem<Wry>>>);
const TRAY_CLICK_DEBOUNCE_MS: u64 = 300; 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";
@@ -58,14 +57,14 @@ enum IconKind {
} }
struct LatencyMenuItem { struct LatencyMenuItem {
item: MenuItem<DynRuntime>, item: MenuItem<Wry>,
running: bool, running: bool,
proxies: Vec<ProxyLatencyItem>, proxies: Vec<ProxyLatencyItem>,
provider_state: ProxyViewProviderState, provider_state: ProxyViewProviderState,
} }
struct ProxyLatencyItem { struct ProxyLatencyItem {
item: CheckMenuItem<DynRuntime>, item: CheckMenuItem<Wry>,
name: std::string::String, name: std::string::String,
provider_name: Option<std::string::String>, provider_name: Option<std::string::String>,
text: std::string::String, text: std::string::String,
@@ -567,7 +566,7 @@ fn create_hotkeys(hotkeys: &Option<Vec<String>>) -> HashMap<&str, &str> {
fn create_profile_menu_item( fn create_profile_menu_item(
app_handle: &AppHandle, app_handle: &AppHandle,
profiles_preview: Vec<IProfilePreview<'_>>, profiles_preview: Vec<IProfilePreview<'_>>,
) -> Result<Vec<CheckMenuItem<DynRuntime>>> { ) -> Result<Vec<CheckMenuItem<Wry>>> {
profiles_preview profiles_preview
.into_iter() .into_iter()
.map(|profile| { .map(|profile| {
@@ -678,7 +677,7 @@ fn create_subcreate_proxy_menu_item(
texts: &MenuTexts, texts: &MenuTexts,
verge: &IVerge, verge: &IVerge,
profiles: &crate::config::IProfiles, profiles: &crate::config::IProfiles,
) -> Vec<Submenu<DynRuntime>> { ) -> Vec<Submenu<Wry>> {
let Some(view) = view else { return Vec::new() }; let Some(view) = view else { return Vec::new() };
view.groups view.groups
.iter() .iter()
@@ -740,8 +739,8 @@ fn create_subcreate_proxy_menu_item(
}, },
); );
let separator = PredefinedMenuItem::separator(app_handle).ok()?; let separator = PredefinedMenuItem::separator(app_handle).ok()?;
let mut items: Vec<&dyn IsMenuItem<DynRuntime>> = vec![&test_item, &separator]; let mut items: Vec<&dyn IsMenuItem<Wry>> = vec![&test_item, &separator];
items.extend(group_items.iter().map(|item| item as &dyn IsMenuItem<DynRuntime>)); items.extend(group_items.iter().map(|item| item as &dyn IsMenuItem<Wry>));
Submenu::with_id_and_items( Submenu::with_id_and_items(
app_handle, app_handle,
format!("proxy_group_{}", group.name), format!("proxy_group_{}", group.name),
@@ -758,7 +757,7 @@ fn create_subcreate_proxy_menu_item(
fn create_proxy_menu_item( fn create_proxy_menu_item(
app_handle: &AppHandle, app_handle: &AppHandle,
show_proxy_groups_inline: bool, show_proxy_groups_inline: bool,
proxy_submenus: Vec<Submenu<DynRuntime>>, proxy_submenus: Vec<Submenu<Wry>>,
proxies_text: &str, proxies_text: &str,
) -> Result<ProxyMenuItem> { ) -> Result<ProxyMenuItem> {
let (proxies_submenu, inline_proxy_items) = if show_proxy_groups_inline { let (proxies_submenu, inline_proxy_items) = if show_proxy_groups_inline {
@@ -766,13 +765,13 @@ fn create_proxy_menu_item(
None, None,
proxy_submenus proxy_submenus
.into_iter() .into_iter()
.map(|submenu| Box::new(submenu) as Box<dyn IsMenuItem<DynRuntime>>) .map(|submenu| Box::new(submenu) as Box<dyn IsMenuItem<Wry>>)
.collect(), .collect(),
) )
} else if !proxy_submenus.is_empty() { } else if !proxy_submenus.is_empty() {
let proxy_submenu_refs: Vec<&dyn IsMenuItem<DynRuntime>> = proxy_submenus let proxy_submenu_refs: Vec<&dyn IsMenuItem<Wry>> = proxy_submenus
.iter() .iter()
.map(|submenu| submenu as &dyn IsMenuItem<DynRuntime>) .map(|submenu| submenu as &dyn IsMenuItem<Wry>)
.collect(); .collect();
( (
@@ -799,10 +798,7 @@ async fn create_tray_menu(
tun_mode_available: bool, tun_mode_available: bool,
profiles_preview: Vec<IProfilePreview<'_>>, profiles_preview: Vec<IProfilePreview<'_>>,
options: TrayMenuOptions, options: TrayMenuOptions,
) -> Result<( ) -> Result<(tauri::menu::Menu<Wry>, HashMap<std::string::String, LatencyMenuItem>)> {
tauri::menu::Menu<DynRuntime>,
HashMap<std::string::String, LatencyMenuItem>,
)> {
let current_proxy_mode = mode.unwrap_or(""); let current_proxy_mode = mode.unwrap_or("");
let mut verge_settings = Config::verge().await.latest_arc(); let mut verge_settings = Config::verge().await.latest_arc();
@@ -840,12 +836,12 @@ async fn create_tray_menu(
let hotkeys = create_hotkeys(&verge_settings.hotkeys); let hotkeys = create_hotkeys(&verge_settings.hotkeys);
let profile_menu_items: Vec<CheckMenuItem<DynRuntime>> = create_profile_menu_item(app_handle, profiles_preview)?; let profile_menu_items: Vec<CheckMenuItem<Wry>> = create_profile_menu_item(app_handle, profiles_preview)?;
let texts = MenuTexts::new(); let texts = MenuTexts::new();
let profile_menu_items_refs: Vec<&dyn IsMenuItem<DynRuntime>> = profile_menu_items let profile_menu_items_refs: Vec<&dyn IsMenuItem<Wry>> = profile_menu_items
.iter() .iter()
.map(|item| item as &dyn IsMenuItem<DynRuntime>) .map(|item| item as &dyn IsMenuItem<Wry>)
.collect(); .collect();
let open_window = &MenuItem::with_id( let open_window = &MenuItem::with_id(
@@ -898,9 +894,9 @@ async fn create_tray_menu(
outbound_modes_label.as_str(), outbound_modes_label.as_str(),
true, true,
&[ &[
rule_mode as &dyn IsMenuItem<DynRuntime>, rule_mode as &dyn IsMenuItem<Wry>,
global_mode as &dyn IsMenuItem<DynRuntime>, global_mode as &dyn IsMenuItem<Wry>,
direct_mode as &dyn IsMenuItem<DynRuntime>, direct_mode as &dyn IsMenuItem<Wry>,
], ],
)?) )?)
}; };
@@ -1013,7 +1009,7 @@ async fn create_tray_menu(
&texts.more, &texts.more,
true, true,
&[ &[
copy_env as &dyn IsMenuItem<DynRuntime>, copy_env as &dyn IsMenuItem<Wry>,
close_all_connections, close_all_connections,
restart_clash, restart_clash,
restart_app, restart_app,
@@ -1030,13 +1026,13 @@ async fn create_tray_menu(
let separator = &PredefinedMenuItem::separator(app_handle)?; let separator = &PredefinedMenuItem::separator(app_handle)?;
let mut menu_items: Vec<&dyn IsMenuItem<DynRuntime>> = vec![open_window, separator]; let mut menu_items: Vec<&dyn IsMenuItem<Wry>> = vec![open_window, separator];
if show_outbound_modes_inline { if show_outbound_modes_inline {
menu_items.extend_from_slice(&[ menu_items.extend_from_slice(&[
rule_mode as &dyn IsMenuItem<DynRuntime>, rule_mode as &dyn IsMenuItem<Wry>,
global_mode as &dyn IsMenuItem<DynRuntime>, global_mode as &dyn IsMenuItem<Wry>,
direct_mode as &dyn IsMenuItem<DynRuntime>, direct_mode as &dyn IsMenuItem<Wry>,
]); ]);
} else if let Some(ref outbound_modes) = outbound_modes { } else if let Some(ref outbound_modes) = outbound_modes {
menu_items.push(outbound_modes); menu_items.push(outbound_modes);
@@ -1056,14 +1052,14 @@ async fn create_tray_menu(
menu_items.extend_from_slice(&[ menu_items.extend_from_slice(&[
separator, separator,
system_proxy as &dyn IsMenuItem<DynRuntime>, system_proxy as &dyn IsMenuItem<Wry>,
tun_mode as &dyn IsMenuItem<DynRuntime>, tun_mode as &dyn IsMenuItem<Wry>,
separator, separator,
lightweight_mode as &dyn IsMenuItem<DynRuntime>, lightweight_mode as &dyn IsMenuItem<Wry>,
open_dir as &dyn IsMenuItem<DynRuntime>, open_dir as &dyn IsMenuItem<Wry>,
more as &dyn IsMenuItem<DynRuntime>, more as &dyn IsMenuItem<Wry>,
separator, separator,
quit as &dyn IsMenuItem<DynRuntime>, quit as &dyn IsMenuItem<Wry>,
]); ]);
let menu = tauri::menu::MenuBuilder::new(app_handle).items(&menu_items).build()?; let menu = tauri::menu::MenuBuilder::new(app_handle).items(&menu_items).build()?;
@@ -1164,15 +1160,7 @@ fn on_menu_event(_: &AppHandle, event: MenuEvent) {
logging!(error, Type::Tray, "Failed to close all connections from tray: {err}"); logging!(error, Type::Tray, "Failed to close all connections from tray: {err}");
} }
} }
MenuIds::COPY_ENV => { MenuIds::COPY_ENV => feat::copy_clash_env().await,
if let Err(err) = feat::copy_clash_env().await {
logging!(
error,
Type::Tray,
"Failed to copy proxy environment variables from tray: {err:#}"
);
}
}
MenuIds::CONF_DIR => { MenuIds::CONF_DIR => {
let _ = cmd::open_app_dir().await; let _ = cmd::open_app_dir().await;
} }
+2 -2
View File
@@ -132,7 +132,7 @@ impl TraySpeedController {
let app_handle = handle::Handle::app_handle(); let app_handle = handle::Handle::app_handle();
if let Some(tray) = app_handle.tray_by_id(super::TRAY_ID) { if let Some(tray) = app_handle.tray_by_id(super::TRAY_ID) {
let result = tray.with_inner_blocking(|inner| { let result = tray.with_inner_tray_icon(|inner| {
if let Some(status_item) = inner.ns_status_item() { if let Some(status_item) = inner.ns_status_item() {
tray_speed::clear_speed_attributed_title(&status_item); tray_speed::clear_speed_attributed_title(&status_item);
} }
@@ -167,7 +167,7 @@ impl TraySpeedController {
fn apply_tray_speed(up: u64, down: u64) { fn apply_tray_speed(up: u64, down: u64) {
let app_handle = handle::Handle::app_handle(); let app_handle = handle::Handle::app_handle();
if let Some(tray) = app_handle.tray_by_id(super::TRAY_ID) { if let Some(tray) = app_handle.tray_by_id(super::TRAY_ID) {
let result = tray.with_inner_blocking(move |inner| { let result = tray.with_inner_tray_icon(move |inner| {
if let Some(status_item) = inner.ns_status_item() { if let Some(status_item) = inner.ns_status_item() {
tray_speed::set_speed_attributed_title(&status_item, up, down); tray_speed::set_speed_attributed_title(&status_item, up, down);
} }
+2 -2
View File
@@ -34,7 +34,7 @@ impl SilentUpdater {
} }
} }
#[derive(Serialize, Deserialize, specta::Type)] #[derive(Serialize, Deserialize)]
struct UpdateCacheMeta { struct UpdateCacheMeta {
version: String, version: String,
downloaded_at: String, downloaded_at: String,
@@ -214,7 +214,7 @@ fn nsis_language_id(app_language: &str) -> &'static str {
} }
/// Same wire shape as the updater plugin's JS `DownloadEvent`. /// Same wire shape as the updater plugin's JS `DownloadEvent`.
#[derive(Clone, Serialize, specta::Type)] #[derive(Clone, Serialize)]
#[serde(tag = "event", content = "data")] #[serde(tag = "event", content = "data")]
pub enum DownloadEvent { pub enum DownloadEvent {
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
+5 -11
View File
@@ -51,7 +51,7 @@ pub struct CoreConfigValidator {
is_processing: AtomicBool, is_processing: AtomicBool,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, specta::Type)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub enum ValidationErrorKind { pub enum ValidationErrorKind {
FileMissing, FileMissing,
@@ -94,7 +94,7 @@ impl ValidationErrorKind {
} }
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, specta::Type)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub enum ValidationSkipReason { pub enum ValidationSkipReason {
Exiting, Exiting,
@@ -110,18 +110,12 @@ impl fmt::Display for ValidationSkipReason {
} }
} }
#[derive(Debug, Clone, PartialEq, Eq, Serialize, specta::Type)] #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[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,
} }
+1 -4
View File
@@ -16,13 +16,10 @@ use smartstring::alias::String;
use std::path::PathBuf; use std::path::PathBuf;
use tokio::fs; use tokio::fs;
#[derive(Debug, Serialize, specta::Type)] #[derive(Debug, Serialize)]
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,
} }
+13 -3
View File
@@ -34,10 +34,12 @@ static STAGING_GENERATION: AtomicU64 = AtomicU64::new(0);
/// `.rollback` and `.old` are fixed paths, so two upgrades must not overlap. /// `.rollback` and `.old` are fixed paths, so two upgrades must not overlap.
static UPGRADE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); static UPGRADE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
#[derive(Debug, serde::Serialize, specta::Type)] #[derive(Debug, serde::Serialize)]
pub struct CoreUpgradeReport { pub struct CoreUpgradeReport {
/// False when the managed core was already at the latest version. /// False when the managed core was already at the latest version.
pub upgraded: bool, pub upgraded: bool,
pub from: std::string::String,
pub to: std::string::String,
} }
pub async fn upgrade_core(force: bool) -> Result<CoreUpgradeReport> { pub async fn upgrade_core(force: bool) -> Result<CoreUpgradeReport> {
@@ -60,7 +62,11 @@ pub async fn upgrade_core(force: bool) -> Result<CoreUpgradeReport> {
logging!(debug, Type::Core, "core upgrade: latest version resolved via {proxy:?}"); logging!(debug, Type::Core, "core upgrade: latest version resolved via {proxy:?}");
if !force && installed == latest { if !force && installed == latest {
return Ok(CoreUpgradeReport { upgraded: false }); return Ok(CoreUpgradeReport {
upgraded: false,
from: installed,
to: latest,
});
} }
let package = download_package(proxy, alpha, &latest).await?; let package = download_package(proxy, alpha, &latest).await?;
@@ -144,7 +150,11 @@ pub async fn upgrade_core(force: bool) -> Result<CoreUpgradeReport> {
#[cfg(windows)] #[cfg(windows)]
let _ = std::fs::remove_file(target.with_extension("old")); let _ = std::fs::remove_file(target.with_extension("old"));
Ok(CoreUpgradeReport { upgraded: true }) Ok(CoreUpgradeReport {
upgraded: true,
from: installed,
to: latest,
})
} }
/// Whether this upgrade handed bytes to the Service's approved core directory. /// Whether this upgrade handed bytes to the Service's approved core directory.
+2 -5
View File
@@ -15,14 +15,11 @@ use crate::{
utils::dirs, utils::dirs,
}; };
#[derive(Serialize, specta::Type)] #[derive(Serialize)]
#[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(
+1 -4
View File
@@ -8,13 +8,10 @@ use std::path::{Component, Path, PathBuf};
use tokio::fs; use tokio::fs;
use tokio::io::AsyncWriteExt as _; use tokio::io::AsyncWriteExt as _;
#[derive(Debug, serde::Serialize, serde::Deserialize, specta::Type)] #[derive(Debug, serde::Serialize, serde::Deserialize)]
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,
} }
+6 -6
View File
@@ -11,7 +11,6 @@ use crate::{
window_manager::WindowManager, window_manager::WindowManager,
}, },
}; };
use anyhow::Context as _;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use std::env; use std::env;
use tauri_plugin_clipboard_manager::ClipboardExt as _; use tauri_plugin_clipboard_manager::ClipboardExt as _;
@@ -96,7 +95,7 @@ pub async fn toggle_tun_mode(not_save_file: Option<bool>) -> bool {
} }
} }
pub async fn copy_clash_env() -> anyhow::Result<()> { pub async fn copy_clash_env() {
let env_ip = env::var("CLASH_VERGE_REV_IP").ok(); let env_ip = env::var("CLASH_VERGE_REV_IP").ok();
let verge_cfg = Config::verge().await.latest_arc(); let verge_cfg = Config::verge().await.latest_arc();
let ip = env_ip let ip = env_ip
@@ -134,11 +133,12 @@ pub async fn copy_clash_env() -> anyhow::Result<()> {
} }
"fish" => format!("set -x http_proxy {http_proxy}; set -x https_proxy {http_proxy}"), "fish" => format!("set -x http_proxy {http_proxy}; set -x https_proxy {http_proxy}"),
_ => { _ => {
anyhow::bail!("Invalid environment variable format: {env_type}"); logging!(error, Type::ProxyMode, "copy_clash_env: Invalid env type! {env_type}");
return;
} }
}; };
clipboard if let Err(err) = clipboard.write_text(&export_text) {
.write_text(export_text) logging!(error, Type::ProxyMode, "Failed to write to clipboard: {err}");
.context("Failed to write proxy environment variables to clipboard") }
} }
-234
View File
@@ -1,234 +0,0 @@
use crate::cmd;
pub fn builder() -> tauri_specta::Builder<tauri::DynRuntime> {
tauri_specta::Builder::new()
.types(&platform_types())
.commands(tauri_specta::collect_commands![
tauri_plugin_clash_verge_sysinfo::commands::get_system_info,
tauri_plugin_clash_verge_sysinfo::commands::get_app_uptime,
tauri_plugin_clash_verge_sysinfo::commands::export_diagnostic_info::<tauri::DynRuntime>,
cmd::probe_listener,
cmd::save_proxy_ports,
cmd::get_sys_proxy,
cmd::get_auto_proxy,
cmd::get_embedded_server_port,
cmd::open_app_dir,
cmd::open_logs_dir,
cmd::open_core_dir,
cmd::get_network_interfaces,
cmd::get_system_hostname,
cmd::restart_app,
cmd::install_update,
cmd::cancel_update_download,
cmd::restart_core,
cmd::upgrade_clash_core,
cmd::get_runtime_state,
cmd::get_pending_failures,
cmd::get_sidecar_failure,
cmd::entry_lightweight_mode,
cmd::install_service,
cmd::uninstall_service,
cmd::reinstall_service,
cmd::repair_service,
cmd::continue_with_sidecar,
cmd::sync_runtime_providers,
cmd::get_clash_info,
cmd::patch_clash_config,
cmd::patch_clash_mode,
cmd::get_clash_mode,
cmd::change_clash_core,
cmd::get_runtime_config,
cmd::get_proxy_view,
cmd::get_runtime_yaml,
cmd::get_runtime_logs,
cmd::get_runtime_proxy_chain_config,
cmd::update_proxy_chain_config_in_runtime,
cmd::invoke_uwp_tool,
cmd::copy_clash_env,
cmd::sync_tray_proxy_selection,
cmd::record_selected_node,
cmd::forget_selected_node,
cmd::save_dns_config,
cmd::apply_dns_config,
cmd::set_dns_override,
cmd::take_dns_override_notice,
cmd::take_service_fallback_notice,
cmd::get_core_startup_error,
cmd::take_service_repair_notice,
cmd::take_service_owner_notice,
cmd::take_discarded_keys_notice,
cmd::get_dns_config_content,
cmd::validate_dns_config,
cmd::get_clash_logs,
cmd::get_verge_config,
cmd::patch_verge_config,
cmd::test_delay,
cmd::get_app_dir,
cmd::copy_icon_file,
cmd::download_icon_cache,
cmd::open_devtools,
cmd::exit_app,
cmd::get_network_interfaces_info,
cmd::get_profiles,
cmd::enhance_profiles,
cmd::patch_profiles_config,
cmd::view_profile,
cmd::patch_profile,
cmd::create_profile,
cmd::import_profile,
cmd::reorder_profile,
cmd::update_profile,
cmd::delete_profile,
cmd::read_profile_file,
cmd::save_profile_file,
cmd::get_next_update_time,
cmd::create_local_backup,
cmd::list_local_backup,
cmd::delete_local_backup,
cmd::restore_local_backup,
cmd::import_local_backup,
cmd::export_local_backup,
cmd::create_webdav_backup,
cmd::save_webdav_config,
cmd::list_webdav_backup,
cmd::delete_webdav_backup,
cmd::restore_webdav_backup,
cmd::get_unlock_items,
cmd::check_media_unlock,
cmd::check_media_unlock_item,
])
.error_handling(tauri_specta::ErrorHandlingMode::Throw)
.dangerously_cast_bigints_to_number()
.typ::<crate::core::notify::notification::VergeEventPayloads>()
}
// Tauri transports YAML values as JSON; keep YAML storage out of the IPC type graph.
#[derive(serde::Serialize, serde::Deserialize, specta::Type)]
#[serde(transparent)]
pub struct YamlMapping(#[specta(type = std::collections::HashMap<String, JsonValue>)] pub serde_yaml_ng::Mapping);
#[derive(serde::Serialize, serde::Deserialize, specta::Type)]
#[serde(transparent)]
pub struct YamlValue(#[specta(type = JsonValue)] pub serde_yaml_ng::Value);
#[derive(serde::Serialize, specta::Type)]
pub struct WebDavFile {
pub href: String,
#[specta(type = String)]
pub last_modified: chrono::DateTime<chrono::Utc>,
}
impl From<reqwest_dav::list_cmd::ListFile> for WebDavFile {
fn from(file: reqwest_dav::list_cmd::ListFile) -> Self {
Self {
href: file.href,
last_modified: file.last_modified,
}
}
}
#[derive(serde::Serialize, specta::Type)]
pub struct NetworkInterfaceView {
pub name: String,
pub addr: Vec<InterfaceAddress>,
pub mac_addr: Option<String>,
}
#[derive(serde::Serialize, serde::Deserialize, specta::Type)]
pub enum InterfaceAddress {
V4(IpAddress),
V6(IpAddress),
}
#[derive(serde::Serialize, serde::Deserialize, specta::Type)]
pub struct IpAddress {
pub ip: String,
}
impl From<network_interface::NetworkInterface> for NetworkInterfaceView {
fn from(interface: network_interface::NetworkInterface) -> Self {
Self {
name: interface.name,
addr: interface
.addr
.into_iter()
.map(|address| match address {
network_interface::Addr::V4(address) => InterfaceAddress::V4(IpAddress {
ip: address.ip.to_string(),
}),
network_interface::Addr::V6(address) => InterfaceAddress::V6(IpAddress {
ip: address.ip.to_string(),
}),
})
.collect(),
mac_addr: interface.mac_addr,
}
}
}
#[derive(serde::Serialize, serde::Deserialize, specta::Type)]
pub struct DelayHistory {
pub time: String,
pub delay: u16,
}
fn platform_types() -> specta::Types {
use specta::datatype::{DataType, Fields};
let mut types = specta::Types::default().register::<crate::config::IVerge>();
<PlatformVergeFields as specta::Type>::definition(&mut types);
let platform = types
.into_unsorted_iter()
.find(|ty| ty.name == "PlatformVergeFields")
.and_then(|ty| ty.ty.clone());
let Some(DataType::Struct(platform)) = platform else {
unreachable!()
};
let Fields::Named(platform) = platform.fields else {
unreachable!()
};
types.iter_mut(|ty| {
if ty.name != "IVerge" {
return;
}
let Some(DataType::Struct(config)) = &mut ty.ty else {
return;
};
let Fields::Named(fields) = &mut config.fields else {
return;
};
fields
.fields
.retain(|(name, _)| !platform.fields.iter().any(|(platform_name, _)| name == platform_name));
fields.fields.extend(platform.fields.iter().cloned());
});
types
}
// These fields exist only on some hosts; IPC generation covers every desktop target.
#[derive(serde::Serialize, serde::Deserialize, specta::Type)]
struct PlatformVergeFields {
#[specta(optional)]
tray_icon: Option<String>,
#[specta(optional)]
verge_redir_port: Option<u16>,
#[specta(optional)]
verge_redir_enabled: Option<bool>,
#[specta(optional)]
verge_tproxy_port: Option<u16>,
#[specta(optional)]
verge_tproxy_enabled: Option<bool>,
#[specta(optional)]
enable_tray_speed: Option<bool>,
}
#[derive(serde::Serialize, serde::Deserialize, specta::Type)]
#[serde(untagged)]
pub enum JsonValue {
Null(()),
Bool(bool),
Number(f64),
String(String),
// Specta resolves fields in nested functions, where Self is unavailable.
Array(#[specta(type = Vec<JsonValue>)] Vec<Self>),
Object(#[specta(type = std::collections::HashMap<String, JsonValue>)] std::collections::HashMap<String, Self>),
}
+100 -8
View File
@@ -7,7 +7,6 @@ mod constants;
mod core; mod core;
mod enhance; mod enhance;
mod feat; mod feat;
pub mod ipc;
mod process; mod process;
pub mod utils; pub mod utils;
@@ -27,6 +26,9 @@ use tauri_plugin_deep_link::DeepLinkExt as _;
pub static APP_HANDLE: OnceLock<AppHandle> = OnceLock::new(); pub static APP_HANDLE: OnceLock<AppHandle> = OnceLock::new();
// Re-exported for src/bin/frontend-contract.rs; the wire contract stays owned
// by core::notify.
pub use crate::core::notify::frontend_wire_contract;
/// Application initialization helper functions /// Application initialization helper functions
mod app_init { mod app_init {
use super::*; use super::*;
@@ -40,7 +42,7 @@ mod app_init {
} }
/// Setup plugins for the Tauri builder /// Setup plugins for the Tauri builder
pub fn setup_plugins(builder: tauri::Builder) -> tauri::Builder { pub fn setup_plugins(builder: tauri::Builder<tauri::Wry>) -> tauri::Builder<tauri::Wry> {
#[allow(unused_mut)] #[allow(unused_mut)]
let mut builder = builder let mut builder = builder
.plugin(tauri_plugin_clash_verge_sysinfo::init()) .plugin(tauri_plugin_clash_verge_sysinfo::init())
@@ -124,11 +126,101 @@ mod app_init {
Ok(()) Ok(())
} }
pub fn generate_handlers() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { pub fn generate_handlers() -> impl Fn(tauri::ipc::Invoke<tauri::Wry>) -> bool + Send + Sync + 'static {
{ tauri::generate_handler![
let builder = crate::ipc::builder(); tauri_plugin_clash_verge_sysinfo::commands::get_system_info,
move |invoke| builder.invoke_handler()(invoke) tauri_plugin_clash_verge_sysinfo::commands::get_app_uptime,
} tauri_plugin_clash_verge_sysinfo::commands::export_diagnostic_info,
cmd::probe_listener,
cmd::save_proxy_ports,
cmd::get_sys_proxy,
cmd::get_auto_proxy,
cmd::get_embedded_server_port,
cmd::open_app_dir,
cmd::open_logs_dir,
cmd::open_core_dir,
cmd::get_network_interfaces,
cmd::get_system_hostname,
cmd::restart_app,
cmd::install_update,
cmd::cancel_update_download,
cmd::restart_core,
cmd::upgrade_clash_core,
cmd::get_runtime_state,
cmd::get_pending_failures,
cmd::get_sidecar_failure,
cmd::entry_lightweight_mode,
cmd::install_service,
cmd::uninstall_service,
cmd::reinstall_service,
cmd::repair_service,
cmd::continue_with_sidecar,
cmd::sync_runtime_providers,
cmd::get_clash_info,
cmd::patch_clash_config,
cmd::patch_clash_mode,
cmd::get_clash_mode,
cmd::change_clash_core,
cmd::get_runtime_config,
cmd::get_proxy_view,
cmd::get_runtime_yaml,
cmd::get_runtime_logs,
cmd::get_runtime_proxy_chain_config,
cmd::update_proxy_chain_config_in_runtime,
cmd::invoke_uwp_tool,
cmd::copy_clash_env,
cmd::sync_tray_proxy_selection,
cmd::record_selected_node,
cmd::forget_selected_node,
cmd::save_dns_config,
cmd::apply_dns_config,
cmd::set_dns_override,
cmd::take_dns_override_notice,
cmd::take_service_fallback_notice,
cmd::get_core_startup_error,
cmd::take_service_repair_notice,
cmd::take_service_owner_notice,
cmd::take_discarded_keys_notice,
cmd::get_dns_config_content,
cmd::validate_dns_config,
cmd::get_clash_logs,
cmd::get_verge_config,
cmd::patch_verge_config,
cmd::test_delay,
cmd::get_app_dir,
cmd::copy_icon_file,
cmd::download_icon_cache,
cmd::open_devtools,
cmd::exit_app,
cmd::get_network_interfaces_info,
cmd::get_profiles,
cmd::enhance_profiles,
cmd::patch_profiles_config,
cmd::view_profile,
cmd::patch_profile,
cmd::create_profile,
cmd::import_profile,
cmd::reorder_profile,
cmd::update_profile,
cmd::delete_profile,
cmd::read_profile_file,
cmd::save_profile_file,
cmd::get_next_update_time,
cmd::create_local_backup,
cmd::list_local_backup,
cmd::delete_local_backup,
cmd::restore_local_backup,
cmd::import_local_backup,
cmd::export_local_backup,
cmd::create_webdav_backup,
cmd::save_webdav_config,
cmd::list_webdav_backup,
cmd::delete_webdav_backup,
cmd::restore_webdav_backup,
cmd::get_unlock_items,
cmd::check_media_unlock,
cmd::check_media_unlock_item,
]
} }
} }
@@ -181,7 +273,7 @@ pub fn run() -> std::process::ExitCode {
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
utils::linux::workarounds::apply_wayland_webkit_fix(); utils::linux::workarounds::apply_wayland_webkit_fix();
let builder = app_init::setup_plugins(tauri::Builder::default().runtime(tauri_runtime_wry::Wry::default())) let builder = app_init::setup_plugins(tauri::Builder::default())
.setup(|app| { .setup(|app| {
// Logger may not be ready yet, so mirror setup panics to stderr. // Logger may not be ready yet, so mirror setup panics to stderr.
fn log_setup_panic(stage: &str, panic: Box<dyn std::any::Any + Send>) { fn log_setup_panic(stage: &str, panic: Box<dyn std::any::Any + Send>) {
+11
View File
@@ -1,8 +1,19 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::process::ExitCode; use std::process::ExitCode;
#[cfg(not(all(feature = "perf-harness", target_os = "macos")))]
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
#[cfg(all(feature = "perf-harness", target_os = "macos"))]
#[path = "../../scripts/perf/app.rs"]
mod perf;
#[cfg(all(feature = "perf-harness", target_os = "macos"))]
fn main() -> ExitCode {
perf::run()
}
#[cfg(not(all(feature = "perf-harness", target_os = "macos")))]
fn main() -> ExitCode { fn main() -> ExitCode {
let default_parallelism = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1); let default_parallelism = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
let worker_limit = std::cmp::min(default_parallelism, 8); let worker_limit = std::cmp::min(default_parallelism, 8);
+1 -4
View File
@@ -132,10 +132,7 @@ pub fn take_webview_needs_reload() -> bool {
/// reload visible webviews immediately, and defer a hidden main-window reload until activation. /// reload visible webviews immediately, and defer a hidden main-window reload until activation.
/// Registering this callback replaces Tauri's default automatic reload. /// Registering this callback replaces Tauri's default automatic reload.
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
pub fn on_web_content_process_terminated( pub fn on_web_content_process_terminated(webview: &tauri::Webview) {
webview: &tauri::Webview,
_termination: &tauri::webview::WebContentProcessTermination,
) {
if handle::Handle::global().is_exiting() { if handle::Handle::global().is_exiting() {
return; return;
} }
+9 -9
View File
@@ -4,7 +4,7 @@ use clash_verge_logging::{Type, logging};
use std::pin::Pin; use std::pin::Pin;
use std::sync::LazyLock; use std::sync::LazyLock;
use std::time::Duration; use std::time::Duration;
use tauri::{Manager as _, WebviewWindow}; use tauri::{Manager as _, WebviewWindow, Wry};
#[derive(Debug, Clone, Copy, PartialEq)] #[derive(Debug, Clone, Copy, PartialEq)]
pub enum WindowOperationResult { pub enum WindowOperationResult {
@@ -50,7 +50,7 @@ impl WindowManager {
handle::Handle::global().set_activation_policy_regular(); handle::Handle::global().set_activation_policy_regular();
} }
fn get_main_window_with_state() -> (Option<WebviewWindow>, WindowState) { fn get_main_window_with_state() -> (Option<WebviewWindow<Wry>>, WindowState) {
let Some(window) = Self::get_main_window() else { let Some(window) = Self::get_main_window() else {
return (None, WindowState::NotExist); return (None, WindowState::NotExist);
}; };
@@ -76,7 +76,7 @@ impl WindowManager {
Self::get_main_window_with_state().1 Self::get_main_window_with_state().1
} }
pub fn get_main_window() -> Option<WebviewWindow> { pub fn get_main_window() -> Option<WebviewWindow<Wry>> {
let app_handle = handle::Handle::app_handle(); let app_handle = handle::Handle::app_handle();
app_handle.get_webview_window("main") app_handle.get_webview_window("main")
} }
@@ -147,7 +147,7 @@ impl WindowManager {
} }
} }
fn hide_main_window(window: Option<&WebviewWindow>) -> WindowOperationResult { fn hide_main_window(window: Option<&WebviewWindow<Wry>>) -> WindowOperationResult {
logging!(debug, Type::Window, "窗口可见,将隐藏窗口"); logging!(debug, Type::Window, "窗口可见,将隐藏窗口");
if let Some(window) = window { if let Some(window) = window {
match window.close() { match window.close() {
@@ -166,7 +166,7 @@ impl WindowManager {
} }
} }
fn activate_existing_main_window(window: Option<&WebviewWindow>) -> WindowOperationResult { fn activate_existing_main_window(window: Option<&WebviewWindow<Wry>>) -> WindowOperationResult {
logging!(debug, Type::Window, "窗口存在但被隐藏或最小化,将激活窗口"); logging!(debug, Type::Window, "窗口存在但被隐藏或最小化,将激活窗口");
if let Some(window) = window { if let Some(window) = window {
Self::activate_window(window) Self::activate_window(window)
@@ -176,7 +176,7 @@ impl WindowManager {
} }
} }
fn activate_window(window: &WebviewWindow) -> WindowOperationResult { fn activate_window(window: &WebviewWindow<Wry>) -> WindowOperationResult {
logging!(debug, Type::Window, "开始激活窗口"); logging!(debug, Type::Window, "开始激活窗口");
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
Self::set_macos_activation_policy_regular(); Self::set_macos_activation_policy_regular();
@@ -233,15 +233,15 @@ impl WindowManager {
} }
} }
pub fn is_main_window_visible(window: Option<&WebviewWindow>) -> bool { pub fn is_main_window_visible(window: Option<&WebviewWindow<Wry>>) -> bool {
window.map(|w| w.is_visible().unwrap_or(false)).unwrap_or(false) window.map(|w| w.is_visible().unwrap_or(false)).unwrap_or(false)
} }
pub fn is_main_window_focused(window: Option<&WebviewWindow>) -> bool { pub fn is_main_window_focused(window: Option<&WebviewWindow<Wry>>) -> bool {
window.map(|w| w.is_focused().unwrap_or(false)).unwrap_or(false) window.map(|w| w.is_focused().unwrap_or(false)).unwrap_or(false)
} }
fn is_main_window_minimized(window: Option<&WebviewWindow>) -> bool { fn is_main_window_minimized(window: Option<&WebviewWindow<Wry>>) -> bool {
window.map(|w| w.is_minimized().unwrap_or(false)).unwrap_or(false) window.map(|w| w.is_minimized().unwrap_or(false)).unwrap_or(false)
} }
+1 -1
View File
@@ -1,5 +1,5 @@
{ {
"version": "2.5.9", "version": "2.5.8",
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"bundle": { "bundle": {
"active": true, "active": true,
+4 -4
View File
@@ -423,7 +423,7 @@ interface PersistentProxySelectProps
value: string value: string
selectedName: string selectedName: string
groupName: string groupName: string
fixed?: string | null fixed?: string
selectedDelay: number selectedDelay: number
options: ProxyOption[] options: ProxyOption[]
onChange: (value: string) => void onChange: (value: string) => void
@@ -785,8 +785,8 @@ export const CurrentProxyCard = () => {
// The profile selection is the durable source across core restarts and run modes. // The profile selection is the durable source across core restarts and run modes.
handleSelectChange( handleSelectChange(
selectedGroup.name, selectedGroup.name,
previousProxy!, previousProxy,
selectedGroup.fixed!, selectedGroup.fixed,
)({ )({
target: { value: nextName }, target: { value: nextName },
}) })
@@ -940,7 +940,7 @@ export const CurrentProxyCard = () => {
unsortedProxyOptions, unsortedProxyOptions,
sortType, sortType,
delays.of, delays.of,
defaultLatencyTimeout!, defaultLatencyTimeout,
), ),
[ [
delays, delays,
+25 -9
View File
@@ -56,7 +56,26 @@ const openProfileHome = (url: string) => {
void openExternalUrl(url).catch(showNotice.error) void openExternalUrl(url).catch(showNotice.error)
} }
type ProfileItem = IProfileItem // 使用类型定义,而不是导入
interface ProfileExtra {
upload: number
download: number
total: number
expire: number
}
interface ProfileItem {
uid: string
type?: 'local' | 'remote' | 'merge' | 'script'
name?: string
desc?: string
file?: string
url?: string
updated?: number
extra?: ProfileExtra
home?: string
option?: any
}
interface HomeProfileCardProps { interface HomeProfileCardProps {
current: ProfileItem | null | undefined current: ProfileItem | null | undefined
@@ -279,13 +298,10 @@ export const HomeProfileCard = ({
setUpdating(true) setUpdating(true)
try { try {
await mutate( await mutate(() => updateProfile(current.uid, current.option), {
() => updateProfile(current.uid!, current.option ?? undefined), id: `update-profile:${current.uid}`,
{ errorNotice: false,
id: `update-profile:${current.uid}`, })
errorNotice: false,
},
)
onProfileUpdated?.() onProfileUpdated?.()
// 刷新首页数据 // 刷新首页数据
@@ -329,7 +345,7 @@ export const HomeProfileCard = ({
flex: 1, flex: 1,
}, },
}} }}
title={current.name!} title={current.name}
> >
<span>{current.name}</span> <span>{current.name}</span>
<LaunchOutlined <LaunchOutlined
+1 -1
View File
@@ -201,7 +201,7 @@ export const ProxyTunCard: FC = () => {
onClick={() => handleTabChange('tun')} onClick={() => handleTabChange('tun')}
icon={TroubleshootRounded} icon={TroubleshootRounded}
label={t('settings.sections.system.toggles.tunMode')} label={t('settings.sections.system.toggles.tunMode')}
hasIndicator={enable_tun_mode! && isTunModeAvailable} hasIndicator={enable_tun_mode && isTunModeAvailable}
/> />
</Stack> </Stack>
+1 -1
View File
@@ -101,7 +101,7 @@ export const SystemInfoCard = () => {
try { try {
const result = await triggerCheckUpdate() const result = await triggerCheckUpdate()
const info = result.data const info = result.data
if (!info) { if (!info?.available) {
showNotice.success( showNotice.success(
'settings.components.verge.advanced.notifications.latestVersion', 'settings.components.verge.advanced.notifications.latestVersion',
) )
+1 -1
View File
@@ -164,7 +164,7 @@ export const TestCard = () => {
}} }}
> >
{testList.map((item, index) => ( {testList.map((item, index) => (
<SortableItem key={item.uid} id={item.uid!} index={index}> <SortableItem key={item.uid} id={item.uid} index={index}>
<TestItem <TestItem
itemData={item} itemData={item}
onEdit={() => viewerRef.current?.edit(item)} onEdit={() => viewerRef.current?.edit(item)}
+1 -1
View File
@@ -16,7 +16,7 @@ export const UpdateButton = (props: Props) => {
const { updateInfo } = useUpdate() const { updateInfo } = useUpdate()
if (!updateInfo) return null if (!updateInfo?.available) return null
return ( return (
<> <>
+18 -18
View File
@@ -120,7 +120,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
) )
const setLoading = useCallback( const setLoading = useCallback(
(loading: boolean) => { (loading: boolean) => {
setProfileLoading([itemData.uid!], loading) setProfileLoading([itemData.uid], loading)
}, },
[itemData.uid, setProfileLoading], [itemData.uid, setProfileLoading],
) )
@@ -140,7 +140,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
debugLog(`强制刷新定时器任务`) debugLog(`强制刷新定时器任务`)
} }
const nextUpdate = await getNextUpdateTime(itemData.uid!) const nextUpdate = await getNextUpdateTime(itemData.uid)
debugLog(`获取到下次更新时间结果:`, nextUpdate) debugLog(`获取到下次更新时间结果:`, nextUpdate)
if (nextUpdate) { if (nextUpdate) {
@@ -245,7 +245,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const hasHome = !!itemData.home // only subscription url has home page const hasHome = !!itemData.home // only subscription url has home page
const { upload = 0, download = 0, total = 0 } = extra ?? {} const { upload = 0, download = 0, total = 0 } = extra ?? {}
const from = parseUrl(itemData.url!) const from = parseUrl(itemData.url)
const description = itemData.desc const description = itemData.desc
const expire = parseExpire(extra?.expire) const expire = parseExpire(extra?.expire)
const progress = Math.min( const progress = Math.min(
@@ -253,7 +253,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
100, 100,
) )
const loading = loadingCache.has(itemData.uid!) const loading = loadingCache.has(itemData.uid)
const [, forceRefresh] = useReducer((value: number) => value + 1, 0) const [, forceRefresh] = useReducer((value: number) => value + 1, 0)
useEffect(() => { useEffect(() => {
@@ -263,7 +263,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const handler = () => { const handler = () => {
const now = Date.now() const now = Date.now()
const lastUpdate = updated! * 1000 const lastUpdate = updated * 1000
if (now - lastUpdate >= 24 * 36e5) return if (now - lastUpdate >= 24 * 36e5) return
const wait = now - lastUpdate >= 36e5 ? 30e5 : 5e4 const wait = now - lastUpdate >= 36e5 ? 30e5 : 5e4
@@ -293,7 +293,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const [confirmOpen, setConfirmOpen] = useState(false) const [confirmOpen, setConfirmOpen] = useState(false)
const [qrOpen, setQrOpen] = useState(false) const [qrOpen, setQrOpen] = useState(false)
const loadProfileDocument = useCallback(() => readProfileFile(uid!), [uid]) const loadProfileDocument = useCallback(() => readProfileFile(uid), [uid])
const loadMergeDocument = useCallback( const loadMergeDocument = useCallback(
() => readProfileFile(option?.merge ?? ''), () => readProfileFile(option?.merge ?? ''),
[option?.merge], [option?.merge],
@@ -370,7 +370,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const onOpenFile = useLockFn(async () => { const onOpenFile = useLockFn(async () => {
setAnchorEl(null) setAnchorEl(null)
try { try {
await mutate(() => viewProfile(itemData.uid!), { await mutate(() => viewProfile(itemData.uid), {
id: 'view-profile', id: 'view-profile',
errorNotice: false, errorNotice: false,
}) })
@@ -402,7 +402,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
try { try {
const payload = Object.keys(option).length > 0 ? option : undefined const payload = Object.keys(option).length > 0 ? option : undefined
await mutate(() => updateProfile(itemData.uid!, payload), { await mutate(() => updateProfile(itemData.uid, payload), {
id: `update-profile:${itemData.uid}`, id: `update-profile:${itemData.uid}`,
errorNotice: false, errorNotice: false,
}) })
@@ -593,7 +593,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const handleSaveProfileDocument = useLockFn(async () => { const handleSaveProfileDocument = useLockFn(async () => {
const currentValue = profileDocument.value const currentValue = profileDocument.value
const result = await mutate(() => saveProfileFile(uid!, currentValue), { const result = await mutate(() => saveProfileFile(uid, currentValue), {
id: `save-profile-file:${uid}`, id: `save-profile-file:${uid}`,
errorNotice: false, errorNotice: false,
}) })
@@ -728,7 +728,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
variant="h6" variant="h6"
component="h2" component="h2"
noWrap noWrap
title={name!} title={name}
> >
{name} {name}
</Typography> </Typography>
@@ -794,7 +794,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
title={ title={
showNextUpdate showNextUpdate
? t('profiles.components.profileItem.tooltips.showLast') ? t('profiles.components.profileItem.tooltips.showLast')
: `${t('shared.labels.updateTime')}: ${parseExpire(updated!)}\n${t('profiles.components.profileItem.tooltips.showNext')}` : `${t('shared.labels.updateTime')}: ${parseExpire(updated)}\n${t('profiles.components.profileItem.tooltips.showNext')}`
} }
sx={{ sx={{
fontSize: 14, fontSize: 14,
@@ -812,8 +812,8 @@ const ProfileItemBase = (props: ProfileItemProps) => {
> >
{showNextUpdate {showNextUpdate
? nextUpdateTime ? nextUpdateTime
: updated! > 0 : updated > 0
? dayjs(updated! * 1000).fromNow() ? dayjs(updated * 1000).fromNow()
: ''} : ''}
</Typography> </Typography>
</Box> </Box>
@@ -831,7 +831,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
) : ( ) : (
<Box sx={{ ...boxStyle, fontSize: 12, justifyContent: 'flex-end' }}> <Box sx={{ ...boxStyle, fontSize: 12, justifyContent: 'flex-end' }}>
<span title={t('shared.labels.updateTime')}> <span title={t('shared.labels.updateTime')}>
{parseExpire(updated!)} {parseExpire(updated)}
</span> </span>
</Box> </Box>
)} )}
@@ -896,7 +896,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
<RulesEditorViewer <RulesEditorViewer
groupsUid={option?.groups ?? ''} groupsUid={option?.groups ?? ''}
mergeUid={option?.merge ?? ''} mergeUid={option?.merge ?? ''}
profileUid={uid!} profileUid={uid}
property={option?.rules ?? ''} property={option?.rules ?? ''}
open={true} open={true}
onSave={onSave} onSave={onSave}
@@ -905,7 +905,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
)} )}
{proxiesOpen && ( {proxiesOpen && (
<ProxiesEditorViewer <ProxiesEditorViewer
profileUid={uid!} profileUid={uid}
property={option?.proxies ?? ''} property={option?.proxies ?? ''}
open={true} open={true}
onSave={onSave} onSave={onSave}
@@ -916,7 +916,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
<GroupsEditorViewer <GroupsEditorViewer
mergeUid={option?.merge ?? ''} mergeUid={option?.merge ?? ''}
proxiesUid={option?.proxies ?? ''} proxiesUid={option?.proxies ?? ''}
profileUid={uid!} profileUid={uid}
property={option?.groups ?? ''} property={option?.groups ?? ''}
open={true} open={true}
onSave={onSave} onSave={onSave}
@@ -976,7 +976,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
{qrOpen && itemData.url && ( {qrOpen && itemData.url && (
<QrViewer <QrViewer
open={true} open={true}
value={`${itemData.url}${itemData.url.includes('?') ? '&' : '?'}name=${encodeURIComponent(name!)}`} value={`${itemData.url}${itemData.url.includes('?') ? '&' : '?'}name=${encodeURIComponent(name)}`}
onClose={() => setQrOpen(false)} onClose={() => setQrOpen(false)}
/> />
)} )}
+8 -14
View File
@@ -115,13 +115,7 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
} }
const name = form.name || `${form.type} file` const name = form.name || `${form.type} file`
const item = { const item = { ...form, name, option }
type: form.type,
name,
desc: form.desc,
option,
...(form.type === 'remote' ? { url: form.url } : {}),
}
const isRemote = form.type === 'remote' const isRemote = form.type === 'remote'
const isUpdate = openType === 'edit' const isUpdate = openType === 'edit'
@@ -145,7 +139,7 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
t('profiles.modals.profileForm.errors.uidMissing'), t('profiles.modals.profileForm.errors.uidMissing'),
) )
} }
await mutate(() => patchProfile(form.uid!, item), { await mutate(() => patchProfile(form.uid, item), {
id: 'patch-profile', id: 'patch-profile',
errorNotice: false, errorNotice: false,
}) })
@@ -163,7 +157,7 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
t('profiles.modals.profileForm.errors.uidMissing'), t('profiles.modals.profileForm.errors.uidMissing'),
) )
} }
await mutate(() => patchProfile(form.uid!, item), { await mutate(() => patchProfile(form.uid, item), {
id: 'patch-profile', id: 'patch-profile',
errorNotice: false, errorNotice: false,
}) })
@@ -196,13 +190,13 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
t('profiles.modals.profileForm.errors.uidMissing'), t('profiles.modals.profileForm.errors.uidMissing'),
) )
} }
await mutate(() => patchProfile(form.uid!, retryItem), { await mutate(() => patchProfile(form.uid, retryItem), {
id: 'patch-profile', id: 'patch-profile',
errorNotice: false, errorNotice: false,
}) })
await mutate( await mutate(
() => patchProfile(form.uid!, { option: originalOptions }), () => patchProfile(form.uid, { option: originalOptions }),
{ {
id: 'patch-profile', id: 'patch-profile',
errorNotice: false, errorNotice: false,
@@ -419,7 +413,7 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
<InputLabel> <InputLabel>
{t('profiles.modals.profileForm.fields.useSystemProxy')} {t('profiles.modals.profileForm.fields.useSystemProxy')}
</InputLabel> </InputLabel>
<Switch checked={field.value!} {...field} color="primary" /> <Switch checked={field.value} {...field} color="primary" />
</StyledBox> </StyledBox>
)} )}
/> />
@@ -432,7 +426,7 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
<InputLabel> <InputLabel>
{t('profiles.modals.profileForm.fields.useClashProxy')} {t('profiles.modals.profileForm.fields.useClashProxy')}
</InputLabel> </InputLabel>
<Switch checked={field.value!} {...field} color="primary" /> <Switch checked={field.value} {...field} color="primary" />
</StyledBox> </StyledBox>
)} )}
/> />
@@ -445,7 +439,7 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
<InputLabel> <InputLabel>
{t('profiles.modals.profileForm.fields.acceptInvalidCerts')} {t('profiles.modals.profileForm.fields.acceptInvalidCerts')}
</InputLabel> </InputLabel>
<Switch checked={field.value!} {...field} color="primary" /> <Switch checked={field.value} {...field} color="primary" />
</StyledBox> </StyledBox>
)} )}
/> />
@@ -684,9 +684,6 @@ export const RulesEditorViewer = (props: Props) => {
ruleType.name !== 'SUB-RULE' && ( ruleType.name !== 'SUB-RULE' && (
<TextField <TextField
autoComplete="new-password" autoComplete="new-password"
autoCorrect="off"
autoCapitalize="off"
spellCheck="false"
size="small" size="small"
sx={{ minWidth: '240px' }} sx={{ minWidth: '240px' }}
slotProps={{ slotProps={{
+19 -28
View File
@@ -445,14 +445,10 @@ export const ProxyChain = ({
if (isConnected) { if (isConnected) {
setIsConnecting(true) setIsConnecting(true)
try { try {
const result = await mutate( await mutate(() => updateProxyChainConfigInRuntime(null), {
() => updateProxyChainConfigInRuntime(null), id: 'update-proxy-chain-runtime',
{ errorNotice: false,
id: 'update-proxy-chain-runtime', })
errorNotice: false,
},
)
if (!result.ok) return
const targetGroup = const targetGroup =
mode === 'global' mode === 'global'
@@ -465,7 +461,7 @@ export const ProxyChain = ({
id: `select-proxy-node:${targetGroup}`, id: `select-proxy-node:${targetGroup}`,
errorNotice: false, errorNotice: false,
}) })
await recordSelection(targetGroup, 'DIRECT') recordSelection(targetGroup, 'DIRECT')
} catch { } catch {
if (currentProxyChain.length >= 1) { if (currentProxyChain.length >= 1) {
try { try {
@@ -477,7 +473,7 @@ export const ProxyChain = ({
errorNotice: false, errorNotice: false,
}, },
) )
await recordSelection(targetGroup, currentProxyChain[0].name) recordSelection(targetGroup, currentProxyChain[0].name)
} catch { } catch {
// ignore // ignore
} }
@@ -523,14 +519,10 @@ export const ProxyChain = ({
// 第一步:保存链式代理配置 // 第一步:保存链式代理配置
const chainProxies = currentProxyChain.map((node) => node.name) const chainProxies = currentProxyChain.map((node) => node.name)
debugLog('Saving chain config:', chainProxies) debugLog('Saving chain config:', chainProxies)
const result = await mutate( await mutate(() => updateProxyChainConfigInRuntime(chainProxies), {
() => updateProxyChainConfigInRuntime(chainProxies), id: 'update-proxy-chain-runtime',
{ errorNotice: false,
id: 'update-proxy-chain-runtime', })
errorNotice: false,
},
)
if (!result.ok) return
debugLog('Chain configuration saved successfully') debugLog('Chain configuration saved successfully')
// 第二步:连接到代理链的最后一个节点 // 第二步:连接到代理链的最后一个节点
@@ -553,12 +545,12 @@ export const ProxyChain = ({
) )
// The chain moves the group like any other selection, so the profile has to learn about // The chain moves the group like any other selection, so the profile has to learn about
// it: what the profile holds is what gets re-applied the next time the core starts. // it: what the profile holds is what gets re-applied the next time the core starts.
await recordSelection(targetGroup || 'GLOBAL', lastNode.name) recordSelection(targetGroup || 'GLOBAL', lastNode.name)
localStorage.setItem('proxy-chain-group', targetGroup || 'GLOBAL') localStorage.setItem('proxy-chain-group', targetGroup || 'GLOBAL')
localStorage.setItem('proxy-chain-exit-node', lastNode.name) localStorage.setItem('proxy-chain-exit-node', lastNode.name)
// 刷新代理信息以更新连接状态 // 刷新代理信息以更新连接状态
await refreshProxy() refreshProxy()
debugLog('Successfully connected to proxy chain') debugLog('Successfully connected to proxy chain')
} catch (error) { } catch (error) {
console.error('Failed to connect to proxy chain:', error) console.error('Failed to connect to proxy chain:', error)
@@ -627,15 +619,14 @@ export const ProxyChain = ({
<IconButton <IconButton
size="small" size="small"
onClick={() => { onClick={() => {
void mutate(() => updateProxyChainConfigInRuntime(null), { mutate(() => updateProxyChainConfigInRuntime(null), {
id: 'update-proxy-chain-runtime', id: 'update-proxy-chain-runtime',
onFulfilled: () => { errorNotice: false,
localStorage.removeItem('proxy-chain-group') })
localStorage.removeItem('proxy-chain-exit-node') localStorage.removeItem('proxy-chain-group')
localStorage.removeItem('proxy-chain-items') localStorage.removeItem('proxy-chain-exit-node')
onUpdateChain([]) localStorage.removeItem('proxy-chain-items')
}, onUpdateChain([])
}).catch(() => {})
}} }}
sx={{ sx={{
color: theme.palette.error.main, color: theme.palette.error.main,
@@ -5,11 +5,11 @@ export type ProxyEmptyStateReason =
| 'no-proxy-info' | 'no-proxy-info'
type ProfileSummary = { type ProfileSummary = {
current?: string | null current?: string
items?: Array<{ items?: Array<{
uid?: string | null uid?: string
type?: string | null type?: string
}> | null }>
} }
interface ProxyListStateInput { interface ProxyListStateInput {
@@ -20,7 +20,7 @@ interface ProxyListStateInput {
isRunningModePending: boolean isRunningModePending: boolean
} }
const isSubscriptionProfile = (item: { type?: string | null }): boolean => const isSubscriptionProfile = (item: { type?: string }): boolean =>
item.type === 'remote' || item.type === 'local' item.type === 'remote' || item.type === 'local'
/** Decides only pre-render states; the built list owns whether it has renderable content. */ /** Decides only pre-render states; the built list owns whether it has renderable content. */
+8 -14
View File
@@ -400,26 +400,20 @@ export function ProxyGroupsChain(props: ProxyGroupsChainProps) {
setRuleMenuAnchor(null) setRuleMenuAnchor(null)
} }
const handleGroupSelect = async (groupName: string) => { const handleGroupSelect = (groupName: string) => {
onGroupSelect(groupName)
handleGroupMenuClose()
if (mode === 'rule') { if (mode === 'rule') {
try { mutate(() => updateProxyChainConfigInRuntime(null), {
const result = await mutate( id: 'update-proxy-chain-runtime',
() => updateProxyChainConfigInRuntime(null), errorNotice: false,
{ })
id: 'update-proxy-chain-runtime',
},
)
if (!result.ok) return
} catch {
return
}
localStorage.removeItem('proxy-chain-group') localStorage.removeItem('proxy-chain-group')
localStorage.removeItem('proxy-chain-exit-node') localStorage.removeItem('proxy-chain-exit-node')
localStorage.removeItem('proxy-chain-items') localStorage.removeItem('proxy-chain-items')
setProxyChain([]) setProxyChain([])
} }
onGroupSelect(groupName)
handleGroupMenuClose()
} }
const handleCloseDuplicateWarning = useCallback(() => { const handleCloseDuplicateWarning = useCallback(() => {
+2 -2
View File
@@ -198,7 +198,7 @@ export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
{toolsOnLeft && proxyCount} {toolsOnLeft && proxyCount}
<ProxyGroupTools <ProxyGroupTools
side={toolsOnLeft ? 'left' : 'right'} side={toolsOnLeft ? 'left' : 'right'}
url={group.testUrl!} url={group.testUrl}
groupName={group.name} groupName={group.name}
headState={headState!} headState={headState!}
onLocation={() => onLocation(group)} onLocation={() => onLocation(group)}
@@ -247,7 +247,7 @@ export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
return ( return (
<ProxyHead <ProxyHead
sx={{ pl: 2, pr: 3, mt: 0.5, mb: 1 }} sx={{ pl: 2, pr: 3, mt: 0.5, mb: 1 }}
url={group.testUrl!} url={group.testUrl}
groupName={group.name} groupName={group.name}
headState={headState!} headState={headState!}
onLocation={() => onLocation(group)} onLocation={() => onLocation(group)}
@@ -17,6 +17,7 @@ const node = (memberIndex: number, delay: number, name = `${memberIndex}`) =>
history: [{ delay }], history: [{ delay }],
extra: { extra: {
'http://cp.cloudflare.com/generate_204': { 'http://cp.cloudflare.com/generate_204': {
alive: true,
history: [{ time: new Date(0).toISOString(), delay }], history: [{ time: new Date(0).toISOString(), delay }],
}, },
}, },
+7 -7
View File
@@ -110,13 +110,13 @@ const CHAIN_DELAY_GROUP = 'chain-mode'
const virtualGroup = (members: ProxyGroupView['members']): ProxyGroupView => ({ const virtualGroup = (members: ProxyGroupView['members']): ProxyGroupView => ({
name: CHAIN_DELAY_GROUP, name: CHAIN_DELAY_GROUP,
type: 'Selector', type: 'Selector',
alive: true,
udp: false, udp: false,
xudp: false, xudp: false,
tfo: false, tfo: false,
mptcp: false, mptcp: false,
smux: false, smux: false,
history: [], history: [],
extra: {},
members, members,
}) })
@@ -237,7 +237,7 @@ export const useRenderList = (
selected?.name ?? CHAIN_DELAY_GROUP, selected?.name ?? CHAIN_DELAY_GROUP,
'', '',
0, 0,
latencyTimeout!, latencyTimeout,
) )
if (col > 1) { if (col > 1) {
return groupOccurrences(occurrences, col).map((memberCol) => ({ return groupOccurrences(occurrences, col).map((memberCol) => ({
@@ -289,8 +289,8 @@ export const useRenderList = (
key: group.name, key: group.name,
group, group,
headState, headState,
icon: group.icon!, icon: group.icon,
testUrl: group.testUrl!, testUrl: group.testUrl,
}, },
] ]
@@ -300,7 +300,7 @@ export const useRenderList = (
group.name, group.name,
headState.filterText, headState.filterText,
headState.sortType, headState.sortType,
latencyTimeout!, latencyTimeout,
{ {
matchCase: headState.filterMatchCase, matchCase: headState.filterMatchCase,
matchWholeWord: headState.filterMatchWholeWord, matchWholeWord: headState.filterMatchWholeWord,
@@ -337,11 +337,11 @@ export const useRenderList = (
} }
cache.set(group.name, { cache.set(group.name, {
now: group.now!, now: group.now,
members: group.members, members: group.members,
headState, headState,
col, col,
latencyTimeout: latencyTimeout!, latencyTimeout,
delays: groupDelays.get(group.name), delays: groupDelays.get(group.name),
items: ret, items: ret,
}) })
@@ -50,9 +50,9 @@ export const BackupConfigViewer = memo(
const { register, handleSubmit, watch } = useForm<IWebDavConfig>({ const { register, handleSubmit, watch } = useForm<IWebDavConfig>({
defaultValues: { defaultValues: {
url: webdav_url!, url: webdav_url,
username: webdav_username!, username: webdav_username,
password: webdav_password!, password: webdav_password,
}, },
}) })
const url = watch('url') const url = watch('url')
+1 -1
View File
@@ -196,7 +196,7 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
const { verge } = useVerge() const { verge } = useVerge()
const { current: currentProfile } = useProfiles() const { current: currentProfile } = useProfiles()
const dnsEnabled = currentProfile const dnsEnabled = currentProfile
? (verge?.profile_dns_settings?.[currentProfile.uid!]?.enabled ?? ? (verge?.profile_dns_settings?.[currentProfile.uid]?.enabled ??
verge?.enable_dns_settings ?? verge?.enable_dns_settings ??
false) false)
: false : false
@@ -138,7 +138,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
const defaultBypass = () => { const defaultBypass = () => {
if (isWindows) { if (isWindows) {
return 'localhost;127.*;192.168.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;*.local;<local>' return 'localhost;127.*;192.168.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;<local>'
} }
if (systemName === 'linux') { if (systemName === 'linux') {
return 'localhost,127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,::1' return 'localhost,127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,::1'
@@ -438,7 +438,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
<Switch <Switch
edge="end" edge="end"
disabled={!enabled} disabled={!enabled}
checked={value.pac!} checked={value.pac}
onChange={(_, e) => setValue((v) => ({ ...v, pac: e }))} onChange={(_, e) => setValue((v) => ({ ...v, pac: e }))}
/> />
</ListItem> </ListItem>
@@ -455,7 +455,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
<Switch <Switch
edge="end" edge="end"
disabled={!enabled} disabled={!enabled}
checked={value.guard!} checked={value.guard}
onChange={(_, e) => setValue((v) => ({ ...v, guard: e }))} onChange={(_, e) => setValue((v) => ({ ...v, guard: e }))}
sx={{ marginLeft: 'auto' }} sx={{ marginLeft: 'auto' }}
/> />
@@ -1,4 +1,5 @@
import { alpha, Box, Button, LinearProgress } from '@mui/material' import { alpha, Box, Button, LinearProgress } from '@mui/material'
import type { DownloadEvent } from '@tauri-apps/plugin-updater'
import { useLockFn } from 'ahooks' import { useLockFn } from 'ahooks'
import type { Ref } from 'react' import type { Ref } from 'react'
import { import {
@@ -14,7 +15,6 @@ import type { Options as ReactMarkdownOptions } from 'react-markdown'
import { BaseDialog, DialogRef } from '@/components/base' import { BaseDialog, DialogRef } from '@/components/base'
import { useUpdate } from '@/hooks/use-update' import { useUpdate } from '@/hooks/use-update'
import type { DownloadEvent } from '@/services/bindings'
import { import {
cancelUpdateDownload, cancelUpdateDownload,
installUpdate, installUpdate,
+1 -1
View File
@@ -40,7 +40,7 @@ const SettingClash = ({ onError }: Props) => {
const { verge, mutateVerge } = useVerge() const { verge, mutateVerge } = useVerge()
const { current: currentProfile } = useProfiles() const { current: currentProfile } = useProfiles()
const dnsEnabled = currentProfile const dnsEnabled = currentProfile
? (verge?.profile_dns_settings?.[currentProfile.uid!]?.enabled ?? ? (verge?.profile_dns_settings?.[currentProfile.uid]?.enabled ??
verge?.enable_dns_settings ?? verge?.enable_dns_settings ??
false) false)
: false : false
@@ -48,7 +48,7 @@ const SettingVergeAdvanced = ({ onError: _ }: Props) => {
try { try {
const info = await checkUpdate() const info = await checkUpdate()
updateLastCheckTime() updateLastCheckTime()
if (!info) { if (!info?.available) {
showNotice.success( showNotice.success(
'settings.components.verge.advanced.notifications.latestVersion', 'settings.components.verge.advanced.notifications.latestVersion',
) )
+2 -13
View File
@@ -9,7 +9,6 @@ import { useVerge } from '@/hooks/use-verge'
import { navigationItems } from '@/pages/_navigation-meta' import { navigationItems } from '@/pages/_navigation-meta'
import { copyClashEnv } from '@/services/cmds' import { copyClashEnv } from '@/services/cmds'
import { supportedLanguages } from '@/services/i18n' import { supportedLanguages } from '@/services/i18n'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import getSystem from '@/utils/get-system' import getSystem from '@/utils/get-system'
@@ -76,18 +75,8 @@ const SettingVergeBasic = ({ onError }: Props) => {
} }
const onCopyClashEnv = useCallback(async () => { const onCopyClashEnv = useCallback(async () => {
try { await copyClashEnv()
await mutate(copyClashEnv, { showNotice.success('shared.feedback.notifications.common.copySuccess', 1000)
id: 'copy-clash-env',
onFulfilled: () =>
showNotice.success(
'shared.feedback.notifications.common.copySuccess',
1000,
),
})
} catch {
// The shared mutation boundary reports the failure.
}
}, []) }, [])
return ( return (
+6 -6
View File
@@ -25,11 +25,11 @@ export const TestItem = ({ itemData, onEdit, onDelete: removeTest }: Props) => {
const [position, setPosition] = useState({ left: 0, top: 0 }) const [position, setPosition] = useState({ left: 0, top: 0 })
const [delay, setDelay] = useState(-1) const [delay, setDelay] = useState(-1)
const { uid, name, icon, url } = itemData const { uid, name, icon, url } = itemData
const iconCachePath = useIconCache({ icon: icon!, cacheKey: uid! }) const iconCachePath = useIconCache({ icon, cacheKey: uid })
const onDelay = useCallback(async () => { const onDelay = useCallback(async () => {
setDelay(-2) setDelay(-2)
const result = await cmdTestDelay(url!) const result = await cmdTestDelay(url)
setDelay(result) setDelay(result)
}, [url]) }, [url])
@@ -41,7 +41,7 @@ export const TestItem = ({ itemData, onEdit, onDelete: removeTest }: Props) => {
const onDelete = useLockFn(async () => { const onDelete = useLockFn(async () => {
setAnchorEl(null) setAnchorEl(null)
try { try {
removeTest(uid!) removeTest(uid)
} catch (err: any) { } catch (err: any) {
showNotice.error(err) showNotice.error(err)
} }
@@ -81,17 +81,17 @@ export const TestItem = ({ itemData, onEdit, onDelete: removeTest }: Props) => {
<Box sx={{ display: 'flex', justifyContent: 'center' }}> <Box sx={{ display: 'flex', justifyContent: 'center' }}>
{icon.trim().startsWith('http') && ( {icon.trim().startsWith('http') && (
<img <img
alt={name!} alt={name}
src={iconCachePath === '' ? icon : iconCachePath} src={iconCachePath === '' ? icon : iconCachePath}
height="40px" height="40px"
/> />
)} )}
{icon.trim().startsWith('data') && ( {icon.trim().startsWith('data') && (
<img alt={name!} src={icon!} height="40px" /> <img alt={name} src={icon} height="40px" />
)} )}
{icon.trim().startsWith('<svg') && ( {icon.trim().startsWith('<svg') && (
<img <img
alt={name!} alt={name}
src={`data:image/svg+xml;charset=utf-8,${encodeURIComponent(icon)}`} src={`data:image/svg+xml;charset=utf-8,${encodeURIComponent(icon)}`}
height="40px" height="40px"
/> />
+1 -8
View File
@@ -7,10 +7,8 @@ import { useTranslation } from 'react-i18next'
import { BaseDialog } from '@/components/base' import { BaseDialog } from '@/components/base'
import { useVerge } from '@/hooks/use-verge' import { useVerge } from '@/hooks/use-verge'
import type { IVergeTestItem_Serialize } from '@/services/bindings'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
interface Props { interface Props {
onChange: (uid: string, patch?: Partial<IVergeTestItem>) => void onChange: (uid: string, patch?: Partial<IVergeTestItem>) => void
} }
@@ -79,12 +77,7 @@ export const TestViewer = forwardRef<TestViewerRef, Props>(
if (openType === 'new') { if (openType === 'new') {
const uid = nanoid() const uid = nanoid()
const item: IVergeTestItem_Serialize = { const item = { ...form, uid }
uid,
name: form.name ?? null,
icon: form.icon ?? null,
url: form.url ?? null,
}
const newList = [...testList, item] const newList = [...testList, item]
await patchVerge({ test_list: newList }) await patchVerge({ test_list: newList })
onChange(uid) onChange(uid)
+2 -3
View File
@@ -1,6 +1,5 @@
import { useCallback, useEffect, useRef } from 'react' import { useCallback, useEffect, useRef } from 'react'
import type { ProfilePatch, ProfileSelection } from '@/services/bindings'
import { getProfiles, patchProfile, patchProfilesConfig } from '@/services/cmds' import { getProfiles, patchProfile, patchProfilesConfig } from '@/services/cmds'
import { mutate } from '@/services/mutate' import { mutate } from '@/services/mutate'
import { migrateProfileTestUrls } from '@/services/proxy-test-url' import { migrateProfileTestUrls } from '@/services/proxy-test-url'
@@ -47,7 +46,7 @@ export const useProfiles = () => {
}, []) }, [])
const patchProfiles = useCallback( const patchProfiles = useCallback(
async (value: ProfileSelection) => { async (value: Partial<IProfilesConfig>) => {
try { try {
const result = await mutate(() => patchProfilesConfig(value), { const result = await mutate(() => patchProfilesConfig(value), {
id: 'patch-profiles-config', id: 'patch-profiles-config',
@@ -78,7 +77,7 @@ export const useProfiles = () => {
) )
const patchCurrent = useCallback( const patchCurrent = useCallback(
async (value: ProfilePatch) => { async (value: Partial<IProfileItem>) => {
if (profiles?.current) { if (profiles?.current) {
const uid = profiles.current const uid = profiles.current
await mutate(() => patchProfile(uid, value), { await mutate(() => patchProfile(uid, value), {

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