Compare commits

...
Author SHA1 Message Date
renovate[bot] debb722620 chore(deps): update dependency knip to v6.50.0 2026-12-03 01:35:59 +00:00
dependabot[bot]anddependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 9bdd2c0623 build(deps): bump cookie (#8807)
Bumps the cargo group with 1 update in the / directory: [cookie](https://github.com/rwf2/cookie-rs).

Updates `cookie` from 0.18.1 to 0.18.3
- [Changelog](https://github.com/rwf2/cookie-rs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rwf2/cookie-rs/compare/0.18.1...0.18.3)

---
updated-dependencies:
- dependency-name: cookie
  dependency-version: 0.18.3
  dependency-type: indirect
  dependency-group: cargo
...

Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-12-02 16:34:41 +00:00
renovate[bot]Tungliesrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
39fd5e968b chore(deps): update cargo dependencies (#8811)
* test(draft): cover conflict wakeup and busy layer

* chore(deps): update cargo dependencies

---------

Co-authored-by: Tunglies <77394545+Tunglies@users.noreply.github.com>
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-02 13:41:44 +00:00
Tunglies c9223b204b fix(limiter): handle stale clock samples and timestamp overflow
A caller could sample the clock at 1000 ms and pause while another
caller was admitted at 2000 ms. On resuming, the first caller could
load the newer last_run_ms, mistake its stale sample for a clock
rollback, and replace 2000 with 1000. This reopened the 100 ms period
and let another check at 2000 ms pass. Load last_run_ms before sampling
the clock so the stale caller's compare-exchange fails if a newer
admission has changed that value. Preserve sequential clock rollback
behavior and the existing atomic orderings.

The period check also added the period to last_run_ms. A last admission
at u64::MAX - 55 with a 56 ms period overflowed on the next check:
debug builds panicked and release builds wrapped the deadline to zero,
admitting a duplicate timestamp. Compare elapsed time against the
period only after confirming the clock has not moved backward, which
makes the subtraction safe and preserves the exact period boundary.

Enable the stale-sample and overflow regressions, keep the saved
Proptest seed, and add Loom coverage for advancing time and multiple
stale callers plus a deterministic test at u64::MAX.
2026-12-02 21:18:45 +08:00
renovate[bot]renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>❤是纱雾酱哟~
9c3a433979 chore(deps): update agentic workflows to v1.4.5 (#8809)
- Bump actions in `copilot-setup-steps.yml`
- Bump other agentic workflow lockfiles

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
2026-12-02 12:42:22 +00:00
renovate[bot]andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 2943b58ef7 chore(deps): update dependency terser to v5.51.3 [security] (#8810)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-02 10:33:16 +00:00
Tunglies 186ec116fa refactor(frontend): outfox foxact, foxts, and eslint-plugin-sukka (#8808)
* chore(eslint): remove eslint-plugin-sukka

* refactor(frontend): remove foxts and inline local utilities

* refactor(frontend): remove foxact and replace with local hooks

* refactor(proxy): reuse local storage for group preferences
2026-12-02 01:34:55 +00:00
renovate[bot]renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>❤是纱雾酱哟~
87de9bd5bf chore(deps): update github/gh-aw-actions action to v1.4.4 (#8804)
* chore(deps): update github/gh-aw-actions action to v1.4.4

* chore(gh-aw): update agentic workflows to v1.4.4

- Updates workflow tooling and threat detection
- Refreshes generated workflows with the latest compiler, container digests, and GitHub MCP server
- Improves detection activation metadata restoration and prepares detection inputs before reporting or artifacts run

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

---------

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
2026-12-01 18:12:16 +00:00
❤是纱雾酱哟~andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 37ff669436 chore(deps): update dependency tldts to v7.6.4 (#8805)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-01 17:56:26 +00:00
❤是纱雾酱哟~ b45f12a21e chore(deps): upgrade 4 npm dependencies in a batch (#8803)
- Bump eslint from ^10.11.0 to ^10.16.0
- Bump eslint-plugin-import-x from ^4.17.1 to ^4.18.1
- Bump typescript-eslint from ^8.70.0 to ^8.74.0
- Bump vitest from ^5.0.1 to ^5.0.3

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

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


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

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

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

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

- Version bump via `gh aw upgrade`

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

---------

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
2026-11-30 13:58:27 +00:00
Jeferson Araujo b484a8f24c fix(i18n): translate the connection rule dialog to pt-BR (#8771) 2026-11-30 08:30:04 +00:00
46 changed files with 2541 additions and 1951 deletions
+2 -2
View File
@@ -4,8 +4,8 @@
"features": {
"ghcr.io/devcontainers/features/node:2": {
"version": "26.13.1",
"pnpmVersion": "12.23.0"
"version": "26.14.0",
"pnpmVersion": "12.25.1"
},
"ghcr.io/devcontainers/features/rust:1": {
"version": "1.100.1",
+65 -263
View File
@@ -1,275 +1,77 @@
---
name: Agentic Workflows
description: GitHub Agentic Workflows (gh-aw) - Create, debug, and upgrade AI-powered workflows with intelligent prompt routing.
description: Routes GitHub Agentic Workflows tasks to focused authoring, debugging, and reference guidance.
disable-model-invocation: true
---
# GitHub Agentic Workflows Agent
This agent helps you work with **GitHub Agentic Workflows (gh-aw)**, a CLI extension for creating AI-powered workflows in natural language using markdown files.
Dispatch gh-aw tasks to the matching prompt or reference. Load only what the task
needs; follow its instructions and the target repository's `.github/aw/instructions.md`
when present. Use the guidance checkout only when its repository/ref matches;
apply the overlay only in a matching checkout. The target repository's overlay
overrides conflicting guidance. Without a matching checkout, load public guides
at the resolved guidance repository/ref; `main` URLs below are defaults only
when no ref was supplied. Do not create or edit workflows unless requested.
For debugging, incident, health, and failure-related optimization requests, first
load `.github/aw/debug-bootstrap.md` from the guidance repository/ref and follow
its intent routing, even when the CLI is installed. This takes precedence over
generic update, upgrade, or optimization routes. Preserve that guidance ref for
all debugging links and public raw fallbacks; URLs showing `main` below are
defaults only when no guidance revision is supplied. Reuse already-loaded guides.
The intent index is `.github/aw/debug-scenarios.md`; load only the selected
specialized route, not every debugging reference.
## Execution and safety
## Repository Instructions Overlay
Load the target repository's `.github/aw/instructions.md`, if present.
Use `@.github/aw/instructions.md` only in a matching checkout; do not substitute
a guidance-repository overlay.
Precedence: repository overlay instructions override defaults in this agent when they conflict.
- For incident, health, and failure-related optimization requests,
use intent routing before generic update, upgrade, or optimization routes.
First load
[debug-bootstrap.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-bootstrap.md)
from the resolved guidance repository/ref, even when the CLI is installed.
Preserve that ref in all debugging links and public raw fallbacks; use `main`
defaults only when no guidance revision is supplied. Reuse already-loaded guides.
Then load only the selected route in
[.github/aw/debug-scenarios.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-scenarios.md).
- Do not dispatch workflows to obtain evidence. Compile is not execution
authorization. Follow [debug-agentic-workflow.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-agentic-workflow.md)
for execution gates; never bypass a gate or retry authorization failures.
- Use `gh aw` for authoring and compilation; `copilot` is a separate runtime.
Compile Markdown workflows before Actions can execute them.
- Bash is enabled by default; do not restrict commands unnecessarily.
- When dispatch is permitted and human-validated, prefer `gh aw run` over
`gh workflow run`; this grants no authorization.
- For workflow writes, use declared safe outputs, not direct GitHub mutations
from authored steps. Load [safe-outputs.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/safe-outputs.md)
for write behavior and configuration.
- Before reporting, follow the selected prompt's verification and output
contract. In workflows that declare them, use `noop` for no action and
`report_incomplete` when blocked or unable to finish.
- Use only authorized tools and credentials. Never expose secret values.
- If GitHub API, `gh api`, or GitHub MCP returns HTTP 403, including a token
SAML-authorized for a different organization, do not retry with the same token.
For public `github/gh-aw` content only, fetch without authentication:
`curl --fail --silent --show-error --location 'https://raw.githubusercontent.com/github/gh-aw/main/<path>'`.
Preserve the repository-relative path, including `.github/`; never send an Authorization header or token to the raw URL. Apply this fallback to
referenced instructions and `SKILL.md` files. If fetching fails, report that error.
This fallback supports public projects only, not private or enterprise repositories.
## What This Agent Does
This is a **dispatcher agent** that routes your request to the appropriate specialized prompt based on your task:
- **Creating new workflows**: Routes to `create` prompt
- **Updating existing workflows**: Routes to `update` prompt
- **Diagnosis, patching, and active debugging**: Routes to `debug-agentic-workflow` for the local-first strategy, evidence triage and live gates
- **Repository-wide debugging or run analysis**: Routes to `analyzing-runs` for existing-run failure clustering before selecting a workflow; supplied run/failure scope takes precedence
- **Upgrading workflows**: Routes to `upgrade-agentic-workflows` prompt
- **Creating report-generating workflows**: Routes to `report` prompt — consult this whenever the workflow posts status updates, audits, analyses, or any structured output as issues, discussions, or comments
- **Creating shared components**: Routes to `create-shared-agentic-workflow` prompt
- **Fixing Dependabot PRs**: Routes to `dependabot` prompt — use this when Dependabot opens PRs that modify generated manifest files (`.github/workflows/package.json`, `.github/workflows/requirements.txt`, `.github/workflows/go.mod`). Never merge those PRs directly; instead update the source `.md` files and rerun `gh aw compile --dependabot` to bundle all fixes
- **Analyzing test coverage**: Routes to `test-coverage` prompt — consult this whenever the workflow reads, analyzes, or reports on test coverage data from PRs or CI runs
- **Rendering ASCII charts in markdown**: Routes to `asciicharts` guide — consult this whenever the workflow needs compact charts that render reliably in GitHub issues, comments, or discussions
- **CLI commands and triggering workflows**: Routes to `cli-commands` guide — consult this whenever the user asks how to run, compile, debug, or manage workflows from the command line, or when they need the MCP tool equivalent of a `gh aw` command
- **Reducing token consumption / cost optimization**: Routes to `token-optimization` guide — consult this whenever the user asks how to reduce token usage, lower costs, speed up workflows, or measure the impact of prompt changes with experiments
- **Choosing workflow architectures and design patterns**: Routes to `patterns` guide — consult this whenever the user asks for strategy, architecture, operating models, or pattern selection for agentic workflows
- **Git-backed work queues**: Routes to `work-queue` instructions for producers, dispatchers, workers, observers, deployment and recovery
- **Third-party repository setup/configuration**: Routes to `connectors` instructions; inspect editable declarations, normal local/pinned imports, `import-schema`, credential/authentication XML and matching golden consumers. Use `gh aw connector <id> setup --file PATH` for phase-specific credential names/scopes and external acquisition/renewal guidance. Supply exact approved resources and secret names only through `with`; never secret values. Importing enables no capabilities, native methods, write credentials, broad grants or live webhook ingress. Select reads and staged safe outputs separately and derive network hosts from the contract, not a built-in provider catalog. Token acquisition/refresh and provider permissions remain external.
- **Local SDLC issue bootstrap**: Follow `.github/aw/squad.md`.
Workflows may optionally include:
- **Project tracking / monitoring** (GitHub Projects updates, status reporting)
- **Orchestration / coordination** (one workflow assigning agents or dispatching and coordinating other workflows)
## Files This Applies To
- Workflow files: `.github/workflows/*.md` and `.github/workflows/**/*.md`
- Workflow lock files: `.github/workflows/*.lock.yml`
- Shared components: `.github/workflows/shared/*.md`
- Configuration: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/github-agentic-workflows.md`
## Problems This Solves
- **Workflow Creation**: Design secure, validated agentic workflows with proper triggers, tools, and permissions
- **Diagnosis and Patching**: Analyze evidence and produce regression-backed fixes without requiring live runs
- **Active Debugging**: Run bounded edit/test/run/audit loops where permitted, stopping on dispatch 403 responses
- **Version Upgrades**: Migrate workflows to new gh-aw versions, apply codemods, fix breaking changes
- **Component Design**: Create reusable shared workflow components that wrap MCP servers
## How to Use
When you interact with this agent, it will:
1. **Understand your intent** - Determine what kind of task you're trying to accomplish
2. **Route to the right prompt** - Load the specialized prompt file for your task
3. **Execute the task** - Follow the detailed instructions in the loaded prompt
## Available Prompts
> **Note**: The prompt and reference files below are from [`github/gh-aw`](https://github.com/github/gh-aw). Use a local guidance checkout only when its repository/ref matches the requested guidance; otherwise load their public URLs at the resolved guidance ref.
If GitHub API, `gh api`, or GitHub MCP downloads return HTTP 403 (including a token SAML-authorized for a different organization), do not retry with the same token. Fetch the public file without authentication from `https://raw.githubusercontent.com/github/gh-aw/main/<path>` instead, preserving its repository-relative path (including `.github/`). For example: `curl --fail --silent --show-error --location 'https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-agentic-workflow.md'`. Use the same fallback for referenced instructions and `SKILL.md` files; never send an Authorization header or token to the raw URL. If the public download fails, report that error rather than proceeding without the required instructions. This fallback is for public `github/gh-aw` content only, not private or enterprise repositories.
### Create New Workflow
**Load when**: User wants to create a new workflow from scratch, add automation, or design a workflow that doesn't exist yet
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-agentic-workflow.md`
**Use cases**:
- "Create a workflow that triages issues"
- "I need a workflow to label pull requests"
- "Design a weekly research automation"
### Update Existing Workflow
**Load when**: User wants to modify, improve, or refactor an existing workflow
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/update-agentic-workflow.md`
**Use cases**:
- "Add web-fetch tool to the issue-classifier workflow"
- "Update the PR reviewer to use discussions instead of issues"
- "Improve the prompt for the weekly-research workflow"
### Diagnose, Patch, or Debug a Workflow
**Load when**: User needs to investigate, audit, debug, or understand a workflow, troubleshoot issues, analyze logs, or fix errors
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-agentic-workflow.md`
The shared strategy distinguishes diagnosis/patching from permitted active debug
loops using explicit live gates and includes existing-run evidence triage.
For CLI setup or run-URL scoping in a fresh session, first load
`https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-bootstrap.md`; it bootstraps
this same strategy rather than a separate debug procedure.
**Use cases**:
- "Why is this workflow failing?"
- "Analyze the logs for workflow X"
- "Investigate missing tool calls in run #12345"
### Analyze Existing Runs or Repository-Wide Failures
**Load when**: User asks to debug or optimize agentic workflows generally, without a specific run/failure scope
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/analyzing-runs.md`
Start with repository-wide existing-run failure clustering, not an arbitrary
workflow or a request to pick one. Supplied workflow/run/failure scope takes
precedence. Use the shared debugging strategy for subsequent fixes; never
dispatch workflows to obtain evidence.
### Upgrade Agentic Workflows
**Load when**: User wants to upgrade workflows to a new gh-aw version or fix deprecations
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/upgrade-agentic-workflows.md`
**Use cases**:
- "Upgrade all workflows to the latest version"
- "Fix deprecated fields in workflows"
- "Apply breaking changes from the new release"
### Create a Report-Generating Workflow
**Load when**: The workflow being created or updated produces reports — recurring status updates, audit summaries, analyses, or any structured output posted as a GitHub issue, discussion, or comment
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/report.md`
**Use cases**:
- "Create a weekly CI health report"
- "Post a daily security audit to Discussions"
- "Add a status update comment to open PRs"
### Create Shared Agentic Workflow
**Load when**: User wants to create a reusable workflow component or wrap an MCP server
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-shared-agentic-workflow.md`
**Use cases**:
- "Create a shared component for Notion integration"
- "Wrap the Slack MCP server as a reusable component"
- "Design a shared workflow for database queries"
### Fix Dependabot PRs
**Load when**: User needs to close or fix open Dependabot PRs that update dependencies in generated manifest files (`.github/workflows/package.json`, `.github/workflows/requirements.txt`, `.github/workflows/go.mod`)
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/dependabot.md`
**Use cases**:
- "Fix the open Dependabot PRs for npm dependencies"
- "Bundle and close the Dependabot PRs for workflow dependencies"
- "Update @playwright/test to fix the Dependabot PR"
### Analyze Test Coverage
**Load when**: The workflow reads, analyzes, or reports test coverage — whether triggered by a PR, a schedule, or a slash command. Always consult this prompt before designing the coverage data strategy.
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/test-coverage.md`
**Use cases**:
- "Create a workflow that comments coverage on PRs"
- "Analyze coverage trends over time"
- "Add a coverage gate that blocks PRs below a threshold"
### CLI Commands Reference
**Load when**: The user asks how to run, compile, debug, or manage workflows from the command line; needs the MCP tool equivalent of a `gh aw` command; or is in a restricted environment (e.g., Copilot Cloud) without direct CLI access.
**Reference file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/cli-commands.md`
**Use cases**:
- "How do I trigger workflow X on the main branch?"
- "What's the MCP equivalent of `gh aw logs`?"
- "I'm in Copilot Cloud — how do I compile a workflow?"
- "Show me all available gh aw commands"
### Token Consumption Optimization
**Load when**: The user asks how to reduce token usage, lower workflow costs, make a workflow faster or cheaper, or measure the impact of prompt or configuration changes.
**Reference file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/token-optimization.md`
**Use cases**:
- "How do I reduce the token cost of this workflow?"
- "My workflow is too expensive — how do I optimize it?"
- "How do I compare token usage between two runs?"
- "Should I use gh-proxy or the MCP server?"
- "How do I use sub-agents to reduce costs?"
- "How do I measure the impact of a prompt change?"
### Workflow Pattern Selection
**Load when**: The user asks for architecture, strategy, operating model selection, or pattern recommendations for building agentic workflows.
**Reference file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/patterns.md`
**Use cases**:
- "Which pattern should I use for multi-repo rollout?"
- "How should I structure this workflow architecture?"
- "What pattern fits slash-command triage?"
- "Should this be DispatchOps or DailyOps?"
## Instructions
### Work Queue
For queue design, deployment, inspection or recovery, load
`https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/work-queue.md`.
Also load it after the primary create/update/debug/upgrade prompt whenever a
workflow uses `tools.work-queue`. Load linked developer docs and specifications
only when needed; do not substitute lightweight WorkQueueOps backlog guidance
for the Git-backed protocol.
When a user interacts with you:
1. **Identify the task type** from the user's request
2. **Load the appropriate prompt** from the URLs listed above
3. **Follow the loaded prompt's instructions** exactly
4. **If uncertain**, ask clarifying questions to determine the right prompt
## Quick Reference
```bash
# Initialize repository for agentic workflows
gh aw init
# Generate the lock file for a workflow
gh aw compile [workflow-name]
# Only where permitted and human-validated under debug-agentic-workflow.md:
gh aw run <workflow-name> --ref REVIEWED_REF
# Debug workflow runs
gh aw logs [workflow-name] --repo HOST/OWNER/REPO
gh aw audit <run-url> # preserve host/repository and any job/step scope
gh aw compile <workflow-name> --dry-run # first test of workflow changes
# Upgrade workflows
gh aw fix --write
gh aw compile --validate
```
## Key Features of gh-aw
- **Natural Language Workflows**: Write workflows in markdown with YAML frontmatter
- **AI Engine Support**: Copilot, Claude, Codex, or custom engines
- **MCP Server Integration**: Connect to Model Context Protocol servers for tools
- **Safe Outputs**: Structured communication between AI and GitHub API
- **Strict Mode**: Security-first validation and sandboxing
- **Shared Components**: Reusable workflow building blocks
- **Repo Memory**: Persistent git-backed storage for agents
- **Sandboxed Execution**: All workflows run in the Agent Workflow Firewall (AWF) sandbox, enabling full `bash` and `edit` tools by default
## Important Notes
- For complete documentation, load `.github/aw/github-agentic-workflows.md` from the resolved guidance repository/ref.
- Use gh-aw MCP tools only when exposed and authorized; otherwise use available CLI, cached evidence or static source through the CLI/MCP reference.
- Workflows must be compiled to `.lock.yml` files before running in GitHub Actions
- **Bash tools are enabled by default** - Don't restrict bash commands unnecessarily since workflows are sandboxed by the AWF
- Follow security best practices: minimal permissions, explicit network access, no template injection
- **Network configuration**: Use ecosystem identifiers (`node`, `python`, `go`, etc.) or explicit FQDNs in `network.allowed`. Bare shorthands like `npm` or `pypi` are **not** valid. See `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/network.md` for the full list of valid ecosystem identifiers and domain patterns.
- **Single-file output**: When creating a workflow, produce exactly **one** workflow `.md` file. Do not create separate documentation files (architecture docs, runbooks, usage guides, etc.). If documentation is needed, add a brief `## Usage` section inside the workflow file itself.
- **Triggering runs**: Only where permitted and human-validated under `debug-agentic-workflow.md`, prefer `gh aw run <workflow-name>` over `gh workflow run <file>.lock.yml` for workflow resolution, input validation and run-tracking. Use the reviewed remote ref; explicit no-dispatch rules override user requests.
- **CLI commands reference**: For a complete guide on all `gh aw` commands and their MCP tool equivalents (for restricted environments), see `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/cli-commands.md`
- **Creating new workflows**: [create-agentic-workflow.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-agentic-workflow.md)
- **Updating workflows**: [update-agentic-workflow.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/update-agentic-workflow.md)
- **Diagnosing, patching, or debugging a workflow**: use the debugging route above, then [debug-agentic-workflow.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-agentic-workflow.md).
- **Analyzing existing runs or repository-wide failures**: [analyzing-runs.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/analyzing-runs.md). Start with failure clustering; supplied workflow/run scope takes precedence.
- **Upgrading workflows**: [upgrade-agentic-workflows.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/upgrade-agentic-workflows.md)
- **Creating report-generating workflows**: [report.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/report.md)
- **Creating shared components**: [create-shared-agentic-workflow.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-shared-agentic-workflow.md)
- **Fixing Dependabot workflow-manifest PRs**: [dependabot.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/dependabot.md); never merge manifest-only PRs, update source Markdown, and compile with `--dependabot`.
- **Analyzing test coverage**: [test-coverage.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/test-coverage.md)
- **CLI commands or restricted environments**: [cli-commands.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/cli-commands.md). For logs, use `gh aw logs [workflow-name] --repo HOST/OWNER/REPO`.
- **Reducing token use or cost**: [token-optimization.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/token-optimization.md)
- **Selecting workflow architecture or patterns**: [patterns.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/patterns.md)
- **Designing, deploying, inspecting, or recovering work queues**: [work-queue.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/work-queue.md). Also load it after the primary create/update/debug/upgrade prompt when `tools.work-queue` is used.
- **Compact Markdown/ASCII charts**: [asciicharts.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/asciicharts.md) for charts rendered directly in issues or comments.
- **Third-party integrations**: [connectors.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/connectors.md); inspect the selected declaration and its schema/docs. Bind approved resources and secret names only; importing grants no capabilities or credentials.
- **Local SDLC issue bootstrap**: [squad.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/squad.md)
Workflows may optionally include project tracking or coordination; consult the
selected design prompt.
For general workflow authoring, load
[github-agentic-workflows.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/github-agentic-workflows.md).
Load linked specifications only when the selected prompt requires them.
<!-- instruction-prefix-end -->
+38 -13
View File
@@ -5,10 +5,10 @@
"version": "v9.0.0",
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
},
"github/gh-aw-actions/setup@v1.4.1": {
"github/gh-aw-actions/setup@v1.4.5": {
"repo": "github/gh-aw-actions/setup",
"version": "v1.4.1",
"sha": "367d4dc4e89caf85422092845006e4a4a660d926"
"version": "v1.4.5",
"sha": "a83eaf07e756a15e65f669eb32d00787cf5a2569"
}
},
"containers": {
@@ -52,6 +52,11 @@
"digest": "sha256:fef2443688fc8991d995b935963ef82cec704a867d5e53146f13e86819484059",
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.21@sha256:fef2443688fc8991d995b935963ef82cec704a867d5e53146f13e86819484059"
},
"ghcr.io/github/gh-aw-firewall/agent:0.29.22": {
"image": "ghcr.io/github/gh-aw-firewall/agent:0.29.22",
"digest": "sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad",
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"
},
"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13": {
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13",
"digest": "sha256:61f12dcff38eb008b645d87a5541763452f409d9040eb243718764944167b1a2",
@@ -92,6 +97,11 @@
"digest": "sha256:3293e5813a4e51bf1c5a1b22a762a25033d3ccc5f3582acb2572ad68045ce0e7",
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.21@sha256:3293e5813a4e51bf1c5a1b22a762a25033d3ccc5f3582acb2572ad68045ce0e7"
},
"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22": {
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22",
"digest": "sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca",
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"
},
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11": {
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11",
"digest": "sha256:97782bc0d8ff7f80f19ae2fdc5e1668517aa732a6fa077e64b8d3919238496d2",
@@ -112,6 +122,11 @@
"digest": "sha256:facec98ac9b6ce41273f325b78475ef8d11c38842f62fc2ad823937203564cc3",
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.21@sha256:facec98ac9b6ce41273f325b78475ef8d11c38842f62fc2ad823937203564cc3"
},
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22": {
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22",
"digest": "sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7",
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"
},
"ghcr.io/github/gh-aw-firewall/router:0.29.14": {
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.14",
"digest": "sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0",
@@ -127,6 +142,11 @@
"digest": "sha256:681b2ca49f33e3954e5f3824767b3f2d4c747a60272ec303d0be27221531450a",
"pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.21@sha256:681b2ca49f33e3954e5f3824767b3f2d4c747a60272ec303d0be27221531450a"
},
"ghcr.io/github/gh-aw-firewall/router:0.29.22": {
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.22",
"digest": "sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb",
"pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"
},
"ghcr.io/github/gh-aw-firewall/squid:0.28.13": {
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13",
"digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56",
@@ -167,20 +187,25 @@
"digest": "sha256:ccc189ace632f3f42fa2ee1e77feb67d438e0975c591520da3f473c132e6216d",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.21@sha256:ccc189ace632f3f42fa2ee1e77feb67d438e0975c591520da3f473c132e6216d"
},
"ghcr.io/github/gh-aw-mcpg:v0.5.15": {
"image": "ghcr.io/github/gh-aw-mcpg:v0.5.15",
"digest": "sha256:3f6567e6db31d820e43031fa17a745e5a056fd074604192a884ac12a443ff5c1",
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.5.15@sha256:3f6567e6db31d820e43031fa17a745e5a056fd074604192a884ac12a443ff5c1"
"ghcr.io/github/gh-aw-firewall/squid:0.29.22": {
"image": "ghcr.io/github/gh-aw-firewall/squid:0.29.22",
"digest": "sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"
},
"ghcr.io/github/gh-aw-mcpg:v0.5.16": {
"image": "ghcr.io/github/gh-aw-mcpg:v0.5.16",
"digest": "sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059",
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"
},
"ghcr.io/github/gh-aw-node": {
"image": "ghcr.io/github/gh-aw-node",
"digest": "sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc",
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc"
"digest": "sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f",
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f"
},
"ghcr.io/github/github-mcp-server:v2.2.0": {
"image": "ghcr.io/github/github-mcp-server:v2.2.0",
"digest": "sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174",
"pinned_image": "ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174"
"ghcr.io/github/github-mcp-server:v2.3.0": {
"image": "ghcr.io/github/github-mcp-server:v2.3.0",
"digest": "sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6",
"pinned_image": "ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6"
}
}
}
@@ -100,6 +100,7 @@ Use the task routes above first. This inventory is not required startup context.
- `.github/aw/charts.md`
- `.github/aw/cli-commands.md`
- `.github/aw/compat.md`
- `.github/aw/connectors-authoring.md`
- `.github/aw/connectors.md`
- `.github/aw/context.md`
- `.github/aw/create-agentic-workflow-design.md`
@@ -148,6 +149,7 @@ Use the task routes above first. This inventory is not required startup context.
- `.github/aw/maintainer.md`
- `.github/aw/mcp-clis.md`
- `.github/aw/memory-stateful-patterns.md`
- `.github/aw/memory-wiki-comment.md`
- `.github/aw/memory.md`
- `.github/aw/messages.md`
- `.github/aw/multi-agent-research.md`
+5 -5
View File
@@ -51,7 +51,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- name: Install dependencies
run: pnpm install --frozen-lockfile
@@ -182,7 +182,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -262,7 +262,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -395,7 +395,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -479,7 +479,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6.1.1
name: Install pnpm
+1 -1
View File
@@ -63,7 +63,7 @@ jobs:
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
+3 -3
View File
@@ -31,9 +31,9 @@ jobs:
with:
persist-credentials: false
- name: Install gh-aw extension
uses: github/gh-aw-actions/setup-cli@367d4dc4e89caf85422092845006e4a4a660d926 # v1.4.1
uses: github/gh-aw-actions/setup-cli@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5
with:
version: v1.4.1
version: v1.4.5
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@stable
with:
@@ -49,7 +49,7 @@ jobs:
- name: Install Node.js
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Install frontend dependencies
env:
+1 -1
View File
@@ -43,7 +43,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
+1 -1
View File
@@ -104,7 +104,7 @@ jobs:
if: github.event.inputs[matrix.input] == 'true'
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -61,7 +61,7 @@ jobs:
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
if: github.event.action != 'closed'
+8 -8
View File
@@ -46,7 +46,7 @@ jobs:
fetch-depth: 0
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- name: Validate source and publish the approved snapshot
id: source
env:
@@ -231,7 +231,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -330,7 +330,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -461,7 +461,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -542,7 +542,7 @@ jobs:
fetch-depth: 0
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
with:
run_install: false
@@ -565,7 +565,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
@@ -593,7 +593,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
@@ -661,7 +661,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -28,7 +28,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- name: Install pnpm
uses: pnpm/action-setup@v6
+1 -1
View File
@@ -31,7 +31,7 @@ jobs:
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- name: Sync Mihomo version
id: sync
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
+2 -2
View File
@@ -15,7 +15,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
@@ -39,7 +39,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
+2 -2
View File
@@ -1,3 +1,3 @@
nodejs 26.13.1
pnpm 12.23.0
nodejs 26.14.0
pnpm 12.25.1
rust 1.100.1
Generated
+357 -19
View File
@@ -469,9 +469,9 @@ dependencies = [
[[package]]
name = "backon"
version = "1.6.0"
version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cffb0e931875b666fc4fcb20fee52e9bbd1ef836fd9e9e04ec21555f9f85f7ef"
checksum = "aa51bf3329e243b4ceebb25fddaa797b3e2d225c733b215548ffd1fa99294d5d"
dependencies = [
"fastrand",
"gloo-timers",
@@ -514,7 +514,16 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
dependencies = [
"bit-vec",
"bit-vec 0.8.0",
]
[[package]]
name = "bit-set"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c"
dependencies = [
"bit-vec 0.10.2",
]
[[package]]
@@ -523,6 +532,16 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
[[package]]
name = "bit-vec"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0"
dependencies = [
"borsh",
"serde",
]
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -741,6 +760,30 @@ dependencies = [
"static_assertions",
]
[[package]]
name = "borsh"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a"
dependencies = [
"borsh-derive",
"bytes",
"cfg_aliases",
]
[[package]]
name = "borsh-derive"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56"
dependencies = [
"once_cell",
"proc-macro-crate 3.5.0",
"proc-macro2",
"quote",
"syn 3.0.5",
]
[[package]]
name = "brotli"
version = "9.0.0"
@@ -1159,9 +1202,9 @@ dependencies = [
"tristr",
"warp",
"webpki-roots",
"windows 0.62.2",
"windows 0.101.0",
"windows-service",
"windows-sys 0.61.2",
"windows-sys 0.101.0",
"winreg 0.56.0",
"zip",
]
@@ -1187,6 +1230,10 @@ dependencies = [
[[package]]
name = "clash-verge-limiter"
version = "0.1.0"
dependencies = [
"loom",
"proptest",
]
[[package]]
name = "clash-verge-logging"
@@ -1468,9 +1515,9 @@ dependencies = [
[[package]]
name = "cookie"
version = "0.18.1"
version = "0.18.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747"
checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a"
dependencies = [
"percent-encoding",
"time",
@@ -1558,6 +1605,12 @@ dependencies = [
"libc",
]
[[package]]
name = "core_detect"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
[[package]]
name = "core_maths"
version = "0.1.1"
@@ -2127,7 +2180,7 @@ version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc"
dependencies = [
"bit-set",
"bit-set 0.8.0",
"cssparser",
"foldhash 0.2.0",
"html5ever",
@@ -2719,6 +2772,18 @@ dependencies = [
"x11",
]
[[package]]
name = "generator"
version = "0.8.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66831419d9074e766421508dff218bf79d99616bc5e56e34599d3b433714a4a4"
dependencies = [
"libc",
"log",
"windows-core 0.100.0",
"windows-sys 0.61.2",
]
[[package]]
name = "generic-array"
version = "0.14.7"
@@ -2973,9 +3038,9 @@ dependencies = [
[[package]]
name = "gloo-timers"
version = "0.3.0"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994"
checksum = "a4460540da666acdb5722b2a62ac47d18f627fcfc0c728d04dc7226b3f6d40a7"
dependencies = [
"futures-channel",
"futures-core",
@@ -4124,6 +4189,19 @@ version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "loom"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1611ddbf89dc6ae42cfbd51fc207836140130257646eab8d6d2fb16577db2d2"
dependencies = [
"cfg-if",
"generator",
"scoped-tls",
"tracing",
"tracing-subscriber",
]
[[package]]
name = "lru-slab"
version = "0.1.2"
@@ -5528,6 +5606,26 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "proptest"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0"
dependencies = [
"bit-set 0.11.1",
"bit-vec 0.10.2",
"bitflags 2.13.2",
"chacha20",
"core_detect",
"num-traits",
"rand 0.10.2",
"rand_xorshift",
"regex-syntax",
"rusty-fork",
"tempfile",
"unarray",
]
[[package]]
name = "prost"
version = "0.14.4"
@@ -5582,6 +5680,12 @@ version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "quick-error"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
[[package]]
name = "quick-error"
version = "2.0.1"
@@ -5769,6 +5873,15 @@ dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "rand_xorshift"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf"
dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "raw-window-handle"
version = "0.6.2"
@@ -6219,9 +6332,9 @@ dependencies = [
[[package]]
name = "rustls"
version = "0.23.46"
version = "0.23.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
checksum = "4ac0e747c10d93d873fd4c50b26ef47ad92d1bfb48f6922003bb514070f6e88c"
dependencies = [
"aws-lc-rs",
"log",
@@ -6300,6 +6413,18 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "rusty-fork"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"
dependencies = [
"fnv",
"quick-error 1.2.3",
"tempfile",
"wait-timeout",
]
[[package]]
name = "ryu"
version = "1.0.23"
@@ -7145,9 +7270,9 @@ dependencies = [
[[package]]
name = "sysinfo"
version = "0.40.4"
version = "0.40.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e80749408e2d8bec0ffa303012cf4e1b3b355f4a09087b4fdf7473680f6a2de"
checksum = "0ebe31c61260d7bc4bfc204a2d096c428a4c9ef59ca48bfa693d17fec4f129ad"
dependencies = [
"libc",
"memchr",
@@ -8097,7 +8222,7 @@ dependencies = [
"fax",
"flate2",
"half",
"quick-error",
"quick-error 2.0.1",
"weezl",
"zune-jpeg",
]
@@ -8728,6 +8853,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "unarray"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
[[package]]
name = "unicase"
version = "2.9.0"
@@ -8882,6 +9013,15 @@ dependencies = [
"utf8parse",
]
[[package]]
name = "wait-timeout"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
dependencies = [
"libc",
]
[[package]]
name = "walkdir"
version = "2.5.0"
@@ -9317,6 +9457,20 @@ dependencies = [
"windows-numerics 0.3.1",
]
[[package]]
name = "windows"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa86febe1d5f623619e56067e9c6f84c368cf94f9f36df738875a0dc5affd752"
dependencies = [
"windows-collections 0.101.0",
"windows-core 0.101.0",
"windows-future 0.101.0",
"windows-numerics 0.101.0",
"windows-reference",
"windows-time",
]
[[package]]
name = "windows-collections"
version = "0.2.0"
@@ -9335,14 +9489,23 @@ dependencies = [
"windows-core 0.62.2",
]
[[package]]
name = "windows-collections"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c988c3f56b2a0cf740d2837950f25c43539ea6c004a5244085ce6749e1c61f29"
dependencies = [
"windows-core 0.101.0",
]
[[package]]
name = "windows-core"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"
dependencies = [
"windows-implement",
"windows-interface",
"windows-implement 0.60.2",
"windows-interface 0.59.3",
"windows-link 0.1.3",
"windows-result 0.3.4",
"windows-strings 0.4.2",
@@ -9354,13 +9517,39 @@ version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-implement 0.60.2",
"windows-interface 0.59.3",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
name = "windows-core"
version = "0.100.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "803590c6856f51d15fa2e9fabe4f4703122c8737f72ef2741b4ac09d4c2192f5"
dependencies = [
"windows-implement 0.100.0",
"windows-interface 0.100.0",
"windows-link 0.100.0",
"windows-result 0.100.0",
"windows-strings 0.100.0",
]
[[package]]
name = "windows-core"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27abecb0bac0f1602c4e0d0c885aca58e9a2a25d852135b96e4d0f9daf989aac"
dependencies = [
"windows-implement 0.101.0",
"windows-interface 0.101.0",
"windows-link 0.101.0",
"windows-result 0.101.0",
"windows-strings 0.101.0",
]
[[package]]
name = "windows-future"
version = "0.2.1"
@@ -9383,6 +9572,17 @@ dependencies = [
"windows-threading 0.2.1",
]
[[package]]
name = "windows-future"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c1de418ec955682054a08c9a2925719c76af9408397fd89fc7c2418bd3b2551"
dependencies = [
"windows-core 0.101.0",
"windows-link 0.101.0",
"windows-threading 0.101.0",
]
[[package]]
name = "windows-implement"
version = "0.60.2"
@@ -9394,6 +9594,28 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "windows-implement"
version = "0.100.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bc1bc82e5a1b1a4d7255861b07881a0407b552f50a4d8543c0c7276fa96f6e8"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-implement"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33a7f9008fbe08b219a4d9b2db1ceff71b9ed7f0e02472a3bf2046a2b258f933"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
@@ -9405,6 +9627,28 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.100.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3f7005c3b757b9b82c2f40c0e71094ff1080adddaf3e8b6ce99b545d3c48796"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67d1b654cf5aa8120c8c796fe6c88f0e0407512c341e83ea7bb65b933b596474"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-link"
version = "0.1.3"
@@ -9417,6 +9661,18 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-link"
version = "0.100.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b39de7c7fe78858b0144c50c3fc000bab3be17d5e9b85b1053871693c7f7415"
[[package]]
name = "windows-link"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4e57b2aae53a240c62b65069a63eaf8d5fa747f5d0d8e670c5210a98847bce4"
[[package]]
name = "windows-numerics"
version = "0.2.0"
@@ -9437,6 +9693,25 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-numerics"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d54e417b9761be91da0ab663a5e393e9e54820e55fa9a1d902b978bda3a71ba"
dependencies = [
"windows-core 0.101.0",
]
[[package]]
name = "windows-reference"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0a017bb8eab108f37103deaa4eaad24ce324c30c6f72628a59250be24c87466"
dependencies = [
"windows-core 0.101.0",
"windows-time",
]
[[package]]
name = "windows-registry"
version = "0.6.1"
@@ -9466,6 +9741,24 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-result"
version = "0.100.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44873a1ef61c85d5e2991db91fe656cfcf0731097e00dff1ac860f1cb3b752a0"
dependencies = [
"windows-link 0.100.0",
]
[[package]]
name = "windows-result"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a02baed928b12dbc90e3a37d1504af179d275e13427510f6bcded0607c9251a7"
dependencies = [
"windows-link 0.101.0",
]
[[package]]
name = "windows-service"
version = "0.8.1"
@@ -9495,6 +9788,24 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-strings"
version = "0.100.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a70b590c684f1d2854f74999896f7c0558f1bdde62f599088599e20ea1d2f60"
dependencies = [
"windows-link 0.100.0",
]
[[package]]
name = "windows-strings"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3301e29c2a308301e0e84fe4242684b1310864f3e15aba65b4ae41f1a44f7f95"
dependencies = [
"windows-link 0.101.0",
]
[[package]]
name = "windows-sys"
version = "0.45.0"
@@ -9549,6 +9860,15 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-sys"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eed2df9f5f458664c87437f6758f0d93085b06433bf66b2b84c23c19f3d2012c"
dependencies = [
"windows-link 0.101.0",
]
[[package]]
name = "windows-targets"
version = "0.42.2"
@@ -9630,6 +9950,24 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-threading"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e1e41d72a0564ebe2cbb9487ed918acfc71d541683b84816a424dc3c7939592"
dependencies = [
"windows-link 0.101.0",
]
[[package]]
name = "windows-time"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "186ef23b1710095987bf5281bd19e3669934d4353946f24cbdcfd0ed4f2deff6"
dependencies = [
"windows-core 0.101.0",
]
[[package]]
name = "windows-version"
version = "0.1.7"
+6 -1
View File
@@ -68,6 +68,8 @@ tauri-plugin-clipboard-manager = "2.5.0"
parking_lot = "0.13.0"
anyhow = "1.0.105"
futures = "0.3.34"
loom = "0.7.3"
proptest = "1.12.0"
chrono = "0.4.45"
criterion = { version = "0.8.2", features = ["async_tokio"] }
tokio = { version = "1.54.1", features = [
@@ -95,7 +97,7 @@ socket2 = "0.6.5"
# *** For Windows platform only ***
deelevate = "0.2.0"
windows-sys = { version = "0.61.2", features = [
windows-sys = { version = "0.101.0", features = [
"Win32_Foundation",
"Win32_NetworkManagement_IpHelper",
"Win32_Networking_WinSock",
@@ -108,6 +110,9 @@ windows-sys = { version = "0.61.2", features = [
] }
# *********************************
[workspace.lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(loom)'] }
[workspace.lints.clippy]
# fallible_impl_from = "deny" // 过于激进,暂时不开启
# implicit_clone = "deny" // 可能会造成额外开销,暂时不开启
+57 -4
View File
@@ -1,7 +1,14 @@
use std::sync::Arc;
use std::{
pin::pin,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
task::{Context, Poll, Wake, Waker},
};
use clash_verge_draft::{Draft, DraftTransaction};
use tokio::sync::Notify;
use tokio::sync::{Notify, oneshot};
#[derive(Clone, Debug, Default, PartialEq)]
struct Config {
@@ -78,6 +85,47 @@ async fn async_update_rejects_a_changed_committed_value() -> anyhow::Result<()>
Ok(())
}
#[test]
fn parked_async_update_is_woken_after_optimistic_conflict() {
#[derive(Default)]
struct WakeFlag(AtomicBool);
impl Wake for WakeFlag {
fn wake(self: Arc<Self>) {
self.0.store(true, Ordering::Relaxed);
}
}
let draft = Draft::new(1);
let (finish, finished) = oneshot::channel();
let mut owner = pin!(draft.with_data_modify(|value| async move {
finished.await?;
Ok((value + 10, ()))
}));
let mut owner_context = Context::from_waker(Waker::noop());
assert!(owner.as_mut().poll(&mut owner_context).is_pending());
let wake_flag = Arc::new(WakeFlag::default());
let waker = Waker::from(Arc::clone(&wake_flag));
let mut waiter_context = Context::from_waker(&waker);
let mut waiter = pin!(draft.with_data_modify(|value| async move { Ok((value + 1, value)) }));
// The fast retry wakes once before the waiter parks on Notify.
assert!(waiter.as_mut().poll(&mut waiter_context).is_pending());
assert!(wake_flag.0.swap(false, Ordering::Relaxed), "fast retry did not wake");
assert!(waiter.as_mut().poll(&mut waiter_context).is_pending());
assert!(!wake_flag.0.load(Ordering::Relaxed), "waiter did not park");
draft.edit_draft(|value| *value = 7);
draft.apply();
assert!(finish.send(()).is_ok());
assert!(matches!(owner.as_mut().poll(&mut owner_context), Poll::Ready(Err(_))));
assert_eq!(**draft.data_arc(), 7);
assert!(wake_flag.0.load(Ordering::Relaxed), "parked waiter was not notified");
assert!(matches!(waiter.as_mut().poll(&mut waiter_context), Poll::Ready(Ok(7))));
assert_eq!(**draft.data_arc(), 8);
}
#[test]
fn transaction_commits_every_layer() -> anyhow::Result<()> {
let first = Draft::new(1_u8);
@@ -112,10 +160,15 @@ fn dropped_transaction_rolls_every_layer_back() -> anyhow::Result<()> {
#[test]
fn transaction_claims_are_exclusive_and_release_partial_claims() -> anyhow::Result<()> {
let first = Draft::new(1_u8);
let second = Draft::new(2_u8);
let second = Draft::new(2_u16);
let held = DraftTransaction::begin(vec![&second])?;
assert!(DraftTransaction::begin(vec![&first, &second]).is_err());
let busy = DraftTransaction::begin(vec![&first, &second])
.err()
.ok_or_else(|| anyhow::anyhow!("transaction claimed an already-held layer"))?;
let layer = std::any::type_name::<u16>();
assert_eq!(busy.layer, layer);
assert!(busy.to_string().contains(layer));
let available = DraftTransaction::begin(vec![&first])?;
drop(available);
+6
View File
@@ -5,5 +5,11 @@ edition = "2024"
[dependencies]
[dev-dependencies]
proptest = { workspace = true }
[target.'cfg(loom)'.dependencies]
loom = { workspace = true }
[lints]
workspace = true
+43 -6
View File
@@ -1,5 +1,12 @@
#[cfg(loom)]
use loom::sync::Arc;
#[cfg(loom)]
use loom::sync::atomic::AtomicU64;
#[cfg(not(loom))]
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
#[cfg(not(loom))]
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub type SystemLimiter = Limiter<SystemClock>;
@@ -38,6 +45,7 @@ pub struct Limiter<C: Clock = SystemClock> {
}
impl<C: Clock> Limiter<C> {
#[cfg(not(loom))]
pub const fn new(period: Duration, clock: C) -> Self {
Self {
last_run_ms: AtomicU64::new(0),
@@ -46,11 +54,21 @@ impl<C: Clock> Limiter<C> {
}
}
pub fn check(&self) -> bool {
let now = self.clock.now_ms();
let last = self.last_run_ms.load(Ordering::Relaxed);
#[cfg(loom)]
pub fn new(period: Duration, clock: C) -> Self {
Self {
last_run_ms: AtomicU64::new(0),
period_ms: period.as_millis() as u64,
clock,
}
}
if now < last + self.period_ms && now >= last {
pub fn check(&self) -> bool {
// Load before sampling so a stale sample cannot move a newer admission backward.
let last = self.last_run_ms.load(Ordering::Relaxed);
let now = self.clock.now_ms();
if now >= last && now - last < self.period_ms {
return false;
}
@@ -74,6 +92,22 @@ mod tests {
}
}
#[test]
fn system_clock_reports_unix_epoch_milliseconds() {
const MAX_DRIFT_MS: u64 = 5 * 60 * 1_000;
let wall_clock_ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64;
let clock_ms = SystemClock.now_ms();
assert!(
clock_ms.abs_diff(wall_clock_ms) <= MAX_DRIFT_MS,
"SystemClock::now_ms() should return Unix epoch milliseconds, got {clock_ms} while wall clock is {wall_clock_ms}"
);
}
#[test]
fn enforces_the_period_boundary() {
let clock = MockClock(AtomicU64::new(1_000));
@@ -100,7 +134,10 @@ mod tests {
}
let admitted = handles
.into_iter()
.map(|handle| handle.join().unwrap_or(false))
.map(|handle| match handle.join() {
Ok(admitted) => admitted,
Err(panic) => std::panic::resume_unwind(panic),
})
.filter(|passed| *passed)
.count();
+225
View File
@@ -0,0 +1,225 @@
#![cfg(loom)]
use std::sync::atomic::Ordering;
use std::time::Duration;
use clash_verge_limiter::{Clock, Limiter};
use loom::sync::Arc;
use loom::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize};
const PERIOD_MS: u64 = 100;
const START_MS: u64 = 1_000;
struct MockClock(AtomicU64);
impl Clock for MockClock {
fn now_ms(&self) -> u64 {
self.0.load(Ordering::SeqCst)
}
}
type TestLimiter = Limiter<Arc<MockClock>>;
struct AdvancingClock(AtomicU64);
impl Clock for AdvancingClock {
fn now_ms(&self) -> u64 {
self.0.fetch_add(1, Ordering::SeqCst)
}
}
fn limiter_at(now_ms: u64) -> (Arc<MockClock>, Arc<TestLimiter>) {
let clock = Arc::new(MockClock(AtomicU64::new(now_ms)));
let limiter = Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock));
(clock, Arc::new(limiter))
}
fn run_two_concurrent_checks<C: Clock + 'static>(limiter: &Arc<Limiter<C>>) -> usize {
let handles: [_; 2] = std::array::from_fn(|_| {
let limiter = Arc::clone(limiter);
loom::thread::spawn(move || limiter.check())
});
handles
.into_iter()
.map(|handle| match handle.join() {
Ok(admitted) => admitted,
Err(panic) => std::panic::resume_unwind(panic),
})
.filter(|admitted| *admitted)
.count()
}
#[test]
fn admits_exactly_one_caller_in_an_eligible_window() {
loom::model(|| {
let (_clock, limiter) = limiter_at(START_MS);
assert_eq!(run_two_concurrent_checks(&limiter), 1);
});
}
#[test]
fn rejects_concurrent_callers_inside_the_restricted_period() {
loom::model(|| {
let (clock, limiter) = limiter_at(START_MS);
assert!(limiter.check());
clock.0.store(START_MS + PERIOD_MS - 1, Ordering::SeqCst);
assert_eq!(run_two_concurrent_checks(&limiter), 0);
});
}
#[test]
fn admits_exactly_one_caller_at_the_period_boundary() {
loom::model(|| {
let (clock, limiter) = limiter_at(START_MS);
assert!(limiter.check());
clock.0.store(START_MS + PERIOD_MS, Ordering::SeqCst);
assert_eq!(run_two_concurrent_checks(&limiter), 1);
});
}
#[test]
fn concurrent_clock_advancement_admits_exactly_one_caller() {
loom::model(|| {
let clock = Arc::new(AdvancingClock(AtomicU64::new(START_MS)));
let limiter = Arc::new(Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock)));
assert_eq!(run_two_concurrent_checks(&limiter), 1);
});
}
struct StaleClock {
current: AtomicU64,
reads: AtomicUsize,
stale_reads: usize,
sampled: AtomicUsize,
released: AtomicBool,
}
impl StaleClock {
fn new(now_ms: u64, stale_reads: usize) -> Self {
Self {
current: AtomicU64::new(now_ms),
reads: AtomicUsize::new(0),
stale_reads,
sampled: AtomicUsize::new(0),
released: AtomicBool::new(false),
}
}
fn release(&self) {
self.released.store(true, Ordering::SeqCst);
}
}
impl Clock for StaleClock {
fn now_ms(&self) -> u64 {
if self.reads.fetch_add(1, Ordering::SeqCst) < self.stale_reads {
let stale = self.current.load(Ordering::SeqCst);
self.sampled.fetch_add(1, Ordering::SeqCst);
// Parking can wake spuriously; re-check the release flag on each
// wake. Unparking after setting the flag avoids a lost wakeup.
while !self.released.load(Ordering::SeqCst) {
loom::thread::park();
}
stale
} else {
self.current.load(Ordering::SeqCst)
}
}
}
/// Regression: a caller that sampled the clock before a newer admission must
/// not overwrite that admission when it resumes.
#[test]
fn stale_clock_sample_does_not_reopen_the_period() {
loom::model(|| {
const LATER_MS: u64 = START_MS + PERIOD_MS * 10;
let clock = Arc::new(StaleClock::new(START_MS, 1));
let limiter = Arc::new(Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock)));
let stale_caller = {
let limiter = Arc::clone(&limiter);
loom::thread::spawn(move || limiter.check())
};
while clock.sampled.load(Ordering::SeqCst) < 1 {
loom::thread::yield_now();
}
clock.current.store(LATER_MS, Ordering::SeqCst);
let later_caller = {
let limiter = Arc::clone(&limiter);
loom::thread::spawn(move || limiter.check())
};
let later_admitted = later_caller.join().unwrap();
assert!(
later_admitted,
"the later caller must be admitted before the stale caller resumes"
);
clock.release();
stale_caller.thread().unpark();
let stale_admitted = stale_caller.join().unwrap();
let reopened = limiter.check();
assert!(
!stale_admitted,
"stale caller must not be admitted after the later caller"
);
assert!(
!reopened,
"stale caller admitted={stale_admitted} moved last_run_ms from {LATER_MS} back to {START_MS}"
);
});
}
#[test]
fn multiple_stale_clock_samples_cannot_reopen_the_period() {
loom::model(|| {
const LATER_MS: u64 = START_MS + PERIOD_MS * 10;
let clock = Arc::new(StaleClock::new(START_MS, 2));
let limiter = Arc::new(Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock)));
let stale_callers: [_; 2] = std::array::from_fn(|_| {
let limiter = Arc::clone(&limiter);
loom::thread::spawn(move || limiter.check())
});
while clock.sampled.load(Ordering::SeqCst) < 2 {
loom::thread::yield_now();
}
clock.current.store(LATER_MS, Ordering::SeqCst);
assert!(
limiter.check(),
"the later caller must be admitted before the stale callers resume"
);
clock.release();
for caller in &stale_callers {
caller.thread().unpark();
}
let stale_admitted = stale_callers
.into_iter()
.map(|caller| caller.join().unwrap())
.filter(|admitted| *admitted)
.count();
assert_eq!(
stale_admitted, 0,
"stale callers must not be admitted after the later caller"
);
assert!(!limiter.check(), "stale callers reopened the period at {LATER_MS}");
});
}
@@ -0,0 +1,7 @@
# Seeds for failure cases proptest has generated in the past. It is
# automatically read and these particular cases re-run before any
# novel cases are generated.
#
# It is recommended to check this file in to source control so that
# everyone who runs the test benefits from these saved cases.
cc 0139d921e3faaf32821ee0c596b0d495ffc72ce94200b8d5a795883db56305e6 # shrinks to period = 56, start = 18446744073709551560
@@ -0,0 +1,211 @@
#![cfg(not(loom))]
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use clash_verge_limiter::{Clock, Limiter};
use proptest::prelude::*;
use proptest::test_runner::FileFailurePersistence;
const CASES: u32 = 10_000;
const MAX_PERIOD_MS: u64 = 100_000;
const MAX_START_MS: u64 = 1_000_000;
const MAX_DELTA_MS: u64 = 10_000;
/// Returns one clock value per call, in order. The test supplies exactly as
/// many values as the limiter will read.
struct SequenceClock {
values: Vec<u64>,
next: AtomicUsize,
}
impl SequenceClock {
const fn new(values: Vec<u64>) -> Self {
Self {
values,
next: AtomicUsize::new(0),
}
}
}
impl Clock for SequenceClock {
fn now_ms(&self) -> u64 {
let index = self.next.fetch_add(1, Ordering::SeqCst);
self.values[index]
}
}
fn timestamps(start: u64, deltas: &[u64]) -> Vec<u64> {
let mut now = start;
let mut values = Vec::with_capacity(deltas.len() + 1);
values.push(now);
for delta in deltas {
now += delta;
values.push(now);
}
values
}
proptest! {
#![proptest_config(ProptestConfig {
cases: CASES,
failure_persistence: Some(Box::new(FileFailurePersistence::Direct(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/properties.proptest-regressions"
)))),
..ProptestConfig::default()
})]
/// For positive periods and nondecreasing time, admission is equivalent to
/// reaching the next allowed timestamp after the previous admission.
#[test]
fn sequential_results_match_the_next_allowed_time_contract(
period in 1u64..=MAX_PERIOD_MS,
start in MAX_PERIOD_MS..=MAX_START_MS,
deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64),
) {
let times = timestamps(start, &deltas);
let clock = SequenceClock::new(times.clone());
let limiter = Limiter::new(Duration::from_millis(period), &clock);
let mut last_admitted = None;
for now in times {
let expected = match last_admitted {
None => true,
Some(last) => now >= last + period,
};
let actual = limiter.check();
prop_assert!(
actual == expected,
"period={} now={} last={:?}",
period,
now,
last_admitted
);
if actual {
last_admitted = Some(now);
}
}
}
/// An admission at the period boundary is accepted, while a repeated or
/// pre-boundary check is rejected.
#[test]
fn period_boundary_and_repeated_checks_follow_the_period(
period in 1u64..=MAX_PERIOD_MS,
start in MAX_PERIOD_MS..=MAX_START_MS,
) {
let boundary = start + period;
let clock = SequenceClock::new(vec![start, start, boundary - 1, boundary]);
let limiter = Limiter::new(Duration::from_millis(period), &clock);
prop_assert!(limiter.check(), "first check at {}", start);
prop_assert!(!limiter.check(), "repeated check at {}", start);
prop_assert!(!limiter.check(), "pre-boundary check at {}", boundary - 1);
prop_assert!(limiter.check(), "boundary check at {}", boundary);
}
/// Any two admitted timestamps in a monotonic sequence are separated by at
/// least one configured period.
#[test]
fn admitted_timestamps_are_at_least_one_period_apart(
period in 1u64..=MAX_PERIOD_MS,
start in MAX_PERIOD_MS..=MAX_START_MS,
deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64),
) {
let times = timestamps(start, &deltas);
let clock = SequenceClock::new(times.clone());
let limiter = Limiter::new(Duration::from_millis(period), &clock);
let mut admitted = Vec::new();
for now in times {
if limiter.check() {
admitted.push(now);
}
}
for pair in admitted.windows(2) {
prop_assert!(
pair[1] - pair[0] >= period,
"period={} admitted pair={:?}",
period,
pair
);
}
}
/// A rejected duplicate at the current admission timestamp must not change
/// the outcomes of later checks.
#[test]
fn rejected_checks_do_not_change_future_admissions(
period in 1u64..=MAX_PERIOD_MS,
start in MAX_PERIOD_MS..=MAX_START_MS,
deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64),
) {
let base_times = timestamps(start, &deltas);
let base_clock = SequenceClock::new(base_times.clone());
let base = Limiter::new(Duration::from_millis(period), &base_clock);
let base_results: Vec<bool> = base_times.iter().map(|_| base.check()).collect();
let mut repeated_times = vec![start, start];
repeated_times.extend_from_slice(&base_times[1..]);
let repeated_len = repeated_times.len();
let repeated_clock = SequenceClock::new(repeated_times);
let repeated = Limiter::new(Duration::from_millis(period), &repeated_clock);
let repeated_results: Vec<bool> = (0..repeated_len).map(|_| repeated.check()).collect();
prop_assert!(repeated_results[0]);
prop_assert!(!repeated_results[1]);
prop_assert_eq!(&base_results[1..], &repeated_results[2..]);
}
/// Every sub-millisecond period is represented as zero milliseconds, so it
/// must produce the same admissions as `Duration::ZERO`. This deliberately
/// does not assert a policy for zero periods.
#[test]
fn zero_and_submillisecond_periods_are_equivalent(
nanos in 0u64..1_000_000,
start in 0u64..=MAX_START_MS,
deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64),
) {
let times = timestamps(start, &deltas);
let zero_clock = SequenceClock::new(times.clone());
let zero = Limiter::new(Duration::ZERO, &zero_clock);
let submillisecond_clock = SequenceClock::new(times.clone());
let submillisecond =
Limiter::new(Duration::from_nanos(nanos), &submillisecond_clock);
for now in times {
prop_assert_eq!(
zero.check(),
submillisecond.check(),
"nanos={} now={}",
nanos,
now
);
}
}
/// Regression: timestamp arithmetic must not overflow near `u64::MAX`.
#[test]
fn extreme_timestamp_and_period_do_not_overflow(
period in 1u64..=1_000,
start in (u64::MAX - 1_000)..=u64::MAX,
) {
let clock = SequenceClock::new(vec![start, start]);
let limiter = Limiter::new(Duration::from_millis(period), &clock);
prop_assert!(limiter.check());
prop_assert!(!limiter.check());
}
}
#[test]
fn max_timestamp_boundary_does_not_overflow() {
let clock = SequenceClock::new(vec![u64::MAX - 1, u64::MAX, u64::MAX]);
let limiter = Limiter::new(Duration::from_millis(1), &clock);
assert!(limiter.check());
assert!(limiter.check());
assert!(!limiter.check());
}
@@ -12,7 +12,7 @@ parking_lot = { workspace = true }
serde = { workspace = true, features = ["derive"] }
# sysinfo 0.38.2 conflicts with dark-light
# see https://github.com/GuillaumeGomez/sysinfo/issues/1623
sysinfo = { version = "0.40.4", default-features = false, features = ["network", "system"] }
sysinfo = { version = "0.40.5", default-features = false, features = ["network", "system"] }
[target.'cfg(not(windows))'.dependencies]
libc = "0.2.191"
-3
View File
@@ -7,7 +7,6 @@ import pluginImportX from 'eslint-plugin-import-x'
import pluginReactCompiler from 'eslint-plugin-react-compiler'
import pluginReactHooks from 'eslint-plugin-react-hooks'
import pluginReactRefresh from 'eslint-plugin-react-refresh'
import PluginSukka from 'eslint-plugin-sukka'
import pluginUnusedImports from 'eslint-plugin-unused-imports'
import globals from 'globals'
import tseslint from 'typescript-eslint'
@@ -112,7 +111,6 @@ export default defineConfig([
'import-x': pluginImportX,
'react-refresh': pluginReactRefresh,
'unused-imports': pluginUnusedImports,
sukka: PluginSukka,
},
extends: [
@@ -182,7 +180,6 @@ export default defineConfig([
'@eslint-react/no-unused-class-component-members': 'error',
'@eslint-react/no-unused-state': 'error',
'@eslint-react/jsx-no-useless-fragment': 'warn',
'sukka/react-prefer-destructuring-assignment': 'warn',
// TypeScript
'@typescript-eslint/no-explicit-any': 'off',
+7 -10
View File
@@ -57,8 +57,6 @@
"ahooks": "^3.10.0",
"cidr-block": "^2.3.0",
"dayjs": "1.11.23",
"foxact": "^0.3.12",
"foxts": "^5.9.1",
"i18next": "^27.0.0",
"js-yaml": "^5.4.2",
"lodash-es": "^4.18.1",
@@ -78,7 +76,7 @@
"rehype-sanitize": "^6.0.0",
"swr": "^2.5.1",
"tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#main",
"tldts": "7.6.2",
"tldts": "7.6.4",
"types-pac": "^1.0.3",
"validator": "^13.15.35"
},
@@ -100,30 +98,29 @@
"cli-color": "^2.0.4",
"commander": "^15.0.0",
"cross-env": "^10.1.0",
"eslint": "^10.11.0",
"eslint": "^10.16.0",
"eslint-import-resolver-typescript": "^4.4.5",
"eslint-plugin-es-x": "^10.0.1",
"eslint-plugin-import-x": "^4.17.1",
"eslint-plugin-import-x": "^4.18.1",
"eslint-plugin-react-compiler": "19.1.0-rc.2",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.7",
"eslint-plugin-sukka": "^10.2.0",
"eslint-plugin-unused-imports": "^4.4.1",
"globals": "^17.12.0",
"https-proxy-agent": "^9.1.0",
"husky": "^9.1.7",
"jiti": "^2.7.0",
"knip": "6.49.0",
"knip": "6.50.0",
"lint-staged": "^17.5.1",
"sass": "^1.104.1",
"tar": "^8.0.0",
"terser": "^5.51.2",
"tsrs": "0.20.0-ts7.1.0-beta",
"typescript": "^6.0.3",
"typescript-eslint": "^8.70.0",
"typescript-eslint": "^8.74.0",
"vite": "^8.3.0",
"vite-plugin-svgr": "^5.2.0",
"vitest": "^5.0.1"
"vitest": "^5.0.3"
},
"lint-staged": {
"*.{ts,tsx,js,mjs}": [
@@ -135,5 +132,5 @@
]
},
"type": "module",
"packageManager": "pnpm@12.23.0"
"packageManager": "pnpm@12.25.1"
}
+840 -1171
View File
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -86,7 +86,7 @@ getrandom = "0.4.3"
futures = { workspace = true }
gethostname = "1.1.0"
tauri-plugin-notification = "2.8.1"
backon = { version = "1.6.0", features = ["tokio-sleep"] }
backon = { version = "1.7.0", features = ["tokio-sleep"] }
tauri-plugin-http = "2.9.0"
tracing = { workspace = true }
tauri-plugin-devtools = { version = "2.2.3", optional = true }
@@ -97,7 +97,7 @@ clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verg
] }
arc-swap = "1.9.5"
tokio-rustls = "0.26.6"
rustls = { version = "0.23.46", features = ["ring"] }
rustls = { version = "0.23.47", features = ["ring"] }
webpki-roots = "1.0.12"
dark-light = "3.0.0"
bytes = "1.12.2"
@@ -143,7 +143,7 @@ quick-xml = "0.42.0"
runas = "=1.2.0"
winreg = "0.56.0"
windows-service = "0.8.1"
windows = { version = "0.62.2", features = [
windows = { version = "0.101.0", features = [
"Win32_System_Com",
"Win32_System_Ole",
"Win32_System_TaskScheduler",
+20 -28
View File
@@ -1,5 +1,4 @@
import { useTheme } from '@mui/material/styles'
import { useLocalStorage } from 'foxact/use-local-storage'
import {
memo,
useCallback,
@@ -13,6 +12,8 @@ import {
} from 'react'
import { useTranslation } from 'react-i18next'
import { useLocalStorage } from '@/hooks/use-local-storage'
import {
ConnectionColumnManager,
type ConnectionColumnOption,
@@ -62,6 +63,19 @@ type ColumnField =
type ColumnSizingState = Record<string, number>
type VisibilityState = Record<string, boolean>
const EMPTY_RECORD = {}
const EMPTY_COLUMN_ORDER: string[] = []
const parseColumnVisibility = (value: string): VisibilityState => {
const parsed = JSON.parse(value)
return parsed && typeof parsed === 'object' ? parsed : EMPTY_RECORD
}
const parseColumnOrder = (value: string): string[] => {
const parsed = JSON.parse(value)
return Array.isArray(parsed) ? parsed : EMPTY_COLUMN_ORDER
}
interface BaseColumn {
field: ColumnField
headerName: string
@@ -368,42 +382,20 @@ export const ConnectionTable = (props: Props) => {
const theme = useTheme()
const [columnWidths, setColumnWidths] = useLocalStorage<ColumnSizingState>(
'connection-table-widths',
{},
EMPTY_RECORD,
)
const [columnVisibilityModel, setColumnVisibilityModel] =
useLocalStorage<VisibilityState>(
'connection-table-visibility',
{},
{
serializer: JSON.stringify,
deserializer: (value) => {
try {
const parsed = JSON.parse(value)
if (parsed && typeof parsed === 'object') return parsed
} catch (err) {
console.warn('Failed to parse connection-table-visibility', err)
}
return {}
},
},
EMPTY_RECORD,
parseColumnVisibility,
)
const [columnOrder, setColumnOrder] = useLocalStorage<string[]>(
'connection-table-order',
[],
{
serializer: JSON.stringify,
deserializer: (value) => {
try {
const parsed = JSON.parse(value)
if (Array.isArray(parsed)) return parsed
} catch (err) {
console.warn('Failed to parse connection-table-order', err)
}
return []
},
},
EMPTY_COLUMN_ORDER,
parseColumnOrder,
)
const baseColumns = useMemo<BaseColumn[]>(() => {
+1 -1
View File
@@ -1,5 +1,5 @@
import { Box, Typography, alpha, useTheme } from '@mui/material'
import React, { forwardRef, ReactNode } from 'react'
import { forwardRef, ReactNode } from 'react'
// 自定义卡片组件接口
interface EnhancedCardProps {
+22 -16
View File
@@ -14,20 +14,18 @@ import {
Typography,
} from '@mui/material'
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow'
import { useEffect } from 'foxact/use-abortable-effect'
import { useIntersection } from 'foxact/use-intersection'
import { useLocalStorage } from 'foxact/use-local-storage'
import type { XOR } from 'foxts/ts-xor'
import {
forwardRef,
memo,
useCallback,
useEffect,
useEffectEvent,
useMemo,
useState,
} from 'react'
import { useTranslation } from 'react-i18next'
import { useLocalStorage } from '@/hooks/use-local-storage'
import { getIpInfo } from '@/services/api'
import { useQuery } from '@/services/query-client'
import getSystem from '@/utils/get-system'
@@ -72,15 +70,14 @@ const getCountryFlag = (countryCode: string | undefined) => {
return String.fromCodePoint(...codePoints)
}
type CountDownState = XOR<
{
type: 'countdown'
remainingSeconds: number
},
{
type: 'revalidating'
}
>
type CountDownState =
| {
type: 'countdown'
remainingSeconds: number
}
| {
type: 'revalidating'
}
const IPInfoCardContainer = forwardRef<HTMLElement, React.PropsWithChildren>(
({ children }, ref) => {
@@ -114,10 +111,19 @@ export const IpInfoCard = () => {
)
const appWindow = useMemo(() => getCurrentWebviewWindow(), [])
const [hasIntersected, setHasIntersected] = useState(false)
// Once intersected, the card stays eligible for refresh until unmount.
const [containerRef, hasIntersected, _resetIntersected] = useIntersection({
rootMargin: '0px',
})
const containerRef = useCallback((element: HTMLElement | null) => {
if (!element) return
const observer = new IntersectionObserver((entries) => {
if (entries.some((e) => e.isIntersecting || e.intersectionRatio > 0)) {
setHasIntersected(true)
observer.disconnect()
}
})
observer.observe(element)
return () => observer.disconnect()
}, [])
const [countdown, setCountdown] = useState<CountDownState>({
type: 'countdown',
@@ -19,10 +19,6 @@ import {
styled,
} from '@mui/material'
import { useLockFn } from 'ahooks'
import {
cancelIdleCallback,
requestIdleCallback,
} from 'foxact/request-idle-callback'
import * as yaml from 'js-yaml'
import {
startTransition,
@@ -350,10 +346,12 @@ export const GroupsEditorViewer = (props: Props) => {
}
}
const handle = requestIdleCallback(serialize)
return () => {
cancelIdleCallback(handle)
if (typeof window.requestIdleCallback === 'function') {
const handle = window.requestIdleCallback(serialize)
return () => window.cancelIdleCallback(handle)
}
const handle = window.setTimeout(serialize, 1)
return () => window.clearTimeout(handle)
}
}, [prependSeq, appendSeq, deleteSeq])
+50 -57
View File
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useReducer } from 'react'
import { useCallback, useEffect, useState } from 'react'
import { useLocalStorage } from '@/hooks/use-local-storage'
import { useProfiles } from '@/hooks/use-profiles'
import { ProxySortType } from './use-filter-sort'
@@ -16,9 +17,13 @@ export interface HeadState {
testUrl: string
}
type HeadStateStorage = Record<string, Record<string, HeadState>>
type ProfileHeadState = Record<string, HeadState>
type HeadStateStorage = Record<string, ProfileHeadState>
const HEAD_STATE_KEY = 'proxy-head-state'
const EMPTY_STORAGE: HeadStateStorage = {}
const EMPTY_PROFILE: ProfileHeadState = {}
export const DEFAULT_STATE: HeadState = {
open: false,
showType: true,
@@ -31,77 +36,65 @@ export const DEFAULT_STATE: HeadState = {
testUrl: '',
}
type HeadStateAction =
| { type: 'reset' }
| { type: 'replace'; payload: Record<string, HeadState> }
| { type: 'update'; groupName: string; patch: Partial<HeadState> }
const parseStorage = (raw: string): HeadStateStorage => {
const value = JSON.parse(raw) as HeadStateStorage | null
return value && typeof value === 'object' && !Array.isArray(value)
? value
: EMPTY_STORAGE
}
function headStateReducer(
state: Record<string, HeadState>,
action: HeadStateAction,
): Record<string, HeadState> {
switch (action.type) {
case 'reset':
return {}
case 'replace':
return action.payload
case 'update': {
const prev = state[action.groupName] || DEFAULT_STATE
return { ...state, [action.groupName]: { ...prev, ...action.patch } }
}
default:
return state
}
const getProfileState = (storage: HeadStateStorage, profile: string) => {
const state = storage[profile]
return state && typeof state === 'object' && !Array.isArray(state)
? state
: EMPTY_PROFILE
}
export function useHeadStateNew() {
const { profiles } = useProfiles()
const current = profiles?.current || ''
const [state, dispatch] = useReducer(headStateReducer, {})
useEffect(() => {
try {
const data = JSON.parse(
localStorage.getItem(HEAD_STATE_KEY)!,
) as HeadStateStorage
const value = data[current] || {}
if (value && typeof value === 'object') {
dispatch({ type: 'replace', payload: value })
} else {
dispatch({ type: 'reset' })
}
} catch {
dispatch({ type: 'reset' })
}
}, [current])
const [storage, setStorage] = useLocalStorage(
HEAD_STATE_KEY,
EMPTY_STORAGE,
parseStorage,
)
const saved = getProfileState(storage, current)
// The active profile owns its live state even if persistence fails.
const [state, setState] = useState(() => ({
profile: { id: current, initialGroups: saved },
groups: saved,
}))
const { profile, groups } = state
if (profile.id !== current) {
setState({ profile: { id: current, initialGroups: saved }, groups: saved })
}
useEffect(() => {
if (groups === profile.initialGroups) return
const timer = setTimeout(() => {
try {
const item = localStorage.getItem(HEAD_STATE_KEY)
let data = (item ? JSON.parse(item) : {}) as HeadStateStorage
if (!data || typeof data !== 'object') data = {}
data[current] = state
localStorage.setItem(HEAD_STATE_KEY, JSON.stringify(data))
} catch {}
setStorage((previous) => ({
...previous,
[profile.id]: groups,
}))
})
return () => clearTimeout(timer)
}, [state, current])
}, [groups, profile, setStorage])
const setHeadState = useCallback(
(groupName: string, obj: Partial<HeadState>) => {
dispatch({ type: 'update', groupName, patch: obj })
(groupName: string, patch: Partial<HeadState>) => {
setState((previous) => {
if (previous.profile !== profile) return previous
const group = previous.groups[groupName] ?? DEFAULT_STATE
return {
profile,
groups: { ...previous.groups, [groupName]: { ...group, ...patch } },
}
})
},
[],
[profile],
)
return [state, setHeadState] as const
return [groups, setHeadState] as const
}
+2 -5
View File
@@ -1,4 +1,4 @@
import { useLocalStorage } from 'foxact/use-local-storage'
import { useLocalStorage } from './use-local-storage'
const defaultClashLog: IClashLog = {
enable: true,
@@ -8,7 +8,4 @@ const defaultClashLog: IClashLog = {
}
export const useClashLog = () =>
useLocalStorage<IClashLog>('clash-log', defaultClashLog, {
serializer: JSON.stringify,
deserializer: JSON.parse,
})
useLocalStorage<IClashLog>('clash-log', defaultClashLog)
+1 -5
View File
@@ -1,4 +1,4 @@
import { useLocalStorage } from 'foxact/use-local-storage'
import { useLocalStorage } from './use-local-storage'
const defaultConnectionSetting: IConnectionSetting = { layout: 'table' }
@@ -6,8 +6,4 @@ export const useConnectionSetting = () =>
useLocalStorage<IConnectionSetting>(
'connections-setting',
defaultConnectionSetting,
{
serializer: JSON.stringify,
deserializer: JSON.parse,
},
)
+21 -20
View File
@@ -1,6 +1,5 @@
/* eslint-disable @eslint-react/set-state-in-effect */
import { useEffect } from 'foxact/use-abortable-effect'
import { useCallback, useState } from 'react'
import { useCallback, useEffect, useState } from 'react'
import { showNotice } from '@/services/notice-service'
@@ -42,26 +41,28 @@ export const useEditorDocument = ({ open, load }: UseEditorDocumentOptions) => {
}
}, [applyLoadedValue, load])
useEffect(
(signal) => {
resetDocumentState()
useEffect(() => {
let cancelled = false
resetDocumentState()
if (!open) return
if (!open) return
load()
.then((nextValue) => {
if (signal.aborted) return
applyLoadedValue(nextValue)
})
.catch((error) => {
if (!signal.aborted) showNotice.error(error)
})
.finally(() => {
if (!signal.aborted) setLoading(false)
})
},
[applyLoadedValue, load, open, resetDocumentState],
)
load()
.then((nextValue) => {
if (cancelled) return
applyLoadedValue(nextValue)
})
.catch((error) => {
if (!cancelled) showNotice.error(error)
})
.finally(() => {
if (!cancelled) setLoading(false)
})
return () => {
cancelled = true
}
}, [applyLoadedValue, load, open, resetDocumentState])
const markSaved = useCallback((nextValue: string) => {
setSavedValue(nextValue)
+148
View File
@@ -0,0 +1,148 @@
import { useCallback, useMemo, useSyncExternalStore } from 'react'
interface StorageEntry {
listeners: Set<() => void>
raw: string | null
parsedRaw: string | null
parsed: unknown
deserializer?: (value: string) => unknown
}
const entries = new Map<string, StorageEntry>()
const readRaw = (key: string): string | null => {
try {
return window.localStorage.getItem(key)
} catch (error) {
console.warn(`[useLocalStorage] Failed to read "${key}"`, error)
return null
}
}
const getRaw = (key: string): string | null => {
const entry = entries.get(key)
return entry ? entry.raw : readRaw(key)
}
const handleStorageEvent = (event: StorageEvent) => {
if (event.storageArea !== window.localStorage) return
if (event.key === null) {
entries.forEach((entry) => {
entry.raw = null
entry.parsedRaw = null
entry.parsed = undefined
entry.listeners.forEach((listener) => listener())
})
return
}
const entry = entries.get(event.key)
if (!entry) return
entry.raw = event.newValue
entry.parsedRaw = null
entry.parsed = undefined
entry.listeners.forEach((listener) => listener())
}
const subscribeKey = (key: string, listener: () => void) => {
if (entries.size === 0) {
window.addEventListener('storage', handleStorageEvent)
}
let entry = entries.get(key)
if (!entry) {
entry = {
listeners: new Set(),
raw: readRaw(key),
parsedRaw: null,
parsed: undefined,
}
entries.set(key, entry)
}
entry.listeners.add(listener)
return () => {
const current = entries.get(key)
if (current) {
current.listeners.delete(listener)
if (current.listeners.size === 0) entries.delete(key)
}
if (entries.size === 0) {
window.removeEventListener('storage', handleStorageEvent)
}
}
}
const parseRaw = <T>(
key: string,
raw: string | null,
defaultValue: T,
deserializer: (value: string) => T,
): T => {
if (raw === null) return defaultValue
const entry = entries.get(key)
if (entry && entry.parsedRaw === raw && entry.deserializer === deserializer) {
return entry.parsed as T
}
try {
const value = deserializer(raw)
if (entry) {
entry.parsedRaw = raw
entry.parsed = value
entry.deserializer = deserializer
}
return value
} catch (error) {
console.warn(`[useLocalStorage] Failed to deserialize "${key}"`, error)
return defaultValue
}
}
export const useLocalStorage = <T>(
key: string,
defaultValue: T,
deserializer: (value: string) => T = JSON.parse,
): [T, (value: T | ((prev: T) => T)) => void] => {
const subscribe = useCallback(
(listener: () => void) => subscribeKey(key, listener),
[key],
)
const raw = useSyncExternalStore(subscribe, () => getRaw(key))
const value = useMemo<T>(
() => parseRaw(key, raw, defaultValue, deserializer),
[key, raw, defaultValue, deserializer],
)
const setValue = useCallback(
(next: T | ((prev: T) => T)) => {
try {
const entry = entries.get(key)
const currentRaw = entry ? entry.raw : readRaw(key)
const resolved =
typeof next === 'function'
? (next as (prev: T) => T)(
parseRaw(key, currentRaw, defaultValue, deserializer),
)
: next
const serialized = JSON.stringify(resolved)
if (currentRaw === serialized) return
window.localStorage.setItem(key, serialized)
if (entry) {
entry.raw = serialized
entry.parsedRaw = null
entry.parsed = undefined
entry.listeners.forEach((listener) => listener())
}
} catch (error) {
console.warn(`[useLocalStorage] Failed to write "${key}"`, error)
}
},
[key, defaultValue, deserializer],
)
return [value, setValue]
}
+33 -33
View File
@@ -32,39 +32,39 @@
}
},
"ruleDialog": {
"title": "Add rule…",
"matchBy": "Match by",
"domain": "Domain",
"unavailable": "Not available",
"destination": "Add to the prepend rules of “{{name}}”.",
"newConnections": "New connections will match the updated configuration.",
"processPathHint": "Matches all destinations accessed by processes at this path.",
"processNameHint": "Matches all destinations accessed by processes with this name.",
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
"addAndApply": "Add and apply",
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
"applyFailed": "The rule could not be applied. Your selection has been kept.",
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
"saved": "Rule saved and configuration applied.",
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
"noProfile": "No active profile with an editable rule extension is available.",
"entry": "Configure rule…",
"modifyTitle": "Modify rule",
"domainScope": "Domain scope",
"exactDomain": "Only this domain",
"allSubdomains": "This domain and all its subdomains",
"title": "Adicionar regra…",
"matchBy": "Correspondência por",
"domain": "Domínio",
"unavailable": "Indisponível",
"destination": "Adicionar no início das regras de “{{name}}”.",
"newConnections": "As novas conexões seguirão a configuração atualizada.",
"processPathHint": "Corresponde a todos os destinos acessados por processos neste caminho.",
"processNameHint": "Corresponde a todos os destinos acessados por processos com este nome.",
"ruleModeHint": "O roteamento por regras funciona no modo Regra.",
"addAndApply": "Adicionar e aplicar",
"profileChanged": "O perfil ativo mudou. Feche esta janela e adicione a regra novamente.",
"applyFailed": "Não foi possível aplicar a regra. Sua seleção foi mantida.",
"unsupportedValue": "Este valor contém caracteres que não podem ser usados em uma regra rápida.",
"saved": "Regra salva e configuração aplicada.",
"noMetadata": "Esta conexão não tem informações de domínio, processo ou IP para configurar uma regra.",
"noProfile": "Não há um perfil ativo com uma extensão de regras editável.",
"entry": "Configurar regra…",
"modifyTitle": "Modificar regra",
"domainScope": "Escopo do domínio",
"exactDomain": "Apenas este domínio",
"allSubdomains": "Este domínio e todos os seus subdomínios",
"rootDomain": "Domínio principal e todos os seus subdomínios ({{domain}})",
"policyUnavailable": "This policy is no longer available. Choose another policy.",
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
"saveAndApply": "Save and apply",
"sourceIp": "Source IP",
"destinationIp": "Destination IP",
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
"fullPath": "Full path",
"connectionHost": "Current connection domain: {{host}}",
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
"matchingDomain": "Matching domain",
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
"policyUnavailable": "Esta política não está mais disponível. Escolha outra.",
"editDestination": "Atualizar a regra existente em “{{name}}”, mantendo sua posição.",
"saveAndApply": "Salvar e aplicar",
"sourceIp": "IP de origem",
"destinationIp": "IP de destino",
"sourceHint": "Corresponde a todas as solicitações deste IP ou sub-rede, inclusive de outros aplicativos. Sem filtro de portas.",
"destinationHint": "Corresponde a este IP de destino ou sub-rede em todos os domínios. Sem filtro de portas.",
"fullPath": "Caminho completo",
"connectionHost": "Domínio da conexão atual: {{host}}",
"invalidDomain": "Informe o domínio atual ou um domínio superior com pelo menos dois segmentos.",
"matchingDomain": "Domínio correspondente",
"invalidIp": "Informe um IP e um tamanho de prefixo válidos: 0–32 para IPv4 ou 0–128 para IPv6."
}
}
+15 -18
View File
@@ -1,7 +1,6 @@
import './assets/styles/index.scss'
import { ResizeObserver } from '@juggle/resize-observer'
import { ComposeContextProvider } from 'foxact/compose-context-provider'
import React from 'react'
import { createRoot } from 'react-dom/client'
import { RouterProvider } from 'react-router'
@@ -38,26 +37,24 @@ if (!container) {
disableWebViewShortcuts()
const initializeApp = (initialThemeMode: 'light' | 'dark') => {
const contexts = [
<ThemeModeProvider key="theme" initialState={initialThemeMode} />,
<AppStoreProvider key="app-store" />,
<UpdateStateProvider key="update" />,
]
const root = createRoot(container)
root.render(
<React.StrictMode>
<ComposeContextProvider contexts={contexts}>
<BaseErrorBoundary>
<SWRConfig value={swrConfig}>
<WindowProvider>
<AppDataProvider>
<RouterProvider router={router} />
</AppDataProvider>
</WindowProvider>
</SWRConfig>
</BaseErrorBoundary>
</ComposeContextProvider>
<ThemeModeProvider initialState={initialThemeMode}>
<AppStoreProvider>
<UpdateStateProvider>
<BaseErrorBoundary>
<SWRConfig value={swrConfig}>
<WindowProvider>
<AppDataProvider>
<RouterProvider router={router} />
</AppDataProvider>
</WindowProvider>
</SWRConfig>
</BaseErrorBoundary>
</UpdateStateProvider>
</AppStoreProvider>
</ThemeModeProvider>
</React.StrictMode>,
)
}
+78 -62
View File
@@ -1,8 +1,5 @@
import { getName, getVersion } from '@tauri-apps/api/app'
import { fetch } from '@tauri-apps/plugin-http'
import { asyncRetry } from 'foxts/async-retry'
import { extractErrorMessage } from 'foxts/extract-error-message'
import { once } from 'foxts/once'
import i18n from 'i18next'
import { getBaseConfig } from 'tauri-plugin-mihomo-api'
@@ -10,15 +7,42 @@ import { debugLog } from '@/utils/debug'
import { getRuntimeConfig } from './cmds'
const getUserAgentPromise = once(async () => {
try {
const [name, version] = await Promise.all([getName(), getVersion()])
return `${name}/${version}`
} catch (error) {
console.debug('Failed to build User-Agent, fallback to default', error)
return 'clash-verge-rev'
let userAgentPromise: Promise<string> | null = null
const getUserAgentPromise = () =>
(userAgentPromise ??= Promise.all([getName(), getVersion()])
.then(([name, version]) => `${name}/${version}`)
.catch((error) => {
console.debug('Failed to build User-Agent, fallback to default', error)
return 'clash-verge-rev'
}))
const extractErrorMessage = (error: unknown): string | null =>
error instanceof Error ? `${error.name}: ${error.message}`.trim() : null
const retryWithBackoff = async <T>(
fn: (bail: (error: unknown) => never) => Promise<T>,
retries: number,
): Promise<T> => {
let bailed = false
const bail = (error: unknown): never => {
bailed = true
throw error
}
})
for (let attempt = 0; ; attempt++) {
try {
return await fn(bail)
} catch (error) {
if (bailed || attempt >= retries) throw error
const delay = Math.min(
Math.round((Math.random() + 1) * 1000 * 2 ** attempt),
4000,
)
await new Promise((resolve) => setTimeout(resolve, delay))
}
}
}
// Get current IP and geolocation information (refactored IP detection with service-specific mappings)
interface IpInfo {
ip: string
@@ -249,61 +273,53 @@ export const getIpInfo = async (): Promise<
debugLog(`尝试IP检测服务: ${service.url}`)
try {
return await asyncRetry(
async (bail) => {
console.debug('Fetching IP information:', service.url)
return await retryWithBackoff(async (bail) => {
console.debug('Fetching IP information:', service.url)
const timeoutController = new AbortController()
const timeoutId = setTimeout(() => {
timeoutController.abort()
}, serviceTimeout)
const timeoutController = new AbortController()
const timeoutId = setTimeout(() => {
timeoutController.abort()
}, serviceTimeout)
try {
const response = await fetch(service.url, {
method: 'GET',
proxy,
signal: timeoutController.signal,
connectTimeout: serviceTimeout,
headers: {
'User-Agent': userAgent,
},
})
try {
const response = await fetch(service.url, {
method: 'GET',
proxy,
signal: timeoutController.signal,
connectTimeout: serviceTimeout,
headers: {
'User-Agent': userAgent,
},
})
if (!response.ok) {
return bail(
new Error(
`IP 检测服务出错,状态码: ${response.status} from ${service.url}`,
),
)
}
let data: any
try {
data = await response.json()
} catch {
return bail(new Error(`无法解析 JSON 响应 from ${service.url}`))
}
if (data && data.ip) {
debugLog(`IP检测成功,使用服务: ${service.url}`)
return Object.assign(service.mapping(data), {
// use last fetch success timestamp
lastFetchTs: Date.now(),
})
} else {
return bail(new Error(`无效的响应格式 from ${service.url}`))
}
} finally {
clearTimeout(timeoutId)
if (!response.ok) {
return bail(
new Error(
`IP 检测服务出错,状态码: ${response.status} from ${service.url}`,
),
)
}
},
{
retries: maxRetries,
minTimeout: 1000,
maxTimeout: 4000,
randomize: true,
},
)
let data: any
try {
data = await response.json()
} catch {
return bail(new Error(`无法解析 JSON 响应 from ${service.url}`))
}
if (data && data.ip) {
debugLog(`IP检测成功,使用服务: ${service.url}`)
return Object.assign(service.mapping(data), {
// use last fetch success timestamp
lastFetchTs: Date.now(),
})
} else {
return bail(new Error(`无效的响应格式 from ${service.url}`))
}
} finally {
clearTimeout(timeoutId)
}
}, maxRetries)
} catch (error) {
debugLog(`IP检测服务失败: ${service.url}`, error)
lastError = error
+47 -14
View File
@@ -1,18 +1,51 @@
import { createContextState } from 'foxact/create-context-state'
import {
createContext,
createElement,
use,
useState,
type Dispatch,
type ReactNode,
type SetStateAction,
} from 'react'
const [ThemeModeProvider, useThemeMode, useSetThemeMode] = createContextState<
'light' | 'dark'
>()
import noop from '@/utils/noop'
// save update state
const [UpdateStateProvider, useUpdateState, useSetUpdateState] =
createContextState<boolean>(false)
type ThemeMode = 'light' | 'dark'
export {
ThemeModeProvider,
useThemeMode,
useSetThemeMode,
UpdateStateProvider,
useUpdateState,
useSetUpdateState,
const ThemeModeContext = createContext<ThemeMode>('light')
const SetThemeModeContext =
createContext<Dispatch<SetStateAction<ThemeMode>>>(noop)
export const ThemeModeProvider = ({
initialState,
children,
}: {
initialState: ThemeMode
children?: ReactNode
}) => {
const [mode, setMode] = useState<ThemeMode>(initialState)
return createElement(
ThemeModeContext,
{ value: mode },
createElement(SetThemeModeContext, { value: setMode }, children),
)
}
export const useThemeMode = () => use(ThemeModeContext)
export const useSetThemeMode = () => use(SetThemeModeContext)
const UpdateStateContext = createContext<boolean>(false)
const SetUpdateStateContext =
createContext<Dispatch<SetStateAction<boolean>>>(noop)
export const UpdateStateProvider = ({ children }: { children?: ReactNode }) => {
const [state, setState] = useState(false)
return createElement(
UpdateStateContext,
{ value: state },
createElement(SetUpdateStateContext, { value: setState }, children),
)
}
export const useUpdateState = () => use(UpdateStateContext)
export const useSetUpdateState = () => use(SetUpdateStateContext)