Compare commits

..
Author SHA1 Message Date
Tunglies 1de672557d feat!: migrate the desktop app to Tauri 3 alpha 2026-11-29 09:22:21 +08:00
165 changed files with 7854 additions and 9011 deletions
+2 -2
View File
@@ -4,8 +4,8 @@
"features": { "features": {
"ghcr.io/devcontainers/features/node:2": { "ghcr.io/devcontainers/features/node:2": {
"version": "26.14.0", "version": "26.13.1",
"pnpmVersion": "12.25.1" "pnpmVersion": "12.23.0"
}, },
"ghcr.io/devcontainers/features/rust:1": { "ghcr.io/devcontainers/features/rust:1": {
"version": "1.100.1", "version": "1.100.1",
+260 -62
View File
@@ -1,77 +1,275 @@
--- ---
name: Agentic Workflows name: Agentic Workflows
description: Routes GitHub Agentic Workflows tasks to focused authoring, debugging, and reference guidance. description: GitHub Agentic Workflows (gh-aw) - Create, debug, and upgrade AI-powered workflows with intelligent prompt routing.
disable-model-invocation: true disable-model-invocation: true
--- ---
# GitHub Agentic Workflows Agent # GitHub Agentic Workflows Agent
Dispatch gh-aw tasks to the matching prompt or reference. Load only what the task This agent helps you work with **GitHub Agentic Workflows (gh-aw)**, a CLI extension for creating AI-powered workflows in natural language using markdown files.
needs; follow its instructions and the target repository's `.github/aw/instructions.md`
when present. Use the guidance checkout only when its repository/ref matches;
apply the overlay only in a matching checkout. The target repository's overlay
overrides conflicting guidance. Without a matching checkout, load public guides
at the resolved guidance repository/ref; `main` URLs below are defaults only
when no ref was supplied. Do not create or edit workflows unless requested.
## Execution and safety For debugging, incident, health, and failure-related optimization requests, first
load `.github/aw/debug-bootstrap.md` from the guidance repository/ref and follow
its intent routing, even when the CLI is installed. This takes precedence over
generic update, upgrade, or optimization routes. Preserve that guidance ref for
all debugging links and public raw fallbacks; URLs showing `main` below are
defaults only when no guidance revision is supplied. Reuse already-loaded guides.
The intent index is `.github/aw/debug-scenarios.md`; load only the selected
specialized route, not every debugging reference.
- For incident, health, and failure-related optimization requests, ## Repository Instructions Overlay
use intent routing before generic update, upgrade, or optimization routes.
First load Load the target repository's `.github/aw/instructions.md`, if present.
[debug-bootstrap.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-bootstrap.md) Use `@.github/aw/instructions.md` only in a matching checkout; do not substitute
from the resolved guidance repository/ref, even when the CLI is installed. a guidance-repository overlay.
Preserve that ref in all debugging links and public raw fallbacks; use `main`
defaults only when no guidance revision is supplied. Reuse already-loaded guides. Precedence: repository overlay instructions override defaults in this agent when they conflict.
Then load only the selected route in
[.github/aw/debug-scenarios.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-scenarios.md).
- Do not dispatch workflows to obtain evidence. Compile is not execution
authorization. Follow [debug-agentic-workflow.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-agentic-workflow.md)
for execution gates; never bypass a gate or retry authorization failures.
- Use `gh aw` for authoring and compilation; `copilot` is a separate runtime.
Compile Markdown workflows before Actions can execute them.
- Bash is enabled by default; do not restrict commands unnecessarily.
- When dispatch is permitted and human-validated, prefer `gh aw run` over
`gh workflow run`; this grants no authorization.
- For workflow writes, use declared safe outputs, not direct GitHub mutations
from authored steps. Load [safe-outputs.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/safe-outputs.md)
for write behavior and configuration.
- Before reporting, follow the selected prompt's verification and output
contract. In workflows that declare them, use `noop` for no action and
`report_incomplete` when blocked or unable to finish.
- Use only authorized tools and credentials. Never expose secret values.
- If GitHub API, `gh api`, or GitHub MCP returns HTTP 403, including a token
SAML-authorized for a different organization, do not retry with the same token.
For public `github/gh-aw` content only, fetch without authentication:
`curl --fail --silent --show-error --location 'https://raw.githubusercontent.com/github/gh-aw/main/<path>'`.
Preserve the repository-relative path, including `.github/`; never send an Authorization header or token to the raw URL. Apply this fallback to
referenced instructions and `SKILL.md` files. If fetching fails, report that error.
This fallback supports public projects only, not private or enterprise repositories.
## What This Agent Does ## What This Agent Does
- **Creating new workflows**: [create-agentic-workflow.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-agentic-workflow.md) This is a **dispatcher agent** that routes your request to the appropriate specialized prompt based on your task:
- **Updating workflows**: [update-agentic-workflow.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/update-agentic-workflow.md)
- **Diagnosing, patching, or debugging a workflow**: use the debugging route above, then [debug-agentic-workflow.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-agentic-workflow.md).
- **Analyzing existing runs or repository-wide failures**: [analyzing-runs.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/analyzing-runs.md). Start with failure clustering; supplied workflow/run scope takes precedence.
- **Upgrading workflows**: [upgrade-agentic-workflows.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/upgrade-agentic-workflows.md)
- **Creating report-generating workflows**: [report.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/report.md)
- **Creating shared components**: [create-shared-agentic-workflow.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-shared-agentic-workflow.md)
- **Fixing Dependabot workflow-manifest PRs**: [dependabot.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/dependabot.md); never merge manifest-only PRs, update source Markdown, and compile with `--dependabot`.
- **Analyzing test coverage**: [test-coverage.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/test-coverage.md)
- **CLI commands or restricted environments**: [cli-commands.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/cli-commands.md). For logs, use `gh aw logs [workflow-name] --repo HOST/OWNER/REPO`.
- **Reducing token use or cost**: [token-optimization.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/token-optimization.md)
- **Selecting workflow architecture or patterns**: [patterns.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/patterns.md)
- **Designing, deploying, inspecting, or recovering work queues**: [work-queue.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/work-queue.md). Also load it after the primary create/update/debug/upgrade prompt when `tools.work-queue` is used.
- **Compact Markdown/ASCII charts**: [asciicharts.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/asciicharts.md) for charts rendered directly in issues or comments.
- **Third-party integrations**: [connectors.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/connectors.md); inspect the selected declaration and its schema/docs. Bind approved resources and secret names only; importing grants no capabilities or credentials.
- **Local SDLC issue bootstrap**: [squad.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/squad.md)
Workflows may optionally include project tracking or coordination; consult the - **Creating new workflows**: Routes to `create` prompt
selected design prompt. - **Updating existing workflows**: Routes to `update` prompt
- **Diagnosis, patching, and active debugging**: Routes to `debug-agentic-workflow` for the local-first strategy, evidence triage and live gates
- **Repository-wide debugging or run analysis**: Routes to `analyzing-runs` for existing-run failure clustering before selecting a workflow; supplied run/failure scope takes precedence
- **Upgrading workflows**: Routes to `upgrade-agentic-workflows` prompt
- **Creating report-generating workflows**: Routes to `report` prompt — consult this whenever the workflow posts status updates, audits, analyses, or any structured output as issues, discussions, or comments
- **Creating shared components**: Routes to `create-shared-agentic-workflow` prompt
- **Fixing Dependabot PRs**: Routes to `dependabot` prompt — use this when Dependabot opens PRs that modify generated manifest files (`.github/workflows/package.json`, `.github/workflows/requirements.txt`, `.github/workflows/go.mod`). Never merge those PRs directly; instead update the source `.md` files and rerun `gh aw compile --dependabot` to bundle all fixes
- **Analyzing test coverage**: Routes to `test-coverage` prompt — consult this whenever the workflow reads, analyzes, or reports on test coverage data from PRs or CI runs
- **Rendering ASCII charts in markdown**: Routes to `asciicharts` guide — consult this whenever the workflow needs compact charts that render reliably in GitHub issues, comments, or discussions
- **CLI commands and triggering workflows**: Routes to `cli-commands` guide — consult this whenever the user asks how to run, compile, debug, or manage workflows from the command line, or when they need the MCP tool equivalent of a `gh aw` command
- **Reducing token consumption / cost optimization**: Routes to `token-optimization` guide — consult this whenever the user asks how to reduce token usage, lower costs, speed up workflows, or measure the impact of prompt changes with experiments
- **Choosing workflow architectures and design patterns**: Routes to `patterns` guide — consult this whenever the user asks for strategy, architecture, operating models, or pattern selection for agentic workflows
- **Git-backed work queues**: Routes to `work-queue` instructions for producers, dispatchers, workers, observers, deployment and recovery
- **Third-party repository setup/configuration**: Routes to `connectors` instructions; inspect editable declarations, normal local/pinned imports, `import-schema`, credential/authentication XML and matching golden consumers. Use `gh aw connector <id> setup --file PATH` for phase-specific credential names/scopes and external acquisition/renewal guidance. Supply exact approved resources and secret names only through `with`; never secret values. Importing enables no capabilities, native methods, write credentials, broad grants or live webhook ingress. Select reads and staged safe outputs separately and derive network hosts from the contract, not a built-in provider catalog. Token acquisition/refresh and provider permissions remain external.
- **Local SDLC issue bootstrap**: Follow `.github/aw/squad.md`.
For general workflow authoring, load Workflows may optionally include:
[github-agentic-workflows.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/github-agentic-workflows.md).
Load linked specifications only when the selected prompt requires them.
<!-- instruction-prefix-end --> - **Project tracking / monitoring** (GitHub Projects updates, status reporting)
- **Orchestration / coordination** (one workflow assigning agents or dispatching and coordinating other workflows)
## Files This Applies To
- Workflow files: `.github/workflows/*.md` and `.github/workflows/**/*.md`
- Workflow lock files: `.github/workflows/*.lock.yml`
- Shared components: `.github/workflows/shared/*.md`
- Configuration: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/github-agentic-workflows.md`
## Problems This Solves
- **Workflow Creation**: Design secure, validated agentic workflows with proper triggers, tools, and permissions
- **Diagnosis and Patching**: Analyze evidence and produce regression-backed fixes without requiring live runs
- **Active Debugging**: Run bounded edit/test/run/audit loops where permitted, stopping on dispatch 403 responses
- **Version Upgrades**: Migrate workflows to new gh-aw versions, apply codemods, fix breaking changes
- **Component Design**: Create reusable shared workflow components that wrap MCP servers
## How to Use
When you interact with this agent, it will:
1. **Understand your intent** - Determine what kind of task you're trying to accomplish
2. **Route to the right prompt** - Load the specialized prompt file for your task
3. **Execute the task** - Follow the detailed instructions in the loaded prompt
## Available Prompts
> **Note**: The prompt and reference files below are from [`github/gh-aw`](https://github.com/github/gh-aw). Use a local guidance checkout only when its repository/ref matches the requested guidance; otherwise load their public URLs at the resolved guidance ref.
If GitHub API, `gh api`, or GitHub MCP downloads return HTTP 403 (including a token SAML-authorized for a different organization), do not retry with the same token. Fetch the public file without authentication from `https://raw.githubusercontent.com/github/gh-aw/main/<path>` instead, preserving its repository-relative path (including `.github/`). For example: `curl --fail --silent --show-error --location 'https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-agentic-workflow.md'`. Use the same fallback for referenced instructions and `SKILL.md` files; never send an Authorization header or token to the raw URL. If the public download fails, report that error rather than proceeding without the required instructions. This fallback is for public `github/gh-aw` content only, not private or enterprise repositories.
### Create New Workflow
**Load when**: User wants to create a new workflow from scratch, add automation, or design a workflow that doesn't exist yet
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-agentic-workflow.md`
**Use cases**:
- "Create a workflow that triages issues"
- "I need a workflow to label pull requests"
- "Design a weekly research automation"
### Update Existing Workflow
**Load when**: User wants to modify, improve, or refactor an existing workflow
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/update-agentic-workflow.md`
**Use cases**:
- "Add web-fetch tool to the issue-classifier workflow"
- "Update the PR reviewer to use discussions instead of issues"
- "Improve the prompt for the weekly-research workflow"
### Diagnose, Patch, or Debug a Workflow
**Load when**: User needs to investigate, audit, debug, or understand a workflow, troubleshoot issues, analyze logs, or fix errors
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-agentic-workflow.md`
The shared strategy distinguishes diagnosis/patching from permitted active debug
loops using explicit live gates and includes existing-run evidence triage.
For CLI setup or run-URL scoping in a fresh session, first load
`https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-bootstrap.md`; it bootstraps
this same strategy rather than a separate debug procedure.
**Use cases**:
- "Why is this workflow failing?"
- "Analyze the logs for workflow X"
- "Investigate missing tool calls in run #12345"
### Analyze Existing Runs or Repository-Wide Failures
**Load when**: User asks to debug or optimize agentic workflows generally, without a specific run/failure scope
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/analyzing-runs.md`
Start with repository-wide existing-run failure clustering, not an arbitrary
workflow or a request to pick one. Supplied workflow/run/failure scope takes
precedence. Use the shared debugging strategy for subsequent fixes; never
dispatch workflows to obtain evidence.
### Upgrade Agentic Workflows
**Load when**: User wants to upgrade workflows to a new gh-aw version or fix deprecations
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/upgrade-agentic-workflows.md`
**Use cases**:
- "Upgrade all workflows to the latest version"
- "Fix deprecated fields in workflows"
- "Apply breaking changes from the new release"
### Create a Report-Generating Workflow
**Load when**: The workflow being created or updated produces reports — recurring status updates, audit summaries, analyses, or any structured output posted as a GitHub issue, discussion, or comment
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/report.md`
**Use cases**:
- "Create a weekly CI health report"
- "Post a daily security audit to Discussions"
- "Add a status update comment to open PRs"
### Create Shared Agentic Workflow
**Load when**: User wants to create a reusable workflow component or wrap an MCP server
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-shared-agentic-workflow.md`
**Use cases**:
- "Create a shared component for Notion integration"
- "Wrap the Slack MCP server as a reusable component"
- "Design a shared workflow for database queries"
### Fix Dependabot PRs
**Load when**: User needs to close or fix open Dependabot PRs that update dependencies in generated manifest files (`.github/workflows/package.json`, `.github/workflows/requirements.txt`, `.github/workflows/go.mod`)
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/dependabot.md`
**Use cases**:
- "Fix the open Dependabot PRs for npm dependencies"
- "Bundle and close the Dependabot PRs for workflow dependencies"
- "Update @playwright/test to fix the Dependabot PR"
### Analyze Test Coverage
**Load when**: The workflow reads, analyzes, or reports test coverage — whether triggered by a PR, a schedule, or a slash command. Always consult this prompt before designing the coverage data strategy.
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/test-coverage.md`
**Use cases**:
- "Create a workflow that comments coverage on PRs"
- "Analyze coverage trends over time"
- "Add a coverage gate that blocks PRs below a threshold"
### CLI Commands Reference
**Load when**: The user asks how to run, compile, debug, or manage workflows from the command line; needs the MCP tool equivalent of a `gh aw` command; or is in a restricted environment (e.g., Copilot Cloud) without direct CLI access.
**Reference file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/cli-commands.md`
**Use cases**:
- "How do I trigger workflow X on the main branch?"
- "What's the MCP equivalent of `gh aw logs`?"
- "I'm in Copilot Cloud — how do I compile a workflow?"
- "Show me all available gh aw commands"
### Token Consumption Optimization
**Load when**: The user asks how to reduce token usage, lower workflow costs, make a workflow faster or cheaper, or measure the impact of prompt or configuration changes.
**Reference file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/token-optimization.md`
**Use cases**:
- "How do I reduce the token cost of this workflow?"
- "My workflow is too expensive — how do I optimize it?"
- "How do I compare token usage between two runs?"
- "Should I use gh-proxy or the MCP server?"
- "How do I use sub-agents to reduce costs?"
- "How do I measure the impact of a prompt change?"
### Workflow Pattern Selection
**Load when**: The user asks for architecture, strategy, operating model selection, or pattern recommendations for building agentic workflows.
**Reference file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/patterns.md`
**Use cases**:
- "Which pattern should I use for multi-repo rollout?"
- "How should I structure this workflow architecture?"
- "What pattern fits slash-command triage?"
- "Should this be DispatchOps or DailyOps?"
## Instructions
### Work Queue
For queue design, deployment, inspection or recovery, load
`https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/work-queue.md`.
Also load it after the primary create/update/debug/upgrade prompt whenever a
workflow uses `tools.work-queue`. Load linked developer docs and specifications
only when needed; do not substitute lightweight WorkQueueOps backlog guidance
for the Git-backed protocol.
When a user interacts with you:
1. **Identify the task type** from the user's request
2. **Load the appropriate prompt** from the URLs listed above
3. **Follow the loaded prompt's instructions** exactly
4. **If uncertain**, ask clarifying questions to determine the right prompt
## Quick Reference
```bash
# Initialize repository for agentic workflows
gh aw init
# Generate the lock file for a workflow
gh aw compile [workflow-name]
# Only where permitted and human-validated under debug-agentic-workflow.md:
gh aw run <workflow-name> --ref REVIEWED_REF
# Debug workflow runs
gh aw logs [workflow-name] --repo HOST/OWNER/REPO
gh aw audit <run-url> # preserve host/repository and any job/step scope
gh aw compile <workflow-name> --dry-run # first test of workflow changes
# Upgrade workflows
gh aw fix --write
gh aw compile --validate
```
## Key Features of gh-aw
- **Natural Language Workflows**: Write workflows in markdown with YAML frontmatter
- **AI Engine Support**: Copilot, Claude, Codex, or custom engines
- **MCP Server Integration**: Connect to Model Context Protocol servers for tools
- **Safe Outputs**: Structured communication between AI and GitHub API
- **Strict Mode**: Security-first validation and sandboxing
- **Shared Components**: Reusable workflow building blocks
- **Repo Memory**: Persistent git-backed storage for agents
- **Sandboxed Execution**: All workflows run in the Agent Workflow Firewall (AWF) sandbox, enabling full `bash` and `edit` tools by default
## Important Notes
- For complete documentation, load `.github/aw/github-agentic-workflows.md` from the resolved guidance repository/ref.
- Use gh-aw MCP tools only when exposed and authorized; otherwise use available CLI, cached evidence or static source through the CLI/MCP reference.
- Workflows must be compiled to `.lock.yml` files before running in GitHub Actions
- **Bash tools are enabled by default** - Don't restrict bash commands unnecessarily since workflows are sandboxed by the AWF
- Follow security best practices: minimal permissions, explicit network access, no template injection
- **Network configuration**: Use ecosystem identifiers (`node`, `python`, `go`, etc.) or explicit FQDNs in `network.allowed`. Bare shorthands like `npm` or `pypi` are **not** valid. See `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/network.md` for the full list of valid ecosystem identifiers and domain patterns.
- **Single-file output**: When creating a workflow, produce exactly **one** workflow `.md` file. Do not create separate documentation files (architecture docs, runbooks, usage guides, etc.). If documentation is needed, add a brief `## Usage` section inside the workflow file itself.
- **Triggering runs**: Only where permitted and human-validated under `debug-agentic-workflow.md`, prefer `gh aw run <workflow-name>` over `gh workflow run <file>.lock.yml` for workflow resolution, input validation and run-tracking. Use the reviewed remote ref; explicit no-dispatch rules override user requests.
- **CLI commands reference**: For a complete guide on all `gh aw` commands and their MCP tool equivalents (for restricted environments), see `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/cli-commands.md`
+13 -38
View File
@@ -5,10 +5,10 @@
"version": "v9.0.0", "version": "v9.0.0",
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3" "sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
}, },
"github/gh-aw-actions/setup@v1.4.5": { "github/gh-aw-actions/setup@v1.4.1": {
"repo": "github/gh-aw-actions/setup", "repo": "github/gh-aw-actions/setup",
"version": "v1.4.5", "version": "v1.4.1",
"sha": "a83eaf07e756a15e65f669eb32d00787cf5a2569" "sha": "367d4dc4e89caf85422092845006e4a4a660d926"
} }
}, },
"containers": { "containers": {
@@ -52,11 +52,6 @@
"digest": "sha256:fef2443688fc8991d995b935963ef82cec704a867d5e53146f13e86819484059", "digest": "sha256:fef2443688fc8991d995b935963ef82cec704a867d5e53146f13e86819484059",
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.21@sha256:fef2443688fc8991d995b935963ef82cec704a867d5e53146f13e86819484059" "pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.21@sha256:fef2443688fc8991d995b935963ef82cec704a867d5e53146f13e86819484059"
}, },
"ghcr.io/github/gh-aw-firewall/agent:0.29.22": {
"image": "ghcr.io/github/gh-aw-firewall/agent:0.29.22",
"digest": "sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad",
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"
},
"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13": { "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13": {
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13", "image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13",
"digest": "sha256:61f12dcff38eb008b645d87a5541763452f409d9040eb243718764944167b1a2", "digest": "sha256:61f12dcff38eb008b645d87a5541763452f409d9040eb243718764944167b1a2",
@@ -97,11 +92,6 @@
"digest": "sha256:3293e5813a4e51bf1c5a1b22a762a25033d3ccc5f3582acb2572ad68045ce0e7", "digest": "sha256:3293e5813a4e51bf1c5a1b22a762a25033d3ccc5f3582acb2572ad68045ce0e7",
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.21@sha256:3293e5813a4e51bf1c5a1b22a762a25033d3ccc5f3582acb2572ad68045ce0e7" "pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.21@sha256:3293e5813a4e51bf1c5a1b22a762a25033d3ccc5f3582acb2572ad68045ce0e7"
}, },
"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22": {
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22",
"digest": "sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca",
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"
},
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11": { "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11": {
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11", "image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11",
"digest": "sha256:97782bc0d8ff7f80f19ae2fdc5e1668517aa732a6fa077e64b8d3919238496d2", "digest": "sha256:97782bc0d8ff7f80f19ae2fdc5e1668517aa732a6fa077e64b8d3919238496d2",
@@ -122,11 +112,6 @@
"digest": "sha256:facec98ac9b6ce41273f325b78475ef8d11c38842f62fc2ad823937203564cc3", "digest": "sha256:facec98ac9b6ce41273f325b78475ef8d11c38842f62fc2ad823937203564cc3",
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.21@sha256:facec98ac9b6ce41273f325b78475ef8d11c38842f62fc2ad823937203564cc3" "pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.21@sha256:facec98ac9b6ce41273f325b78475ef8d11c38842f62fc2ad823937203564cc3"
}, },
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22": {
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22",
"digest": "sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7",
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"
},
"ghcr.io/github/gh-aw-firewall/router:0.29.14": { "ghcr.io/github/gh-aw-firewall/router:0.29.14": {
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.14", "image": "ghcr.io/github/gh-aw-firewall/router:0.29.14",
"digest": "sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0", "digest": "sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0",
@@ -142,11 +127,6 @@
"digest": "sha256:681b2ca49f33e3954e5f3824767b3f2d4c747a60272ec303d0be27221531450a", "digest": "sha256:681b2ca49f33e3954e5f3824767b3f2d4c747a60272ec303d0be27221531450a",
"pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.21@sha256:681b2ca49f33e3954e5f3824767b3f2d4c747a60272ec303d0be27221531450a" "pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.21@sha256:681b2ca49f33e3954e5f3824767b3f2d4c747a60272ec303d0be27221531450a"
}, },
"ghcr.io/github/gh-aw-firewall/router:0.29.22": {
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.22",
"digest": "sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb",
"pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"
},
"ghcr.io/github/gh-aw-firewall/squid:0.28.13": { "ghcr.io/github/gh-aw-firewall/squid:0.28.13": {
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13", "image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13",
"digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56", "digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56",
@@ -187,25 +167,20 @@
"digest": "sha256:ccc189ace632f3f42fa2ee1e77feb67d438e0975c591520da3f473c132e6216d", "digest": "sha256:ccc189ace632f3f42fa2ee1e77feb67d438e0975c591520da3f473c132e6216d",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.21@sha256:ccc189ace632f3f42fa2ee1e77feb67d438e0975c591520da3f473c132e6216d" "pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.21@sha256:ccc189ace632f3f42fa2ee1e77feb67d438e0975c591520da3f473c132e6216d"
}, },
"ghcr.io/github/gh-aw-firewall/squid:0.29.22": { "ghcr.io/github/gh-aw-mcpg:v0.5.15": {
"image": "ghcr.io/github/gh-aw-firewall/squid:0.29.22", "image": "ghcr.io/github/gh-aw-mcpg:v0.5.15",
"digest": "sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882", "digest": "sha256:3f6567e6db31d820e43031fa17a745e5a056fd074604192a884ac12a443ff5c1",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882" "pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.5.15@sha256:3f6567e6db31d820e43031fa17a745e5a056fd074604192a884ac12a443ff5c1"
},
"ghcr.io/github/gh-aw-mcpg:v0.5.16": {
"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"
}, },
"ghcr.io/github/gh-aw-node": { "ghcr.io/github/gh-aw-node": {
"image": "ghcr.io/github/gh-aw-node", "image": "ghcr.io/github/gh-aw-node",
"digest": "sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f", "digest": "sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc",
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f" "pinned_image": "ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc"
}, },
"ghcr.io/github/github-mcp-server:v2.3.0": { "ghcr.io/github/github-mcp-server:v2.2.0": {
"image": "ghcr.io/github/github-mcp-server:v2.3.0", "image": "ghcr.io/github/github-mcp-server:v2.2.0",
"digest": "sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6", "digest": "sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174",
"pinned_image": "ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6" "pinned_image": "ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174"
} }
} }
} }
-5
View File
@@ -1,5 +0,0 @@
# GitHub Copilot Instructions
Read and follow [AGENTS.md](../AGENTS.md) before working in this repository.
@../AGENTS.md
@@ -100,7 +100,6 @@ Use the task routes above first. This inventory is not required startup context.
- `.github/aw/charts.md` - `.github/aw/charts.md`
- `.github/aw/cli-commands.md` - `.github/aw/cli-commands.md`
- `.github/aw/compat.md` - `.github/aw/compat.md`
- `.github/aw/connectors-authoring.md`
- `.github/aw/connectors.md` - `.github/aw/connectors.md`
- `.github/aw/context.md` - `.github/aw/context.md`
- `.github/aw/create-agentic-workflow-design.md` - `.github/aw/create-agentic-workflow-design.md`
@@ -149,7 +148,6 @@ Use the task routes above first. This inventory is not required startup context.
- `.github/aw/maintainer.md` - `.github/aw/maintainer.md`
- `.github/aw/mcp-clis.md` - `.github/aw/mcp-clis.md`
- `.github/aw/memory-stateful-patterns.md` - `.github/aw/memory-stateful-patterns.md`
- `.github/aw/memory-wiki-comment.md`
- `.github/aw/memory.md` - `.github/aw/memory.md`
- `.github/aw/messages.md` - `.github/aw/messages.md`
- `.github/aw/multi-agent-research.md` - `.github/aw/multi-agent-research.md`
+13 -13
View File
@@ -51,7 +51,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
- name: Install dependencies - name: Install dependencies
run: pnpm install --frozen-lockfile run: pnpm install --frozen-lockfile
@@ -182,7 +182,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check - name: Pnpm install and check
@@ -262,9 +262,17 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check
run: |
pnpm i
pnpm run prebuild ${{ matrix.target }}
- name: Release ${{ env.TAG_CHANNEL }} Version
run: pnpm release-version autobuild-latest
- name: 'Setup for linux' - name: 'Setup for linux'
run: |- run: |-
sudo ls -lR /etc/apt/ sudo ls -lR /etc/apt/
@@ -309,14 +317,6 @@ jobs:
gcc-arm-linux-gnueabihf \ gcc-arm-linux-gnueabihf \
g++-arm-linux-gnueabihf g++-arm-linux-gnueabihf
- name: Pnpm install and check
run: |
pnpm i
pnpm run prebuild ${{ matrix.target }}
- name: Release ${{ env.TAG_CHANNEL }} Version
run: pnpm release-version autobuild-latest
- name: Tauri Build for Linux - name: Tauri Build for Linux
run: | run: |
export PKG_CONFIG_ALLOW_CROSS=1 export PKG_CONFIG_ALLOW_CROSS=1
@@ -395,7 +395,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check - name: Pnpm install and check
@@ -479,7 +479,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
- uses: pnpm/action-setup@v6.1.1 - uses: pnpm/action-setup@v6.1.1
name: Install pnpm name: Install pnpm
+1 -1
View File
@@ -63,7 +63,7 @@ jobs:
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
cache: 'pnpm' cache: 'pnpm'
- run: pnpm install --frozen-lockfile - run: pnpm install --frozen-lockfile
+3 -3
View File
@@ -31,9 +31,9 @@ jobs:
with: with:
persist-credentials: false persist-credentials: false
- name: Install gh-aw extension - name: Install gh-aw extension
uses: github/gh-aw-actions/setup-cli@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5 uses: github/gh-aw-actions/setup-cli@367d4dc4e89caf85422092845006e4a4a660d926 # v1.4.1
with: with:
version: v1.4.5 version: v1.4.1
- name: Install Rust Stable - name: Install Rust Stable
uses: dtolnay/rust-toolchain@stable uses: dtolnay/rust-toolchain@stable
with: with:
@@ -49,7 +49,7 @@ jobs:
- name: Install Node.js - name: Install Node.js
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
cache: 'pnpm' cache: 'pnpm'
- name: Install frontend dependencies - name: Install frontend dependencies
env: env:
+1 -1
View File
@@ -43,7 +43,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
+9 -9
View File
@@ -104,17 +104,9 @@ jobs:
if: github.event.inputs[matrix.input] == 'true' if: github.event.inputs[matrix.input] == 'true'
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
cache: 'pnpm' cache: 'pnpm'
- name: Add Rust Target
if: github.event.inputs[matrix.input] == 'true'
run: |
# Ensure cross target is installed for the pinned toolchain; fallback without explicit toolchain if needed
rustup target add ${{ matrix.target }} --toolchain 1.100.1 || rustup target add ${{ matrix.target }}
rustup target list --installed
echo "Rust target ${{ matrix.target }} installed."
- name: Pnpm install and check - name: Pnpm install and check
if: github.event.inputs[matrix.input] == 'true' if: github.event.inputs[matrix.input] == 'true'
run: | run: |
@@ -125,6 +117,14 @@ jobs:
if: github.event.inputs[matrix.input] == 'true' if: github.event.inputs[matrix.input] == 'true'
run: pnpm release-version ${{ env.TAG_NAME }} run: pnpm release-version ${{ env.TAG_NAME }}
- name: Add Rust Target
if: github.event.inputs[matrix.input] == 'true'
run: |
# Ensure cross target is installed for the pinned toolchain; fallback without explicit toolchain if needed
rustup target add ${{ matrix.target }} --toolchain 1.100.1 || rustup target add ${{ matrix.target }}
rustup target list --installed
echo "Rust target ${{ matrix.target }} installed."
- name: Tauri build - name: Tauri build
if: github.event.inputs[matrix.input] == 'true' if: github.event.inputs[matrix.input] == 'true'
uses: tauri-apps/tauri-action@v1 uses: tauri-apps/tauri-action@v1
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
cache: 'pnpm' cache: 'pnpm'
- run: pnpm install --frozen-lockfile - run: pnpm install --frozen-lockfile
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -61,7 +61,7 @@ jobs:
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
if: github.event.action != 'closed' if: github.event.action != 'closed'
+13 -13
View File
@@ -46,7 +46,7 @@ jobs:
fetch-depth: 0 fetch-depth: 0
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
- name: Validate source and publish the approved snapshot - name: Validate source and publish the approved snapshot
id: source id: source
env: env:
@@ -231,7 +231,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check - name: Pnpm install and check
@@ -330,9 +330,14 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check
run: |
pnpm i
pnpm run prebuild ${{ matrix.target }}
- name: 'Setup for linux' - name: 'Setup for linux'
run: |- run: |-
sudo ls -lR /etc/apt/ sudo ls -lR /etc/apt/
@@ -377,11 +382,6 @@ jobs:
gcc-arm-linux-gnueabihf \ gcc-arm-linux-gnueabihf \
g++-arm-linux-gnueabihf g++-arm-linux-gnueabihf
- name: Pnpm install and check
run: |
pnpm i
pnpm run prebuild ${{ matrix.target }}
- name: Build for Linux - name: Build for Linux
run: | run: |
export PKG_CONFIG_ALLOW_CROSS=1 export PKG_CONFIG_ALLOW_CROSS=1
@@ -461,7 +461,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check - name: Pnpm install and check
@@ -542,7 +542,7 @@ jobs:
fetch-depth: 0 fetch-depth: 0
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
with: with:
run_install: false run_install: false
@@ -565,7 +565,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
@@ -593,7 +593,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
@@ -661,7 +661,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -28,7 +28,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
- name: Install pnpm - name: Install pnpm
uses: pnpm/action-setup@v6 uses: pnpm/action-setup@v6
+1 -1
View File
@@ -31,7 +31,7 @@ jobs:
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
- name: Sync Mihomo version - name: Sync Mihomo version
id: sync id: sync
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
+2 -2
View File
@@ -15,7 +15,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
@@ -39,7 +39,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.14.0' node-version: '26.13.1'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
+2 -2
View File
@@ -1,3 +1,3 @@
nodejs 26.14.0 nodejs 26.13.1
pnpm 12.25.1 pnpm 12.23.0
rust 1.100.1 rust 1.100.1
-4
View File
@@ -60,10 +60,6 @@ the ownership evidence the AI-slop review evaluates (see
- For development and bug fixes, follow the - For development and bug fixes, follow the
[development workflow](CONTRIBUTING.md#development-workflow). [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). - For code review and verification of review fixes, follow [REVIEW.md](REVIEW.md).
Review is read-only unless changes are authorized; findings do not expand Review is read-only unless changes are authorized; findings do not expand
that authorization to unrelated fixes, commits, pushes, or GitHub updates. that authorization to unrelated fixes, commits, pushes, or GitHub updates.
Generated
+649 -875
View File
File diff suppressed because it is too large Load Diff
+6 -29
View File
@@ -9,13 +9,6 @@ members = [
"crates/tauri-plugin-clash-verge-sysinfo", "crates/tauri-plugin-clash-verge-sysinfo",
"crates/clash-verge-i18n", "crates/clash-verge-i18n",
"crates/clash-verge-limiter", "crates/clash-verge-limiter",
"crates/clash-verge-subscription",
"crates/clash-verge-runtime-bundle",
"crates/clash-verge-config-render",
"crates/clash-verge-profile-script",
"crates/clash-verge-proxy-view",
"crates/clash-verge-profile",
"crates/clash-verge-backup-archive",
] ]
resolver = "2" resolver = "2"
@@ -57,11 +50,8 @@ split-debuginfo = "unpacked"
[patch.crates-io] [patch.crates-io]
# Backport Windows menu command ID recycling on the muda 0.20 compatibility branch. # Backport Windows menu command ID recycling on the muda 0.20 compatibility branch.
muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdfa785f20f3c7ece8468e2" } muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdfa785f20f3c7ece8468e2" }
tauri-plugin-wdio-webdriver = { git = "https://github.com/Tunglies/desktop-mobile.git", rev = "2745082c7f487c5e0c9568000b5a7ac24234d6e4" }
[workspace.dependencies] [workspace.dependencies]
clash-verge-config-render = { path = "crates/clash-verge-config-render" }
clash-verge-profile-script = { path = "crates/clash-verge-profile-script" }
clash-verge-draft = { path = "crates/clash-verge-draft" } clash-verge-draft = { path = "crates/clash-verge-draft" }
clash-verge-task = { path = "crates/clash-verge-task" } clash-verge-task = { path = "crates/clash-verge-task" }
clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" } clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" }
@@ -69,26 +59,16 @@ clash-verge-logging = { path = "crates/clash-verge-logging" }
clash-verge-signal = { path = "crates/clash-verge-signal" } clash-verge-signal = { path = "crates/clash-verge-signal" }
clash-verge-i18n = { path = "crates/clash-verge-i18n" } clash-verge-i18n = { path = "crates/clash-verge-i18n" }
clash-verge-limiter = { path = "crates/clash-verge-limiter" } clash-verge-limiter = { path = "crates/clash-verge-limiter" }
clash-verge-subscription = { path = "crates/clash-verge-subscription" }
clash-verge-runtime-bundle = { path = "crates/clash-verge-runtime-bundle" }
clash-verge-proxy-view = { path = "crates/clash-verge-proxy-view" }
clash-verge-profile = { path = "crates/clash-verge-profile" }
clash-verge-backup-archive = { path = "crates/clash-verge-backup-archive" }
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", rev = "fd00f5af2363517e67de57a7ead67737175ac376", version = "2.8.3", default-features = false }
tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" } tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" }
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" } tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
tracing = "0.1.44" tracing = "0.1.44"
tauri = { version = "2.13.0" } tauri = { version = "=3.0.0-alpha.6" }
tauri-plugin-clipboard-manager = "2.5.0" tauri-runtime-wry = "=3.0.0-alpha.6"
tauri-plugin-clipboard-manager = "=3.0.0-alpha.3"
parking_lot = "0.13.0" parking_lot = "0.13.0"
anyhow = "1.0.105" anyhow = "1.0.105"
thiserror = "2.0.20"
zip = "9.9.0"
boa_engine = "0.22.0"
futures = "0.3.34" futures = "0.3.34"
loom = "0.7.3"
proptest = "1.12.0"
chrono = "0.4.45" chrono = "0.4.45"
criterion = { version = "0.8.2", features = ["async_tokio"] } criterion = { version = "0.8.2", features = ["async_tokio"] }
tokio = { version = "1.54.1", features = [ tokio = { version = "1.54.1", features = [
@@ -112,13 +92,11 @@ serde = { version = "1.0.229" }
tristr = { git = "https://github.com/Tunglies/tristr", rev = "d849e5cff47a570849c2e1bada0a2b6481cf3378", default-features = false, features = ["serde", "specta"] } tristr = { git = "https://github.com/Tunglies/tristr", rev = "d849e5cff47a570849c2e1bada0a2b6481cf3378", default-features = false, features = ["serde", "specta"] }
serde_json = { version = "1.0.154" } serde_json = { version = "1.0.154" }
serde_yaml_ng = { version = "0.10.0" } serde_yaml_ng = { version = "0.10.0" }
sha2 = "0.11.2"
specta = "=2.0.0-rc.26"
socket2 = "0.6.5" socket2 = "0.6.5"
# *** For Windows platform only *** # *** For Windows platform only ***
deelevate = "0.2.0" deelevate = "0.2.0"
windows-sys = { version = "0.101.0", features = [ windows-sys = { version = "0.61.2", features = [
"Win32_Foundation", "Win32_Foundation",
"Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_IpHelper",
"Win32_Networking_WinSock", "Win32_Networking_WinSock",
@@ -131,9 +109,6 @@ windows-sys = { version = "0.101.0", features = [
] } ] }
# ********************************* # *********************************
[workspace.lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(loom)'] }
[workspace.lints.clippy] [workspace.lints.clippy]
# fallible_impl_from = "deny" // 过于激进,暂时不开启 # fallible_impl_from = "deny" // 过于激进,暂时不开启
# implicit_clone = "deny" // 可能会造成额外开销,暂时不开启 # implicit_clone = "deny" // 可能会造成额外开销,暂时不开启
@@ -150,6 +125,7 @@ copy_iterator = "deny"
correctness = { level = "deny", priority = -1 } correctness = { level = "deny", priority = -1 }
dbg_macro = "warn" dbg_macro = "warn"
equatable_if_let = "deny" equatable_if_let = "deny"
expect_used = "warn"
expl_impl_clone_on_copy = "deny" expl_impl_clone_on_copy = "deny"
future_not_send = "deny" future_not_send = "deny"
iter_on_empty_collections = "deny" iter_on_empty_collections = "deny"
@@ -188,6 +164,7 @@ unnecessary_self_imports = "deny"
unnecessary_wraps = "deny" unnecessary_wraps = "deny"
unused_async = "deny" unused_async = "deny"
unused_trait_names = "deny" unused_trait_names = "deny"
unwrap_used = "warn"
use_self = "deny" use_self = "deny"
useless_let_if_seq = "deny" useless_let_if_seq = "deny"
wildcard_imports = "deny" wildcard_imports = "deny"
-4
View File
@@ -23,7 +23,6 @@
GitHub, so they never reach users. --> GitHub, so they never reach users. -->
## v2.6.0 ## v2.6.0
- 使用 2.6.x 服务模式时请安装随附的服务,2.5.x 客户端无法使用新版服务
- **Mihomo 内核升级至 v1.19.34** - **Mihomo 内核升级至 v1.19.34**
<details> <details>
@@ -34,7 +33,6 @@
- 修复检测更新后又发布新版时,应用内更新失败 - 修复检测更新后又发布新版时,应用内更新失败
- 修复关闭「自动检查更新」后,手动检查更新时弹窗空白 - 修复关闭「自动检查更新」后,手动检查更新时弹窗空白
- 修复订阅响应过大导致内存占用过高,限制单次下载为 4 MiB - 修复订阅响应过大导致内存占用过高,限制单次下载为 4 MiB
- 修复服务端文件名无效时导入的订阅名称为空
- 修复全局模式默认停在 `DIRECT` 或 `REJECT` 导致流量未经代理,现自动切换到第一个策略组 - 修复全局模式默认停在 `DIRECT` 或 `REJECT` 导致流量未经代理,现自动切换到第一个策略组
- 修复订阅中未加引号的 REALITY `short-id`(如 `1234e123`)被误读为数字,导致订阅无法启用 - 修复订阅中未加引号的 REALITY `short-id`(如 `1234e123`)被误读为数字,导致订阅无法启用
- 修复订阅中唯一的代理组名为 `GLOBAL` 或没有代理组时,规则模式下代理页面显示「未获取到代理信息」 - 修复订阅中唯一的代理组名为 `GLOBAL` 或没有代理组时,规则模式下代理页面显示「未获取到代理信息」
@@ -50,7 +48,6 @@
**🖥️ Windows** **🖥️ Windows**
- 修复 Windows 服务启动失败后自动切换内核,现显示原因并等待用户选择
- 修复 Windows 普通用户因权限不足无法开启「开机自启」 - 修复 Windows 普通用户因权限不足无法开启「开机自启」
**🍎 macOS** **🍎 macOS**
@@ -62,7 +59,6 @@
**🐧 Linux** **🐧 Linux**
- 修复 Linux OpenRC 环境下服务安装失败 - 修复 Linux OpenRC 环境下服务安装失败
- 修复 Linux 左键点击托盘图标时无法唤回主窗口
</details> </details>
-5
View File
@@ -1,5 +0,0 @@
# 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
+9 -46
View File
@@ -2,34 +2,19 @@
## Choose the boundary ## 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 - 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 creating a crate, identify its owner, what callers supply, and what can be
verified through the crate API. Extract a crate when it provides a useful verified through the crate API. Keep a module when the proposed boundary only
dependency, portability, testing, or ownership boundary. Keep a module when relocates implementation or introduces a pass-through API.
the proposed boundary only relocates implementation or introduces a - Keep the dependency direction from the app to the crate. Resolve app paths,
pass-through API. read product settings, start app-owned tasks, and publish UI events in the app.
- Keep capability crates independent by default. Compose peer capabilities in Pass the values, resources, or callbacks the crate needs. For example,
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,
[logging](clash-verge-logging/src/lib.rs) owns its pipeline and writers while the [logging](clash-verge-logging/src/lib.rs) owns its pipeline and writers while the
app supplies directories and limits through `LoggerConfig`. app supplies directories and limits through `LoggerConfig`.
- Run framework-independent tests without starting the desktop app. A platform - Keep framework and platform dependencies scoped to the capability that needs
adapter can own runtime startup when its resource lifetime requires it, as them. Runtime-independent logic should be runnable without the desktop app.
[signal](clash-verge-signal/src/lib.rs) does for Linux shutdown. 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 ## Design the API
@@ -46,14 +31,6 @@
workspace lints. Reuse workspace dependencies where available and declare workspace lints. Reuse workspace dependencies where available and declare
only the features the crate needs. 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 ## Own background work
- Give ordered start, replacement, and cleanup to one task owner. Reuse - Give ordered start, replacement, and cleanup to one task owner. Reuse
@@ -66,20 +43,6 @@
transaction boundaries and keep the reply path free of locks held by the 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 waiting caller. Cancel only at safe boundaries and own issued effects through
completion or explicit reconciliation. 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 Verify the extracted contract through its public API when practical. Use
`cargo test -p <crate>` for focused tests and keep native behavior checks at the `cargo test -p <crate>` for focused tests and keep native behavior checks at the
@@ -1,11 +0,0 @@
[package]
name = "clash-verge-backup-archive"
version = "0.1.0"
edition = "2024"
[dependencies]
thiserror = { workspace = true }
zip = { workspace = true }
[lints]
workspace = true
@@ -1,7 +0,0 @@
#[derive(Debug, thiserror::Error)]
pub enum ArchiveError {
#[error(transparent)]
Zip(#[from] zip::result::ZipError),
#[error(transparent)]
Io(#[from] std::io::Error),
}
@@ -1,65 +0,0 @@
mod error;
pub use error::ArchiveError;
use std::io::{Seek, Write};
use zip::{CompressionMethod, ZipWriter, write::SimpleFileOptions};
pub struct BackupWriter<W: Write + Seek> {
zip: ZipWriter<W>,
options: SimpleFileOptions,
}
impl<W: Write + Seek> BackupWriter<W> {
pub fn new(target: W) -> Result<Self, ArchiveError> {
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<impl Write + use<'a, W>, ArchiveError> {
self.start_file(&format!("profiles/{filename}"))
}
pub fn start_file<'a>(&'a mut self, name: &str) -> Result<impl Write + use<'a, W>, ArchiveError> {
self.zip.start_file_with_options(self.options.name(name.as_bytes()))?;
Ok(&mut self.zip)
}
pub fn finish(self) -> Result<W, ArchiveError> {
Ok(self.zip.finish()?)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{Cursor, Read as _};
use zip::ZipArchive;
#[test]
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)?;
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);
Ok(())
}
}
@@ -1,18 +0,0 @@
[package]
name = "clash-verge-config-render"
version = "0.1.0"
edition = "2024"
[dependencies]
clash-verge-logging = { workspace = true }
log = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
serde_yaml_ng = { workspace = true }
tristr = { workspace = true }
[dev-dependencies]
tokio = { workspace = true }
[lints]
workspace = true
File diff suppressed because it is too large Load Diff
@@ -1,81 +0,0 @@
use super::{ResultLog, ScriptOutcome, field::use_lowercase};
use serde_yaml_ng::Mapping;
use tristr::alias::String;
type ScriptResult = (Mapping, Vec<String>, ResultLog);
/// Never fails: exceptions are logged and the input config is returned unchanged.
pub(super) async fn use_script<Fut: Future<Output = ScriptOutcome> + Send>(
script: String,
config: Mapping,
name: String,
execute: impl FnOnce(String, serde_json::Value, String) -> Fut + Send,
) -> ScriptResult {
// The template is identity-plus-lowercasing; skip the Boa round-trip.
if script == super::ITEM_SCRIPT {
return (use_lowercase(config), vec![], vec![]);
}
let json = match serde_json::to_value(&config) {
Ok(mut json) => {
if let Some(map) = json.as_object_mut() {
let mut lowered = serde_json::Map::with_capacity(map.len());
for (key, value) in std::mem::take(map) {
let mut key = key;
key.make_ascii_lowercase();
lowered.insert(key, value);
}
*map = lowered;
}
json
}
Err(err) => return (config, vec![], vec![("exception".into(), err.to_string().into())]),
};
let (outcome, mut logs) = execute(script, json, name).await;
match outcome {
Ok(result) => {
let result = use_lowercase(result);
// Compared against the config as handed in, not the lowercased copy the script saw.
let changed_keys = result
.iter()
.filter(|(key, value)| config.get(key) != Some(value))
.filter_map(|(key, _)| {
let mut key: String = key.as_str()?.into();
key.make_ascii_lowercase();
Some(key)
})
.collect();
(result, changed_keys, logs)
}
Err(reason) => {
logs.push(("exception".into(), reason.into()));
(config, vec![], logs)
}
}
}
#[cfg(test)]
mod tests {
use std::future::ready;
use super::{Mapping, use_script};
#[tokio::test]
async fn default_template_skips_the_executor() {
let mut called = false;
let mut config = Mapping::new();
config.insert("MiXeD".into(), true.into());
let (config, changed_keys, logs) =
use_script(crate::ITEM_SCRIPT.into(), config, "profile".into(), |_, _, _| {
called = true;
ready((Ok(Mapping::new()), vec![]))
})
.await;
assert!(!called);
assert_eq!(config["mixed"], serde_yaml_ng::Value::Bool(true));
assert!(changed_keys.is_empty());
assert!(logs.is_empty());
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ harness = false
[dependencies] [dependencies]
parking_lot = { workspace = true } parking_lot = { workspace = true }
thiserror = { workspace = true } anyhow = { workspace = true }
tokio = { workspace = true } tokio = { workspace = true }
[dev-dependencies] [dev-dependencies]
+3 -3
View File
@@ -2,7 +2,7 @@ use criterion::{Criterion, criterion_group, criterion_main};
use std::hint::black_box; use std::hint::black_box;
use tokio::runtime::Runtime; use tokio::runtime::Runtime;
use clash_verge_draft::{Draft, DraftConflict}; use clash_verge_draft::Draft;
#[derive(Default, Clone, Debug)] #[derive(Default, Clone, Debug)]
struct IVerge { struct IVerge {
@@ -99,8 +99,8 @@ pub fn bench_draft(c: &mut Criterion) {
group.bench_function("with_data_modify_async", |b| { group.bench_function("with_data_modify_async", |b| {
b.to_async(&rt).iter(|| async { b.to_async(&rt).iter(|| async {
let draft = black_box(make_draft()); let draft = black_box(make_draft());
let _: Result<(), DraftConflict> = draft let _: Result<(), anyhow::Error> = draft
.with_data_modify(|mut box_data| async move { .with_data_modify::<_, _, _>(|mut box_data| async move {
box_data.enable_auto_launch = Some(!box_data.enable_auto_launch.unwrap_or(false)); box_data.enable_auto_launch = Some(!box_data.enable_auto_launch.unwrap_or(false));
Ok((box_data, ())) Ok((box_data, ()))
}) })
-12
View File
@@ -1,12 +0,0 @@
/// 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,
}
+25 -12
View File
@@ -1,7 +1,3 @@
mod error;
pub use error::{DraftBusy, DraftConflict};
use parking_lot::Mutex; use parking_lot::Mutex;
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{ use std::sync::atomic::{
@@ -95,16 +91,14 @@ impl<T: Clone> Draft<T> {
} }
/// Optimistically replaces committed data after an asynchronous edit. /// Optimistically replaces committed data after an asynchronous edit.
/// The caller's error type carries both edit failures and publication conflicts.
#[inline] #[inline]
pub async fn with_data_modify<F, Fut, R, E>(&self, f: F) -> Result<R, E> pub async fn with_data_modify<F, Fut, R>(&self, f: F) -> Result<R, anyhow::Error>
where where
T: Send + Sync + 'static, T: Send + Sync + 'static,
F: FnOnce(T) -> Fut + Send, F: FnOnce(T) -> Fut + Send,
Fut: std::future::Future<Output = Result<(T, R), E>> + Send, Fut: std::future::Future<Output = Result<(T, R), anyhow::Error>> + Send,
E: From<DraftConflict>,
{ {
let permit = self.acquire_data_modify_permit().await; let _permit = self.acquire_data_modify_permit().await;
let (local, original_arc) = { let (local, original_arc) = {
let guard = self.inner.data.lock(); let guard = self.inner.data.lock();
let arc = Arc::clone(&guard.0); let arc = Arc::clone(&guard.0);
@@ -114,9 +108,9 @@ impl<T: Clone> Draft<T> {
let (new_local, res) = f(local).await?; let (new_local, res) = f(local).await?;
let mut guard = self.inner.data.lock(); let mut guard = self.inner.data.lock();
if !Arc::ptr_eq(&guard.0, &original_arc) { if !Arc::ptr_eq(&guard.0, &original_arc) {
drop(guard); return Err(anyhow::anyhow!(
drop(permit); "Optimistic lock failed: Committed data has changed during async operation"
return Err(DraftConflict.into()); ));
} }
guard.0 = Arc::new(Box::new(new_local)); guard.0 = Arc::new(Box::new(new_local));
drop(guard); drop(guard);
@@ -197,6 +191,25 @@ impl<T: Clone + Send + Sync> DraftLayer for Draft<T> {
} }
} }
/// 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. /// 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. /// A layer has one draft slot, so concurrent transactions cannot be isolated and are rejected.
+13 -71
View File
@@ -1,14 +1,7 @@
use std::{ use std::sync::Arc;
pin::pin,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
task::{Context, Poll, Wake, Waker},
};
use clash_verge_draft::{Draft, DraftBusy, DraftConflict, DraftTransaction}; use clash_verge_draft::{Draft, DraftTransaction};
use tokio::sync::{Notify, oneshot}; use tokio::sync::Notify;
#[derive(Clone, Debug, Default, PartialEq)] #[derive(Clone, Debug, Default, PartialEq)]
struct Config { struct Config {
@@ -35,19 +28,14 @@ fn edits_can_be_committed_or_discarded() {
} }
#[tokio::test] #[tokio::test]
async fn async_updates_are_serialized() -> Result<(), Box<dyn std::error::Error>> { async fn async_updates_are_serialized() -> anyhow::Result<()> {
let draft = Arc::new(Draft::new(0_u8)); let draft = Arc::new(Draft::new(0_u8));
let mut updates = Vec::new(); let mut updates = Vec::new();
for _ in 0..16 { for _ in 0..16 {
let draft = Arc::clone(&draft); let draft = Arc::clone(&draft);
updates.push(tokio::spawn(async move { updates.push(tokio::spawn(async move {
draft draft.with_data_modify(|value| async move { Ok((value + 1, ())) }).await
.with_data_modify(|value| async move {
tokio::task::yield_now().await;
Ok::<_, DraftConflict>((value + 1, ()))
})
.await
})); }));
} }
for update in updates { for update in updates {
@@ -59,7 +47,7 @@ async fn async_updates_are_serialized() -> Result<(), Box<dyn std::error::Error>
} }
#[tokio::test] #[tokio::test]
async fn async_update_rejects_a_changed_committed_value() -> Result<(), Box<dyn std::error::Error>> { async fn async_update_rejects_a_changed_committed_value() -> anyhow::Result<()> {
let draft = Arc::new(Draft::new(Config::default())); let draft = Arc::new(Draft::new(Config::default()));
let started = Arc::new(Notify::new()); let started = Arc::new(Notify::new());
let finish = Arc::new(Notify::new()); let finish = Arc::new(Notify::new());
@@ -73,7 +61,7 @@ async fn async_update_rejects_a_changed_committed_value() -> Result<(), Box<dyn
started.notify_one(); started.notify_one();
finish.notified().await; finish.notified().await;
config.enabled = true; config.enabled = true;
Ok::<_, DraftConflict>((config, ())) Ok((config, ()))
}) })
.await .await
}) })
@@ -84,55 +72,14 @@ async fn async_update_rejects_a_changed_committed_value() -> Result<(), Box<dyn
draft.apply(); draft.apply();
finish.notify_one(); finish.notify_one();
assert_eq!(update.await?, Err(DraftConflict)); assert!(update.await?.is_err());
assert!(!draft.data_arc().enabled); assert!(!draft.data_arc().enabled);
assert_eq!(draft.data_arc().port, 7897); assert_eq!(draft.data_arc().port, 7897);
Ok(()) Ok(())
} }
#[test] #[test]
fn parked_async_update_is_woken_after_optimistic_conflict() { fn transaction_commits_every_layer() -> anyhow::Result<()> {
#[derive(Default)]
struct WakeFlag(AtomicBool);
impl Wake for WakeFlag {
fn wake(self: Arc<Self>) {
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.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());
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::<_, 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());
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() -> Result<(), DraftBusy> {
let first = Draft::new(1_u8); let first = Draft::new(1_u8);
let second = Draft::new(String::from("a")); let second = Draft::new(String::from("a"));
let transaction = DraftTransaction::begin(vec![&first, &second])?; let transaction = DraftTransaction::begin(vec![&first, &second])?;
@@ -147,7 +94,7 @@ fn transaction_commits_every_layer() -> Result<(), DraftBusy> {
} }
#[test] #[test]
fn dropped_transaction_rolls_every_layer_back() -> Result<(), DraftBusy> { fn dropped_transaction_rolls_every_layer_back() -> anyhow::Result<()> {
let first = Draft::new(1_u8); let first = Draft::new(1_u8);
let second = Draft::new(String::from("a")); let second = Draft::new(String::from("a"));
@@ -163,17 +110,12 @@ fn dropped_transaction_rolls_every_layer_back() -> Result<(), DraftBusy> {
} }
#[test] #[test]
fn transaction_claims_are_exclusive_and_release_partial_claims() -> Result<(), DraftBusy> { fn transaction_claims_are_exclusive_and_release_partial_claims() -> anyhow::Result<()> {
let first = Draft::new(1_u8); let first = Draft::new(1_u8);
let second = Draft::new(2_u16); let second = Draft::new(2_u8);
let held = DraftTransaction::begin(vec![&second])?; let held = DraftTransaction::begin(vec![&second])?;
let busy = DraftTransaction::begin(vec![&first, &second]) assert!(DraftTransaction::begin(vec![&first, &second]).is_err());
.err()
.expect("transaction claimed an already-held layer");
let layer = std::any::type_name::<u16>();
assert_eq!(busy.layer, layer);
assert!(busy.to_string().contains(layer));
let available = DraftTransaction::begin(vec![&first])?; let available = DraftTransaction::begin(vec![&first])?;
drop(available); drop(available);
+5 -8
View File
@@ -23,20 +23,17 @@ fn resolve_supported_language(language: &str) -> Option<Cow<'static, str>> {
return None; return None;
} }
let normalized = language.to_lowercase().replace('_', "-"); let normalized = language.to_lowercase().replace('_', "-");
let mut prefix = normalized.as_str(); let segments: Vec<&str> = normalized.split('-').collect();
loop { for i in (1..=segments.len()).rev() {
if let Some(alias) = locale_alias(prefix) let prefix = segments[..i].join("-");
if let Some(alias) = locale_alias(&prefix)
&& let Some(found) = SUPPORTED_LOCALES.iter().find(|l| l.eq_ignore_ascii_case(alias)) && let Some(found) = SUPPORTED_LOCALES.iter().find(|l| l.eq_ignore_ascii_case(alias))
{ {
return Some(found.clone()); 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()); return Some(found.clone());
} }
let Some((shorter, _)) = prefix.rsplit_once('-') else {
break;
};
prefix = shorter;
} }
None None
} }
-6
View File
@@ -5,11 +5,5 @@ edition = "2024"
[dependencies] [dependencies]
[dev-dependencies]
proptest = { workspace = true }
[target.'cfg(loom)'.dependencies]
loom = { workspace = true }
[lints] [lints]
workspace = true workspace = true
+4 -41
View File
@@ -1,12 +1,5 @@
#[cfg(loom)]
use loom::sync::Arc;
#[cfg(loom)]
use loom::sync::atomic::AtomicU64;
#[cfg(not(loom))]
use std::sync::Arc; use std::sync::Arc;
#[cfg(not(loom))] use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::{Duration, SystemTime, UNIX_EPOCH}; use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub type SystemLimiter = Limiter<SystemClock>; pub type SystemLimiter = Limiter<SystemClock>;
@@ -45,7 +38,6 @@ pub struct Limiter<C: Clock = SystemClock> {
} }
impl<C: Clock> Limiter<C> { impl<C: Clock> Limiter<C> {
#[cfg(not(loom))]
pub const fn new(period: Duration, clock: C) -> Self { pub const fn new(period: Duration, clock: C) -> Self {
Self { Self {
last_run_ms: AtomicU64::new(0), last_run_ms: AtomicU64::new(0),
@@ -54,21 +46,11 @@ impl<C: Clock> Limiter<C> {
} }
} }
#[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,
}
}
pub fn check(&self) -> bool { 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(); let now = self.clock.now_ms();
let last = self.last_run_ms.load(Ordering::Relaxed);
if now >= last && now - last < self.period_ms { if now < last + self.period_ms && now >= last {
return false; return false;
} }
@@ -92,22 +74,6 @@ 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] #[test]
fn enforces_the_period_boundary() { fn enforces_the_period_boundary() {
let clock = MockClock(AtomicU64::new(1_000)); let clock = MockClock(AtomicU64::new(1_000));
@@ -134,10 +100,7 @@ mod tests {
} }
let admitted = handles let admitted = handles
.into_iter() .into_iter()
.map(|handle| match handle.join() { .map(|handle| handle.join().unwrap_or(false))
Ok(admitted) => admitted,
Err(panic) => std::panic::resume_unwind(panic),
})
.filter(|passed| *passed) .filter(|passed| *passed)
.count(); .count();
-225
View File
@@ -1,225 +0,0 @@
#![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<Arc<MockClock>>;
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<MockClock>, Arc<TestLimiter>) {
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<C: Clock + 'static>(limiter: &Arc<Limiter<C>>) -> 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}");
});
}
@@ -1,7 +0,0 @@
# 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
@@ -1,211 +0,0 @@
#![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<u64>,
next: AtomicUsize,
}
impl SequenceClock {
const fn new(values: Vec<u64>) -> 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<u64> {
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<bool> = 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<bool> = (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());
}
+1 -1
View File
@@ -6,7 +6,7 @@ edition = "2024"
[dependencies] [dependencies]
log = { workspace = true } log = { workspace = true }
parking_lot = { workspace = true } parking_lot = { workspace = true }
thiserror = { workspace = true } anyhow = { workspace = true }
flexi_logger = { workspace = true } flexi_logger = { workspace = true }
tracing-estuary = { workspace = true } tracing-estuary = { workspace = true }
-11
View File
@@ -1,11 +0,0 @@
#[derive(Debug, thiserror::Error)]
pub enum LoggerError {
#[error(transparent)]
Pipeline(Box<dyn std::error::Error + Send + Sync>),
#[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),
}
+12 -18
View File
@@ -1,7 +1,3 @@
mod error;
pub use error::LoggerError;
use std::{ use std::{
collections::VecDeque, collections::VecDeque,
fmt, fmt,
@@ -14,6 +10,7 @@ use std::{
time::Duration, time::Duration,
}; };
use anyhow::{Result, bail};
use flexi_logger::{ use flexi_logger::{
Cleanup, Criterion, DeferredNow, FileSpec, Naming, Cleanup, Criterion, DeferredNow, FileSpec, Naming,
writers::{FileLogWriter, FileLogWriterBuilder, LogWriter as _}, writers::{FileLogWriter, FileLogWriterBuilder, LogWriter as _},
@@ -180,7 +177,7 @@ impl Logger {
/// Installs the global tracing pipeline. `RUST_LOG` (parsed as a bare /// Installs the global tracing pipeline. `RUST_LOG` (parsed as a bare
/// level) overrides the configured level. /// level) overrides the configured level.
pub fn init(&self, cfg: &LoggerConfig) -> Result<(), LoggerError> { pub fn init(&self, cfg: &LoggerConfig) -> Result<()> {
let log_level = std::env::var("RUST_LOG") let log_level = std::env::var("RUST_LOG")
.ok() .ok()
.and_then(|v| LevelFilter::from_str(v.trim()).ok()) .and_then(|v| LevelFilter::from_str(v.trim()).ok())
@@ -189,15 +186,14 @@ impl Logger {
let pipeline = tracing_estuary::PipelineBuilder::new() let pipeline = tracing_estuary::PipelineBuilder::new()
.default_level(log_level) .default_level(log_level)
.file_writer(self.generate_file_log_writer()) .file_writer(self.generate_file_log_writer())
.init() .init()?;
.map_err(|error| LoggerError::Pipeline(error.into_boxed_dyn_error()))?;
self.pipeline.set(pipeline).ok(); self.pipeline.set(pipeline).ok();
Ok(()) Ok(())
} }
/// Installs the sidecar file writer and the panic hook. Safe to call when /// Installs the sidecar file writer and the panic hook. Safe to call when
/// the pipeline is owned elsewhere (e.g. a devtools-provided subscriber). /// the pipeline is owned elsewhere (e.g. a devtools-provided subscriber).
pub fn init_sidecar(&self, cfg: &LoggerConfig) -> Result<(), LoggerError> { pub fn init_sidecar(&self, cfg: &LoggerConfig) -> Result<()> {
self.store_config(cfg); self.store_config(cfg);
self.ensure_sidecar_writer(self.generate_sidecar_builder())?; self.ensure_sidecar_writer(self.generate_sidecar_builder())?;
@@ -249,7 +245,7 @@ impl Logger {
/// Ensures the sidecar writer exists and points at `builder`'s config: /// Ensures the sidecar writer exists and points at `builder`'s config:
/// built once, then reset in place — flexi's flusher thread cannot be /// built once, then reset in place — flexi's flusher thread cannot be
/// stopped, so every dropped writer would leak a thread and an fd. /// stopped, so every dropped writer would leak a thread and an fd.
fn ensure_sidecar_writer(&self, builder: FileLogWriterBuilder) -> Result<(), LoggerError> { fn ensure_sidecar_writer(&self, builder: FileLogWriterBuilder) -> Result<()> {
let sidecar = self.sidecar_file_writer.write(); let sidecar = self.sidecar_file_writer.write();
match sidecar.as_ref() { match sidecar.as_ref() {
Some(writer) => { Some(writer) => {
@@ -300,29 +296,27 @@ impl Logger {
} }
/// only update app log level /// only update app log level
pub fn update_log_level(&self, level: LevelFilter) -> Result<(), LoggerError> { pub fn update_log_level(&self, level: LevelFilter) -> Result<()> {
if let Some(pipeline) = self.pipeline.get() { if let Some(pipeline) = self.pipeline.get() {
pipeline pipeline.filter.set_default_level(level)?;
.filter
.set_default_level(level)
.map_err(|error| LoggerError::Pipeline(error.into_boxed_dyn_error()))?;
} else { } else {
return Err(LoggerError::PipelineUnavailable); bail!("failed to get tracing pipeline, make sure it init");
}; };
Ok(()) Ok(())
} }
/// Rebuilds both file writers with the new limits. /// Rebuilds both file writers with the new limits.
pub fn update_log_config(&self, log_max_size: u64, log_max_count: usize) -> Result<(), LoggerError> { pub fn update_log_config(&self, log_max_size: u64, log_max_count: usize) -> Result<()> {
self.log_max_size.store(log_max_size, Ordering::SeqCst); self.log_max_size.store(log_max_size, Ordering::SeqCst);
self.log_max_count.store(log_max_count, Ordering::SeqCst); self.log_max_count.store(log_max_count, Ordering::SeqCst);
if let Some(pipeline) = self.pipeline.get() { if let Some(pipeline) = self.pipeline.get() {
let log_file_writer = self.generate_file_log_writer(); let log_file_writer = self.generate_file_log_writer();
if let Some(sink) = pipeline.sink.as_ref() { if let Some(sink) = pipeline.sink.as_ref() {
sink.reset(log_file_writer).map_err(LoggerError::ResetWriter)?; sink.reset(log_file_writer)
.map_err(|error| anyhow::anyhow!("failed to reset log writer: {error}"))?;
} }
} else { } else {
return Err(LoggerError::PipelineUnavailable); bail!("failed to get tracing pipeline, make sure it init");
}; };
self.ensure_sidecar_writer(self.generate_sidecar_builder())?; self.ensure_sidecar_writer(self.generate_sidecar_builder())?;
Ok(()) Ok(())
@@ -1,16 +0,0 @@
[package]
name = "clash-verge-profile-script"
version = "0.1.0"
edition = "2024"
[dependencies]
boa_engine = { workspace = true }
clash-verge-logging = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
serde_yaml_ng = { workspace = true }
tokio = { workspace = true }
tristr = { workspace = true }
[lints]
workspace = true
-17
View File
@@ -1,17 +0,0 @@
[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
-5
View File
@@ -1,5 +0,0 @@
#[derive(Debug, thiserror::Error)]
#[error("failed to get the profile item \"uid:{uid}\"")]
pub struct ProfileNotFound {
pub(super) uid: String,
}
-397
View File
@@ -1,397 +0,0 @@
mod error;
pub mod selected_nodes;
mod subscription_schedule;
pub use error::ProfileNotFound;
pub use subscription_schedule::SubscriptionSchedule;
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<String>,
/// enum value: remote | local | script | merge
#[serde(rename = "type")]
pub itype: Option<String>,
pub name: Option<String>,
pub file: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub desc: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub selected: Option<Vec<PrfSelected>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub extra: Option<PrfExtra>,
pub updated: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub option: Option<PrfOption>,
#[serde(skip_serializing_if = "Option::is_none")]
pub home: Option<String>,
#[serde(skip)]
pub file_data: Option<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)]
#[serde(default)]
pub struct PrfSelected {
pub name: Option<String>,
pub now: Option<String>,
}
#[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<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub with_proxy: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub self_proxy: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub update_interval: Option<u64>,
/// HTTP request timeout in seconds
/// default is 60 seconds
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout_seconds: Option<u64>,
/// default is `false`
#[serde(skip_serializing_if = "Option::is_none")]
pub danger_accept_invalid_certs: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_auto_update: Option<bool>,
pub merge: Option<String>,
pub script: Option<String>,
pub rules: Option<String>,
pub proxies: Option<String>,
pub groups: Option<String>,
}
impl PrfOption {
pub fn merge(one: Option<&Self>, other: Option<&Self>) -> Option<Self> {
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<String>,
pub items: Option<Vec<PrfItem>>,
}
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<String>,
}
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<str>) -> Result<&PrfItem, ProfileNotFound> {
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() })
}
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.
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<ProfileDeletePlan, ProfileNotFound> {
let deleting_current = self.current.as_deref().is_none_or(|current| current == uid);
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);
}
}
}
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,
})
}
pub fn profiles_preview(&self) -> Option<Vec<IProfilePreview<'_>>> {
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 remove_item(items: &mut Vec<PrfItem>, target_uid: Option<&str>) -> Option<PrfItem> {
let index = items.iter().position(|item| item.uid.as_deref() == target_uid)?;
Some(items.remove(index))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn old_index_preserves_missing_and_explicit_values() -> Result<(), Box<dyn std::error::Error>> {
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::<IProfiles>("{}")?)?,
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<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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(())
}
}
@@ -1,147 +0,0 @@
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<PrfSelected>,
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<SelectedGroup<'a>>,
) -> 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<SelectedGroup<'a>>,
) -> 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::<Vec<_>>();
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<SelectedGroup<'a>>,
) -> Vec<String> {
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()
}
@@ -1,49 +0,0 @@
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<Self> {
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<usize>, now: i64) -> Self {
let full = Self::interval_duration(interval_minutes);
let elapsed = updated
.filter(|updated| *updated > 0)
.map_or(0, |updated| (now.max(0) as u64).saturating_sub(updated 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<usize>) -> Option<i64> {
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)
}
}
-12
View File
@@ -1,12 +0,0 @@
[package]
name = "clash-verge-proxy-view"
version = "0.1.0"
edition = "2024"
[dependencies]
serde = { workspace = true, features = ["derive"] }
specta = { workspace = true, features = ["derive"] }
tristr = { workspace = true }
[lints]
workspace = true
@@ -1,17 +0,0 @@
[package]
name = "clash-verge-runtime-bundle"
version = "0.1.0"
edition = "2024"
[dependencies]
thiserror = { workspace = true }
clash-verge-logging = { workspace = true }
hex = "0.4.3"
log = { workspace = true }
serde_yaml_ng = { workspace = true }
sha2 = { workspace = true }
tristr = { workspace = true }
tokio = { workspace = true, features = ["fs"] }
[lints]
workspace = true
@@ -1,43 +0,0 @@
use std::path::PathBuf;
#[derive(Debug, thiserror::Error)]
pub enum RuntimeBundleError {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error("failed to read runtime config {path:?}")]
ReadConfig {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("failed to parse runtime config {path:?}")]
ParseConfig {
path: PathBuf,
#[source]
source: serde_yaml_ng::Error,
},
#[error("runtime config has no parent directory")]
MissingConfigDirectory,
#[error("runtime provider destination {0:?} is declared for two different sources")]
DifferentSources(String),
#[error("runtime provider destination {0:?} is claimed more than once")]
DuplicateDestination(String),
#[error("local runtime provider is unavailable: {path:?}")]
LocalProviderUnavailable {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("local runtime provider is outside the config root: {0:?}")]
LocalProviderOutsideRoot(PathBuf),
#[error("runtime provider destination traverses outside the runtime")]
DestinationOutsideRuntime,
#[error("runtime provider path has no existing ancestor: {0:?}")]
MissingAncestor(PathBuf),
#[error("runtime provider path is outside the config root: {0:?}")]
ProviderOutsideRoot(PathBuf),
#[error("local runtime provider destination traverses outside the runtime")]
LocalDestinationOutsideRuntime,
#[error("local runtime provider destination is empty")]
EmptyDestination,
}
+1 -1
View File
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024" edition = "2024"
rust-version = "1.91" rust-version = "1.91"
[target.'cfg(target_os = "linux")'.dependencies] [dependencies]
clash-verge-logging = { workspace = true } clash-verge-logging = { workspace = true }
log = { workspace = true } log = { workspace = true }
tokio = { workspace = true, features = ["signal"] } tokio = { workspace = true, features = ["signal"] }
@@ -1,14 +0,0 @@
[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
@@ -1,84 +0,0 @@
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<Cow<'a, str>>,
}
pub fn decode_subscription_link(link: &Url) -> Option<SubscriptionLink<'_>> {
if !matches!(link.scheme(), "clash" | "clash-verge") {
return None;
}
// The embedded URL can contain unescaped query separators of its own.
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),
name,
})
}
fn decode_subscription_url(raw_url: &str) -> Cow<'_, str> {
if Url::parse(raw_url).is_ok() {
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();
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 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(())
}
}
@@ -1,7 +0,0 @@
#[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,
}
-244
View File
@@ -1,244 +0,0 @@
mod deep_link;
mod error;
pub use deep_link::{SubscriptionLink, decode_subscription_link};
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<String>,
pub usage: Option<SubscriptionUsage>,
pub update_interval_minutes: Option<u64>,
pub home: Option<String>,
}
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<SubscriptionDocument<'a>, SubscriptionError> {
let body = body.trim_start_matches('\u{feff}');
let yaml = serde_yaml_ng::from_str::<Mapping>(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::<u64>().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<String> {
if let Some(filename) = headers.get("content-disposition").and_then(disposition_filename) {
return Some(filename);
}
let filename = url.path().rsplit('/').next()?;
let filename = percent_decode_str(filename).decode_utf8_lossy();
if filename.trim().is_empty() {
return None;
}
Some(filename.into_owned())
}
fn disposition_filename(header: &http::HeaderValue) -> Option<String> {
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<String> {
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<T>) -> Option<T> {
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<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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 reads_filename_parameters_before_falling_back_to_the_url_path() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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(())
}
}
+1 -2
View File
@@ -1,6 +1,5 @@
//! Task drivers and retry primitives with caller-managed runtime and cancellation. //! Single-owner task drivers with caller-managed runtime and cancellation.
pub mod countdown; pub mod countdown;
pub mod retry;
pub mod scheduled_task; pub mod scheduled_task;
pub mod watch_task; pub mod watch_task;
@@ -12,7 +12,7 @@ parking_lot = { workspace = true }
serde = { workspace = true, features = ["derive"] } serde = { workspace = true, features = ["derive"] }
# sysinfo 0.38.2 conflicts with dark-light # sysinfo 0.38.2 conflicts with dark-light
# see https://github.com/GuillaumeGomez/sysinfo/issues/1623 # see https://github.com/GuillaumeGomez/sysinfo/issues/1623
sysinfo = { version = "0.40.5", default-features = false, features = ["network", "system"] } sysinfo = { version = "0.40.4", default-features = false, features = ["network", "system"] }
[target.'cfg(not(windows))'.dependencies] [target.'cfg(not(windows))'.dependencies]
libc = "0.2.191" libc = "0.2.191"
+3
View File
@@ -7,6 +7,7 @@ import pluginImportX from 'eslint-plugin-import-x'
import pluginReactCompiler from 'eslint-plugin-react-compiler' import pluginReactCompiler from 'eslint-plugin-react-compiler'
import pluginReactHooks from 'eslint-plugin-react-hooks' import pluginReactHooks from 'eslint-plugin-react-hooks'
import pluginReactRefresh from 'eslint-plugin-react-refresh' import pluginReactRefresh from 'eslint-plugin-react-refresh'
import PluginSukka from 'eslint-plugin-sukka'
import pluginUnusedImports from 'eslint-plugin-unused-imports' import pluginUnusedImports from 'eslint-plugin-unused-imports'
import globals from 'globals' import globals from 'globals'
import tseslint from 'typescript-eslint' import tseslint from 'typescript-eslint'
@@ -111,6 +112,7 @@ export default defineConfig([
'import-x': pluginImportX, 'import-x': pluginImportX,
'react-refresh': pluginReactRefresh, 'react-refresh': pluginReactRefresh,
'unused-imports': pluginUnusedImports, 'unused-imports': pluginUnusedImports,
sukka: PluginSukka,
}, },
extends: [ extends: [
@@ -180,6 +182,7 @@ export default defineConfig([
'@eslint-react/no-unused-class-component-members': 'error', '@eslint-react/no-unused-class-component-members': 'error',
'@eslint-react/no-unused-state': 'error', '@eslint-react/no-unused-state': 'error',
'@eslint-react/jsx-no-useless-fragment': 'warn', '@eslint-react/jsx-no-useless-fragment': 'warn',
'sukka/react-prefer-destructuring-assignment': 'warn',
// TypeScript // TypeScript
'@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-explicit-any': 'off',
+20 -17
View File
@@ -47,16 +47,18 @@
"@mui/icons-material": "^9.4.0", "@mui/icons-material": "^9.4.0",
"@mui/material": "^9.4.0", "@mui/material": "^9.4.0",
"@tanstack/react-virtual": "^3.14.13", "@tanstack/react-virtual": "^3.14.13",
"@tauri-apps/api": "2.13.0", "@tauri-apps/api": "3.0.0-alpha.3",
"@tauri-apps/plugin-clipboard-manager": "2.5.0", "@tauri-apps/plugin-clipboard-manager": "3.0.0-alpha.3",
"@tauri-apps/plugin-dialog": "2.8.4", "@tauri-apps/plugin-dialog": "3.0.0-alpha.4",
"@tauri-apps/plugin-fs": "2.7.1", "@tauri-apps/plugin-fs": "3.0.0-alpha.3",
"@tauri-apps/plugin-http": "2.9.0", "@tauri-apps/plugin-http": "3.0.0-alpha.3",
"@tauri-apps/plugin-opener": "2.7.3", "@tauri-apps/plugin-opener": "3.0.0-alpha.3",
"@tauri-apps/plugin-updater": "2.14.1", "@tauri-apps/plugin-updater": "3.0.0-alpha.3",
"ahooks": "^3.10.0", "ahooks": "^3.10.0",
"cidr-block": "^2.3.0", "cidr-block": "^2.3.0",
"dayjs": "1.11.23", "dayjs": "1.11.23",
"foxact": "^0.3.12",
"foxts": "^5.9.1",
"i18next": "^27.0.0", "i18next": "^27.0.0",
"js-yaml": "^5.4.2", "js-yaml": "^5.4.2",
"lodash-es": "^4.18.1", "lodash-es": "^4.18.1",
@@ -75,8 +77,8 @@
"rehype-raw": "^7.0.0", "rehype-raw": "^7.0.0",
"rehype-sanitize": "^6.0.0", "rehype-sanitize": "^6.0.0",
"swr": "^2.5.1", "swr": "^2.5.1",
"tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#main", "tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#8ddbec3a24eea8be18b5eaa1aba16f87f23e9583",
"tldts": "7.6.4", "tldts": "7.6.2",
"types-pac": "^1.0.3", "types-pac": "^1.0.3",
"validator": "^13.15.35" "validator": "^13.15.35"
}, },
@@ -85,7 +87,7 @@
"@biomejs/biome": "^2.5.14", "@biomejs/biome": "^2.5.14",
"@eslint-react/eslint-plugin": "^5.20.5", "@eslint-react/eslint-plugin": "^5.20.5",
"@eslint/js": "^10.0.1", "@eslint/js": "^10.0.1",
"@tauri-apps/cli": "2.13.0", "@tauri-apps/cli": "3.0.0-alpha.6",
"@types/lodash-es": "^4.17.12", "@types/lodash-es": "^4.17.12",
"@types/node": "^26.0.0", "@types/node": "^26.0.0",
"@types/react": "19.3.3", "@types/react": "19.3.3",
@@ -98,29 +100,30 @@
"cli-color": "^2.0.4", "cli-color": "^2.0.4",
"commander": "^15.0.0", "commander": "^15.0.0",
"cross-env": "^10.1.0", "cross-env": "^10.1.0",
"eslint": "^10.16.0", "eslint": "^10.11.0",
"eslint-import-resolver-typescript": "^4.4.5", "eslint-import-resolver-typescript": "^4.4.5",
"eslint-plugin-es-x": "^10.0.1", "eslint-plugin-es-x": "^10.0.1",
"eslint-plugin-import-x": "^4.18.1", "eslint-plugin-import-x": "^4.17.1",
"eslint-plugin-react-compiler": "19.1.0-rc.2", "eslint-plugin-react-compiler": "19.1.0-rc.2",
"eslint-plugin-react-hooks": "^7.1.1", "eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.7", "eslint-plugin-react-refresh": "^0.5.7",
"eslint-plugin-sukka": "^10.2.0",
"eslint-plugin-unused-imports": "^4.4.1", "eslint-plugin-unused-imports": "^4.4.1",
"globals": "^17.12.0", "globals": "^17.12.0",
"https-proxy-agent": "^9.1.0", "https-proxy-agent": "^9.1.0",
"husky": "^9.1.7", "husky": "^9.1.7",
"jiti": "^2.7.0", "jiti": "^2.7.0",
"knip": "6.49.0", "knip": "6.48.0",
"lint-staged": "^17.5.1", "lint-staged": "^17.5.1",
"sass": "^1.104.1", "sass": "^1.104.1",
"tar": "^8.0.0", "tar": "^7.5.22",
"terser": "^5.51.2", "terser": "^5.51.2",
"tsrs": "0.20.0-ts7.1.0-beta", "tsrs": "0.20.0-ts7.1.0-beta",
"typescript": "^6.0.3", "typescript": "^6.0.3",
"typescript-eslint": "^8.74.0", "typescript-eslint": "^8.70.0",
"vite": "^8.3.0", "vite": "^8.3.0",
"vite-plugin-svgr": "^5.2.0", "vite-plugin-svgr": "^5.2.0",
"vitest": "^5.0.3" "vitest": "^5.0.1"
}, },
"lint-staged": { "lint-staged": {
"*.{ts,tsx,js,mjs}": [ "*.{ts,tsx,js,mjs}": [
@@ -132,5 +135,5 @@
] ]
}, },
"type": "module", "type": "module",
"packageManager": "pnpm@12.25.1" "packageManager": "pnpm@12.23.0"
} }
+1401 -1052
View File
File diff suppressed because it is too large Load Diff
+3 -1
View File
@@ -1,6 +1,7 @@
use objc2::{class, msg_send, runtime::AnyObject, sel}; use objc2::{class, msg_send, runtime::AnyObject, sel};
use objc2_foundation::{NSPoint, NSRect, ns_string}; use objc2_foundation::{NSPoint, NSRect, ns_string};
use tauri::{Manager as _, WebviewWindow}; use tauri::{Manager as _, WebviewWindow};
use tauri_runtime_wry::WebviewWryExt as _;
#[link(name = "CoreGraphics", kind = "framework")] #[link(name = "CoreGraphics", kind = "framework")]
unsafe extern "C" { unsafe extern "C" {
@@ -140,7 +141,7 @@ async fn perf_state(window: WebviewWindow, action: String) -> Result<serde_json:
let (tx, rx) = std::sync::mpsc::channel(); let (tx, rx) = std::sync::mpsc::channel();
let fail_app = window.app_handle().clone(); let fail_app = window.app_handle().clone();
window window
.with_webview(move |view| unsafe { .with_wry_webview(move |view| unsafe {
let native = &*(view.ns_window() as *const AnyObject); let native = &*(view.ns_window() as *const AnyObject);
let sender = std::ptr::null::<AnyObject>(); let sender = std::ptr::null::<AnyObject>();
let display = match display_state(native) { let display = match display_state(native) {
@@ -212,6 +213,7 @@ pub fn run() -> std::process::ExitCode {
#[cfg(not(feature = "clippy"))] #[cfg(not(feature = "clippy"))]
let context = tauri::generate_context!(); let context = tauri::generate_context!();
let result = tauri::Builder::default() let result = tauri::Builder::default()
.runtime(tauri_runtime_wry::Wry::default())
.plugin(tauri_plugin_wdio_webdriver::init()) .plugin(tauri_plugin_wdio_webdriver::init())
.invoke_handler(tauri::generate_handler![perf_state, get_clash_logs, get_verge_config]) .invoke_handler(tauri::generate_handler![perf_state, get_clash_logs, get_verge_config])
.setup(|app| { .setup(|app| {
+17 -20
View File
@@ -9,7 +9,7 @@ import AdmZip from 'adm-zip'
import { HttpsProxyAgent } from 'https-proxy-agent' import { HttpsProxyAgent } from 'https-proxy-agent'
import { extract } from 'tar' import { extract } from 'tar'
import { resolveServiceBundle as serviceBundleFromMetadata } from './service-release.mjs' import { resolveServiceRelease } from './service-release.mjs'
import { log_debug, log_error, log_info, log_success } from './utils.mjs' import { log_debug, log_error, log_info, log_success } from './utils.mjs'
/** Prepares platform resources, caching versions and unchanged files unless `--force` is used. */ /** Prepares platform resources, caching versions and unchanged files unless `--force` is used. */
@@ -581,30 +581,23 @@ async function resolveServiceBundle() {
} }
}) })
const metadata = JSON.parse( const cargoManifest = await fsp.readFile(
execFileSync( path.join(cwd, 'src-tauri', 'Cargo.toml'),
'cargo', 'utf8',
[
'metadata',
'--locked',
'--format-version',
'1',
'--filter-platform',
SIDECAR_HOST,
],
{ cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },
),
) )
const bundle = serviceBundleFromMetadata(metadata, SIDECAR_HOST, platform) const serviceDependency = cargoManifest
if (bundle.manifest) { .split(/\r?\n/)
.find((line) => line.trimStart().startsWith('clash_verge_service_ipc ='))
const sourcePath = serviceDependency?.match(/\bpath\s*=\s*"([^"]+)"/)?.[1]
if (sourcePath) {
const manifest = path.resolve(cwd, 'src-tauri', sourcePath, 'Cargo.toml')
const targetDirectory = path.join(cwd, 'target', 'bundled-service') const targetDirectory = path.join(cwd, 'target', 'bundled-service')
execFileSync( execFileSync(
'cargo', 'cargo',
[ [
'build', 'build',
'--locked',
'--manifest-path', '--manifest-path',
bundle.manifest, manifest,
'--target-dir', '--target-dir',
targetDirectory, targetDirectory,
'--target', '--target',
@@ -612,7 +605,7 @@ async function resolveServiceBundle() {
'--release', '--release',
'--features', '--features',
'standalone,client', 'standalone,client',
...SERVICE_BINARIES.flatMap((name) => ['--bin', name]), '--bins',
], ],
{ stdio: 'inherit' }, { stdio: 'inherit' },
) )
@@ -627,7 +620,11 @@ async function resolveServiceBundle() {
} }
return return
} }
const { archiveFile, downloadURL } = bundle const { archiveFile, downloadURL } = resolveServiceRelease(
cargoManifest,
SIDECAR_HOST,
platform,
)
const tempDir = path.join(TEMP_DIR, 'clash-verge-service-ipc') const tempDir = path.join(TEMP_DIR, 'clash-verge-service-ipc')
const tempArchive = path.join(tempDir, archiveFile) const tempArchive = path.join(tempDir, archiveFile)
+10 -23
View File
@@ -1,35 +1,22 @@
const SERVICE_URL_PREFIX = const SERVICE_URL_PREFIX =
'https://github.com/clash-verge-rev/clash-verge-service-ipc/releases/download' 'https://github.com/clash-verge-rev/clash-verge-service-ipc/releases/download'
export function resolveServiceBundle(metadata, host, platform) { export function resolveServiceRelease(cargoManifest, host, platform) {
const app = metadata.packages.find( const dependency = cargoManifest
(pkg) => .split(/\r?\n/)
pkg.name === 'clash-verge' && metadata.workspace_members.includes(pkg.id), .find((line) => line.trimStart().startsWith('clash_verge_service_ipc ='))
) const packageVersion = dependency?.match(/\bversion\s*=\s*"([^"]+)"/)?.[1]
const dependency = app?.dependencies.find( if (!packageVersion) {
(dep) => dep.name === 'clash_verge_service_ipc',
)
const edge = metadata.resolve.nodes
.find((node) => node.id === app?.id)
?.deps.find((dep) => dep.name === 'clash_verge_service_ipc')
const service = metadata.packages.find((pkg) => pkg.id === edge?.pkg)
if (!service || !dependency) {
throw new Error('Cargo did not resolve the desktop IPC client dependency')
}
if (!service.source || new URL(service.source).searchParams.has('rev')) {
return { manifest: service.manifest_path }
}
const declared = dependency.req.replace(/^[=^]/, '')
if (declared !== service.version) {
throw new Error( throw new Error(
`Service release version ${declared} differs from the resolved IPC client ${service.version}`, 'clash_verge_service_ipc dependency must declare an inline version',
) )
} }
const version = `v${declared}`
const version = `v${packageVersion}`
const archiveExt = platform === 'win32' ? 'zip' : 'tar.gz' const archiveExt = platform === 'win32' ? 'zip' : 'tar.gz'
const archiveFile = `clash-verge-service-ipc-${version}-${host}.${archiveExt}` const archiveFile = `clash-verge-service-ipc-${version}-${host}.${archiveExt}`
return { return {
version,
archiveFile, archiveFile,
downloadURL: `${SERVICE_URL_PREFIX}/${version}/${archiveFile}`, downloadURL: `${SERVICE_URL_PREFIX}/${version}/${archiveFile}`,
} }
+3 -10
View File
@@ -1,17 +1,10 @@
# Backend Architecture Guardrails # Backend Architecture Guardrails
Follow [Workspace Crate Architecture](../crates/AGENTS.md) when changing Use [Workspace Crate Architecture](../crates/AGENTS.md) when extracting backend
backend capability boundaries, reusable orchestration, or background task capabilities or changing background task ownership.
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 - **Configuration and effects.** `config` owns source configuration, drafts, and
persistence coordination. Persistence adapters perform storage and recovery. persistence. The effects layer classifies every Verge patch field, including
The effects layer classifies every Verge patch field, including
fields without effects and platform-specific fields, and reconciles requested fields without effects and platform-specific fields, and reconciles requested
state in dependency order. Publish rollbackable state after persistence and state in dependency order. Publish rollbackable state after persistence and
commit. On failure, preserve already applied runtime effects, independently commit. On failure, preserve already applied runtime effects, independently
+28 -36
View File
@@ -27,7 +27,7 @@ perf-harness = ["dep:tauri-plugin-wdio-webdriver"]
identifier = "io.github.clash-verge-rev.clash-verge-rev" identifier = "io.github.clash-verge-rev.clash-verge-rev"
[build-dependencies] [build-dependencies]
tauri-build = { version = "2.8.0", features = [] } tauri-build = { version = "=3.0.0-alpha.4", features = [] }
[dependencies] [dependencies]
clash-verge-draft = { workspace = true } clash-verge-draft = { workspace = true }
@@ -36,23 +36,16 @@ clash-verge-media-unlock = { workspace = true }
clash-verge-logging = { workspace = true } clash-verge-logging = { workspace = true }
clash-verge-i18n = { workspace = true } clash-verge-i18n = { workspace = true }
clash-verge-limiter = { workspace = true } clash-verge-limiter = { workspace = true }
clash-verge-subscription = { workspace = true }
clash-verge-runtime-bundle = { workspace = true }
clash-verge-config-render = { workspace = true }
clash-verge-profile-script = { workspace = true }
clash-verge-proxy-view = { workspace = true }
clash-verge-profile = { workspace = true }
clash-verge-backup-archive = { workspace = true }
tauri-plugin-clash-verge-sysinfo = { workspace = true } tauri-plugin-clash-verge-sysinfo = { workspace = true }
tauri-plugin-clipboard-manager = { workspace = true } tauri-plugin-clipboard-manager = { workspace = true }
tauri = { workspace = true, features = [ tauri = { workspace = true, features = [
"protocol-asset", "protocol-asset",
"devtools",
"tracing", "tracing",
"tray-icon", "tray-icon",
"image-ico", "image-ico",
"image-png", "image-png",
] } ] }
tauri-runtime-wry = { workspace = true, features = ["common-controls-v6", "devtools", "tracing"] }
parking_lot = { workspace = true } parking_lot = { workspace = true }
anyhow = { workspace = true } anyhow = { workspace = true }
tokio = { workspace = true } tokio = { workspace = true }
@@ -64,10 +57,12 @@ tristr = { workspace = true }
socket2 = { workspace = true } socket2 = { workspace = true }
warp = { version = "0.4.4", features = ["server"] } warp = { version = "0.4.4", features = ["server"] }
open = "5.4.5" open = "5.4.5"
rfd = { version = "0.18.0", default-features = false, features = ["common-controls-v6", "xdg-portal"] }
dirs = "7.0.0" dirs = "7.0.0"
dunce = "1.0.5" dunce = "1.0.5"
nanoid = "0.5" nanoid = "0.5"
chrono = { workspace = true } chrono = { workspace = true }
boa_engine = "0.22.0"
http-body-util = "0.1.5" http-body-util = "0.1.5"
percent-encoding = "2.3.2" percent-encoding = "2.3.2"
reqwest = { workspace = true } reqwest = { workspace = true }
@@ -75,54 +70,51 @@ sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs.git", rev = "
"guard", "guard",
] } ] }
network-interface = { version = "2.0.5", features = ["serde"] } network-interface = { version = "2.0.5", features = ["serde"] }
tauri-plugin-shell = "2.6.0" tauri-plugin-shell = "=3.0.0-alpha.3"
tauri-plugin-opener = "2.7.3" tauri-plugin-opener = "=3.0.0-alpha.3"
tauri-plugin-dialog = { version = "2.9.0", default-features = false, features = ["gtk3"] } tauri-plugin-dialog = "=3.0.0-alpha.4"
tauri-plugin-fs = "2.8.0" tauri-plugin-fs = "=3.0.0-alpha.3"
tauri-plugin-deep-link = "2.6.3" tauri-plugin-deep-link = { git = "https://github.com/tauri-apps/plugins-workspace", rev = "f69e3649d7612a44dfb456a4990c588ea278d73a" }
tauri-plugin-window-state = "2.5.1" tauri-plugin-window-state = "=3.0.0-alpha.2"
zip = { workspace = true } zip = "9.9.0"
flate2 = "1.1.11" flate2 = "1.1.11"
reqwest_dav = "0.4.0" reqwest_dav = "0.4.0"
aes-gcm = { version = "0.11.1" } aes-gcm = { version = "0.11.1" }
base64 = "0.23.1" base64 = "0.23.1"
sha2 = { workspace = true } sha2 = "0.11.2"
getrandom = "0.4.3" getrandom = "0.4.3"
futures = { workspace = true } futures = { workspace = true }
gethostname = "1.1.0" gethostname = "1.1.0"
tauri-plugin-notification = "2.8.1" tauri-plugin-notification = "=3.0.0-alpha.3"
tauri-plugin-http = "2.10.0" backon = { version = "1.6.0", features = ["tokio-sleep"] }
backon = { version = "1.7.0", features = ["tokio-sleep"] } tauri-plugin-http = "=3.0.0-alpha.3"
tracing = { workspace = true } tracing = { workspace = true }
tauri-plugin-devtools = { version = "2.2.3", optional = true } tauri-plugin-devtools = { version = "=3.0.0-alpha.0", optional = true }
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "7e4fa8642cf6c394ed88b5a969420d8eab60087f" } tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "8ddbec3a24eea8be18b5eaa1aba16f87f23e9583" }
async-trait = "0.1.92" async-trait = "0.1.92"
clash_verge_service_ipc = { workspace = true, features = ["client"] } clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", features = [
"client",
] }
arc-swap = "1.9.5" arc-swap = "1.9.5"
tokio-rustls = "0.26.6" tokio-rustls = "0.26.6"
rustls = { version = "0.23.47", features = ["ring"] } rustls = { version = "0.23.46", features = ["ring"] }
webpki-roots = "1.0.12" webpki-roots = "1.0.12"
dark-light = "3.0.0" dark-light = "3.0.0"
bytes = "1.12.2" bytes = "1.12.2"
tokio-util = { version = "0.7.20", features = ["time"] } tokio-util = { version = "0.7.20", features = ["time"] }
specta = { workspace = true, features = ["derive", "function", "serde_json"] } specta = { version = "=2.0.0-rc.26", features = ["derive", "function", "serde_json"] }
tauri-specta = { version = "=2.0.0-rc.26", features = ["derive", "typescript"] } tauri-specta = { git = "https://github.com/tauri-apps/tauri-specta", rev = "6bcec0cdec0c92decf404c85ff01b4d8c3868599", features = ["derive", "typescript"] }
specta-typescript = "=0.0.13" specta-typescript = "=0.0.13"
[target.'cfg(unix)'.dependencies] [target.'cfg(unix)'.dependencies]
libc = "0.2.191" libc = "0.2.191"
[target.'cfg(target_os = "linux")'.dependencies] [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. # Upstream has no session-end signal support on Linux; see crates/clash-verge-signal.
clash-verge-signal = { workspace = true } 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] [target.'cfg(target_os = "macos")'.dependencies]
tauri-plugin-wdio-webdriver = { version = "=2.0.0-next.0", optional = true } tauri-plugin-wdio-webdriver = { git = "https://github.com/Tunglies/desktop-mobile.git", rev = "3c936ad889b153bbe60902f74cbf69ef04d0e8d0", optional = true }
objc2 = "0.6.5" objc2 = "0.6.5"
objc2-foundation = { version = "0.3.2", features = [ objc2-foundation = { version = "0.3.2", features = [
"NSString", "NSString",
@@ -151,7 +143,7 @@ quick-xml = "0.42.0"
runas = "=1.2.0" runas = "=1.2.0"
winreg = "0.56.0" winreg = "0.56.0"
windows-service = "0.8.1" windows-service = "0.8.1"
windows = { version = "0.101.0", features = [ windows = { version = "0.62.2", features = [
"Win32_System_Com", "Win32_System_Com",
"Win32_System_Ole", "Win32_System_Ole",
"Win32_System_TaskScheduler", "Win32_System_TaskScheduler",
@@ -160,9 +152,9 @@ windows = { version = "0.101.0", features = [
windows-sys.workspace = true windows-sys.workspace = true
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies] [target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
tauri-plugin-autostart = "2.7.0" tauri-plugin-autostart = "=3.0.0-alpha.3"
tauri-plugin-global-shortcut = "2.4.1" tauri-plugin-global-shortcut = "=3.0.0-alpha.3"
tauri-plugin-updater = "2.14.1" tauri-plugin-updater = "=3.0.0-alpha.3"
[dev-dependencies] [dev-dependencies]
tokio = { workspace = true, features = ["test-util"] } tokio = { workspace = true, features = ["test-util"] }
-2
View File
@@ -1,5 +1,3 @@
#![deny(clippy::expect_used, clippy::unwrap_used)]
fn main() -> Result<(), Box<dyn std::error::Error>> { fn main() -> Result<(), Box<dyn std::error::Error>> {
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows")
&& std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") && std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc")
-1
View File
@@ -70,7 +70,6 @@
"dialog:allow-open", "dialog:allow-open",
"global-shortcut:allow-is-registered", "global-shortcut:allow-is-registered",
"global-shortcut:allow-register", "global-shortcut:allow-register",
"global-shortcut:allow-register-all",
"global-shortcut:allow-unregister", "global-shortcut:allow-unregister",
"global-shortcut:allow-unregister-all", "global-shortcut:allow-unregister-all",
"clipboard-manager:allow-read-text", "clipboard-manager:allow-read-text",
-2
View File
@@ -1,5 +1,3 @@
#![deny(clippy::expect_used, clippy::unwrap_used)]
// Dev-only target: Tauri ships everything under src/bin/ to /usr/bin in deb/rpm // 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. // bundles (PR #8131), so this generator must stay an example, never a bin.
fn main() -> Result<(), Box<dyn std::error::Error>> { fn main() -> Result<(), Box<dyn std::error::Error>> {
+8 -11
View File
@@ -81,9 +81,6 @@ Var VC_RUNTIME_NEEDED
Var ServiceExisted Var ServiceExisted
Var ServiceStartType Var ServiceStartType
Var ServiceWasRunning Var ServiceWasRunning
Var ExistingVersionKind
Var Webview2DownloadResult
Var Webview2InstallExitCode
Name "${PRODUCTNAME}" Name "${PRODUCTNAME}"
BrandingText "${COPYRIGHT}" BrandingText "${COPYRIGHT}"
@@ -217,13 +214,13 @@ Function PageReinstall
; Compare this installar version with the existing installation ; Compare this installar version with the existing installation
; and modify the messages presented to the user accordingly ; and modify the messages presented to the user accordingly
compare_version: compare_version:
StrCpy $ExistingVersionKind "$(older)" StrCpy $R4 "$(older)"
${If} $WixMode = 1 ${If} $WixMode = 1
ReadRegStr $R0 HKLM "$R6" "DisplayVersion" ReadRegStr $R0 HKLM "$R6" "DisplayVersion"
${Else} ${Else}
ReadRegStr $R0 SHCTX "${UNINSTKEY}" "DisplayVersion" ReadRegStr $R0 SHCTX "${UNINSTKEY}" "DisplayVersion"
${EndIf} ${EndIf}
${IfThen} $R0 == "" ${|} StrCpy $ExistingVersionKind "$(unknown)" ${|} ${IfThen} $R0 == "" ${|} StrCpy $R4 "$(unknown)" ${|}
nsis_tauri_utils::SemverCompare "${VERSION}" $R0 nsis_tauri_utils::SemverCompare "${VERSION}" $R0
Pop $R0 Pop $R0
@@ -898,8 +895,8 @@ Section WebView2
Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe" Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe"
DetailPrint "$(webview2Downloading)" DetailPrint "$(webview2Downloading)"
NSISdl::download "https://go.microsoft.com/fwlink/p/?LinkId=2124703" "$TEMP\MicrosoftEdgeWebview2Setup.exe" NSISdl::download "https://go.microsoft.com/fwlink/p/?LinkId=2124703" "$TEMP\MicrosoftEdgeWebview2Setup.exe"
Pop $Webview2DownloadResult Pop $0
${If} $Webview2DownloadResult == "success" ${If} $0 == "success"
DetailPrint "$(webview2DownloadSuccess)" DetailPrint "$(webview2DownloadSuccess)"
${Else} ${Else}
DetailPrint "$(webview2DownloadError)" DetailPrint "$(webview2DownloadError)"
@@ -930,8 +927,8 @@ Section WebView2
install_webview2: install_webview2:
DetailPrint "$(installingWebview2)" DetailPrint "$(installingWebview2)"
; $6 holds the path to the webview2 installer ; $6 holds the path to the webview2 installer
ExecWait "$6 ${WEBVIEW2INSTALLERARGS} /install" $Webview2InstallExitCode ExecWait "$6 ${WEBVIEW2INSTALLERARGS} /install" $1
${If} $Webview2InstallExitCode = 0 ${If} $1 = 0
DetailPrint "$(webview2InstallSuccess)" DetailPrint "$(webview2InstallSuccess)"
${Else} ${Else}
DetailPrint "$(webview2InstallError)" DetailPrint "$(webview2InstallError)"
@@ -956,8 +953,8 @@ Section WebView2
${If} $R1 != "" ${If} $R1 != ""
; Chromium updater docs: https://source.chromium.org/chromium/chromium/src/+/main:docs/updater/user_manual.md ; 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" ; Modified from "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft EdgeWebView\ModifyPath"
ExecWait `"$R1" /install appguid=${WEBVIEW2APPGUID}&needsadmin=true` $Webview2InstallExitCode ExecWait `"$R1" /install appguid=${WEBVIEW2APPGUID}&needsadmin=true` $1
${If} $Webview2InstallExitCode = 0 ${If} $1 = 0
DetailPrint "$(webview2InstallSuccess)" DetailPrint "$(webview2InstallSuccess)"
${Else} ${Else}
MessageBox MB_ICONEXCLAMATION|MB_ABORTRETRYIGNORE "$(webview2InstallError)" IDIGNORE ignore IDRETRY update_webview MessageBox MB_ICONEXCLAMATION|MB_ABORTRETRYIGNORE "$(webview2InstallError)" IDIGNORE ignore IDRETRY update_webview
+5 -5
View File
@@ -1,10 +1,10 @@
use super::{CmdResult, CommandFailure, WithErrorCode as _, proxy_aware_coded_error, proxy_aware_error}; use super::{CmdResult, CommandFailure, WithErrorCode as _, proxy_aware_coded_error, proxy_aware_error};
use crate::core::notify::NoticeStatus; use crate::core::notify::NoticeStatus;
use crate::feat; use crate::feat;
use crate::utils::dirs; use crate::utils::{dirs, yaml_emitter};
use crate::{ use crate::{
cmd::StringifyErr as _, cmd::StringifyErr as _,
config::{ClashInfo, Config, mihomo_yaml, profiles::save_committed_profiles}, config::{ClashInfo, Config, profiles::profiles_save_file_safe},
constants, constants,
core::{ core::{
CoreManager, handle, CoreManager, handle,
@@ -59,7 +59,7 @@ pub async fn change_clash_core(clash_core: std::string::String) -> CmdResult<Opt
match CoreManager::global().change_core(&clash_core).await { match CoreManager::global().change_core(&clash_core).await {
Ok(_) => { Ok(_) => {
logging_error!(Type::Core, save_committed_profiles().await); logging_error!(Type::Core, profiles_save_file_safe().await);
match CoreManager::global().restart_core().await { match CoreManager::global().restart_core().await {
Ok(_) => { Ok(_) => {
@@ -88,7 +88,7 @@ pub async fn change_clash_core(clash_core: std::string::String) -> CmdResult<Opt
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn restart_core() -> CmdResult { pub async fn restart_core() -> CmdResult {
logging_error!(Type::Core, save_committed_profiles().await); logging_error!(Type::Core, profiles_save_file_safe().await);
let result = CoreManager::global() let result = CoreManager::global()
.restart_core() .restart_core()
.await .await
@@ -132,7 +132,7 @@ pub async fn save_dns_config(dns_config: crate::ipc::YamlMapping) -> CmdResult {
let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG); let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG);
let yaml_str = mihomo_yaml::serialize_for_export(&dns_config.0).stringify_err()?; let yaml_str = yaml_emitter::to_mihomo_config_string(&dns_config.0).stringify_err()?;
fs::write(&dns_path, yaml_str).await.stringify_err()?; fs::write(&dns_path, yaml_str).await.stringify_err()?;
logging!(info, Type::Config, "DNS config saved to {dns_path:?}"); logging!(info, Type::Config, "DNS config saved to {dns_path:?}");
+51 -35
View File
@@ -5,12 +5,12 @@ use crate::core::notify::NoticeStatus;
use crate::utils::window_manager::WindowManager; use crate::utils::window_manager::WindowManager;
use crate::{ use crate::{
config::{ config::{
Config, IProfiles, PrfItem, PrfOption, build_remote_profile, Config, IProfiles, PrfItem, PrfOption,
profiles::{ profiles::{
PROFILE_WRITE_LOCK, append_profile, cleanup_profile_files, patch_profile_item, reorder_profiles, PROFILE_WRITE_LOCK, profiles_append_item_with_filedata_safe, profiles_patch_item_safe,
save_committed_profiles, save_profiles, profiles_reorder_safe, profiles_save_file_safe,
}, },
read_profile_item_file, profiles_append_item_safe,
}, },
core::{CoreManager, handle, timer::Timer, tray::Tray, validate::ValidationOutcome}, core::{CoreManager, handle, timer::Timer, tray::Tray, validate::ValidationOutcome},
feat, feat,
@@ -45,7 +45,7 @@ pub async fn get_profiles() -> CmdResult<SharedDraft<IProfiles>> {
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn enhance_profiles() -> CmdResult<ValidationOutcome> { pub async fn enhance_profiles() -> CmdResult<ValidationOutcome> {
match CoreManager::global().update_config_forced().await { match feat::enhance_profiles().await {
Ok(outcome) if outcome.is_valid() => { Ok(outcome) if outcome.is_valid() => {
handle::Handle::refresh_clash(); handle::Handle::refresh_clash();
Ok(outcome) Ok(outcome)
@@ -71,7 +71,7 @@ pub async fn enhance_profiles() -> CmdResult<ValidationOutcome> {
#[tracing::instrument(skip_all, level = "info", fields(url = %help::mask_url(&url), uid = tracing::field::Empty))] #[tracing::instrument(skip_all, level = "info", fields(url = %help::mask_url(&url), uid = tracing::field::Empty))]
#[specta::specta] #[specta::specta]
pub async fn import_profile(url: std::string::String, option: Option<PrfOption>) -> CmdResult { pub async fn import_profile(url: std::string::String, option: Option<PrfOption>) -> CmdResult {
let item = &mut match build_remote_profile(&url, None, None, option.as_ref()).await { let item = &mut match PrfItem::from_url(&url, None, None, option.as_ref()).await {
Ok(it) => it, Ok(it) => it,
Err(e) => { Err(e) => {
logging!(error, Type::Cmd, "[导入订阅] 下载失败: {e:#}"); logging!(error, Type::Cmd, "[导入订阅] 下载失败: {e:#}");
@@ -79,12 +79,12 @@ pub async fn import_profile(url: std::string::String, option: Option<PrfOption>)
} }
}; };
if let Err(e) = append_profile(item).await { if let Err(e) = profiles_append_item_safe(item).await {
logging!(error, Type::Cmd, "[导入订阅] 保存配置失败: {e:#}"); logging!(error, Type::Cmd, "[导入订阅] 保存配置失败: {e:#}");
return Err(coded_error("PROFILE_IMPORT_FAILED", e)); return Err(coded_error("PROFILE_IMPORT_FAILED", e));
} }
if let Err(e) = save_committed_profiles().await { if let Err(e) = profiles_save_file_safe().await {
logging!(error, Type::Cmd, "[导入订阅] 保存配置文件失败: {e:#}"); logging!(error, Type::Cmd, "[导入订阅] 保存配置文件失败: {e:#}");
return Err(coded_error("PROFILE_IMPORT_FAILED", e)); return Err(coded_error("PROFILE_IMPORT_FAILED", e));
} }
@@ -103,7 +103,7 @@ pub async fn import_profile(url: std::string::String, option: Option<PrfOption>)
pub async fn reorder_profile(active_id: std::string::String, over_id: std::string::String) -> CmdResult { pub async fn reorder_profile(active_id: std::string::String, over_id: std::string::String) -> CmdResult {
let active_id: String = active_id.into(); let active_id: String = active_id.into();
let over_id: String = over_id.into(); let over_id: String = over_id.into();
match reorder_profiles(&active_id, &over_id).await { match profiles_reorder_safe(&active_id, &over_id).await {
Ok(_) => { Ok(_) => {
logging!(info, Type::Cmd, "重新排序配置文件: {} -> {}", active_id, over_id); logging!(info, Type::Cmd, "重新排序配置文件: {} -> {}", active_id, over_id);
Ok(()) Ok(())
@@ -126,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<std::string::String>) -> CmdResult { pub async fn create_profile(item: ProfileCreate, file_data: Option<std::string::String>) -> CmdResult {
let item: PrfItem = item.into(); let item: PrfItem = item.into();
let file_data = file_data.map(String::from); let file_data = file_data.map(String::from);
match profiles::create_profile(&item, file_data).await { match profiles_append_item_with_filedata_safe(&item, file_data).await {
Ok(_) => { Ok(_) => {
save_committed_profiles() profiles_save_file_safe()
.await .await
.with_error_code("PROFILE_CREATE_FAILED")?; .with_error_code("PROFILE_CREATE_FAILED")?;
logging_error!(Type::Timer, Timer::global().refresh().await); logging_error!(Type::Timer, Timer::global().refresh().await);
@@ -159,10 +159,9 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
let profiles = Config::profiles().await; let profiles = Config::profiles().await;
let result = profiles let result = profiles
.with_data_modify::<_, _, _, anyhow::Error>(|mut candidate| async move { .with_data_modify(|mut candidate| async move {
let original = candidate.clone(); let original = candidate.clone();
let plan = candidate.plan_delete_item(&index)?; let (should_update, plan) = candidate.plan_delete_item(&index)?;
let should_update = plan.deleting_current;
let guard = if should_update { let guard = if should_update {
match CoreManager::global() match CoreManager::global()
.update_config_forced_with_profiles(&candidate, &original) .update_config_forced_with_profiles(&candidate, &original)
@@ -172,11 +171,11 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
Err(outcome) => return Ok((original, Err(outcome))), Err(outcome) => return Ok((original, Err(outcome))),
} }
} else { } else {
save_profiles(&candidate).await?; candidate.save_file().await?;
None None
}; };
let current = candidate.current.clone(); let current = candidate.current.clone();
cleanup_profile_files(plan.files).await; plan.cleanup().await;
Ok((candidate, Ok((should_update, current, guard)))) Ok((candidate, Ok((should_update, current, guard))))
}) })
.await .await
@@ -211,14 +210,18 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
Ok(()) Ok(())
} }
async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> { async fn restore_previous_profile(prev_profile: &str) -> CmdResult<()> {
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile); logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
let restore_profiles = IProfiles {
current: Some(prev_profile.into()),
items: None,
};
Config::profiles() Config::profiles()
.await .await
.edit_draft(|d| d.patch_current(Some(prev_profile))); .edit_draft(|d| d.patch_config(&restore_profiles));
Config::profiles().await.apply(); Config::profiles().await.apply();
crate::process::AsyncHandler::spawn(|| async move { crate::process::AsyncHandler::spawn(|| async move {
if let Err(e) = save_committed_profiles().await { if let Err(e) = profiles_save_file_safe().await {
logging!(warn, Type::Cmd, "异步保存恢复配置文件失败: {e:#}"); logging!(warn, Type::Cmd, "异步保存恢复配置文件失败: {e:#}");
} }
}); });
@@ -233,7 +236,10 @@ async fn commit_current_profile(profiles: &Draft<IProfiles>, current: Option<Str
profiles profiles
.with_data_modify(|mut committed| async move { .with_data_modify(|mut committed| async move {
committed.patch_current(Some(&current)); committed.patch_config(&IProfiles {
current: Some(current),
items: None,
});
Ok((committed, ())) Ok((committed, ()))
}) })
.await .await
@@ -246,7 +252,7 @@ async fn handle_success(current_value: Option<&String>) -> CmdResult<ValidationO
// Runtime refresh and tray rebuilding happen after saved node selections are restored. // Runtime refresh and tray rebuilding happen after saved node selections are restored.
profiles::activate_selected_nodes(); profiles::activate_selected_nodes();
if let Err(e) = save_committed_profiles().await { if let Err(e) = profiles_save_file_safe().await {
logging!(warn, Type::Cmd, "异步保存配置文件失败: {e:#}"); logging!(warn, Type::Cmd, "异步保存配置文件失败: {e:#}");
} }
@@ -391,12 +397,16 @@ pub async fn patch_profiles_config(profiles: ProfileSelection) -> CmdResult<Vali
}); });
let _profile_write_guard = PROFILE_WRITE_LOCK.lock().await; let _profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
let profiles = IProfiles {
current: profiles.current,
items: None,
};
let target_profile = profiles.current.as_ref(); let target_profile = profiles.current.as_ref();
let previous_profile = Config::profiles().await.data_arc().current.clone(); let previous_profile = Config::profiles().await.data_arc().current.clone();
Config::profiles().await.edit_draft(|d| { Config::profiles().await.edit_draft(|d| {
d.patch_current(target_profile); d.patch_config(&profiles);
}); });
perform_config_update(target_profile, previous_profile.as_ref()) perform_config_update(target_profile, previous_profile.as_ref())
@@ -432,7 +442,7 @@ pub async fn patch_profile(index: std::string::String, profile: ProfilePatch) ->
// Prevent an in-flight restore from overwriting a newer UI or chain selection. // Prevent an in-flight restore from overwriting a newer UI or chain selection.
let records_a_selection = profile.selected.is_some(); let records_a_selection = profile.selected.is_some();
patch_profile_item(&index, &profile) profiles_patch_item_safe(&index, &profile)
.await .await
.with_error_code("PROFILE_UPDATE_FAILED")?; .with_error_code("PROFILE_UPDATE_FAILED")?;
@@ -482,17 +492,20 @@ pub async fn view_profile(index: std::string::String) -> CmdResult {
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::string::String> { pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::string::String> {
let file = { let item = {
let profiles = Config::profiles().await; let profiles = Config::profiles().await;
let profiles_ref = profiles.latest_arc(); let profiles_ref = profiles.latest_arc();
profiles_ref PrfItem {
.get_item(&index) file: profiles_ref
.with_error_code("PROFILE_READ_FAILED")? .get_item(&index)
.file .with_error_code("PROFILE_READ_FAILED")?
.clone() .file
.to_owned(),
..Default::default()
}
}; };
if let Some(file) = file.as_ref() { if let Some(file) = item.file.as_ref() {
let path = dirs::app_profiles_dir() let path = dirs::app_profiles_dir()
.with_error_code("PROFILE_READ_FAILED")? .with_error_code("PROFILE_READ_FAILED")?
.join(file.as_str()); .join(file.as_str());
@@ -508,9 +521,7 @@ pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::str
} }
} }
let data = read_profile_item_file(file.as_deref()) let data = item.read_file().await.with_error_code("PROFILE_READ_FAILED")?;
.await
.with_error_code("PROFILE_READ_FAILED")?;
Ok(data.into()) Ok(data.into())
} }
@@ -564,11 +575,16 @@ mod tests {
current: Some("a".into()), current: Some("a".into()),
items: Some(vec![profile("a"), profile("b")]), items: Some(vec![profile("a"), profile("b")]),
}); });
profiles.edit_draft(|draft| draft.patch_current(Some(&"b".into()))); profiles.edit_draft(|draft| {
draft.patch_config(&IProfiles {
current: Some("b".into()),
items: None,
});
});
profiles profiles
.with_data_modify(|mut committed| async move { .with_data_modify(|mut committed| async move {
committed.items.get_or_insert_with(Vec::new).push(profile("new")); committed.items.get_or_insert_with(Vec::new).push(profile("new"));
Ok::<_, clash_verge_draft::DraftConflict>((committed, ())) Ok((committed, ()))
}) })
.await?; .await?;
+92 -10
View File
@@ -1,6 +1,14 @@
use super::CmdResult; use super::CmdResult;
use crate::{cmd::StringifyErr as _, config::Config, core::handle::Handle}; use crate::{
use clash_verge_proxy_view::ProxyViewV1; cmd::StringifyErr as _,
config::Config,
core::{
handle::Handle,
proxy_view::{GroupScope, ProxyViewBuilder, ProxyViewInput, ProxyViewV1},
},
};
use serde_yaml_ng::Mapping;
use std::collections::{BTreeMap, HashSet};
/// Merges one selection pair into fresh backend state to avoid stale-list overwrites. /// Merges one selection pair into fresh backend state to avoid stale-list overwrites.
#[tauri::command] #[tauri::command]
@@ -19,16 +27,90 @@ pub async fn switch_proxy_node(group_name: String, proxy_name: String, unfix: bo
.stringify_err() .stringify_err()
} }
fn runtime_group_order(config: Option<&Mapping>) -> Vec<String> {
let mut seen = HashSet::new();
config
.and_then(|config| config.get("proxy-groups"))
.and_then(|groups| groups.as_sequence())
.into_iter()
.flatten()
.filter_map(|group| group.get("name"))
.filter_map(|name| name.as_str())
.filter(|name| !name.is_empty() && *name != "GLOBAL")
.filter(|name| seen.insert(*name))
.map(str::to_owned)
.collect()
}
/// Mirrors Mihomo: `include-all`/`include-all-providers` replace `use` with every provider, sorted.
fn runtime_group_scopes(config: Option<&Mapping>) -> BTreeMap<String, GroupScope> {
let Some(config) = config else {
return BTreeMap::new();
};
let mut all_providers = config
.get("proxy-providers")
.and_then(|providers| providers.as_mapping())
.into_iter()
.flat_map(|providers| providers.keys())
.filter_map(|name| name.as_str())
.map(str::to_owned)
.collect::<Vec<_>>();
all_providers.sort();
let flag = |group: &Mapping, key: &str| group.get(key).and_then(|value| value.as_bool()) == Some(true);
config
.get("proxy-groups")
.and_then(|groups| groups.as_sequence())
.into_iter()
.flatten()
.filter_map(|group| group.as_mapping())
.filter_map(|group| {
let name = group.get("name")?.as_str()?.to_owned();
let providers = if flag(group, "include-all") || flag(group, "include-all-providers") {
all_providers.clone()
} else {
group
.get("use")
.and_then(|providers| providers.as_sequence())
.into_iter()
.flatten()
.filter_map(|provider| provider.as_str())
.map(str::to_owned)
.collect()
};
let exclude_types = group
.get("exclude-type")
.and_then(|types| types.as_str())
.filter(|types| !types.is_empty())
.map_or_default(|types| types.split('|').map(str::to_owned).collect());
Some((
name,
GroupScope {
providers,
exclude_types,
},
))
})
.collect()
}
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn get_proxy_view() -> CmdResult<ProxyViewV1> { pub async fn get_proxy_view() -> CmdResult<ProxyViewV1> {
let runtime = Config::runtime().await.latest_arc(); let runtime = Config::runtime().await;
let latest_runtime = runtime.latest_arc();
let runtime_group_order = runtime_group_order(latest_runtime.config.as_ref());
let group_scopes = runtime_group_scopes(latest_runtime.config.as_ref());
let mihomo = Handle::mihomo(); let mihomo = Handle::mihomo();
crate::feat::proxy_view::load_proxy_view( let (proxies, providers) = tokio::join!(mihomo.get_proxies(), mihomo.get_proxy_providers(),);
runtime.config.as_ref(), let proxies = proxies.stringify_err()?;
mihomo.get_proxies(),
mihomo.get_proxy_providers(), Ok(ProxyViewBuilder::build(ProxyViewInput {
) runtime_group_order,
.await group_scopes,
.stringify_err() proxies,
providers: providers.ok(),
}))
} }
+3 -7
View File
@@ -1,9 +1,5 @@
use super::CmdResult; use super::CmdResult;
use crate::{ use crate::{cmd::StringifyErr as _, config::Config, core::CoreManager, utils::yaml_emitter};
cmd::StringifyErr as _,
config::{Config, mihomo_yaml},
core::CoreManager,
};
use anyhow::{Context as _, anyhow}; use anyhow::{Context as _, anyhow};
use std::collections::HashMap; use std::collections::HashMap;
use tristr::alias::String; use tristr::alias::String;
@@ -28,7 +24,7 @@ pub async fn get_runtime_yaml() -> CmdResult<std::string::String> {
let config = runtime.config.as_ref(); let config = runtime.config.as_ref();
config config
.ok_or_else(|| anyhow!("failed to parse config to yaml file")) .ok_or_else(|| anyhow!("failed to parse config to yaml file"))
.and_then(|config| mihomo_yaml::serialize_for_export(config).context("failed to convert config to yaml")) .and_then(|config| yaml_emitter::to_mihomo_config_string(config).context("failed to convert config to yaml"))
.stringify_err() .stringify_err()
} }
@@ -91,7 +87,7 @@ pub async fn get_runtime_proxy_chain_config(
config.insert("proxies".into(), proxies_chain); config.insert("proxies".into(), proxies_chain);
mihomo_yaml::serialize_for_export(&config) yaml_emitter::to_mihomo_config_string(&config)
.context("YAML generation failed") .context("YAML generation failed")
.stringify_err() .stringify_err()
} else { } else {
+8 -2
View File
@@ -2,7 +2,7 @@ use super::CmdResult;
use crate::{ use crate::{
cmd::StringifyErr as _, cmd::StringifyErr as _,
cmd::validate::{ValidationNoticeTarget, handle_validation_notice}, cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
config::{Config, IProfiles, read_profile_item_file}, config::{Config, IProfiles, PrfItem},
core::auto_backup::{self, AutoBackupTrigger}, core::auto_backup::{self, AutoBackupTrigger},
core::{ core::{
CoreManager, handle, CoreManager, handle,
@@ -58,7 +58,13 @@ pub async fn save_profile_file(
)) ))
})?; })?;
let original_content = if original_existed { let original_content = if original_existed {
read_profile_item_file(Some(rel_path.as_str())).await.stringify_err()? PrfItem {
file: Some(rel_path.clone()),
..Default::default()
}
.read_file()
.await
.stringify_err()?
} else { } else {
String::new() String::new()
}; };
+135 -6
View File
@@ -8,7 +8,17 @@ use crate::{
}, },
}; };
async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str) -> CmdResult { #[derive(Debug, PartialEq, Eq, serde::Serialize, specta::Type)]
#[serde(tag = "status", rename_all = "camelCase")]
pub enum ServiceInstallOutcome {
Installed,
#[cfg_attr(not(any(windows, test)), allow(dead_code))]
Sidecar {
reason: String,
},
}
async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str) -> CmdResult<ServiceInstallOutcome> {
let manager = CoreManager::global(); let manager = CoreManager::global();
let result = { let result = {
let _lifecycle = manager.lifecycle_lock.lock().await; let _lifecycle = manager.lifecycle_lock.lock().await;
@@ -23,12 +33,56 @@ async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str)
} }
SERVICE_MANAGER.handle_service_status(status).await SERVICE_MANAGER.handle_service_status(status).await
}; };
result.map_err(|error| proxy_aware_coded_error(&error, error_code)) #[cfg(windows)]
return finish_service_installation(result, error_code, async |reason| {
manager.continue_with_sidecar(Some(reason)).await
})
.await;
#[cfg(not(windows))]
result
.map(|()| ServiceInstallOutcome::Installed)
.map_err(|error| proxy_aware_coded_error(&error, error_code))
}
#[cfg(any(windows, test))]
async fn finish_service_installation<Fallback>(
installation: anyhow::Result<()>,
error_code: &str,
fallback: Fallback,
) -> CmdResult<ServiceInstallOutcome>
where
Fallback: AsyncFnOnce(&str) -> anyhow::Result<()>,
{
let Err(error) = installation else {
return Ok(ServiceInstallOutcome::Installed);
};
let Some(failure) = error.downcast_ref::<clash_verge_service_ipc::management::InstallationVerificationError>()
else {
return Err(proxy_aware_coded_error(&error, error_code));
};
let reasons = failure
.status
.cores
.iter()
.filter_map(|core| match &core.availability {
clash_verge_service_ipc::CoreAvailability::Rejected { reason } => Some(format!("{}: {reason}", core.name)),
_ => None,
})
.collect::<Vec<_>>();
if reasons.is_empty() {
return Err(proxy_aware_coded_error(&error, error_code));
}
let reason = reasons.join("\n");
fallback(reason.as_str())
.await
.map_err(|error| proxy_aware_coded_error(&error, "SERVICE_SIDECAR_FAILED"))?;
Ok(ServiceInstallOutcome::Sidecar { reason })
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn install_service() -> CmdResult { pub async fn install_service() -> CmdResult<ServiceInstallOutcome> {
execute_service_operation_sync(ServiceStatus::InstallRequired, "SERVICE_INSTALL_FAILED").await execute_service_operation_sync(ServiceStatus::InstallRequired, "SERVICE_INSTALL_FAILED").await
} }
@@ -43,13 +97,13 @@ pub async fn uninstall_service() -> CmdResult {
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn reinstall_service() -> CmdResult { pub async fn reinstall_service() -> CmdResult<ServiceInstallOutcome> {
execute_service_operation_sync(ServiceStatus::ReinstallRequired, "SERVICE_REINSTALL_FAILED").await execute_service_operation_sync(ServiceStatus::ReinstallRequired, "SERVICE_REINSTALL_FAILED").await
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn repair_service() -> CmdResult { pub async fn repair_service() -> CmdResult<ServiceInstallOutcome> {
execute_service_operation_sync(ServiceStatus::ForceReinstallRequired, "SERVICE_REPAIR_FAILED").await execute_service_operation_sync(ServiceStatus::ForceReinstallRequired, "SERVICE_REPAIR_FAILED").await
} }
@@ -57,7 +111,7 @@ pub async fn repair_service() -> CmdResult {
#[specta::specta] #[specta::specta]
pub async fn continue_with_sidecar() -> CmdResult { pub async fn continue_with_sidecar() -> CmdResult {
crate::core::CoreManager::global() crate::core::CoreManager::global()
.continue_with_sidecar() .continue_with_sidecar(None)
.await .await
.map_err(|error| proxy_aware_coded_error(&error, "SERVICE_SIDECAR_FAILED")) .map_err(|error| proxy_aware_coded_error(&error, "SERVICE_SIDECAR_FAILED"))
} }
@@ -68,6 +122,12 @@ pub fn get_sidecar_failure() -> crate::core::notification::SidecarFailureSnapsho
crate::core::notification::sidecar_failure_snapshot() crate::core::notification::sidecar_failure_snapshot()
} }
#[tauri::command]
#[specta::specta]
pub fn take_service_fallback_notice() -> Option<crate::core::service::ServiceFallbackNotice> {
crate::core::service::take_service_fallback_notice()
}
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub fn get_core_startup_error() -> Option<crate::core::manager::CoreFailure> { pub fn get_core_startup_error() -> Option<crate::core::manager::CoreFailure> {
@@ -93,3 +153,72 @@ pub fn sync_runtime_providers() {
request_runtime_provider_sync(timing::RUNTIME_PROVIDER_SETTLE); request_runtime_provider_sync(timing::RUNTIME_PROVIDER_SETTLE);
} }
} }
#[cfg(test)]
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
mod tests {
use super::{ServiceInstallOutcome, finish_service_installation};
use clash_verge_service_ipc::{
CoreAvailability, CoreInspection, InstallationStatus, ProtocolInfo, management::InstallationVerificationError,
};
use std::cell::Cell;
#[tokio::test]
async fn rejected_installation_reports_sidecar_only_after_successful_continuation() {
let reason = "core path C:\\ is writable by Everyone";
for (availability, fallback_ready) in [
(None, false),
(Some(CoreAvailability::Missing), false),
(Some(CoreAvailability::DigestMismatch), false),
(Some(CoreAvailability::Rejected { reason: reason.into() }), false),
(Some(CoreAvailability::Rejected { reason: reason.into() }), true),
] {
let fallback_called = Cell::new(false);
let rejected = matches!(&availability, Some(CoreAvailability::Rejected { .. }));
let error = match availability {
Some(availability) => anyhow::Error::new(InstallationVerificationError {
status: InstallationStatus {
service_sha256: String::new(),
protocol: ProtocolInfo::current(),
cores: vec![CoreInspection {
name: "verge-mihomo.exe".into(),
availability,
}],
core_busy: false,
},
}),
None => anyhow::anyhow!("{reason}"),
}
.context("install service failed");
let result = finish_service_installation(Err(error), "SERVICE_INSTALL_FAILED", async |_| {
fallback_called.set(true);
anyhow::ensure!(fallback_ready, "another core is running");
Ok(())
})
.await;
assert_eq!(fallback_called.get(), rejected);
if rejected && fallback_ready {
assert_eq!(
result,
Ok(ServiceInstallOutcome::Sidecar {
reason: format!("verge-mihomo.exe: {reason}")
})
);
} else {
let error = result.expect_err("an unavailable fallback must remain an error");
assert_eq!(
error.code.as_deref(),
Some(if rejected {
"SERVICE_SIDECAR_FAILED"
} else {
"SERVICE_INSTALL_FAILED"
})
);
if rejected {
assert!(error.detail.contains("another core is running"));
}
}
}
}
}
+1 -4
View File
@@ -1,4 +1,3 @@
use super::mihomo_yaml;
use crate::constants::{network, tun as tun_const}; use crate::constants::{network, tun as tun_const};
use crate::utils::dirs::{path_to_str, sidecar_ipc_path}; use crate::utils::dirs::{path_to_str, sidecar_ipc_path};
use crate::utils::{dirs, help}; use crate::utils::{dirs, help};
@@ -151,9 +150,7 @@ impl IClashTemp {
} }
pub async fn save_config(&self) -> Result<()> { pub async fn save_config(&self) -> Result<()> {
let path = dirs::clash_path()?; help::save_yaml(&dirs::clash_path()?, &self.0, Some("# Generated by Clash Verge")).await
let yaml = mihomo_yaml::serialize(&self.0)?;
help::save_yaml_str(&path, &yaml, Some("# Generated by Clash Verge")).await
} }
pub fn get_mixed_port(&self) -> u16 { pub fn get_mixed_port(&self) -> u16 {
+11 -15
View File
@@ -1,16 +1,13 @@
use super::{IClashTemp, IProfiles, IVerge, MixedPort, mihomo_yaml}; use super::{IClashTemp, IProfiles, IVerge, MixedPort};
use crate::core::notify::NoticeStatus; use crate::core::notify::NoticeStatus;
use crate::{ use crate::{
config::{ config::{PrfItem, profiles_append_item_to_safe, runtime::IRuntime},
prfitem::{build_merge_profile, build_script_profile},
profiles::{append_to_profile_index, load_profiles, save_profiles},
runtime::IRuntime,
},
constants::{files, timing}, constants::{files, timing},
core::{ core::{
CoreManager, CoreManager,
handle::{self, Handle}, handle::{self, Handle},
listener::MIXED_PORT_KEY, listener::MIXED_PORT_KEY,
runtime_bundle::resolve_provider_path_conflicts,
tray, tray,
validate::CoreConfigValidator, validate::CoreConfigValidator,
}, },
@@ -22,7 +19,6 @@ use anyhow::{Result, anyhow};
use backon::{ExponentialBuilder, Retryable as _}; use backon::{ExponentialBuilder, Retryable as _};
use clash_verge_draft::Draft; use clash_verge_draft::Draft;
use clash_verge_logging::{Type, logging, logging_error}; use clash_verge_logging::{Type, logging, logging_error};
use clash_verge_runtime_bundle::resolve_provider_path_conflicts;
use serde_yaml_ng::{Mapping, Value}; use serde_yaml_ng::{Mapping, Value};
use std::{collections::HashSet, path::PathBuf}; use std::{collections::HashSet, path::PathBuf};
use tokio::sync::{Mutex, MutexGuard, OnceCell}; use tokio::sync::{Mutex, MutexGuard, OnceCell};
@@ -49,7 +45,7 @@ impl Config {
Self { Self {
clash_config: Draft::new(IClashTemp::new().await), clash_config: Draft::new(IClashTemp::new().await),
verge_config: Draft::new(IVerge::new().await), verge_config: Draft::new(IVerge::new().await),
profiles_config: Draft::new(load_profiles().await), profiles_config: Draft::new(IProfiles::new().await),
runtime_config: Draft::new(IRuntime::default()), runtime_config: Draft::new(IRuntime::default()),
} }
}) })
@@ -141,12 +137,12 @@ impl Config {
} }
if profiles.latest_arc().get_item("Merge").is_err() { if profiles.latest_arc().get_item("Merge").is_err() {
let merge_item = &mut build_merge_profile(Some("Merge".into())); let merge_item = &mut PrfItem::from_merge(Some("Merge".into()));
append_to_profile_index(&profiles, merge_item).await?; profiles_append_item_to_safe(&profiles, merge_item).await?;
} }
if profiles.latest_arc().get_item("Script").is_err() { if profiles.latest_arc().get_item("Script").is_err() {
let script_item = &mut build_script_profile(Some("Script".into())); let script_item = &mut PrfItem::from_script(Some("Script".into()));
append_to_profile_index(&profiles, script_item).await?; profiles_append_item_to_safe(&profiles, script_item).await?;
} }
Ok(()) Ok(())
} }
@@ -230,7 +226,7 @@ impl Config {
{ {
return Ok(std::sync::Arc::clone(cached)); return Ok(std::sync::Arc::clone(cached));
} }
let yaml_str = std::sync::Arc::new(mihomo_yaml::serialize(config)?); let yaml_str = std::sync::Arc::new(serde_yaml_ng::to_string(config)?);
*RUNTIME_YAML_CACHE.lock() = Some((key, std::sync::Arc::clone(&yaml_str))); *RUNTIME_YAML_CACHE.lock() = Some((key, std::sync::Arc::clone(&yaml_str)));
Ok(yaml_str) Ok(yaml_str)
}) })
@@ -250,7 +246,7 @@ impl Config {
} }
pub(crate) async fn generate_with_profiles(profiles: &IProfiles) -> Result<()> { pub(crate) async fn generate_with_profiles(profiles: &IProfiles) -> Result<()> {
let (mut config, exists_keys, logs, dns_override) = enhance::render_runtime_config(profiles).await?; let (mut config, exists_keys, logs, dns_override) = enhance::enhance(profiles).await?;
resolve_provider_path_conflicts(&mut config, &dirs::app_home_dir()?)?; resolve_provider_path_conflicts(&mut config, &dirs::app_home_dir()?)?;
sanitize_tunnels_proxy(&mut config); sanitize_tunnels_proxy(&mut config);
@@ -314,7 +310,7 @@ impl Config {
let _profile_write = super::profiles::PROFILE_WRITE_LOCK.lock().await; let _profile_write = super::profiles::PROFILE_WRITE_LOCK.lock().await;
let profiles = Self::profiles().await; let profiles = Self::profiles().await;
profiles.apply(); profiles.apply();
logging_error!(Type::Config, save_profiles(&profiles.data_arc()).await); logging_error!(Type::Config, profiles.data_arc().save_file().await);
}); });
let _ = tokio::join!(save_clash_task, save_verge_task, save_profiles_task); let _ = tokio::join!(save_clash_task, save_verge_task, save_profiles_task);
+1 -6
View File
@@ -3,7 +3,6 @@ mod clash;
mod config; mod config;
pub(crate) mod dns; pub(crate) mod dns;
mod encrypt; mod encrypt;
pub(crate) mod mihomo_yaml;
mod mixed_port; mod mixed_port;
mod port; mod port;
mod prfitem; mod prfitem;
@@ -13,11 +12,7 @@ pub(crate) mod snapshot;
mod verge; mod verge;
pub(crate) use self::config::Config; pub(crate) use self::config::Config;
pub(crate) use self::prfitem::{ pub use self::{clash::*, encrypt::*, mixed_port::*, prfitem::*, profiles::*, verge::*};
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};
macro_rules! patch_opt_field { macro_rules! patch_opt_field {
($lv:expr, $rv:expr, $key:tt) => { ($lv:expr, $rv:expr, $key:tt) => {
+462 -351
View File
@@ -1,4 +1,4 @@
use super::{PrfExtra, PrfItem, PrfOption}; use super::patch_opt_field;
use crate::{ use crate::{
config::profiles, config::profiles,
@@ -9,7 +9,8 @@ use crate::{
}, },
}; };
use anyhow::{Context as _, Result, bail}; 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 std::time::Duration;
use tokio::fs; use tokio::fs;
use tristr::alias::String; use tristr::alias::String;
@@ -17,285 +18,476 @@ use tristr::alias::String;
use reqwest_dav::re_exports::url::form_urlencoded; use reqwest_dav::re_exports::url::form_urlencoded;
use tauri::Url; use tauri::Url;
/// Builds an item from a partial value that must include `itype`. pub(super) fn normalize_profile_home_url(raw: &str) -> Option<String> {
pub(super) async fn build_profile(item: &PrfItem, file_data: Option<String>) -> Result<PrfItem> { let url = Url::parse(raw.trim()).ok()?;
let itype = item
.itype if !matches!(url.scheme(), "http" | "https") {
.as_ref() return None;
.ok_or_else(|| anyhow::anyhow!("type should not be null"))?; }
match itype.as_str() {
"remote" => { url.host_str()?;
let url = item Some(url.as_str().into())
.url }
.as_ref()
.ok_or_else(|| anyhow::anyhow!("url should not be null"))?; #[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)]
let name = item.name.as_ref(); #[serde(default)]
let desc = item.desc.as_ref(); pub struct PrfItem {
let option = item.option.as_ref(); pub uid: Option<String>,
build_remote_profile(url, name, desc, option).await
/// enum value: remote | local | script | merge
#[serde(rename = "type")]
pub itype: Option<String>,
pub name: Option<String>,
pub file: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub desc: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub selected: Option<Vec<PrfSelected>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub extra: Option<PrfExtra>,
pub updated: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub option: Option<PrfOption>,
#[serde(skip_serializing_if = "Option::is_none")]
pub home: Option<String>,
#[serde(skip)]
pub file_data: Option<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)]
#[serde(default)]
pub struct PrfSelected {
pub name: Option<String>,
pub now: Option<String>,
}
#[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<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub with_proxy: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub self_proxy: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub update_interval: Option<u64>,
/// HTTP request timeout in seconds
/// default is 60 seconds
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout_seconds: Option<u64>,
/// default is `false`
#[serde(skip_serializing_if = "Option::is_none")]
pub danger_accept_invalid_certs: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_auto_update: Option<bool>,
pub merge: Option<String>,
pub script: Option<String>,
pub rules: Option<String>,
pub proxies: Option<String>,
pub groups: Option<String>,
}
impl PrfOption {
pub(crate) fn merge(one: Option<&Self>, other: Option<&Self>) -> Option<Self> {
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,
} }
"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(); impl PrfItem {
from_local(name, desc, file_data, option).await /// Builds an item from a partial value that must include `itype`.
pub(super) async fn from(item: &Self, file_data: Option<String>) -> Result<Self> {
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}\""),
} }
typ => bail!("invalid profile item type \"{typ}\""), }
async fn append_companion_item(item: &mut Self) -> Result<String> {
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<String>,
script: &mut Option<String>,
rules: &mut Option<String>,
proxies: &mut Option<String>,
groups: &mut Option<String>,
) -> 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<String>,
option: Option<&PrfOption>,
) -> Result<Self> {
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<Self> {
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 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::<String>(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::<String>(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::<u64>() {
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 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::<Mapping>(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`");
}
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,
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(data.into()),
})
}
pub(super) fn from_merge(uid: Option<String>) -> 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<String>) -> 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<String> {
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<String> { macro_rules! current_field {
profiles::append_profile(item).await?; ($name:ident, $field:ident) => {
item.uid pub(crate) fn $name(&self) -> Option<&String> {
.clone() self.option.as_ref().and_then(|o| o.$field.as_ref())
.ok_or_else(|| anyhow::anyhow!("appended companion item has no uid"))
}
async fn prepare_profile_options(source: Option<&PrfOption>) -> Result<PrfOption> {
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 options.script.is_none() {
options.script = Some(append_companion_item(&mut build_script_profile(None)).await?);
}
if options.rules.is_none() {
options.rules = Some(append_companion_item(&mut from_rules()).await?);
}
if options.proxies.is_none() {
options.proxies = Some(append_companion_item(&mut from_proxies()).await?);
}
if options.groups.is_none() {
options.groups = Some(append_companion_item(&mut from_groups()).await?);
}
Ok(options)
}
async fn from_local(
name: String,
desc: String,
file_data: Option<String>,
option: Option<&PrfOption>,
) -> Result<PrfItem> {
let uid = help::get_uid("L").into();
let file = format!("{uid}.yaml").into();
let options = prepare_profile_options(option).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(options),
home: None,
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(file_data.unwrap_or_else(|| tmpl::ITEM_LOCAL.into())),
})
}
pub(crate) struct DownloadedSubscription {
url: Url,
suggested_name: Option<std::string::String>,
extra: Option<PrfExtra>,
update_interval_minutes: Option<u64>,
home: Option<String>,
body: String,
}
pub(crate) struct RemoteProfileRefresh {
pub(super) extra: Option<PrfExtra>,
pub(super) home: Option<String>,
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<PrfItem> {
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
.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) fn subscription_proxy(options: Option<&PrfOption>) -> ProxyType {
if options.and_then(|options| options.self_proxy) == Some(true) {
ProxyType::Localhost
} 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<DownloadedSubscription> {
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, Some(timeout), user_agent, 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 extra = document.usage.map(|usage| PrfExtra {
upload: usage.upload,
download: usage.download,
total: usage.total,
expire: usage.expire,
});
Ok(DownloadedSubscription {
suggested_name: document.filename,
update_interval_minutes: document.update_interval_minutes,
home: document.home.map(Into::into),
body: document.body.into(),
url,
extra,
})
} }
pub(crate) async fn prepare_remote_refresh( impl PrfItem {
downloaded: DownloadedSubscription, current_field!(current_merge, merge);
option: Option<&PrfOption>, current_field!(current_script, script);
) -> Result<RemoteProfileRefresh> { current_field!(current_rules, rules);
let mut options = prepare_profile_options(option).await?; current_field!(current_proxies, proxies);
options.update_interval = options.update_interval.or(downloaded.update_interval_minutes); current_field!(current_groups, groups);
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: options,
body: downloaded.body,
})
} }
pub(super) fn build_merge_profile(uid: Option<String>) -> PrfItem { fn allow_auto_update_enabled(option: Option<&PrfOption>) -> bool {
let (id, template) = if let Some(uid) = uid { option.and_then(|o| o.allow_auto_update).unwrap_or(true)
(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<String>) -> 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<String> {
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())
} }
/// Fix URLs where query parameters are incorrectly appended to the path segment /// Fix URLs where query parameters are incorrectly appended to the path segment
@@ -326,84 +518,3 @@ fn fix_dirty_url(input: &str) -> Result<Url> {
Ok(url) Ok(url)
} }
#[cfg(test)]
mod tests {
use super::*;
use tokio::{
io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader},
net::TcpListener,
};
#[tokio::test]
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 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()
);
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),
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 = build_remote_profile(&url, None, None, Some(&option)).await?;
let refresh_option = PrfOption {
update_interval: None,
..option
};
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"));
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));
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(())
}
}
File diff suppressed because it is too large Load Diff
+37
View File
@@ -2,6 +2,10 @@ use serde_yaml_ng::{Mapping, Value};
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use tristr::alias::String; use tristr::alias::String;
use crate::enhance::field::use_keys;
const PATCH_CONFIG_INNER: [&str; 5] = ["allow-lan", "ipv6", "log-level", "unified-delay", "tunnels"];
#[derive(Default, Clone)] #[derive(Default, Clone)]
pub struct IRuntime { pub struct IRuntime {
pub config: Option<Mapping>, pub config: Option<Mapping>,
@@ -13,6 +17,39 @@ pub struct IRuntime {
} }
impl IRuntime { impl IRuntime {
#[inline]
pub fn patch_config(&mut self, patch: &Mapping) {
let config = if let Some(config) = self.config.as_mut() {
config
} else {
return;
};
for key in PATCH_CONFIG_INNER.iter() {
if let Some(value) = patch.get(key) {
config.insert((*key).into(), value.clone());
}
}
let Some(patch_tun) = patch.get("tun") else {
return;
};
let tun_key = Value::from("tun");
if !matches!(config.get(&tun_key), Some(Value::Mapping(_))) {
config.insert(tun_key.clone(), Value::Mapping(Mapping::new()));
}
if let (Some(patch_tun_mapping), Some(Value::Mapping(tun))) = (patch_tun.as_mapping(), config.get_mut(&tun_key))
{
for key in use_keys(patch_tun_mapping) {
if let Some(value) = patch_tun_mapping.get(key.as_str()) {
tun.insert(Value::from(key.as_str()), value.clone());
}
}
}
}
/// Rebuilds `dialer-proxy` links from an ordered proxy chain, or removes them for `None`. /// Rebuilds `dialer-proxy` links from an ordered proxy chain, or removes them for `None`.
#[inline] #[inline]
pub fn update_proxy_chain_config(&mut self, proxy_chain_config: Option<Value>) { pub fn update_proxy_chain_config(&mut self, proxy_chain_config: Option<Value>) {
+17
View File
@@ -64,5 +64,22 @@ pub mod files {
pub mod tun { pub mod tun {
pub const DEFAULT_STACK: &str = "mips"; pub const DEFAULT_STACK: &str = "mips";
pub const DEFAULT_MTU: u16 = 1500;
pub const DNS_HIJACK: &[&str] = &["any:53"]; pub const DNS_HIJACK: &[&str] = &["any:53"];
/// Saved dialog fields; `enable` belongs to the verge switch.
pub const GUI_KEYS: &[&str] = &[
"stack",
"device",
"auto-route",
"route-exclude-address",
#[cfg(target_os = "linux")]
"auto-redirect",
"auto-detect-interface",
"dns-hijack",
"dns-mode",
"strict-route",
"mtu",
];
} }
+1 -1
View File
@@ -20,7 +20,7 @@ pub async fn update_launch() -> Result<()> {
use clash_verge_logging::logging_error; use clash_verge_logging::logging_error;
use tauri_plugin_autostart::ManagerExt as _; use tauri_plugin_autostart::ManagerExt as _;
let autostart_manager = app_handle.autolaunch(); let autostart_manager = app_handle.autostart();
if is_enable { if is_enable {
logging_error!(Type::System, "{:?}", autostart_manager.enable()); logging_error!(Type::System, "{:?}", autostart_manager.enable());
} else { } else {
+16 -18
View File
@@ -3,7 +3,6 @@ use crate::{config::Config, process::AsyncHandler, utils::dirs};
use anyhow::Error; use anyhow::Error;
use arc_swap::{ArcSwap, ArcSwapOption}; use arc_swap::{ArcSwap, ArcSwapOption};
use backon::{ConstantBuilder, Retryable as _}; use backon::{ConstantBuilder, Retryable as _};
use clash_verge_backup_archive::BackupWriter;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use reqwest_dav::list_cmd::{ListEntity, ListFile, ListMultiStatus}; use reqwest_dav::list_cmd::{ListEntity, ListFile, ListMultiStatus};
use std::{ use std::{
@@ -16,6 +15,7 @@ use std::{
}; };
use tokio::{fs, time::timeout}; use tokio::{fs, time::timeout};
use tristr::alias::String; use tristr::alias::String;
use zip::write::SimpleFileOptions;
const APP_VERSION: &str = env!("CARGO_PKG_VERSION"); const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
@@ -275,7 +275,9 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
let value = zip_path.clone(); let value = zip_path.clone();
let file = AsyncHandler::spawn_blocking(move || std::fs::File::create(&value)).await??; let file = AsyncHandler::spawn_blocking(move || std::fs::File::create(&value)).await??;
let mut archive = BackupWriter::new(file)?; let mut zip = zip::ZipWriter::new(file);
zip.add_directory("profiles/", SimpleFileOptions::default())?;
let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
if let Ok(mut entries) = fs::read_dir(dirs::app_profiles_dir()?).await { if let Ok(mut entries) = fs::read_dir(dirs::app_profiles_dir()?).await {
while let Some(entry) = entries.next_entry().await? { while let Some(entry) = entries.next_entry().await? {
@@ -285,16 +287,15 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
let file_name = file_name_os let file_name = file_name_os
.to_str() .to_str()
.ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?; .ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?;
let mut entry = archive.start_profile(file_name)?; let backup_path = format!("profiles/{}", file_name);
zip.start_file(backup_path, options)?;
let file_content = fs::read(&path).await?; let file_content = fs::read(&path).await?;
entry.write_all(&file_content)?; zip.write_all(&file_content)?;
} }
} }
} }
zip.start_file(dirs::CLASH_CONFIG, options)?;
archive zip.write_all(fs::read(dirs::clash_path()?).await?.as_slice())?;
.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 verge_text = fs::read_to_string(dirs::verge_path()?).await?;
let mut verge_config: serde_json::Value = serde_yaml_ng::from_str(&verge_text)?; let mut verge_config: serde_json::Value = serde_yaml_ng::from_str(&verge_text)?;
@@ -303,20 +304,17 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
obj.remove("webdav_password"); obj.remove("webdav_password");
obj.remove("webdav_url"); obj.remove("webdav_url");
} }
archive zip.start_file(dirs::VERGE_CONFIG, options)?;
.start_file(dirs::VERGE_CONFIG)? zip.write_all(serde_yaml_ng::to_string(&verge_config)?.as_bytes())?;
.write_all(serde_yaml_ng::to_string(&verge_config)?.as_bytes())?;
let dns_config_path = dirs::app_home_dir()?.join(DNS_CONFIG); let dns_config_path = dirs::app_home_dir()?.join(DNS_CONFIG);
if dns_config_path.exists() { if dns_config_path.exists() {
archive zip.start_file(DNS_CONFIG, options)?;
.start_file(DNS_CONFIG)? zip.write_all(fs::read(&dns_config_path).await?.as_slice())?;
.write_all(&fs::read(&dns_config_path).await?)?;
} }
archive zip.start_file(dirs::PROFILE_YAML, options)?;
.start_file(dirs::PROFILE_YAML)? zip.write_all(fs::read(dirs::profiles_path()?).await?.as_slice())?;
.write_all(&fs::read(dirs::profiles_path()?).await?)?; zip.finish()?;
archive.finish()?;
Ok((zip_file_name, zip_path)) Ok((zip_file_name, zip_path))
} }
+2 -6
View File
@@ -3,11 +3,7 @@ use crate::process::AsyncHandler;
use crate::singleton; use crate::singleton;
use crate::utils::notification::{NotificationEvent, notify_event}; use crate::utils::notification::{NotificationEvent, notify_event};
use crate::utils::window_manager::WindowManager; use crate::utils::window_manager::WindowManager;
use crate::{ use crate::{config::Config, core::handle, core::lightweight::entry_lightweight_mode, feat};
config::Config,
core::{CoreManager, handle, lightweight::entry_lightweight_mode},
feat,
};
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use arc_swap::ArcSwap; use arc_swap::ArcSwap;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
@@ -169,7 +165,7 @@ impl Hotkey {
}); });
} }
HotkeyFunction::ReactivateProfiles => { HotkeyFunction::ReactivateProfiles => {
AsyncHandler::spawn(async move || match CoreManager::global().update_config_forced().await { AsyncHandler::spawn(async move || match feat::enhance_profiles().await {
Ok(outcome) if outcome.is_valid() => { Ok(outcome) if outcome.is_valid() => {
handle::Handle::refresh_clash(); handle::Handle::refresh_clash();
notify_event(NotificationEvent::ProfilesReactivated).await; notify_event(NotificationEvent::ProfilesReactivated).await;
+8 -9
View File
@@ -2,7 +2,7 @@ use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
use crate::core::notify::NoticeStatus; use crate::core::notify::NoticeStatus;
use crate::core::service::StageRequest; use crate::core::service::StageRequest;
use crate::{ use crate::{
config::{Config, IProfiles, mihomo_yaml, profiles::save_profiles, runtime::IRuntime}, config::{Config, IProfiles, runtime::IRuntime},
constants::timing, constants::timing,
core::{ core::{
handle, handle,
@@ -88,8 +88,8 @@ fn plan_config_application(attempt: &StageAttempt) -> ConfigApplication {
} }
} }
async fn ask_to_stage(path: &std::path::Path, session: &clash_verge_service_ipc::OwnerSessionProof) -> StageAttempt { async fn ask_to_stage(path: &std::path::Path) -> StageAttempt {
match crate::core::service::stage_runtime_by_service(path, session).await { match crate::core::service::stage_runtime_by_service(path).await {
Ok(StageRequest::Answered(outcome)) => StageAttempt::Answered(outcome), Ok(StageRequest::Answered(outcome)) => StageAttempt::Answered(outcome),
Ok(StageRequest::Refused { code, message }) => { Ok(StageRequest::Refused { code, message }) => {
let message = message.into(); let message = message.into();
@@ -170,8 +170,7 @@ impl CoreManager {
} }
}); });
let yaml = mihomo_yaml::serialize(clash_config)?; help::save_yaml(&runtime_path, &clash_config, Some("# Clash Verge Runtime")).await?;
help::save_yaml_str(&runtime_path, &yaml, Some("# Clash Verge Runtime")).await?;
handle::Handle::notice(status, message); handle::Handle::notice(status, message);
Ok(()) Ok(())
} }
@@ -244,7 +243,7 @@ impl CoreManager {
crate::config::profiles::restore_selected_nodes().await; crate::config::profiles::restore_selected_nodes().await;
return Ok(Err(outcome)); return Ok(Err(outcome));
} }
match save_profiles(candidate).await { match candidate.save_file().await {
Ok(()) => { Ok(()) => {
tracing::Span::current().record("outcome", "committed"); tracing::Span::current().record("outcome", "committed");
Ok(Ok(guard)) Ok(Ok(guard))
@@ -433,10 +432,10 @@ impl CoreManager {
} }
async fn attempt_staging(&self, path: &std::path::Path) -> StageAttempt { async fn attempt_staging(&self, path: &std::path::Path) -> StageAttempt {
let Ok(session) = crate::core::service::active_service_session() else { if !crate::core::service::active_service_supports_runtime_staging() {
return StageAttempt::Unsupported; return StageAttempt::Unsupported;
}; }
stage_with_confirmation(timing::STAGE_CONFIRM_TIMEOUT, || ask_to_stage(path, &session)).await stage_with_confirmation(timing::STAGE_CONFIRM_TIMEOUT, || ask_to_stage(path)).await
} }
/// Reload the Core from `path`, and replace the Core if it will not take it. /// Reload the Core from `path`, and replace the Core if it will not take it.
+174 -15
View File
@@ -188,6 +188,48 @@ where
apply_proxy().await apply_proxy().await
} }
#[cfg(any(target_os = "windows", test))]
async fn run_service_start_with_sidecar_fallback<Start, StartFuture, Check, CheckFuture, Fallback, FallbackFuture>(
start_service: Start,
confirm_idle: Check,
start_sidecar: Fallback,
record_unavailable: impl FnOnce(std::string::String),
) -> Result<()>
where
Start: FnOnce() -> StartFuture,
StartFuture: std::future::Future<Output = Result<()>>,
Check: FnOnce() -> CheckFuture,
CheckFuture: std::future::Future<Output = Result<()>>,
Fallback: FnOnce(anyhow::Error) -> FallbackFuture,
FallbackFuture: std::future::Future<Output = Result<()>>,
{
let Err(error) = start_service().await else {
return Ok(());
};
let refusal = error.downcast_ref::<crate::core::service::ServiceStartRefusal>();
let location_refused = refusal.is_some_and(|refusal| {
refusal.code == clash_verge_service_ipc::ServiceErrorCode::InvalidInstallLocation as u16
});
if refusal.is_some() && !location_refused {
return Err(error);
}
// A lost start response can hide a running core; the shared check must resolve occupancy.
if let Err(probe_error) = confirm_idle().await {
let error = error.context(format!("Sidecar fallback was not safe: {probe_error:#}"));
record_unavailable(format!("{error:#}"));
return Err(error);
}
logging!(
warn,
Type::Core,
"Service could not start the core; falling back to Sidecar: {error:#}"
);
let reason = format!("{error:#}");
start_sidecar(error)
.await
.map_err(|error| error.context(format!("Sidecar fallback failed after Service failure: {reason}")))
}
async fn run_sidecar_termination_transition<Clear, ClearFuture, Terminate, TerminateFuture>( async fn run_sidecar_termination_transition<Clear, ClearFuture, Terminate, TerminateFuture>(
clear_proxy: Clear, clear_proxy: Clear,
terminate_sidecar: Terminate, terminate_sidecar: Terminate,
@@ -284,7 +326,11 @@ where
start_sidecar().await start_sidecar().await
} }
fn report_sidecar_failure(error: anyhow::Error) -> anyhow::Error { fn report_sidecar_failure(error: anyhow::Error, service_rejection: Option<&str>) -> anyhow::Error {
let error = match service_rejection {
Some(reason) => error.context(format!("Service core rejected: {reason}; Sidecar fallback failed")),
None => error,
};
// Proxy failures have their own pending state and recovery dialog. // Proxy failures have their own pending state and recovery dialog.
if SysproxyFailure::from_chain(&error).is_none() { if SysproxyFailure::from_chain(&error).is_none() {
crate::core::notification::record_sidecar_failure(format!("{error:#}").into()); crate::core::notification::record_sidecar_failure(format!("{error:#}").into());
@@ -322,11 +368,12 @@ impl CoreManager {
} }
#[tracing::instrument(skip_all, level = "info", fields(status = tracing::field::Empty, tun_disabled = false, readiness_generation = tracing::field::Empty))] #[tracing::instrument(skip_all, level = "info", fields(status = tracing::field::Empty, tun_disabled = false, readiness_generation = tracing::field::Empty))]
pub async fn continue_with_sidecar(&self) -> Result<()> { pub async fn continue_with_sidecar(&self, service_rejection: Option<&str>) -> Result<()> {
if !self.try_start_config_update() { if !self.try_start_config_update() {
return Err(report_sidecar_failure(anyhow::anyhow!( return Err(report_sidecar_failure(
"configuration update is already running" anyhow::anyhow!("configuration update is already running"),
))); service_rejection,
));
} }
let _config_update = DropGuard::new((), |()| { let _config_update = DropGuard::new((), |()| {
self.finish_config_update(); self.finish_config_update();
@@ -343,8 +390,11 @@ impl CoreManager {
if !can_allow_sidecar_for_session(&mode, &status) { if !can_allow_sidecar_for_session(&mode, &status) {
anyhow::bail!("Sidecar continuation is not allowed from {mode:?} / {status:?}"); anyhow::bail!("Sidecar continuation is not allowed from {mode:?} / {status:?}");
} }
#[cfg(target_os = "windows")]
if matches!(*mode, RunningMode::NotRunning) { if matches!(*mode, RunningMode::NotRunning) {
crate::core::service::release_service_core_for_sidecar().await?; clash_verge_service_ipc::execution::check_sidecar_available()
.await
.map_err(super::state::explain_core_occupancy)?;
} }
if !matches!(status, ServiceStatus::SidecarAllowed) { if !matches!(status, ServiceStatus::SidecarAllowed) {
SERVICE_MANAGER.allow_sidecar_for_session()?; SERVICE_MANAGER.allow_sidecar_for_session()?;
@@ -397,7 +447,7 @@ impl CoreManager {
Ok(()) Ok(())
} }
.await; .await;
result.map_err(report_sidecar_failure) result.map_err(|error| report_sidecar_failure(error, service_rejection))
} }
#[tracing::instrument(skip_all, level = "info", fields(readiness_generation = tracing::field::Empty))] #[tracing::instrument(skip_all, level = "info", fields(readiness_generation = tracing::field::Empty))]
@@ -413,7 +463,6 @@ impl CoreManager {
let _life = self.lifecycle_lock.lock().await; let _life = self.lifecycle_lock.lock().await;
self.controlled_stop_core_inner().await?; self.controlled_stop_core_inner().await?;
crate::core::service::release_service_core_for_sidecar().await?;
let result = run_uninstall_transition( let result = run_uninstall_transition(
|| async { || async {
@@ -589,6 +638,8 @@ impl CoreManager {
self.rollback_failed_start().await; self.rollback_failed_start().await;
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
crate::utils::resolve::dns::sync_public_dns().await; crate::utils::resolve::dns::sync_public_dns().await;
#[cfg(target_os = "windows")]
self.try_sidecar_after_service_unavailable().await?;
return Ok(()); return Ok(());
} }
if Handle::global().is_exiting() { if Handle::global().is_exiting() {
@@ -597,15 +648,27 @@ impl CoreManager {
} }
let result = match startup { let result = match startup {
StartupDecision::Service => self.start_core_by_service().await.inspect_err(|error| { StartupDecision::Service => {
if error #[cfg(target_os = "windows")]
.downcast_ref::<crate::core::service::ServiceStartRefusal>()
.is_none()
{ {
crate::core::runstate::RUN_STATE run_service_start_with_sidecar_fallback(
.observe(crate::core::runstate::ServiceHealth::Unavailable(format!("{error:#}"))); || self.start_core_by_service(),
|| async {
clash_verge_service_ipc::execution::check_sidecar_available()
.await
.map_err(super::state::explain_core_occupancy)
},
|error| self.start_sidecar_after_service_failure(error),
|reason| {
crate::core::runstate::RUN_STATE
.observe(crate::core::runstate::ServiceHealth::Unavailable(reason));
},
)
.await
} }
}), #[cfg(not(target_os = "windows"))]
self.start_core_by_service().await
}
StartupDecision::Sidecar => self.start_core_by_sidecar().await, StartupDecision::Sidecar => self.start_core_by_sidecar().await,
StartupDecision::Wait => Ok(()), StartupDecision::Wait => Ok(()),
}; };
@@ -621,6 +684,53 @@ impl CoreManager {
result result
} }
#[cfg(target_os = "windows")]
async fn try_sidecar_after_service_unavailable(&self) -> Result<()> {
use crate::core::runstate::{RUN_STATE, ServiceHealth};
let state = RUN_STATE.state();
if state.pending.is_some() || state.op_in_flight || Handle::global().is_exiting() {
return Ok(());
}
let reason = match state.health {
ServiceHealth::Unavailable(reason) => reason,
ServiceHealth::VersionMismatch => "registered service is unavailable or incompatible".to_owned(),
_ => return Ok(()),
};
if let Err(error) = clash_verge_service_ipc::execution::check_sidecar_available()
.await
.map_err(super::state::explain_core_occupancy)
{
logging!(
warn,
Type::Core,
"Service unavailable ({reason}); Sidecar fallback withheld: {error:#}"
);
return Ok(());
}
self.start_sidecar_after_service_failure(anyhow::anyhow!(reason)).await
}
#[cfg(target_os = "windows")]
async fn start_sidecar_after_service_failure(&self, error: anyhow::Error) -> Result<()> {
use crate::core::runstate::RUN_STATE;
if Handle::global().is_exiting() {
return Err(error.context("application exited before Sidecar fallback"));
}
let reason = format!("{error:#}");
RUN_STATE.allow_sidecar_after_service_refusal(reason.clone())?;
logging!(warn, Type::Core, "Starting Sidecar with Service unavailable: {reason}");
let result = self.start_core_by_sidecar().await;
if result.is_err() {
SERVICE_MANAGER.withdraw_sidecar_allowance();
self.rollback_failed_start().await;
} else {
crate::core::service::notify_service_fallback(&reason);
}
result.map_err(|error| error.context(format!("Service failure before Sidecar startup: {reason}")))
}
#[tracing::instrument(skip_all, level = "info", fields(mode = ?*self.get_running_mode()))] #[tracing::instrument(skip_all, level = "info", fields(mode = ?*self.get_running_mode()))]
pub async fn stop_core(&self) -> Result<()> { pub async fn stop_core(&self) -> Result<()> {
let _life = self.lifecycle_lock.lock().await; let _life = self.lifecycle_lock.lock().await;
@@ -736,6 +846,13 @@ impl CoreManager {
let is_admin = is_current_app_handle_admin(Handle::app_handle()); let is_admin = is_current_app_handle_admin(Handle::app_handle());
if !should_wait_for_service(tun_enabled, service_ready, is_admin) { if !should_wait_for_service(tun_enabled, service_ready, is_admin) {
if tun_enabled && !service_ready && is_admin {
logging!(
info,
Type::Core,
"service unavailable while app is elevated; starting sidecar immediately"
);
}
return; return;
} }
@@ -748,6 +865,8 @@ impl CoreManager {
return; return;
} }
// Failing to become ready is not fatal here: the caller falls back to Sidecar, and a
// transient transport failure must not overwrite the last confirmed install state.
let attempts = (timing::SERVICE_WAIT_MAX.as_millis() / timing::SERVICE_WAIT_INTERVAL.as_millis()) as usize; let attempts = (timing::SERVICE_WAIT_MAX.as_millis() / timing::SERVICE_WAIT_INTERVAL.as_millis()) as usize;
let wait = crate::core::runstate::RUN_STATE.await_ready(attempts, timing::SERVICE_WAIT_INTERVAL); let wait = crate::core::runstate::RUN_STATE.await_ready(attempts, timing::SERVICE_WAIT_INTERVAL);
let _ = tokio::time::timeout(timing::SERVICE_WAIT_MAX, wait).await; let _ = tokio::time::timeout(timing::SERVICE_WAIT_MAX, wait).await;
@@ -1291,6 +1410,46 @@ mod tests {
} }
} }
#[tokio::test]
async fn blocked_windows_fallback_records_failure_without_starting_sidecar() {
use crate::core::runstate::{FakeEnv, RunStateStore, ServiceHealth};
for idle in [false, true] {
let store = RunStateStore::new(FakeEnv::new());
store.observe(ServiceHealth::Ready);
let started = AtomicBool::new(false);
let result = super::run_service_start_with_sidecar_fallback(
|| async {
Err(crate::core::service::ServiceStartRefusal {
code: clash_verge_service_ipc::ServiceErrorCode::InvalidInstallLocation as u16,
core_path: "verge-mihomo.exe".into(),
message: "no administrator-approved copy is installed".into(),
}
.into())
},
|| async move {
anyhow::ensure!(idle, "another core is running");
Ok(())
},
|_| async {
started.store(true, Ordering::SeqCst);
Ok(())
},
|reason| store.observe(ServiceHealth::Unavailable(reason)),
)
.await;
assert_eq!(started.load(Ordering::SeqCst), idle);
assert_eq!(result.is_ok(), idle);
assert!(!store.state().sidecar_allowed);
if !idle {
assert!(store.state().service_needs_attention());
assert!(!store.state().service_usable());
assert!(result.is_err_and(|error| format!("{error:#}").contains("another core is running")));
}
}
}
#[test] #[test]
fn failed_service_install_can_continue_with_an_existing_sidecar() { fn failed_service_install_can_continue_with_an_existing_sidecar() {
assert!(can_allow_sidecar_for_session( assert!(can_allow_sidecar_for_session(
+1 -1
View File
@@ -235,7 +235,7 @@ impl CoreManager {
anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}"); anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}");
} }
use clash_verge_task::retry::{RetryError, RetryPolicy, retry}; use crate::utils::retry::{RetryError, RetryPolicy, retry};
retry( retry(
RetryPolicy::fixed( RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add(MAX_PORT_FALLBACK_RETRIES), std::num::NonZeroUsize::MIN.saturating_add(MAX_PORT_FALLBACK_RETRIES),
+81 -114
View File
@@ -1,6 +1,7 @@
#[cfg(test)] #[cfg(test)]
use super::claim_core_readiness_generation; use super::claim_core_readiness_generation;
use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode}; use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
use crate::utils::retry::{RetryError, RetryPolicy, retry};
use crate::{ use crate::{
AsyncHandler, AsyncHandler,
config::Config, config::Config,
@@ -10,19 +11,30 @@ use crate::{
}; };
use anyhow::{Context as _, Result}; use anyhow::{Context as _, Result};
use clash_verge_logging::Type; use clash_verge_logging::Type;
use clash_verge_task::retry::{RetryError, RetryPolicy, retry}; use futures::{
use futures::{FutureExt as _, future::Shared}; FutureExt as _,
future::{Map, Shared},
};
use log::Level; use log::Level;
use std::num::NonZeroUsize; use std::num::NonZeroUsize;
use std::path::Path; use std::path::Path;
use std::sync::Arc;
use tauri_plugin_mihomo::MihomoExt as _; use tauri_plugin_mihomo::MihomoExt as _;
use tauri_plugin_shell::ShellExt as _; use tauri_plugin_shell::ShellExt as _;
use tauri_plugin_shell::process::CommandChild; use tauri_plugin_shell::process::CommandChild;
use tokio::sync::oneshot; use tokio::task::{JoinError, JoinHandle};
pub(super) fn explain_core_occupancy(error: anyhow::Error) -> anyhow::Error {
let detail = error.to_string();
if detail.starts_with("process verge-mihomo") && detail.ends_with("; refusing a second core") {
error.context(clash_verge_i18n::t!("core.alreadyRunning").into_owned())
} else {
error
}
}
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> { fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> {
use crate::config::mihomo_yaml;
use serde_yaml_ng::{Mapping, Value}; use serde_yaml_ng::{Mapping, Value};
let mut config: Mapping = serde_yaml_ng::from_str(yaml)?; let mut config: Mapping = serde_yaml_ng::from_str(yaml)?;
@@ -35,7 +47,7 @@ fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> {
tun.as_mapping_mut() tun.as_mapping_mut()
.context("invalid Sidecar TUN configuration")? .context("invalid Sidecar TUN configuration")?
.insert(Value::from("enable"), Value::Bool(false)); .insert(Value::from("enable"), Value::Bool(false));
Ok(mihomo_yaml::serialize(&config)?) Ok(serde_yaml_ng::to_string(&config)?)
} }
const SIDECAR_READINESS_ATTEMPTS: usize = 30; const SIDECAR_READINESS_ATTEMPTS: usize = 30;
@@ -133,10 +145,18 @@ fn should_clear_terminated_sidecar(
matches!(running_mode, RunningMode::Sidecar) && current_generation == Some(terminated_generation) matches!(running_mode, RunningMode::Sidecar) && current_generation == Some(terminated_generation)
} }
type ShareExitResult = fn(Result<(), JoinError>) -> Result<(), Arc<JoinError>>;
type SidecarExit = Shared<Map<JoinHandle<()>, ShareExitResult>>;
fn share_exit(exit: JoinHandle<()>) -> SidecarExit {
let share_error: ShareExitResult = |result| result.map_err(Arc::new);
exit.map(share_error).shared()
}
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub(super) struct SidecarSession { pub(super) struct SidecarSession {
process: Option<SidecarProcess>, process: Option<SidecarProcess>,
exit: Option<Shared<oneshot::Receiver<()>>>, exit: Option<SidecarExit>,
} }
#[derive(Debug)] #[derive(Debug)]
@@ -174,7 +194,10 @@ impl CoreManager {
#[tracing::instrument(skip_all, level = "info", fields(pid = tracing::field::Empty))] #[tracing::instrument(skip_all, level = "info", fields(pid = tracing::field::Empty))]
pub(super) async fn start_core_by_sidecar(&self) -> Result<()> { pub(super) async fn start_core_by_sidecar(&self) -> Result<()> {
self.wait_for_sidecar_exit().await?; self.wait_for_sidecar_exit().await?;
service::require_service_core_released()?; let execution = clash_verge_service_ipc::execution::reserve_sidecar()
.await
.inspect_err(service::record_residual_service)
.map_err(explain_core_occupancy)?;
self.core_stopped(); self.core_stopped();
let sidecar_ipc = dirs::sidecar_ipc_path()?; let sidecar_ipc = dirs::sidecar_ipc_path()?;
@@ -197,11 +220,13 @@ impl CoreManager {
#[cfg(unix)] #[cfg(unix)]
discard_unwritable_core_cache(&config_dir); discard_unwritable_core_cache(&config_dir);
#[cfg(unix)]
let previous_mask = unsafe { tauri_plugin_clash_verge_sysinfo::libc::umask(0o077) };
let command = app_handle let command = app_handle
.shell() .shell()
.sidecar(clash_core.as_str()) .sidecar(clash_core.as_str())
.map_err(|error| anyhow::anyhow!("failed to build sidecar command for core {clash_core:?}: {error:#}"))?; .map_err(|error| anyhow::anyhow!("failed to build sidecar command for core {clash_core:?}: {error:#}"))?;
let command = command.kill_on_drop(true).args([ let command = command.args([
"-d", "-d",
dirs::path_to_str(&config_dir)?, dirs::path_to_str(&config_dir)?,
"-f", "-f",
@@ -218,13 +243,6 @@ impl CoreManager {
"LISTEN_NAMEDPIPE_SDDL", "LISTEN_NAMEDPIPE_SDDL",
crate::core::owner_identity::current_user_pipe_sddl()?, crate::core::owner_identity::current_user_pipe_sddl()?,
); );
#[cfg(unix)]
let restore_mask = std::mem::DropGuard::new(
unsafe { tauri_plugin_clash_verge_sysinfo::libc::umask(0o077) },
|mask| {
unsafe { tauri_plugin_clash_verge_sysinfo::libc::umask(mask) };
},
);
let (mut rx, child) = command.spawn().map_err(|error| { let (mut rx, child) = command.spawn().map_err(|error| {
anyhow::anyhow!( anyhow::anyhow!(
"failed to start sidecar core {clash_core:?} with config {} and data directory {}: {error:#}", "failed to start sidecar core {clash_core:?} with config {} and data directory {}: {error:#}",
@@ -232,10 +250,35 @@ impl CoreManager {
config_dir.display() config_dir.display()
) )
})?; })?;
let (terminated, termination) = tokio::sync::oneshot::channel();
let exit = execution.release_after_exit(child.pid(), termination);
self.sidecar.lock().exit = Some(share_exit(exit));
#[cfg(target_os = "windows")]
let job = {
match create_and_assign_sidecar_job(child.pid()) {
Ok(job) => job,
Err(job_error) => {
let pid = child.pid();
let error = match child.kill() {
Ok(()) => job_error,
Err(kill_error) => anyhow::anyhow!(
"failed to configure Job Object for sidecar PID {pid}: \
{job_error:#}; failed to terminate child: {kill_error:#}"
),
};
logging!(error, Type::Core, "Failed to start sidecar: {error:#}");
return Err(error);
}
}
};
#[cfg(unix)] #[cfg(unix)]
drop(restore_mask); unsafe {
let (terminated, termination) = oneshot::channel(); tauri_plugin_clash_verge_sysinfo::libc::umask(previous_mask)
self.sidecar.lock().exit = Some(termination.shared()); };
let pid = child.pid(); let pid = child.pid();
tracing::Span::current().record("pid", pid); tracing::Span::current().record("pid", pid);
@@ -273,30 +316,6 @@ impl CoreManager {
} }
}); });
#[cfg(target_os = "windows")]
let job = {
match create_and_assign_sidecar_job(child.pid()) {
Ok(job) => job,
Err(job_error) => {
let pid = child.pid();
let error = match child.kill() {
Ok(()) => {
self.sidecar.lock().exit.take();
job_error
}
Err(kill_error) => anyhow::anyhow!(
"failed to configure Job Object for sidecar PID {pid}: \
{job_error:#}; failed to terminate child: {kill_error:#}"
),
};
logging!(error, Type::Core, "Failed to start sidecar: {error:#}");
return Err(error);
}
}
};
let readiness = poll_sidecar_readiness(SIDECAR_READINESS_ATTEMPTS, SIDECAR_READINESS_INTERVAL, || async { let readiness = poll_sidecar_readiness(SIDECAR_READINESS_ATTEMPTS, SIDECAR_READINESS_INTERVAL, || async {
tokio::time::timeout(SIDECAR_READINESS_PROBE_TIMEOUT, async { tokio::time::timeout(SIDECAR_READINESS_PROBE_TIMEOUT, async {
handle::Handle::mihomo().get_version().await handle::Handle::mihomo().get_version().await
@@ -310,10 +329,7 @@ impl CoreManager {
proxy_control::stop_guard().await; proxy_control::stop_guard().await;
self.core_stopped(); self.core_stopped();
return match child.kill() { return match child.kill() {
Ok(()) => { Ok(()) => Err(readiness_error),
self.sidecar.lock().exit.take();
Err(readiness_error)
}
Err(kill_error) => Err(anyhow::anyhow!( Err(kill_error) => Err(anyhow::anyhow!(
"{readiness_error:#}; failed to terminate unready sidecar PID {pid}: {kill_error:#}" "{readiness_error:#}; failed to terminate unready sidecar PID {pid}: {kill_error:#}"
)), )),
@@ -341,11 +357,8 @@ impl CoreManager {
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
drop(process.job); drop(process.job);
match process.child.kill() { if let Err(error) = process.child.kill() {
Ok(()) => { logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}");
self.sidecar.lock().exit.take();
}
Err(error) => logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}"),
} }
} }
let result = self.wait_for_sidecar_exit().await; let result = self.wait_for_sidecar_exit().await;
@@ -379,13 +392,12 @@ impl CoreManager {
#[tracing::instrument(skip_all, level = "info", fields(config_file = %config_file.display()))] #[tracing::instrument(skip_all, level = "info", fields(config_file = %config_file.display()))]
pub(super) async fn start_core_by_service_with_config(&self, config_file: &Path) -> Result<()> { pub(super) async fn start_core_by_service_with_config(&self, config_file: &Path) -> Result<()> {
self.wait_for_sidecar_exit().await?; // 交接时等待 sidecar 释放 ext-controller 通道。
let start = tokio::sync::OnceCell::new();
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
{ {
use crate::constants::timing; use crate::constants::timing;
retry_service_start(timing::SERVICE_START_RETRIES, timing::SERVICE_START_RETRY_DELAY, || { retry_service_start(timing::SERVICE_START_RETRIES, timing::SERVICE_START_RETRY_DELAY, || {
service::run_core_by_service(config_file, &start) service::run_core_by_service(config_file)
}) })
.await?; .await?;
self.mark_core_ready(); self.mark_core_ready();
@@ -397,7 +409,7 @@ impl CoreManager {
#[cfg(not(target_os = "windows"))] #[cfg(not(target_os = "windows"))]
{ {
service::run_core_by_service(config_file, &start).await?; service::run_core_by_service(config_file).await?;
self.mark_core_ready(); self.mark_core_ready();
self.core_started(RunningMode::Service); self.core_started(RunningMode::Service);
self.restore_selected_nodes().await; self.restore_selected_nodes().await;
@@ -543,6 +555,20 @@ mod readiness_tests {
time::Duration, time::Duration,
}; };
#[test]
fn core_occupancy_explanation_preserves_the_original_error() {
for detail in [
"process verge-mihomo remains after IPC failure; refusing a second core",
"process verge-mihomo-alpha.exe (PID 123) is still running; refusing a second core",
] {
let error = super::explain_core_occupancy(anyhow::anyhow!(detail));
assert_eq!(error.to_string(), clash_verge_i18n::t!("core.alreadyRunning"));
assert_eq!(error.root_cause().to_string(), detail);
}
let error = super::explain_core_occupancy(anyhow::anyhow!("could not inspect remaining cores"));
assert_eq!(error.to_string(), "could not inspect remaining cores");
}
#[tokio::test] #[tokio::test]
async fn sidecar_readiness_poll_is_bounded_and_accepts_a_real_api_response() -> anyhow::Result<()> { async fn sidecar_readiness_poll_is_bounded_and_accepts_a_real_api_response() -> anyhow::Result<()> {
let attempts = Arc::new(AtomicUsize::new(0)); let attempts = Arc::new(AtomicUsize::new(0));
@@ -703,65 +729,6 @@ mod tests {
Ok(()) Ok(())
} }
#[test]
fn forced_parent_exit_releases_the_sidecar_job() -> Result<()> {
use std::io::{BufRead as _, BufReader, Write as _};
use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _, OwnedHandle};
use windows_sys::Win32::{
Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT},
System::Threading::{OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject},
};
const HELPER: &str = "CVR_TEST_SIDECAR_JOB_PARENT";
if std::env::var_os(HELPER).is_some() {
let mut child = spawn_long_lived()?;
let _job = create_and_assign_sidecar_job(child.id()).inspect_err(|_| {
let _ = child.kill();
let _ = child.wait();
})?;
println!("\nSIDECAR_PID={}", child.id());
std::io::stdout().flush()?;
std::io::stdin().read_line(&mut String::new())?;
return Ok(());
}
let mut parent = std::mem::DropGuard::new(
Command::new(std::env::current_exe()?)
.args(["forced_parent_exit_releases_the_sidecar_job", "--nocapture"])
.env(HELPER, "1")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?,
|mut parent| {
let _ = parent.kill();
let _ = parent.wait();
},
);
let stdout = parent
.stdout
.take()
.ok_or_else(|| anyhow::anyhow!("missing helper stdout"))?;
let mut pid = None;
for line in BufReader::new(stdout).lines() {
if let Some(value) = line?.strip_prefix("SIDECAR_PID=") {
pid = Some(value.parse()?);
break;
}
}
let pid = pid.ok_or_else(|| anyhow::anyhow!("helper did not report its child"))?;
let raw = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) };
anyhow::ensure!(!raw.is_null(), "could not open helper child {pid}");
let child = unsafe { OwnedHandle::from_raw_handle(raw) };
assert_eq!(unsafe { WaitForSingleObject(child.as_raw_handle(), 0) }, WAIT_TIMEOUT);
parent.kill()?;
parent.wait()?;
assert_eq!(
unsafe { WaitForSingleObject(child.as_raw_handle(), 5000) },
WAIT_OBJECT_0
);
Ok(())
}
#[test] #[test]
fn returns_err_for_invalid_pid() { fn returns_err_for_invalid_pid() {
// Windows PIDs are multiples of four; this one is effectively impossible. // Windows PIDs are multiples of four; this one is effectively impossible.
+2
View File
@@ -11,7 +11,9 @@ pub mod network_watch;
pub mod notify; pub mod notify;
pub(crate) mod owner_identity; pub(crate) mod owner_identity;
pub mod proxy_control; pub mod proxy_control;
pub mod proxy_view;
pub mod runstate; pub mod runstate;
pub(crate) mod runtime_bundle;
pub mod service; pub mod service;
pub mod sysopt; pub mod sysopt;
pub mod timer; pub mod timer;
+6 -1
View File
@@ -19,6 +19,9 @@ pub enum NoticeStatus {
ServiceCoreRepairRequired, ServiceCoreRepairRequired,
#[serde(rename = "service_core::app_data_not_owned")] #[serde(rename = "service_core::app_data_not_owned")]
ServiceCoreAppDataNotOwned, ServiceCoreAppDataNotOwned,
#[serde(rename = "service_core::sidecar_fallback")]
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
ServiceCoreSidecarFallback,
#[serde(rename = "dns_override::auto_disabled")] #[serde(rename = "dns_override::auto_disabled")]
DnsOverrideAutoDisabled, DnsOverrideAutoDisabled,
#[serde(rename = "enhance::discarded_keys")] #[serde(rename = "enhance::discarded_keys")]
@@ -78,13 +81,14 @@ impl NoticeStatus {
/// test both derive their variant list from here; expected strings stay /// test both derive their variant list from here; expected strings stay
/// hand-written in the test so renames cannot slip through. /// hand-written in the test so renames cannot slip through.
#[cfg(test)] #[cfg(test)]
pub const ALL: [Self; 32] = [ pub const ALL: [Self; 33] = [
Self::ImportSubUrlOk, Self::ImportSubUrlOk,
Self::ImportSubUrlError, Self::ImportSubUrlError,
Self::SetConfigError, Self::SetConfigError,
Self::CoreStartError, Self::CoreStartError,
Self::ServiceCoreRepairRequired, Self::ServiceCoreRepairRequired,
Self::ServiceCoreAppDataNotOwned, Self::ServiceCoreAppDataNotOwned,
Self::ServiceCoreSidecarFallback,
Self::DnsOverrideAutoDisabled, Self::DnsOverrideAutoDisabled,
Self::EnhanceDiscardedKeys, Self::EnhanceDiscardedKeys,
Self::TunModeAutoDisabled, Self::TunModeAutoDisabled,
@@ -128,6 +132,7 @@ mod tests {
"core_start::error", "core_start::error",
"service_core::repair_required", "service_core::repair_required",
"service_core::app_data_not_owned", "service_core::app_data_not_owned",
"service_core::sidecar_fallback",
"dns_override::auto_disabled", "dns_override::auto_disabled",
"enhance::discarded_keys", "enhance::discarded_keys",
"tun_mode::auto_disabled", "tun_mode::auto_disabled",
+3 -3
View File
@@ -390,10 +390,10 @@ fn service_proxy_config(verge: &IVerge, mixed_port: u16, pac_port: u16) -> Resul
/// the write's, so it stays a failure. /// the write's, so it stays a failure.
fn service_apply_result(requested: &MacosProxyConfig, outcome: ProxyApplyOutcome) -> Result<()> { fn service_apply_result(requested: &MacosProxyConfig, outcome: ProxyApplyOutcome) -> Result<()> {
match outcome { match outcome {
ProxyApplyOutcome::Applied => Ok(()), ProxyApplyOutcome::Applied | ProxyApplyOutcome::NotRequested => Ok(()),
// Direct fallback satisfies a disable request. // Direct fallback satisfies a disable request.
ProxyApplyOutcome::DirectFallback { .. } if matches!(requested, MacosProxyConfig::Disabled) => Ok(()), ProxyApplyOutcome::DirectFallback { .. } if matches!(requested, MacosProxyConfig::Disabled) => Ok(()),
// The service reports a missing network service as fallback before any OS write. // Older helpers encode a failed service lookup as fallback even when no OS write occurred.
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
ProxyApplyOutcome::DirectFallback { message } ProxyApplyOutcome::DirectFallback { message }
if message == sysproxy::Error::NoActiveNetworkService.to_string() => if message == sysproxy::Error::NoActiveNetworkService.to_string() =>
@@ -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. /// A failed system call is usually a transient RPC hiccup, so give it a few tries.
async fn clear_with_retry() -> Result<()> { async fn clear_with_retry() -> Result<()> {
use clash_verge_task::retry::{RetryError, RetryPolicy, retry}; use crate::utils::retry::{RetryError, RetryPolicy, retry};
retry( retry(
RetryPolicy::fixed( RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add((CLEAR_ATTEMPTS - 1) as usize), std::num::NonZeroUsize::MIN.saturating_add((CLEAR_ATTEMPTS - 1) as usize),
@@ -1,40 +1,15 @@
use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::collections::{BTreeMap, BTreeSet};
use serde::Serialize; use serde::Serialize;
use tristr::alias::String; use tauri_plugin_mihomo::models::{
DelayHistory, Proxies, Proxy, ProxyProvider, ProxyProviders, ProxyType, VehicleType,
};
pub struct ProxyViewInput { pub struct ProxyViewInput {
pub runtime_group_order: Vec<String>, pub runtime_group_order: Vec<String>,
pub group_scopes: BTreeMap<String, GroupScope>, pub group_scopes: BTreeMap<String, GroupScope>,
pub proxies: HashMap<String, ProxySnapshot>, pub proxies: Proxies,
pub providers: Option<BTreeMap<String, ProviderSnapshot>>, pub providers: Option<ProxyProviders>,
}
pub struct ProxySnapshot {
pub name: String,
pub proxy_type: String,
pub all: Option<Vec<String>>,
pub fixed: Option<String>,
pub hidden: Option<bool>,
pub icon: Option<String>,
pub now: Option<String>,
pub test_url: Option<String>,
pub id: Option<String>,
pub history: Vec<DelayHistory>,
pub capabilities: ProxyCapabilities,
}
pub struct ProviderSnapshot {
pub vehicle_type: ProxyProviderVehicleType,
pub proxies: Vec<ProxySnapshot>,
pub updated_at: Option<String>,
pub subscription_info: Option<ProxySubscriptionInfo>,
}
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
pub struct DelayHistory {
pub time: String,
pub delay: u16,
} }
/// The providers a group draws from (Mihomo order) and its `exclude-type` entries. /// The providers a group draws from (Mihomo order) and its `exclude-type` entries.
@@ -43,6 +18,8 @@ pub struct GroupScope {
pub exclude_types: Vec<String>, pub exclude_types: Vec<String>,
} }
pub struct ProxyViewBuilder;
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)] #[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct ProxyViewV1 { pub struct ProxyViewV1 {
@@ -85,7 +62,8 @@ pub struct ProxyCapabilities {
pub struct ProxyGroupView { pub struct ProxyGroupView {
pub name: String, pub name: String,
#[serde(rename = "type")] #[serde(rename = "type")]
pub proxy_type: String, #[specta(type = String)]
pub proxy_type: ProxyType,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub now: Option<String>, pub now: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
@@ -96,6 +74,7 @@ pub struct ProxyGroupView {
pub icon: Option<String>, pub icon: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub test_url: Option<String>, pub test_url: Option<String>,
#[specta(type = Vec<crate::ipc::DelayHistory>)]
pub history: Vec<DelayHistory>, pub history: Vec<DelayHistory>,
#[serde(flatten)] #[serde(flatten)]
pub capabilities: ProxyCapabilities, pub capabilities: ProxyCapabilities,
@@ -108,7 +87,9 @@ pub struct ProxyNodeView {
pub record_id: String, pub record_id: String,
pub name: String, pub name: String,
#[serde(rename = "type")] #[serde(rename = "type")]
pub proxy_type: String, #[specta(type = String)]
pub proxy_type: ProxyType,
#[specta(type = Vec<crate::ipc::DelayHistory>)]
pub history: Vec<DelayHistory>, pub history: Vec<DelayHistory>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>, pub id: Option<String>,
@@ -209,8 +190,8 @@ struct MemberResolver<'a> {
impl<'a> MemberResolver<'a> { impl<'a> MemberResolver<'a> {
/// Same-name records in the order Mihomo lists them in `group`: `use` order, after `exclude-type`. /// Same-name records in the order Mihomo lists them in `group`: `use` order, after `exclude-type`.
fn scoped_candidates(&self, group: &str, candidates: &'a [(String, String)]) -> Vec<&'a String> { fn scoped_candidates(&self, group: &str, name: &str) -> Vec<&'a String> {
let Some(scope) = self.group_scopes.get(group) else { let (Some(scope), Some(candidates)) = (self.group_scopes.get(group), self.provider_candidates.get(name)) else {
return Vec::new(); return Vec::new();
}; };
scope scope
@@ -219,23 +200,17 @@ impl<'a> MemberResolver<'a> {
.flat_map(|provider| candidates.iter().filter(move |(owner, _)| owner == provider)) .flat_map(|provider| candidates.iter().filter(move |(owner, _)| owner == provider))
.map(|(_, record_id)| record_id) .map(|(_, record_id)| record_id)
.filter(|record_id| { .filter(|record_id| {
scope.exclude_types.is_empty() !self.records.get(*record_id).is_some_and(|node| {
|| !self.records.get(*record_id).is_some_and(|node| { scope
scope .exclude_types
.exclude_types .iter()
.iter() .any(|excluded| excluded.eq_ignore_ascii_case(node.proxy_type.as_str()))
.any(|excluded| excluded.eq_ignore_ascii_case(node.proxy_type.as_str())) })
})
}) })
.collect() .collect()
} }
fn resolve( fn resolve(&self, name: String, scoped: Option<&String>) -> ProxyMemberRef {
&self,
group: &str,
name: String,
seen: &mut BTreeMap<String, (usize, Vec<&'a String>)>,
) -> ProxyMemberRef {
if self.group_names.contains(&name) { if self.group_names.contains(&name) {
ProxyMemberRef::Group { name } ProxyMemberRef::Group { name }
} else if let Some(record_id) = self.core_node_ids.get(&name) { } else if let Some(record_id) = self.core_node_ids.get(&name) {
@@ -250,30 +225,16 @@ impl<'a> MemberResolver<'a> {
} }
} else { } else {
let candidates = self.provider_candidates.get(&name).map_or(&[][..], Vec::as_slice); let candidates = self.provider_candidates.get(&name).map_or(&[][..], Vec::as_slice);
let record_id = match candidates { match (scoped, candidates) {
[(_, record_id)] => Some(record_id), (Some(record_id), _) | (None, [(_, record_id)]) => ProxyMemberRef::Node {
[] => {
return ProxyMemberRef::Unresolved {
name,
reason: ProxyMemberUnresolvedReason::Missing,
};
}
_ => {
// The n-th occurrence in Mihomo's member list selects the n-th scoped candidate.
let (occurrence, scoped) = seen
.entry(name.clone())
.or_insert_with(|| (0, self.scoped_candidates(group, candidates)));
let record_id = scoped.get(*occurrence).or_else(|| scoped.first()).copied();
*occurrence += 1;
record_id
}
};
match record_id {
Some(record_id) => ProxyMemberRef::Node {
name, name,
record_id: record_id.clone(), record_id: record_id.clone(),
}, },
None => ProxyMemberRef::Unresolved { (None, []) => ProxyMemberRef::Unresolved {
name,
reason: ProxyMemberUnresolvedReason::Missing,
},
(None, _) => ProxyMemberRef::Unresolved {
name, name,
reason: ProxyMemberUnresolvedReason::Ambiguous, reason: ProxyMemberUnresolvedReason::Ambiguous,
}, },
@@ -282,14 +243,14 @@ impl<'a> MemberResolver<'a> {
} }
} }
impl ProxyViewInput { impl ProxyViewBuilder {
pub fn into_view(self) -> ProxyViewV1 { pub fn build(input: ProxyViewInput) -> ProxyViewV1 {
let Self { let ProxyViewInput {
runtime_group_order, runtime_group_order,
group_scopes, group_scopes,
proxies, proxies,
providers, providers,
} = self; } = input;
let provider_state = if providers.is_some() { let provider_state = if providers.is_some() {
ProxyViewProviderState::Ready ProxyViewProviderState::Ready
} else { } else {
@@ -309,7 +270,7 @@ impl ProxyViewInput {
let global = core_groups let global = core_groups
.remove("GLOBAL") .remove("GLOBAL")
.map(|proxy| build_group("GLOBAL".into(), proxy, &resolver)); .map(|proxy| build_group("GLOBAL".to_owned(), proxy, &resolver));
let (groups, order_source) = build_ordered_groups(core_groups, runtime_group_order, &resolver); let (groups, order_source) = build_ordered_groups(core_groups, runtime_group_order, &resolver);
let direct = core_node_ids.get("DIRECT").cloned(); let direct = core_node_ids.get("DIRECT").cloned();
let standalone = build_standalone(&core_node_ids); let standalone = build_standalone(&core_node_ids);
@@ -328,13 +289,11 @@ impl ProxyViewInput {
} }
} }
fn partition_core( fn partition_core(proxies: Proxies) -> (BTreeMap<String, Proxy>, BTreeMap<String, Proxy>) {
proxies: HashMap<String, ProxySnapshot>,
) -> (BTreeMap<String, ProxySnapshot>, BTreeMap<String, ProxySnapshot>) {
let mut groups = BTreeMap::new(); let mut groups = BTreeMap::new();
let mut nodes = BTreeMap::new(); let mut nodes = BTreeMap::new();
for (name, proxy) in proxies { for (name, proxy) in proxies.proxies {
if proxy.all.is_some() { if proxy.all.is_some() {
groups.insert(name, proxy); groups.insert(name, proxy);
} else { } else {
@@ -346,13 +305,13 @@ fn partition_core(
} }
fn build_core_records( fn build_core_records(
core_nodes: BTreeMap<String, ProxySnapshot>, core_nodes: BTreeMap<String, Proxy>,
) -> (BTreeMap<String, ProxyNodeView>, BTreeMap<String, String>) { ) -> (BTreeMap<String, ProxyNodeView>, BTreeMap<String, String>) {
let mut records = BTreeMap::new(); let mut records = BTreeMap::new();
let mut ids = BTreeMap::new(); let mut ids = BTreeMap::new();
for (index, (name, proxy)) in core_nodes.into_iter().enumerate() { for (index, (name, proxy)) in core_nodes.into_iter().enumerate() {
let record_id: String = format!("c:{index}").into(); let record_id = format!("c:{index}");
ids.insert(name.clone(), record_id.clone()); ids.insert(name.clone(), record_id.clone());
records.insert( records.insert(
record_id.clone(), record_id.clone(),
@@ -369,24 +328,32 @@ fn build_core_records(
} }
fn build_provider_records( fn build_provider_records(
providers: Option<BTreeMap<String, ProviderSnapshot>>, providers: Option<ProxyProviders>,
records: &mut BTreeMap<String, ProxyNodeView>, records: &mut BTreeMap<String, ProxyNodeView>,
) -> (Vec<ProxyProviderView>, ProviderCandidates) { ) -> (Vec<ProxyProviderView>, ProviderCandidates) {
let providers = providers.map_or_default(|providers| providers.providers.into_iter().collect::<BTreeMap<_, _>>());
let mut views = Vec::new(); let mut views = Vec::new();
let mut candidates = BTreeMap::new(); let mut candidates = BTreeMap::new();
for (provider_name, provider) in providers.into_iter().flatten() { for (provider_name, provider) in providers {
let ProviderSnapshot { let ProxyProvider {
vehicle_type, vehicle_type,
proxies, proxies,
updated_at, updated_at,
subscription_info, subscription_info,
..
} = provider; } = provider;
let vehicle_type = match vehicle_type {
VehicleType::HTTP => ProxyProviderVehicleType::Http,
VehicleType::File => ProxyProviderVehicleType::File,
VehicleType::Inline => ProxyProviderVehicleType::Inline,
_ => continue,
};
let provider_index = views.len(); let provider_index = views.len();
let mut proxy_record_ids = Vec::new(); let mut proxy_record_ids = Vec::new();
for (member_index, proxy) in proxies.into_iter().enumerate() { for (member_index, proxy) in proxies.into_iter().enumerate() {
let record_id: String = format!("p:{provider_index}:{member_index}").into(); let record_id = format!("p:{provider_index}:{member_index}");
let proxy_name = proxy.name.clone(); let proxy_name = proxy.name.clone();
let node_name = proxy.name.clone(); let node_name = proxy.name.clone();
candidates candidates
@@ -412,7 +379,12 @@ fn build_provider_records(
name: provider_name, name: provider_name,
vehicle_type, vehicle_type,
updated_at, updated_at,
subscription_info, subscription_info: subscription_info.map(|subscription_info| ProxySubscriptionInfo {
upload: subscription_info.upload,
download: subscription_info.download,
total: subscription_info.total,
expire: subscription_info.expire,
}),
proxy_record_ids, proxy_record_ids,
}); });
} }
@@ -420,8 +392,8 @@ fn build_provider_records(
(views, candidates) (views, candidates)
} }
fn build_group(name: String, proxy: ProxySnapshot, resolver: &MemberResolver<'_>) -> ProxyGroupView { fn build_group(name: String, proxy: Proxy, resolver: &MemberResolver<'_>) -> ProxyGroupView {
let ProxySnapshot { let Proxy {
all, all,
fixed, fixed,
hidden, hidden,
@@ -429,15 +401,27 @@ fn build_group(name: String, proxy: ProxySnapshot, resolver: &MemberResolver<'_>
now, now,
test_url, test_url,
history, history,
capabilities, udp,
xudp,
tfo,
mptcp,
smux,
proxy_type, proxy_type,
.. ..
} = proxy; } = proxy;
let mut seen = BTreeMap::new(); // The n-th occurrence of a name in `all` is the n-th scoped candidate.
let mut seen = BTreeMap::<String, (usize, Vec<&String>)>::new();
let members = all let members = all
.unwrap_or_default() .unwrap_or_default()
.into_iter() .into_iter()
.map(|member| resolver.resolve(&name, member, &mut seen)) .map(|member| {
let (occurrence, scoped) = seen
.entry(member.clone())
.or_insert_with(|| (0, resolver.scoped_candidates(&name, &member)));
let picked = scoped.get(*occurrence).or_else(|| scoped.first()).copied();
*occurrence += 1;
resolver.resolve(member, picked)
})
.collect(); .collect();
ProxyGroupView { ProxyGroupView {
@@ -449,19 +433,29 @@ fn build_group(name: String, proxy: ProxySnapshot, resolver: &MemberResolver<'_>
icon, icon,
test_url, test_url,
history, history,
capabilities, capabilities: ProxyCapabilities {
udp,
xudp,
tfo,
mptcp,
smux,
},
members, members,
} }
} }
fn build_node(record_id: String, name: String, proxy: ProxySnapshot, source: ProxyNodeSource) -> ProxyNodeView { fn build_node(record_id: String, name: String, proxy: Proxy, source: ProxyNodeSource) -> ProxyNodeView {
let ProxySnapshot { let Proxy {
id, id,
hidden, hidden,
icon, icon,
test_url, test_url,
history, history,
capabilities, udp,
xudp,
tfo,
mptcp,
smux,
proxy_type, proxy_type,
.. ..
} = proxy; } = proxy;
@@ -475,13 +469,19 @@ fn build_node(record_id: String, name: String, proxy: ProxySnapshot, source: Pro
hidden, hidden,
icon, icon,
test_url, test_url,
capabilities, capabilities: ProxyCapabilities {
udp,
xudp,
tfo,
mptcp,
smux,
},
source, source,
} }
} }
fn build_ordered_groups( fn build_ordered_groups(
mut core_groups: BTreeMap<String, ProxySnapshot>, mut core_groups: BTreeMap<String, Proxy>,
runtime_group_order: Vec<String>, runtime_group_order: Vec<String>,
resolver: &MemberResolver<'_>, resolver: &MemberResolver<'_>,
) -> (Vec<ProxyGroupView>, ProxyViewOrderSource) { ) -> (Vec<ProxyGroupView>, ProxyViewOrderSource) {
+10 -2
View File
@@ -67,9 +67,17 @@ impl RunStateEnv for RealEnv {
} }
async fn trusted_install_evidence(&self) -> Result<bool> { async fn trusted_install_evidence(&self) -> Result<bool> {
tokio::task::spawn_blocking(crate::core::service::trusted_service_evidence) let registered = tokio::task::spawn_blocking(crate::core::service::trusted_service_evidence)
.await .await
.context("service registration probe did not finish")? .context("service registration probe did not finish")??;
// A helper that outlived its registration is a broken Service, not an absent one.
#[cfg(unix)]
if !registered && let Err(error) = clash_verge_service_ipc::execution::check_sidecar_available().await {
return Ok(error
.downcast_ref::<clash_verge_service_ipc::execution::ResidualServiceError>()
.is_some());
}
Ok(registered)
} }
fn is_elevated(&self) -> bool { fn is_elevated(&self) -> bool {

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