Compare commits

...
Author SHA1 Message Date
renovate[bot] f9b70913a8 chore(deps): update node.js to v26.14.0 2026-12-01 01:09:49 +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
Tunglies 929bb6a0a1 refactor(backend): share single-owner drivers for background tasks (#8759)
* docs(backend): define background task ownership

* refactor(backend): give background operations single task owners

* test(backend): remove actor migration regression cases

* docs(changelog): drop backend actor migration entry

* refactor(backend): extract workspace task drivers

* fix(timer): omit profile identifier from panic log

* docs(backend): define workspace crate boundaries

* refactor(lightweight): use the task countdown driver

* refactor(lightweight): name countdown callbacks

* refactor(task): simplify driver startup and coalescing requests

* refactor(core): bind service handoff to the sidecar generation

* refactor(tun): coalesce background run state reconciliation

* refactor(core): own sidecar exit resources in one session

* refactor(core): remove automatic Windows service handoff

* refactor(task): simplify coalescing job signals

* refactor(runstate): keep operation status with service state

* refactor(dns): coalesce background override synchronization

* refactor(sysproxy): own the local guard under its operation lock

* fix(tray): read menu settings at publication

* fix(dns): retain script lock across caller cancellation

* refactor(profiles): own selected node restoration in one task

* refactor(timer): own subscription schedules in the scheduler

* test(timer): remove the added application test

* fix(service): renew provider sync retry budget on refresh
2026-11-29 00:42:52 +00:00
doTHTYanddoTHTY 9724aa6d4d docs(i18n): align contributor guidance with PR template (#8760)
- The i18n guide told contributors to list routine command results in a PR checklist, which conflicts with the PR template's rule to keep only review-relevant evidence.

Co-authored-by: doTHTY <362276034+doTHTY@users.noreply.github.com>
2026-11-28 15:22:14 +00:00
❤是纱雾酱哟~andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 1be3ee67f8 chore(deps): update dependency tldts to v7.6.2 (#8763)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-28 15:19:05 +00:00
❤是纱雾酱哟~andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> cc99c90a66 chore(deps): update npm dependencies (#8758)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-28 12:51:55 +00:00
❤是纱雾酱哟~andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 377d497eb3 chore(deps): update rust toolchain to v1.100.1 (#8757)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-28 09:55:39 +00:00
❤是纱雾酱哟~andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 2bce842968 chore(deps): update rust crate zip to 9.9.0 (#8756)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-28 08:35:13 +00:00
renovate[bot]renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>❤是纱雾酱哟~
e813a80902 chore(deps): update github/gh-aw-actions action to v1.4.1 (#8755)
* chore(deps): update github/gh-aw-actions action to v1.4.1

* chore(deps): bump agentic workflows to v1.4.1

- Upgrade 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-28 07:51:25 +00:00
63 changed files with 2286 additions and 2089 deletions
+2 -2
View File
@@ -4,11 +4,11 @@
"features": { "features": {
"ghcr.io/devcontainers/features/node:2": { "ghcr.io/devcontainers/features/node:2": {
"version": "26.13.1", "version": "26.14.0",
"pnpmVersion": "12.23.0" "pnpmVersion": "12.23.0"
}, },
"ghcr.io/devcontainers/features/rust:1": { "ghcr.io/devcontainers/features/rust:1": {
"version": "1.100.0", "version": "1.100.1",
"profile": "default" "profile": "default"
}, },
"ghcr.io/devcontainers/features/git:1": {}, "ghcr.io/devcontainers/features/git:1": {},
+65 -263
View File
@@ -1,275 +1,77 @@
--- ---
name: Agentic Workflows 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 disable-model-invocation: true
--- ---
# GitHub Agentic Workflows Agent # 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 ## Execution and safety
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.
## Repository Instructions Overlay - For incident, health, and failure-related optimization requests,
use intent routing before generic update, upgrade, or optimization routes.
Load the target repository's `.github/aw/instructions.md`, if present. First load
Use `@.github/aw/instructions.md` only in a matching checkout; do not substitute [debug-bootstrap.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-bootstrap.md)
a guidance-repository overlay. 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`
Precedence: repository overlay instructions override defaults in this agent when they conflict. 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 ## 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**: [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)
- **Creating new workflows**: Routes to `create` prompt - **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).
- **Updating existing workflows**: Routes to `update` prompt - **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.
- **Diagnosis, patching, and active debugging**: Routes to `debug-agentic-workflow` for the local-first strategy, evidence triage and live gates - **Upgrading workflows**: [upgrade-agentic-workflows.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/upgrade-agentic-workflows.md)
- **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 - **Creating report-generating workflows**: [report.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/report.md)
- **Upgrading workflows**: Routes to `upgrade-agentic-workflows` prompt - **Creating shared components**: [create-shared-agentic-workflow.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-shared-agentic-workflow.md)
- **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 - **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`.
- **Creating shared components**: Routes to `create-shared-agentic-workflow` prompt - **Analyzing test coverage**: [test-coverage.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/test-coverage.md)
- **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 - **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`.
- **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 - **Reducing token use or cost**: [token-optimization.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/token-optimization.md)
- **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 - **Selecting workflow architecture or patterns**: [patterns.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/patterns.md)
- **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 - **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.
- **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 - **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.
- **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 - **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.
- **Git-backed work queues**: Routes to `work-queue` instructions for producers, dispatchers, workers, observers, deployment and recovery - **Local SDLC issue bootstrap**: [squad.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/squad.md)
- **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 or coordination; consult the
selected design prompt.
Workflows may optionally include:
For general workflow authoring, load
- **Project tracking / monitoring** (GitHub Projects updates, status reporting) [github-agentic-workflows.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/github-agentic-workflows.md).
- **Orchestration / coordination** (one workflow assigning agents or dispatching and coordinating other workflows) Load linked specifications only when the selected prompt requires them.
## Files This Applies To <!-- instruction-prefix-end -->
- 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`
+57 -7
View File
@@ -5,10 +5,10 @@
"version": "v9.0.0", "version": "v9.0.0",
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3" "sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
}, },
"github/gh-aw-actions/setup@v1.4.0": { "github/gh-aw-actions/setup@v1.4.2": {
"repo": "github/gh-aw-actions/setup", "repo": "github/gh-aw-actions/setup",
"version": "v1.4.0", "version": "v1.4.2",
"sha": "b907753c079ddd7d6829a0d8c24e02e818b4b45f" "sha": "d7852d91d5d1d13e7848771edab8bd1792a08651"
} }
}, },
"containers": { "containers": {
@@ -47,6 +47,16 @@
"digest": "sha256:b9cd8d7d1a9c2693e5d91db035a678fb1ea8d87ce691e08ec091b327e5e8ba75", "digest": "sha256:b9cd8d7d1a9c2693e5d91db035a678fb1ea8d87ce691e08ec091b327e5e8ba75",
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.20@sha256:b9cd8d7d1a9c2693e5d91db035a678fb1ea8d87ce691e08ec091b327e5e8ba75" "pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.20@sha256:b9cd8d7d1a9c2693e5d91db035a678fb1ea8d87ce691e08ec091b327e5e8ba75"
}, },
"ghcr.io/github/gh-aw-firewall/agent:0.29.21": {
"image": "ghcr.io/github/gh-aw-firewall/agent:0.29.21",
"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": { "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13": {
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13", "image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13",
"digest": "sha256:61f12dcff38eb008b645d87a5541763452f409d9040eb243718764944167b1a2", "digest": "sha256:61f12dcff38eb008b645d87a5541763452f409d9040eb243718764944167b1a2",
@@ -82,6 +92,16 @@
"digest": "sha256:fc6c1eff686514d26ff90ae1398e0f6e3dcad8d2e43d11b16df312c1e72c0ace", "digest": "sha256:fc6c1eff686514d26ff90ae1398e0f6e3dcad8d2e43d11b16df312c1e72c0ace",
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.20@sha256:fc6c1eff686514d26ff90ae1398e0f6e3dcad8d2e43d11b16df312c1e72c0ace" "pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.20@sha256:fc6c1eff686514d26ff90ae1398e0f6e3dcad8d2e43d11b16df312c1e72c0ace"
}, },
"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.21": {
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.21",
"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": { "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11": {
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11", "image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11",
"digest": "sha256:97782bc0d8ff7f80f19ae2fdc5e1668517aa732a6fa077e64b8d3919238496d2", "digest": "sha256:97782bc0d8ff7f80f19ae2fdc5e1668517aa732a6fa077e64b8d3919238496d2",
@@ -97,6 +117,16 @@
"digest": "sha256:743396030b149763880978f35ad679fe02b1c0be6697b01fbf6d43f4ac2ae081", "digest": "sha256:743396030b149763880978f35ad679fe02b1c0be6697b01fbf6d43f4ac2ae081",
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.20@sha256:743396030b149763880978f35ad679fe02b1c0be6697b01fbf6d43f4ac2ae081" "pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.20@sha256:743396030b149763880978f35ad679fe02b1c0be6697b01fbf6d43f4ac2ae081"
}, },
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.21": {
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.21",
"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": { "ghcr.io/github/gh-aw-firewall/router:0.29.14": {
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.14", "image": "ghcr.io/github/gh-aw-firewall/router:0.29.14",
"digest": "sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0", "digest": "sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0",
@@ -107,6 +137,16 @@
"digest": "sha256:732c3741e866099c6c2095aad7c84a18266486563deb51d7cce723f9bfc48721", "digest": "sha256:732c3741e866099c6c2095aad7c84a18266486563deb51d7cce723f9bfc48721",
"pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.20@sha256:732c3741e866099c6c2095aad7c84a18266486563deb51d7cce723f9bfc48721" "pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.20@sha256:732c3741e866099c6c2095aad7c84a18266486563deb51d7cce723f9bfc48721"
}, },
"ghcr.io/github/gh-aw-firewall/router:0.29.21": {
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.21",
"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": { "ghcr.io/github/gh-aw-firewall/squid:0.28.13": {
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13", "image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13",
"digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56", "digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56",
@@ -142,10 +182,20 @@
"digest": "sha256:1c4a4a12fcea206a81d656cb1f73847420a2c041d02ab51235364079a1e31d71", "digest": "sha256:1c4a4a12fcea206a81d656cb1f73847420a2c041d02ab51235364079a1e31d71",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.20@sha256:1c4a4a12fcea206a81d656cb1f73847420a2c041d02ab51235364079a1e31d71" "pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.20@sha256:1c4a4a12fcea206a81d656cb1f73847420a2c041d02ab51235364079a1e31d71"
}, },
"ghcr.io/github/gh-aw-mcpg:v0.5.14": { "ghcr.io/github/gh-aw-firewall/squid:0.29.21": {
"image": "ghcr.io/github/gh-aw-mcpg:v0.5.14", "image": "ghcr.io/github/gh-aw-firewall/squid:0.29.21",
"digest": "sha256:716b41d53a20660e945c351c08140380430d65d98d3263596e45114c29fa7a43", "digest": "sha256:ccc189ace632f3f42fa2ee1e77feb67d438e0975c591520da3f473c132e6216d",
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.5.14@sha256:716b41d53a20660e945c351c08140380430d65d98d3263596e45114c29fa7a43" "pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.21@sha256:ccc189ace632f3f42fa2ee1e77feb67d438e0975c591520da3f473c132e6216d"
},
"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": { "ghcr.io/github/gh-aw-node": {
"image": "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/charts.md`
- `.github/aw/cli-commands.md` - `.github/aw/cli-commands.md`
- `.github/aw/compat.md` - `.github/aw/compat.md`
- `.github/aw/connectors-authoring.md`
- `.github/aw/connectors.md` - `.github/aw/connectors.md`
- `.github/aw/context.md` - `.github/aw/context.md`
- `.github/aw/create-agentic-workflow-design.md` - `.github/aw/create-agentic-workflow-design.md`
@@ -148,6 +149,7 @@ Use the task routes above first. This inventory is not required startup context.
- `.github/aw/maintainer.md` - `.github/aw/maintainer.md`
- `.github/aw/mcp-clis.md` - `.github/aw/mcp-clis.md`
- `.github/aw/memory-stateful-patterns.md` - `.github/aw/memory-stateful-patterns.md`
- `.github/aw/memory-wiki-comment.md`
- `.github/aw/memory.md` - `.github/aw/memory.md`
- `.github/aw/messages.md` - `.github/aw/messages.md`
- `.github/aw/multi-agent-research.md` - `.github/aw/multi-agent-research.md`
@@ -156,6 +158,7 @@ Use the task routes above first. This inventory is not required startup context.
- `.github/aw/otel.md` - `.github/aw/otel.md`
- `.github/aw/patterns.md` - `.github/aw/patterns.md`
- `.github/aw/playwright.md` - `.github/aw/playwright.md`
- `.github/aw/pr-finisher.md`
- `.github/aw/pr-reviewer.md` - `.github/aw/pr-reviewer.md`
- `.github/aw/release-workflow.md` - `.github/aw/release-workflow.md`
- `.github/aw/repo-factory.md` - `.github/aw/repo-factory.md`
+8 -8
View File
@@ -51,7 +51,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- name: Install dependencies - name: Install dependencies
run: pnpm install --frozen-lockfile run: pnpm install --frozen-lockfile
@@ -154,7 +154,7 @@ jobs:
- name: Install Rust Stable - name: Install Rust Stable
uses: dtolnay/rust-toolchain@master uses: dtolnay/rust-toolchain@master
with: with:
toolchain: '1.100.0' toolchain: '1.100.1'
targets: ${{ matrix.target }} targets: ${{ matrix.target }}
- name: Rust Cache - name: Rust Cache
@@ -182,7 +182,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check - name: Pnpm install and check
@@ -240,7 +240,7 @@ jobs:
- name: Install Rust Stable - name: Install Rust Stable
uses: dtolnay/rust-toolchain@master uses: dtolnay/rust-toolchain@master
with: with:
toolchain: '1.100.0' toolchain: '1.100.1'
targets: ${{ matrix.target }} targets: ${{ matrix.target }}
- name: Rust Cache - name: Rust Cache
@@ -262,7 +262,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check - name: Pnpm install and check
@@ -373,7 +373,7 @@ jobs:
- name: Install Rust Stable - name: Install Rust Stable
uses: dtolnay/rust-toolchain@master uses: dtolnay/rust-toolchain@master
with: with:
toolchain: '1.100.0' toolchain: '1.100.1'
targets: ${{ matrix.target }} targets: ${{ matrix.target }}
- name: Rust Cache - name: Rust Cache
@@ -395,7 +395,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check - name: Pnpm install and check
@@ -479,7 +479,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6.1.1 - uses: pnpm/action-setup@v6.1.1
name: Install pnpm name: Install pnpm
+1 -1
View File
@@ -63,7 +63,7 @@ jobs:
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- run: pnpm install --frozen-lockfile - run: pnpm install --frozen-lockfile
+3 -3
View File
@@ -31,9 +31,9 @@ jobs:
with: with:
persist-credentials: false persist-credentials: false
- name: Install gh-aw extension - name: Install gh-aw extension
uses: github/gh-aw-actions/setup-cli@b907753c079ddd7d6829a0d8c24e02e818b4b45f # v1.4.0 uses: github/gh-aw-actions/setup-cli@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
with: with:
version: v1.4.0 version: v1.4.2
- name: Install Rust Stable - name: Install Rust Stable
uses: dtolnay/rust-toolchain@stable uses: dtolnay/rust-toolchain@stable
with: with:
@@ -49,7 +49,7 @@ jobs:
- name: Install Node.js - name: Install Node.js
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- name: Install frontend dependencies - name: Install frontend dependencies
env: env:
+1 -1
View File
@@ -43,7 +43,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
+3 -3
View File
@@ -74,7 +74,7 @@ jobs:
- name: Install Rust Stable - name: Install Rust Stable
if: github.event.inputs[matrix.input] == 'true' if: github.event.inputs[matrix.input] == 'true'
uses: dtolnay/rust-toolchain@1.100.0 uses: dtolnay/rust-toolchain@1.100.1
- name: Rust Cache - name: Rust Cache
if: github.event.inputs[matrix.input] == 'true' if: github.event.inputs[matrix.input] == 'true'
@@ -104,7 +104,7 @@ jobs:
if: github.event.inputs[matrix.input] == 'true' if: github.event.inputs[matrix.input] == 'true'
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check - name: Pnpm install and check
@@ -121,7 +121,7 @@ jobs:
if: github.event.inputs[matrix.input] == 'true' if: github.event.inputs[matrix.input] == 'true'
run: | run: |
# Ensure cross target is installed for the pinned toolchain; fallback without explicit toolchain if needed # Ensure cross target is installed for the pinned toolchain; fallback without explicit toolchain if needed
rustup target add ${{ matrix.target }} --toolchain 1.100.0 || rustup target add ${{ matrix.target }} rustup target add ${{ matrix.target }} --toolchain 1.100.1 || rustup target add ${{ matrix.target }}
rustup target list --installed rustup target list --installed
echo "Rust target ${{ matrix.target }} installed." echo "Rust target ${{ matrix.target }} installed."
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- run: pnpm install --frozen-lockfile - run: pnpm install --frozen-lockfile
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -61,7 +61,7 @@ jobs:
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
if: github.event.action != 'closed' if: github.event.action != 'closed'
+11 -11
View File
@@ -46,7 +46,7 @@ jobs:
fetch-depth: 0 fetch-depth: 0
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- name: Validate source and publish the approved snapshot - name: Validate source and publish the approved snapshot
id: source id: source
env: env:
@@ -203,7 +203,7 @@ jobs:
- name: Install Rust Stable - name: Install Rust Stable
uses: dtolnay/rust-toolchain@master uses: dtolnay/rust-toolchain@master
with: with:
toolchain: '1.100.0' toolchain: '1.100.1'
targets: ${{ matrix.target }} targets: ${{ matrix.target }}
- name: Rust Cache - name: Rust Cache
@@ -231,7 +231,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check - name: Pnpm install and check
@@ -308,7 +308,7 @@ jobs:
- name: Install Rust Stable - name: Install Rust Stable
uses: dtolnay/rust-toolchain@master uses: dtolnay/rust-toolchain@master
with: with:
toolchain: '1.100.0' toolchain: '1.100.1'
targets: ${{ matrix.target }} targets: ${{ matrix.target }}
- name: Rust Cache - name: Rust Cache
@@ -330,7 +330,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check - name: Pnpm install and check
@@ -439,7 +439,7 @@ jobs:
- name: Install Rust Stable - name: Install Rust Stable
uses: dtolnay/rust-toolchain@master uses: dtolnay/rust-toolchain@master
with: with:
toolchain: '1.100.0' toolchain: '1.100.1'
targets: ${{ matrix.target }} targets: ${{ matrix.target }}
- name: Rust Cache - name: Rust Cache
@@ -461,7 +461,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check - name: Pnpm install and check
@@ -542,7 +542,7 @@ jobs:
fetch-depth: 0 fetch-depth: 0
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
with: with:
run_install: false run_install: false
@@ -565,7 +565,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
@@ -593,7 +593,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
@@ -661,7 +661,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -22,13 +22,13 @@ jobs:
- name: Install Rust - name: Install Rust
uses: dtolnay/rust-toolchain@master uses: dtolnay/rust-toolchain@master
with: with:
toolchain: '1.100.0' toolchain: '1.100.1'
targets: x86_64-pc-windows-msvc targets: x86_64-pc-windows-msvc
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- name: Install pnpm - name: Install pnpm
uses: pnpm/action-setup@v6 uses: pnpm/action-setup@v6
+1 -1
View File
@@ -31,7 +31,7 @@ jobs:
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- name: Sync Mihomo version - name: Sync Mihomo version
id: sync id: sync
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
+2 -2
View File
@@ -15,7 +15,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
@@ -39,7 +39,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
+2 -2
View File
@@ -1,3 +1,3 @@
nodejs 26.13.1 nodejs 26.14.0
pnpm 12.23.0 pnpm 12.23.0
rust 1.100.0 rust 1.100.1
Generated
+12 -2
View File
@@ -1098,6 +1098,7 @@ dependencies = [
"clash-verge-logging", "clash-verge-logging",
"clash-verge-media-unlock", "clash-verge-media-unlock",
"clash-verge-signal", "clash-verge-signal",
"clash-verge-task",
"clash_verge_service_ipc", "clash_verge_service_ipc",
"dark-light", "dark-light",
"deelevate", "deelevate",
@@ -1222,6 +1223,15 @@ dependencies = [
"tokio", "tokio",
] ]
[[package]]
name = "clash-verge-task"
version = "0.1.0"
dependencies = [
"futures",
"parking_lot 0.13.0",
"tokio",
]
[[package]] [[package]]
name = "clash_verge_service_ipc" name = "clash_verge_service_ipc"
version = "2.8.2" version = "2.8.2"
@@ -10199,9 +10209,9 @@ dependencies = [
[[package]] [[package]]
name = "zip" name = "zip"
version = "9.8.2" version = "9.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce" checksum = "07db37dec4a7c468df4723fba4cadb4822d1d0f10dbea367100b6a6881b2a9c9"
dependencies = [ dependencies = [
"aes", "aes",
"bzip2", "bzip2",
+3
View File
@@ -2,6 +2,7 @@
members = [ members = [
"src-tauri", "src-tauri",
"crates/clash-verge-draft", "crates/clash-verge-draft",
"crates/clash-verge-task",
"crates/clash-verge-media-unlock", "crates/clash-verge-media-unlock",
"crates/clash-verge-logging", "crates/clash-verge-logging",
"crates/clash-verge-signal", "crates/clash-verge-signal",
@@ -52,6 +53,7 @@ muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdf
[workspace.dependencies] [workspace.dependencies]
clash-verge-draft = { path = "crates/clash-verge-draft" } clash-verge-draft = { path = "crates/clash-verge-draft" }
clash-verge-task = { path = "crates/clash-verge-task" }
clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" } clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" }
clash-verge-logging = { path = "crates/clash-verge-logging" } clash-verge-logging = { path = "crates/clash-verge-logging" }
clash-verge-signal = { path = "crates/clash-verge-signal" } clash-verge-signal = { path = "crates/clash-verge-signal" }
@@ -65,6 +67,7 @@ tauri = { version = "2.12.7" }
tauri-plugin-clipboard-manager = "2.5.0" tauri-plugin-clipboard-manager = "2.5.0"
parking_lot = "0.13.0" parking_lot = "0.13.0"
anyhow = "1.0.105" anyhow = "1.0.105"
futures = "0.3.34"
chrono = "0.4.45" chrono = "0.4.45"
criterion = { version = "0.8.2", features = ["async_tokio"] } criterion = { version = "0.8.2", features = ["async_tokio"] }
tokio = { version = "1.54.1", features = [ tokio = { version = "1.54.1", features = [
+51
View File
@@ -0,0 +1,51 @@
# Workspace Crate Architecture
## Choose the boundary
- 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,
[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.
## Design the API
- Start with concrete types for data and outcomes. Use a trait when methods must
cooperate under one contract, a closure for one supplied operation, and
`impl Future` when the caller owns scheduling. Add type parameters and bounds
where the contract needs them. Use dynamic dispatch when the API needs to hold
heterogeneous implementations, as [draft](clash-verge-draft/src/lib.rs) does
for the layers claimed by `DraftTransaction`.
- Keep state and its invariants with one owner. Expose snapshots, typed
operations, or guards. Draft owns claim, commit, and rollback of its in-memory
layers. The caller owns persistence and the recovery of external effects.
- Name product workspace libraries with the `clash-verge-` prefix and inherit
workspace lints. Reuse workspace dependencies where available and declare
only the features the crate needs.
## Own background work
- Give ordered start, replacement, and cleanup to one task owner. Reuse
[`clash-verge-task`](clash-verge-task/src/lib.rs) for coalescing scheduled jobs
and replaceable sessions. Keep domain policy, execution callbacks, and runtime
startup at the call site. Select a driver whose delivery guarantees match the
caller's needs.
- Use typed inputs. Coalesce only when intermediate requests may be skipped.
Reply with the actual outcome when a caller waits for completion. Preserve
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.
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
app boundary. For timing, prefer Tokio's paused clock for task drivers or a
small clock interface where time is an input, as in
[`clash-verge-limiter`](clash-verge-limiter/src/lib.rs).
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "clash-verge-task"
version = "0.1.0"
edition = "2024"
publish = false
[dependencies]
futures = { workspace = true }
parking_lot = { workspace = true }
tokio = { workspace = true }
[dev-dependencies]
tokio = { workspace = true, features = ["test-util"] }
[lints]
workspace = true
+60
View File
@@ -0,0 +1,60 @@
use std::{future::Future, time::Duration};
use tokio::{sync::mpsc, time::sleep};
enum Command<T> {
Arm(T),
Disarm,
}
pub struct Countdown<T> {
commands: mpsc::UnboundedSender<Command<T>>,
}
impl<T> Countdown<T> {
pub fn arm(&self, input: T) {
let _ = self.commands.send(Command::Arm(input));
}
pub fn disarm(&self) {
let _ = self.commands.send(Command::Disarm);
}
}
/// Create a countdown with a caller-owned driver. An active countdown ignores
/// additional arms. Disarm and channel closure take precedence over expiry.
///
/// Return `None` from `delay` to reject an arm before starting the countdown.
/// The delay future may be dropped on disarm, including while it loads the duration.
pub fn new<T, Fut>(
mut delay: impl FnMut(T) -> Option<Fut> + Send,
mut elapsed: impl FnMut(T) + Send,
) -> (Countdown<T>, impl Future<Output = ()> + Send)
where
T: Copy + Send,
Fut: Future<Output = Duration> + Send,
{
let (commands, mut receiver) = mpsc::unbounded_channel();
let driver = async move {
while let Some(command) = receiver.recv().await {
let Command::Arm(input) = command else { continue };
let Some(delay) = delay(input) else { continue };
let countdown = async { sleep(delay.await).await };
tokio::pin!(countdown);
loop {
tokio::select! {
biased;
command = receiver.recv() => match command {
Some(Command::Arm(_)) => {}
Some(Command::Disarm) => break,
None => return,
},
() = &mut countdown => {
elapsed(input);
break;
}
}
}
}
};
(Countdown { commands }, driver)
}
+5
View File
@@ -0,0 +1,5 @@
//! Single-owner task drivers with caller-managed runtime and cancellation.
pub mod countdown;
pub mod scheduled_task;
pub mod watch_task;
@@ -0,0 +1,146 @@
use futures::FutureExt as _;
use parking_lot::Mutex;
use std::{
future::Future,
panic::AssertUnwindSafe,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
};
use tokio::{
sync::Notify,
time::{Instant, sleep_until},
};
/// The next decision after the driver drains pending inputs.
pub enum Next<W> {
Idle,
At(Instant),
Run(W),
}
/// Synchronous policy owned and called by one driver.
pub trait ScheduledTask {
/// The merged pending input. Its default value represents no requests.
type Input: Default;
type Work: Copy + Send;
type Output;
fn on_input(&mut self, input: Self::Input, now: Instant);
fn next(&mut self, now: Instant) -> Next<Self::Work>;
/// Receives the execution result or an unwind from the execution callback.
fn finished(&mut self, work: Self::Work, result: std::thread::Result<Self::Output>, now: Instant);
}
/// A coalescing slot shared with one driver.
pub struct Mailbox<I> {
pending: Mutex<I>,
changed: Notify,
}
impl<I> Mailbox<I> {
/// Merge into the pending slot under a short synchronous lock.
///
/// Return true from `merge` when the driver should wake up. This only
/// submits input. Any completion reply belongs to the caller's protocol.
pub fn update(&self, merge: impl FnOnce(&mut I) -> bool) {
let changed = merge(&mut *self.pending.lock());
if changed {
self.changed.notify_one();
}
}
}
/// Create the mailbox and its driver. The caller chooses how to run the future.
///
/// While the driver is running, pending inputs wake idle waits and do not
/// interrupt an active job. Keep the driver alive until any issued effects
/// complete. Dropping producers does not shut it down.
pub fn new<P, F, Fut>(policy: P, execute: F) -> (Arc<Mailbox<P::Input>>, impl Future<Output = ()> + Send + 'static)
where
P: ScheduledTask + Send + 'static,
P::Input: Send + 'static,
F: FnMut(P::Work) -> Fut + Send + 'static,
Fut: Future<Output = P::Output> + Send + 'static,
{
let inbox = Arc::new(Mailbox {
pending: Mutex::default(),
changed: Notify::new(),
});
let receiver = Arc::clone(&inbox);
(inbox, drive(policy, receiver, execute))
}
async fn drive<P, F, Fut>(mut policy: P, inbox: Arc<Mailbox<P::Input>>, mut execute: F)
where
P: ScheduledTask,
F: FnMut(P::Work) -> Fut,
Fut: Future<Output = P::Output>,
{
loop {
let input = std::mem::take(&mut *inbox.pending.lock());
let now = Instant::now();
policy.on_input(input, now);
match policy.next(now) {
Next::Idle => inbox.changed.notified().await,
Next::At(due) => {
tokio::select! {
_ = inbox.changed.notified() => {}
_ = sleep_until(due) => {}
}
}
Next::Run(work) => {
// Pending inputs merge while the job runs. They cannot interrupt its effects.
let run = &mut execute;
let result = AssertUnwindSafe(async move { run(work).await }).catch_unwind().await;
policy.finished(work, result, Instant::now());
}
}
}
}
/// A request to run a job with at most one pending successor.
pub struct CoalescingJob(Arc<JobSignal>);
#[derive(Default)]
struct JobSignal {
pending: AtomicBool,
changed: Notify,
}
impl CoalescingJob {
pub fn request(&self) {
if !self.0.pending.swap(true, Ordering::Release) {
self.0.changed.notify_one();
}
}
}
/// Reconcile on demand without interrupting work in progress.
pub fn coalescing<Fut>(
mut execute: impl FnMut() -> Fut + Send + 'static,
mut on_panic: impl FnMut() + Send + 'static,
) -> (CoalescingJob, impl Future<Output = ()> + Send + 'static)
where
Fut: Future<Output = ()> + Send + 'static,
{
let signal = Arc::new(JobSignal::default());
let worker_signal = Arc::clone(&signal);
let driver = async move {
loop {
worker_signal.changed.notified().await;
// Requests coalesce until the driver claims the batch, even after it has been woken.
worker_signal.pending.swap(false, Ordering::Acquire);
let run = &mut execute;
if AssertUnwindSafe(async move { run().await })
.catch_unwind()
.await
.is_err()
{
on_panic();
}
}
};
(CoalescingJob(signal), driver)
}
+31
View File
@@ -0,0 +1,31 @@
use futures::FutureExt as _;
use std::{future::Future, panic::AssertUnwindSafe};
use tokio::sync::watch;
/// Run a session for each observed nonempty plan, beginning on the first change.
///
/// Subscribe while the plan is `None` before publishing the first session.
/// While a session runs, plans may coalesce to the latest value. The callback
/// chooses where to observe replacements and owns any issued effects until it
/// returns. An unwinding callback is reported before observing the next plan.
pub async fn run<T, F, Fut>(mut desired: watch::Receiver<Option<T>>, mut run: F, mut on_panic: impl FnMut(T) + Send)
where
T: Clone + Send + Sync,
F: FnMut(T, watch::Receiver<Option<T>>) -> Fut + Send,
Fut: Future<Output = ()> + Send,
{
while desired.changed().await.is_ok() {
let state = desired.borrow_and_update().clone();
if let Some(state) = state {
// Cancellation can consume updates on this clone without skipping them in the owner.
let updates = desired.clone();
if AssertUnwindSafe(async { run(state.clone(), updates).await })
.catch_unwind()
.await
.is_err()
{
on_panic(state);
}
}
}
}
+259
View File
@@ -0,0 +1,259 @@
use clash_verge_task::{
countdown,
scheduled_task::{self, Mailbox, Next, ScheduledTask},
watch_task,
};
use std::{error::Error, future::ready, time::Duration};
use tokio::{
sync::{mpsc, oneshot, watch},
time::{Instant, advance, timeout},
};
type TestResult = Result<(), Box<dyn Error>>;
struct Schedule {
due: Option<Instant>,
completed: mpsc::UnboundedSender<bool>,
}
impl ScheduledTask for Schedule {
type Input = Option<Instant>;
type Work = Instant;
type Output = ();
fn on_input(&mut self, input: Self::Input, _: Instant) {
self.due = self.due.into_iter().chain(input).min();
}
fn next(&mut self, now: Instant) -> Next<Instant> {
match self.due {
Some(due) if due <= now => {
self.due = None;
Next::Run(due)
}
Some(due) => Next::At(due),
None => Next::Idle,
}
}
fn finished(&mut self, _: Instant, result: std::thread::Result<()>, _: Instant) {
let _ = self.completed.send(result.is_ok());
}
}
fn request(mailbox: &Mailbox<Option<Instant>>, due: Instant) {
mailbox.update(|pending| {
if pending.is_some_and(|current| current <= due) {
return false;
}
*pending = Some(due);
true
});
}
async fn receive<T: Send>(receiver: &mut mpsc::UnboundedReceiver<T>) -> Result<T, Box<dyn Error>> {
timeout(Duration::from_secs(10), receiver.recv())
.await?
.ok_or_else(|| "driver event channel closed".into())
}
#[tokio::test(start_paused = true)]
async fn countdown_keeps_the_first_arm_until_it_expires() -> TestResult {
let delay = Duration::from_secs(4);
let (elapsed, mut events) = mpsc::unbounded_channel();
let (countdown, driver) = countdown::new(
move |_| Some(ready(delay)),
move |input| {
let _ = elapsed.send(input);
},
);
let mut driver = Box::pin(driver);
let start = Instant::now();
countdown.arm(1);
assert!(futures::poll!(driver.as_mut()).is_pending());
advance(Duration::from_secs(2)).await;
countdown.arm(2);
let driver = tokio::spawn(driver);
assert_eq!(receive(&mut events).await?, 1);
assert_eq!(Instant::now() - start, delay);
drop(countdown);
driver.await?;
assert!(events.try_recv().is_err());
Ok(())
}
#[tokio::test(start_paused = true)]
async fn ready_disarm_wins_and_the_next_arm_starts_a_new_countdown() -> TestResult {
let delay = Duration::from_secs(4);
let (elapsed, mut events) = mpsc::unbounded_channel();
let (countdown, driver) = countdown::new(
move |_| Some(ready(delay)),
move |input| {
let _ = elapsed.send(input);
},
);
let mut driver = Box::pin(driver);
countdown.arm(1);
assert!(futures::poll!(driver.as_mut()).is_pending());
advance(delay).await;
countdown.disarm();
countdown.arm(2);
let rearmed_at = Instant::now();
let driver = tokio::spawn(driver);
assert_eq!(receive(&mut events).await?, 2);
assert_eq!(Instant::now() - rearmed_at, delay);
drop(countdown);
driver.await?;
Ok(())
}
#[tokio::test]
#[allow(clippy::panic, reason = "inject an unwind into a coalescing job")]
async fn coalescing_preserves_one_pending_batch_through_a_panic() -> TestResult {
let (started, mut runs) = mpsc::unbounded_channel();
let (panicked, mut panics) = mpsc::unbounded_channel();
let mut first = true;
let (job, driver) = scheduled_task::coalescing(
move || {
let (release, wait) = oneshot::channel();
let _ = started.send(release);
let fail = std::mem::take(&mut first);
async move {
let _ = wait.await;
if fail {
panic!("test job panic");
}
}
},
move || {
let _ = panicked.send(());
},
);
let mut driver = Box::pin(driver);
assert!(futures::poll!(driver.as_mut()).is_pending());
job.request();
job.request();
assert!(futures::poll!(driver.as_mut()).is_pending());
runs.try_recv()?.send(()).map_err(|()| "first job was dropped")?;
assert!(futures::poll!(driver.as_mut()).is_pending());
panics.try_recv()?;
assert!(runs.try_recv().is_err());
job.request();
assert!(futures::poll!(driver.as_mut()).is_pending());
let release = runs.try_recv()?;
job.request();
job.request();
release.send(()).map_err(|()| "second job was dropped")?;
assert!(futures::poll!(driver.as_mut()).is_pending());
runs.try_recv()?.send(()).map_err(|()| "successor was dropped")?;
assert!(futures::poll!(driver.as_mut()).is_pending());
assert!(runs.try_recv().is_err());
Ok(())
}
#[tokio::test(start_paused = true)]
async fn an_earlier_request_reschedules_an_idle_wait() -> TestResult {
let (completed, mut results) = mpsc::unbounded_channel();
let (mailbox, driver) = scheduled_task::new(Schedule { due: None, completed }, |_| async {});
let mut driver = Box::pin(driver);
let start = Instant::now();
request(&mailbox, start + Duration::from_secs(8));
assert!(futures::poll!(driver.as_mut()).is_pending());
request(&mailbox, start + Duration::from_secs(2));
let driver = tokio::spawn(driver);
assert!(receive(&mut results).await?);
assert_eq!(Instant::now() - start, Duration::from_secs(2));
driver.abort();
Ok(())
}
#[tokio::test(start_paused = true)]
async fn active_work_finishes_before_one_coalesced_successor() -> TestResult {
let (completed, mut results) = mpsc::unbounded_channel();
let (started, mut runs) = mpsc::unbounded_channel();
let (mailbox, driver) = scheduled_task::new(Schedule { due: None, completed }, move |due| {
let (release, wait) = oneshot::channel();
let _ = started.send((due, release));
async move {
let _ = wait.await;
}
});
let driver = tokio::spawn(driver);
let start = Instant::now();
request(&mailbox, start);
let (_, release) = receive(&mut runs).await?;
let next = start + Duration::from_secs(2);
request(&mailbox, start + Duration::from_secs(4));
request(&mailbox, next);
advance(Duration::from_secs(5)).await;
assert!(runs.try_recv().is_err());
assert!(results.try_recv().is_err());
release.send(()).map_err(|()| "first job was dropped")?;
assert!(receive(&mut results).await?);
let (due, release) = receive(&mut runs).await?;
assert_eq!(due, next);
release.send(()).map_err(|()| "second job was dropped")?;
assert!(receive(&mut results).await?);
assert!(timeout(Duration::from_secs(1), runs.recv()).await.is_err());
driver.abort();
Ok(())
}
#[tokio::test(start_paused = true)]
#[allow(clippy::panic, reason = "inject an unwind into the execution future")]
async fn a_job_panic_reports_failure_and_allows_more_work() -> TestResult {
let (completed, mut results) = mpsc::unbounded_channel();
let start = Instant::now();
let (mailbox, driver) = scheduled_task::new(Schedule { due: None, completed }, move |due| async move {
if due == start {
panic!("test job panic");
}
});
let driver = tokio::spawn(driver);
request(&mailbox, start);
assert!(!receive(&mut results).await?);
request(&mailbox, start + Duration::from_secs(1));
assert!(receive(&mut results).await?);
driver.abort();
Ok(())
}
#[tokio::test(start_paused = true)]
#[allow(clippy::panic, reason = "inject an unwind after observing session replacement")]
async fn a_session_panic_does_not_consume_the_replacement() -> TestResult {
let (plan, desired) = watch::channel(None);
let (event, mut events) = mpsc::unbounded_channel();
let panicked = event.clone();
let driver = tokio::spawn(watch_task::run(
desired,
move |session, mut updates| {
let event = event.clone();
async move {
let _ = event.send((session, false));
if session == 1 && updates.changed().await.is_ok() {
panic!("test session panic");
}
}
},
move |session| {
let _ = panicked.send((session, true));
},
));
plan.send_replace(Some(1));
assert_eq!(receive(&mut events).await?, (1, false));
plan.send_replace(Some(2));
assert_eq!(receive(&mut events).await?, (1, true));
assert_eq!(receive(&mut events).await?, (2, false));
drop(plan);
driver.await?;
Ok(())
}
+1 -1
View File
@@ -73,4 +73,4 @@ Native UI strings (tray menu, notifications, dialogs) use `rust-i18n` with YAML
- File an issue for missing context, tooling bugs, or localization gaps so we can track them. - File an issue for missing context, tooling bugs, or localization gaps so we can track them.
- PRs that touch UI should include screenshots or GIFs whenever text length may affect layout. - PRs that touch UI should include screenshots or GIFs whenever text length may affect layout.
- Mention the commands you ran (formatting, type generation, tests) in the PR checklist. If you need extra context or review help, request it via a PR comment. - Keep routine command results in the working conversation rather than the PR body; report only material localization or layout gaps. If you need extra context or review help, request it via a PR comment.
+4 -4
View File
@@ -78,7 +78,7 @@
"rehype-sanitize": "^6.0.0", "rehype-sanitize": "^6.0.0",
"swr": "^2.5.1", "swr": "^2.5.1",
"tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#main", "tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#main",
"tldts": "7.5.5", "tldts": "7.6.3",
"types-pac": "^1.0.3", "types-pac": "^1.0.3",
"validator": "^13.15.35" "validator": "^13.15.35"
}, },
@@ -90,7 +90,7 @@
"@tauri-apps/cli": "2.12.6", "@tauri-apps/cli": "2.12.6",
"@types/lodash-es": "^4.17.12", "@types/lodash-es": "^4.17.12",
"@types/node": "^26.0.0", "@types/node": "^26.0.0",
"@types/react": "19.3.0", "@types/react": "19.3.3",
"@types/react-dom": "19.3.0", "@types/react-dom": "19.3.0",
"@types/validator": "^13.15.10", "@types/validator": "^13.15.10",
"@vitejs/plugin-legacy": "^8.2.3", "@vitejs/plugin-legacy": "^8.2.3",
@@ -113,10 +113,10 @@
"https-proxy-agent": "^9.1.0", "https-proxy-agent": "^9.1.0",
"husky": "^9.1.7", "husky": "^9.1.7",
"jiti": "^2.7.0", "jiti": "^2.7.0",
"knip": "6.48.0", "knip": "6.49.0",
"lint-staged": "^17.5.1", "lint-staged": "^17.5.1",
"sass": "^1.104.1", "sass": "^1.104.1",
"tar": "^7.5.22", "tar": "^8.0.0",
"terser": "^5.51.2", "terser": "^5.51.2",
"tsrs": "0.20.0-ts7.1.0-beta", "tsrs": "0.20.0-ts7.1.0-beta",
"typescript": "^6.0.3", "typescript": "^6.0.3",
+198 -208
View File
@@ -199,10 +199,10 @@ importers:
version: 0.5.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1) version: 0.5.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@emotion/react': '@emotion/react':
specifier: ^11.14.0 specifier: ^11.14.0
version: 11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0) version: 11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
'@emotion/styled': '@emotion/styled':
specifier: ^11.14.1 specifier: ^11.14.1
version: 11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0) version: 11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
'@juggle/resize-observer': '@juggle/resize-observer':
specifier: ^3.4.0 specifier: ^3.4.0
version: 3.4.0 version: 3.4.0
@@ -211,10 +211,10 @@ importers:
version: 4.7.0(monaco-editor@0.58.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) version: 4.7.0(monaco-editor@0.58.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@mui/icons-material': '@mui/icons-material':
specifier: ^9.4.0 specifier: ^9.4.0
version: 9.4.0(@mui/material@9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/react@19.3.0)(react@19.3.1) version: 9.4.0(@mui/material@9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/react@19.3.3)(react@19.3.1)
'@mui/material': '@mui/material':
specifier: ^9.4.0 specifier: ^9.4.0
version: 9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) version: 9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@tanstack/react-virtual': '@tanstack/react-virtual':
specifier: ^3.14.13 specifier: ^3.14.13
version: 3.14.13(react-dom@19.3.1(react@19.3.1))(react@19.3.1) version: 3.14.13(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
@@ -286,16 +286,16 @@ importers:
version: 19.3.1(react@19.3.1) version: 19.3.1(react@19.3.1)
react-error-boundary: react-error-boundary:
specifier: 6.1.6 specifier: 6.1.6
version: 6.1.6(@types/react@19.3.0)(react@19.3.1) version: 6.1.6(@types/react@19.3.3)(react@19.3.1)
react-hook-form: react-hook-form:
specifier: ^7.88.0 specifier: ^7.88.0
version: 7.88.0(react@19.3.1) version: 7.88.0(react@19.3.1)
react-i18next: react-i18next:
specifier: 18.0.3 specifier: 18.0.3
version: 18.0.3(@types/react@19.3.0)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3) version: 18.0.3(@types/react@19.3.3)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3)
react-markdown: react-markdown:
specifier: 10.1.0 specifier: 10.1.0
version: 10.1.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0) version: 10.1.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
react-router: react-router:
specifier: ^8.4.0 specifier: ^8.4.0
version: 8.4.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1) version: 8.4.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
@@ -312,8 +312,8 @@ importers:
specifier: github:clash-verge-rev/tauri-plugin-mihomo#main specifier: github:clash-verge-rev/tauri-plugin-mihomo#main
version: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f version: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f
tldts: tldts:
specifier: 7.5.5 specifier: 7.6.3
version: 7.5.5 version: 7.6.3
types-pac: types-pac:
specifier: ^1.0.3 specifier: ^1.0.3
version: 1.0.3 version: 1.0.3
@@ -343,11 +343,11 @@ importers:
specifier: ^26.0.0 specifier: ^26.0.0
version: 26.6.5 version: 26.6.5
'@types/react': '@types/react':
specifier: 19.3.0 specifier: 19.3.3
version: 19.3.0 version: 19.3.3
'@types/react-dom': '@types/react-dom':
specifier: 19.3.0 specifier: 19.3.0
version: 19.3.0(@types/react@19.3.0) version: 19.3.0(@types/react@19.3.3)
'@types/validator': '@types/validator':
specifier: ^13.15.10 specifier: ^13.15.10
version: 13.15.10 version: 13.15.10
@@ -412,8 +412,8 @@ importers:
specifier: ^2.7.0 specifier: ^2.7.0
version: 2.7.0 version: 2.7.0
knip: knip:
specifier: 6.48.0 specifier: 6.49.0
version: 6.48.0 version: 6.49.0
lint-staged: lint-staged:
specifier: ^17.5.1 specifier: ^17.5.1
version: 17.5.1 version: 17.5.1
@@ -421,8 +421,8 @@ importers:
specifier: ^1.104.1 specifier: ^1.104.1
version: 1.104.1 version: 1.104.1
tar: tar:
specifier: ^7.5.22 specifier: ^8.0.0
version: 7.5.22 version: 8.0.2
terser: terser:
specifier: ^5.51.2 specifier: ^5.51.2
version: 5.51.2 version: 5.51.2
@@ -1387,10 +1387,6 @@ packages:
resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==}
engines: {node: '>=18.18'} engines: {node: '>=18.18'}
'@isaacs/fs-minipass@4.0.1':
resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==}
engines: {node: '>=18.0.0'}
'@jridgewell/gen-mapping@0.3.13': '@jridgewell/gen-mapping@0.3.13':
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
@@ -1578,124 +1574,124 @@ packages:
'@octokit/types@18.0.0': '@octokit/types@18.0.0':
resolution: {integrity: sha512-l6bAF43PNxkJp6g+W4PjoUSSkxHomXw2nOum5CTftJz1NlV3vu93NImgOYtLf6CbBUb5j+fiuzW0PPQ5JTSvZA==} resolution: {integrity: sha512-l6bAF43PNxkJp6g+W4PjoUSSkxHomXw2nOum5CTftJz1NlV3vu93NImgOYtLf6CbBUb5j+fiuzW0PPQ5JTSvZA==}
'@oxc-parser/binding-android-arm-eabi@0.156.0': '@oxc-parser/binding-android-arm-eabi@0.160.0':
resolution: {integrity: sha512-RMq7DKNzEp1T51QKNLTn0NryNEt2IYfh7mZBlIdi2Ju52ltOEDMeIXv0XBpA6dL7j7ChjlcovtGcc1Jv4qMipg==} resolution: {integrity: sha512-IGhHufQ5uRhivrpzCcUJ92Mj4kYyFVhghaWk9hgZP/b+7WxdzdhFqBbH+PwEcfssDdIW10YHXcFvWib3kMX4Zg==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm] cpu: [arm]
os: [android] os: [android]
'@oxc-parser/binding-android-arm64@0.156.0': '@oxc-parser/binding-android-arm64@0.160.0':
resolution: {integrity: sha512-mwkWKhOBpmh8fWc3m4MiLsmEAtx0YuHmvyo9ff557cnb3QZ2kt2eauSz75wCGIpiZG3gUsJ4WwzEjm4R4/BHig==} resolution: {integrity: sha512-VxqVDFdTJG/QrJJ5pc/JIocKExtxCGcKf9qBsjIMS2VymVnHNdDu58d35pkgxIMFhxJ92YD79+66SBv86GXfCw==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64] cpu: [arm64]
os: [android] os: [android]
'@oxc-parser/binding-darwin-arm64@0.156.0': '@oxc-parser/binding-darwin-arm64@0.160.0':
resolution: {integrity: sha512-6pGR5fUszM9M4eBBapqpGjCRJolFwuCldx8bRQjqXyM09cQysBTWVF2Ttg4UNJVxYSaw5RRINbveCOOCrsuGvA==} resolution: {integrity: sha512-W5ULJkX2YAZAi6h2gkWCZCq1Ws5ZTIejBXjQP3tdf/UOeJaNQes4Vo5659/szYrFoBTef+WWcOU4HaY3TT4OYQ==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64] cpu: [arm64]
os: [darwin] os: [darwin]
'@oxc-parser/binding-darwin-x64@0.156.0': '@oxc-parser/binding-darwin-x64@0.160.0':
resolution: {integrity: sha512-M9QghL7uCAqMKjYJv1rDGblfEvkeQu3QzTPd7Uwo16gG3uO7m9ikVQ9OL8FZTnKzU4vbCEby6kTlEkqN+JeEMA==} resolution: {integrity: sha512-NNV6qakT/DX8SLqpe/gJ2ab2yDVJ+y6DKdJrbyTAdkpMjTP1KljiUxtAwoKVlHVPqfGMFPpSHIU9yL3FAWG/3w==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64] cpu: [x64]
os: [darwin] os: [darwin]
'@oxc-parser/binding-freebsd-x64@0.156.0': '@oxc-parser/binding-freebsd-x64@0.160.0':
resolution: {integrity: sha512-lX0ANxSwAOrpOT7NHB+YsrBqDJ8sOVon5m7GS9eQtkuUeNzQMMGpFsJLsStawTbrdwOF5KDVxgPWcKmt/DIZUQ==} resolution: {integrity: sha512-P1Ay7bTnFJarHefoBOOrzZ8ynRluk0w92p/+PwkAYgg38Fh5Z2eQN2slzYqODyNQRDd2YrdecLV038V6KmqfXw==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64] cpu: [x64]
os: [freebsd] os: [freebsd]
'@oxc-parser/binding-linux-arm-gnueabihf@0.156.0': '@oxc-parser/binding-linux-arm-gnueabihf@0.160.0':
resolution: {integrity: sha512-iPgYpasRcqk7X3TGncQg7B+6RotDvG8weug0UrgF+FXLf4KmaNDyT91BKONlqbHcNgK9Nryp7AEZGuQn32fP6g==} resolution: {integrity: sha512-jw16rzFMeyaGRTVoHTiKAe5qHa6T5v54GX0TGoAvbEskN+hQcK0pZQ+pi5n3yGZ7b1+vTF2eBuqQP98mgcd6XA==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm] cpu: [arm]
os: [linux] os: [linux]
'@oxc-parser/binding-linux-arm-musleabihf@0.156.0': '@oxc-parser/binding-linux-arm-musleabihf@0.160.0':
resolution: {integrity: sha512-sJqJDEZevtkEfoxrXfaRTkSt6Itckr549cIfBbs11UgXv8bFyqQsXTQa6iKm8mTiWYmCDDFJf7TLnqxcbqzPOw==} resolution: {integrity: sha512-B55bnJn8XMC8NDBbEsL6Za2ZuFx6RIG49GMSlHYfpIc2pWQ6sbJRwarP+iKXnPgpJ1N7wfOAotMp58NUYjzQaQ==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm] cpu: [arm]
os: [linux] os: [linux]
'@oxc-parser/binding-linux-arm64-gnu@0.156.0': '@oxc-parser/binding-linux-arm64-gnu@0.160.0':
resolution: {integrity: sha512-mrQs5OdRiqKskRuWEORPKT6YGIFhrpVvCvL9hqVaIh60EzgR4qjPvSsV6hWZcOfyWHBTbdEvfnDJPh/eQlxPRQ==} resolution: {integrity: sha512-YKVHxONDpWXTPfilLv2MKvaI7VbYnKHARr5wJ3KKKGk0OkauDc0tVFyZlKFwIy9+br46fh8AjTVCnz6+9gKxVA==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@oxc-parser/binding-linux-arm64-musl@0.156.0': '@oxc-parser/binding-linux-arm64-musl@0.160.0':
resolution: {integrity: sha512-ZtPqgCU3+wpU7dvX7YbaEiw71r0UdguzuPhcx4PIEZSs4XFqc6F5wXCtNdb6M7m3DMErlxrwosryoXrzYOY/Gg==} resolution: {integrity: sha512-uiVA0AemCVB3+oZ3JmjQCSEqiGIgl+o3+bLqORIfviJbyYlVUChoRh6cVbyyDG6zm4fW0RtQIdKq3fVYuNTA3Q==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
libc: [musl] libc: [musl]
'@oxc-parser/binding-linux-ppc64-gnu@0.156.0': '@oxc-parser/binding-linux-ppc64-gnu@0.160.0':
resolution: {integrity: sha512-ZuGRT/adReZZJn3PYNneb1HQIOH0iIZ2fzFgC1/XJYpMQ5KsRKmWIEzy3wEFsUwIOTomCmnmTZ/zbFYo9z9VeA==} resolution: {integrity: sha512-h/tr4lWGdRXs4rUktl84Z0CprQhdDlxN4D82/cCcoKr0Kb4TEIJriXZVqHPznp12/uBWcV+BiihUBPbeyZm1KQ==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64] cpu: [ppc64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@oxc-parser/binding-linux-riscv64-gnu@0.156.0': '@oxc-parser/binding-linux-riscv64-gnu@0.160.0':
resolution: {integrity: sha512-T+iWCeAOoEAJpHqr6/pogHIv98g9p8Ctccysm/h962hG4ayX5OL2c0Ih4oYe+JuFndLXy/OASvwMlTPe76sIiw==} resolution: {integrity: sha512-bA/Ba24KZYxorIUBHF2NbXM0OVY24xowGu4L0YBzpXhivt+ks1z8BT/c+BYGSfdFFqWrfNkC5TJjQGWdRkUHWQ==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64] cpu: [riscv64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@oxc-parser/binding-linux-riscv64-musl@0.156.0': '@oxc-parser/binding-linux-riscv64-musl@0.160.0':
resolution: {integrity: sha512-wL55bI2kVKfwdxScbw60zVgzAqbQbmE5zpSPWPZoZ9RSG8egm6ITE/UWE5mDWlglxz1QElJCcUbpaJCtHD11BQ==} resolution: {integrity: sha512-1uI9RghjO7/JQzkL9M/EDnG0Egy5z4v3k5TCUbPESZVUawHEmC52MMnCLe7f2CjMtiLjsm879CnO2HkRtsECNA==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64] cpu: [riscv64]
os: [linux] os: [linux]
libc: [musl] libc: [musl]
'@oxc-parser/binding-linux-s390x-gnu@0.156.0': '@oxc-parser/binding-linux-s390x-gnu@0.160.0':
resolution: {integrity: sha512-+D+JilhLqwrDLODYEl4qtovVwgxKALb23FkAWBiPvgmUWYgjCV83KKuwwxZJM8GCdKlNA1vt3iKtow8HUFjXtg==} resolution: {integrity: sha512-1gaVKLXjT+UML8w8ypK93KUJurvUUmegqgQ/7qijDNpGCuogmTOIu0KgsYqL2hH//amY3AtfQhTTMlw9l363wA==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x] cpu: [s390x]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@oxc-parser/binding-linux-x64-gnu@0.156.0': '@oxc-parser/binding-linux-x64-gnu@0.160.0':
resolution: {integrity: sha512-jRfwpN4xKrsEpC+SgrUPY5k0mINYZn7aLrt22I3uQFoumiSgHgsLYgS9f84ntbkvSydH4HiwGuDa2b1XCHaJzw==} resolution: {integrity: sha512-v44/JCrzpIof2jAJwF9W1j9l7mZKEaKihd8vBECBaNyIPcOiO4dtkeGX51MxnGmrJbsltdvTJb60VXLyMyAD2w==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
libc: [glibc] libc: [glibc]
'@oxc-parser/binding-linux-x64-musl@0.156.0': '@oxc-parser/binding-linux-x64-musl@0.160.0':
resolution: {integrity: sha512-P/ajnypgLmxmuRRyCIZcp2o4lOwmCaXYH5+eqDTcCW+MCTI+csKSw/Zc6GB67jZoVa4ey3q1jXEt7S60adBEMQ==} resolution: {integrity: sha512-NOT9x+x27Aitn+z6PggidaeHiKOpbglRXwzcHg+3VqbMT7nv/C3fnXKeVESy4o0u3Yb3mEocwPrtzlT5O53JSA==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
libc: [musl] libc: [musl]
'@oxc-parser/binding-openharmony-arm64@0.156.0': '@oxc-parser/binding-openharmony-arm64@0.160.0':
resolution: {integrity: sha512-WSN6rQZZc9KqgZ4lMfjVDvqKhVOCjey/YEZIPisGXmwBqwgWOzru207dyiH50LHcf1n9LO2oceGk/id6RL9v0g==} resolution: {integrity: sha512-kXFdUqEkbB1E66dfqu7sk65w0CaDVp+uPeJ4eOacxBuVgKk/poy+b8/XpFfV443UNB8LUUvzgTzyWLxDQte2Dw==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64] cpu: [arm64]
os: [openharmony] os: [openharmony]
'@oxc-parser/binding-win32-arm64-msvc@0.156.0': '@oxc-parser/binding-win32-arm64-msvc@0.160.0':
resolution: {integrity: sha512-l21Tz6tjraGBC3JefVeJZ9pojD0fCiB62PydAv+i9nrqJX7z/pDmyDNYLamDr/PRcQ4UQbFwkSnz7NKBB9UMLw==} resolution: {integrity: sha512-tzYHz6BOwmKCY2c8txeV06CkMzwEVQhFwug8OR75q2UVRMfksf9yD5UBjAeauPEiFhzNogg1RRyk8UZ0bjMXvg==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64] cpu: [arm64]
os: [win32] os: [win32]
'@oxc-parser/binding-win32-ia32-msvc@0.156.0': '@oxc-parser/binding-win32-ia32-msvc@0.160.0':
resolution: {integrity: sha512-CUq0ZFl/RODqPiIgfNNSamkpTj5x8AjBTkR/y1DNVIQiTGnmWqjHcn3o08ZW3q/LgkI4g9G9g6UirmmQFvuOZw==} resolution: {integrity: sha512-vyYZ4gcWUPuPANDj66eBnZ7+CFzUU0pzX28a5armxejWxM7onM3awHkM4PB/al8eEZ3MH8l0AprX/1jXrfGh7Q==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ia32] cpu: [ia32]
os: [win32] os: [win32]
'@oxc-parser/binding-win32-x64-msvc@0.156.0': '@oxc-parser/binding-win32-x64-msvc@0.160.0':
resolution: {integrity: sha512-dcpx5Y1x2v/cs7U/q3SZMvmxfyXjVvqC86jMuw2ZZUbHDd7W2cW7uSMQfg3GLVaE68Su3H9xd/Pc4v6QNyeSRg==} resolution: {integrity: sha512-KvENUAjmLfLBJBTF9yQ2wb5/DH41+FPM45oM7NMTgW0R3kN49NUj314SaDqqqkba+4cNTBt8NA2Ux5dekZB68w==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64] cpu: [x64]
os: [win32] os: [win32]
@@ -1703,6 +1699,9 @@ packages:
'@oxc-project/types@0.156.0': '@oxc-project/types@0.156.0':
resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==}
'@oxc-project/types@0.160.0':
resolution: {integrity: sha512-gw4k9syEmnckbOgw2A2FU1TBDdX9hfwV9jEn/uio65pguPzwWiXQS3OIJDMEhv9m06tj9XiEe6RoD0YA+LgreA==}
'@oxc-resolver/binding-android-arm-eabi@11.24.2': '@oxc-resolver/binding-android-arm-eabi@11.24.2':
resolution: {integrity: sha512-y09e0L0SRI2OA2tUIrjBgoV3eH5hvUKXNkJqXmNo5V2WxIjyC7I7aJfRLMEVpA8yi95f90gFDvO0VMgrDw+vwA==} resolution: {integrity: sha512-y09e0L0SRI2OA2tUIrjBgoV3eH5hvUKXNkJqXmNo5V2WxIjyC7I7aJfRLMEVpA8yi95f90gFDvO0VMgrDw+vwA==}
cpu: [arm] cpu: [arm]
@@ -2005,6 +2004,9 @@ packages:
rollup: rollup:
optional: true optional: true
'@standard-schema/spec@1.1.0':
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
'@svgr/babel-plugin-add-jsx-attribute@8.0.0': '@svgr/babel-plugin-add-jsx-attribute@8.0.0':
resolution: {integrity: sha512-b9MIk7yhdS1pMCZM8VeNfUlSKVRhsHZNMl5O9SfaX0l0t5wjdgu4IDzGB8bpnGBBOjGST3rRFVsaaEtI4W6f7g==} resolution: {integrity: sha512-b9MIk7yhdS1pMCZM8VeNfUlSKVRhsHZNMl5O9SfaX0l0t5wjdgu4IDzGB8bpnGBBOjGST3rRFVsaaEtI4W6f7g==}
engines: {node: '>=14'} engines: {node: '>=14'}
@@ -2283,8 +2285,8 @@ packages:
peerDependencies: peerDependencies:
'@types/react': '*' '@types/react': '*'
'@types/react@19.3.0': '@types/react@19.3.3':
resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==} resolution: {integrity: sha512-K8uWpJc4teiuOPdiP1umjeA9rGMgVPiXuoL66fcS1QlwBT1WMqY8PORmub9FadopIs+RCW6siYEs7Lpq+vDlog==}
'@types/trusted-types@2.0.7': '@types/trusted-types@2.0.7':
resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==} resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}
@@ -2661,10 +2663,6 @@ packages:
resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==} resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==}
engines: {node: '>= 20.19.0'} engines: {node: '>= 20.19.0'}
chownr@3.0.0:
resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==}
engines: {node: '>=18'}
cidr-block@2.3.0: cidr-block@2.3.0:
resolution: {integrity: sha512-U5NE6QJKNOhIsVrI6sicbwGtEmEORbrz9B5Mbl+Mi05sz1Ic4egoLGV4DkJp56VWva61WxOf+vzIxTKEmRazqg==} resolution: {integrity: sha512-U5NE6QJKNOhIsVrI6sicbwGtEmEORbrz9B5Mbl+Mi05sz1Ic4egoLGV4DkJp56VWva61WxOf+vzIxTKEmRazqg==}
engines: {node: '>=16'} engines: {node: '>=16'}
@@ -3106,9 +3104,9 @@ packages:
resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==} resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==}
engines: {node: '>= 6'} engines: {node: '>= 6'}
formatly@0.11.4: formatly@0.12.3:
resolution: {integrity: sha512-TeCC10lP8KCgoX+Fe5lryILIT0/Dy+nP0OSVnsuB5CwXoLuOdqxCYlPFF1inR8S/zTy1ec7TjhS2TeRKWzzImA==} resolution: {integrity: sha512-jGtjZLVw6OXvfwqxrxYBc+x+CxmOcMT/KjZagmkrYCQTEtQxJPablRqZPFSNq75drNsHsadjb1djIsE9KE705w==}
engines: {node: '>=18.14.0'} engines: {node: ^20.12.0 || >=22}
hasBin: true hasBin: true
foxact@0.3.12: foxact@0.3.12:
@@ -3358,8 +3356,8 @@ packages:
keyv@5.6.0: keyv@5.6.0:
resolution: {integrity: sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==} resolution: {integrity: sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==}
knip@6.48.0: knip@6.49.0:
resolution: {integrity: sha512-v+Gfp6uiOeXaaj+Khk2Z7/fTTZYWLnDwxZapQUyy8WoQFLYXiUHXqRdFJTwRnrKNA1gPXTPi5NGTKKLXyImVrg==} resolution: {integrity: sha512-8Gf4R0xcJx1NdNKfr6gOGgSVBE1flB+KHPKPybDTKJ/hPtnswxyFE7Zpsk71kBvzAKReezakbe3DbQ0qAT4vzA==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true hasBin: true
@@ -3601,14 +3599,6 @@ packages:
resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==} resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==}
engines: {node: 18 || 20 || >=22} engines: {node: 18 || 20 || >=22}
minipass@7.1.3:
resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==}
engines: {node: '>=16 || 14 >=14.17'}
minizlib@3.1.0:
resolution: {integrity: sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==}
engines: {node: '>= 18'}
monaco-editor@0.58.0: monaco-editor@0.58.0:
resolution: {integrity: sha512-Lj5hlfT4zdM5GSG9VxTHslWnwibGBvO6d9Mq/+9zmb1CkTZnib4+uAZUKl1zg+tMHRgY2OGax6hHKZNBtldR1g==} resolution: {integrity: sha512-Lj5hlfT4zdM5GSG9VxTHslWnwibGBvO6d9Mq/+9zmb1CkTZnib4+uAZUKl1zg+tMHRgY2OGax6hHKZNBtldR1g==}
@@ -3677,8 +3667,8 @@ packages:
resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==}
engines: {node: '>= 0.8.0'} engines: {node: '>= 0.8.0'}
oxc-parser@0.156.0: oxc-parser@0.160.0:
resolution: {integrity: sha512-7JhjgOfZjrIFJH5TlHrpRua864Si5GvwrPr5+eIRCY2sszhKXo6pyhP0HQKOGTtfO4UowwZ72XTGba0+lZphOQ==} resolution: {integrity: sha512-IIc9PydmdnTcH1hucWCHfTUbAuHWPDEs8+WlmW7td3jJnaYrbzvPQgcc99FEJc0gURrVU8EskpAr2VMyJ8VbzA==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
oxc-resolver@11.24.2: oxc-resolver@11.24.2:
@@ -3706,6 +3696,15 @@ packages:
resolution: {integrity: sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==} resolution: {integrity: sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==}
engines: {node: '>=8'} engines: {node: '>=8'}
parse-standard-args@0.3.0:
resolution: {integrity: sha512-SH663jox6V7vxSZgroZJw9DgvSbcNHWOnjHjgvsPyj0/+OIbFraNJyDQbA+ATaAUIi0OGAmV27bIGUgcAEM41g==}
engines: {node: '>=18.7.0'}
peerDependencies:
'@clack/prompts': '>=0.11'
peerDependenciesMeta:
'@clack/prompts':
optional: true
parse5@7.3.0: parse5@7.3.0:
resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==} resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==}
@@ -4024,9 +4023,9 @@ packages:
systemjs@6.15.1: systemjs@6.15.1:
resolution: {integrity: sha512-Nk8c4lXvMB98MtbmjX7JwJRgJOL8fluecYCfCeYBznwmpOs8Bf15hLM6z4z71EDAhQVrQrI+wt1aLWSXZq+hXA==} resolution: {integrity: sha512-Nk8c4lXvMB98MtbmjX7JwJRgJOL8fluecYCfCeYBznwmpOs8Bf15hLM6z4z71EDAhQVrQrI+wt1aLWSXZq+hXA==}
tar@7.5.22: tar@8.0.2:
resolution: {integrity: sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==} resolution: {integrity: sha512-1keL/dBVXwzliTinVjILeV/qZ2K3NNVFpg4JM1h3REOUJFamSLZmzVbCJXS6mF91//NwSaCbQ0gqmNwzE+ExCA==}
engines: {node: '>=18'} engines: {node: '>=22'}
tauri-plugin-mihomo-api@https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f: tauri-plugin-mihomo-api@https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f:
resolution: {gitHosted: true, integrity: sha512-4nRJ9eBOdd+mT9KaqEhUNya8bh/zaHHAJMBRgFR62KxSZ0S77mcjkB6Bz2xmHqPdYrhbi58aD6UcybEp4a6UyA==, tarball: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f} resolution: {gitHosted: true, integrity: sha512-4nRJ9eBOdd+mT9KaqEhUNya8bh/zaHHAJMBRgFR62KxSZ0S77mcjkB6Bz2xmHqPdYrhbi58aD6UcybEp4a6UyA==, tarball: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f}
@@ -4057,11 +4056,11 @@ packages:
resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
engines: {node: '>=12.0.0'} engines: {node: '>=12.0.0'}
tldts-core@7.5.5: tldts-core@7.6.3:
resolution: {integrity: sha512-rEJz/8cJFY/bdF354gl14yxavbrIbvM+FcbkYVQ6CSCMQTJdUFUIm39TTWSiGPvcpQh7/F6qHrD3SkwwdgtDCw==} resolution: {integrity: sha512-HjQiEhyxofqR2GM1cOp8CSwMYoKpmz/guhmZniTUayo7W/8d6uXebMelNanMFwRz0jKcMIprTzQDLuPdDyTBNA==}
tldts@7.5.5: tldts@7.6.3:
resolution: {integrity: sha512-Hy6IImaWALzJOgCIss4gIFi4G0M9lqk95pFKCUVxQPZw+biZ1Pv6f28JpYgahpJB+BufA0HYsIU/aP/WIx3KRg==} resolution: {integrity: sha512-x/ocO0PagQVYQHoAk19SsR9j/ylnRLU82sugMUl9eGdHGHgw46NLzopvcYDUCW/kgVFwJe/syU9dMjbrS2e5cQ==}
hasBin: true hasBin: true
trim-lines@3.0.1: trim-lines@3.0.1:
@@ -4113,8 +4112,8 @@ packages:
engines: {node: '>=14.17'} engines: {node: '>=14.17'}
hasBin: true hasBin: true
unbash@6.0.4: unbash@6.0.5:
resolution: {integrity: sha512-t3OptUArewg9OpYGDskTSlxhyLDahfmZ4d36hE44Efb1y3HRLLpzsVqwH+AwBVymP4t7pP71xN+nnduudn2awA==} resolution: {integrity: sha512-5P8o+nYRueKpHxmemofYqZRZCSWAi+Tqy31MQS8l/sT54Z+Axn55N9CnWPo19BxxJD4wYYf6RqlcURhWkrFXew==}
engines: {node: '>=14'} engines: {node: '>=14'}
undici-types@8.9.0: undici-types@8.9.0:
@@ -4320,10 +4319,6 @@ packages:
yallist@3.1.1: yallist@3.1.1:
resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}
yallist@5.0.0:
resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==}
engines: {node: '>=18'}
yaml@1.10.3: yaml@1.10.3:
resolution: {integrity: sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==} resolution: {integrity: sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==}
engines: {node: '>= 6'} engines: {node: '>= 6'}
@@ -5201,7 +5196,7 @@ snapshots:
'@emotion/memoize@0.9.0': {} '@emotion/memoize@0.9.0': {}
'@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)': '@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)':
dependencies: dependencies:
'@babel/runtime': 7.29.7 '@babel/runtime': 7.29.7
'@emotion/babel-plugin': 11.13.5(supports-color@7.2.0) '@emotion/babel-plugin': 11.13.5(supports-color@7.2.0)
@@ -5213,7 +5208,7 @@ snapshots:
hoist-non-react-statics: 3.3.2 hoist-non-react-statics: 3.3.2
react: 19.3.1 react: 19.3.1
optionalDependencies: optionalDependencies:
'@types/react': 19.3.0 '@types/react': 19.3.3
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
@@ -5227,18 +5222,18 @@ snapshots:
'@emotion/sheet@1.4.0': {} '@emotion/sheet@1.4.0': {}
'@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)': '@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)':
dependencies: dependencies:
'@babel/runtime': 7.29.7 '@babel/runtime': 7.29.7
'@emotion/babel-plugin': 11.13.5(supports-color@7.2.0) '@emotion/babel-plugin': 11.13.5(supports-color@7.2.0)
'@emotion/is-prop-valid': 1.4.0 '@emotion/is-prop-valid': 1.4.0
'@emotion/react': 11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0) '@emotion/react': 11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
'@emotion/serialize': 1.3.3 '@emotion/serialize': 1.3.3
'@emotion/use-insertion-effect-with-fallbacks': 1.2.0(react@19.3.1) '@emotion/use-insertion-effect-with-fallbacks': 1.2.0(react@19.3.1)
'@emotion/utils': 1.4.2 '@emotion/utils': 1.4.2
react: 19.3.1 react: 19.3.1
optionalDependencies: optionalDependencies:
'@types/react': 19.3.0 '@types/react': 19.3.3
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
@@ -5468,10 +5463,6 @@ snapshots:
'@humanwhocodes/retry@0.4.3': {} '@humanwhocodes/retry@0.4.3': {}
'@isaacs/fs-minipass@4.0.1':
dependencies:
minipass: 7.1.3
'@jridgewell/gen-mapping@0.3.13': '@jridgewell/gen-mapping@0.3.13':
dependencies: dependencies:
'@jridgewell/sourcemap-codec': 1.6.0 '@jridgewell/sourcemap-codec': 1.6.0
@@ -5519,23 +5510,23 @@ snapshots:
'@mui/core-downloads-tracker@9.4.0': {} '@mui/core-downloads-tracker@9.4.0': {}
'@mui/icons-material@9.4.0(@mui/material@9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/react@19.3.0)(react@19.3.1)': '@mui/icons-material@9.4.0(@mui/material@9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/react@19.3.3)(react@19.3.1)':
dependencies: dependencies:
'@babel/runtime': 7.29.7 '@babel/runtime': 7.29.7
'@mui/material': 9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@mui/material': 9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
react: 19.3.1 react: 19.3.1
optionalDependencies: optionalDependencies:
'@types/react': 19.3.0 '@types/react': 19.3.3
'@mui/material@9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': '@mui/material@9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)':
dependencies: dependencies:
'@babel/runtime': 7.29.7 '@babel/runtime': 7.29.7
'@mui/core-downloads-tracker': 9.4.0 '@mui/core-downloads-tracker': 9.4.0
'@mui/system': 9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1) '@mui/system': 9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)
'@mui/types': 9.4.0(@types/react@19.3.0) '@mui/types': 9.4.0(@types/react@19.3.3)
'@mui/utils': 9.4.0(@types/react@19.3.0)(react@19.3.1) '@mui/utils': 9.4.0(@types/react@19.3.3)(react@19.3.1)
'@popperjs/core': 2.11.8 '@popperjs/core': 2.11.8
'@types/react-transition-group': 4.4.12(@types/react@19.3.0) '@types/react-transition-group': 4.4.12(@types/react@19.3.3)
clsx: 2.1.1 clsx: 2.1.1
csstype: 3.2.3 csstype: 3.2.3
prop-types: 15.8.1 prop-types: 15.8.1
@@ -5544,20 +5535,20 @@ snapshots:
react-is: 19.3.0 react-is: 19.3.0
react-transition-group: 4.4.5(react-dom@19.3.1(react@19.3.1))(react@19.3.1) react-transition-group: 4.4.5(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
optionalDependencies: optionalDependencies:
'@emotion/react': 11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0) '@emotion/react': 11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
'@emotion/styled': 11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0) '@emotion/styled': 11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
'@types/react': 19.3.0 '@types/react': 19.3.3
'@mui/private-theming@9.4.0(@types/react@19.3.0)(react@19.3.1)': '@mui/private-theming@9.4.0(@types/react@19.3.3)(react@19.3.1)':
dependencies: dependencies:
'@babel/runtime': 7.29.7 '@babel/runtime': 7.29.7
'@mui/utils': 9.4.0(@types/react@19.3.0)(react@19.3.1) '@mui/utils': 9.4.0(@types/react@19.3.3)(react@19.3.1)
prop-types: 15.8.1 prop-types: 15.8.1
react: 19.3.1 react: 19.3.1
optionalDependencies: optionalDependencies:
'@types/react': 19.3.0 '@types/react': 19.3.3
'@mui/styled-engine@9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(react@19.3.1)': '@mui/styled-engine@9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(react@19.3.1)':
dependencies: dependencies:
'@babel/runtime': 7.29.7 '@babel/runtime': 7.29.7
'@emotion/cache': 11.14.0 '@emotion/cache': 11.14.0
@@ -5567,42 +5558,42 @@ snapshots:
prop-types: 15.8.1 prop-types: 15.8.1
react: 19.3.1 react: 19.3.1
optionalDependencies: optionalDependencies:
'@emotion/react': 11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0) '@emotion/react': 11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
'@emotion/styled': 11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0) '@emotion/styled': 11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
'@mui/system@9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)': '@mui/system@9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)':
dependencies: dependencies:
'@babel/runtime': 7.29.7 '@babel/runtime': 7.29.7
'@mui/private-theming': 9.4.0(@types/react@19.3.0)(react@19.3.1) '@mui/private-theming': 9.4.0(@types/react@19.3.3)(react@19.3.1)
'@mui/styled-engine': 9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(react@19.3.1) '@mui/styled-engine': 9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(react@19.3.1)
'@mui/types': 9.4.0(@types/react@19.3.0) '@mui/types': 9.4.0(@types/react@19.3.3)
'@mui/utils': 9.4.0(@types/react@19.3.0)(react@19.3.1) '@mui/utils': 9.4.0(@types/react@19.3.3)(react@19.3.1)
clsx: 2.1.1 clsx: 2.1.1
csstype: 3.2.3 csstype: 3.2.3
prop-types: 15.8.1 prop-types: 15.8.1
react: 19.3.1 react: 19.3.1
optionalDependencies: optionalDependencies:
'@emotion/react': 11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0) '@emotion/react': 11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
'@emotion/styled': 11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0) '@emotion/styled': 11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
'@types/react': 19.3.0 '@types/react': 19.3.3
'@mui/types@9.4.0(@types/react@19.3.0)': '@mui/types@9.4.0(@types/react@19.3.3)':
dependencies: dependencies:
'@babel/runtime': 7.29.7 '@babel/runtime': 7.29.7
optionalDependencies: optionalDependencies:
'@types/react': 19.3.0 '@types/react': 19.3.3
'@mui/utils@9.4.0(@types/react@19.3.0)(react@19.3.1)': '@mui/utils@9.4.0(@types/react@19.3.3)(react@19.3.1)':
dependencies: dependencies:
'@babel/runtime': 7.29.7 '@babel/runtime': 7.29.7
'@mui/types': 9.4.0(@types/react@19.3.0) '@mui/types': 9.4.0(@types/react@19.3.3)
'@types/prop-types': 15.7.15 '@types/prop-types': 15.7.15
clsx: 2.1.1 clsx: 2.1.1
prop-types: 15.8.1 prop-types: 15.8.1
react: 19.3.1 react: 19.3.1
react-is: 19.3.0 react-is: 19.3.0
optionalDependencies: optionalDependencies:
'@types/react': 19.3.0 '@types/react': 19.3.3
'@napi-rs/wasm-runtime@1.2.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)': '@napi-rs/wasm-runtime@1.2.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)':
dependencies: dependencies:
@@ -5676,65 +5667,67 @@ snapshots:
dependencies: dependencies:
'@octokit/openapi-types': 29.0.1 '@octokit/openapi-types': 29.0.1
'@oxc-parser/binding-android-arm-eabi@0.156.0': '@oxc-parser/binding-android-arm-eabi@0.160.0':
optional: true optional: true
'@oxc-parser/binding-android-arm64@0.156.0': '@oxc-parser/binding-android-arm64@0.160.0':
optional: true optional: true
'@oxc-parser/binding-darwin-arm64@0.156.0': '@oxc-parser/binding-darwin-arm64@0.160.0':
optional: true optional: true
'@oxc-parser/binding-darwin-x64@0.156.0': '@oxc-parser/binding-darwin-x64@0.160.0':
optional: true optional: true
'@oxc-parser/binding-freebsd-x64@0.156.0': '@oxc-parser/binding-freebsd-x64@0.160.0':
optional: true optional: true
'@oxc-parser/binding-linux-arm-gnueabihf@0.156.0': '@oxc-parser/binding-linux-arm-gnueabihf@0.160.0':
optional: true optional: true
'@oxc-parser/binding-linux-arm-musleabihf@0.156.0': '@oxc-parser/binding-linux-arm-musleabihf@0.160.0':
optional: true optional: true
'@oxc-parser/binding-linux-arm64-gnu@0.156.0': '@oxc-parser/binding-linux-arm64-gnu@0.160.0':
optional: true optional: true
'@oxc-parser/binding-linux-arm64-musl@0.156.0': '@oxc-parser/binding-linux-arm64-musl@0.160.0':
optional: true optional: true
'@oxc-parser/binding-linux-ppc64-gnu@0.156.0': '@oxc-parser/binding-linux-ppc64-gnu@0.160.0':
optional: true optional: true
'@oxc-parser/binding-linux-riscv64-gnu@0.156.0': '@oxc-parser/binding-linux-riscv64-gnu@0.160.0':
optional: true optional: true
'@oxc-parser/binding-linux-riscv64-musl@0.156.0': '@oxc-parser/binding-linux-riscv64-musl@0.160.0':
optional: true optional: true
'@oxc-parser/binding-linux-s390x-gnu@0.156.0': '@oxc-parser/binding-linux-s390x-gnu@0.160.0':
optional: true optional: true
'@oxc-parser/binding-linux-x64-gnu@0.156.0': '@oxc-parser/binding-linux-x64-gnu@0.160.0':
optional: true optional: true
'@oxc-parser/binding-linux-x64-musl@0.156.0': '@oxc-parser/binding-linux-x64-musl@0.160.0':
optional: true optional: true
'@oxc-parser/binding-openharmony-arm64@0.156.0': '@oxc-parser/binding-openharmony-arm64@0.160.0':
optional: true optional: true
'@oxc-parser/binding-win32-arm64-msvc@0.156.0': '@oxc-parser/binding-win32-arm64-msvc@0.160.0':
optional: true optional: true
'@oxc-parser/binding-win32-ia32-msvc@0.156.0': '@oxc-parser/binding-win32-ia32-msvc@0.160.0':
optional: true optional: true
'@oxc-parser/binding-win32-x64-msvc@0.156.0': '@oxc-parser/binding-win32-x64-msvc@0.160.0':
optional: true optional: true
'@oxc-project/types@0.156.0': {} '@oxc-project/types@0.156.0': {}
'@oxc-project/types@0.160.0': {}
'@oxc-resolver/binding-android-arm-eabi@11.24.2': '@oxc-resolver/binding-android-arm-eabi@11.24.2':
optional: true optional: true
@@ -5912,6 +5905,8 @@ snapshots:
estree-walker: 2.0.2 estree-walker: 2.0.2
picomatch: 4.0.7 picomatch: 4.0.7
'@standard-schema/spec@1.1.0': {}
'@svgr/babel-plugin-add-jsx-attribute@8.0.0(@babel/core@7.29.7(supports-color@7.2.0))': '@svgr/babel-plugin-add-jsx-attribute@8.0.0(@babel/core@7.29.7(supports-color@7.2.0))':
dependencies: dependencies:
'@babel/core': 7.29.7(supports-color@7.2.0) '@babel/core': 7.29.7(supports-color@7.2.0)
@@ -6134,15 +6129,15 @@ snapshots:
'@types/prop-types@15.7.15': {} '@types/prop-types@15.7.15': {}
'@types/react-dom@19.3.0(@types/react@19.3.0)': '@types/react-dom@19.3.0(@types/react@19.3.3)':
dependencies: dependencies:
'@types/react': 19.3.0 '@types/react': 19.3.3
'@types/react-transition-group@4.4.12(@types/react@19.3.0)': '@types/react-transition-group@4.4.12(@types/react@19.3.3)':
dependencies: dependencies:
'@types/react': 19.3.0 '@types/react': 19.3.3
'@types/react@19.3.0': '@types/react@19.3.3':
dependencies: dependencies:
csstype: 3.2.3 csstype: 3.2.3
@@ -6501,8 +6496,6 @@ snapshots:
dependencies: dependencies:
readdirp: 5.1.1 readdirp: 5.1.1
chownr@3.0.0: {}
cidr-block@2.3.0: {} cidr-block@2.3.0: {}
cli-color@2.0.4: cli-color@2.0.4:
@@ -7045,10 +7038,15 @@ snapshots:
hasown: 2.0.4 hasown: 2.0.4
mime-types: 2.1.35 mime-types: 2.1.35
formatly@0.11.4: formatly@0.12.3:
dependencies: dependencies:
fd-package-json: 2.0.0 fd-package-json: 2.0.0
package-manager-detector: 1.8.0 package-manager-detector: 1.8.0
parse-standard-args: 0.3.0
tinyexec: 1.3.1
zod: 4.6.5
transitivePeerDependencies:
- '@clack/prompts'
foxact@0.3.12(react-dom@19.3.1(react@19.3.1))(react@19.3.1): foxact@0.3.12(react-dom@19.3.1(react@19.3.1))(react@19.3.1):
dependencies: dependencies:
@@ -7319,19 +7317,21 @@ snapshots:
dependencies: dependencies:
'@keyv/serialize': 1.1.1 '@keyv/serialize': 1.1.1
knip@6.48.0: knip@6.49.0:
dependencies: dependencies:
formatly: 0.11.4 formatly: 0.12.3
get-tsconfig: 4.14.3 get-tsconfig: 4.14.3
jiti: 2.7.0 jiti: 2.7.0
oxc-parser: 0.156.0 oxc-parser: 0.160.0
oxc-resolver: 11.24.2 oxc-resolver: 11.24.2
picomatch: 4.0.7 picomatch: 4.0.7
smol-toml: 1.9.1 smol-toml: 1.9.1
strip-json-comments: 5.0.3 strip-json-comments: 5.0.3
tinyglobby: 0.2.17 tinyglobby: 0.2.17
unbash: 6.0.4 unbash: 6.0.5
yaml: 2.9.1 yaml: 2.9.1
transitivePeerDependencies:
- '@clack/prompts'
levn@0.4.1: levn@0.4.1:
dependencies: dependencies:
@@ -7680,12 +7680,6 @@ snapshots:
dependencies: dependencies:
brace-expansion: 5.0.12 brace-expansion: 5.0.12
minipass@7.1.3: {}
minizlib@3.1.0:
dependencies:
minipass: 7.1.3
monaco-editor@0.58.0: monaco-editor@0.58.0:
dependencies: dependencies:
'@vscode/diff': 0.0.2-145 '@vscode/diff': 0.0.2-145
@@ -7760,29 +7754,29 @@ snapshots:
type-check: 0.4.0 type-check: 0.4.0
word-wrap: 1.2.5 word-wrap: 1.2.5
oxc-parser@0.156.0: oxc-parser@0.160.0:
dependencies: dependencies:
'@oxc-project/types': 0.156.0 '@oxc-project/types': 0.160.0
optionalDependencies: optionalDependencies:
'@oxc-parser/binding-android-arm-eabi': 0.156.0 '@oxc-parser/binding-android-arm-eabi': 0.160.0
'@oxc-parser/binding-android-arm64': 0.156.0 '@oxc-parser/binding-android-arm64': 0.160.0
'@oxc-parser/binding-darwin-arm64': 0.156.0 '@oxc-parser/binding-darwin-arm64': 0.160.0
'@oxc-parser/binding-darwin-x64': 0.156.0 '@oxc-parser/binding-darwin-x64': 0.160.0
'@oxc-parser/binding-freebsd-x64': 0.156.0 '@oxc-parser/binding-freebsd-x64': 0.160.0
'@oxc-parser/binding-linux-arm-gnueabihf': 0.156.0 '@oxc-parser/binding-linux-arm-gnueabihf': 0.160.0
'@oxc-parser/binding-linux-arm-musleabihf': 0.156.0 '@oxc-parser/binding-linux-arm-musleabihf': 0.160.0
'@oxc-parser/binding-linux-arm64-gnu': 0.156.0 '@oxc-parser/binding-linux-arm64-gnu': 0.160.0
'@oxc-parser/binding-linux-arm64-musl': 0.156.0 '@oxc-parser/binding-linux-arm64-musl': 0.160.0
'@oxc-parser/binding-linux-ppc64-gnu': 0.156.0 '@oxc-parser/binding-linux-ppc64-gnu': 0.160.0
'@oxc-parser/binding-linux-riscv64-gnu': 0.156.0 '@oxc-parser/binding-linux-riscv64-gnu': 0.160.0
'@oxc-parser/binding-linux-riscv64-musl': 0.156.0 '@oxc-parser/binding-linux-riscv64-musl': 0.160.0
'@oxc-parser/binding-linux-s390x-gnu': 0.156.0 '@oxc-parser/binding-linux-s390x-gnu': 0.160.0
'@oxc-parser/binding-linux-x64-gnu': 0.156.0 '@oxc-parser/binding-linux-x64-gnu': 0.160.0
'@oxc-parser/binding-linux-x64-musl': 0.156.0 '@oxc-parser/binding-linux-x64-musl': 0.160.0
'@oxc-parser/binding-openharmony-arm64': 0.156.0 '@oxc-parser/binding-openharmony-arm64': 0.160.0
'@oxc-parser/binding-win32-arm64-msvc': 0.156.0 '@oxc-parser/binding-win32-arm64-msvc': 0.160.0
'@oxc-parser/binding-win32-ia32-msvc': 0.156.0 '@oxc-parser/binding-win32-ia32-msvc': 0.160.0
'@oxc-parser/binding-win32-x64-msvc': 0.156.0 '@oxc-parser/binding-win32-x64-msvc': 0.160.0
oxc-resolver@11.24.2: oxc-resolver@11.24.2:
optionalDependencies: optionalDependencies:
@@ -7837,6 +7831,10 @@ snapshots:
json-parse-even-better-errors: 2.3.1 json-parse-even-better-errors: 2.3.1
lines-and-columns: 1.2.4 lines-and-columns: 1.2.4
parse-standard-args@0.3.0:
dependencies:
'@standard-schema/spec': 1.1.0
parse5@7.3.0: parse5@7.3.0:
dependencies: dependencies:
entities: 6.0.1 entities: 6.0.1
@@ -7894,11 +7892,11 @@ snapshots:
react: 19.3.1 react: 19.3.1
scheduler: 0.28.0 scheduler: 0.28.0
react-error-boundary@6.1.6(@types/react@19.3.0)(react@19.3.1): react-error-boundary@6.1.6(@types/react@19.3.3)(react@19.3.1):
dependencies: dependencies:
react: 19.3.1 react: 19.3.1
optionalDependencies: optionalDependencies:
'@types/react': 19.3.0 '@types/react': 19.3.3
react-fast-compare@3.2.2: {} react-fast-compare@3.2.2: {}
@@ -7906,24 +7904,24 @@ snapshots:
dependencies: dependencies:
react: 19.3.1 react: 19.3.1
react-i18next@18.0.3(@types/react@19.3.0)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3): react-i18next@18.0.3(@types/react@19.3.3)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3):
dependencies: dependencies:
html-parse-stringify: 4.0.1 html-parse-stringify: 4.0.1
i18next: 27.0.1(typescript@6.0.3) i18next: 27.0.1(typescript@6.0.3)
react: 19.3.1 react: 19.3.1
optionalDependencies: optionalDependencies:
'@types/react': 19.3.0 '@types/react': 19.3.3
typescript: 6.0.3 typescript: 6.0.3
react-is@16.13.1: {} react-is@16.13.1: {}
react-is@19.3.0: {} react-is@19.3.0: {}
react-markdown@10.1.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0): react-markdown@10.1.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0):
dependencies: dependencies:
'@types/hast': 3.0.5 '@types/hast': 3.0.5
'@types/mdast': 4.0.4 '@types/mdast': 4.0.4
'@types/react': 19.3.0 '@types/react': 19.3.3
devlop: 1.1.0 devlop: 1.1.0
hast-util-to-jsx-runtime: 2.3.6(supports-color@7.2.0) hast-util-to-jsx-runtime: 2.3.6(supports-color@7.2.0)
html-url-attributes: 3.0.1 html-url-attributes: 3.0.1
@@ -8135,13 +8133,7 @@ snapshots:
systemjs@6.15.1: {} systemjs@6.15.1: {}
tar@7.5.22: tar@8.0.2: {}
dependencies:
'@isaacs/fs-minipass': 4.0.1
chownr: 3.0.0
minipass: 7.1.3
minizlib: 3.1.0
yallist: 5.0.0
tauri-plugin-mihomo-api@https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f: tauri-plugin-mihomo-api@https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f:
dependencies: dependencies:
@@ -8170,11 +8162,11 @@ snapshots:
fdir: 6.5.0(picomatch@4.0.7) fdir: 6.5.0(picomatch@4.0.7)
picomatch: 4.0.7 picomatch: 4.0.7
tldts-core@7.5.5: {} tldts-core@7.6.3: {}
tldts@7.5.5: tldts@7.6.3:
dependencies: dependencies:
tldts-core: 7.5.5 tldts-core: 7.6.3
trim-lines@3.0.1: {} trim-lines@3.0.1: {}
@@ -8221,7 +8213,7 @@ snapshots:
typescript@6.0.3: {} typescript@6.0.3: {}
unbash@6.0.4: {} unbash@6.0.5: {}
undici-types@8.9.0: {} undici-types@8.9.0: {}
@@ -8409,8 +8401,6 @@ snapshots:
yallist@3.1.1: {} yallist@3.1.1: {}
yallist@5.0.0: {}
yaml@1.10.3: {} yaml@1.10.3: {}
yaml@2.9.1: {} yaml@2.9.1: {}
+1 -1
View File
@@ -1,3 +1,3 @@
[toolchain] [toolchain]
channel = "1.100.0" channel = "1.100.1"
components = ["rustfmt", "clippy"] components = ["rustfmt", "clippy"]
+16 -21
View File
@@ -1,24 +1,19 @@
# Backend Architecture Guardrails # Backend Architecture Guardrails
These rules supplement the repository's root `AGENTS.md`. Use [Workspace Crate Architecture](../crates/AGENTS.md) when extracting backend
capabilities or changing background task ownership.
- **Configuration ownership.** `config` owns source configuration, drafts and - **Configuration and effects.** `config` owns source configuration, drafts, and
persistence. The effects layer owns patch orchestration. Rollbackable persistence. The effects layer classifies every Verge patch field, including
transactions publish state after persistence and commit; already applied fields without effects and platform-specific fields, and reconciles requested
runtime and independently committed state remain authoritative even when a state in dependency order. Publish rollbackable state after persistence and
later step fails. Preserve that state, its notifications and the error. commit. On failure, preserve already applied runtime effects, independently
- **Effect ownership.** The declarative registry classifies every Verge patch field, committed state, their notifications, and the error.
including fields without effects and platform-specific fields. Effects - **Wire contract.** Use typed notifications and preserve event names, status
reconcile toward the requested state with explicit dependencies and ordering. values, and payload compatibility with frontend consumers.
Configuration rollback does not imply reversal of OS or lifecycle effects. - **Lock order.** Acquire configuration-write, configuration-update, Core
- **Shared wire contract.** Notifications are typed. Event names, status values lifecycle, and DNS ownership in that order when needed. Preserve independent
and payload shapes stay compatible with frontend producers and consumers. transaction boundaries and release synchronous guards before suspension.
- **Synchronization ownership.** Configuration-write serialization precedes - **Retries.** Reuse the backend retry policy and preserve attempts, delays, and
configuration-update ownership, which precedes Core lifecycle ownership. terminal errors. Keep monitor lifetime, condition waits, and candidate fallback
When both are held, the lifecycle lock precedes the DNS lock. Independent under their own contracts.
transactions retain their ownership boundaries; asynchronous work does not
hold synchronous data guards across suspension.
- **Retry ownership.** Bounded retries share backend policy while preserving
attempts, delays and terminal errors. Background monitors own their lifetime
and cancellation separately; waiting for a condition or traversing distinct
candidates is not a retry policy.
+3 -2
View File
@@ -31,6 +31,7 @@ tauri-build = { version = "2.7.6", features = [] }
[dependencies] [dependencies]
clash-verge-draft = { workspace = true } clash-verge-draft = { workspace = true }
clash-verge-task = { workspace = true }
clash-verge-media-unlock = { workspace = true } clash-verge-media-unlock = { workspace = true }
clash-verge-logging = { workspace = true } clash-verge-logging = { workspace = true }
clash-verge-i18n = { workspace = true } clash-verge-i18n = { workspace = true }
@@ -75,14 +76,14 @@ tauri-plugin-dialog = "2.8.4"
tauri-plugin-fs = "2.7.1" tauri-plugin-fs = "2.7.1"
tauri-plugin-deep-link = "2.6.3" tauri-plugin-deep-link = "2.6.3"
tauri-plugin-window-state = "2.5.0" tauri-plugin-window-state = "2.5.0"
zip = "9.8.2" zip = "9.9.0"
flate2 = "1.1.11" flate2 = "1.1.11"
reqwest_dav = "0.4.0" reqwest_dav = "0.4.0"
aes-gcm = { version = "0.11.1" } aes-gcm = { version = "0.11.1" }
base64 = "0.23.1" base64 = "0.23.1"
sha2 = "0.11.2" sha2 = "0.11.2"
getrandom = "0.4.3" getrandom = "0.4.3"
futures = "0.3.34" futures = { workspace = true }
gethostname = "1.1.0" gethostname = "1.1.0"
tauri-plugin-notification = "2.8.1" tauri-plugin-notification = "2.8.1"
backon = { version = "1.6.0", features = ["tokio-sleep"] } backon = { version = "1.6.0", features = ["tokio-sleep"] }
+2 -2
View File
@@ -3,7 +3,7 @@ use crate::{
cmd::StringifyErr as _, cmd::StringifyErr as _,
cmd::validate::{ValidationNoticeTarget, handle_validation_notice}, cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
config::{Config, IProfiles, PrfItem}, config::{Config, IProfiles, PrfItem},
core::auto_backup::{AutoBackupManager, AutoBackupTrigger}, core::auto_backup::{self, AutoBackupTrigger},
core::{ core::{
CoreManager, handle, CoreManager, handle,
validate::{CoreConfigValidator, ValidationOutcome}, validate::{CoreConfigValidator, ValidationOutcome},
@@ -86,7 +86,7 @@ pub async fn save_profile_file(
if changes_applied.is_valid() if changes_applied.is_valid()
&& let Some(trigger) = backup_trigger && let Some(trigger) = backup_trigger
{ {
AutoBackupManager::trigger_backup(trigger); auto_backup::trigger_backup(trigger);
} }
Ok(changes_applied) Ok(changes_applied)
+18 -2
View File
@@ -2,14 +2,19 @@ use crate::core::notify::NoticeStatus;
use crate::utils::help; use crate::utils::help;
use anyhow::Result; use anyhow::Result;
use clash_verge_draft::DraftTransaction; use clash_verge_draft::DraftTransaction;
use clash_verge_logging::{Type, logging, logging_error};
use clash_verge_task::scheduled_task::{self, CoalescingJob};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_yaml_ng::{Mapping, Value}; use serde_yaml_ng::{Mapping, Value};
use sha2::{Digest as _, Sha256}; use sha2::{Digest as _, Sha256};
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{
LazyLock,
atomic::{AtomicBool, Ordering},
};
use tristr::alias::String; use tristr::alias::String;
use super::{Config, IVerge}; use super::{Config, IVerge};
use crate::core::handle::Handle; use crate::{core::handle::Handle, process::AsyncHandler};
static PENDING_DNS_OVERRIDE_NOTICE: AtomicBool = AtomicBool::new(false); static PENDING_DNS_OVERRIDE_NOTICE: AtomicBool = AtomicBool::new(false);
@@ -124,7 +129,18 @@ impl IVerge {
} }
} }
static DNS_OVERRIDE_SYNC: LazyLock<CoalescingJob> = LazyLock::new(|| {
AsyncHandler::start_driver(scheduled_task::coalescing(
|| async { logging_error!(Type::Config, Config::sync_dns_override().await) },
|| logging!(error, Type::Config, "DNS override synchronization panicked"),
))
});
impl Config { impl Config {
pub(crate) fn request_dns_override_sync() {
DNS_OVERRIDE_SYNC.request();
}
pub(crate) async fn sync_dns_override() -> Result<()> { pub(crate) async fn sync_dns_override() -> Result<()> {
let _config_write = Self::lock_config_write().await; let _config_write = Self::lock_config_write().await;
let state = Self::runtime().await.data_arc().dns_override.clone(); let state = Self::runtime().await.data_arc().dns_override.clone();
+126 -103
View File
@@ -6,6 +6,7 @@ use crate::core::notify::{Refresh, announce};
use crate::utils::retry::{RetryError, RetryPolicy, retry, retry_with_state}; use crate::utils::retry::{RetryError, RetryPolicy, retry, retry_with_state};
use crate::{ use crate::{
core::{handle, tray::Tray}, core::{handle, tray::Tray},
process::AsyncHandler,
utils::{ utils::{
dirs::{self, PathBufExec as _}, dirs::{self, PathBufExec as _},
help, help,
@@ -14,27 +15,27 @@ use crate::{
use anyhow::{Context as _, Result, bail}; use anyhow::{Context as _, Result, bail};
use clash_verge_draft::Draft; use clash_verge_draft::Draft;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use parking_lot::Mutex; use futures::FutureExt as _;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_yaml_ng::Mapping; use serde_yaml_ng::Mapping;
use std::num::NonZeroUsize; use std::num::NonZeroUsize;
use std::{ use std::{
collections::{HashMap, HashSet}, collections::{HashMap, HashSet},
panic::AssertUnwindSafe,
path::{Component, Path}, path::{Component, Path},
sync::{ sync::OnceLock,
LazyLock,
atomic::{AtomicU64, Ordering},
},
time::{Duration, Instant}, time::{Duration, Instant},
}; };
use tauri_plugin_mihomo::models::{Proxies, ProxyType}; use tauri_plugin_mihomo::models::{Proxies, ProxyType};
use tokio::{fs, task::JoinHandle}; use tokio::{
fs,
sync::{oneshot, watch},
};
use tristr::alias::String; use tristr::alias::String;
pub(crate) static PROFILE_WRITE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); pub(crate) static PROFILE_WRITE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
static ACTIVATE_SELECTED_TASK: LazyLock<Mutex<Option<JoinHandle<()>>>> = LazyLock::new(|| Mutex::new(None)); static SELECTED_ACTIVATION: OnceLock<watch::Sender<SelectedActivation>> = OnceLock::new();
static ACTIVATE_SELECTED_GENERATION: AtomicU64 = AtomicU64::new(0);
// The plugin already limits the request/response phase to 5 seconds. This outer timeout also covers // The plugin already limits the request/response phase to 5 seconds. This outer timeout also covers
// lock acquisition, connection-pool waiting, and local-socket connection establishment. // lock acquisition, connection-pool waiting, and local-socket connection establishment.
@@ -579,11 +580,15 @@ fn reconcile_selected_nodes(
/// Cancels restoration so it cannot overwrite a newer selection or profile snapshot. /// Cancels restoration so it cannot overwrite a newer selection or profile snapshot.
pub(crate) fn supersede_selected_activation() { pub(crate) fn supersede_selected_activation() {
ACTIVATE_SELECTED_GENERATION.fetch_add(1, Ordering::AcqRel); if let Some(inbox) = SELECTED_ACTIVATION.get() {
inbox.send_modify(|state| state.replace(None));
}
} }
fn is_activation_current(generation: u64) -> bool { fn is_activation_current(generation: u64) -> bool {
ACTIVATE_SELECTED_GENERATION.load(Ordering::Acquire) == generation SELECTED_ACTIVATION
.get()
.is_some_and(|inbox| inbox.borrow().generation == generation)
} }
async fn fetch_proxies_with_timeout() -> Result<Proxies> { async fn fetch_proxies_with_timeout() -> Result<Proxies> {
@@ -641,6 +646,10 @@ fn global_exit_target(proxies: &Proxies) -> Option<&str> {
/// Moves GLOBAL off a built-in unless the profile records any GLOBAL choice. /// Moves GLOBAL off a built-in unless the profile records any GLOBAL choice.
pub(crate) async fn leave_default_global_exit() -> Result<()> { pub(crate) async fn leave_default_global_exit() -> Result<()> {
leave_default_global_exit_if(|| true).await
}
async fn leave_default_global_exit_if(is_current: impl FnOnce() -> bool) -> Result<()> {
let profiles = Config::profiles().await.data_arc(); let profiles = Config::profiles().await.data_arc();
let has_record = profiles let has_record = profiles
.current .current
@@ -652,7 +661,7 @@ pub(crate) async fn leave_default_global_exit() -> Result<()> {
return Ok(()); return Ok(());
} }
let snapshot = fetch_proxies_with_timeout().await?; let snapshot = fetch_proxies_with_timeout().await?;
let Some(target) = global_exit_target(&snapshot) else { let Some(target) = global_exit_target(&snapshot).filter(|_| is_current()) else {
return Ok(()); return Ok(());
}; };
select_node_with_timeout(&String::from("GLOBAL"), &String::from(target)).await?; select_node_with_timeout(&String::from("GLOBAL"), &String::from(target)).await?;
@@ -913,23 +922,11 @@ async fn settle_pending_selections(selected: &[PrfSelected], completed: &mut Has
.await; .await;
} }
/// Releases the first-pass waiter even when restoration exits early.
struct FirstPassSignal(Option<tokio::sync::oneshot::Sender<()>>);
impl FirstPassSignal {
fn notify(&mut self) {
if let Some(sender) = self.0.take() {
let _ = sender.send(());
}
}
}
async fn activate_selected_nodes_worker( async fn activate_selected_nodes_worker(
profile_uid: String, profile_uid: String,
selected: Vec<PrfSelected>, selected: Vec<PrfSelected>,
generation: u64, generation: u64,
repair: SelectionRepair, request: ActivationRequest,
mut first_pass_done: FirstPassSignal,
) -> Result<()> { ) -> Result<()> {
let first_snapshot = fetch_proxies_with_timeout().await?; let first_snapshot = fetch_proxies_with_timeout().await?;
if !is_activation_current(generation) { if !is_activation_current(generation) {
@@ -987,9 +984,9 @@ async fn activate_selected_nodes_worker(
return Ok(()); return Ok(());
} }
if repair == SelectionRepair::KeepRecords { if let ActivationRequest::Restore(first_pass) = request {
// Remaining selections depend on provider loading and continue in the background. // Remaining selections depend on provider loading and continue in the background.
first_pass_done.notify(); let _ = first_pass.send(());
settle_pending_selections(&selected, &mut completed_activations, generation).await; settle_pending_selections(&selected, &mut completed_activations, generation).await;
return Ok(()); return Ok(());
} }
@@ -1007,25 +1004,35 @@ async fn activate_selected_nodes_worker(
Ok(()) Ok(())
} }
/// Whether an activation may also prune the records it cannot match. enum ActivationRequest {
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum SelectionRepair {
/// Prune records after a fully loaded profile switch. /// Prune records after a fully loaded profile switch.
Prune, Prune,
/// Preserve records during startup while provider-backed groups may still be absent. /// Preserve records at startup and release the first-pass waiter on early exit.
KeepRecords, Restore(oneshot::Sender<()>),
}
#[derive(Default)]
struct SelectedActivation {
generation: u64,
pending: Option<ActivationRequest>,
}
impl SelectedActivation {
fn replace(&mut self, request: Option<ActivationRequest>) {
self.generation = self.generation.wrapping_add(1);
self.pending = request;
}
} }
pub(crate) fn activate_selected_nodes() { pub(crate) fn activate_selected_nodes() {
// The first-pass signal is for callers that wait; a profile switch does not, and dropping submit_selected_activation(ActivationRequest::Prune);
// the receiver simply makes the send a no-op.
drop(activate_selected_nodes_with(SelectionRepair::Prune));
} }
/// Restores available selections before the system proxy points at the core, then retries the rest. /// Restores available selections before the system proxy points at the core, then retries the rest.
pub(crate) async fn restore_selected_nodes() { pub(crate) async fn restore_selected_nodes() {
let first_pass = activate_selected_nodes_with(SelectionRepair::KeepRecords); let (first_pass, done) = oneshot::channel();
if tokio::time::timeout(SELECTED_NODES_FIRST_PASS_BUDGET, first_pass) submit_selected_activation(ActivationRequest::Restore(first_pass));
if tokio::time::timeout(SELECTED_NODES_FIRST_PASS_BUDGET, done)
.await .await
.is_err() .is_err()
{ {
@@ -1037,63 +1044,82 @@ pub(crate) async fn restore_selected_nodes() {
} }
} }
fn activate_selected_nodes_with(repair: SelectionRepair) -> tokio::sync::oneshot::Receiver<()> { fn submit_selected_activation(request: ActivationRequest) {
logging!(debug, Type::Config, "starting activating selected nodes"); logging!(debug, Type::Config, "starting activating selected nodes");
let mut active_task = ACTIVATE_SELECTED_TASK.lock(); let inbox = SELECTED_ACTIVATION.get_or_init(|| {
let generation = ACTIVATE_SELECTED_GENERATION.fetch_add(1, Ordering::AcqRel) + 1; let (inbox, changes) = watch::channel(SelectedActivation::default());
let previous_task = active_task.take(); let worker_inbox = inbox.clone();
let (first_pass_sender, first_pass_done) = tokio::sync::oneshot::channel(); AsyncHandler::spawn(move || run_selected_activation(worker_inbox, changes));
inbox
let handle = tokio::spawn(async move {
// Dropping this releases the startup waiter on every early exit.
let first_pass = FirstPassSignal(Some(first_pass_sender));
if let Some(previous_task) = previous_task {
let _ = previous_task.await;
}
if !is_activation_current(generation) {
return;
}
let result = async {
// A draft may be a profile switch that has not passed validation yet.
let profiles = Config::profiles().await.data_arc();
let current = profiles.current.clone().context("no current profile running")?;
let selected = profiles
.get_item(&current)
.context("failed to get current profile")?
.selected
.clone()
.unwrap_or_default();
if Config::clash().await.latest_arc().get_mode().as_deref() == Some("global")
&& let Err(err) = leave_default_global_exit().await
{
logging!(warn, Type::Config, "failed to move GLOBAL off its default: {err:#}");
}
if selected.is_empty() {
if is_activation_current(generation) {
announce(Refresh::Clash);
}
return Ok(());
}
activate_selected_nodes_worker(current, selected, generation, repair, first_pass).await
}
.await;
if is_activation_current(generation) {
if let Err(err) = result {
logging!(error, Type::Config, "failed to activate selected nodes: {err:#}");
// The profile itself is already active even if node restoration failed.
announce(Refresh::Clash);
}
update_tray_after_activation(generation).await;
logging!(debug, Type::Config, "activating selected nodes done!");
}
}); });
*active_task = Some(handle); inbox.send_modify(|state| state.replace(Some(request)));
drop(active_task); }
first_pass_done
async fn run_selected_activation(
inbox: watch::Sender<SelectedActivation>,
mut changes: watch::Receiver<SelectedActivation>,
) {
while changes.changed().await.is_ok() {
let mut activation = None;
inbox.send_if_modified(|state| {
activation = state.pending.take().map(|request| (state.generation, request));
// Taking the request leaves the active generation unchanged.
false
});
if let Some((generation, request)) = activation
&& AssertUnwindSafe(activate_selected_request(generation, request))
.catch_unwind()
.await
.is_err()
{
logging!(error, Type::Config, "selected nodes activation panicked");
}
}
}
async fn activate_selected_request(generation: u64, request: ActivationRequest) {
if !is_activation_current(generation) {
return;
}
let result = async {
// A draft may be a profile switch that has not passed validation yet.
let profiles = Config::profiles().await.data_arc();
let current = profiles.current.clone().context("no current profile running")?;
let selected = profiles
.get_item(&current)
.context("failed to get current profile")?
.selected
.clone()
.unwrap_or_default();
if Config::clash().await.latest_arc().get_mode().as_deref() == Some("global")
&& is_activation_current(generation)
&& let Err(err) = leave_default_global_exit_if(|| is_activation_current(generation)).await
{
logging!(warn, Type::Config, "failed to move GLOBAL off its default: {err:#}");
}
if !is_activation_current(generation) {
return Ok(());
}
if selected.is_empty() {
announce(Refresh::Clash);
return Ok(());
}
activate_selected_nodes_worker(current, selected, generation, request).await
}
.await;
if is_activation_current(generation) {
if let Err(err) = result {
logging!(error, Type::Config, "failed to activate selected nodes: {err:#}");
// The profile itself is already active even if node restoration failed.
announce(Refresh::Clash);
}
update_tray_after_activation(generation).await;
logging!(debug, Type::Config, "activating selected nodes done!");
}
} }
#[cfg(test)] #[cfg(test)]
@@ -1331,7 +1357,7 @@ mod tests {
fn a_group_missing_from_both_snapshots_is_dropped_from_the_records() { fn a_group_missing_from_both_snapshots_is_dropped_from_the_records() {
// This is the pruning a profile switch wants and a core start must not do: the record is // This is the pruning a profile switch wants and a core start must not do: the record is
// gone from the plan, and `persist_reconciled_selected` writes the plan back. Pinned here // gone from the plan, and `persist_reconciled_selected` writes the plan back. Pinned here
// because it is why `SelectionRepair` exists — the predicate is right, the question is // because it is why `ActivationRequest` distinguishes these cases — the predicate is right, the question is
// only who is entitled to act on it. // only who is entitled to act on it.
let saved = vec![selected("provider-group", "saved")]; let saved = vec![selected("provider-group", "saved")];
let empty = proxies(vec![]); let empty = proxies(vec![]);
@@ -1360,19 +1386,16 @@ mod tests {
} }
#[test] #[test]
fn superseding_an_activation_makes_the_one_in_flight_stand_down() { fn replacement_releases_a_pending_first_pass_and_invalidates_its_generation() {
// What a selection made during a start relies on: the restore that is still polling the let mut activation = SelectedActivation::default();
// core has to notice it has been overtaken, or it will push the older node back. let (first_pass, mut done) = oneshot::channel();
let generation = ACTIVATE_SELECTED_GENERATION.load(Ordering::Acquire) + 1; activation.replace(Some(ActivationRequest::Restore(first_pass)));
ACTIVATE_SELECTED_GENERATION.store(generation, Ordering::Release); let generation = activation.generation;
assert!(is_activation_current(generation));
supersede_selected_activation(); activation.replace(None);
assert!( assert_ne!(activation.generation, generation);
!is_activation_current(generation), assert!(matches!(done.try_recv(), Err(oneshot::error::TryRecvError::Closed)));
"an activation that has been overtaken must stop before it puts anything"
);
} }
#[test] #[test]
-6
View File
@@ -42,12 +42,6 @@ pub mod timing {
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
pub const SERVICE_WAIT_INTERVAL: Duration = Duration::from_millis(200); pub const SERVICE_WAIT_INTERVAL: Duration = Duration::from_millis(200);
// 回退 sidecar 后继续等待服务就绪并尝试交接。
#[cfg(target_os = "windows")]
pub const SERVICE_HANDOFF_WINDOW: Duration = Duration::from_secs(120);
#[cfg(target_os = "windows")]
pub const SERVICE_HANDOFF_INTERVAL: Duration = Duration::from_secs(2);
// 交接时等待 sidecar 释放 ext-controller 通道。 // 交接时等待 sidecar 释放 ext-controller 通道。
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
pub const SERVICE_START_RETRIES: usize = 5; pub const SERVICE_START_RETRIES: usize = 5;
+130 -151
View File
@@ -1,29 +1,23 @@
use crate::process::AsyncHandler;
use crate::{ use crate::{
config::{Config, IVerge}, config::{Config, IVerge},
feat::create_local_backup_with_namer, feat::create_local_backup_with_namer,
process::AsyncHandler,
utils::dirs::local_backup_dir, utils::dirs::local_backup_dir,
}; };
use anyhow::Result; use anyhow::Result;
use chrono::Local;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use clash_verge_task::scheduled_task::{self, Mailbox, Next, ScheduledTask};
use std::{ use std::{
path::PathBuf, path::PathBuf,
sync::{ sync::{Arc, LazyLock},
OnceLock,
atomic::{AtomicBool, AtomicI64, Ordering},
},
time::{Duration, UNIX_EPOCH}, time::{Duration, UNIX_EPOCH},
}; };
use tokio::{ use tokio::{fs, time::Instant};
fs,
sync::{Mutex, watch},
};
const DEFAULT_INTERVAL_HOURS: u64 = 24; const DEFAULT_INTERVAL_HOURS: u64 = 24;
const MIN_INTERVAL_HOURS: u64 = 1; const MIN_INTERVAL_HOURS: u64 = 1;
const MAX_INTERVAL_HOURS: u64 = 168; const MAX_INTERVAL_HOURS: u64 = 168;
const MIN_BACKUP_INTERVAL_SECS: i64 = 60; const MIN_BACKUP_INTERVAL: Duration = Duration::from_secs(60);
const AUTO_BACKUP_KEEP: usize = 20; const AUTO_BACKUP_KEEP: usize = 20;
const AUTO_MARKER: &str = "-auto-"; const AUTO_MARKER: &str = "-auto-";
@@ -42,13 +36,9 @@ impl AutoBackupTrigger {
Self::GlobalScript => "script", Self::GlobalScript => "script",
} }
} }
const fn is_schedule(self) -> bool {
matches!(self, Self::Scheduled)
}
} }
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct AutoBackupSettings { struct AutoBackupSettings {
schedule_enabled: bool, schedule_enabled: bool,
interval_hours: u64, interval_hours: u64,
@@ -56,6 +46,11 @@ struct AutoBackupSettings {
} }
impl AutoBackupSettings { impl AutoBackupSettings {
fn interval(self) -> Option<Duration> {
self.schedule_enabled
.then(|| Duration::from_secs(self.interval_hours * 3600))
}
fn from_verge(verge: &IVerge) -> Self { fn from_verge(verge: &IVerge) -> Self {
let interval = verge let interval = verge
.auto_backup_interval_hours .auto_backup_interval_hours
@@ -80,155 +75,139 @@ impl Default for AutoBackupSettings {
} }
} }
pub struct AutoBackupManager { #[derive(Default)]
settings_tx: watch::Sender<AutoBackupSettings>, struct BackupInput {
// The watch channel is the single settings store; no duplicate copies. settings: Option<AutoBackupSettings>,
settings_rx: watch::Receiver<AutoBackupSettings>, restart_schedule: bool,
runner_started: AtomicBool, clear_pending_edit: bool,
exec_lock: Mutex<()>, edit_before_settings: Option<AutoBackupTrigger>,
last_backup: AtomicI64, edit: Option<AutoBackupTrigger>,
} }
impl AutoBackupManager { impl BackupInput {
pub fn global() -> &'static Self { fn update_settings(&mut self, settings: AutoBackupSettings) -> bool {
static INSTANCE: OnceLock<AutoBackupManager> = OnceLock::new(); if self.settings == Some(settings) {
INSTANCE.get_or_init(|| { return false;
let (settings_tx, settings_rx) = watch::channel(AutoBackupSettings::default()); }
Self { // A pending off/on or interval round trip still restarts the countdown.
settings_tx, self.restart_schedule |= self
settings_rx, .settings
runner_started: AtomicBool::new(false), .is_some_and(|previous| previous.interval() != settings.interval());
exec_lock: Mutex::new(()), self.settings = Some(settings);
last_backup: AtomicI64::new(0), if !settings.change_enabled {
self.clear_pending_edit = true;
self.edit = None;
self.edit_before_settings = None;
}
true
}
const fn request_edit(&mut self, trigger: AutoBackupTrigger) -> bool {
let pending = match self.settings {
Some(settings) if settings.change_enabled => &mut self.edit,
Some(_) => return false,
None => &mut self.edit_before_settings,
};
if pending.is_some() {
return false;
}
*pending = Some(trigger);
true
}
}
static BACKUP_REQUESTS: LazyLock<Arc<Mailbox<BackupInput>>> =
LazyLock::new(|| AsyncHandler::start_driver(scheduled_task::new(BackupSchedule::default(), execute_backup)));
pub(crate) async fn init() {
let _write = Config::lock_config_write().await;
publish_settings(&Config::verge().await.data_arc());
}
pub(crate) fn publish_settings(verge: &IVerge) {
let settings = AutoBackupSettings::from_verge(verge);
BACKUP_REQUESTS.update(|pending| pending.update_settings(settings));
}
pub(crate) fn trigger_backup(trigger: AutoBackupTrigger) {
BACKUP_REQUESTS.update(|pending| pending.request_edit(trigger));
}
#[derive(Default)]
struct BackupSchedule {
settings: AutoBackupSettings,
due: Option<Instant>,
edit: Option<AutoBackupTrigger>,
last_backup: Option<Instant>,
}
impl ScheduledTask for BackupSchedule {
type Input = BackupInput;
type Work = AutoBackupTrigger;
type Output = Result<Instant>;
fn on_input(&mut self, input: BackupInput, now: Instant) {
if input.clear_pending_edit {
self.edit = None;
}
let previous_edit = if self.settings.change_enabled {
input.edit_before_settings
} else {
None
};
if let Some(settings) = input.settings {
if input.restart_schedule || self.settings.interval() != settings.interval() {
self.due = settings.interval().map(|interval| now + interval);
} }
}) self.settings = settings;
}
if self.settings.change_enabled {
self.edit = self.edit.or(previous_edit).or(input.edit);
} else {
self.edit = None;
}
} }
pub async fn init(&self) -> Result<()> { fn next(&mut self, now: Instant) -> Next<AutoBackupTrigger> {
let settings = Self::load_settings().await; let throttled = self.last_backup.is_some_and(|last| now - last < MIN_BACKUP_INTERVAL);
let _ = self.settings_tx.send_replace(settings); if self.due.is_some_and(|due| due <= now) {
self.maybe_start_runner(settings); self.due = None;
Ok(()) if !throttled {
} return Next::Run(AutoBackupTrigger::Scheduled);
pub async fn refresh_settings(&self) -> Result<()> {
let settings = Self::load_settings().await;
let _ = self.settings_tx.send_replace(settings);
self.maybe_start_runner(settings);
Ok(())
}
pub fn trigger_backup(trigger: AutoBackupTrigger) {
AsyncHandler::spawn(move || async move {
if let Err(err) = Self::global().execute_trigger(trigger).await {
logging!(
warn,
Type::Backup,
"Auto backup execution failed ({:?}): {err:#?}",
trigger
);
} }
}); self.due = self.settings.interval().map(|interval| now + interval);
}
if let Some(edit) = self.edit.take()
&& !throttled
{
return Next::Run(edit);
}
self.due.map_or(Next::Idle, Next::At)
} }
fn maybe_start_runner(&self, settings: AutoBackupSettings) { fn finished(&mut self, trigger: AutoBackupTrigger, result: std::thread::Result<Self::Output>, now: Instant) {
if settings.schedule_enabled { if trigger == AutoBackupTrigger::Scheduled {
self.ensure_runner(); self.due = self.settings.interval().map(|interval| now + interval);
}
match result {
Ok(Ok(created_at)) => self.last_backup = Some(created_at),
Ok(Err(err)) => logging!(warn, Type::Backup, "Auto backup failed ({trigger:?}): {err:#}"),
Err(_) => logging!(error, Type::Backup, "Auto backup panicked ({trigger:?})"),
} }
} }
}
fn ensure_runner(&self) { async fn execute_backup(trigger: AutoBackupTrigger) -> Result<Instant> {
if self.runner_started.swap(true, Ordering::SeqCst) { let file_name = create_local_backup_with_namer(|name| append_auto_suffix(name, trigger.slug()).into()).await?;
return; let created_at = Instant::now();
}
let mut rx = self.settings_tx.subscribe(); if let Err(err) = cleanup_auto_backups().await {
AsyncHandler::spawn(move || async move { logging!(warn, Type::Backup, "Failed to cleanup old auto backups: {err:#?}");
Self::run_scheduler(&mut rx).await;
});
} }
async fn run_scheduler(rx: &mut watch::Receiver<AutoBackupSettings>) { logging!(info, Type::Backup, "Auto backup created ({trigger:?}): {file_name}");
let mut current = *rx.borrow(); Ok(created_at)
loop {
if !current.schedule_enabled {
if rx.changed().await.is_err() {
break;
}
current = *rx.borrow();
continue;
}
let duration = Duration::from_secs(current.interval_hours.saturating_mul(3600));
let sleeper = tokio::time::sleep(duration);
tokio::pin!(sleeper);
tokio::select! {
_ = &mut sleeper => {
if let Err(err) = Self::global()
.execute_trigger(AutoBackupTrigger::Scheduled)
.await
{
logging!(
warn,
Type::Backup,
"Scheduled auto backup failed: {err:#?}"
);
}
}
changed = rx.changed() => {
if changed.is_err() {
break;
}
current = *rx.borrow();
}
}
}
}
async fn execute_trigger(&self, trigger: AutoBackupTrigger) -> Result<()> {
let snapshot = *self.settings_rx.borrow();
if trigger.is_schedule() && !snapshot.schedule_enabled {
return Ok(());
}
if !trigger.is_schedule() && !snapshot.change_enabled {
return Ok(());
}
if !self.should_run_now() {
return Ok(());
}
let _guard = self.exec_lock.lock().await;
if !self.should_run_now() {
return Ok(());
}
let file_name = create_local_backup_with_namer(|name| append_auto_suffix(name, trigger.slug()).into()).await?;
self.last_backup.store(Local::now().timestamp(), Ordering::Release);
if let Err(err) = cleanup_auto_backups().await {
logging!(warn, Type::Backup, "Failed to cleanup old auto backups: {err:#?}");
}
logging!(info, Type::Backup, "Auto backup created ({:?}): {}", trigger, file_name);
Ok(())
}
fn should_run_now(&self) -> bool {
let last = self.last_backup.load(Ordering::Acquire);
if last == 0 {
return true;
}
let now = Local::now().timestamp();
now.saturating_sub(last) >= MIN_BACKUP_INTERVAL_SECS
}
async fn load_settings() -> AutoBackupSettings {
let verge = Config::verge().await;
AutoBackupSettings::from_verge(&verge.latest_arc())
}
} }
fn append_auto_suffix(file_name: &str, slug: &str) -> String { fn append_auto_suffix(file_name: &str, slug: &str) -> String {
+105 -104
View File
@@ -5,14 +5,16 @@ use crate::{
}; };
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use clash_verge_task::countdown::{self, Countdown};
use crate::utils::window_manager::WindowManager; use crate::utils::window_manager::WindowManager;
use anyhow::Result; use anyhow::Result;
use parking_lot::Mutex; use parking_lot::Mutex;
use std::sync::atomic::{AtomicU8, AtomicU32, Ordering}; use std::future::Future;
use std::sync::LazyLock;
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
use std::time::Duration;
use tauri::Listener as _; use tauri::Listener as _;
use tokio::sync::oneshot;
use tokio::time::{Duration, sleep};
#[repr(u8)] #[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -41,27 +43,24 @@ impl LightweightState {
static LIGHTWEIGHT_STATE: AtomicU8 = AtomicU8::new(LightweightState::Normal as u8); static LIGHTWEIGHT_STATE: AtomicU8 = AtomicU8::new(LightweightState::Normal as u8);
struct WindowListener { struct WindowListener {
handler_id: AtomicU32, handler_id: Option<tauri::EventId>,
event: &'static str, event: &'static str,
label: &'static str, label: &'static str,
} }
impl WindowListener { impl WindowListener {
fn setup(&self, on_event: impl Fn() + Send + 'static) { fn setup(&mut self, on_event: impl Fn() + Send + 'static) {
if let Some(window) = WindowManager::get_main_window() { if let Some(window) = WindowManager::get_main_window() {
let previous_handler_id = self.handler_id.swap(0, Ordering::AcqRel); if let Some(id) = self.handler_id.take() {
if previous_handler_id != 0 { window.unlisten(id);
window.unlisten(previous_handler_id);
logging!(debug, Type::Lightweight, "覆盖旧的{}监听", self.label); logging!(debug, Type::Lightweight, "覆盖旧的{}监听", self.label);
} }
let handler_id = window.listen(self.event, move |_event| on_event()); self.handler_id = Some(window.listen(self.event, move |_event| on_event()));
self.handler_id.store(handler_id, Ordering::Release);
} }
} }
fn cancel(&self) { fn cancel(&mut self) {
let id = self.handler_id.swap(0, Ordering::AcqRel); if let Some(id) = self.handler_id.take() {
if id != 0 {
if let Some(window) = WindowManager::get_main_window() { if let Some(window) = WindowManager::get_main_window() {
window.unlisten(id); window.unlisten(id);
} }
@@ -70,19 +69,28 @@ impl WindowListener {
} }
} }
static WINDOW_CLOSE_LISTENER: WindowListener = WindowListener { struct WindowListeners {
handler_id: AtomicU32::new(0), close: WindowListener,
event: "tauri://close-requested", focus: WindowListener,
label: "窗口关闭", }
};
static WEBVIEW_FOCUS_LISTENER: WindowListener = WindowListener { static WINDOW_LISTENERS: Mutex<WindowListeners> = Mutex::new(WindowListeners {
handler_id: AtomicU32::new(0), close: WindowListener {
event: "tauri://focus", handler_id: None,
label: "窗口焦点", event: "tauri://close-requested",
}; label: "窗口关闭",
},
focus: WindowListener {
handler_id: None,
event: "tauri://focus",
label: "窗口焦点",
},
});
static CANCEL_TX: Mutex<Option<oneshot::Sender<()>>> = Mutex::new(None); static TIMER_GENERATION: AtomicU64 = AtomicU64::new(0);
static COUNTDOWN: LazyLock<Countdown<u64>> =
LazyLock::new(|| AsyncHandler::start_driver(countdown::new(prepare_countdown, enter_lightweight_on_timeout)));
#[inline] #[inline]
fn get_state() -> LightweightState { fn get_state() -> LightweightState {
@@ -118,11 +126,12 @@ async fn refresh_lightweight_tray_state() {
} }
pub async fn auto_lightweight_boot() -> Result<()> { pub async fn auto_lightweight_boot() -> Result<()> {
let generation = TIMER_GENERATION.load(Ordering::Acquire);
let verge_config = Config::verge().await; let verge_config = Config::verge().await;
let is_enable_auto = verge_config.data_arc().enable_auto_light_weight_mode.unwrap_or(false); let is_enable_auto = verge_config.data_arc().enable_auto_light_weight_mode.unwrap_or(false);
let is_silent_start = verge_config.data_arc().enable_silent_start.unwrap_or(false); let is_silent_start = verge_config.data_arc().enable_silent_start.unwrap_or(false);
if is_enable_auto { if is_enable_auto && verge_config.latest_arc().enable_auto_light_weight_mode.unwrap_or(false) {
enable_auto_light_weight_mode().await; enable_auto_light_weight_mode_at(generation).await;
} }
if is_silent_start { if is_silent_start {
entry_lightweight_mode().await; entry_lightweight_mode().await;
@@ -131,32 +140,43 @@ pub async fn auto_lightweight_boot() -> Result<()> {
} }
pub async fn enable_auto_light_weight_mode() { pub async fn enable_auto_light_weight_mode() {
enable_auto_light_weight_mode_at(TIMER_GENERATION.load(Ordering::Acquire)).await;
}
async fn enable_auto_light_weight_mode_at(generation: u64) {
if let Err(e) = Timer::global().init().await { if let Err(e) = Timer::global().init().await {
logging!(error, Type::Lightweight, "Failed to initialize timer: {e}"); logging!(error, Type::Lightweight, "Failed to initialize timer: {e}");
return; return;
} }
logging!(info, Type::Lightweight, "开启自动轻量模式"); logging!(info, Type::Lightweight, "开启自动轻量模式");
setup_window_close_listener(); setup_auto_light_weight_listeners(generation);
setup_webview_focus_listener();
} }
pub fn disable_auto_light_weight_mode() { pub fn disable_auto_light_weight_mode() {
logging!(info, Type::Lightweight, "关闭自动轻量模式"); logging!(info, Type::Lightweight, "关闭自动轻量模式");
cancel_light_weight_timer(); TIMER_GENERATION.fetch_add(1, Ordering::AcqRel);
cancel_window_close_listener(); COUNTDOWN.disarm();
cancel_webview_focus_listener(); let mut listeners = WINDOW_LISTENERS.lock();
listeners.close.cancel();
listeners.focus.cancel();
} }
pub async fn entry_lightweight_mode() -> bool { pub async fn entry_lightweight_mode() -> bool {
let entered = begin_lightweight_mode();
if entered {
COUNTDOWN.disarm();
}
refresh_lightweight_tray_state().await;
entered
}
fn begin_lightweight_mode() -> bool {
if !try_transition(LightweightState::Normal, LightweightState::In) { if !try_transition(LightweightState::Normal, LightweightState::In) {
logging!(debug, Type::Lightweight, "无需进入轻量模式,跳过调用"); logging!(debug, Type::Lightweight, "无需进入轻量模式,跳过调用");
refresh_lightweight_tray_state().await;
return false; return false;
} }
record_state_and_log(LightweightState::In); record_state_and_log(LightweightState::In);
WindowManager::destroy_main_window(); WindowManager::destroy_main_window();
cancel_light_weight_timer();
refresh_lightweight_tray_state().await;
true true
} }
@@ -172,16 +192,11 @@ pub async fn exit_lightweight_mode() -> bool {
} }
record_state_and_log(LightweightState::Exiting); record_state_and_log(LightweightState::Exiting);
WindowManager::show_main_window().await; WindowManager::show_main_window().await;
let enable_auto_light_weight_mode = Config::verge() let generation = TIMER_GENERATION.load(Ordering::Acquire);
.await if auto_light_weight_is_enabled().await {
.data_arc() setup_auto_light_weight_listeners(generation);
.enable_auto_light_weight_mode
.unwrap_or(false);
if enable_auto_light_weight_mode {
setup_window_close_listener();
setup_webview_focus_listener();
} }
cancel_light_weight_timer(); COUNTDOWN.disarm();
record_state_and_log(LightweightState::Normal); record_state_and_log(LightweightState::Normal);
refresh_lightweight_tray_state().await; refresh_lightweight_tray_state().await;
true true
@@ -189,78 +204,64 @@ pub async fn exit_lightweight_mode() -> bool {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
pub async fn add_light_weight_timer() { pub async fn add_light_weight_timer() {
setup_light_weight_timer().await; let generation = TIMER_GENERATION.load(Ordering::Acquire);
if auto_light_weight_is_enabled().await {
COUNTDOWN.arm(generation);
}
} }
fn setup_window_close_listener() { async fn auto_light_weight_is_enabled() -> bool {
WINDOW_CLOSE_LISTENER.setup(|| { let verge = Config::verge().await;
std::mem::drop(AsyncHandler::spawn(|| async { // A disable applies before persistence. A rollback restores eligibility for future hides.
setup_light_weight_timer().await; verge.data_arc().enable_auto_light_weight_mode.unwrap_or(false)
})); && verge.latest_arc().enable_auto_light_weight_mode.unwrap_or(false)
logging!(info, Type::Lightweight, "监听到关闭请求,开始轻量模式计时");
});
} }
fn cancel_window_close_listener() { fn setup_auto_light_weight_listeners(generation: u64) {
WINDOW_CLOSE_LISTENER.cancel(); let mut listeners = WINDOW_LISTENERS.lock();
} if generation != TIMER_GENERATION.load(Ordering::Acquire) {
fn setup_webview_focus_listener() {
WEBVIEW_FOCUS_LISTENER.setup(|| {
cancel_light_weight_timer();
logging!(debug, Type::Lightweight, "监听到窗口获得焦点,取消轻量模式计时");
});
}
fn cancel_webview_focus_listener() {
WEBVIEW_FOCUS_LISTENER.cancel();
}
async fn setup_light_weight_timer() {
let once_by_minutes = Config::verge().await.data_arc().auto_light_weight_minutes.unwrap_or(10);
let mut cancel_tx_guard = CANCEL_TX.lock();
if cancel_tx_guard.is_some() {
logging!(
debug,
Type::Timer,
"Lightweight mode timer already exists, skipping setup"
);
return; return;
} }
listeners.close.setup(move || {
let (tx, rx) = oneshot::channel::<()>(); COUNTDOWN.arm(generation);
*cancel_tx_guard = Some(tx); logging!(info, Type::Lightweight, "监听到关闭请求,开始轻量模式计时");
drop(cancel_tx_guard); });
listeners.focus.setup(move || {
AsyncHandler::spawn(move || async move { if generation == TIMER_GENERATION.load(Ordering::Acquire) {
tokio::select! { COUNTDOWN.disarm();
_ = sleep(Duration::from_secs(once_by_minutes.saturating_mul(60))) => { logging!(debug, Type::Lightweight, "监听到窗口获得焦点,取消轻量模式计时");
logging!(info, Type::Timer, "Lightweight mode timer expired, entering lightweight mode");
{
let mut guard = CANCEL_TX.lock();
*guard = None;
}
entry_lightweight_mode().await;
}
_ = rx => {
logging!(debug, Type::Timer, "Received cancel signal, stopping lightweight mode timer");
}
} }
}); });
}
fn prepare_countdown(generation: u64) -> Option<impl Future<Output = Duration>> {
// Unlisten can be deferred while Tauri is delivering an event.
if generation != TIMER_GENERATION.load(Ordering::Acquire) {
return None;
}
Some(async {
let minutes = Config::verge().await.data_arc().auto_light_weight_minutes.unwrap_or(10);
logging!(
info,
Type::Timer,
"Lightweight mode timer set, entering lightweight mode in {} minutes",
minutes
);
Duration::from_secs(minutes.saturating_mul(60))
})
}
fn enter_lightweight_on_timeout(generation: u64) {
if generation != TIMER_GENERATION.load(Ordering::Acquire) {
return;
}
logging!( logging!(
info, info,
Type::Timer, Type::Timer,
"Lightweight mode timer set, entering lightweight mode in {} minutes", "Lightweight mode timer expired, entering lightweight mode"
once_by_minutes
); );
} begin_lightweight_mode();
AsyncHandler::spawn(refresh_lightweight_tray_state);
fn cancel_light_weight_timer() {
let mut cancel_tx_guard = CANCEL_TX.lock();
if let Some(tx) = cancel_tx_guard.take() {
let _ = tx.send(());
logging!(debug, Type::Timer, "Timer cancelled");
}
} }
-173
View File
@@ -326,13 +326,6 @@ where
start_sidecar().await start_sidecar().await
} }
#[cfg(target_os = "windows")]
enum HandoffOutcome {
NotReady,
Done,
Failed,
}
fn report_sidecar_failure(error: anyhow::Error, service_rejection: Option<&str>) -> anyhow::Error { fn report_sidecar_failure(error: anyhow::Error, service_rejection: Option<&str>) -> anyhow::Error {
let error = match service_rejection { let error = match service_rejection {
Some(reason) => error.context(format!("Service core rejected: {reason}; Sidecar fallback failed")), Some(reason) => error.context(format!("Service core rejected: {reason}; Sidecar fallback failed")),
@@ -688,11 +681,6 @@ impl CoreManager {
return result; return result;
} }
#[cfg(target_os = "windows")]
if matches!(*self.get_running_mode(), RunningMode::Sidecar) {
self.spawn_service_handoff_watcher().await;
}
result result
} }
@@ -883,167 +871,6 @@ impl CoreManager {
let wait = crate::core::runstate::RUN_STATE.await_ready(attempts, timing::SERVICE_WAIT_INTERVAL); let wait = crate::core::runstate::RUN_STATE.await_ready(attempts, timing::SERVICE_WAIT_INTERVAL);
let _ = tokio::time::timeout(timing::SERVICE_WAIT_MAX, wait).await; let _ = tokio::time::timeout(timing::SERVICE_WAIT_MAX, wait).await;
} }
#[cfg(target_os = "windows")]
async fn spawn_service_handoff_watcher(&self) {
use crate::constants::timing;
use crate::process::AsyncHandler;
use std::sync::atomic::Ordering;
use std::time::Instant;
// An accepted Sidecar is the user's decision for this session, not a wait for the Service.
let needs_service = Config::verge().await.latest_arc().enable_tun_mode.unwrap_or(false)
&& !crate::core::runstate::RUN_STATE.state().sidecar_allowed;
if !needs_service {
return;
}
if self.handoff_watcher_running.swap(true, Ordering::AcqRel) {
return;
}
logging!(
info,
Type::Core,
"service not ready at startup; sidecar active, watching for handoff"
);
AsyncHandler::spawn(|| async move {
let manager = Self::global();
let started = Instant::now();
use crate::utils::retry::{RetryError, RetryPolicy, retry};
let attempts = std::num::NonZeroUsize::MIN.saturating_add(
(timing::SERVICE_HANDOFF_WINDOW.as_millis() / timing::SERVICE_HANDOFF_INTERVAL.as_millis()) as usize,
);
let _ = retry(RetryPolicy::fixed(attempts, std::time::Duration::ZERO), |_| async {
if started.elapsed() >= timing::SERVICE_HANDOFF_WINDOW {
logging!(
info,
Type::Core,
"service handoff window elapsed; staying in sidecar mode"
);
return Ok(());
}
// The window is checked before waiting, including the final handoff attempt.
tokio::time::sleep(timing::SERVICE_HANDOFF_INTERVAL).await;
if !matches!(*manager.get_running_mode(), RunningMode::Sidecar) {
return Ok(());
}
match manager.try_handoff_sidecar_to_service().await {
HandoffOutcome::Done => Ok(()),
HandoffOutcome::Failed => {
logging!(warn, Type::Core, "handoff attempt failed; staying in sidecar mode");
Ok(())
}
HandoffOutcome::NotReady => Err(RetryError::Retry(())),
}
})
.await;
manager.handoff_watcher_running.store(false, Ordering::Release);
});
}
#[cfg(target_os = "windows")]
async fn refresh_service_readiness_for_handoff() -> bool {
if SERVICE_MANAGER.confirm_ready().await.is_err() {
return false;
}
crate::core::runstate::RUN_STATE.state().service_usable()
}
#[cfg(target_os = "windows")]
#[tracing::instrument(skip_all, level = "debug", fields(outcome = tracing::field::Empty))]
async fn try_handoff_sidecar_to_service(&self) -> HandoffOutcome {
// Before probing: a probe reply records an observation, which clears sidecar_allowed.
if crate::core::runstate::RUN_STATE.state().sidecar_allowed {
return HandoffOutcome::Done;
}
if !Self::refresh_service_readiness_for_handoff().await {
return HandoffOutcome::NotReady;
}
if !self.try_start_config_update() {
return HandoffOutcome::NotReady;
}
let _config_update = DropGuard::new((), |()| {
self.finish_config_update();
});
// Lock order is config then lifecycle.
let _life = self.lifecycle_lock.lock().await;
if !matches!(*self.get_running_mode(), RunningMode::Sidecar)
|| !Config::verge().await.latest_arc().enable_tun_mode.unwrap_or(false)
|| crate::core::runstate::RUN_STATE.state().sidecar_allowed
{
return HandoffOutcome::Done;
}
logging!(
info,
Type::Core,
"service became ready; handing off from sidecar to service"
);
if let Err(error) = self.stop_sidecar_after_proxy_clear().await {
logging!(
error,
Type::Core,
"failed to clear proxy before sidecar handoff: {error:#}"
);
return HandoffOutcome::Failed;
}
let service_result = run_ready_core_start_transition(
|| self.start_core_by_service(),
|| {
matches!(*self.get_running_mode(), RunningMode::Service)
&& self.current_core_readiness_generation().is_some()
},
|| self.apply_proxy_after_start(),
)
.await;
let Err(service_error) = service_result else {
logging!(info, Type::Core, "handoff to service mode succeeded");
return HandoffOutcome::Done;
};
logging!(error, Type::Core, "handoff to service failed: {service_error:#}");
if let Err(cleanup_error) = self.controlled_stop_core_inner().await {
logging!(
error,
Type::Core,
"failed to stop service before sidecar fallback: {cleanup_error:#}"
);
return HandoffOutcome::Failed;
}
let sidecar_result = run_ready_core_start_transition(
|| self.start_core_by_sidecar(),
|| {
matches!(*self.get_running_mode(), RunningMode::Sidecar)
&& self.current_core_readiness_generation().is_some()
},
|| self.apply_proxy_after_start(),
)
.await;
if let Err(sidecar_error) = sidecar_result {
logging!(error, Type::Core, "sidecar fallback failed: {sidecar_error:#}");
if let Err(cleanup_error) = self.rollback_failed_sidecar_transition().await {
logging!(
error,
Type::Core,
"failed to clear proxy before sidecar rollback: {cleanup_error:#}"
);
}
} else {
logging!(
info,
Type::Core,
"sidecar fallback became ready and restored proxy state"
);
}
HandoffOutcome::Failed
}
} }
#[cfg(test)] #[cfg(test)]
+6 -59
View File
@@ -4,8 +4,8 @@ mod lifecycle;
mod state; mod state;
use anyhow::Result; use anyhow::Result;
use arc_swap::{ArcSwap, ArcSwapOption}; use arc_swap::ArcSwapOption;
use clash_verge_logging::{LogRing, Type, logging, logging_error}; use clash_verge_logging::{LogRing, Type, logging};
use std::{ use std::{
fmt, fmt,
sync::{ sync::{
@@ -14,12 +14,9 @@ use std::{
}, },
time::Instant, time::Instant,
}; };
use tauri_plugin_shell::process::CommandChild;
use crate::core::runstate::{RUN_STATE, RealEnv, RunStateStore}; use crate::core::runstate::{RUN_STATE, RealEnv, RunStateStore};
use crate::singleton; use crate::singleton;
#[cfg(target_os = "windows")]
use std::os::windows::io::OwnedHandle;
pub(crate) static CLASH_LOGGER: LazyLock<Arc<LogRing>> = LazyLock::new(|| Arc::new(LogRing::new())); pub(crate) static CLASH_LOGGER: LazyLock<Arc<LogRing>> = LazyLock::new(|| Arc::new(LogRing::new()));
@@ -89,46 +86,26 @@ pub struct CoreManager {
/// A reference rather than the global directly, so a test can supervise a Core without /// A reference rather than the global directly, so a test can supervise a Core without
/// racing every other test for one process-wide Running Mode. /// racing every other test for one process-wide Running Mode.
run_state: &'static RunStateStore<RealEnv>, run_state: &'static RunStateStore<RealEnv>,
state: ArcSwap<State>, sidecar: parking_lot::Mutex<state::SidecarSession>,
last_update: ArcSwapOption<Instant>, last_update: ArcSwapOption<Instant>,
#[cfg(target_os = "windows")]
job_handle: ArcSwapOption<OwnedHandle>,
config_update_in_progress: AtomicBool, config_update_in_progress: AtomicBool,
core_readiness_state: AtomicU64, core_readiness_state: AtomicU64,
startup_error: parking_lot::Mutex<Option<CoreFailure>>, startup_error: parking_lot::Mutex<Option<CoreFailure>>,
sidecar_exit: tokio::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,
// 串行化 start/stop/restart 和 sidecar→service 交接。 // 串行化 start/stop/restart 和 sidecar→service 交接。
// 锁序固定为 config_update_in_progress → lifecycle_lock。 // 锁序固定为 config_update_in_progress → lifecycle_lock。
pub(crate) lifecycle_lock: tokio::sync::Mutex<()>, pub(crate) lifecycle_lock: tokio::sync::Mutex<()>,
// sidecar→service 交接 watcher 单实例标志。
#[cfg(target_os = "windows")]
handoff_watcher_running: AtomicBool,
}
/// Process-level state owned by `CoreManager`.
///
/// Running Mode deliberately does *not* live here — it belongs to `core::runstate`, which
/// keeps it consistent with Service Health and derives PAC availability from it.
#[derive(Debug, Default)]
struct State {
child_sidecar: ArcSwapOption<CommandChild>,
} }
impl Default for CoreManager { impl Default for CoreManager {
fn default() -> Self { fn default() -> Self {
Self { Self {
run_state: &RUN_STATE, run_state: &RUN_STATE,
state: ArcSwap::new(Arc::new(State::default())), sidecar: parking_lot::Mutex::default(),
last_update: ArcSwapOption::new(None), last_update: ArcSwapOption::new(None),
#[cfg(target_os = "windows")]
job_handle: ArcSwapOption::new(None),
config_update_in_progress: AtomicBool::new(false), config_update_in_progress: AtomicBool::new(false),
core_readiness_state: AtomicU64::new(0), core_readiness_state: AtomicU64::new(0),
startup_error: parking_lot::Mutex::new(None), startup_error: parking_lot::Mutex::new(None),
sidecar_exit: tokio::sync::Mutex::new(None),
lifecycle_lock: tokio::sync::Mutex::new(()), lifecycle_lock: tokio::sync::Mutex::new(()),
#[cfg(target_os = "windows")]
handoff_watcher_running: AtomicBool::new(false),
} }
} }
} }
@@ -162,18 +139,6 @@ impl CoreManager {
self.startup_error.lock().clone() self.startup_error.lock().clone()
} }
pub fn take_child_sidecar(&self) -> Option<CommandChild> {
self.state
.load()
.child_sidecar
.swap(None)
.and_then(|arc| Arc::try_unwrap(arc).ok())
}
pub fn get_running_sidecar_pid(&self) -> Option<u32> {
self.state.load().child_sidecar.load_full().map(|child| child.pid())
}
pub fn get_last_update(&self) -> Option<Arc<Instant>> { pub fn get_last_update(&self) -> Option<Arc<Instant>> {
self.last_update.load_full() self.last_update.load_full()
} }
@@ -218,11 +183,6 @@ impl CoreManager {
self.run_state.core_start_settled(); self.run_state.core_start_settled();
} }
pub fn set_running_child_sidecar(&self, child: CommandChild) {
let state = self.state.load();
state.child_sidecar.store(Some(Arc::new(child)));
}
fn mark_core_ready(&self) -> u64 { fn mark_core_ready(&self) -> u64 {
let mut current = self.core_readiness_state.load(Ordering::Acquire); let mut current = self.core_readiness_state.load(Ordering::Acquire);
loop { loop {
@@ -257,27 +217,14 @@ impl CoreManager {
self.last_update.store(Some(Arc::new(time))); self.last_update.store(Some(Arc::new(time)));
} }
/// Replaces the Windows Job Object handle owned by the core manager
///
/// Passing `None` drops the current handle, which closes the Job Object
/// and terminates its assigned processes due to `KILL_ON_JOB_CLOSE`.
///
/// This method is currently only used on Windows.
#[cfg(target_os = "windows")]
fn set_job_handle(&self, handle: Option<OwnedHandle>) {
self.job_handle.store(handle.map(Arc::new));
}
pub(crate) fn try_start_config_update(&self) -> bool { pub(crate) fn try_start_config_update(&self) -> bool {
!self.config_update_in_progress.swap(true, Ordering::AcqRel) !self.config_update_in_progress.swap(true, Ordering::AcqRel)
} }
pub(crate) fn finish_config_update(&self) { pub(crate) fn finish_config_update(&self) {
self.config_update_in_progress.store(false, Ordering::Release); self.config_update_in_progress.store(false, Ordering::Release);
// Spawned because the caller may still hold the config write lock this waits for. // The caller may still hold the config write lock that synchronization needs.
crate::process::AsyncHandler::spawn(|| async { crate::config::Config::request_dns_override_sync();
logging_error!(Type::Config, crate::config::Config::sync_dns_override().await);
});
} }
#[tracing::instrument(skip_all, level = "info", fields(retries = 0))] #[tracing::instrument(skip_all, level = "info", fields(retries = 0))]
+64 -30
View File
@@ -11,11 +11,18 @@ use crate::{
}; };
use anyhow::{Context as _, Result}; use anyhow::{Context as _, Result};
use clash_verge_logging::Type; use clash_verge_logging::Type;
use futures::{
FutureExt as _,
future::{Map, Shared},
};
use log::Level; use log::Level;
use std::num::NonZeroUsize; use std::num::NonZeroUsize;
use std::path::Path; use std::path::Path;
use std::sync::Arc;
use tauri_plugin_mihomo::MihomoExt as _; use tauri_plugin_mihomo::MihomoExt as _;
use tauri_plugin_shell::ShellExt as _; use tauri_plugin_shell::ShellExt as _;
use tauri_plugin_shell::process::CommandChild;
use tokio::task::{JoinError, JoinHandle};
pub(super) fn explain_core_occupancy(error: anyhow::Error) -> anyhow::Error { pub(super) fn explain_core_occupancy(error: anyhow::Error) -> anyhow::Error {
let detail = error.to_string(); let detail = error.to_string();
@@ -130,8 +137,34 @@ where
.context("Mihomo API did not become ready") .context("Mihomo API did not become ready")
} }
fn should_clear_terminated_sidecar(running_mode: &RunningMode, current_pid: Option<u32>, terminated_pid: u32) -> bool { fn should_clear_terminated_sidecar(
matches!(running_mode, RunningMode::Sidecar) && current_pid == Some(terminated_pid) running_mode: &RunningMode,
current_generation: Option<u64>,
terminated_generation: u64,
) -> bool {
matches!(running_mode, RunningMode::Sidecar) && current_generation == Some(terminated_generation)
}
type ShareExitResult = fn(Result<(), JoinError>) -> Result<(), Arc<JoinError>>;
type SidecarExit = Shared<Map<JoinHandle<()>, ShareExitResult>>;
fn share_exit(exit: JoinHandle<()>) -> SidecarExit {
let share_error: ShareExitResult = |result| result.map_err(Arc::new);
exit.map(share_error).shared()
}
#[derive(Debug, Default)]
pub(super) struct SidecarSession {
process: Option<SidecarProcess>,
exit: Option<SidecarExit>,
}
#[derive(Debug)]
struct SidecarProcess {
generation: u64,
child: CommandChild,
#[cfg(target_os = "windows")]
job: OwnedHandle,
} }
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
@@ -218,7 +251,8 @@ impl CoreManager {
) )
})?; })?;
let (terminated, termination) = tokio::sync::oneshot::channel(); let (terminated, termination) = tokio::sync::oneshot::channel();
*self.sidecar_exit.lock().await = Some(execution.release_after_exit(child.pid(), termination)); let exit = execution.release_after_exit(child.pid(), termination);
self.sidecar.lock().exit = Some(share_exit(exit));
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
let job = { let job = {
match create_and_assign_sidecar_job(child.pid()) { match create_and_assign_sidecar_job(child.pid()) {
@@ -274,7 +308,7 @@ impl CoreManager {
}; };
Logger::global().writer_sidecar_log(Level::Info, &message); Logger::global().writer_sidecar_log(Level::Info, &message);
CLASH_LOGGER.clear_logs(); CLASH_LOGGER.clear_logs();
manager.clear_terminated_sidecar(pid).await; manager.clear_terminated_sidecar(core_readiness_generation).await;
break; break;
} }
_ => {} _ => {}
@@ -302,9 +336,12 @@ impl CoreManager {
}; };
} }
#[cfg(target_os = "windows")] self.sidecar.lock().process = Some(SidecarProcess {
self.set_job_handle(Some(job)); generation: core_readiness_generation,
self.set_running_child_sidecar(child); child,
#[cfg(target_os = "windows")]
job,
});
self.core_started(RunningMode::Sidecar); self.core_started(RunningMode::Sidecar);
self.restore_selected_nodes().await; self.restore_selected_nodes().await;
@@ -314,18 +351,13 @@ impl CoreManager {
/// Terminates the sidecar after its caller has successfully cleared the /// Terminates the sidecar after its caller has successfully cleared the
/// system proxy. /// system proxy.
pub(super) async fn stop_core_by_sidecar_unprepared(&self) -> Result<()> { pub(super) async fn stop_core_by_sidecar_unprepared(&self) -> Result<()> {
if let Some(child) = self.take_child_sidecar() { let process = self.sidecar.lock().process.take();
let pid = child.pid(); if let Some(process) = process {
let pid = process.child.pid();
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
{ drop(process.job);
// Setting the job handle to None clears the stored handle and
// closes the previous Windows job handle in `set_job_handle`.
self.set_job_handle(None);
let _ = pid;
}
if let Err(error) = child.kill() { if let Err(error) = process.child.kill() {
logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}"); logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}");
} }
} }
@@ -335,15 +367,15 @@ impl CoreManager {
} }
async fn wait_for_sidecar_exit(&self) -> Result<()> { async fn wait_for_sidecar_exit(&self) -> Result<()> {
let mut exit = self.sidecar_exit.lock().await; // The lifecycle lock serializes callers. Keep a receipt in the session across timeouts.
if let Some(task) = exit.as_mut() { let exit = self.sidecar.lock().exit.clone();
tokio::time::timeout(std::time::Duration::from_secs(5), task) if let Some(exit) = exit {
tokio::time::timeout(std::time::Duration::from_secs(5), exit)
.await .await
.context("Sidecar has not exited; core handoff is blocked")? .context("Sidecar has not exited; core handoff is blocked")?
.context("Sidecar exit monitoring failed")?; .context("Sidecar exit monitoring failed")?;
exit.take(); self.sidecar.lock().exit.take();
} }
drop(exit);
Ok(()) Ok(())
} }
@@ -392,15 +424,17 @@ impl CoreManager {
Ok(()) Ok(())
} }
async fn clear_terminated_sidecar(&self, terminated_pid: u32) { async fn clear_terminated_sidecar(&self, terminated_generation: u64) {
let _life = self.lifecycle_lock.lock().await; let _life = self.lifecycle_lock.lock().await;
if !should_clear_terminated_sidecar(&self.get_running_mode(), self.get_running_sidecar_pid(), terminated_pid) { let process = {
return; let mut session = self.sidecar.lock();
} let current = session.process.as_ref().map(|process| process.generation);
if !should_clear_terminated_sidecar(&self.get_running_mode(), current, terminated_generation) {
let _ = self.take_child_sidecar(); return;
#[cfg(target_os = "windows")] }
self.set_job_handle(None); session.process.take()
};
drop(process);
proxy_control::stop_guard().await; proxy_control::stop_guard().await;
self.core_stopped(); self.core_stopped();
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
+14 -2
View File
@@ -3,13 +3,25 @@
//! Proxy settings live per network service. A write that found no service wrote nothing, and a //! Proxy settings live per network service. A write that found no service wrote nothing, and a
//! switch to another service leaves the proxy on the old one; both need the write repeated. //! switch to another service leaves the proxy on the old one; both need the write repeated.
use crate::{config::Config, core::CoreManager, core::proxy_control, process::AsyncHandler}; use crate::{
config::Config,
core::{CoreManager, proxy_control},
process::AsyncHandler,
};
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use clash_verge_task::scheduled_task::{self, CoalescingJob};
use parking_lot::Mutex; use parking_lot::Mutex;
use std::sync::LazyLock;
use sysproxy::NetworkServiceMonitor; use sysproxy::NetworkServiceMonitor;
static MONITOR: Mutex<Option<NetworkServiceMonitor>> = Mutex::new(None); static MONITOR: Mutex<Option<NetworkServiceMonitor>> = Mutex::new(None);
static REAPPLY: LazyLock<CoalescingJob> = LazyLock::new(|| {
AsyncHandler::start_driver(scheduled_task::coalescing(reapply, || {
logging!(error, Type::Core, "network proxy reapply panicked");
}))
});
pub fn is_armed() -> bool { pub fn is_armed() -> bool {
MONITOR.lock().is_some() MONITOR.lock().is_some()
} }
@@ -18,7 +30,7 @@ pub fn is_armed() -> bool {
/// appearing from here on is never missed. /// appearing from here on is never missed.
pub fn start() { pub fn start() {
match NetworkServiceMonitor::start(|| { match NetworkServiceMonitor::start(|| {
AsyncHandler::spawn(reapply); REAPPLY.request();
}) { }) {
Ok(monitor) => { Ok(monitor) => {
*MONITOR.lock() = Some(monitor); *MONITOR.lock() = Some(monitor);
+110 -47
View File
@@ -18,13 +18,20 @@ use crate::{
use anyhow::{Result, ensure}; use anyhow::{Result, ensure};
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use clash_verge_service_ipc::{MacosProxyConfig, OwnerSessionProof, ProxyApplyOutcome}; use clash_verge_service_ipc::{MacosProxyConfig, OwnerSessionProof, ProxyApplyOutcome};
use clash_verge_task::watch_task;
use std::{ use std::{
borrow::Borrow, borrow::Borrow,
future::Future, future::Future,
sync::atomic::{AtomicU64, Ordering}, sync::{
Arc, LazyLock, Once,
atomic::{AtomicU64, Ordering},
},
time::Duration, time::Duration,
}; };
use tokio::{sync::Mutex, time::timeout}; use tokio::{
sync::{Mutex, watch},
time::timeout,
};
const CLEAR_ATTEMPTS: u32 = 3; const CLEAR_ATTEMPTS: u32 = 3;
const CLEAR_RETRY_DELAY: Duration = Duration::from_millis(100); const CLEAR_RETRY_DELAY: Duration = Duration::from_millis(100);
@@ -215,23 +222,40 @@ const fn refusal_classification(service_usable: Option<bool>) -> SysproxyFailure
const LOOPBACK_HOST: &str = "127.0.0.1"; const LOOPBACK_HOST: &str = "127.0.0.1";
const MAX_SERVICE_BYPASS_LEN: usize = 8192; const MAX_SERVICE_BYPASS_LEN: usize = 8192;
static SERVICE_PROXY_OPERATIONS: ServiceProxyOperations = ServiceProxyOperations::new(); static SERVICE_PROXY_OPERATIONS: LazyLock<ServiceProxyOperations> = LazyLock::new(ServiceProxyOperations::new);
struct ServiceProxyOperations { struct ServiceProxyOperations {
guard: watch::Sender<Option<Arc<ServiceGuard>>>,
guard_generation: AtomicU64, guard_generation: AtomicU64,
operation_lock: Mutex<()>, operation_lock: Mutex<()>,
} }
impl ServiceProxyOperations { impl ServiceProxyOperations {
const fn new() -> Self { fn new() -> Self {
Self { Self {
guard: watch::channel(None).0,
guard_generation: AtomicU64::new(0), guard_generation: AtomicU64::new(0),
operation_lock: Mutex::const_new(()), operation_lock: Mutex::const_new(()),
} }
} }
fn invalidate_guard(&self) -> u64 { fn invalidate_guard(&self) -> u64 {
self.guard_generation.fetch_add(1, Ordering::AcqRel).wrapping_add(1) let mut generation = 0;
self.guard.send_if_modified(|active| {
generation = self.guard_generation.fetch_add(1, Ordering::AcqRel).wrapping_add(1);
active.take().is_some()
});
generation
}
fn start_guard(&self, guard: ServiceGuard) -> bool {
self.guard.send_if_modified(|active| {
if !guard_generation_is_current(&self.guard_generation, guard.generation) {
return false;
}
*active = Some(Arc::new(guard));
true
})
} }
async fn run_service_operation<F, Fut, T>(&self, operation: F) -> T async fn run_service_operation<F, Fut, T>(&self, operation: F) -> T
@@ -606,51 +630,90 @@ pub async fn refresh_guard() -> Result<()> {
let proxy = current_service_proxy_config(&verge).await?; let proxy = current_service_proxy_config(&verge).await?;
let proof = service::active_service_session()?; let proof = service::active_service_session()?;
let interval = Duration::from_secs(verge.proxy_guard_duration.unwrap_or(30).max(1)); let interval = Duration::from_secs(verge.proxy_guard_duration.unwrap_or(30).max(1));
AsyncHandler::spawn(move || async move { static START_GUARD_MONITOR: Once = Once::new();
let mut consecutive_failures = 0u32; START_GUARD_MONITOR.call_once(|| {
loop { let receiver = SERVICE_PROXY_OPERATIONS.guard.subscribe();
tokio::time::sleep(interval).await; AsyncHandler::spawn(move || {
match SERVICE_PROXY_OPERATIONS watch_task::run(receiver, monitor_guard, |guard| {
.run_guard_request( let generation = guard.generation;
generation, logging!(
&proof, error,
&proxy, Type::Core,
|| matches!(*CoreManager::global().get_running_mode(), RunningMode::Service), "service proxy guard panicked (generation {generation})"
service::active_service_session, );
|| service::set_system_proxy_by_service_with_session(&proxy, &proof), })
) });
.await });
{ if SERVICE_PROXY_OPERATIONS.start_guard(ServiceGuard {
Ok(true) => consecutive_failures = 0, generation,
Ok(false) => { proof,
logging!(debug, Type::Core, "proxy guard superseded (generation {generation})"); proxy,
break; interval,
} }) {
Err(error) if is_missing_network_service_failure(&error) => { notification::retire_guard_failures();
consecutive_failures = 0; }
logging!(debug, Type::Core, "system proxy guard waits for a network service"); Ok(())
} }
Err(error) => {
consecutive_failures += 1; struct ServiceGuard {
logging!( generation: u64,
warn, proof: Arc<OwnerSessionProof>,
Type::Core, proxy: MacosProxyConfig,
"failed to refresh system proxy through Service (generation {generation}, {}/{}): {:#}", interval: Duration,
consecutive_failures, }
GUARD_FAILURES_BEFORE_STOPPING,
error async fn monitor_guard(guard: Arc<ServiceGuard>, mut updates: watch::Receiver<Option<Arc<ServiceGuard>>>) {
); let ServiceGuard {
if consecutive_failures >= GUARD_FAILURES_BEFORE_STOPPING { generation,
report_guard_stopped(generation, &error).await; proof,
break; proxy,
} interval,
} = guard.as_ref();
let mut consecutive_failures = 0u32;
loop {
tokio::select! {
biased;
_ = updates.changed() => return,
() = tokio::time::sleep(*interval) => {}
}
match SERVICE_PROXY_OPERATIONS
.run_guard_request(
*generation,
proof,
proxy,
|| matches!(*CoreManager::global().get_running_mode(), RunningMode::Service),
service::active_service_session,
|| service::set_system_proxy_by_service_with_session(proxy, proof),
)
.await
{
Ok(true) => consecutive_failures = 0,
Ok(false) => {
logging!(debug, Type::Core, "proxy guard superseded (generation {generation})");
return;
}
Err(error) if is_missing_network_service_failure(&error) => {
consecutive_failures = 0;
logging!(debug, Type::Core, "system proxy guard waits for a network service");
}
Err(error) => {
consecutive_failures += 1;
logging!(
warn,
Type::Core,
"failed to refresh system proxy through Service (generation {generation}, {}/{}): {:#}",
consecutive_failures,
GUARD_FAILURES_BEFORE_STOPPING,
error
);
if consecutive_failures >= GUARD_FAILURES_BEFORE_STOPPING {
report_guard_stopped(*generation, &error).await;
return;
} }
} }
} }
}); }
// Retire only after the replacement guard starts successfully.
notification::retire_guard_failures();
Ok(())
} }
const GUARD_FAILURES_BEFORE_STOPPING: u32 = 3; const GUARD_FAILURES_BEFORE_STOPPING: u32 = 3;
+1 -3
View File
@@ -93,9 +93,7 @@ impl RunStateEnv for RealEnv {
fn publish(&self, state: &RunState) { fn publish(&self, state: &RunState) {
// Reconciliation must run before the app handle exists and must not block this transition. // Reconciliation must run before the app handle exists and must not block this transition.
crate::process::AsyncHandler::spawn(|| async { crate::feat::request_tun_reconciliation();
crate::feat::reconcile_tun_availability().await;
});
let Some(app_handle) = crate::APP_HANDLE.get() else { let Some(app_handle) = crate::APP_HANDLE.get() else {
return; return;
+21 -25
View File
@@ -9,10 +9,7 @@ mod owner;
mod probe; mod probe;
use std::{ use std::{
sync::{ sync::{Arc, LazyLock},
Arc, LazyLock,
atomic::{AtomicBool, Ordering},
},
time::Duration, time::Duration,
}; };
@@ -57,6 +54,7 @@ impl std::fmt::Display for ReadyWaitError {
#[derive(Debug, Default)] #[derive(Debug, Default)]
struct VersionedService { struct VersionedService {
service: StoredService, service: StoredService,
operation_running: bool,
generation: u64, generation: u64,
observation: u64, observation: u64,
} }
@@ -79,7 +77,6 @@ pub struct RunStateStore<E: RunStateEnv> {
env: E, env: E,
service: Mutex<VersionedService>, service: Mutex<VersionedService>,
mode: ArcSwap<RunningMode>, mode: ArcSwap<RunningMode>,
operation_running: AtomicBool,
operation_done: Notify, operation_done: Notify,
} }
@@ -89,7 +86,6 @@ impl<E: RunStateEnv> RunStateStore<E> {
env, env,
service: Mutex::new(VersionedService::default()), service: Mutex::new(VersionedService::default()),
mode: ArcSwap::new(Arc::new(RunningMode::NotRunning)), mode: ArcSwap::new(Arc::new(RunningMode::NotRunning)),
operation_running: AtomicBool::new(false),
operation_done: Notify::new(), operation_done: Notify::new(),
} }
} }
@@ -97,8 +93,18 @@ impl<E: RunStateEnv> RunStateStore<E> {
/// The last known Run State, without waiting and without probing. /// The last known Run State, without waiting and without probing.
/// It reports when a privileged operation may make the snapshot stale. /// It reports when a privileged operation may make the snapshot stale.
pub fn state(&self) -> RunState { pub fn state(&self) -> RunState {
let service = self.service.lock().service.clone(); let (service, op_in_flight) = {
self.snapshot(service) let state = self.service.lock();
(state.service.clone(), state.operation_running)
};
RunState {
health: service.health,
pending: service.pending,
sidecar_allowed: service.sidecar_allowed,
mode: *self.mode.load().as_ref(),
is_admin: self.env.is_elevated(),
op_in_flight,
}
} }
/// Returns one snapshot taken after any operation visible in that snapshot has settled. /// Returns one snapshot taken after any operation visible in that snapshot has settled.
@@ -309,7 +315,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
/// Accepts Sidecar only while the Service is unusable and no conflicting operation is active. /// Accepts Sidecar only while the Service is unusable and no conflicting operation is active.
pub fn allow_sidecar_for_session(&self) -> Result<()> { pub fn allow_sidecar_for_session(&self) -> Result<()> {
let mut state = self.service.lock(); let mut state = self.service.lock();
if self.operation_running.load(Ordering::Acquire) { if state.operation_running {
bail!("service operation already running"); bail!("service operation already running");
} }
let permitted = match (state.service.pending, state.service.sidecar_allowed) { let permitted = match (state.service.pending, state.service.sidecar_allowed) {
@@ -333,7 +339,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
pub fn allow_sidecar_after_service_refusal(&self, reason: String) -> Result<()> { pub fn allow_sidecar_after_service_refusal(&self, reason: String) -> Result<()> {
let mut state = self.service.lock(); let mut state = self.service.lock();
if self.operation_running.load(Ordering::Acquire) || state.service.pending.is_some() { if state.operation_running || state.service.pending.is_some() {
bail!("cannot fall back while a service operation is pending"); bail!("cannot fall back while a service operation is pending");
} }
// Publish the refusal and allowance together so it never asks the UI for a repair. // Publish the refusal and allowance together so it never asks the UI for a repair.
@@ -348,7 +354,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
/// Requests installation only for a confirmed absent Service. /// Requests installation only for a confirmed absent Service.
pub fn require_install_for_session(&self) -> Result<()> { pub fn require_install_for_session(&self) -> Result<()> {
let mut state = self.service.lock(); let mut state = self.service.lock();
if self.operation_running.load(Ordering::Acquire) { if state.operation_running {
bail!("service operation already running"); bail!("service operation already running");
} }
if state.service.pending.is_none() if state.service.pending.is_none()
@@ -427,9 +433,10 @@ impl<E: RunStateEnv> RunStateStore<E> {
/// Only one privileged operation may be in flight; [`Self::settled`] waits on this. /// Only one privileged operation may be in flight; [`Self::settled`] waits on this.
pub fn begin_operation(&self) -> Result<OperationGuard<'_, E>> { pub fn begin_operation(&self) -> Result<OperationGuard<'_, E>> {
let mut state = self.service.lock(); let mut state = self.service.lock();
if self.operation_running.swap(true, Ordering::AcqRel) { if state.operation_running {
bail!("service operation already running"); bail!("service operation already running");
} }
state.operation_running = true;
state.bump(); state.bump();
drop(state); drop(state);
self.announce(); self.announce();
@@ -438,7 +445,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
#[cfg(test)] #[cfg(test)]
pub fn operation_in_flight(&self) -> bool { pub fn operation_in_flight(&self) -> bool {
self.operation_running.load(Ordering::Acquire) self.service.lock().operation_running
} }
#[cfg(test)] #[cfg(test)]
@@ -455,17 +462,6 @@ impl<E: RunStateEnv> RunStateStore<E> {
fn announce(&self) { fn announce(&self) {
self.env.publish(&self.state()); self.env.publish(&self.state());
} }
fn snapshot(&self, service: StoredService) -> RunState {
RunState {
health: service.health,
pending: service.pending,
sidecar_allowed: service.sidecar_allowed,
mode: *self.mode.load().as_ref(),
is_admin: self.env.is_elevated(),
op_in_flight: self.operation_running.load(Ordering::Acquire),
}
}
} }
/// Releases the privileged-operation slot and wakes everything waiting in [`RunStateStore::settled`]. /// Releases the privileged-operation slot and wakes everything waiting in [`RunStateStore::settled`].
@@ -476,7 +472,7 @@ pub struct OperationGuard<'a, E: RunStateEnv> {
impl<E: RunStateEnv> Drop for OperationGuard<'_, E> { impl<E: RunStateEnv> Drop for OperationGuard<'_, E> {
fn drop(&mut self) { fn drop(&mut self) {
self.store.operation_running.store(false, Ordering::Release); self.store.service.lock().operation_running = false;
self.store.operation_done.notify_waiters(); self.store.operation_done.notify_waiters();
self.store.announce(); self.store.announce();
} }
+146 -101
View File
@@ -26,9 +26,9 @@ use clash_verge_service_ipc::{
RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot, RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot,
StageRuntimeOutcome, StartClashRequest, WriterConfig, StageRuntimeOutcome, StartClashRequest, WriterConfig,
}; };
use clash_verge_task::scheduled_task::{self, Mailbox, Next, ScheduledTask};
use clash_verge_task::watch_task;
use parking_lot::Mutex; use parking_lot::Mutex;
#[cfg(target_os = "macos")]
use std::sync::LazyLock;
use std::{ use std::{
collections::HashMap, collections::HashMap,
env::current_exe, env::current_exe,
@@ -36,11 +36,12 @@ use std::{
path::{Path, PathBuf}, path::{Path, PathBuf},
process::Command as StdCommand, process::Command as StdCommand,
sync::{ sync::{
Arc, Arc, LazyLock,
atomic::{AtomicBool, AtomicU64, Ordering}, atomic::{AtomicBool, AtomicU64, Ordering},
}, },
time::{Duration, SystemTime, UNIX_EPOCH}, time::{Duration, SystemTime, UNIX_EPOCH},
}; };
use tokio::{sync::watch, time::Instant};
static OWNER_MONITOR_GENERATION: AtomicU64 = AtomicU64::new(0); static OWNER_MONITOR_GENERATION: AtomicU64 = AtomicU64::new(0);
static ACTIVE_SERVICE_SESSION: Mutex<Option<ActiveServiceSession>> = Mutex::new(None); static ACTIVE_SERVICE_SESSION: Mutex<Option<ActiveServiceSession>> = Mutex::new(None);
@@ -838,63 +839,85 @@ fn decode_hex(encoded: &str) -> Result<Vec<u8>> {
.collect() .collect()
} }
static PROVIDER_SYNC_QUEUED: AtomicBool = AtomicBool::new(false); static PROVIDER_SYNC_REQUESTS: LazyLock<Arc<Mailbox<Option<Instant>>>> = LazyLock::new(|| {
// Serializing the whole read-and-publish pass prevents an older cache from replacing a newer one. AsyncHandler::start_driver(scheduled_task::new(ProviderSchedule::default(), |_| {
static PROVIDER_SYNC_SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); sync_runtime_providers_by_service()
}))
});
static SYNC_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0); static SYNC_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
const RUNTIME_PROVIDER_SYNC_ATTEMPTS: u32 = 4; const RUNTIME_PROVIDER_SYNC_ATTEMPTS: u32 = 4;
const CONTENT_COMPARE_CHUNK: usize = 64 * 1024; const CONTENT_COMPARE_CHUNK: usize = 64 * 1024;
pub(crate) fn request_runtime_provider_sync(delay: Duration) { pub(crate) fn request_runtime_provider_sync(delay: Duration) {
if PROVIDER_SYNC_QUEUED.swap(true, Ordering::AcqRel) { let due = Instant::now() + delay;
return; PROVIDER_SYNC_REQUESTS.update(|pending| {
} if pending.is_some_and(|current| current <= due) {
AsyncHandler::spawn(move || async move { return false;
tokio::time::sleep(delay).await; }
use crate::utils::retry::{RetryError, RetryPolicy, retry}; *pending = Some(due);
let _ = retry( true
RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add((RUNTIME_PROVIDER_SYNC_ATTEMPTS - 1) as usize),
constants::timing::RUNTIME_PROVIDER_SYNC_RETRY_DELAY,
),
|index| async move {
let attempt = index as u32 + 1;
let outcome = {
let _serial = PROVIDER_SYNC_SERIAL.lock().await;
if attempt == 1 {
PROVIDER_SYNC_QUEUED.store(false, Ordering::Release);
}
sync_runtime_providers_by_service().await
};
match outcome {
Ok(ProviderSync { pending: 0, .. }) => Ok(()),
Ok(ProviderSync { pending, .. }) if attempt < RUNTIME_PROVIDER_SYNC_ATTEMPTS => {
logging!(
info,
Type::Service,
"{pending} provider caches are not ready yet; retrying"
);
Err(RetryError::Retry(()))
}
Ok(ProviderSync { pending, .. }) => {
logging!(warn, Type::Service, "{pending} provider caches were not synced");
Ok(())
}
Err(error) => {
logging!(
warn,
Type::Service,
"failed to sync provider caches from the service: {error:#}"
);
Ok(())
}
}
},
)
.await;
}); });
} }
#[derive(Default)]
struct ProviderSchedule {
requested: Option<Instant>,
retry: Option<(Instant, u32)>,
}
impl ScheduledTask for ProviderSchedule {
type Input = Option<Instant>;
type Work = u32;
type Output = Result<ProviderSync>;
fn on_input(&mut self, requested: Self::Input, _: Instant) {
if let Some(requested) = requested {
self.requested = Some(self.requested.map_or(requested, |current| current.min(requested)));
}
}
fn next(&mut self, now: Instant) -> Next<u32> {
let Some(due) = self.requested.into_iter().chain(self.retry.map(|(due, _)| due)).min() else {
return Next::Idle;
};
if due > now {
return Next::At(due);
}
let retry_attempt = self
.retry
.take_if(|(due, _)| *due <= now)
.map_or(1, |(_, attempt)| attempt);
let fresh_request = self.requested.take_if(|due| *due <= now).is_some();
Next::Run(if fresh_request { 1 } else { retry_attempt })
}
fn finished(&mut self, attempt: u32, result: std::thread::Result<Self::Output>, now: Instant) {
match result {
Ok(Ok(ProviderSync { pending: 0, .. })) => self.retry = None,
Ok(Ok(ProviderSync { pending, .. })) if attempt < RUNTIME_PROVIDER_SYNC_ATTEMPTS => {
logging!(
info,
Type::Service,
"{pending} provider caches are not ready yet; retrying"
);
self.retry = Some((now + constants::timing::RUNTIME_PROVIDER_SYNC_RETRY_DELAY, attempt + 1));
}
Ok(Ok(ProviderSync { pending, .. })) => {
logging!(warn, Type::Service, "{pending} provider caches were not synced");
}
Ok(Err(error)) => {
logging!(
warn,
Type::Service,
"failed to sync provider caches from the service: {error:#}"
);
}
Err(_) => logging!(error, Type::Service, "provider cache sync panicked"),
}
}
}
#[derive(Debug, Default)] #[derive(Debug, Default)]
struct ProviderSync { struct ProviderSync {
synced: usize, synced: usize,
@@ -1451,55 +1474,74 @@ const OWNER_MONITOR_INTERVAL: Duration = Duration::from_secs(5);
/// Mirrors `OwnerWatch`'s tolerance, for the log line only. /// Mirrors `OwnerWatch`'s tolerance, for the log line only.
const SUSTAINED_OWNER_SAMPLES: u8 = 3; const SUSTAINED_OWNER_SAMPLES: u8 = 3;
fn start_owner_monitor() { static OWNER_MONITOR: LazyLock<watch::Sender<Option<u64>>> = LazyLock::new(|| {
let generation = OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel) + 1; let (sender, receiver) = watch::channel(None);
AsyncHandler::spawn(move || async move { AsyncHandler::spawn(move || {
logging!(debug, Type::Service, "owner monitor started (generation {generation})"); watch_task::run(receiver, monitor_owner, |generation| {
let mut watch = OwnerWatch::new(); logging!(error, Type::Service, "owner monitor panicked (generation {generation})");
let mut core_restarts = None; })
loop {
tokio::time::sleep(OWNER_MONITOR_INTERVAL).await;
if OWNER_MONITOR_GENERATION.load(Ordering::Acquire) != generation {
logging!(
debug,
Type::Service,
"owner monitor superseded (generation {generation})"
);
break;
}
if !matches!(*CoreManager::global().get_running_mode(), RunningMode::Service) {
logging!(
debug,
Type::Service,
"owner monitor stopped; core no longer in service mode (generation {generation})"
);
break;
}
let (sample, status) = read_owner_sample().await;
if let Some(status) = &status {
log_core_restarts(&mut core_restarts, status);
}
let mut step = watch.observe(sample);
if matches!(step, OwnerStep::VerifyTransport) {
if watch.just_became_sustained() {
logging!(
warn,
Type::Service,
"service owner status unavailable for {SUSTAINED_OWNER_SAMPLES} samples (generation {generation}); \
preserving local proxy state while the core endpoint still answers"
);
}
let owner_endpoint_available = Handle::mihomo().get_version().await.is_ok();
step = watch.resolve_transport(owner_endpoint_available);
}
if let OwnerStep::Recover(reason) = step {
recover_after_owner_loss(generation, reason, status.as_ref()).await;
break;
}
}
}); });
sender
});
fn start_owner_monitor() {
OWNER_MONITOR.send_modify(|active| {
*active = Some(OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel).wrapping_add(1));
});
}
async fn monitor_owner(generation: u64, mut updates: watch::Receiver<Option<u64>>) {
logging!(debug, Type::Service, "owner monitor started (generation {generation})");
let mut watch = OwnerWatch::new();
let mut core_restarts = None;
loop {
let (step, status) = tokio::select! {
biased;
_ = updates.changed() => return,
result = async {
tokio::time::sleep(OWNER_MONITOR_INTERVAL).await;
if owner_monitor_generation() != generation
|| !matches!(*CoreManager::global().get_running_mode(), RunningMode::Service)
{
return None;
}
Some(probe_owner(generation, &mut watch, &mut core_restarts).await)
} => match result {
Some(observation) => observation,
None => return,
}
};
if let OwnerStep::Recover(reason) = step {
recover_after_owner_loss(generation, reason, status.as_ref()).await;
return;
}
}
}
async fn probe_owner(
generation: u64,
watch: &mut OwnerWatch,
core_restarts: &mut Option<u32>,
) -> (OwnerStep, Option<ServiceStatusSnapshot>) {
let (sample, status) = read_owner_sample().await;
if let Some(status) = &status {
log_core_restarts(core_restarts, status);
}
let mut step = watch.observe(sample);
if matches!(step, OwnerStep::VerifyTransport) {
if watch.just_became_sustained() {
logging!(
warn,
Type::Service,
"service owner status unavailable for {SUSTAINED_OWNER_SAMPLES} samples (generation {generation}); \
preserving local proxy state while the core endpoint still answers"
);
}
let owner_endpoint_available = Handle::mihomo().get_version().await.is_ok();
step = watch.resolve_transport(owner_endpoint_available);
}
(step, status)
} }
/// The Service logs its watchdog restarts where the app cannot read them. /// The Service logs its watchdog restarts where the app cannot read them.
@@ -1583,7 +1625,10 @@ fn session_matches_active_status(is_active: bool, active_generation: Option<u64>
} }
fn cancel_owner_monitors() { fn cancel_owner_monitors() {
OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel); OWNER_MONITOR.send_modify(|active| {
OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel);
*active = None;
});
} }
pub(crate) fn owner_monitor_generation() -> u64 { pub(crate) fn owner_monitor_generation() -> u64 {
+46 -81
View File
@@ -6,13 +6,9 @@ use crate::{
}; };
use anyhow::Result; use anyhow::Result;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use parking_lot::RwLock;
use std::{ use std::{
mem::DropGuard, mem::DropGuard,
sync::{ sync::atomic::{AtomicBool, Ordering},
Arc,
atomic::{AtomicBool, Ordering},
},
time::Duration, time::Duration,
}; };
use sysproxy::{Autoproxy, GuardMonitor, GuardType, Sysproxy}; use sysproxy::{Autoproxy, GuardMonitor, GuardType, Sysproxy};
@@ -243,18 +239,16 @@ async fn current_os_proxy_state(sys: Sysproxy, auto: Autoproxy) -> OsProxyState
pub(crate) struct Sysopt { pub(crate) struct Sysopt {
// Owns the proxy target pair; every reader and writer goes through this lock. // Owns the proxy target pair; every reader and writer goes through this lock.
proxy_state_lock: TokioMutex<(Sysproxy, Autoproxy)>, proxy_state_lock: TokioMutex<(Sysproxy, Autoproxy)>,
guard_operation_lock: TokioMutex<()>,
reset_sysproxy: AtomicBool, reset_sysproxy: AtomicBool,
guard: Arc<RwLock<GuardMonitor>>, guard: TokioMutex<GuardMonitor>,
} }
impl Default for Sysopt { impl Default for Sysopt {
fn default() -> Self { fn default() -> Self {
Self { Self {
proxy_state_lock: TokioMutex::new((Sysproxy::default(), Autoproxy::default())), proxy_state_lock: TokioMutex::new((Sysproxy::default(), Autoproxy::default())),
guard_operation_lock: TokioMutex::new(()),
reset_sysproxy: AtomicBool::new(false), reset_sysproxy: AtomicBool::new(false),
guard: Arc::new(RwLock::new(GuardMonitor::new(GuardType::None, Duration::from_secs(30)))), guard: TokioMutex::new(GuardMonitor::new(GuardType::None, Duration::from_secs(30))),
} }
} }
} }
@@ -295,14 +289,9 @@ impl Sysopt {
Self::default() Self::default()
} }
fn access_guard(&self) -> Arc<RwLock<GuardMonitor>> {
Arc::clone(&self.guard)
}
/// Stop the guard and return whether it drained. /// Stop the guard and return whether it drained.
async fn stop_proxy_guard_locked(&self) -> bool { async fn drain_guard(guard: &GuardMonitor) -> bool {
// Drop the parking_lot read guard before awaiting. let idle = guard.shutdown();
let idle = self.access_guard().read().shutdown();
let drained = idle.wait_timeout(GUARD_DRAIN_TIMEOUT).await; let drained = idle.wait_timeout(GUARD_DRAIN_TIMEOUT).await;
if !drained { if !drained {
logging!( logging!(
@@ -316,23 +305,23 @@ impl Sysopt {
/// Stop the guard before handing OS proxy ownership elsewhere. /// Stop the guard before handing OS proxy ownership elsewhere.
pub(super) async fn stop_proxy_guard(&self) -> bool { pub(super) async fn stop_proxy_guard(&self) -> bool {
let _operation = self.guard_operation_lock.lock().await; let guard = self.guard.lock().await;
self.stop_proxy_guard_locked().await Self::drain_guard(&guard).await
} }
/// Reconcile guard state with configuration and report success. /// Reconcile guard state with configuration and report success.
pub(super) async fn refresh_guard(&self) -> bool { pub(super) async fn refresh_guard(&self) -> bool {
logging!(info, Type::Core, "Refreshing system proxy guard..."); logging!(info, Type::Core, "Refreshing system proxy guard...");
let verge = Config::verge().await.latest_arc(); let verge = Config::verge().await.latest_arc();
let _operation = self.guard_operation_lock.lock().await; let mut guard = self.guard.lock().await;
if !verge.enable_system_proxy.unwrap_or_default() { if !verge.enable_system_proxy.unwrap_or_default() {
logging!(info, Type::Core, "System proxy is disabled."); logging!(info, Type::Core, "System proxy is disabled.");
let _drained = self.stop_proxy_guard_locked().await; let _drained = Self::drain_guard(&guard).await;
return true; return true;
} }
if !verge.enable_proxy_guard.unwrap_or_default() { if !verge.enable_proxy_guard.unwrap_or_default() {
logging!(info, Type::Core, "System proxy guard is disabled."); logging!(info, Type::Core, "System proxy guard is disabled.");
let _drained = self.stop_proxy_guard_locked().await; let _drained = Self::drain_guard(&guard).await;
return true; return true;
} }
logging!( logging!(
@@ -341,52 +330,27 @@ impl Sysopt {
"Updating system proxy with duration: {} seconds", "Updating system proxy with duration: {} seconds",
verge.proxy_guard_duration.unwrap_or(30) verge.proxy_guard_duration.unwrap_or(30)
); );
{ guard.set_interval(Duration::from_secs(verge.proxy_guard_duration.unwrap_or(30)));
let guard = self.access_guard();
guard
.write()
.set_interval(Duration::from_secs(verge.proxy_guard_duration.unwrap_or(30)));
}
logging!(info, Type::Core, "Starting system proxy guard..."); logging!(info, Type::Core, "Starting system proxy guard...");
{ if !guard.start() {
let guard = self.access_guard(); logging!(
if !guard.read().start() { warn,
logging!( Type::Core,
warn, "the system proxy guard refused to start; a previous run has not finished"
Type::Core, );
"the system proxy guard refused to start; a previous run has not finished"
);
}
} }
while self.access_guard().read().get_state().is_pendding() { while guard.get_state().is_pendding() {
tokio::time::sleep(Duration::from_millis(10)).await; tokio::time::sleep(Duration::from_millis(10)).await;
} }
// `start()` false may also mean a guard was already running. // `start()` false may also mean a guard was already running.
!self.access_guard().read().get_state().is_stopped() !guard.get_state().is_stopped()
}
/// Recover OS and guard state after a failed write.
async fn recover_from_failed_write(
&self,
error: anyhow::Error,
earlier_step_completed: bool,
guard_was_running: bool,
off: (Sysproxy, Autoproxy),
) -> anyhow::Error {
recover_from_failed_write(
error,
earlier_step_completed,
|state| self.recover_guard_after_failure(state, guard_was_running),
|| disable_all_proxies(off.0, off.1),
)
.await
} }
/// Reconcile the guard with the authoritative state. /// Reconcile the guard with the authoritative state.
fn recover_guard_after_failure(&self, state: AuthoritativeState, was_running: bool) { fn recover_guard_after_failure(guard: &mut GuardMonitor, state: AuthoritativeState, was_running: bool) {
match state { match state {
AuthoritativeState::Unchanged if was_running => { AuthoritativeState::Unchanged if was_running => {
let restarted = self.access_guard().read().start(); let restarted = guard.start();
if !restarted { if !restarted {
logging!( logging!(
warn, warn,
@@ -397,7 +361,7 @@ impl Sysopt {
} }
AuthoritativeState::Unchanged => {} AuthoritativeState::Unchanged => {}
AuthoritativeState::Unknown => { AuthoritativeState::Unknown => {
self.access_guard().write().set_guard_type(GuardType::None); guard.set_guard_type(GuardType::None);
} }
} }
} }
@@ -465,11 +429,11 @@ impl Sysopt {
(sys.clone(), auto.clone(), guard_type) (sys.clone(), auto.clone(), guard_type)
}; };
let _guard_operation = self.guard_operation_lock.lock().await; let mut guard = self.guard.lock().await;
// Drain the guard before any OS read or write. // Drain the guard before any OS read or write.
let guard_was_running = !self.access_guard().read().get_state().is_stopped(); let guard_was_running = !guard.get_state().is_stopped();
let idle = self.access_guard().read().shutdown(); let idle = guard.shutdown();
let drained = idle.wait_timeout(GUARD_DRAIN_TIMEOUT).await; let drained = idle.wait_timeout(GUARD_DRAIN_TIMEOUT).await;
// A slow guard does not stop the write, but it does make the OS read untrustworthy. // A slow guard does not stop the write, but it does make the OS read untrustworthy.
@@ -477,7 +441,7 @@ impl Sysopt {
&& drained && drained
&& current_os_proxy_state(sys.clone(), auto.clone()).await == OsProxyState::AlreadyApplied && current_os_proxy_state(sys.clone(), auto.clone()).await == OsProxyState::AlreadyApplied
{ {
self.access_guard().write().set_guard_type(guard_type); guard.set_guard_type(guard_type);
return Ok(()); return Ok(());
} }
@@ -508,24 +472,25 @@ impl Sysopt {
}) })
.await; .await;
match applied { let (earlier_step_completed, error) = match applied {
Ok(Ok(())) => {} Ok(Ok(())) => {
Ok(Err((earlier_step_completed, error))) => { guard.set_guard_type(guard_type);
return Err(self return Ok(());
.recover_from_failed_write(error, earlier_step_completed, guard_was_running, compensation)
.await);
} }
Err(join_error) => { Ok(Err(failure)) => failure,
let error = anyhow::Error::from(join_error).context("the system proxy write task did not finish"); Err(error) => (
return Err(self false,
.recover_from_failed_write(error, false, guard_was_running, compensation) anyhow::Error::from(error).context("the system proxy write task did not finish"),
.await); ),
} };
}
// Never point the guard at a target that failed to reach the OS. Err(recover_from_failed_write(
self.access_guard().write().set_guard_type(guard_type); error,
Ok(()) earlier_step_completed,
|state| Self::recover_guard_after_failure(&mut guard, state, guard_was_running),
|| disable_all_proxies(compensation.0, compensation.1),
)
.await)
} }
/// reset the sysproxy /// reset the sysproxy
@@ -545,8 +510,8 @@ impl Sysopt {
self.reset_sysproxy.store(false, Ordering::SeqCst); self.reset_sysproxy.store(false, Ordering::SeqCst);
}); });
let mut proxy_state = self.proxy_state_lock.lock().await; let mut proxy_state = self.proxy_state_lock.lock().await;
let _guard_operation = self.guard_operation_lock.lock().await; let guard = self.guard.lock().await;
let drained = self.stop_proxy_guard_locked().await; let drained = Self::drain_guard(&guard).await;
// 直接关闭所有代理 // 直接关闭所有代理
let (sys, auto) = { let (sys, auto) = {
@@ -567,7 +532,7 @@ impl Sysopt {
disable_until_the_last_write_is_ours( disable_until_the_last_write_is_ours(
drained, drained,
|| disable_all_proxies(sys.clone(), auto.clone()), || disable_all_proxies(sys.clone(), auto.clone()),
|| self.stop_proxy_guard_locked(), || Self::drain_guard(&guard),
) )
.await .await
} }
+86 -189
View File
@@ -1,32 +1,26 @@
use crate::{ use crate::{
config::{Config, PrfItem}, config::{Config, IProfiles, PrfItem},
feat, feat,
process::AsyncHandler, process::AsyncHandler,
singleton, singleton,
utils::resolve::is_resolve_done, utils::resolve::is_resolve_done,
}; };
use anyhow::Result; use anyhow::{Context as _, Result};
use clash_verge_draft::Draft;
use clash_verge_logging::{Type, logging, logging_error}; use clash_verge_logging::{Type, logging, logging_error};
use futures::StreamExt as _; use futures::{FutureExt as _, StreamExt as _};
use parking_lot::{Mutex, RwLock}; use std::{collections::HashMap, panic::AssertUnwindSafe, time::Duration};
use std::{
collections::HashMap,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::Duration,
};
use tokio::{ use tokio::{
sync::mpsc, sync::{mpsc, oneshot},
time::{sleep, timeout}, time::{sleep, timeout},
}; };
use tokio_util::time::{DelayQueue, delay_queue::Key}; use tokio_util::time::{DelayQueue, delay_queue::Key};
use tristr::alias::String; use tristr::alias::String;
enum TimerCommand { enum TimerCommand {
Apply(HashMap<String, TaskSchedule>), Initialize(oneshot::Sender<()>),
RunNow(String), Refresh(oneshot::Sender<()>),
NextUpdateTime(String, oneshot::Sender<Option<i64>>),
TaskFinished(String), TaskFinished(String),
} }
@@ -70,19 +64,19 @@ async fn run_timer_profile_update_transition<Started, Update, UpdateFuture, Fini
Started: FnOnce(), Started: FnOnce(),
Update: FnOnce() -> UpdateFuture, Update: FnOnce() -> UpdateFuture,
UpdateFuture: std::future::Future<Output = Output>, UpdateFuture: std::future::Future<Output = Output>,
Finished: FnOnce(Output), Finished: FnOnce(std::thread::Result<Output>),
Completed: FnOnce(), Completed: FnOnce(),
{ {
update_started(); update_started();
let result = update_profile().await; let result = AssertUnwindSafe(async { update_profile().await }).catch_unwind().await;
update_finished(result); update_finished(result);
update_completed(); update_completed();
} }
impl TaskState { impl TaskState {
const fn new(key: Key, interval_minutes: u64) -> Self { const fn new(key: Option<Key>, interval_minutes: u64) -> Self {
Self { Self {
key: Some(key), key,
interval_minutes, interval_minutes,
running: false, running: false,
retired: false, retired: false,
@@ -92,10 +86,6 @@ impl TaskState {
pub struct Timer { pub struct Timer {
command_tx: mpsc::UnboundedSender<TimerCommand>, command_tx: mpsc::UnboundedSender<TimerCommand>,
command_rx: Mutex<Option<mpsc::UnboundedReceiver<TimerCommand>>>,
refresh_lock: tokio::sync::Mutex<()>,
pub timer_map: Arc<RwLock<HashMap<String, u64>>>,
pub initialized: AtomicBool,
} }
singleton!(Timer, TIMER_INSTANCE); singleton!(Timer, TIMER_INSTANCE);
@@ -103,115 +93,31 @@ singleton!(Timer, TIMER_INSTANCE);
impl Timer { impl Timer {
fn new() -> Self { fn new() -> Self {
let (command_tx, command_rx) = mpsc::unbounded_channel(); let (command_tx, command_rx) = mpsc::unbounded_channel();
Self { let scheduler_tx = command_tx.clone();
command_tx, AsyncHandler::spawn(move || async move {
command_rx: Mutex::new(Some(command_rx)), let profiles = Config::profiles().await;
refresh_lock: tokio::sync::Mutex::new(()), Self::run_scheduler(command_rx, scheduler_tx, profiles).await;
timer_map: Arc::new(RwLock::new(HashMap::new())), });
initialized: AtomicBool::new(false), Self { command_tx }
}
} }
pub async fn init(&self) -> Result<()> { pub async fn init(&self) -> Result<()> {
if self self.update_schedule(TimerCommand::Initialize).await
.initialized
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
.is_err()
{
logging!(debug, Type::Timer, "Timer already initialized, skipping...");
return Ok(());
}
let command_rx = { self.command_rx.lock().take() };
if let Some(command_rx) = command_rx {
let command_tx = self.command_tx.clone();
AsyncHandler::spawn(move || async move {
Self::run_scheduler(command_rx, command_tx).await;
});
}
if let Err(e) = self.refresh().await {
self.initialized.store(false, Ordering::SeqCst);
logging!(error, Type::Timer, "Failed to initialize timer: {e:#}");
return Err(e);
}
{
let timer_map = self.timer_map.read();
logging!(debug, Type::Timer, "Registered timer task count: {}", timer_map.len());
for (uid, interval) in timer_map.iter() {
logging!(
debug,
Type::Timer,
"Registered timer task: uid={}, interval={}min",
uid,
interval
);
}
}
// Redundant with first_delay == ZERO, kept as the immediate path; mark_task_running
// no-ops whichever of the two arrives second.
let cur_timestamp = chrono::Local::now().timestamp();
if let Some(items) = Config::profiles().await.data_arc().items.as_ref() {
for item in items.iter() {
if let Some(option) = item.option.as_ref()
&& option.allow_auto_update.unwrap_or(true)
&& let Some(interval) = option.update_interval
&& interval > 0
&& let Some(uid) = item.uid.as_ref()
&& let Some(updated) = item.updated
&& cur_timestamp - (updated as i64) >= (interval as i64) * 60
{
logging!(info, Type::Timer, "Running overdue timer task immediately: uid={}", uid);
let _ = self.command_tx.send(TimerCommand::RunNow(uid.clone()));
}
}
}
logging!(info, Type::Timer, "Timer initialization completed");
Ok(())
} }
pub async fn refresh(&self) -> Result<()> { pub async fn refresh(&self) -> Result<()> {
let _refresh_guard = self.refresh_lock.lock().await; self.update_schedule(TimerCommand::Refresh).await
let new_schedule = self.gen_map().await;
// Cache intervals only: first_delay shrinks every second, so comparing it would make
// every refresh look like a change.
let new_map: HashMap<String, u64> = new_schedule
.iter()
.map(|(uid, schedule)| (uid.clone(), schedule.interval_minutes))
.collect();
let mut cache = self.timer_map.write();
if *cache == new_map {
logging!(debug, Type::Timer, "No timer changes needed");
return Ok(());
}
logging!(
info,
Type::Timer,
"Refreshing timer tasks map, count: {}",
new_map.len()
);
*cache = new_map;
drop(cache);
let _ = self.command_tx.send(TimerCommand::Apply(new_schedule));
Ok(())
} }
async fn gen_map(&self) -> HashMap<String, TaskSchedule> { async fn update_schedule(&self, command: fn(oneshot::Sender<()>) -> TimerCommand) -> Result<()> {
if let Some(items) = Config::profiles().await.data_arc().items.as_ref() { let (reply, done) = oneshot::channel();
return Self::gen_map_from_items(items); self.command_tx
} .send(command(reply))
.context("profile timer scheduler stopped")?;
HashMap::new() done.await.context("profile timer scheduler stopped")
} }
fn gen_map_from_items(items: &[PrfItem]) -> HashMap<String, TaskSchedule> { fn gen_map_from_items(items: &[PrfItem], initializing: bool) -> HashMap<String, TaskSchedule> {
let now = chrono::Local::now().timestamp(); let now = chrono::Local::now().timestamp();
let mut new_map = HashMap::new(); let mut new_map = HashMap::new();
@@ -221,7 +127,12 @@ impl Timer {
&& option.allow_auto_update.unwrap_or(true) && option.allow_auto_update.unwrap_or(true)
&& interval > 0 && interval > 0
{ {
new_map.insert(uid.clone(), TaskSchedule::new(interval, item.updated, 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);
} }
} }
@@ -231,24 +142,50 @@ impl Timer {
async fn run_scheduler( async fn run_scheduler(
mut command_rx: mpsc::UnboundedReceiver<TimerCommand>, mut command_rx: mpsc::UnboundedReceiver<TimerCommand>,
command_tx: mpsc::UnboundedSender<TimerCommand>, command_tx: mpsc::UnboundedSender<TimerCommand>,
profiles: Draft<IProfiles>,
) { ) {
let mut queue = DelayQueue::new(); let mut queue = DelayQueue::new();
let mut tasks = HashMap::new(); let mut tasks = HashMap::new();
let mut initialized = false;
loop { loop {
tokio::select! { tokio::select! {
Some(expired) = queue.next() => { Some(expired) = queue.next(), if initialized => {
let uid = expired.into_inner(); let uid = expired.into_inner();
Self::run_expired_task(&mut tasks, uid, command_tx.clone()); Self::run_expired_task(&mut tasks, uid, command_tx.clone());
} }
command = command_rx.recv() => { command = command_rx.recv() => {
match command { match command {
Some(TimerCommand::Apply(new_map)) => { Some(TimerCommand::Initialize(reply)) => {
Self::apply_timer_map(&mut queue, &mut tasks, new_map); if !initialized {
// Pre-init refreshes are queryable. Start from the current
// timestamps when the queue first becomes eligible to fire.
let profiles = profiles.data_arc();
let schedule = Self::gen_map_from_items(profiles.items.as_deref().unwrap_or_default(), true);
tasks.clear();
Self::apply_timer_map(&mut queue, &mut tasks, schedule);
initialized = true;
logging!(info, Type::Timer, "Timer initialization completed");
}
let _ = reply.send(());
} }
Some(TimerCommand::RunNow(uid)) => { Some(TimerCommand::Refresh(reply)) => {
Self::run_task_now(&mut queue, &mut tasks, uid, command_tx.clone()); let profiles = profiles.data_arc();
let schedule = Self::gen_map_from_items(profiles.items.as_deref().unwrap_or_default(), false);
if initialized {
Self::apply_timer_map(&mut queue, &mut tasks, schedule);
} else {
tasks = schedule
.into_iter()
.map(|(uid, schedule)| (uid, TaskState::new(None, schedule.interval_minutes)))
.collect();
}
let _ = reply.send(());
}
Some(TimerCommand::NextUpdateTime(uid, reply)) => {
let next = Self::next_update_time(&tasks, &profiles.latest_arc(), &uid);
let _ = reply.send(next);
} }
Some(TimerCommand::TaskFinished(uid)) => { Some(TimerCommand::TaskFinished(uid)) => {
Self::finish_task(&mut queue, &mut tasks, uid); Self::finish_task(&mut queue, &mut tasks, uid);
@@ -321,7 +258,7 @@ impl Timer {
schedule.interval_minutes, schedule.interval_minutes,
schedule.first_delay.as_secs() schedule.first_delay.as_secs()
); );
tasks.insert(uid, TaskState::new(key, schedule.interval_minutes)); tasks.insert(uid, TaskState::new(Some(key), schedule.interval_minutes));
} }
fn update_task_interval(queue: &mut DelayQueue<String>, uid: &str, state: &mut TaskState, schedule: &TaskSchedule) { fn update_task_interval(queue: &mut DelayQueue<String>, uid: &str, state: &mut TaskState, schedule: &TaskSchedule) {
@@ -353,52 +290,13 @@ impl Timer {
}; };
state.key = None; state.key = None;
if !Self::mark_task_running(state, &uid, false) { if state.running {
return; return;
} }
state.running = true;
Self::spawn_update_task(uid, command_tx); Self::spawn_update_task(uid, command_tx);
} }
fn run_task_now(
queue: &mut DelayQueue<String>,
tasks: &mut HashMap<String, TaskState>,
uid: String,
command_tx: mpsc::UnboundedSender<TimerCommand>,
) {
let Some(state) = tasks.get_mut(&uid) else {
return;
};
if !Self::mark_task_running(state, &uid, true) {
return;
}
if let Some(key) = state.key.take() {
queue.remove(&key);
}
Self::spawn_update_task(uid, command_tx);
}
fn mark_task_running(state: &mut TaskState, uid: &str, immediate: bool) -> bool {
if !state.running {
state.running = true;
return true;
}
if immediate {
logging!(
debug,
Type::Timer,
"Timer task already running, skip immediate uid={}",
uid
);
} else {
logging!(debug, Type::Timer, "Timer task already running, skip uid={}", uid);
}
false
}
fn finish_task(queue: &mut DelayQueue<String>, tasks: &mut HashMap<String, TaskState>, uid: String) { fn finish_task(queue: &mut DelayQueue<String>, tasks: &mut HashMap<String, TaskState>, uid: String) {
let Some(state) = tasks.get_mut(&uid) else { let Some(state) = tasks.get_mut(&uid) else {
return; return;
@@ -441,21 +339,19 @@ impl Timer {
} }
pub async fn get_next_update_time(&self, uid: &str) -> Option<i64> { pub async fn get_next_update_time(&self, uid: &str) -> Option<i64> {
logging!(debug, Type::Timer, "Getting next update time, uid={}", uid); let (reply, result) = oneshot::channel();
self.command_tx
.send(TimerCommand::NextUpdateTime(uid.into(), reply))
.ok()?;
result.await.ok().flatten()
}
let task_interval = *self.timer_map.read().get(uid)?; fn next_update_time(tasks: &HashMap<String, TaskState>, profiles: &IProfiles, uid: &str) -> Option<i64> {
let profiles = Config::profiles().await; let task = tasks.get(uid).filter(|task| !task.retired)?;
let profiles_guard = profiles.latest_arc(); let updated = profiles.get_item(uid).ok()?.updated.filter(|updated| *updated > 0)?;
let items = profiles_guard.items.as_ref()?; let updated = i64::try_from(updated).ok()?;
let interval = i64::try_from(task.interval_minutes).ok()?.checked_mul(60)?;
let profile = items.iter().find(|item| item.uid.as_deref() == Some(uid))?; updated.checked_add(interval)
let updated = profile.updated.unwrap_or(0) as i64;
if updated > 0 {
Some(updated + (task_interval as i64 * 60))
} else {
None
}
} }
fn emit_update_event(uid: &str, is_start: bool) { fn emit_update_event(uid: &str, is_start: bool) {
@@ -474,12 +370,13 @@ impl Timer {
|| Self::emit_update_event(uid, true), || Self::emit_update_event(uid, true),
|| feat::update_profile(uid, None, false), || feat::update_profile(uid, None, false),
|result| match result { |result| match result {
Ok(_) => { Ok(Ok(_)) => {
logging!(debug, Type::Timer, "timer task completed for uid: {}", uid); logging!(debug, Type::Timer, "timer task completed for uid: {}", uid);
} }
Err(e) => { Ok(Err(e)) => {
logging_error!(Type::Timer, "Failed to update profile uid {}: {e:#}", uid); logging_error!(Type::Timer, "Failed to update profile uid {}: {e:#}", uid);
} }
Err(_) => logging!(error, Type::Timer, "Profile update worker panicked"),
}, },
|| Self::emit_update_event(uid, false), || Self::emit_update_event(uid, false),
) )
@@ -552,7 +449,7 @@ mod tests {
remote_profile("missing-interval", Some(true), None), remote_profile("missing-interval", Some(true), None),
]; ];
let map = Timer::gen_map_from_items(&items); let map = Timer::gen_map_from_items(&items, false);
assert_eq!(map.len(), 2); assert_eq!(map.len(), 2);
assert_eq!(map.get("enabled").map(|s| s.interval_minutes), Some(30)); assert_eq!(map.get("enabled").map(|s| s.interval_minutes), Some(30));
@@ -763,8 +660,8 @@ mod tests {
}, },
{ {
let calls = Arc::clone(&calls); let calls = Arc::clone(&calls);
move |result: anyhow::Result<()>| { move |result| {
assert!(result.is_ok()); assert!(matches!(result, Ok(Ok(()))));
calls.lock().push("terminal-result"); calls.lock().push("terminal-result");
} }
}, },
+12 -26
View File
@@ -212,22 +212,9 @@ impl Tray {
return Ok(()); return Ok(());
}; };
let verge = Config::verge().await.latest_arc(); let verge = Config::verge().await;
let system_proxy = verge.enable_system_proxy.unwrap_or(false);
let tun_mode = verge.enable_tun_mode.unwrap_or(false);
let mode = {
Config::clash()
.await
.latest_arc()
.0
.get("mode")
.map_or("rule", |val| val.as_str().unwrap_or("rule"))
.to_owned()
};
let is_lightweight_mode = is_in_lightweight_mode();
let fetch_proxy_groups = let fetch_proxy_groups =
include_proxy_groups && verge.tray_proxy_groups_display_mode.as_deref() != Some("disable"); include_proxy_groups && verge.latest_arc().tray_proxy_groups_display_mode.as_deref() != Some("disable");
// TODO: should update tray menu again when it was timeout error // TODO: should update tray menu again when it was timeout error
let (proxy_nodes_data, runtime_proxy_groups_order) = if fetch_proxy_groups { let (proxy_nodes_data, runtime_proxy_groups_order) = if fetch_proxy_groups {
@@ -257,29 +244,28 @@ impl Tray {
(None, None) (None, None)
}; };
let verge = if fetch_proxy_groups { let clash = Config::clash().await;
Config::verge().await.latest_arc() let profiles = Config::profiles().await;
} else {
verge
};
let profiles = Config::profiles().await.latest_arc();
let (tx, rx) = tokio::sync::oneshot::channel(); let (tx, rx) = tokio::sync::oneshot::channel();
let dispatch_handle = app_handle.clone(); let dispatch_handle = app_handle.clone();
app_handle app_handle
.run_on_main_thread(move || { .run_on_main_thread(move || {
let _ = tx.send((|| -> Result<()> { let _ = tx.send((|| -> Result<()> {
let verge = verge.latest_arc();
let clash = clash.latest_arc();
let mode = clash.0.get("mode").and_then(|mode| mode.as_str()).unwrap_or("rule");
let menu = build_tray_menu( let menu = build_tray_menu(
&dispatch_handle, &dispatch_handle,
TrayMenuOptions { TrayMenuOptions {
mode: Some(mode.as_str()), mode: Some(mode),
system_proxy_enabled: system_proxy, system_proxy_enabled: verge.enable_system_proxy.unwrap_or(false),
tun_mode_enabled: tun_mode, tun_mode_enabled: verge.enable_tun_mode.unwrap_or(false),
is_lightweight_mode, is_lightweight_mode: is_in_lightweight_mode(),
include_proxy_groups, include_proxy_groups,
}, },
&verge, &verge,
&profiles, &profiles.latest_arc(),
runtime_proxy_groups_order, runtime_proxy_groups_order,
proxy_nodes_data, proxy_nodes_data,
)?; )?;
+88 -117
View File
@@ -2,28 +2,18 @@ use crate::core::handle;
use crate::process::AsyncHandler; use crate::process::AsyncHandler;
use crate::utils::{connections_stream, tray_speed}; use crate::utils::{connections_stream, tray_speed};
use crate::{Type, logging}; use crate::{Type, logging};
use parking_lot::Mutex; use std::sync::OnceLock;
use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use tauri::async_runtime::JoinHandle; use tokio::sync::watch;
use tauri_plugin_mihomo::models::WsConnectionId;
use connections_stream::{MihomoWsEventStream, StreamConsumeState, TrafficSpeedEvent};
const TRAY_SPEED_RETRY_DELAY: Duration = Duration::from_secs(1); const TRAY_SPEED_RETRY_DELAY: Duration = Duration::from_secs(1);
const TRAY_SPEED_STALE_TIMEOUT: Duration = Duration::from_secs(5); const TRAY_SPEED_STALE_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Clone)] #[derive(Default)]
pub struct TraySpeedController { pub struct TraySpeedController {
speed_task: Arc<Mutex<Option<JoinHandle<()>>>>, enabled: OnceLock<watch::Sender<bool>>,
speed_connection_id: Arc<Mutex<Option<WsConnectionId>>>,
}
impl Default for TraySpeedController {
fn default() -> Self {
Self {
speed_task: Arc::new(Mutex::new(None)),
speed_connection_id: Arc::new(Mutex::new(None)),
}
}
} }
impl TraySpeedController { impl TraySpeedController {
@@ -32,104 +22,102 @@ impl TraySpeedController {
} }
pub fn update_task(&self, enable_tray_speed: bool) { pub fn update_task(&self, enable_tray_speed: bool) {
if enable_tray_speed { let enabled = self.enabled.get_or_init(|| {
self.start_task(); let (enabled, receiver) = watch::channel(false);
} else { AsyncHandler::spawn(move || Self::run(receiver));
self.stop_task(); enabled
});
enabled.send_replace(enable_tray_speed);
}
async fn run(mut enabled: watch::Receiver<bool>) {
while enabled.changed().await.is_ok() {
let should_run = *enabled.borrow_and_update();
if should_run {
Self::run_enabled(&mut enabled).await;
} else {
Self::clear_tray_speed();
}
} }
} }
fn start_task(&self) { async fn run_enabled(enabled: &mut watch::Receiver<bool>) {
if handle::Handle::global().is_exiting() { while !handle::Handle::global().is_exiting() {
return; if !Self::has_main_tray() {
} logging!(warn, Type::Tray, "托盘不可用,停止托盘速率任务");
return;
}
if !Self::has_main_tray() { // Keep the registered stream outside the cancellable future until it is disconnected.
logging!(warn, Type::Tray, "托盘不可用,跳过启动托盘速率任务"); let mut stream = None;
return; let disabled = tokio::select! {
} biased;
_ = Self::wait_until_disabled(enabled) => true,
let mut guard = self.speed_task.lock(); _ = Self::read_speed(&mut stream) => false,
if guard.as_ref().is_some_and(|task| !task.inner().is_finished()) { };
return; if disabled {
} Self::clear_tray_speed();
}
let speed_connection_id = Arc::clone(&self.speed_connection_id); if let Some(stream) = stream {
let task = AsyncHandler::spawn(move || async move { let disconnect = connections_stream::disconnect_connection(stream.connection_id);
loop { tokio::pin!(disconnect);
if handle::Handle::global().is_exiting() { tokio::select! {
break; biased;
} _ = Self::wait_until_disabled(enabled), if !disabled => {
Self::clear_tray_speed();
if !Self::has_main_tray() { disconnect.await;
logging!(warn, Type::Tray, "托盘已不可用,停止托盘速率任务"); return;
break;
}
let stream_connect_result = connections_stream::connect_traffic_stream().await;
let mut speed_stream = match stream_connect_result {
Ok(stream) => stream,
Err(err) => {
logging!(debug, Type::Tray, "托盘速率流连接失败,稍后重试: {err}");
Self::apply_tray_speed(0, 0);
tokio::time::sleep(TRAY_SPEED_RETRY_DELAY).await;
continue;
}
};
Self::set_speed_connection_id(&speed_connection_id, Some(speed_stream.connection_id));
loop {
let next_state = speed_stream
.next_event(TRAY_SPEED_STALE_TIMEOUT, || handle::Handle::global().is_exiting())
.await;
match next_state {
connections_stream::StreamConsumeState::Event(speed_event) => {
Self::apply_tray_speed(speed_event.up, speed_event.down);
}
connections_stream::StreamConsumeState::Stale => {
logging!(debug, Type::Tray, "托盘速率流长时间未收到有效数据,触发重连");
Self::apply_tray_speed(0, 0);
break;
}
connections_stream::StreamConsumeState::Closed
| connections_stream::StreamConsumeState::ExitRequested => {
break;
}
} }
_ = &mut disconnect => {}
} }
}
if disabled || handle::Handle::global().is_exiting() || !Self::has_main_tray() {
return;
}
Self::disconnect_speed_connection(&speed_connection_id).await; if *enabled.borrow() {
if handle::Handle::global().is_exiting() || !Self::has_main_tray() {
break;
}
// `Stale` already reset the display; this covers remote close.
Self::apply_tray_speed(0, 0); Self::apply_tray_speed(0, 0);
tokio::time::sleep(TRAY_SPEED_RETRY_DELAY).await;
} }
if tokio::time::timeout(TRAY_SPEED_RETRY_DELAY, Self::wait_until_disabled(enabled))
Self::set_speed_connection_id(&speed_connection_id, None); .await
}); .is_ok()
{
*guard = Some(task); Self::clear_tray_speed();
return;
}
}
} }
fn stop_task(&self) { async fn wait_until_disabled(enabled: &mut watch::Receiver<bool>) {
let task = self.speed_task.lock().take(); let _ = enabled.wait_for(|enabled| !enabled).await;
let speed_connection_id = Arc::clone(&self.speed_connection_id); }
AsyncHandler::spawn(move || async move { async fn read_speed(stream: &mut Option<MihomoWsEventStream<TrafficSpeedEvent>>) {
// Await abort before disconnect so the task cannot consume and lose the connection ID. let speed_stream = match connections_stream::connect_traffic_stream().await {
if let Some(task) = task { Ok(connected) => stream.insert(connected),
task.abort(); Err(err) => {
let _ = task.await; logging!(debug, Type::Tray, "托盘速率流连接失败,稍后重试: {err}");
return;
} }
Self::disconnect_speed_connection(&speed_connection_id).await; };
});
loop {
match speed_stream
.next_event(TRAY_SPEED_STALE_TIMEOUT, || handle::Handle::global().is_exiting())
.await
{
StreamConsumeState::Event(event) => Self::apply_tray_speed(event.up, event.down),
StreamConsumeState::Stale => {
logging!(debug, Type::Tray, "托盘速率流长时间未收到有效数据,触发重连");
Self::apply_tray_speed(0, 0);
return;
}
StreamConsumeState::Closed | StreamConsumeState::ExitRequested => return,
}
}
}
fn clear_tray_speed() {
let app_handle = handle::Handle::app_handle(); let app_handle = handle::Handle::app_handle();
if let Some(tray) = app_handle.tray_by_id(super::TRAY_ID) { if let Some(tray) = app_handle.tray_by_id(super::TRAY_ID) {
let result = tray.with_inner_tray_icon(|inner| { let result = tray.with_inner_tray_icon(|inner| {
@@ -147,23 +135,6 @@ impl TraySpeedController {
handle::Handle::app_handle().tray_by_id(super::TRAY_ID).is_some() handle::Handle::app_handle().tray_by_id(super::TRAY_ID).is_some()
} }
fn set_speed_connection_id(
speed_connection_id: &Arc<Mutex<Option<WsConnectionId>>>,
connection_id: Option<WsConnectionId>,
) {
*speed_connection_id.lock() = connection_id;
}
fn take_speed_connection_id(speed_connection_id: &Arc<Mutex<Option<WsConnectionId>>>) -> Option<WsConnectionId> {
speed_connection_id.lock().take()
}
async fn disconnect_speed_connection(speed_connection_id: &Arc<Mutex<Option<WsConnectionId>>>) {
if let Some(connection_id) = Self::take_speed_connection_id(speed_connection_id) {
connections_stream::disconnect_connection(connection_id).await;
}
}
fn apply_tray_speed(up: u64, down: u64) { fn apply_tray_speed(up: u64, down: u64) {
let app_handle = handle::Handle::app_handle(); let app_handle = handle::Handle::app_handle();
if let Some(tray) = app_handle.tray_by_id(super::TRAY_ID) { if let Some(tray) = app_handle.tray_by_id(super::TRAY_ID) {
+2 -1
View File
@@ -1,6 +1,6 @@
use crate::{ use crate::{
config::{Config, IClashTemp, IProfiles, IVerge}, config::{Config, IClashTemp, IProfiles, IVerge},
core::{CoreManager, backup, proxy_control, proxy_control::SystemProxyStateUnknown}, core::{CoreManager, auto_backup, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
process::AsyncHandler, process::AsyncHandler,
utils::{ utils::{
dirs::{PathBufExec as _, app_home_dir, local_backup_dir, verge_path}, dirs::{PathBufExec as _, app_home_dir, local_backup_dir, verge_path},
@@ -58,6 +58,7 @@ async fn finalize_restored_verge_config(
*d = restored.clone(); *d = restored.clone();
}); });
verge_draft.apply(); verge_draft.apply();
auto_backup::publish_settings(&verge_draft.data_arc());
// Turn it off here; a failing core side effect below would otherwise skip this step. // Turn it off here; a failing core side effect below would otherwise skip this step.
if !restored.enable_system_proxy.unwrap_or_default() { if !restored.enable_system_proxy.unwrap_or_default() {
+31 -14
View File
@@ -21,24 +21,38 @@ pub(super) enum Effect {
pub(super) type Effects = BTreeSet<Effect>; pub(super) type Effects = BTreeSet<Effect>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(super) enum AfterCommit {
BackupSettings,
}
#[derive(Default)]
pub(super) struct EffectPlan {
pub(super) before_commit: Effects,
pub(super) after_commit: BTreeSet<AfterCommit>,
}
macro_rules! select_field { macro_rules! select_field {
($effects:ident, $field:ident, NoEffect) => { let _ = $field; }; ($effects:ident, $field:ident, NoEffect) => { let _ = $field; };
($effects:ident, $field:ident, [$($effect:ident),*]) => { ($effects:ident, $field:ident, [$($effect:ident),*]) => {
if $field.is_some() { $effects.extend([$(Effect::$effect),*]); } if $field.is_some() { $effects.before_commit.extend([$(Effect::$effect),*]); }
};
($effects:ident, $field:ident, (AfterCommit $effect:ident)) => {
if $field.is_some() { $effects.after_commit.insert(AfterCommit::$effect); }
}; };
($effects:ident, $field:ident, Tun) => { ($effects:ident, $field:ident, Tun) => {
select_field!($effects, $field, [ClashConfig, TrayMenu, TrayTooltip, TrayIcon]); select_field!($effects, $field, [ClashConfig, TrayMenu, TrayTooltip, TrayIcon]);
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
if *$field == Some(true) { $effects.insert(Effect::RestartCore); } if *$field == Some(true) { $effects.before_commit.insert(Effect::RestartCore); }
}; };
} }
macro_rules! verge_registry { macro_rules! verge_registry {
($( $(#[$cfg:meta])* $field:ident => $rule:tt; )*) => { ($( $(#[$cfg:meta])* $field:ident => $rule:tt; )*) => {
pub(super) fn verge_effects(patch: &IVerge) -> Effects { pub(super) fn verge_effects(patch: &IVerge) -> EffectPlan {
// No rest pattern: even fields omitted by serde must be classified at compile time. // No rest pattern: even fields omitted by serde must be classified at compile time.
let IVerge { $( $(#[$cfg])* $field, )* } = patch; let IVerge { $( $(#[$cfg])* $field, )* } = patch;
let mut effects = Effects::new(); let mut effects = EffectPlan::default();
$( $(#[$cfg])* { select_field!(effects, $field, $rule); } )* $( $(#[$cfg])* { select_field!(effects, $field, $rule); } )*
effects effects
} }
@@ -100,9 +114,9 @@ verge_registry! {
proxy_layout_column => NoEffect; proxy_layout_column => NoEffect;
test_list => NoEffect; test_list => NoEffect;
auto_log_clean => NoEffect; auto_log_clean => NoEffect;
enable_auto_backup_schedule => NoEffect; enable_auto_backup_schedule => (AfterCommit BackupSettings);
auto_backup_interval_hours => NoEffect; auto_backup_interval_hours => (AfterCommit BackupSettings);
auto_backup_on_change => NoEffect; auto_backup_on_change => (AfterCommit BackupSettings);
#[cfg(not(target_os = "windows"))] #[cfg(not(target_os = "windows"))]
verge_redir_port => [RestartCore]; verge_redir_port => [RestartCore];
#[cfg(not(target_os = "windows"))] #[cfg(not(target_os = "windows"))]
@@ -130,7 +144,7 @@ verge_registry! {
enable_external_controller => [RestartCore]; enable_external_controller => [RestartCore];
} }
pub(super) fn clash_effects(patch: &serde_yaml_ng::Mapping) -> Effects { pub(super) fn clash_effects(patch: &serde_yaml_ng::Mapping) -> EffectPlan {
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
let mut effects = Effects::new(); let mut effects = Effects::new();
for key in patch.keys() { for key in patch.keys() {
@@ -157,7 +171,10 @@ pub(super) fn clash_effects(patch: &serde_yaml_ng::Mapping) -> Effects {
if patch.is_empty() { if patch.is_empty() {
effects.insert(Effect::ClashConfig); effects.insert(Effect::ClashConfig);
} }
effects EffectPlan {
before_commit: effects,
..Default::default()
}
} }
#[cfg(test)] #[cfg(test)]
@@ -172,7 +189,7 @@ mod tests {
#[test] #[test]
fn representative_verge_patches_map_to_frozen_effects() { fn representative_verge_patches_map_to_frozen_effects() {
assert_eq!(verge_effects(&IVerge::default()), Effects::new()); assert_eq!(verge_effects(&IVerge::default()).before_commit, Effects::new());
let cases: [(IVerge, &[Effect]); 9] = [ let cases: [(IVerge, &[Effect]); 9] = [
( (
@@ -216,7 +233,7 @@ mod tests {
]; ];
for (patch, expected) in cases { for (patch, expected) in cases {
assert_eq!( assert_eq!(
verge_effects(&patch), verge_effects(&patch).before_commit,
expected.iter().copied().collect::<Effects>(), expected.iter().copied().collect::<Effects>(),
"patch mapping drifted for {expected:?}" "patch mapping drifted for {expected:?}"
); );
@@ -225,7 +242,7 @@ mod tests {
let tun = verge_patch(|p| p.enable_tun_mode = Some(true)); let tun = verge_patch(|p| p.enable_tun_mode = Some(true));
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
assert_eq!( assert_eq!(
verge_effects(&tun), verge_effects(&tun).before_commit,
[ [
Effect::RestartCore, Effect::RestartCore,
Effect::ClashConfig, Effect::ClashConfig,
@@ -238,7 +255,7 @@ mod tests {
); );
#[cfg(not(target_os = "linux"))] #[cfg(not(target_os = "linux"))]
assert_eq!( assert_eq!(
verge_effects(&tun), verge_effects(&tun).before_commit,
[ [
Effect::ClashConfig, Effect::ClashConfig,
Effect::TrayIcon, Effect::TrayIcon,
@@ -281,7 +298,7 @@ mod tests {
]; ];
for (patch, expected) in cases { for (patch, expected) in cases {
assert_eq!( assert_eq!(
clash_effects(&patch), clash_effects(&patch).before_commit,
expected.iter().copied().collect::<Effects>(), expected.iter().copied().collect::<Effects>(),
"clash mapping drifted for {expected:?}" "clash mapping drifted for {expected:?}"
); );
+10 -6
View File
@@ -1,11 +1,11 @@
use super::effects::{Effect, Effects}; use super::effects::{AfterCommit, Effect, EffectPlan};
use crate::core::notify::{Refresh, announce}; use crate::core::notify::{Refresh, announce};
use crate::{ use crate::{
config::{ config::{
Config, IVerge, Config, IVerge,
snapshot::{capture_config_files, restore_files}, snapshot::{capture_config_files, restore_files},
}, },
core::auto_backup::AutoBackupManager, core::auto_backup,
core::{ core::{
CoreManager, SilentUpdater, autostart, hotkey, lightweight, logger, manager::ConfigUpdateGuard, proxy_control, CoreManager, SilentUpdater, autostart, hotkey, lightweight, logger, manager::ConfigUpdateGuard, proxy_control,
tray, tray,
@@ -108,7 +108,7 @@ async fn ensure_effect(
Ok(()) Ok(())
} }
pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: Effects) -> Result<()> { pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: EffectPlan) -> Result<()> {
let manager = CoreManager::global(); let manager = CoreManager::global();
let update = manager.claim_config_update(config_write)?; let update = manager.claim_config_update(config_write)?;
let clash = Config::clash().await; let clash = Config::clash().await;
@@ -130,7 +130,7 @@ pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, e
Patch::Clash(patch) => clash.edit_draft(|draft| draft.patch_config(patch)), Patch::Clash(patch) => clash.edit_draft(|draft| draft.patch_config(patch)),
} }
let result: Result<()> = async { let result: Result<()> = async {
for effect in effects.iter().copied() { for effect in effects.before_commit.iter().copied() {
let result = Box::pin(ensure_effect(effect, verge_patch, manager, &update)).await; let result = Box::pin(ensure_effect(effect, verge_patch, manager, &update)).await;
if matches!(patch, Patch::Clash(_)) && matches!(effect, Effect::TrayMenu | Effect::TrayIcon) { if matches!(patch, Patch::Clash(_)) && matches!(effect, Effect::TrayMenu | Effect::TrayIcon) {
// Tray failures must not reject an applied Clash mode change. // Tray failures must not reject an applied Clash mode change.
@@ -166,10 +166,14 @@ pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, e
if patch.auto_check_update == Some(false) { if patch.auto_check_update == Some(false) {
SilentUpdater::global().discard_pending().await; SilentUpdater::global().discard_pending().await;
} }
if effects.contains(&Effect::ClashConfig) { if effects.before_commit.contains(&Effect::ClashConfig) {
announce(Refresh::Clash); announce(Refresh::Clash);
} }
logging_error!(Type::Backup, AutoBackupManager::global().refresh_settings().await); for effect in effects.after_commit {
match effect {
AfterCommit::BackupSettings => auto_backup::publish_settings(&verge.data_arc()),
}
}
announce(Refresh::Verge); announce(Refresh::Verge);
} }
Patch::Clash(_) => announce(Refresh::Clash), Patch::Clash(_) => announce(Refresh::Clash),
+20 -2
View File
@@ -4,19 +4,37 @@ use crate::core::notify::NoticeStatus;
use std::{ use std::{
mem::DropGuard, mem::DropGuard,
sync::atomic::{AtomicBool, Ordering}, sync::{
LazyLock,
atomic::{AtomicBool, Ordering},
},
}; };
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use clash_verge_task::scheduled_task::{self, CoalescingJob};
use crate::{ use crate::{
config::{Config, IVerge}, config::{Config, IVerge},
core::{handle::Handle, manager::RunningMode, runstate::RUN_STATE}, core::{handle::Handle, manager::RunningMode, runstate::RUN_STATE},
process::AsyncHandler,
}; };
/// Prevents recursive runtime disable writes. /// Prevents recursive runtime disable writes.
static DISABLING_TUN: AtomicBool = AtomicBool::new(false); static DISABLING_TUN: AtomicBool = AtomicBool::new(false);
static TUN_RECONCILE: LazyLock<CoalescingJob> = LazyLock::new(|| {
AsyncHandler::start_driver(scheduled_task::coalescing(reconcile_tun_availability, || {
logging!(error, Type::Core, "TUN reconciliation panicked");
}))
});
pub(crate) fn request_tun_reconciliation() {
// The internal disable can publish Run State as part of its own effects.
if !DISABLING_TUN.load(Ordering::Acquire) {
TUN_RECONCILE.request();
}
}
/// Turn TUN off when startup confirms the Service is absent, so the Core can start on Sidecar. /// Turn TUN off when startup confirms the Service is absent, so the Core can start on Sidecar.
/// ///
/// Runs before the runtime config is generated. /// Runs before the runtime config is generated.
@@ -61,7 +79,7 @@ pub async fn reconcile_tun_availability() {
return; return;
} }
// The flag coalesces newly spawned tasks while the config lock serializes writers. // Suppress recursive requests while the config lock serializes writers.
DISABLING_TUN.store(true, Ordering::Release); DISABLING_TUN.store(true, Ordering::Release);
let _disabling_tun = DropGuard::new((), |()| { let _disabling_tun = DropGuard::new((), |()| {
DISABLING_TUN.store(false, Ordering::Release); DISABLING_TUN.store(false, Ordering::Release);
+1 -11
View File
@@ -304,17 +304,7 @@ async fn clean_session_ending_best_effort() -> CleanupResult {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
pub async fn hide() { pub async fn hide() {
use crate::core::lightweight::add_light_weight_timer; crate::core::lightweight::add_light_weight_timer().await;
let enable_auto_light_weight_mode = Config::verge()
.await
.data_arc()
.enable_auto_light_weight_mode
.unwrap_or(false);
if enable_auto_light_weight_mode {
add_light_weight_timer().await;
}
if let Some(window) = WindowManager::get_main_window() if let Some(window) = WindowManager::get_main_window()
&& window.is_visible().unwrap_or(false) && window.is_visible().unwrap_or(false)
+5
View File
@@ -4,6 +4,11 @@ use tauri::{async_runtime, async_runtime::JoinHandle};
pub struct AsyncHandler; pub struct AsyncHandler;
impl AsyncHandler { impl AsyncHandler {
pub(crate) fn start_driver<H>((handle, driver): (H, impl Future<Output = ()> + Send + 'static)) -> H {
Self::spawn(move || driver);
handle
}
#[inline] #[inline]
#[track_caller] #[track_caller]
pub fn spawn<F, Fut>(f: F) -> JoinHandle<()> pub fn spawn<F, Fut>(f: F) -> JoinHandle<()>
+26 -12
View File
@@ -8,7 +8,7 @@ use std::{
process::{Command, Stdio}, process::{Command, Stdio},
time::{Duration, Instant}, time::{Duration, Instant},
}; };
use tokio::sync::Mutex; use tokio::sync::{Mutex, MutexGuard};
// Any address routed into TUN works, since dns-hijack answers it; the value only matters if left behind. // Any address routed into TUN works, since dns-hijack answers it; the value only matters if left behind.
const PLACEHOLDER_DNS: &str = "114.114.114.114\n223.5.5.5\n1.1.1.1"; const PLACEHOLDER_DNS: &str = "114.114.114.114\n223.5.5.5\n1.1.1.1";
@@ -42,13 +42,17 @@ fn needs_public_dns(config: &Mapping) -> bool {
} }
/// Sets the placeholder DNS while the running config needs it, and restores the system DNS otherwise. /// Sets the placeholder DNS while the running config needs it, and restores the system DNS otherwise.
#[allow(
clippy::significant_drop_tightening,
reason = "the DNS lock covers the state read and is transferred to the script worker"
)]
pub async fn sync_public_dns() { pub async fn sync_public_dns() {
use crate::{ use crate::{
config::Config, config::Config,
core::{CoreManager, handle::Handle, manager::RunningMode}, core::{CoreManager, handle::Handle, manager::RunningMode},
}; };
let _guard = DNS_LOCK.lock().await; let guard = DNS_LOCK.lock().await;
// Exit cleanup restores DNS on its own budget; a sync queued behind it must not undo that. // Exit cleanup restores DNS on its own budget; a sync queued behind it must not undo that.
if Handle::global().is_exiting() { if Handle::global().is_exiting() {
return; return;
@@ -56,20 +60,19 @@ pub async fn sync_public_dns() {
let core_running = !matches!(*CoreManager::global().get_running_mode(), RunningMode::NotRunning); let core_running = !matches!(*CoreManager::global().get_running_mode(), RunningMode::NotRunning);
let runtime = Config::runtime().await.latest_arc(); let runtime = Config::runtime().await.latest_arc();
if core_running && runtime.config.as_ref().is_some_and(needs_public_dns) { if core_running && runtime.config.as_ref().is_some_and(needs_public_dns) {
set_public_dns().await; set_public_dns(guard).await;
} else { } else {
let _ = unset_public_dns().await; let _ = unset_public_dns(guard).await;
} }
} }
pub async fn restore_public_dns() -> anyhow::Result<()> { pub async fn restore_public_dns() -> anyhow::Result<()> {
let _guard = DNS_LOCK.lock().await; unset_public_dns(DNS_LOCK.lock().await).await
unset_public_dns().await
} }
async fn set_public_dns() { async fn set_public_dns(guard: MutexGuard<'static, ()>) {
logging!(debug, Type::Config, "try to set system dns"); logging!(debug, Type::Config, "try to set system dns");
let result = run_dns_script("set_dns.sh", true).await; let result = run_dns_script(DnsScript::Set, guard).await;
match result { match result {
Ok(DnsScriptOutcome::Complete) => logging!(info, Type::Config, "set system dns successfully"), Ok(DnsScriptOutcome::Complete) => logging!(info, Type::Config, "set system dns successfully"),
Ok(DnsScriptOutcome::Deferred) => { Ok(DnsScriptOutcome::Deferred) => {
@@ -79,9 +82,9 @@ async fn set_public_dns() {
} }
} }
async fn unset_public_dns() -> anyhow::Result<()> { async fn unset_public_dns(guard: MutexGuard<'static, ()>) -> anyhow::Result<()> {
logging!(debug, Type::Config, "try to unset system dns"); logging!(debug, Type::Config, "try to unset system dns");
let result = run_dns_script("unset_dns.sh", false).await.map(|_| ()); let result = run_dns_script(DnsScript::Restore, guard).await.map(|_| ());
match &result { match &result {
Ok(()) => logging!(info, Type::Config, "unset system dns successfully"), Ok(()) => logging!(info, Type::Config, "unset system dns successfully"),
Err(err) => logging!(error, Type::Config, "unset system dns failed: {err:#}"), Err(err) => logging!(error, Type::Config, "unset system dns failed: {err:#}"),
@@ -89,13 +92,22 @@ async fn unset_public_dns() -> anyhow::Result<()> {
result result
} }
enum DnsScript {
Set,
Restore,
}
enum DnsScriptOutcome { enum DnsScriptOutcome {
Complete, Complete,
Deferred, Deferred,
} }
/// On timeout the script's whole process group is killed, so no networksetup it started writes late. /// On timeout the script's whole process group is killed, so no networksetup it started writes late.
async fn run_dns_script(script_name: &str, allow_deferred: bool) -> anyhow::Result<DnsScriptOutcome> { async fn run_dns_script(action: DnsScript, guard: MutexGuard<'static, ()>) -> anyhow::Result<DnsScriptOutcome> {
let script_name = match action {
DnsScript::Set => "set_dns.sh",
DnsScript::Restore => "unset_dns.sh",
};
let resource_dir = crate::utils::dirs::app_resources_dir()?; let resource_dir = crate::utils::dirs::app_resources_dir()?;
let script = resource_dir.join(script_name); let script = resource_dir.join(script_name);
let dir = dns_state_dir()?; let dir = dns_state_dir()?;
@@ -111,6 +123,8 @@ async fn run_dns_script(script_name: &str, allow_deferred: bool) -> anyhow::Resu
.spawn() .spawn()
.with_context(|| format!("failed to run {}", script.display()))?; .with_context(|| format!("failed to run {}", script.display()))?;
crate::process::AsyncHandler::spawn_blocking(move || { crate::process::AsyncHandler::spawn_blocking(move || {
// The caller can time out while the child is still running.
let _guard = guard;
let deadline = Instant::now() + DNS_SCRIPT_TIMEOUT; let deadline = Instant::now() + DNS_SCRIPT_TIMEOUT;
let status = loop { let status = loop {
if let Some(status) = child.try_wait()? { if let Some(status) = child.try_wait()? {
@@ -128,7 +142,7 @@ async fn run_dns_script(script_name: &str, allow_deferred: bool) -> anyhow::Resu
pipe.read_to_string(&mut stderr)?; pipe.read_to_string(&mut stderr)?;
} }
// EX_TEMPFAIL is reserved by set_dns.sh for a network service that is not ready. // EX_TEMPFAIL is reserved by set_dns.sh for a network service that is not ready.
if allow_deferred && status.code() == Some(75) { if matches!(action, DnsScript::Set) && status.code() == Some(75) {
return Ok(DnsScriptOutcome::Deferred); return Ok(DnsScriptOutcome::Deferred);
} }
ensure!( ensure!(
+2 -2
View File
@@ -12,7 +12,7 @@ use crate::{
service::{SERVICE_MANAGER, ServiceManager}, service::{SERVICE_MANAGER, ServiceManager},
tray::Tray, tray::Tray,
}, },
core::{auto_backup::AutoBackupManager, lightweight::auto_lightweight_boot}, core::{auto_backup, lightweight::auto_lightweight_boot},
feat, feat,
process::AsyncHandler, process::AsyncHandler,
utils::{init, server, window_manager::WindowManager}, utils::{init, server, window_manager::WindowManager},
@@ -150,7 +150,7 @@ async fn init_auto_lightweight_boot() {
} }
async fn init_auto_backup() { async fn init_auto_backup() {
logging_error!(Type::Setup, AutoBackupManager::global().init().await); auto_backup::init().await;
} }
fn init_silent_updater() { fn init_silent_updater() {
+33 -33
View File
@@ -32,39 +32,39 @@
} }
}, },
"ruleDialog": { "ruleDialog": {
"title": "Add rule…", "title": "Adicionar regra…",
"matchBy": "Match by", "matchBy": "Correspondência por",
"domain": "Domain", "domain": "Domínio",
"unavailable": "Not available", "unavailable": "Indisponível",
"destination": "Add to the prepend rules of “{{name}}”.", "destination": "Adicionar no início das regras de “{{name}}”.",
"newConnections": "New connections will match the updated configuration.", "newConnections": "As novas conexões seguirão a configuração atualizada.",
"processPathHint": "Matches all destinations accessed by processes at this path.", "processPathHint": "Corresponde a todos os destinos acessados por processos neste caminho.",
"processNameHint": "Matches all destinations accessed by processes with this name.", "processNameHint": "Corresponde a todos os destinos acessados por processos com este nome.",
"ruleModeHint": "Rule-based routing takes effect in Rule mode.", "ruleModeHint": "O roteamento por regras funciona no modo Regra.",
"addAndApply": "Add and apply", "addAndApply": "Adicionar e aplicar",
"profileChanged": "The active profile changed. Close this dialog and add the rule again.", "profileChanged": "O perfil ativo mudou. Feche esta janela e adicione a regra novamente.",
"applyFailed": "The rule could not be applied. Your selection has been kept.", "applyFailed": "Não foi possível aplicar a regra. Sua seleção foi mantida.",
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.", "unsupportedValue": "Este valor contém caracteres que não podem ser usados em uma regra rápida.",
"saved": "Rule saved and configuration applied.", "saved": "Regra salva e configuração aplicada.",
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.", "noMetadata": "Esta conexão não tem informações de domínio, processo ou IP para configurar uma regra.",
"noProfile": "No active profile with an editable rule extension is available.", "noProfile": "Não há um perfil ativo com uma extensão de regras editável.",
"entry": "Configure rule…", "entry": "Configurar regra…",
"modifyTitle": "Modify rule", "modifyTitle": "Modificar regra",
"domainScope": "Domain scope", "domainScope": "Escopo do domínio",
"exactDomain": "Only this domain", "exactDomain": "Apenas este domínio",
"allSubdomains": "This domain and all its subdomains", "allSubdomains": "Este domínio e todos os seus subdomínios",
"rootDomain": "Domínio principal e todos os seus subdomínios ({{domain}})", "rootDomain": "Domínio principal e todos os seus subdomínios ({{domain}})",
"policyUnavailable": "This policy is no longer available. Choose another policy.", "policyUnavailable": "Esta política não está mais disponível. Escolha outra.",
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.", "editDestination": "Atualizar a regra existente em “{{name}}”, mantendo sua posição.",
"saveAndApply": "Save and apply", "saveAndApply": "Salvar e aplicar",
"sourceIp": "Source IP", "sourceIp": "IP de origem",
"destinationIp": "Destination IP", "destinationIp": "IP de destino",
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.", "sourceHint": "Corresponde a todas as solicitações deste IP ou sub-rede, inclusive de outros aplicativos. Sem filtro de portas.",
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.", "destinationHint": "Corresponde a este IP de destino ou sub-rede em todos os domínios. Sem filtro de portas.",
"fullPath": "Full path", "fullPath": "Caminho completo",
"connectionHost": "Current connection domain: {{host}}", "connectionHost": "Domínio da conexão atual: {{host}}",
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.", "invalidDomain": "Informe o domínio atual ou um domínio superior com pelo menos dois segmentos.",
"matchingDomain": "Matching domain", "matchingDomain": "Domínio correspondente",
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6." "invalidIp": "Informe um IP e um tamanho de prefixo válidos: 0–32 para IPv4 ou 0–128 para IPv6."
} }
} }