From 87de9bd5bf2005b0ae893b0f14e7f0d3a19c7097 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:12:16 +0000 Subject: [PATCH 01/33] chore(deps): update github/gh-aw-actions action to v1.4.4 (#8804) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore(deps): update github/gh-aw-actions action to v1.4.4 * chore(gh-aw): update agentic workflows to v1.4.4 - Updates workflow tooling and threat detection - Refreshes generated workflows with the latest compiler, container digests, and GitHub MCP server - Improves detection activation metadata restoration and prepares detection inputs before reporting or artifacts run Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com> --------- Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com> Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com> --- .github/aw/actions-lock.json | 18 ++--- .github/workflows/copilot-setup-steps.yml | 4 +- .github/workflows/pr-ai-slop-review.lock.yml | 63 ++++++++++-------- .github/workflows/pr-verify-fix.lock.yml | 65 ++++++++++--------- .../workflows/renovate-minor-review.lock.yml | 63 ++++++++++-------- 5 files changed, 117 insertions(+), 96 deletions(-) diff --git a/.github/aw/actions-lock.json b/.github/aw/actions-lock.json index 01db1433f..5bd56cb02 100644 --- a/.github/aw/actions-lock.json +++ b/.github/aw/actions-lock.json @@ -5,10 +5,10 @@ "version": "v9.0.0", "sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3" }, - "github/gh-aw-actions/setup@v1.4.2": { + "github/gh-aw-actions/setup@v1.4.4": { "repo": "github/gh-aw-actions/setup", - "version": "v1.4.2", - "sha": "d7852d91d5d1d13e7848771edab8bd1792a08651" + "version": "v1.4.4", + "sha": "6147e7c2fba711fb36ac73c79cba401d1e213c4e" } }, "containers": { @@ -199,13 +199,13 @@ }, "ghcr.io/github/gh-aw-node": { "image": "ghcr.io/github/gh-aw-node", - "digest": "sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc", - "pinned_image": "ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc" + "digest": "sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f", + "pinned_image": "ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f" }, - "ghcr.io/github/github-mcp-server:v2.2.0": { - "image": "ghcr.io/github/github-mcp-server:v2.2.0", - "digest": "sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174", - "pinned_image": "ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174" + "ghcr.io/github/github-mcp-server:v2.3.0": { + "image": "ghcr.io/github/github-mcp-server:v2.3.0", + "digest": "sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6", + "pinned_image": "ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6" } } } diff --git a/.github/workflows/copilot-setup-steps.yml b/.github/workflows/copilot-setup-steps.yml index 183c47ce7..b353f728e 100644 --- a/.github/workflows/copilot-setup-steps.yml +++ b/.github/workflows/copilot-setup-steps.yml @@ -31,9 +31,9 @@ jobs: with: persist-credentials: false - name: Install gh-aw extension - uses: github/gh-aw-actions/setup-cli@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 + uses: github/gh-aw-actions/setup-cli@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 with: - version: v1.4.2 + version: v1.4.4 - name: Install Rust Stable uses: dtolnay/rust-toolchain@stable with: diff --git a/.github/workflows/pr-ai-slop-review.lock.yml b/.github/workflows/pr-ai-slop-review.lock.yml index 416ae4a14..fe8942d3e 100644 --- a/.github/workflows/pr-ai-slop-review.lock.yml +++ b/.github/workflows/pr-ai-slop-review.lock.yml @@ -1,6 +1,6 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"4ca5835c0c9cd01f3432b873f5a177ca6d3d1dbd6a35939e2058dcb37aa224b4","body_hash":"ca82fafbe18061d7c8bd708dc18e91b9116faf0c921a7fa35be1538d47a2b005","compiler_version":"v1.4.2","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}} -# 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":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"d7852d91d5d1d13e7848771edab8bd1792a08651","version":"v1.4.2"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.16","digest":"sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc","pinned_image":"ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc"},{"image":"ghcr.io/github/github-mcp-server:v2.2.0","digest":"sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174","pinned_image":"ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","add_labels","noop","remove_labels","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"14ba41178a91b10b7de6":{"name":"Agentic Workflows"}}} -# This file was automatically generated by gh-aw (v1.4.2). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"4ca5835c0c9cd01f3432b873f5a177ca6d3d1dbd6a35939e2058dcb37aa224b4","body_hash":"ca82fafbe18061d7c8bd708dc18e91b9116faf0c921a7fa35be1538d47a2b005","compiler_version":"v1.4.4","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}} +# 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":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"6147e7c2fba711fb36ac73c79cba401d1e213c4e","version":"v1.4.4"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.16","digest":"sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f","pinned_image":"ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f"},{"image":"ghcr.io/github/github-mcp-server:v2.3.0","digest":"sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6","pinned_image":"ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","add_labels","noop","remove_labels","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"14ba41178a91b10b7de6":{"name":"Agentic Workflows"}}} +# This file was automatically generated by gh-aw (v1.4.4). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md # # ___ _ _ # / _ \ | | (_) @@ -44,12 +44,12 @@ # - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 # - actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 # - actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 -# - github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 +# - github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 # # Container images used: # - ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059 -# - ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc -# - ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174 +# - ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f +# - ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6 # - ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad # - ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca # - ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7 @@ -130,7 +130,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 + uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -152,7 +152,7 @@ jobs: GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }} GH_AW_INFO_VERSION: "1.0.103" GH_AW_INFO_AGENT_VERSION: "1.0.103" - GH_AW_INFO_CLI_VERSION: "v1.4.2" + GH_AW_INFO_CLI_VERSION: "v1.4.4" GH_AW_INFO_WORKFLOW_NAME: "PR AI Slop Review" GH_AW_INFO_WORKFLOW_ID: ${{ job.workflow_ref }} GH_AW_INFO_WORKFLOW_SHA: ${{ job.workflow_sha }} @@ -271,7 +271,7 @@ jobs: if: steps.daily-ai-credits-workflow-guardrail.outputs.daily_ai_credits_guardrail_status != 'quota_blocked' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_COMPILED_VERSION: "v1.4.2" + GH_AW_COMPILED_VERSION: "v1.4.4" GH_AW_HAS_SAFE_OUTPUTS: "true" GH_AW_BLOCKED_VERSION_REPORT_AS_ISSUE: "false" GH_AW_WORKFLOW_NAME: "PR AI Slop Review" @@ -558,7 +558,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 + uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -654,7 +654,7 @@ jobs: 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 && (result.retryAfterMs == null || /\\\\bquota exceeded\\\\b/i.test(result.output))) {',\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 && (result.retryAfterMs == null || /\\\\bquota exceeded\\\\b/i.test(result.output))) {',\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" - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059 ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174 ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7 ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059 ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6 ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7 ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882 - name: Prepare Safe Outputs Directories run: | mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs" @@ -899,12 +899,12 @@ jobs: mkdir -p "$HOME/.copilot" GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node) - cat << GH_AW_MCP_CONFIG_d448207cb151e2cb_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" + cat << GH_AW_MCP_CONFIG_36d6009112b7e687_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" { "mcpServers": { "safeoutputs": { "type": "stdio", - "container": "ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc", + "container": "ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f", "mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"], "args": ["-w", "\${GITHUB_WORKSPACE}"], "entrypoint": "sh", @@ -963,7 +963,7 @@ jobs: } } } - GH_AW_MCP_CONFIG_d448207cb151e2cb_EOF + GH_AW_MCP_CONFIG_36d6009112b7e687_EOF - name: Mount MCP servers as CLIs id: mount-mcp-clis continue-on-error: true @@ -1104,7 +1104,7 @@ jobs: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} GH_AW_TIMEOUT_MINUTES: ${{ fromJSON(vars.GH_AW_DEFAULT_TIMEOUT_MINUTES || '20') }} - GH_AW_VERSION: v1.4.2 + GH_AW_VERSION: v1.4.4 GH_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN || github.token }} GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true @@ -1417,7 +1417,7 @@ jobs: permissions: actions: read # Read workflow runs and artifacts for workflow context. id-token: write # Request an OIDC token for authenticated services. - issues: write # Create or update issues and comments. + issues: write # Enabled by issue reporting, safe outputs, steering, work queues, reaction cleanup, or explicit job permissions. pull-requests: write # Create or update pull requests and review comments. concurrency: group: "gh-aw-conclusion-pr-ai-slop-review-${{ inputs.pr_number }}" @@ -1437,7 +1437,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 + uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1816,7 +1816,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 + uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1830,11 +1830,12 @@ jobs: GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Download activation artifact + id: download-detection-activation continue-on-error: true uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: activation - path: /tmp/gh-aw + path: ${{ runner.temp }}/gh-aw-detection-activation - name: Download agent output artifact id: download-agent-output continue-on-error: true @@ -1855,6 +1856,10 @@ jobs: - name: Clear agent token usage if: always() run: rm -f /tmp/gh-aw/agent_usage.json + - name: Restore activation metadata + if: always() + run: | + bash "${RUNNER_TEMP}/gh-aw/actions/restore_detection_activation_metadata.sh" "${RUNNER_TEMP}/gh-aw-detection-activation" "/tmp/gh-aw" - name: Checkout repository for patch context if: needs.agent.outputs.has_patch == 'true' uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -1903,8 +1908,10 @@ jobs: - name: Prepare threat detection files id: detection_prepare if: always() && steps.detection_guard.outputs.run_detection == 'true' + env: + ACTIVATION_DOWNLOAD_OUTCOME: ${{ steps.download-detection-activation.outcome }} run: | - bash "${RUNNER_TEMP}/gh-aw/actions/prepare_threat_detection_files.sh" + bash "${RUNNER_TEMP}/gh-aw/actions/prepare_detection_inputs.sh" "${RUNNER_TEMP}/gh-aw-detection-activation" "/tmp/gh-aw" - name: Install AWF binary id: detection_awf_install run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.29.22 --rootless @@ -1921,7 +1928,7 @@ jobs: GH_AW_COPILOT_MIN_VERSION: 1.0.35 - name: Execute threat detection with AWF id: detection_agentic_execution - if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_staging_reset.outcome == 'success' && steps.detection_prepare.outcome == 'success' && steps.detection_awf_install.outcome == 'success' + if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.detection_staging_reset.outcome == 'success' && steps.detection_awf_install.outcome == 'success' continue-on-error: true timeout-minutes: 10 env: @@ -1934,11 +1941,11 @@ jobs: GH_AW_LLM_PROVIDER: github GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }} GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} - GH_AW_MODEL_FALLBACK: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }} + GH_AW_MODEL_FALLBACK: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'detection' }} GH_AW_PHASE: detection GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_TIMEOUT_MINUTES: 10 - GH_AW_VERSION: v1.4.2 + GH_AW_VERSION: v1.4.4 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -2046,7 +2053,7 @@ jobs: await main({ additionalDirectories: ["/tmp/gh-aw/threat-detection/sandbox/firewall"], persistDetectionMasks }); - name: Parse threat detection token usage for step summary id: parse_detection_token_usage - if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' + if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' continue-on-error: true uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: @@ -2082,7 +2089,7 @@ jobs: const { persistDetectionMasks } = require(path.join(actionsDir, 'detection_mask_state.cjs')); await main({ additionalDirectories: ["/tmp/gh-aw/threat-detection/sandbox/firewall"], persistDetectionMasks }); - name: Render detection log - if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success' + if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success' continue-on-error: true uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 with: @@ -2094,7 +2101,7 @@ jobs: const { main } = require(path.join(actionsDir, 'render_detection_log.cjs')); await main(); - name: Upload threat detection artifact - if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success' && steps.detection_staging_reset.outcome == 'success' + if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success' && steps.detection_staging_reset.outcome == 'success' uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: detection @@ -2110,7 +2117,7 @@ jobs: retention-days: ${{ vars.GH_AW_DEFAULT_ARTIFACT_RETENTION_DAYS || '0' }} - name: Conclude threat detection id: detection_conclusion - if: always() && steps.detection_guard.outputs.run_detection == 'false' || (always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success') + if: always() && steps.detection_guard.outputs.run_detection == 'false' || (always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success') env: RUN_DETECTION: ${{ steps.detection_guard.outputs.run_detection }} DETECTION_AGENTIC_EXECUTION_OUTCOME: ${{ steps.detection_agentic_execution.outcome }} @@ -2182,7 +2189,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 + uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} diff --git a/.github/workflows/pr-verify-fix.lock.yml b/.github/workflows/pr-verify-fix.lock.yml index 8aa15d0e4..cb5e8a80f 100644 --- a/.github/workflows/pr-verify-fix.lock.yml +++ b/.github/workflows/pr-verify-fix.lock.yml @@ -1,6 +1,6 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"d6b72464a3766dd7d74aefe4c7dd982ae7ae2db951f8040f978feca9166adb39","body_hash":"deddd98c5fa425a91487fb5f50dc59ac61ae395bdcd4dff6543f1e8e563a7d73","compiler_version":"v1.4.2","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}} -# 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":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"d7852d91d5d1d13e7848771edab8bd1792a08651","version":"v1.4.2"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.16","digest":"sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc","pinned_image":"ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc"},{"image":"ghcr.io/github/github-mcp-server:v2.2.0","digest":"sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174","pinned_image":"ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","noop","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"14ba41178a91b10b7de6":{"name":"Agentic Workflows"}}} -# This file was automatically generated by gh-aw (v1.4.2). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"d6b72464a3766dd7d74aefe4c7dd982ae7ae2db951f8040f978feca9166adb39","body_hash":"deddd98c5fa425a91487fb5f50dc59ac61ae395bdcd4dff6543f1e8e563a7d73","compiler_version":"v1.4.4","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}} +# 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":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"6147e7c2fba711fb36ac73c79cba401d1e213c4e","version":"v1.4.4"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.16","digest":"sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f","pinned_image":"ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f"},{"image":"ghcr.io/github/github-mcp-server:v2.3.0","digest":"sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6","pinned_image":"ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","noop","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"14ba41178a91b10b7de6":{"name":"Agentic Workflows"}}} +# This file was automatically generated by gh-aw (v1.4.4). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md # # ___ _ _ # / _ \ | | (_) @@ -43,12 +43,12 @@ # - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 # - actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 # - actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 -# - github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 +# - github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 # # Container images used: # - ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059 -# - ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc -# - ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174 +# - ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f +# - ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6 # - ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad # - ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca # - ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7 @@ -141,7 +141,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 + uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -165,7 +165,7 @@ jobs: GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }} GH_AW_INFO_VERSION: "1.0.103" GH_AW_INFO_AGENT_VERSION: "1.0.103" - GH_AW_INFO_CLI_VERSION: "v1.4.2" + GH_AW_INFO_CLI_VERSION: "v1.4.4" GH_AW_INFO_WORKFLOW_NAME: "Verify Review Fixes" GH_AW_INFO_WORKFLOW_ID: ${{ job.workflow_ref }} GH_AW_INFO_WORKFLOW_SHA: ${{ job.workflow_sha }} @@ -284,7 +284,7 @@ jobs: if: steps.daily-ai-credits-workflow-guardrail.outputs.daily_ai_credits_guardrail_status != 'quota_blocked' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_COMPILED_VERSION: "v1.4.2" + GH_AW_COMPILED_VERSION: "v1.4.4" GH_AW_HAS_SAFE_OUTPUTS: "true" GH_AW_BLOCKED_VERSION_REPORT_AS_ISSUE: "false" GH_AW_WORKFLOW_NAME: "Verify Review Fixes" @@ -596,7 +596,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 + uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -693,7 +693,7 @@ jobs: GH_AW_SKILL_DIR: ".github/skills" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh" - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059 ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174 ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7 ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059 ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6 ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7 ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882 - name: Prepare Safe Outputs Directories run: | mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs" @@ -902,12 +902,12 @@ jobs: mkdir -p "$HOME/.copilot" GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node) - cat << GH_AW_MCP_CONFIG_e9f853f8279889ed_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" + cat << GH_AW_MCP_CONFIG_060492a5ed2a5139_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" { "mcpServers": { "safeoutputs": { "type": "stdio", - "container": "ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc", + "container": "ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f", "mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"], "args": ["-w", "\${GITHUB_WORKSPACE}"], "entrypoint": "sh", @@ -965,7 +965,7 @@ jobs: } } } - GH_AW_MCP_CONFIG_e9f853f8279889ed_EOF + GH_AW_MCP_CONFIG_060492a5ed2a5139_EOF - name: Mount MCP servers as CLIs id: mount-mcp-clis continue-on-error: true @@ -1105,7 +1105,7 @@ jobs: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} GH_AW_TIMEOUT_MINUTES: ${{ fromJSON(vars.GH_AW_DEFAULT_TIMEOUT_MINUTES || '20') }} - GH_AW_VERSION: v1.4.2 + GH_AW_VERSION: v1.4.4 GH_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN || github.token }} GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true @@ -1419,7 +1419,7 @@ jobs: permissions: actions: read # Read workflow runs and artifacts for workflow context. id-token: write # Request an OIDC token for authenticated services. - issues: write # Create or update issues and comments. + issues: write # Enabled by issue reporting, safe outputs, steering, work queues, reaction cleanup, or explicit job permissions. pull-requests: write # Create or update pull requests and review comments. concurrency: group: "gh-aw-conclusion-pr-verify-fix-${{ github.event.issue.number || inputs.pr_number || github.run_id }}" @@ -1439,7 +1439,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 + uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1818,7 +1818,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 + uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1832,11 +1832,12 @@ jobs: GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Download activation artifact + id: download-detection-activation continue-on-error: true uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: activation - path: /tmp/gh-aw + path: ${{ runner.temp }}/gh-aw-detection-activation - name: Download agent output artifact id: download-agent-output continue-on-error: true @@ -1857,6 +1858,10 @@ jobs: - name: Clear agent token usage if: always() run: rm -f /tmp/gh-aw/agent_usage.json + - name: Restore activation metadata + if: always() + run: | + bash "${RUNNER_TEMP}/gh-aw/actions/restore_detection_activation_metadata.sh" "${RUNNER_TEMP}/gh-aw-detection-activation" "/tmp/gh-aw" - name: Checkout repository for patch context if: needs.agent.outputs.has_patch == 'true' uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -1905,8 +1910,10 @@ jobs: - name: Prepare threat detection files id: detection_prepare if: always() && steps.detection_guard.outputs.run_detection == 'true' + env: + ACTIVATION_DOWNLOAD_OUTCOME: ${{ steps.download-detection-activation.outcome }} run: | - bash "${RUNNER_TEMP}/gh-aw/actions/prepare_threat_detection_files.sh" + bash "${RUNNER_TEMP}/gh-aw/actions/prepare_detection_inputs.sh" "${RUNNER_TEMP}/gh-aw-detection-activation" "/tmp/gh-aw" - name: Install AWF binary id: detection_awf_install run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.29.22 --rootless @@ -1923,7 +1930,7 @@ jobs: GH_AW_COPILOT_MIN_VERSION: 1.0.35 - name: Execute threat detection with AWF id: detection_agentic_execution - if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_staging_reset.outcome == 'success' && steps.detection_prepare.outcome == 'success' && steps.detection_awf_install.outcome == 'success' + if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.detection_staging_reset.outcome == 'success' && steps.detection_awf_install.outcome == 'success' continue-on-error: true timeout-minutes: 10 env: @@ -1936,11 +1943,11 @@ jobs: GH_AW_LLM_PROVIDER: github GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }} GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} - GH_AW_MODEL_FALLBACK: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }} + GH_AW_MODEL_FALLBACK: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'detection' }} GH_AW_PHASE: detection GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_TIMEOUT_MINUTES: 10 - GH_AW_VERSION: v1.4.2 + GH_AW_VERSION: v1.4.4 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -2048,7 +2055,7 @@ jobs: await main({ additionalDirectories: ["/tmp/gh-aw/threat-detection/sandbox/firewall"], persistDetectionMasks }); - name: Parse threat detection token usage for step summary id: parse_detection_token_usage - if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' + if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' continue-on-error: true uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: @@ -2084,7 +2091,7 @@ jobs: const { persistDetectionMasks } = require(path.join(actionsDir, 'detection_mask_state.cjs')); await main({ additionalDirectories: ["/tmp/gh-aw/threat-detection/sandbox/firewall"], persistDetectionMasks }); - name: Render detection log - if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success' + if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success' continue-on-error: true uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 with: @@ -2096,7 +2103,7 @@ jobs: const { main } = require(path.join(actionsDir, 'render_detection_log.cjs')); await main(); - name: Upload threat detection artifact - if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success' && steps.detection_staging_reset.outcome == 'success' + if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success' && steps.detection_staging_reset.outcome == 'success' uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: detection @@ -2112,7 +2119,7 @@ jobs: retention-days: ${{ vars.GH_AW_DEFAULT_ARTIFACT_RETENTION_DAYS || '0' }} - name: Conclude threat detection id: detection_conclusion - if: always() && steps.detection_guard.outputs.run_detection == 'false' || (always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success') + if: always() && steps.detection_guard.outputs.run_detection == 'false' || (always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success') env: RUN_DETECTION: ${{ steps.detection_guard.outputs.run_detection }} DETECTION_AGENTIC_EXECUTION_OUTCOME: ${{ steps.detection_agentic_execution.outcome }} @@ -2145,7 +2152,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 + uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -2240,7 +2247,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 + uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} diff --git a/.github/workflows/renovate-minor-review.lock.yml b/.github/workflows/renovate-minor-review.lock.yml index 5080f745e..33c93ce51 100644 --- a/.github/workflows/renovate-minor-review.lock.yml +++ b/.github/workflows/renovate-minor-review.lock.yml @@ -1,6 +1,6 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"e44852fbf56eab99e67b3f6a306f75195603ece6ed130e55652a2467efed1415","body_hash":"7835f25016082d56592b67f4d2bf5b839eb02a6fa8f03d65699ed6bae979c5ad","compiler_version":"v1.4.2","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}} -# 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":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"d7852d91d5d1d13e7848771edab8bd1792a08651","version":"v1.4.2"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.16","digest":"sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc","pinned_image":"ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc"},{"image":"ghcr.io/github/github-mcp-server:v2.2.0","digest":"sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174","pinned_image":"ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","noop","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"14ba41178a91b10b7de6":{"name":"Agentic Workflows"}}} -# This file was automatically generated by gh-aw (v1.4.2). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"e44852fbf56eab99e67b3f6a306f75195603ece6ed130e55652a2467efed1415","body_hash":"7835f25016082d56592b67f4d2bf5b839eb02a6fa8f03d65699ed6bae979c5ad","compiler_version":"v1.4.4","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}} +# 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":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"6147e7c2fba711fb36ac73c79cba401d1e213c4e","version":"v1.4.4"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.16","digest":"sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f","pinned_image":"ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f"},{"image":"ghcr.io/github/github-mcp-server:v2.3.0","digest":"sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6","pinned_image":"ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","noop","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"14ba41178a91b10b7de6":{"name":"Agentic Workflows"}}} +# This file was automatically generated by gh-aw (v1.4.4). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md # # ___ _ _ # / _ \ | | (_) @@ -43,12 +43,12 @@ # - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 # - actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 # - actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 -# - github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 +# - github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 # # Container images used: # - ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059 -# - ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc -# - ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174 +# - ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f +# - ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6 # - ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad # - ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca # - ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7 @@ -133,7 +133,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 + uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -155,7 +155,7 @@ jobs: GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }} GH_AW_INFO_VERSION: "1.0.103" GH_AW_INFO_AGENT_VERSION: "1.0.103" - GH_AW_INFO_CLI_VERSION: "v1.4.2" + GH_AW_INFO_CLI_VERSION: "v1.4.4" GH_AW_INFO_WORKFLOW_NAME: "Renovate Minor Upgrade Analysis" GH_AW_INFO_WORKFLOW_ID: ${{ job.workflow_ref }} GH_AW_INFO_WORKFLOW_SHA: ${{ job.workflow_sha }} @@ -274,7 +274,7 @@ jobs: if: steps.daily-ai-credits-workflow-guardrail.outputs.daily_ai_credits_guardrail_status != 'quota_blocked' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_COMPILED_VERSION: "v1.4.2" + GH_AW_COMPILED_VERSION: "v1.4.4" GH_AW_HAS_SAFE_OUTPUTS: "true" GH_AW_BLOCKED_VERSION_REPORT_AS_ISSUE: "false" GH_AW_WORKFLOW_NAME: "Renovate Minor Upgrade Analysis" @@ -562,7 +562,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 + uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -674,7 +674,7 @@ jobs: GH_AW_SKILL_DIR: ".github/skills" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh" - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059 ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174 ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7 ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059 ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6 ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7 ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882 - name: Prepare Safe Outputs Directories run: | mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs" @@ -885,12 +885,12 @@ jobs: mkdir -p "$HOME/.copilot" GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node) - cat << GH_AW_MCP_CONFIG_d448207cb151e2cb_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" + cat << GH_AW_MCP_CONFIG_36d6009112b7e687_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" { "mcpServers": { "safeoutputs": { "type": "stdio", - "container": "ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc", + "container": "ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f", "mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"], "args": ["-w", "\${GITHUB_WORKSPACE}"], "entrypoint": "sh", @@ -949,7 +949,7 @@ jobs: } } } - GH_AW_MCP_CONFIG_d448207cb151e2cb_EOF + GH_AW_MCP_CONFIG_36d6009112b7e687_EOF - name: Mount MCP servers as CLIs id: mount-mcp-clis continue-on-error: true @@ -1094,7 +1094,7 @@ jobs: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} GH_AW_TIMEOUT_MINUTES: ${{ fromJSON(vars.GH_AW_DEFAULT_TIMEOUT_MINUTES || '20') }} - GH_AW_VERSION: v1.4.2 + GH_AW_VERSION: v1.4.4 GH_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN || github.token }} GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true @@ -1413,7 +1413,7 @@ jobs: permissions: actions: read # Read workflow runs and artifacts for workflow context. id-token: write # Request an OIDC token for authenticated services. - issues: write # Create or update issues and comments. + issues: write # Enabled by issue reporting, safe outputs, steering, work queues, reaction cleanup, or explicit job permissions. pull-requests: write # Create or update pull requests and review comments. concurrency: group: "gh-aw-conclusion-renovate-minor-review-${{ inputs.pr_number }}" @@ -1433,7 +1433,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 + uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1812,7 +1812,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 + uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1826,11 +1826,12 @@ jobs: GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Download activation artifact + id: download-detection-activation continue-on-error: true uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: activation - path: /tmp/gh-aw + path: ${{ runner.temp }}/gh-aw-detection-activation - name: Download agent output artifact id: download-agent-output continue-on-error: true @@ -1851,6 +1852,10 @@ jobs: - name: Clear agent token usage if: always() run: rm -f /tmp/gh-aw/agent_usage.json + - name: Restore activation metadata + if: always() + run: | + bash "${RUNNER_TEMP}/gh-aw/actions/restore_detection_activation_metadata.sh" "${RUNNER_TEMP}/gh-aw-detection-activation" "/tmp/gh-aw" - name: Checkout repository for patch context if: needs.agent.outputs.has_patch == 'true' uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -1899,8 +1904,10 @@ jobs: - name: Prepare threat detection files id: detection_prepare if: always() && steps.detection_guard.outputs.run_detection == 'true' + env: + ACTIVATION_DOWNLOAD_OUTCOME: ${{ steps.download-detection-activation.outcome }} run: | - bash "${RUNNER_TEMP}/gh-aw/actions/prepare_threat_detection_files.sh" + bash "${RUNNER_TEMP}/gh-aw/actions/prepare_detection_inputs.sh" "${RUNNER_TEMP}/gh-aw-detection-activation" "/tmp/gh-aw" - name: Install AWF binary id: detection_awf_install run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.29.22 --rootless @@ -1917,7 +1924,7 @@ jobs: GH_AW_COPILOT_MIN_VERSION: 1.0.35 - name: Execute threat detection with AWF id: detection_agentic_execution - if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_staging_reset.outcome == 'success' && steps.detection_prepare.outcome == 'success' && steps.detection_awf_install.outcome == 'success' + if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.detection_staging_reset.outcome == 'success' && steps.detection_awf_install.outcome == 'success' continue-on-error: true timeout-minutes: 10 env: @@ -1930,11 +1937,11 @@ jobs: GH_AW_LLM_PROVIDER: github GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }} GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} - GH_AW_MODEL_FALLBACK: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }} + GH_AW_MODEL_FALLBACK: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'detection' }} GH_AW_PHASE: detection GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_TIMEOUT_MINUTES: 10 - GH_AW_VERSION: v1.4.2 + GH_AW_VERSION: v1.4.4 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -2042,7 +2049,7 @@ jobs: await main({ additionalDirectories: ["/tmp/gh-aw/threat-detection/sandbox/firewall"], persistDetectionMasks }); - name: Parse threat detection token usage for step summary id: parse_detection_token_usage - if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' + if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' continue-on-error: true uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: @@ -2078,7 +2085,7 @@ jobs: const { persistDetectionMasks } = require(path.join(actionsDir, 'detection_mask_state.cjs')); await main({ additionalDirectories: ["/tmp/gh-aw/threat-detection/sandbox/firewall"], persistDetectionMasks }); - name: Render detection log - if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success' + if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success' continue-on-error: true uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 with: @@ -2090,7 +2097,7 @@ jobs: const { main } = require(path.join(actionsDir, 'render_detection_log.cjs')); await main(); - name: Upload threat detection artifact - if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success' && steps.detection_staging_reset.outcome == 'success' + if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success' && steps.detection_staging_reset.outcome == 'success' uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: detection @@ -2106,7 +2113,7 @@ jobs: retention-days: ${{ vars.GH_AW_DEFAULT_ARTIFACT_RETENTION_DAYS || '0' }} - name: Conclude threat detection id: detection_conclusion - if: always() && steps.detection_guard.outputs.run_detection == 'false' || (always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success') + if: always() && steps.detection_guard.outputs.run_detection == 'false' || (always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success') env: RUN_DETECTION: ${{ steps.detection_guard.outputs.run_detection }} DETECTION_AGENTIC_EXECUTION_OUTCOME: ${{ steps.detection_agentic_execution.outcome }} @@ -2178,7 +2185,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2 + uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} From 186ec116fa93ed3fb55f97ffab1e63bb6ff43cd4 Mon Sep 17 00:00:00 2001 From: Tunglies Date: Wed, 2 Dec 2026 01:34:55 +0000 Subject: [PATCH 02/33] refactor(frontend): outfox foxact, foxts, and eslint-plugin-sukka (#8808) * chore(eslint): remove eslint-plugin-sukka * refactor(frontend): remove foxts and inline local utilities * refactor(frontend): remove foxact and replace with local hooks * refactor(proxy): reuse local storage for group preferences --- eslint.config.ts | 3 - package.json | 3 - pnpm-lock.yaml | 80 ---------- .../connection/connection-table.tsx | 48 +++--- src/components/home/ip-info-card.tsx | 38 +++-- .../profile/groups-editor-viewer.tsx | 12 +- src/components/proxy/use-head-state.ts | 107 ++++++------- src/hooks/use-clash-log.ts | 7 +- src/hooks/use-connection-setting.ts | 6 +- src/hooks/use-editor-document.ts | 41 ++--- src/hooks/use-local-storage.ts | 148 ++++++++++++++++++ src/main.tsx | 33 ++-- src/services/api.ts | 140 +++++++++-------- src/services/states.ts | 61 ++++++-- 14 files changed, 409 insertions(+), 318 deletions(-) create mode 100644 src/hooks/use-local-storage.ts diff --git a/eslint.config.ts b/eslint.config.ts index 2f3aa9dc0..0500267ba 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -7,7 +7,6 @@ import pluginImportX from 'eslint-plugin-import-x' import pluginReactCompiler from 'eslint-plugin-react-compiler' import pluginReactHooks from 'eslint-plugin-react-hooks' import pluginReactRefresh from 'eslint-plugin-react-refresh' -import PluginSukka from 'eslint-plugin-sukka' import pluginUnusedImports from 'eslint-plugin-unused-imports' import globals from 'globals' import tseslint from 'typescript-eslint' @@ -112,7 +111,6 @@ export default defineConfig([ 'import-x': pluginImportX, 'react-refresh': pluginReactRefresh, 'unused-imports': pluginUnusedImports, - sukka: PluginSukka, }, extends: [ @@ -182,7 +180,6 @@ export default defineConfig([ '@eslint-react/no-unused-class-component-members': 'error', '@eslint-react/no-unused-state': 'error', '@eslint-react/jsx-no-useless-fragment': 'warn', - 'sukka/react-prefer-destructuring-assignment': 'warn', // TypeScript '@typescript-eslint/no-explicit-any': 'off', diff --git a/package.json b/package.json index a60494afc..1716de387 100644 --- a/package.json +++ b/package.json @@ -57,8 +57,6 @@ "ahooks": "^3.10.0", "cidr-block": "^2.3.0", "dayjs": "1.11.23", - "foxact": "^0.3.12", - "foxts": "^5.9.1", "i18next": "^27.0.0", "js-yaml": "^5.4.2", "lodash-es": "^4.18.1", @@ -107,7 +105,6 @@ "eslint-plugin-react-compiler": "19.1.0-rc.2", "eslint-plugin-react-hooks": "^7.1.1", "eslint-plugin-react-refresh": "^0.5.7", - "eslint-plugin-sukka": "^10.2.0", "eslint-plugin-unused-imports": "^4.4.1", "globals": "^17.12.0", "https-proxy-agent": "^9.1.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 044229d32..8b3224ac5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -248,12 +248,6 @@ importers: dayjs: specifier: 1.11.23 version: 1.11.23 - foxact: - specifier: ^0.3.12 - version: 0.3.12(react-dom@19.3.1(react@19.3.1))(react@19.3.1) - foxts: - specifier: ^5.9.1 - version: 5.9.1 i18next: specifier: ^27.0.0 version: 27.0.1(typescript@6.0.3) @@ -393,9 +387,6 @@ importers: eslint-plugin-react-refresh: specifier: ^0.5.7 version: 0.5.7(eslint@10.16.0(jiti@2.7.0)) - eslint-plugin-sukka: - specifier: ^10.2.0 - version: 10.2.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) eslint-plugin-unused-imports: specifier: ^4.4.1 version: 4.4.1(@typescript-eslint/eslint-plugin@8.74.0(@typescript-eslint/parser@8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0)) @@ -2569,9 +2560,6 @@ packages: resolution: {integrity: sha512-zlnpg0jNcibNrO7GG9IeHH7maWFeCz+Ja1wx/7tZNU5ASSSSZ+/qZciM0/LHCYxSdqv5h2sdbQ/PXYdOuetXvA==} engines: {node: '>=0.10'} - client-only@0.0.1: - resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==} - clsx@2.1.1: resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} engines: {node: '>=6'} @@ -2850,12 +2838,6 @@ packages: eslint: '*' typescript: '*' - eslint-plugin-sukka@10.2.0: - resolution: {integrity: sha512-BbErYY/fymqL7Te5yiDeBGfSF7QMxzZrT4SQpFI2e8ecRun3oYbL5aJm4kzFfeUzNZ/hET8T7pedpaH1fuXXHg==} - peerDependencies: - eslint: '>=9.29.0' - typescript: '*' - eslint-plugin-unused-imports@4.4.1: resolution: {integrity: sha512-oZGYUz1X3sRMGUB+0cZyK2VcvRX5lm/vB56PgNNcU+7ficUCKm66oZWKUubXWnOuPjQ8PvmXtCViXBMONPe7tQ==} peerDependencies: @@ -2929,9 +2911,6 @@ packages: event-emitter@0.3.5: resolution: {integrity: sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==} - event-target-bus@1.1.0: - resolution: {integrity: sha512-24JX34nM0qRcsj7KvtLbVpMcX8ZQYmb0+0a6viaV2GJtVFg5UGyJyDLITkBipJIG0fSscNskI2PxdhTBIMeg8g==} - expect-type@1.4.0: resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} engines: {node: '>=12.0.0'} @@ -2945,10 +2924,6 @@ packages: fast-deep-equal@3.1.3: resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} - fast-fnv1a@1.0.0: - resolution: {integrity: sha512-Y7iaFmz24pNJX+nqXgDuyHYFTfV9XPWJRfqp0hlG0Xuz1vKnelwLwvmKkbvVVvp5WzYWnrovBTLdk2PWkOYzCg==} - engines: {node: ^22.15.0 || ^23.8.0 || >=24.0.0} - fast-json-stable-stringify@2.1.0: resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} @@ -2983,10 +2958,6 @@ packages: flatted@3.4.4: resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} - fnv1a52@1.0.0: - resolution: {integrity: sha512-dUnV6Uok578HuGYTC/EM0LqeXewXBCHsh/kmLkdcqN1zgSy7K3gCIrshPBS5JwW20XSaRv4Vnz7z8lMjOV8jWw==} - engines: {node: '>=18.0.0'} - follow-redirects@1.16.2: resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==} engines: {node: '>=4.0'} @@ -3005,20 +2976,6 @@ packages: engines: {node: ^20.12.0 || >=22} hasBin: true - foxact@0.3.12: - resolution: {integrity: sha512-sXE1plDgAUsKWzqbAMq/+ifRI3TSOnDPmyZGoaniW9AhtZqk3cOEUSC0jC4a4srvLf4PXwtCB+zQczBdxHGSDA==} - peerDependencies: - react: '*' - react-dom: '*' - peerDependenciesMeta: - react: - optional: true - react-dom: - optional: true - - foxts@5.9.1: - resolution: {integrity: sha512-NrIHGlf4LZGTjjGlVi3gmMbtvC4871SFUflu9yb8X91FYppAk+WMiYS6ZlaEgkPqAkgIGNeq+Y5YCL80GL6v8g==} - fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -3833,9 +3790,6 @@ packages: engines: {node: '>=10'} hasBin: true - server-only@0.0.1: - resolution: {integrity: sha512-qepMx2JxAa5jjfzxG79yPPq+8BuFToHd1hm7kI+Z4zAq1ftQiP7HcxMhDDItrbtwVeLg/cY2JnKnrcFkmiswNA==} - shebang-command@2.0.0: resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} engines: {node: '>=8'} @@ -6390,8 +6344,6 @@ snapshots: memoizee: 0.4.17 timers-ext: 0.1.8 - client-only@0.0.1: {} - clsx@2.1.1: {} combined-stream@1.0.8: @@ -6728,16 +6680,6 @@ snapshots: transitivePeerDependencies: - supports-color - eslint-plugin-sukka@10.2.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3): - dependencies: - '@typescript-eslint/types': 8.74.0 - '@typescript-eslint/utils': 8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) - eslint: 10.16.0(jiti@2.7.0) - foxts: 5.9.1 - typescript: 6.0.3 - transitivePeerDependencies: - - supports-color - eslint-plugin-unused-imports@4.4.1(@typescript-eslint/eslint-plugin@8.74.0(@typescript-eslint/parser@8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0)): dependencies: eslint: 10.16.0(jiti@2.7.0) @@ -6835,8 +6777,6 @@ snapshots: d: 1.0.2 es5-ext: 0.10.64 - event-target-bus@1.1.0: {} - expect-type@1.4.0: {} ext@1.7.0: @@ -6847,8 +6787,6 @@ snapshots: fast-deep-equal@3.1.3: {} - fast-fnv1a@1.0.0: {} - fast-json-stable-stringify@2.1.0: {} fast-levenshtein@2.0.6: {} @@ -6880,8 +6818,6 @@ snapshots: flatted@3.4.4: {} - fnv1a52@1.0.0: {} - follow-redirects@1.16.2(debug@4.4.3): optionalDependencies: debug: 4.4.3 @@ -6904,20 +6840,6 @@ snapshots: transitivePeerDependencies: - '@clack/prompts' - foxact@0.3.12(react-dom@19.3.1(react@19.3.1))(react@19.3.1): - dependencies: - client-only: 0.0.1 - event-target-bus: 1.1.0 - server-only: 0.0.1 - optionalDependencies: - react: 19.3.1 - react-dom: 19.3.1(react@19.3.1) - - foxts@5.9.1: - dependencies: - fast-fnv1a: 1.0.0 - fnv1a52: 1.0.0 - fsevents@2.3.3: optional: true @@ -7921,8 +7843,6 @@ snapshots: semver@7.8.5: {} - server-only@0.0.1: {} - shebang-command@2.0.0: dependencies: shebang-regex: 3.0.0 diff --git a/src/components/connection/connection-table.tsx b/src/components/connection/connection-table.tsx index 6270a65e1..0a38b0161 100644 --- a/src/components/connection/connection-table.tsx +++ b/src/components/connection/connection-table.tsx @@ -1,5 +1,4 @@ import { useTheme } from '@mui/material/styles' -import { useLocalStorage } from 'foxact/use-local-storage' import { memo, useCallback, @@ -13,6 +12,8 @@ import { } from 'react' import { useTranslation } from 'react-i18next' +import { useLocalStorage } from '@/hooks/use-local-storage' + import { ConnectionColumnManager, type ConnectionColumnOption, @@ -62,6 +63,19 @@ type ColumnField = type ColumnSizingState = Record type VisibilityState = Record +const EMPTY_RECORD = {} +const EMPTY_COLUMN_ORDER: string[] = [] + +const parseColumnVisibility = (value: string): VisibilityState => { + const parsed = JSON.parse(value) + return parsed && typeof parsed === 'object' ? parsed : EMPTY_RECORD +} + +const parseColumnOrder = (value: string): string[] => { + const parsed = JSON.parse(value) + return Array.isArray(parsed) ? parsed : EMPTY_COLUMN_ORDER +} + interface BaseColumn { field: ColumnField headerName: string @@ -368,42 +382,20 @@ export const ConnectionTable = (props: Props) => { const theme = useTheme() const [columnWidths, setColumnWidths] = useLocalStorage( 'connection-table-widths', - {}, + EMPTY_RECORD, ) const [columnVisibilityModel, setColumnVisibilityModel] = useLocalStorage( 'connection-table-visibility', - {}, - { - serializer: JSON.stringify, - deserializer: (value) => { - try { - const parsed = JSON.parse(value) - if (parsed && typeof parsed === 'object') return parsed - } catch (err) { - console.warn('Failed to parse connection-table-visibility', err) - } - return {} - }, - }, + EMPTY_RECORD, + parseColumnVisibility, ) const [columnOrder, setColumnOrder] = useLocalStorage( 'connection-table-order', - [], - { - serializer: JSON.stringify, - deserializer: (value) => { - try { - const parsed = JSON.parse(value) - if (Array.isArray(parsed)) return parsed - } catch (err) { - console.warn('Failed to parse connection-table-order', err) - } - return [] - }, - }, + EMPTY_COLUMN_ORDER, + parseColumnOrder, ) const baseColumns = useMemo(() => { diff --git a/src/components/home/ip-info-card.tsx b/src/components/home/ip-info-card.tsx index 6df77a1fa..e5ce23d51 100644 --- a/src/components/home/ip-info-card.tsx +++ b/src/components/home/ip-info-card.tsx @@ -14,20 +14,18 @@ import { Typography, } from '@mui/material' import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow' -import { useEffect } from 'foxact/use-abortable-effect' -import { useIntersection } from 'foxact/use-intersection' -import { useLocalStorage } from 'foxact/use-local-storage' -import type { XOR } from 'foxts/ts-xor' import { forwardRef, memo, useCallback, + useEffect, useEffectEvent, useMemo, useState, } from 'react' import { useTranslation } from 'react-i18next' +import { useLocalStorage } from '@/hooks/use-local-storage' import { getIpInfo } from '@/services/api' import { useQuery } from '@/services/query-client' import getSystem from '@/utils/get-system' @@ -72,15 +70,14 @@ const getCountryFlag = (countryCode: string | undefined) => { return String.fromCodePoint(...codePoints) } -type CountDownState = XOR< - { - type: 'countdown' - remainingSeconds: number - }, - { - type: 'revalidating' - } -> +type CountDownState = + | { + type: 'countdown' + remainingSeconds: number + } + | { + type: 'revalidating' + } const IPInfoCardContainer = forwardRef( ({ children }, ref) => { @@ -114,10 +111,19 @@ export const IpInfoCard = () => { ) const appWindow = useMemo(() => getCurrentWebviewWindow(), []) + const [hasIntersected, setHasIntersected] = useState(false) // Once intersected, the card stays eligible for refresh until unmount. - const [containerRef, hasIntersected, _resetIntersected] = useIntersection({ - rootMargin: '0px', - }) + const containerRef = useCallback((element: HTMLElement | null) => { + if (!element) return + const observer = new IntersectionObserver((entries) => { + if (entries.some((e) => e.isIntersecting || e.intersectionRatio > 0)) { + setHasIntersected(true) + observer.disconnect() + } + }) + observer.observe(element) + return () => observer.disconnect() + }, []) const [countdown, setCountdown] = useState({ type: 'countdown', diff --git a/src/components/profile/groups-editor-viewer.tsx b/src/components/profile/groups-editor-viewer.tsx index 631162639..dfab5fb1d 100644 --- a/src/components/profile/groups-editor-viewer.tsx +++ b/src/components/profile/groups-editor-viewer.tsx @@ -19,10 +19,6 @@ import { styled, } from '@mui/material' import { useLockFn } from 'ahooks' -import { - cancelIdleCallback, - requestIdleCallback, -} from 'foxact/request-idle-callback' import * as yaml from 'js-yaml' import { startTransition, @@ -350,10 +346,12 @@ export const GroupsEditorViewer = (props: Props) => { } } - const handle = requestIdleCallback(serialize) - return () => { - cancelIdleCallback(handle) + if (typeof window.requestIdleCallback === 'function') { + const handle = window.requestIdleCallback(serialize) + return () => window.cancelIdleCallback(handle) } + const handle = window.setTimeout(serialize, 1) + return () => window.clearTimeout(handle) } }, [prependSeq, appendSeq, deleteSeq]) diff --git a/src/components/proxy/use-head-state.ts b/src/components/proxy/use-head-state.ts index 5d30c5e1c..5a3504246 100644 --- a/src/components/proxy/use-head-state.ts +++ b/src/components/proxy/use-head-state.ts @@ -1,5 +1,6 @@ -import { useCallback, useEffect, useReducer } from 'react' +import { useCallback, useEffect, useState } from 'react' +import { useLocalStorage } from '@/hooks/use-local-storage' import { useProfiles } from '@/hooks/use-profiles' import { ProxySortType } from './use-filter-sort' @@ -16,9 +17,13 @@ export interface HeadState { testUrl: string } -type HeadStateStorage = Record> +type ProfileHeadState = Record +type HeadStateStorage = Record const HEAD_STATE_KEY = 'proxy-head-state' +const EMPTY_STORAGE: HeadStateStorage = {} +const EMPTY_PROFILE: ProfileHeadState = {} + export const DEFAULT_STATE: HeadState = { open: false, showType: true, @@ -31,77 +36,65 @@ export const DEFAULT_STATE: HeadState = { testUrl: '', } -type HeadStateAction = - | { type: 'reset' } - | { type: 'replace'; payload: Record } - | { type: 'update'; groupName: string; patch: Partial } +const parseStorage = (raw: string): HeadStateStorage => { + const value = JSON.parse(raw) as HeadStateStorage | null + return value && typeof value === 'object' && !Array.isArray(value) + ? value + : EMPTY_STORAGE +} -function headStateReducer( - state: Record, - action: HeadStateAction, -): Record { - switch (action.type) { - case 'reset': - return {} - case 'replace': - return action.payload - case 'update': { - const prev = state[action.groupName] || DEFAULT_STATE - return { ...state, [action.groupName]: { ...prev, ...action.patch } } - } - default: - return state - } +const getProfileState = (storage: HeadStateStorage, profile: string) => { + const state = storage[profile] + return state && typeof state === 'object' && !Array.isArray(state) + ? state + : EMPTY_PROFILE } export function useHeadStateNew() { const { profiles } = useProfiles() const current = profiles?.current || '' - const [state, dispatch] = useReducer(headStateReducer, {}) - - useEffect(() => { - try { - const data = JSON.parse( - localStorage.getItem(HEAD_STATE_KEY)!, - ) as HeadStateStorage - - const value = data[current] || {} - - if (value && typeof value === 'object') { - dispatch({ type: 'replace', payload: value }) - } else { - dispatch({ type: 'reset' }) - } - } catch { - dispatch({ type: 'reset' }) - } - }, [current]) + const [storage, setStorage] = useLocalStorage( + HEAD_STATE_KEY, + EMPTY_STORAGE, + parseStorage, + ) + const saved = getProfileState(storage, current) + // The active profile owns its live state even if persistence fails. + const [state, setState] = useState(() => ({ + profile: { id: current, initialGroups: saved }, + groups: saved, + })) + const { profile, groups } = state + if (profile.id !== current) { + setState({ profile: { id: current, initialGroups: saved }, groups: saved }) + } useEffect(() => { + if (groups === profile.initialGroups) return const timer = setTimeout(() => { - try { - const item = localStorage.getItem(HEAD_STATE_KEY) - - let data = (item ? JSON.parse(item) : {}) as HeadStateStorage - - if (!data || typeof data !== 'object') data = {} - - data[current] = state - - localStorage.setItem(HEAD_STATE_KEY, JSON.stringify(data)) - } catch {} + setStorage((previous) => ({ + ...previous, + [profile.id]: groups, + })) }) return () => clearTimeout(timer) - }, [state, current]) + }, [groups, profile, setStorage]) const setHeadState = useCallback( - (groupName: string, obj: Partial) => { - dispatch({ type: 'update', groupName, patch: obj }) + (groupName: string, patch: Partial) => { + setState((previous) => { + if (previous.profile !== profile) return previous + const group = previous.groups[groupName] ?? DEFAULT_STATE + return { + profile, + groups: { ...previous.groups, [groupName]: { ...group, ...patch } }, + } + }) }, - [], + [profile], ) - return [state, setHeadState] as const + return [groups, setHeadState] as const } diff --git a/src/hooks/use-clash-log.ts b/src/hooks/use-clash-log.ts index 1e0349ec3..a118ae23e 100644 --- a/src/hooks/use-clash-log.ts +++ b/src/hooks/use-clash-log.ts @@ -1,4 +1,4 @@ -import { useLocalStorage } from 'foxact/use-local-storage' +import { useLocalStorage } from './use-local-storage' const defaultClashLog: IClashLog = { enable: true, @@ -8,7 +8,4 @@ const defaultClashLog: IClashLog = { } export const useClashLog = () => - useLocalStorage('clash-log', defaultClashLog, { - serializer: JSON.stringify, - deserializer: JSON.parse, - }) + useLocalStorage('clash-log', defaultClashLog) diff --git a/src/hooks/use-connection-setting.ts b/src/hooks/use-connection-setting.ts index 032f9c4a8..49a2c89c9 100644 --- a/src/hooks/use-connection-setting.ts +++ b/src/hooks/use-connection-setting.ts @@ -1,4 +1,4 @@ -import { useLocalStorage } from 'foxact/use-local-storage' +import { useLocalStorage } from './use-local-storage' const defaultConnectionSetting: IConnectionSetting = { layout: 'table' } @@ -6,8 +6,4 @@ export const useConnectionSetting = () => useLocalStorage( 'connections-setting', defaultConnectionSetting, - { - serializer: JSON.stringify, - deserializer: JSON.parse, - }, ) diff --git a/src/hooks/use-editor-document.ts b/src/hooks/use-editor-document.ts index 3e276dc85..1833f14d5 100644 --- a/src/hooks/use-editor-document.ts +++ b/src/hooks/use-editor-document.ts @@ -1,6 +1,5 @@ /* eslint-disable @eslint-react/set-state-in-effect */ -import { useEffect } from 'foxact/use-abortable-effect' -import { useCallback, useState } from 'react' +import { useCallback, useEffect, useState } from 'react' import { showNotice } from '@/services/notice-service' @@ -42,26 +41,28 @@ export const useEditorDocument = ({ open, load }: UseEditorDocumentOptions) => { } }, [applyLoadedValue, load]) - useEffect( - (signal) => { - resetDocumentState() + useEffect(() => { + let cancelled = false + resetDocumentState() - if (!open) return + if (!open) return - load() - .then((nextValue) => { - if (signal.aborted) return - applyLoadedValue(nextValue) - }) - .catch((error) => { - if (!signal.aborted) showNotice.error(error) - }) - .finally(() => { - if (!signal.aborted) setLoading(false) - }) - }, - [applyLoadedValue, load, open, resetDocumentState], - ) + load() + .then((nextValue) => { + if (cancelled) return + applyLoadedValue(nextValue) + }) + .catch((error) => { + if (!cancelled) showNotice.error(error) + }) + .finally(() => { + if (!cancelled) setLoading(false) + }) + + return () => { + cancelled = true + } + }, [applyLoadedValue, load, open, resetDocumentState]) const markSaved = useCallback((nextValue: string) => { setSavedValue(nextValue) diff --git a/src/hooks/use-local-storage.ts b/src/hooks/use-local-storage.ts new file mode 100644 index 000000000..cf871f229 --- /dev/null +++ b/src/hooks/use-local-storage.ts @@ -0,0 +1,148 @@ +import { useCallback, useMemo, useSyncExternalStore } from 'react' + +interface StorageEntry { + listeners: Set<() => void> + raw: string | null + parsedRaw: string | null + parsed: unknown + deserializer?: (value: string) => unknown +} + +const entries = new Map() + +const readRaw = (key: string): string | null => { + try { + return window.localStorage.getItem(key) + } catch (error) { + console.warn(`[useLocalStorage] Failed to read "${key}"`, error) + return null + } +} + +const getRaw = (key: string): string | null => { + const entry = entries.get(key) + return entry ? entry.raw : readRaw(key) +} + +const handleStorageEvent = (event: StorageEvent) => { + if (event.storageArea !== window.localStorage) return + + if (event.key === null) { + entries.forEach((entry) => { + entry.raw = null + entry.parsedRaw = null + entry.parsed = undefined + entry.listeners.forEach((listener) => listener()) + }) + return + } + + const entry = entries.get(event.key) + if (!entry) return + entry.raw = event.newValue + entry.parsedRaw = null + entry.parsed = undefined + entry.listeners.forEach((listener) => listener()) +} + +const subscribeKey = (key: string, listener: () => void) => { + if (entries.size === 0) { + window.addEventListener('storage', handleStorageEvent) + } + + let entry = entries.get(key) + if (!entry) { + entry = { + listeners: new Set(), + raw: readRaw(key), + parsedRaw: null, + parsed: undefined, + } + entries.set(key, entry) + } + entry.listeners.add(listener) + + return () => { + const current = entries.get(key) + if (current) { + current.listeners.delete(listener) + if (current.listeners.size === 0) entries.delete(key) + } + if (entries.size === 0) { + window.removeEventListener('storage', handleStorageEvent) + } + } +} + +const parseRaw = ( + key: string, + raw: string | null, + defaultValue: T, + deserializer: (value: string) => T, +): T => { + if (raw === null) return defaultValue + const entry = entries.get(key) + if (entry && entry.parsedRaw === raw && entry.deserializer === deserializer) { + return entry.parsed as T + } + try { + const value = deserializer(raw) + if (entry) { + entry.parsedRaw = raw + entry.parsed = value + entry.deserializer = deserializer + } + return value + } catch (error) { + console.warn(`[useLocalStorage] Failed to deserialize "${key}"`, error) + return defaultValue + } +} + +export const useLocalStorage = ( + key: string, + defaultValue: T, + deserializer: (value: string) => T = JSON.parse, +): [T, (value: T | ((prev: T) => T)) => void] => { + const subscribe = useCallback( + (listener: () => void) => subscribeKey(key, listener), + [key], + ) + + const raw = useSyncExternalStore(subscribe, () => getRaw(key)) + + const value = useMemo( + () => parseRaw(key, raw, defaultValue, deserializer), + [key, raw, defaultValue, deserializer], + ) + + const setValue = useCallback( + (next: T | ((prev: T) => T)) => { + try { + const entry = entries.get(key) + const currentRaw = entry ? entry.raw : readRaw(key) + const resolved = + typeof next === 'function' + ? (next as (prev: T) => T)( + parseRaw(key, currentRaw, defaultValue, deserializer), + ) + : next + + const serialized = JSON.stringify(resolved) + if (currentRaw === serialized) return + window.localStorage.setItem(key, serialized) + if (entry) { + entry.raw = serialized + entry.parsedRaw = null + entry.parsed = undefined + entry.listeners.forEach((listener) => listener()) + } + } catch (error) { + console.warn(`[useLocalStorage] Failed to write "${key}"`, error) + } + }, + [key, defaultValue, deserializer], + ) + + return [value, setValue] +} diff --git a/src/main.tsx b/src/main.tsx index 5a0f0d76d..baa37d842 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -1,7 +1,6 @@ import './assets/styles/index.scss' import { ResizeObserver } from '@juggle/resize-observer' -import { ComposeContextProvider } from 'foxact/compose-context-provider' import React from 'react' import { createRoot } from 'react-dom/client' import { RouterProvider } from 'react-router' @@ -38,26 +37,24 @@ if (!container) { disableWebViewShortcuts() const initializeApp = (initialThemeMode: 'light' | 'dark') => { - const contexts = [ - , - , - , - ] - const root = createRoot(container) root.render( - - - - - - - - - - - + + + + + + + + + + + + + + + , ) } diff --git a/src/services/api.ts b/src/services/api.ts index 343ab2e61..8098b9c65 100644 --- a/src/services/api.ts +++ b/src/services/api.ts @@ -1,8 +1,5 @@ import { getName, getVersion } from '@tauri-apps/api/app' import { fetch } from '@tauri-apps/plugin-http' -import { asyncRetry } from 'foxts/async-retry' -import { extractErrorMessage } from 'foxts/extract-error-message' -import { once } from 'foxts/once' import i18n from 'i18next' import { getBaseConfig } from 'tauri-plugin-mihomo-api' @@ -10,15 +7,42 @@ import { debugLog } from '@/utils/debug' import { getRuntimeConfig } from './cmds' -const getUserAgentPromise = once(async () => { - try { - const [name, version] = await Promise.all([getName(), getVersion()]) - return `${name}/${version}` - } catch (error) { - console.debug('Failed to build User-Agent, fallback to default', error) - return 'clash-verge-rev' +let userAgentPromise: Promise | null = null +const getUserAgentPromise = () => + (userAgentPromise ??= Promise.all([getName(), getVersion()]) + .then(([name, version]) => `${name}/${version}`) + .catch((error) => { + console.debug('Failed to build User-Agent, fallback to default', error) + return 'clash-verge-rev' + })) + +const extractErrorMessage = (error: unknown): string | null => + error instanceof Error ? `${error.name}: ${error.message}`.trim() : null + +const retryWithBackoff = async ( + fn: (bail: (error: unknown) => never) => Promise, + retries: number, +): Promise => { + let bailed = false + const bail = (error: unknown): never => { + bailed = true + throw error } -}) + + for (let attempt = 0; ; attempt++) { + try { + return await fn(bail) + } catch (error) { + if (bailed || attempt >= retries) throw error + + const delay = Math.min( + Math.round((Math.random() + 1) * 1000 * 2 ** attempt), + 4000, + ) + await new Promise((resolve) => setTimeout(resolve, delay)) + } + } +} // Get current IP and geolocation information (refactored IP detection with service-specific mappings) interface IpInfo { ip: string @@ -249,61 +273,53 @@ export const getIpInfo = async (): Promise< debugLog(`尝试IP检测服务: ${service.url}`) try { - return await asyncRetry( - async (bail) => { - console.debug('Fetching IP information:', service.url) + return await retryWithBackoff(async (bail) => { + console.debug('Fetching IP information:', service.url) - const timeoutController = new AbortController() - const timeoutId = setTimeout(() => { - timeoutController.abort() - }, serviceTimeout) + const timeoutController = new AbortController() + const timeoutId = setTimeout(() => { + timeoutController.abort() + }, serviceTimeout) - try { - const response = await fetch(service.url, { - method: 'GET', - proxy, - signal: timeoutController.signal, - connectTimeout: serviceTimeout, - headers: { - 'User-Agent': userAgent, - }, - }) + try { + const response = await fetch(service.url, { + method: 'GET', + proxy, + signal: timeoutController.signal, + connectTimeout: serviceTimeout, + headers: { + 'User-Agent': userAgent, + }, + }) - if (!response.ok) { - return bail( - new Error( - `IP 检测服务出错,状态码: ${response.status} from ${service.url}`, - ), - ) - } - - let data: any - try { - data = await response.json() - } catch { - return bail(new Error(`无法解析 JSON 响应 from ${service.url}`)) - } - - if (data && data.ip) { - debugLog(`IP检测成功,使用服务: ${service.url}`) - return Object.assign(service.mapping(data), { - // use last fetch success timestamp - lastFetchTs: Date.now(), - }) - } else { - return bail(new Error(`无效的响应格式 from ${service.url}`)) - } - } finally { - clearTimeout(timeoutId) + if (!response.ok) { + return bail( + new Error( + `IP 检测服务出错,状态码: ${response.status} from ${service.url}`, + ), + ) } - }, - { - retries: maxRetries, - minTimeout: 1000, - maxTimeout: 4000, - randomize: true, - }, - ) + + let data: any + try { + data = await response.json() + } catch { + return bail(new Error(`无法解析 JSON 响应 from ${service.url}`)) + } + + if (data && data.ip) { + debugLog(`IP检测成功,使用服务: ${service.url}`) + return Object.assign(service.mapping(data), { + // use last fetch success timestamp + lastFetchTs: Date.now(), + }) + } else { + return bail(new Error(`无效的响应格式 from ${service.url}`)) + } + } finally { + clearTimeout(timeoutId) + } + }, maxRetries) } catch (error) { debugLog(`IP检测服务失败: ${service.url}`, error) lastError = error diff --git a/src/services/states.ts b/src/services/states.ts index b48bcfa3c..049543b69 100644 --- a/src/services/states.ts +++ b/src/services/states.ts @@ -1,18 +1,51 @@ -import { createContextState } from 'foxact/create-context-state' +import { + createContext, + createElement, + use, + useState, + type Dispatch, + type ReactNode, + type SetStateAction, +} from 'react' -const [ThemeModeProvider, useThemeMode, useSetThemeMode] = createContextState< - 'light' | 'dark' ->() +import noop from '@/utils/noop' -// save update state -const [UpdateStateProvider, useUpdateState, useSetUpdateState] = - createContextState(false) +type ThemeMode = 'light' | 'dark' -export { - ThemeModeProvider, - useThemeMode, - useSetThemeMode, - UpdateStateProvider, - useUpdateState, - useSetUpdateState, +const ThemeModeContext = createContext('light') +const SetThemeModeContext = + createContext>>(noop) + +export const ThemeModeProvider = ({ + initialState, + children, +}: { + initialState: ThemeMode + children?: ReactNode +}) => { + const [mode, setMode] = useState(initialState) + return createElement( + ThemeModeContext, + { value: mode }, + createElement(SetThemeModeContext, { value: setMode }, children), + ) } + +export const useThemeMode = () => use(ThemeModeContext) +export const useSetThemeMode = () => use(SetThemeModeContext) + +const UpdateStateContext = createContext(false) +const SetUpdateStateContext = + createContext>>(noop) + +export const UpdateStateProvider = ({ children }: { children?: ReactNode }) => { + const [state, setState] = useState(false) + return createElement( + UpdateStateContext, + { value: state }, + createElement(SetUpdateStateContext, { value: setState }, children), + ) +} + +export const useUpdateState = () => use(UpdateStateContext) +export const useSetUpdateState = () => use(SetUpdateStateContext) From 2943b58ef74c64e4fcc37d96acbaee7ceda9ea51 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:33:16 +0000 Subject: [PATCH 03/33] chore(deps): update dependency terser to v5.51.3 [security] (#8810) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- pnpm-lock.yaml | 225 +++++++++++++------------------------------------ 1 file changed, 58 insertions(+), 167 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8b3224ac5..a985c73b0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -347,10 +347,10 @@ importers: version: 13.15.10 '@vitejs/plugin-legacy': specifier: ^8.2.3 - version: 8.2.3(terser@5.51.2)(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.2)(yaml@2.9.1)) + version: 8.2.3(terser@5.51.3)(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.3)(yaml@2.9.1)) '@vitejs/plugin-react': specifier: ^6.1.1 - version: 6.1.1(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.2)(yaml@2.9.1)) + version: 6.1.1(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.3)(yaml@2.9.1)) adm-zip: specifier: ^0.6.1 version: 0.6.1 @@ -371,13 +371,13 @@ importers: version: 10.16.0(jiti@2.7.0) eslint-import-resolver-typescript: specifier: ^4.4.5 - version: 4.4.5(eslint-plugin-import-x@4.18.1(@typescript-eslint/utils@8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0)))(eslint@10.16.0(jiti@2.7.0)) + version: 4.4.5(eslint-plugin-import-x@4.18.1(@typescript-eslint/utils@8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0)))(eslint@10.16.0(jiti@2.7.0)) eslint-plugin-es-x: specifier: ^10.0.1 version: 10.0.1(eslint@10.16.0(jiti@2.7.0)) eslint-plugin-import-x: specifier: ^4.18.1 - version: 4.18.1(@typescript-eslint/utils@8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0)) + version: 4.18.1(@typescript-eslint/utils@8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0)) eslint-plugin-react-compiler: specifier: 19.1.0-rc.2 version: 19.1.0-rc.2(eslint@10.16.0(jiti@2.7.0)) @@ -416,7 +416,7 @@ importers: version: 8.0.2 terser: specifier: ^5.51.2 - version: 5.51.2 + version: 5.51.3 tsrs: specifier: 0.20.0-ts7.1.0-beta version: 0.20.0-ts7.1.0-beta @@ -428,13 +428,13 @@ importers: version: 8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) vite: specifier: ^8.3.0 - version: 8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.2)(yaml@2.9.1) + version: 8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.3)(yaml@2.9.1) vite-plugin-svgr: specifier: ^5.2.0 - version: 5.2.0(typescript@6.0.3)(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.2)(yaml@2.9.1)) + version: 5.2.0(typescript@6.0.3)(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.3)(yaml@2.9.1)) vitest: specifier: ^5.0.3 - version: 5.1.2(@types/node@26.6.5)(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.2)(yaml@2.9.1)) + version: 5.1.2(@types/node@26.6.5)(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.3)(yaml@2.9.1)) packages: @@ -2153,45 +2153,22 @@ packages: eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 typescript: '>=4.8.4 <6.1.0' - '@typescript-eslint/project-service@8.70.0': - resolution: {integrity: sha512-hFHbTNqhU9G+2eKFXCBVb1tjFT/LceiJ4+HfLO4pTpDI0KHi6iajpcFFkaSQ9gXmCh7n82A0PthaayEdN6mspQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - typescript: '>=4.8.4 <6.1.0' - '@typescript-eslint/project-service@8.74.0': resolution: {integrity: sha512-z/mymuE+JlEeSFIv3Mo70EvgG1Zz74Hl0IDfExfXutARAP834bt+MppTD7mVAwmZO0GdxdOAi0jbTam749eH6g==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} peerDependencies: typescript: '>=4.8.4 <6.1.0' - '@typescript-eslint/scope-manager@8.70.0': - resolution: {integrity: sha512-8nP3Kwh5hlgZ4FicGvmznAmJe8UL4sdU8tLukrPaMuQmDuk4Y8xYfzu/aYZW4xT2JCgc7H/TpDI5cGlxcWJSqQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@typescript-eslint/scope-manager@8.74.0': resolution: {integrity: sha512-kpOdpu4CpWN5U38ox3f727DwWRBtUAVhyUJtqTBYe5gf2wYoxac7PgKP14txrxN7ICVtcjlLdzjqfRgpSnDKvQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@typescript-eslint/tsconfig-utils@8.70.0': - resolution: {integrity: sha512-adnkeeNq9Sq1sUf4+FRVc0KdgYghzsgFpZSQVZVvY0LCuUuN0FnQgyGzCJeC4fW1cdXseBAjU2EOqUIjbNcZUw==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - typescript: '>=4.8.4 <6.1.0' - '@typescript-eslint/tsconfig-utils@8.74.0': resolution: {integrity: sha512-p07wAuaS6BjCYgOSXKJi4YhvTnAf7fiG37e9THcpnYaQEt2QiTTYZWKwUFNgeRiywiMudazhzgddAirZ0GgHtQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} peerDependencies: typescript: '>=4.8.4 <6.1.0' - '@typescript-eslint/type-utils@8.70.0': - resolution: {integrity: sha512-NUMKIhYVaVIVLnRL9CRt+VVcuLgSHUCpXn4/+K8wql+vdInUzvx8BjUO1oJ7cG9shjFJKtF8F8Hh2kCh3/KBVw==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 - typescript: '>=4.8.4 <6.1.0' - '@typescript-eslint/type-utils@8.74.0': resolution: {integrity: sha512-CV3Y3la8l3F9ANfxcfpgSSiQgJTe4IeLEoZV4O/gcW86Ugp8X6SKiQ0vm+QegXaRIbbDMokZZSF3A1CgiU/kPw==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -2199,20 +2176,10 @@ packages: eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 typescript: '>=4.8.4 <6.1.0' - '@typescript-eslint/types@8.70.0': - resolution: {integrity: sha512-asTOIYhDg4zdzOScCyaytrsV3cR6B4ecPQlXw/dJIm7J/MZTtCtfVII9JD8Geh4jTCrK/Xe6cg5UevoleMcoJQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@typescript-eslint/types@8.74.0': resolution: {integrity: sha512-MpnMrJCVNpP1iVL8NiHkQZgQqIMBH5ewDGUPBh1pqQXwFtMFjsl1M03QcYPXmv6stCKEiF0PN7CGbU1ZbXFzEA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@typescript-eslint/typescript-estree@8.70.0': - resolution: {integrity: sha512-d9NmHMPEKQ7QCLLm1jI3zmoQBwT5KwFYjXBJ9ymZfKCUU+5rmTRykKAFvH5Qn/ZCds3CEAFS9OC9M/jkl0X2bA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - typescript: '>=4.8.4 <6.1.0' - '@typescript-eslint/typescript-estree@8.74.0': resolution: {integrity: sha512-wL348k6l92DNG+kPP5rVpKwNBoz7a3xRZy3TPKc1uymQttd7u7gcMv3eENmcuh4CjC4mO3FTM0DYstFXMyDLuw==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -2223,13 +2190,6 @@ packages: '@typescript/native': optional: true - '@typescript-eslint/utils@8.70.0': - resolution: {integrity: sha512-oZmtKJz/4fufZ2p3+Cn3ijEojcdfR+1zYDH2xKYrEly0dR/Q/1xUPRCOlKGxod78nWlU2UnDe09GZ3TaknBFGA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 - typescript: '>=4.8.4 <6.1.0' - '@typescript-eslint/utils@8.74.0': resolution: {integrity: sha512-IpWXPxXXomzxyTcvjhZJexgdvtTR1TooLAPpuxzaGqQ8BHll1lf4Ysp/BTE/l0U5TJ+x1j7B4bEM8pLRrvY+XA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -2237,10 +2197,6 @@ packages: eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 typescript: '>=4.8.4 <6.1.0' - '@typescript-eslint/visitor-keys@8.70.0': - resolution: {integrity: sha512-BoC8PiO4Hkdo0TVJh9Ntxr5MxPDI7/oFsrygN5ADelFSeXG/qgNuucIGA+L5Z6JpPTE/uRfcTWtscjbUaufepQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@typescript-eslint/visitor-keys@8.74.0': resolution: {integrity: sha512-XSZmOtMUbWCBIM+2BK134FyMFxmll1mW2mPLk/PSwYQYzGIPMgJAqL929U4qXVizLv7Xq5b7r41/o7Ombuwk0g==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -3325,9 +3281,6 @@ packages: lru-queue@0.1.0: resolution: {integrity: sha512-BpdYkt9EvGl8OfWHDQPISVpcl5xZthb+XPsbELj5AQXxIC8IriDZIQYjBJPEm5rS420sjZ0TLEzRcq5KdBhYrQ==} - magic-string@1.4.1: - resolution: {integrity: sha512-8lyCu36ErXR0J9uaGKlKQoiLZKmtI63YGLE8G2o9jyRPdr4X47LusSOwgOJOzcVtp81fTAAjxR7BwKz682Jhow==} - magic-string@1.4.5: resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==} @@ -3447,10 +3400,6 @@ packages: resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==} engines: {node: '>= 0.6'} - minimatch@10.2.6: - resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==} - engines: {node: 18 || 20 || >=22} - minimatch@11.0.9: resolution: {integrity: sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==} engines: {node: 20 || >=22} @@ -3880,8 +3829,8 @@ packages: resolution: {gitHosted: true, integrity: sha512-4nRJ9eBOdd+mT9KaqEhUNya8bh/zaHHAJMBRgFR62KxSZ0S77mcjkB6Bz2xmHqPdYrhbi58aD6UcybEp4a6UyA==, tarball: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f} version: 0.7.1 - terser@5.51.2: - resolution: {integrity: sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==} + terser@5.51.3: + resolution: {integrity: sha512-j5jPZZ6Sz0Eg2unusKhdRzUhUlHXJ3Bw2AkIXyJ6AqajWwihUlZOdJS+KSnZzmtVk6mFGdm3hHg0+M2sgyEz5Q==} engines: {node: '>=10'} hasBin: true @@ -5104,12 +5053,13 @@ snapshots: '@eslint-react/ast@5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3)': dependencies: '@typescript-eslint/types': 8.74.0 - '@typescript-eslint/typescript-estree': 8.70.0(typescript@6.0.3) - '@typescript-eslint/utils': 8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/typescript-estree': 8.74.0(typescript@6.0.3) + '@typescript-eslint/utils': 8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) eslint: 10.16.0(jiti@2.7.0) string-ts: 2.3.1 typescript: 6.0.3 transitivePeerDependencies: + - '@typescript/native' - supports-color '@eslint-react/core@5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3)': @@ -5120,11 +5070,12 @@ snapshots: '@eslint-react/var': 5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) '@typescript-eslint/scope-manager': 8.74.0 '@typescript-eslint/types': 8.74.0 - '@typescript-eslint/utils': 8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/utils': 8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) eslint: 10.16.0(jiti@2.7.0) ts-pattern: 5.9.0 typescript: 6.0.3 transitivePeerDependencies: + - '@typescript/native' - supports-color '@eslint-react/eslint-plugin@5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3)': @@ -5139,14 +5090,16 @@ snapshots: eslint-plugin-react-x: 5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) typescript: 6.0.3 transitivePeerDependencies: + - '@typescript/native' - supports-color '@eslint-react/eslint@5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3)': dependencies: - '@typescript-eslint/utils': 8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/utils': 8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) eslint: 10.16.0(jiti@2.7.0) typescript: 6.0.3 transitivePeerDependencies: + - '@typescript/native' - supports-color '@eslint-react/jsx@5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3)': @@ -5156,22 +5109,24 @@ snapshots: '@eslint-react/shared': 5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) '@eslint-react/var': 5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) '@typescript-eslint/types': 8.74.0 - '@typescript-eslint/utils': 8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/utils': 8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) eslint: 10.16.0(jiti@2.7.0) ts-pattern: 5.9.0 typescript: 6.0.3 transitivePeerDependencies: + - '@typescript/native' - supports-color '@eslint-react/shared@5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3)': dependencies: '@eslint-react/eslint': 5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) - '@typescript-eslint/utils': 8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/utils': 8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) eslint: 10.16.0(jiti@2.7.0) ts-pattern: 5.9.0 typescript: 6.0.3 zod: 4.6.5 transitivePeerDependencies: + - '@typescript/native' - supports-color '@eslint-react/var@5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3)': @@ -5180,11 +5135,12 @@ snapshots: '@eslint-react/eslint': 5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) '@typescript-eslint/scope-manager': 8.74.0 '@typescript-eslint/types': 8.74.0 - '@typescript-eslint/utils': 8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/utils': 8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) eslint: 10.16.0(jiti@2.7.0) ts-pattern: 5.9.0 typescript: 6.0.3 transitivePeerDependencies: + - '@typescript/native' - supports-color '@eslint/config-array@0.23.7': @@ -5949,15 +5905,6 @@ snapshots: - '@typescript/native' - supports-color - '@typescript-eslint/project-service@8.70.0(typescript@6.0.3)': - dependencies: - '@typescript-eslint/tsconfig-utils': 8.70.0(typescript@6.0.3) - '@typescript-eslint/types': 8.74.0 - debug: 4.4.3 - typescript: 6.0.3 - transitivePeerDependencies: - - supports-color - '@typescript-eslint/project-service@8.74.0(typescript@6.0.3)': dependencies: '@typescript-eslint/tsconfig-utils': 8.74.0(typescript@6.0.3) @@ -5967,36 +5914,15 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/scope-manager@8.70.0': - dependencies: - '@typescript-eslint/types': 8.70.0 - '@typescript-eslint/visitor-keys': 8.70.0 - '@typescript-eslint/scope-manager@8.74.0': dependencies: '@typescript-eslint/types': 8.74.0 '@typescript-eslint/visitor-keys': 8.74.0 - '@typescript-eslint/tsconfig-utils@8.70.0(typescript@6.0.3)': - dependencies: - typescript: 6.0.3 - '@typescript-eslint/tsconfig-utils@8.74.0(typescript@6.0.3)': dependencies: typescript: 6.0.3 - '@typescript-eslint/type-utils@8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3)': - dependencies: - '@typescript-eslint/types': 8.70.0 - '@typescript-eslint/typescript-estree': 8.70.0(typescript@6.0.3) - '@typescript-eslint/utils': 8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) - debug: 4.4.3 - eslint: 10.16.0(jiti@2.7.0) - ts-api-utils: 2.5.0(typescript@6.0.3) - typescript: 6.0.3 - transitivePeerDependencies: - - supports-color - '@typescript-eslint/type-utils@8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3)': dependencies: '@typescript-eslint/types': 8.74.0 @@ -6010,25 +5936,8 @@ snapshots: - '@typescript/native' - supports-color - '@typescript-eslint/types@8.70.0': {} - '@typescript-eslint/types@8.74.0': {} - '@typescript-eslint/typescript-estree@8.70.0(typescript@6.0.3)': - dependencies: - '@typescript-eslint/project-service': 8.70.0(typescript@6.0.3) - '@typescript-eslint/tsconfig-utils': 8.70.0(typescript@6.0.3) - '@typescript-eslint/types': 8.70.0 - '@typescript-eslint/visitor-keys': 8.70.0 - debug: 4.4.3 - minimatch: 10.2.6 - semver: 7.8.5 - tinyglobby: 0.2.17 - ts-api-utils: 2.5.0(typescript@6.0.3) - typescript: 6.0.3 - transitivePeerDependencies: - - supports-color - '@typescript-eslint/typescript-estree@8.74.0(typescript@6.0.3)': dependencies: '@typescript-eslint/project-service': 8.74.0(typescript@6.0.3) @@ -6044,17 +5953,6 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/utils@8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3)': - dependencies: - '@eslint-community/eslint-utils': 4.10.1(eslint@10.16.0(jiti@2.7.0)) - '@typescript-eslint/scope-manager': 8.70.0 - '@typescript-eslint/types': 8.70.0 - '@typescript-eslint/typescript-estree': 8.70.0(typescript@6.0.3) - eslint: 10.16.0(jiti@2.7.0) - typescript: 6.0.3 - transitivePeerDependencies: - - supports-color - '@typescript-eslint/utils@8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3)': dependencies: '@eslint-community/eslint-utils': 4.10.1(eslint@10.16.0(jiti@2.7.0)) @@ -6067,11 +5965,6 @@ snapshots: - '@typescript/native' - supports-color - '@typescript-eslint/visitor-keys@8.70.0': - dependencies: - '@typescript-eslint/types': 8.70.0 - eslint-visitor-keys: 5.0.1 - '@typescript-eslint/visitor-keys@8.74.0': dependencies: '@typescript-eslint/types': 8.74.0 @@ -6149,7 +6042,7 @@ snapshots: '@unrs/resolver-binding-win32-x64-msvc@1.12.2': optional: true - '@vitejs/plugin-legacy@8.2.3(terser@5.51.2)(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.2)(yaml@2.9.1))': + '@vitejs/plugin-legacy@8.2.3(terser@5.51.3)(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.3)(yaml@2.9.1))': dependencies: '@babel/core': 7.29.7 '@babel/plugin-transform-dynamic-import': 7.29.7(@babel/core@7.29.7) @@ -6160,27 +6053,27 @@ snapshots: browserslist: 4.29.0 browserslist-to-esbuild: 2.1.1(browserslist@4.29.0) core-js: 3.50.0 - magic-string: 1.4.1 + magic-string: 1.4.5 regenerator-runtime: 0.14.1 systemjs: 6.15.1 - terser: 5.51.2 - vite: 8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.2)(yaml@2.9.1) + terser: 5.51.3 + vite: 8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.3)(yaml@2.9.1) transitivePeerDependencies: - supports-color - '@vitejs/plugin-react@6.1.1(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.2)(yaml@2.9.1))': + '@vitejs/plugin-react@6.1.1(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.3)(yaml@2.9.1))': dependencies: '@rolldown/pluginutils': 1.0.1 - vite: 8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.2)(yaml@2.9.1) + vite: 8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.3)(yaml@2.9.1) - '@vitest/mocker@5.1.2(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.2)(yaml@2.9.1))': + '@vitest/mocker@5.1.2(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.3)(yaml@2.9.1))': dependencies: '@jridgewell/trace-mapping': 0.3.31 '@vitest/spy': 5.1.2 estree-walker: 3.0.3 magic-string: 1.4.5 optionalDependencies: - vite: 8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.2)(yaml@2.9.1) + vite: 8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.3)(yaml@2.9.1) '@vitest/spy@5.1.2': {} @@ -6516,7 +6409,7 @@ snapshots: optionalDependencies: unrs-resolver: 1.12.2 - eslint-import-resolver-typescript@4.4.5(eslint-plugin-import-x@4.18.1(@typescript-eslint/utils@8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0)))(eslint@10.16.0(jiti@2.7.0)): + eslint-import-resolver-typescript@4.4.5(eslint-plugin-import-x@4.18.1(@typescript-eslint/utils@8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0)))(eslint@10.16.0(jiti@2.7.0)): dependencies: debug: 4.4.3 eslint: 10.16.0(jiti@2.7.0) @@ -6527,7 +6420,7 @@ snapshots: tinyglobby: 0.2.17 unrs-resolver: 1.12.2 optionalDependencies: - eslint-plugin-import-x: 4.18.1(@typescript-eslint/utils@8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0)) + eslint-plugin-import-x: 4.18.1(@typescript-eslint/utils@8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0)) transitivePeerDependencies: - supports-color @@ -6538,7 +6431,7 @@ snapshots: eslint: 10.16.0(jiti@2.7.0) eslint-type-tracer: 0.5.2(eslint@10.16.0(jiti@2.7.0)) - eslint-plugin-import-x@4.18.1(@typescript-eslint/utils@8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0)): + eslint-plugin-import-x@4.18.1(@typescript-eslint/utils@8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0)): dependencies: '@typescript-eslint/types': 8.74.0 cjs-module-lexer: 2.3.0 @@ -6553,7 +6446,7 @@ snapshots: stable-hash-x: 0.2.0 unrs-resolver: 1.12.2 optionalDependencies: - '@typescript-eslint/utils': 8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/utils': 8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) transitivePeerDependencies: - supports-color @@ -6578,11 +6471,12 @@ snapshots: '@eslint-react/shared': 5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) '@eslint-react/var': 5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) '@typescript-eslint/types': 8.74.0 - '@typescript-eslint/utils': 8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/utils': 8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) compare-versions: 6.1.1 eslint: 10.16.0(jiti@2.7.0) typescript: 6.0.3 transitivePeerDependencies: + - '@typescript/native' - supports-color eslint-plugin-react-hooks@7.1.1(eslint@10.16.0(jiti@2.7.0)): @@ -6604,10 +6498,11 @@ snapshots: '@eslint-react/jsx': 5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) '@eslint-react/shared': 5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) '@typescript-eslint/types': 8.74.0 - '@typescript-eslint/utils': 8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/utils': 8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) eslint: 10.16.0(jiti@2.7.0) typescript: 6.0.3 transitivePeerDependencies: + - '@typescript/native' - supports-color eslint-plugin-react-naming-convention@5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3): @@ -6618,11 +6513,12 @@ snapshots: '@eslint-react/shared': 5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) '@eslint-react/var': 5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) '@typescript-eslint/types': 8.74.0 - '@typescript-eslint/utils': 8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/utils': 8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) eslint: 10.16.0(jiti@2.7.0) ts-pattern: 5.9.0 typescript: 6.0.3 transitivePeerDependencies: + - '@typescript/native' - supports-color eslint-plugin-react-refresh@0.5.7(eslint@10.16.0(jiti@2.7.0)): @@ -6637,10 +6533,11 @@ snapshots: '@eslint-react/shared': 5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) '@eslint-react/var': 5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) '@typescript-eslint/types': 8.74.0 - '@typescript-eslint/utils': 8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/utils': 8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) eslint: 10.16.0(jiti@2.7.0) typescript: 6.0.3 transitivePeerDependencies: + - '@typescript/native' - supports-color eslint-plugin-react-web-api@5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3): @@ -6651,11 +6548,12 @@ snapshots: '@eslint-react/shared': 5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) '@eslint-react/var': 5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) '@typescript-eslint/types': 8.74.0 - '@typescript-eslint/utils': 8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/utils': 8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) eslint: 10.16.0(jiti@2.7.0) ts-pattern: 5.9.0 typescript: 6.0.3 transitivePeerDependencies: + - '@typescript/native' - supports-color eslint-plugin-react-x@5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3): @@ -6667,10 +6565,10 @@ snapshots: '@eslint-react/shared': 5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) '@eslint-react/var': 5.20.5(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) '@typescript-eslint/scope-manager': 8.74.0 - '@typescript-eslint/type-utils': 8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/type-utils': 8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) '@typescript-eslint/types': 8.74.0 - '@typescript-eslint/typescript-estree': 8.70.0(typescript@6.0.3) - '@typescript-eslint/utils': 8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/typescript-estree': 8.74.0(typescript@6.0.3) + '@typescript-eslint/utils': 8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) compare-versions: 6.1.1 eslint: 10.16.0(jiti@2.7.0) string-ts: 2.3.1 @@ -6678,6 +6576,7 @@ snapshots: ts-pattern: 5.9.0 typescript: 6.0.3 transitivePeerDependencies: + - '@typescript/native' - supports-color eslint-plugin-unused-imports@4.4.1(@typescript-eslint/eslint-plugin@8.74.0(@typescript-eslint/parser@8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0)): @@ -7200,10 +7099,6 @@ snapshots: dependencies: es5-ext: 0.10.64 - magic-string@1.4.1: - dependencies: - '@jridgewell/sourcemap-codec': 1.6.0 - magic-string@1.4.5: dependencies: '@jridgewell/sourcemap-codec': 1.6.0 @@ -7455,10 +7350,6 @@ snapshots: dependencies: mime-db: 1.52.0 - minimatch@10.2.6: - dependencies: - brace-expansion: 5.0.12 - minimatch@11.0.9: dependencies: '@isaacs/nonrecursive-glob-match': 1.1.0 @@ -7914,7 +7805,7 @@ snapshots: dependencies: '@tauri-apps/api': 2.12.5 - terser@5.51.2: + terser@5.51.3: dependencies: '@jridgewell/source-map': 0.3.11 acorn: 8.18.0 @@ -8097,18 +7988,18 @@ snapshots: '@types/unist': 3.0.3 vfile-message: 4.0.3 - vite-plugin-svgr@5.2.0(typescript@6.0.3)(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.2)(yaml@2.9.1)): + vite-plugin-svgr@5.2.0(typescript@6.0.3)(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.3)(yaml@2.9.1)): dependencies: '@rollup/pluginutils': 5.4.0 '@svgr/core': 8.1.0(typescript@6.0.3) '@svgr/plugin-jsx': 8.1.0(@svgr/core@8.1.0(typescript@6.0.3)) - vite: 8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.2)(yaml@2.9.1) + vite: 8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.3)(yaml@2.9.1) transitivePeerDependencies: - rollup - supports-color - typescript - vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.2)(yaml@2.9.1): + vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.3)(yaml@2.9.1): dependencies: lightningcss: 1.33.0 picomatch: 4.0.7 @@ -8120,13 +8011,13 @@ snapshots: fsevents: 2.3.3 jiti: 2.7.0 sass: 1.104.1 - terser: 5.51.2 + terser: 5.51.3 yaml: 2.9.1 - vitest@5.1.2(@types/node@26.6.5)(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.2)(yaml@2.9.1)): + vitest@5.1.2(@types/node@26.6.5)(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.3)(yaml@2.9.1)): dependencies: '@types/chai': 5.2.3 - '@vitest/mocker': 5.1.2(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.2)(yaml@2.9.1)) + '@vitest/mocker': 5.1.2(vite@8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.3)(yaml@2.9.1)) chai: 6.3.0 es-module-lexer: 2.3.2 expect-type: 1.4.0 @@ -8137,7 +8028,7 @@ snapshots: tinybench: 6.2.5 tinyexec: 1.3.1 tinyglobby: 0.2.17 - vite: 8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.2)(yaml@2.9.1) + vite: 8.3.3(@types/node@26.6.5)(jiti@2.7.0)(sass@1.104.1)(terser@5.51.3)(yaml@2.9.1) why-is-node-running: 3.2.1 optionalDependencies: '@types/node': 26.6.5 From 9c3a43397929a3d5f7b634415c4a7345393120c8 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:42:22 +0000 Subject: [PATCH 04/33] chore(deps): update agentic workflows to v1.4.5 (#8809) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Bump actions in `copilot-setup-steps.yml` - Bump other agentic workflow lockfiles Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com> Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com> --- .github/aw/actions-lock.json | 6 ++-- .github/workflows/copilot-setup-steps.yml | 4 +-- .github/workflows/pr-ai-slop-review.lock.yml | 34 +++++++++--------- .github/workflows/pr-verify-fix.lock.yml | 36 +++++++++---------- .../workflows/renovate-minor-review.lock.yml | 34 +++++++++--------- 5 files changed, 54 insertions(+), 60 deletions(-) diff --git a/.github/aw/actions-lock.json b/.github/aw/actions-lock.json index 5bd56cb02..e3dd78173 100644 --- a/.github/aw/actions-lock.json +++ b/.github/aw/actions-lock.json @@ -5,10 +5,10 @@ "version": "v9.0.0", "sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3" }, - "github/gh-aw-actions/setup@v1.4.4": { + "github/gh-aw-actions/setup@v1.4.5": { "repo": "github/gh-aw-actions/setup", - "version": "v1.4.4", - "sha": "6147e7c2fba711fb36ac73c79cba401d1e213c4e" + "version": "v1.4.5", + "sha": "a83eaf07e756a15e65f669eb32d00787cf5a2569" } }, "containers": { diff --git a/.github/workflows/copilot-setup-steps.yml b/.github/workflows/copilot-setup-steps.yml index b353f728e..89a123a78 100644 --- a/.github/workflows/copilot-setup-steps.yml +++ b/.github/workflows/copilot-setup-steps.yml @@ -31,9 +31,9 @@ jobs: with: persist-credentials: false - name: Install gh-aw extension - uses: github/gh-aw-actions/setup-cli@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 + uses: github/gh-aw-actions/setup-cli@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 with: - version: v1.4.4 + version: v1.4.5 - name: Install Rust Stable uses: dtolnay/rust-toolchain@stable with: diff --git a/.github/workflows/pr-ai-slop-review.lock.yml b/.github/workflows/pr-ai-slop-review.lock.yml index fe8942d3e..beff27659 100644 --- a/.github/workflows/pr-ai-slop-review.lock.yml +++ b/.github/workflows/pr-ai-slop-review.lock.yml @@ -1,6 +1,6 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"4ca5835c0c9cd01f3432b873f5a177ca6d3d1dbd6a35939e2058dcb37aa224b4","body_hash":"ca82fafbe18061d7c8bd708dc18e91b9116faf0c921a7fa35be1538d47a2b005","compiler_version":"v1.4.4","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}} -# 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":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"6147e7c2fba711fb36ac73c79cba401d1e213c4e","version":"v1.4.4"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.16","digest":"sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f","pinned_image":"ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f"},{"image":"ghcr.io/github/github-mcp-server:v2.3.0","digest":"sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6","pinned_image":"ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","add_labels","noop","remove_labels","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"14ba41178a91b10b7de6":{"name":"Agentic Workflows"}}} -# This file was automatically generated by gh-aw (v1.4.4). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"4ca5835c0c9cd01f3432b873f5a177ca6d3d1dbd6a35939e2058dcb37aa224b4","body_hash":"ca82fafbe18061d7c8bd708dc18e91b9116faf0c921a7fa35be1538d47a2b005","compiler_version":"v1.4.5","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}} +# 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":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"a83eaf07e756a15e65f669eb32d00787cf5a2569","version":"v1.4.5"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.16","digest":"sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f","pinned_image":"ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f"},{"image":"ghcr.io/github/github-mcp-server:v2.3.0","digest":"sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6","pinned_image":"ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","add_labels","noop","remove_labels","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"14ba41178a91b10b7de6":{"name":"Agentic Workflows"}}} +# This file was automatically generated by gh-aw (v1.4.5). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md # # ___ _ _ # / _ \ | | (_) @@ -44,7 +44,7 @@ # - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 # - actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 # - actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 -# - github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 +# - github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 # # Container images used: # - ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059 @@ -130,7 +130,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 + uses: github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -152,7 +152,7 @@ jobs: GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }} GH_AW_INFO_VERSION: "1.0.103" GH_AW_INFO_AGENT_VERSION: "1.0.103" - GH_AW_INFO_CLI_VERSION: "v1.4.4" + GH_AW_INFO_CLI_VERSION: "v1.4.5" GH_AW_INFO_WORKFLOW_NAME: "PR AI Slop Review" GH_AW_INFO_WORKFLOW_ID: ${{ job.workflow_ref }} GH_AW_INFO_WORKFLOW_SHA: ${{ job.workflow_sha }} @@ -271,7 +271,7 @@ jobs: if: steps.daily-ai-credits-workflow-guardrail.outputs.daily_ai_credits_guardrail_status != 'quota_blocked' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_COMPILED_VERSION: "v1.4.4" + GH_AW_COMPILED_VERSION: "v1.4.5" GH_AW_HAS_SAFE_OUTPUTS: "true" GH_AW_BLOCKED_VERSION_REPORT_AS_ISSUE: "false" GH_AW_WORKFLOW_NAME: "PR AI Slop Review" @@ -558,7 +558,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 + uses: github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1104,7 +1104,7 @@ jobs: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} GH_AW_TIMEOUT_MINUTES: ${{ fromJSON(vars.GH_AW_DEFAULT_TIMEOUT_MINUTES || '20') }} - GH_AW_VERSION: v1.4.4 + GH_AW_VERSION: v1.4.5 GH_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN || github.token }} GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true @@ -1197,8 +1197,7 @@ jobs: env: GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} run: | - mkdir -p /tmp/gh-aw - cp "$GH_AW_SAFE_OUTPUTS" /tmp/gh-aw/safeoutputs.jsonl 2>/dev/null || true + bash "${RUNNER_TEMP}/gh-aw/actions/safe_copy.sh" file "$GH_AW_SAFE_OUTPUTS" /tmp/gh-aw/safeoutputs.jsonl || true - name: Ingest agent output id: collect_output if: always() @@ -1437,7 +1436,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 + uses: github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1816,7 +1815,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 + uses: github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1945,7 +1944,7 @@ jobs: GH_AW_PHASE: detection GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_TIMEOUT_MINUTES: 10 - GH_AW_VERSION: v1.4.4 + GH_AW_VERSION: v1.4.5 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -2030,9 +2029,8 @@ jobs: if: always() && steps.detection_guard.outputs.run_detection == 'true' continue-on-error: true run: | - mkdir -p /tmp/gh-aw/threat-detection/sandbox/firewall - if [ -d /tmp/gh-aw/sandbox/firewall/logs ]; then mkdir -p /tmp/gh-aw/threat-detection/sandbox/firewall/logs && cp -r /tmp/gh-aw/sandbox/firewall/logs/. /tmp/gh-aw/threat-detection/sandbox/firewall/logs/; fi - if [ -d /tmp/gh-aw/sandbox/firewall/audit ]; then mkdir -p /tmp/gh-aw/threat-detection/sandbox/firewall/audit && cp -r /tmp/gh-aw/sandbox/firewall/audit/. /tmp/gh-aw/threat-detection/sandbox/firewall/audit/; fi + bash "${RUNNER_TEMP}/gh-aw/actions/safe_copy.sh" tree /tmp/gh-aw/sandbox/firewall/logs /tmp/gh-aw/threat-detection/sandbox/firewall/logs + bash "${RUNNER_TEMP}/gh-aw/actions/safe_copy.sh" tree /tmp/gh-aw/sandbox/firewall/audit /tmp/gh-aw/threat-detection/sandbox/firewall/audit - name: Redact secrets in detection logs id: redact_detection_logs if: always() && steps.detection_guard.outputs.run_detection == 'true' @@ -2189,7 +2187,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 + uses: github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} diff --git a/.github/workflows/pr-verify-fix.lock.yml b/.github/workflows/pr-verify-fix.lock.yml index cb5e8a80f..7c63fdf58 100644 --- a/.github/workflows/pr-verify-fix.lock.yml +++ b/.github/workflows/pr-verify-fix.lock.yml @@ -1,6 +1,6 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"d6b72464a3766dd7d74aefe4c7dd982ae7ae2db951f8040f978feca9166adb39","body_hash":"deddd98c5fa425a91487fb5f50dc59ac61ae395bdcd4dff6543f1e8e563a7d73","compiler_version":"v1.4.4","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}} -# 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":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"6147e7c2fba711fb36ac73c79cba401d1e213c4e","version":"v1.4.4"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.16","digest":"sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f","pinned_image":"ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f"},{"image":"ghcr.io/github/github-mcp-server:v2.3.0","digest":"sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6","pinned_image":"ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","noop","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"14ba41178a91b10b7de6":{"name":"Agentic Workflows"}}} -# This file was automatically generated by gh-aw (v1.4.4). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"d6b72464a3766dd7d74aefe4c7dd982ae7ae2db951f8040f978feca9166adb39","body_hash":"deddd98c5fa425a91487fb5f50dc59ac61ae395bdcd4dff6543f1e8e563a7d73","compiler_version":"v1.4.5","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}} +# 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":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"a83eaf07e756a15e65f669eb32d00787cf5a2569","version":"v1.4.5"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.16","digest":"sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f","pinned_image":"ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f"},{"image":"ghcr.io/github/github-mcp-server:v2.3.0","digest":"sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6","pinned_image":"ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","noop","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"14ba41178a91b10b7de6":{"name":"Agentic Workflows"}}} +# This file was automatically generated by gh-aw (v1.4.5). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md # # ___ _ _ # / _ \ | | (_) @@ -43,7 +43,7 @@ # - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 # - actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 # - actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 -# - github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 +# - github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 # # Container images used: # - ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059 @@ -141,7 +141,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 + uses: github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -165,7 +165,7 @@ jobs: GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }} GH_AW_INFO_VERSION: "1.0.103" GH_AW_INFO_AGENT_VERSION: "1.0.103" - GH_AW_INFO_CLI_VERSION: "v1.4.4" + GH_AW_INFO_CLI_VERSION: "v1.4.5" GH_AW_INFO_WORKFLOW_NAME: "Verify Review Fixes" GH_AW_INFO_WORKFLOW_ID: ${{ job.workflow_ref }} GH_AW_INFO_WORKFLOW_SHA: ${{ job.workflow_sha }} @@ -284,7 +284,7 @@ jobs: if: steps.daily-ai-credits-workflow-guardrail.outputs.daily_ai_credits_guardrail_status != 'quota_blocked' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_COMPILED_VERSION: "v1.4.4" + GH_AW_COMPILED_VERSION: "v1.4.5" GH_AW_HAS_SAFE_OUTPUTS: "true" GH_AW_BLOCKED_VERSION_REPORT_AS_ISSUE: "false" GH_AW_WORKFLOW_NAME: "Verify Review Fixes" @@ -596,7 +596,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 + uses: github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1105,7 +1105,7 @@ jobs: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} GH_AW_TIMEOUT_MINUTES: ${{ fromJSON(vars.GH_AW_DEFAULT_TIMEOUT_MINUTES || '20') }} - GH_AW_VERSION: v1.4.4 + GH_AW_VERSION: v1.4.5 GH_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN || github.token }} GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true @@ -1198,8 +1198,7 @@ jobs: env: GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} run: | - mkdir -p /tmp/gh-aw - cp "$GH_AW_SAFE_OUTPUTS" /tmp/gh-aw/safeoutputs.jsonl 2>/dev/null || true + bash "${RUNNER_TEMP}/gh-aw/actions/safe_copy.sh" file "$GH_AW_SAFE_OUTPUTS" /tmp/gh-aw/safeoutputs.jsonl || true - name: Ingest agent output id: collect_output if: always() @@ -1439,7 +1438,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 + uses: github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1818,7 +1817,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 + uses: github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1947,7 +1946,7 @@ jobs: GH_AW_PHASE: detection GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_TIMEOUT_MINUTES: 10 - GH_AW_VERSION: v1.4.4 + GH_AW_VERSION: v1.4.5 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -2032,9 +2031,8 @@ jobs: if: always() && steps.detection_guard.outputs.run_detection == 'true' continue-on-error: true run: | - mkdir -p /tmp/gh-aw/threat-detection/sandbox/firewall - if [ -d /tmp/gh-aw/sandbox/firewall/logs ]; then mkdir -p /tmp/gh-aw/threat-detection/sandbox/firewall/logs && cp -r /tmp/gh-aw/sandbox/firewall/logs/. /tmp/gh-aw/threat-detection/sandbox/firewall/logs/; fi - if [ -d /tmp/gh-aw/sandbox/firewall/audit ]; then mkdir -p /tmp/gh-aw/threat-detection/sandbox/firewall/audit && cp -r /tmp/gh-aw/sandbox/firewall/audit/. /tmp/gh-aw/threat-detection/sandbox/firewall/audit/; fi + bash "${RUNNER_TEMP}/gh-aw/actions/safe_copy.sh" tree /tmp/gh-aw/sandbox/firewall/logs /tmp/gh-aw/threat-detection/sandbox/firewall/logs + bash "${RUNNER_TEMP}/gh-aw/actions/safe_copy.sh" tree /tmp/gh-aw/sandbox/firewall/audit /tmp/gh-aw/threat-detection/sandbox/firewall/audit - name: Redact secrets in detection logs id: redact_detection_logs if: always() && steps.detection_guard.outputs.run_detection == 'true' @@ -2152,7 +2150,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 + uses: github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -2247,7 +2245,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 + uses: github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} diff --git a/.github/workflows/renovate-minor-review.lock.yml b/.github/workflows/renovate-minor-review.lock.yml index 33c93ce51..c8ffbcf4c 100644 --- a/.github/workflows/renovate-minor-review.lock.yml +++ b/.github/workflows/renovate-minor-review.lock.yml @@ -1,6 +1,6 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"e44852fbf56eab99e67b3f6a306f75195603ece6ed130e55652a2467efed1415","body_hash":"7835f25016082d56592b67f4d2bf5b839eb02a6fa8f03d65699ed6bae979c5ad","compiler_version":"v1.4.4","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}} -# 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":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"6147e7c2fba711fb36ac73c79cba401d1e213c4e","version":"v1.4.4"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.16","digest":"sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f","pinned_image":"ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f"},{"image":"ghcr.io/github/github-mcp-server:v2.3.0","digest":"sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6","pinned_image":"ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","noop","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"14ba41178a91b10b7de6":{"name":"Agentic Workflows"}}} -# This file was automatically generated by gh-aw (v1.4.4). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"e44852fbf56eab99e67b3f6a306f75195603ece6ed130e55652a2467efed1415","body_hash":"7835f25016082d56592b67f4d2bf5b839eb02a6fa8f03d65699ed6bae979c5ad","compiler_version":"v1.4.5","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}} +# 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":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"a83eaf07e756a15e65f669eb32d00787cf5a2569","version":"v1.4.5"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.16","digest":"sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f","pinned_image":"ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f"},{"image":"ghcr.io/github/github-mcp-server:v2.3.0","digest":"sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6","pinned_image":"ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","noop","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"14ba41178a91b10b7de6":{"name":"Agentic Workflows"}}} +# This file was automatically generated by gh-aw (v1.4.5). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md # # ___ _ _ # / _ \ | | (_) @@ -43,7 +43,7 @@ # - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 # - actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 # - actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 -# - github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 +# - github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 # # Container images used: # - ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059 @@ -133,7 +133,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 + uses: github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -155,7 +155,7 @@ jobs: GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }} GH_AW_INFO_VERSION: "1.0.103" GH_AW_INFO_AGENT_VERSION: "1.0.103" - GH_AW_INFO_CLI_VERSION: "v1.4.4" + GH_AW_INFO_CLI_VERSION: "v1.4.5" GH_AW_INFO_WORKFLOW_NAME: "Renovate Minor Upgrade Analysis" GH_AW_INFO_WORKFLOW_ID: ${{ job.workflow_ref }} GH_AW_INFO_WORKFLOW_SHA: ${{ job.workflow_sha }} @@ -274,7 +274,7 @@ jobs: if: steps.daily-ai-credits-workflow-guardrail.outputs.daily_ai_credits_guardrail_status != 'quota_blocked' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_COMPILED_VERSION: "v1.4.4" + GH_AW_COMPILED_VERSION: "v1.4.5" GH_AW_HAS_SAFE_OUTPUTS: "true" GH_AW_BLOCKED_VERSION_REPORT_AS_ISSUE: "false" GH_AW_WORKFLOW_NAME: "Renovate Minor Upgrade Analysis" @@ -562,7 +562,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 + uses: github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1094,7 +1094,7 @@ jobs: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} GH_AW_TIMEOUT_MINUTES: ${{ fromJSON(vars.GH_AW_DEFAULT_TIMEOUT_MINUTES || '20') }} - GH_AW_VERSION: v1.4.4 + GH_AW_VERSION: v1.4.5 GH_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN || github.token }} GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true @@ -1193,8 +1193,7 @@ jobs: env: GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} run: | - mkdir -p /tmp/gh-aw - cp "$GH_AW_SAFE_OUTPUTS" /tmp/gh-aw/safeoutputs.jsonl 2>/dev/null || true + bash "${RUNNER_TEMP}/gh-aw/actions/safe_copy.sh" file "$GH_AW_SAFE_OUTPUTS" /tmp/gh-aw/safeoutputs.jsonl || true - name: Ingest agent output id: collect_output if: always() @@ -1433,7 +1432,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 + uses: github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1812,7 +1811,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 + uses: github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1941,7 +1940,7 @@ jobs: GH_AW_PHASE: detection GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_TIMEOUT_MINUTES: 10 - GH_AW_VERSION: v1.4.4 + GH_AW_VERSION: v1.4.5 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -2026,9 +2025,8 @@ jobs: if: always() && steps.detection_guard.outputs.run_detection == 'true' continue-on-error: true run: | - mkdir -p /tmp/gh-aw/threat-detection/sandbox/firewall - if [ -d /tmp/gh-aw/sandbox/firewall/logs ]; then mkdir -p /tmp/gh-aw/threat-detection/sandbox/firewall/logs && cp -r /tmp/gh-aw/sandbox/firewall/logs/. /tmp/gh-aw/threat-detection/sandbox/firewall/logs/; fi - if [ -d /tmp/gh-aw/sandbox/firewall/audit ]; then mkdir -p /tmp/gh-aw/threat-detection/sandbox/firewall/audit && cp -r /tmp/gh-aw/sandbox/firewall/audit/. /tmp/gh-aw/threat-detection/sandbox/firewall/audit/; fi + bash "${RUNNER_TEMP}/gh-aw/actions/safe_copy.sh" tree /tmp/gh-aw/sandbox/firewall/logs /tmp/gh-aw/threat-detection/sandbox/firewall/logs + bash "${RUNNER_TEMP}/gh-aw/actions/safe_copy.sh" tree /tmp/gh-aw/sandbox/firewall/audit /tmp/gh-aw/threat-detection/sandbox/firewall/audit - name: Redact secrets in detection logs id: redact_detection_logs if: always() && steps.detection_guard.outputs.run_detection == 'true' @@ -2185,7 +2183,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4 + uses: github/gh-aw-actions/setup@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} From c9223b204b173e5001547fafbe213f77d33a655c Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:10:12 +0800 Subject: [PATCH 05/33] fix(limiter): handle stale clock samples and timestamp overflow A caller could sample the clock at 1000 ms and pause while another caller was admitted at 2000 ms. On resuming, the first caller could load the newer last_run_ms, mistake its stale sample for a clock rollback, and replace 2000 with 1000. This reopened the 100 ms period and let another check at 2000 ms pass. Load last_run_ms before sampling the clock so the stale caller's compare-exchange fails if a newer admission has changed that value. Preserve sequential clock rollback behavior and the existing atomic orderings. The period check also added the period to last_run_ms. A last admission at u64::MAX - 55 with a 56 ms period overflowed on the next check: debug builds panicked and release builds wrapped the deadline to zero, admitting a duplicate timestamp. Compare elapsed time against the period only after confirming the clock has not moved backward, which makes the subtraction safe and preserves the exact period boundary. Enable the stale-sample and overflow regressions, keep the saved Proptest seed, and add Loom coverage for advancing time and multiple stale callers plus a deterministic test at u64::MAX. --- Cargo.lock | 213 ++++++++++++++++- Cargo.toml | 5 + crates/clash-verge-limiter/Cargo.toml | 6 + crates/clash-verge-limiter/src/lib.rs | 49 +++- crates/clash-verge-limiter/tests/loom.rs | 225 ++++++++++++++++++ .../tests/properties.proptest-regressions | 7 + .../clash-verge-limiter/tests/properties.rs | 211 ++++++++++++++++ 7 files changed, 703 insertions(+), 13 deletions(-) create mode 100644 crates/clash-verge-limiter/tests/loom.rs create mode 100644 crates/clash-verge-limiter/tests/properties.proptest-regressions create mode 100644 crates/clash-verge-limiter/tests/properties.rs diff --git a/Cargo.lock b/Cargo.lock index c47f34fc7..65fc3aa64 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -514,7 +514,16 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" dependencies = [ - "bit-vec", + "bit-vec 0.8.0", +] + +[[package]] +name = "bit-set" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec 0.10.2", ] [[package]] @@ -523,6 +532,16 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" +[[package]] +name = "bit-vec" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0" +dependencies = [ + "borsh", + "serde", +] + [[package]] name = "bitflags" version = "1.3.2" @@ -741,6 +760,30 @@ dependencies = [ "static_assertions", ] +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 3.0.5", +] + [[package]] name = "brotli" version = "9.0.0" @@ -1187,6 +1230,10 @@ dependencies = [ [[package]] name = "clash-verge-limiter" version = "0.1.0" +dependencies = [ + "loom", + "proptest", +] [[package]] name = "clash-verge-logging" @@ -1558,6 +1605,12 @@ dependencies = [ "libc", ] +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "core_maths" version = "0.1.1" @@ -2127,7 +2180,7 @@ version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc" dependencies = [ - "bit-set", + "bit-set 0.8.0", "cssparser", "foldhash 0.2.0", "html5ever", @@ -2719,6 +2772,18 @@ dependencies = [ "x11", ] +[[package]] +name = "generator" +version = "0.8.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66831419d9074e766421508dff218bf79d99616bc5e56e34599d3b433714a4a4" +dependencies = [ + "libc", + "log", + "windows-core 0.100.0", + "windows-sys 0.61.2", +] + [[package]] name = "generic-array" version = "0.14.7" @@ -4124,6 +4189,19 @@ version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" +[[package]] +name = "loom" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1611ddbf89dc6ae42cfbd51fc207836140130257646eab8d6d2fb16577db2d2" +dependencies = [ + "cfg-if", + "generator", + "scoped-tls", + "tracing", + "tracing-subscriber", +] + [[package]] name = "lru-slab" version = "0.1.2" @@ -5528,6 +5606,26 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bit-set 0.11.1", + "bit-vec 0.10.2", + "bitflags 2.13.2", + "chacha20", + "core_detect", + "num-traits", + "rand 0.10.2", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + [[package]] name = "prost" version = "0.14.4" @@ -5582,6 +5680,12 @@ version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + [[package]] name = "quick-error" version = "2.0.1" @@ -5769,6 +5873,15 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -6300,6 +6413,18 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error 1.2.3", + "tempfile", + "wait-timeout", +] + [[package]] name = "ryu" version = "1.0.23" @@ -8097,7 +8222,7 @@ dependencies = [ "fax", "flate2", "half", - "quick-error", + "quick-error 2.0.1", "weezl", "zune-jpeg", ] @@ -8728,6 +8853,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + [[package]] name = "unicase" version = "2.9.0" @@ -8882,6 +9013,15 @@ dependencies = [ "utf8parse", ] +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + [[package]] name = "walkdir" version = "2.5.0" @@ -9341,8 +9481,8 @@ version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" dependencies = [ - "windows-implement", - "windows-interface", + "windows-implement 0.60.2", + "windows-interface 0.59.3", "windows-link 0.1.3", "windows-result 0.3.4", "windows-strings 0.4.2", @@ -9354,13 +9494,26 @@ version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ - "windows-implement", - "windows-interface", + "windows-implement 0.60.2", + "windows-interface 0.59.3", "windows-link 0.2.1", "windows-result 0.4.1", "windows-strings 0.5.1", ] +[[package]] +name = "windows-core" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "803590c6856f51d15fa2e9fabe4f4703122c8737f72ef2741b4ac09d4c2192f5" +dependencies = [ + "windows-implement 0.100.0", + "windows-interface 0.100.0", + "windows-link 0.100.0", + "windows-result 0.100.0", + "windows-strings 0.100.0", +] + [[package]] name = "windows-future" version = "0.2.1" @@ -9394,6 +9547,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "windows-implement" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc1bc82e5a1b1a4d7255861b07881a0407b552f50a4d8543c0c7276fa96f6e8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows-interface" version = "0.59.3" @@ -9405,6 +9569,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "windows-interface" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3f7005c3b757b9b82c2f40c0e71094ff1080adddaf3e8b6ce99b545d3c48796" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows-link" version = "0.1.3" @@ -9417,6 +9592,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-link" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b39de7c7fe78858b0144c50c3fc000bab3be17d5e9b85b1053871693c7f7415" + [[package]] name = "windows-numerics" version = "0.2.0" @@ -9466,6 +9647,15 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-result" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44873a1ef61c85d5e2991db91fe656cfcf0731097e00dff1ac860f1cb3b752a0" +dependencies = [ + "windows-link 0.100.0", +] + [[package]] name = "windows-service" version = "0.8.1" @@ -9495,6 +9685,15 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-strings" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a70b590c684f1d2854f74999896f7c0558f1bdde62f599088599e20ea1d2f60" +dependencies = [ + "windows-link 0.100.0", +] + [[package]] name = "windows-sys" version = "0.45.0" diff --git a/Cargo.toml b/Cargo.toml index 71857be3f..dc750f7af 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,6 +68,8 @@ tauri-plugin-clipboard-manager = "2.5.0" parking_lot = "0.13.0" anyhow = "1.0.105" futures = "0.3.34" +loom = "0.7" +proptest = "1.12.0" chrono = "0.4.45" criterion = { version = "0.8.2", features = ["async_tokio"] } tokio = { version = "1.54.1", features = [ @@ -108,6 +110,9 @@ windows-sys = { version = "0.61.2", features = [ ] } # ********************************* +[workspace.lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(loom)'] } + [workspace.lints.clippy] # fallible_impl_from = "deny" // 过于激进,暂时不开启 # implicit_clone = "deny" // 可能会造成额外开销,暂时不开启 diff --git a/crates/clash-verge-limiter/Cargo.toml b/crates/clash-verge-limiter/Cargo.toml index 1f856f1f2..419a16f82 100644 --- a/crates/clash-verge-limiter/Cargo.toml +++ b/crates/clash-verge-limiter/Cargo.toml @@ -5,5 +5,11 @@ edition = "2024" [dependencies] +[dev-dependencies] +proptest = { workspace = true } + +[target.'cfg(loom)'.dependencies] +loom = { workspace = true } + [lints] workspace = true diff --git a/crates/clash-verge-limiter/src/lib.rs b/crates/clash-verge-limiter/src/lib.rs index 7af97fc07..9a6a52e00 100644 --- a/crates/clash-verge-limiter/src/lib.rs +++ b/crates/clash-verge-limiter/src/lib.rs @@ -1,5 +1,12 @@ +#[cfg(loom)] +use loom::sync::Arc; +#[cfg(loom)] +use loom::sync::atomic::AtomicU64; +#[cfg(not(loom))] use std::sync::Arc; -use std::sync::atomic::{AtomicU64, Ordering}; +#[cfg(not(loom))] +use std::sync::atomic::AtomicU64; +use std::sync::atomic::Ordering; use std::time::{Duration, SystemTime, UNIX_EPOCH}; pub type SystemLimiter = Limiter; @@ -38,6 +45,7 @@ pub struct Limiter { } impl Limiter { + #[cfg(not(loom))] pub const fn new(period: Duration, clock: C) -> Self { Self { last_run_ms: AtomicU64::new(0), @@ -46,11 +54,21 @@ impl Limiter { } } - pub fn check(&self) -> bool { - let now = self.clock.now_ms(); - let last = self.last_run_ms.load(Ordering::Relaxed); + #[cfg(loom)] + pub fn new(period: Duration, clock: C) -> Self { + Self { + last_run_ms: AtomicU64::new(0), + period_ms: period.as_millis() as u64, + clock, + } + } - if now < last + self.period_ms && now >= last { + pub fn check(&self) -> bool { + // Load before sampling so a stale sample cannot move a newer admission backward. + let last = self.last_run_ms.load(Ordering::Relaxed); + let now = self.clock.now_ms(); + + if now >= last && now - last < self.period_ms { return false; } @@ -74,6 +92,22 @@ mod tests { } } + #[test] + fn system_clock_reports_unix_epoch_milliseconds() { + const MAX_DRIFT_MS: u64 = 5 * 60 * 1_000; + + let wall_clock_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as u64; + let clock_ms = SystemClock.now_ms(); + + assert!( + clock_ms.abs_diff(wall_clock_ms) <= MAX_DRIFT_MS, + "SystemClock::now_ms() should return Unix epoch milliseconds, got {clock_ms} while wall clock is {wall_clock_ms}" + ); + } + #[test] fn enforces_the_period_boundary() { let clock = MockClock(AtomicU64::new(1_000)); @@ -100,7 +134,10 @@ mod tests { } let admitted = handles .into_iter() - .map(|handle| handle.join().unwrap_or(false)) + .map(|handle| match handle.join() { + Ok(admitted) => admitted, + Err(panic) => std::panic::resume_unwind(panic), + }) .filter(|passed| *passed) .count(); diff --git a/crates/clash-verge-limiter/tests/loom.rs b/crates/clash-verge-limiter/tests/loom.rs new file mode 100644 index 000000000..b0a58e865 --- /dev/null +++ b/crates/clash-verge-limiter/tests/loom.rs @@ -0,0 +1,225 @@ +#![cfg(loom)] + +use std::sync::atomic::Ordering; +use std::time::Duration; + +use clash_verge_limiter::{Clock, Limiter}; +use loom::sync::Arc; +use loom::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize}; + +const PERIOD_MS: u64 = 100; +const START_MS: u64 = 1_000; + +struct MockClock(AtomicU64); + +impl Clock for MockClock { + fn now_ms(&self) -> u64 { + self.0.load(Ordering::SeqCst) + } +} + +type TestLimiter = Limiter>; + +struct AdvancingClock(AtomicU64); + +impl Clock for AdvancingClock { + fn now_ms(&self) -> u64 { + self.0.fetch_add(1, Ordering::SeqCst) + } +} + +fn limiter_at(now_ms: u64) -> (Arc, Arc) { + let clock = Arc::new(MockClock(AtomicU64::new(now_ms))); + let limiter = Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock)); + (clock, Arc::new(limiter)) +} + +fn run_two_concurrent_checks(limiter: &Arc>) -> usize { + let handles: [_; 2] = std::array::from_fn(|_| { + let limiter = Arc::clone(limiter); + loom::thread::spawn(move || limiter.check()) + }); + + handles + .into_iter() + .map(|handle| match handle.join() { + Ok(admitted) => admitted, + Err(panic) => std::panic::resume_unwind(panic), + }) + .filter(|admitted| *admitted) + .count() +} + +#[test] +fn admits_exactly_one_caller_in_an_eligible_window() { + loom::model(|| { + let (_clock, limiter) = limiter_at(START_MS); + + assert_eq!(run_two_concurrent_checks(&limiter), 1); + }); +} + +#[test] +fn rejects_concurrent_callers_inside_the_restricted_period() { + loom::model(|| { + let (clock, limiter) = limiter_at(START_MS); + assert!(limiter.check()); + + clock.0.store(START_MS + PERIOD_MS - 1, Ordering::SeqCst); + + assert_eq!(run_two_concurrent_checks(&limiter), 0); + }); +} + +#[test] +fn admits_exactly_one_caller_at_the_period_boundary() { + loom::model(|| { + let (clock, limiter) = limiter_at(START_MS); + assert!(limiter.check()); + + clock.0.store(START_MS + PERIOD_MS, Ordering::SeqCst); + + assert_eq!(run_two_concurrent_checks(&limiter), 1); + }); +} + +#[test] +fn concurrent_clock_advancement_admits_exactly_one_caller() { + loom::model(|| { + let clock = Arc::new(AdvancingClock(AtomicU64::new(START_MS))); + let limiter = Arc::new(Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock))); + + assert_eq!(run_two_concurrent_checks(&limiter), 1); + }); +} + +struct StaleClock { + current: AtomicU64, + reads: AtomicUsize, + stale_reads: usize, + sampled: AtomicUsize, + released: AtomicBool, +} + +impl StaleClock { + fn new(now_ms: u64, stale_reads: usize) -> Self { + Self { + current: AtomicU64::new(now_ms), + reads: AtomicUsize::new(0), + stale_reads, + sampled: AtomicUsize::new(0), + released: AtomicBool::new(false), + } + } + + fn release(&self) { + self.released.store(true, Ordering::SeqCst); + } +} + +impl Clock for StaleClock { + fn now_ms(&self) -> u64 { + if self.reads.fetch_add(1, Ordering::SeqCst) < self.stale_reads { + let stale = self.current.load(Ordering::SeqCst); + self.sampled.fetch_add(1, Ordering::SeqCst); + + // Parking can wake spuriously; re-check the release flag on each + // wake. Unparking after setting the flag avoids a lost wakeup. + while !self.released.load(Ordering::SeqCst) { + loom::thread::park(); + } + + stale + } else { + self.current.load(Ordering::SeqCst) + } + } +} + +/// Regression: a caller that sampled the clock before a newer admission must +/// not overwrite that admission when it resumes. +#[test] +fn stale_clock_sample_does_not_reopen_the_period() { + loom::model(|| { + const LATER_MS: u64 = START_MS + PERIOD_MS * 10; + + let clock = Arc::new(StaleClock::new(START_MS, 1)); + let limiter = Arc::new(Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock))); + + let stale_caller = { + let limiter = Arc::clone(&limiter); + loom::thread::spawn(move || limiter.check()) + }; + + while clock.sampled.load(Ordering::SeqCst) < 1 { + loom::thread::yield_now(); + } + clock.current.store(LATER_MS, Ordering::SeqCst); + + let later_caller = { + let limiter = Arc::clone(&limiter); + loom::thread::spawn(move || limiter.check()) + }; + + let later_admitted = later_caller.join().unwrap(); + assert!( + later_admitted, + "the later caller must be admitted before the stale caller resumes" + ); + + clock.release(); + stale_caller.thread().unpark(); + + let stale_admitted = stale_caller.join().unwrap(); + let reopened = limiter.check(); + + assert!( + !stale_admitted, + "stale caller must not be admitted after the later caller" + ); + assert!( + !reopened, + "stale caller admitted={stale_admitted} moved last_run_ms from {LATER_MS} back to {START_MS}" + ); + }); +} + +#[test] +fn multiple_stale_clock_samples_cannot_reopen_the_period() { + loom::model(|| { + const LATER_MS: u64 = START_MS + PERIOD_MS * 10; + + let clock = Arc::new(StaleClock::new(START_MS, 2)); + let limiter = Arc::new(Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock))); + + let stale_callers: [_; 2] = std::array::from_fn(|_| { + let limiter = Arc::clone(&limiter); + loom::thread::spawn(move || limiter.check()) + }); + + while clock.sampled.load(Ordering::SeqCst) < 2 { + loom::thread::yield_now(); + } + clock.current.store(LATER_MS, Ordering::SeqCst); + assert!( + limiter.check(), + "the later caller must be admitted before the stale callers resume" + ); + + clock.release(); + for caller in &stale_callers { + caller.thread().unpark(); + } + + let stale_admitted = stale_callers + .into_iter() + .map(|caller| caller.join().unwrap()) + .filter(|admitted| *admitted) + .count(); + assert_eq!( + stale_admitted, 0, + "stale callers must not be admitted after the later caller" + ); + assert!(!limiter.check(), "stale callers reopened the period at {LATER_MS}"); + }); +} diff --git a/crates/clash-verge-limiter/tests/properties.proptest-regressions b/crates/clash-verge-limiter/tests/properties.proptest-regressions new file mode 100644 index 000000000..5908198d6 --- /dev/null +++ b/crates/clash-verge-limiter/tests/properties.proptest-regressions @@ -0,0 +1,7 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc 0139d921e3faaf32821ee0c596b0d495ffc72ce94200b8d5a795883db56305e6 # shrinks to period = 56, start = 18446744073709551560 diff --git a/crates/clash-verge-limiter/tests/properties.rs b/crates/clash-verge-limiter/tests/properties.rs new file mode 100644 index 000000000..afd3d7f35 --- /dev/null +++ b/crates/clash-verge-limiter/tests/properties.rs @@ -0,0 +1,211 @@ +#![cfg(not(loom))] + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; + +use clash_verge_limiter::{Clock, Limiter}; +use proptest::prelude::*; +use proptest::test_runner::FileFailurePersistence; + +const CASES: u32 = 10_000; +const MAX_PERIOD_MS: u64 = 100_000; +const MAX_START_MS: u64 = 1_000_000; +const MAX_DELTA_MS: u64 = 10_000; + +/// Returns one clock value per call, in order. The test supplies exactly as +/// many values as the limiter will read. +struct SequenceClock { + values: Vec, + next: AtomicUsize, +} + +impl SequenceClock { + const fn new(values: Vec) -> Self { + Self { + values, + next: AtomicUsize::new(0), + } + } +} + +impl Clock for SequenceClock { + fn now_ms(&self) -> u64 { + let index = self.next.fetch_add(1, Ordering::SeqCst); + self.values[index] + } +} + +fn timestamps(start: u64, deltas: &[u64]) -> Vec { + let mut now = start; + let mut values = Vec::with_capacity(deltas.len() + 1); + values.push(now); + for delta in deltas { + now += delta; + values.push(now); + } + values +} + +proptest! { + #![proptest_config(ProptestConfig { + cases: CASES, + failure_persistence: Some(Box::new(FileFailurePersistence::Direct(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/properties.proptest-regressions" + )))), + ..ProptestConfig::default() + })] + + /// For positive periods and nondecreasing time, admission is equivalent to + /// reaching the next allowed timestamp after the previous admission. + #[test] + fn sequential_results_match_the_next_allowed_time_contract( + period in 1u64..=MAX_PERIOD_MS, + start in MAX_PERIOD_MS..=MAX_START_MS, + deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64), + ) { + let times = timestamps(start, &deltas); + let clock = SequenceClock::new(times.clone()); + let limiter = Limiter::new(Duration::from_millis(period), &clock); + let mut last_admitted = None; + + for now in times { + let expected = match last_admitted { + None => true, + Some(last) => now >= last + period, + }; + let actual = limiter.check(); + prop_assert!( + actual == expected, + "period={} now={} last={:?}", + period, + now, + last_admitted + ); + if actual { + last_admitted = Some(now); + } + } + } + + /// An admission at the period boundary is accepted, while a repeated or + /// pre-boundary check is rejected. + #[test] + fn period_boundary_and_repeated_checks_follow_the_period( + period in 1u64..=MAX_PERIOD_MS, + start in MAX_PERIOD_MS..=MAX_START_MS, + ) { + let boundary = start + period; + let clock = SequenceClock::new(vec![start, start, boundary - 1, boundary]); + let limiter = Limiter::new(Duration::from_millis(period), &clock); + + prop_assert!(limiter.check(), "first check at {}", start); + prop_assert!(!limiter.check(), "repeated check at {}", start); + prop_assert!(!limiter.check(), "pre-boundary check at {}", boundary - 1); + prop_assert!(limiter.check(), "boundary check at {}", boundary); + } + + /// Any two admitted timestamps in a monotonic sequence are separated by at + /// least one configured period. + #[test] + fn admitted_timestamps_are_at_least_one_period_apart( + period in 1u64..=MAX_PERIOD_MS, + start in MAX_PERIOD_MS..=MAX_START_MS, + deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64), + ) { + let times = timestamps(start, &deltas); + let clock = SequenceClock::new(times.clone()); + let limiter = Limiter::new(Duration::from_millis(period), &clock); + let mut admitted = Vec::new(); + + for now in times { + if limiter.check() { + admitted.push(now); + } + } + + for pair in admitted.windows(2) { + prop_assert!( + pair[1] - pair[0] >= period, + "period={} admitted pair={:?}", + period, + pair + ); + } + } + + /// A rejected duplicate at the current admission timestamp must not change + /// the outcomes of later checks. + #[test] + fn rejected_checks_do_not_change_future_admissions( + period in 1u64..=MAX_PERIOD_MS, + start in MAX_PERIOD_MS..=MAX_START_MS, + deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64), + ) { + let base_times = timestamps(start, &deltas); + let base_clock = SequenceClock::new(base_times.clone()); + let base = Limiter::new(Duration::from_millis(period), &base_clock); + let base_results: Vec = base_times.iter().map(|_| base.check()).collect(); + + let mut repeated_times = vec![start, start]; + repeated_times.extend_from_slice(&base_times[1..]); + let repeated_len = repeated_times.len(); + let repeated_clock = SequenceClock::new(repeated_times); + let repeated = Limiter::new(Duration::from_millis(period), &repeated_clock); + let repeated_results: Vec = (0..repeated_len).map(|_| repeated.check()).collect(); + + prop_assert!(repeated_results[0]); + prop_assert!(!repeated_results[1]); + prop_assert_eq!(&base_results[1..], &repeated_results[2..]); + } + + /// Every sub-millisecond period is represented as zero milliseconds, so it + /// must produce the same admissions as `Duration::ZERO`. This deliberately + /// does not assert a policy for zero periods. + #[test] + fn zero_and_submillisecond_periods_are_equivalent( + nanos in 0u64..1_000_000, + start in 0u64..=MAX_START_MS, + deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64), + ) { + let times = timestamps(start, &deltas); + let zero_clock = SequenceClock::new(times.clone()); + let zero = Limiter::new(Duration::ZERO, &zero_clock); + let submillisecond_clock = SequenceClock::new(times.clone()); + let submillisecond = + Limiter::new(Duration::from_nanos(nanos), &submillisecond_clock); + + for now in times { + prop_assert_eq!( + zero.check(), + submillisecond.check(), + "nanos={} now={}", + nanos, + now + ); + } + } + + /// Regression: timestamp arithmetic must not overflow near `u64::MAX`. + #[test] + fn extreme_timestamp_and_period_do_not_overflow( + period in 1u64..=1_000, + start in (u64::MAX - 1_000)..=u64::MAX, + ) { + let clock = SequenceClock::new(vec![start, start]); + let limiter = Limiter::new(Duration::from_millis(period), &clock); + + prop_assert!(limiter.check()); + prop_assert!(!limiter.check()); + } +} + +#[test] +fn max_timestamp_boundary_does_not_overflow() { + let clock = SequenceClock::new(vec![u64::MAX - 1, u64::MAX, u64::MAX]); + let limiter = Limiter::new(Duration::from_millis(1), &clock); + + assert!(limiter.check()); + assert!(limiter.check()); + assert!(!limiter.check()); +} From 39fd5e968be29fa0bb1524660add4cd04676f3e4 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:41:44 +0000 Subject: [PATCH 06/33] chore(deps): update cargo dependencies (#8811) * test(draft): cover conflict wakeup and busy layer * chore(deps): update cargo dependencies --------- Co-authored-by: Tunglies <77394545+Tunglies@users.noreply.github.com> Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- Cargo.lock | 159 ++++++++++++++++-- Cargo.toml | 4 +- crates/clash-verge-draft/tests/test_me.rs | 61 ++++++- .../Cargo.toml | 2 +- src-tauri/Cargo.toml | 6 +- 5 files changed, 212 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 65fc3aa64..abb378523 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -469,9 +469,9 @@ dependencies = [ [[package]] name = "backon" -version = "1.6.0" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cffb0e931875b666fc4fcb20fee52e9bbd1ef836fd9e9e04ec21555f9f85f7ef" +checksum = "aa51bf3329e243b4ceebb25fddaa797b3e2d225c733b215548ffd1fa99294d5d" dependencies = [ "fastrand", "gloo-timers", @@ -1202,9 +1202,9 @@ dependencies = [ "tristr", "warp", "webpki-roots", - "windows 0.62.2", + "windows 0.101.0", "windows-service", - "windows-sys 0.61.2", + "windows-sys 0.101.0", "winreg 0.56.0", "zip", ] @@ -3038,9 +3038,9 @@ dependencies = [ [[package]] name = "gloo-timers" -version = "0.3.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994" +checksum = "a4460540da666acdb5722b2a62ac47d18f627fcfc0c728d04dc7226b3f6d40a7" dependencies = [ "futures-channel", "futures-core", @@ -6332,9 +6332,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.46" +version = "0.23.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +checksum = "4ac0e747c10d93d873fd4c50b26ef47ad92d1bfb48f6922003bb514070f6e88c" dependencies = [ "aws-lc-rs", "log", @@ -7270,9 +7270,9 @@ dependencies = [ [[package]] name = "sysinfo" -version = "0.40.4" +version = "0.40.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e80749408e2d8bec0ffa303012cf4e1b3b355f4a09087b4fdf7473680f6a2de" +checksum = "0ebe31c61260d7bc4bfc204a2d096c428a4c9ef59ca48bfa693d17fec4f129ad" dependencies = [ "libc", "memchr", @@ -9457,6 +9457,20 @@ dependencies = [ "windows-numerics 0.3.1", ] +[[package]] +name = "windows" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa86febe1d5f623619e56067e9c6f84c368cf94f9f36df738875a0dc5affd752" +dependencies = [ + "windows-collections 0.101.0", + "windows-core 0.101.0", + "windows-future 0.101.0", + "windows-numerics 0.101.0", + "windows-reference", + "windows-time", +] + [[package]] name = "windows-collections" version = "0.2.0" @@ -9475,6 +9489,15 @@ dependencies = [ "windows-core 0.62.2", ] +[[package]] +name = "windows-collections" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c988c3f56b2a0cf740d2837950f25c43539ea6c004a5244085ce6749e1c61f29" +dependencies = [ + "windows-core 0.101.0", +] + [[package]] name = "windows-core" version = "0.61.2" @@ -9514,6 +9537,19 @@ dependencies = [ "windows-strings 0.100.0", ] +[[package]] +name = "windows-core" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27abecb0bac0f1602c4e0d0c885aca58e9a2a25d852135b96e4d0f9daf989aac" +dependencies = [ + "windows-implement 0.101.0", + "windows-interface 0.101.0", + "windows-link 0.101.0", + "windows-result 0.101.0", + "windows-strings 0.101.0", +] + [[package]] name = "windows-future" version = "0.2.1" @@ -9536,6 +9572,17 @@ dependencies = [ "windows-threading 0.2.1", ] +[[package]] +name = "windows-future" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c1de418ec955682054a08c9a2925719c76af9408397fd89fc7c2418bd3b2551" +dependencies = [ + "windows-core 0.101.0", + "windows-link 0.101.0", + "windows-threading 0.101.0", +] + [[package]] name = "windows-implement" version = "0.60.2" @@ -9558,6 +9605,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "windows-implement" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33a7f9008fbe08b219a4d9b2db1ceff71b9ed7f0e02472a3bf2046a2b258f933" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows-interface" version = "0.59.3" @@ -9580,6 +9638,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "windows-interface" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67d1b654cf5aa8120c8c796fe6c88f0e0407512c341e83ea7bb65b933b596474" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows-link" version = "0.1.3" @@ -9598,6 +9667,12 @@ version = "0.100.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b39de7c7fe78858b0144c50c3fc000bab3be17d5e9b85b1053871693c7f7415" +[[package]] +name = "windows-link" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4e57b2aae53a240c62b65069a63eaf8d5fa747f5d0d8e670c5210a98847bce4" + [[package]] name = "windows-numerics" version = "0.2.0" @@ -9618,6 +9693,25 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-numerics" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d54e417b9761be91da0ab663a5e393e9e54820e55fa9a1d902b978bda3a71ba" +dependencies = [ + "windows-core 0.101.0", +] + +[[package]] +name = "windows-reference" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0a017bb8eab108f37103deaa4eaad24ce324c30c6f72628a59250be24c87466" +dependencies = [ + "windows-core 0.101.0", + "windows-time", +] + [[package]] name = "windows-registry" version = "0.6.1" @@ -9656,6 +9750,15 @@ dependencies = [ "windows-link 0.100.0", ] +[[package]] +name = "windows-result" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a02baed928b12dbc90e3a37d1504af179d275e13427510f6bcded0607c9251a7" +dependencies = [ + "windows-link 0.101.0", +] + [[package]] name = "windows-service" version = "0.8.1" @@ -9694,6 +9797,15 @@ dependencies = [ "windows-link 0.100.0", ] +[[package]] +name = "windows-strings" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3301e29c2a308301e0e84fe4242684b1310864f3e15aba65b4ae41f1a44f7f95" +dependencies = [ + "windows-link 0.101.0", +] + [[package]] name = "windows-sys" version = "0.45.0" @@ -9748,6 +9860,15 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-sys" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed2df9f5f458664c87437f6758f0d93085b06433bf66b2b84c23c19f3d2012c" +dependencies = [ + "windows-link 0.101.0", +] + [[package]] name = "windows-targets" version = "0.42.2" @@ -9829,6 +9950,24 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-threading" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e1e41d72a0564ebe2cbb9487ed918acfc71d541683b84816a424dc3c7939592" +dependencies = [ + "windows-link 0.101.0", +] + +[[package]] +name = "windows-time" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "186ef23b1710095987bf5281bd19e3669934d4353946f24cbdcfd0ed4f2deff6" +dependencies = [ + "windows-core 0.101.0", +] + [[package]] name = "windows-version" version = "0.1.7" diff --git a/Cargo.toml b/Cargo.toml index dc750f7af..8fe876bf9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,7 +68,7 @@ tauri-plugin-clipboard-manager = "2.5.0" parking_lot = "0.13.0" anyhow = "1.0.105" futures = "0.3.34" -loom = "0.7" +loom = "0.7.3" proptest = "1.12.0" chrono = "0.4.45" criterion = { version = "0.8.2", features = ["async_tokio"] } @@ -97,7 +97,7 @@ socket2 = "0.6.5" # *** For Windows platform only *** deelevate = "0.2.0" -windows-sys = { version = "0.61.2", features = [ +windows-sys = { version = "0.101.0", features = [ "Win32_Foundation", "Win32_NetworkManagement_IpHelper", "Win32_Networking_WinSock", diff --git a/crates/clash-verge-draft/tests/test_me.rs b/crates/clash-verge-draft/tests/test_me.rs index af0e403ec..44c95c99e 100644 --- a/crates/clash-verge-draft/tests/test_me.rs +++ b/crates/clash-verge-draft/tests/test_me.rs @@ -1,7 +1,14 @@ -use std::sync::Arc; +use std::{ + pin::pin, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + task::{Context, Poll, Wake, Waker}, +}; use clash_verge_draft::{Draft, DraftTransaction}; -use tokio::sync::Notify; +use tokio::sync::{Notify, oneshot}; #[derive(Clone, Debug, Default, PartialEq)] struct Config { @@ -78,6 +85,47 @@ async fn async_update_rejects_a_changed_committed_value() -> anyhow::Result<()> Ok(()) } +#[test] +fn parked_async_update_is_woken_after_optimistic_conflict() { + #[derive(Default)] + struct WakeFlag(AtomicBool); + + impl Wake for WakeFlag { + fn wake(self: Arc) { + self.0.store(true, Ordering::Relaxed); + } + } + + let draft = Draft::new(1); + let (finish, finished) = oneshot::channel(); + let mut owner = pin!(draft.with_data_modify(|value| async move { + finished.await?; + Ok((value + 10, ())) + })); + let mut owner_context = Context::from_waker(Waker::noop()); + assert!(owner.as_mut().poll(&mut owner_context).is_pending()); + + let wake_flag = Arc::new(WakeFlag::default()); + let waker = Waker::from(Arc::clone(&wake_flag)); + let mut waiter_context = Context::from_waker(&waker); + let mut waiter = pin!(draft.with_data_modify(|value| async move { Ok((value + 1, value)) })); + + // The fast retry wakes once before the waiter parks on Notify. + assert!(waiter.as_mut().poll(&mut waiter_context).is_pending()); + assert!(wake_flag.0.swap(false, Ordering::Relaxed), "fast retry did not wake"); + assert!(waiter.as_mut().poll(&mut waiter_context).is_pending()); + assert!(!wake_flag.0.load(Ordering::Relaxed), "waiter did not park"); + + draft.edit_draft(|value| *value = 7); + draft.apply(); + assert!(finish.send(()).is_ok()); + assert!(matches!(owner.as_mut().poll(&mut owner_context), Poll::Ready(Err(_)))); + assert_eq!(**draft.data_arc(), 7); + assert!(wake_flag.0.load(Ordering::Relaxed), "parked waiter was not notified"); + assert!(matches!(waiter.as_mut().poll(&mut waiter_context), Poll::Ready(Ok(7)))); + assert_eq!(**draft.data_arc(), 8); +} + #[test] fn transaction_commits_every_layer() -> anyhow::Result<()> { let first = Draft::new(1_u8); @@ -112,10 +160,15 @@ fn dropped_transaction_rolls_every_layer_back() -> anyhow::Result<()> { #[test] fn transaction_claims_are_exclusive_and_release_partial_claims() -> anyhow::Result<()> { let first = Draft::new(1_u8); - let second = Draft::new(2_u8); + let second = Draft::new(2_u16); let held = DraftTransaction::begin(vec![&second])?; - assert!(DraftTransaction::begin(vec![&first, &second]).is_err()); + let busy = DraftTransaction::begin(vec![&first, &second]) + .err() + .ok_or_else(|| anyhow::anyhow!("transaction claimed an already-held layer"))?; + let layer = std::any::type_name::(); + assert_eq!(busy.layer, layer); + assert!(busy.to_string().contains(layer)); let available = DraftTransaction::begin(vec![&first])?; drop(available); diff --git a/crates/tauri-plugin-clash-verge-sysinfo/Cargo.toml b/crates/tauri-plugin-clash-verge-sysinfo/Cargo.toml index 883a6d951..e855a8842 100644 --- a/crates/tauri-plugin-clash-verge-sysinfo/Cargo.toml +++ b/crates/tauri-plugin-clash-verge-sysinfo/Cargo.toml @@ -12,7 +12,7 @@ parking_lot = { workspace = true } serde = { workspace = true, features = ["derive"] } # sysinfo 0.38.2 conflicts with dark-light # see https://github.com/GuillaumeGomez/sysinfo/issues/1623 -sysinfo = { version = "0.40.4", default-features = false, features = ["network", "system"] } +sysinfo = { version = "0.40.5", default-features = false, features = ["network", "system"] } [target.'cfg(not(windows))'.dependencies] libc = "0.2.191" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 87618160a..a5760618e 100755 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -86,7 +86,7 @@ getrandom = "0.4.3" futures = { workspace = true } gethostname = "1.1.0" tauri-plugin-notification = "2.8.1" -backon = { version = "1.6.0", features = ["tokio-sleep"] } +backon = { version = "1.7.0", features = ["tokio-sleep"] } tauri-plugin-http = "2.9.0" tracing = { workspace = true } tauri-plugin-devtools = { version = "2.2.3", optional = true } @@ -97,7 +97,7 @@ clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verg ] } arc-swap = "1.9.5" tokio-rustls = "0.26.6" -rustls = { version = "0.23.46", features = ["ring"] } +rustls = { version = "0.23.47", features = ["ring"] } webpki-roots = "1.0.12" dark-light = "3.0.0" bytes = "1.12.2" @@ -143,7 +143,7 @@ quick-xml = "0.42.0" runas = "=1.2.0" winreg = "0.56.0" windows-service = "0.8.1" -windows = { version = "0.62.2", features = [ +windows = { version = "0.101.0", features = [ "Win32_System_Com", "Win32_System_Ole", "Win32_System_TaskScheduler", From 9bdd2c062399750f5461fe11c37b56d53f0bd89a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:34:41 +0000 Subject: [PATCH 07/33] build(deps): bump cookie (#8807) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps the cargo group with 1 update in the / directory: [cookie](https://github.com/rwf2/cookie-rs). Updates `cookie` from 0.18.1 to 0.18.3 - [Changelog](https://github.com/rwf2/cookie-rs/blob/master/CHANGELOG.md) - [Commits](https://github.com/rwf2/cookie-rs/compare/0.18.1...0.18.3) --- updated-dependencies: - dependency-name: cookie dependency-version: 0.18.3 dependency-type: indirect dependency-group: cargo ... Signed-off-by: dependabot[bot] Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index abb378523..102c03a3d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1515,9 +1515,9 @@ dependencies = [ [[package]] name = "cookie" -version = "0.18.1" +version = "0.18.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" +checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a" dependencies = [ "percent-encoding", "time", From 16ef6fbc34fb5e51d2b974c58f6530b63404f45d Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:16:26 +0800 Subject: [PATCH 08/33] fix(i18n): resolve startup locales consistently MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Prefer a supported saved language over the cache and browser locale. Align frontend alias resolution with Rust and ignore unsupported saved values when the layout mounts so they cannot overwrite the fallback. In Rust, walk borrowed prefixes instead of rebuilding strings. This preserves locale resolution and removes quadratic work on long tags. Across all 14 shipped locale IDs (equally weighted), median lookup time fell from 40.0 to 22.4 ns and heap allocations fell from 4 to 2 per lookup. A synthetic 64 KiB tag fell from 771 ms to 240 µs. --- crates/clash-verge-i18n/src/lib.rs | 13 +++++--- src/hooks/use-i18n.ts | 26 ++++----------- src/services/i18n.ts | 52 +++++++++++++++++++---------- src/services/preload.ts | 53 +++++------------------------- 4 files changed, 57 insertions(+), 87 deletions(-) diff --git a/crates/clash-verge-i18n/src/lib.rs b/crates/clash-verge-i18n/src/lib.rs index 6989dfb7d..9a99d23d2 100644 --- a/crates/clash-verge-i18n/src/lib.rs +++ b/crates/clash-verge-i18n/src/lib.rs @@ -23,17 +23,20 @@ fn resolve_supported_language(language: &str) -> Option> { return None; } let normalized = language.to_lowercase().replace('_', "-"); - let segments: Vec<&str> = normalized.split('-').collect(); - for i in (1..=segments.len()).rev() { - let prefix = segments[..i].join("-"); - if let Some(alias) = locale_alias(&prefix) + let mut prefix = normalized.as_str(); + loop { + if let Some(alias) = locale_alias(prefix) && let Some(found) = SUPPORTED_LOCALES.iter().find(|l| l.eq_ignore_ascii_case(alias)) { return Some(found.clone()); } - if let Some(found) = SUPPORTED_LOCALES.iter().find(|l| l.eq_ignore_ascii_case(&prefix)) { + if let Some(found) = SUPPORTED_LOCALES.iter().find(|l| l.eq_ignore_ascii_case(prefix)) { return Some(found.clone()); } + let Some((shorter, _)) = prefix.rsplit_once('-') else { + break; + }; + prefix = shorter; } None } diff --git a/src/hooks/use-i18n.ts b/src/hooks/use-i18n.ts index 1f07b11ea..6eb719543 100644 --- a/src/hooks/use-i18n.ts +++ b/src/hooks/use-i18n.ts @@ -1,21 +1,16 @@ -import { useState, useCallback } from 'react' +import { useCallback } from 'react' import { useTranslation } from 'react-i18next' -import { - changeLanguage, - resolveLanguage, - supportedLanguages, -} from '@/services/i18n' +import { changeLanguage, resolveSupportedLanguage } from '@/services/i18n' export const useI18n = () => { - const { i18n, t } = useTranslation() - const [isLoading, setIsLoading] = useState(false) + const { i18n } = useTranslation() const switchLanguage = useCallback( async (language: string) => { - const targetLanguage = resolveLanguage(language) + const targetLanguage = resolveSupportedLanguage(language) - if (!supportedLanguages.includes(targetLanguage)) { + if (!targetLanguage) { console.warn(`Unsupported language: ${language}`) return } @@ -24,23 +19,14 @@ export const useI18n = () => { return } - setIsLoading(true) try { await changeLanguage(targetLanguage) } catch (error) { console.error('Failed to change language:', error) - } finally { - setIsLoading(false) } }, [i18n.language], ) - return { - currentLanguage: i18n.language, - supportedLanguages, - switchLanguage, - isLoading, - t, - } + return { switchLanguage } } diff --git a/src/services/i18n.ts b/src/services/i18n.ts index 588de9ea5..71bc67aab 100644 --- a/src/services/i18n.ts +++ b/src/services/i18n.ts @@ -24,27 +24,43 @@ const LANGUAGE_STORAGE_KEY = 'verge-language' const normalizeLanguage = (language?: string) => language?.toLowerCase().replace(/_/g, '-') -export const resolveLanguage = (language?: string) => { +// Aliases whose catalog differs from the base tag, as in clash-verge-i18n. +const languageAliases = new Map([ + ['ja', 'jp'], + ['zh-tw', 'zhtw'], + ['zh-hk', 'zhtw'], + ['zh-hant', 'zhtw'], + ['zh-mo', 'zhtw'], + ['zh-cht', 'zhtw'], +]) +const maxLanguageTagLength = Math.max( + ...[...supportedLanguages, ...languageAliases.keys()].map( + (tag) => tag.length, + ), +) + +export const resolveSupportedLanguage = (language?: string) => { const normalized = normalizeLanguage(language) - if (!normalized) { - return FALLBACK_LANGUAGE + if (!normalized) return undefined + + // Longer prefixes cannot match a catalog or alias. + let end = + normalized.length <= maxLanguageTagLength + ? normalized.length + : normalized.lastIndexOf('-', maxLanguageTagLength) + while (end > 0) { + const prefix = normalized.slice(0, end) + const alias = languageAliases.get(prefix) + if (alias) return alias + if (supportedLanguages.includes(prefix)) return prefix + end = normalized.lastIndexOf('-', end - 1) } - - if (normalized === 'zh-tw') return 'zhtw' - if (normalized === 'zh-cn') return 'zh' - - if (supportedLanguages.includes(normalized)) { - return normalized - } - - const baseLanguage = normalized.split('-')[0] - if (supportedLanguages.includes(baseLanguage)) { - return baseLanguage - } - - return FALLBACK_LANGUAGE + return undefined } +export const resolveLanguage = (language?: string) => + resolveSupportedLanguage(language) ?? FALLBACK_LANGUAGE + const getLanguageStorage = () => { if (typeof window === 'undefined') return null try { @@ -54,7 +70,7 @@ const getLanguageStorage = () => { } } -export const cacheLanguage = (language: string) => { +const cacheLanguage = (language: string) => { const storage = getLanguageStorage() if (!storage) return diff --git a/src/services/preload.ts b/src/services/preload.ts index 28729c75f..4d593ed8b 100644 --- a/src/services/preload.ts +++ b/src/services/preload.ts @@ -1,9 +1,9 @@ import { getVergeConfig } from './cmds' import { - cacheLanguage, getCachedLanguage, initializeLanguage, resolveLanguage, + resolveSupportedLanguage, } from './i18n' let vergeConfigCache: IVergeConfig | null | undefined @@ -57,50 +57,15 @@ const preloadConfig = async () => { } } -const preloadLanguage = async ( - vergeConfig?: IVergeConfig | null, - loadConfig: () => Promise = preloadConfig, -) => { - const cachedLanguage = getCachedLanguage() - if (cachedLanguage) { - return cachedLanguage - } - - let resolvedConfig = vergeConfig - - if (resolvedConfig === undefined) { - try { - resolvedConfig = await loadConfig() - } catch (error) { - console.warn( - '[preload.ts] Failed to read language from Verge config:', - error, - ) - resolvedConfig = null - } - } - - const languageFromConfig = resolvedConfig?.language - if (languageFromConfig) { - const resolved = resolveLanguage(languageFromConfig) - cacheLanguage(resolved) - return resolved - } - - const browserLanguage = resolveLanguage( - typeof navigator !== 'undefined' ? navigator.language : undefined, - ) - cacheLanguage(browserLanguage) - return browserLanguage -} - export const preloadAppData = async () => { - const configPromise = preloadConfig() - const initialLanguage = await preloadLanguage(undefined, () => configPromise) - const [config] = await Promise.all([ - configPromise, - initializeLanguage(initialLanguage), - ]) + const config = await preloadConfig() + const initialLanguage = + resolveSupportedLanguage(config?.language ?? undefined) ?? + getCachedLanguage() ?? + resolveLanguage( + typeof navigator !== 'undefined' ? navigator.language : undefined, + ) + await initializeLanguage(initialLanguage) const initialThemeMode = resolveThemeMode(config) return { initialThemeMode } } From a76818326d7a1c0c049dc158709dc76990d0fb1f Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 08:07:50 +0000 Subject: [PATCH 09/33] chore(deps): update tauri (#8764) * chore(deps): update tauri * fix(installer): align NSIS locale variables with Tauri 2.13 * chore(tray): migrate template icons to Tauri 2.13 APIs * fix(core): resolve the bundled core for validation fingerprints * fix(deps): resolve Tauri 2.13 with the patched WebDriver * fix(tray): wake the main window from Linux tray clicks Use StatusNotifierItem activation to wake the dashboard, including lightweight mode. Closes #8517 * fix(tray): gate template icon handling to macOS at compile time * fix(deps): select GTK3 for Linux dialogs * fix(linux): return when the startup dialog cannot initialize GTK --------- Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Tunglies <77394545+Tunglies@users.noreply.github.com> --- Cargo.lock | 818 ++++++++--------------- Cargo.toml | 3 +- Changelog.md | 1 + package.json | 4 +- pnpm-lock.yaml | 122 ++-- src-tauri/Cargo.toml | 18 +- src-tauri/packages/windows/installer.nsi | 19 +- src-tauri/src/core/tray/mod.rs | 63 +- src-tauri/src/core/validate.rs | 8 +- src-tauri/src/utils/startup.rs | 23 + 10 files changed, 437 insertions(+), 642 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 102c03a3d..520ee55c3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -345,25 +345,25 @@ dependencies = [ [[package]] name = "atk" -version = "0.18.2" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b" +checksum = "780a62f5d3373a8461bdc9258527bd03fe9299779446681199005712b24cc1d7" dependencies = [ "atk-sys", - "glib 0.18.5", + "glib", "libc", ] [[package]] name = "atk-sys" -version = "0.18.2" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086" +checksum = "56fd0f13d1dedae306538653b8e42034a2260d1ac3ee920e7a5c31475d7184a5" dependencies = [ - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "glib-sys", + "gobject-sys", "libc", - "system-deps 6.2.2", + "system-deps 9.0.1", ] [[package]] @@ -508,30 +508,15 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" -[[package]] -name = "bit-set" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" -dependencies = [ - "bit-vec 0.8.0", -] - [[package]] name = "bit-set" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" dependencies = [ - "bit-vec 0.10.2", + "bit-vec", ] -[[package]] -name = "bit-vec" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" - [[package]] name = "bit-vec" version = "0.10.2" @@ -778,7 +763,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" dependencies = [ "once_cell", - "proc-macro-crate 3.5.0", + "proc-macro-crate", "proc-macro2", "quote", "syn 3.0.5", @@ -882,27 +867,25 @@ dependencies = [ [[package]] name = "cairo-rs" -version = "0.18.5" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2" +checksum = "62bf7f026ae17fe688938438ec1da2b69f69832f1428a17258f6ee9a7f6e1815" dependencies = [ "bitflags 2.13.2", "cairo-sys-rs", - "glib 0.18.5", + "glib", "libc", - "once_cell", - "thiserror 1.0.69", ] [[package]] name = "cairo-sys-rs" -version = "0.18.2" +version = "0.22.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51" +checksum = "ee548131103ad8f698c6725669647b9c757b3b66992dd6a026037596417bee21" dependencies = [ - "glib-sys 0.18.1", + "glib-sys", "libc", - "system-deps 6.2.2", + "system-deps 9.0.1", ] [[package]] @@ -926,18 +909,19 @@ dependencies = [ [[package]] name = "cargo-platform" -version = "0.1.9" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea" +checksum = "dd0061da739915fae12ea00e16397555ed4371a6bb285431aab930f61b0aa4ba" dependencies = [ "serde", + "serde_core", ] [[package]] name = "cargo_metadata" -version = "0.19.2" +version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba" +checksum = "ef987d17b0a113becdd19d3d0022d04d7ef41f9efe4f3fb63ac44ba61df3ade9" dependencies = [ "camino", "cargo-platform", @@ -1002,16 +986,6 @@ dependencies = [ "web-time", ] -[[package]] -name = "cfg-expr" -version = "0.15.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" -dependencies = [ - "smallvec", - "target-lexicon 0.12.16", -] - [[package]] name = "cfg-expr" version = "0.20.9" @@ -1019,7 +993,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe4ece8474b5f766c63426647e7b4b316b67431ade1036a8313cee24a03ae917" dependencies = [ "smallvec", - "target-lexicon 0.13.5", + "target-lexicon", ] [[package]] @@ -1151,6 +1125,7 @@ dependencies = [ "futures", "gethostname", "getrandom 0.4.3", + "gtk", "http-body-util", "libc", "log", @@ -1165,7 +1140,7 @@ dependencies = [ "quick-xml 0.42.0", "reqwest 0.13.5", "reqwest_dav", - "rfd 0.18.0", + "rfd", "runas", "rustls", "serde", @@ -1723,6 +1698,15 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.22" @@ -1758,14 +1742,14 @@ dependencies = [ [[package]] name = "cssparser" -version = "0.37.0" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98" +checksum = "11119743ad110e8c1bdccd930d7f5c30c99e5fc76a7b63ec9807e84eef0c5f59" dependencies = [ "cssparser-macros", "dtoa-short", "itoa", - "phf 0.13.1", + "phf 0.14.0", "smallvec", ] @@ -2176,11 +2160,11 @@ dependencies = [ [[package]] name = "dom_query" -version = "0.28.0" +version = "0.30.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc" +checksum = "b35b4f772a1a8b88e5545a67c2d3a62a93d4edccc5a68f2145fe52e39c96d275" dependencies = [ - "bit-set 0.8.0", + "bit-set", "cssparser", "foldhash 0.2.0", "html5ever", @@ -2675,100 +2659,100 @@ dependencies = [ [[package]] name = "gdk" -version = "0.18.2" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691" +checksum = "50b79a7fa8b0e9fe6c77118e48cc00a23eb41052c190434d9cda7746418efca6" dependencies = [ "cairo-rs", "gdk-pixbuf", "gdk-sys", "gio", - "glib 0.18.5", + "glib", "libc", "pango", ] [[package]] name = "gdk-pixbuf" -version = "0.18.5" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec" +checksum = "aabb44971913eb9f7bf6747f6e88889386007d8ce8cfd1ca2735751b664e7079" dependencies = [ "gdk-pixbuf-sys", "gio", - "glib 0.18.5", + "glib", "libc", - "once_cell", ] [[package]] name = "gdk-pixbuf-sys" -version = "0.18.0" +version = "0.22.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7" +checksum = "9d5209294ba3775f9b650bf78bfadeba4332089f2329b3e2f6ce0a4957a45bff" dependencies = [ - "gio-sys 0.18.1", - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "gio-sys", + "glib-sys", + "gobject-sys", "libc", - "system-deps 6.2.2", + "system-deps 9.0.1", ] [[package]] name = "gdk-sys" -version = "0.18.2" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7" +checksum = "463ac2e2f204918dcaeb3c34810bd7fe94448d2b8d4fa13a5ab45a4fc3e88e50" dependencies = [ "cairo-sys-rs", "gdk-pixbuf-sys", - "gio-sys 0.18.1", - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "gio-sys", + "glib-sys", + "gobject-sys", "libc", "pango-sys", "pkg-config", - "system-deps 6.2.2", + "system-deps 9.0.1", ] [[package]] name = "gdkwayland-sys" -version = "0.18.2" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69" +checksum = "82559ece0c0952519a3513ecd90638e5db59e00c851f1d3ea05ac7ff2a46942e" dependencies = [ "gdk-sys", - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "glib-sys", + "gobject-sys", "libc", "pkg-config", - "system-deps 6.2.2", + "system-deps 9.0.1", ] [[package]] name = "gdkx11" -version = "0.18.2" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3caa00e14351bebbc8183b3c36690327eb77c49abc2268dd4bd36b856db3fbfe" +checksum = "bad7a698a74652ddba8dc348f9933f6f209fbcf3ab318f2c1fd72c6b2fa99505" dependencies = [ "gdk", "gdkx11-sys", "gio", - "glib 0.18.5", + "glib", "libc", "x11", ] [[package]] name = "gdkx11-sys" -version = "0.18.2" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d" +checksum = "a103facf2056ce28125a49501f98beb01d1e3c9477257a8e05cfc5d3d677709e" dependencies = [ + "cairo-sys-rs", "gdk-sys", - "glib-sys 0.18.1", + "glib-sys", "libc", - "system-deps 6.2.2", + "system-deps 9.0.1", "x11", ] @@ -2854,54 +2838,39 @@ dependencies = [ [[package]] name = "gio" -version = "0.18.4" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73" +checksum = "536990682bab3b8bf68a78d298ccae69702a114290b096edf2bec6eb2e4013b3" dependencies = [ "futures-channel", "futures-core", "futures-io", "futures-util", - "gio-sys 0.18.1", - "glib 0.18.5", + "gio-sys", + "glib", "libc", - "once_cell", "pin-project-lite", "smallvec", - "thiserror 1.0.69", ] [[package]] name = "gio-sys" -version = "0.18.1" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2" +checksum = "b9c253490f9a475047f109bf6ccb68c407e9d186b7bfab01849188f4e669e669" dependencies = [ - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "glib-sys", + "gobject-sys", "libc", - "system-deps 6.2.2", - "winapi", -] - -[[package]] -name = "gio-sys" -version = "0.21.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0071fe88dba8e40086c8ff9bbb62622999f49628344b1d1bf490a48a29d80f22" -dependencies = [ - "glib-sys 0.21.5", - "gobject-sys 0.21.5", - "libc", - "system-deps 7.0.8", + "system-deps 9.0.1", "windows-sys 0.61.2", ] [[package]] name = "glib" -version = "0.18.5" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5" +checksum = "c9c4cbf1972a07741ae5ce9b23a582a90efc69745fc713f8b037b8d962f604da" dependencies = [ "bitflags 2.13.2", "futures-channel", @@ -2909,33 +2878,10 @@ dependencies = [ "futures-executor", "futures-task", "futures-util", - "gio-sys 0.18.1", - "glib-macros 0.18.5", - "glib-sys 0.18.1", - "gobject-sys 0.18.0", - "libc", - "memchr", - "once_cell", - "smallvec", - "thiserror 1.0.69", -] - -[[package]] -name = "glib" -version = "0.21.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16de123c2e6c90ce3b573b7330de19be649080ec612033d397d72da265f1bd8b" -dependencies = [ - "bitflags 2.13.2", - "futures-channel", - "futures-core", - "futures-executor", - "futures-task", - "futures-util", - "gio-sys 0.21.5", - "glib-macros 0.21.5", - "glib-sys 0.21.5", - "gobject-sys 0.21.5", + "gio-sys", + "glib-macros", + "glib-sys", + "gobject-sys", "libc", "memchr", "smallvec", @@ -2943,49 +2889,24 @@ dependencies = [ [[package]] name = "glib-macros" -version = "0.18.5" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc" +checksum = "d4014e54e2049108c93cf278b64e89f490849402e09b455a25dfa2098cc35093" dependencies = [ - "heck 0.4.1", - "proc-macro-crate 2.0.0", - "proc-macro-error", + "heck", "proc-macro2", "quote", - "syn 2.0.119", -] - -[[package]] -name = "glib-macros" -version = "0.21.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf59b675301228a696fe01c3073974643365080a76cc3ed5bc2cbc466ad87f17" -dependencies = [ - "heck 0.5.0", - "proc-macro-crate 3.5.0", - "proc-macro2", - "quote", - "syn 2.0.119", + "syn 3.0.5", ] [[package]] name = "glib-sys" -version = "0.18.1" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898" +checksum = "8b01e8b94529c2698b98f765b887f1e001b76195c1e25d1139aa9336019e745d" dependencies = [ "libc", - "system-deps 6.2.2", -] - -[[package]] -name = "glib-sys" -version = "0.21.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d95e1a3a19ae464a7286e14af9a90683c64d70c02532d88d87ce95056af3e6c" -dependencies = [ - "libc", - "system-deps 7.0.8", + "system-deps 9.0.1", ] [[package]] @@ -3050,24 +2971,13 @@ dependencies = [ [[package]] name = "gobject-sys" -version = "0.18.0" +version = "0.22.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44" +checksum = "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834" dependencies = [ - "glib-sys 0.18.1", + "glib-sys", "libc", - "system-deps 6.2.2", -] - -[[package]] -name = "gobject-sys" -version = "0.21.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dca35da0d19a18f4575f3cb99fe1c9e029a2941af5662f326f738a21edaf294" -dependencies = [ - "glib-sys 0.21.5", - "libc", - "system-deps 7.0.8", + "system-deps 9.0.1", ] [[package]] @@ -3082,9 +2992,9 @@ dependencies = [ [[package]] name = "gtk" -version = "0.18.2" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a" +checksum = "a86cafafc177054a1d555a0b302044d2b5f82e1c1e23d152a7ba252dc6bfced0" dependencies = [ "atk", "cairo-rs", @@ -3093,7 +3003,7 @@ dependencies = [ "gdk", "gdk-pixbuf", "gio", - "glib 0.18.5", + "glib", "gtk-sys", "gtk3-macros", "libc", @@ -3103,33 +3013,32 @@ dependencies = [ [[package]] name = "gtk-sys" -version = "0.18.2" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414" +checksum = "a0e6f055c4a2ce6598b32373595b0c9985f1c7cc448afe4f09fee33fb738b488" dependencies = [ "atk-sys", "cairo-sys-rs", "gdk-pixbuf-sys", "gdk-sys", - "gio-sys 0.18.1", - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "gio-sys", + "glib-sys", + "gobject-sys", "libc", "pango-sys", - "system-deps 6.2.2", + "system-deps 9.0.1", ] [[package]] name = "gtk3-macros" -version = "0.18.2" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d" +checksum = "5fcce21fcb0c4c4fc48bab8d4eee5aacdb361f85d234756430e6e793bd3d95cf" dependencies = [ - "proc-macro-crate 1.3.1", - "proc-macro-error", + "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.5", ] [[package]] @@ -3231,12 +3140,6 @@ dependencies = [ "http", ] -[[package]] -name = "heck" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" - [[package]] name = "heck" version = "0.5.0" @@ -3286,12 +3189,13 @@ dependencies = [ [[package]] name = "html5ever" -version = "0.39.0" +version = "0.40.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8" +checksum = "456a1a377e608e555d22ddab27ac0114bc7a7b4199078108e34c2aeae6c9b130" dependencies = [ "log", "markup5ever", + "memchr", ] [[package]] @@ -3792,25 +3696,25 @@ checksum = "4d3667095d64c3ecffc96463a21157b04bf3e252f6e8d5750b20c02e33c194e3" [[package]] name = "javascriptcore-rs" -version = "1.1.2" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc" +checksum = "3806310bf87dd1858b0cd99dad0c49efb06ee56d346e77385d89e7f8db04f5d0" dependencies = [ - "bitflags 1.3.2", - "glib 0.18.5", + "bitflags 2.13.2", + "glib", "javascriptcore-rs-sys", ] [[package]] name = "javascriptcore-rs-sys" -version = "1.1.1" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124" +checksum = "2844fb472dd4f76e43a15ee27d2f140b9113adeab21403be084fb653d7a704f9" dependencies = [ - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "glib-sys", + "gobject-sys", "libc", - "system-deps 6.2.2", + "system-deps 9.0.1", ] [[package]] @@ -3962,9 +3866,9 @@ dependencies = [ [[package]] name = "json-patch" -version = "4.2.0" +version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72" +checksum = "aa295c8f71b9bad32d060e0e145f96dcba0cc6c6171e129646140d1c96b05617" dependencies = [ "jsonptr", "serde", @@ -3974,9 +3878,9 @@ dependencies = [ [[package]] name = "jsonptr" -version = "0.7.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe" +checksum = "72c22d99362c7aac7d77efab6b49c2181674b165d7e6e7c755b3432ded64bf51" dependencies = [ "serde", "serde_json", @@ -4030,6 +3934,26 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "ksni" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49a7ac89853917f01d75f6bac3e7c8e282ae621dd63fbbfc50fe331304fa580" +dependencies = [ + "arc-swap", + "async-executor", + "async-io", + "async-lock", + "crossbeam-queue", + "futures-channel", + "futures-lite", + "futures-util", + "pastey", + "serde", + "task-local", + "zbus", +] + [[package]] name = "lazy-regex" version = "3.6.1" @@ -4061,26 +3985,22 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libappindicator" -version = "0.9.0" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a" +checksum = "f57fd42f20edd22ee374ebcedda7bdecd1d5d1e76f11880d9ff2898ed2150d76" dependencies = [ - "glib 0.18.5", "gtk", - "gtk-sys", "libappindicator-sys", - "log", ] [[package]] name = "libappindicator-sys" -version = "0.9.0" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf" +checksum = "0b76d3d67eb285f611b14654cd097f52eb7e83acc2b59913147f8ac695b61149" dependencies = [ "gtk-sys", "libloading", - "once_cell", ] [[package]] @@ -4106,12 +4026,12 @@ dependencies = [ [[package]] name = "libloading" -version = "0.7.4" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +checksum = "a1832accd5a4ca2795ace4d05d15c4039be15b62d3b950eff99746a990e3cc10" dependencies = [ "cfg-if", - "winapi", + "windows-link 0.2.1", ] [[package]] @@ -4258,9 +4178,9 @@ dependencies = [ [[package]] name = "markup5ever" -version = "0.39.0" +version = "0.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de" +checksum = "0ab3dc68ac4a0f5719e560136778c1ee716e296030d75dbd4484e37e39e3a842" dependencies = [ "log", "tendril", @@ -4378,18 +4298,19 @@ dependencies = [ [[package]] name = "muda" -version = "0.20.0" -source = "git+https://github.com/wonfen/muda.git?rev=547de49352791653fbdfa785f20f3c7ece8468e2#547de49352791653fbdfa785f20f3c7ece8468e2" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a775675be5389020a44c56efbdf3bbea8b97f47dfdd325e6c5c5213797a7e0aa" dependencies = [ "crossbeam-channel", "dpi", "gtk", "keyboard-types 0.8.3", + "libc", "objc2", "objc2-app-kit", "objc2-core-foundation", "objc2-foundation", - "once_cell", "png", "serde", "thiserror 2.0.20", @@ -4637,7 +4558,7 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" dependencies = [ - "proc-macro-crate 3.5.0", + "proc-macro-crate", "proc-macro2", "quote", "syn 2.0.119", @@ -4833,16 +4754,6 @@ dependencies = [ "objc2-core-foundation", ] -[[package]] -name = "objc2-javascript-core" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a1e6550c4caed348956ce3370c9ffeca70bb1dbed4fa96112e7c6170e074586" -dependencies = [ - "objc2", - "objc2-core-foundation", -] - [[package]] name = "objc2-osa-kit" version = "0.3.2" @@ -4944,8 +4855,6 @@ dependencies = [ "objc2-app-kit", "objc2-core-foundation", "objc2-foundation", - "objc2-javascript-core", - "objc2-security", ] [[package]] @@ -5078,27 +4987,25 @@ dependencies = [ [[package]] name = "pango" -version = "0.18.3" +version = "0.22.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4" +checksum = "0b2022dbbd82e1c42bd950a6f1df9b98c796e725dce5ec275e03cbf9772e4efa" dependencies = [ "gio", - "glib 0.18.5", - "libc", - "once_cell", + "glib", "pango-sys", ] [[package]] name = "pango-sys" -version = "0.18.0" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5" +checksum = "dd6be7bdb6cde4c49703315c1818a14382ce500dce57179a8d05f1c5efe4955f" dependencies = [ - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "glib-sys", + "gobject-sys", "libc", - "system-deps 6.2.2", + "system-deps 9.0.1", ] [[package]] @@ -5229,24 +5136,13 @@ dependencies = [ "phf_shared 0.11.3", ] -[[package]] -name = "phf" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" -dependencies = [ - "phf_macros 0.13.1", - "phf_shared 0.13.1", - "serde", -] - [[package]] name = "phf" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" dependencies = [ - "phf_macros 0.14.0", + "phf_macros", "phf_shared 0.14.0", "serde", ] @@ -5263,12 +5159,12 @@ dependencies = [ [[package]] name = "phf_codegen" -version = "0.13.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1" +checksum = "41b585a510fb76fdebead6897982ef2a03a21d8e6cbcca904999742a4afc6ffe" dependencies = [ - "phf_generator 0.13.1", - "phf_shared 0.13.1", + "phf_generator 0.14.0", + "phf_shared 0.14.0", ] [[package]] @@ -5281,16 +5177,6 @@ dependencies = [ "rand 0.8.7", ] -[[package]] -name = "phf_generator" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" -dependencies = [ - "fastrand", - "phf_shared 0.13.1", -] - [[package]] name = "phf_generator" version = "0.14.0" @@ -5301,19 +5187,6 @@ dependencies = [ "phf_shared 0.14.0", ] -[[package]] -name = "phf_macros" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" -dependencies = [ - "phf_generator 0.13.1", - "phf_shared 0.13.1", - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "phf_macros" version = "0.14.0" @@ -5336,15 +5209,6 @@ dependencies = [ "siphasher", ] -[[package]] -name = "phf_shared" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" -dependencies = [ - "siphasher", -] - [[package]] name = "phf_shared" version = "0.14.0" @@ -5393,9 +5257,9 @@ dependencies = [ [[package]] name = "pkg-config" -version = "0.3.33" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" [[package]] name = "plist" @@ -5465,12 +5329,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "pollster" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336" - [[package]] name = "polonius-the-crab" version = "0.5.0" @@ -5545,25 +5403,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" -[[package]] -name = "proc-macro-crate" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" -dependencies = [ - "once_cell", - "toml_edit 0.19.15", -] - -[[package]] -name = "proc-macro-crate" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e8366a6159044a37876a2b9817124296703c586a5c92e2c53751fa06d8d43e8" -dependencies = [ - "toml_edit 0.20.7", -] - [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -5573,30 +5412,6 @@ dependencies = [ "toml_edit 0.25.13+spec-1.1.0", ] -[[package]] -name = "proc-macro-error" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" -dependencies = [ - "proc-macro-error-attr", - "proc-macro2", - "quote", - "syn 1.0.109", - "version_check", -] - -[[package]] -name = "proc-macro-error-attr" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" -dependencies = [ - "proc-macro2", - "quote", - "version_check", -] - [[package]] name = "proc-macro2" version = "1.0.107" @@ -5612,8 +5427,8 @@ version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" dependencies = [ - "bit-set 0.11.1", - "bit-vec 0.10.2", + "bit-set", + "bit-vec", "bitflags 2.13.2", "chacha20", "core_detect", @@ -6122,32 +5937,6 @@ dependencies = [ "url", ] -[[package]] -name = "rfd" -version = "0.17.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220" -dependencies = [ - "block2", - "dispatch2", - "glib-sys 0.18.1", - "gobject-sys 0.18.0", - "gtk-sys", - "js-sys", - "libc", - "log", - "objc2", - "objc2-app-kit", - "objc2-core-foundation", - "objc2-foundation", - "percent-encoding", - "raw-window-handle", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "windows-sys 0.61.2", -] - [[package]] name = "rfd" version = "0.18.0" @@ -6156,6 +5945,9 @@ checksum = "c4b9d4857b10297ffb0f64cae711e983a7aeaee561848d56d429d3858bd8ed93" dependencies = [ "block2", "dispatch2", + "glib-sys", + "gobject-sys", + "gtk-sys", "js-sys", "libc", "log", @@ -6165,7 +5957,6 @@ dependencies = [ "objc2-foundation", "objc2-uniform-type-identifiers", "percent-encoding", - "pollster", "raw-window-handle", "wasm-bindgen", "wasm-bindgen-futures", @@ -6543,17 +6334,15 @@ dependencies = [ [[package]] name = "selectors" -version = "0.38.0" +version = "0.41.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d" +checksum = "8322aebea94a6cc288ff884e8a49bdbceef60206c400c6c46d22e62fc4fd91a6" dependencies = [ "bitflags 2.13.2", "cssparser", "derive_more", "log", "new_debug_unreachable", - "phf 0.13.1", - "phf_codegen 0.13.1", "precomputed-hash", "rustc-hash", "servo_arc", @@ -6819,9 +6608,9 @@ dependencies = [ [[package]] name = "servo_arc" -version = "0.4.3" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930" +checksum = "b4eceb519ec34d8290aaf6e46f435102f2bfa63f22b05a144fb16ab266d3b198" dependencies = [ "stable_deref_trait", ] @@ -7033,28 +6822,28 @@ dependencies = [ [[package]] name = "soup3" -version = "0.5.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f" +checksum = "92d38b59ff6d302538efd337e15d04d61c5b909ec223c60ae4061d74605a962a" dependencies = [ "futures-channel", "gio", - "glib 0.18.5", + "glib", "libc", "soup3-sys", ] [[package]] name = "soup3-sys" -version = "0.5.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27" +checksum = "79d5d25225bb06f83b78ff8cc35973b56d45fcdd21af6ed6d2bbd67f5a6f9bea" dependencies = [ - "gio-sys 0.18.1", - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "gio-sys", + "glib-sys", + "gobject-sys", "libc", - "system-deps 6.2.2", + "system-deps 7.0.8", ] [[package]] @@ -7129,24 +6918,24 @@ checksum = "ff7589a1859b09232522bb9edf076ca7fcf14ded96685d3fa629db73023ffbb7" [[package]] name = "string_cache" -version = "0.9.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901" +checksum = "ffa8a5dbe8b3f0bbe29d4c3225daafaeead63afdc1b65fc4c01a1384166038e6" dependencies = [ "new_debug_unreachable", "parking_lot 0.12.5", - "phf_shared 0.13.1", + "phf_shared 0.14.0", "precomputed-hash", ] [[package]] name = "string_cache_codegen" -version = "0.6.1" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69" +checksum = "928dcdf75e47626b3617a976ec205d9f057584c371c1f23b782129268d0e6edc" dependencies = [ - "phf_generator 0.13.1", - "phf_shared 0.13.1", + "phf_generator 0.14.0", + "phf_shared 0.14.0", "proc-macro2", "quote", ] @@ -7172,7 +6961,7 @@ version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" dependencies = [ - "heck 0.5.0", + "heck", "proc-macro2", "quote", "syn 2.0.119", @@ -7323,25 +7112,25 @@ dependencies = [ [[package]] name = "system-deps" -version = "6.2.2" +version = "7.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" +checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7" dependencies = [ - "cfg-expr 0.15.8", - "heck 0.5.0", + "cfg-expr", + "heck", "pkg-config", - "toml 0.8.23", + "toml 1.2.1+spec-1.1.0", "version-compare", ] [[package]] name = "system-deps" -version = "7.0.8" +version = "9.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7" +checksum = "db551ad38aac61d5e0343e0eeeb0163be3115c4e23b6a025959570ee0c03c67d" dependencies = [ - "cfg-expr 0.20.9", - "heck 0.5.0", + "cfg-expr", + "heck", "pkg-config", "toml 1.2.1+spec-1.1.0", "version-compare", @@ -7355,10 +7144,11 @@ checksum = "c0e973b34477b7823833469eb0f5a3a60370fef7a453e02d751b59180d0a5a05" [[package]] name = "tao" -version = "0.37.2" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5777b06fe6435126ae8d816eba269e050e1e10d302cf5461e9c49eccabc3548" +checksum = "018765afffb658648fbdfa825af8f117ceee0499296811802d8359663932e7b7" dependencies = [ + "async-channel", "bitflags 2.13.2", "block2", "core-foundation 0.10.1", @@ -7421,12 +7211,6 @@ dependencies = [ "xattr", ] -[[package]] -name = "target-lexicon" -version = "0.12.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" - [[package]] name = "target-lexicon" version = "0.13.5" @@ -7434,10 +7218,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" [[package]] -name = "tauri" -version = "2.12.7" +name = "task-local" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30fbfbb9dc9a2697b0e96d909ddc295fb18d2d82a58ed542ab8d9eba2edbe6da" +checksum = "2972044a9e5e448a506a7ff6f0d03b566d8ef4cd6918a58fc59835a0f8666626" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "tauri" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad570590a6620bd7a767910958cdc581308bef2ccae4a2b794f0347aa5169b75" dependencies = [ "anyhow", "bytes", @@ -7448,7 +7241,7 @@ dependencies = [ "getrandom 0.3.4", "glob", "gtk", - "heck 0.5.0", + "heck", "http", "http-range", "image", @@ -7490,19 +7283,16 @@ dependencies = [ [[package]] name = "tauri-build" -version = "2.7.6" +version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73d80784e874fa117b9b00a6680cf2f9b8a51bbd14406bea980cf8f328b00646" +checksum = "97cc0781e9d66f684d7150507d5423fc05322312ddfd12f24c30e833cf183153" dependencies = [ "anyhow", "cargo_toml", "dirs 7.0.0", "glob", - "heck 0.5.0", "json-patch", - "schemars 0.8.22", "semver 1.0.28", - "serde", "serde_json", "static_vcruntime", "strsim", @@ -7513,9 +7303,9 @@ dependencies = [ [[package]] name = "tauri-codegen" -version = "2.7.6" +version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5dc6caab4da5646f57648f39b794bae118f0dd4a4305eeb8c892966171f4852" +checksum = "96c0e6d4ad77790f6da7ac445f1a8908211785e5324bb6a9662582f3ac127231" dependencies = [ "base64 0.23.1", "brotli", @@ -7526,25 +7316,22 @@ dependencies = [ "proc-macro2", "quote", "semver 1.0.28", - "serde", "serde_json", "sha2 0.11.2", "syn 2.0.119", "tauri-utils", "thiserror 2.0.20", - "time", - "url", "uuid", "walkdir", ] [[package]] name = "tauri-macros" -version = "2.7.6" +version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2831c5da8603a96b1efc0b650c2cb6decc69b6cda257d815fe70c7f5be53818e" +checksum = "564854181dbca954a49e852140be2d810c4fc3e882538e8f530bb197bd69cfec" dependencies = [ - "heck 0.5.0", + "heck", "proc-macro2", "quote", "syn 2.0.119", @@ -7554,9 +7341,9 @@ dependencies = [ [[package]] name = "tauri-plugin" -version = "2.7.1" +version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1140cf34a3b3b836a13103dcab17f18831d5cc3534cbd435dc01a5c6daa65aa2" +checksum = "7ace389bb5d5ac6379af1e50981a7860e254157c8d333627473a2c9d23134047" dependencies = [ "anyhow", "glob", @@ -7661,13 +7448,13 @@ dependencies = [ [[package]] name = "tauri-plugin-dialog" -version = "2.8.4" +version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce0fb9c2b6d34a9720627ed930ebc8af26f61e648695aecaeb03d5c33c5896f5" +checksum = "96f4dcf1a6c6009f4a58928e8a523b95465e982d12c58db054a1ea7c6c8e1a0f" dependencies = [ "log", "raw-window-handle", - "rfd 0.17.2", + "rfd", "serde", "serde_json", "tauri", @@ -7679,9 +7466,9 @@ dependencies = [ [[package]] name = "tauri-plugin-fs" -version = "2.7.1" +version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d58eb1d4984e535f47a642ffec09a2da6f5c18a12b5902d12126cb7626d628b" +checksum = "4a1649dc7e9429b2f32164fb6614abff8bc10ed8802fa186cef72df4276eed20" dependencies = [ "anyhow", "dunce", @@ -7718,9 +7505,9 @@ dependencies = [ [[package]] name = "tauri-plugin-http" -version = "2.9.0" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c278945f30912c8c32728265c66d16ca1b139509c4874d00579f5c8c5276605a" +checksum = "7620ee481cef3c8a9a2ca25b30c430439e725b849bb6085fcb883ff7ed577136" dependencies = [ "bytes", "cookie_store", @@ -7867,16 +7654,15 @@ dependencies = [ [[package]] name = "tauri-plugin-wdio-webdriver" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a775b0b59f6f12b38d1f28667311a89cd07f532f540e27d65c6eadfba1156d8" +version = "2.0.0-next.0" +source = "git+https://github.com/Tunglies/desktop-mobile.git?rev=2745082c7f487c5e0c9568000b5a7ac24234d6e4#2745082c7f487c5e0c9568000b5a7ac24234d6e4" dependencies = [ "async-trait", "axum", "base64 0.22.1", "block2", "cairo-rs", - "glib 0.21.5", + "glib", "gtk", "javascriptcore-rs", "objc2", @@ -7900,9 +7686,9 @@ dependencies = [ [[package]] name = "tauri-plugin-window-state" -version = "2.5.0" +version = "2.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d6815cab7b212f9cfe16a9d79d8d22f9e14159e4a9460f7dec1467167a008e3" +checksum = "9c7ac6e8c4ace7deb355d922d1fb82cce3d5b9801b1b64ce0243f2f2d0040219" dependencies = [ "bitflags 2.13.2", "log", @@ -7915,9 +7701,9 @@ dependencies = [ [[package]] name = "tauri-runtime" -version = "2.12.4" +version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60c2b14bd5265b63993cdc34ad526fb836e0fd0cf64a4634a895db0784844d5e" +checksum = "33ebc9c0fc7a10f26169edd4adcc8798030cd025b2621791fe7f7e0330105c68" dependencies = [ "cookie", "dpi", @@ -7940,9 +7726,9 @@ dependencies = [ [[package]] name = "tauri-runtime-wry" -version = "2.12.5" +version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8c14a025255cc9816d401635035075b09b6cc9973b7b8fd7b8fcb8753f30f92" +checksum = "34a8d0c102664aaec2d2bfc4e8c4375e253a4192f574bb4352517c152643c6a8" dependencies = [ "gtk", "http", @@ -7970,7 +7756,7 @@ version = "2.0.0-rc.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe71fc209fa4c49f959644f1ae2d70f72d5675bcb3d3ad8518122fa7b330994e" dependencies = [ - "heck 0.5.0", + "heck", "paste", "serde", "serde_json", @@ -7990,7 +7776,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dbf5689a1dbf2611e2351b79ba042ca089d0a3ce45274695e79084cd732a5aec" dependencies = [ "darling 0.24.1", - "heck 0.5.0", + "heck", "proc-macro2", "quote", "syn 3.0.5", @@ -7998,9 +7784,9 @@ dependencies = [ [[package]] name = "tauri-utils" -version = "2.10.4" +version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28d1d33d4453c5df0bf1672dbc7ada69d8ed74f56a4316d964a4aa73d4ecd3ad" +checksum = "4b3bb2217a2c5632f25a375c305f5a1f9b3beaa7b0614a21e79f297b6b3cbc92" dependencies = [ "anyhow", "brotli", @@ -8014,7 +7800,7 @@ dependencies = [ "json-patch", "log", "memchr", - "phf 0.13.1", + "phf 0.14.0", "plist", "proc-macro2", "quote", @@ -8036,9 +7822,9 @@ dependencies = [ [[package]] name = "tauri-winres" -version = "0.3.6" +version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc65d45c68858bfe420dd29e834b5d15dbecf8a07a8a16cf4d532c7b1f69d4b6" +checksum = "c52bb6904475a6ca662f15ef787f18ade61d5740a1ee12c45d3b748efdb6f796" dependencies = [ "dunce", "embed-resource", @@ -8439,28 +8225,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "toml_edit" -version = "0.19.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" -dependencies = [ - "indexmap 2.14.0", - "toml_datetime 0.6.11", - "winnow 0.5.40", -] - -[[package]] -name = "toml_edit" -version = "0.20.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70f427fce4d84c72b5b732388bf4a9f4531b53f74e2887e3ecb2481f68f66d81" -dependencies = [ - "indexmap 2.14.0", - "toml_datetime 0.6.11", - "winnow 0.5.40", -] - [[package]] name = "toml_edit" version = "0.22.27" @@ -8715,12 +8479,13 @@ dependencies = [ [[package]] name = "tray-icon" -version = "0.25.1" +version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72" +checksum = "19886363e700addca09f3787a1394eda88a80c89b9305f96effb9ea5ce09146d" dependencies = [ "crossbeam-channel", "dirs 7.0.0", + "ksni", "libappindicator", "muda", "objc2", @@ -8728,7 +8493,6 @@ dependencies = [ "objc2-core-foundation", "objc2-core-graphics", "objc2-foundation", - "once_cell", "png", "serde", "thiserror 2.0.20", @@ -9246,31 +9010,31 @@ dependencies = [ [[package]] name = "web_atoms" -version = "0.2.5" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "075474b12bcb3d2e3d4546580e9de478eeeead668a1761e2a8860c836b7ef297" +checksum = "7572660c8890448ba236b7376f27e389c6a7e1c70195622faced601f855c0ada" dependencies = [ - "phf 0.13.1", - "phf_codegen 0.13.1", + "phf 0.14.0", + "phf_codegen 0.14.0", "string_cache", "string_cache_codegen", ] [[package]] name = "webkit2gtk" -version = "2.0.2" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793" +checksum = "d10c534cfa5ce140449e4317116730d99f11dad6fbbb9fbd50e12eec44a01570" dependencies = [ - "bitflags 1.3.2", + "bitflags 2.13.2", "cairo-rs", "gdk", "gdk-sys", "gio", - "gio-sys 0.18.1", - "glib 0.18.5", - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "gio-sys", + "glib", + "glib-sys", + "gobject-sys", "gtk", "gtk-sys", "javascriptcore-rs", @@ -9282,22 +9046,22 @@ dependencies = [ [[package]] name = "webkit2gtk-sys" -version = "2.0.2" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5" +checksum = "8b1f9b6c0d50840d7299df258bab498aaac1eb4fe10e0bdd327b9d175dec0f5a" dependencies = [ - "bitflags 1.3.2", + "bitflags 2.13.2", "cairo-sys-rs", "gdk-sys", - "gio-sys 0.18.1", - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "gio-sys", + "glib-sys", + "gobject-sys", "gtk-sys", "javascriptcore-rs-sys", "libc", "pkg-config", "soup3-sys", - "system-deps 6.2.2", + "system-deps 9.0.1", ] [[package]] @@ -10157,15 +9921,6 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" -[[package]] -name = "winnow" -version = "0.5.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" -dependencies = [ - "memchr", -] - [[package]] name = "winnow" version = "0.7.15" @@ -10242,9 +9997,9 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "wry" -version = "0.57.1" +version = "0.58.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "759c50ddad0ef9913bb5496cb9d509a50433a3b78cb0238d61105526589cf0e9" +checksum = "a9fadb3ce0a4ec6f7acddf364af8bbf14f5a1e532e5d5eed3b8141cdd3b3a774" dependencies = [ "base64 0.23.1", "block2", @@ -10269,7 +10024,7 @@ dependencies = [ "objc2-web-kit", "percent-encoding", "raw-window-handle", - "sha2 0.10.9", + "sha2 0.11.2", "soup3", "tao-macros", "thiserror 2.0.20", @@ -10420,7 +10175,7 @@ version = "5.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" dependencies = [ - "proc-macro-crate 3.5.0", + "proc-macro-crate", "proc-macro2", "quote", "syn 3.0.5", @@ -10663,7 +10418,7 @@ version = "5.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "864155e69b4352db0c7f374917bf45d1e0c8d17659c8b3dbf9795f3673f8c497" dependencies = [ - "proc-macro-crate 3.5.0", + "proc-macro-crate", "proc-macro2", "quote", "syn 3.0.5", @@ -10682,3 +10437,8 @@ dependencies = [ "syn 3.0.5", "winnow 1.0.4", ] + +[[patch.unused]] +name = "muda" +version = "0.20.0" +source = "git+https://github.com/wonfen/muda.git?rev=547de49352791653fbdfa785f20f3c7ece8468e2#547de49352791653fbdfa785f20f3c7ece8468e2" diff --git a/Cargo.toml b/Cargo.toml index 8fe876bf9..e6208cdce 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,6 +50,7 @@ split-debuginfo = "unpacked" [patch.crates-io] # Backport Windows menu command ID recycling on the muda 0.20 compatibility branch. muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdfa785f20f3c7ece8468e2" } +tauri-plugin-wdio-webdriver = { git = "https://github.com/Tunglies/desktop-mobile.git", rev = "2745082c7f487c5e0c9568000b5a7ac24234d6e4" } [workspace.dependencies] clash-verge-draft = { path = "crates/clash-verge-draft" } @@ -63,7 +64,7 @@ tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", bra tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" } tracing = "0.1.44" -tauri = { version = "2.12.7" } +tauri = { version = "2.13.0" } tauri-plugin-clipboard-manager = "2.5.0" parking_lot = "0.13.0" anyhow = "1.0.105" diff --git a/Changelog.md b/Changelog.md index fbfe25a88..50b0d60e6 100644 --- a/Changelog.md +++ b/Changelog.md @@ -59,6 +59,7 @@ **🐧 Linux** - 修复 Linux OpenRC 环境下服务安装失败 +- 修复 Linux 左键点击托盘图标时无法唤回主窗口 diff --git a/package.json b/package.json index 1716de387..9a53fec75 100644 --- a/package.json +++ b/package.json @@ -47,7 +47,7 @@ "@mui/icons-material": "^9.4.0", "@mui/material": "^9.4.0", "@tanstack/react-virtual": "^3.14.13", - "@tauri-apps/api": "2.12.5", + "@tauri-apps/api": "2.13.0", "@tauri-apps/plugin-clipboard-manager": "2.5.0", "@tauri-apps/plugin-dialog": "2.8.4", "@tauri-apps/plugin-fs": "2.7.1", @@ -85,7 +85,7 @@ "@biomejs/biome": "^2.5.14", "@eslint-react/eslint-plugin": "^5.20.5", "@eslint/js": "^10.0.1", - "@tauri-apps/cli": "2.12.6", + "@tauri-apps/cli": "2.13.0", "@types/lodash-es": "^4.17.12", "@types/node": "^26.0.0", "@types/react": "19.3.3", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a985c73b0..a45066497 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -219,8 +219,8 @@ importers: specifier: ^3.14.13 version: 3.14.13(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@tauri-apps/api': - specifier: 2.12.5 - version: 2.12.5 + specifier: 2.13.0 + version: 2.13.0 '@tauri-apps/plugin-clipboard-manager': specifier: 2.5.0 version: 2.5.0 @@ -328,8 +328,8 @@ importers: specifier: ^10.0.1 version: 10.0.1(eslint@10.16.0(jiti@2.7.0)) '@tauri-apps/cli': - specifier: 2.12.6 - version: 2.12.6 + specifier: 2.13.0 + version: 2.13.0 '@types/lodash-es': specifier: ^4.17.12 version: 4.17.12 @@ -1922,82 +1922,82 @@ packages: '@tanstack/virtual-core@3.17.11': resolution: {integrity: sha512-+ILjvtHup6Y2hzQ6YzwMgX1Q+oQpxEGOXCEsCNaPoIP0VxMbizIBTmYTDtkerkIQS8/CbP1BRuyt8V/8BCsy1g==} - '@tauri-apps/api@2.12.5': - resolution: {integrity: sha512-G9QIMt5fzED+aS4QhVK3w1HWLKpLIwH/MnpCr9z1ugGEHnS2ORmqrLkc0uALOjRK4qXJy+4Yiw8LDl/KicC1Hg==} + '@tauri-apps/api@2.13.0': + resolution: {integrity: sha512-O0uLpOZcFxbHMtkSv8sE6WNTuoUu4pOHtKQn0R6GPAFNJaOgaFa+LrR3emw1jRWA9ebVC8PZUS3Q2p881yFNrA==} - '@tauri-apps/cli-darwin-arm64@2.12.6': - resolution: {integrity: sha512-Uokwk1hFfJoG54+kD8iU0St33jAIkNvojnjEfBZ6UbL5rnM10AiFwUS/2DHTJ9R4/Kba4U44v7djfMuWFTQgeg==} + '@tauri-apps/cli-darwin-arm64@2.13.0': + resolution: {integrity: sha512-xqWG7E1j6HEcU0ZMXIxNP5MqtR3LKfvb+6iH5bvG6e3QgpaEP1Syz/j1fnX7M55Raqi6Rs4FJGTHlsG8C65Mtg==} engines: {node: '>= 10'} cpu: [arm64] os: [darwin] - '@tauri-apps/cli-darwin-x64@2.12.6': - resolution: {integrity: sha512-WhahqzcyHCpCzh4Taf0ZbBm6nGkvuOSh5ffrgOO7EdYaYe+RBQK8LOlFu+bbjul5v9cdLDi3kco+0+7IlZtTVA==} + '@tauri-apps/cli-darwin-x64@2.13.0': + resolution: {integrity: sha512-L4WEEqEc7WH3KFCnbpSUnlPud5Qs/CQ+i1USaOvhwTy3PO3JpeW1sTKB7WKUG9QeGke7tE1KL8liVd8/3lpqgg==} engines: {node: '>= 10'} cpu: [x64] os: [darwin] - '@tauri-apps/cli-linux-arm-gnueabihf@2.12.6': - resolution: {integrity: sha512-GB6weN+iFHxiFZ9SOKW6fINis7gnxohoOldR7sryBe7uaavkFGaMCa0yQs5njeXPWvzlE9WTQ13z8oDjmqK+Ww==} + '@tauri-apps/cli-linux-arm-gnueabihf@2.13.0': + resolution: {integrity: sha512-SRjozN64oQgs1I8ErMsNqTKmlSSyAQ9yVM7X+0FUkZQ0isqx42qOzJ02HkKhoEG/+ucZ15HjsL+LEe0ooFjxVg==} engines: {node: '>= 10'} cpu: [arm] os: [linux] - '@tauri-apps/cli-linux-arm64-gnu@2.12.6': - resolution: {integrity: sha512-mdHoUFYKfztUtPKE0C2hhGkEo7j6swXjg+5yRRKSD7A2gLkRPQFIXWD/DAYhiJdeAkyA8MCP6nvvKvg/4YryWQ==} + '@tauri-apps/cli-linux-arm64-gnu@2.13.0': + resolution: {integrity: sha512-ZZWiHcyrtLCCoUdfOBVWazKwDtc/c09BXrxziXcL2lUSnUBOWpzd9ROo0EzNDGDJEFB8S4cQHx+wRG6GL2MyFA==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] libc: [glibc] - '@tauri-apps/cli-linux-arm64-musl@2.12.6': - resolution: {integrity: sha512-2BxB+9a3JRN0eJ0t0qGe8IKJfgBLOZDE8a499OXH+yg4J9bMpSK1oHXBxnHuSHFWhby4QnQ/t+sBf7tRC0UZeA==} + '@tauri-apps/cli-linux-arm64-musl@2.13.0': + resolution: {integrity: sha512-0W9GgBF155WPbcVnYJHxDxVXDM/gYSywGKfGZIQrMMLv03AqeMcc+mxz4/NZBT5FO36jHPxhy8VNiy0yk+qfzQ==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] libc: [musl] - '@tauri-apps/cli-linux-riscv64-gnu@2.12.6': - resolution: {integrity: sha512-sb58RsNHex9QVqHdN1cf9MMlamUWAtk1NzuxTZalUnBUHfblIbe71hfmdI6whDZ84MufgOdeg/bzvhrbZS1r0w==} + '@tauri-apps/cli-linux-riscv64-gnu@2.13.0': + resolution: {integrity: sha512-1kKCOh768IIoqgE4o7g5zhi5SnbzqW8p82RmPcg8zFYLb17+LNwvMzpJexUWqIM2U2QkbT8rH0wfcjiaR6rTDA==} engines: {node: '>= 10'} cpu: [riscv64] os: [linux] libc: [glibc] - '@tauri-apps/cli-linux-x64-gnu@2.12.6': - resolution: {integrity: sha512-ZAb4/CHRma3ErjL2RGfHjITTUBIs4zySf0hIli9BddOtEdSx0ze0hEgxl+HfBVc5OEW/QmbiZ2E2+CkkHc8Pcg==} + '@tauri-apps/cli-linux-x64-gnu@2.13.0': + resolution: {integrity: sha512-Riq+64bPGAFoLjgnqcslFIb0Rijnm5oCjLCX6xZETWClNPMADmHflCyNwLO7XO3s97Uv6ZX2yTnpwULAyII08A==} engines: {node: '>= 10'} cpu: [x64] os: [linux] libc: [glibc] - '@tauri-apps/cli-linux-x64-musl@2.12.6': - resolution: {integrity: sha512-ueSzM2Du6r4i1d/lby9kEvrhPnXw5zM/VYvcW1ldEWSpkUyVohsBXkmD+U7vMskEW5tXeCUenki7nYVxyGBGpQ==} + '@tauri-apps/cli-linux-x64-musl@2.13.0': + resolution: {integrity: sha512-xbkW27qp9+YrU1pLebEJy300jH9NtUWEAMpMsCYS3KiZ00jv9ui3p26YWINhTgo+Yj53CDTK9B7ROViCKAluqQ==} engines: {node: '>= 10'} cpu: [x64] os: [linux] libc: [musl] - '@tauri-apps/cli-win32-arm64-msvc@2.12.6': - resolution: {integrity: sha512-6bmOt2BQSe0Bba+5CJcTKSML7VOYDxyiAKyBrjo86VxMdC1usIQmklu3Xc83s3QoK1rOMwwbANlPF6i5R2mvIg==} + '@tauri-apps/cli-win32-arm64-msvc@2.13.0': + resolution: {integrity: sha512-gjjU8TYHXPenmQvmdvJYwGX1KNHBG/3dXviJvBuX2S1hV4uOFMulTVWnPKPn3N/HgfCn0p5+7HzPKKobdNAfSg==} engines: {node: '>= 10'} cpu: [arm64] os: [win32] - '@tauri-apps/cli-win32-ia32-msvc@2.12.6': - resolution: {integrity: sha512-9q9ZFNuFreBczwyJuhhlrEOBzGClwWUYirQ2GBl66Y6EaNl17IdLH8TRqoY9wYB1LnctNBi+Fa/WMGtFA4BtFQ==} + '@tauri-apps/cli-win32-ia32-msvc@2.13.0': + resolution: {integrity: sha512-9Ln67dSuuIaVJAhdvOnJOtD9gQxeHCvhQ6OcbkxaM0EZu1Ed1ZqxImpyVBov6c7AJfzpollO93i7ZXJGsnYMtQ==} engines: {node: '>= 10'} cpu: [ia32] os: [win32] - '@tauri-apps/cli-win32-x64-msvc@2.12.6': - resolution: {integrity: sha512-ion7Chbj21ROxMRpjQ7G8rz5sIOaI7IoBQum1oq5sl1V5zGWyc/oYnCrQhVqO2TxK/lBDWxt648BzLi02SY3Xg==} + '@tauri-apps/cli-win32-x64-msvc@2.13.0': + resolution: {integrity: sha512-IPcIRMjzAXgYTH+rQxFQFwrHu4/3txIA2ONNmQpWUCHXQgukazrPYJrKaMJSjDh83ysbusjsQ16Z89qhtxFNJA==} engines: {node: '>= 10'} cpu: [x64] os: [win32] - '@tauri-apps/cli@2.12.6': - resolution: {integrity: sha512-/cOeQgqq8PBDPODOjjT0YHs4qxKCHcQMWMiBm4rLM3JNr9mZE+PHNKOK4zAkhIUtYMNL/0fweW48VNvzD1AbqA==} + '@tauri-apps/cli@2.13.0': + resolution: {integrity: sha512-NhPUU24BnPfofhfPlPCJFPHVG9sVq7B4V9zGCRXFEhXFeNnLtjwnHSDoiR3IXoJUumsKd/q6sNLsMr/rr88GBQ==} engines: {node: '>= 10'} hasBin: true @@ -5710,78 +5710,78 @@ snapshots: '@tanstack/virtual-core@3.17.11': {} - '@tauri-apps/api@2.12.5': {} + '@tauri-apps/api@2.13.0': {} - '@tauri-apps/cli-darwin-arm64@2.12.6': + '@tauri-apps/cli-darwin-arm64@2.13.0': optional: true - '@tauri-apps/cli-darwin-x64@2.12.6': + '@tauri-apps/cli-darwin-x64@2.13.0': optional: true - '@tauri-apps/cli-linux-arm-gnueabihf@2.12.6': + '@tauri-apps/cli-linux-arm-gnueabihf@2.13.0': optional: true - '@tauri-apps/cli-linux-arm64-gnu@2.12.6': + '@tauri-apps/cli-linux-arm64-gnu@2.13.0': optional: true - '@tauri-apps/cli-linux-arm64-musl@2.12.6': + '@tauri-apps/cli-linux-arm64-musl@2.13.0': optional: true - '@tauri-apps/cli-linux-riscv64-gnu@2.12.6': + '@tauri-apps/cli-linux-riscv64-gnu@2.13.0': optional: true - '@tauri-apps/cli-linux-x64-gnu@2.12.6': + '@tauri-apps/cli-linux-x64-gnu@2.13.0': optional: true - '@tauri-apps/cli-linux-x64-musl@2.12.6': + '@tauri-apps/cli-linux-x64-musl@2.13.0': optional: true - '@tauri-apps/cli-win32-arm64-msvc@2.12.6': + '@tauri-apps/cli-win32-arm64-msvc@2.13.0': optional: true - '@tauri-apps/cli-win32-ia32-msvc@2.12.6': + '@tauri-apps/cli-win32-ia32-msvc@2.13.0': optional: true - '@tauri-apps/cli-win32-x64-msvc@2.12.6': + '@tauri-apps/cli-win32-x64-msvc@2.13.0': optional: true - '@tauri-apps/cli@2.12.6': + '@tauri-apps/cli@2.13.0': optionalDependencies: - '@tauri-apps/cli-darwin-arm64': 2.12.6 - '@tauri-apps/cli-darwin-x64': 2.12.6 - '@tauri-apps/cli-linux-arm-gnueabihf': 2.12.6 - '@tauri-apps/cli-linux-arm64-gnu': 2.12.6 - '@tauri-apps/cli-linux-arm64-musl': 2.12.6 - '@tauri-apps/cli-linux-riscv64-gnu': 2.12.6 - '@tauri-apps/cli-linux-x64-gnu': 2.12.6 - '@tauri-apps/cli-linux-x64-musl': 2.12.6 - '@tauri-apps/cli-win32-arm64-msvc': 2.12.6 - '@tauri-apps/cli-win32-ia32-msvc': 2.12.6 - '@tauri-apps/cli-win32-x64-msvc': 2.12.6 + '@tauri-apps/cli-darwin-arm64': 2.13.0 + '@tauri-apps/cli-darwin-x64': 2.13.0 + '@tauri-apps/cli-linux-arm-gnueabihf': 2.13.0 + '@tauri-apps/cli-linux-arm64-gnu': 2.13.0 + '@tauri-apps/cli-linux-arm64-musl': 2.13.0 + '@tauri-apps/cli-linux-riscv64-gnu': 2.13.0 + '@tauri-apps/cli-linux-x64-gnu': 2.13.0 + '@tauri-apps/cli-linux-x64-musl': 2.13.0 + '@tauri-apps/cli-win32-arm64-msvc': 2.13.0 + '@tauri-apps/cli-win32-ia32-msvc': 2.13.0 + '@tauri-apps/cli-win32-x64-msvc': 2.13.0 '@tauri-apps/plugin-clipboard-manager@2.5.0': dependencies: - '@tauri-apps/api': 2.12.5 + '@tauri-apps/api': 2.13.0 '@tauri-apps/plugin-dialog@2.8.4': dependencies: - '@tauri-apps/api': 2.12.5 + '@tauri-apps/api': 2.13.0 '@tauri-apps/plugin-fs@2.7.1': dependencies: - '@tauri-apps/api': 2.12.5 + '@tauri-apps/api': 2.13.0 '@tauri-apps/plugin-http@2.9.0': dependencies: - '@tauri-apps/api': 2.12.5 + '@tauri-apps/api': 2.13.0 '@tauri-apps/plugin-opener@2.7.3': dependencies: - '@tauri-apps/api': 2.12.5 + '@tauri-apps/api': 2.13.0 '@tauri-apps/plugin-updater@2.14.1': dependencies: - '@tauri-apps/api': 2.12.5 + '@tauri-apps/api': 2.13.0 '@tsrs/darwin-arm64@0.20.0-ts7.1.0-beta': optional: true @@ -7803,7 +7803,7 @@ snapshots: tauri-plugin-mihomo-api@https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f: dependencies: - '@tauri-apps/api': 2.12.5 + '@tauri-apps/api': 2.13.0 terser@5.51.3: dependencies: diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index a5760618e..10f66b1dd 100755 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -27,7 +27,7 @@ perf-harness = ["dep:tauri-plugin-wdio-webdriver"] identifier = "io.github.clash-verge-rev.clash-verge-rev" [build-dependencies] -tauri-build = { version = "2.7.6", features = [] } +tauri-build = { version = "2.8.0", features = [] } [dependencies] clash-verge-draft = { workspace = true } @@ -57,7 +57,6 @@ tristr = { workspace = true } socket2 = { workspace = true } warp = { version = "0.4.4", features = ["server"] } open = "5.4.5" -rfd = { version = "0.18.0", default-features = false, features = ["common-controls-v6", "xdg-portal"] } dirs = "7.0.0" dunce = "1.0.5" nanoid = "0.5" @@ -72,10 +71,10 @@ sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs.git", rev = " network-interface = { version = "2.0.5", features = ["serde"] } tauri-plugin-shell = "2.6.0" tauri-plugin-opener = "2.7.3" -tauri-plugin-dialog = "2.8.4" -tauri-plugin-fs = "2.7.1" +tauri-plugin-dialog = { version = "2.9.0", default-features = false, features = ["gtk3"] } +tauri-plugin-fs = "2.8.0" tauri-plugin-deep-link = "2.6.3" -tauri-plugin-window-state = "2.5.0" +tauri-plugin-window-state = "2.5.1" zip = "9.9.0" flate2 = "1.1.11" reqwest_dav = "0.4.0" @@ -86,8 +85,8 @@ getrandom = "0.4.3" futures = { workspace = true } gethostname = "1.1.0" tauri-plugin-notification = "2.8.1" +tauri-plugin-http = "2.10.0" backon = { version = "1.7.0", features = ["tokio-sleep"] } -tauri-plugin-http = "2.9.0" tracing = { workspace = true } tauri-plugin-devtools = { version = "2.2.3", optional = true } tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "7e4fa8642cf6c394ed88b5a969420d8eab60087f" } @@ -110,11 +109,16 @@ specta-typescript = "=0.0.13" libc = "0.2.191" [target.'cfg(target_os = "linux")'.dependencies] +gtk = "0.19" +tauri = { workspace = true, features = ["linux-ksni"] } # Upstream has no session-end signal support on Linux; see crates/clash-verge-signal. clash-verge-signal = { workspace = true } +[target.'cfg(not(target_os = "linux"))'.dependencies] +rfd = { version = "0.18.0", default-features = false, features = ["common-controls-v6"] } + [target.'cfg(target_os = "macos")'.dependencies] -tauri-plugin-wdio-webdriver = { version = "=1.5.1", optional = true } +tauri-plugin-wdio-webdriver = { version = "=2.0.0-next.0", optional = true } objc2 = "0.6.5" objc2-foundation = { version = "0.3.2", features = [ "NSString", diff --git a/src-tauri/packages/windows/installer.nsi b/src-tauri/packages/windows/installer.nsi index d40880023..beb12d4ad 100644 --- a/src-tauri/packages/windows/installer.nsi +++ b/src-tauri/packages/windows/installer.nsi @@ -81,6 +81,9 @@ Var VC_RUNTIME_NEEDED Var ServiceExisted Var ServiceStartType Var ServiceWasRunning +Var ExistingVersionKind +Var Webview2DownloadResult +Var Webview2InstallExitCode Name "${PRODUCTNAME}" BrandingText "${COPYRIGHT}" @@ -214,13 +217,13 @@ Function PageReinstall ; Compare this installar version with the existing installation ; and modify the messages presented to the user accordingly compare_version: - StrCpy $R4 "$(older)" + StrCpy $ExistingVersionKind "$(older)" ${If} $WixMode = 1 ReadRegStr $R0 HKLM "$R6" "DisplayVersion" ${Else} ReadRegStr $R0 SHCTX "${UNINSTKEY}" "DisplayVersion" ${EndIf} - ${IfThen} $R0 == "" ${|} StrCpy $R4 "$(unknown)" ${|} + ${IfThen} $R0 == "" ${|} StrCpy $ExistingVersionKind "$(unknown)" ${|} nsis_tauri_utils::SemverCompare "${VERSION}" $R0 Pop $R0 @@ -895,8 +898,8 @@ Section WebView2 Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe" DetailPrint "$(webview2Downloading)" NSISdl::download "https://go.microsoft.com/fwlink/p/?LinkId=2124703" "$TEMP\MicrosoftEdgeWebview2Setup.exe" - Pop $0 - ${If} $0 == "success" + Pop $Webview2DownloadResult + ${If} $Webview2DownloadResult == "success" DetailPrint "$(webview2DownloadSuccess)" ${Else} DetailPrint "$(webview2DownloadError)" @@ -927,8 +930,8 @@ Section WebView2 install_webview2: DetailPrint "$(installingWebview2)" ; $6 holds the path to the webview2 installer - ExecWait "$6 ${WEBVIEW2INSTALLERARGS} /install" $1 - ${If} $1 = 0 + ExecWait "$6 ${WEBVIEW2INSTALLERARGS} /install" $Webview2InstallExitCode + ${If} $Webview2InstallExitCode = 0 DetailPrint "$(webview2InstallSuccess)" ${Else} DetailPrint "$(webview2InstallError)" @@ -953,8 +956,8 @@ Section WebView2 ${If} $R1 != "" ; Chromium updater docs: https://source.chromium.org/chromium/chromium/src/+/main:docs/updater/user_manual.md ; Modified from "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft EdgeWebView\ModifyPath" - ExecWait `"$R1" /install appguid=${WEBVIEW2APPGUID}&needsadmin=true` $1 - ${If} $1 = 0 + ExecWait `"$R1" /install appguid=${WEBVIEW2APPGUID}&needsadmin=true` $Webview2InstallExitCode + ${If} $Webview2InstallExitCode = 0 DetailPrint "$(webview2InstallSuccess)" ${Else} MessageBox MB_ICONEXCLAMATION|MB_ABORTRETRYIGNORE "$(webview2InstallError)" IDIGNORE ignore IDRETRY update_webview diff --git a/src-tauri/src/core/tray/mod.rs b/src-tauri/src/core/tray/mod.rs index 35a1223f1..433562e78 100644 --- a/src-tauri/src/core/tray/mod.rs +++ b/src-tauri/src/core/tray/mod.rs @@ -296,19 +296,16 @@ impl Tray { let (_is_custom_icon, icon_bytes) = TrayState::get_tray_icon(verge).await; - let template = { - #[cfg(target_os = "macos")] - { - verge.tray_icon.as_ref().is_none_or(|v| v == "monochrome") - } - #[cfg(not(target_os = "macos"))] - { - false - } - }; let icon = Some(tauri::image::Image::from_bytes(&icon_bytes)?); - - logging_error!(Type::Tray, tray.set_icon_with_as_template(icon, template)); + #[cfg(target_os = "macos")] + let result = if verge.tray_icon.as_ref().is_none_or(|v| v == "monochrome") { + tray.set_icon_templated(icon) + } else { + tray.set_icon(icon) + }; + #[cfg(not(target_os = "macos"))] + let result = tray.set_icon(icon); + logging_error!(Type::Tray, result); Ok(()) } @@ -404,26 +401,21 @@ impl Tray { let icon_bytes = TrayState::get_tray_icon(&verge).await.1; let icon = tauri::image::Image::from_bytes(&icon_bytes)?; - #[cfg(target_os = "linux")] - let builder = TrayIconBuilder::with_id(TRAY_ID).icon(icon).icon_as_template(false); + let builder = TrayIconBuilder::with_id(TRAY_ID); + #[cfg(target_os = "macos")] + let builder = if verge.tray_icon.as_ref().is_none_or(|v| v == "monochrome") { + builder.icon_templated(icon) + } else { + builder.icon(icon) + }; + #[cfg(not(target_os = "macos"))] + let builder = builder.icon(icon); #[cfg(any(target_os = "macos", target_os = "windows"))] let show_menu_on_left_click = verge.tray_event.as_ref().is_some_and(|v| v == "tray_menu"); - #[cfg(not(target_os = "linux"))] - let mut builder = TrayIconBuilder::with_id(TRAY_ID).icon(icon).icon_as_template(false); - #[cfg(target_os = "macos")] - { - let is_monochrome = verge.tray_icon.as_ref().is_none_or(|v| v == "monochrome"); - builder = builder.icon_as_template(is_monochrome); - } - #[cfg(any(target_os = "macos", target_os = "windows"))] - { - if !show_menu_on_left_click { - builder = builder.show_menu_on_left_click(false); - } - } + let builder = builder.show_menu_on_left_click(show_menu_on_left_click); let tray = builder.build(app_handle)?; tray.on_tray_icon_event(on_tray_icon_event); @@ -870,9 +862,14 @@ fn on_tray_icon_event(_tray_icon: &TrayIcon, tray_event: TrayIconEvent) { return; } + const CLICK_STATE: MouseButtonState = if cfg!(target_os = "linux") { + MouseButtonState::Up + } else { + MouseButtonState::Down + }; if let TrayIconEvent::Click { button: MouseButton::Left, - button_state: MouseButtonState::Down, + button_state: CLICK_STATE, .. } = tray_event { @@ -882,9 +879,13 @@ fn on_tray_icon_event(_tray_icon: &TrayIcon, tray_event: TrayIconEvent) { } AsyncHandler::spawn(|| async move { - let verge = Config::verge().await.data_arc(); - let verge_tray_event = verge.tray_event.clone().unwrap_or_else(|| "main_window".into()); - let verge_tray_action = TrayAction::from(verge_tray_event.as_str()); + let configured_event = if cfg!(target_os = "linux") { + None + } else { + Config::verge().await.data_arc().tray_event.clone() + }; + let verge_tray_event = configured_event.as_deref().unwrap_or("main_window"); + let verge_tray_action = TrayAction::from(verge_tray_event); logging!(debug, Type::Tray, "tray event: {verge_tray_action:?}"); match verge_tray_action { TrayAction::SystemProxy => { diff --git a/src-tauri/src/core/validate.rs b/src-tauri/src/core/validate.rs index 4871c238d..7d708ff42 100644 --- a/src-tauri/src/core/validate.rs +++ b/src-tauri/src/core/validate.rs @@ -7,6 +7,7 @@ use std::{ sync::LazyLock, sync::atomic::{AtomicBool, Ordering}, }; +use tauri::Manager as _; use tauri_plugin_shell::ShellExt as _; use tokio::fs; use tristr::alias::String; @@ -26,9 +27,10 @@ async fn validation_fingerprint(yaml: &str) -> u64 { let mut hasher = DefaultHasher::new(); yaml.hash(&mut hasher); core.as_str().hash(&mut hasher); - let binary = std::env::current_exe() - .into_iter() - .map(|exe| exe.with_file_name(format!("{}{}", core.as_str(), std::env::consts::EXE_SUFFIX))); + let binary = handle::Handle::app_handle() + .path() + .resolve_external_bin(core.as_str()) + .into_iter(); // The test run reads geo databases from the app dir; a geo update must revalidate. let geo = dirs::app_home_dir().into_iter().flat_map(|dir| { super::runtime_bundle::GEO_ASSETS diff --git a/src-tauri/src/utils/startup.rs b/src-tauri/src/utils/startup.rs index efd20c90a..6969acbd4 100644 --- a/src-tauri/src/utils/startup.rs +++ b/src-tauri/src/utils/startup.rs @@ -30,6 +30,29 @@ pub(crate) fn report_error(error: &anyhow::Error) { } }; + show_error_dialog(&message); +} + +#[cfg(target_os = "linux")] +fn show_error_dialog(message: &str) { + use gtk::prelude::DialogExt as _; + + // rfd's GTK3 MessageDialog waits indefinitely if its GTK worker fails to initialize. + if gtk::init().is_err() { + return; + } + + gtk::MessageDialog::builder() + .message_type(gtk::MessageType::Error) + .title("Clash Verge startup failed") + .text(message) + .buttons(gtk::ButtonsType::Ok) + .build() + .run(); +} + +#[cfg(not(target_os = "linux"))] +fn show_error_dialog(message: &str) { let _ = rfd::MessageDialog::new() .set_level(rfd::MessageLevel::Error) .set_title("Clash Verge startup failed") From 032eb9767e54d768cd0b928ce2d29606cd469770 Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:13:46 +0800 Subject: [PATCH 10/33] chore(clippy): scope crate lint policy Keep panic-on-error lints at application target roots and scope signal dependencies to Linux. --- Cargo.toml | 2 -- crates/.clippy.toml | 5 +++++ crates/clash-verge-signal/Cargo.toml | 2 +- src-tauri/build.rs | 2 ++ src-tauri/examples/frontend-contract.rs | 2 ++ src-tauri/src/lib.rs | 1 + src-tauri/src/main.rs | 1 + 7 files changed, 12 insertions(+), 3 deletions(-) create mode 100644 crates/.clippy.toml diff --git a/Cargo.toml b/Cargo.toml index e6208cdce..716830d60 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -130,7 +130,6 @@ copy_iterator = "deny" correctness = { level = "deny", priority = -1 } dbg_macro = "warn" equatable_if_let = "deny" -expect_used = "warn" expl_impl_clone_on_copy = "deny" future_not_send = "deny" iter_on_empty_collections = "deny" @@ -169,7 +168,6 @@ unnecessary_self_imports = "deny" unnecessary_wraps = "deny" unused_async = "deny" unused_trait_names = "deny" -unwrap_used = "warn" use_self = "deny" useless_let_if_seq = "deny" wildcard_imports = "deny" diff --git a/crates/.clippy.toml b/crates/.clippy.toml new file mode 100644 index 000000000..6853f759c --- /dev/null +++ b/crates/.clippy.toml @@ -0,0 +1,5 @@ +# Clippy loads a single configuration file, so repeat the workspace defaults. +avoid-breaking-exported-api = true +allow-unwrap-in-tests = true +cognitive-complexity-threshold = 25 +excessive-nesting-threshold = 5 diff --git a/crates/clash-verge-signal/Cargo.toml b/crates/clash-verge-signal/Cargo.toml index f8a03ac48..12c5b124f 100644 --- a/crates/clash-verge-signal/Cargo.toml +++ b/crates/clash-verge-signal/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2024" rust-version = "1.91" -[dependencies] +[target.'cfg(target_os = "linux")'.dependencies] clash-verge-logging = { workspace = true } log = { workspace = true } tokio = { workspace = true, features = ["signal"] } diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 13df77750..1f67c509e 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -1,3 +1,5 @@ +#![deny(clippy::expect_used, clippy::unwrap_used)] + fn main() -> Result<(), Box> { if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") && std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") diff --git a/src-tauri/examples/frontend-contract.rs b/src-tauri/examples/frontend-contract.rs index 933b424fe..045f596d3 100644 --- a/src-tauri/examples/frontend-contract.rs +++ b/src-tauri/examples/frontend-contract.rs @@ -1,3 +1,5 @@ +#![deny(clippy::expect_used, clippy::unwrap_used)] + // Dev-only target: Tauri ships everything under src/bin/ to /usr/bin in deb/rpm // bundles (PR #8131), so this generator must stay an example, never a bin. fn main() -> Result<(), Box> { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 61382454d..7a6905602 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,4 +1,5 @@ #![allow(non_snake_case)] +#![deny(clippy::expect_used, clippy::unwrap_used)] #![recursion_limit = "512"] mod cmd; diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 20f54300e..25ead2a49 100755 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -1,4 +1,5 @@ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] +#![deny(clippy::expect_used, clippy::unwrap_used)] use std::process::ExitCode; #[cfg(not(all(feature = "perf-harness", target_os = "macos")))] From 03ff4f846cdd0a305721ac1716cc78a48baec290 Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:13:47 +0800 Subject: [PATCH 11/33] docs(agents): define Rust backend architecture boundaries Document which layer owns Rust capabilities, fallible inputs, background work, and crate validation. --- AGENTS.md | 4 ++++ crates/AGENTS.md | 49 ++++++++++++++++++++++++++++++++++++--------- src-tauri/AGENTS.md | 13 +++++++++--- 3 files changed, 54 insertions(+), 12 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e64505af7..d4c227efd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,6 +60,10 @@ the ownership evidence the AI-slop review evaluates (see - For development and bug fixes, follow the [development workflow](CONTRIBUTING.md#development-workflow). +- For Rust backend changes that affect capability ownership or dependency + boundaries, follow [Workspace Crate Architecture](crates/AGENTS.md). + For Tauri commands and desktop integration, also follow + [Backend Architecture Guardrails](src-tauri/AGENTS.md). - For code review and verification of review fixes, follow [REVIEW.md](REVIEW.md). Review is read-only unless changes are authorized; findings do not expand that authorization to unrelated fixes, commits, pushes, or GitHub updates. diff --git a/crates/AGENTS.md b/crates/AGENTS.md index 5436a3d04..fa92c9b93 100644 --- a/crates/AGENTS.md +++ b/crates/AGENTS.md @@ -2,19 +2,28 @@ ## Choose the boundary +- Apply Functional Core, Imperative Shell and Ports and Adapters. Keep domain + types, invariants, parsing, validation, and deterministic transitions + independent of Tauri, concrete OS APIs, and implicit application state. +- Keep use cases, async coordination, cancellation, and timeouts in + framework-independent application modules. Pass dependencies explicitly. + Define ports where an external effect needs a contract. Adapters implement + the contracts owned by their consumers. Keep filesystem, network, IPC, process, + and OS-specific operations in their adapters. - Extract a capability whose invariants can be owned behind a small API. Before creating a crate, identify its owner, what callers supply, and what can be - verified through the crate API. Keep a module when the proposed boundary only - relocates implementation or introduces a pass-through API. -- Keep the dependency direction from the app to the crate. Resolve app paths, - read product settings, start app-owned tasks, and publish UI events in the app. - Pass the values, resources, or callbacks the crate needs. For example, + verified through the crate API. Extract a crate when it provides a useful + dependency, portability, testing, or ownership boundary. Keep a module when + the proposed boundary only relocates implementation or introduces a + pass-through API. +- Keep dependencies pointing toward domain and application contracts. Resolve + app paths and read current settings at the application boundary. Pass in the + required values, resources, or callbacks. For example, [logging](clash-verge-logging/src/lib.rs) owns its pipeline and writers while the app supplies directories and limits through `LoggerConfig`. -- Keep framework and platform dependencies scoped to the capability that needs - them. Runtime-independent logic should be runnable without the desktop app. - A platform adapter can own runtime startup when its resource lifetime requires - it, as [signal](clash-verge-signal/src/lib.rs) does for Linux shutdown. +- Run framework-independent tests without starting the desktop app. A platform + adapter can own runtime startup when its resource lifetime requires it, as + [signal](clash-verge-signal/src/lib.rs) does for Linux shutdown. ## Design the API @@ -31,6 +40,14 @@ workspace lints. Reuse workspace dependencies where available and declare only the features the crate needs. +## Handle fallible input + +- Define crate-owned error types with `thiserror` in a dedicated `error` module. + Re-export public errors through their established import paths. +- Crates may use `unwrap()` or `expect()` for internal invariants. Propagate + errors from required external data and use defaults only when the input + contract gives the default a meaning. + ## Own background work - Give ordered start, replacement, and cleanup to one task owner. Reuse @@ -43,6 +60,20 @@ transaction boundaries and keep the reply path free of locks held by the waiting caller. Cancel only at safe boundaries and own issued effects through completion or explicit reconciliation. +- Distinguish requested effects from completed effects in typed outcomes. + Define how failures, cancellation, and timeouts affect publication, retry, + rollback, or reconciliation. + +## Validate new crates + +- Fuzz the public boundary before tuning. Exercise malformed input, fallback + behavior, and failures that can affect user data. Preserve the corpus and + record the baseline revision and dependency resolution. +- Try at least one targeted performance improvement. Compare the baseline and + candidate on the same workload and build settings. Record stable gains, flat + cases, and regressions, and justify which changes to keep. +- Fuzz the final candidate again. Use the baseline corpus and compare outputs, + diagnostics, and errors with the baseline where behavior should be preserved. Verify the extracted contract through its public API when practical. Use `cargo test -p ` for focused tests and keep native behavior checks at the diff --git a/src-tauri/AGENTS.md b/src-tauri/AGENTS.md index af2554807..5be7ee572 100644 --- a/src-tauri/AGENTS.md +++ b/src-tauri/AGENTS.md @@ -1,10 +1,17 @@ # Backend Architecture Guardrails -Use [Workspace Crate Architecture](../crates/AGENTS.md) when extracting backend -capabilities or changing background task ownership. +Follow [Workspace Crate Architecture](../crates/AGENTS.md) when changing +backend capability boundaries, reusable orchestration, or background task +ownership. +- **Tauri adapter.** Commands validate transport input, delegate to application + use cases, and map results and errors to IPC. Tauri wires dependencies and + owns desktop lifecycle, window and tray integration, and event delivery. + Keep domain validation and reusable orchestration independent of command + handlers and framework state. - **Configuration and effects.** `config` owns source configuration, drafts, and - persistence. The effects layer classifies every Verge patch field, including + persistence coordination. Persistence adapters perform storage and recovery. + The effects layer classifies every Verge patch field, including fields without effects and platform-specific fields, and reconciles requested state in dependency order. Publish rollbackable state after persistence and commit. On failure, preserve already applied runtime effects, independently From 72e7201abc24b9ba441758ff7c1ca4719016e0ed Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:13:47 +0800 Subject: [PATCH 12/33] refactor(draft): type async publication conflicts Return typed conflicts for async Draft edits. Release the lock and edit permit before converting the error, and exercise overlapping updates. --- Cargo.lock | 2 +- Cargo.toml | 1 + crates/clash-verge-draft/Cargo.toml | 2 +- crates/clash-verge-draft/bench/benche_me.rs | 6 ++-- crates/clash-verge-draft/src/error.rs | 12 +++++++ crates/clash-verge-draft/src/lib.rs | 37 +++++++-------------- crates/clash-verge-draft/tests/test_me.rs | 31 +++++++++-------- src-tauri/src/cmd/profile.rs | 4 +-- 8 files changed, 50 insertions(+), 45 deletions(-) create mode 100644 crates/clash-verge-draft/src/error.rs diff --git a/Cargo.lock b/Cargo.lock index 520ee55c3..2ed2454dd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1188,9 +1188,9 @@ dependencies = [ name = "clash-verge-draft" version = "0.1.0" dependencies = [ - "anyhow", "criterion", "parking_lot 0.13.0", + "thiserror 2.0.20", "tokio", ] diff --git a/Cargo.toml b/Cargo.toml index 716830d60..938a85030 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,6 +68,7 @@ tauri = { version = "2.13.0" } tauri-plugin-clipboard-manager = "2.5.0" parking_lot = "0.13.0" anyhow = "1.0.105" +thiserror = "2.0.20" futures = "0.3.34" loom = "0.7.3" proptest = "1.12.0" diff --git a/crates/clash-verge-draft/Cargo.toml b/crates/clash-verge-draft/Cargo.toml index 40351c26a..f82611ea6 100644 --- a/crates/clash-verge-draft/Cargo.toml +++ b/crates/clash-verge-draft/Cargo.toml @@ -10,7 +10,7 @@ harness = false [dependencies] parking_lot = { workspace = true } -anyhow = { workspace = true } +thiserror = { workspace = true } tokio = { workspace = true } [dev-dependencies] diff --git a/crates/clash-verge-draft/bench/benche_me.rs b/crates/clash-verge-draft/bench/benche_me.rs index 6c1af9e49..f06702937 100644 --- a/crates/clash-verge-draft/bench/benche_me.rs +++ b/crates/clash-verge-draft/bench/benche_me.rs @@ -2,7 +2,7 @@ use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; use tokio::runtime::Runtime; -use clash_verge_draft::Draft; +use clash_verge_draft::{Draft, DraftConflict}; #[derive(Default, Clone, Debug)] struct IVerge { @@ -99,8 +99,8 @@ pub fn bench_draft(c: &mut Criterion) { group.bench_function("with_data_modify_async", |b| { b.to_async(&rt).iter(|| async { let draft = black_box(make_draft()); - let _: Result<(), anyhow::Error> = draft - .with_data_modify::<_, _, _>(|mut box_data| async move { + let _: Result<(), DraftConflict> = draft + .with_data_modify(|mut box_data| async move { box_data.enable_auto_launch = Some(!box_data.enable_auto_launch.unwrap_or(false)); Ok((box_data, ())) }) diff --git a/crates/clash-verge-draft/src/error.rs b/crates/clash-verge-draft/src/error.rs new file mode 100644 index 000000000..4fb2f4afc --- /dev/null +++ b/crates/clash-verge-draft/src/error.rs @@ -0,0 +1,12 @@ +/// Committed data changed before an asynchronous edit could publish. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[error("Optimistic lock failed: Committed data has changed during async operation")] +pub struct DraftConflict; + +/// Another transaction is already staging a change to one of the layers asked for. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("configuration layer {layer} is being changed elsewhere")] +pub struct DraftBusy { + /// The layer that was already claimed. + pub layer: &'static str, +} diff --git a/crates/clash-verge-draft/src/lib.rs b/crates/clash-verge-draft/src/lib.rs index d1a968cb2..42bd650d9 100644 --- a/crates/clash-verge-draft/src/lib.rs +++ b/crates/clash-verge-draft/src/lib.rs @@ -1,3 +1,7 @@ +mod error; + +pub use error::{DraftBusy, DraftConflict}; + use parking_lot::Mutex; use std::sync::Arc; use std::sync::atomic::{ @@ -91,14 +95,16 @@ impl Draft { } /// Optimistically replaces committed data after an asynchronous edit. + /// The caller's error type carries both edit failures and publication conflicts. #[inline] - pub async fn with_data_modify(&self, f: F) -> Result + pub async fn with_data_modify(&self, f: F) -> Result where T: Send + Sync + 'static, F: FnOnce(T) -> Fut + Send, - Fut: std::future::Future> + Send, + Fut: std::future::Future> + Send, + E: From, { - let _permit = self.acquire_data_modify_permit().await; + let permit = self.acquire_data_modify_permit().await; let (local, original_arc) = { let guard = self.inner.data.lock(); let arc = Arc::clone(&guard.0); @@ -108,9 +114,9 @@ impl Draft { let (new_local, res) = f(local).await?; let mut guard = self.inner.data.lock(); if !Arc::ptr_eq(&guard.0, &original_arc) { - return Err(anyhow::anyhow!( - "Optimistic lock failed: Committed data has changed during async operation" - )); + drop(guard); + drop(permit); + return Err(DraftConflict.into()); } guard.0 = Arc::new(Box::new(new_local)); drop(guard); @@ -191,25 +197,6 @@ impl DraftLayer for Draft { } } -/// Another transaction is already staging a change to one of the layers asked for. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct DraftBusy { - /// The layer that was already claimed. - pub layer: &'static str, -} - -impl std::fmt::Display for DraftBusy { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - formatter, - "configuration layer {} is being changed elsewhere", - self.layer - ) - } -} - -impl std::error::Error for DraftBusy {} - /// Exclusively claims several draft layers and rolls them all back unless committed. /// /// A layer has one draft slot, so concurrent transactions cannot be isolated and are rejected. diff --git a/crates/clash-verge-draft/tests/test_me.rs b/crates/clash-verge-draft/tests/test_me.rs index 44c95c99e..301291a3e 100644 --- a/crates/clash-verge-draft/tests/test_me.rs +++ b/crates/clash-verge-draft/tests/test_me.rs @@ -7,7 +7,7 @@ use std::{ task::{Context, Poll, Wake, Waker}, }; -use clash_verge_draft::{Draft, DraftTransaction}; +use clash_verge_draft::{Draft, DraftBusy, DraftConflict, DraftTransaction}; use tokio::sync::{Notify, oneshot}; #[derive(Clone, Debug, Default, PartialEq)] @@ -35,14 +35,19 @@ fn edits_can_be_committed_or_discarded() { } #[tokio::test] -async fn async_updates_are_serialized() -> anyhow::Result<()> { +async fn async_updates_are_serialized() -> Result<(), Box> { let draft = Arc::new(Draft::new(0_u8)); let mut updates = Vec::new(); for _ in 0..16 { let draft = Arc::clone(&draft); updates.push(tokio::spawn(async move { - draft.with_data_modify(|value| async move { Ok((value + 1, ())) }).await + draft + .with_data_modify(|value| async move { + tokio::task::yield_now().await; + Ok::<_, DraftConflict>((value + 1, ())) + }) + .await })); } for update in updates { @@ -54,7 +59,7 @@ async fn async_updates_are_serialized() -> anyhow::Result<()> { } #[tokio::test] -async fn async_update_rejects_a_changed_committed_value() -> anyhow::Result<()> { +async fn async_update_rejects_a_changed_committed_value() -> Result<(), Box> { let draft = Arc::new(Draft::new(Config::default())); let started = Arc::new(Notify::new()); let finish = Arc::new(Notify::new()); @@ -68,7 +73,7 @@ async fn async_update_rejects_a_changed_committed_value() -> anyhow::Result<()> started.notify_one(); finish.notified().await; config.enabled = true; - Ok((config, ())) + Ok::<_, DraftConflict>((config, ())) }) .await }) @@ -79,7 +84,7 @@ async fn async_update_rejects_a_changed_committed_value() -> anyhow::Result<()> draft.apply(); finish.notify_one(); - assert!(update.await?.is_err()); + assert_eq!(update.await?, Err(DraftConflict)); assert!(!draft.data_arc().enabled); assert_eq!(draft.data_arc().port, 7897); Ok(()) @@ -99,8 +104,8 @@ fn parked_async_update_is_woken_after_optimistic_conflict() { let draft = Draft::new(1); let (finish, finished) = oneshot::channel(); let mut owner = pin!(draft.with_data_modify(|value| async move { - finished.await?; - Ok((value + 10, ())) + finished.await.expect("owner completion signal"); + Ok::<_, DraftConflict>((value + 10, ())) })); let mut owner_context = Context::from_waker(Waker::noop()); assert!(owner.as_mut().poll(&mut owner_context).is_pending()); @@ -108,7 +113,7 @@ fn parked_async_update_is_woken_after_optimistic_conflict() { let wake_flag = Arc::new(WakeFlag::default()); let waker = Waker::from(Arc::clone(&wake_flag)); let mut waiter_context = Context::from_waker(&waker); - let mut waiter = pin!(draft.with_data_modify(|value| async move { Ok((value + 1, value)) })); + let mut waiter = pin!(draft.with_data_modify(|value| async move { Ok::<_, DraftConflict>((value + 1, value)) })); // The fast retry wakes once before the waiter parks on Notify. assert!(waiter.as_mut().poll(&mut waiter_context).is_pending()); @@ -127,7 +132,7 @@ fn parked_async_update_is_woken_after_optimistic_conflict() { } #[test] -fn transaction_commits_every_layer() -> anyhow::Result<()> { +fn transaction_commits_every_layer() -> Result<(), DraftBusy> { let first = Draft::new(1_u8); let second = Draft::new(String::from("a")); let transaction = DraftTransaction::begin(vec![&first, &second])?; @@ -142,7 +147,7 @@ fn transaction_commits_every_layer() -> anyhow::Result<()> { } #[test] -fn dropped_transaction_rolls_every_layer_back() -> anyhow::Result<()> { +fn dropped_transaction_rolls_every_layer_back() -> Result<(), DraftBusy> { let first = Draft::new(1_u8); let second = Draft::new(String::from("a")); @@ -158,14 +163,14 @@ fn dropped_transaction_rolls_every_layer_back() -> anyhow::Result<()> { } #[test] -fn transaction_claims_are_exclusive_and_release_partial_claims() -> anyhow::Result<()> { +fn transaction_claims_are_exclusive_and_release_partial_claims() -> Result<(), DraftBusy> { let first = Draft::new(1_u8); let second = Draft::new(2_u16); let held = DraftTransaction::begin(vec![&second])?; let busy = DraftTransaction::begin(vec![&first, &second]) .err() - .ok_or_else(|| anyhow::anyhow!("transaction claimed an already-held layer"))?; + .expect("transaction claimed an already-held layer"); let layer = std::any::type_name::(); assert_eq!(busy.layer, layer); assert!(busy.to_string().contains(layer)); diff --git a/src-tauri/src/cmd/profile.rs b/src-tauri/src/cmd/profile.rs index 5c43c1508..47e968483 100644 --- a/src-tauri/src/cmd/profile.rs +++ b/src-tauri/src/cmd/profile.rs @@ -159,7 +159,7 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult { let profiles = Config::profiles().await; let result = profiles - .with_data_modify(|mut candidate| async move { + .with_data_modify::<_, _, _, anyhow::Error>(|mut candidate| async move { let original = candidate.clone(); let (should_update, plan) = candidate.plan_delete_item(&index)?; let guard = if should_update { @@ -584,7 +584,7 @@ mod tests { profiles .with_data_modify(|mut committed| async move { committed.items.get_or_insert_with(Vec::new).push(profile("new")); - Ok((committed, ())) + Ok::<_, clash_verge_draft::DraftConflict>((committed, ())) }) .await?; From ad285eac9573f013c76c6de8174b27ffbd875ced Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:13:48 +0800 Subject: [PATCH 13/33] refactor(logging): use typed logger errors Expose crate-owned logger errors and preserve the underlying error sources. --- Cargo.lock | 2 +- crates/clash-verge-logging/Cargo.toml | 2 +- crates/clash-verge-logging/src/error.rs | 11 +++++++++ crates/clash-verge-logging/src/lib.rs | 30 +++++++++++++++---------- 4 files changed, 31 insertions(+), 14 deletions(-) create mode 100644 crates/clash-verge-logging/src/error.rs diff --git a/Cargo.lock b/Cargo.lock index 2ed2454dd..0f8933c15 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1214,10 +1214,10 @@ dependencies = [ name = "clash-verge-logging" version = "0.1.0" dependencies = [ - "anyhow", "flexi_logger", "log", "parking_lot 0.13.0", + "thiserror 2.0.20", "tracing-estuary", ] diff --git a/crates/clash-verge-logging/Cargo.toml b/crates/clash-verge-logging/Cargo.toml index c6d9feb20..c0c193e77 100644 --- a/crates/clash-verge-logging/Cargo.toml +++ b/crates/clash-verge-logging/Cargo.toml @@ -6,7 +6,7 @@ edition = "2024" [dependencies] log = { workspace = true } parking_lot = { workspace = true } -anyhow = { workspace = true } +thiserror = { workspace = true } flexi_logger = { workspace = true } tracing-estuary = { workspace = true } diff --git a/crates/clash-verge-logging/src/error.rs b/crates/clash-verge-logging/src/error.rs new file mode 100644 index 000000000..a95a4db9f --- /dev/null +++ b/crates/clash-verge-logging/src/error.rs @@ -0,0 +1,11 @@ +#[derive(Debug, thiserror::Error)] +pub enum LoggerError { + #[error(transparent)] + Pipeline(Box), + #[error(transparent)] + Sidecar(#[from] flexi_logger::FlexiLoggerError), + #[error("failed to get tracing pipeline, make sure it init")] + PipelineUnavailable, + #[error("failed to reset log writer: {0}")] + ResetWriter(String), +} diff --git a/crates/clash-verge-logging/src/lib.rs b/crates/clash-verge-logging/src/lib.rs index ee8df5c53..e3bbc6eec 100644 --- a/crates/clash-verge-logging/src/lib.rs +++ b/crates/clash-verge-logging/src/lib.rs @@ -1,3 +1,7 @@ +mod error; + +pub use error::LoggerError; + use std::{ collections::VecDeque, fmt, @@ -10,7 +14,6 @@ use std::{ time::Duration, }; -use anyhow::{Result, bail}; use flexi_logger::{ Cleanup, Criterion, DeferredNow, FileSpec, Naming, writers::{FileLogWriter, FileLogWriterBuilder, LogWriter as _}, @@ -177,7 +180,7 @@ impl Logger { /// Installs the global tracing pipeline. `RUST_LOG` (parsed as a bare /// level) overrides the configured level. - pub fn init(&self, cfg: &LoggerConfig) -> Result<()> { + pub fn init(&self, cfg: &LoggerConfig) -> Result<(), LoggerError> { let log_level = std::env::var("RUST_LOG") .ok() .and_then(|v| LevelFilter::from_str(v.trim()).ok()) @@ -186,14 +189,15 @@ impl Logger { let pipeline = tracing_estuary::PipelineBuilder::new() .default_level(log_level) .file_writer(self.generate_file_log_writer()) - .init()?; + .init() + .map_err(|error| LoggerError::Pipeline(error.into_boxed_dyn_error()))?; self.pipeline.set(pipeline).ok(); Ok(()) } /// Installs the sidecar file writer and the panic hook. Safe to call when /// the pipeline is owned elsewhere (e.g. a devtools-provided subscriber). - pub fn init_sidecar(&self, cfg: &LoggerConfig) -> Result<()> { + pub fn init_sidecar(&self, cfg: &LoggerConfig) -> Result<(), LoggerError> { self.store_config(cfg); self.ensure_sidecar_writer(self.generate_sidecar_builder())?; @@ -245,7 +249,7 @@ impl Logger { /// Ensures the sidecar writer exists and points at `builder`'s config: /// built once, then reset in place — flexi's flusher thread cannot be /// stopped, so every dropped writer would leak a thread and an fd. - fn ensure_sidecar_writer(&self, builder: FileLogWriterBuilder) -> Result<()> { + fn ensure_sidecar_writer(&self, builder: FileLogWriterBuilder) -> Result<(), LoggerError> { let sidecar = self.sidecar_file_writer.write(); match sidecar.as_ref() { Some(writer) => { @@ -296,27 +300,29 @@ impl Logger { } /// only update app log level - pub fn update_log_level(&self, level: LevelFilter) -> Result<()> { + pub fn update_log_level(&self, level: LevelFilter) -> Result<(), LoggerError> { if let Some(pipeline) = self.pipeline.get() { - pipeline.filter.set_default_level(level)?; + pipeline + .filter + .set_default_level(level) + .map_err(|error| LoggerError::Pipeline(error.into_boxed_dyn_error()))?; } else { - bail!("failed to get tracing pipeline, make sure it init"); + return Err(LoggerError::PipelineUnavailable); }; Ok(()) } /// Rebuilds both file writers with the new limits. - pub fn update_log_config(&self, log_max_size: u64, log_max_count: usize) -> Result<()> { + pub fn update_log_config(&self, log_max_size: u64, log_max_count: usize) -> Result<(), LoggerError> { self.log_max_size.store(log_max_size, Ordering::SeqCst); self.log_max_count.store(log_max_count, Ordering::SeqCst); if let Some(pipeline) = self.pipeline.get() { let log_file_writer = self.generate_file_log_writer(); if let Some(sink) = pipeline.sink.as_ref() { - sink.reset(log_file_writer) - .map_err(|error| anyhow::anyhow!("failed to reset log writer: {error}"))?; + sink.reset(log_file_writer).map_err(LoggerError::ResetWriter)?; } } else { - bail!("failed to get tracing pipeline, make sure it init"); + return Err(LoggerError::PipelineUnavailable); }; self.ensure_sidecar_writer(self.generate_sidecar_builder())?; Ok(()) From 9614dee991966248d4bcc6c37af495e63d1c9dd7 Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:13:49 +0800 Subject: [PATCH 14/33] refactor(subscription): extract response decoding Keep HTTP and persistence in the app. Decode response metadata and framing in the crate, and fall back when the server filename is invalid. --- Cargo.lock | 12 ++ Cargo.toml | 2 + Changelog.md | 1 + crates/clash-verge-subscription/Cargo.toml | 14 ++ crates/clash-verge-subscription/src/error.rs | 7 + crates/clash-verge-subscription/src/lib.rs | 191 +++++++++++++++++++ src-tauri/Cargo.toml | 1 + src-tauri/src/config/prfitem.rs | 104 ++-------- src-tauri/src/config/profiles.rs | 3 +- src-tauri/src/utils/help.rs | 23 --- 10 files changed, 244 insertions(+), 114 deletions(-) create mode 100644 crates/clash-verge-subscription/Cargo.toml create mode 100644 crates/clash-verge-subscription/src/error.rs create mode 100644 crates/clash-verge-subscription/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 0f8933c15..87864b539 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1115,6 +1115,7 @@ dependencies = [ "clash-verge-logging", "clash-verge-media-unlock", "clash-verge-signal", + "clash-verge-subscription", "clash-verge-task", "clash_verge_service_ipc", "dark-light", @@ -1245,6 +1246,17 @@ dependencies = [ "tokio", ] +[[package]] +name = "clash-verge-subscription" +version = "0.1.0" +dependencies = [ + "http", + "percent-encoding", + "serde_yaml_ng", + "thiserror 2.0.20", + "url", +] + [[package]] name = "clash-verge-task" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 938a85030..3c81142ca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ members = [ "crates/tauri-plugin-clash-verge-sysinfo", "crates/clash-verge-i18n", "crates/clash-verge-limiter", + "crates/clash-verge-subscription", ] resolver = "2" @@ -60,6 +61,7 @@ clash-verge-logging = { path = "crates/clash-verge-logging" } clash-verge-signal = { path = "crates/clash-verge-signal" } clash-verge-i18n = { path = "crates/clash-verge-i18n" } clash-verge-limiter = { path = "crates/clash-verge-limiter" } +clash-verge-subscription = { path = "crates/clash-verge-subscription" } tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" } tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" } tracing = "0.1.44" diff --git a/Changelog.md b/Changelog.md index 50b0d60e6..3d500e11d 100644 --- a/Changelog.md +++ b/Changelog.md @@ -33,6 +33,7 @@ - 修复检测更新后又发布新版时,应用内更新失败 - 修复关闭「自动检查更新」后,手动检查更新时弹窗空白 - 修复订阅响应过大导致内存占用过高,限制单次下载为 4 MiB +- 修复服务端文件名无效时导入的订阅名称为空 - 修复全局模式默认停在 `DIRECT` 或 `REJECT` 导致流量未经代理,现自动切换到第一个策略组 - 修复订阅中未加引号的 REALITY `short-id`(如 `1234e123`)被误读为数字,导致订阅无法启用 - 修复订阅中唯一的代理组名为 `GLOBAL` 或没有代理组时,规则模式下代理页面显示「未获取到代理信息」 diff --git a/crates/clash-verge-subscription/Cargo.toml b/crates/clash-verge-subscription/Cargo.toml new file mode 100644 index 000000000..ed4a95730 --- /dev/null +++ b/crates/clash-verge-subscription/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "clash-verge-subscription" +version = "0.1.0" +edition = "2024" + +[dependencies] +thiserror = { workspace = true } +http = "1" +percent-encoding = "2.3.2" +serde_yaml_ng = { workspace = true } +url = "2.5" + +[lints] +workspace = true diff --git a/crates/clash-verge-subscription/src/error.rs b/crates/clash-verge-subscription/src/error.rs new file mode 100644 index 000000000..b34147872 --- /dev/null +++ b/crates/clash-verge-subscription/src/error.rs @@ -0,0 +1,7 @@ +#[derive(Debug, thiserror::Error)] +pub enum SubscriptionError { + #[error("the remote profile data is invalid yaml")] + InvalidYaml(#[source] serde_yaml_ng::Error), + #[error("profile does not contain `proxies` or `proxy-providers`")] + MissingProviders, +} diff --git a/crates/clash-verge-subscription/src/lib.rs b/crates/clash-verge-subscription/src/lib.rs new file mode 100644 index 000000000..367cccedd --- /dev/null +++ b/crates/clash-verge-subscription/src/lib.rs @@ -0,0 +1,191 @@ +mod error; + +pub use error::SubscriptionError; + +use http::HeaderMap; +use percent_encoding::percent_decode_str; +use serde_yaml_ng::Mapping; +use url::Url; + +pub struct SubscriptionDocument<'a> { + pub body: &'a str, + pub filename: Option, + pub usage: Option, + pub update_interval_minutes: Option, + pub home: Option, +} + +pub struct SubscriptionUsage { + pub upload: u64, + pub download: u64, + pub total: u64, + pub expire: u64, +} + +pub fn decode_subscription<'a>( + url: &Url, + headers: &HeaderMap, + body: &'a str, +) -> Result, SubscriptionError> { + let body = body.trim_start_matches('\u{feff}'); + let yaml = serde_yaml_ng::from_str::(body).map_err(SubscriptionError::InvalidYaml)?; + + if !yaml.contains_key("proxies") && !yaml.contains_key("proxy-providers") { + return Err(SubscriptionError::MissingProviders); + } + + let usage = headers.iter().find_map(|(name, value)| { + let prefix = name.as_str().strip_suffix("subscription-userinfo")?; + if !prefix.is_empty() && !prefix.ends_with('-') { + return None; + } + + let value = value.to_str().unwrap_or(""); + Some(SubscriptionUsage { + upload: find_field(value, "upload", |field| field.parse().ok()).unwrap_or(0), + download: find_field(value, "download", |field| field.parse().ok()).unwrap_or(0), + total: find_field(value, "total", |field| field.parse().ok()).unwrap_or(0), + expire: find_field(value, "expire", |field| field.parse().ok()).unwrap_or(0), + }) + }); + let update_interval_minutes = headers.get("profile-update-interval").and_then(|value| { + let hours = value.to_str().ok()?.parse::().ok()?; + hours.checked_mul(60) + }); + let home = headers + .get("profile-web-page-url") + .and_then(|value| value.to_str().ok()) + .and_then(normalize_profile_home_url); + + Ok(SubscriptionDocument { + body, + filename: subscription_filename(url, headers), + usage, + update_interval_minutes, + home, + }) +} + +fn subscription_filename(url: &Url, headers: &HeaderMap) -> Option { + if let Some(value) = headers.get("content-disposition") { + let disposition = format!("{value:?}"); + let disposition = disposition.trim_matches('"'); + if let Some(encoded) = find_field(disposition, "filename*", Some) + && let Ok(decoded) = percent_decode_str(encoded).decode_utf8() + && let Some(filename) = decoded.split("''").last() + && !filename.trim().is_empty() + { + return Some(filename.to_owned()); + } + if let Some(filename) = find_field(disposition, "filename", Some).map(|name| name.trim_matches('"')) + && !filename.trim().is_empty() + { + return Some(filename.to_owned()); + } + } + + let url = url.as_str(); + let path = url.split_once('?').map_or(url, |(path, _)| path); + let filename = path.rsplit_once('/').map_or(path, |(_, filename)| filename); + let filename = percent_decode_str(filename).decode_utf8_lossy(); + if filename.trim().is_empty() { + return None; + } + Some(filename.into_owned()) +} + +pub fn normalize_profile_home_url(raw: &str) -> Option { + let url = Url::parse(raw.trim()).ok()?; + + if !matches!(url.scheme(), "http" | "https") { + return None; + } + + url.host_str()?; + Some(url.as_str().into()) +} + +fn find_field<'a, T>(target: &'a str, key: &str, mut parse: impl FnMut(&'a str) -> Option) -> Option { + target.split(';').map(str::trim).find_map(|s| { + let (name, value) = s.split_once('=')?; + if name != key { + return None; + } + + parse(value) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use http::HeaderValue; + + #[test] + fn decodes_metadata_and_preserves_provider_only_yaml() -> Result<(), Box> { + let url = Url::parse("https://example.com/fallback.yaml")?; + let mut headers = HeaderMap::new(); + headers.insert( + "content-disposition", + HeaderValue::from_static("attachment; filename*=UTF-8''My%20Profile.yaml; filename=fallback.yaml"), + ); + headers.insert( + "x-amz-meta-subscription-userinfo", + HeaderValue::from_static("upload=1; download=2; total=3; expire=4"), + ); + headers.insert("profile-update-interval", HeaderValue::from_static("2")); + headers.insert( + "profile-web-page-url", + HeaderValue::from_static(" https://example.com "), + ); + let yaml = "# keep this comment\nproxy-providers: {}\n"; + let body = format!("\u{feff}{yaml}"); + + let document = decode_subscription(&url, &headers, &body)?; + assert_eq!(document.body, yaml); + assert_eq!(document.filename.as_deref(), Some("My Profile.yaml")); + assert_eq!(document.update_interval_minutes, Some(120)); + assert_eq!(document.home.as_deref(), Some("https://example.com/")); + let usage = document.usage.ok_or("missing subscription usage")?; + assert_eq!((usage.upload, usage.download, usage.total, usage.expire), (1, 2, 3, 4)); + Ok(()) + } + + #[test] + fn falls_back_when_suggested_filename_is_invalid_or_empty() -> Result<(), Box> { + let url = Url::parse("https://example.com/url.yaml?token=value")?; + let root_url = Url::parse("https://example.com/")?; + for (disposition, url, expected) in [ + ( + "attachment; filename*=UTF-8''%FF; filename=valid.yaml", + &url, + Some("valid.yaml"), + ), + ( + "attachment; filename*=UTF-8''; filename=valid.yaml", + &url, + Some("valid.yaml"), + ), + ("attachment; filename*=UTF-8''%FF", &url, Some("url.yaml")), + ("attachment; filename=", &root_url, None), + ] { + let mut headers = HeaderMap::new(); + headers.insert("content-disposition", HeaderValue::from_static(disposition)); + let document = decode_subscription(url, &headers, "proxies: []")?; + assert_eq!(document.filename.as_deref(), expected); + } + Ok(()) + } + + #[test] + fn ignores_overflowing_server_interval() -> Result<(), Box> { + let url = Url::parse("https://example.com/My%20Profile.yaml?token=value")?; + let mut headers = HeaderMap::new(); + headers.insert("profile-update-interval", HeaderValue::from_str(&u64::MAX.to_string())?); + + let document = decode_subscription(&url, &headers, "proxies: []")?; + assert_eq!(document.update_interval_minutes, None); + assert_eq!(document.filename.as_deref(), Some("My Profile.yaml")); + Ok(()) + } +} diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 10f66b1dd..f1721a8fc 100755 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -36,6 +36,7 @@ clash-verge-media-unlock = { workspace = true } clash-verge-logging = { workspace = true } clash-verge-i18n = { workspace = true } clash-verge-limiter = { workspace = true } +clash-verge-subscription = { workspace = true } tauri-plugin-clash-verge-sysinfo = { workspace = true } tauri-plugin-clipboard-manager = { workspace = true } tauri = { workspace = true, features = [ diff --git a/src-tauri/src/config/prfitem.rs b/src-tauri/src/config/prfitem.rs index 94a3c0252..e60afac54 100644 --- a/src-tauri/src/config/prfitem.rs +++ b/src-tauri/src/config/prfitem.rs @@ -9,8 +9,8 @@ use crate::{ }, }; use anyhow::{Context as _, Result, bail}; +use clash_verge_subscription::decode_subscription; use serde::{Deserialize, Serialize}; -use serde_yaml_ng::Mapping; use std::time::Duration; use tokio::fs; use tristr::alias::String; @@ -18,17 +18,6 @@ use tristr::alias::String; use reqwest_dav::re_exports::url::form_urlencoded; use tauri::Url; -pub(super) fn normalize_profile_home_url(raw: &str) -> Option { - let url = Url::parse(raw.trim()).ok()?; - - if !matches!(url.scheme(), "http" | "https") { - return None; - } - - url.host_str()?; - Some(url.as_str().into()) -} - #[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)] #[serde(default)] pub struct PrfItem { @@ -290,84 +279,19 @@ impl PrfItem { bail!("failed to fetch remote profile with status {status_code}") } - let header = resp.headers(); - - let extra; - 'extra: { - for (k, v) in header.iter() { - let key_lower = k.as_str().to_ascii_lowercase(); - // Accept standard custom-metadata prefixes (x-amz-meta-, x-obs-meta-, x-cos-meta-, etc.). - if key_lower - .strip_suffix("subscription-userinfo") - .is_some_and(|prefix| prefix.is_empty() || prefix.ends_with('-')) - { - let sub_info = v.to_str().unwrap_or(""); - extra = Some(PrfExtra { - upload: help::parse_str(sub_info, "upload").unwrap_or(0), - download: help::parse_str(sub_info, "download").unwrap_or(0), - total: help::parse_str(sub_info, "total").unwrap_or(0), - expire: help::parse_str(sub_info, "expire").unwrap_or(0), - }); - break 'extra; - } - } - extra = None; - } - - let filename = match header.get("Content-Disposition") { - Some(value) => { - let filename = format!("{value:?}"); - let filename = filename.trim_matches('"'); - match help::parse_str::(filename, "filename*") { - Some(filename) => { - let iter = percent_encoding::percent_decode(filename.as_bytes()); - let filename = iter.decode_utf8().unwrap_or_default(); - filename.split("''").last().map(|s| s.into()) - } - None => match help::parse_str::(filename, "filename") { - Some(filename) => { - let filename = filename.trim_matches('"'); - Some(filename.into()) - } - None => None, - }, - } - } - None => { - Some(crate::utils::help::get_last_part_and_decode(url.as_str()).unwrap_or_else(|| "Remote File".into())) - } - }; - let update_interval = match update_interval { - Some(val) => Some(val), - None => match header.get("profile-update-interval") { - Some(value) => match value.to_str().unwrap_or("").parse::() { - Ok(val) => Some(val * 60), // hour -> min - Err(_) => None, - }, - None => None, - }, - }; - - let home = header - .get("profile-web-page-url") - .and_then(|value| value.to_str().ok()) - .and_then(normalize_profile_home_url); - + let document = decode_subscription(&url, resp.headers(), resp.text())?; + let update_interval = update_interval.or(document.update_interval_minutes); + let extra = document.usage.map(|usage| PrfExtra { + upload: usage.upload, + download: usage.download, + total: usage.total, + expire: usage.expire, + }); let uid = help::get_uid("R").into(); let file = format!("{uid}.yaml").into(); - let name = name.map_or_else( - || filename.map_or_else(|| "Remote File".into(), |s| s.into()), - |s| s.to_owned(), - ); - let data = resp.text(); - - let data = data.trim_start_matches('\u{feff}'); - - let yaml = serde_yaml_ng::from_str::(data).context("the remote profile data is invalid yaml")?; - - if !yaml.contains_key("proxies") && !yaml.contains_key("proxy-providers") { - bail!("profile does not contain `proxies` or `proxy-providers`"); - } + let name = name + .cloned() + .unwrap_or_else(|| document.filename.map_or_else(|| "Remote File".into(), Into::into)); Self::ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?; @@ -390,9 +314,9 @@ impl PrfItem { allow_auto_update, ..PrfOption::default() }), - home, + home: document.home.map(Into::into), updated: Some(chrono::Local::now().timestamp() as usize), - file_data: Some(data.into()), + file_data: Some(document.body.into()), }) } diff --git a/src-tauri/src/config/profiles.rs b/src-tauri/src/config/profiles.rs index 2c11e2c7a..a262985f7 100644 --- a/src-tauri/src/config/profiles.rs +++ b/src-tauri/src/config/profiles.rs @@ -1,6 +1,6 @@ use super::{ PrfOption, patch_opt_field, - prfitem::{PrfItem, PrfSelected, normalize_profile_home_url}, + prfitem::{PrfItem, PrfSelected}, }; use crate::core::notify::{Refresh, announce}; use crate::utils::retry::{RetryError, RetryPolicy, retry, retry_with_state}; @@ -15,6 +15,7 @@ use crate::{ use anyhow::{Context as _, Result, bail}; use clash_verge_draft::Draft; use clash_verge_logging::{Type, logging}; +use clash_verge_subscription::normalize_profile_home_url; use futures::FutureExt as _; use serde::{Deserialize, Serialize}; use serde_yaml_ng::Mapping; diff --git a/src-tauri/src/utils/help.rs b/src-tauri/src/utils/help.rs index b77655a6d..53b7346e8 100644 --- a/src-tauri/src/utils/help.rs +++ b/src-tauri/src/utils/help.rs @@ -8,7 +8,6 @@ use serde_yaml_ng::{Mapping, Value}; use std::{ mem::DropGuard, path::{Path, PathBuf}, - str::FromStr, }; use tokio::io::AsyncWriteExt as _; @@ -212,16 +211,6 @@ pub fn get_uid(prefix: &str) -> String { format!("{prefix}{id}") } -pub fn parse_str(target: &str, key: &str) -> Option { - target.split(';').map(str::trim).find_map(|s| { - let mut parts = s.splitn(2, '='); - match (parts.next(), parts.next()) { - (Some(k), Some(v)) if k == key => v.parse::().ok(), - _ => None, - } - }) -} - pub fn hex_encode(bytes: &[u8]) -> String { const HEX: &[u8; 16] = b"0123456789abcdef"; let mut out = String::with_capacity(bytes.len() * 2); @@ -307,18 +296,6 @@ pub fn mask_err(err: &str) -> String { result } -pub fn get_last_part_and_decode(url: &str) -> Option { - let path = url.split('?').next().unwrap_or(""); - let segments: Vec<&str> = path.split('/').collect(); - let last_segment = segments.last()?; - - Some( - percent_encoding::percent_decode_str(last_segment) - .decode_utf8_lossy() - .to_string(), - ) -} - pub fn open_file(path: PathBuf) -> Result<()> { open::that_detached(path.as_os_str())?; Ok(()) From 64490c44ab05189181ee50d8cc75194afb56915a Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:13:52 +0800 Subject: [PATCH 15/33] refactor(profile): extract profile models and index rules Move profile models and index rules into the crate, preserving serialization and returning a typed missing-profile error. --- Cargo.lock | 13 + Cargo.toml | 3 + crates/clash-verge-profile/Cargo.toml | 17 + crates/clash-verge-profile/src/error.rs | 5 + crates/clash-verge-profile/src/lib.rs | 407 ++++++++++++++ src-tauri/Cargo.toml | 1 + src-tauri/src/cmd/profile.rs | 65 +-- src-tauri/src/cmd/save_profile.rs | 10 +- src-tauri/src/config/config.rs | 14 +- src-tauri/src/config/mod.rs | 4 +- src-tauri/src/config/prfitem.rs | 693 +++++++++++------------- src-tauri/src/config/profiles.rs | 608 +++++++-------------- src-tauri/src/core/manager/config.rs | 4 +- src-tauri/src/enhance/mod.rs | 5 +- src-tauri/src/feat/backup.rs | 4 +- src-tauri/src/feat/dns.rs | 4 +- src-tauri/src/feat/profile.rs | 4 +- src-tauri/src/utils/init.rs | 9 +- src-tauri/src/utils/resolve/scheme.rs | 4 +- 19 files changed, 1018 insertions(+), 856 deletions(-) create mode 100644 crates/clash-verge-profile/Cargo.toml create mode 100644 crates/clash-verge-profile/src/error.rs create mode 100644 crates/clash-verge-profile/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 87864b539..6deccbcf6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1114,6 +1114,7 @@ dependencies = [ "clash-verge-limiter", "clash-verge-logging", "clash-verge-media-unlock", + "clash-verge-profile", "clash-verge-signal", "clash-verge-subscription", "clash-verge-task", @@ -1237,6 +1238,18 @@ dependencies = [ "tokio", ] +[[package]] +name = "clash-verge-profile" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "serde_yaml_ng", + "specta", + "thiserror 2.0.20", + "tristr", +] + [[package]] name = "clash-verge-signal" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 3c81142ca..886ece520 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ members = [ "crates/clash-verge-i18n", "crates/clash-verge-limiter", "crates/clash-verge-subscription", + "crates/clash-verge-profile", ] resolver = "2" @@ -62,6 +63,7 @@ clash-verge-signal = { path = "crates/clash-verge-signal" } clash-verge-i18n = { path = "crates/clash-verge-i18n" } clash-verge-limiter = { path = "crates/clash-verge-limiter" } clash-verge-subscription = { path = "crates/clash-verge-subscription" } +clash-verge-profile = { path = "crates/clash-verge-profile" } tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" } tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" } tracing = "0.1.44" @@ -97,6 +99,7 @@ serde = { version = "1.0.229" } tristr = { git = "https://github.com/Tunglies/tristr", rev = "d849e5cff47a570849c2e1bada0a2b6481cf3378", default-features = false, features = ["serde", "specta"] } serde_json = { version = "1.0.154" } serde_yaml_ng = { version = "0.10.0" } +specta = "=2.0.0-rc.26" socket2 = "0.6.5" # *** For Windows platform only *** diff --git a/crates/clash-verge-profile/Cargo.toml b/crates/clash-verge-profile/Cargo.toml new file mode 100644 index 000000000..173234b11 --- /dev/null +++ b/crates/clash-verge-profile/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "clash-verge-profile" +version = "0.1.0" +edition = "2024" + +[dependencies] +serde = { workspace = true, features = ["derive"] } +specta = { workspace = true, features = ["derive"] } +thiserror = { workspace = true } +tristr = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } +serde_yaml_ng = { workspace = true } + +[lints] +workspace = true diff --git a/crates/clash-verge-profile/src/error.rs b/crates/clash-verge-profile/src/error.rs new file mode 100644 index 000000000..0c5a27812 --- /dev/null +++ b/crates/clash-verge-profile/src/error.rs @@ -0,0 +1,5 @@ +#[derive(Debug, thiserror::Error)] +#[error("failed to get the profile item \"uid:{uid}\"")] +pub struct ProfileNotFound { + pub(super) uid: String, +} diff --git a/crates/clash-verge-profile/src/lib.rs b/crates/clash-verge-profile/src/lib.rs new file mode 100644 index 000000000..a92e25033 --- /dev/null +++ b/crates/clash-verge-profile/src/lib.rs @@ -0,0 +1,407 @@ +mod error; + +pub use error::ProfileNotFound; + +use serde::{Deserialize, Serialize}; +use tristr::alias::String; + +macro_rules! patch_opt_field { + ($lv:expr, $rv:expr, $key:tt) => { + if ($rv.$key).is_some() { + $lv.$key = $rv.$key.clone(); + } + }; +} + +#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)] +#[serde(default)] +pub struct PrfItem { + pub uid: Option, + + /// enum value: remote | local | script | merge + #[serde(rename = "type")] + pub itype: Option, + pub name: Option, + pub file: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub desc: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub selected: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub extra: Option, + pub updated: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub option: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub home: Option, + #[serde(skip)] + pub file_data: Option, +} + +#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)] +#[serde(default)] +pub struct PrfSelected { + pub name: Option, + pub now: Option, +} + +#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize, specta::Type)] +pub struct PrfExtra { + pub upload: u64, + pub download: u64, + pub total: u64, + pub expire: u64, +} + +#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)] +#[serde(default)] +pub struct PrfOption { + #[serde(skip_serializing_if = "Option::is_none")] + pub user_agent: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub with_proxy: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub self_proxy: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub update_interval: Option, + /// HTTP request timeout in seconds + /// default is 60 seconds + #[serde(skip_serializing_if = "Option::is_none")] + pub timeout_seconds: Option, + /// default is `false` + #[serde(skip_serializing_if = "Option::is_none")] + pub danger_accept_invalid_certs: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub allow_auto_update: Option, + pub merge: Option, + pub script: Option, + pub rules: Option, + pub proxies: Option, + pub groups: Option, +} + +impl PrfOption { + pub fn merge(one: Option<&Self>, other: Option<&Self>) -> Option { + match (one, other) { + (Some(a_ref), Some(b_ref)) => { + let mut result = a_ref.clone(); + patch_opt_field!(result, b_ref, user_agent); + patch_opt_field!(result, b_ref, with_proxy); + patch_opt_field!(result, b_ref, self_proxy); + patch_opt_field!(result, b_ref, danger_accept_invalid_certs); + patch_opt_field!(result, b_ref, allow_auto_update); + patch_opt_field!(result, b_ref, update_interval); + patch_opt_field!(result, b_ref, merge); + patch_opt_field!(result, b_ref, script); + patch_opt_field!(result, b_ref, rules); + patch_opt_field!(result, b_ref, proxies); + patch_opt_field!(result, b_ref, groups); + patch_opt_field!(result, b_ref, timeout_seconds); + Some(result) + } + (Some(a_ref), None) => Some(a_ref.clone()), + (None, Some(b_ref)) => Some(b_ref.clone()), + (None, None) => None, + } + } +} + +macro_rules! current_field { + ($name:ident, $field:ident) => { + pub fn $name(&self) -> Option<&String> { + self.option.as_ref().and_then(|o| o.$field.as_ref()) + } + }; +} + +impl PrfItem { + current_field!(current_merge, merge); + current_field!(current_script, script); + current_field!(current_rules, rules); + current_field!(current_proxies, proxies); + current_field!(current_groups, groups); +} + +/// Define the `profiles.yaml` schema +#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)] +#[serde(default)] +pub struct IProfiles { + pub current: Option, + pub items: Option>, +} + +pub struct IProfilePreview<'a> { + pub uid: &'a String, + pub name: &'a String, + pub is_current: bool, +} + +pub struct ProfileDeletePlan { + pub deleting_current: bool, + pub files: Vec, +} + +impl IProfiles { + pub fn patch_current(&mut self, current: Option<&String>) { + let items = self.items.get_or_insert_with(Vec::new); + if let Some(current) = current + && items.iter().any(|item| item.uid.as_ref() == Some(current)) + { + self.current = Some(current.clone()); + } + } + + pub fn get_item(&self, uid: impl AsRef) -> Result<&PrfItem, ProfileNotFound> { + let uid_str = uid.as_ref(); + + if let Some(items) = self.items.as_ref() { + for each in items.iter() { + if let Some(uid_val) = &each.uid + && uid_val.as_str() == uid_str + { + return Ok(each); + } + } + } + + Err(ProfileNotFound { + uid: uid_str.to_owned(), + }) + } + + /// Inserts a prepared entry after any required body write. + pub fn append_item(&mut self, item: &PrfItem) { + if self.current.is_none() && matches!(item.itype.as_deref(), Some("remote" | "local")) { + self.current = item.uid.clone(); + } + + self.items.get_or_insert_with(Vec::new).push(item.clone()); + } + + /// Returns true if both IDs were found, including when the item stayed at its old position. + pub fn reorder(&mut self, active_id: &str, over_id: &str) -> bool { + let Some(items) = self.items.as_mut() else { + return false; + }; + let old_index = items.iter().rposition(|item| item.uid.as_deref() == Some(active_id)); + let new_index = items.iter().rposition(|item| item.uid.as_deref() == Some(over_id)); + let (Some(old_idx), Some(new_idx)) = (old_index, new_index) else { + return false; + }; + let item = items.remove(old_idx); + items.insert(new_idx, item); + true + } + + pub fn plan_delete_item(&mut self, uid: &str) -> Result { + let deleting_current = self.current.as_deref().is_none_or(|current| current == uid); + let delete_uids = self.get_item(uid)?.option.as_ref().map_or_else(Vec::new, |op| { + [ + op.merge.clone(), + op.script.clone(), + op.rules.clone(), + op.proxies.clone(), + op.groups.clone(), + ] + .into_iter() + .collect::>() + }); + let mut items = self.items.take().unwrap_or_default(); + let mut files = Vec::new(); + + if let Some(file) = take_item_file_by_uid(&mut items, Some(uid)) { + files.push(file); + } + + for delete_uid in delete_uids { + if let Some(file) = take_item_file_by_uid(&mut items, delete_uid.as_deref()) { + files.push(file); + } + } + + if deleting_current { + self.current = None; + for item in items.iter() { + if matches!(item.itype.as_deref(), Some("remote" | "local")) { + self.current = item.uid.clone(); + break; + } + } + } + + self.items = Some(items); + Ok(ProfileDeletePlan { + deleting_current, + files, + }) + } + + pub fn profiles_preview(&self) -> Option>> { + self.items.as_ref().map(|items| { + items + .iter() + .filter_map(|e| { + if let (Some(uid), Some(name)) = (e.uid.as_ref(), e.name.as_ref()) { + let is_current = self.current.as_ref() == Some(uid); + let preview = IProfilePreview { uid, name, is_current }; + Some(preview) + } else { + None + } + }) + .collect() + }) + } +} + +fn take_item_file_by_uid(items: &mut Vec, target_uid: Option<&str>) -> Option { + let index = items.iter().position(|item| item.uid.as_deref() == target_uid)?; + items.remove(index).file +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn old_index_preserves_missing_and_explicit_values() -> Result<(), Box> { + let mut profiles: IProfiles = serde_yaml_ng::from_str( + r#" +current: first +items: + - uid: first + type: remote + option: {allow_auto_update: false, update_interval: 0, merge: ""} + file_data: ignored + - uid: second + name: "" +"#, + )?; + let first = profiles.get_item("first")?; + assert!(first.file_data.is_none()); + assert_eq!(first.current_merge().map(String::as_str), Some("")); + assert!(first.current_script().is_none()); + if let Some(items) = profiles.items.as_mut() { + items[0].file_data = Some("in memory".into()); + } + assert_eq!( + serde_json::to_value(&profiles)?, + serde_json::json!({ + "current": "first", + "items": [ + {"uid": "first", "type": "remote", "name": null, "file": null, "updated": null, + "option": {"allow_auto_update": false, "update_interval": 0, "merge": "", + "script": null, "rules": null, "proxies": null, "groups": null}}, + {"uid": "second", "type": null, "name": "", "file": null, "updated": null} + ] + }) + ); + assert_eq!( + serde_json::to_value(serde_yaml_ng::from_str::("{}")?)?, + serde_json::json!({"current": null, "items": null}) + ); + Ok(()) + } + + #[test] + fn merge_overrides_only_explicit_values() { + let base = PrfOption { + user_agent: Some("original".into()), + allow_auto_update: Some(true), + update_interval: Some(60), + merge: Some("original-merge".into()), + ..Default::default() + }; + let overrides = PrfOption { + user_agent: Some("".into()), + allow_auto_update: Some(false), + update_interval: Some(0), + ..Default::default() + }; + let expected = PrfOption { + merge: base.merge.clone(), + ..overrides.clone() + }; + assert_eq!(PrfOption::merge(Some(&base), Some(&overrides)), Some(expected)); + assert_eq!(PrfOption::merge(None, None), None); + assert_eq!( + PrfOption::merge(None, Some(&PrfOption::default())), + Some(PrfOption::default()) + ); + } + + #[test] + fn lookup_preview_and_reorder_preserve_duplicate_uid_rules() -> Result<(), Box> { + let mut profiles: IProfiles = serde_yaml_ng::from_str( + r#" +current: duplicate +items: + - {uid: duplicate, name: first} + - {uid: duplicate, name: last} + - {uid: target, name: ""} + - {name: no UID} +"#, + )?; + assert_eq!(profiles.get_item("duplicate")?.name.as_deref(), Some("first")); + assert!(!profiles.reorder("missing", "target")); + assert!(!profiles.reorder("duplicate", "missing")); + assert!(profiles.reorder("duplicate", "duplicate")); + assert!(profiles.reorder("duplicate", "target")); + let preview = profiles.profiles_preview().unwrap_or_default(); + let names: Vec<_> = preview + .iter() + .map(|item| (item.name.as_str(), item.is_current)) + .collect(); + assert_eq!(names, [("first", true), ("", false), ("last", true)]); + Ok(()) + } + + #[test] + fn current_patch_initializes_missing_items_and_only_selects_an_existing_uid() { + let mut profiles = IProfiles::default(); + profiles.patch_current(None); + assert!(matches!(&profiles.items, Some(items) if items.is_empty())); + assert!(profiles.current.is_none()); + profiles.append_item(&PrfItem { + uid: Some("script".into()), + itype: Some("script".into()), + ..Default::default() + }); + assert!(profiles.current.is_none()); + profiles.append_item(&PrfItem { + uid: Some("local".into()), + itype: Some("local".into()), + ..Default::default() + }); + assert_eq!(profiles.current.as_deref(), Some("local")); + profiles.patch_current(None); + profiles.patch_current(Some(&String::from("missing"))); + assert_eq!(profiles.current.as_deref(), Some("local")); + profiles.patch_current(Some(&String::from("script"))); + assert_eq!(profiles.current.as_deref(), Some("script")); + } + + #[test] + fn delete_plan_preserves_file_order_and_legacy_missing_uid_matching() -> Result<(), Box> { + let mut profiles: IProfiles = serde_yaml_ng::from_str( + r" +items: + - {uid: active, type: remote, file: first.yaml, option: {merge: owned}} + - {uid: owned, type: merge, file: owned.yaml} + - {type: script, file: missing-uid.js} + - {uid: next, type: local, file: next.yaml} +", + )?; + let plan = profiles.plan_delete_item("active")?; + assert!(plan.deleting_current); + assert_eq!( + plan.files, + ["first.yaml", "owned.yaml", "missing-uid.js"].map(String::from) + ); + assert_eq!(profiles.current.as_deref(), Some("next")); + assert!(profiles.get_item("owned").is_err()); + Ok(()) + } +} diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index f1721a8fc..b6bb4d532 100755 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -37,6 +37,7 @@ clash-verge-logging = { workspace = true } clash-verge-i18n = { workspace = true } clash-verge-limiter = { workspace = true } clash-verge-subscription = { workspace = true } +clash-verge-profile = { workspace = true } tauri-plugin-clash-verge-sysinfo = { workspace = true } tauri-plugin-clipboard-manager = { workspace = true } tauri = { workspace = true, features = [ diff --git a/src-tauri/src/cmd/profile.rs b/src-tauri/src/cmd/profile.rs index 47e968483..a299cdd22 100644 --- a/src-tauri/src/cmd/profile.rs +++ b/src-tauri/src/cmd/profile.rs @@ -5,12 +5,13 @@ use crate::core::notify::NoticeStatus; use crate::utils::window_manager::WindowManager; use crate::{ config::{ - Config, IProfiles, PrfItem, PrfOption, + Config, IProfiles, PrfItem, PrfOption, fetch_remote_profile, profiles::{ - PROFILE_WRITE_LOCK, profiles_append_item_with_filedata_safe, profiles_patch_item_safe, - profiles_reorder_safe, profiles_save_file_safe, + PROFILE_WRITE_LOCK, cleanup_profile_files, profiles_append_item_safe, + profiles_append_item_with_filedata_safe, profiles_patch_item_safe, profiles_reorder_safe, + profiles_save_file_safe, save_profiles, }, - profiles_append_item_safe, + read_profile_item_file, }, core::{CoreManager, handle, timer::Timer, tray::Tray, validate::ValidationOutcome}, feat, @@ -71,7 +72,7 @@ pub async fn enhance_profiles() -> CmdResult { #[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) -> CmdResult { - let item = &mut match PrfItem::from_url(&url, None, None, option.as_ref()).await { + let item = &mut match fetch_remote_profile(&url, None, None, option.as_ref()).await { Ok(it) => it, Err(e) => { logging!(error, Type::Cmd, "[导入订阅] 下载失败: {e:#}"); @@ -161,7 +162,8 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult { let result = profiles .with_data_modify::<_, _, _, anyhow::Error>(|mut candidate| async move { let original = candidate.clone(); - let (should_update, plan) = candidate.plan_delete_item(&index)?; + let plan = candidate.plan_delete_item(&index)?; + let should_update = plan.deleting_current; let guard = if should_update { match CoreManager::global() .update_config_forced_with_profiles(&candidate, &original) @@ -171,11 +173,11 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult { Err(outcome) => return Ok((original, Err(outcome))), } } else { - candidate.save_file().await?; + save_profiles(&candidate).await?; None }; let current = candidate.current.clone(); - plan.cleanup().await; + cleanup_profile_files(plan.files).await; Ok((candidate, Ok((should_update, current, guard)))) }) .await @@ -210,15 +212,11 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult { Ok(()) } -async fn restore_previous_profile(prev_profile: &str) -> CmdResult<()> { +async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> { logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile); - let restore_profiles = IProfiles { - current: Some(prev_profile.into()), - items: None, - }; Config::profiles() .await - .edit_draft(|d| d.patch_config(&restore_profiles)); + .edit_draft(|d| d.patch_current(Some(prev_profile))); Config::profiles().await.apply(); crate::process::AsyncHandler::spawn(|| async move { if let Err(e) = profiles_save_file_safe().await { @@ -236,10 +234,7 @@ async fn commit_current_profile(profiles: &Draft, current: Option CmdResult CmdResult { #[tauri::command] #[specta::specta] pub async fn read_profile_file(index: std::string::String) -> CmdResult { - let item = { + let file = { let profiles = Config::profiles().await; let profiles_ref = profiles.latest_arc(); - PrfItem { - file: profiles_ref - .get_item(&index) - .with_error_code("PROFILE_READ_FAILED")? - .file - .to_owned(), - ..Default::default() - } + profiles_ref + .get_item(&index) + .with_error_code("PROFILE_READ_FAILED")? + .file + .clone() }; - if let Some(file) = item.file.as_ref() { + if let Some(file) = file.as_ref() { let path = dirs::app_profiles_dir() .with_error_code("PROFILE_READ_FAILED")? .join(file.as_str()); @@ -521,7 +509,9 @@ pub async fn read_profile_file(index: std::string::String) -> CmdResult { diff --git a/src-tauri/src/config/prfitem.rs b/src-tauri/src/config/prfitem.rs index e60afac54..83aefa7fd 100644 --- a/src-tauri/src/config/prfitem.rs +++ b/src-tauri/src/config/prfitem.rs @@ -1,4 +1,4 @@ -use super::patch_opt_field; +use super::{PrfExtra, PrfItem, PrfOption}; use crate::{ config::profiles, @@ -10,7 +10,6 @@ use crate::{ }; use anyhow::{Context as _, Result, bail}; use clash_verge_subscription::decode_subscription; -use serde::{Deserialize, Serialize}; use std::time::Duration; use tokio::fs; use tristr::alias::String; @@ -18,396 +17,266 @@ use tristr::alias::String; use reqwest_dav::re_exports::url::form_urlencoded; use tauri::Url; -#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)] -#[serde(default)] -pub struct PrfItem { - pub uid: Option, - - /// enum value: remote | local | script | merge - #[serde(rename = "type")] - pub itype: Option, - pub name: Option, - pub file: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub desc: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub url: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub selected: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub extra: Option, - - pub updated: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub option: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub home: Option, - - #[serde(skip)] - pub file_data: Option, -} - -#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)] -#[serde(default)] -pub struct PrfSelected { - pub name: Option, - pub now: Option, -} - -#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize, specta::Type)] -pub struct PrfExtra { - pub upload: u64, - pub download: u64, - pub total: u64, - pub expire: u64, -} - -#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)] -#[serde(default)] -pub struct PrfOption { - #[serde(skip_serializing_if = "Option::is_none")] - pub user_agent: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub with_proxy: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub self_proxy: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub update_interval: Option, - - /// HTTP request timeout in seconds - /// default is 60 seconds - #[serde(skip_serializing_if = "Option::is_none")] - pub timeout_seconds: Option, - - /// default is `false` - #[serde(skip_serializing_if = "Option::is_none")] - pub danger_accept_invalid_certs: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub allow_auto_update: Option, - pub merge: Option, - pub script: Option, - pub rules: Option, - pub proxies: Option, - pub groups: Option, -} - -impl PrfOption { - pub(crate) fn merge(one: Option<&Self>, other: Option<&Self>) -> Option { - match (one, other) { - (Some(a_ref), Some(b_ref)) => { - let mut result = a_ref.clone(); - patch_opt_field!(result, b_ref, user_agent); - patch_opt_field!(result, b_ref, with_proxy); - patch_opt_field!(result, b_ref, self_proxy); - patch_opt_field!(result, b_ref, danger_accept_invalid_certs); - patch_opt_field!(result, b_ref, allow_auto_update); - patch_opt_field!(result, b_ref, update_interval); - patch_opt_field!(result, b_ref, merge); - patch_opt_field!(result, b_ref, script); - patch_opt_field!(result, b_ref, rules); - patch_opt_field!(result, b_ref, proxies); - patch_opt_field!(result, b_ref, groups); - patch_opt_field!(result, b_ref, timeout_seconds); - Some(result) - } - (Some(a_ref), None) => Some(a_ref.clone()), - (None, Some(b_ref)) => Some(b_ref.clone()), - (None, None) => None, +/// Builds an item from a partial value that must include `itype`. +pub(super) async fn build_profile(item: &PrfItem, file_data: Option) -> Result { + let itype = item + .itype + .as_ref() + .ok_or_else(|| anyhow::anyhow!("type should not be null"))?; + match itype.as_str() { + "remote" => { + let url = item + .url + .as_ref() + .ok_or_else(|| anyhow::anyhow!("url should not be null"))?; + let name = item.name.as_ref(); + let desc = item.desc.as_ref(); + let option = item.option.as_ref(); + fetch_remote_profile(url, name, desc, option).await } + "local" => { + let name = item.name.clone().unwrap_or_else(|| "Local File".into()); + let desc = item.desc.clone().unwrap_or_else(|| "".into()); + let option = item.option.as_ref(); + from_local(name, desc, file_data, option).await + } + typ => bail!("invalid profile item type \"{typ}\""), } } -impl PrfItem { - /// Builds an item from a partial value that must include `itype`. - pub(super) async fn from(item: &Self, file_data: Option) -> Result { - let itype = item - .itype - .as_ref() - .ok_or_else(|| anyhow::anyhow!("type should not be null"))?; - match itype.as_str() { - "remote" => { - let url = item - .url - .as_ref() - .ok_or_else(|| anyhow::anyhow!("url should not be null"))?; - let name = item.name.as_ref(); - let desc = item.desc.as_ref(); - let option = item.option.as_ref(); - Self::from_url(url, name, desc, option).await - } - "local" => { - let name = item.name.clone().unwrap_or_else(|| "Local File".into()); - let desc = item.desc.clone().unwrap_or_else(|| "".into()); - let option = item.option.as_ref(); - Self::from_local(name, desc, file_data, option).await - } - typ => bail!("invalid profile item type \"{typ}\""), - } - } - - async fn append_companion_item(item: &mut Self) -> Result { - profiles::profiles_append_item_safe(item).await?; - item.uid - .clone() - .ok_or_else(|| anyhow::anyhow!("appended companion item has no uid")) - } - - async fn ensure_companion_items( - merge: &mut Option, - script: &mut Option, - rules: &mut Option, - proxies: &mut Option, - groups: &mut Option, - ) -> Result<()> { - if merge.is_none() { - *merge = Some(Self::append_companion_item(&mut Self::from_merge(None)).await?); - } - if script.is_none() { - *script = Some(Self::append_companion_item(&mut Self::from_script(None)).await?); - } - if rules.is_none() { - *rules = Some(Self::append_companion_item(&mut Self::from_rules()).await?); - } - if proxies.is_none() { - *proxies = Some(Self::append_companion_item(&mut Self::from_proxies()).await?); - } - if groups.is_none() { - *groups = Some(Self::append_companion_item(&mut Self::from_groups()).await?); - } - Ok(()) - } - - async fn from_local( - name: String, - desc: String, - file_data: Option, - option: Option<&PrfOption>, - ) -> Result { - let uid = help::get_uid("L").into(); - let file = format!("{uid}.yaml").into(); - let opt_ref = option.as_ref(); - let update_interval = opt_ref.and_then(|o| o.update_interval); - let mut merge = opt_ref.and_then(|o| o.merge.clone()); - let mut script = opt_ref.and_then(|o| o.script.clone()); - let mut rules = opt_ref.and_then(|o| o.rules.clone()); - let mut proxies = opt_ref.and_then(|o| o.proxies.clone()); - let mut groups = opt_ref.and_then(|o| o.groups.clone()); - - Self::ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?; - Ok(Self { - uid: Some(uid), - itype: Some("local".into()), - name: Some(name), - desc: Some(desc), - file: Some(file), - url: None, - selected: None, - extra: None, - option: Some(PrfOption { - update_interval, - merge, - script, - rules, - proxies, - groups, - ..PrfOption::default() - }), - home: None, - updated: Some(chrono::Local::now().timestamp() as usize), - file_data: Some(file_data.unwrap_or_else(|| tmpl::ITEM_LOCAL.into())), - }) - } - - pub(crate) async fn from_url( - url: &str, - name: Option<&String>, - desc: Option<&String>, - option: Option<&PrfOption>, - ) -> Result { - let with_proxy = option.is_some_and(|o| o.with_proxy.unwrap_or(false)); - let self_proxy = option.is_some_and(|o| o.self_proxy.unwrap_or(false)); - let accept_invalid_certs = option.is_some_and(|o| o.danger_accept_invalid_certs.unwrap_or(false)); - let allow_auto_update = Some(allow_auto_update_enabled(option)); - let user_agent = option.and_then(|o| o.user_agent.clone()); - let update_interval = option.and_then(|o| o.update_interval); - let timeout = option.and_then(|o| o.timeout_seconds).unwrap_or(20); - let mut merge = option.and_then(|o| o.merge.clone()); - let mut script = option.and_then(|o| o.script.clone()); - let mut rules = option.and_then(|o| o.rules.clone()); - let mut proxies = option.and_then(|o| o.proxies.clone()); - let mut groups = option.and_then(|o| o.groups.clone()); - - let proxy_type = if self_proxy { - ProxyType::Localhost - } else if with_proxy { - ProxyType::System - } else { - ProxyType::None - }; - - let url = fix_dirty_url(url)?; - - let resp = match NetworkManager::new() - .get( - url.as_str(), - proxy_type, - Some(timeout), - user_agent.clone(), - accept_invalid_certs, - ) - .await - { - Ok(r) => r, - Err(e) => { - tokio::time::sleep(Duration::from_millis(100)).await; - return Err(e).context("failed to fetch remote profile"); - } - }; - - let status_code = resp.status(); - if !status_code.is_success() { - bail!("failed to fetch remote profile with status {status_code}") - } - - let document = decode_subscription(&url, resp.headers(), resp.text())?; - let update_interval = update_interval.or(document.update_interval_minutes); - let extra = document.usage.map(|usage| PrfExtra { - upload: usage.upload, - download: usage.download, - total: usage.total, - expire: usage.expire, - }); - let uid = help::get_uid("R").into(); - let file = format!("{uid}.yaml").into(); - let name = name - .cloned() - .unwrap_or_else(|| document.filename.map_or_else(|| "Remote File".into(), Into::into)); - - Self::ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?; - - Ok(Self { - uid: Some(uid), - itype: Some("remote".into()), - name: Some(name), - desc: desc.cloned(), - file: Some(file), - url: Some(url.as_str().into()), - selected: None, - extra, - option: Some(PrfOption { - update_interval, - merge, - script, - rules, - proxies, - groups, - allow_auto_update, - ..PrfOption::default() - }), - home: document.home.map(Into::into), - updated: Some(chrono::Local::now().timestamp() as usize), - file_data: Some(document.body.into()), - }) - } - - pub(super) fn from_merge(uid: Option) -> Self { - let (id, template) = if let Some(uid) = uid { - (uid, tmpl::ITEM_MERGE.into()) - } else { - (help::get_uid("m").into(), tmpl::ITEM_MERGE_EMPTY.into()) - }; - let file = format!("{id}.yaml").into(); - - Self { - uid: Some(id), - itype: Some("merge".into()), - file: Some(file), - updated: Some(chrono::Local::now().timestamp() as usize), - file_data: Some(template), - ..Default::default() - } - } - - pub(super) fn from_script(uid: Option) -> Self { - let id = if let Some(uid) = uid { - uid - } else { - help::get_uid("s").into() - }; - let file = format!("{id}.js").into(); // js ext - Self { - uid: Some(id), - itype: Some("script".into()), - file: Some(file), - updated: Some(chrono::Local::now().timestamp() as usize), - file_data: Some(tmpl::ITEM_SCRIPT.into()), - ..Default::default() - } - } - - fn new_seq_item(prefix: &str, itype: &str, template: &str) -> Self { - let uid = help::get_uid(prefix).into(); - let file = format!("{uid}.yaml").into(); // yaml ext - - Self { - uid: Some(uid), - itype: Some(itype.into()), - file: Some(file), - updated: Some(chrono::Local::now().timestamp() as usize), - file_data: Some(template.into()), - ..Default::default() - } - } - - fn from_rules() -> Self { - Self::new_seq_item("r", "rules", tmpl::ITEM_RULES) - } - - fn from_proxies() -> Self { - Self::new_seq_item("p", "proxies", tmpl::ITEM_PROXIES) - } - - fn from_groups() -> Self { - Self::new_seq_item("g", "groups", tmpl::ITEM_GROUPS) - } - - pub(crate) async fn read_file(&self) -> Result { - let file = self - .file - .as_ref() - .ok_or_else(|| anyhow::anyhow!("could not find the file"))?; - let path = dirs::app_profiles_dir()?.join(file.as_str()); - let content = fs::read_to_string(&path) - .await - .with_context(|| format!("failed to read the file \"{}\"", path.display()))?; - Ok(content.into()) - } +async fn append_companion_item(item: &mut PrfItem) -> Result { + profiles::profiles_append_item_safe(item).await?; + item.uid + .clone() + .ok_or_else(|| anyhow::anyhow!("appended companion item has no uid")) } -macro_rules! current_field { - ($name:ident, $field:ident) => { - pub(crate) fn $name(&self) -> Option<&String> { - self.option.as_ref().and_then(|o| o.$field.as_ref()) +async fn ensure_companion_items( + merge: &mut Option, + script: &mut Option, + rules: &mut Option, + proxies: &mut Option, + groups: &mut Option, +) -> Result<()> { + if merge.is_none() { + *merge = Some(append_companion_item(&mut build_merge_profile(None)).await?); + } + if script.is_none() { + *script = Some(append_companion_item(&mut build_script_profile(None)).await?); + } + if rules.is_none() { + *rules = Some(append_companion_item(&mut from_rules()).await?); + } + if proxies.is_none() { + *proxies = Some(append_companion_item(&mut from_proxies()).await?); + } + if groups.is_none() { + *groups = Some(append_companion_item(&mut from_groups()).await?); + } + Ok(()) +} + +async fn from_local( + name: String, + desc: String, + file_data: Option, + option: Option<&PrfOption>, +) -> Result { + let uid = help::get_uid("L").into(); + let file = format!("{uid}.yaml").into(); + let opt_ref = option.as_ref(); + let update_interval = opt_ref.and_then(|o| o.update_interval); + let mut merge = opt_ref.and_then(|o| o.merge.clone()); + let mut script = opt_ref.and_then(|o| o.script.clone()); + let mut rules = opt_ref.and_then(|o| o.rules.clone()); + let mut proxies = opt_ref.and_then(|o| o.proxies.clone()); + let mut groups = opt_ref.and_then(|o| o.groups.clone()); + + ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?; + Ok(PrfItem { + uid: Some(uid), + itype: Some("local".into()), + name: Some(name), + desc: Some(desc), + file: Some(file), + url: None, + selected: None, + extra: None, + option: Some(PrfOption { + update_interval, + merge, + script, + rules, + proxies, + groups, + ..PrfOption::default() + }), + home: None, + updated: Some(chrono::Local::now().timestamp() as usize), + file_data: Some(file_data.unwrap_or_else(|| tmpl::ITEM_LOCAL.into())), + }) +} + +pub(crate) async fn fetch_remote_profile( + url: &str, + name: Option<&String>, + desc: Option<&String>, + option: Option<&PrfOption>, +) -> Result { + let with_proxy = option.is_some_and(|o| o.with_proxy.unwrap_or(false)); + let self_proxy = option.is_some_and(|o| o.self_proxy.unwrap_or(false)); + let accept_invalid_certs = option.is_some_and(|o| o.danger_accept_invalid_certs.unwrap_or(false)); + let allow_auto_update = Some(allow_auto_update_enabled(option)); + let user_agent = option.and_then(|o| o.user_agent.clone()); + let update_interval = option.and_then(|o| o.update_interval); + let timeout = option.and_then(|o| o.timeout_seconds).unwrap_or(20); + let mut merge = option.and_then(|o| o.merge.clone()); + let mut script = option.and_then(|o| o.script.clone()); + let mut rules = option.and_then(|o| o.rules.clone()); + let mut proxies = option.and_then(|o| o.proxies.clone()); + let mut groups = option.and_then(|o| o.groups.clone()); + + let proxy_type = if self_proxy { + ProxyType::Localhost + } else if with_proxy { + ProxyType::System + } else { + ProxyType::None + }; + + let url = fix_dirty_url(url)?; + + let resp = match NetworkManager::new() + .get( + url.as_str(), + proxy_type, + Some(timeout), + user_agent.clone(), + accept_invalid_certs, + ) + .await + { + Ok(r) => r, + Err(e) => { + tokio::time::sleep(Duration::from_millis(100)).await; + return Err(e).context("failed to fetch remote profile"); } }; + + let status_code = resp.status(); + if !status_code.is_success() { + bail!("failed to fetch remote profile with status {status_code}") + } + + let document = decode_subscription(&url, resp.headers(), resp.text())?; + let update_interval = update_interval.or(document.update_interval_minutes); + let extra = document.usage.map(|usage| PrfExtra { + upload: usage.upload, + download: usage.download, + total: usage.total, + expire: usage.expire, + }); + let uid = help::get_uid("R").into(); + let file = format!("{uid}.yaml").into(); + let name = name + .cloned() + .unwrap_or_else(|| document.filename.map_or_else(|| "Remote File".into(), Into::into)); + + ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?; + + Ok(PrfItem { + uid: Some(uid), + itype: Some("remote".into()), + name: Some(name), + desc: desc.cloned(), + file: Some(file), + url: Some(url.as_str().into()), + selected: None, + extra, + option: Some(PrfOption { + update_interval, + merge, + script, + rules, + proxies, + groups, + allow_auto_update, + ..PrfOption::default() + }), + home: document.home.map(Into::into), + updated: Some(chrono::Local::now().timestamp() as usize), + file_data: Some(document.body.into()), + }) } -impl PrfItem { - current_field!(current_merge, merge); - current_field!(current_script, script); - current_field!(current_rules, rules); - current_field!(current_proxies, proxies); - current_field!(current_groups, groups); +pub(super) fn build_merge_profile(uid: Option) -> PrfItem { + let (id, template) = if let Some(uid) = uid { + (uid, tmpl::ITEM_MERGE.into()) + } else { + (help::get_uid("m").into(), tmpl::ITEM_MERGE_EMPTY.into()) + }; + let file = format!("{id}.yaml").into(); + + PrfItem { + uid: Some(id), + itype: Some("merge".into()), + file: Some(file), + updated: Some(chrono::Local::now().timestamp() as usize), + file_data: Some(template), + ..Default::default() + } +} + +pub(super) fn build_script_profile(uid: Option) -> PrfItem { + let id = if let Some(uid) = uid { + uid + } else { + help::get_uid("s").into() + }; + let file = format!("{id}.js").into(); // js ext + PrfItem { + uid: Some(id), + itype: Some("script".into()), + file: Some(file), + updated: Some(chrono::Local::now().timestamp() as usize), + file_data: Some(tmpl::ITEM_SCRIPT.into()), + ..Default::default() + } +} + +fn new_seq_item(prefix: &str, itype: &str, template: &str) -> PrfItem { + let uid = help::get_uid(prefix).into(); + let file = format!("{uid}.yaml").into(); // yaml ext + + PrfItem { + uid: Some(uid), + itype: Some(itype.into()), + file: Some(file), + updated: Some(chrono::Local::now().timestamp() as usize), + file_data: Some(template.into()), + ..Default::default() + } +} + +fn from_rules() -> PrfItem { + new_seq_item("r", "rules", tmpl::ITEM_RULES) +} + +fn from_proxies() -> PrfItem { + new_seq_item("p", "proxies", tmpl::ITEM_PROXIES) +} + +fn from_groups() -> PrfItem { + new_seq_item("g", "groups", tmpl::ITEM_GROUPS) +} + +pub(crate) async fn read_profile_item_file(file: Option<&str>) -> Result { + let file = file.ok_or_else(|| anyhow::anyhow!("could not find the file"))?; + let path = dirs::app_profiles_dir()?.join(file); + let content = fs::read_to_string(&path) + .await + .with_context(|| format!("failed to read the file \"{}\"", path.display()))?; + Ok(content.into()) } fn allow_auto_update_enabled(option: Option<&PrfOption>) -> bool { @@ -442,3 +311,63 @@ fn fix_dirty_url(input: &str) -> Result { Ok(url) } + +#[cfg(test)] +mod tests { + use super::*; + use tokio::{ + io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader}, + net::TcpListener, + }; + + #[tokio::test] + async fn fetch_remote_profile_maps_response_to_profile_model() -> Result<()> { + const BODY: &str = "# keep this comment\nproxies: []\n"; + let listener = TcpListener::bind("127.0.0.1:0").await?; + let url = format!("http://{}/subscription", listener.local_addr()?); + let server = tokio::spawn(async move { + let (socket, _) = listener.accept().await?; + let mut socket = BufReader::new(socket); + let mut line = std::string::String::new(); + loop { + line.clear(); + if socket.read_line(&mut line).await? == 0 || line == "\r\n" { + break; + } + } + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\ + Content-Disposition: attachment; filename=remote.yaml\r\n\ + Profile-Update-Interval: 2\r\n\ + Profile-Web-Page-Url: https://example.invalid/\r\n\ + Subscription-Userinfo: upload=1; download=2; total=3; expire=4\r\n\r\n{BODY}", + BODY.len() + ); + socket.get_mut().write_all(response.as_bytes()).await + }); + let option = PrfOption { + update_interval: Some(0), + allow_auto_update: Some(false), + timeout_seconds: Some(5), + merge: Some("test-merge".into()), + script: Some("test-script".into()), + rules: Some("test-rules".into()), + proxies: Some("test-proxies".into()), + groups: Some("test-groups".into()), + ..Default::default() + }; + let item: clash_verge_profile::PrfItem = fetch_remote_profile(&url, None, None, Some(&option)).await?; + server.await??; + assert_eq!(item.itype.as_deref(), Some("remote")); + assert_eq!(item.name.as_deref(), Some("remote.yaml")); + assert_eq!(item.home.as_deref(), Some("https://example.invalid/")); + assert_eq!(item.file_data.as_deref(), Some(BODY)); + assert_eq!(item.current_merge().map(String::as_str), Some("test-merge")); + let usage = item.extra.context("expected decoded usage")?; + assert_eq!((usage.upload, usage.download, usage.total, usage.expire), (1, 2, 3, 4)); + let fetched_option = item.option.context("expected profile options")?; + assert_eq!(fetched_option.update_interval, Some(0)); + assert_eq!(fetched_option.allow_auto_update, Some(false)); + Ok(()) + } +} diff --git a/src-tauri/src/config/profiles.rs b/src-tauri/src/config/profiles.rs index a262985f7..3fb44b26c 100644 --- a/src-tauri/src/config/profiles.rs +++ b/src-tauri/src/config/profiles.rs @@ -1,7 +1,4 @@ -use super::{ - PrfOption, patch_opt_field, - prfitem::{PrfItem, PrfSelected}, -}; +use super::{PrfItem, PrfOption, PrfSelected, patch_opt_field, prfitem::build_profile}; use crate::core::notify::{Refresh, announce}; use crate::utils::retry::{RetryError, RetryPolicy, retry, retry_with_state}; use crate::{ @@ -15,9 +12,9 @@ use crate::{ use anyhow::{Context as _, Result, bail}; use clash_verge_draft::Draft; use clash_verge_logging::{Type, logging}; +pub use clash_verge_profile::{IProfilePreview, IProfiles}; use clash_verge_subscription::normalize_profile_home_url; use futures::FutureExt as _; -use serde::{Deserialize, Serialize}; use serde_yaml_ng::Mapping; use std::num::NonZeroUsize; use std::{ @@ -49,359 +46,218 @@ const SELECTED_NODES_SETTLE_INTERVAL: Duration = Duration::from_secs(1); /// Bounds startup waiting; remaining selections continue restoring in the background. const SELECTED_NODES_FIRST_PASS_BUDGET: Duration = Duration::from_secs(3); -/// Define the `profiles.yaml` schema -#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)] -#[serde(default)] -pub struct IProfiles { - pub current: Option, - - pub items: Option>, -} - -pub struct IProfilePreview<'a> { - pub uid: &'a String, - pub name: &'a String, - pub is_current: bool, -} - -pub(crate) struct ProfileDeletePlan { - files: Vec, -} - -impl ProfileDeletePlan { - pub(crate) async fn cleanup(self) { - let Ok(dir) = dirs::app_profiles_dir() else { - return; - }; - for file in self.files { - let path = dir.join(file.as_str()); - if let Err(error) = path.remove_if_exists().await { - logging!( - warn, - Type::Config, - "Failed to remove deleted profile file {}: {error:#}", - path.display() - ); - } +pub(crate) async fn cleanup_profile_files(files: Vec) { + let Ok(dir) = dirs::app_profiles_dir() else { + return; + }; + for file in files { + let path = dir.join(file.as_str()); + if let Err(error) = path.remove_if_exists().await { + logging!( + warn, + Type::Config, + "Failed to remove deleted profile file {}: {error:#}", + path.display() + ); } } } -impl IProfiles { - fn take_item_file_by_uid(items: &mut Vec, target_uid: Option<&str>) -> Option { - let index = items.iter().position(|item| item.uid.as_deref() == target_uid)?; - items.remove(index).file - } +pub(crate) async fn load_profiles() -> IProfiles { + let path = match dirs::profiles_path() { + Ok(p) => p, + Err(err) => { + logging!(error, Type::Config, "failed to get profiles path: {err:#}"); + return IProfiles::default(); + } + }; - pub async fn new() -> Self { - let path = match dirs::profiles_path() { - Ok(p) => p, - Err(err) => { - logging!(error, Type::Config, "failed to get profiles path: {err:#}"); - return Self::default(); - } - }; - - match help::read_yaml::(&path).await { - Ok(mut profiles) => { - let items = profiles.items.get_or_insert_with(Vec::new); - let mut home_changed = false; - for item in items.iter_mut() { - if item.uid.is_none() { - item.uid = Some(help::get_uid("d").into()); - } - if item.itype.as_deref() == Some("remote") { - item.option - .get_or_insert_with(PrfOption::default) - .allow_auto_update - .get_or_insert(true); - } - - if item - .home - .as_deref() - .is_some_and(|home| normalize_profile_home_url(home).is_none()) - { - item.home = None; - home_changed = true; - } + match help::read_yaml::(&path).await { + Ok(mut profiles) => { + let items = profiles.items.get_or_insert_with(Vec::new); + let mut home_changed = false; + for item in items.iter_mut() { + if item.uid.is_none() { + item.uid = Some(help::get_uid("d").into()); + } + if item.itype.as_deref() == Some("remote") { + item.option + .get_or_insert_with(PrfOption::default) + .allow_auto_update + .get_or_insert(true); } - if home_changed && let Err(err) = profiles.save_file().await { - logging!(error, Type::Config, "无法保存已清理的 profiles.yaml: {err:#}"); - } - profiles - } - Err(err) => { - logging!(error, Type::Config, "failed to read profiles.yaml: {err:#}"); - Self::default() - } - } - } - - pub async fn save_file(&self) -> Result<()> { - help::save_yaml(&dirs::profiles_path()?, self, Some("# Profiles Config for Clash Verge")).await - } - - /// 只修改current,valid和chain - pub fn patch_config(&mut self, patch: &Self) { - if self.items.is_none() { - self.items = Some(vec![]); - } - - if let Some(current) = &patch.current - && let Some(items) = self.items.as_ref() - { - let some_uid = Some(current); - if items.iter().any(|e| e.uid.as_ref() == some_uid) { - self.current = some_uid.cloned(); - } - } - } - - pub fn get_item(&self, uid: impl AsRef) -> Result<&PrfItem> { - let uid_str = uid.as_ref(); - - if let Some(items) = self.items.as_ref() { - for each in items.iter() { - if let Some(uid_val) = &each.uid - && uid_val.as_str() == uid_str + if item + .home + .as_deref() + .is_some_and(|home| normalize_profile_home_url(home).is_none()) { - return Ok(each); + item.home = None; + home_changed = true; } } - } - bail!("failed to get the profile item \"uid:{}\"", uid_str); - } - - async fn append_item(&mut self, item: &mut PrfItem) -> Result<()> { - let uid = &item.uid; - if uid.is_none() { - bail!("the uid should not be null"); - } - - if let Some(file_data) = item.file_data.take() { - if item.file.is_none() { - bail!("the file should not be null"); + if home_changed && let Err(err) = save_profiles(&profiles).await { + logging!(error, Type::Config, "无法保存已清理的 profiles.yaml: {err:#}"); } - - let file = item - .file - .clone() - .ok_or_else(|| anyhow::anyhow!("file field is required when file_data is provided"))?; - let path = dirs::app_profiles_dir()?.join(file.as_str()); - - fs::write(&path, file_data.as_bytes()) - .await - .with_context(|| format!("failed to write to file \"{file}\""))?; + profiles } - - if self.current.is_none() && (item.itype == Some("remote".into()) || item.itype == Some("local".into())) { - self.current = uid.to_owned(); + Err(err) => { + logging!(error, Type::Config, "failed to read profiles.yaml: {err:#}"); + IProfiles::default() } + } +} - if self.items.is_none() { - self.items = Some(vec![]); - } +pub(crate) async fn save_profiles(profiles: &IProfiles) -> Result<()> { + help::save_yaml( + &dirs::profiles_path()?, + profiles, + Some("# Profiles Config for Clash Verge"), + ) + .await +} - if let Some(items) = self.items.as_mut() { - items.push(item.to_owned()); - } - - Ok(()) +async fn append_item(profiles: &mut IProfiles, item: &mut PrfItem) -> Result<()> { + if item.uid.is_none() { + bail!("the uid should not be null"); } - async fn reorder(&mut self, active_id: &str, over_id: &str) -> Result<()> { - { - let Some(items) = self.items.as_mut() else { - return Ok(()); - }; - let old_index = items.iter().rposition(|item| item.uid.as_deref() == Some(active_id)); - let new_index = items.iter().rposition(|item| item.uid.as_deref() == Some(over_id)); - let (Some(old_idx), Some(new_idx)) = (old_index, new_index) else { - return Ok(()); - }; - let item = items.remove(old_idx); - items.insert(new_idx, item); + if let Some(file_data) = item.file_data.take() { + if item.file.is_none() { + bail!("the file should not be null"); } - self.save_file().await + + let file = item + .file + .clone() + .ok_or_else(|| anyhow::anyhow!("file field is required when file_data is provided"))?; + let path = dirs::app_profiles_dir()?.join(file.as_str()); + + fs::write(&path, file_data.as_bytes()) + .await + .with_context(|| format!("failed to write to file \"{file}\""))?; } - async fn patch_item(&mut self, uid: &str, item: &PrfItem) -> Result<()> { - if let Some(file) = &item.file { - Self::validate_profile_file(file)?; + profiles.append_item(item); + Ok(()) +} + +async fn patch_item(profiles: &mut IProfiles, uid: &str, item: &PrfItem) -> Result<()> { + if let Some(file) = &item.file { + validate_profile_file(file)?; + } + + let mut items = profiles.items.take().unwrap_or_default(); + + for each in items.iter_mut() { + if each.uid.as_deref() == Some(uid) { + patch_opt_field!(each, item, itype); + patch_opt_field!(each, item, name); + patch_opt_field!(each, item, desc); + patch_opt_field!(each, item, file); + patch_opt_field!(each, item, url); + patch_opt_field!(each, item, selected); + patch_opt_field!(each, item, extra); + patch_opt_field!(each, item, updated); + patch_opt_field!(each, item, option); + + profiles.items = Some(items); + return save_profiles(profiles).await; } + } - let mut items = self.items.take().unwrap_or_default(); + profiles.items = Some(items); + bail!("failed to find the profile item \"uid:{uid}\"") +} +fn validate_profile_file(file: &str) -> Result<()> { + let mut components = Path::new(file).components(); + if file.is_empty() + || file.contains('/') + || file.contains('\\') + || !matches!( + (components.next(), components.next()), + (Some(Component::Normal(_)), None) + ) + { + bail!("profile file must be a single filename"); + } + + Ok(()) +} + +/// Updates fields returned by a remote profile refresh. +async fn update_item(profiles: &mut IProfiles, uid: &str, item: &mut PrfItem) -> Result<()> { + if profiles.items.is_none() { + profiles.items = Some(vec![]); + } + + let _ = profiles.get_item(uid)?; + + if let Some(items) = profiles.items.as_mut() { for each in items.iter_mut() { if each.uid.as_deref() == Some(uid) { - patch_opt_field!(each, item, itype); - patch_opt_field!(each, item, name); - patch_opt_field!(each, item, desc); - patch_opt_field!(each, item, file); - patch_opt_field!(each, item, url); - patch_opt_field!(each, item, selected); - patch_opt_field!(each, item, extra); - patch_opt_field!(each, item, updated); - patch_opt_field!(each, item, option); + each.extra = item.extra; + each.updated = item.updated; + each.home = item.home.to_owned(); + each.option = PrfOption::merge(each.option.as_ref(), item.option.as_ref()); + if let Some(file_data) = item.file_data.take() { + let file = each.file.take(); + let file = + file.unwrap_or_else(|| item.file.take().unwrap_or_else(|| format!("{}.yaml", uid).into())); - self.items = Some(items); - return self.save_file().await; + each.file = Some(file.clone()); + + let path = dirs::app_profiles_dir()?.join(file.as_str()); + + fs::write(&path, file_data.as_bytes()) + .await + .with_context(|| format!("failed to write to file \"{file}\""))?; + } + + break; } } - - self.items = Some(items); - bail!("failed to find the profile item \"uid:{uid}\"") } - fn validate_profile_file(file: &str) -> Result<()> { - let mut components = Path::new(file).components(); - if file.is_empty() - || file.contains('/') - || file.contains('\\') - || !matches!( - (components.next(), components.next()), - (Some(Component::Normal(_)), None) - ) + save_profiles(profiles).await +} + +/// Raise intervals below `min_minutes`. `None`/`0` mean "never auto-update", left alone. +/// Returns how many changed so the caller can skip a pointless write. +pub(crate) fn raise_short_update_intervals(profiles: &mut IProfiles, min_minutes: u64) -> usize { + let mut raised = 0; + + for item in profiles.items.iter_mut().flatten() { + let Some(option) = item.option.as_mut() else { + continue; + }; + if option + .update_interval + .is_some_and(|interval| (1..min_minutes).contains(&interval)) { - bail!("profile file must be a single filename"); - } - - Ok(()) - } - - /// Updates fields returned by a remote profile refresh. - async fn update_item(&mut self, uid: &str, item: &mut PrfItem) -> Result<()> { - if self.items.is_none() { - self.items = Some(vec![]); - } - - let _ = self.get_item(uid)?; - - if let Some(items) = self.items.as_mut() { - for each in items.iter_mut() { - if each.uid.as_deref() == Some(uid) { - each.extra = item.extra; - each.updated = item.updated; - each.home = item.home.to_owned(); - each.option = PrfOption::merge(each.option.as_ref(), item.option.as_ref()); - if let Some(file_data) = item.file_data.take() { - let file = each.file.take(); - let file = - file.unwrap_or_else(|| item.file.take().unwrap_or_else(|| format!("{}.yaml", uid).into())); - - each.file = Some(file.clone()); - - let path = dirs::app_profiles_dir()?.join(file.as_str()); - - fs::write(&path, file_data.as_bytes()) - .await - .with_context(|| format!("failed to write to file \"{file}\""))?; - } - - break; - } - } - } - - self.save_file().await - } - - /// Raise intervals below `min_minutes`. `None`/`0` mean "never auto-update", left alone. - /// Returns how many changed so the caller can skip a pointless write. - pub fn raise_short_update_intervals(&mut self, min_minutes: u64) -> usize { - let mut raised = 0; - - for item in self.items.iter_mut().flatten() { - let Some(option) = item.option.as_mut() else { - continue; - }; - if option - .update_interval - .is_some_and(|interval| (1..min_minutes).contains(&interval)) - { - option.update_interval = Some(min_minutes); - raised += 1; - } - } - - raised - } - - pub(crate) fn plan_delete_item(&mut self, uid: &str) -> Result<(bool, ProfileDeletePlan)> { - let deleting_current = self.current.as_deref().is_none_or(|current| current == uid); - let delete_uids = self.get_item(uid)?.option.as_ref().map_or_else(Vec::new, |op| { - [ - op.merge.clone(), - op.script.clone(), - op.rules.clone(), - op.proxies.clone(), - op.groups.clone(), - ] - .into_iter() - .collect::>() - }); - let mut items = self.items.take().unwrap_or_default(); - let mut files = Vec::new(); - - if let Some(file) = Self::take_item_file_by_uid(&mut items, Some(uid)) { - files.push(file); - } - - for delete_uid in delete_uids { - if let Some(file) = Self::take_item_file_by_uid(&mut items, delete_uid.as_deref()) { - files.push(file); - } - } - - if deleting_current { - self.current = None; - for item in items.iter() { - if item.itype == Some("remote".into()) || item.itype == Some("local".into()) { - self.current = item.uid.clone(); - break; - } - } - } - - self.items = Some(items); - Ok((deleting_current, ProfileDeletePlan { files })) - } - - /// 获取current指向的订阅内容 - pub async fn current_mapping(&self) -> Result { - match (self.current.as_ref(), self.items.as_ref()) { - (Some(current), Some(items)) => { - if let Some(item) = items.iter().find(|e| e.uid.as_ref() == Some(current)) { - let file_path = match item.file.as_ref() { - Some(file) => dirs::app_profiles_dir()?.join(file.as_str()), - None => bail!("failed to get the file field"), - }; - return help::read_mapping(&file_path).await; - } - bail!("failed to find the current profile \"uid:{current}\""); - } - _ => Ok(Mapping::new()), + option.update_interval = Some(min_minutes); + raised += 1; } } - pub fn profiles_preview(&self) -> Option>> { - self.items.as_ref().map(|items| { - items - .iter() - .filter_map(|e| { - if let (Some(uid), Some(name)) = (e.uid.as_ref(), e.name.as_ref()) { - let is_current = self.current.as_ref() == Some(uid); - let preview = IProfilePreview { uid, name, is_current }; - Some(preview) - } else { - None - } - }) - .collect() - }) + raised +} + +pub(crate) async fn current_mapping(profiles: &IProfiles) -> Result { + match (profiles.current.as_ref(), profiles.items.as_ref()) { + (Some(current), Some(items)) => { + if let Some(item) = items.iter().find(|e| e.uid.as_ref() == Some(current)) { + let file_path = match item.file.as_ref() { + Some(file) => dirs::app_profiles_dir()?.join(file.as_str()), + None => bail!("failed to get the file field"), + }; + return help::read_mapping(&file_path).await; + } + bail!("failed to find the current profile \"uid:{current}\""); + } + _ => Ok(Mapping::new()), } } @@ -409,7 +265,7 @@ impl IProfiles { use crate::config::Config; pub(crate) async fn profiles_append_item_with_filedata_safe(item: &PrfItem, file_data: Option) -> Result<()> { - let item = &mut PrfItem::from(item, file_data).await?; + let item = &mut build_profile(item, file_data).await?; profiles_append_item_safe(item).await } @@ -436,26 +292,40 @@ pub(crate) async fn profiles_append_item_safe(item: &mut PrfItem) -> Result<()> pub(super) async fn profiles_append_item_to_safe(profiles: &Draft, item: &mut PrfItem) -> Result<()> { profiles .with_data_modify(|mut profiles| async move { - profiles.append_item(item).await?; + append_item(&mut profiles, item).await?; Ok((profiles, ())) }) .await } pub(crate) async fn profiles_patch_item_safe(index: &str, item: &PrfItem) -> Result<()> { - with_profiles_edit(|mut profiles| async move { profiles.patch_item(index, item).await.map(|_| profiles) }).await + with_profiles_edit(|mut profiles| async move { + patch_item(&mut profiles, index, item).await?; + Ok(profiles) + }) + .await } pub(crate) async fn profiles_reorder_safe(active_id: &str, over_id: &str) -> Result<()> { - with_profiles_edit(|mut profiles| async move { profiles.reorder(active_id, over_id).await.map(|_| profiles) }).await + with_profiles_edit(|mut profiles| async move { + if profiles.reorder(active_id, over_id) { + save_profiles(&profiles).await?; + } + Ok(profiles) + }) + .await } pub(crate) async fn profiles_save_file_safe() -> Result<()> { - with_profiles_edit(|profiles| async move { profiles.save_file().await.map(|_| profiles) }).await + with_profiles_edit(|profiles| async move { save_profiles(&profiles).await.map(|_| profiles) }).await } pub(crate) async fn profiles_update_item_safe(index: &str, item: &mut PrfItem) -> Result<()> { - with_profiles_edit(|mut profiles| async move { profiles.update_item(index, item).await.map(|_| profiles) }).await + with_profiles_edit(|mut profiles| async move { + update_item(&mut profiles, index, item).await?; + Ok(profiles) + }) + .await } #[derive(Debug, PartialEq, Eq)] @@ -784,7 +654,7 @@ pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result now: Some(node.into()), }), } - profiles.save_file().await?; + save_profiles(&profiles).await?; Ok((profiles, true)) }) .await @@ -813,7 +683,7 @@ pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> { if !selected.is_empty() { item.selected = Some(selected); } - profiles.save_file().await?; + save_profiles(&profiles).await?; Ok((profiles, true)) }) .await @@ -844,7 +714,7 @@ async fn persist_reconciled_selected( } profile.selected = (!selected.is_empty()).then_some(selected); - profiles.save_file().await?; + save_profiles(&profiles).await?; Ok((profiles, true)) }) .await @@ -1128,19 +998,6 @@ mod tests { use super::*; use tauri_plugin_mihomo::models::Proxy; - fn deletion_item(uid: &str, kind: &str, file: &str, merge: Option<&str>) -> PrfItem { - PrfItem { - uid: Some(uid.into()), - itype: Some(kind.into()), - file: Some(file.into()), - option: merge.map(|uid| PrfOption { - merge: Some(uid.into()), - ..PrfOption::default() - }), - ..PrfItem::default() - } - } - fn interval_item(uid: &str, update_interval: Option) -> PrfItem { PrfItem { uid: Some(uid.into()), @@ -1153,43 +1010,6 @@ mod tests { } } - #[tokio::test] - async fn missing_reorder_ids_preserve_ordered_items() -> Result<()> { - let mut profiles = IProfiles { - current: Some("a".into()), - items: Some(vec![ - PrfItem { - uid: Some("a".into()), - ..PrfItem::default() - }, - PrfItem { - uid: Some("b".into()), - ..PrfItem::default() - }, - PrfItem { - uid: Some("c".into()), - ..PrfItem::default() - }, - ]), - }; - let expected = Some(vec![Some("a"), Some("b"), Some("c")]); - - profiles.reorder("missing", "b").await?; - let ordered_uids = profiles - .items - .as_ref() - .map(|items| items.iter().map(|item| item.uid.as_deref()).collect::>()); - assert_eq!(ordered_uids, expected); - - profiles.reorder("a", "missing").await?; - let ordered_uids = profiles - .items - .as_ref() - .map(|items| items.iter().map(|item| item.uid.as_deref()).collect::>()); - assert_eq!(ordered_uids, expected); - Ok(()) - } - #[test] fn raising_intervals_only_touches_those_scheduled_too_often() { let mut profiles = IProfiles { @@ -1210,7 +1030,7 @@ mod tests { ]), }; - assert_eq!(profiles.raise_short_update_intervals(1440), 2); + assert_eq!(raise_short_update_intervals(&mut profiles, 1440), 2); let intervals: Vec> = profiles .items @@ -1224,32 +1044,12 @@ mod tests { ); assert_eq!( - profiles.raise_short_update_intervals(1440), + raise_short_update_intervals(&mut profiles, 1440), 0, "a second pass must be a no-op, so re-running the migration cannot churn the file" ); } - #[test] - fn delete_plan_defers_files_and_selects_replacement() -> Result<()> { - let mut profiles = IProfiles { - current: Some("a".into()), - items: Some(vec![ - deletion_item("a", "remote", "a.yaml", Some("owned")), - deletion_item("owned", "merge", "owned.yaml", None), - deletion_item("b", "local", "b.yaml", None), - ]), - }; - - let (should_update, plan) = profiles.plan_delete_item("a")?; - - assert!(should_update); - assert_eq!(profiles.current.as_deref(), Some("b")); - assert_eq!(plan.files, vec![String::from("a.yaml"), String::from("owned.yaml")]); - assert!(profiles.get_item("owned").is_err()); - Ok(()) - } - fn selected(group: &str, node: &str) -> PrfSelected { PrfSelected { name: Some(group.into()), diff --git a/src-tauri/src/core/manager/config.rs b/src-tauri/src/core/manager/config.rs index c97ba5df4..7dd783758 100644 --- a/src-tauri/src/core/manager/config.rs +++ b/src-tauri/src/core/manager/config.rs @@ -2,7 +2,7 @@ use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode}; use crate::core::notify::NoticeStatus; use crate::core::service::StageRequest; use crate::{ - config::{Config, IProfiles, runtime::IRuntime}, + config::{Config, IProfiles, profiles::save_profiles, runtime::IRuntime}, constants::timing, core::{ handle, @@ -243,7 +243,7 @@ impl CoreManager { crate::config::profiles::restore_selected_nodes().await; return Ok(Err(outcome)); } - match candidate.save_file().await { + match save_profiles(candidate).await { Ok(()) => { tracing::Span::current().record("outcome", "committed"); Ok(Ok(guard)) diff --git a/src-tauri/src/enhance/mod.rs b/src-tauri/src/enhance/mod.rs index ed541cf4f..766775ded 100644 --- a/src-tauri/src/enhance/mod.rs +++ b/src-tauri/src/enhance/mod.rs @@ -18,7 +18,7 @@ use crate::config::dns::{DnsOverrideState, dns_override_source}; use crate::core::handle::Handle; use crate::utils::dirs; use crate::{ - config::{Config, IProfiles, IVerge, PrfItem}, + config::{Config, IProfiles, IVerge, PrfItem, profiles::current_mapping}, constants, utils::tmpl, }; @@ -174,8 +174,7 @@ async fn collect_profile_items(profiles: &IProfiles) -> Result { None => return Ok(ProfileItems::default()), }; - let current = profiles - .current_mapping() + let current = current_mapping(profiles) .await .with_context(|| format!("failed to read current profile \"{current_profile_uid}\""))?; diff --git a/src-tauri/src/feat/backup.rs b/src-tauri/src/feat/backup.rs index 934ee28e7..21dafb1f5 100644 --- a/src-tauri/src/feat/backup.rs +++ b/src-tauri/src/feat/backup.rs @@ -1,5 +1,5 @@ use crate::{ - config::{Config, IClashTemp, IProfiles, IVerge}, + config::{Config, IClashTemp, IVerge, profiles::load_profiles}, core::{CoreManager, auto_backup, backup, proxy_control, proxy_control::SystemProxyStateUnknown}, process::AsyncHandler, utils::{ @@ -46,7 +46,7 @@ async fn finalize_restored_verge_config( }); clash_draft.apply(); - let restored_profiles = IProfiles::new().await; + let restored_profiles = load_profiles().await; let profiles_draft = Config::profiles().await; profiles_draft.edit_draft(|d| { *d = restored_profiles; diff --git a/src-tauri/src/feat/dns.rs b/src-tauri/src/feat/dns.rs index 0bb2dd624..8c3edf5f4 100644 --- a/src-tauri/src/feat/dns.rs +++ b/src-tauri/src/feat/dns.rs @@ -8,7 +8,7 @@ use crate::{ config::{ Config, dns::{ProfileDnsSettings, dns_override_source}, - profiles::PROFILE_WRITE_LOCK, + profiles::{PROFILE_WRITE_LOCK, current_mapping}, }, constants::files::DNS_CONFIG, core::CoreManager, @@ -36,7 +36,7 @@ pub async fn set_dns_override( ); let source = dns_override_source( profiles.current.as_deref().unwrap_or_default(), - &profiles.current_mapping().await?, + ¤t_mapping(&profiles).await?, )?; if enabled && let Some(source) = source.as_ref().filter(|source| Some(*source) != confirmation.as_ref()) { return Ok(DnsOverrideOutcome::ConfirmationRequired { source: source.clone() }); diff --git a/src-tauri/src/feat/profile.rs b/src-tauri/src/feat/profile.rs index a12c060b4..b05721d28 100644 --- a/src-tauri/src/feat/profile.rs +++ b/src-tauri/src/feat/profile.rs @@ -2,7 +2,7 @@ use crate::core::notify::NoticeStatus; use crate::core::notify::{Refresh, announce}; use crate::{ cmd, - config::{Config, PrfItem, PrfOption, profiles::profiles_update_item_safe}, + config::{Config, PrfOption, fetch_remote_profile, profiles::profiles_update_item_safe}, core::{CoreManager, handle, tray, validate::ValidationOutcome}, process::AsyncHandler, utils::help::{mask_err, mask_url}, @@ -289,7 +289,7 @@ async fn perform_profile_update( } tracing::Span::current().record("strategy", name); let started = std::time::Instant::now(); - let result = PrfItem::from_url(url, None, None, options.as_ref()).await; + let result = fetch_remote_profile(url, None, None, options.as_ref()).await; let elapsed_field = match strategy { Strategy::Configured => "configured_elapsed", Strategy::Clash => "clash_elapsed", diff --git a/src-tauri/src/utils/init.rs b/src-tauri/src/utils/init.rs index 927fc797f..d0ba10f94 100644 --- a/src-tauri/src/utils/init.rs +++ b/src-tauri/src/utils/init.rs @@ -1,5 +1,8 @@ use crate::{ - config::{Config, IClashTemp, IProfiles, IVerge}, + config::{ + Config, IClashTemp, IProfiles, IVerge, + profiles::{raise_short_update_intervals, save_profiles}, + }, constants, core::handle, logging, @@ -266,9 +269,9 @@ pub async fn migrate_short_update_intervals() -> Result<()> { if profiles.items.is_none() { anyhow::bail!("profiles.yaml was not loaded; refusing to record the migration as done"); } - let raised = profiles.raise_short_update_intervals(min); + let raised = raise_short_update_intervals(&mut profiles, min); if raised > 0 { - profiles.save_file().await?; + save_profiles(&profiles).await?; } Ok((profiles, raised)) }) diff --git a/src-tauri/src/utils/resolve/scheme.rs b/src-tauri/src/utils/resolve/scheme.rs index 86aa598fd..a46c5b34a 100644 --- a/src-tauri/src/utils/resolve/scheme.rs +++ b/src-tauri/src/utils/resolve/scheme.rs @@ -5,7 +5,7 @@ use tauri::Url; use tristr::alias::String; use crate::{ - config::{Config, PrfItem, profiles}, + config::{Config, PrfItem, fetch_remote_profile, profiles}, core::{CoreManager, handle, timer::Timer}, utils::help, }; @@ -113,7 +113,7 @@ async fn import_subscription(url: &str, name: Option<&String>) { } async fn fetch_profile_item(url: &str, name: Option<&String>) -> Option { - match PrfItem::from_url(url, name, None, None).await { + match fetch_remote_profile(url, name, None, None).await { Ok(item) => Some(item), Err(e) => { logging!(error, Type::Config, "failed to parse profile from url: {:?}", e); From c6e59ad53874ae221be3c11c26610ca5c061e618 Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:13:53 +0800 Subject: [PATCH 16/33] refactor(profile): separate subscription refresh and scheduling policy Separate download and scheduling policy from the subscription use case while retaining the existing write path. --- crates/clash-verge-profile/src/lib.rs | 2 + .../src/subscription_schedule.rs | 49 +++++ src-tauri/src/cmd/profile.rs | 4 +- src-tauri/src/config/mod.rs | 2 +- src-tauri/src/config/prfitem.rs | 184 ++++++++++++----- src-tauri/src/config/profiles.rs | 56 +++--- src-tauri/src/core/timer.rs | 46 +---- src-tauri/src/feat/mod.rs | 2 + src-tauri/src/feat/profile.rs | 179 +---------------- src-tauri/src/feat/subscription.rs | 185 ++++++++++++++++++ src-tauri/src/utils/resolve/scheme.rs | 4 +- 11 files changed, 407 insertions(+), 306 deletions(-) create mode 100644 crates/clash-verge-profile/src/subscription_schedule.rs create mode 100644 src-tauri/src/feat/subscription.rs diff --git a/crates/clash-verge-profile/src/lib.rs b/crates/clash-verge-profile/src/lib.rs index a92e25033..4f8743f4f 100644 --- a/crates/clash-verge-profile/src/lib.rs +++ b/crates/clash-verge-profile/src/lib.rs @@ -1,6 +1,8 @@ mod error; +mod subscription_schedule; pub use error::ProfileNotFound; +pub use subscription_schedule::SubscriptionSchedule; use serde::{Deserialize, Serialize}; use tristr::alias::String; diff --git a/crates/clash-verge-profile/src/subscription_schedule.rs b/crates/clash-verge-profile/src/subscription_schedule.rs new file mode 100644 index 000000000..58f6d21b2 --- /dev/null +++ b/crates/clash-verge-profile/src/subscription_schedule.rs @@ -0,0 +1,49 @@ +use super::PrfItem; +use std::time::Duration; + +/// Scheduling policy for a Profile, independent of the task queue and clock. +#[derive(Debug, PartialEq, Eq)] +pub struct SubscriptionSchedule { + pub interval_minutes: u64, + pub first_delay: Duration, +} + +impl SubscriptionSchedule { + pub fn for_profile(item: &PrfItem, initializing: bool, now: i64) -> Option { + let option = item.option.as_ref()?; + let interval = option.update_interval.filter(|interval| *interval > 0)?; + if !option.allow_auto_update.unwrap_or(true) { + return None; + } + + let mut schedule = Self::new(interval, item.updated, now); + // Startup historically treats an explicit zero timestamp as overdue. + if initializing && item.updated == Some(0) { + schedule.first_delay = Duration::ZERO; + } + Some(schedule) + } + + pub fn new(interval_minutes: u64, updated: Option, now: i64) -> Self { + let full = Self::interval_duration(interval_minutes); + let elapsed = updated + .filter(|updated| *updated > 0) + .map_or(0, |updated| now.saturating_sub(updated as i64).max(0) as u64); + + Self { + interval_minutes, + first_delay: full.saturating_sub(Duration::from_secs(elapsed)), + } + } + + pub const fn interval_duration(interval_minutes: u64) -> Duration { + Duration::from_secs(interval_minutes.saturating_mul(60)) + } + + /// The UI deadline is based on the last saved update. The queue can delay retries further. + pub fn reported_deadline(interval_minutes: u64, updated: Option) -> Option { + let updated = i64::try_from(updated.filter(|updated| *updated > 0)?).ok()?; + let interval = i64::try_from(interval_minutes).ok()?.checked_mul(60)?; + updated.checked_add(interval) + } +} diff --git a/src-tauri/src/cmd/profile.rs b/src-tauri/src/cmd/profile.rs index a299cdd22..18163b48d 100644 --- a/src-tauri/src/cmd/profile.rs +++ b/src-tauri/src/cmd/profile.rs @@ -5,7 +5,7 @@ use crate::core::notify::NoticeStatus; use crate::utils::window_manager::WindowManager; use crate::{ config::{ - Config, IProfiles, PrfItem, PrfOption, fetch_remote_profile, + Config, IProfiles, PrfItem, PrfOption, build_remote_profile, profiles::{ PROFILE_WRITE_LOCK, cleanup_profile_files, profiles_append_item_safe, profiles_append_item_with_filedata_safe, profiles_patch_item_safe, profiles_reorder_safe, @@ -72,7 +72,7 @@ pub async fn enhance_profiles() -> CmdResult { #[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) -> CmdResult { - let item = &mut match fetch_remote_profile(&url, None, None, option.as_ref()).await { + let item = &mut match build_remote_profile(&url, None, None, option.as_ref()).await { Ok(it) => it, Err(e) => { logging!(error, Type::Cmd, "[导入订阅] 下载失败: {e:#}"); diff --git a/src-tauri/src/config/mod.rs b/src-tauri/src/config/mod.rs index 3ba0084ff..2127ca959 100644 --- a/src-tauri/src/config/mod.rs +++ b/src-tauri/src/config/mod.rs @@ -12,7 +12,7 @@ pub(crate) mod snapshot; mod verge; pub(crate) use self::config::Config; -pub(crate) use self::prfitem::{fetch_remote_profile, read_profile_item_file}; +pub(crate) use self::prfitem::{build_remote_profile, fetch_remote_refresh, read_profile_item_file}; pub use self::{clash::*, encrypt::*, mixed_port::*, profiles::*, verge::*}; pub use clash_verge_profile::{PrfExtra, PrfItem, PrfOption, PrfSelected}; diff --git a/src-tauri/src/config/prfitem.rs b/src-tauri/src/config/prfitem.rs index 83aefa7fd..2eedf9fbf 100644 --- a/src-tauri/src/config/prfitem.rs +++ b/src-tauri/src/config/prfitem.rs @@ -32,7 +32,7 @@ pub(super) async fn build_profile(item: &PrfItem, file_data: Option) -> let name = item.name.as_ref(); let desc = item.desc.as_ref(); let option = item.option.as_ref(); - fetch_remote_profile(url, name, desc, option).await + build_remote_profile(url, name, desc, option).await } "local" => { let name = item.name.clone().unwrap_or_else(|| "Local File".into()); @@ -117,24 +117,72 @@ async fn from_local( }) } -pub(crate) async fn fetch_remote_profile( +struct DownloadedSubscription { + url: Url, + suggested_name: Option, + extra: Option, + update_interval_minutes: Option, + home: Option, + body: String, +} + +pub(crate) struct RemoteProfileRefresh { + pub(super) extra: Option, + pub(super) home: Option, + pub(super) updated: usize, + pub(super) option: PrfOption, + pub(super) body: String, +} + +pub(crate) async fn build_remote_profile( url: &str, name: Option<&String>, desc: Option<&String>, option: Option<&PrfOption>, ) -> Result { + let mut downloaded = download_subscription(url, option).await?; + let uid: String = help::get_uid("R").into(); + let file = format!("{uid}.yaml").into(); + let name = name + .cloned() + .or_else(|| downloaded.suggested_name.take().map(Into::into)) + .unwrap_or_else(|| "Remote File".into()); + let url = downloaded.url.as_str().into(); + let RemoteProfileRefresh { + extra, + home, + updated, + option, + body, + } = prepare_remote_refresh(downloaded, option).await?; + + Ok(PrfItem { + uid: Some(uid), + itype: Some("remote".into()), + name: Some(name), + desc: desc.cloned(), + file: Some(file), + url: Some(url), + selected: None, + extra, + option: Some(option), + home, + updated: Some(updated), + file_data: Some(body), + }) +} + +pub(crate) async fn fetch_remote_refresh(url: &str, option: Option<&PrfOption>) -> Result { + let downloaded = download_subscription(url, option).await?; + prepare_remote_refresh(downloaded, option).await +} + +async fn download_subscription(url: &str, option: Option<&PrfOption>) -> Result { let with_proxy = option.is_some_and(|o| o.with_proxy.unwrap_or(false)); let self_proxy = option.is_some_and(|o| o.self_proxy.unwrap_or(false)); let accept_invalid_certs = option.is_some_and(|o| o.danger_accept_invalid_certs.unwrap_or(false)); - let allow_auto_update = Some(allow_auto_update_enabled(option)); let user_agent = option.and_then(|o| o.user_agent.clone()); - let update_interval = option.and_then(|o| o.update_interval); let timeout = option.and_then(|o| o.timeout_seconds).unwrap_or(20); - let mut merge = option.and_then(|o| o.merge.clone()); - let mut script = option.and_then(|o| o.script.clone()); - let mut rules = option.and_then(|o| o.rules.clone()); - let mut proxies = option.and_then(|o| o.proxies.clone()); - let mut groups = option.and_then(|o| o.groups.clone()); let proxy_type = if self_proxy { ProxyType::Localhost @@ -151,7 +199,7 @@ pub(crate) async fn fetch_remote_profile( url.as_str(), proxy_type, Some(timeout), - user_agent.clone(), + user_agent, accept_invalid_certs, ) .await @@ -169,43 +217,52 @@ pub(crate) async fn fetch_remote_profile( } let document = decode_subscription(&url, resp.headers(), resp.text())?; - let update_interval = update_interval.or(document.update_interval_minutes); let extra = document.usage.map(|usage| PrfExtra { upload: usage.upload, download: usage.download, total: usage.total, expire: usage.expire, }); - let uid = help::get_uid("R").into(); - let file = format!("{uid}.yaml").into(); - let name = name - .cloned() - .unwrap_or_else(|| document.filename.map_or_else(|| "Remote File".into(), Into::into)); - - ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?; - - Ok(PrfItem { - uid: Some(uid), - itype: Some("remote".into()), - name: Some(name), - desc: desc.cloned(), - file: Some(file), - url: Some(url.as_str().into()), - selected: None, - extra, - option: Some(PrfOption { - update_interval, - merge, - script, - rules, - proxies, - groups, - allow_auto_update, - ..PrfOption::default() - }), + Ok(DownloadedSubscription { + suggested_name: document.filename, + update_interval_minutes: document.update_interval_minutes, home: document.home.map(Into::into), - updated: Some(chrono::Local::now().timestamp() as usize), - file_data: Some(document.body.into()), + body: document.body.into(), + url, + extra, + }) +} + +async fn prepare_remote_refresh( + downloaded: DownloadedSubscription, + option: Option<&PrfOption>, +) -> Result { + let mut resolved = PrfOption { + update_interval: option + .and_then(|o| o.update_interval) + .or(downloaded.update_interval_minutes), + merge: option.and_then(|o| o.merge.clone()), + script: option.and_then(|o| o.script.clone()), + rules: option.and_then(|o| o.rules.clone()), + proxies: option.and_then(|o| o.proxies.clone()), + groups: option.and_then(|o| o.groups.clone()), + allow_auto_update: Some(allow_auto_update_enabled(option)), + ..PrfOption::default() + }; + ensure_companion_items( + &mut resolved.merge, + &mut resolved.script, + &mut resolved.rules, + &mut resolved.proxies, + &mut resolved.groups, + ) + .await?; + Ok(RemoteProfileRefresh { + extra: downloaded.extra, + home: downloaded.home, + updated: chrono::Local::now().timestamp() as usize, + option: resolved, + body: downloaded.body, }) } @@ -321,20 +378,11 @@ mod tests { }; #[tokio::test] - async fn fetch_remote_profile_maps_response_to_profile_model() -> Result<()> { + async fn import_and_refresh_share_subscription_decoding() -> Result<()> { const BODY: &str = "# keep this comment\nproxies: []\n"; let listener = TcpListener::bind("127.0.0.1:0").await?; let url = format!("http://{}/subscription", listener.local_addr()?); let server = tokio::spawn(async move { - let (socket, _) = listener.accept().await?; - let mut socket = BufReader::new(socket); - let mut line = std::string::String::new(); - loop { - line.clear(); - if socket.read_line(&mut line).await? == 0 || line == "\r\n" { - break; - } - } let response = format!( "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\ Content-Disposition: attachment; filename=remote.yaml\r\n\ @@ -343,7 +391,19 @@ mod tests { Subscription-Userinfo: upload=1; download=2; total=3; expire=4\r\n\r\n{BODY}", BODY.len() ); - socket.get_mut().write_all(response.as_bytes()).await + for _ in 0..2 { + let (socket, _) = listener.accept().await?; + let mut socket = BufReader::new(socket); + let mut line = std::string::String::new(); + loop { + line.clear(); + if socket.read_line(&mut line).await? == 0 || line == "\r\n" { + break; + } + } + socket.get_mut().write_all(response.as_bytes()).await?; + } + Ok::<_, std::io::Error>(()) }); let option = PrfOption { update_interval: Some(0), @@ -356,7 +416,15 @@ mod tests { groups: Some("test-groups".into()), ..Default::default() }; - let item: clash_verge_profile::PrfItem = fetch_remote_profile(&url, None, None, Some(&option)).await?; + let item: clash_verge_profile::PrfItem = build_remote_profile(&url, None, None, Some(&option)).await?; + let refresh = fetch_remote_refresh( + &url, + Some(&PrfOption { + update_interval: None, + ..option + }), + ) + .await?; server.await??; assert_eq!(item.itype.as_deref(), Some("remote")); assert_eq!(item.name.as_deref(), Some("remote.yaml")); @@ -368,6 +436,18 @@ mod tests { let fetched_option = item.option.context("expected profile options")?; assert_eq!(fetched_option.update_interval, Some(0)); assert_eq!(fetched_option.allow_auto_update, Some(false)); + + assert_eq!(refresh.body.as_str(), BODY); + assert_eq!(refresh.home, item.home); + let usage = refresh.extra.context("expected refresh usage")?; + assert_eq!((usage.upload, usage.download, usage.total, usage.expire), (1, 2, 3, 4)); + assert_eq!( + refresh.option, + PrfOption { + update_interval: Some(120), + ..fetched_option + } + ); Ok(()) } } diff --git a/src-tauri/src/config/profiles.rs b/src-tauri/src/config/profiles.rs index 3fb44b26c..6a5ef1107 100644 --- a/src-tauri/src/config/profiles.rs +++ b/src-tauri/src/config/profiles.rs @@ -1,4 +1,7 @@ -use super::{PrfItem, PrfOption, PrfSelected, patch_opt_field, prfitem::build_profile}; +use super::{ + PrfItem, PrfOption, PrfSelected, patch_opt_field, + prfitem::{RemoteProfileRefresh, build_profile}, +}; use crate::core::notify::{Refresh, announce}; use crate::utils::retry::{RetryError, RetryPolicy, retry, retry_with_state}; use crate::{ @@ -188,37 +191,26 @@ fn validate_profile_file(file: &str) -> Result<()> { } /// Updates fields returned by a remote profile refresh. -async fn update_item(profiles: &mut IProfiles, uid: &str, item: &mut PrfItem) -> Result<()> { - if profiles.items.is_none() { - profiles.items = Some(vec![]); - } - +async fn apply_remote_refresh(profiles: &mut IProfiles, uid: &str, refresh: RemoteProfileRefresh) -> Result<()> { let _ = profiles.get_item(uid)?; - if let Some(items) = profiles.items.as_mut() { - for each in items.iter_mut() { - if each.uid.as_deref() == Some(uid) { - each.extra = item.extra; - each.updated = item.updated; - each.home = item.home.to_owned(); - each.option = PrfOption::merge(each.option.as_ref(), item.option.as_ref()); - if let Some(file_data) = item.file_data.take() { - let file = each.file.take(); - let file = - file.unwrap_or_else(|| item.file.take().unwrap_or_else(|| format!("{}.yaml", uid).into())); - - each.file = Some(file.clone()); - - let path = dirs::app_profiles_dir()?.join(file.as_str()); - - fs::write(&path, file_data.as_bytes()) - .await - .with_context(|| format!("failed to write to file \"{file}\""))?; - } - - break; - } - } + if let Some(each) = profiles + .items + .iter_mut() + .flatten() + .find(|item| item.uid.as_deref() == Some(uid)) + { + each.extra = refresh.extra; + each.updated = Some(refresh.updated); + each.home = refresh.home; + each.option = PrfOption::merge(each.option.as_ref(), Some(&refresh.option)); + let file = each + .file + .get_or_insert_with(|| format!("{}.yaml", help::get_uid("R")).into()); + let path = dirs::app_profiles_dir()?.join(file.as_str()); + fs::write(&path, refresh.body.as_bytes()) + .await + .with_context(|| format!("failed to write to file \"{file}\""))?; } save_profiles(profiles).await @@ -320,9 +312,9 @@ pub(crate) async fn profiles_save_file_safe() -> Result<()> { with_profiles_edit(|profiles| async move { save_profiles(&profiles).await.map(|_| profiles) }).await } -pub(crate) async fn profiles_update_item_safe(index: &str, item: &mut PrfItem) -> Result<()> { +pub(crate) async fn apply_remote_refresh_safe(index: &str, refresh: RemoteProfileRefresh) -> Result<()> { with_profiles_edit(|mut profiles| async move { - update_item(&mut profiles, index, item).await?; + apply_remote_refresh(&mut profiles, index, refresh).await?; Ok(profiles) }) .await diff --git a/src-tauri/src/core/timer.rs b/src-tauri/src/core/timer.rs index d1051b3cd..bae8efb21 100644 --- a/src-tauri/src/core/timer.rs +++ b/src-tauri/src/core/timer.rs @@ -8,6 +8,7 @@ use crate::{ use anyhow::{Context as _, Result}; use clash_verge_draft::Draft; use clash_verge_logging::{Type, logging, logging_error}; +use clash_verge_profile::SubscriptionSchedule as TaskSchedule; use futures::{FutureExt as _, StreamExt as _}; use std::{collections::HashMap, panic::AssertUnwindSafe, time::Duration}; use tokio::{ @@ -24,28 +25,6 @@ enum TimerCommand { TaskFinished(String), } -/// Next update is due at `updated + interval`, but the queue only takes a delay from now. -#[derive(Debug, PartialEq, Eq)] -struct TaskSchedule { - interval_minutes: u64, - first_delay: Duration, -} - -impl TaskSchedule { - /// No recorded `updated` -> full interval. Deadline already past -> `ZERO`, fires at once. - fn new(interval_minutes: u64, updated: Option, now: i64) -> Self { - let full = Timer::interval_duration(interval_minutes); - let elapsed = updated - .filter(|updated| *updated > 0) - .map_or(0, |updated| now.saturating_sub(updated as i64).max(0) as u64); - - Self { - interval_minutes, - first_delay: full.saturating_sub(Duration::from_secs(elapsed)), - } - } -} - struct TaskState { key: Option, interval_minutes: u64, @@ -122,16 +101,9 @@ impl Timer { let mut new_map = HashMap::new(); for item in items { - if let Some(option) = item.option.as_ref() - && let (Some(interval), Some(uid)) = (option.update_interval, &item.uid) - && option.allow_auto_update.unwrap_or(true) - && interval > 0 + if let Some(uid) = &item.uid + && let Some(schedule) = TaskSchedule::for_profile(item, initializing, now) { - let mut schedule = TaskSchedule::new(interval, item.updated, now); - // Startup historically treats an explicit zero timestamp as overdue. - if initializing && item.updated == Some(0) { - schedule.first_delay = Duration::ZERO; - } new_map.insert(uid.clone(), schedule); } } @@ -317,7 +289,7 @@ impl Timer { // Full interval, not from `updated`: a failed run leaves `updated` in the past, so // counting from it would retry at zero delay and spin. - let key = Self::schedule_task(queue, &uid, Self::interval_duration(state.interval_minutes)); + let key = Self::schedule_task(queue, &uid, TaskSchedule::interval_duration(state.interval_minutes)); state.key = Some(key); } @@ -330,10 +302,6 @@ impl Timer { }); } - const fn interval_duration(interval_minutes: u64) -> Duration { - Duration::from_secs(interval_minutes.saturating_mul(60)) - } - fn schedule_task(queue: &mut DelayQueue, uid: &str, delay: Duration) -> Key { queue.insert(String::from(uid), delay) } @@ -348,10 +316,8 @@ impl Timer { fn next_update_time(tasks: &HashMap, profiles: &IProfiles, uid: &str) -> Option { let task = tasks.get(uid).filter(|task| !task.retired)?; - let updated = profiles.get_item(uid).ok()?.updated.filter(|updated| *updated > 0)?; - let updated = i64::try_from(updated).ok()?; - let interval = i64::try_from(task.interval_minutes).ok()?.checked_mul(60)?; - updated.checked_add(interval) + let updated = profiles.get_item(uid).ok()?.updated; + TaskSchedule::reported_deadline(task.interval_minutes, updated) } fn emit_update_event(uid: &str, is_start: bool) { diff --git a/src-tauri/src/feat/mod.rs b/src-tauri/src/feat/mod.rs index 6cf5fcb8c..f9ce00d87 100644 --- a/src-tauri/src/feat/mod.rs +++ b/src-tauri/src/feat/mod.rs @@ -9,6 +9,7 @@ mod icon; mod listener; mod profile; mod proxy; +mod subscription; mod tun; mod window; @@ -22,5 +23,6 @@ pub use icon::*; pub use listener::*; pub use profile::*; pub use proxy::*; +pub use subscription::update_profile; pub use tun::*; pub use window::*; diff --git a/src-tauri/src/feat/profile.rs b/src-tauri/src/feat/profile.rs index b05721d28..5faa49faa 100644 --- a/src-tauri/src/feat/profile.rs +++ b/src-tauri/src/feat/profile.rs @@ -1,13 +1,11 @@ -use crate::core::notify::NoticeStatus; use crate::core::notify::{Refresh, announce}; use crate::{ cmd, - config::{Config, PrfOption, fetch_remote_profile, profiles::profiles_update_item_safe}, + config::Config, core::{CoreManager, handle, tray, validate::ValidationOutcome}, process::AsyncHandler, - utils::help::{mask_err, mask_url}, }; -use anyhow::{Result, bail}; +use anyhow::Result; use clash_verge_logging::{Type, logging}; use std::collections::{HashMap, HashSet}; use tauri_plugin_mihomo::models::{Proxy, ProxyType, Rule}; @@ -201,179 +199,6 @@ async fn finish_proxy_switch(stale_proxies: Vec) { } } -async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result)>> { - let profiles = Config::profiles().await; - let profiles = profiles.latest_arc(); - let item = profiles.get_item(uid)?; - let is_remote = item.itype.as_ref().is_some_and(|s| s == "remote"); - - if !is_remote { - logging!(info, Type::Config, "[订阅更新] 不是远程订阅,跳过更新"); - Ok(None) - } else if item.url.is_none() { - logging!(warn, Type::Config, "[订阅更新] 缺少URL,无法更新"); - bail!("failed to get the profile item url"); - } else if !ignore_auto_update && !item.option.as_ref().and_then(|o| o.allow_auto_update).unwrap_or(true) { - logging!(info, Type::Config, "[订阅更新] 禁止自动更新,跳过更新"); - Ok(None) - } else { - logging!( - info, - Type::Config, - "[订阅更新] 远程订阅,URL: {}", - mask_url( - item.url - .as_ref() - .ok_or_else(|| anyhow::anyhow!("Profile URL is None"))? - ) - ); - Ok(Some(( - item.url.clone().ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?, - item.option.clone(), - ))) - } -} - -#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))] -async fn perform_profile_update( - uid: &str, - url: &str, - opt: Option<&PrfOption>, - option: Option<&PrfOption>, - is_mannual_trigger: bool, -) -> Result<()> { - let merged_opt = PrfOption::merge(opt, option); - let profiles = Config::profiles().await; - let profiles_arc = profiles.latest_arc(); - let profile_name = profiles_arc - .get_item(uid) - .ok() - .and_then(|item| item.name.clone()) - .unwrap_or_else(|| String::from("UnKnown Profile")); - - #[derive(Clone, Copy)] - enum Strategy { - Configured, - Clash, - System, - } - - let result = - crate::utils::retry::try_strategies(Strategy::Configured, [Strategy::Clash, Strategy::System], |strategy| { - let mut options = merged_opt.clone(); - async move { - let (name, success, failure) = match strategy { - Strategy::Configured => ( - "configured", - "[订阅更新] 更新订阅配置成功", - "[订阅更新] 直接更新失败: {},尝试使用Clash代理更新", - ), - Strategy::Clash => ( - "clash", - "[订阅更新] 使用 Clash代理 更新订阅配置成功", - "[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新", - ), - Strategy::System => ( - "system", - "[订阅更新] 使用 系统代理 更新订阅配置成功", - "[订阅更新] 系统代理更新失败: {},所有重试均已失败", - ), - }; - match strategy { - Strategy::Configured => {} - Strategy::Clash | Strategy::System => { - let option = options.get_or_insert_with(PrfOption::default); - option.self_proxy = Some(matches!(strategy, Strategy::Clash)); - option.with_proxy = Some(matches!(strategy, Strategy::System)); - } - } - tracing::Span::current().record("strategy", name); - let started = std::time::Instant::now(); - let result = fetch_remote_profile(url, None, None, options.as_ref()).await; - let elapsed_field = match strategy { - Strategy::Configured => "configured_elapsed", - Strategy::Clash => "clash_elapsed", - Strategy::System => "system_elapsed", - }; - tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed())); - match &result { - Ok(_) => logging!(info, Type::Config, "{success}"), - Err(error) => logging!( - warn, - Type::Config, - "{}", - failure.replace("{}", &mask_err(&format!("{error:#}"))) - ), - } - result - } - }) - .await; - let last_err = match result { - Ok((strategy, mut item)) => { - // A persistence error must not replay a successful download with another transport. - profiles_update_item_safe(uid, &mut item).await?; - if !matches!(strategy, Strategy::Configured) { - handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str()); - } - return Ok(()); - } - Err(error) => error, - }; - - let last_err = mask_err(&last_err.to_string()); - if is_mannual_trigger { - handle::Handle::notice( - NoticeStatus::UpdateFailedEvenWithClash, - format!("{profile_name} - {last_err}"), - ); - } - bail!(last_err) -} - -#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_mannual_trigger))] -pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_mannual_trigger: bool) -> Result<()> { - let url_opt = should_update_profile(uid, is_mannual_trigger).await?; - - let profile_persisted = match url_opt { - Some((url, opt)) => { - perform_profile_update(uid, &url, opt.as_ref(), option, is_mannual_trigger).await?; - true - } - None => false, - }; - let profiles = Config::profiles().await; - let is_current = profiles.latest_arc().current.as_deref() == Some(uid); - let should_refresh = is_current || (!profile_persisted && is_mannual_trigger); - - if should_refresh { - logging!(debug, Type::Config, "[订阅更新] 更新内核配置"); - match CoreManager::global().update_config_with_force(is_mannual_trigger).await { - Ok(outcome) if outcome.is_valid() => announce(Refresh::Clash), - Ok(outcome @ (ValidationOutcome::Skipped { .. } | ValidationOutcome::Busy)) if !is_mannual_trigger => { - logging!(info, Type::Config, "[订阅更新] 本次配置刷新已跳过: {}", outcome); - } - result => { - let message = match result { - Ok(outcome) => outcome.to_string(), - Err(err) => err.to_string(), - }; - let message = mask_err(&message); - let message = if profile_persisted { - format!("订阅已保存,但未能确认已应用到内核: {message}") - } else { - message - }; - logging!(error, Type::Config, "[订阅更新] 更新失败: {}", message); - handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str()); - bail!(message); - } - } - } - - Ok(()) -} - /// 增强配置 pub async fn enhance_profiles() -> Result { CoreManager::global().update_config_forced().await diff --git a/src-tauri/src/feat/subscription.rs b/src-tauri/src/feat/subscription.rs new file mode 100644 index 000000000..47a0ca545 --- /dev/null +++ b/src-tauri/src/feat/subscription.rs @@ -0,0 +1,185 @@ +use crate::{ + config::{Config, PrfOption, fetch_remote_refresh, profiles::apply_remote_refresh_safe}, + core::{ + CoreManager, handle, + notify::{NoticeStatus, Refresh, announce}, + validate::ValidationOutcome, + }, + utils::help::{mask_err, mask_url}, +}; +use anyhow::{Result, bail}; +use clash_verge_logging::{Type, logging}; +use tristr::alias::String; + +async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result)>> { + let profiles = Config::profiles().await; + let profiles = profiles.latest_arc(); + let item = profiles.get_item(uid)?; + let is_remote = item.itype.as_ref().is_some_and(|s| s == "remote"); + + if !is_remote { + logging!(info, Type::Config, "[订阅更新] 不是远程订阅,跳过更新"); + Ok(None) + } else if item.url.is_none() { + logging!(warn, Type::Config, "[订阅更新] 缺少URL,无法更新"); + bail!("failed to get the profile item url"); + } else if !ignore_auto_update && !item.option.as_ref().and_then(|o| o.allow_auto_update).unwrap_or(true) { + logging!(info, Type::Config, "[订阅更新] 禁止自动更新,跳过更新"); + Ok(None) + } else { + logging!( + info, + Type::Config, + "[订阅更新] 远程订阅,URL: {}", + mask_url( + item.url + .as_ref() + .ok_or_else(|| anyhow::anyhow!("Profile URL is None"))? + ) + ); + Ok(Some(( + item.url.clone().ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?, + item.option.clone(), + ))) + } +} + +#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))] +async fn perform_profile_update( + uid: &str, + url: &str, + opt: Option<&PrfOption>, + option: Option<&PrfOption>, + is_manual_trigger: bool, +) -> Result<()> { + let merged_opt = PrfOption::merge(opt, option); + let profiles = Config::profiles().await; + let profiles_arc = profiles.latest_arc(); + let profile_name = profiles_arc + .get_item(uid) + .ok() + .and_then(|item| item.name.clone()) + .unwrap_or_else(|| String::from("UnKnown Profile")); + + #[derive(Clone, Copy)] + enum Strategy { + Configured, + Clash, + System, + } + + let result = + crate::utils::retry::try_strategies(Strategy::Configured, [Strategy::Clash, Strategy::System], |strategy| { + let mut options = merged_opt.clone(); + async move { + let (name, success, failure) = match strategy { + Strategy::Configured => ( + "configured", + "[订阅更新] 更新订阅配置成功", + "[订阅更新] 直接更新失败: {},尝试使用Clash代理更新", + ), + Strategy::Clash => ( + "clash", + "[订阅更新] 使用 Clash代理 更新订阅配置成功", + "[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新", + ), + Strategy::System => ( + "system", + "[订阅更新] 使用 系统代理 更新订阅配置成功", + "[订阅更新] 系统代理更新失败: {},所有重试均已失败", + ), + }; + match strategy { + Strategy::Configured => {} + Strategy::Clash | Strategy::System => { + let option = options.get_or_insert_with(PrfOption::default); + option.self_proxy = Some(matches!(strategy, Strategy::Clash)); + option.with_proxy = Some(matches!(strategy, Strategy::System)); + } + } + tracing::Span::current().record("strategy", name); + let started = std::time::Instant::now(); + let result = fetch_remote_refresh(url, options.as_ref()).await; + let elapsed_field = match strategy { + Strategy::Configured => "configured_elapsed", + Strategy::Clash => "clash_elapsed", + Strategy::System => "system_elapsed", + }; + tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed())); + match &result { + Ok(_) => logging!(info, Type::Config, "{success}"), + Err(error) => logging!( + warn, + Type::Config, + "{}", + failure.replace("{}", &mask_err(&format!("{error:#}"))) + ), + } + result + } + }) + .await; + let last_err = match result { + Ok((strategy, refresh)) => { + // A persistence error must not replay a successful download with another transport. + apply_remote_refresh_safe(uid, refresh).await?; + if !matches!(strategy, Strategy::Configured) { + handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str()); + } + return Ok(()); + } + Err(error) => error, + }; + + let last_err = mask_err(&last_err.to_string()); + if is_manual_trigger { + handle::Handle::notice( + NoticeStatus::UpdateFailedEvenWithClash, + format!("{profile_name} - {last_err}"), + ); + } + bail!(last_err) +} + +#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_manual_trigger))] +pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_manual_trigger: bool) -> Result<()> { + let url_opt = should_update_profile(uid, is_manual_trigger).await?; + + let profile_persisted = match url_opt { + Some((url, opt)) => { + perform_profile_update(uid, &url, opt.as_ref(), option, is_manual_trigger).await?; + true + } + None => false, + }; + let profiles = Config::profiles().await; + let is_current = profiles.latest_arc().current.as_deref() == Some(uid); + let should_refresh = is_current || (!profile_persisted && is_manual_trigger); + + if should_refresh { + logging!(debug, Type::Config, "[订阅更新] 更新内核配置"); + match CoreManager::global().update_config_with_force(is_manual_trigger).await { + Ok(outcome) if outcome.is_valid() => announce(Refresh::Clash), + Ok(outcome @ (ValidationOutcome::Skipped { .. } | ValidationOutcome::Busy)) if !is_manual_trigger => { + logging!(info, Type::Config, "[订阅更新] 本次配置刷新已跳过: {}", outcome); + } + result => { + let message = match result { + Ok(outcome) => outcome.to_string(), + Err(err) => err.to_string(), + }; + let message = mask_err(&message); + let message = if profile_persisted { + format!("订阅已保存,但未能确认已应用到内核: {message}") + } else { + message + }; + logging!(error, Type::Config, "[订阅更新] 更新失败: {}", message); + handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str()); + bail!(message); + } + } + } + + Ok(()) +} diff --git a/src-tauri/src/utils/resolve/scheme.rs b/src-tauri/src/utils/resolve/scheme.rs index a46c5b34a..c507bad8f 100644 --- a/src-tauri/src/utils/resolve/scheme.rs +++ b/src-tauri/src/utils/resolve/scheme.rs @@ -5,7 +5,7 @@ use tauri::Url; use tristr::alias::String; use crate::{ - config::{Config, PrfItem, fetch_remote_profile, profiles}, + config::{Config, PrfItem, build_remote_profile, profiles}, core::{CoreManager, handle, timer::Timer}, utils::help, }; @@ -113,7 +113,7 @@ async fn import_subscription(url: &str, name: Option<&String>) { } async fn fetch_profile_item(url: &str, name: Option<&String>) -> Option { - match fetch_remote_profile(url, name, None, None).await { + match build_remote_profile(url, name, None, None).await { Ok(item) => Some(item), Err(e) => { logging!(error, Type::Config, "failed to parse profile from url: {:?}", e); From 85c0a60ddbc78146d5c4eefa5187023bd6448afd Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:09:13 +0800 Subject: [PATCH 17/33] refactor(subscription): decode deep links in the subscription crate --- .../clash-verge-subscription/src/deep_link.rs | 59 +++++++++++++++++++ crates/clash-verge-subscription/src/lib.rs | 2 + src-tauri/src/utils/resolve/scheme.rs | 48 ++------------- 3 files changed, 65 insertions(+), 44 deletions(-) create mode 100644 crates/clash-verge-subscription/src/deep_link.rs diff --git a/crates/clash-verge-subscription/src/deep_link.rs b/crates/clash-verge-subscription/src/deep_link.rs new file mode 100644 index 000000000..d0ea94c16 --- /dev/null +++ b/crates/clash-verge-subscription/src/deep_link.rs @@ -0,0 +1,59 @@ +use percent_encoding::percent_decode_str; +use std::borrow::Cow; +use url::Url; + +pub struct SubscriptionLink<'a> { + pub url: Cow<'a, str>, + pub name: Option>, +} + +pub fn decode_subscription_link(link: &Url) -> Option> { + if !matches!(link.scheme(), "clash" | "clash-verge") { + return None; + } + + // The embedded URL can contain unescaped query separators of its own. + let raw_url = link.query()?.split_once("url=")?.1.trim(); + let name = link.query_pairs().find(|(key, _)| key == "name").map(|(_, name)| name); + Some(SubscriptionLink { + url: decode_subscription_url(raw_url), + name, + }) +} + +fn decode_subscription_url(raw_url: &str) -> Cow<'_, str> { + let mut candidate = Cow::Borrowed(raw_url); + if Url::parse(raw_url).is_ok() { + return candidate; + } + + for _ in 0..2 { + let decoded = percent_decode_str(&candidate).decode_utf8_lossy(); + if decoded == candidate { + break; + } + candidate = Cow::Owned(decoded.into_owned()); + if Url::parse(&candidate).is_ok() { + break; + } + } + candidate +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn preserves_nested_query_separators_and_decodes_wrapped_links() -> Result<(), url::ParseError> { + let plain = Url::parse("clash://install-config?name=Work%20VPN&url=https://example.invalid/sub?a=1&b=2")?; + let link = decode_subscription_link(&plain).expect("plain subscription link"); + assert_eq!(link.name.as_deref(), Some("Work VPN")); + assert!(matches!(link.url, Cow::Borrowed("https://example.invalid/sub?a=1&b=2"))); + + let encoded = Url::parse("clash-verge://install-config?url=https%253A%252F%252Fexample.invalid%252Fsub")?; + let link = decode_subscription_link(&encoded).expect("double-encoded subscription link"); + assert_eq!(link.url, "https://example.invalid/sub"); + Ok(()) + } +} diff --git a/crates/clash-verge-subscription/src/lib.rs b/crates/clash-verge-subscription/src/lib.rs index 367cccedd..fd2cbdd76 100644 --- a/crates/clash-verge-subscription/src/lib.rs +++ b/crates/clash-verge-subscription/src/lib.rs @@ -1,5 +1,7 @@ +mod deep_link; mod error; +pub use deep_link::{SubscriptionLink, decode_subscription_link}; pub use error::SubscriptionError; use http::HeaderMap; diff --git a/src-tauri/src/utils/resolve/scheme.rs b/src-tauri/src/utils/resolve/scheme.rs index c507bad8f..b16ffa448 100644 --- a/src-tauri/src/utils/resolve/scheme.rs +++ b/src-tauri/src/utils/resolve/scheme.rs @@ -1,6 +1,5 @@ use crate::core::notify::NoticeStatus; use anyhow::Result; -use percent_encoding::percent_decode_str; use tauri::Url; use tristr::alias::String; @@ -10,6 +9,7 @@ use crate::{ utils::help, }; use clash_verge_logging::{Type, logging, logging_error}; +use clash_verge_subscription::decode_subscription_link; pub(super) async fn resolve_scheme(param: &str) -> Result<()> { let param_str = if param.starts_with("[") && param.len() > 4 { @@ -26,7 +26,7 @@ pub(super) async fn resolve_scheme(param: &str) -> Result<()> { let link_parsed = Url::parse(param_str) .map_err(|e| anyhow::anyhow!("failed to parse deep link: {e:?}, param: {masked_deep_link}"))?; - let Some((url, name)) = extract_subscription_info(&link_parsed) else { + let Some(link) = decode_subscription_link(&link_parsed) else { logging!( warn, Type::Config, @@ -35,51 +35,11 @@ pub(super) async fn resolve_scheme(param: &str) -> Result<()> { return Ok(()); }; - import_subscription(&url, name.as_ref()).await; + let name = link.name.map(String::from); + import_subscription(&link.url, name.as_ref()).await; Ok(()) } -fn extract_subscription_info(link_parsed: &Url) -> Option<(std::string::String, Option)> { - if !matches!(link_parsed.scheme(), "clash" | "clash-verge") { - return None; - } - - let name = link_parsed - .query_pairs() - .find(|(key, _)| key == "name") - .map(|(_, value)| value.into()); - let url = extract_subscription_url(link_parsed)?; - Some((url, name)) -} - -fn extract_subscription_url(link_parsed: &Url) -> Option { - let query = link_parsed.query()?; - let prefix = "url="; - let pos = query.find(prefix)?; - let raw_url = query[pos + prefix.len()..].trim(); - Some(decode_subscription_url(raw_url)) -} - -fn decode_subscription_url(raw_url: &str) -> std::string::String { - // Avoid double-decoding nested subscription URLs; decode only when needed. - if Url::parse(raw_url).is_ok() { - return raw_url.to_string(); - } - - let mut candidate = raw_url.to_string(); - for _ in 0..2 { - let next = percent_decode_str(&candidate).decode_utf8_lossy().to_string(); - if next == candidate { - break; - } - candidate = next; - if Url::parse(&candidate).is_ok() { - break; - } - } - candidate -} - async fn import_subscription(url: &str, name: Option<&String>) { let had_current_profile = { let profiles = Config::profiles().await; From 00cb43f5de3e249798a43546a1688e3d3c57b9af Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:20:46 +0800 Subject: [PATCH 18/33] refactor(profile): extract selected node recovery rules --- crates/clash-verge-profile/src/lib.rs | 1 + .../clash-verge-profile/src/selected_nodes.rs | 147 ++++++++++++ src-tauri/src/config/profiles.rs | 210 +++++------------- 3 files changed, 202 insertions(+), 156 deletions(-) create mode 100644 crates/clash-verge-profile/src/selected_nodes.rs diff --git a/crates/clash-verge-profile/src/lib.rs b/crates/clash-verge-profile/src/lib.rs index 4f8743f4f..6f2a354d0 100644 --- a/crates/clash-verge-profile/src/lib.rs +++ b/crates/clash-verge-profile/src/lib.rs @@ -1,4 +1,5 @@ mod error; +pub mod selected_nodes; mod subscription_schedule; pub use error::ProfileNotFound; diff --git a/crates/clash-verge-profile/src/selected_nodes.rs b/crates/clash-verge-profile/src/selected_nodes.rs new file mode 100644 index 000000000..a9d1c9cd5 --- /dev/null +++ b/crates/clash-verge-profile/src/selected_nodes.rs @@ -0,0 +1,147 @@ +use super::PrfSelected; +use std::collections::HashSet; +use tristr::alias::String; + +pub struct SelectedGroup<'a> { + pub members: Option<&'a [std::string::String]>, + pub current: Option<&'a str>, + pub selectable: bool, +} + +#[derive(Debug, PartialEq, Eq)] +pub struct SelectedNodesPlan { + pub selected: Vec, + pub activations: Vec<(String, String)>, + pub repaired_count: usize, +} + +fn node_is_available(available_nodes: &[std::string::String], node: &str) -> bool { + available_nodes.iter().any(|available| available == node) +} + +pub fn selected_nodes_need_confirmation<'a, Snapshot>( + selected: &[PrfSelected], + snapshot: &'a Snapshot, + lookup: impl Fn(&'a Snapshot, &str) -> Option>, +) -> bool { + selected.iter().any(|selected_item| { + let (Some(group_name), Some(node)) = (&selected_item.name, &selected_item.now) else { + return false; + }; + let Some(group) = lookup(snapshot, group_name) else { + return true; + }; + let Some(available_nodes) = group.members.filter(|nodes| !nodes.is_empty()) else { + return true; + }; + !node_is_available(available_nodes, node) + }) +} + +pub fn reconcile_selected_nodes<'a, Snapshot>( + selected: &[PrfSelected], + previous: Option<&'a Snapshot>, + current: &'a Snapshot, + lookup: impl Fn(&'a Snapshot, &str) -> Option>, +) -> SelectedNodesPlan { + let mut plan = SelectedNodesPlan { + selected: Vec::with_capacity(selected.len()), + activations: Vec::new(), + repaired_count: 0, + }; + let mut seen_groups = HashSet::new(); + let mut unique_selected = selected + .iter() + .rev() + .filter(|item| item.name.as_deref().is_some_and(|name| seen_groups.insert(name))) + .collect::>(); + unique_selected.reverse(); + plan.repaired_count += selected.len() - unique_selected.len(); + + for selected_item in unique_selected { + let (Some(group_name), Some(node)) = (&selected_item.name, &selected_item.now) else { + plan.repaired_count += 1; + continue; + }; + let Some(group) = lookup(current, group_name) else { + if previous.is_some_and(|snapshot| lookup(snapshot, group_name).is_none()) { + plan.repaired_count += 1; + } else { + plan.selected.push(selected_item.clone()); + } + continue; + }; + let Some(available_nodes) = group.members.filter(|nodes| !nodes.is_empty()) else { + // Provider-backed groups can be temporarily incomplete immediately after a reload. + plan.selected.push(selected_item.clone()); + continue; + }; + if !group.selectable { + let preferred_node = group + .current + .filter(|current| node_is_available(available_nodes, current)) + .or_else(|| node_is_available(available_nodes, node).then_some(node.as_str())); + let Some(preferred_node) = preferred_node else { + plan.repaired_count += 1; + continue; + }; + plan.repaired_count += usize::from(preferred_node != node.as_str()); + plan.selected.push(PrfSelected { + name: Some(group_name.clone()), + now: Some(preferred_node.into()), + }); + continue; + } + + if node_is_available(available_nodes, node) { + plan.selected.push(selected_item.clone()); + if group.current != Some(node.as_str()) { + plan.activations.push((group_name.clone(), node.clone())); + } + continue; + } + + let missing_was_confirmed = previous + .and_then(|snapshot| lookup(snapshot, group_name)) + .and_then(|group| group.members) + .filter(|nodes| !nodes.is_empty()) + .is_some_and(|nodes| !node_is_available(nodes, node)); + if !missing_was_confirmed { + plan.selected.push(selected_item.clone()); + continue; + } + + plan.repaired_count += 1; + if let Some(current_node) = group + .current + .filter(|current| node_is_available(available_nodes, current)) + { + plan.selected.push(PrfSelected { + name: Some(group_name.clone()), + now: Some(current_node.into()), + }); + } + } + + plan +} + +/// Returns recorded selections whose groups have not reached the requested node. +pub fn unsettled_selections<'a, Snapshot>( + selected: &[PrfSelected], + snapshot: &'a Snapshot, + lookup: impl Fn(&'a Snapshot, &str) -> Option>, +) -> Vec { + selected + .iter() + .filter_map(|item| { + let (Some(group_name), Some(node)) = (&item.name, &item.now) else { + return None; + }; + match lookup(snapshot, group_name) { + Some(group) if group.current == Some(node.as_str()) => None, + _ => Some(group_name.clone()), + } + }) + .collect() +} diff --git a/src-tauri/src/config/profiles.rs b/src-tauri/src/config/profiles.rs index 6a5ef1107..c687c166e 100644 --- a/src-tauri/src/config/profiles.rs +++ b/src-tauri/src/config/profiles.rs @@ -15,13 +15,16 @@ use crate::{ use anyhow::{Context as _, Result, bail}; use clash_verge_draft::Draft; use clash_verge_logging::{Type, logging}; +use clash_verge_profile::selected_nodes::{ + SelectedGroup, reconcile_selected_nodes, selected_nodes_need_confirmation, unsettled_selections, +}; pub use clash_verge_profile::{IProfilePreview, IProfiles}; use clash_verge_subscription::normalize_profile_home_url; use futures::FutureExt as _; use serde_yaml_ng::Mapping; use std::num::NonZeroUsize; use std::{ - collections::{HashMap, HashSet}, + collections::HashMap, panic::AssertUnwindSafe, path::{Component, Path}, sync::OnceLock, @@ -320,125 +323,16 @@ pub(crate) async fn apply_remote_refresh_safe(index: &str, refresh: RemoteProfil .await } -#[derive(Debug, PartialEq, Eq)] -struct SelectedNodesPlan { - selected: Vec, - activations: Vec<(String, String)>, - repaired_count: usize, -} - -fn node_is_available(available_nodes: &[std::string::String], node: &str) -> bool { - available_nodes.iter().any(|available| available == node) -} - -fn selected_nodes_need_confirmation(selected: &[PrfSelected], proxies: &Proxies) -> bool { - selected.iter().any(|selected_item| { - let (Some(group_name), Some(node)) = (&selected_item.name, &selected_item.now) else { - return false; - }; - let Some(group) = proxies.proxies.get(group_name.as_str()) else { - return true; - }; - let Some(available_nodes) = group.all.as_deref().filter(|nodes| !nodes.is_empty()) else { - return true; - }; - !node_is_available(available_nodes, node) - }) -} - -fn reconcile_selected_nodes( - selected: &[PrfSelected], - previous: Option<&Proxies>, - proxies: &Proxies, -) -> SelectedNodesPlan { - let mut plan = SelectedNodesPlan { - selected: Vec::with_capacity(selected.len()), - activations: Vec::new(), - repaired_count: 0, - }; - let mut seen_groups = HashSet::new(); - let mut unique_selected = selected - .iter() - .rev() - .filter(|item| item.name.as_ref().is_some_and(|name| seen_groups.insert(name.clone()))) - .collect::>(); - unique_selected.reverse(); - plan.repaired_count += selected.len() - unique_selected.len(); - - for selected_item in unique_selected { - let (Some(group_name), Some(node)) = (&selected_item.name, &selected_item.now) else { - plan.repaired_count += 1; - continue; - }; - let Some(group) = proxies.proxies.get(group_name.as_str()) else { - if previous.is_some_and(|snapshot| !snapshot.proxies.contains_key(group_name.as_str())) { - plan.repaired_count += 1; - } else { - plan.selected.push(selected_item.clone()); - } - continue; - }; - let Some(available_nodes) = group.all.as_deref().filter(|nodes| !nodes.is_empty()) else { - // Provider-backed groups can be temporarily incomplete immediately after a reload. - plan.selected.push(selected_item.clone()); - continue; - }; - let is_selectable_group = matches!( - &group.proxy_type, +fn selected_group<'a>(snapshot: &'a Proxies, name: &str) -> Option> { + let group = snapshot.proxies.get(name)?; + Some(SelectedGroup { + members: group.all.as_deref(), + current: group.now.as_deref(), + selectable: matches!( + group.proxy_type, ProxyType::Selector | ProxyType::URLTest | ProxyType::Fallback | ProxyType::LoadBalance - ); - if !is_selectable_group { - let preferred_node = group - .now - .as_deref() - .filter(|current| node_is_available(available_nodes, current)) - .or_else(|| node_is_available(available_nodes, node).then_some(node.as_str())); - if let Some(preferred_node) = preferred_node { - if preferred_node != node.as_str() { - plan.repaired_count += 1; - } - plan.selected.push(PrfSelected { - name: Some(group_name.clone()), - now: Some(preferred_node.into()), - }); - } else { - plan.repaired_count += 1; - } - continue; - } - - if node_is_available(available_nodes, node) { - plan.selected.push(selected_item.clone()); - if group.now.as_deref() != Some(node.as_str()) { - plan.activations.push((group_name.clone(), node.clone())); - } - continue; - } - - let missing_was_confirmed = previous - .and_then(|snapshot| snapshot.proxies.get(group_name.as_str())) - .and_then(|group| group.all.as_deref()) - .filter(|nodes| !nodes.is_empty()) - .is_some_and(|nodes| !node_is_available(nodes, node)); - if !missing_was_confirmed { - plan.selected.push(selected_item.clone()); - continue; - } - - plan.repaired_count += 1; - if let Some(current_node) = group - .now - .as_deref() - .filter(|current| node_is_available(available_nodes, current)) - { - plan.selected.push(PrfSelected { - name: Some(group_name.clone()), - now: Some(current_node.into()), - }); - } - } - - plan + ), + }) } /// Cancels restoration so it cannot overwrite a newer selection or profile snapshot. @@ -712,22 +606,6 @@ async fn persist_reconciled_selected( .await } -/// Returns recorded selections whose groups have not reached the requested node. -fn unsettled_selections(selected: &[PrfSelected], proxies: &Proxies) -> Vec { - selected - .iter() - .filter_map(|item| { - let (Some(group_name), Some(node)) = (&item.name, &item.now) else { - return None; - }; - match proxies.proxies.get(group_name.as_str()) { - Some(group) if group.now.as_deref() == Some(node.as_str()) => None, - _ => Some(group_name.clone()), - } - }) - .collect() -} - /// Retries selections while provider-backed groups finish loading. async fn settle_pending_selections(selected: &[PrfSelected], completed: &mut HashMap, generation: u64) { let deadline = Instant::now() + SELECTED_NODES_SETTLE_DEADLINE; @@ -754,7 +632,7 @@ async fn settle_pending_selections(selected: &[PrfSelected], completed: &mut Has if !is_activation_current(*generation) { return Ok(()); } - let pending = unsettled_selections(selected, &snapshot); + let pending = unsettled_selections(selected, &snapshot, selected_group); if pending.is_empty() { return Ok(()); } @@ -768,7 +646,7 @@ async fn settle_pending_selections(selected: &[PrfSelected], completed: &mut Has ); return Ok(()); } - let plan = reconcile_selected_nodes(selected, None, &snapshot); + let plan = reconcile_selected_nodes(selected, None, &snapshot, selected_group); if apply_activations(&plan.activations, completed, *generation) .await .is_none() @@ -796,8 +674,8 @@ async fn activate_selected_nodes_worker( return Ok(()); } - let needs_confirmation = selected_nodes_need_confirmation(&selected, &first_snapshot); - let immediate_plan = reconcile_selected_nodes(&selected, None, &first_snapshot); + let needs_confirmation = selected_nodes_need_confirmation(&selected, &first_snapshot, selected_group); + let immediate_plan = reconcile_selected_nodes(&selected, None, &first_snapshot, selected_group); logging!( debug, Type::Config, @@ -825,7 +703,8 @@ async fn activate_selected_nodes_worker( if !is_activation_current(generation) { return Ok(()); } - let confirmed_plan = reconcile_selected_nodes(&selected, Some(&first_snapshot), &second_snapshot); + let confirmed_plan = + reconcile_selected_nodes(&selected, Some(&first_snapshot), &second_snapshot, selected_group); logging!( debug, Type::Config, @@ -1095,13 +974,13 @@ mod tests { let unloaded = proxies(vec![("provider-group", &[], None)]); assert!( - reconcile_selected_nodes(&saved, Some(&unloaded), &unloaded) + reconcile_selected_nodes(&saved, Some(&unloaded), &unloaded, selected_group) .activations .is_empty(), "nothing can be activated while the group is empty" ); assert_eq!( - unsettled_selections(&saved, &unloaded), + unsettled_selections(&saved, &unloaded, selected_group), vec![String::from("provider-group")], "so the restore must keep looking rather than call it done" ); @@ -1113,7 +992,7 @@ mod tests { let loaded = proxies(vec![("Proxy", &["Node A", "Node B"], Some("Node A"))]); assert!( - unsettled_selections(&saved, &loaded).is_empty(), + unsettled_selections(&saved, &loaded, selected_group).is_empty(), "a group already on its node needs nothing, even though it produces no activation" ); } @@ -1125,7 +1004,10 @@ mod tests { let saved = vec![selected("Proxy", "Node A")]; let wrong = proxies(vec![("Proxy", &["Node A", "Node B"], Some("Node B"))]); - assert_eq!(unsettled_selections(&saved, &wrong), vec![String::from("Proxy")]); + assert_eq!( + unsettled_selections(&saved, &wrong, selected_group), + vec![String::from("Proxy")] + ); } #[test] @@ -1143,7 +1025,7 @@ mod tests { }, ]; - assert!(unsettled_selections(&malformed, &proxies(vec![])).is_empty()); + assert!(unsettled_selections(&malformed, &proxies(vec![]), selected_group).is_empty()); } #[test] @@ -1155,7 +1037,7 @@ mod tests { let saved = vec![selected("provider-group", "saved")]; let empty = proxies(vec![]); - let plan = reconcile_selected_nodes(&saved, Some(&empty), &empty); + let plan = reconcile_selected_nodes(&saved, Some(&empty), &empty, selected_group); assert!( plan.selected.is_empty(), @@ -1172,7 +1054,7 @@ mod tests { let had_it = proxies(vec![("provider-group", &["saved"], Some("saved"))]); let lost_it = proxies(vec![]); - let plan = reconcile_selected_nodes(&saved, Some(&had_it), &lost_it); + let plan = reconcile_selected_nodes(&saved, Some(&had_it), &lost_it, selected_group); assert_eq!(plan.selected, saved); assert_eq!(plan.repaired_count, 0); @@ -1198,6 +1080,7 @@ mod tests { &saved, None, &proxies(vec![("group", &["current", "saved"], Some("current"))]), + selected_group, ); assert_eq!(plan.selected, saved); @@ -1208,7 +1091,12 @@ mod tests { #[test] fn replaces_missing_node_with_valid_current_node() { let snapshot = proxies(vec![("group", &["current"], Some("current"))]); - let plan = reconcile_selected_nodes(&[selected("group", "renamed-node")], Some(&snapshot), &snapshot); + let plan = reconcile_selected_nodes( + &[selected("group", "renamed-node")], + Some(&snapshot), + &snapshot, + selected_group, + ); assert_eq!(plan.selected, vec![selected("group", "current")]); assert!(plan.activations.is_empty()); @@ -1221,7 +1109,12 @@ mod tests { ("group", &["current"], Some("current")), ("other-node", &[], None), ]); - let plan = reconcile_selected_nodes(&[selected("group", "other-node")], Some(&snapshot), &snapshot); + let plan = reconcile_selected_nodes( + &[selected("group", "other-node")], + Some(&snapshot), + &snapshot, + selected_group, + ); assert_eq!(plan.selected, vec![selected("group", "current")]); assert!(plan.activations.is_empty()); @@ -1243,7 +1136,7 @@ mod tests { )]), }; - let plan = reconcile_selected_nodes(&[selected("group", "saved")], None, &snapshot); + let plan = reconcile_selected_nodes(&[selected("group", "saved")], None, &snapshot, selected_group); assert_eq!(plan.selected, vec![selected("group", "current")]); assert!(plan.activations.is_empty()); @@ -1261,6 +1154,7 @@ mod tests { ], Some(&snapshot), &snapshot, + selected_group, ); assert!(plan.selected.is_empty()); @@ -1274,8 +1168,8 @@ mod tests { let incomplete = proxies(vec![("group", &[], None)]); let complete = proxies(vec![("group", &["current"], Some("current"))]); - let incomplete_plan = reconcile_selected_nodes(&saved, None, &incomplete); - let one_snapshot_plan = reconcile_selected_nodes(&saved, None, &complete); + let incomplete_plan = reconcile_selected_nodes(&saved, None, &incomplete, selected_group); + let one_snapshot_plan = reconcile_selected_nodes(&saved, None, &complete, selected_group); assert_eq!(incomplete_plan.selected, saved); assert_eq!(incomplete_plan.repaired_count, 0); @@ -1289,7 +1183,7 @@ mod tests { let incomplete = Proxies::default(); let complete = proxies(vec![("group", &["current", "saved"], Some("current"))]); - let plan = reconcile_selected_nodes(&saved, Some(&incomplete), &complete); + let plan = reconcile_selected_nodes(&saved, Some(&incomplete), &complete, selected_group); assert_eq!(plan.selected, saved); assert_eq!(plan.activations, vec![("group".into(), "saved".into())]); @@ -1301,7 +1195,7 @@ mod tests { let saved = vec![selected("group", "old"), selected("group", "new")]; let snapshot = proxies(vec![("group", &["old", "new"], Some("old"))]); - let plan = reconcile_selected_nodes(&saved, None, &snapshot); + let plan = reconcile_selected_nodes(&saved, None, &snapshot, selected_group); assert_eq!(plan.selected, vec![selected("group", "new")]); assert_eq!(plan.activations, vec![("group".into(), "new".into())]); @@ -1316,8 +1210,12 @@ mod tests { ("stale-group", &["fallback"], Some("fallback")), ]); - assert!(selected_nodes_need_confirmation(&saved, &first_snapshot)); - let immediate_plan = reconcile_selected_nodes(&saved, None, &first_snapshot); + assert!(selected_nodes_need_confirmation( + &saved, + &first_snapshot, + selected_group + )); + let immediate_plan = reconcile_selected_nodes(&saved, None, &first_snapshot, selected_group); assert_eq!(immediate_plan.selected, saved); assert_eq!(immediate_plan.activations, vec![("valid-group".into(), "saved".into())]); From 0bc38ba664553dd66bdc7b5bf978bc33a4f3e283 Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:33:44 +0800 Subject: [PATCH 19/33] docs(agents): define dependencies between capability crates --- crates/AGENTS.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/AGENTS.md b/crates/AGENTS.md index fa92c9b93..f6fc71da3 100644 --- a/crates/AGENTS.md +++ b/crates/AGENTS.md @@ -16,6 +16,12 @@ dependency, portability, testing, or ownership boundary. Keep a module when the proposed boundary only relocates implementation or introduces a pass-through API. +- Keep capability crates independent by default. Compose peer capabilities in + the application and pass inputs or callbacks through the consumer's API. + Depend on another workspace crate for foundational mechanisms such as logging + and task primitives, or for a shared domain contract required to enforce the + same invariant. Keep tightly coupled rules together when separating them + would duplicate that contract or split its ownership. - Keep dependencies pointing toward domain and application contracts. Resolve app paths and read current settings at the application boundary. Pass in the required values, resources, or callbacks. For example, From 911a3c58faf9c9846ff02b9788086d623bf67ba5 Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:48:04 +0800 Subject: [PATCH 20/33] refactor(task): move retry primitives into the task crate --- crates/clash-verge-task/src/lib.rs | 3 +- .../clash-verge-task/src}/retry.rs | 103 +++++++++--------- src-tauri/src/config/profiles.rs | 2 +- src-tauri/src/core/manager/mod.rs | 2 +- src-tauri/src/core/manager/state.rs | 2 +- src-tauri/src/core/proxy_control.rs | 2 +- src-tauri/src/core/runstate/mod.rs | 2 +- src-tauri/src/core/service.rs | 4 +- src-tauri/src/feat/core_upgrade.rs | 2 +- src-tauri/src/feat/subscription.rs | 11 +- src-tauri/src/utils/macos_launch_guard.rs | 2 +- src-tauri/src/utils/mod.rs | 1 - src-tauri/src/utils/server.rs | 2 +- 13 files changed, 69 insertions(+), 69 deletions(-) rename {src-tauri/src/utils => crates/clash-verge-task/src}/retry.rs (67%) diff --git a/crates/clash-verge-task/src/lib.rs b/crates/clash-verge-task/src/lib.rs index 890fb4a33..e3c369b22 100644 --- a/crates/clash-verge-task/src/lib.rs +++ b/crates/clash-verge-task/src/lib.rs @@ -1,5 +1,6 @@ -//! Single-owner task drivers with caller-managed runtime and cancellation. +//! Task drivers and retry primitives with caller-managed runtime and cancellation. pub mod countdown; +pub mod retry; pub mod scheduled_task; pub mod watch_task; diff --git a/src-tauri/src/utils/retry.rs b/crates/clash-verge-task/src/retry.rs similarity index 67% rename from src-tauri/src/utils/retry.rs rename to crates/clash-verge-task/src/retry.rs index 72c79017b..730c3b3d6 100644 --- a/src-tauri/src/utils/retry.rs +++ b/crates/clash-verge-task/src/retry.rs @@ -21,25 +21,29 @@ pub enum RetryError { Stop(E), } +impl RetryError { + fn into_inner(self) -> E { + match self { + Self::Retry(error) | Self::Stop(error) => error, + } + } +} + pub async fn retry>> + Send>( policy: RetryPolicy, mut operation: impl FnMut(usize) -> Fut + Send, ) -> Result { let mut result = operation(0).await; for (index, delay) in policy.delays().enumerate() { - match result { - Ok(_) | Err(RetryError::Stop(_)) => break, - Err(RetryError::Retry(_)) => { - if !delay.is_zero() { - tokio::time::sleep(delay).await; - } - } + if !matches!(result, Err(RetryError::Retry(_))) { + break; + } + if !delay.is_zero() { + tokio::time::sleep(delay).await; } result = operation(index + 1).await; } - result.map_err(|error| match error { - RetryError::Retry(error) | RetryError::Stop(error) => error, - }) + result.map_err(RetryError::into_inner) } pub async fn try_strategies< @@ -53,15 +57,14 @@ pub async fn try_strategies< rest: [S; N], mut operation: impl FnMut(S) -> Fut + Send, ) -> Result<(S, T), E> { - retry( - RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(N), Duration::ZERO), - move |attempt| { - let strategy = if attempt == 0 { first } else { rest[attempt - 1] }; - let future = operation(strategy); - async move { future.await.map(|value| (strategy, value)).map_err(RetryError::Retry) } - }, - ) - .await + let mut result = operation(first).await.map(|value| (first, value)); + for strategy in rest { + if result.is_ok() { + break; + } + result = operation(strategy).await.map(|value| (strategy, value)); + } + result } pub async fn retry_with_state( @@ -71,19 +74,15 @@ pub async fn retry_with_state( ) -> Result { let mut result = operation(&mut state, 0).await; for (index, delay) in policy.delays().enumerate() { - match result { - Ok(_) | Err(RetryError::Stop(_)) => break, - Err(RetryError::Retry(_)) => { - if !delay.is_zero() { - tokio::time::sleep(delay).await; - } - } + if !matches!(result, Err(RetryError::Retry(_))) { + break; + } + if !delay.is_zero() { + tokio::time::sleep(delay).await; } result = operation(&mut state, index + 1).await; } - result.map_err(|error| match error { - RetryError::Retry(error) | RetryError::Stop(error) => error, - }) + result.map_err(RetryError::into_inner) } pub fn retry_sync( @@ -92,41 +91,39 @@ pub fn retry_sync( ) -> Result { let mut result = operation(0); for (index, delay) in policy.delays().enumerate() { - match result { - Ok(_) | Err(RetryError::Stop(_)) => break, - Err(RetryError::Retry(_)) => { - if !delay.is_zero() { - std::thread::sleep(delay); - } - } + if !matches!(result, Err(RetryError::Retry(_))) { + break; + } + if !delay.is_zero() { + std::thread::sleep(delay); } result = operation(index + 1); } - result.map_err(|error| match error { - RetryError::Retry(error) | RetryError::Stop(error) => error, - }) + result.map_err(RetryError::into_inner) } #[cfg(test)] mod tests { use super::*; + use std::future::ready; - #[tokio::test] + #[tokio::test(start_paused = true)] async fn retries_stop_at_success_terminal_error_or_attempt_limit() { - let policy = RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(2), Duration::ZERO); + let delay = Duration::from_millis(50); + let policy = RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(2), delay); + let started = tokio::time::Instant::now(); let mut calls = 0; let success = retry(policy, |attempt| { calls += 1; - async move { - if attempt == 1 { - Ok(7) - } else { - Err(RetryError::Retry(attempt)) - } - } + ready(if attempt == 1 { + Ok(7) + } else { + Err(RetryError::Retry(attempt)) + }) }) .await; assert_eq!((success, calls), (Ok(7), 2)); + assert_eq!(started.elapsed(), delay); calls = 0; let stopped = retry(policy, |_| { calls += 1; @@ -134,6 +131,7 @@ mod tests { }) .await; assert_eq!((stopped, calls), (Err("terminal"), 1)); + assert_eq!(started.elapsed(), delay); calls = 0; let exhausted = retry(policy, |attempt| { calls += 1; @@ -141,6 +139,7 @@ mod tests { }) .await; assert_eq!((exhausted, calls), (Err(2), 3)); + assert_eq!(started.elapsed(), delay * 3); } #[tokio::test] @@ -161,11 +160,9 @@ mod tests { let result = retry_with_state(policy, Vec::new(), |visited, attempt| { Box::pin(async move { visited.push(attempt); - if visited.len() == 3 { - Ok(visited.clone()) - } else { - Err(RetryError::Retry(())) - } + (visited.len() == 3) + .then(|| visited.clone()) + .ok_or(RetryError::Retry(())) }) }) .await; diff --git a/src-tauri/src/config/profiles.rs b/src-tauri/src/config/profiles.rs index c687c166e..4f1eead42 100644 --- a/src-tauri/src/config/profiles.rs +++ b/src-tauri/src/config/profiles.rs @@ -3,7 +3,6 @@ use super::{ prfitem::{RemoteProfileRefresh, build_profile}, }; use crate::core::notify::{Refresh, announce}; -use crate::utils::retry::{RetryError, RetryPolicy, retry, retry_with_state}; use crate::{ core::{handle, tray::Tray}, process::AsyncHandler, @@ -20,6 +19,7 @@ use clash_verge_profile::selected_nodes::{ }; pub use clash_verge_profile::{IProfilePreview, IProfiles}; use clash_verge_subscription::normalize_profile_home_url; +use clash_verge_task::retry::{RetryError, RetryPolicy, retry, retry_with_state}; use futures::FutureExt as _; use serde_yaml_ng::Mapping; use std::num::NonZeroUsize; diff --git a/src-tauri/src/core/manager/mod.rs b/src-tauri/src/core/manager/mod.rs index ca95ad073..6a1747463 100644 --- a/src-tauri/src/core/manager/mod.rs +++ b/src-tauri/src/core/manager/mod.rs @@ -235,7 +235,7 @@ impl CoreManager { anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}"); } - use crate::utils::retry::{RetryError, RetryPolicy, retry}; + use clash_verge_task::retry::{RetryError, RetryPolicy, retry}; retry( RetryPolicy::fixed( std::num::NonZeroUsize::MIN.saturating_add(MAX_PORT_FALLBACK_RETRIES), diff --git a/src-tauri/src/core/manager/state.rs b/src-tauri/src/core/manager/state.rs index 85a3d43de..538212ca5 100644 --- a/src-tauri/src/core/manager/state.rs +++ b/src-tauri/src/core/manager/state.rs @@ -1,7 +1,6 @@ #[cfg(test)] use super::claim_core_readiness_generation; use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode}; -use crate::utils::retry::{RetryError, RetryPolicy, retry}; use crate::{ AsyncHandler, config::Config, @@ -11,6 +10,7 @@ use crate::{ }; use anyhow::{Context as _, Result}; use clash_verge_logging::Type; +use clash_verge_task::retry::{RetryError, RetryPolicy, retry}; use futures::{ FutureExt as _, future::{Map, Shared}, diff --git a/src-tauri/src/core/proxy_control.rs b/src-tauri/src/core/proxy_control.rs index f012b2d47..38befc063 100644 --- a/src-tauri/src/core/proxy_control.rs +++ b/src-tauri/src/core/proxy_control.rs @@ -555,7 +555,7 @@ pub async fn clear() -> Result<()> { /// A failed system call is usually a transient RPC hiccup, so give it a few tries. async fn clear_with_retry() -> Result<()> { - use crate::utils::retry::{RetryError, RetryPolicy, retry}; + use clash_verge_task::retry::{RetryError, RetryPolicy, retry}; retry( RetryPolicy::fixed( std::num::NonZeroUsize::MIN.saturating_add((CLEAR_ATTEMPTS - 1) as usize), diff --git a/src-tauri/src/core/runstate/mod.rs b/src-tauri/src/core/runstate/mod.rs index b6e5dd29c..097e0f527 100644 --- a/src-tauri/src/core/runstate/mod.rs +++ b/src-tauri/src/core/runstate/mod.rs @@ -135,7 +135,7 @@ impl RunStateStore { /// Retries transport failures but stops at the first readable reply, including a rejection. pub async fn await_ready(&self, attempts: usize, interval: Duration) -> Result { - use crate::utils::retry::{RetryError, RetryPolicy, retry}; + use clash_verge_task::retry::{RetryError, RetryPolicy, retry}; let attempts = std::num::NonZeroUsize::new(attempts).ok_or_else(|| { ReadyWaitError::Unreachable(anyhow::anyhow!( "service readiness wait was configured with no attempts" diff --git a/src-tauri/src/core/service.rs b/src-tauri/src/core/service.rs index b2763578a..b405e635d 100644 --- a/src-tauri/src/core/service.rs +++ b/src-tauri/src/core/service.rs @@ -1282,7 +1282,7 @@ async fn create_sync_temp(target: &Path) -> Result<(PathBuf, tokio::fs::File)> { .with_context(|| format!("failed to create provider cache directory {}", parent.display()))?; } let name = target.file_name().map_or_default(|name| name.to_string_lossy()); - use crate::utils::retry::{RetryError, RetryPolicy, retry}; + use clash_verge_task::retry::{RetryError, RetryPolicy, retry}; retry( RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(7), std::time::Duration::ZERO), |_| async { @@ -1699,7 +1699,7 @@ async fn recover_after_owner_loss_while_locked(reason: OwnerRecoveryReason) { } async fn clear_proxy_after_owner_loss() { - use crate::utils::retry::{RetryError, RetryPolicy, retry}; + use clash_verge_task::retry::{RetryError, RetryPolicy, retry}; let result = retry( RetryPolicy::fixed( std::num::NonZeroUsize::MIN.saturating_add(2), diff --git a/src-tauri/src/feat/core_upgrade.rs b/src-tauri/src/feat/core_upgrade.rs index 645274ec1..7d265777b 100644 --- a/src-tauri/src/feat/core_upgrade.rs +++ b/src-tauri/src/feat/core_upgrade.rs @@ -349,7 +349,7 @@ fn stage_core(target: &Path, package: &[u8], version: &str) -> Result Result<(PathBuf, File)> { - use crate::utils::retry::{RetryError, RetryPolicy, retry_sync}; + use clash_verge_task::retry::{RetryError, RetryPolicy, retry_sync}; retry_sync( RetryPolicy::fixed( std::num::NonZeroUsize::MIN.saturating_add(31), diff --git a/src-tauri/src/feat/subscription.rs b/src-tauri/src/feat/subscription.rs index 47a0ca545..6ac22cf6a 100644 --- a/src-tauri/src/feat/subscription.rs +++ b/src-tauri/src/feat/subscription.rs @@ -68,8 +68,10 @@ async fn perform_profile_update( System, } - let result = - crate::utils::retry::try_strategies(Strategy::Configured, [Strategy::Clash, Strategy::System], |strategy| { + let result = clash_verge_task::retry::try_strategies( + Strategy::Configured, + [Strategy::Clash, Strategy::System], + |strategy| { let mut options = merged_opt.clone(); async move { let (name, success, failure) = match strategy { @@ -117,8 +119,9 @@ async fn perform_profile_update( } result } - }) - .await; + }, + ) + .await; let last_err = match result { Ok((strategy, refresh)) => { // A persistence error must not replay a successful download with another transport. diff --git a/src-tauri/src/utils/macos_launch_guard.rs b/src-tauri/src/utils/macos_launch_guard.rs index 761438634..896fa7c62 100644 --- a/src-tauri/src/utils/macos_launch_guard.rs +++ b/src-tauri/src/utils/macos_launch_guard.rs @@ -109,7 +109,7 @@ fn current_user_home() -> anyhow::Result { } .max(1024); - use crate::utils::retry::{RetryError, RetryPolicy, retry_sync}; + use clash_verge_task::retry::{RetryError, RetryPolicy, retry_sync}; retry_sync( RetryPolicy::fixed( std::num::NonZeroUsize::MIN.saturating_add(11), diff --git a/src-tauri/src/utils/mod.rs b/src-tauri/src/utils/mod.rs index e190227cb..106ec4669 100644 --- a/src-tauri/src/utils/mod.rs +++ b/src-tauri/src/utils/mod.rs @@ -11,7 +11,6 @@ pub(crate) mod network; pub use crate::core::notify::desktop as notification; pub mod port; pub mod resolve; -pub mod retry; #[cfg(target_os = "windows")] pub mod schtasks; pub mod server; diff --git a/src-tauri/src/utils/server.rs b/src-tauri/src/utils/server.rs index bb3577947..fb9052db8 100644 --- a/src-tauri/src/utils/server.rs +++ b/src-tauri/src/utils/server.rs @@ -52,7 +52,7 @@ pub async fn check_singleton() -> Result { .context("failed to initialize singleton lock")?; if !try_lock_instance(&lock).context("failed to acquire singleton lock")? { let deadline = std::time::Instant::now() + Duration::from_secs(20); - use crate::utils::retry::{RetryError, RetryPolicy, retry}; + use clash_verge_task::retry::{RetryError, RetryPolicy, retry}; let secondary = retry( RetryPolicy::fixed( std::num::NonZeroUsize::MIN.saturating_add(400), From 18f733fca93e84e075b11a057ce75c49e290e172 Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:08:20 +0800 Subject: [PATCH 21/33] refactor(backup): extract backup ZIP writing --- Cargo.lock | 9 ++ Cargo.toml | 3 + crates/clash-verge-backup-archive/Cargo.toml | 11 ++ .../clash-verge-backup-archive/src/error.rs | 13 +++ crates/clash-verge-backup-archive/src/lib.rs | 104 ++++++++++++++++++ src-tauri/Cargo.toml | 3 +- src-tauri/src/core/backup.rs | 34 +++--- 7 files changed, 160 insertions(+), 17 deletions(-) create mode 100644 crates/clash-verge-backup-archive/Cargo.toml create mode 100644 crates/clash-verge-backup-archive/src/error.rs create mode 100644 crates/clash-verge-backup-archive/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 6deccbcf6..2012fa485 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1109,6 +1109,7 @@ dependencies = [ "boa_engine", "bytes", "chrono", + "clash-verge-backup-archive", "clash-verge-draft", "clash-verge-i18n", "clash-verge-limiter", @@ -1186,6 +1187,14 @@ dependencies = [ "zip", ] +[[package]] +name = "clash-verge-backup-archive" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.20", + "zip", +] + [[package]] name = "clash-verge-draft" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 886ece520..2b211583e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ members = [ "crates/clash-verge-limiter", "crates/clash-verge-subscription", "crates/clash-verge-profile", + "crates/clash-verge-backup-archive", ] resolver = "2" @@ -64,6 +65,7 @@ clash-verge-i18n = { path = "crates/clash-verge-i18n" } clash-verge-limiter = { path = "crates/clash-verge-limiter" } clash-verge-subscription = { path = "crates/clash-verge-subscription" } clash-verge-profile = { path = "crates/clash-verge-profile" } +clash-verge-backup-archive = { path = "crates/clash-verge-backup-archive" } tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" } tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" } tracing = "0.1.44" @@ -73,6 +75,7 @@ tauri-plugin-clipboard-manager = "2.5.0" parking_lot = "0.13.0" anyhow = "1.0.105" thiserror = "2.0.20" +zip = "9.9.0" futures = "0.3.34" loom = "0.7.3" proptest = "1.12.0" diff --git a/crates/clash-verge-backup-archive/Cargo.toml b/crates/clash-verge-backup-archive/Cargo.toml new file mode 100644 index 000000000..47ec0396b --- /dev/null +++ b/crates/clash-verge-backup-archive/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "clash-verge-backup-archive" +version = "0.1.0" +edition = "2024" + +[dependencies] +thiserror = { workspace = true } +zip = { workspace = true } + +[lints] +workspace = true diff --git a/crates/clash-verge-backup-archive/src/error.rs b/crates/clash-verge-backup-archive/src/error.rs new file mode 100644 index 000000000..de04927c3 --- /dev/null +++ b/crates/clash-verge-backup-archive/src/error.rs @@ -0,0 +1,13 @@ +#[derive(Debug, thiserror::Error)] +pub enum ArchiveError { + #[error(transparent)] + Zip(#[from] zip::result::ZipError), + #[error(transparent)] + Io(#[from] std::io::Error), + #[error("backup contains a symbolic link")] + Symlink, + #[error("backup contains an invalid path")] + InvalidPath, + #[error("archive contains profile recovery data")] + ReservedEntry, +} diff --git a/crates/clash-verge-backup-archive/src/lib.rs b/crates/clash-verge-backup-archive/src/lib.rs new file mode 100644 index 000000000..0f6c75685 --- /dev/null +++ b/crates/clash-verge-backup-archive/src/lib.rs @@ -0,0 +1,104 @@ +mod error; + +pub use error::ArchiveError; + +use std::{ + io::{self, Read, Seek, Write}, + path::{Component, Path}, +}; +use zip::{CompressionMethod, ZipArchive, ZipWriter, write::SimpleFileOptions}; + +pub struct BackupWriter { + zip: ZipWriter, + options: SimpleFileOptions, +} + +impl BackupWriter { + pub fn new(target: W) -> Result { + let mut zip = ZipWriter::new(target); + zip.add_directory("profiles/", SimpleFileOptions::default())?; + let options = SimpleFileOptions::default().compression_method(CompressionMethod::Stored); + Ok(Self { zip, options }) + } + + pub fn start_profile<'a>(&'a mut self, filename: &str) -> Result, ArchiveError> { + self.start_file(&format!("profiles/{filename}")) + } + + pub fn start_file<'a>(&'a mut self, name: &str) -> Result, ArchiveError> { + self.zip.start_file_with_options(self.options.name(name.as_bytes()))?; + Ok(&mut self.zip) + } + + pub fn finish(self) -> Result { + Ok(self.zip.finish()?) + } +} + +pub struct ValidatedBackup { + zip: ZipArchive, +} + +impl ValidatedBackup { + pub fn open(source: R, reserved_names: &[&str]) -> Result { + let mut zip = ZipArchive::new(source)?; + for index in 0..zip.len() { + let mut entry = zip.by_index(index)?; + if entry.is_symlink() { + return Err(ArchiveError::Symlink); + } + let path = entry.enclosed_name().ok_or(ArchiveError::InvalidPath)?; + for component in path.components() { + let Component::Normal(name) = component else { + continue; + }; + let name = name.to_string_lossy(); + if reserved_names + .iter() + .any(|reserved| name.eq_ignore_ascii_case(reserved)) + { + return Err(ArchiveError::ReservedEntry); + } + } + io::copy(&mut entry, &mut io::sink())?; + } + Ok(Self { zip }) + } + + pub fn extract_to(mut self, destination: &Path) -> Result<(), ArchiveError> { + self.zip.extract(destination)?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn writes_and_validates_the_backup_layout() -> Result<(), ArchiveError> { + let mut writer = BackupWriter::new(Cursor::new(Vec::new()))?; + writer.start_profile("example.yaml")?.write_all(b"proxies: []\n")?; + writer.start_file("profiles.yaml")?.write_all(b"items: []\n")?; + let source = writer.finish()?; + + let mut zip = ZipArchive::new(source.clone())?; + assert_eq!(zip.len(), 3); + assert_eq!(zip.by_index(0)?.name()?, "profiles/"); + let profile_time = { + let mut entry = zip.by_index(1)?; + assert_eq!(entry.name()?, "profiles/example.yaml"); + assert_eq!(entry.compression(), CompressionMethod::Stored); + let mut contents = Vec::new(); + entry.read_to_end(&mut contents)?; + assert_eq!(contents, b"proxies: []\n"); + entry.last_modified() + }; + let index = zip.by_index(2)?; + assert_eq!(index.name()?, "profiles.yaml"); + assert_eq!(index.last_modified(), profile_time); + ValidatedBackup::open(source, &[".profile-refresh", ".profile-refresh.lock"])?; + Ok(()) + } +} diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index b6bb4d532..da77a5232 100755 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -38,6 +38,7 @@ clash-verge-i18n = { workspace = true } clash-verge-limiter = { workspace = true } clash-verge-subscription = { workspace = true } clash-verge-profile = { workspace = true } +clash-verge-backup-archive = { workspace = true } tauri-plugin-clash-verge-sysinfo = { workspace = true } tauri-plugin-clipboard-manager = { workspace = true } tauri = { workspace = true, features = [ @@ -77,7 +78,7 @@ tauri-plugin-dialog = { version = "2.9.0", default-features = false, features = tauri-plugin-fs = "2.8.0" tauri-plugin-deep-link = "2.6.3" tauri-plugin-window-state = "2.5.1" -zip = "9.9.0" +zip = { workspace = true } flate2 = "1.1.11" reqwest_dav = "0.4.0" aes-gcm = { version = "0.11.1" } diff --git a/src-tauri/src/core/backup.rs b/src-tauri/src/core/backup.rs index d0d40ca67..64d8f9485 100644 --- a/src-tauri/src/core/backup.rs +++ b/src-tauri/src/core/backup.rs @@ -3,6 +3,7 @@ use crate::{config::Config, process::AsyncHandler, utils::dirs}; use anyhow::Error; use arc_swap::{ArcSwap, ArcSwapOption}; use backon::{ConstantBuilder, Retryable as _}; +use clash_verge_backup_archive::BackupWriter; use clash_verge_logging::{Type, logging}; use reqwest_dav::list_cmd::{ListEntity, ListFile, ListMultiStatus}; use std::{ @@ -15,7 +16,6 @@ use std::{ }; use tokio::{fs, time::timeout}; use tristr::alias::String; -use zip::write::SimpleFileOptions; const APP_VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -275,9 +275,7 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> { let value = zip_path.clone(); let file = AsyncHandler::spawn_blocking(move || std::fs::File::create(&value)).await??; - let mut zip = zip::ZipWriter::new(file); - zip.add_directory("profiles/", SimpleFileOptions::default())?; - let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + let mut archive = BackupWriter::new(file)?; if let Ok(mut entries) = fs::read_dir(dirs::app_profiles_dir()?).await { while let Some(entry) = entries.next_entry().await? { @@ -287,15 +285,16 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> { let file_name = file_name_os .to_str() .ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?; - let backup_path = format!("profiles/{}", file_name); - zip.start_file(backup_path, options)?; + let mut entry = archive.start_profile(file_name)?; let file_content = fs::read(&path).await?; - zip.write_all(&file_content)?; + entry.write_all(&file_content)?; } } } - zip.start_file(dirs::CLASH_CONFIG, options)?; - zip.write_all(fs::read(dirs::clash_path()?).await?.as_slice())?; + + archive + .start_file(dirs::CLASH_CONFIG)? + .write_all(&fs::read(dirs::clash_path()?).await?)?; let verge_text = fs::read_to_string(dirs::verge_path()?).await?; let mut verge_config: serde_json::Value = serde_yaml_ng::from_str(&verge_text)?; @@ -304,17 +303,20 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> { obj.remove("webdav_password"); obj.remove("webdav_url"); } - zip.start_file(dirs::VERGE_CONFIG, options)?; - zip.write_all(serde_yaml_ng::to_string(&verge_config)?.as_bytes())?; + archive + .start_file(dirs::VERGE_CONFIG)? + .write_all(serde_yaml_ng::to_string(&verge_config)?.as_bytes())?; let dns_config_path = dirs::app_home_dir()?.join(DNS_CONFIG); if dns_config_path.exists() { - zip.start_file(DNS_CONFIG, options)?; - zip.write_all(fs::read(&dns_config_path).await?.as_slice())?; + archive + .start_file(DNS_CONFIG)? + .write_all(&fs::read(&dns_config_path).await?)?; } - zip.start_file(dirs::PROFILE_YAML, options)?; - zip.write_all(fs::read(dirs::profiles_path()?).await?.as_slice())?; - zip.finish()?; + archive + .start_file(dirs::PROFILE_YAML)? + .write_all(&fs::read(dirs::profiles_path()?).await?)?; + archive.finish()?; Ok((zip_file_name, zip_path)) } From 041454be5778542d83ed2fad6bd33adbf817110a Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:58:35 +0800 Subject: [PATCH 22/33] refactor(subscription): keep profile writes outside proxy fallback --- src-tauri/src/config/mod.rs | 4 +++- src-tauri/src/config/prfitem.rs | 25 +++++++++---------------- src-tauri/src/config/profiles.rs | 7 ++++++- src-tauri/src/feat/subscription.rs | 16 ++++++++++++---- 4 files changed, 30 insertions(+), 22 deletions(-) diff --git a/src-tauri/src/config/mod.rs b/src-tauri/src/config/mod.rs index 2127ca959..3fc525de0 100644 --- a/src-tauri/src/config/mod.rs +++ b/src-tauri/src/config/mod.rs @@ -12,7 +12,9 @@ pub(crate) mod snapshot; mod verge; pub(crate) use self::config::Config; -pub(crate) use self::prfitem::{build_remote_profile, fetch_remote_refresh, read_profile_item_file}; +pub(crate) use self::prfitem::{ + build_remote_profile, download_subscription, prepare_remote_refresh, read_profile_item_file, +}; pub use self::{clash::*, encrypt::*, mixed_port::*, profiles::*, verge::*}; pub use clash_verge_profile::{PrfExtra, PrfItem, PrfOption, PrfSelected}; diff --git a/src-tauri/src/config/prfitem.rs b/src-tauri/src/config/prfitem.rs index 2eedf9fbf..a82416211 100644 --- a/src-tauri/src/config/prfitem.rs +++ b/src-tauri/src/config/prfitem.rs @@ -117,7 +117,7 @@ async fn from_local( }) } -struct DownloadedSubscription { +pub(crate) struct DownloadedSubscription { url: Url, suggested_name: Option, extra: Option, @@ -172,12 +172,7 @@ pub(crate) async fn build_remote_profile( }) } -pub(crate) async fn fetch_remote_refresh(url: &str, option: Option<&PrfOption>) -> Result { - let downloaded = download_subscription(url, option).await?; - prepare_remote_refresh(downloaded, option).await -} - -async fn download_subscription(url: &str, option: Option<&PrfOption>) -> Result { +pub(crate) async fn download_subscription(url: &str, option: Option<&PrfOption>) -> Result { let with_proxy = option.is_some_and(|o| o.with_proxy.unwrap_or(false)); let self_proxy = option.is_some_and(|o| o.self_proxy.unwrap_or(false)); let accept_invalid_certs = option.is_some_and(|o| o.danger_accept_invalid_certs.unwrap_or(false)); @@ -233,7 +228,7 @@ async fn download_subscription(url: &str, option: Option<&PrfOption>) -> Result< }) } -async fn prepare_remote_refresh( +pub(crate) async fn prepare_remote_refresh( downloaded: DownloadedSubscription, option: Option<&PrfOption>, ) -> Result { @@ -417,14 +412,12 @@ mod tests { ..Default::default() }; let item: clash_verge_profile::PrfItem = build_remote_profile(&url, None, None, Some(&option)).await?; - let refresh = fetch_remote_refresh( - &url, - Some(&PrfOption { - update_interval: None, - ..option - }), - ) - .await?; + let refresh_option = PrfOption { + update_interval: None, + ..option + }; + let downloaded = download_subscription(&url, Some(&refresh_option)).await?; + let refresh = prepare_remote_refresh(downloaded, Some(&refresh_option)).await?; server.await??; assert_eq!(item.itype.as_deref(), Some("remote")); assert_eq!(item.name.as_deref(), Some("remote.yaml")); diff --git a/src-tauri/src/config/profiles.rs b/src-tauri/src/config/profiles.rs index 4f1eead42..3ae3ed2f1 100644 --- a/src-tauri/src/config/profiles.rs +++ b/src-tauri/src/config/profiles.rs @@ -315,8 +315,13 @@ pub(crate) async fn profiles_save_file_safe() -> Result<()> { with_profiles_edit(|profiles| async move { save_profiles(&profiles).await.map(|_| profiles) }).await } -pub(crate) async fn apply_remote_refresh_safe(index: &str, refresh: RemoteProfileRefresh) -> Result<()> { +pub(crate) async fn apply_remote_refresh_safe(index: &str, url: &str, refresh: RemoteProfileRefresh) -> Result<()> { with_profiles_edit(|mut profiles| async move { + let current = profiles.get_item(index)?; + anyhow::ensure!( + current.itype.as_deref() == Some("remote") && current.url.as_deref() == Some(url), + "profile source changed during refresh" + ); apply_remote_refresh(&mut profiles, index, refresh).await?; Ok(profiles) }) diff --git a/src-tauri/src/feat/subscription.rs b/src-tauri/src/feat/subscription.rs index 6ac22cf6a..af4125341 100644 --- a/src-tauri/src/feat/subscription.rs +++ b/src-tauri/src/feat/subscription.rs @@ -1,5 +1,5 @@ use crate::{ - config::{Config, PrfOption, fetch_remote_refresh, profiles::apply_remote_refresh_safe}, + config::{Config, PrfOption, download_subscription, prepare_remote_refresh, profiles::apply_remote_refresh_safe}, core::{ CoreManager, handle, notify::{NoticeStatus, Refresh, announce}, @@ -101,7 +101,7 @@ async fn perform_profile_update( } tracing::Span::current().record("strategy", name); let started = std::time::Instant::now(); - let result = fetch_remote_refresh(url, options.as_ref()).await; + let result = download_subscription(url, options.as_ref()).await; let elapsed_field = match strategy { Strategy::Configured => "configured_elapsed", Strategy::Clash => "clash_elapsed", @@ -123,9 +123,17 @@ async fn perform_profile_update( ) .await; let last_err = match result { - Ok((strategy, refresh)) => { + Ok((strategy, downloaded)) => { // A persistence error must not replay a successful download with another transport. - apply_remote_refresh_safe(uid, refresh).await?; + let profiles = Config::profiles().await; + let snapshot = profiles.latest_arc(); + let current = snapshot.get_item(uid)?; + anyhow::ensure!( + current.itype.as_deref() == Some("remote") && current.url.as_deref() == Some(url), + "profile source changed during refresh" + ); + let refresh = prepare_remote_refresh(downloaded, merged_opt.as_ref()).await?; + apply_remote_refresh_safe(uid, url, refresh).await?; if !matches!(strategy, Strategy::Configured) { handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str()); } From c4ee0e0c8a0d7d38b30c1ae112be28210f8040d1 Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:59:24 +0800 Subject: [PATCH 23/33] fix(profile): preserve delays for future update timestamps --- crates/clash-verge-profile/src/subscription_schedule.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/clash-verge-profile/src/subscription_schedule.rs b/crates/clash-verge-profile/src/subscription_schedule.rs index 58f6d21b2..1276e5ba4 100644 --- a/crates/clash-verge-profile/src/subscription_schedule.rs +++ b/crates/clash-verge-profile/src/subscription_schedule.rs @@ -28,7 +28,7 @@ impl SubscriptionSchedule { let full = Self::interval_duration(interval_minutes); let elapsed = updated .filter(|updated| *updated > 0) - .map_or(0, |updated| now.saturating_sub(updated as i64).max(0) as u64); + .map_or(0, |updated| (now.max(0) as u64).saturating_sub(updated as u64)); Self { interval_minutes, From 390231a0432747662ba7578b2fdd2d70899346f4 Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:59:25 +0800 Subject: [PATCH 24/33] fix(subscription): preserve filenames from response headers and URL paths --- crates/clash-verge-subscription/src/lib.rs | 89 +++++++++++++++++----- 1 file changed, 70 insertions(+), 19 deletions(-) diff --git a/crates/clash-verge-subscription/src/lib.rs b/crates/clash-verge-subscription/src/lib.rs index fd2cbdd76..76f0959d5 100644 --- a/crates/clash-verge-subscription/src/lib.rs +++ b/crates/clash-verge-subscription/src/lib.rs @@ -69,26 +69,10 @@ pub fn decode_subscription<'a>( } fn subscription_filename(url: &Url, headers: &HeaderMap) -> Option { - if let Some(value) = headers.get("content-disposition") { - let disposition = format!("{value:?}"); - let disposition = disposition.trim_matches('"'); - if let Some(encoded) = find_field(disposition, "filename*", Some) - && let Ok(decoded) = percent_decode_str(encoded).decode_utf8() - && let Some(filename) = decoded.split("''").last() - && !filename.trim().is_empty() - { - return Some(filename.to_owned()); - } - if let Some(filename) = find_field(disposition, "filename", Some).map(|name| name.trim_matches('"')) - && !filename.trim().is_empty() - { - return Some(filename.to_owned()); - } + if let Some(filename) = headers.get("content-disposition").and_then(disposition_filename) { + return Some(filename); } - - let url = url.as_str(); - let path = url.split_once('?').map_or(url, |(path, _)| path); - let filename = path.rsplit_once('/').map_or(path, |(_, filename)| filename); + let filename = url.path().rsplit('/').next()?; let filename = percent_decode_str(filename).decode_utf8_lossy(); if filename.trim().is_empty() { return None; @@ -96,6 +80,57 @@ fn subscription_filename(url: &Url, headers: &HeaderMap) -> Option { Some(filename.into_owned()) } +fn disposition_filename(header: &http::HeaderValue) -> Option { + let mut quoted = false; + let mut escaped = false; + let fields = header.as_bytes().split(|&byte| { + if escaped { + escaped = false; + } else if quoted && byte == b'\\' { + escaped = true; + } else if byte == b'"' { + quoted = !quoted; + } else if !quoted && byte == b';' { + return true; + } + false + }); + + let mut plain = None; + for field in fields { + let Some((key, value)) = std::str::from_utf8(field).ok().and_then(|s| s.split_once('=')) else { + continue; + }; + let value = value.trim(); + if key.trim().eq_ignore_ascii_case("filename*") { + let encoded = value.splitn(3, '\'').nth(2).unwrap_or(value); + if let Ok(name) = percent_decode_str(encoded).decode_utf8() + && !name.trim().is_empty() + { + return Some(name.into_owned()); + } + } else if plain.is_none() && key.trim().eq_ignore_ascii_case("filename") { + let name = unquote_filename(value); + if !name.trim().is_empty() { + plain = Some(name); + } + } + } + plain +} + +fn unquote_filename(value: &str) -> String { + let Some(inner) = value.strip_prefix('"').and_then(|s| s.strip_suffix('"')) else { + return value.to_owned(); + }; + let mut chars = inner.chars(); + let mut name = String::with_capacity(inner.len()); + while let Some(ch) = chars.next() { + name.push(if ch == '\\' { chars.next().unwrap_or(ch) } else { ch }); + } + name +} + pub fn normalize_profile_home_url(raw: &str) -> Option { let url = Url::parse(raw.trim()).ok()?; @@ -179,6 +214,22 @@ mod tests { Ok(()) } + #[test] + fn reads_filename_parameters_before_falling_back_to_the_url_path() -> Result<(), Box> { + let url = Url::parse("https://example.invalid/sub.yaml#my/notes")?; + for (disposition, expected) in [ + (r#"attachment; FileName="My; \"Work\".yaml""#, r#"My; "Work".yaml"#), + ("attachment; filename*=UTF-8'en'Work%27%27s.yaml", "Work''s.yaml"), + ("attachment", "sub.yaml"), + ] { + let mut headers = HeaderMap::new(); + headers.insert("content-disposition", HeaderValue::from_static(disposition)); + let document = decode_subscription(&url, &headers, "proxies: []")?; + assert_eq!(document.filename.as_deref(), Some(expected)); + } + Ok(()) + } + #[test] fn ignores_overflowing_server_interval() -> Result<(), Box> { let url = Url::parse("https://example.com/My%20Profile.yaml?token=value")?; From c53e005f254292e65319ac2593af7de6942464c1 Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:59:25 +0800 Subject: [PATCH 25/33] fix(subscription): separate deep link parameters from nested URLs --- .../clash-verge-subscription/src/deep_link.rs | 33 ++++++++++++++++--- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/clash-verge-subscription/src/deep_link.rs b/crates/clash-verge-subscription/src/deep_link.rs index d0ea94c16..dc38f3492 100644 --- a/crates/clash-verge-subscription/src/deep_link.rs +++ b/crates/clash-verge-subscription/src/deep_link.rs @@ -13,7 +13,11 @@ pub fn decode_subscription_link(link: &Url) -> Option> { } // The embedded URL can contain unescaped query separators of its own. - let raw_url = link.query()?.split_once("url=")?.1.trim(); + let query = link.query()?; + let raw_url = query + .strip_prefix("url=") + .or_else(|| query.split_once("&url=").map(|(_, url)| url))? + .trim(); let name = link.query_pairs().find(|(key, _)| key == "name").map(|(_, name)| name); Some(SubscriptionLink { url: decode_subscription_url(raw_url), @@ -22,10 +26,16 @@ pub fn decode_subscription_link(link: &Url) -> Option> { } fn decode_subscription_url(raw_url: &str) -> Cow<'_, str> { - let mut candidate = Cow::Borrowed(raw_url); if Url::parse(raw_url).is_ok() { - return candidate; + return Cow::Borrowed(raw_url); } + // Only the outer name has meaning here. Partly encoded URLs can still contain literal path and query delimiters. + let mut candidate = Cow::Borrowed( + raw_url + .split_once("&name=") + .filter(|(value, _)| !value.contains(['/', '?', '&'])) + .map_or(raw_url, |(value, _)| value), + ); for _ in 0..2 { let decoded = percent_decode_str(&candidate).decode_utf8_lossy(); @@ -51,7 +61,22 @@ mod tests { assert_eq!(link.name.as_deref(), Some("Work VPN")); assert!(matches!(link.url, Cow::Borrowed("https://example.invalid/sub?a=1&b=2"))); - let encoded = Url::parse("clash-verge://install-config?url=https%253A%252F%252Fexample.invalid%252Fsub")?; + let partial = Url::parse("clash://install-config?url=https%3A%2F%2Fexample.invalid/a&b/file?token=abc")?; + assert_eq!( + decode_subscription_link(&partial).expect("partially encoded link").url, + "https://example.invalid/a&b/file?token=abc" + ); + + let missing = Url::parse("clash://install-config?name=myurl=notes")?; + assert!(decode_subscription_link(&missing).is_none()); + let named = Url::parse("clash://install-config?name=myurl=notes&url=https://example.invalid/work")?; + assert_eq!( + decode_subscription_link(&named).expect("named link").url, + "https://example.invalid/work" + ); + + let encoded = + Url::parse("clash-verge://install-config?url=https%253A%252F%252Fexample.invalid%252Fsub&name=Work")?; let link = decode_subscription_link(&encoded).expect("double-encoded subscription link"); assert_eq!(link.url, "https://example.invalid/sub"); Ok(()) From c742a9a17c4b18cc870fb5c2e59d01e0db49dfd5 Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:38:18 +0800 Subject: [PATCH 26/33] refactor(profile): look up the refresh target once --- crates/clash-verge-profile/src/lib.rs | 27 ++++++++-------- src-tauri/src/config/profiles.rs | 45 +++++++++------------------ src-tauri/src/feat/subscription.rs | 4 +-- 3 files changed, 30 insertions(+), 46 deletions(-) diff --git a/crates/clash-verge-profile/src/lib.rs b/crates/clash-verge-profile/src/lib.rs index 6f2a354d0..261e0079c 100644 --- a/crates/clash-verge-profile/src/lib.rs +++ b/crates/clash-verge-profile/src/lib.rs @@ -157,21 +157,20 @@ impl IProfiles { } pub fn get_item(&self, uid: impl AsRef) -> Result<&PrfItem, ProfileNotFound> { - let uid_str = uid.as_ref(); + let uid = uid.as_ref(); + self.items + .iter() + .flatten() + .find(|item| item.uid.as_deref() == Some(uid)) + .ok_or_else(|| ProfileNotFound { uid: uid.to_owned() }) + } - if let Some(items) = self.items.as_ref() { - for each in items.iter() { - if let Some(uid_val) = &each.uid - && uid_val.as_str() == uid_str - { - return Ok(each); - } - } - } - - Err(ProfileNotFound { - uid: uid_str.to_owned(), - }) + pub fn get_item_mut(&mut self, uid: &str) -> Result<&mut PrfItem, ProfileNotFound> { + self.items + .iter_mut() + .flatten() + .find(|item| item.uid.as_deref() == Some(uid)) + .ok_or_else(|| ProfileNotFound { uid: uid.to_owned() }) } /// Inserts a prepared entry after any required body write. diff --git a/src-tauri/src/config/profiles.rs b/src-tauri/src/config/profiles.rs index 3ae3ed2f1..3b25a8fcc 100644 --- a/src-tauri/src/config/profiles.rs +++ b/src-tauri/src/config/profiles.rs @@ -193,32 +193,6 @@ fn validate_profile_file(file: &str) -> Result<()> { Ok(()) } -/// Updates fields returned by a remote profile refresh. -async fn apply_remote_refresh(profiles: &mut IProfiles, uid: &str, refresh: RemoteProfileRefresh) -> Result<()> { - let _ = profiles.get_item(uid)?; - - if let Some(each) = profiles - .items - .iter_mut() - .flatten() - .find(|item| item.uid.as_deref() == Some(uid)) - { - each.extra = refresh.extra; - each.updated = Some(refresh.updated); - each.home = refresh.home; - each.option = PrfOption::merge(each.option.as_ref(), Some(&refresh.option)); - let file = each - .file - .get_or_insert_with(|| format!("{}.yaml", help::get_uid("R")).into()); - let path = dirs::app_profiles_dir()?.join(file.as_str()); - fs::write(&path, refresh.body.as_bytes()) - .await - .with_context(|| format!("failed to write to file \"{file}\""))?; - } - - save_profiles(profiles).await -} - /// Raise intervals below `min_minutes`. `None`/`0` mean "never auto-update", left alone. /// Returns how many changed so the caller can skip a pointless write. pub(crate) fn raise_short_update_intervals(profiles: &mut IProfiles, min_minutes: u64) -> usize { @@ -315,14 +289,25 @@ pub(crate) async fn profiles_save_file_safe() -> Result<()> { with_profiles_edit(|profiles| async move { save_profiles(&profiles).await.map(|_| profiles) }).await } -pub(crate) async fn apply_remote_refresh_safe(index: &str, url: &str, refresh: RemoteProfileRefresh) -> Result<()> { +pub(crate) async fn save_remote_refresh(uid: &str, url: &str, refresh: RemoteProfileRefresh) -> Result<()> { with_profiles_edit(|mut profiles| async move { - let current = profiles.get_item(index)?; + let profile = profiles.get_item_mut(uid)?; anyhow::ensure!( - current.itype.as_deref() == Some("remote") && current.url.as_deref() == Some(url), + profile.itype.as_deref() == Some("remote") && profile.url.as_deref() == Some(url), "profile source changed during refresh" ); - apply_remote_refresh(&mut profiles, index, refresh).await?; + profile.extra = refresh.extra; + profile.updated = Some(refresh.updated); + profile.home = refresh.home; + profile.option = PrfOption::merge(profile.option.as_ref(), Some(&refresh.option)); + let file = profile + .file + .get_or_insert_with(|| format!("{}.yaml", help::get_uid("R")).into()); + let path = dirs::app_profiles_dir()?.join(file.as_str()); + fs::write(&path, refresh.body.as_bytes()) + .await + .with_context(|| format!("failed to write to file \"{file}\""))?; + save_profiles(&profiles).await?; Ok(profiles) }) .await diff --git a/src-tauri/src/feat/subscription.rs b/src-tauri/src/feat/subscription.rs index af4125341..469b628b2 100644 --- a/src-tauri/src/feat/subscription.rs +++ b/src-tauri/src/feat/subscription.rs @@ -1,5 +1,5 @@ use crate::{ - config::{Config, PrfOption, download_subscription, prepare_remote_refresh, profiles::apply_remote_refresh_safe}, + config::{Config, PrfOption, download_subscription, prepare_remote_refresh, profiles::save_remote_refresh}, core::{ CoreManager, handle, notify::{NoticeStatus, Refresh, announce}, @@ -133,7 +133,7 @@ async fn perform_profile_update( "profile source changed during refresh" ); let refresh = prepare_remote_refresh(downloaded, merged_opt.as_ref()).await?; - apply_remote_refresh_safe(uid, url, refresh).await?; + save_remote_refresh(uid, url, refresh).await?; if !matches!(strategy, Strategy::Configured) { handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str()); } From 83a520ea19bf7d2be77777880604774d0e3167ec Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:38:23 +0800 Subject: [PATCH 27/33] refactor(subscription): pass the proxy directly to each download --- src-tauri/src/config/mod.rs | 2 +- src-tauri/src/config/prfitem.rs | 35 +++++---- src-tauri/src/feat/subscription.rs | 112 ++++++++++++++--------------- 3 files changed, 72 insertions(+), 77 deletions(-) diff --git a/src-tauri/src/config/mod.rs b/src-tauri/src/config/mod.rs index 3fc525de0..21335bad7 100644 --- a/src-tauri/src/config/mod.rs +++ b/src-tauri/src/config/mod.rs @@ -13,7 +13,7 @@ mod verge; pub(crate) use self::config::Config; pub(crate) use self::prfitem::{ - build_remote_profile, download_subscription, prepare_remote_refresh, read_profile_item_file, + build_remote_profile, download_subscription, prepare_remote_refresh, read_profile_item_file, subscription_proxy, }; pub use self::{clash::*, encrypt::*, mixed_port::*, profiles::*, verge::*}; pub use clash_verge_profile::{PrfExtra, PrfItem, PrfOption, PrfSelected}; diff --git a/src-tauri/src/config/prfitem.rs b/src-tauri/src/config/prfitem.rs index a82416211..698708904 100644 --- a/src-tauri/src/config/prfitem.rs +++ b/src-tauri/src/config/prfitem.rs @@ -140,7 +140,7 @@ pub(crate) async fn build_remote_profile( desc: Option<&String>, option: Option<&PrfOption>, ) -> Result { - let mut downloaded = download_subscription(url, option).await?; + let mut downloaded = download_subscription(url, option, subscription_proxy(option)).await?; let uid: String = help::get_uid("R").into(); let file = format!("{uid}.yaml").into(); let name = name @@ -172,31 +172,28 @@ pub(crate) async fn build_remote_profile( }) } -pub(crate) async fn download_subscription(url: &str, option: Option<&PrfOption>) -> Result { - let with_proxy = option.is_some_and(|o| o.with_proxy.unwrap_or(false)); - let self_proxy = option.is_some_and(|o| o.self_proxy.unwrap_or(false)); - let accept_invalid_certs = option.is_some_and(|o| o.danger_accept_invalid_certs.unwrap_or(false)); - let user_agent = option.and_then(|o| o.user_agent.clone()); - let timeout = option.and_then(|o| o.timeout_seconds).unwrap_or(20); - - let proxy_type = if self_proxy { +pub(crate) fn subscription_proxy(options: Option<&PrfOption>) -> ProxyType { + if options.and_then(|options| options.self_proxy) == Some(true) { ProxyType::Localhost - } else if with_proxy { + } else if options.and_then(|options| options.with_proxy) == Some(true) { ProxyType::System } else { ProxyType::None - }; + } +} +pub(crate) async fn download_subscription( + url: &str, + option: Option<&PrfOption>, + proxy: ProxyType, +) -> Result { + let accept_invalid_certs = option.is_some_and(|o| o.danger_accept_invalid_certs.unwrap_or(false)); + let user_agent = option.and_then(|o| o.user_agent.clone()); + let timeout = option.and_then(|o| o.timeout_seconds).unwrap_or(20); let url = fix_dirty_url(url)?; let resp = match NetworkManager::new() - .get( - url.as_str(), - proxy_type, - Some(timeout), - user_agent, - accept_invalid_certs, - ) + .get(url.as_str(), proxy, Some(timeout), user_agent, accept_invalid_certs) .await { Ok(r) => r, @@ -416,7 +413,7 @@ mod tests { update_interval: None, ..option }; - let downloaded = download_subscription(&url, Some(&refresh_option)).await?; + let downloaded = download_subscription(&url, Some(&refresh_option), ProxyType::None).await?; let refresh = prepare_remote_refresh(downloaded, Some(&refresh_option)).await?; server.await??; assert_eq!(item.itype.as_deref(), Some("remote")); diff --git a/src-tauri/src/feat/subscription.rs b/src-tauri/src/feat/subscription.rs index 469b628b2..906dff649 100644 --- a/src-tauri/src/feat/subscription.rs +++ b/src-tauri/src/feat/subscription.rs @@ -1,11 +1,17 @@ use crate::{ - config::{Config, PrfOption, download_subscription, prepare_remote_refresh, profiles::save_remote_refresh}, + config::{ + Config, PrfOption, download_subscription, prepare_remote_refresh, profiles::save_remote_refresh, + subscription_proxy, + }, core::{ CoreManager, handle, notify::{NoticeStatus, Refresh, announce}, validate::ValidationOutcome, }, - utils::help::{mask_err, mask_url}, + utils::{ + help::{mask_err, mask_url}, + network::ProxyType, + }, }; use anyhow::{Result, bail}; use clash_verge_logging::{Type, logging}; @@ -48,11 +54,13 @@ async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result, - option: Option<&PrfOption>, + profile_options: Option<&PrfOption>, + overrides: Option<&PrfOption>, is_manual_trigger: bool, ) -> Result<()> { - let merged_opt = PrfOption::merge(opt, option); + let options = PrfOption::merge(profile_options, overrides); + let options = options.as_ref(); + let configured_proxy = subscription_proxy(options); let profiles = Config::profiles().await; let profiles_arc = profiles.latest_arc(); let profile_name = profiles_arc @@ -71,54 +79,44 @@ async fn perform_profile_update( let result = clash_verge_task::retry::try_strategies( Strategy::Configured, [Strategy::Clash, Strategy::System], - |strategy| { - let mut options = merged_opt.clone(); - async move { - let (name, success, failure) = match strategy { - Strategy::Configured => ( - "configured", - "[订阅更新] 更新订阅配置成功", - "[订阅更新] 直接更新失败: {},尝试使用Clash代理更新", - ), - Strategy::Clash => ( - "clash", - "[订阅更新] 使用 Clash代理 更新订阅配置成功", - "[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新", - ), - Strategy::System => ( - "system", - "[订阅更新] 使用 系统代理 更新订阅配置成功", - "[订阅更新] 系统代理更新失败: {},所有重试均已失败", - ), - }; - match strategy { - Strategy::Configured => {} - Strategy::Clash | Strategy::System => { - let option = options.get_or_insert_with(PrfOption::default); - option.self_proxy = Some(matches!(strategy, Strategy::Clash)); - option.with_proxy = Some(matches!(strategy, Strategy::System)); - } - } - tracing::Span::current().record("strategy", name); - let started = std::time::Instant::now(); - let result = download_subscription(url, options.as_ref()).await; - let elapsed_field = match strategy { - Strategy::Configured => "configured_elapsed", - Strategy::Clash => "clash_elapsed", - Strategy::System => "system_elapsed", - }; - tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed())); - match &result { - Ok(_) => logging!(info, Type::Config, "{success}"), - Err(error) => logging!( - warn, - Type::Config, - "{}", - failure.replace("{}", &mask_err(&format!("{error:#}"))) - ), - } - result + |strategy| async move { + let (name, proxy, elapsed_field, success, failure) = match strategy { + Strategy::Configured => ( + "configured", + configured_proxy, + "configured_elapsed", + "[订阅更新] 更新订阅配置成功", + "[订阅更新] 直接更新失败: {},尝试使用Clash代理更新", + ), + Strategy::Clash => ( + "clash", + ProxyType::Localhost, + "clash_elapsed", + "[订阅更新] 使用 Clash代理 更新订阅配置成功", + "[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新", + ), + Strategy::System => ( + "system", + ProxyType::System, + "system_elapsed", + "[订阅更新] 使用 系统代理 更新订阅配置成功", + "[订阅更新] 系统代理更新失败: {},所有重试均已失败", + ), + }; + tracing::Span::current().record("strategy", name); + let started = std::time::Instant::now(); + let result = download_subscription(url, options, proxy).await; + tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed())); + match &result { + Ok(_) => logging!(info, Type::Config, "{success}"), + Err(error) => logging!( + warn, + Type::Config, + "{}", + failure.replace("{}", &mask_err(&format!("{error:#}"))) + ), } + result }, ) .await; @@ -132,7 +130,7 @@ async fn perform_profile_update( current.itype.as_deref() == Some("remote") && current.url.as_deref() == Some(url), "profile source changed during refresh" ); - let refresh = prepare_remote_refresh(downloaded, merged_opt.as_ref()).await?; + let refresh = prepare_remote_refresh(downloaded, options).await?; save_remote_refresh(uid, url, refresh).await?; if !matches!(strategy, Strategy::Configured) { handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str()); @@ -154,11 +152,11 @@ async fn perform_profile_update( #[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_manual_trigger))] pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_manual_trigger: bool) -> Result<()> { - let url_opt = should_update_profile(uid, is_manual_trigger).await?; + let subscription = should_update_profile(uid, is_manual_trigger).await?; - let profile_persisted = match url_opt { - Some((url, opt)) => { - perform_profile_update(uid, &url, opt.as_ref(), option, is_manual_trigger).await?; + let profile_persisted = match subscription { + Some((url, profile_options)) => { + perform_profile_update(uid, &url, profile_options.as_ref(), option, is_manual_trigger).await?; true } None => false, From 3af8034e024ae8a0b96ae72e4a0144e236c541dd Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:38:28 +0800 Subject: [PATCH 28/33] refactor(profile): build companion options in one place --- src-tauri/src/config/prfitem.rs | 88 ++++++++++----------------------- 1 file changed, 27 insertions(+), 61 deletions(-) diff --git a/src-tauri/src/config/prfitem.rs b/src-tauri/src/config/prfitem.rs index 698708904..d1e795400 100644 --- a/src-tauri/src/config/prfitem.rs +++ b/src-tauri/src/config/prfitem.rs @@ -51,29 +51,32 @@ async fn append_companion_item(item: &mut PrfItem) -> Result { .ok_or_else(|| anyhow::anyhow!("appended companion item has no uid")) } -async fn ensure_companion_items( - merge: &mut Option, - script: &mut Option, - rules: &mut Option, - proxies: &mut Option, - groups: &mut Option, -) -> Result<()> { - if merge.is_none() { - *merge = Some(append_companion_item(&mut build_merge_profile(None)).await?); +async fn prepare_profile_options(source: Option<&PrfOption>) -> Result { + let mut options = PrfOption { + update_interval: source.and_then(|options| options.update_interval), + merge: source.and_then(|options| options.merge.clone()), + script: source.and_then(|options| options.script.clone()), + rules: source.and_then(|options| options.rules.clone()), + proxies: source.and_then(|options| options.proxies.clone()), + groups: source.and_then(|options| options.groups.clone()), + ..PrfOption::default() + }; + if options.merge.is_none() { + options.merge = Some(append_companion_item(&mut build_merge_profile(None)).await?); } - if script.is_none() { - *script = Some(append_companion_item(&mut build_script_profile(None)).await?); + if options.script.is_none() { + options.script = Some(append_companion_item(&mut build_script_profile(None)).await?); } - if rules.is_none() { - *rules = Some(append_companion_item(&mut from_rules()).await?); + if options.rules.is_none() { + options.rules = Some(append_companion_item(&mut from_rules()).await?); } - if proxies.is_none() { - *proxies = Some(append_companion_item(&mut from_proxies()).await?); + if options.proxies.is_none() { + options.proxies = Some(append_companion_item(&mut from_proxies()).await?); } - if groups.is_none() { - *groups = Some(append_companion_item(&mut from_groups()).await?); + if options.groups.is_none() { + options.groups = Some(append_companion_item(&mut from_groups()).await?); } - Ok(()) + Ok(options) } async fn from_local( @@ -84,15 +87,7 @@ async fn from_local( ) -> Result { let uid = help::get_uid("L").into(); let file = format!("{uid}.yaml").into(); - let opt_ref = option.as_ref(); - let update_interval = opt_ref.and_then(|o| o.update_interval); - let mut merge = opt_ref.and_then(|o| o.merge.clone()); - let mut script = opt_ref.and_then(|o| o.script.clone()); - let mut rules = opt_ref.and_then(|o| o.rules.clone()); - let mut proxies = opt_ref.and_then(|o| o.proxies.clone()); - let mut groups = opt_ref.and_then(|o| o.groups.clone()); - - ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?; + let options = prepare_profile_options(option).await?; Ok(PrfItem { uid: Some(uid), itype: Some("local".into()), @@ -102,15 +97,7 @@ async fn from_local( url: None, selected: None, extra: None, - option: Some(PrfOption { - update_interval, - merge, - script, - rules, - proxies, - groups, - ..PrfOption::default() - }), + option: Some(options), home: None, updated: Some(chrono::Local::now().timestamp() as usize), file_data: Some(file_data.unwrap_or_else(|| tmpl::ITEM_LOCAL.into())), @@ -229,31 +216,14 @@ pub(crate) async fn prepare_remote_refresh( downloaded: DownloadedSubscription, option: Option<&PrfOption>, ) -> Result { - let mut resolved = PrfOption { - update_interval: option - .and_then(|o| o.update_interval) - .or(downloaded.update_interval_minutes), - merge: option.and_then(|o| o.merge.clone()), - script: option.and_then(|o| o.script.clone()), - rules: option.and_then(|o| o.rules.clone()), - proxies: option.and_then(|o| o.proxies.clone()), - groups: option.and_then(|o| o.groups.clone()), - allow_auto_update: Some(allow_auto_update_enabled(option)), - ..PrfOption::default() - }; - ensure_companion_items( - &mut resolved.merge, - &mut resolved.script, - &mut resolved.rules, - &mut resolved.proxies, - &mut resolved.groups, - ) - .await?; + let mut options = prepare_profile_options(option).await?; + options.update_interval = options.update_interval.or(downloaded.update_interval_minutes); + options.allow_auto_update = Some(option.and_then(|options| options.allow_auto_update).unwrap_or(true)); Ok(RemoteProfileRefresh { extra: downloaded.extra, home: downloaded.home, updated: chrono::Local::now().timestamp() as usize, - option: resolved, + option: options, body: downloaded.body, }) } @@ -328,10 +298,6 @@ pub(crate) async fn read_profile_item_file(file: Option<&str>) -> Result Ok(content.into()) } -fn allow_auto_update_enabled(option: Option<&PrfOption>) -> bool { - option.and_then(|o| o.allow_auto_update).unwrap_or(true) -} - /// Fix URLs where query parameters are incorrectly appended to the path segment /// /// Incorrect Example: https://example.com/path¶m1=value1 From 966e0e03ff3d781326af95f63774d2fe6ef9fa0e Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:38:32 +0800 Subject: [PATCH 29/33] refactor(profile): remove companions from the deleted profile --- crates/clash-verge-profile/src/lib.rs | 55 +++++++++++---------------- 1 file changed, 22 insertions(+), 33 deletions(-) diff --git a/crates/clash-verge-profile/src/lib.rs b/crates/clash-verge-profile/src/lib.rs index 261e0079c..cdf82788b 100644 --- a/crates/clash-verge-profile/src/lib.rs +++ b/crates/clash-verge-profile/src/lib.rs @@ -199,41 +199,30 @@ impl IProfiles { pub fn plan_delete_item(&mut self, uid: &str) -> Result { let deleting_current = self.current.as_deref().is_none_or(|current| current == uid); - let delete_uids = self.get_item(uid)?.option.as_ref().map_or_else(Vec::new, |op| { - [ - op.merge.clone(), - op.script.clone(), - op.rules.clone(), - op.proxies.clone(), - op.groups.clone(), - ] - .into_iter() - .collect::>() - }); - let mut items = self.items.take().unwrap_or_default(); - let mut files = Vec::new(); - - if let Some(file) = take_item_file_by_uid(&mut items, Some(uid)) { - files.push(file); - } - - for delete_uid in delete_uids { - if let Some(file) = take_item_file_by_uid(&mut items, delete_uid.as_deref()) { - files.push(file); - } - } - - if deleting_current { - self.current = None; - for item in items.iter() { - if matches!(item.itype.as_deref(), Some("remote" | "local")) { - self.current = item.uid.clone(); - break; + let missing_profile = || ProfileNotFound { uid: uid.to_owned() }; + let items = self.items.as_mut().ok_or_else(missing_profile)?; + let profile = remove_item(items, Some(uid)).ok_or_else(missing_profile)?; + let mut files = Vec::from_iter(profile.file); + if let Some(options) = profile.option { + for companion_uid in [ + options.merge, + options.script, + options.rules, + options.proxies, + options.groups, + ] { + if let Some(file) = remove_item(items, companion_uid.as_deref()).and_then(|item| item.file) { + files.push(file); } } } - self.items = Some(items); + if deleting_current { + self.current = items + .iter() + .find(|item| matches!(item.itype.as_deref(), Some("remote" | "local"))) + .and_then(|item| item.uid.clone()); + } Ok(ProfileDeletePlan { deleting_current, files, @@ -258,9 +247,9 @@ impl IProfiles { } } -fn take_item_file_by_uid(items: &mut Vec, target_uid: Option<&str>) -> Option { +fn remove_item(items: &mut Vec, target_uid: Option<&str>) -> Option { let index = items.iter().position(|item| item.uid.as_deref() == target_uid)?; - items.remove(index).file + Some(items.remove(index)) } #[cfg(test)] From 80fca9684887b6e1554b8c60a5394f64d0d69c5b Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:38:36 +0800 Subject: [PATCH 30/33] style(profile): keep profile fields together --- crates/clash-verge-profile/src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/clash-verge-profile/src/lib.rs b/crates/clash-verge-profile/src/lib.rs index cdf82788b..8a56d1ae9 100644 --- a/crates/clash-verge-profile/src/lib.rs +++ b/crates/clash-verge-profile/src/lib.rs @@ -20,7 +20,6 @@ macro_rules! patch_opt_field { #[serde(default)] pub struct PrfItem { pub uid: Option, - /// enum value: remote | local | script | merge #[serde(rename = "type")] pub itype: Option, From 651f297785bb662261f589ba71c007b0e3884fac Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:38:42 +0800 Subject: [PATCH 31/33] refactor(profile): name index operations after what they change --- src-tauri/src/cmd/clash.rs | 6 +++--- src-tauri/src/cmd/profile.rs | 21 ++++++++++----------- src-tauri/src/config/config.rs | 6 +++--- src-tauri/src/config/prfitem.rs | 2 +- src-tauri/src/config/profiles.rs | 16 ++++++++-------- src-tauri/src/utils/resolve/scheme.rs | 4 ++-- 6 files changed, 27 insertions(+), 28 deletions(-) diff --git a/src-tauri/src/cmd/clash.rs b/src-tauri/src/cmd/clash.rs index 8c6468955..0a9720719 100644 --- a/src-tauri/src/cmd/clash.rs +++ b/src-tauri/src/cmd/clash.rs @@ -4,7 +4,7 @@ use crate::feat; use crate::utils::{dirs, yaml_emitter}; use crate::{ cmd::StringifyErr as _, - config::{ClashInfo, Config, profiles::profiles_save_file_safe}, + config::{ClashInfo, Config, profiles::save_committed_profiles}, constants, core::{ CoreManager, handle, @@ -59,7 +59,7 @@ pub async fn change_clash_core(clash_core: std::string::String) -> CmdResult { - logging_error!(Type::Core, profiles_save_file_safe().await); + logging_error!(Type::Core, save_committed_profiles().await); match CoreManager::global().restart_core().await { Ok(_) => { @@ -88,7 +88,7 @@ pub async fn change_clash_core(clash_core: std::string::String) -> CmdResult CmdResult { - logging_error!(Type::Core, profiles_save_file_safe().await); + logging_error!(Type::Core, save_committed_profiles().await); let result = CoreManager::global() .restart_core() .await diff --git a/src-tauri/src/cmd/profile.rs b/src-tauri/src/cmd/profile.rs index 18163b48d..23f03c47e 100644 --- a/src-tauri/src/cmd/profile.rs +++ b/src-tauri/src/cmd/profile.rs @@ -7,9 +7,8 @@ use crate::{ config::{ Config, IProfiles, PrfItem, PrfOption, build_remote_profile, profiles::{ - PROFILE_WRITE_LOCK, cleanup_profile_files, profiles_append_item_safe, - profiles_append_item_with_filedata_safe, profiles_patch_item_safe, profiles_reorder_safe, - profiles_save_file_safe, save_profiles, + PROFILE_WRITE_LOCK, append_profile, cleanup_profile_files, patch_profile_item, reorder_profiles, + save_committed_profiles, save_profiles, }, read_profile_item_file, }, @@ -80,12 +79,12 @@ pub async fn import_profile(url: std::string::String, option: Option) } }; - if let Err(e) = profiles_append_item_safe(item).await { + if let Err(e) = append_profile(item).await { logging!(error, Type::Cmd, "[导入订阅] 保存配置失败: {e:#}"); return Err(coded_error("PROFILE_IMPORT_FAILED", e)); } - if let Err(e) = profiles_save_file_safe().await { + if let Err(e) = save_committed_profiles().await { logging!(error, Type::Cmd, "[导入订阅] 保存配置文件失败: {e:#}"); return Err(coded_error("PROFILE_IMPORT_FAILED", e)); } @@ -104,7 +103,7 @@ pub async fn import_profile(url: std::string::String, option: Option) 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 reorder_profiles(&active_id, &over_id).await { Ok(_) => { logging!(info, Type::Cmd, "重新排序配置文件: {} -> {}", active_id, over_id); Ok(()) @@ -127,9 +126,9 @@ pub async fn reorder_profile(active_id: std::string::String, over_id: std::strin pub async fn create_profile(item: ProfileCreate, file_data: Option) -> 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::create_profile(&item, file_data).await { Ok(_) => { - profiles_save_file_safe() + save_committed_profiles() .await .with_error_code("PROFILE_CREATE_FAILED")?; logging_error!(Type::Timer, Timer::global().refresh().await); @@ -219,7 +218,7 @@ async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> { .edit_draft(|d| d.patch_current(Some(prev_profile))); Config::profiles().await.apply(); crate::process::AsyncHandler::spawn(|| async move { - if let Err(e) = profiles_save_file_safe().await { + if let Err(e) = save_committed_profiles().await { logging!(warn, Type::Cmd, "异步保存恢复配置文件失败: {e:#}"); } }); @@ -247,7 +246,7 @@ async fn handle_success(current_value: Option<&String>) -> CmdResult // Prevent an in-flight restore from overwriting a newer UI or chain selection. let records_a_selection = profile.selected.is_some(); - profiles_patch_item_safe(&index, &profile) + patch_profile_item(&index, &profile) .await .with_error_code("PROFILE_UPDATE_FAILED")?; diff --git a/src-tauri/src/config/config.rs b/src-tauri/src/config/config.rs index ec7ccc028..240d66636 100644 --- a/src-tauri/src/config/config.rs +++ b/src-tauri/src/config/config.rs @@ -3,7 +3,7 @@ use crate::core::notify::NoticeStatus; use crate::{ config::{ prfitem::{build_merge_profile, build_script_profile}, - profiles::{load_profiles, profiles_append_item_to_safe, save_profiles}, + profiles::{append_to_profile_index, load_profiles, save_profiles}, runtime::IRuntime, }, constants::{files, timing}, @@ -142,11 +142,11 @@ impl Config { if profiles.latest_arc().get_item("Merge").is_err() { let merge_item = &mut build_merge_profile(Some("Merge".into())); - profiles_append_item_to_safe(&profiles, merge_item).await?; + append_to_profile_index(&profiles, merge_item).await?; } if profiles.latest_arc().get_item("Script").is_err() { let script_item = &mut build_script_profile(Some("Script".into())); - profiles_append_item_to_safe(&profiles, script_item).await?; + append_to_profile_index(&profiles, script_item).await?; } Ok(()) } diff --git a/src-tauri/src/config/prfitem.rs b/src-tauri/src/config/prfitem.rs index d1e795400..2eb1fb608 100644 --- a/src-tauri/src/config/prfitem.rs +++ b/src-tauri/src/config/prfitem.rs @@ -45,7 +45,7 @@ pub(super) async fn build_profile(item: &PrfItem, file_data: Option) -> } async fn append_companion_item(item: &mut PrfItem) -> Result { - profiles::profiles_append_item_safe(item).await?; + profiles::append_profile(item).await?; item.uid .clone() .ok_or_else(|| anyhow::anyhow!("appended companion item has no uid")) diff --git a/src-tauri/src/config/profiles.rs b/src-tauri/src/config/profiles.rs index 3b25a8fcc..121cbe78f 100644 --- a/src-tauri/src/config/profiles.rs +++ b/src-tauri/src/config/profiles.rs @@ -233,9 +233,9 @@ pub(crate) async fn current_mapping(profiles: &IProfiles) -> Result { // These helpers serialize asynchronous operations against committed profile data. use crate::config::Config; -pub(crate) async fn profiles_append_item_with_filedata_safe(item: &PrfItem, file_data: Option) -> Result<()> { +pub(crate) async fn create_profile(item: &PrfItem, file_data: Option) -> Result<()> { let item = &mut build_profile(item, file_data).await?; - profiles_append_item_safe(item).await + append_profile(item).await } /// Applies `edit` to the committed profiles; commits only when the edit succeeds. @@ -253,12 +253,12 @@ where .await } -pub(crate) async fn profiles_append_item_safe(item: &mut PrfItem) -> Result<()> { +pub(crate) async fn append_profile(item: &mut PrfItem) -> Result<()> { let profiles = Config::profiles().await; - profiles_append_item_to_safe(&profiles, item).await + append_to_profile_index(&profiles, item).await } -pub(super) async fn profiles_append_item_to_safe(profiles: &Draft, item: &mut PrfItem) -> Result<()> { +pub(super) async fn append_to_profile_index(profiles: &Draft, item: &mut PrfItem) -> Result<()> { profiles .with_data_modify(|mut profiles| async move { append_item(&mut profiles, item).await?; @@ -267,7 +267,7 @@ pub(super) async fn profiles_append_item_to_safe(profiles: &Draft, it .await } -pub(crate) async fn profiles_patch_item_safe(index: &str, item: &PrfItem) -> Result<()> { +pub(crate) async fn patch_profile_item(index: &str, item: &PrfItem) -> Result<()> { with_profiles_edit(|mut profiles| async move { patch_item(&mut profiles, index, item).await?; Ok(profiles) @@ -275,7 +275,7 @@ pub(crate) async fn profiles_patch_item_safe(index: &str, item: &PrfItem) -> Res .await } -pub(crate) async fn profiles_reorder_safe(active_id: &str, over_id: &str) -> Result<()> { +pub(crate) async fn reorder_profiles(active_id: &str, over_id: &str) -> Result<()> { with_profiles_edit(|mut profiles| async move { if profiles.reorder(active_id, over_id) { save_profiles(&profiles).await?; @@ -285,7 +285,7 @@ pub(crate) async fn profiles_reorder_safe(active_id: &str, over_id: &str) -> Res .await } -pub(crate) async fn profiles_save_file_safe() -> Result<()> { +pub(crate) async fn save_committed_profiles() -> Result<()> { with_profiles_edit(|profiles| async move { save_profiles(&profiles).await.map(|_| profiles) }).await } diff --git a/src-tauri/src/utils/resolve/scheme.rs b/src-tauri/src/utils/resolve/scheme.rs index b16ffa448..5ff14ac56 100644 --- a/src-tauri/src/utils/resolve/scheme.rs +++ b/src-tauri/src/utils/resolve/scheme.rs @@ -51,14 +51,14 @@ async fn import_subscription(url: &str, name: Option<&String>) { }; let uid = item.uid.clone().unwrap_or_default(); - if let Err(e) = profiles::profiles_append_item_safe(&mut item).await { + if let Err(e) = profiles::append_profile(&mut item).await { logging!(error, Type::Config, "failed to import subscription url: {:?}", e); Config::profiles().await.discard(); handle::Handle::notice(NoticeStatus::ImportSubUrlError, e.to_string()); return; } - if let Err(e) = profiles::profiles_save_file_safe().await { + if let Err(e) = profiles::save_committed_profiles().await { logging!(error, Type::Config, "failed to save imported subscription: {e:#}"); handle::Handle::notice(NoticeStatus::ImportSubUrlError, e.to_string()); return; From 35dbb3716d366f959f3824ec7cbf54994e05a99c Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:38:46 +0800 Subject: [PATCH 32/33] refactor(profile): call the core reload directly --- src-tauri/src/cmd/profile.rs | 2 +- src-tauri/src/core/hotkey.rs | 8 ++++++-- src-tauri/src/feat/profile.rs | 7 +------ 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src-tauri/src/cmd/profile.rs b/src-tauri/src/cmd/profile.rs index 23f03c47e..3e6283ff9 100644 --- a/src-tauri/src/cmd/profile.rs +++ b/src-tauri/src/cmd/profile.rs @@ -45,7 +45,7 @@ pub async fn get_profiles() -> CmdResult> { #[tauri::command] #[specta::specta] pub async fn enhance_profiles() -> CmdResult { - match feat::enhance_profiles().await { + match CoreManager::global().update_config_forced().await { Ok(outcome) if outcome.is_valid() => { handle::Handle::refresh_clash(); Ok(outcome) diff --git a/src-tauri/src/core/hotkey.rs b/src-tauri/src/core/hotkey.rs index 5ecff74dc..b3ad13315 100755 --- a/src-tauri/src/core/hotkey.rs +++ b/src-tauri/src/core/hotkey.rs @@ -3,7 +3,11 @@ use crate::process::AsyncHandler; use crate::singleton; use crate::utils::notification::{NotificationEvent, notify_event}; use crate::utils::window_manager::WindowManager; -use crate::{config::Config, core::handle, core::lightweight::entry_lightweight_mode, feat}; +use crate::{ + config::Config, + core::{CoreManager, handle, lightweight::entry_lightweight_mode}, + feat, +}; use anyhow::{Result, bail}; use arc_swap::ArcSwap; use clash_verge_logging::{Type, logging}; @@ -165,7 +169,7 @@ impl Hotkey { }); } HotkeyFunction::ReactivateProfiles => { - AsyncHandler::spawn(async move || match feat::enhance_profiles().await { + AsyncHandler::spawn(async move || match CoreManager::global().update_config_forced().await { Ok(outcome) if outcome.is_valid() => { handle::Handle::refresh_clash(); notify_event(NotificationEvent::ProfilesReactivated).await; diff --git a/src-tauri/src/feat/profile.rs b/src-tauri/src/feat/profile.rs index 5faa49faa..cfd9e5e69 100644 --- a/src-tauri/src/feat/profile.rs +++ b/src-tauri/src/feat/profile.rs @@ -2,7 +2,7 @@ use crate::core::notify::{Refresh, announce}; use crate::{ cmd, config::Config, - core::{CoreManager, handle, tray, validate::ValidationOutcome}, + core::{handle, tray}, process::AsyncHandler, }; use anyhow::Result; @@ -199,11 +199,6 @@ async fn finish_proxy_switch(stale_proxies: Vec) { } } -/// 增强配置 -pub async fn enhance_profiles() -> Result { - CoreManager::global().update_config_forced().await -} - #[cfg(test)] mod tests { use super::*; From a272280f1ad02619677b1d8f037afa5ef055954f Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:38:51 +0800 Subject: [PATCH 33/33] refactor(backup): move archive validation to the restore change --- .../clash-verge-backup-archive/src/error.rs | 6 --- crates/clash-verge-backup-archive/src/lib.rs | 51 +++---------------- 2 files changed, 6 insertions(+), 51 deletions(-) diff --git a/crates/clash-verge-backup-archive/src/error.rs b/crates/clash-verge-backup-archive/src/error.rs index de04927c3..d675c75fb 100644 --- a/crates/clash-verge-backup-archive/src/error.rs +++ b/crates/clash-verge-backup-archive/src/error.rs @@ -4,10 +4,4 @@ pub enum ArchiveError { Zip(#[from] zip::result::ZipError), #[error(transparent)] Io(#[from] std::io::Error), - #[error("backup contains a symbolic link")] - Symlink, - #[error("backup contains an invalid path")] - InvalidPath, - #[error("archive contains profile recovery data")] - ReservedEntry, } diff --git a/crates/clash-verge-backup-archive/src/lib.rs b/crates/clash-verge-backup-archive/src/lib.rs index 0f6c75685..27a00ff15 100644 --- a/crates/clash-verge-backup-archive/src/lib.rs +++ b/crates/clash-verge-backup-archive/src/lib.rs @@ -2,11 +2,8 @@ mod error; pub use error::ArchiveError; -use std::{ - io::{self, Read, Seek, Write}, - path::{Component, Path}, -}; -use zip::{CompressionMethod, ZipArchive, ZipWriter, write::SimpleFileOptions}; +use std::io::{Seek, Write}; +use zip::{CompressionMethod, ZipWriter, write::SimpleFileOptions}; pub struct BackupWriter { zip: ZipWriter, @@ -35,55 +32,20 @@ impl BackupWriter { } } -pub struct ValidatedBackup { - zip: ZipArchive, -} - -impl ValidatedBackup { - pub fn open(source: R, reserved_names: &[&str]) -> Result { - let mut zip = ZipArchive::new(source)?; - for index in 0..zip.len() { - let mut entry = zip.by_index(index)?; - if entry.is_symlink() { - return Err(ArchiveError::Symlink); - } - let path = entry.enclosed_name().ok_or(ArchiveError::InvalidPath)?; - for component in path.components() { - let Component::Normal(name) = component else { - continue; - }; - let name = name.to_string_lossy(); - if reserved_names - .iter() - .any(|reserved| name.eq_ignore_ascii_case(reserved)) - { - return Err(ArchiveError::ReservedEntry); - } - } - io::copy(&mut entry, &mut io::sink())?; - } - Ok(Self { zip }) - } - - pub fn extract_to(mut self, destination: &Path) -> Result<(), ArchiveError> { - self.zip.extract(destination)?; - Ok(()) - } -} - #[cfg(test)] mod tests { use super::*; - use std::io::Cursor; + use std::io::{Cursor, Read as _}; + use zip::ZipArchive; #[test] - fn writes_and_validates_the_backup_layout() -> Result<(), ArchiveError> { + fn writes_the_backup_layout() -> Result<(), ArchiveError> { let mut writer = BackupWriter::new(Cursor::new(Vec::new()))?; writer.start_profile("example.yaml")?.write_all(b"proxies: []\n")?; writer.start_file("profiles.yaml")?.write_all(b"items: []\n")?; let source = writer.finish()?; - let mut zip = ZipArchive::new(source.clone())?; + let mut zip = ZipArchive::new(source)?; assert_eq!(zip.len(), 3); assert_eq!(zip.by_index(0)?.name()?, "profiles/"); let profile_time = { @@ -98,7 +60,6 @@ mod tests { let index = zip.by_index(2)?; assert_eq!(index.name()?, "profiles.yaml"); assert_eq!(index.last_modified(), profile_time); - ValidatedBackup::open(source, &[".profile-refresh", ".profile-refresh.lock"])?; Ok(()) } }