Compare commits

..
Author SHA1 Message Date
Tunglies a987ea9f6d refactor(subscription): keep profile writes outside proxy fallback 2026-12-02 02:10:09 +08:00
Tunglies e290a7946d refactor(backup): extract backup ZIP writing 2026-12-02 02:10:09 +08:00
Tunglies 59e315abeb refactor(task): move retry primitives into the task crate 2026-12-02 02:10:09 +08:00
Tunglies 87b3cf6561 docs(agents): define dependencies between capability crates 2026-12-02 02:10:09 +08:00
Tunglies 0010659329 refactor(profile): extract selected node recovery rules 2026-12-02 02:10:09 +08:00
Tunglies e30f1b0e47 refactor(subscription): decode deep links in the subscription crate 2026-12-02 02:10:09 +08:00
Tunglies c3c65bb418 refactor(profile): separate subscription refresh and scheduling policy
Separate download and scheduling policy from the subscription use case while retaining the existing write path.
2026-12-02 02:10:09 +08:00
Tunglies 9de413db1e refactor(profile): extract profile models and index rules
Move profile models and index rules into the crate, preserving serialization and returning a typed missing-profile error.
2026-12-02 02:10:09 +08:00
Tunglies 0605236489 refactor(subscription): extract response decoding
Keep HTTP and persistence in the app. Decode response metadata and framing in the crate, and fall back when the server filename is invalid.
2026-12-02 02:10:09 +08:00
Tunglies b5b939ce03 refactor(logging): use typed logger errors
Expose crate-owned logger errors and preserve the underlying error sources.
2026-12-02 02:10:09 +08:00
Tunglies 6fdbea3748 refactor(draft): type async publication conflicts
Return typed conflicts for async Draft edits. Release the lock and edit permit before converting the error, and exercise overlapping updates.
2026-12-02 02:10:09 +08:00
Tunglies 12b2e340ca docs(agents): define Rust backend architecture boundaries
Document which layer owns Rust capabilities, fallible inputs, background work, and crate validation.
2026-12-02 02:10:09 +08:00
Tunglies 4cc3a2fd0c chore(clippy): scope crate lint policy
Keep panic-on-error lints at application target roots and scope signal dependencies to Linux.
2026-12-02 02:10:09 +08:00
❤是纱雾酱哟~andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 37ff669436 chore(deps): update dependency tldts to v7.6.4 (#8805)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-01 17:56:26 +00:00
❤是纱雾酱哟~ b45f12a21e chore(deps): upgrade 4 npm dependencies in a batch (#8803)
- Bump eslint from ^10.11.0 to ^10.16.0
- Bump eslint-plugin-import-x from ^4.17.1 to ^4.18.1
- Bump typescript-eslint from ^8.70.0 to ^8.74.0
- Bump vitest from ^5.0.1 to ^5.0.3

Assisted-by: Copilot Fusion (Standard), actually GPT-6.1 Terra

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
2026-12-01 16:53:50 +00:00
dependabot[bot]anddependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 81e62504a6 build(deps): bump cross-spawn (#8799)
Bumps the npm_and_yarn group with 1 update in the / directory: [cross-spawn](https://github.com/moxystudio/node-cross-spawn).


Updates `cross-spawn` from 7.0.6 to 7.1.2
- [Release notes](https://github.com/moxystudio/node-cross-spawn/releases)
- [Changelog](https://github.com/moxystudio/node-cross-spawn/blob/master/CHANGELOG.md)
- [Commits](https://github.com/moxystudio/node-cross-spawn/compare/v7.0.6...v7.1.2)

---
updated-dependencies:
- dependency-name: cross-spawn
  dependency-version: 7.1.2
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-12-01 14:17:43 +00:00
renovate[bot]andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 251fb0e12e chore(deps): update dependency pnpm to v12.25.1 (#8798)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-01 13:44:59 +00:00
renovate[bot]andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 623f568116 chore(deps): update dependency react-router to v8.5.1 [security] (#8792)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-01 07:34:16 +00:00
renovate[bot]andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 4d387243e8 chore(deps): update node.js to v26.14.0 (#8793)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-01 07:34:13 +00:00
renovate[bot]andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 074aaee18c chore(deps): update dependency tldts to v7.6.3 (#8785)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-30 14:12:28 +00:00
renovate[bot]renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>❤是纱雾酱哟~
6d1069abd4 chore(deps): update github/gh-aw-actions action to v1.4.2 (#8773)
* chore(deps): update github/gh-aw-actions action to v1.4.2

* chore(gh-aw): bump agentic workflows from 1.4.1 to 1.4.2

- Version bump via `gh aw upgrade`

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>

---------

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
2026-11-30 13:58:27 +00:00
Jeferson Araujo b484a8f24c fix(i18n): translate the connection rule dialog to pt-BR (#8771) 2026-11-30 08:30:04 +00:00
❤是纱雾酱哟~andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> e04fae62d9 chore(deps): update dependency tar to v8 (#8769)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-29 14:25:03 +00:00
❤是纱雾酱哟~andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 4ce69ec2b1 chore(deps): update dependency knip to v6.49.0 (#8768)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-29 14:19:06 +00:00
❤是纱雾酱哟~ 8d242b5732 chore(agents): adds instructions for GitHub Copilot (#8765)
- Create `.github/copilot-instructions.md` as agent-specific instruction
  file for GitHub Copilot
- Use "one-line-wrapper" prompt to `AGENTS.md`, like `GEMINI.md`
- Use "at annotation syntax" for instructions importing, like
  `CLAUDE.md`

Assisted-by: Copilot Fusion (High), actually GPT-6.1 Sol, GPT-6.1 Terra and GPT-6 Luna

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
2026-11-29 08:30:36 +00:00
98 changed files with 3967 additions and 3536 deletions
+2 -2
View File
@@ -4,8 +4,8 @@
"features": {
"ghcr.io/devcontainers/features/node:2": {
"version": "26.13.1",
"pnpmVersion": "12.23.0"
"version": "26.14.0",
"pnpmVersion": "12.25.1"
},
"ghcr.io/devcontainers/features/rust:1": {
"version": "1.100.1",
+65 -263
View File
@@ -1,275 +1,77 @@
---
name: Agentic Workflows
description: GitHub Agentic Workflows (gh-aw) - Create, debug, and upgrade AI-powered workflows with intelligent prompt routing.
description: Routes GitHub Agentic Workflows tasks to focused authoring, debugging, and reference guidance.
disable-model-invocation: true
---
# GitHub Agentic Workflows Agent
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.
Dispatch gh-aw tasks to the matching prompt or reference. Load only what the task
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.
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.
## Execution and safety
## Repository Instructions Overlay
Load the target repository's `.github/aw/instructions.md`, if present.
Use `@.github/aw/instructions.md` only in a matching checkout; do not substitute
a guidance-repository overlay.
Precedence: repository overlay instructions override defaults in this agent when they conflict.
- For incident, health, and failure-related optimization requests,
use intent routing before generic update, upgrade, or optimization routes.
First load
[debug-bootstrap.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-bootstrap.md)
from the resolved guidance repository/ref, even when the CLI is installed.
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.
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
This is a **dispatcher agent** that routes your request to the appropriate specialized prompt based on your task:
- **Creating new workflows**: Routes to `create` 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`.
Workflows may optionally include:
- **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`
- **Creating new workflows**: [create-agentic-workflow.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-agentic-workflow.md)
- **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
selected design prompt.
For general workflow authoring, load
[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 -->
+32 -7
View File
@@ -5,10 +5,10 @@
"version": "v9.0.0",
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
},
"github/gh-aw-actions/setup@v1.4.1": {
"github/gh-aw-actions/setup@v1.4.2": {
"repo": "github/gh-aw-actions/setup",
"version": "v1.4.1",
"sha": "367d4dc4e89caf85422092845006e4a4a660d926"
"version": "v1.4.2",
"sha": "d7852d91d5d1d13e7848771edab8bd1792a08651"
}
},
"containers": {
@@ -52,6 +52,11 @@
"digest": "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": {
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13",
"digest": "sha256:61f12dcff38eb008b645d87a5541763452f409d9040eb243718764944167b1a2",
@@ -92,6 +97,11 @@
"digest": "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": {
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11",
"digest": "sha256:97782bc0d8ff7f80f19ae2fdc5e1668517aa732a6fa077e64b8d3919238496d2",
@@ -112,6 +122,11 @@
"digest": "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": {
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.14",
"digest": "sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0",
@@ -127,6 +142,11 @@
"digest": "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": {
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13",
"digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56",
@@ -167,10 +187,15 @@
"digest": "sha256:ccc189ace632f3f42fa2ee1e77feb67d438e0975c591520da3f473c132e6216d",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.21@sha256:ccc189ace632f3f42fa2ee1e77feb67d438e0975c591520da3f473c132e6216d"
},
"ghcr.io/github/gh-aw-mcpg:v0.5.15": {
"image": "ghcr.io/github/gh-aw-mcpg:v0.5.15",
"digest": "sha256:3f6567e6db31d820e43031fa17a745e5a056fd074604192a884ac12a443ff5c1",
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.5.15@sha256:3f6567e6db31d820e43031fa17a745e5a056fd074604192a884ac12a443ff5c1"
"ghcr.io/github/gh-aw-firewall/squid:0.29.22": {
"image": "ghcr.io/github/gh-aw-firewall/squid:0.29.22",
"digest": "sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"
},
"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": {
"image": "ghcr.io/github/gh-aw-node",
+5
View File
@@ -0,0 +1,5 @@
# GitHub Copilot Instructions
Read and follow [AGENTS.md](../AGENTS.md) before working in this repository.
@../AGENTS.md
@@ -100,6 +100,7 @@ Use the task routes above first. This inventory is not required startup context.
- `.github/aw/charts.md`
- `.github/aw/cli-commands.md`
- `.github/aw/compat.md`
- `.github/aw/connectors-authoring.md`
- `.github/aw/connectors.md`
- `.github/aw/context.md`
- `.github/aw/create-agentic-workflow-design.md`
@@ -148,6 +149,7 @@ Use the task routes above first. This inventory is not required startup context.
- `.github/aw/maintainer.md`
- `.github/aw/mcp-clis.md`
- `.github/aw/memory-stateful-patterns.md`
- `.github/aw/memory-wiki-comment.md`
- `.github/aw/memory.md`
- `.github/aw/messages.md`
- `.github/aw/multi-agent-research.md`
+5 -5
View File
@@ -51,7 +51,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- name: Install dependencies
run: pnpm install --frozen-lockfile
@@ -182,7 +182,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -262,7 +262,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -395,7 +395,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -479,7 +479,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6.1.1
name: Install pnpm
+1 -1
View File
@@ -63,7 +63,7 @@ jobs:
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
+3 -3
View File
@@ -31,9 +31,9 @@ jobs:
with:
persist-credentials: false
- name: Install gh-aw extension
uses: github/gh-aw-actions/setup-cli@367d4dc4e89caf85422092845006e4a4a660d926 # v1.4.1
uses: github/gh-aw-actions/setup-cli@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
with:
version: v1.4.1
version: v1.4.2
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@stable
with:
@@ -49,7 +49,7 @@ jobs:
- name: Install Node.js
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Install frontend dependencies
env:
+1 -1
View File
@@ -43,7 +43,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
+1 -1
View File
@@ -104,7 +104,7 @@ jobs:
if: github.event.inputs[matrix.input] == 'true'
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- 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
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
if: github.event.action != 'closed'
+8 -8
View File
@@ -46,7 +46,7 @@ jobs:
fetch-depth: 0
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- name: Validate source and publish the approved snapshot
id: source
env:
@@ -231,7 +231,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -330,7 +330,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -461,7 +461,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -542,7 +542,7 @@ jobs:
fetch-depth: 0
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
with:
run_install: false
@@ -565,7 +565,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
@@ -593,7 +593,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
@@ -661,7 +661,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
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
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- name: Install pnpm
uses: pnpm/action-setup@v6
+1 -1
View File
@@ -31,7 +31,7 @@ jobs:
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- name: Sync Mihomo version
id: sync
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
+2 -2
View File
@@ -15,7 +15,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
@@ -39,7 +39,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
+2 -2
View File
@@ -1,3 +1,3 @@
nodejs 26.13.1
pnpm 12.23.0
nodejs 26.14.0
pnpm 12.25.1
rust 1.100.1
+4
View File
@@ -60,6 +60,10 @@ the ownership evidence the AI-slop review evaluates (see
- For development and bug fixes, follow the
[development workflow](CONTRIBUTING.md#development-workflow).
- For Rust backend changes that affect capability ownership or dependency
boundaries, follow [Workspace Crate Architecture](crates/AGENTS.md).
For Tauri commands and desktop integration, also follow
[Backend Architecture Guardrails](src-tauri/AGENTS.md).
- For code review and verification of review fixes, follow [REVIEW.md](REVIEW.md).
Review is read-only unless changes are authorized; findings do not expand
that authorization to unrelated fixes, commits, pushes, or GitHub updates.
Generated
+277 -191
View File
File diff suppressed because it is too large Load Diff
+11 -5
View File
@@ -9,6 +9,9 @@ members = [
"crates/tauri-plugin-clash-verge-sysinfo",
"crates/clash-verge-i18n",
"crates/clash-verge-limiter",
"crates/clash-verge-subscription",
"crates/clash-verge-profile",
"crates/clash-verge-backup-archive",
]
resolver = "2"
@@ -59,15 +62,19 @@ clash-verge-logging = { path = "crates/clash-verge-logging" }
clash-verge-signal = { path = "crates/clash-verge-signal" }
clash-verge-i18n = { path = "crates/clash-verge-i18n" }
clash-verge-limiter = { path = "crates/clash-verge-limiter" }
clash-verge-subscription = { path = "crates/clash-verge-subscription" }
clash-verge-profile = { path = "crates/clash-verge-profile" }
clash-verge-backup-archive = { path = "crates/clash-verge-backup-archive" }
tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" }
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
tracing = "0.1.44"
tauri = { version = "=3.0.0-alpha.6" }
tauri-runtime-wry = "=3.0.0-alpha.6"
tauri-plugin-clipboard-manager = "=3.0.0-alpha.3"
tauri = { version = "2.12.7" }
tauri-plugin-clipboard-manager = "2.5.0"
parking_lot = "0.13.0"
anyhow = "1.0.105"
thiserror = "2.0.20"
zip = "9.9.0"
futures = "0.3.34"
chrono = "0.4.45"
criterion = { version = "0.8.2", features = ["async_tokio"] }
@@ -92,6 +99,7 @@ serde = { version = "1.0.229" }
tristr = { git = "https://github.com/Tunglies/tristr", rev = "d849e5cff47a570849c2e1bada0a2b6481cf3378", default-features = false, features = ["serde", "specta"] }
serde_json = { version = "1.0.154" }
serde_yaml_ng = { version = "0.10.0" }
specta = "=2.0.0-rc.26"
socket2 = "0.6.5"
# *** For Windows platform only ***
@@ -125,7 +133,6 @@ copy_iterator = "deny"
correctness = { level = "deny", priority = -1 }
dbg_macro = "warn"
equatable_if_let = "deny"
expect_used = "warn"
expl_impl_clone_on_copy = "deny"
future_not_send = "deny"
iter_on_empty_collections = "deny"
@@ -164,7 +171,6 @@ unnecessary_self_imports = "deny"
unnecessary_wraps = "deny"
unused_async = "deny"
unused_trait_names = "deny"
unwrap_used = "warn"
use_self = "deny"
useless_let_if_seq = "deny"
wildcard_imports = "deny"
+1
View File
@@ -33,6 +33,7 @@
- 修复检测更新后又发布新版时,应用内更新失败
- 修复关闭「自动检查更新」后,手动检查更新时弹窗空白
- 修复订阅响应过大导致内存占用过高,限制单次下载为 4 MiB
- 修复服务端文件名无效时导入的订阅名称为空
- 修复全局模式默认停在 `DIRECT` 或 `REJECT` 导致流量未经代理,现自动切换到第一个策略组
- 修复订阅中未加引号的 REALITY `short-id`(如 `1234e123`)被误读为数字,导致订阅无法启用
- 修复订阅中唯一的代理组名为 `GLOBAL` 或没有代理组时,规则模式下代理页面显示「未获取到代理信息」
+5
View File
@@ -0,0 +1,5 @@
# Clippy loads a single configuration file, so repeat the workspace defaults.
avoid-breaking-exported-api = true
allow-unwrap-in-tests = true
cognitive-complexity-threshold = 25
excessive-nesting-threshold = 5
+46 -9
View File
@@ -2,19 +2,34 @@
## Choose the boundary
- Apply Functional Core, Imperative Shell and Ports and Adapters. Keep domain
types, invariants, parsing, validation, and deterministic transitions
independent of Tauri, concrete OS APIs, and implicit application state.
- Keep use cases, async coordination, cancellation, and timeouts in
framework-independent application modules. Pass dependencies explicitly.
Define ports where an external effect needs a contract. Adapters implement
the contracts owned by their consumers. Keep filesystem, network, IPC, process,
and OS-specific operations in their adapters.
- Extract a capability whose invariants can be owned behind a small API. Before
creating a crate, identify its owner, what callers supply, and what can be
verified through the crate API. Keep a module when the proposed boundary only
relocates implementation or introduces a pass-through API.
- Keep the dependency direction from the app to the crate. Resolve app paths,
read product settings, start app-owned tasks, and publish UI events in the app.
Pass the values, resources, or callbacks the crate needs. For example,
verified through the crate API. Extract a crate when it provides a useful
dependency, portability, testing, or ownership boundary. Keep a module when
the proposed boundary only relocates implementation or introduces a
pass-through API.
- Keep capability crates independent by default. Compose peer capabilities in
the application and pass inputs or callbacks through the consumer's API.
Depend on another workspace crate for foundational mechanisms such as logging
and task primitives, or for a shared domain contract required to enforce the
same invariant. Keep tightly coupled rules together when separating them
would duplicate that contract or split its ownership.
- Keep dependencies pointing toward domain and application contracts. Resolve
app paths and read current settings at the application boundary. Pass in the
required values, resources, or callbacks. For example,
[logging](clash-verge-logging/src/lib.rs) owns its pipeline and writers while the
app supplies directories and limits through `LoggerConfig`.
- Keep framework and platform dependencies scoped to the capability that needs
them. Runtime-independent logic should be runnable without the desktop app.
A platform adapter can own runtime startup when its resource lifetime requires
it, as [signal](clash-verge-signal/src/lib.rs) does for Linux shutdown.
- Run framework-independent tests without starting the desktop app. A platform
adapter can own runtime startup when its resource lifetime requires it, as
[signal](clash-verge-signal/src/lib.rs) does for Linux shutdown.
## Design the API
@@ -31,6 +46,14 @@
workspace lints. Reuse workspace dependencies where available and declare
only the features the crate needs.
## Handle fallible input
- Define crate-owned error types with `thiserror` in a dedicated `error` module.
Re-export public errors through their established import paths.
- Crates may use `unwrap()` or `expect()` for internal invariants. Propagate
errors from required external data and use defaults only when the input
contract gives the default a meaning.
## Own background work
- Give ordered start, replacement, and cleanup to one task owner. Reuse
@@ -43,6 +66,20 @@
transaction boundaries and keep the reply path free of locks held by the
waiting caller. Cancel only at safe boundaries and own issued effects through
completion or explicit reconciliation.
- Distinguish requested effects from completed effects in typed outcomes.
Define how failures, cancellation, and timeouts affect publication, retry,
rollback, or reconciliation.
## Validate new crates
- Fuzz the public boundary before tuning. Exercise malformed input, fallback
behavior, and failures that can affect user data. Preserve the corpus and
record the baseline revision and dependency resolution.
- Try at least one targeted performance improvement. Compare the baseline and
candidate on the same workload and build settings. Record stable gains, flat
cases, and regressions, and justify which changes to keep.
- Fuzz the final candidate again. Use the baseline corpus and compare outputs,
diagnostics, and errors with the baseline where behavior should be preserved.
Verify the extracted contract through its public API when practical. Use
`cargo test -p <crate>` for focused tests and keep native behavior checks at the
@@ -0,0 +1,11 @@
[package]
name = "clash-verge-backup-archive"
version = "0.1.0"
edition = "2024"
[dependencies]
thiserror = { workspace = true }
zip = { workspace = true }
[lints]
workspace = true
@@ -0,0 +1,13 @@
#[derive(Debug, thiserror::Error)]
pub enum ArchiveError {
#[error(transparent)]
Zip(#[from] zip::result::ZipError),
#[error(transparent)]
Io(#[from] std::io::Error),
#[error("backup contains a symbolic link")]
Symlink,
#[error("backup contains an invalid path")]
InvalidPath,
#[error("archive contains profile recovery data")]
ReservedEntry,
}
@@ -0,0 +1,104 @@
mod error;
pub use error::ArchiveError;
use std::{
io::{self, Read, Seek, Write},
path::{Component, Path},
};
use zip::{CompressionMethod, ZipArchive, ZipWriter, write::SimpleFileOptions};
pub struct BackupWriter<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()?)
}
}
pub struct ValidatedBackup<R: Read + Seek> {
zip: ZipArchive<R>,
}
impl<R: Read + Seek> ValidatedBackup<R> {
pub fn open(source: R, reserved_names: &[&str]) -> Result<Self, ArchiveError> {
let mut zip = ZipArchive::new(source)?;
for index in 0..zip.len() {
let mut entry = zip.by_index(index)?;
if entry.is_symlink() {
return Err(ArchiveError::Symlink);
}
let path = entry.enclosed_name().ok_or(ArchiveError::InvalidPath)?;
for component in path.components() {
let Component::Normal(name) = component else {
continue;
};
let name = name.to_string_lossy();
if reserved_names
.iter()
.any(|reserved| name.eq_ignore_ascii_case(reserved))
{
return Err(ArchiveError::ReservedEntry);
}
}
io::copy(&mut entry, &mut io::sink())?;
}
Ok(Self { zip })
}
pub fn extract_to(mut self, destination: &Path) -> Result<(), ArchiveError> {
self.zip.extract(destination)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
#[test]
fn writes_and_validates_the_backup_layout() -> Result<(), ArchiveError> {
let mut writer = BackupWriter::new(Cursor::new(Vec::new()))?;
writer.start_profile("example.yaml")?.write_all(b"proxies: []\n")?;
writer.start_file("profiles.yaml")?.write_all(b"items: []\n")?;
let source = writer.finish()?;
let mut zip = ZipArchive::new(source.clone())?;
assert_eq!(zip.len(), 3);
assert_eq!(zip.by_index(0)?.name()?, "profiles/");
let profile_time = {
let mut entry = zip.by_index(1)?;
assert_eq!(entry.name()?, "profiles/example.yaml");
assert_eq!(entry.compression(), CompressionMethod::Stored);
let mut contents = Vec::new();
entry.read_to_end(&mut contents)?;
assert_eq!(contents, b"proxies: []\n");
entry.last_modified()
};
let index = zip.by_index(2)?;
assert_eq!(index.name()?, "profiles.yaml");
assert_eq!(index.last_modified(), profile_time);
ValidatedBackup::open(source, &[".profile-refresh", ".profile-refresh.lock"])?;
Ok(())
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ harness = false
[dependencies]
parking_lot = { workspace = true }
anyhow = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }
[dev-dependencies]
+3 -3
View File
@@ -2,7 +2,7 @@ use criterion::{Criterion, criterion_group, criterion_main};
use std::hint::black_box;
use tokio::runtime::Runtime;
use clash_verge_draft::Draft;
use clash_verge_draft::{Draft, DraftConflict};
#[derive(Default, Clone, Debug)]
struct IVerge {
@@ -99,8 +99,8 @@ pub fn bench_draft(c: &mut Criterion) {
group.bench_function("with_data_modify_async", |b| {
b.to_async(&rt).iter(|| async {
let draft = black_box(make_draft());
let _: Result<(), anyhow::Error> = draft
.with_data_modify::<_, _, _>(|mut box_data| async move {
let _: Result<(), DraftConflict> = draft
.with_data_modify(|mut box_data| async move {
box_data.enable_auto_launch = Some(!box_data.enable_auto_launch.unwrap_or(false));
Ok((box_data, ()))
})
+12
View File
@@ -0,0 +1,12 @@
/// Committed data changed before an asynchronous edit could publish.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("Optimistic lock failed: Committed data has changed during async operation")]
pub struct DraftConflict;
/// Another transaction is already staging a change to one of the layers asked for.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("configuration layer {layer} is being changed elsewhere")]
pub struct DraftBusy {
/// The layer that was already claimed.
pub layer: &'static str,
}
+12 -25
View File
@@ -1,3 +1,7 @@
mod error;
pub use error::{DraftBusy, DraftConflict};
use parking_lot::Mutex;
use std::sync::Arc;
use std::sync::atomic::{
@@ -91,14 +95,16 @@ impl<T: Clone> Draft<T> {
}
/// Optimistically replaces committed data after an asynchronous edit.
/// The caller's error type carries both edit failures and publication conflicts.
#[inline]
pub async fn with_data_modify<F, Fut, R>(&self, f: F) -> Result<R, anyhow::Error>
pub async fn with_data_modify<F, Fut, R, E>(&self, f: F) -> Result<R, E>
where
T: Send + Sync + 'static,
F: FnOnce(T) -> Fut + Send,
Fut: std::future::Future<Output = Result<(T, R), anyhow::Error>> + Send,
Fut: std::future::Future<Output = Result<(T, R), E>> + 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 guard = self.inner.data.lock();
let arc = Arc::clone(&guard.0);
@@ -108,9 +114,9 @@ impl<T: Clone> Draft<T> {
let (new_local, res) = f(local).await?;
let mut guard = self.inner.data.lock();
if !Arc::ptr_eq(&guard.0, &original_arc) {
return Err(anyhow::anyhow!(
"Optimistic lock failed: Committed data has changed during async operation"
));
drop(guard);
drop(permit);
return Err(DraftConflict.into());
}
guard.0 = Arc::new(Box::new(new_local));
drop(guard);
@@ -191,25 +197,6 @@ impl<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.
///
/// A layer has one draft slot, so concurrent transactions cannot be isolated and are rejected.
+14 -9
View File
@@ -1,6 +1,6 @@
use std::sync::Arc;
use clash_verge_draft::{Draft, DraftTransaction};
use clash_verge_draft::{Draft, DraftBusy, DraftConflict, DraftTransaction};
use tokio::sync::Notify;
#[derive(Clone, Debug, Default, PartialEq)]
@@ -28,14 +28,19 @@ fn edits_can_be_committed_or_discarded() {
}
#[tokio::test]
async fn async_updates_are_serialized() -> anyhow::Result<()> {
async fn async_updates_are_serialized() -> Result<(), Box<dyn std::error::Error>> {
let draft = Arc::new(Draft::new(0_u8));
let mut updates = Vec::new();
for _ in 0..16 {
let draft = Arc::clone(&draft);
updates.push(tokio::spawn(async move {
draft.with_data_modify(|value| async move { Ok((value + 1, ())) }).await
draft
.with_data_modify(|value| async move {
tokio::task::yield_now().await;
Ok::<_, DraftConflict>((value + 1, ()))
})
.await
}));
}
for update in updates {
@@ -47,7 +52,7 @@ async fn async_updates_are_serialized() -> anyhow::Result<()> {
}
#[tokio::test]
async fn async_update_rejects_a_changed_committed_value() -> anyhow::Result<()> {
async fn async_update_rejects_a_changed_committed_value() -> Result<(), Box<dyn std::error::Error>> {
let draft = Arc::new(Draft::new(Config::default()));
let started = Arc::new(Notify::new());
let finish = Arc::new(Notify::new());
@@ -61,7 +66,7 @@ async fn async_update_rejects_a_changed_committed_value() -> anyhow::Result<()>
started.notify_one();
finish.notified().await;
config.enabled = true;
Ok((config, ()))
Ok::<_, DraftConflict>((config, ()))
})
.await
})
@@ -72,14 +77,14 @@ async fn async_update_rejects_a_changed_committed_value() -> anyhow::Result<()>
draft.apply();
finish.notify_one();
assert!(update.await?.is_err());
assert_eq!(update.await?, Err(DraftConflict));
assert!(!draft.data_arc().enabled);
assert_eq!(draft.data_arc().port, 7897);
Ok(())
}
#[test]
fn transaction_commits_every_layer() -> anyhow::Result<()> {
fn transaction_commits_every_layer() -> Result<(), DraftBusy> {
let first = Draft::new(1_u8);
let second = Draft::new(String::from("a"));
let transaction = DraftTransaction::begin(vec![&first, &second])?;
@@ -94,7 +99,7 @@ fn transaction_commits_every_layer() -> anyhow::Result<()> {
}
#[test]
fn dropped_transaction_rolls_every_layer_back() -> anyhow::Result<()> {
fn dropped_transaction_rolls_every_layer_back() -> Result<(), DraftBusy> {
let first = Draft::new(1_u8);
let second = Draft::new(String::from("a"));
@@ -110,7 +115,7 @@ fn dropped_transaction_rolls_every_layer_back() -> anyhow::Result<()> {
}
#[test]
fn transaction_claims_are_exclusive_and_release_partial_claims() -> anyhow::Result<()> {
fn transaction_claims_are_exclusive_and_release_partial_claims() -> Result<(), DraftBusy> {
let first = Draft::new(1_u8);
let second = Draft::new(2_u8);
let held = DraftTransaction::begin(vec![&second])?;
+1 -1
View File
@@ -6,7 +6,7 @@ edition = "2024"
[dependencies]
log = { workspace = true }
parking_lot = { workspace = true }
anyhow = { workspace = true }
thiserror = { workspace = true }
flexi_logger = { workspace = true }
tracing-estuary = { workspace = true }
+11
View File
@@ -0,0 +1,11 @@
#[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),
}
+18 -12
View File
@@ -1,3 +1,7 @@
mod error;
pub use error::LoggerError;
use std::{
collections::VecDeque,
fmt,
@@ -10,7 +14,6 @@ use std::{
time::Duration,
};
use anyhow::{Result, bail};
use flexi_logger::{
Cleanup, Criterion, DeferredNow, FileSpec, Naming,
writers::{FileLogWriter, FileLogWriterBuilder, LogWriter as _},
@@ -177,7 +180,7 @@ impl Logger {
/// Installs the global tracing pipeline. `RUST_LOG` (parsed as a bare
/// level) overrides the configured level.
pub fn init(&self, cfg: &LoggerConfig) -> Result<()> {
pub fn init(&self, cfg: &LoggerConfig) -> Result<(), LoggerError> {
let log_level = std::env::var("RUST_LOG")
.ok()
.and_then(|v| LevelFilter::from_str(v.trim()).ok())
@@ -186,14 +189,15 @@ impl Logger {
let pipeline = tracing_estuary::PipelineBuilder::new()
.default_level(log_level)
.file_writer(self.generate_file_log_writer())
.init()?;
.init()
.map_err(|error| LoggerError::Pipeline(error.into_boxed_dyn_error()))?;
self.pipeline.set(pipeline).ok();
Ok(())
}
/// Installs the sidecar file writer and the panic hook. Safe to call when
/// the pipeline is owned elsewhere (e.g. a devtools-provided subscriber).
pub fn init_sidecar(&self, cfg: &LoggerConfig) -> Result<()> {
pub fn init_sidecar(&self, cfg: &LoggerConfig) -> Result<(), LoggerError> {
self.store_config(cfg);
self.ensure_sidecar_writer(self.generate_sidecar_builder())?;
@@ -245,7 +249,7 @@ impl Logger {
/// Ensures the sidecar writer exists and points at `builder`'s config:
/// built once, then reset in place — flexi's flusher thread cannot be
/// stopped, so every dropped writer would leak a thread and an fd.
fn ensure_sidecar_writer(&self, builder: FileLogWriterBuilder) -> Result<()> {
fn ensure_sidecar_writer(&self, builder: FileLogWriterBuilder) -> Result<(), LoggerError> {
let sidecar = self.sidecar_file_writer.write();
match sidecar.as_ref() {
Some(writer) => {
@@ -296,27 +300,29 @@ impl Logger {
}
/// only update app log level
pub fn update_log_level(&self, level: LevelFilter) -> Result<()> {
pub fn update_log_level(&self, level: LevelFilter) -> Result<(), LoggerError> {
if let Some(pipeline) = self.pipeline.get() {
pipeline.filter.set_default_level(level)?;
pipeline
.filter
.set_default_level(level)
.map_err(|error| LoggerError::Pipeline(error.into_boxed_dyn_error()))?;
} else {
bail!("failed to get tracing pipeline, make sure it init");
return Err(LoggerError::PipelineUnavailable);
};
Ok(())
}
/// Rebuilds both file writers with the new limits.
pub fn update_log_config(&self, log_max_size: u64, log_max_count: usize) -> Result<()> {
pub fn update_log_config(&self, log_max_size: u64, log_max_count: usize) -> Result<(), LoggerError> {
self.log_max_size.store(log_max_size, Ordering::SeqCst);
self.log_max_count.store(log_max_count, Ordering::SeqCst);
if let Some(pipeline) = self.pipeline.get() {
let log_file_writer = self.generate_file_log_writer();
if let Some(sink) = pipeline.sink.as_ref() {
sink.reset(log_file_writer)
.map_err(|error| anyhow::anyhow!("failed to reset log writer: {error}"))?;
sink.reset(log_file_writer).map_err(LoggerError::ResetWriter)?;
}
} else {
bail!("failed to get tracing pipeline, make sure it init");
return Err(LoggerError::PipelineUnavailable);
};
self.ensure_sidecar_writer(self.generate_sidecar_builder())?;
Ok(())
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "clash-verge-profile"
version = "0.1.0"
edition = "2024"
[dependencies]
serde = { workspace = true, features = ["derive"] }
specta = { workspace = true, features = ["derive"] }
thiserror = { workspace = true }
tristr = { workspace = true }
[dev-dependencies]
serde_json = { workspace = true }
serde_yaml_ng = { workspace = true }
[lints]
workspace = true
+5
View File
@@ -0,0 +1,5 @@
#[derive(Debug, thiserror::Error)]
#[error("failed to get the profile item \"uid:{uid}\"")]
pub struct ProfileNotFound {
pub(super) uid: String,
}
+410
View File
@@ -0,0 +1,410 @@
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_str = uid.as_ref();
if let Some(items) = self.items.as_ref() {
for each in items.iter() {
if let Some(uid_val) = &each.uid
&& uid_val.as_str() == uid_str
{
return Ok(each);
}
}
}
Err(ProfileNotFound {
uid: uid_str.to_owned(),
})
}
/// Inserts a prepared entry after any required body write.
pub fn append_item(&mut self, item: &PrfItem) {
if self.current.is_none() && matches!(item.itype.as_deref(), Some("remote" | "local")) {
self.current = item.uid.clone();
}
self.items.get_or_insert_with(Vec::new).push(item.clone());
}
/// Returns true if both IDs were found, including when the item stayed at its old position.
pub fn reorder(&mut self, active_id: &str, over_id: &str) -> bool {
let Some(items) = self.items.as_mut() else {
return false;
};
let old_index = items.iter().rposition(|item| item.uid.as_deref() == Some(active_id));
let new_index = items.iter().rposition(|item| item.uid.as_deref() == Some(over_id));
let (Some(old_idx), Some(new_idx)) = (old_index, new_index) else {
return false;
};
let item = items.remove(old_idx);
items.insert(new_idx, item);
true
}
pub fn plan_delete_item(&mut self, uid: &str) -> Result<ProfileDeletePlan, ProfileNotFound> {
let deleting_current = self.current.as_deref().is_none_or(|current| current == uid);
let delete_uids = self.get_item(uid)?.option.as_ref().map_or_else(Vec::new, |op| {
[
op.merge.clone(),
op.script.clone(),
op.rules.clone(),
op.proxies.clone(),
op.groups.clone(),
]
.into_iter()
.collect::<Vec<_>>()
});
let mut items = self.items.take().unwrap_or_default();
let mut files = Vec::new();
if let Some(file) = take_item_file_by_uid(&mut items, Some(uid)) {
files.push(file);
}
for delete_uid in delete_uids {
if let Some(file) = take_item_file_by_uid(&mut items, delete_uid.as_deref()) {
files.push(file);
}
}
if deleting_current {
self.current = None;
for item in items.iter() {
if matches!(item.itype.as_deref(), Some("remote" | "local")) {
self.current = item.uid.clone();
break;
}
}
}
self.items = Some(items);
Ok(ProfileDeletePlan {
deleting_current,
files,
})
}
pub fn profiles_preview(&self) -> Option<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 take_item_file_by_uid(items: &mut Vec<PrfItem>, target_uid: Option<&str>) -> Option<String> {
let index = items.iter().position(|item| item.uid.as_deref() == target_uid)?;
items.remove(index).file
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn old_index_preserves_missing_and_explicit_values() -> Result<(), Box<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(())
}
}
@@ -0,0 +1,147 @@
use super::PrfSelected;
use std::collections::HashSet;
use tristr::alias::String;
pub struct SelectedGroup<'a> {
pub members: Option<&'a [std::string::String]>,
pub current: Option<&'a str>,
pub selectable: bool,
}
#[derive(Debug, PartialEq, Eq)]
pub struct SelectedNodesPlan {
pub selected: Vec<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()
}
@@ -0,0 +1,49 @@
use super::PrfItem;
use std::time::Duration;
/// Scheduling policy for a Profile, independent of the task queue and clock.
#[derive(Debug, PartialEq, Eq)]
pub struct SubscriptionSchedule {
pub interval_minutes: u64,
pub first_delay: Duration,
}
impl SubscriptionSchedule {
pub fn for_profile(item: &PrfItem, initializing: bool, now: i64) -> Option<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.saturating_sub(updated as i64).max(0) as u64);
Self {
interval_minutes,
first_delay: full.saturating_sub(Duration::from_secs(elapsed)),
}
}
pub const fn interval_duration(interval_minutes: u64) -> Duration {
Duration::from_secs(interval_minutes.saturating_mul(60))
}
/// The UI deadline is based on the last saved update. The queue can delay retries further.
pub fn reported_deadline(interval_minutes: u64, updated: Option<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)
}
}
+1 -1
View File
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024"
rust-version = "1.91"
[dependencies]
[target.'cfg(target_os = "linux")'.dependencies]
clash-verge-logging = { workspace = true }
log = { workspace = true }
tokio = { workspace = true, features = ["signal"] }
@@ -0,0 +1,14 @@
[package]
name = "clash-verge-subscription"
version = "0.1.0"
edition = "2024"
[dependencies]
thiserror = { workspace = true }
http = "1"
percent-encoding = "2.3.2"
serde_yaml_ng = { workspace = true }
url = "2.5"
[lints]
workspace = true
@@ -0,0 +1,59 @@
use percent_encoding::percent_decode_str;
use std::borrow::Cow;
use url::Url;
pub struct SubscriptionLink<'a> {
pub url: Cow<'a, str>,
pub name: Option<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 raw_url = link.query()?.split_once("url=")?.1.trim();
let name = link.query_pairs().find(|(key, _)| key == "name").map(|(_, name)| name);
Some(SubscriptionLink {
url: decode_subscription_url(raw_url),
name,
})
}
fn decode_subscription_url(raw_url: &str) -> Cow<'_, str> {
let mut candidate = Cow::Borrowed(raw_url);
if Url::parse(raw_url).is_ok() {
return candidate;
}
for _ in 0..2 {
let decoded = percent_decode_str(&candidate).decode_utf8_lossy();
if decoded == candidate {
break;
}
candidate = Cow::Owned(decoded.into_owned());
if Url::parse(&candidate).is_ok() {
break;
}
}
candidate
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn preserves_nested_query_separators_and_decodes_wrapped_links() -> Result<(), url::ParseError> {
let plain = Url::parse("clash://install-config?name=Work%20VPN&url=https://example.invalid/sub?a=1&b=2")?;
let link = decode_subscription_link(&plain).expect("plain subscription link");
assert_eq!(link.name.as_deref(), Some("Work VPN"));
assert!(matches!(link.url, Cow::Borrowed("https://example.invalid/sub?a=1&b=2")));
let encoded = Url::parse("clash-verge://install-config?url=https%253A%252F%252Fexample.invalid%252Fsub")?;
let link = decode_subscription_link(&encoded).expect("double-encoded subscription link");
assert_eq!(link.url, "https://example.invalid/sub");
Ok(())
}
}
@@ -0,0 +1,7 @@
#[derive(Debug, thiserror::Error)]
pub enum SubscriptionError {
#[error("the remote profile data is invalid yaml")]
InvalidYaml(#[source] serde_yaml_ng::Error),
#[error("profile does not contain `proxies` or `proxy-providers`")]
MissingProviders,
}
+193
View File
@@ -0,0 +1,193 @@
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(value) = headers.get("content-disposition") {
let disposition = format!("{value:?}");
let disposition = disposition.trim_matches('"');
if let Some(encoded) = find_field(disposition, "filename*", Some)
&& let Ok(decoded) = percent_decode_str(encoded).decode_utf8()
&& let Some(filename) = decoded.split("''").last()
&& !filename.trim().is_empty()
{
return Some(filename.to_owned());
}
if let Some(filename) = find_field(disposition, "filename", Some).map(|name| name.trim_matches('"'))
&& !filename.trim().is_empty()
{
return Some(filename.to_owned());
}
}
let url = url.as_str();
let path = url.split_once('?').map_or(url, |(path, _)| path);
let filename = path.rsplit_once('/').map_or(path, |(_, filename)| filename);
let filename = percent_decode_str(filename).decode_utf8_lossy();
if filename.trim().is_empty() {
return None;
}
Some(filename.into_owned())
}
pub fn normalize_profile_home_url(raw: &str) -> Option<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 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(())
}
}
+2 -1
View File
@@ -1,5 +1,6 @@
//! Single-owner task drivers with caller-managed runtime and cancellation.
//! Task drivers and retry primitives with caller-managed runtime and cancellation.
pub mod countdown;
pub mod retry;
pub mod scheduled_task;
pub mod watch_task;
@@ -21,25 +21,29 @@ pub enum RetryError<E> {
Stop(E),
}
impl<E> RetryError<E> {
fn into_inner(self) -> E {
match self {
Self::Retry(error) | Self::Stop(error) => error,
}
}
}
pub async fn retry<T: Send, E: Send, Fut: Future<Output = Result<T, RetryError<E>>> + Send>(
policy: RetryPolicy,
mut operation: impl FnMut(usize) -> Fut + Send,
) -> Result<T, E> {
let mut result = operation(0).await;
for (index, delay) in policy.delays().enumerate() {
match result {
Ok(_) | Err(RetryError::Stop(_)) => break,
Err(RetryError::Retry(_)) => {
if !delay.is_zero() {
tokio::time::sleep(delay).await;
}
}
if !matches!(result, Err(RetryError::Retry(_))) {
break;
}
if !delay.is_zero() {
tokio::time::sleep(delay).await;
}
result = operation(index + 1).await;
}
result.map_err(|error| match error {
RetryError::Retry(error) | RetryError::Stop(error) => error,
})
result.map_err(RetryError::into_inner)
}
pub async fn try_strategies<
@@ -53,15 +57,14 @@ pub async fn try_strategies<
rest: [S; N],
mut operation: impl FnMut(S) -> Fut + Send,
) -> Result<(S, T), E> {
retry(
RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(N), Duration::ZERO),
move |attempt| {
let strategy = if attempt == 0 { first } else { rest[attempt - 1] };
let future = operation(strategy);
async move { future.await.map(|value| (strategy, value)).map_err(RetryError::Retry) }
},
)
.await
let mut result = operation(first).await.map(|value| (first, value));
for strategy in rest {
if result.is_ok() {
break;
}
result = operation(strategy).await.map(|value| (strategy, value));
}
result
}
pub async fn retry_with_state<S: Send, T: Send, E: Send>(
@@ -71,19 +74,15 @@ pub async fn retry_with_state<S: Send, T: Send, E: Send>(
) -> Result<T, E> {
let mut result = operation(&mut state, 0).await;
for (index, delay) in policy.delays().enumerate() {
match result {
Ok(_) | Err(RetryError::Stop(_)) => break,
Err(RetryError::Retry(_)) => {
if !delay.is_zero() {
tokio::time::sleep(delay).await;
}
}
if !matches!(result, Err(RetryError::Retry(_))) {
break;
}
if !delay.is_zero() {
tokio::time::sleep(delay).await;
}
result = operation(&mut state, index + 1).await;
}
result.map_err(|error| match error {
RetryError::Retry(error) | RetryError::Stop(error) => error,
})
result.map_err(RetryError::into_inner)
}
pub fn retry_sync<T, E>(
@@ -92,41 +91,39 @@ pub fn retry_sync<T, E>(
) -> Result<T, E> {
let mut result = operation(0);
for (index, delay) in policy.delays().enumerate() {
match result {
Ok(_) | Err(RetryError::Stop(_)) => break,
Err(RetryError::Retry(_)) => {
if !delay.is_zero() {
std::thread::sleep(delay);
}
}
if !matches!(result, Err(RetryError::Retry(_))) {
break;
}
if !delay.is_zero() {
std::thread::sleep(delay);
}
result = operation(index + 1);
}
result.map_err(|error| match error {
RetryError::Retry(error) | RetryError::Stop(error) => error,
})
result.map_err(RetryError::into_inner)
}
#[cfg(test)]
mod tests {
use super::*;
use std::future::ready;
#[tokio::test]
#[tokio::test(start_paused = true)]
async fn retries_stop_at_success_terminal_error_or_attempt_limit() {
let policy = RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(2), Duration::ZERO);
let delay = Duration::from_millis(50);
let policy = RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(2), delay);
let started = tokio::time::Instant::now();
let mut calls = 0;
let success = retry(policy, |attempt| {
calls += 1;
async move {
if attempt == 1 {
Ok(7)
} else {
Err(RetryError::Retry(attempt))
}
}
ready(if attempt == 1 {
Ok(7)
} else {
Err(RetryError::Retry(attempt))
})
})
.await;
assert_eq!((success, calls), (Ok(7), 2));
assert_eq!(started.elapsed(), delay);
calls = 0;
let stopped = retry(policy, |_| {
calls += 1;
@@ -134,6 +131,7 @@ mod tests {
})
.await;
assert_eq!((stopped, calls), (Err("terminal"), 1));
assert_eq!(started.elapsed(), delay);
calls = 0;
let exhausted = retry(policy, |attempt| {
calls += 1;
@@ -141,6 +139,7 @@ mod tests {
})
.await;
assert_eq!((exhausted, calls), (Err(2), 3));
assert_eq!(started.elapsed(), delay * 3);
}
#[tokio::test]
@@ -161,11 +160,9 @@ mod tests {
let result = retry_with_state(policy, Vec::new(), |visited, attempt| {
Box::pin(async move {
visited.push(attempt);
if visited.len() == 3 {
Ok(visited.clone())
} else {
Err(RetryError::Retry(()))
}
(visited.len() == 3)
.then(|| visited.clone())
.ok_or(RetryError::Retry(()))
})
})
.await;
+17 -17
View File
@@ -47,13 +47,13 @@
"@mui/icons-material": "^9.4.0",
"@mui/material": "^9.4.0",
"@tanstack/react-virtual": "^3.14.13",
"@tauri-apps/api": "3.0.0-alpha.3",
"@tauri-apps/plugin-clipboard-manager": "3.0.0-alpha.3",
"@tauri-apps/plugin-dialog": "3.0.0-alpha.4",
"@tauri-apps/plugin-fs": "3.0.0-alpha.3",
"@tauri-apps/plugin-http": "3.0.0-alpha.3",
"@tauri-apps/plugin-opener": "3.0.0-alpha.3",
"@tauri-apps/plugin-updater": "3.0.0-alpha.3",
"@tauri-apps/api": "2.12.5",
"@tauri-apps/plugin-clipboard-manager": "2.5.0",
"@tauri-apps/plugin-dialog": "2.8.4",
"@tauri-apps/plugin-fs": "2.7.1",
"@tauri-apps/plugin-http": "2.9.0",
"@tauri-apps/plugin-opener": "2.7.3",
"@tauri-apps/plugin-updater": "2.14.1",
"ahooks": "^3.10.0",
"cidr-block": "^2.3.0",
"dayjs": "1.11.23",
@@ -77,8 +77,8 @@
"rehype-raw": "^7.0.0",
"rehype-sanitize": "^6.0.0",
"swr": "^2.5.1",
"tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#8ddbec3a24eea8be18b5eaa1aba16f87f23e9583",
"tldts": "7.6.2",
"tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#main",
"tldts": "7.6.4",
"types-pac": "^1.0.3",
"validator": "^13.15.35"
},
@@ -87,7 +87,7 @@
"@biomejs/biome": "^2.5.14",
"@eslint-react/eslint-plugin": "^5.20.5",
"@eslint/js": "^10.0.1",
"@tauri-apps/cli": "3.0.0-alpha.6",
"@tauri-apps/cli": "2.12.6",
"@types/lodash-es": "^4.17.12",
"@types/node": "^26.0.0",
"@types/react": "19.3.3",
@@ -100,10 +100,10 @@
"cli-color": "^2.0.4",
"commander": "^15.0.0",
"cross-env": "^10.1.0",
"eslint": "^10.11.0",
"eslint": "^10.16.0",
"eslint-import-resolver-typescript": "^4.4.5",
"eslint-plugin-es-x": "^10.0.1",
"eslint-plugin-import-x": "^4.17.1",
"eslint-plugin-import-x": "^4.18.1",
"eslint-plugin-react-compiler": "19.1.0-rc.2",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.7",
@@ -113,17 +113,17 @@
"https-proxy-agent": "^9.1.0",
"husky": "^9.1.7",
"jiti": "^2.7.0",
"knip": "6.48.0",
"knip": "6.49.0",
"lint-staged": "^17.5.1",
"sass": "^1.104.1",
"tar": "^7.5.22",
"tar": "^8.0.0",
"terser": "^5.51.2",
"tsrs": "0.20.0-ts7.1.0-beta",
"typescript": "^6.0.3",
"typescript-eslint": "^8.70.0",
"typescript-eslint": "^8.74.0",
"vite": "^8.3.0",
"vite-plugin-svgr": "^5.2.0",
"vitest": "^5.0.1"
"vitest": "^5.0.3"
},
"lint-staged": {
"*.{ts,tsx,js,mjs}": [
@@ -135,5 +135,5 @@
]
},
"type": "module",
"packageManager": "pnpm@12.23.0"
"packageManager": "pnpm@12.25.1"
}
+1116 -1276
View File
File diff suppressed because it is too large Load Diff
+1 -3
View File
@@ -1,7 +1,6 @@
use objc2::{class, msg_send, runtime::AnyObject, sel};
use objc2_foundation::{NSPoint, NSRect, ns_string};
use tauri::{Manager as _, WebviewWindow};
use tauri_runtime_wry::WebviewWryExt as _;
#[link(name = "CoreGraphics", kind = "framework")]
unsafe extern "C" {
@@ -141,7 +140,7 @@ async fn perf_state(window: WebviewWindow, action: String) -> Result<serde_json:
let (tx, rx) = std::sync::mpsc::channel();
let fail_app = window.app_handle().clone();
window
.with_wry_webview(move |view| unsafe {
.with_webview(move |view| unsafe {
let native = &*(view.ns_window() as *const AnyObject);
let sender = std::ptr::null::<AnyObject>();
let display = match display_state(native) {
@@ -213,7 +212,6 @@ pub fn run() -> std::process::ExitCode {
#[cfg(not(feature = "clippy"))]
let context = tauri::generate_context!();
let result = tauri::Builder::default()
.runtime(tauri_runtime_wry::Wry::default())
.plugin(tauri_plugin_wdio_webdriver::init())
.invoke_handler(tauri::generate_handler![perf_state, get_clash_logs, get_verge_config])
.setup(|app| {
+10 -3
View File
@@ -1,10 +1,17 @@
# Backend Architecture Guardrails
Use [Workspace Crate Architecture](../crates/AGENTS.md) when extracting backend
capabilities or changing background task ownership.
Follow [Workspace Crate Architecture](../crates/AGENTS.md) when changing
backend capability boundaries, reusable orchestration, or background task
ownership.
- **Tauri adapter.** Commands validate transport input, delegate to application
use cases, and map results and errors to IPC. Tauri wires dependencies and
owns desktop lifecycle, window and tray integration, and event delivery.
Keep domain validation and reusable orchestration independent of command
handlers and framework state.
- **Configuration and effects.** `config` owns source configuration, drafts, and
persistence. The effects layer classifies every Verge patch field, including
persistence coordination. Persistence adapters perform storage and recovery.
The effects layer classifies every Verge patch field, including
fields without effects and platform-specific fields, and reconciles requested
state in dependency order. Publish rollbackable state after persistence and
commit. On failure, preserve already applied runtime effects, independently
+21 -18
View File
@@ -27,7 +27,7 @@ perf-harness = ["dep:tauri-plugin-wdio-webdriver"]
identifier = "io.github.clash-verge-rev.clash-verge-rev"
[build-dependencies]
tauri-build = { version = "=3.0.0-alpha.4", features = [] }
tauri-build = { version = "2.7.6", features = [] }
[dependencies]
clash-verge-draft = { workspace = true }
@@ -36,16 +36,19 @@ clash-verge-media-unlock = { workspace = true }
clash-verge-logging = { workspace = true }
clash-verge-i18n = { workspace = true }
clash-verge-limiter = { workspace = true }
clash-verge-subscription = { workspace = true }
clash-verge-profile = { workspace = true }
clash-verge-backup-archive = { workspace = true }
tauri-plugin-clash-verge-sysinfo = { workspace = true }
tauri-plugin-clipboard-manager = { workspace = true }
tauri = { workspace = true, features = [
"protocol-asset",
"devtools",
"tracing",
"tray-icon",
"image-ico",
"image-png",
] }
tauri-runtime-wry = { workspace = true, features = ["common-controls-v6", "devtools", "tracing"] }
parking_lot = { workspace = true }
anyhow = { workspace = true }
tokio = { workspace = true }
@@ -70,13 +73,13 @@ sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs.git", rev = "
"guard",
] }
network-interface = { version = "2.0.5", features = ["serde"] }
tauri-plugin-shell = "=3.0.0-alpha.3"
tauri-plugin-opener = "=3.0.0-alpha.3"
tauri-plugin-dialog = "=3.0.0-alpha.4"
tauri-plugin-fs = "=3.0.0-alpha.3"
tauri-plugin-deep-link = { git = "https://github.com/tauri-apps/plugins-workspace", rev = "f69e3649d7612a44dfb456a4990c588ea278d73a" }
tauri-plugin-window-state = "=3.0.0-alpha.2"
zip = "9.9.0"
tauri-plugin-shell = "2.6.0"
tauri-plugin-opener = "2.7.3"
tauri-plugin-dialog = "2.8.4"
tauri-plugin-fs = "2.7.1"
tauri-plugin-deep-link = "2.6.3"
tauri-plugin-window-state = "2.5.0"
zip = { workspace = true }
flate2 = "1.1.11"
reqwest_dav = "0.4.0"
aes-gcm = { version = "0.11.1" }
@@ -85,12 +88,12 @@ sha2 = "0.11.2"
getrandom = "0.4.3"
futures = { workspace = true }
gethostname = "1.1.0"
tauri-plugin-notification = "=3.0.0-alpha.3"
tauri-plugin-notification = "2.8.1"
backon = { version = "1.6.0", features = ["tokio-sleep"] }
tauri-plugin-http = "=3.0.0-alpha.3"
tauri-plugin-http = "2.9.0"
tracing = { workspace = 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 = "8ddbec3a24eea8be18b5eaa1aba16f87f23e9583" }
tauri-plugin-devtools = { version = "2.2.3", optional = true }
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "7e4fa8642cf6c394ed88b5a969420d8eab60087f" }
async-trait = "0.1.92"
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", features = [
"client",
@@ -103,7 +106,7 @@ dark-light = "3.0.0"
bytes = "1.12.2"
tokio-util = { version = "0.7.20", features = ["time"] }
specta = { version = "=2.0.0-rc.26", features = ["derive", "function", "serde_json"] }
tauri-specta = { git = "https://github.com/tauri-apps/tauri-specta", rev = "6bcec0cdec0c92decf404c85ff01b4d8c3868599", features = ["derive", "typescript"] }
tauri-specta = { version = "=2.0.0-rc.26", features = ["derive", "typescript"] }
specta-typescript = "=0.0.13"
[target.'cfg(unix)'.dependencies]
@@ -114,7 +117,7 @@ libc = "0.2.191"
clash-verge-signal = { workspace = true }
[target.'cfg(target_os = "macos")'.dependencies]
tauri-plugin-wdio-webdriver = { git = "https://github.com/Tunglies/desktop-mobile.git", rev = "3c936ad889b153bbe60902f74cbf69ef04d0e8d0", optional = true }
tauri-plugin-wdio-webdriver = { version = "=1.5.1", optional = true }
objc2 = "0.6.5"
objc2-foundation = { version = "0.3.2", features = [
"NSString",
@@ -152,9 +155,9 @@ windows = { version = "0.62.2", features = [
windows-sys.workspace = true
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
tauri-plugin-autostart = "=3.0.0-alpha.3"
tauri-plugin-global-shortcut = "=3.0.0-alpha.3"
tauri-plugin-updater = "=3.0.0-alpha.3"
tauri-plugin-autostart = "2.7.0"
tauri-plugin-global-shortcut = "2.4.1"
tauri-plugin-updater = "2.14.1"
[dev-dependencies]
tokio = { workspace = true, features = ["test-util"] }
+2
View File
@@ -1,3 +1,5 @@
#![deny(clippy::expect_used, clippy::unwrap_used)]
fn main() -> Result<(), Box<dyn std::error::Error>> {
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows")
&& std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc")
+1
View File
@@ -70,6 +70,7 @@
"dialog:allow-open",
"global-shortcut:allow-is-registered",
"global-shortcut:allow-register",
"global-shortcut:allow-register-all",
"global-shortcut:allow-unregister",
"global-shortcut:allow-unregister-all",
"clipboard-manager:allow-read-text",
+2
View File
@@ -1,3 +1,5 @@
#![deny(clippy::expect_used, clippy::unwrap_used)]
// Dev-only target: Tauri ships everything under src/bin/ to /usr/bin in deb/rpm
// bundles (PR #8131), so this generator must stay an example, never a bin.
fn main() -> Result<(), Box<dyn std::error::Error>> {
+27 -42
View File
@@ -5,12 +5,13 @@ use crate::core::notify::NoticeStatus;
use crate::utils::window_manager::WindowManager;
use crate::{
config::{
Config, IProfiles, PrfItem, PrfOption,
Config, IProfiles, PrfItem, PrfOption, build_remote_profile,
profiles::{
PROFILE_WRITE_LOCK, profiles_append_item_with_filedata_safe, profiles_patch_item_safe,
profiles_reorder_safe, profiles_save_file_safe,
PROFILE_WRITE_LOCK, cleanup_profile_files, profiles_append_item_safe,
profiles_append_item_with_filedata_safe, profiles_patch_item_safe, profiles_reorder_safe,
profiles_save_file_safe, save_profiles,
},
profiles_append_item_safe,
read_profile_item_file,
},
core::{CoreManager, handle, timer::Timer, tray::Tray, validate::ValidationOutcome},
feat,
@@ -71,7 +72,7 @@ pub async fn enhance_profiles() -> CmdResult<ValidationOutcome> {
#[tracing::instrument(skip_all, level = "info", fields(url = %help::mask_url(&url), uid = tracing::field::Empty))]
#[specta::specta]
pub async fn import_profile(url: std::string::String, option: Option<PrfOption>) -> CmdResult {
let item = &mut match PrfItem::from_url(&url, None, None, option.as_ref()).await {
let item = &mut match build_remote_profile(&url, None, None, option.as_ref()).await {
Ok(it) => it,
Err(e) => {
logging!(error, Type::Cmd, "[导入订阅] 下载失败: {e:#}");
@@ -159,9 +160,10 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
let profiles = Config::profiles().await;
let result = profiles
.with_data_modify(|mut candidate| async move {
.with_data_modify::<_, _, _, anyhow::Error>(|mut candidate| async move {
let original = candidate.clone();
let (should_update, plan) = candidate.plan_delete_item(&index)?;
let plan = candidate.plan_delete_item(&index)?;
let should_update = plan.deleting_current;
let guard = if should_update {
match CoreManager::global()
.update_config_forced_with_profiles(&candidate, &original)
@@ -171,11 +173,11 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
Err(outcome) => return Ok((original, Err(outcome))),
}
} else {
candidate.save_file().await?;
save_profiles(&candidate).await?;
None
};
let current = candidate.current.clone();
plan.cleanup().await;
cleanup_profile_files(plan.files).await;
Ok((candidate, Ok((should_update, current, guard))))
})
.await
@@ -210,15 +212,11 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
Ok(())
}
async fn restore_previous_profile(prev_profile: &str) -> CmdResult<()> {
async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> {
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
let restore_profiles = IProfiles {
current: Some(prev_profile.into()),
items: None,
};
Config::profiles()
.await
.edit_draft(|d| d.patch_config(&restore_profiles));
.edit_draft(|d| d.patch_current(Some(prev_profile)));
Config::profiles().await.apply();
crate::process::AsyncHandler::spawn(|| async move {
if let Err(e) = profiles_save_file_safe().await {
@@ -236,10 +234,7 @@ async fn commit_current_profile(profiles: &Draft<IProfiles>, current: Option<Str
profiles
.with_data_modify(|mut committed| async move {
committed.patch_config(&IProfiles {
current: Some(current),
items: None,
});
committed.patch_current(Some(&current));
Ok((committed, ()))
})
.await
@@ -397,16 +392,12 @@ pub async fn patch_profiles_config(profiles: ProfileSelection) -> CmdResult<Vali
});
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 previous_profile = Config::profiles().await.data_arc().current.clone();
Config::profiles().await.edit_draft(|d| {
d.patch_config(&profiles);
d.patch_current(target_profile);
});
perform_config_update(target_profile, previous_profile.as_ref())
@@ -492,20 +483,17 @@ pub async fn view_profile(index: std::string::String) -> CmdResult {
#[tauri::command]
#[specta::specta]
pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::string::String> {
let item = {
let file = {
let profiles = Config::profiles().await;
let profiles_ref = profiles.latest_arc();
PrfItem {
file: profiles_ref
.get_item(&index)
.with_error_code("PROFILE_READ_FAILED")?
.file
.to_owned(),
..Default::default()
}
profiles_ref
.get_item(&index)
.with_error_code("PROFILE_READ_FAILED")?
.file
.clone()
};
if let Some(file) = item.file.as_ref() {
if let Some(file) = file.as_ref() {
let path = dirs::app_profiles_dir()
.with_error_code("PROFILE_READ_FAILED")?
.join(file.as_str());
@@ -521,7 +509,9 @@ pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::str
}
}
let data = item.read_file().await.with_error_code("PROFILE_READ_FAILED")?;
let data = read_profile_item_file(file.as_deref())
.await
.with_error_code("PROFILE_READ_FAILED")?;
Ok(data.into())
}
@@ -575,16 +565,11 @@ mod tests {
current: Some("a".into()),
items: Some(vec![profile("a"), profile("b")]),
});
profiles.edit_draft(|draft| {
draft.patch_config(&IProfiles {
current: Some("b".into()),
items: None,
});
});
profiles.edit_draft(|draft| draft.patch_current(Some(&"b".into())));
profiles
.with_data_modify(|mut committed| async move {
committed.items.get_or_insert_with(Vec::new).push(profile("new"));
Ok((committed, ()))
Ok::<_, clash_verge_draft::DraftConflict>((committed, ()))
})
.await?;
+2 -8
View File
@@ -2,7 +2,7 @@ use super::CmdResult;
use crate::{
cmd::StringifyErr as _,
cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
config::{Config, IProfiles, PrfItem},
config::{Config, IProfiles, read_profile_item_file},
core::auto_backup::{self, AutoBackupTrigger},
core::{
CoreManager, handle,
@@ -58,13 +58,7 @@ pub async fn save_profile_file(
))
})?;
let original_content = if original_existed {
PrfItem {
file: Some(rel_path.clone()),
..Default::default()
}
.read_file()
.await
.stringify_err()?
read_profile_item_file(Some(rel_path.as_str())).await.stringify_err()?
} else {
String::new()
};
+9 -5
View File
@@ -1,7 +1,11 @@
use super::{IClashTemp, IProfiles, IVerge, MixedPort};
use crate::core::notify::NoticeStatus;
use crate::{
config::{PrfItem, profiles_append_item_to_safe, runtime::IRuntime},
config::{
prfitem::{build_merge_profile, build_script_profile},
profiles::{load_profiles, profiles_append_item_to_safe, save_profiles},
runtime::IRuntime,
},
constants::{files, timing},
core::{
CoreManager,
@@ -45,7 +49,7 @@ impl Config {
Self {
clash_config: Draft::new(IClashTemp::new().await),
verge_config: Draft::new(IVerge::new().await),
profiles_config: Draft::new(IProfiles::new().await),
profiles_config: Draft::new(load_profiles().await),
runtime_config: Draft::new(IRuntime::default()),
}
})
@@ -137,11 +141,11 @@ impl Config {
}
if profiles.latest_arc().get_item("Merge").is_err() {
let merge_item = &mut PrfItem::from_merge(Some("Merge".into()));
let merge_item = &mut build_merge_profile(Some("Merge".into()));
profiles_append_item_to_safe(&profiles, merge_item).await?;
}
if profiles.latest_arc().get_item("Script").is_err() {
let script_item = &mut PrfItem::from_script(Some("Script".into()));
let script_item = &mut build_script_profile(Some("Script".into()));
profiles_append_item_to_safe(&profiles, script_item).await?;
}
Ok(())
@@ -310,7 +314,7 @@ impl Config {
let _profile_write = super::profiles::PROFILE_WRITE_LOCK.lock().await;
let profiles = Self::profiles().await;
profiles.apply();
logging_error!(Type::Config, profiles.data_arc().save_file().await);
logging_error!(Type::Config, save_profiles(&profiles.data_arc()).await);
});
let _ = tokio::join!(save_clash_task, save_verge_task, save_profiles_task);
+5 -1
View File
@@ -12,7 +12,11 @@ pub(crate) mod snapshot;
mod verge;
pub(crate) use self::config::Config;
pub use self::{clash::*, encrypt::*, mixed_port::*, prfitem::*, profiles::*, verge::*};
pub(crate) use self::prfitem::{
build_remote_profile, download_subscription, prepare_remote_refresh, read_profile_item_file,
};
pub use self::{clash::*, encrypt::*, mixed_port::*, profiles::*, verge::*};
pub use clash_verge_profile::{PrfExtra, PrfItem, PrfOption, PrfSelected};
macro_rules! patch_opt_field {
($lv:expr, $rv:expr, $key:tt) => {
+385 -459
View File
@@ -1,4 +1,4 @@
use super::patch_opt_field;
use super::{PrfExtra, PrfItem, PrfOption};
use crate::{
config::profiles,
@@ -9,8 +9,7 @@ use crate::{
},
};
use anyhow::{Context as _, Result, bail};
use serde::{Deserialize, Serialize};
use serde_yaml_ng::Mapping;
use clash_verge_subscription::decode_subscription;
use std::time::Duration;
use tokio::fs;
use tristr::alias::String;
@@ -18,472 +17,318 @@ use tristr::alias::String;
use reqwest_dav::re_exports::url::form_urlencoded;
use tauri::Url;
pub(super) fn normalize_profile_home_url(raw: &str) -> Option<String> {
let url = Url::parse(raw.trim()).ok()?;
if !matches!(url.scheme(), "http" | "https") {
return None;
}
url.host_str()?;
Some(url.as_str().into())
}
#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)]
#[serde(default)]
pub struct PrfItem {
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(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,
/// Builds an item from a partial value that must include `itype`.
pub(super) async fn build_profile(item: &PrfItem, file_data: Option<String>) -> Result<PrfItem> {
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();
build_remote_profile(url, name, desc, option).await
}
"local" => {
let name = item.name.clone().unwrap_or_else(|| "Local File".into());
let desc = item.desc.clone().unwrap_or_else(|| "".into());
let option = item.option.as_ref();
from_local(name, desc, file_data, option).await
}
typ => bail!("invalid profile item type \"{typ}\""),
}
}
impl PrfItem {
/// Builds an item from a partial value that must include `itype`.
pub(super) async fn from(item: &Self, file_data: Option<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}\""),
}
}
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> {
profiles::profiles_append_item_safe(item).await?;
item.uid
.clone()
.ok_or_else(|| anyhow::anyhow!("appended companion item has no uid"))
}
macro_rules! current_field {
($name:ident, $field:ident) => {
pub(crate) fn $name(&self) -> Option<&String> {
self.option.as_ref().and_then(|o| o.$field.as_ref())
async fn ensure_companion_items(
merge: &mut Option<String>,
script: &mut Option<String>,
rules: &mut Option<String>,
proxies: &mut Option<String>,
groups: &mut Option<String>,
) -> Result<()> {
if merge.is_none() {
*merge = Some(append_companion_item(&mut build_merge_profile(None)).await?);
}
if script.is_none() {
*script = Some(append_companion_item(&mut build_script_profile(None)).await?);
}
if rules.is_none() {
*rules = Some(append_companion_item(&mut from_rules()).await?);
}
if proxies.is_none() {
*proxies = Some(append_companion_item(&mut from_proxies()).await?);
}
if groups.is_none() {
*groups = Some(append_companion_item(&mut from_groups()).await?);
}
Ok(())
}
async fn from_local(
name: String,
desc: String,
file_data: Option<String>,
option: Option<&PrfOption>,
) -> Result<PrfItem> {
let uid = help::get_uid("L").into();
let file = format!("{uid}.yaml").into();
let opt_ref = option.as_ref();
let update_interval = opt_ref.and_then(|o| o.update_interval);
let mut merge = opt_ref.and_then(|o| o.merge.clone());
let mut script = opt_ref.and_then(|o| o.script.clone());
let mut rules = opt_ref.and_then(|o| o.rules.clone());
let mut proxies = opt_ref.and_then(|o| o.proxies.clone());
let mut groups = opt_ref.and_then(|o| o.groups.clone());
ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?;
Ok(PrfItem {
uid: Some(uid),
itype: Some("local".into()),
name: Some(name),
desc: Some(desc),
file: Some(file),
url: None,
selected: None,
extra: None,
option: Some(PrfOption {
update_interval,
merge,
script,
rules,
proxies,
groups,
..PrfOption::default()
}),
home: None,
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(file_data.unwrap_or_else(|| tmpl::ITEM_LOCAL.into())),
})
}
pub(crate) 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).await?;
let uid: String = help::get_uid("R").into();
let file = format!("{uid}.yaml").into();
let name = name
.cloned()
.or_else(|| downloaded.suggested_name.take().map(Into::into))
.unwrap_or_else(|| "Remote File".into());
let url = downloaded.url.as_str().into();
let RemoteProfileRefresh {
extra,
home,
updated,
option,
body,
} = prepare_remote_refresh(downloaded, option).await?;
Ok(PrfItem {
uid: Some(uid),
itype: Some("remote".into()),
name: Some(name),
desc: desc.cloned(),
file: Some(file),
url: Some(url),
selected: None,
extra,
option: Some(option),
home,
updated: Some(updated),
file_data: Some(body),
})
}
pub(crate) async fn download_subscription(url: &str, option: Option<&PrfOption>) -> Result<DownloadedSubscription> {
let with_proxy = option.is_some_and(|o| o.with_proxy.unwrap_or(false));
let self_proxy = option.is_some_and(|o| o.self_proxy.unwrap_or(false));
let accept_invalid_certs = option.is_some_and(|o| o.danger_accept_invalid_certs.unwrap_or(false));
let user_agent = option.and_then(|o| o.user_agent.clone());
let timeout = option.and_then(|o| o.timeout_seconds).unwrap_or(20);
let proxy_type = if self_proxy {
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,
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,
})
}
impl PrfItem {
current_field!(current_merge, merge);
current_field!(current_script, script);
current_field!(current_rules, rules);
current_field!(current_proxies, proxies);
current_field!(current_groups, groups);
pub(crate) async fn prepare_remote_refresh(
downloaded: DownloadedSubscription,
option: Option<&PrfOption>,
) -> Result<RemoteProfileRefresh> {
let mut resolved = PrfOption {
update_interval: option
.and_then(|o| o.update_interval)
.or(downloaded.update_interval_minutes),
merge: option.and_then(|o| o.merge.clone()),
script: option.and_then(|o| o.script.clone()),
rules: option.and_then(|o| o.rules.clone()),
proxies: option.and_then(|o| o.proxies.clone()),
groups: option.and_then(|o| o.groups.clone()),
allow_auto_update: Some(allow_auto_update_enabled(option)),
..PrfOption::default()
};
ensure_companion_items(
&mut resolved.merge,
&mut resolved.script,
&mut resolved.rules,
&mut resolved.proxies,
&mut resolved.groups,
)
.await?;
Ok(RemoteProfileRefresh {
extra: downloaded.extra,
home: downloaded.home,
updated: chrono::Local::now().timestamp() as usize,
option: resolved,
body: downloaded.body,
})
}
pub(super) fn build_merge_profile(uid: Option<String>) -> PrfItem {
let (id, template) = if let Some(uid) = uid {
(uid, tmpl::ITEM_MERGE.into())
} else {
(help::get_uid("m").into(), tmpl::ITEM_MERGE_EMPTY.into())
};
let file = format!("{id}.yaml").into();
PrfItem {
uid: Some(id),
itype: Some("merge".into()),
file: Some(file),
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(template),
..Default::default()
}
}
pub(super) fn build_script_profile(uid: Option<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())
}
fn allow_auto_update_enabled(option: Option<&PrfOption>) -> bool {
@@ -518,3 +363,84 @@ fn fix_dirty_url(input: &str) -> Result<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)).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
+1 -1
View File
@@ -20,7 +20,7 @@ pub async fn update_launch() -> Result<()> {
use clash_verge_logging::logging_error;
use tauri_plugin_autostart::ManagerExt as _;
let autostart_manager = app_handle.autostart();
let autostart_manager = app_handle.autolaunch();
if is_enable {
logging_error!(Type::System, "{:?}", autostart_manager.enable());
} else {
+18 -16
View File
@@ -3,6 +3,7 @@ use crate::{config::Config, process::AsyncHandler, utils::dirs};
use anyhow::Error;
use arc_swap::{ArcSwap, ArcSwapOption};
use backon::{ConstantBuilder, Retryable as _};
use clash_verge_backup_archive::BackupWriter;
use clash_verge_logging::{Type, logging};
use reqwest_dav::list_cmd::{ListEntity, ListFile, ListMultiStatus};
use std::{
@@ -15,7 +16,6 @@ use std::{
};
use tokio::{fs, time::timeout};
use tristr::alias::String;
use zip::write::SimpleFileOptions;
const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
@@ -275,9 +275,7 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
let value = zip_path.clone();
let file = AsyncHandler::spawn_blocking(move || std::fs::File::create(&value)).await??;
let mut zip = zip::ZipWriter::new(file);
zip.add_directory("profiles/", SimpleFileOptions::default())?;
let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
let mut archive = BackupWriter::new(file)?;
if let Ok(mut entries) = fs::read_dir(dirs::app_profiles_dir()?).await {
while let Some(entry) = entries.next_entry().await? {
@@ -287,15 +285,16 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
let file_name = file_name_os
.to_str()
.ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?;
let backup_path = format!("profiles/{}", file_name);
zip.start_file(backup_path, options)?;
let mut entry = archive.start_profile(file_name)?;
let file_content = fs::read(&path).await?;
zip.write_all(&file_content)?;
entry.write_all(&file_content)?;
}
}
}
zip.start_file(dirs::CLASH_CONFIG, options)?;
zip.write_all(fs::read(dirs::clash_path()?).await?.as_slice())?;
archive
.start_file(dirs::CLASH_CONFIG)?
.write_all(&fs::read(dirs::clash_path()?).await?)?;
let verge_text = fs::read_to_string(dirs::verge_path()?).await?;
let mut verge_config: serde_json::Value = serde_yaml_ng::from_str(&verge_text)?;
@@ -304,17 +303,20 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
obj.remove("webdav_password");
obj.remove("webdav_url");
}
zip.start_file(dirs::VERGE_CONFIG, options)?;
zip.write_all(serde_yaml_ng::to_string(&verge_config)?.as_bytes())?;
archive
.start_file(dirs::VERGE_CONFIG)?
.write_all(serde_yaml_ng::to_string(&verge_config)?.as_bytes())?;
let dns_config_path = dirs::app_home_dir()?.join(DNS_CONFIG);
if dns_config_path.exists() {
zip.start_file(DNS_CONFIG, options)?;
zip.write_all(fs::read(&dns_config_path).await?.as_slice())?;
archive
.start_file(DNS_CONFIG)?
.write_all(&fs::read(&dns_config_path).await?)?;
}
zip.start_file(dirs::PROFILE_YAML, options)?;
zip.write_all(fs::read(dirs::profiles_path()?).await?.as_slice())?;
zip.finish()?;
archive
.start_file(dirs::PROFILE_YAML)?
.write_all(&fs::read(dirs::profiles_path()?).await?)?;
archive.finish()?;
Ok((zip_file_name, zip_path))
}
+2 -2
View File
@@ -2,7 +2,7 @@ use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
use crate::core::notify::NoticeStatus;
use crate::core::service::StageRequest;
use crate::{
config::{Config, IProfiles, runtime::IRuntime},
config::{Config, IProfiles, profiles::save_profiles, runtime::IRuntime},
constants::timing,
core::{
handle,
@@ -243,7 +243,7 @@ impl CoreManager {
crate::config::profiles::restore_selected_nodes().await;
return Ok(Err(outcome));
}
match candidate.save_file().await {
match save_profiles(candidate).await {
Ok(()) => {
tracing::Span::current().record("outcome", "committed");
Ok(Ok(guard))
+1 -1
View File
@@ -235,7 +235,7 @@ impl CoreManager {
anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}");
}
use crate::utils::retry::{RetryError, RetryPolicy, retry};
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
retry(
RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add(MAX_PORT_FALLBACK_RETRIES),
+1 -1
View File
@@ -1,7 +1,6 @@
#[cfg(test)]
use super::claim_core_readiness_generation;
use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
use crate::utils::retry::{RetryError, RetryPolicy, retry};
use crate::{
AsyncHandler,
config::Config,
@@ -11,6 +10,7 @@ use crate::{
};
use anyhow::{Context as _, Result};
use clash_verge_logging::Type;
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
use futures::{
FutureExt as _,
future::{Map, Shared},
+1 -1
View File
@@ -555,7 +555,7 @@ pub async fn clear() -> Result<()> {
/// A failed system call is usually a transient RPC hiccup, so give it a few tries.
async fn clear_with_retry() -> Result<()> {
use crate::utils::retry::{RetryError, RetryPolicy, retry};
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
retry(
RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add((CLEAR_ATTEMPTS - 1) as usize),
+1 -1
View File
@@ -135,7 +135,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
/// Retries transport failures but stops at the first readable reply, including a rejection.
pub async fn await_ready(&self, attempts: usize, interval: Duration) -> Result<RunState, ReadyWaitError> {
use crate::utils::retry::{RetryError, RetryPolicy, retry};
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
let attempts = std::num::NonZeroUsize::new(attempts).ok_or_else(|| {
ReadyWaitError::Unreachable(anyhow::anyhow!(
"service readiness wait was configured with no attempts"
+2 -2
View File
@@ -1282,7 +1282,7 @@ async fn create_sync_temp(target: &Path) -> Result<(PathBuf, tokio::fs::File)> {
.with_context(|| format!("failed to create provider cache directory {}", parent.display()))?;
}
let name = target.file_name().map_or_default(|name| name.to_string_lossy());
use crate::utils::retry::{RetryError, RetryPolicy, retry};
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
retry(
RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(7), std::time::Duration::ZERO),
|_| async {
@@ -1699,7 +1699,7 @@ async fn recover_after_owner_loss_while_locked(reason: OwnerRecoveryReason) {
}
async fn clear_proxy_after_owner_loss() {
use crate::utils::retry::{RetryError, RetryPolicy, retry};
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
let result = retry(
RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add(2),
+6 -40
View File
@@ -8,6 +8,7 @@ use crate::{
use anyhow::{Context as _, Result};
use clash_verge_draft::Draft;
use clash_verge_logging::{Type, logging, logging_error};
use clash_verge_profile::SubscriptionSchedule as TaskSchedule;
use futures::{FutureExt as _, StreamExt as _};
use std::{collections::HashMap, panic::AssertUnwindSafe, time::Duration};
use tokio::{
@@ -24,28 +25,6 @@ enum TimerCommand {
TaskFinished(String),
}
/// Next update is due at `updated + interval`, but the queue only takes a delay from now.
#[derive(Debug, PartialEq, Eq)]
struct TaskSchedule {
interval_minutes: u64,
first_delay: Duration,
}
impl TaskSchedule {
/// No recorded `updated` -> full interval. Deadline already past -> `ZERO`, fires at once.
fn new(interval_minutes: u64, updated: Option<usize>, now: i64) -> Self {
let full = Timer::interval_duration(interval_minutes);
let elapsed = updated
.filter(|updated| *updated > 0)
.map_or(0, |updated| now.saturating_sub(updated as i64).max(0) as u64);
Self {
interval_minutes,
first_delay: full.saturating_sub(Duration::from_secs(elapsed)),
}
}
}
struct TaskState {
key: Option<Key>,
interval_minutes: u64,
@@ -122,16 +101,9 @@ impl Timer {
let mut new_map = HashMap::new();
for item in items {
if let Some(option) = item.option.as_ref()
&& let (Some(interval), Some(uid)) = (option.update_interval, &item.uid)
&& option.allow_auto_update.unwrap_or(true)
&& interval > 0
if let Some(uid) = &item.uid
&& let Some(schedule) = TaskSchedule::for_profile(item, initializing, now)
{
let mut schedule = TaskSchedule::new(interval, item.updated, now);
// Startup historically treats an explicit zero timestamp as overdue.
if initializing && item.updated == Some(0) {
schedule.first_delay = Duration::ZERO;
}
new_map.insert(uid.clone(), schedule);
}
}
@@ -317,7 +289,7 @@ impl Timer {
// Full interval, not from `updated`: a failed run leaves `updated` in the past, so
// counting from it would retry at zero delay and spin.
let key = Self::schedule_task(queue, &uid, Self::interval_duration(state.interval_minutes));
let key = Self::schedule_task(queue, &uid, TaskSchedule::interval_duration(state.interval_minutes));
state.key = Some(key);
}
@@ -330,10 +302,6 @@ impl Timer {
});
}
const fn interval_duration(interval_minutes: u64) -> Duration {
Duration::from_secs(interval_minutes.saturating_mul(60))
}
fn schedule_task(queue: &mut DelayQueue<String>, uid: &str, delay: Duration) -> Key {
queue.insert(String::from(uid), delay)
}
@@ -348,10 +316,8 @@ impl Timer {
fn next_update_time(tasks: &HashMap<String, TaskState>, profiles: &IProfiles, uid: &str) -> Option<i64> {
let task = tasks.get(uid).filter(|task| !task.retired)?;
let updated = profiles.get_item(uid).ok()?.updated.filter(|updated| *updated > 0)?;
let updated = i64::try_from(updated).ok()?;
let interval = i64::try_from(task.interval_minutes).ok()?.checked_mul(60)?;
updated.checked_add(interval)
let updated = profiles.get_item(uid).ok()?.updated;
TaskSchedule::reported_deadline(task.interval_minutes, updated)
}
fn emit_update_event(uid: &str, is_start: bool) {
+31 -33
View File
@@ -24,7 +24,7 @@ use std::collections::HashMap;
use std::sync::LazyLock;
use std::time::Duration;
use tauri::{
AppHandle, DynRuntime, Manager as _,
AppHandle, Wry,
menu::{CheckMenuItem, IsMenuItem, MenuEvent, MenuItem, PredefinedMenuItem, Submenu},
};
use tristr::alias::String;
@@ -36,7 +36,7 @@ use menu_def::{MenuIds, MenuTexts};
// TODO: 是否需要将可变菜单抽离存储起来,后续直接更新对应菜单实例,无需重新创建菜单(待考虑)
type ProxyMenuItem = (Option<Submenu<DynRuntime>>, Vec<Box<dyn IsMenuItem<DynRuntime>>>);
type ProxyMenuItem = (Option<Submenu<Wry>>, Vec<Box<dyn IsMenuItem<Wry>>>);
const TRAY_CLICK_DEBOUNCE_MS: u64 = 300;
pub const TRAY_ID: &str = "clash-verge-rev-tray";
@@ -468,7 +468,7 @@ fn create_hotkeys(hotkeys: &Option<Vec<String>>) -> HashMap<&str, &str> {
fn create_profile_menu_item(
app_handle: &AppHandle,
profiles_preview: Vec<IProfilePreview<'_>>,
) -> Result<Vec<CheckMenuItem<DynRuntime>>> {
) -> Result<Vec<CheckMenuItem<Wry>>> {
profiles_preview
.into_iter()
.map(|profile| {
@@ -490,9 +490,9 @@ fn create_subcreate_proxy_menu_item(
proxy_mode: &str,
proxy_group_order_map: Option<HashMap<String, usize>>,
proxy_nodes_data: Option<Proxies>,
) -> Vec<Submenu<DynRuntime>> {
let proxy_submenus: Vec<Submenu<DynRuntime>> = {
let mut submenus: Vec<(String, usize, Submenu<DynRuntime>)> = Vec::new();
) -> Vec<Submenu<Wry>> {
let proxy_submenus: Vec<Submenu<Wry>> = {
let mut submenus: Vec<(String, usize, Submenu<Wry>)> = Vec::new();
// TODO: 应用启动时,内核还未启动完全,无法获取代理节点信息
if let Some(proxy_nodes_data) = proxy_nodes_data {
@@ -512,7 +512,7 @@ fn create_subcreate_proxy_menu_item(
let now_proxy = group_data.now.as_deref().unwrap_or_default();
let group_items: Vec<CheckMenuItem<DynRuntime>> = all_proxies
let group_items: Vec<CheckMenuItem<Wry>> = all_proxies
.iter()
.filter_map(|proxy_str| {
let is_selected = *proxy_str == now_proxy;
@@ -545,10 +545,8 @@ fn create_subcreate_proxy_menu_item(
let group_display_name = group_name.to_string();
let group_items_refs: Vec<&dyn IsMenuItem<DynRuntime>> = group_items
.iter()
.map(|item| item as &dyn IsMenuItem<DynRuntime>)
.collect();
let group_items_refs: Vec<&dyn IsMenuItem<Wry>> =
group_items.iter().map(|item| item as &dyn IsMenuItem<Wry>).collect();
if let Ok(submenu) = Submenu::with_id_and_items(
app_handle,
@@ -584,7 +582,7 @@ fn create_subcreate_proxy_menu_item(
fn create_proxy_menu_item(
app_handle: &AppHandle,
show_proxy_groups_inline: bool,
proxy_submenus: Vec<Submenu<DynRuntime>>,
proxy_submenus: Vec<Submenu<Wry>>,
proxies_text: &str,
) -> Result<ProxyMenuItem> {
let (proxies_submenu, inline_proxy_items) = if show_proxy_groups_inline {
@@ -592,13 +590,13 @@ fn create_proxy_menu_item(
None,
proxy_submenus
.into_iter()
.map(|submenu| Box::new(submenu) as Box<dyn IsMenuItem<DynRuntime>>)
.map(|submenu| Box::new(submenu) as Box<dyn IsMenuItem<Wry>>)
.collect(),
)
} else if !proxy_submenus.is_empty() {
let proxy_submenu_refs: Vec<&dyn IsMenuItem<DynRuntime>> = proxy_submenus
let proxy_submenu_refs: Vec<&dyn IsMenuItem<Wry>> = proxy_submenus
.iter()
.map(|submenu| submenu as &dyn IsMenuItem<DynRuntime>)
.map(|submenu| submenu as &dyn IsMenuItem<Wry>)
.collect();
(
@@ -624,7 +622,7 @@ fn build_tray_menu(
profiles_config: &IProfiles,
proxy_group_order_map: Option<HashMap<String, usize>>,
proxy_nodes_data: Option<Proxies>,
) -> Result<tauri::menu::Menu<DynRuntime>> {
) -> Result<tauri::menu::Menu<Wry>> {
let current_proxy_mode = options.mode.unwrap_or("");
let tun_mode_available = crate::core::runstate::RUN_STATE.state().tun_capable();
@@ -641,13 +639,13 @@ fn build_tray_menu(
let hotkeys = create_hotkeys(&verge_settings.hotkeys);
let profile_menu_items: Vec<CheckMenuItem<DynRuntime>> =
let profile_menu_items: Vec<CheckMenuItem<Wry>> =
create_profile_menu_item(app_handle, profiles_config.profiles_preview().unwrap_or_default())?;
let texts = MenuTexts::new();
let profile_menu_items_refs: Vec<&dyn IsMenuItem<DynRuntime>> = profile_menu_items
let profile_menu_items_refs: Vec<&dyn IsMenuItem<Wry>> = profile_menu_items
.iter()
.map(|item| item as &dyn IsMenuItem<DynRuntime>)
.map(|item| item as &dyn IsMenuItem<Wry>)
.collect();
let open_window = &MenuItem::with_id(
@@ -700,9 +698,9 @@ fn build_tray_menu(
outbound_modes_label.as_str(),
true,
&[
rule_mode as &dyn IsMenuItem<DynRuntime>,
global_mode as &dyn IsMenuItem<DynRuntime>,
direct_mode as &dyn IsMenuItem<DynRuntime>,
rule_mode as &dyn IsMenuItem<Wry>,
global_mode as &dyn IsMenuItem<Wry>,
direct_mode as &dyn IsMenuItem<Wry>,
],
)?)
};
@@ -807,7 +805,7 @@ fn build_tray_menu(
&texts.more,
true,
&[
copy_env as &dyn IsMenuItem<DynRuntime>,
copy_env as &dyn IsMenuItem<Wry>,
close_all_connections,
restart_clash,
restart_app,
@@ -824,13 +822,13 @@ fn build_tray_menu(
let separator = &PredefinedMenuItem::separator(app_handle)?;
let mut menu_items: Vec<&dyn IsMenuItem<DynRuntime>> = vec![open_window, separator];
let mut menu_items: Vec<&dyn IsMenuItem<Wry>> = vec![open_window, separator];
if show_outbound_modes_inline {
menu_items.extend_from_slice(&[
rule_mode as &dyn IsMenuItem<DynRuntime>,
global_mode as &dyn IsMenuItem<DynRuntime>,
direct_mode as &dyn IsMenuItem<DynRuntime>,
rule_mode as &dyn IsMenuItem<Wry>,
global_mode as &dyn IsMenuItem<Wry>,
direct_mode as &dyn IsMenuItem<Wry>,
]);
} else if let Some(ref outbound_modes) = outbound_modes {
menu_items.push(outbound_modes);
@@ -850,14 +848,14 @@ fn build_tray_menu(
menu_items.extend_from_slice(&[
separator,
system_proxy as &dyn IsMenuItem<DynRuntime>,
tun_mode as &dyn IsMenuItem<DynRuntime>,
system_proxy as &dyn IsMenuItem<Wry>,
tun_mode as &dyn IsMenuItem<Wry>,
separator,
lightweight_mode as &dyn IsMenuItem<DynRuntime>,
open_dir as &dyn IsMenuItem<DynRuntime>,
more as &dyn IsMenuItem<DynRuntime>,
lightweight_mode as &dyn IsMenuItem<Wry>,
open_dir as &dyn IsMenuItem<Wry>,
more as &dyn IsMenuItem<Wry>,
separator,
quit as &dyn IsMenuItem<DynRuntime>,
quit as &dyn IsMenuItem<Wry>,
]);
let menu = tauri::menu::MenuBuilder::new(app_handle).items(&menu_items).build()?;
+2 -2
View File
@@ -120,7 +120,7 @@ impl TraySpeedController {
fn clear_tray_speed() {
let app_handle = handle::Handle::app_handle();
if let Some(tray) = app_handle.tray_by_id(super::TRAY_ID) {
let result = tray.with_inner_blocking(|inner| {
let result = tray.with_inner_tray_icon(|inner| {
if let Some(status_item) = inner.ns_status_item() {
tray_speed::clear_speed_attributed_title(&status_item);
}
@@ -138,7 +138,7 @@ impl TraySpeedController {
fn apply_tray_speed(up: u64, down: u64) {
let app_handle = handle::Handle::app_handle();
if let Some(tray) = app_handle.tray_by_id(super::TRAY_ID) {
let result = tray.with_inner_blocking(move |inner| {
let result = tray.with_inner_tray_icon(move |inner| {
if let Some(status_item) = inner.ns_status_item() {
tray_speed::set_speed_attributed_title(&status_item, up, down);
}
+2 -3
View File
@@ -18,7 +18,7 @@ use crate::config::dns::{DnsOverrideState, dns_override_source};
use crate::core::handle::Handle;
use crate::utils::dirs;
use crate::{
config::{Config, IProfiles, IVerge, PrfItem},
config::{Config, IProfiles, IVerge, PrfItem, profiles::current_mapping},
constants,
utils::tmpl,
};
@@ -174,8 +174,7 @@ async fn collect_profile_items(profiles: &IProfiles) -> Result<ProfileItems> {
None => return Ok(ProfileItems::default()),
};
let current = profiles
.current_mapping()
let current = current_mapping(profiles)
.await
.with_context(|| format!("failed to read current profile \"{current_profile_uid}\""))?;
+2 -2
View File
@@ -1,5 +1,5 @@
use crate::{
config::{Config, IClashTemp, IProfiles, IVerge},
config::{Config, IClashTemp, IVerge, profiles::load_profiles},
core::{CoreManager, auto_backup, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
process::AsyncHandler,
utils::{
@@ -46,7 +46,7 @@ async fn finalize_restored_verge_config(
});
clash_draft.apply();
let restored_profiles = IProfiles::new().await;
let restored_profiles = load_profiles().await;
let profiles_draft = Config::profiles().await;
profiles_draft.edit_draft(|d| {
*d = restored_profiles;
+1 -1
View File
@@ -349,7 +349,7 @@ fn stage_core(target: &Path, package: &[u8], version: &str) -> Result<StagedCore
}
fn create_staging_file(directory: &Path, core_name: &OsStr) -> Result<(PathBuf, File)> {
use crate::utils::retry::{RetryError, RetryPolicy, retry_sync};
use clash_verge_task::retry::{RetryError, RetryPolicy, retry_sync};
retry_sync(
RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add(31),
+2 -2
View File
@@ -8,7 +8,7 @@ use crate::{
config::{
Config,
dns::{ProfileDnsSettings, dns_override_source},
profiles::PROFILE_WRITE_LOCK,
profiles::{PROFILE_WRITE_LOCK, current_mapping},
},
constants::files::DNS_CONFIG,
core::CoreManager,
@@ -36,7 +36,7 @@ pub async fn set_dns_override(
);
let source = dns_override_source(
profiles.current.as_deref().unwrap_or_default(),
&profiles.current_mapping().await?,
&current_mapping(&profiles).await?,
)?;
if enabled && let Some(source) = source.as_ref().filter(|source| Some(*source) != confirmation.as_ref()) {
return Ok(DnsOverrideOutcome::ConfirmationRequired { source: source.clone() });
+2
View File
@@ -9,6 +9,7 @@ mod icon;
mod listener;
mod profile;
mod proxy;
mod subscription;
mod tun;
mod window;
@@ -22,5 +23,6 @@ pub use icon::*;
pub use listener::*;
pub use profile::*;
pub use proxy::*;
pub use subscription::update_profile;
pub use tun::*;
pub use window::*;
+2 -177
View File
@@ -1,13 +1,11 @@
use crate::core::notify::NoticeStatus;
use crate::core::notify::{Refresh, announce};
use crate::{
cmd,
config::{Config, PrfItem, PrfOption, profiles::profiles_update_item_safe},
config::Config,
core::{CoreManager, handle, tray, validate::ValidationOutcome},
process::AsyncHandler,
utils::help::{mask_err, mask_url},
};
use anyhow::{Result, bail};
use anyhow::Result;
use clash_verge_logging::{Type, logging};
use std::collections::{HashMap, HashSet};
use tauri_plugin_mihomo::models::{Proxy, ProxyType, Rule};
@@ -201,179 +199,6 @@ async fn finish_proxy_switch(stale_proxies: Vec<std::string::String>) {
}
}
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
let profiles = Config::profiles().await;
let profiles = profiles.latest_arc();
let item = profiles.get_item(uid)?;
let is_remote = item.itype.as_ref().is_some_and(|s| s == "remote");
if !is_remote {
logging!(info, Type::Config, "[订阅更新] 不是远程订阅,跳过更新");
Ok(None)
} else if item.url.is_none() {
logging!(warn, Type::Config, "[订阅更新] 缺少URL,无法更新");
bail!("failed to get the profile item url");
} else if !ignore_auto_update && !item.option.as_ref().and_then(|o| o.allow_auto_update).unwrap_or(true) {
logging!(info, Type::Config, "[订阅更新] 禁止自动更新,跳过更新");
Ok(None)
} else {
logging!(
info,
Type::Config,
"[订阅更新] 远程订阅,URL: {}",
mask_url(
item.url
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?
)
);
Ok(Some((
item.url.clone().ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?,
item.option.clone(),
)))
}
}
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))]
async fn perform_profile_update(
uid: &str,
url: &str,
opt: Option<&PrfOption>,
option: Option<&PrfOption>,
is_mannual_trigger: bool,
) -> Result<()> {
let merged_opt = PrfOption::merge(opt, option);
let profiles = Config::profiles().await;
let profiles_arc = profiles.latest_arc();
let profile_name = profiles_arc
.get_item(uid)
.ok()
.and_then(|item| item.name.clone())
.unwrap_or_else(|| String::from("UnKnown Profile"));
#[derive(Clone, Copy)]
enum Strategy {
Configured,
Clash,
System,
}
let result =
crate::utils::retry::try_strategies(Strategy::Configured, [Strategy::Clash, Strategy::System], |strategy| {
let mut options = merged_opt.clone();
async move {
let (name, success, failure) = match strategy {
Strategy::Configured => (
"configured",
"[订阅更新] 更新订阅配置成功",
"[订阅更新] 直接更新失败: {},尝试使用Clash代理更新",
),
Strategy::Clash => (
"clash",
"[订阅更新] 使用 Clash代理 更新订阅配置成功",
"[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新",
),
Strategy::System => (
"system",
"[订阅更新] 使用 系统代理 更新订阅配置成功",
"[订阅更新] 系统代理更新失败: {},所有重试均已失败",
),
};
match strategy {
Strategy::Configured => {}
Strategy::Clash | Strategy::System => {
let option = options.get_or_insert_with(PrfOption::default);
option.self_proxy = Some(matches!(strategy, Strategy::Clash));
option.with_proxy = Some(matches!(strategy, Strategy::System));
}
}
tracing::Span::current().record("strategy", name);
let started = std::time::Instant::now();
let result = PrfItem::from_url(url, None, None, options.as_ref()).await;
let elapsed_field = match strategy {
Strategy::Configured => "configured_elapsed",
Strategy::Clash => "clash_elapsed",
Strategy::System => "system_elapsed",
};
tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed()));
match &result {
Ok(_) => logging!(info, Type::Config, "{success}"),
Err(error) => logging!(
warn,
Type::Config,
"{}",
failure.replace("{}", &mask_err(&format!("{error:#}")))
),
}
result
}
})
.await;
let last_err = match result {
Ok((strategy, mut item)) => {
// A persistence error must not replay a successful download with another transport.
profiles_update_item_safe(uid, &mut item).await?;
if !matches!(strategy, Strategy::Configured) {
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str());
}
return Ok(());
}
Err(error) => error,
};
let last_err = mask_err(&last_err.to_string());
if is_mannual_trigger {
handle::Handle::notice(
NoticeStatus::UpdateFailedEvenWithClash,
format!("{profile_name} - {last_err}"),
);
}
bail!(last_err)
}
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_mannual_trigger))]
pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_mannual_trigger: bool) -> Result<()> {
let url_opt = should_update_profile(uid, is_mannual_trigger).await?;
let profile_persisted = match url_opt {
Some((url, opt)) => {
perform_profile_update(uid, &url, opt.as_ref(), option, is_mannual_trigger).await?;
true
}
None => false,
};
let profiles = Config::profiles().await;
let is_current = profiles.latest_arc().current.as_deref() == Some(uid);
let should_refresh = is_current || (!profile_persisted && is_mannual_trigger);
if should_refresh {
logging!(debug, Type::Config, "[订阅更新] 更新内核配置");
match CoreManager::global().update_config_with_force(is_mannual_trigger).await {
Ok(outcome) if outcome.is_valid() => announce(Refresh::Clash),
Ok(outcome @ (ValidationOutcome::Skipped { .. } | ValidationOutcome::Busy)) if !is_mannual_trigger => {
logging!(info, Type::Config, "[订阅更新] 本次配置刷新已跳过: {}", outcome);
}
result => {
let message = match result {
Ok(outcome) => outcome.to_string(),
Err(err) => err.to_string(),
};
let message = mask_err(&message);
let message = if profile_persisted {
format!("订阅已保存,但未能确认已应用到内核: {message}")
} else {
message
};
logging!(error, Type::Config, "[订阅更新] 更新失败: {}", message);
handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str());
bail!(message);
}
}
}
Ok(())
}
/// 增强配置
pub async fn enhance_profiles() -> Result<ValidationOutcome> {
CoreManager::global().update_config_forced().await
+196
View File
@@ -0,0 +1,196 @@
use crate::{
config::{Config, PrfOption, download_subscription, prepare_remote_refresh, profiles::apply_remote_refresh_safe},
core::{
CoreManager, handle,
notify::{NoticeStatus, Refresh, announce},
validate::ValidationOutcome,
},
utils::help::{mask_err, mask_url},
};
use anyhow::{Result, bail};
use clash_verge_logging::{Type, logging};
use tristr::alias::String;
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
let profiles = Config::profiles().await;
let profiles = profiles.latest_arc();
let item = profiles.get_item(uid)?;
let is_remote = item.itype.as_ref().is_some_and(|s| s == "remote");
if !is_remote {
logging!(info, Type::Config, "[订阅更新] 不是远程订阅,跳过更新");
Ok(None)
} else if item.url.is_none() {
logging!(warn, Type::Config, "[订阅更新] 缺少URL,无法更新");
bail!("failed to get the profile item url");
} else if !ignore_auto_update && !item.option.as_ref().and_then(|o| o.allow_auto_update).unwrap_or(true) {
logging!(info, Type::Config, "[订阅更新] 禁止自动更新,跳过更新");
Ok(None)
} else {
logging!(
info,
Type::Config,
"[订阅更新] 远程订阅,URL: {}",
mask_url(
item.url
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?
)
);
Ok(Some((
item.url.clone().ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?,
item.option.clone(),
)))
}
}
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))]
async fn perform_profile_update(
uid: &str,
url: &str,
opt: Option<&PrfOption>,
option: Option<&PrfOption>,
is_manual_trigger: bool,
) -> Result<()> {
let merged_opt = PrfOption::merge(opt, option);
let profiles = Config::profiles().await;
let profiles_arc = profiles.latest_arc();
let profile_name = profiles_arc
.get_item(uid)
.ok()
.and_then(|item| item.name.clone())
.unwrap_or_else(|| String::from("UnKnown Profile"));
#[derive(Clone, Copy)]
enum Strategy {
Configured,
Clash,
System,
}
let result = clash_verge_task::retry::try_strategies(
Strategy::Configured,
[Strategy::Clash, Strategy::System],
|strategy| {
let mut options = merged_opt.clone();
async move {
let (name, success, failure) = match strategy {
Strategy::Configured => (
"configured",
"[订阅更新] 更新订阅配置成功",
"[订阅更新] 直接更新失败: {},尝试使用Clash代理更新",
),
Strategy::Clash => (
"clash",
"[订阅更新] 使用 Clash代理 更新订阅配置成功",
"[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新",
),
Strategy::System => (
"system",
"[订阅更新] 使用 系统代理 更新订阅配置成功",
"[订阅更新] 系统代理更新失败: {},所有重试均已失败",
),
};
match strategy {
Strategy::Configured => {}
Strategy::Clash | Strategy::System => {
let option = options.get_or_insert_with(PrfOption::default);
option.self_proxy = Some(matches!(strategy, Strategy::Clash));
option.with_proxy = Some(matches!(strategy, Strategy::System));
}
}
tracing::Span::current().record("strategy", name);
let started = std::time::Instant::now();
let result = download_subscription(url, options.as_ref()).await;
let elapsed_field = match strategy {
Strategy::Configured => "configured_elapsed",
Strategy::Clash => "clash_elapsed",
Strategy::System => "system_elapsed",
};
tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed()));
match &result {
Ok(_) => logging!(info, Type::Config, "{success}"),
Err(error) => logging!(
warn,
Type::Config,
"{}",
failure.replace("{}", &mask_err(&format!("{error:#}")))
),
}
result
}
},
)
.await;
let last_err = match result {
Ok((strategy, downloaded)) => {
// A persistence error must not replay a successful download with another transport.
let profiles = Config::profiles().await;
let snapshot = profiles.latest_arc();
let current = snapshot.get_item(uid)?;
anyhow::ensure!(
current.itype.as_deref() == Some("remote") && current.url.as_deref() == Some(url),
"profile source changed during refresh"
);
let refresh = prepare_remote_refresh(downloaded, merged_opt.as_ref()).await?;
apply_remote_refresh_safe(uid, url, refresh).await?;
if !matches!(strategy, Strategy::Configured) {
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str());
}
return Ok(());
}
Err(error) => error,
};
let last_err = mask_err(&last_err.to_string());
if is_manual_trigger {
handle::Handle::notice(
NoticeStatus::UpdateFailedEvenWithClash,
format!("{profile_name} - {last_err}"),
);
}
bail!(last_err)
}
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_manual_trigger))]
pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_manual_trigger: bool) -> Result<()> {
let url_opt = should_update_profile(uid, is_manual_trigger).await?;
let profile_persisted = match url_opt {
Some((url, opt)) => {
perform_profile_update(uid, &url, opt.as_ref(), option, is_manual_trigger).await?;
true
}
None => false,
};
let profiles = Config::profiles().await;
let is_current = profiles.latest_arc().current.as_deref() == Some(uid);
let should_refresh = is_current || (!profile_persisted && is_manual_trigger);
if should_refresh {
logging!(debug, Type::Config, "[订阅更新] 更新内核配置");
match CoreManager::global().update_config_with_force(is_manual_trigger).await {
Ok(outcome) if outcome.is_valid() => announce(Refresh::Clash),
Ok(outcome @ (ValidationOutcome::Skipped { .. } | ValidationOutcome::Busy)) if !is_manual_trigger => {
logging!(info, Type::Config, "[订阅更新] 本次配置刷新已跳过: {}", outcome);
}
result => {
let message = match result {
Ok(outcome) => outcome.to_string(),
Err(err) => err.to_string(),
};
let message = mask_err(&message);
let message = if profile_persisted {
format!("订阅已保存,但未能确认已应用到内核: {message}")
} else {
message
};
logging!(error, Type::Config, "[订阅更新] 更新失败: {}", message);
handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str());
bail!(message);
}
}
}
Ok(())
}
+2 -2
View File
@@ -1,12 +1,12 @@
use crate::cmd;
pub fn builder() -> tauri_specta::Builder<tauri::DynRuntime> {
pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
tauri_specta::Builder::new()
.types(&platform_types())
.commands(tauri_specta::collect_commands![
tauri_plugin_clash_verge_sysinfo::commands::get_system_info,
tauri_plugin_clash_verge_sysinfo::commands::get_app_uptime,
tauri_plugin_clash_verge_sysinfo::commands::export_diagnostic_info::<tauri::DynRuntime>,
tauri_plugin_clash_verge_sysinfo::commands::export_diagnostic_info::<tauri::Wry>,
cmd::probe_listener,
cmd::save_proxy_ports,
cmd::get_sys_proxy,
+5 -6
View File
@@ -1,4 +1,5 @@
#![allow(non_snake_case)]
#![deny(clippy::expect_used, clippy::unwrap_used)]
#![recursion_limit = "512"]
mod cmd;
@@ -40,7 +41,7 @@ mod app_init {
}
/// Setup plugins for the Tauri builder
pub fn setup_plugins(builder: tauri::Builder) -> tauri::Builder {
pub fn setup_plugins(builder: tauri::Builder<tauri::Wry>) -> tauri::Builder<tauri::Wry> {
#[allow(unused_mut)]
let mut builder = builder
.plugin(tauri_plugin_clash_verge_sysinfo::init())
@@ -82,9 +83,7 @@ mod app_init {
#[cfg(any(target_os = "linux", all(debug_assertions, windows)))]
{
logging!(debug, Type::Setup, "注册深层链接...");
if let Err(error) = app.deep_link().register_all() {
logging!(warn, Type::Setup, "Failed to register deep links: {error}");
}
let _ = app.deep_link().register_all();
}
app.deep_link().on_open_url(|event| {
@@ -125,7 +124,7 @@ mod app_init {
Ok(())
}
pub fn generate_handlers() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static {
pub fn generate_handlers() -> impl Fn(tauri::ipc::Invoke<tauri::Wry>) -> bool + Send + Sync + 'static {
{
let builder = crate::ipc::builder();
move |invoke| builder.invoke_handler()(invoke)
@@ -182,7 +181,7 @@ pub fn run() -> std::process::ExitCode {
#[cfg(target_os = "linux")]
utils::linux::workarounds::apply_wayland_webkit_fix();
let builder = app_init::setup_plugins(tauri::Builder::default().runtime(tauri_runtime_wry::Wry::default()))
let builder = app_init::setup_plugins(tauri::Builder::default())
.setup(|app| {
// Logger may not be ready yet, so mirror setup panics to stderr.
fn log_setup_panic(stage: &str, panic: Box<dyn std::any::Any + Send>) {
+1
View File
@@ -1,4 +1,5 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#![deny(clippy::expect_used, clippy::unwrap_used)]
use std::process::ExitCode;
#[cfg(not(all(feature = "perf-harness", target_os = "macos")))]
-23
View File
@@ -8,7 +8,6 @@ use serde_yaml_ng::{Mapping, Value};
use std::{
mem::DropGuard,
path::{Path, PathBuf},
str::FromStr,
};
use tokio::io::AsyncWriteExt as _;
@@ -212,16 +211,6 @@ pub fn get_uid(prefix: &str) -> String {
format!("{prefix}{id}")
}
pub fn parse_str<T: FromStr>(target: &str, key: &str) -> Option<T> {
target.split(';').map(str::trim).find_map(|s| {
let mut parts = s.splitn(2, '=');
match (parts.next(), parts.next()) {
(Some(k), Some(v)) if k == key => v.parse::<T>().ok(),
_ => None,
}
})
}
pub fn hex_encode(bytes: &[u8]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
@@ -307,18 +296,6 @@ pub fn mask_err(err: &str) -> String {
result
}
pub fn get_last_part_and_decode(url: &str) -> Option<String> {
let path = url.split('?').next().unwrap_or("");
let segments: Vec<&str> = path.split('/').collect();
let last_segment = segments.last()?;
Some(
percent_encoding::percent_decode_str(last_segment)
.decode_utf8_lossy()
.to_string(),
)
}
pub fn open_file(path: PathBuf) -> Result<()> {
open::that_detached(path.as_os_str())?;
Ok(())
+6 -3
View File
@@ -1,5 +1,8 @@
use crate::{
config::{Config, IClashTemp, IProfiles, IVerge},
config::{
Config, IClashTemp, IProfiles, IVerge,
profiles::{raise_short_update_intervals, save_profiles},
},
constants,
core::handle,
logging,
@@ -266,9 +269,9 @@ pub async fn migrate_short_update_intervals() -> Result<()> {
if profiles.items.is_none() {
anyhow::bail!("profiles.yaml was not loaded; refusing to record the migration as done");
}
let raised = profiles.raise_short_update_intervals(min);
let raised = raise_short_update_intervals(&mut profiles, min);
if raised > 0 {
profiles.save_file().await?;
save_profiles(&profiles).await?;
}
Ok((profiles, raised))
})
+1 -1
View File
@@ -109,7 +109,7 @@ fn current_user_home() -> anyhow::Result<PathBuf> {
}
.max(1024);
use crate::utils::retry::{RetryError, RetryPolicy, retry_sync};
use clash_verge_task::retry::{RetryError, RetryPolicy, retry_sync};
retry_sync(
RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add(11),
-1
View File
@@ -11,7 +11,6 @@ pub(crate) mod network;
pub use crate::core::notify::desktop as notification;
pub mod port;
pub mod resolve;
pub mod retry;
#[cfg(target_os = "windows")]
pub mod schtasks;
pub mod server;
+6 -46
View File
@@ -1,15 +1,15 @@
use crate::core::notify::NoticeStatus;
use anyhow::Result;
use percent_encoding::percent_decode_str;
use tauri::Url;
use tristr::alias::String;
use crate::{
config::{Config, PrfItem, profiles},
config::{Config, PrfItem, build_remote_profile, profiles},
core::{CoreManager, handle, timer::Timer},
utils::help,
};
use clash_verge_logging::{Type, logging, logging_error};
use clash_verge_subscription::decode_subscription_link;
pub(super) async fn resolve_scheme(param: &str) -> Result<()> {
let param_str = if param.starts_with("[") && param.len() > 4 {
@@ -26,7 +26,7 @@ pub(super) async fn resolve_scheme(param: &str) -> Result<()> {
let link_parsed = Url::parse(param_str)
.map_err(|e| anyhow::anyhow!("failed to parse deep link: {e:?}, param: {masked_deep_link}"))?;
let Some((url, name)) = extract_subscription_info(&link_parsed) else {
let Some(link) = decode_subscription_link(&link_parsed) else {
logging!(
warn,
Type::Config,
@@ -35,51 +35,11 @@ pub(super) async fn resolve_scheme(param: &str) -> Result<()> {
return Ok(());
};
import_subscription(&url, name.as_ref()).await;
let name = link.name.map(String::from);
import_subscription(&link.url, name.as_ref()).await;
Ok(())
}
fn extract_subscription_info(link_parsed: &Url) -> Option<(std::string::String, Option<String>)> {
if !matches!(link_parsed.scheme(), "clash" | "clash-verge") {
return None;
}
let name = link_parsed
.query_pairs()
.find(|(key, _)| key == "name")
.map(|(_, value)| value.into());
let url = extract_subscription_url(link_parsed)?;
Some((url, name))
}
fn extract_subscription_url(link_parsed: &Url) -> Option<std::string::String> {
let query = link_parsed.query()?;
let prefix = "url=";
let pos = query.find(prefix)?;
let raw_url = query[pos + prefix.len()..].trim();
Some(decode_subscription_url(raw_url))
}
fn decode_subscription_url(raw_url: &str) -> std::string::String {
// Avoid double-decoding nested subscription URLs; decode only when needed.
if Url::parse(raw_url).is_ok() {
return raw_url.to_string();
}
let mut candidate = raw_url.to_string();
for _ in 0..2 {
let next = percent_decode_str(&candidate).decode_utf8_lossy().to_string();
if next == candidate {
break;
}
candidate = next;
if Url::parse(&candidate).is_ok() {
break;
}
}
candidate
}
async fn import_subscription(url: &str, name: Option<&String>) {
let had_current_profile = {
let profiles = Config::profiles().await;
@@ -113,7 +73,7 @@ async fn import_subscription(url: &str, name: Option<&String>) {
}
async fn fetch_profile_item(url: &str, name: Option<&String>) -> Option<PrfItem> {
match PrfItem::from_url(url, name, None, None).await {
match build_remote_profile(url, name, None, None).await {
Ok(item) => Some(item),
Err(e) => {
logging!(error, Type::Config, "failed to parse profile from url: {:?}", e);
+1 -4
View File
@@ -132,10 +132,7 @@ pub fn take_webview_needs_reload() -> bool {
/// reload visible webviews immediately, and defer a hidden main-window reload until activation.
/// Registering this callback replaces Tauri's default automatic reload.
#[cfg(target_os = "macos")]
pub fn on_web_content_process_terminated(
webview: &tauri::Webview,
_termination: &tauri::webview::WebContentProcessTermination,
) {
pub fn on_web_content_process_terminated(webview: &tauri::Webview) {
if handle::Handle::global().is_exiting() {
return;
}
+1 -1
View File
@@ -52,7 +52,7 @@ pub async fn check_singleton() -> Result<SingletonDisposition> {
.context("failed to initialize singleton lock")?;
if !try_lock_instance(&lock).context("failed to acquire singleton lock")? {
let deadline = std::time::Instant::now() + Duration::from_secs(20);
use crate::utils::retry::{RetryError, RetryPolicy, retry};
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
let secondary = retry(
RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add(400),
+9 -9
View File
@@ -4,7 +4,7 @@ use clash_verge_logging::{Type, logging};
use std::pin::Pin;
use std::sync::LazyLock;
use std::time::Duration;
use tauri::{Manager as _, WebviewWindow};
use tauri::{Manager as _, WebviewWindow, Wry};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum WindowOperationResult {
@@ -50,7 +50,7 @@ impl WindowManager {
handle::Handle::global().set_activation_policy_regular();
}
fn get_main_window_with_state() -> (Option<WebviewWindow>, WindowState) {
fn get_main_window_with_state() -> (Option<WebviewWindow<Wry>>, WindowState) {
let Some(window) = Self::get_main_window() else {
return (None, WindowState::NotExist);
};
@@ -76,7 +76,7 @@ impl WindowManager {
Self::get_main_window_with_state().1
}
pub fn get_main_window() -> Option<WebviewWindow> {
pub fn get_main_window() -> Option<WebviewWindow<Wry>> {
let app_handle = handle::Handle::app_handle();
app_handle.get_webview_window("main")
}
@@ -147,7 +147,7 @@ impl WindowManager {
}
}
fn hide_main_window(window: Option<&WebviewWindow>) -> WindowOperationResult {
fn hide_main_window(window: Option<&WebviewWindow<Wry>>) -> WindowOperationResult {
logging!(debug, Type::Window, "窗口可见,将隐藏窗口");
if let Some(window) = window {
match window.close() {
@@ -166,7 +166,7 @@ impl WindowManager {
}
}
fn activate_existing_main_window(window: Option<&WebviewWindow>) -> WindowOperationResult {
fn activate_existing_main_window(window: Option<&WebviewWindow<Wry>>) -> WindowOperationResult {
logging!(debug, Type::Window, "窗口存在但被隐藏或最小化,将激活窗口");
if let Some(window) = window {
Self::activate_window(window)
@@ -176,7 +176,7 @@ impl WindowManager {
}
}
fn activate_window(window: &WebviewWindow) -> WindowOperationResult {
fn activate_window(window: &WebviewWindow<Wry>) -> WindowOperationResult {
logging!(debug, Type::Window, "开始激活窗口");
#[cfg(target_os = "macos")]
Self::set_macos_activation_policy_regular();
@@ -233,15 +233,15 @@ impl WindowManager {
}
}
pub fn is_main_window_visible(window: Option<&WebviewWindow>) -> bool {
pub fn is_main_window_visible(window: Option<&WebviewWindow<Wry>>) -> bool {
window.is_some_and(|w| w.is_visible().unwrap_or(false))
}
pub fn is_main_window_focused(window: Option<&WebviewWindow>) -> bool {
pub fn is_main_window_focused(window: Option<&WebviewWindow<Wry>>) -> bool {
window.is_some_and(|w| w.is_focused().unwrap_or(false))
}
fn is_main_window_minimized(window: Option<&WebviewWindow>) -> bool {
fn is_main_window_minimized(window: Option<&WebviewWindow<Wry>>) -> bool {
window.is_some_and(|w| w.is_minimized().unwrap_or(false))
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { Box, Typography, alpha, useTheme } from '@mui/material'
import React, { forwardRef, ReactNode } from 'react'
import { forwardRef, ReactNode } from 'react'
// 自定义卡片组件接口
interface EnhancedCardProps {
+1 -1
View File
@@ -94,7 +94,7 @@ export const SystemInfoCard = () => {
try {
const result = await triggerCheckUpdate()
const info = result.data
if (!info) {
if (!info?.available) {
showNotice.success(
'settings.components.verge.advanced.notifications.latestVersion',
)
+1 -1
View File
@@ -16,7 +16,7 @@ export const UpdateButton = (props: Props) => {
const { updateInfo } = useUpdate()
if (!updateInfo) return null
if (!updateInfo?.available) return null
return (
<>
@@ -48,7 +48,7 @@ const SettingVergeAdvanced = ({ onError: _ }: Props) => {
try {
const info = await checkUpdate()
updateLastCheckTime()
if (!info) {
if (!info?.available) {
showNotice.success(
'settings.components.verge.advanced.notifications.latestVersion',
)
+33 -33
View File
@@ -32,39 +32,39 @@
}
},
"ruleDialog": {
"title": "Add rule…",
"matchBy": "Match by",
"domain": "Domain",
"unavailable": "Not available",
"destination": "Add to the prepend rules of “{{name}}”.",
"newConnections": "New connections will match the updated configuration.",
"processPathHint": "Matches all destinations accessed by processes at this path.",
"processNameHint": "Matches all destinations accessed by processes with this name.",
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
"addAndApply": "Add and apply",
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
"applyFailed": "The rule could not be applied. Your selection has been kept.",
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
"saved": "Rule saved and configuration applied.",
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
"noProfile": "No active profile with an editable rule extension is available.",
"entry": "Configure rule…",
"modifyTitle": "Modify rule",
"domainScope": "Domain scope",
"exactDomain": "Only this domain",
"allSubdomains": "This domain and all its subdomains",
"title": "Adicionar regra…",
"matchBy": "Correspondência por",
"domain": "Domínio",
"unavailable": "Indisponível",
"destination": "Adicionar no início das regras de “{{name}}”.",
"newConnections": "As novas conexões seguirão a configuração atualizada.",
"processPathHint": "Corresponde a todos os destinos acessados por processos neste caminho.",
"processNameHint": "Corresponde a todos os destinos acessados por processos com este nome.",
"ruleModeHint": "O roteamento por regras funciona no modo Regra.",
"addAndApply": "Adicionar e aplicar",
"profileChanged": "O perfil ativo mudou. Feche esta janela e adicione a regra novamente.",
"applyFailed": "Não foi possível aplicar a regra. Sua seleção foi mantida.",
"unsupportedValue": "Este valor contém caracteres que não podem ser usados em uma regra rápida.",
"saved": "Regra salva e configuração aplicada.",
"noMetadata": "Esta conexão não tem informações de domínio, processo ou IP para configurar uma regra.",
"noProfile": "Não há um perfil ativo com uma extensão de regras editável.",
"entry": "Configurar regra…",
"modifyTitle": "Modificar regra",
"domainScope": "Escopo do domínio",
"exactDomain": "Apenas este domínio",
"allSubdomains": "Este domínio e todos os seus subdomínios",
"rootDomain": "Domínio principal e todos os seus subdomínios ({{domain}})",
"policyUnavailable": "This policy is no longer available. Choose another policy.",
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
"saveAndApply": "Save and apply",
"sourceIp": "Source IP",
"destinationIp": "Destination IP",
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
"fullPath": "Full path",
"connectionHost": "Current connection domain: {{host}}",
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
"matchingDomain": "Matching domain",
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
"policyUnavailable": "Esta política não está mais disponível. Escolha outra.",
"editDestination": "Atualizar a regra existente em “{{name}}”, mantendo sua posição.",
"saveAndApply": "Salvar e aplicar",
"sourceIp": "IP de origem",
"destinationIp": "IP de destino",
"sourceHint": "Corresponde a todas as solicitações deste IP ou sub-rede, inclusive de outros aplicativos. Sem filtro de portas.",
"destinationHint": "Corresponde a este IP de destino ou sub-rede em todos os domínios. Sem filtro de portas.",
"fullPath": "Caminho completo",
"connectionHost": "Domínio da conexão atual: {{host}}",
"invalidDomain": "Informe o domínio atual ou um domínio superior com pelo menos dois segmentos.",
"matchingDomain": "Domínio correspondente",
"invalidIp": "Informe um IP e um tamanho de prefixo válidos: 0–32 para IPv4 ou 0–128 para IPv6."
}
}