mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-24 14:32:13 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
62666b5e27 | ||
|
|
2db9da5d06 | ||
|
|
371ca6e907 | ||
|
|
b02fb26c0c | ||
|
|
a2d875cebd |
@@ -1,3 +1,2 @@
|
||||
avoid-breaking-exported-api = true
|
||||
allow-unwrap-in-tests = true
|
||||
cognitive-complexity-threshold = 25
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
|
||||
"features": {
|
||||
"ghcr.io/devcontainers/features/node:2": {
|
||||
"version": "26.13.1",
|
||||
"pnpmVersion": "12.21.0"
|
||||
"version": "26.13.0",
|
||||
"pnpmVersion": "12.18.0"
|
||||
},
|
||||
"ghcr.io/devcontainers/features/rust:1": {
|
||||
"version": "1.100.0",
|
||||
"version": "1.99.1",
|
||||
"profile": "default"
|
||||
},
|
||||
"ghcr.io/devcontainers/features/git:1": {},
|
||||
@@ -29,6 +29,7 @@
|
||||
"biomejs.biome"
|
||||
],
|
||||
"settings": {
|
||||
"rust-analyzer.cargo.features": ["verge-dev"],
|
||||
"rust-analyzer.check.command": "clippy",
|
||||
"editor.formatOnSave": true,
|
||||
"editor.defaultFormatter": "biomejs.biome",
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
# Issue and PR Guidelines
|
||||
|
||||
These rules apply to Issue and PR work, including operations through `gh` or an
|
||||
API. The root [AGENTS.md](../AGENTS.md) defines the repository-wide contract.
|
||||
|
||||
## Issues
|
||||
|
||||
When creating, drafting, triaging, splitting, or implementing from a community
|
||||
issue, follow [ISSUE_GUIDELINES.md](ISSUE_GUIDELINES.md). Do not create or modify
|
||||
GitHub issues without explicit authorization.
|
||||
|
||||
## PR Descriptions
|
||||
|
||||
When creating or updating a PR body, follow the
|
||||
[PR template](PULL_REQUEST_TEMPLATE.md). Describe the final change; replace stale
|
||||
text instead of appending work history. Omit routine check-pass declarations,
|
||||
including Clippy, lint, and local tests. Keep only evidence and limitations that
|
||||
help reviewers assess the change; the template defines what belongs in the body
|
||||
and when Scope is needed.
|
||||
|
||||
Before publishing or updating a PR body, remove repetition, self-evaluation, and
|
||||
details already clear from the diff. Keep only sentences that help review the
|
||||
change.
|
||||
|
||||
## AI Disclosure
|
||||
|
||||
When an agent creates or co-creates a PR or Issue, append a final body line with
|
||||
the model and effort used (e.g. `Assisted by: GPT-5.6 High`). Effort may be omitted
|
||||
when the runtime does not report it. Human contributors are not asked to disclose
|
||||
AI assistance. Disclosure is transparency only and carries no positive or
|
||||
negative weight.
|
||||
@@ -1,29 +1,3 @@
|
||||
<!--
|
||||
Describe the final problem, approach, and evidence needed to review this change.
|
||||
When updating the body, replace stale text instead of appending implementation
|
||||
history or review-round summaries.
|
||||
|
||||
State each fact once. Omit details already clear from the diff unless they
|
||||
explain a non-obvious constraint or trade-off. Describe concrete behavior instead
|
||||
of self-evaluation or unsupported assurances such as "more robust" or "seamless".
|
||||
Mention unchanged behavior or excluded areas only when they matter to review.
|
||||
Before publishing, remove any sentence whose deletion loses no information
|
||||
needed to understand the problem, approach, evidence, or material limitations.
|
||||
|
||||
Omit file-by-file diff summaries, internal planning scores, agent handoffs, and
|
||||
routine check results such as "Clippy passed", "lint passed", or "local tests
|
||||
passed". Do not add a Validation/Testing section for a command checklist.
|
||||
Include concrete before/after behavior or measurements when they support the
|
||||
change, and retain limitations that affect review. Link reviewer-accessible
|
||||
details when needed; do not paste full scripts, logs, or test matrices into the
|
||||
body, including collapsed sections.
|
||||
|
||||
Keep Scope only when explaining necessary changes outside the core fix, PR
|
||||
dependencies, or why added tests are needed. Do not repeat Approach there.
|
||||
For small changes, Problem and Approach may be combined into one short paragraph;
|
||||
remove unnecessary headings instead of adding text to fill them.
|
||||
-->
|
||||
|
||||
## Problem
|
||||
|
||||
What breaks or what is missing. Product bug fixes and features require a
|
||||
@@ -40,6 +14,4 @@ Why this change solves the problem — the reasoning behind the approach, not a
|
||||
|
||||
## Scope
|
||||
|
||||
Optional: explain necessary changes outside the core fix, PR dependencies, or
|
||||
why added tests are needed. Otherwise remove this section. New tests are not
|
||||
expected by default.
|
||||
What changed. If anything outside the core fix was touched, explain why it was necessary. New tests are not expected by default — if any were added, justify why each is needed.
|
||||
|
||||
@@ -1,275 +1,10 @@
|
||||
---
|
||||
name: Agentic Workflows
|
||||
description: GitHub Agentic Workflows (gh-aw) - Create, debug, and upgrade AI-powered workflows with intelligent prompt routing.
|
||||
description: Create, update, debug, and upgrade GitHub Agentic Workflows (gh-aw).
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
## 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.
|
||||
|
||||
## 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`
|
||||
Use the repository [agentic-workflows skill](../skills/agentic-workflows/SKILL.md)
|
||||
for task routing, version-matched references, and compilation requirements.
|
||||
Load only the route needed for the current task. This agent is for workflow
|
||||
maintenance; product development and code review follow the root AGENTS.md.
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
"version": "v9.0.0",
|
||||
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
|
||||
},
|
||||
"github/gh-aw-actions/setup@v1.3.1": {
|
||||
"github/gh-aw-actions/setup@v1.0.1": {
|
||||
"repo": "github/gh-aw-actions/setup",
|
||||
"version": "v1.3.1",
|
||||
"sha": "dfe97a19c8249d41e2adfc95f92db2b8facea58f"
|
||||
"version": "v1.0.1",
|
||||
"sha": "221ba4f4319de6b8e809d1a15528b3ae6a818aa5"
|
||||
}
|
||||
},
|
||||
"containers": {
|
||||
@@ -32,16 +32,6 @@
|
||||
"digest": "sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.28.23@sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-firewall/agent:0.29.11": {
|
||||
"image": "ghcr.io/github/gh-aw-firewall/agent:0.29.11",
|
||||
"digest": "sha256:8774a73c351395b41d2ad0af4ddb4689007c67de3cd08bd9f43bb8a0e300690e",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.11@sha256:8774a73c351395b41d2ad0af4ddb4689007c67de3cd08bd9f43bb8a0e300690e"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-firewall/agent:0.29.14": {
|
||||
"image": "ghcr.io/github/gh-aw-firewall/agent:0.29.14",
|
||||
"digest": "sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa"
|
||||
},
|
||||
"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",
|
||||
@@ -62,31 +52,6 @@
|
||||
"digest": "sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.23@sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.11": {
|
||||
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.11",
|
||||
"digest": "sha256:88d2d0e315a504d93fd4fb8847fd0f6b7f4469f41a6fc6047b3dc9654c56ab2c",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.11@sha256:88d2d0e315a504d93fd4fb8847fd0f6b7f4469f41a6fc6047b3dc9654c56ab2c"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14": {
|
||||
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14",
|
||||
"digest": "sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0"
|
||||
},
|
||||
"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",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11@sha256:97782bc0d8ff7f80f19ae2fdc5e1668517aa732a6fa077e64b8d3919238496d2"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14": {
|
||||
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14",
|
||||
"digest": "sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14@sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-firewall/router:0.29.14": {
|
||||
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.14",
|
||||
"digest": "sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.14@sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-firewall/squid:0.28.13": {
|
||||
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13",
|
||||
"digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56",
|
||||
@@ -107,30 +72,20 @@
|
||||
"digest": "sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.28.23@sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-firewall/squid:0.29.11": {
|
||||
"image": "ghcr.io/github/gh-aw-firewall/squid:0.29.11",
|
||||
"digest": "sha256:861739ecf924dd2db5e5fb652db2ad82aaafd1615623297ddabc8f41a36b2847",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.11@sha256:861739ecf924dd2db5e5fb652db2ad82aaafd1615623297ddabc8f41a36b2847"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-firewall/squid:0.29.14": {
|
||||
"image": "ghcr.io/github/gh-aw-firewall/squid:0.29.14",
|
||||
"digest": "sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.14@sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-mcpg:v0.5.10": {
|
||||
"image": "ghcr.io/github/gh-aw-mcpg:v0.5.10",
|
||||
"digest": "sha256:629ddcd68a48ab02e7db8af527d2756c6db563b00c1d31d8aa8fcbac96f01c59",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.5.10@sha256:629ddcd68a48ab02e7db8af527d2756c6db563b00c1d31d8aa8fcbac96f01c59"
|
||||
"ghcr.io/github/gh-aw-mcpg:v0.4.25": {
|
||||
"image": "ghcr.io/github/gh-aw-mcpg:v0.4.25",
|
||||
"digest": "sha256:9be0a86220e807a0ecc89e53d7453468f7a53fbc6b3d1efd2299025ffe01d086",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.4.25@sha256:9be0a86220e807a0ecc89e53d7453468f7a53fbc6b3d1efd2299025ffe01d086"
|
||||
},
|
||||
"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:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e"
|
||||
},
|
||||
"ghcr.io/github/github-mcp-server:v2.1.0": {
|
||||
"image": "ghcr.io/github/github-mcp-server:v2.1.0",
|
||||
"digest": "sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a",
|
||||
"pinned_image": "ghcr.io/github/github-mcp-server:v2.1.0@sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a"
|
||||
"ghcr.io/github/github-mcp-server:v1.12.2": {
|
||||
"image": "ghcr.io/github/github-mcp-server:v1.12.2",
|
||||
"digest": "sha256:508a0857ec762b1ab1cece29193345b501fab1dd9d1228a7b617062954cecac6",
|
||||
"pinned_image": "ghcr.io/github/github-mcp-server:v1.12.2@sha256:508a0857ec762b1ab1cece29193345b501fab1dd9d1228a7b617062954cecac6"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,193 +1,40 @@
|
||||
---
|
||||
name: agentic-workflows
|
||||
description: Route gh-aw design, creation, diagnosis, patching, active debugging, upgrades, and local SDLC issue requests to the right strategies.
|
||||
description: Route requests to design, create, update, debug, or upgrade GitHub Agentic Workflows (gh-aw), including workflow cost audits. Use for workflow infrastructure, not ordinary product development or code review.
|
||||
---
|
||||
|
||||
# Agentic Workflows Router
|
||||
|
||||
Use this skill when a user asks to design, create, update, debug, or upgrade GitHub Agentic Workflows in this repository, or prepare a substantial issue for a local, self-contained SDLC.
|
||||
Choose one primary route below. Fetch its reference from
|
||||
`https://raw.githubusercontent.com/github/gh-aw/v1.0.1/.github/aw/`.
|
||||
This version matches the repository's workflow lock and Copilot setup. Before
|
||||
using another version, check the target lock's `compiler_version`; upgrades must
|
||||
align the compiler, setup, and references together.
|
||||
|
||||
This skill is a dispatcher: identify the task type, load the matching workflow prompt/skill file, and follow it directly. Keep responses concise and ask a clarifying question if the correct prompt is unclear.
|
||||
| Task | Reference |
|
||||
| --- | --- |
|
||||
| Design from requirements | `designer.md` |
|
||||
| Create a workflow | `create-agentic-workflow.md` |
|
||||
| Update a workflow | `update-agentic-workflow.md` |
|
||||
| Debug or audit a run | `debug-agentic-workflow.md` |
|
||||
| Upgrade or fix deprecations | `upgrade-agentic-workflows.md` |
|
||||
| Reduce or measure token cost | `token-optimization.md` |
|
||||
| Configure an engine | `configure-agentic-engine.md` |
|
||||
| Create shared components or MCP wrappers | `create-shared-agentic-workflow.md` |
|
||||
| Choose architecture | `patterns.md` |
|
||||
| CLI commands or MCP equivalents | `cli-commands.md` |
|
||||
|
||||
For debugging sessions needing CLI setup or run-URL scoping, first load
|
||||
`https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-bootstrap.md`; it bootstraps
|
||||
the same shared strategy used by the debugging routes below.
|
||||
Read the matched guide, then only the supporting sections needed for the task.
|
||||
Do not preload the reference catalog or full manuals. Add `report.md` for report
|
||||
design, `test-coverage.md` for coverage data, `dependabot.md` for generated
|
||||
manifest updates, or `skills.md` for requested skill/plugin integration. For
|
||||
OTEL/OTLP analysis, use upstream `skills/otel-queries/SKILL.md` at the same tag.
|
||||
If `.github/aw/instructions.md` exists locally, read it as the repository overlay.
|
||||
User scope and repository instructions take precedence over upstream defaults.
|
||||
|
||||
Debugging, incident, health, and failure-related optimization requests use the
|
||||
bootstrap's intent routing before generic update, upgrade, or optimization routes,
|
||||
even when the CLI is installed. Preserve the supplied guidance repository/ref
|
||||
for all debugging links and public raw fallbacks; URLs showing `main` below are
|
||||
defaults only when no guidance revision is supplied. Reuse already-loaded guides.
|
||||
The intent index is `.github/aw/debug-scenarios.md`; load only the selected
|
||||
specialized route, not every debugging reference.
|
||||
|
||||
Repository overlay (optional):
|
||||
- Load the target repository's `.github/aw/instructions.md`, if present, after the matched prompt/skill. Use `@.github/aw/instructions.md` only in a matching checkout; do not substitute a guidance-repository overlay.
|
||||
- Precedence: repository overlay instructions override upstream defaults when they conflict.
|
||||
|
||||
## Load and route
|
||||
|
||||
Read only the files needed for the selected task.
|
||||
Use a local guidance checkout only when its repository/ref matches the requested guidance; otherwise use the resolved guidance repository/ref (default `github/gh-aw`).
|
||||
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.
|
||||
After loading the matching workflow prompt or skill, follow it directly:
|
||||
- Design workflows from scratch via interview: `.github/aw/designer.md`
|
||||
- Create new workflows: `.github/aw/create-agentic-workflow.md`
|
||||
- Configure scheduled dreaming or consolidate persistent memory: `.github/aw/create-agentic-workflow.md`, then `.github/aw/memory.md#scheduled-dreaming`; load `.github/aw/dreaming.md` only when the decision and input scope justify implementation
|
||||
- Configure or add declarative engines: `.github/aw/configure-agentic-engine.md`
|
||||
- Consume, author, or document third-party connectors: `.github/aw/connectors.md`
|
||||
- Create a new connector: `.github/aw/connectors.md#author-or-extend-a-declaration`, then the repository's `.github/skills/create-connector/SKILL.md` when available
|
||||
- Update existing workflows: `.github/aw/update-agentic-workflow.md`
|
||||
- Diagnose, patch, audit, or actively debug workflows: `.github/aw/debug-agentic-workflow.md` (local-first strategy, evidence triage and live gates)
|
||||
- Analyze existing runs, logs, or recurring failures: `.github/aw/analyzing-runs.md`. General repository-wide debugging or optimization requests start here with failure clustering before selecting a workflow.
|
||||
- AWF model/endpoint 400s, silent cross-family sub-agent failures, `model: auto` failures, install-step 404s after a version pin, or questions about version fields: go directly to `.github/aw/debug-agentic-workflow.md#model-and-engine-misconfiguration` before suggesting model changes.
|
||||
- Upgrade workflows and fix deprecations: `.github/aw/upgrade-agentic-workflows.md`
|
||||
- Create shared components or MCP wrappers: `.github/aw/create-shared-agentic-workflow.md`
|
||||
- Create report-generating workflows: `.github/aw/report.md`
|
||||
- Fix Dependabot manifest PRs: `.github/aw/dependabot.md`
|
||||
- Analyze coverage workflows: `.github/aw/test-coverage.md`
|
||||
- Render compact markdown charts: `.github/aw/asciicharts.md`
|
||||
- Map CLI commands to MCP usage: `.github/aw/cli-commands.md`
|
||||
- Choose workflow architecture and patterns: `.github/aw/patterns.md`
|
||||
- Design, deploy, inspect or recover a Git-backed work queue: `.github/aw/work-queue.md`
|
||||
- Optimize token usage and cost: `.github/aw/token-optimization.md`
|
||||
- Advanced cost controls without native settings (custom AIC allowances by server size or shared organization budget policies): read `docs/src/content/docs/reference/cost-management.md#configure-advanced-cost-controls-with-admission` ([published guidance](https://github.github.com/gh-aw/reference/cost-management/#configure-advanced-cost-controls-with-admission)). Explain the external authority requirement and cooperative limits; do not invent frontmatter fields or promise hard caps, reservations, or mid-run cancellation.
|
||||
- Design long-running multi-agent research workflows: `.github/aw/multi-agent-research.md`
|
||||
- Add skills or agent plugins requested by the user (`skills:` / `plugins:` frontmatter, never on-the-fly installs): `.github/aw/skills.md`
|
||||
- Local SDLC issue bootstrap: `.github/aw/squad.md`
|
||||
|
||||
When the task involves OTEL, OTLP, traces, observability backends, or telemetry-driven analysis, also read and follow `skills/otel-queries/SKILL.md` after loading the matching workflow prompt or skill.
|
||||
|
||||
When creating, updating, diagnosing or upgrading a workflow that uses `tools.work-queue`, also load `.github/aw/work-queue.md` after the primary prompt. Load deployment docs, operator reference or specification only when that task needs them.
|
||||
|
||||
For repository initialization or configuration involving third-party integrations,
|
||||
use `.github/aw/connectors.md` and the selected editable declaration's
|
||||
`import-schema` and `connector-documentation` metadata. Discover local declarations,
|
||||
normal local/pinned imports and matching `*-golden.md` consumers; do not invent a
|
||||
built-in provider catalog. Use `gh aw connector <id> setup --file PATH` for
|
||||
phase-specific credential names/scopes and acquisition/renewal guidance.
|
||||
Bind exact approved resources through `with`; secret NAMES only, never values.
|
||||
Select reads/native methods and staged safe outputs independently. Importing must
|
||||
not enable capabilities, write credentials, broad grants or live webhook ingress.
|
||||
Derive network hosts from the selected contract, not provider-name guesses.
|
||||
Token acquisition/refresh, consent and real provider permissions remain external.
|
||||
|
||||
When editing instructions, skills or their generators, keep the complete task
|
||||
contract within the first 7,500 UTF-8 bytes (8,000-byte query limit). Front-load
|
||||
constraints, routes, verification and stop conditions; defer examples and
|
||||
inventories. Preserve safety and exact schema/command names.
|
||||
|
||||
<!-- instruction-prefix-end -->
|
||||
|
||||
## Optional reference inventory
|
||||
|
||||
<details>
|
||||
<summary>Guidance file catalog</summary>
|
||||
|
||||
Use the task routes above first. This inventory is not required startup context.
|
||||
|
||||
- `.github/aw/action-container-substitutions.md`
|
||||
- `.github/aw/agent-runtime-instructions.md`
|
||||
- `.github/aw/agentic-chat.md`
|
||||
- `.github/aw/agentic-engine.md`
|
||||
- `.github/aw/agentic-workflows-mcp.md`
|
||||
- `.github/aw/analyzing-runs.md`
|
||||
- `.github/aw/asciicharts.md`
|
||||
- `.github/aw/campaign.md`
|
||||
- `.github/aw/charts-trending.md`
|
||||
- `.github/aw/charts.md`
|
||||
- `.github/aw/cli-commands.md`
|
||||
- `.github/aw/compat.md`
|
||||
- `.github/aw/connectors.md`
|
||||
- `.github/aw/context.md`
|
||||
- `.github/aw/create-agentic-workflow-design.md`
|
||||
- `.github/aw/create-agentic-workflow-evaluation.md`
|
||||
- `.github/aw/create-agentic-workflow-trigger-details.md`
|
||||
- `.github/aw/create-agentic-workflow-validation.md`
|
||||
- `.github/aw/create-agentic-workflow.md`
|
||||
- `.github/aw/create-shared-agentic-workflow.md`
|
||||
- `.github/aw/custom-declarative-agentic-engine.md`
|
||||
- `.github/aw/debug-agentic-workflow.md`
|
||||
- `.github/aw/debug-bootstrap.md`
|
||||
- `.github/aw/debug-compilation.md`
|
||||
- `.github/aw/debug-live-testing.md`
|
||||
- `.github/aw/debug-model-engine-misconfiguration.md`
|
||||
- `.github/aw/debug-playbook.md`
|
||||
- `.github/aw/debug-scenarios.md`
|
||||
- `.github/aw/debug-security-review.md`
|
||||
- `.github/aw/debug-workflow-evidence.md`
|
||||
- `.github/aw/debug-workflow-health.md`
|
||||
- `.github/aw/dependabot.md`
|
||||
- `.github/aw/deployment-status.md`
|
||||
- `.github/aw/designer-mappings.md`
|
||||
- `.github/aw/designer.md`
|
||||
- `.github/aw/doctor.md`
|
||||
- `.github/aw/documentation-workflows.md`
|
||||
- `.github/aw/dreaming.md`
|
||||
- `.github/aw/drive-memory.md`
|
||||
- `.github/aw/enclaves.md`
|
||||
- `.github/aw/evals.md`
|
||||
- `.github/aw/experiments.md`
|
||||
- `.github/aw/formal-methods.md`
|
||||
- `.github/aw/github-agentic-workflows.md`
|
||||
- `.github/aw/github-mcp-server-pagination.md`
|
||||
- `.github/aw/github-mcp-server-tools.md`
|
||||
- `.github/aw/github-mcp-server.md`
|
||||
- `.github/aw/harbor.md`
|
||||
- `.github/aw/index-search.md`
|
||||
- `.github/aw/instructions.md`
|
||||
- `.github/aw/intent.md`
|
||||
- `.github/aw/jobs.md`
|
||||
- `.github/aw/ledger.md`
|
||||
- `.github/aw/linter-workflows.md`
|
||||
- `.github/aw/llms.md`
|
||||
- `.github/aw/loop.md`
|
||||
- `.github/aw/lsp.md`
|
||||
- `.github/aw/maintainer.md`
|
||||
- `.github/aw/mcp-clis.md`
|
||||
- `.github/aw/memory-stateful-patterns.md`
|
||||
- `.github/aw/memory.md`
|
||||
- `.github/aw/messages.md`
|
||||
- `.github/aw/multi-agent-research.md`
|
||||
- `.github/aw/network.md`
|
||||
- `.github/aw/optimize-agentic-workflow.md`
|
||||
- `.github/aw/otel.md`
|
||||
- `.github/aw/patterns.md`
|
||||
- `.github/aw/playwright.md`
|
||||
- `.github/aw/pr-reviewer.md`
|
||||
- `.github/aw/release-workflow.md`
|
||||
- `.github/aw/repo-factory.md`
|
||||
- `.github/aw/report.md`
|
||||
- `.github/aw/responsible-ai.md`
|
||||
- `.github/aw/reuse.md`
|
||||
- `.github/aw/safe-outputs-automation.md`
|
||||
- `.github/aw/safe-outputs-content.md`
|
||||
- `.github/aw/safe-outputs-management.md`
|
||||
- `.github/aw/safe-outputs-runtime.md`
|
||||
- `.github/aw/safe-outputs.md`
|
||||
- `.github/aw/serena-tool.md`
|
||||
- `.github/aw/shared-safe-jobs.md`
|
||||
- `.github/aw/skills.md`
|
||||
- `.github/aw/squad.md`
|
||||
- `.github/aw/subagents.md`
|
||||
- `.github/aw/syntax-agentic.md`
|
||||
- `.github/aw/syntax-checkout.md`
|
||||
- `.github/aw/syntax-core.md`
|
||||
- `.github/aw/syntax-engine.md`
|
||||
- `.github/aw/syntax-tools-imports.md`
|
||||
- `.github/aw/syntax.md`
|
||||
- `.github/aw/test-coverage.md`
|
||||
- `.github/aw/test-expression.md`
|
||||
- `.github/aw/token-optimization-caching-budgets.md`
|
||||
- `.github/aw/token-optimization-observability.md`
|
||||
- `.github/aw/token-optimization.md`
|
||||
- `.github/aw/triggers.md`
|
||||
- `.github/aw/update-agentic-workflow.md`
|
||||
- `.github/aw/upgrade-agentic-workflows.md`
|
||||
- `.github/aw/visual-regression.md`
|
||||
- `.github/aw/work-queue.md`
|
||||
- `.github/aw/workflow-constraints.md`
|
||||
- `.github/aw/workflow-editing.md`
|
||||
- `.github/aw/workflow-patterns.md`
|
||||
|
||||
</details>
|
||||
Edit workflow `.md` sources and run `gh aw compile <workflow>` with the matching
|
||||
compiler; include the generated lock in the change. Never edit locks directly.
|
||||
Keep permissions and data reads scoped to the workflow's purpose. A request to
|
||||
edit or audit a workflow does not authorize dispatching runs or posting to GitHub.
|
||||
For cost audits, distinguish prompt size from measured run usage, including cache
|
||||
reads/writes; a shorter prompt alone does not prove lower credits or better review.
|
||||
|
||||
@@ -51,7 +51,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '26.13.1'
|
||||
node-version: '26.13.0'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
@@ -154,7 +154,7 @@ jobs:
|
||||
- name: Install Rust Stable
|
||||
uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
toolchain: '1.100.0'
|
||||
toolchain: '1.99.1'
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- name: Rust Cache
|
||||
@@ -182,7 +182,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '26.13.1'
|
||||
node-version: '26.13.0'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Pnpm install and check
|
||||
@@ -240,7 +240,7 @@ jobs:
|
||||
- name: Install Rust Stable
|
||||
uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
toolchain: '1.100.0'
|
||||
toolchain: '1.99.1'
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- name: Rust Cache
|
||||
@@ -262,7 +262,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '26.13.1'
|
||||
node-version: '26.13.0'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Pnpm install and check
|
||||
@@ -373,7 +373,7 @@ jobs:
|
||||
- name: Install Rust Stable
|
||||
uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
toolchain: '1.100.0'
|
||||
toolchain: '1.99.1'
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- name: Rust Cache
|
||||
@@ -395,7 +395,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '26.13.1'
|
||||
node-version: '26.13.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.13.0'
|
||||
|
||||
- uses: pnpm/action-setup@v6.1.1
|
||||
name: Install pnpm
|
||||
|
||||
@@ -63,7 +63,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '26.13.1'
|
||||
node-version: '26.13.0'
|
||||
cache: 'pnpm'
|
||||
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
@@ -31,9 +31,9 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Install gh-aw extension
|
||||
uses: github/gh-aw-actions/setup-cli@dfe97a19c8249d41e2adfc95f92db2b8facea58f # v1.3.1
|
||||
uses: github/gh-aw-actions/setup-cli@406c7719e31d7fe354224d4bb8fe3d4aeb47da1c # v1.2.1
|
||||
with:
|
||||
version: v1.3.1
|
||||
version: v1.0.1
|
||||
- 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.13.0'
|
||||
cache: 'pnpm'
|
||||
- name: Install frontend dependencies
|
||||
env:
|
||||
|
||||
@@ -43,7 +43,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '26.13.1'
|
||||
node-version: '26.13.0'
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
name: Install pnpm
|
||||
|
||||
@@ -74,7 +74,7 @@ jobs:
|
||||
|
||||
- name: Install Rust Stable
|
||||
if: github.event.inputs[matrix.input] == 'true'
|
||||
uses: dtolnay/rust-toolchain@1.100.0
|
||||
uses: dtolnay/rust-toolchain@1.99.1
|
||||
|
||||
- name: Rust Cache
|
||||
if: github.event.inputs[matrix.input] == 'true'
|
||||
@@ -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.13.0'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Pnpm install and check
|
||||
@@ -121,7 +121,7 @@ jobs:
|
||||
if: github.event.inputs[matrix.input] == 'true'
|
||||
run: |
|
||||
# Ensure cross target is installed for the pinned toolchain; fallback without explicit toolchain if needed
|
||||
rustup target add ${{ matrix.target }} --toolchain 1.100.0 || rustup target add ${{ matrix.target }}
|
||||
rustup target add ${{ matrix.target }} --toolchain 1.99.1 || rustup target add ${{ matrix.target }}
|
||||
rustup target list --installed
|
||||
echo "Rust target ${{ matrix.target }} installed."
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ on:
|
||||
- REVIEW.md
|
||||
- src/AGENTS.md
|
||||
- src-tauri/AGENTS.md
|
||||
- .github/AGENTS.md
|
||||
- .github/ISSUE_GUIDELINES.md
|
||||
- .github/agents/agentic-workflows.md
|
||||
- .github/skills/agentic-workflows/SKILL.md
|
||||
@@ -31,7 +30,6 @@ on:
|
||||
- REVIEW.md
|
||||
- src/AGENTS.md
|
||||
- src-tauri/AGENTS.md
|
||||
- .github/AGENTS.md
|
||||
- .github/ISSUE_GUIDELINES.md
|
||||
- .github/agents/agentic-workflows.md
|
||||
- .github/skills/agentic-workflows/SKILL.md
|
||||
@@ -59,8 +57,7 @@ jobs:
|
||||
check AGENTS.md 'Issue first'
|
||||
check AGENTS.md 'Author accountability'
|
||||
check AGENTS.md 'pr-ai-slop-review'
|
||||
check AGENTS.md '(.github/AGENTS.md)'
|
||||
check .github/AGENTS.md '## AI Disclosure'
|
||||
check AGENTS.md 'Disclose AI automation'
|
||||
check CONTRIBUTING.md 'Assisted by:'
|
||||
check .github/workflows/pr-ai-slop-review.md '(../../CONTRIBUTING.md)'
|
||||
check .github/workflows/pr-ai-slop-review.md '(../../AGENTS.md)'
|
||||
@@ -87,7 +84,7 @@ jobs:
|
||||
|
||||
sources = [
|
||||
"AGENTS.md", "CONTRIBUTING.md", "REVIEW.md", "CLAUDE.md", "GEMINI.md",
|
||||
"src/AGENTS.md", "src-tauri/AGENTS.md", ".github/AGENTS.md", ".github/ISSUE_GUIDELINES.md",
|
||||
"src/AGENTS.md", "src-tauri/AGENTS.md", ".github/ISSUE_GUIDELINES.md",
|
||||
".github/PULL_REQUEST_TEMPLATE.md", ".github/workflows/pr-ai-slop-review.md",
|
||||
".github/workflows/pr-verify-fix.md",
|
||||
".github/agents/agentic-workflows.md", ".github/skills/agentic-workflows/SKILL.md",
|
||||
|
||||
@@ -36,7 +36,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '26.13.1'
|
||||
node-version: '26.13.0'
|
||||
cache: 'pnpm'
|
||||
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
+113
-306
File diff suppressed because one or more lines are too long
@@ -30,14 +30,9 @@ max-ai-credits: 60
|
||||
max-turns: 12
|
||||
max-daily-ai-credits: 5000
|
||||
|
||||
# Routine, low-risk tasks such as triage, labeling, and summaries.
|
||||
# See https://github.github.com/gh-aw/reference/model-routing/#setting-the-level-yourself
|
||||
model: router/economy
|
||||
|
||||
permissions:
|
||||
issues: read
|
||||
pull-requests: read
|
||||
copilot-requests: none
|
||||
|
||||
pre-agent-steps:
|
||||
- name: Make Copilot quota exhaustion non-blocking
|
||||
@@ -47,14 +42,14 @@ pre-agent-steps:
|
||||
const harnessPath = `${process.env.RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs`;
|
||||
const harness = fs.readFileSync(harnessPath, 'utf8');
|
||||
const quotaBranch = [
|
||||
' if (isQuotaExceeded && (result.retryAfterMs == null || /\\bquota exceeded\\b/i.test(result.output))) {',
|
||||
' if (isQuotaExceeded) {',
|
||||
' log(`attempt ${attempt + 1}: Copilot quota exceeded — not retrying`);',
|
||||
' return { action: "stop" };',
|
||||
' }',
|
||||
].join('\n');
|
||||
const nonBlockingQuotaBranch = [
|
||||
' let quotaErrorMsg = null;',
|
||||
' if (isQuotaExceeded && (result.retryAfterMs == null || /\\bquota exceeded\\b/i.test(result.output))) {',
|
||||
' if (isQuotaExceeded) {',
|
||||
' log(`attempt ${attempt + 1}: Copilot quota exceeded — not retrying`);',
|
||||
' quotaErrorMsg = { action: "stop" };',
|
||||
' }',
|
||||
|
||||
Generated
+118
-314
File diff suppressed because one or more lines are too long
@@ -26,14 +26,10 @@ imports:
|
||||
max-ai-credits: 60
|
||||
max-turns: 12
|
||||
max-daily-ai-credits: 500
|
||||
# Routine, low-risk tasks such as triage, labeling, and summaries.
|
||||
# See https://github.github.com/gh-aw/reference/model-routing/#setting-the-level-yourself
|
||||
model: router/economy
|
||||
permissions:
|
||||
contents: read
|
||||
issues: read
|
||||
pull-requests: read
|
||||
copilot-requests: none
|
||||
steps:
|
||||
- name: Load review rules from the base revision
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
|
||||
@@ -61,7 +61,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '26.13.1'
|
||||
node-version: '26.13.0'
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
if: github.event.action != 'closed'
|
||||
|
||||
@@ -46,7 +46,7 @@ jobs:
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '26.13.1'
|
||||
node-version: '26.13.0'
|
||||
- name: Validate source and publish the approved snapshot
|
||||
id: source
|
||||
env:
|
||||
@@ -203,7 +203,7 @@ jobs:
|
||||
- name: Install Rust Stable
|
||||
uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
toolchain: '1.100.0'
|
||||
toolchain: '1.99.1'
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- name: Rust Cache
|
||||
@@ -231,7 +231,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '26.13.1'
|
||||
node-version: '26.13.0'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Pnpm install and check
|
||||
@@ -308,7 +308,7 @@ jobs:
|
||||
- name: Install Rust Stable
|
||||
uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
toolchain: '1.100.0'
|
||||
toolchain: '1.99.1'
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- name: Rust Cache
|
||||
@@ -330,7 +330,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '26.13.1'
|
||||
node-version: '26.13.0'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Pnpm install and check
|
||||
@@ -439,7 +439,7 @@ jobs:
|
||||
- name: Install Rust Stable
|
||||
uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
toolchain: '1.100.0'
|
||||
toolchain: '1.99.1'
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- name: Rust Cache
|
||||
@@ -461,7 +461,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '26.13.1'
|
||||
node-version: '26.13.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.13.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.13.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.13.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.13.0'
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
name: Install pnpm
|
||||
|
||||
+115
-308
File diff suppressed because one or more lines are too long
@@ -28,17 +28,11 @@ permissions:
|
||||
contents: read
|
||||
issues: read
|
||||
pull-requests: read
|
||||
copilot-requests: none
|
||||
max-ai-credits: 60
|
||||
max-turns: 12
|
||||
max-daily-ai-credits: 500
|
||||
# Routine, low-risk tasks such as triage, labeling, and summaries.
|
||||
# See https://github.github.com/gh-aw/reference/model-routing/#setting-the-level-yourself
|
||||
model: router/economy
|
||||
network:
|
||||
# GitHub CLI recommend using ecosystem identifiers instead of individual domain names for better maintainability,
|
||||
# hence "node" is prefer than "nodejs.org"
|
||||
allowed: [github, docs.rs, doc.rust-lang.org, node, www.typescriptlang.org]
|
||||
allowed: [github, docs.rs, doc.rust-lang.org, nodejs.org, www.typescriptlang.org]
|
||||
steps:
|
||||
- name: Load trusted metadata parser
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
@@ -22,13 +22,13 @@ jobs:
|
||||
- name: Install Rust
|
||||
uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
toolchain: '1.100.0'
|
||||
toolchain: '1.99.1'
|
||||
targets: x86_64-pc-windows-msvc
|
||||
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '26.13.1'
|
||||
node-version: '26.13.0'
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
name: Sync Mihomo Changelog
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
dry_run:
|
||||
description: Preview the Changelog diff without creating a PR
|
||||
type: boolean
|
||||
default: true
|
||||
schedule:
|
||||
# UTC+8 Monday 11:30
|
||||
- cron: '30 3 * * 1'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
issues: write
|
||||
|
||||
concurrency:
|
||||
group: sync-mihomo-changelog
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ github.event.repository.default_branch }}
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '26.13.1'
|
||||
|
||||
- name: Sync Mihomo version
|
||||
id: sync
|
||||
env:
|
||||
DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}
|
||||
run: |
|
||||
args=()
|
||||
if [[ "$DRY_RUN" == 'true' ]]; then args+=(--dry-run); fi
|
||||
node scripts/sync-mihomo-version.mjs "${args[@]}"
|
||||
|
||||
- name: Create labeled PR and enqueue
|
||||
if: steps.sync.outputs.changed == 'true' && !(github.event_name == 'workflow_dispatch' && inputs.dry_run)
|
||||
uses: actions/github-script@v9
|
||||
env:
|
||||
MIHOMO_VERSION: ${{ steps.sync.outputs.version }}
|
||||
with:
|
||||
script: |
|
||||
const { readFileSync } = await import('node:fs');
|
||||
const { execFileSync } = await import('node:child_process');
|
||||
const { owner, repo } = context.repo;
|
||||
const base = context.payload.repository.default_branch;
|
||||
const version = process.env.MIHOMO_VERSION;
|
||||
const appVersion = JSON.parse(readFileSync('package.json', 'utf8')).version;
|
||||
const branch = `chore/sync-mihomo-${appVersion}-${version}`;
|
||||
const title = `chore: sync Mihomo changelog to ${version}`;
|
||||
const pulls = await github.rest.pulls.list({
|
||||
owner, repo, base, head: `${owner}:${branch}`, state: 'all',
|
||||
});
|
||||
let pr = pulls.data[0];
|
||||
if (pr && (pr.state !== 'open' || pr.user.login !== 'github-actions[bot]')) {
|
||||
throw new Error(`Existing candidate needs maintainer attention: ${pr.html_url}`);
|
||||
}
|
||||
if (!pr) {
|
||||
const sha = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
|
||||
await github.rest.git.createRef({ owner, repo, ref: `refs/heads/${branch}`, sha });
|
||||
await github.graphql(`mutation($input: CreateCommitOnBranchInput!) {
|
||||
createCommitOnBranch(input: $input) { commit { oid } }
|
||||
}`, {
|
||||
input: {
|
||||
branch: { repositoryNameWithOwner: `${owner}/${repo}`, branchName: branch },
|
||||
expectedHeadOid: sha,
|
||||
message: { headline: title },
|
||||
fileChanges: { additions: [{
|
||||
path: 'Changelog.md',
|
||||
contents: readFileSync('Changelog.md').toString('base64'),
|
||||
}] },
|
||||
},
|
||||
});
|
||||
({ data: pr } = await github.rest.pulls.create({
|
||||
owner, repo, base, head: branch, title,
|
||||
body: `## Problem\n\nChangelog.md needs to record the latest stable Mihomo version.\n\n` +
|
||||
`## Approach\n\nRead the same upstream version.txt used by the core download script.\n\n` +
|
||||
`## Scope\n\nOnly the Mihomo version line in Changelog.md changes to ${version}.`,
|
||||
}));
|
||||
}
|
||||
for (let attempt = 0; attempt < 10; attempt++) {
|
||||
({ data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: pr.number }));
|
||||
if (pr.mergeable !== null) break;
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
}
|
||||
if (!pr.mergeable) throw new Error(`Sync PR is not mergeable: ${pr.html_url}`);
|
||||
const files = await github.paginate(github.rest.pulls.listFiles, {
|
||||
owner, repo, pull_number: pr.number,
|
||||
});
|
||||
if (files.length !== 1 || files[0].filename !== 'Changelog.md') {
|
||||
throw new Error('The sync PR must change only Changelog.md.');
|
||||
}
|
||||
await github.rest.issues.addLabels({
|
||||
owner, repo, issue_number: pr.number, labels: ['dependencies', 'upstream'],
|
||||
});
|
||||
const result = await github.graphql(`query($id: ID!) {
|
||||
node(id: $id) { ... on PullRequest { mergeQueueEntry { id } } }
|
||||
}`, { id: pr.node_id });
|
||||
if (!result.node.mergeQueueEntry) {
|
||||
await github.graphql(`mutation($input: EnqueuePullRequestInput!) {
|
||||
enqueuePullRequest(input: $input) { mergeQueueEntry { id } }
|
||||
}`, { input: { pullRequestId: pr.node_id, expectedHeadOid: pr.head.sha } });
|
||||
}
|
||||
await core.summary.addRaw(`Queued Mihomo sync PR: ${pr.html_url}\n`).write();
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '26.13.1'
|
||||
node-version: '26.13.0'
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
name: Install pnpm
|
||||
|
||||
@@ -15,7 +15,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '26.13.1'
|
||||
node-version: '26.13.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.13.0'
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
name: Install pnpm
|
||||
|
||||
+3
-3
@@ -1,3 +1,3 @@
|
||||
nodejs 26.13.1
|
||||
pnpm 12.21.0
|
||||
rust 1.100.0
|
||||
nodejs 26.13.0
|
||||
pnpm 12.18.0
|
||||
rust 1.99.1
|
||||
|
||||
@@ -48,11 +48,16 @@ the ownership evidence the AI-slop review evaluates (see
|
||||
8. **Minimal diffs.** Match the surrounding code's style, naming, and comment
|
||||
density. Do not introduce new dependencies or restructure working code unless
|
||||
the linked issue or stated task demands it.
|
||||
9. **Compiled workflows.** Agentic workflow Markdown, including the
|
||||
9. **Disclose AI automation.** When an agent creates or co-creates a PR or Issue,
|
||||
append a final body line with the model and effort used (e.g.
|
||||
`Assisted by: GPT-5.6 High`). Effort may be omitted when the runtime does not
|
||||
report it. Human contributors are not asked to disclose AI assistance.
|
||||
Disclosure is transparency only and carries no positive or negative weight.
|
||||
10. **Compiled workflows.** Agentic workflow Markdown, including the
|
||||
[AI-slop policy](.github/workflows/pr-ai-slop-review.md) and shared imports,
|
||||
is compiled: after editing it, run `gh aw compile` and commit the affected
|
||||
`.lock.yml` files. Never edit lock files directly.
|
||||
10. **Changelog.** Entries follow the rules in
|
||||
11. **Changelog.** Entries follow the rules in
|
||||
[`template/Changelog.md`](template/Changelog.md): one line per
|
||||
user-visible change, no internals.
|
||||
|
||||
@@ -63,8 +68,6 @@ the ownership evidence the AI-slop review evaluates (see
|
||||
- For code review and verification of review fixes, follow [REVIEW.md](REVIEW.md).
|
||||
Review is read-only unless changes are authorized; findings do not expand
|
||||
that authorization to unrelated fixes, commits, pushes, or GitHub updates.
|
||||
- For macOS frontend performance or WebView memory investigations, follow
|
||||
[scripts/perf/AGENTS.md](scripts/perf/AGENTS.md).
|
||||
- When handing work between agents or review rounds, use the
|
||||
[AI context sharing guidance](REVIEW.md#ai-context-sharing).
|
||||
- Read the relevant sections and linked module rules, expanding only when the
|
||||
@@ -73,5 +76,8 @@ the ownership evidence the AI-slop review evaluates (see
|
||||
|
||||
## Issue and PR Workflows
|
||||
|
||||
For Issue and PR work, read [`.github/AGENTS.md`](.github/AGENTS.md), including
|
||||
when using `gh` or an API without editing files under `.github/`.
|
||||
When drafting, triaging, splitting, or implementing from a community issue, use
|
||||
the conditional checklist in [`.github/ISSUE_GUIDELINES.md`](.github/ISSUE_GUIDELINES.md).
|
||||
Do not make GitHub issue changes without explicit authorization. For PRs, follow
|
||||
the directly loaded [PR template](.github/PULL_REQUEST_TEMPLATE.md); do not
|
||||
duplicate its prompts here.
|
||||
|
||||
+10
-8
@@ -81,20 +81,23 @@ pnpm run prebuild
|
||||
pnpm run prebuild --force # Re-download and overwrite Mihomo core and service binaries
|
||||
```
|
||||
|
||||
### Service Development
|
||||
### Prepare the Development Service Source
|
||||
|
||||
The app consumes the published `clash_verge_service_ipc` crate from its git tag (see [`src-tauri/Cargo.toml`](src-tauri/Cargo.toml)). To work on the Service itself, clone [`clash-verge-service-ipc`](https://github.com/clash-verge-rev/clash-verge-service-ipc) alongside `clash-verge-rev`, check out the matching tag, and temporarily point the dependency at the local path before building.
|
||||
`pnpm dev` builds the development service from a sibling checkout of [`clash-verge-service-ipc`](https://github.com/clash-verge-rev/clash-verge-service-ipc). The binaries downloaded by `pnpm prebuild` do not replace this source checkout.
|
||||
|
||||
Check the `clash_verge_service_ipc` dependency in [`src-tauri/Cargo.toml`](src-tauri/Cargo.toml), then clone the service repository alongside `clash-verge-rev` and check out the matching tag. If the sibling directory already exists, reuse it and check its version rather than overwriting it. Without this checkout, `pnpm dev` fails when it tries to access `../clash-verge-service-ipc/Cargo.toml`.
|
||||
|
||||
### Run the Development Server
|
||||
|
||||
Run these commands from the root of `clash-verge-rev`:
|
||||
|
||||
```bash
|
||||
pnpm dev # Start the desktop app in debug mode
|
||||
pnpm dev # Build the development service and start the desktop app
|
||||
pnpm dev:diff # Alias of pnpm dev
|
||||
pnpm dev:tauri # Run Tauri directly with the tauri-dev feature
|
||||
```
|
||||
|
||||
For frontend-only development, use `pnpm web:dev`. It does not start the Rust backend.
|
||||
For frontend-only development, use `pnpm web:dev`. It does not start the Rust backend or build the development service.
|
||||
|
||||
### Build the Project
|
||||
|
||||
@@ -165,10 +168,9 @@ to run every command for every change. Run commands from the repository root.
|
||||
|
||||
Tie results to the code reviewed: identify the base/head commits for branch
|
||||
comparisons and include task-relevant staged, unstaged, and untracked files in a
|
||||
local review. Keep command-level results in the working conversation. For PR
|
||||
descriptions, follow the [PR template](.github/PULL_REQUEST_TEMPLATE.md): include
|
||||
behavioral evidence and material gaps relevant to review, omitting routine check
|
||||
pass lists. No separate verification report is required. Static checks,
|
||||
local review. Report
|
||||
the command or interaction, observed result, and material gaps in the existing
|
||||
conversation or PR; no separate verification report is required. Static checks,
|
||||
mocks, browser previews, native runs, and remote CI establish different things.
|
||||
When code changes after verification, repeat affected checks. Attribute a failure
|
||||
to the baseline only after comparing the same check on the base revision.
|
||||
|
||||
Generated
+83
-103
@@ -159,9 +159,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "arc-swap"
|
||||
version = "1.9.5"
|
||||
version = "1.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "84a22b5d51209f6de83d37a0b33d320acb8da88823e42a94c075140708f032a5"
|
||||
checksum = "db4c94f57a570fce5d381be3289b3f79aef6332d72948fe82ab5772e423ccf92"
|
||||
dependencies = [
|
||||
"rustversion",
|
||||
]
|
||||
@@ -912,7 +912,7 @@ checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9"
|
||||
dependencies = [
|
||||
"semver 1.0.28",
|
||||
"serde",
|
||||
"toml 1.2.1+spec-1.1.0",
|
||||
"toml 1.1.6+spec-1.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1118,16 +1118,17 @@ dependencies = [
|
||||
"open",
|
||||
"parking_lot 0.13.0",
|
||||
"percent-encoding",
|
||||
"quick-xml 0.42.0",
|
||||
"reqwest 0.13.5",
|
||||
"reqwest_dav",
|
||||
"rfd 0.18.0",
|
||||
"runas",
|
||||
"rustls",
|
||||
"scopeguard",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_yaml_ng",
|
||||
"sha2 0.11.1",
|
||||
"smartstring",
|
||||
"socket2",
|
||||
"specta",
|
||||
"specta-typescript",
|
||||
@@ -1155,7 +1156,6 @@ dependencies = [
|
||||
"tokio-rustls",
|
||||
"tokio-util",
|
||||
"tracing",
|
||||
"tristr",
|
||||
"warp",
|
||||
"webpki-roots",
|
||||
"windows 0.62.2",
|
||||
@@ -1224,8 +1224,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clash_verge_service_ipc"
|
||||
version = "2.8.2"
|
||||
source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?branch=main#3e06ff153e9cb19ae20e0a61f861b371d3f7b2aa"
|
||||
version = "2.7.7"
|
||||
source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?tag=v2.7.7#3ed29700b093190b5e7addcaa892e77f172af544"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"kode-bridge",
|
||||
@@ -1329,7 +1329,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c"
|
||||
dependencies = [
|
||||
"lazy_static",
|
||||
"windows-sys 0.48.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2203,7 +2203,7 @@ dependencies = [
|
||||
"cc",
|
||||
"memchr",
|
||||
"rustc_version 0.4.1",
|
||||
"toml 1.2.1+spec-1.1.0",
|
||||
"toml 1.1.6+spec-1.1.0",
|
||||
"vswhom",
|
||||
"winreg 0.55.0",
|
||||
]
|
||||
@@ -3373,7 +3373,7 @@ dependencies = [
|
||||
"js-sys",
|
||||
"log",
|
||||
"wasm-bindgen",
|
||||
"windows-core 0.61.2",
|
||||
"windows-core 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3878,16 +3878,16 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "kode-bridge"
|
||||
version = "0.6.0"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b17456ae84ba9c0da0f189bf00d13019805b89563ba846cd15ccd8c4bd6a2713"
|
||||
checksum = "cdb14ea1ba42eebb57b46bcdd67a20f11a3f076d846ddf772c68d7439f6c6eca"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures",
|
||||
"http",
|
||||
"httparse",
|
||||
"libc",
|
||||
"parking_lot 0.13.0",
|
||||
"parking_lot 0.12.5",
|
||||
"path-tree",
|
||||
"pin-project-lite",
|
||||
"rand 0.10.2",
|
||||
@@ -3897,7 +3897,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
"tokio-util",
|
||||
"toml 1.2.1+spec-1.1.0",
|
||||
"toml 1.1.6+spec-1.1.0",
|
||||
"tracing",
|
||||
"url",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -4357,18 +4357,6 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nix"
|
||||
version = "0.32.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"cfg-if",
|
||||
"cfg_aliases",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nohash-hasher"
|
||||
version = "0.2.0"
|
||||
@@ -4895,7 +4883,7 @@ checksum = "9cf20a545b305cf1da722b236b5155c9bb35f1d5ceb28c048bd96ca842f41b5b"
|
||||
dependencies = [
|
||||
"android_system_properties",
|
||||
"log",
|
||||
"nix 0.31.3",
|
||||
"nix",
|
||||
"objc2",
|
||||
"objc2-foundation",
|
||||
"objc2-ui-kit",
|
||||
@@ -4909,7 +4897,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.45.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5265,7 +5253,7 @@ checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"indexmap 2.14.0",
|
||||
"quick-xml 0.41.0",
|
||||
"quick-xml",
|
||||
"serde",
|
||||
"time",
|
||||
]
|
||||
@@ -5535,15 +5523,6 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-xml"
|
||||
version = "0.42.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn"
|
||||
version = "0.11.11"
|
||||
@@ -6543,9 +6522,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "serde_spanned"
|
||||
version = "1.1.3"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
|
||||
checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
@@ -6811,6 +6790,18 @@ dependencies = [
|
||||
"thiserror 2.0.20",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smartstring"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a155190f9c039a1e9b6e92efbfa50ae68daad98a0fd6d5521a5a09ef782383e8"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"serde",
|
||||
"static_assertions",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.6.5"
|
||||
@@ -7082,9 +7073,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sysinfo"
|
||||
version = "0.40.3"
|
||||
version = "0.40.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a86bac2f7d06e6384984118ad727f5694110f0ec44d924d05c8fdec3d030bee6"
|
||||
checksum = "0e8a3edbe0394ce115f3917a00349dd242be09eb5a091ed509eaf67b55cfb8a8"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"memchr",
|
||||
@@ -7096,12 +7087,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sysproxy"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/clash-verge-rev/sysproxy-rs.git?rev=2c9d0a538052aac6e44ad413156a6e848da262b9#2c9d0a538052aac6e44ad413156a6e848da262b9"
|
||||
version = "0.7.1"
|
||||
source = "git+https://github.com/clash-verge-rev/sysproxy-rs.git?branch=main#89ad876a0942c049ae72e1472f9fc3ed62023c5e"
|
||||
dependencies = [
|
||||
"iptools",
|
||||
"log",
|
||||
"serde",
|
||||
"system-configuration",
|
||||
"thiserror 2.0.20",
|
||||
"tokio",
|
||||
@@ -7155,7 +7145,7 @@ dependencies = [
|
||||
"cfg-expr 0.20.9",
|
||||
"heck 0.5.0",
|
||||
"pkg-config",
|
||||
"toml 1.2.1+spec-1.1.0",
|
||||
"toml 1.1.6+spec-1.1.0",
|
||||
"version-compare",
|
||||
]
|
||||
|
||||
@@ -7247,9 +7237,9 @@ checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
|
||||
|
||||
[[package]]
|
||||
name = "tauri"
|
||||
version = "2.12.7"
|
||||
version = "2.12.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "30fbfbb9dc9a2697b0e96d909ddc295fb18d2d82a58ed542ab8d9eba2edbe6da"
|
||||
checksum = "5fb0244332cfb9cee7e2a568bf5da29a36ed8fdbd717f6f47a66b6b7b358c072"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bytes",
|
||||
@@ -7302,9 +7292,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-build"
|
||||
version = "2.7.6"
|
||||
version = "2.7.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73d80784e874fa117b9b00a6680cf2f9b8a51bbd14406bea980cf8f328b00646"
|
||||
checksum = "adddb0e648752aaac5da9c3c3c6a68e1e87cab55e3b757b18a9441ef8c3ac614"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"cargo_toml",
|
||||
@@ -7325,9 +7315,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-codegen"
|
||||
version = "2.7.6"
|
||||
version = "2.7.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c5dc6caab4da5646f57648f39b794bae118f0dd4a4305eeb8c892966171f4852"
|
||||
checksum = "fb37631cf71dab5e8ab55e1bdd701e18a52653d90b78e71d0e5598b1e0a61316"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"brotli",
|
||||
@@ -7340,7 +7330,7 @@ dependencies = [
|
||||
"semver 1.0.28",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.11.1",
|
||||
"sha2 0.10.9",
|
||||
"syn 2.0.119",
|
||||
"tauri-utils",
|
||||
"thiserror 2.0.20",
|
||||
@@ -7352,9 +7342,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-macros"
|
||||
version = "2.7.6"
|
||||
version = "2.7.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2831c5da8603a96b1efc0b650c2cb6decc69b6cda257d815fe70c7f5be53818e"
|
||||
checksum = "0cc38db58854c10fb5f91a887ed8bf82d3239bb92b5d8db86eda09e96d9963d1"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -7509,7 +7499,7 @@ dependencies = [
|
||||
"tauri-plugin",
|
||||
"tauri-utils",
|
||||
"thiserror 2.0.20",
|
||||
"toml 1.2.1+spec-1.1.0",
|
||||
"toml 1.1.6+spec-1.1.0",
|
||||
"url",
|
||||
]
|
||||
|
||||
@@ -7530,15 +7520,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-http"
|
||||
version = "2.9.0"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c278945f30912c8c32728265c66d16ca1b139509c4874d00579f5c8c5276605a"
|
||||
checksum = "2c57e3451553f95a1db3bfed6a358a77ce5080b6399a242c6eadac113f97abd2"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"cookie_store",
|
||||
"data-url",
|
||||
"http",
|
||||
"percent-encoding",
|
||||
"regex",
|
||||
"reqwest 0.12.28",
|
||||
"schemars 0.8.22",
|
||||
@@ -7555,8 +7544,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-mihomo"
|
||||
version = "0.7.1"
|
||||
source = "git+https://github.com/clash-verge-rev/tauri-plugin-mihomo?rev=7e4fa8642cf6c394ed88b5a969420d8eab60087f#7e4fa8642cf6c394ed88b5a969420d8eab60087f"
|
||||
version = "0.6.0"
|
||||
source = "git+https://github.com/clash-verge-rev/tauri-plugin-mihomo?rev=7a03d16f4d39b1bb885b7babe66b9e153e34b615#7a03d16f4d39b1bb885b7babe66b9e153e34b615"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"clashmap",
|
||||
@@ -7580,9 +7569,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-notification"
|
||||
version = "2.8.1"
|
||||
version = "2.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "14a226bfb8189ec4ab2c1936e66330ad06c44d9f6c54a674338208491dee177f"
|
||||
checksum = "5bc6c194a95a535abdfbe3bc1af9a43935b8b9b29c216b8e71af8b59132703cf"
|
||||
dependencies = [
|
||||
"log",
|
||||
"notify-rust",
|
||||
@@ -7600,9 +7589,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-opener"
|
||||
version = "2.7.3"
|
||||
version = "2.7.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "54592c6718b42ab198bf11bda6a428a3553ca2f2f8e506df56f6a063ec328331"
|
||||
checksum = "53810be1b4fed22bb6ac3f4cab5a2b80d9391d1af436bda145607532bc0bb219"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"glob",
|
||||
@@ -7727,9 +7716,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-runtime"
|
||||
version = "2.12.4"
|
||||
version = "2.12.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "60c2b14bd5265b63993cdc34ad526fb836e0fd0cf64a4634a895db0784844d5e"
|
||||
checksum = "7c55766d99cea69055904d1735b93c2049302b2e09effd462120deb5581d78e9"
|
||||
dependencies = [
|
||||
"cookie",
|
||||
"dpi",
|
||||
@@ -7752,9 +7741,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-runtime-wry"
|
||||
version = "2.12.5"
|
||||
version = "2.12.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8c14a025255cc9816d401635035075b09b6cc9973b7b8fd7b8fcb8753f30f92"
|
||||
checksum = "e1aa9d8b7a120f879f44fdc1053f7b7dbf416bf0bbc6a72b714dec46b782b52f"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"http",
|
||||
@@ -7810,9 +7799,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-utils"
|
||||
version = "2.10.4"
|
||||
version = "2.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28d1d33d4453c5df0bf1672dbc7ada69d8ed74f56a4316d964a4aa73d4ecd3ad"
|
||||
checksum = "362ab21cd4cc713f2a02b1a9b5688198b1541cfb6907c4281e9190e0f0ef4aa3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"brotli",
|
||||
@@ -7839,7 +7828,7 @@ dependencies = [
|
||||
"serde_with",
|
||||
"swift-rs",
|
||||
"thiserror 2.0.20",
|
||||
"toml 1.2.1+spec-1.1.0",
|
||||
"toml 1.1.6+spec-1.1.0",
|
||||
"url",
|
||||
"urlpattern",
|
||||
"uuid",
|
||||
@@ -7854,7 +7843,7 @@ checksum = "cc65d45c68858bfe420dd29e834b5d15dbecf8a07a8a16cf4d532c7b1f69d4b6"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"embed-resource",
|
||||
"toml 1.2.1+spec-1.1.0",
|
||||
"toml 1.1.6+spec-1.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7875,7 +7864,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.3.4",
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix 1.1.4",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -8220,14 +8209,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "1.2.1+spec-1.1.0"
|
||||
version = "1.1.6+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7"
|
||||
checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a"
|
||||
dependencies = [
|
||||
"indexmap 2.14.0",
|
||||
"serde_core",
|
||||
"serde_spanned 1.1.3",
|
||||
"toml_datetime 1.1.3+spec-1.1.0",
|
||||
"serde_spanned 1.1.1",
|
||||
"toml_datetime 1.1.1+spec-1.1.0",
|
||||
"toml_parser",
|
||||
"toml_writer",
|
||||
"winnow 1.0.4",
|
||||
@@ -8244,9 +8233,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "1.1.3+spec-1.1.0"
|
||||
version = "1.1.1+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
|
||||
checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
@@ -8294,16 +8283,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b"
|
||||
dependencies = [
|
||||
"indexmap 2.14.0",
|
||||
"toml_datetime 1.1.3+spec-1.1.0",
|
||||
"toml_datetime 1.1.1+spec-1.1.0",
|
||||
"toml_parser",
|
||||
"winnow 1.0.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_parser"
|
||||
version = "1.1.5+spec-1.1.0"
|
||||
version = "1.1.3+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
|
||||
checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"
|
||||
dependencies = [
|
||||
"winnow 1.0.4",
|
||||
]
|
||||
@@ -8316,9 +8305,9 @@ checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
|
||||
|
||||
[[package]]
|
||||
name = "toml_writer"
|
||||
version = "1.2.0+spec-1.1.0"
|
||||
version = "1.1.2+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
|
||||
checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
|
||||
|
||||
[[package]]
|
||||
name = "tonic"
|
||||
@@ -8575,15 +8564,6 @@ dependencies = [
|
||||
"stable_deref_trait",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tristr"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/Tunglies/tristr?rev=d849e5cff47a570849c2e1bada0a2b6481cf3378#d849e5cff47a570849c2e1bada0a2b6481cf3378"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"specta",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "try-lock"
|
||||
version = "0.2.5"
|
||||
@@ -8840,9 +8820,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "warp"
|
||||
version = "0.4.4"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c92be475cc42b6b3913eeac77f0cbc0dd8f6a1ad6400c0722dbe36ba0c3ee799"
|
||||
checksum = "c0a808122a8a77eecdabaefd88ddb1913c4be5ea1465399f63ba64c7aa705fea"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-channel",
|
||||
@@ -9008,7 +8988,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quick-xml 0.41.0",
|
||||
"quick-xml",
|
||||
"quote",
|
||||
]
|
||||
|
||||
@@ -9108,9 +9088,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "1.0.12"
|
||||
version = "1.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297"
|
||||
checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
@@ -9204,7 +9184,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.48.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -10146,9 +10126,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "9.6.0"
|
||||
version = "9.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "80cc68510ea7553c30a69c732de5278e94183f68765af6c642dbccefd6ec777e"
|
||||
checksum = "df3845f734baabdd02de353a20580e30ceccd03897def44a4eb8e9654992e294"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"bzip2",
|
||||
@@ -10162,7 +10142,7 @@ dependencies = [
|
||||
"libc",
|
||||
"lzma-rust2",
|
||||
"memchr",
|
||||
"nix 0.32.0",
|
||||
"nix",
|
||||
"pbkdf2",
|
||||
"ppmd-rust",
|
||||
"sha1 0.11.0",
|
||||
|
||||
+3
-3
@@ -61,7 +61,7 @@ tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", bra
|
||||
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
|
||||
tracing = "0.1.44"
|
||||
|
||||
tauri = { version = "2.12.7" }
|
||||
tauri = { version = "2.12.5" }
|
||||
tauri-plugin-clipboard-manager = "2.5.0"
|
||||
parking_lot = "0.13.0"
|
||||
anyhow = "1.0.104"
|
||||
@@ -84,8 +84,9 @@ reqwest = { version = "0.13.5", features = [
|
||||
] }
|
||||
rust_iso3166 = "0.2.0"
|
||||
|
||||
smartstring = { version = "2.0.0" }
|
||||
|
||||
serde = { version = "1.0.229" }
|
||||
tristr = { git = "https://github.com/Tunglies/tristr", rev = "d849e5cff47a570849c2e1bada0a2b6481cf3378", default-features = false, features = ["serde", "specta"] }
|
||||
serde_json = { version = "1.0.154" }
|
||||
serde_yaml_ng = { version = "0.10.0" }
|
||||
socket2 = "0.6.5"
|
||||
@@ -131,7 +132,6 @@ large_const_arrays = "warn"
|
||||
large_futures = "deny"
|
||||
large_stack_arrays = "warn"
|
||||
large_types_passed_by_value = "deny"
|
||||
map_unwrap_or = "deny"
|
||||
missing_const_for_fn = "deny"
|
||||
mutex_atomic = "deny"
|
||||
mutex_integer = "deny"
|
||||
|
||||
+1
-30
@@ -13,8 +13,6 @@
|
||||
first (Windows/macOS/Linux) when the change is platform-specific;
|
||||
merge sub-symptoms as 主题:症状、症状; full-width punctuation,
|
||||
「」 for UI labels, backticks for config keys and commands
|
||||
- omit the redundant suffix 「的问题」; end with the concrete symptom
|
||||
or outcome instead
|
||||
- platform entries sit under their platform heading (bold, emoji
|
||||
prefixed, ordered Windows/macOS/Linux, combined for pairs like
|
||||
macOS/Linux) at the end of their section;
|
||||
@@ -23,61 +21,34 @@
|
||||
GitHub, so they never reach users. -->
|
||||
## v2.6.0
|
||||
|
||||
- **Mihomo 内核升级至 v1.19.34**
|
||||
|
||||
<details>
|
||||
<summary><strong> 🐞 修复问题 </strong></summary>
|
||||
|
||||
- 修复「外部控制器」复制成功的提示一闪而过
|
||||
- 修复订阅的规则、代理组、节点编辑器快速连续操作时条目可能重复或错位
|
||||
- 修复检测更新后又发布新版时,应用内更新失败
|
||||
- 修复订阅响应过大导致内存占用过高,限制单次下载为 4 MiB
|
||||
- 修复全局模式默认停在 `DIRECT` 或 `REJECT` 导致流量未经代理,现自动切换到第一个策略组
|
||||
- 修复订阅中未加引号的 REALITY `short-id`(如 `1234e123`)被误读为数字,导致订阅无法启用
|
||||
- 修复订阅中唯一的代理组名为 `GLOBAL` 或没有代理组时,规则模式下代理页面显示「未获取到代理信息」
|
||||
- 修复窗口较窄时,首页「当前节点」卡片中过长的节点名把延迟标签挤出卡片
|
||||
- 修复断开链式代理时清空已选节点,导致再次连接需要重新选择
|
||||
- 修复「连接」页表格排序时表头换行、标题位置跳动
|
||||
- 修复「TUN 设置」未手动保存时,界面显示的默认 MTU 1500 未生效
|
||||
- 修复连接详情较窄时操作按钮偏离右侧
|
||||
- 修复「链式代理」节点列表按名称排序,未保持订阅中的节点顺序
|
||||
- 修复规则模式下 Muse AI 解锁检测显示错误的出口地区
|
||||
- 修复使用系统代理或本地代理认证时首页 IP 信息显示直连地址或报错
|
||||
|
||||
**🖥️ Windows**
|
||||
|
||||
- 修复 Windows 普通用户因权限不足无法开启「开机自启」
|
||||
- 修复切换订阅后节点延迟显示旧订阅结果,进入代理页面时主动刷新延迟记录
|
||||
|
||||
**🍎 macOS**
|
||||
|
||||
- 修复 macOS TUN 模式下原有 DNS 被清除、关闭后 DNS 未恢复及联网后设置未生效
|
||||
- 修复 macOS 断网时误报代理已回退直连,恢复联网后自动重试系统代理
|
||||
- 修复 macOS 切换主题后标题栏保留原有深浅色
|
||||
|
||||
**🐧 Linux**
|
||||
|
||||
- 修复 Linux OpenRC 环境下服务安装失败
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong> ✨ 新增功能 </strong></summary>
|
||||
|
||||
- 新增连接页面按网络协议(TCP/UDP)筛选连接
|
||||
- 新增从连接详情设置域名、进程或源/目标 IP 规则,支持识别主域、匹配子域、自定义 IP 网段及修改已有规则
|
||||
- 新增规则模式下在规则流量未经过的代理组选节点时,自动将首个包含该组的 `select` 代理组切换到该组,可在「杂项设置」关闭
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong> 🚀 优化改进 </strong></summary>
|
||||
|
||||
- 优化设置页打开时的开销:布局设置弹窗首次打开时才加载图标
|
||||
- 优化连接、规则和日志筛选:切换页面后保留过滤条件
|
||||
- 优化全局模式代理列表:仅显示 `GLOBAL` 节点,选中其中的策略组时才显示该组
|
||||
- 优化设置页开关和选项所在行的鼠标悬停高亮,便于对应说明与控件
|
||||
- 优化首页「当前节点」卡片:按规则指向的代理组逐级显示和切换实际生效的节点,选中后下拉菜单自动收起
|
||||
- 优化延迟测试:节点超时后自动重测一次再显示结果,减少网络波动造成的误报
|
||||
|
||||
**🍎 macOS**
|
||||
|
||||
|
||||
@@ -108,10 +108,11 @@ pnpm run prebuild
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
`pnpm dev` runs the desktop app in debug mode against the single Service
|
||||
channel: an installed service is reused, and an uninstalled one keeps the app
|
||||
in Sidecar mode. Debug sessions keep their profiles and settings in the
|
||||
isolated `.dev` application data directory.
|
||||
`pnpm dev` preserves the Development Channel's installed service state: an
|
||||
existing service is used, while a previously uninstalled service remains
|
||||
uninstalled and the app starts in Sidecar mode. Use `pnpm dev:service` to
|
||||
explicitly install or update the isolated development service before launch,
|
||||
or `pnpm dev:sidecar` to force the unprivileged Sidecar workflow.
|
||||
|
||||
## Contributions
|
||||
|
||||
|
||||
@@ -15,6 +15,3 @@ tokio = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
criterion = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -19,7 +19,6 @@ fn make_draft() -> Draft<IVerge> {
|
||||
}
|
||||
|
||||
pub fn bench_draft(c: &mut Criterion) {
|
||||
#[allow(clippy::panic, reason = "bench setup cannot proceed without a runtime")]
|
||||
let rt = Runtime::new().unwrap_or_else(|e| panic!("Tokio runtime init failed: {e}"));
|
||||
|
||||
let mut group = c.benchmark_group("draft");
|
||||
|
||||
@@ -102,7 +102,6 @@ impl<T: Clone> Draft<T> {
|
||||
let (local, original_arc) = {
|
||||
let guard = self.inner.data.lock();
|
||||
let arc = Arc::clone(&guard.0);
|
||||
drop(guard);
|
||||
((**arc).clone(), arc)
|
||||
};
|
||||
let (new_local, res) = f(local).await?;
|
||||
@@ -113,7 +112,6 @@ impl<T: Clone> Draft<T> {
|
||||
));
|
||||
}
|
||||
guard.0 = Arc::new(Box::new(new_local));
|
||||
drop(guard);
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
@@ -127,10 +125,7 @@ impl<T: Clone> Draft<T> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
async fn acquire_data_modify_permit(&self) -> DataModifyPermit<'_>
|
||||
where
|
||||
T: Send + Sync,
|
||||
{
|
||||
async fn acquire_data_modify_permit(&self) -> DataModifyPermit<'_> {
|
||||
for _ in 0..DATA_MODIFY_FAST_RETRY_YIELDS {
|
||||
if let Some(permit) = self.try_acquire_data_modify_permit() {
|
||||
return permit;
|
||||
|
||||
@@ -15,6 +15,3 @@ default = []
|
||||
tokio-trace = ["tracing-estuary/tokio-trace"]
|
||||
chrome-trace = ["tracing-estuary/chrome-trace"]
|
||||
color = ["tracing-estuary/color"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -160,7 +160,7 @@ pub struct Logger {
|
||||
static LOGGER: OnceLock<Logger> = OnceLock::new();
|
||||
|
||||
impl Logger {
|
||||
const fn new() -> Self {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
pipeline: OnceLock::new(),
|
||||
sidecar_file_writer: RwLock::new(None),
|
||||
@@ -185,7 +185,7 @@ impl Logger {
|
||||
self.store_config(cfg);
|
||||
let pipeline = tracing_estuary::PipelineBuilder::new()
|
||||
.default_level(log_level)
|
||||
.file_writer(self.generate_file_log_writer())
|
||||
.file_writer(self.generate_file_log_writer()?)
|
||||
.init()?;
|
||||
self.pipeline.set(pipeline).ok();
|
||||
Ok(())
|
||||
@@ -206,10 +206,10 @@ impl Logger {
|
||||
.map(|s| (*s).to_string())
|
||||
.or_else(|| info.payload().downcast_ref::<String>().cloned())
|
||||
.unwrap_or_else(|| "Unknown panic payload".to_string());
|
||||
let location = info.location().map_or_else(
|
||||
|| "Unknown location".to_string(),
|
||||
|loc| format!("{}:{}", loc.file(), loc.line()),
|
||||
);
|
||||
let location = info
|
||||
.location()
|
||||
.map(|loc| format!("{}:{}", loc.file(), loc.line()))
|
||||
.unwrap_or_else(|| "Unknown location".to_string());
|
||||
logging!(error, Type::System, "Panic occurred at {}: {}", location, payload);
|
||||
Self::global().flush_logs();
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
@@ -225,11 +225,11 @@ impl Logger {
|
||||
self.log_max_count.store(cfg.max_count, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
fn generate_file_log_writer(&self) -> FileLogWriterBuilder {
|
||||
fn generate_file_log_writer(&self) -> Result<FileLogWriterBuilder> {
|
||||
let log_dir = self.log_dir.get().cloned().unwrap_or_default();
|
||||
let log_max_size = self.log_max_size.load(Ordering::SeqCst);
|
||||
let log_max_count = self.log_max_count.load(Ordering::SeqCst);
|
||||
FileLogWriter::builder(FileSpec::default().directory(log_dir).basename(""))
|
||||
let flwb = FileLogWriter::builder(FileSpec::default().directory(log_dir).basename(""))
|
||||
.format(tracing_estuary::file_format_with_level)
|
||||
.write_mode(flexi_logger::WriteMode::BufferAndFlushWith(
|
||||
WRITE_BUFFER_CAPACITY,
|
||||
@@ -239,7 +239,8 @@ impl Logger {
|
||||
Criterion::Size(log_max_size * 1024),
|
||||
ROTATE_NAMING,
|
||||
Cleanup::KeepLogFiles(log_max_count),
|
||||
)
|
||||
);
|
||||
Ok(flwb)
|
||||
}
|
||||
|
||||
/// Ensures the sidecar writer exists and points at `builder`'s config:
|
||||
@@ -310,7 +311,7 @@ impl Logger {
|
||||
self.log_max_size.store(log_max_size, Ordering::SeqCst);
|
||||
self.log_max_count.store(log_max_count, Ordering::SeqCst);
|
||||
if let Some(pipeline) = self.pipeline.get() {
|
||||
let log_file_writer = self.generate_file_log_writer();
|
||||
let log_file_writer = self.generate_file_log_writer()?;
|
||||
if let Some(sink) = pipeline.sink.as_ref() {
|
||||
sink.reset(log_file_writer)
|
||||
.map_err(|error| anyhow::anyhow!("failed to reset log writer: {error}"))?;
|
||||
|
||||
@@ -13,13 +13,14 @@ pub(super) async fn check_chatgpt(client: &Client) -> UnlockItem {
|
||||
|
||||
let web_status = get_text(client, "https://api.openai.com/compliance/cookie_requirements")
|
||||
.await
|
||||
.map_or("Failed", |body| {
|
||||
.map(|body| {
|
||||
if body.to_ascii_lowercase().contains("unsupported_country") {
|
||||
"Unsupported Country/Region"
|
||||
} else {
|
||||
"Yes"
|
||||
}
|
||||
});
|
||||
})
|
||||
.unwrap_or("Failed");
|
||||
|
||||
UnlockItem::checked(CHATGPT_WEB_NAME, web_status, region)
|
||||
}
|
||||
|
||||
@@ -157,10 +157,11 @@ async fn is_unavailable(client: &Client) -> bool {
|
||||
.get("https://disneyplus.com")
|
||||
.send()
|
||||
.await
|
||||
.map_or(true, |response| {
|
||||
.map(|response| {
|
||||
let url = response.url().as_str();
|
||||
url.contains("preview") || url.contains("unavailable")
|
||||
})
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
async fn fallback_region(client: &Client) -> Option<UnlockItem> {
|
||||
|
||||
@@ -1,23 +1,28 @@
|
||||
use reqwest::Client;
|
||||
|
||||
use crate::utils::classify_restricted_status;
|
||||
use crate::utils::{classify_restricted_status, get_trace_location};
|
||||
|
||||
use super::UnlockItem;
|
||||
|
||||
pub(crate) const MUSE_AI_NAME: &str = "Muse AI";
|
||||
|
||||
const MUSE_URL: &str = "https://muse.ai";
|
||||
const CLOUDFLARE_TRACE_URL: &str = "https://www.cloudflare.com/cdn-cgi/trace";
|
||||
|
||||
// The aymh ("Are You a Human") gateway answers plain HTTP requests with a
|
||||
// generic Meta error page that always contains the Facebook logo asset.
|
||||
const AYMH_ERROR_MARKERS: &[&str] = &["Sorry, something went wrong", "static.facebook.com/images/logos"];
|
||||
|
||||
pub(super) async fn check_muse_ai(client: &Client) -> UnlockItem {
|
||||
// muse.ai is served by Vercel and does not expose a service-specific region trace endpoint.
|
||||
// Querying a generic third-party domain (e.g. www.cloudflare.com/cdn-cgi/trace) would report
|
||||
// that domain's proxy group rather than muse.ai's actual exit in Rule mode, so leave region as None.
|
||||
// muse.ai itself is served by Vercel, so resolve the exit region through
|
||||
// the generic Cloudflare trace endpoint instead of a service-specific one.
|
||||
let region = get_trace_location(client, CLOUDFLARE_TRACE_URL)
|
||||
.await
|
||||
.map(|code| code.trim().to_ascii_uppercase())
|
||||
.map(|code| UnlockItem::region_label(&code));
|
||||
|
||||
let Ok(response) = client.get(MUSE_URL).send().await else {
|
||||
return UnlockItem::checked(MUSE_AI_NAME, "Failed (Network Connection)", None);
|
||||
return UnlockItem::checked(MUSE_AI_NAME, "Failed (Network Connection)", region);
|
||||
};
|
||||
|
||||
let status = response.status();
|
||||
@@ -39,5 +44,5 @@ pub(super) async fn check_muse_ai(client: &Client) -> UnlockItem {
|
||||
classify_restricted_status(status).unwrap_or("Failed")
|
||||
};
|
||||
|
||||
UnlockItem::checked(MUSE_AI_NAME, result, None)
|
||||
UnlockItem::checked(MUSE_AI_NAME, result, region)
|
||||
}
|
||||
|
||||
@@ -114,10 +114,11 @@ async fn check_netflix_cdn(client: &Client) -> UnlockItem {
|
||||
}
|
||||
|
||||
match response.json::<FastResponse>().await {
|
||||
Ok(data) => data.targets.first().map_or_else(
|
||||
|| item("Unknown"),
|
||||
|target| UnlockItem::checked_region(NETFLIX_NAME, "Yes", &target.location.country),
|
||||
),
|
||||
Ok(data) => data
|
||||
.targets
|
||||
.first()
|
||||
.map(|target| UnlockItem::checked_region(NETFLIX_NAME, "Yes", &target.location.country))
|
||||
.unwrap_or_else(|| item("Unknown")),
|
||||
Err(e) => {
|
||||
logging!(error, Type::Network, "解析 Fast.com API 响应失败: {e}");
|
||||
item("Failed (解析错误)")
|
||||
|
||||
@@ -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.3", default-features = false, features = ["network", "system"] }
|
||||
sysinfo = { version = "0.40.1", default-features = false, features = ["network", "system"] }
|
||||
|
||||
[target.'cfg(not(windows))'.dependencies]
|
||||
libc = "0.2.191"
|
||||
|
||||
@@ -118,7 +118,8 @@ fn is_binary_admin() -> bool {
|
||||
#[cfg(windows)]
|
||||
Token::with_current_process()
|
||||
.and_then(|token| token.privilege_level())
|
||||
.is_ok_and(|level| level != PrivilegeLevel::NotPrivileged)
|
||||
.map(|level| level != PrivilegeLevel::NotPrivileged)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
"duplicates",
|
||||
"cycles"
|
||||
],
|
||||
"ignoreBinaries": ["diff", "rustc"],
|
||||
"ignoreBinaries": ["rustc", "cc"],
|
||||
"ignoreDependencies": ["lint-staged"],
|
||||
"ignoreIssues": {
|
||||
"src/types/generated/**": ["exports", "types"],
|
||||
|
||||
+22
-12
@@ -4,7 +4,11 @@
|
||||
"license": "GPL-3.0-only",
|
||||
"scripts": {
|
||||
"prepare": "husky || true",
|
||||
"dev": "cross-env RUST_BACKTRACE=full tauri dev",
|
||||
"dev": "node scripts/dev.mjs dev",
|
||||
"dev:service": "node scripts/dev.mjs service",
|
||||
"dev:sidecar": "node scripts/dev.mjs sidecar",
|
||||
"dev:diff": "node scripts/dev.mjs dev",
|
||||
"dev:trace": "node scripts/dev.mjs trace",
|
||||
"dev:tauri": "cross-env RUST_BACKTRACE=full tauri dev -f tauri-dev",
|
||||
"build": "cross-env NODE_OPTIONS='--max-old-space-size=4096' tauri build",
|
||||
"build:fast": "cross-env NODE_OPTIONS='--max-old-space-size=4096' tauri build -- --profile fast-release",
|
||||
@@ -32,7 +36,11 @@
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"knip:check": "knip",
|
||||
"knip:report": "knip --no-exit-code"
|
||||
"knip:report": "knip --no-exit-code",
|
||||
"perf:build": "node scripts/perf/build.mjs",
|
||||
"perf:run": "node scripts/perf/run.mjs",
|
||||
"perf:compare": "node scripts/perf/compare.mjs",
|
||||
"perf:test": "node --test scripts/perf/report.test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dnd-kit/collision": "^0.5.0",
|
||||
@@ -46,12 +54,12 @@
|
||||
"@mui/icons-material": "^9.4.0",
|
||||
"@mui/material": "^9.4.0",
|
||||
"@tanstack/react-virtual": "^3.14.13",
|
||||
"@tauri-apps/api": "2.12.5",
|
||||
"@tauri-apps/api": "2.12.4",
|
||||
"@tauri-apps/plugin-clipboard-manager": "2.5.0",
|
||||
"@tauri-apps/plugin-dialog": "2.8.4",
|
||||
"@tauri-apps/plugin-fs": "2.7.1",
|
||||
"@tauri-apps/plugin-http": "2.9.0",
|
||||
"@tauri-apps/plugin-opener": "2.7.3",
|
||||
"@tauri-apps/plugin-http": "2.8.3",
|
||||
"@tauri-apps/plugin-opener": "2.7.2",
|
||||
"@tauri-apps/plugin-updater": "2.14.1",
|
||||
"ahooks": "^3.10.0",
|
||||
"cidr-block": "^2.3.0",
|
||||
@@ -59,7 +67,7 @@
|
||||
"dayjs": "1.11.23",
|
||||
"foxact": "^0.3.12",
|
||||
"foxts": "^5.9.1",
|
||||
"i18next": "^27.0.0",
|
||||
"i18next": "^26.4.2",
|
||||
"js-yaml": "^5.4.2",
|
||||
"lodash-es": "^4.18.1",
|
||||
"meta-json-schema": "^1.19.31",
|
||||
@@ -71,14 +79,13 @@
|
||||
"react-dom": "19.3.1",
|
||||
"react-error-boundary": "6.1.6",
|
||||
"react-hook-form": "^7.88.0",
|
||||
"react-i18next": "18.0.3",
|
||||
"react-i18next": "17.1.13",
|
||||
"react-markdown": "10.1.0",
|
||||
"react-router": "^8.4.0",
|
||||
"rehype-raw": "^7.0.0",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"swr": "^2.5.1",
|
||||
"tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#main",
|
||||
"tldts": "7.4.19",
|
||||
"types-pac": "^1.0.3",
|
||||
"validator": "^13.15.35"
|
||||
},
|
||||
@@ -87,7 +94,7 @@
|
||||
"@biomejs/biome": "^2.5.14",
|
||||
"@eslint-react/eslint-plugin": "^5.20.5",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@tauri-apps/cli": "2.12.6",
|
||||
"@tauri-apps/cli": "2.12.4",
|
||||
"@types/lodash-es": "^4.17.12",
|
||||
"@types/node": "^26.0.0",
|
||||
"@types/react": "19.3.0",
|
||||
@@ -95,6 +102,7 @@
|
||||
"@types/validator": "^13.15.10",
|
||||
"@vitejs/plugin-legacy": "^8.2.3",
|
||||
"@vitejs/plugin-react": "^6.1.1",
|
||||
"@wdio/tauri-service": "1.5.1",
|
||||
"adm-zip": "^0.6.1",
|
||||
"axios": "^1.20.0",
|
||||
"cli-color": "^2.0.4",
|
||||
@@ -113,7 +121,7 @@
|
||||
"https-proxy-agent": "^9.1.0",
|
||||
"husky": "^9.1.7",
|
||||
"jiti": "^2.7.0",
|
||||
"knip": "6.47.0",
|
||||
"knip": "6.44.2",
|
||||
"lint-staged": "^17.5.1",
|
||||
"sass": "^1.104.1",
|
||||
"tar": "^7.5.22",
|
||||
@@ -123,7 +131,9 @@
|
||||
"typescript-eslint": "^8.70.0",
|
||||
"vite": "^8.3.0",
|
||||
"vite-plugin-svgr": "^5.2.0",
|
||||
"vitest": "^5.0.1"
|
||||
"vitest": "^5.0.1",
|
||||
"webdriverio": "10.2.0",
|
||||
"ws": "8.22.2"
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.{ts,tsx,js,mjs}": [
|
||||
@@ -135,5 +145,5 @@
|
||||
]
|
||||
},
|
||||
"type": "module",
|
||||
"packageManager": "pnpm@12.21.0"
|
||||
"packageManager": "pnpm@12.18.0"
|
||||
}
|
||||
|
||||
Generated
+1894
-191
File diff suppressed because it is too large
Load Diff
+6
-1
@@ -50,7 +50,12 @@
|
||||
},
|
||||
{
|
||||
"description": "Update Tauri npm packages and Cargo crates together so frontend and backend stay in sync",
|
||||
"matchPackageNames": ["@tauri-apps/**", "tauri", "tauri-*"],
|
||||
"matchPackageNames": [
|
||||
"@tauri-apps/**",
|
||||
"@wdio/tauri-service",
|
||||
"tauri",
|
||||
"tauri-*"
|
||||
],
|
||||
"groupName": "tauri",
|
||||
"addLabels": ["tauri"]
|
||||
},
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
[toolchain]
|
||||
channel = "1.100.0"
|
||||
channel = "1.99.1"
|
||||
components = ["rustfmt", "clippy"]
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
import { constants } from 'node:fs'
|
||||
import { open } from 'node:fs/promises'
|
||||
import { request } from 'node:http'
|
||||
import { connect } from 'node:net'
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 10_000
|
||||
const DEFAULT_RETRY_DELAY_MS = 100
|
||||
const TRANSIENT_REQUEST_ERRORS = new Set([
|
||||
'ECONNREFUSED',
|
||||
'ECONNRESET',
|
||||
'EPIPE',
|
||||
'ETIMEDOUT',
|
||||
])
|
||||
const SAFE_REQUEST_ERROR_CODES = new Set([
|
||||
...TRANSIENT_REQUEST_ERRORS,
|
||||
'EACCES',
|
||||
'EINVAL',
|
||||
'ENOTFOUND',
|
||||
])
|
||||
|
||||
function validateInstanceRecord(record) {
|
||||
if (
|
||||
!record ||
|
||||
!Number.isInteger(record.port) ||
|
||||
record.port < 1 ||
|
||||
record.port > 65_535
|
||||
) {
|
||||
throw new Error('invalid instance record port')
|
||||
}
|
||||
if (
|
||||
typeof record.token !== 'string' ||
|
||||
!/^[0-9a-f]{64}$/.test(record.token)
|
||||
) {
|
||||
throw new Error('invalid instance record token')
|
||||
}
|
||||
return { port: record.port, token: record.token }
|
||||
}
|
||||
|
||||
function delay(milliseconds) {
|
||||
return new Promise((resolve) => setTimeout(resolve, milliseconds))
|
||||
}
|
||||
|
||||
function safeRequestError(error) {
|
||||
const code = SAFE_REQUEST_ERROR_CODES.has(error?.code)
|
||||
? error.code
|
||||
: 'UNKNOWN'
|
||||
const cause = new Error(code)
|
||||
cause.code = code
|
||||
return new Error('dev quit request failed', { cause })
|
||||
}
|
||||
|
||||
export async function readPrivateInstanceRecord(path, expectedUid) {
|
||||
let handle
|
||||
try {
|
||||
handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)
|
||||
const stat = await handle.stat()
|
||||
if (!stat.isFile()) {
|
||||
throw new Error('instance record must be an ordinary file')
|
||||
}
|
||||
if (stat.uid !== expectedUid) {
|
||||
throw new Error('instance record has the wrong owner')
|
||||
}
|
||||
if ((stat.mode & 0o777) !== 0o600) {
|
||||
throw new Error('instance record permissions must be 0600')
|
||||
}
|
||||
const contents = await handle.readFile({ encoding: 'utf8' })
|
||||
let record
|
||||
try {
|
||||
record = JSON.parse(contents)
|
||||
} catch {
|
||||
throw new Error('instance record is not valid JSON')
|
||||
}
|
||||
return validateInstanceRecord(record)
|
||||
} finally {
|
||||
await handle?.close()
|
||||
}
|
||||
}
|
||||
|
||||
function postDevQuit(record, timeoutMs, requestImpl) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false
|
||||
const settle = (callback, value) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
callback(value)
|
||||
}
|
||||
const outgoing = requestImpl(
|
||||
{
|
||||
host: '127.0.0.1',
|
||||
port: record.port,
|
||||
path: '/commands/dev/quit',
|
||||
method: 'POST',
|
||||
agent: false,
|
||||
headers: {
|
||||
'X-Instance-Token': record.token,
|
||||
},
|
||||
},
|
||||
(response) => {
|
||||
response.on('aborted', () => {})
|
||||
response.on('error', () => {})
|
||||
response.on('close', () => {})
|
||||
settle(resolve, response.statusCode)
|
||||
response.destroy()
|
||||
},
|
||||
)
|
||||
outgoing.once('error', (error) => settle(reject, error))
|
||||
outgoing.setTimeout(timeoutMs, () => {
|
||||
const error = new Error('dev quit request timed out')
|
||||
error.code = 'ETIMEDOUT'
|
||||
outgoing.destroy(error)
|
||||
})
|
||||
outgoing.end()
|
||||
})
|
||||
}
|
||||
|
||||
export async function requestDevQuit(
|
||||
recordOrReader,
|
||||
{
|
||||
timeoutMs = DEFAULT_TIMEOUT_MS,
|
||||
retryDelayMs = DEFAULT_RETRY_DELAY_MS,
|
||||
requestImpl = request,
|
||||
now = Date.now,
|
||||
sleep = delay,
|
||||
} = {},
|
||||
) {
|
||||
const deadline = now() + timeoutMs
|
||||
const readRecord =
|
||||
typeof recordOrReader === 'function'
|
||||
? recordOrReader
|
||||
: async () => recordOrReader
|
||||
|
||||
while (now() < deadline) {
|
||||
let record
|
||||
try {
|
||||
record = validateInstanceRecord(await readRecord())
|
||||
} catch (error) {
|
||||
if (error?.code !== 'ENOENT') {
|
||||
throw error
|
||||
}
|
||||
await sleep(Math.min(retryDelayMs, Math.max(0, deadline - now())))
|
||||
continue
|
||||
}
|
||||
|
||||
const remainingMs = Math.max(1, deadline - now())
|
||||
let status
|
||||
try {
|
||||
status = await postDevQuit(record, remainingMs, requestImpl)
|
||||
} catch (error) {
|
||||
if (!TRANSIENT_REQUEST_ERRORS.has(error?.code)) {
|
||||
throw safeRequestError(error)
|
||||
}
|
||||
await sleep(Math.min(retryDelayMs, Math.max(0, deadline - now())))
|
||||
continue
|
||||
}
|
||||
if (status === 202) {
|
||||
return record
|
||||
}
|
||||
if (status !== 503) {
|
||||
throw new Error(
|
||||
`dev quit request returned HTTP ${status ?? 'without a status'}`,
|
||||
)
|
||||
}
|
||||
await sleep(Math.min(retryDelayMs, Math.max(0, deadline - now())))
|
||||
}
|
||||
|
||||
throw new Error('timed out waiting for the dev quit request to be accepted')
|
||||
}
|
||||
|
||||
function portAcceptsConnections(port, timeoutMs) {
|
||||
return new Promise((resolve) => {
|
||||
const socket = connect({ host: '127.0.0.1', port })
|
||||
let settled = false
|
||||
const finish = (isOpen) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
socket.destroy()
|
||||
resolve(isOpen)
|
||||
}
|
||||
socket.once('connect', () => finish(true))
|
||||
socket.once('error', () => finish(false))
|
||||
socket.setTimeout(Math.max(1, Math.min(1_000, timeoutMs)), () =>
|
||||
finish(false),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
export async function waitForPortClosed(
|
||||
port,
|
||||
{
|
||||
timeoutMs = DEFAULT_TIMEOUT_MS,
|
||||
retryDelayMs = DEFAULT_RETRY_DELAY_MS,
|
||||
probePort = portAcceptsConnections,
|
||||
now = Date.now,
|
||||
sleep = delay,
|
||||
} = {},
|
||||
) {
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65_535) {
|
||||
throw new Error('invalid loopback port')
|
||||
}
|
||||
const deadline = now() + timeoutMs
|
||||
while (now() < deadline) {
|
||||
const remainingMs = deadline - now()
|
||||
if (!(await probePort(port, remainingMs))) {
|
||||
return
|
||||
}
|
||||
await sleep(Math.min(retryDelayMs, Math.max(0, deadline - now())))
|
||||
}
|
||||
throw new Error('timed out waiting for the dev endpoint to close')
|
||||
}
|
||||
|
||||
export function createMacosShutdownController({
|
||||
requestQuit,
|
||||
waitForPortClosed: waitForClosed,
|
||||
waitForChildExit,
|
||||
terminateGroup,
|
||||
finalizeGroup = terminateGroup,
|
||||
exit,
|
||||
report = (message) => console.error(message),
|
||||
timeoutMs = DEFAULT_TIMEOUT_MS,
|
||||
forceTimeoutMs = 2_000,
|
||||
now = Date.now,
|
||||
}) {
|
||||
let signalCount = 0
|
||||
let forced = false
|
||||
let forcedPromise
|
||||
let groupFinalizationPromise
|
||||
|
||||
const remainingBudget = (deadline) => {
|
||||
const remaining = deadline - now()
|
||||
if (remaining <= 0) {
|
||||
throw new Error('timed out waiting for graceful dev shutdown')
|
||||
}
|
||||
return remaining
|
||||
}
|
||||
|
||||
const finalizeOnce = (operation, budget) => {
|
||||
groupFinalizationPromise ??= Promise.resolve().then(() => operation(budget))
|
||||
return groupFinalizationPromise
|
||||
}
|
||||
|
||||
const gracefulShutdown = async () => {
|
||||
const deadline = now() + timeoutMs
|
||||
try {
|
||||
const record = await requestQuit(remainingBudget(deadline))
|
||||
if (forced) return false
|
||||
await waitForClosed(record.port, remainingBudget(deadline))
|
||||
if (forced) return false
|
||||
await waitForChildExit(remainingBudget(deadline))
|
||||
if (forced) return false
|
||||
await finalizeOnce(finalizeGroup, remainingBudget(deadline))
|
||||
if (forced) return false
|
||||
exit(130)
|
||||
return true
|
||||
} catch (error) {
|
||||
report(
|
||||
`Graceful dev shutdown failed: ${error instanceof Error ? error.message : String(error)}`,
|
||||
)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
handleSigint() {
|
||||
signalCount += 1
|
||||
if (signalCount === 1) {
|
||||
return gracefulShutdown()
|
||||
}
|
||||
if (!forcedPromise) {
|
||||
forced = true
|
||||
forcedPromise = finalizeOnce(terminateGroup, forceTimeoutMs).then(
|
||||
() => {
|
||||
exit(130)
|
||||
return true
|
||||
},
|
||||
)
|
||||
}
|
||||
return forcedPromise
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import { execFileSync, spawn } from 'node:child_process'
|
||||
import { access } from 'node:fs/promises'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
export const developmentServiceDirectoryEnvironment =
|
||||
'CLASH_VERGE_DEV_SERVICE_DIR'
|
||||
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const serviceRepository = resolve(
|
||||
repositoryRoot,
|
||||
'..',
|
||||
'clash-verge-service-ipc',
|
||||
)
|
||||
const serviceManifest = join(serviceRepository, 'Cargo.toml')
|
||||
export const developmentServiceWatchPaths = [
|
||||
'src',
|
||||
'resources',
|
||||
'Cargo.toml',
|
||||
'Cargo.lock',
|
||||
].map((name) => join(serviceRepository, name))
|
||||
|
||||
function run(command, args, options = {}) {
|
||||
return new Promise((resolvePromise, reject) => {
|
||||
const child = spawn(command, args, {
|
||||
env: options.env ?? process.env,
|
||||
stdio: options.stdio ?? 'inherit',
|
||||
windowsHide: true,
|
||||
})
|
||||
let stdout = ''
|
||||
child.stdout?.setEncoding('utf8')
|
||||
child.stdout?.on('data', (chunk) => {
|
||||
stdout += chunk
|
||||
})
|
||||
child.once('error', reject)
|
||||
child.once('close', (code, signal) => {
|
||||
if (code === 0) {
|
||||
resolvePromise(stdout)
|
||||
return
|
||||
}
|
||||
const error = new Error(
|
||||
`${command} failed with ${signal ? `signal ${signal}` : `exit code ${code}`}`,
|
||||
)
|
||||
error.exitCode = code
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export async function prepareDevelopmentService() {
|
||||
await access(serviceManifest)
|
||||
const output = await run(
|
||||
'cargo',
|
||||
[
|
||||
'build',
|
||||
'--manifest-path',
|
||||
serviceManifest,
|
||||
'--target-dir',
|
||||
process.env.CARGO_TARGET_DIR ||
|
||||
join(serviceRepository, 'target', 'development'),
|
||||
'--features',
|
||||
'standalone,client,development-channel',
|
||||
'--bins',
|
||||
'--message-format=json-render-diagnostics',
|
||||
],
|
||||
{ stdio: ['inherit', 'pipe', 'inherit'] },
|
||||
)
|
||||
|
||||
const artifacts = new Map()
|
||||
for (const line of output.split(/\r?\n/).filter(Boolean)) {
|
||||
const artifact = JSON.parse(line)
|
||||
if (
|
||||
artifact.reason === 'compiler-artifact' &&
|
||||
resolve(artifact.manifest_path) === serviceManifest &&
|
||||
artifact.target.kind.includes('bin') &&
|
||||
artifact.executable
|
||||
) {
|
||||
artifacts.set(artifact.target.name, resolve(artifact.executable))
|
||||
}
|
||||
}
|
||||
const executables = [
|
||||
'clash-verge-service',
|
||||
'clash-verge-service-install',
|
||||
'clash-verge-service-uninstall',
|
||||
'service-integration-driver',
|
||||
].map((name) => {
|
||||
const executable = artifacts.get(name)
|
||||
if (!executable)
|
||||
throw new Error(`Cargo did not report the ${name} executable`)
|
||||
return executable
|
||||
})
|
||||
const serviceDirectory = dirname(executables[0])
|
||||
for (const executable of executables) {
|
||||
if (dirname(executable) !== serviceDirectory) {
|
||||
throw new Error(
|
||||
'Development service tools were built in different directories',
|
||||
)
|
||||
}
|
||||
await access(executable)
|
||||
}
|
||||
return serviceDirectory
|
||||
}
|
||||
|
||||
export async function ensureDevelopmentService({
|
||||
platform = process.platform,
|
||||
} = {}) {
|
||||
const serviceDirectory = await prepareDevelopmentService()
|
||||
const extension = platform === 'win32' ? '.exe' : ''
|
||||
const installer = join(
|
||||
serviceDirectory,
|
||||
`clash-verge-service-install${extension}`,
|
||||
)
|
||||
const host = execFileSync('rustc', ['-vV'], { encoding: 'utf8' }).match(
|
||||
/^host: (.+)$/m,
|
||||
)?.[1]
|
||||
if (!host) throw new Error('rustc did not report its host target')
|
||||
const args = ['--prepare-install', '--ensure']
|
||||
for (const name of ['verge-mihomo', 'verge-mihomo-alpha']) {
|
||||
args.push(
|
||||
'--core',
|
||||
`${name}${extension}`,
|
||||
join(
|
||||
repositoryRoot,
|
||||
'src-tauri',
|
||||
'sidecar',
|
||||
`${name}-${host}${extension}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
await run(installer, args)
|
||||
return serviceDirectory
|
||||
}
|
||||
+570
@@ -0,0 +1,570 @@
|
||||
import { spawn } from 'node:child_process'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
|
||||
import {
|
||||
createMacosShutdownController,
|
||||
readPrivateInstanceRecord,
|
||||
requestDevQuit,
|
||||
waitForPortClosed,
|
||||
} from './dev-control.mjs'
|
||||
import {
|
||||
developmentServiceDirectoryEnvironment,
|
||||
developmentServiceWatchPaths,
|
||||
ensureDevelopmentService,
|
||||
prepareDevelopmentService,
|
||||
} from './dev-service.mjs'
|
||||
|
||||
const FORCE_GRACE_MS = 2_000
|
||||
const SHUTDOWN_TIMEOUT_MS = 10_000
|
||||
const FORCE_POLL_MS = 50
|
||||
const ANCHOR_EXIT_RESERVE_MS = 100
|
||||
|
||||
export function buildTauriInvocation(
|
||||
mode,
|
||||
environment = process.env,
|
||||
platform = process.platform,
|
||||
) {
|
||||
const env = { ...environment, RUST_BACKTRACE: 'full' }
|
||||
const features = mode === 'sidecar' ? 'verge-dev,dev-sidecar' : 'verge-dev'
|
||||
const args = ['exec', 'tauri', 'dev', '-f', features]
|
||||
if (mode === 'trace') {
|
||||
env.RUSTFLAGS = '--cfg tokio_unstable'
|
||||
args.push('tokio-trace')
|
||||
}
|
||||
for (const path of developmentServiceWatchPaths) {
|
||||
args.push('--additional-watch-folders', path)
|
||||
}
|
||||
return {
|
||||
command: 'pnpm',
|
||||
args,
|
||||
env,
|
||||
detached: platform === 'darwin',
|
||||
}
|
||||
}
|
||||
|
||||
function wait(milliseconds) {
|
||||
return new Promise((resolve) => setTimeout(resolve, milliseconds))
|
||||
}
|
||||
|
||||
function childLifecycle(child) {
|
||||
const spawned = new Promise((resolve, reject) => {
|
||||
child.once('spawn', resolve)
|
||||
child.once('error', reject)
|
||||
})
|
||||
spawned.catch(() => {})
|
||||
const result = new Promise((resolve, reject) => {
|
||||
child.once('error', reject)
|
||||
child.once('exit', (code, signal) => resolve({ code, signal }))
|
||||
})
|
||||
result.catch(() => {})
|
||||
return { result, spawned }
|
||||
}
|
||||
|
||||
function waitForPromise(promise, timeoutMs, message) {
|
||||
if (timeoutMs <= 0) return Promise.reject(new Error(message))
|
||||
let timeout
|
||||
return Promise.race([
|
||||
promise,
|
||||
new Promise((_, reject) => {
|
||||
timeout = setTimeout(() => reject(new Error(message)), timeoutMs)
|
||||
}),
|
||||
]).finally(() => clearTimeout(timeout))
|
||||
}
|
||||
|
||||
function signalDetachedGroup(childPid, signal, signalGroup) {
|
||||
if (!Number.isInteger(childPid) || childPid <= 0) {
|
||||
throw new Error('dev command did not provide a valid child PID')
|
||||
}
|
||||
try {
|
||||
signalGroup(-childPid, signal)
|
||||
return true
|
||||
} catch (error) {
|
||||
if (error?.code === 'ESRCH') return false
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function terminateDetachedGroup(
|
||||
childPid,
|
||||
{
|
||||
signalGroup = process.kill.bind(process),
|
||||
sleep = wait,
|
||||
now = Date.now,
|
||||
graceMs = FORCE_GRACE_MS,
|
||||
pollMs = FORCE_POLL_MS,
|
||||
} = {},
|
||||
) {
|
||||
if (!signalDetachedGroup(childPid, 'SIGTERM', signalGroup)) return
|
||||
|
||||
const deadline = now() + graceMs
|
||||
while (now() < deadline) {
|
||||
await sleep(Math.min(pollMs, deadline - now()))
|
||||
if (now() < deadline && !signalDetachedGroup(childPid, 0, signalGroup)) {
|
||||
return
|
||||
}
|
||||
}
|
||||
signalDetachedGroup(childPid, 'SIGKILL', signalGroup)
|
||||
}
|
||||
|
||||
export function mirrorChildExit(
|
||||
{ code, signal },
|
||||
{
|
||||
exit = (exitCode) => process.exit(exitCode),
|
||||
signalSelf = (childSignal) => {
|
||||
process.removeAllListeners(childSignal)
|
||||
process.kill(process.pid, childSignal)
|
||||
},
|
||||
} = {},
|
||||
) {
|
||||
if (code !== null) {
|
||||
exit(code)
|
||||
return
|
||||
}
|
||||
if (signal) {
|
||||
signalSelf(signal)
|
||||
return
|
||||
}
|
||||
exit(1)
|
||||
}
|
||||
|
||||
function defaultInstallSigint(handler) {
|
||||
process.on('SIGINT', handler)
|
||||
return () => process.off('SIGINT', handler)
|
||||
}
|
||||
|
||||
function defaultInstallSigterm(handler) {
|
||||
process.on('SIGTERM', handler)
|
||||
return () => process.off('SIGTERM', handler)
|
||||
}
|
||||
|
||||
function defaultInstallMessage(handler) {
|
||||
process.on('message', handler)
|
||||
return () => process.off('message', handler)
|
||||
}
|
||||
|
||||
function defaultInstallDisconnect(handler) {
|
||||
process.on('disconnect', handler)
|
||||
return () => process.off('disconnect', handler)
|
||||
}
|
||||
|
||||
function sendToParent(message) {
|
||||
if (process.connected && process.send) process.send(message, () => {})
|
||||
}
|
||||
|
||||
export async function runDevAnchor(mode, dependencies = {}) {
|
||||
if (mode !== 'dev' && mode !== 'trace' && mode !== 'sidecar') {
|
||||
throw new Error('usage: node scripts/dev.mjs --anchor <dev|trace|sidecar>')
|
||||
}
|
||||
|
||||
const environment = dependencies.environment ?? process.env
|
||||
const spawnChild = dependencies.spawnChild ?? spawn
|
||||
const send = dependencies.send ?? sendToParent
|
||||
const exit = dependencies.exit ?? ((code) => process.exit(code))
|
||||
const report = dependencies.report ?? ((message) => console.error(message))
|
||||
const ownPid = dependencies.ownPid ?? process.pid
|
||||
const terminateGroup =
|
||||
dependencies.terminateGroup ??
|
||||
((pid) => terminateDetachedGroup(pid, { graceMs: FORCE_GRACE_MS }))
|
||||
let released = false
|
||||
let disconnectCleanup
|
||||
|
||||
const installSigterm = dependencies.installSigterm ?? defaultInstallSigterm
|
||||
installSigterm(() => {})
|
||||
const installMessage = dependencies.installMessage ?? defaultInstallMessage
|
||||
installMessage((message) => {
|
||||
if (message?.type === 'release' && !disconnectCleanup) {
|
||||
released = true
|
||||
exit(0)
|
||||
}
|
||||
})
|
||||
const installDisconnect =
|
||||
dependencies.installDisconnect ?? defaultInstallDisconnect
|
||||
installDisconnect(() => {
|
||||
if (released || disconnectCleanup) return
|
||||
disconnectCleanup = Promise.resolve()
|
||||
.then(() => terminateGroup(ownPid))
|
||||
.then(() => exit(1))
|
||||
.catch((error) => {
|
||||
report(`Dev anchor cleanup failed: ${error.message}`)
|
||||
exit(1)
|
||||
})
|
||||
})
|
||||
|
||||
const invocation = buildTauriInvocation(mode, environment, 'darwin')
|
||||
let inner
|
||||
try {
|
||||
inner = spawnChild(invocation.command, invocation.args, {
|
||||
env: invocation.env,
|
||||
detached: false,
|
||||
stdio: 'inherit',
|
||||
})
|
||||
} catch {
|
||||
send({ type: 'inner-error', code: 'SPAWN_FAILED' })
|
||||
return
|
||||
}
|
||||
if (!inner || typeof inner.once !== 'function') {
|
||||
send({ type: 'inner-error', code: 'SPAWN_FAILED' })
|
||||
return
|
||||
}
|
||||
|
||||
const innerLifecycle = childLifecycle(inner)
|
||||
try {
|
||||
await innerLifecycle.spawned
|
||||
} catch {
|
||||
send({ type: 'inner-error', code: 'SPAWN_FAILED' })
|
||||
return
|
||||
}
|
||||
send({ type: 'ready' })
|
||||
innerLifecycle.result.then(
|
||||
({ code, signal }) => send({ type: 'inner-result', code, signal }),
|
||||
() => send({ type: 'inner-error', code: 'INNER_FAILED' }),
|
||||
)
|
||||
}
|
||||
|
||||
function createAnchorChannel(anchor, anchorResult) {
|
||||
let innerSettled = false
|
||||
let readySettled = false
|
||||
let resolveResult
|
||||
let rejectResult
|
||||
let resolveReady
|
||||
let rejectReady
|
||||
const innerResult = new Promise((resolve, reject) => {
|
||||
resolveResult = resolve
|
||||
rejectResult = reject
|
||||
})
|
||||
const ready = new Promise((resolve, reject) => {
|
||||
resolveReady = resolve
|
||||
rejectReady = reject
|
||||
})
|
||||
const settleInner = (callback, value) => {
|
||||
if (innerSettled) return
|
||||
innerSettled = true
|
||||
callback(value)
|
||||
}
|
||||
const settleReady = (callback, value) => {
|
||||
if (readySettled) return
|
||||
readySettled = true
|
||||
callback(value)
|
||||
}
|
||||
anchor.on('message', (message) => {
|
||||
if (message?.type === 'ready') {
|
||||
settleReady(resolveReady)
|
||||
} else if (message?.type === 'inner-result') {
|
||||
settleInner(resolveResult, {
|
||||
code: message.code,
|
||||
signal: message.signal,
|
||||
})
|
||||
} else if (message?.type === 'inner-error') {
|
||||
const error = new Error(
|
||||
`inner dev command failed (${message.code ?? 'UNKNOWN'})`,
|
||||
)
|
||||
settleReady(rejectReady, error)
|
||||
settleInner(rejectResult, error)
|
||||
}
|
||||
})
|
||||
anchorResult.then(
|
||||
() => {
|
||||
const error = new Error(
|
||||
'dev group anchor exited before the inner command completed',
|
||||
)
|
||||
settleReady(rejectReady, error)
|
||||
settleInner(rejectResult, error)
|
||||
},
|
||||
() => {
|
||||
const error = new Error('dev group anchor failed')
|
||||
settleReady(rejectReady, error)
|
||||
settleInner(rejectResult, error)
|
||||
},
|
||||
)
|
||||
ready.catch(() => {})
|
||||
innerResult.catch(() => {})
|
||||
return { innerResult, ready }
|
||||
}
|
||||
|
||||
function sendRelease(anchor) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (typeof anchor.send !== 'function') {
|
||||
reject(new Error('dev group anchor IPC is unavailable'))
|
||||
return
|
||||
}
|
||||
anchor.send({ type: 'release' }, (error) => {
|
||||
if (error) reject(new Error('dev group anchor release failed'))
|
||||
else resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function unsafeAnchorError() {
|
||||
return new Error('dev group anchor identity is unsafe')
|
||||
}
|
||||
|
||||
export async function runDevCommand(mode, dependencies = {}) {
|
||||
if (mode !== 'dev' && mode !== 'trace' && mode !== 'sidecar') {
|
||||
throw new Error('usage: node scripts/dev.mjs <dev|trace|sidecar>')
|
||||
}
|
||||
|
||||
const platform = dependencies.platform ?? process.platform
|
||||
const environment = dependencies.environment ?? process.env
|
||||
const spawnChild = dependencies.spawnChild ?? spawn
|
||||
const exit = dependencies.exit ?? ((code) => process.exit(code))
|
||||
const report = dependencies.report ?? ((message) => console.error(message))
|
||||
const mirrorResult = dependencies.mirrorResult ?? mirrorChildExit
|
||||
let recordPath
|
||||
let pendingSigints = 0
|
||||
let dispatchSigint = () => {
|
||||
pendingSigints += 1
|
||||
}
|
||||
let removeSigint = () => {}
|
||||
|
||||
if (platform === 'darwin') {
|
||||
if (!environment.HOME) {
|
||||
throw new Error('HOME is required to locate the dev instance record')
|
||||
}
|
||||
recordPath = join(
|
||||
environment.HOME,
|
||||
'Library/Application Support/io.github.clash-verge-rev.clash-verge-rev.dev/singleton-instance.json',
|
||||
)
|
||||
const installSigint = dependencies.installSigint ?? defaultInstallSigint
|
||||
removeSigint = installSigint(() => dispatchSigint()) ?? (() => {})
|
||||
}
|
||||
|
||||
const tauriInvocation = buildTauriInvocation(mode, environment, platform)
|
||||
const anchorInvocation = {
|
||||
command: dependencies.execPath ?? process.execPath,
|
||||
args: [fileURLToPath(import.meta.url), '--anchor', mode],
|
||||
env: tauriInvocation.env,
|
||||
detached: true,
|
||||
}
|
||||
const invocation = platform === 'darwin' ? anchorInvocation : tauriInvocation
|
||||
let child
|
||||
try {
|
||||
child = spawnChild(invocation.command, invocation.args, {
|
||||
shell: platform === 'win32',
|
||||
env: invocation.env,
|
||||
detached: invocation.detached,
|
||||
stdio:
|
||||
platform === 'darwin'
|
||||
? ['inherit', 'inherit', 'inherit', 'ipc']
|
||||
: 'inherit',
|
||||
})
|
||||
} catch (error) {
|
||||
removeSigint()
|
||||
throw error
|
||||
}
|
||||
if (!child || typeof child.once !== 'function') {
|
||||
removeSigint()
|
||||
throw new Error('dev command failed to return a child process')
|
||||
}
|
||||
const outerLifecycle = childLifecycle(child)
|
||||
|
||||
if (platform !== 'darwin') {
|
||||
mirrorResult(await outerLifecycle.result)
|
||||
return
|
||||
}
|
||||
|
||||
let groupState = 'safe'
|
||||
let finalKillSent = false
|
||||
const anchorChannel = createAnchorChannel(child, outerLifecycle.result)
|
||||
outerLifecycle.result.then(
|
||||
() => {
|
||||
if (groupState !== 'released' && !finalKillSent) groupState = 'unsafe'
|
||||
},
|
||||
() => {
|
||||
groupState = 'unsafe'
|
||||
},
|
||||
)
|
||||
|
||||
try {
|
||||
await outerLifecycle.spawned
|
||||
if (!Number.isInteger(child.pid) || child.pid <= 0) {
|
||||
throw new Error('dev command did not provide a valid child PID')
|
||||
}
|
||||
await waitForPromise(
|
||||
anchorChannel.ready,
|
||||
SHUTDOWN_TIMEOUT_MS,
|
||||
'timed out waiting for the dev group anchor to initialize',
|
||||
)
|
||||
} catch (error) {
|
||||
removeSigint()
|
||||
throw error
|
||||
}
|
||||
|
||||
const anchorPid = child.pid
|
||||
const innerResult = anchorChannel.innerResult
|
||||
let intercepted = false
|
||||
let observedShutdownOperation
|
||||
let anchorFinalization
|
||||
|
||||
const signalGroup = dependencies.signalGroup ?? process.kill.bind(process)
|
||||
const guardedSignalGroup = (pid, signal) => {
|
||||
if (groupState === 'unsafe') throw unsafeAnchorError()
|
||||
if (signal === 'SIGKILL') finalKillSent = true
|
||||
try {
|
||||
signalGroup(pid, signal)
|
||||
} catch (error) {
|
||||
if (error?.code === 'ESRCH') {
|
||||
groupState = 'unsafe'
|
||||
throw unsafeAnchorError()
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const assertGroupAbsent = () => {
|
||||
try {
|
||||
signalGroup(-anchorPid, 0)
|
||||
} catch (error) {
|
||||
if (error?.code === 'ESRCH') return
|
||||
throw new Error('unable to verify that the dev process group exited', {
|
||||
cause: error,
|
||||
})
|
||||
}
|
||||
throw new Error('dev process group still exists after anchor exit')
|
||||
}
|
||||
|
||||
const forceAnchor = async (budget) => {
|
||||
if (groupState === 'unsafe') throw unsafeAnchorError()
|
||||
groupState = 'terminating'
|
||||
if (dependencies.terminateGroup) {
|
||||
await dependencies.terminateGroup(anchorPid, budget)
|
||||
return
|
||||
}
|
||||
const deadline = Date.now() + budget
|
||||
await terminateDetachedGroup(anchorPid, {
|
||||
graceMs: Math.max(0, budget - ANCHOR_EXIT_RESERVE_MS),
|
||||
signalGroup: guardedSignalGroup,
|
||||
})
|
||||
await waitForPromise(
|
||||
outerLifecycle.result,
|
||||
Math.max(1, deadline - Date.now()),
|
||||
'timed out waiting for the dev group anchor to exit',
|
||||
)
|
||||
}
|
||||
|
||||
const releaseAnchor = async (budget) => {
|
||||
if (groupState === 'unsafe') throw unsafeAnchorError()
|
||||
groupState = 'released'
|
||||
const deadline = Date.now() + budget
|
||||
await waitForPromise(
|
||||
sendRelease(child),
|
||||
Math.max(1, deadline - Date.now()),
|
||||
'timed out releasing the dev group anchor',
|
||||
)
|
||||
await waitForPromise(
|
||||
outerLifecycle.result,
|
||||
Math.max(1, deadline - Date.now()),
|
||||
'timed out waiting for the released dev group anchor',
|
||||
)
|
||||
assertGroupAbsent()
|
||||
}
|
||||
|
||||
const finalizeAnchorOnce = (kind, budget) => {
|
||||
anchorFinalization ??=
|
||||
kind === 'release' ? releaseAnchor(budget) : forceAnchor(budget)
|
||||
return anchorFinalization
|
||||
}
|
||||
|
||||
const getUid = dependencies.getUid ?? (() => process.getuid())
|
||||
const requestQuit =
|
||||
dependencies.requestQuit ??
|
||||
((budget) =>
|
||||
requestDevQuit(() => readPrivateInstanceRecord(recordPath, getUid()), {
|
||||
timeoutMs: budget,
|
||||
}))
|
||||
|
||||
const controller = createMacosShutdownController({
|
||||
requestQuit,
|
||||
waitForPortClosed: (port, budget) =>
|
||||
(dependencies.waitForPortClosed ?? waitForPortClosed)(port, {
|
||||
timeoutMs: budget,
|
||||
}),
|
||||
waitForChildExit: (budget) =>
|
||||
waitForPromise(
|
||||
innerResult,
|
||||
budget,
|
||||
'timed out waiting for the inner dev command to exit',
|
||||
),
|
||||
finalizeGroup: (budget) => finalizeAnchorOnce('release', budget),
|
||||
terminateGroup: (budget) => finalizeAnchorOnce('force', budget),
|
||||
exit,
|
||||
report,
|
||||
timeoutMs: SHUTDOWN_TIMEOUT_MS,
|
||||
})
|
||||
|
||||
dispatchSigint = () => {
|
||||
intercepted = true
|
||||
const operation = controller.handleSigint()
|
||||
if (operation !== observedShutdownOperation) {
|
||||
observedShutdownOperation = operation
|
||||
void operation.catch((error) => {
|
||||
report(`Forced dev shutdown failed: ${error.message}`)
|
||||
exit(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
const queuedSigints = pendingSigints
|
||||
pendingSigints = 0
|
||||
for (let index = 0; index < queuedSigints; index += 1) {
|
||||
dispatchSigint()
|
||||
}
|
||||
|
||||
innerResult.then(
|
||||
async (result) => {
|
||||
if (intercepted) return
|
||||
try {
|
||||
await finalizeAnchorOnce('release', SHUTDOWN_TIMEOUT_MS)
|
||||
if (!intercepted) mirrorResult(result)
|
||||
} catch (error) {
|
||||
if (!intercepted) {
|
||||
report(`Dev command failed: ${error.message}`)
|
||||
exit(1)
|
||||
}
|
||||
}
|
||||
},
|
||||
(error) => {
|
||||
if (!intercepted) {
|
||||
report(`Dev command failed: ${error.message}`)
|
||||
exit(1)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
export async function prepareDevRuntime(mode, dependencies = {}) {
|
||||
const ensureService = dependencies.ensureService ?? ensureDevelopmentService
|
||||
const prepareService =
|
||||
dependencies.prepareService ?? prepareDevelopmentService
|
||||
let serviceDirectory
|
||||
if (mode === 'service') {
|
||||
serviceDirectory = await ensureService()
|
||||
} else if (mode === 'dev' || mode === 'trace' || mode === 'sidecar') {
|
||||
serviceDirectory = await prepareService()
|
||||
}
|
||||
return {
|
||||
mode: mode === 'service' ? 'dev' : mode,
|
||||
serviceDirectory,
|
||||
}
|
||||
}
|
||||
|
||||
async function run() {
|
||||
if (process.argv[2] === '--anchor') {
|
||||
await runDevAnchor(process.argv[3])
|
||||
} else {
|
||||
const { mode, serviceDirectory } = await prepareDevRuntime(process.argv[2])
|
||||
if (serviceDirectory) {
|
||||
process.env[developmentServiceDirectoryEnvironment] = serviceDirectory
|
||||
}
|
||||
await runDevCommand(mode)
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
process.argv[1] &&
|
||||
pathToFileURL(process.argv[1]).href === import.meta.url
|
||||
) {
|
||||
run().catch((error) => {
|
||||
console.error(`Unable to start dev command: ${error.message}`)
|
||||
process.exit(1)
|
||||
})
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
# Product Measurement Adapter Guidelines
|
||||
|
||||
[GUIDE.md](GUIDE.md) defines the product adapter boundary and explicit tool invocation.
|
||||
Keep real component imports, initialization and the isolated native entry here,
|
||||
using product frontend/native build dependencies. Do not copy components into the
|
||||
tool. Preserve perf build gates; ordinary builds must not require the external tool.
|
||||
|
||||
The adapter must not load or modify daily configuration or control the daily app,
|
||||
Core, Service, TUN, DNS or system proxy. Preserve loopback isolation, owned-process
|
||||
PID/start attribution, nonactivation, visibility/occlusion and source continuity.
|
||||
Do not weaken gates or substitute Chrome/Vite for native WebView evidence. Label
|
||||
JavaScript adapters separately from native plugin/IPC paths. Expected startup errors
|
||||
must use the owned app's normal nonzero exit, never panic through Tauri setup.
|
||||
|
||||
Review adapter source changes, including initialization and native/build configuration,
|
||||
for changed measurement meaning. Matching interfaces alone do not prove equivalence;
|
||||
an adapter review cannot waive other acceptance conditions.
|
||||
|
||||
For implementation changes, run scoped ESLint, both perf TypeScript projects
|
||||
(`tsconfig.json` and `tsconfig.node.json`), formatting and relevant production checks,
|
||||
including Rust checks for native changes. Run scoped Rust Clippy before freezing
|
||||
the optimized artifact. Check ordinary-build exclusion and application-entry prerequisites.
|
||||
|
||||
Follow the external AGENTS.md's
|
||||
[measurement-validation requirements](https://github.com/clash-verge-rev/clash-verge-rev-harness/blob/main/AGENTS.md)
|
||||
and README's
|
||||
[validation order](https://github.com/clash-verge-rev/clash-verge-rev-harness/blob/main/README.md#validate-before-freezing-a-build).
|
||||
These govern affected native coverage, comparison, failure cleanup and evidence reuse.
|
||||
+132
-27
@@ -1,35 +1,140 @@
|
||||
# Product measurement adapter
|
||||
# macOS Traffic Performance Harness
|
||||
|
||||
This directory owns the isolated native entry, real Traffic/Logs/Connections
|
||||
imports, initialization, JavaScript socket adapter, replay receiver and minimal DOM
|
||||
layer. These evolve with product APIs and use the product's React/Tauri/Wry
|
||||
versions. Keep the explicit perf build gates; ordinary builds need no external tool.
|
||||
This guide is the operating and maintenance contract for humans and coding agents.
|
||||
The only scenario is the production home traffic graph in a dedicated, optimized
|
||||
Tauri WKWebView. It measures foreground updates, native hide, then restoration.
|
||||
It does not initialize the complete homepage or run Mihomo, Service or networking.
|
||||
|
||||
The external [clash-verge-rev-harness operating guide](https://github.com/clash-verge-rev/clash-verge-rev-harness/blob/main/README.md)
|
||||
owns running, sampling, reports, comparison and owned cleanup. Follow its
|
||||
[first setup and installation instructions](https://github.com/clash-verge-rev/clash-verge-rev-harness/blob/main/README.md#build-and-run),
|
||||
reusing an existing checkout. For subsequent calls, pass both absolute roots:
|
||||
## Build And Run
|
||||
|
||||
Use this repository's pnpm, Rust and Xcode Command Line Tools on macOS. No global
|
||||
WebDriver installation is needed. Keep each binary beside its generated manifest.
|
||||
|
||||
```sh
|
||||
project=/absolute/path/to/clash-verge-rev
|
||||
harness=/absolute/path/to/clash-verge-rev-harness
|
||||
node "$harness/build.mjs" --project "$project" --output target/perf/build
|
||||
caffeinate -di node "$harness/run.mjs" --project "$project" --binary target/perf/build/clash-verge --output target/perf/smoke --repeat 1 --seconds 5 --warmup 2
|
||||
node "$harness/compare.mjs" "$project/target/perf/smoke" "$project/target/perf/smoke"
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm perf:build target/perf/baseline-build
|
||||
caffeinate -di pnpm perf:run -- --binary target/perf/baseline-build/clash-verge --output target/perf/baseline --repeat 3 --seconds 20 --warmup 10
|
||||
pnpm perf:compare -- target/perf/baseline target/perf/baseline
|
||||
pnpm perf:test
|
||||
```
|
||||
|
||||
JavaScript socket replacement does not measure native plugin IPC. DOM mutation/text
|
||||
hashes show view-input delivery, not painting or cache ownership. Adapter changes
|
||||
require reviewing measurement meaning under the external validation requirements.
|
||||
`perf:build [directory]` uses release optimization, Vite `--mode perf` and the
|
||||
explicit Cargo `perf-harness` feature. It preserves the binary and records HEAD,
|
||||
dirty state, compiled source, lockfile, frontend, build-settings and binary hashes.
|
||||
Source changes during compilation reject the manifest. Each run also hashes the
|
||||
external collector and runner. Ordinary builds exclude the driver and measurement
|
||||
entry; debug assertions are not the gate. Do not edit compiled inputs during builds.
|
||||
|
||||
For virtual display mode, this adapter places only the hidden measurement window
|
||||
on the exact owned NSScreen, checks complete visibleFrame containment, mode/Space
|
||||
flags and nonactivation, and exits on drift. The tool owns helper lifecycle and topology
|
||||
restoration; see its
|
||||
[virtual display guide](https://github.com/clash-verge-rev/clash-verge-rev-harness/blob/main/README.md#optional-virtual-display).
|
||||
Output directories must be new and Git ignored; use `target/perf/`. JSON/CSV keep
|
||||
raw process samples, observations, phase markers, attribution and cleanup evidence.
|
||||
`summary.json` and `report.md` provide distributions by independent run, phase and
|
||||
process role. Failed runs exit nonzero and retain their evidence. The explicit
|
||||
`traffic-webview-v3` schema rejects older reports instead of silently migrating them.
|
||||
|
||||
`isolation.json` owns the product configuration and process watch scope; keep it
|
||||
aligned with product data directories and executable names. The tool owns
|
||||
[command isolation snapshots](https://github.com/clash-verge-rev/clash-verge-rev-harness/blob/main/README.md#command-isolation-snapshots).
|
||||
The adapter must not load daily configuration or control Core, Service, TUN, DNS
|
||||
or system proxy.
|
||||
## Isolation And Visibility
|
||||
|
||||
The dedicated measurement main bypasses normal initialization and shutdown. It
|
||||
does not read or write daily configuration, subscriptions, proxy, TUN or Service.
|
||||
It uses a distinct app identity and incognito WebView. Both automatic services
|
||||
bind loopback and are owned by the current run; never kill processes by name.
|
||||
|
||||
The measurement window stays above ordinary windows and covers part of the screen,
|
||||
without activation or mouse capture: clicks pass through to the application behind it.
|
||||
Native topmost and click-through states are verified, while native focus and application
|
||||
activation must remain false. WebDriver uses the embedded WebView directly; DOM focus
|
||||
is recorded but not required. Daily windows are unchanged; the topmost window exits
|
||||
with its owned measurement instance. You may keep using another application.
|
||||
The console must be unlocked. Lock state is checked before startup and recorded
|
||||
at phase boundaries; unknown state fails and observed drift rejects comparison.
|
||||
Boundary checks do not provide continuous lock monitoring or unlock the computer.
|
||||
|
||||
No focus does not mean no visibility: shown stages require `document.hidden=false`,
|
||||
fresh Worker data, advancing Canvas draw timestamps and changed Canvas pixels.
|
||||
Topmost placement avoids ordinary-window occlusion; system overlays or another Space
|
||||
can still pause WebKit. Such a run fails; do not weaken Canvas assertions to make it
|
||||
pass. `caffeinate -di` lasts only for the command and cannot prevent deliberate lock.
|
||||
Hidden stages still require continuous input and Worker data.
|
||||
|
||||
## Fixed Workload
|
||||
|
||||
The native window is 1000 x 700 logical pixels. Verify driver dimensions against
|
||||
DPR and record the actual CSS viewport; titlebar space is excluded. The graph is
|
||||
920 x 360 with a ten-minute range, default bezier style and real data retention.
|
||||
The measurement preload sets blur pause false without changing production defaults.
|
||||
|
||||
Deterministic loopback WebSocket replay enters the public traffic append boundary,
|
||||
then the production Worker and Canvas. It does not cover Mihomo or network traffic.
|
||||
There is no history prefill. Absolute 200 ms deadlines sustain 5 Hz without cumulative
|
||||
timer drift or catch-up bursts; missing a complete period fails the source.
|
||||
Warmup is at least the requested duration with a five-second readiness allowance.
|
||||
Fixed input anchors reserve two seconds for each native transition; measured stages
|
||||
retain their full duration. Readiness uses observable state and deadlines, not sleep.
|
||||
Before the first show, wait for actual replay input and Worker data so the graph's
|
||||
visibility listeners are installed; then require fresh Canvas output after showing.
|
||||
Total replay, including allowances, must remain below ten minutes for raw history.
|
||||
Two-input endpoint variation is 400 ms; larger differences reject comparison.
|
||||
|
||||
Worker snapshots are asynchronous. Count/latest-value checks verify deterministic
|
||||
upload/download values at the retained point count, with a joint period of 60 and
|
||||
received-minus-retained count below 60. This detects net missing/duplicate points,
|
||||
not every historical element or exactly cancelling losses and duplicates.
|
||||
Source age must be below 2500 ms, Worker age below 3500 ms and visible draw age below
|
||||
2500 ms. Future timestamps, lost sequence, process changes and failed restore fail.
|
||||
|
||||
## Metrics And Comparison
|
||||
|
||||
The native command obtains the actual WKWebView process ID using the private
|
||||
`_webProcessIdentifier` selector, with availability checking. External collection
|
||||
verifies the canonical system WebContent executable and process start identity.
|
||||
It handles PID reuse and exits; unsupported ownership fails closed. Main and WebView
|
||||
remain separate. Mihomo is not started; shared GPU/network attribution is unavailable.
|
||||
|
||||
CPU is cumulative process time converted from Mach ticks; interval percentages use
|
||||
adjacent valid samples, with one occupied core equal to 100%. The first difference
|
||||
is unavailable. Memory is RSS bytes, not physical footprint or exclusive memory.
|
||||
Reports include CPU mean/P50/P95/peak/seconds, RSS median/P95/peak/delta, sample count
|
||||
and time coverage. Memory slope requires at least 60 seconds of continuous samples.
|
||||
RSS growth is not proof of a leak; process statistics are not function profiles.
|
||||
The embedded driver adds a 20 Hz macOS runloop timer and observation overhead.
|
||||
|
||||
For A/B, build the candidate separately and alternate independent instances:
|
||||
|
||||
```sh
|
||||
pnpm perf:build target/perf/candidate-build
|
||||
for i in 1 2 3; do
|
||||
caffeinate -di pnpm perf:run -- --binary target/perf/baseline-build/clash-verge --repeat 1 --output target/perf/ab-baseline/$i
|
||||
caffeinate -di pnpm perf:run -- --binary target/perf/candidate-build/clash-verge --repeat 1 --output target/perf/ab-candidate/$i
|
||||
done
|
||||
pnpm perf:compare -- target/perf/ab-baseline target/perf/ab-candidate
|
||||
pnpm perf:run -- --binary target/perf/candidate-build/clash-verge --repeat 1 --seconds 5 --warmup 2 --fail-phase hidden --output target/perf/failed
|
||||
```
|
||||
|
||||
Comparison accepts summary files, run directories or groups of run directories.
|
||||
Build mode, toolchain, platform, host, power, WebKit, viewport and workload must match.
|
||||
Invalid and incomparable reports exit 2. A/A remains inconclusive. A/B compares
|
||||
independent-run summaries, not adjacent time samples. An optional third numeric
|
||||
argument is a percentage floor justified by baseline noise; there is no universal
|
||||
pass threshold. Fewer than three runs per group, overlapping ranges or differences
|
||||
within either group's range remain inconclusive. Background load limits inference.
|
||||
|
||||
## Automation Delivery Boundary
|
||||
|
||||
When the operator is a coding agent, the final change keeps only the
|
||||
performance-optimization code. Harness additions introduced during the
|
||||
work — measurement entries, configs, scripts, reports, manifests — must
|
||||
stay untracked by Git and out of every commit; keep them on ignored
|
||||
paths or remove them before delivery. Commits remain minimal and
|
||||
necessary for the optimization itself. Track or commit harness files
|
||||
only when a human explicitly requests it at the end.
|
||||
|
||||
## Maintenance And Acceptance
|
||||
|
||||
Keep measurement code behind the explicit build gates. Reuse the existing driver,
|
||||
Worker, graph, attribution and cleanup; do not add mock IPC or replace real WebView
|
||||
acceptance with Chrome/Vite. Preserve source/binary/report hashes and every failed run.
|
||||
After changes, run scoped ESLint, both perf TypeScript projects, `pnpm perf:test`,
|
||||
format checks and relevant production checks. Verify a real three-phase smoke,
|
||||
three independent runs, A/A, invalid/incomparable reports and injected-failure cleanup.
|
||||
Verify ordinary builds exclude measurement code and daily instance state is intact.
|
||||
Changes to contracts require a schema bump and new reports. Use bounded WebKit CPU
|
||||
or Allocation/Heap captures for deeper diagnosis; do not infer hotspots from counters.
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
import { MihomoWebSocket } from 'tauri-plugin-mihomo-api'
|
||||
|
||||
import { subscribe, scenario } from './replay'
|
||||
|
||||
// Only this perf entry replaces socket transport; the normal application never imports it.
|
||||
export function installAdapter() {
|
||||
const connect = async (kind: string) => {
|
||||
const data = document.documentElement.dataset
|
||||
data.perfSubscriptions = String(Number(data.perfSubscriptions || 0) + 1)
|
||||
const callbacks = new Set<
|
||||
(message: { type: 'Text'; data: string }) => void
|
||||
>()
|
||||
const unsubscribe = subscribe((frame) => {
|
||||
const messages =
|
||||
kind === 'logs'
|
||||
? (frame.payload as ILogItem[])
|
||||
: [
|
||||
kind === 'traffic'
|
||||
? { up: frame.sequence * 1000, down: frame.sequence * 5000 }
|
||||
: frame.payload,
|
||||
]
|
||||
for (const payload of messages) {
|
||||
const message = { type: 'Text' as const, data: JSON.stringify(payload) }
|
||||
callbacks.forEach((callback) => {
|
||||
callback(message)
|
||||
data.perfDelivered = String(Number(data.perfDelivered || 0) + 1)
|
||||
})
|
||||
}
|
||||
})
|
||||
return {
|
||||
addListener: (
|
||||
callback: (message: { type: 'Text'; data: string }) => void,
|
||||
) => {
|
||||
callbacks.add(callback)
|
||||
return () => callbacks.delete(callback)
|
||||
},
|
||||
close: async () => {
|
||||
unsubscribe()
|
||||
callbacks.clear()
|
||||
data.perfSubscriptions = String(Number(data.perfSubscriptions) - 1)
|
||||
},
|
||||
} as unknown as MihomoWebSocket
|
||||
}
|
||||
MihomoWebSocket.connect_logs = async () => connect('logs')
|
||||
MihomoWebSocket.connect_connections = async () => connect('connections')
|
||||
MihomoWebSocket.connect_traffic = async () => connect('traffic')
|
||||
if (scenario === 'logs')
|
||||
localStorage.setItem(
|
||||
'clash-log',
|
||||
JSON.stringify({
|
||||
enable: true,
|
||||
logLevel: 'INFO',
|
||||
logFilter: 'all',
|
||||
logOrder: 'desc',
|
||||
}),
|
||||
)
|
||||
}
|
||||
+21
-227
@@ -1,136 +1,5 @@
|
||||
use objc2::{class, msg_send, runtime::AnyObject, sel};
|
||||
use objc2_foundation::{NSPoint, NSRect, ns_string};
|
||||
use tauri::{Manager as _, WebviewWindow};
|
||||
|
||||
#[link(name = "CoreGraphics", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
fn CGDisplayCopyDisplayMode(display: u32) -> *mut std::ffi::c_void;
|
||||
fn CGDisplayModeGetRefreshRate(mode: *mut std::ffi::c_void) -> f64;
|
||||
fn CGDisplayModeRelease(mode: *mut std::ffi::c_void);
|
||||
fn CGMainDisplayID() -> u32;
|
||||
fn CGDisplayIsInMirrorSet(display: u32) -> u32;
|
||||
fn CGDisplayModeGetWidth(mode: *mut std::ffi::c_void) -> usize;
|
||||
fn CGDisplayModeGetHeight(mode: *mut std::ffi::c_void) -> usize;
|
||||
fn CGDisplayModeGetPixelWidth(mode: *mut std::ffi::c_void) -> usize;
|
||||
fn CGDisplayModeGetPixelHeight(mode: *mut std::ffi::c_void) -> usize;
|
||||
}
|
||||
|
||||
fn expected_display() -> Result<Option<u32>, String> {
|
||||
match std::env::var("PERF_DISPLAY_MODE").as_deref() {
|
||||
Ok("physical") | Err(std::env::VarError::NotPresent) => Ok(None),
|
||||
Ok("virtual") => {
|
||||
let id = std::env::var("PERF_DISPLAY_ID")
|
||||
.map_err(|e| e.to_string())?
|
||||
.parse::<u32>()
|
||||
.map_err(|e| e.to_string())?;
|
||||
if id == 0 {
|
||||
return Err("invalid owned display ID".into());
|
||||
}
|
||||
Ok(Some(id))
|
||||
}
|
||||
_ => Err("unknown measurement display mode".into()),
|
||||
}
|
||||
}
|
||||
const fn bounds(rect: NSRect) -> [f64; 4] {
|
||||
[rect.origin.x, rect.origin.y, rect.size.width, rect.size.height]
|
||||
}
|
||||
fn contained(frame: NSRect, screen: NSRect) -> bool {
|
||||
frame.origin.x >= screen.origin.x
|
||||
&& frame.origin.y >= screen.origin.y
|
||||
&& frame.origin.x + frame.size.width <= screen.origin.x + screen.size.width
|
||||
&& frame.origin.y + frame.size.height <= screen.origin.y + screen.size.height
|
||||
}
|
||||
unsafe fn screen_id(screen: *mut AnyObject) -> u32 {
|
||||
unsafe {
|
||||
if screen.is_null() {
|
||||
return 0;
|
||||
}
|
||||
let dictionary: *mut AnyObject = msg_send![screen, deviceDescription];
|
||||
let value: *mut AnyObject = msg_send![dictionary, objectForKey: ns_string!("NSScreenNumber")];
|
||||
msg_send![value, unsignedIntValue]
|
||||
}
|
||||
}
|
||||
unsafe fn display_state(native: &AnyObject) -> Result<Option<serde_json::Value>, String> {
|
||||
let Some(wanted) = expected_display()? else {
|
||||
return Ok(None);
|
||||
};
|
||||
unsafe {
|
||||
let screen: *mut AnyObject = msg_send![native, screen];
|
||||
let id = screen_id(screen);
|
||||
if id == 0 || id != wanted || id == CGMainDisplayID() || CGDisplayIsInMirrorSet(id) != 0 {
|
||||
return Err("owned virtual screen unavailable".into());
|
||||
}
|
||||
let frame: NSRect = msg_send![screen, frame];
|
||||
let visible: NSRect = msg_send![screen, visibleFrame];
|
||||
let window_frame: NSRect = msg_send![native, frame];
|
||||
let scale: f64 = msg_send![screen, backingScaleFactor];
|
||||
let behavior: usize = msg_send![native, collectionBehavior];
|
||||
let mode = CGDisplayCopyDisplayMode(id);
|
||||
if mode.is_null() {
|
||||
return Err("owned display mode unavailable".into());
|
||||
}
|
||||
let rate = CGDisplayModeGetRefreshRate(mode);
|
||||
let logical = [CGDisplayModeGetWidth(mode), CGDisplayModeGetHeight(mode)];
|
||||
let pixels = [CGDisplayModeGetPixelWidth(mode), CGDisplayModeGetPixelHeight(mode)];
|
||||
CGDisplayModeRelease(mode);
|
||||
if logical != [1280, 900]
|
||||
|| pixels != [2560, 1800]
|
||||
|| scale != 2.0
|
||||
|| (rate - 60.0).abs() > 0.01
|
||||
|| frame.size.width != 1280.0
|
||||
|| frame.size.height != 900.0
|
||||
|| !contained(window_frame, visible)
|
||||
|| behavior & 1 == 0
|
||||
|| behavior & 2 != 0
|
||||
{
|
||||
return Err("owned virtual screen geometry/mode changed".into());
|
||||
}
|
||||
Ok(Some(
|
||||
serde_json::json!({"id": id, "frame": bounds(frame), "visibleFrame": bounds(visible), "windowFrame": bounds(window_frame), "scale": scale, "refreshHz": rate, "collectionBehavior": behavior, "contained": true, "main": false, "mirrored": false, "logical": logical, "pixels": pixels}),
|
||||
))
|
||||
}
|
||||
}
|
||||
unsafe fn target_screen(wanted: u32) -> Result<*mut AnyObject, String> {
|
||||
unsafe {
|
||||
let screens: *mut AnyObject = msg_send![class!(NSScreen), screens];
|
||||
let count: usize = msg_send![screens, count];
|
||||
let mut target = std::ptr::null_mut::<AnyObject>();
|
||||
for index in 0..count {
|
||||
let screen: *mut AnyObject = msg_send![screens, objectAtIndex: index];
|
||||
if screen_id(screen) == wanted {
|
||||
target = screen;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if target.is_null() || wanted == CGMainDisplayID() {
|
||||
return Err("exact owned virtual display missing".into());
|
||||
}
|
||||
Ok(target)
|
||||
}
|
||||
}
|
||||
unsafe fn place_virtual(window: &WebviewWindow) -> Result<(), String> {
|
||||
unsafe {
|
||||
let Some(wanted) = expected_display()? else {
|
||||
return Ok(());
|
||||
};
|
||||
let target = target_screen(wanted)?;
|
||||
let native = &*(window.ns_window().map_err(|e| e.to_string())? as *const AnyObject);
|
||||
let visible: NSRect = msg_send![target, visibleFrame];
|
||||
let frame: NSRect = msg_send![native, frame];
|
||||
if frame.size.width > visible.size.width || frame.size.height > visible.size.height {
|
||||
return Err("owned window does not fit virtual visibleFrame".into());
|
||||
}
|
||||
let behavior: usize = msg_send![native, collectionBehavior];
|
||||
let _: () = msg_send![native, setCollectionBehavior: (behavior & !2usize) | 1usize];
|
||||
let origin = NSPoint::new(
|
||||
visible.origin.x + (visible.size.width - frame.size.width) / 2.0,
|
||||
visible.origin.y + (visible.size.height - frame.size.height) / 2.0,
|
||||
);
|
||||
let _: () = msg_send![native, setFrameOrigin: origin];
|
||||
display_state(native)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
use tauri::WebviewWindow;
|
||||
|
||||
#[tauri::command]
|
||||
async fn perf_state(window: WebviewWindow, action: String) -> Result<serde_json::Value, String> {
|
||||
@@ -138,28 +7,16 @@ async fn perf_state(window: WebviewWindow, action: String) -> Result<serde_json:
|
||||
return Err("unknown measurement action".into());
|
||||
}
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let fail_app = window.app_handle().clone();
|
||||
window
|
||||
.with_webview(move |view| unsafe {
|
||||
let native = &*(view.ns_window() as *const AnyObject);
|
||||
let sender = std::ptr::null::<AnyObject>();
|
||||
let display = match display_state(native) {
|
||||
Ok(state) => state,
|
||||
Err(error) => {
|
||||
let _: () = msg_send![native, orderOut: sender];
|
||||
let _ = tx.send(Err(error));
|
||||
fail_app.exit(2);
|
||||
return;
|
||||
}
|
||||
};
|
||||
if action == "show" {
|
||||
let _: () = msg_send![native, orderBack: sender];
|
||||
} else if action == "hide" {
|
||||
let _: () = msg_send![native, orderOut: sender];
|
||||
}
|
||||
let visible: bool = msg_send![native, isVisible];
|
||||
let occlusion: usize = msg_send![native, occlusionState];
|
||||
let active_space: bool = msg_send![native, isOnActiveSpace];
|
||||
let focused: bool = msg_send![native, isKeyWindow];
|
||||
let click_through: bool = msg_send![native, ignoresMouseEvents];
|
||||
let app: *const AnyObject = msg_send![class!(NSApplication), sharedApplication];
|
||||
@@ -171,41 +28,21 @@ async fn perf_state(window: WebviewWindow, action: String) -> Result<serde_json:
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let _ = tx.send(Ok((
|
||||
pid,
|
||||
visible,
|
||||
focused,
|
||||
active,
|
||||
click_through,
|
||||
occlusion & 2 == 0,
|
||||
active_space,
|
||||
display,
|
||||
)));
|
||||
let _ = tx.send((pid, visible, focused, active, click_through));
|
||||
})
|
||||
.map_err(|e| e.to_string())?;
|
||||
let (pid, visible, focused, active, click_through, occluded, active_space, display) = rx
|
||||
let (pid, visible, focused, active, click_through) = rx
|
||||
.recv_timeout(std::time::Duration::from_secs(5))
|
||||
.map_err(|e| e.to_string())??;
|
||||
.map_err(|e| e.to_string())?;
|
||||
if pid <= 0 {
|
||||
return Err("WKWebView process ownership unavailable".into());
|
||||
}
|
||||
let top = window.is_always_on_top().map_err(|e| e.to_string())?;
|
||||
Ok(serde_json::json!({"main": std::process::id(), "webview": pid,
|
||||
"visible": visible, "nativeFocused": focused, "appActive": active,
|
||||
"virtualScreen": display, "expectedDisplayID": expected_display()?,
|
||||
"top": top, "occluded": occluded, "activeSpace": active_space, "clickThrough": click_through,
|
||||
"top": top, "clickThrough": click_through,
|
||||
"token": std::env::var("PERF_TOKEN").map_err(|e| e.to_string())?}))
|
||||
}
|
||||
#[tauri::command]
|
||||
const fn get_clash_logs() -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn get_verge_config() -> serde_json::Value {
|
||||
serde_json::json!({"language": "en", "theme_mode": "light"})
|
||||
}
|
||||
|
||||
pub fn run() -> std::process::ExitCode {
|
||||
#[cfg(feature = "clippy")]
|
||||
let context = tauri::test::mock_context(tauri::test::noop_assets());
|
||||
@@ -213,66 +50,23 @@ pub fn run() -> std::process::ExitCode {
|
||||
let context = tauri::generate_context!();
|
||||
let result = tauri::Builder::default()
|
||||
.plugin(tauri_plugin_wdio_webdriver::init())
|
||||
.invoke_handler(tauri::generate_handler![perf_state, get_clash_logs, get_verge_config])
|
||||
.invoke_handler(tauri::generate_handler![perf_state])
|
||||
.setup(|app| {
|
||||
let startup = (|| -> Result<(), Box<dyn std::error::Error>> {
|
||||
app.handle()
|
||||
.set_activation_policy(tauri::ActivationPolicy::Prohibited)?;
|
||||
let scenario = std::env::var("PERF_SCENARIO").unwrap_or_else(|_| "traffic".into());
|
||||
let layer = std::env::var("PERF_LAYER").unwrap_or_else(|_| "component".into());
|
||||
if !matches!(scenario.as_str(), "traffic" | "logs" | "connections" | "proxy")
|
||||
|| !matches!(layer.as_str(), "page" | "component" | "dom")
|
||||
{
|
||||
return Err("invalid perf scene".into());
|
||||
}
|
||||
if let Some(wanted) = expected_display().map_err(std::io::Error::other)? {
|
||||
unsafe {
|
||||
target_screen(wanted).map_err(std::io::Error::other)?;
|
||||
}
|
||||
}
|
||||
let port: u16 = std::env::var("PERF_REPLAY_PORT")?.parse()?;
|
||||
let window = tauri::WebviewWindowBuilder::new(
|
||||
app,
|
||||
"perf",
|
||||
tauri::WebviewUrl::App(format!("index.html?port={port}&scenario={scenario}&layer={layer}").into()),
|
||||
)
|
||||
.title("Clash Verge - performance replay")
|
||||
.inner_size(1000., 700.)
|
||||
.visible(false)
|
||||
.focused(false)
|
||||
.focusable(false)
|
||||
.always_on_top(true)
|
||||
.incognito(true)
|
||||
.build()?;
|
||||
window.set_ignore_cursor_events(true)?;
|
||||
unsafe {
|
||||
place_virtual(&window).map_err(std::io::Error::other)?;
|
||||
}
|
||||
if expected_display().map_err(std::io::Error::other)?.is_some() {
|
||||
let handle = app.handle().clone();
|
||||
window.on_window_event(move |event| {
|
||||
if matches!(
|
||||
event,
|
||||
tauri::WindowEvent::Moved(_) | tauri::WindowEvent::ScaleFactorChanged { .. }
|
||||
) && let Some(window) = handle.get_webview_window("perf")
|
||||
{
|
||||
let valid = window
|
||||
.ns_window()
|
||||
.ok()
|
||||
.is_some_and(|native| unsafe { display_state(&*(native as *const AnyObject)).is_ok() });
|
||||
if !valid {
|
||||
let _ = window.hide();
|
||||
handle.exit(2);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(error) = startup {
|
||||
eprintln!("Measurement startup failed: {error}");
|
||||
app.handle().exit(1);
|
||||
}
|
||||
app.handle().set_activation_policy(tauri::ActivationPolicy::Accessory)?;
|
||||
let port: u16 = std::env::var("PERF_REPLAY_PORT")?.parse()?;
|
||||
tauri::WebviewWindowBuilder::new(
|
||||
app,
|
||||
"perf",
|
||||
tauri::WebviewUrl::App(format!("index.html?port={port}").into()),
|
||||
)
|
||||
.title("Clash Verge - performance replay")
|
||||
.inner_size(1000., 700.)
|
||||
.visible(false)
|
||||
.focused(false)
|
||||
.always_on_top(true)
|
||||
.incognito(true)
|
||||
.build()?
|
||||
.set_ignore_cursor_events(true)?;
|
||||
Ok(())
|
||||
})
|
||||
.build(context);
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { createHash } from 'node:crypto'
|
||||
import {
|
||||
copyFileSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
const output = resolve(process.argv[2] ?? 'target/perf/build')
|
||||
const hash = (bytes) => createHash('sha256').update(bytes).digest('hex')
|
||||
const command = (cmd, args) =>
|
||||
execFileSync(cmd, args, { encoding: 'utf8' }).trim()
|
||||
const source = () =>
|
||||
command('git', ['ls-files', '-co', '--exclude-standard'])
|
||||
.split('\n')
|
||||
.filter(existsSync)
|
||||
.filter(
|
||||
(path) =>
|
||||
!path.startsWith('scripts/perf/') ||
|
||||
/\.(rs|tsx|html|mts|json)$/.test(path),
|
||||
)
|
||||
.sort()
|
||||
.map((path) => `${path}\0${hash(readFileSync(path))}`)
|
||||
.join('\n')
|
||||
mkdirSync(output, { recursive: true })
|
||||
const before = hash(source())
|
||||
const buildSettingsSha256 = hash(
|
||||
['Cargo.toml', '.cargo/config.toml']
|
||||
.filter(existsSync)
|
||||
.map((path) => `${path}\0${hash(readFileSync(path))}`)
|
||||
.join('\n'),
|
||||
)
|
||||
execFileSync(
|
||||
'pnpm',
|
||||
[
|
||||
'exec',
|
||||
'vite',
|
||||
'build',
|
||||
'--mode',
|
||||
'perf',
|
||||
'--config',
|
||||
'scripts/perf/vite.mts',
|
||||
],
|
||||
{ stdio: 'inherit' },
|
||||
)
|
||||
const mode = 'release + perf-harness (build settings hash recorded)'
|
||||
const buildCommand =
|
||||
'TAURI_CONFIG=<scripts/perf/tauri.json> cargo build -p clash-verge --release --features perf-harness --locked --target-dir target/perf/cargo'
|
||||
execFileSync(
|
||||
'cargo',
|
||||
[
|
||||
'build',
|
||||
'-p',
|
||||
'clash-verge',
|
||||
'--release',
|
||||
'--features',
|
||||
'perf-harness',
|
||||
'--locked',
|
||||
'--target-dir',
|
||||
'target/perf/cargo',
|
||||
],
|
||||
{
|
||||
stdio: 'inherit',
|
||||
env: {
|
||||
...process.env,
|
||||
TAURI_CONFIG: readFileSync('scripts/perf/tauri.json', 'utf8'),
|
||||
},
|
||||
},
|
||||
)
|
||||
if (before !== hash(source()))
|
||||
throw new Error('Source changed during build; refuse manifest')
|
||||
const binary = `${output}/clash-verge`
|
||||
copyFileSync('target/perf/cargo/release/clash-verge', binary)
|
||||
const files = command('find', ['target/perf/dist', '-type', 'f'])
|
||||
.split('\n')
|
||||
.sort()
|
||||
writeFileSync(
|
||||
`${binary}.json`,
|
||||
JSON.stringify(
|
||||
{
|
||||
head: command('git', ['rev-parse', 'HEAD']),
|
||||
dirty: command('git', ['status', '--porcelain']),
|
||||
sourceSha256: before,
|
||||
binarySha256: hash(readFileSync(binary)),
|
||||
frontendSha256: hash(
|
||||
files.map((path) => `${path}\0${hash(readFileSync(path))}`).join('\n'),
|
||||
),
|
||||
mode,
|
||||
buildSettingsSha256,
|
||||
buildEnvironment: Object.fromEntries(
|
||||
Object.entries(process.env).filter(([key]) =>
|
||||
/^(RUSTFLAGS|CARGO_ENCODED_RUSTFLAGS|CARGO_PROFILE_|RUSTC_WRAPPER)/.test(
|
||||
key,
|
||||
),
|
||||
),
|
||||
),
|
||||
buildCommand,
|
||||
binary,
|
||||
toolchain: `${command('rustc', ['--version'])}; node ${process.version}; pnpm ${command('pnpm', ['--version'])}`,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
)
|
||||
console.log(`Measurement binary and manifest: ${binary}`)
|
||||
@@ -0,0 +1,41 @@
|
||||
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
|
||||
import { compare } from './report.mjs'
|
||||
const args = process.argv.slice(2).filter((v) => v !== '--')
|
||||
if (args.length < 2)
|
||||
throw new Error(
|
||||
'Usage: pnpm perf:compare -- baseline/summary.json candidate/summary.json [noise-threshold-percent]',
|
||||
)
|
||||
const threshold = args[2] === undefined ? null : Number(args[2])
|
||||
if (threshold !== null && (!Number.isFinite(threshold) || threshold < 0))
|
||||
throw new Error(
|
||||
'threshold must be a nonnegative percentage justified by baseline noise',
|
||||
)
|
||||
function load(path) {
|
||||
if (statSync(path).isFile()) return JSON.parse(readFileSync(path))
|
||||
if (existsSync(join(path, 'summary.json')))
|
||||
return load(join(path, 'summary.json'))
|
||||
const reports = readdirSync(path)
|
||||
.sort()
|
||||
.map((name) => load(join(path, name)))
|
||||
const first = reports[0]
|
||||
if (
|
||||
!first ||
|
||||
reports.some(
|
||||
(r) =>
|
||||
r.build?.binarySha256 !== first.build?.binarySha256 ||
|
||||
['invalid', 'incomparable'].includes(compare(first, r).verdict),
|
||||
)
|
||||
)
|
||||
throw new Error('group contains mixed builds, contracts, or invalid runs')
|
||||
return { ...first, runs: reports.flatMap((r) => r.runs) }
|
||||
}
|
||||
let result
|
||||
try {
|
||||
result = compare(...args.slice(0, 2).map(load), threshold)
|
||||
} catch (error) {
|
||||
result = { verdict: 'invalid', reason: String(error) }
|
||||
}
|
||||
console.log(JSON.stringify(result, null, 2))
|
||||
if (['invalid', 'incomparable'].includes(result.verdict)) process.exitCode = 2
|
||||
+49
-28
@@ -1,31 +1,52 @@
|
||||
import { layer, scenario, startReplay } from './replay'
|
||||
import { ThemeProvider, createTheme } from '@mui/material'
|
||||
import { useEffect } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { SWRConfig } from 'swr'
|
||||
|
||||
if (scenario === 'traffic') {
|
||||
await import('./traffic')
|
||||
} else if (scenario === 'proxy') {
|
||||
await import('./proxy')
|
||||
} else {
|
||||
const root = document.getElementById('root')!
|
||||
document.body.style.cssText = 'margin:0;font:14px -apple-system,sans-serif'
|
||||
root.style.cssText = 'width:1000px;height:700px;overflow:hidden'
|
||||
new MutationObserver(() => {
|
||||
document.documentElement.dataset.perfDraw = String(Date.now())
|
||||
}).observe(root, { childList: true, characterData: true, subtree: true })
|
||||
window.addEventListener('error', (event) => {
|
||||
document.documentElement.dataset.perfError = event.message
|
||||
})
|
||||
window.addEventListener('unhandledrejection', (event) => {
|
||||
document.documentElement.dataset.perfError = String(event.reason)
|
||||
})
|
||||
if (layer === 'dom') {
|
||||
const { mount } = await import('./minimal')
|
||||
mount(root)
|
||||
} else {
|
||||
if (layer === 'page') {
|
||||
const { installAdapter } = await import('./adapter')
|
||||
installAdapter()
|
||||
import { EnhancedCanvasTrafficGraph } from '../../src/components/home/enhanced-canvas-traffic-graph'
|
||||
import { useTrafficMonitorEnhanced } from '../../src/hooks/use-traffic-monitor'
|
||||
import { initializeLanguage } from '../../src/services/i18n'
|
||||
import { setPreloadConfig } from '../../src/services/preload'
|
||||
|
||||
setPreloadConfig({
|
||||
pause_render_traffic_stats_on_blur: false,
|
||||
} as IVergeConfig)
|
||||
await initializeLanguage('en')
|
||||
export function Replay() {
|
||||
const {
|
||||
graphData: { appendData },
|
||||
} = useTrafficMonitorEnhanced({ subscribe: false })
|
||||
useEffect(() => {
|
||||
let received = 0,
|
||||
previous = 0,
|
||||
gaps = 0
|
||||
const socket = new WebSocket(
|
||||
`ws://127.0.0.1:${new URLSearchParams(location.search).get('port')}`,
|
||||
)
|
||||
socket.onmessage = ({ data }) => {
|
||||
const point = JSON.parse(data)
|
||||
appendData(point)
|
||||
if (previous && point.sequence !== previous + 1) gaps++
|
||||
previous = point.sequence
|
||||
document.documentElement.dataset.perfReceived = String(++received)
|
||||
document.documentElement.dataset.perfGaps = String(gaps)
|
||||
document.documentElement.dataset.perfSourceTime = String(point.timestamp)
|
||||
}
|
||||
await import('./scenes')
|
||||
}
|
||||
startReplay()
|
||||
return () => socket.close()
|
||||
}, [appendData])
|
||||
return (
|
||||
<main
|
||||
aria-label="Home traffic graph replay"
|
||||
style={{ width: 920, height: 360, margin: 32 }}
|
||||
>
|
||||
<EnhancedCanvasTrafficGraph />
|
||||
</main>
|
||||
)
|
||||
}
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<SWRConfig value={{ revalidateOnFocus: false, revalidateOnReconnect: false }}>
|
||||
<ThemeProvider theme={createTheme()}>
|
||||
<Replay />
|
||||
</ThemeProvider>
|
||||
</SWRConfig>,
|
||||
)
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
// Only this perf build aliases '@tauri-apps/api/core' to a shim that serves
|
||||
// these responses for the proxy scenario; the normal application never
|
||||
// imports it. The runtime-injected __TAURI_INTERNALS__ is read-only, so
|
||||
// interception happens at import resolution instead. Unknown commands pass
|
||||
// through to the real backend (perf_state, event plugin), keeping harness
|
||||
// ownership probes and lifecycle commands working. The proxy scenario is
|
||||
// therefore a JavaScript invoke adapter, not native plugin IPC.
|
||||
|
||||
const GROUP_COUNT = 40
|
||||
const NODES_PER_GROUP = 24
|
||||
|
||||
const capabilities = {
|
||||
udp: true,
|
||||
xudp: false,
|
||||
tfo: false,
|
||||
mptcp: false,
|
||||
smux: false,
|
||||
}
|
||||
|
||||
const history = (delay: number) => [{ time: '2026-11-19T00:00:00Z', delay }]
|
||||
|
||||
const buildProxyView = () => {
|
||||
const records: Record<string, unknown> = {}
|
||||
const groups: {
|
||||
name: string
|
||||
type: string
|
||||
now: string
|
||||
hidden: boolean
|
||||
history: { time: string; delay: number }[]
|
||||
members: unknown[]
|
||||
}[] = []
|
||||
|
||||
for (let g = 0; g < GROUP_COUNT; g++) {
|
||||
const members: unknown[] = []
|
||||
for (let n = 0; n < NODES_PER_GROUP; n++) {
|
||||
const name = `node-${g}-${n}`
|
||||
const recordId = `record-${g}-${n}`
|
||||
records[recordId] = {
|
||||
recordId,
|
||||
name,
|
||||
type: n % 3 === 0 ? 'Shadowsocks' : n % 3 === 1 ? 'Vmess' : 'Trojan',
|
||||
history: history(30 + ((g * 7 + n * 13) % 40) * 10),
|
||||
source: { kind: 'core', proxyName: name },
|
||||
...capabilities,
|
||||
}
|
||||
members.push({ kind: 'node', name, recordId })
|
||||
}
|
||||
groups.push({
|
||||
name: `group-${String(g).padStart(2, '0')}`,
|
||||
type: g % 2 === 0 ? 'Selector' : 'URLTest',
|
||||
now: `node-${g}-0`,
|
||||
hidden: false,
|
||||
history: history(20),
|
||||
members,
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
orderSource: 'runtime',
|
||||
providerState: 'ready',
|
||||
global: {
|
||||
name: 'GLOBAL',
|
||||
type: 'Selector',
|
||||
now: 'group-00',
|
||||
hidden: true,
|
||||
history: [],
|
||||
members: groups.map((group) => ({ kind: 'group', name: group.name })),
|
||||
...capabilities,
|
||||
},
|
||||
direct: 'DIRECT',
|
||||
groups: groups.map((group) => ({ ...group, ...capabilities })),
|
||||
records,
|
||||
standalone: [],
|
||||
providers: [],
|
||||
}
|
||||
}
|
||||
|
||||
const handlers: Record<string, () => unknown> = {
|
||||
get_proxy_view: buildProxyView,
|
||||
get_verge_config: () => ({
|
||||
language: 'en',
|
||||
theme_mode: 'light',
|
||||
proxy_layout_column: 2,
|
||||
default_latency_timeout: 10000,
|
||||
enable_hover_jump_navigator: true,
|
||||
hover_jump_navigator_delay: 200,
|
||||
pause_render_traffic_stats_on_blur: false,
|
||||
}),
|
||||
get_profiles: () => ({
|
||||
current: 'perf-profile',
|
||||
items: [
|
||||
{
|
||||
uid: 'perf-profile',
|
||||
type: 'remote',
|
||||
name: 'Perf Profile',
|
||||
desc: '',
|
||||
url: '',
|
||||
selected: true,
|
||||
extra: {},
|
||||
option: { update_interval: 0 },
|
||||
},
|
||||
],
|
||||
}),
|
||||
get_clash_info: () => ({
|
||||
mixed_port: 7897,
|
||||
socks_port: 0,
|
||||
port: 0,
|
||||
server: '127.0.0.1:9097',
|
||||
secret: null,
|
||||
}),
|
||||
get_runtime_config: () => null,
|
||||
get_sys_proxy: () => ({ enable: false, bypass: '', pac_file: '' }),
|
||||
get_runtime_state: () => ({
|
||||
mode: 'Sidecar',
|
||||
service: 'ready',
|
||||
serviceUnavailableReason: null,
|
||||
pendingAction: null,
|
||||
sidecarAllowed: true,
|
||||
isAdmin: false,
|
||||
opInFlight: false,
|
||||
serviceUsable: true,
|
||||
tunCapable: false,
|
||||
serviceNeedsAttention: false,
|
||||
}),
|
||||
get_sidecar_failure: () => null,
|
||||
get_pending_failures: () => [],
|
||||
'plugin:mihomo|get_configs': () => ({ mode: 'rule', 'mixed-port': 7897 }),
|
||||
'plugin:mihomo|get_rule_providers': () => ({ providers: {} }),
|
||||
'plugin:mihomo|get_rules': () => ({ rules: [] }),
|
||||
}
|
||||
|
||||
/** Returns the mocked response, or undefined to pass through to the backend. */
|
||||
export const mockCommand = (cmd: string): unknown => {
|
||||
const handler = handlers[cmd]
|
||||
return handler ? handler() : undefined
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"configRoots": [
|
||||
"Library/Application Support/io.github.clash-verge-rev.clash-verge-rev",
|
||||
"Library/Application Support/io.github.clash-verge-rev.clash-verge-rev.dev"
|
||||
],
|
||||
"configDirectories": ["profiles"],
|
||||
"configExtensions": [".yaml", ".yml", ".json", ".js"],
|
||||
"processNames": {
|
||||
"app": "clash-verge",
|
||||
"core": "verge-mihomo",
|
||||
"service": "clash-verge-service"
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import { scenario, subscribe } from './replay'
|
||||
|
||||
export function mount(root: HTMLElement) {
|
||||
const rows = Array.from({ length: 20 }, () => {
|
||||
const row = document.createElement('div')
|
||||
row.style.cssText = 'height:32px;white-space:nowrap;overflow:hidden'
|
||||
root.appendChild(row)
|
||||
return row
|
||||
})
|
||||
subscribe(({ payload }) => {
|
||||
const texts =
|
||||
scenario === 'logs'
|
||||
? (payload as ILogItem[]).map((log) => log.payload)
|
||||
: (payload as IConnections).connections.map(
|
||||
(connection) => connection.metadata.host,
|
||||
)
|
||||
rows.forEach((row, index) => {
|
||||
row.textContent = texts[index % texts.length] ?? ''
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
import { ThemeProvider, createTheme } from '@mui/material'
|
||||
import { useEffect } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { SWRConfig } from 'swr'
|
||||
|
||||
import { AppDataProvider } from '../../src/providers/app-data-provider'
|
||||
import { initializeLanguage } from '../../src/services/i18n'
|
||||
import { setPreloadConfig } from '../../src/services/preload'
|
||||
import { swrConfig } from '../../src/services/query-client'
|
||||
import { AppStoreProvider } from '../../src/store/app-store'
|
||||
|
||||
import '../../src/assets/styles/page.scss'
|
||||
|
||||
const root = document.getElementById('root')!
|
||||
document.body.style.cssText = 'margin:0;font:14px -apple-system,sans-serif'
|
||||
root.style.cssText = 'width:1000px;height:700px;overflow:hidden'
|
||||
new MutationObserver(() => {
|
||||
document.documentElement.dataset.perfDraw = String(Date.now())
|
||||
}).observe(root, { childList: true, characterData: true, subtree: true })
|
||||
|
||||
setPreloadConfig({
|
||||
language: 'en',
|
||||
theme_mode: 'light',
|
||||
pause_render_traffic_stats_on_blur: false,
|
||||
} as IVergeConfig)
|
||||
await initializeLanguage('en')
|
||||
|
||||
const ProxyPage = (await import('../../src/pages/proxies')).default
|
||||
|
||||
const findScroller = () => {
|
||||
const elements = document.querySelectorAll<HTMLElement>('#root *')
|
||||
for (const element of elements) {
|
||||
const { overflowY } = getComputedStyle(element)
|
||||
if (
|
||||
(overflowY === 'auto' || overflowY === 'scroll') &&
|
||||
element.scrollHeight > element.clientHeight
|
||||
) {
|
||||
return element
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// Deterministic sawtooth scrolling keeps the virtualizer measuring, the
|
||||
// throttled scroll-position save running and the DOM mutating so the perfDraw
|
||||
// marker tracks view-input delivery. Each applied scroll step counts as one
|
||||
// delivered view input; the interval keeps delivering (throttled by the
|
||||
// browser) while the window is hidden and rAF is suspended.
|
||||
export const ScrollDriver = () => {
|
||||
useEffect(() => {
|
||||
const data = document.documentElement.dataset
|
||||
let stopped = false
|
||||
const step = () => {
|
||||
const scroller = findScroller()
|
||||
if (scroller) {
|
||||
const max = scroller.scrollHeight - scroller.clientHeight
|
||||
if (max > 0) {
|
||||
const next =
|
||||
scroller.scrollTop + 36 > max - 36 ? 0 : scroller.scrollTop + 36
|
||||
scroller.scrollTop = next
|
||||
data.perfScroll = String(Number(data.perfScroll || 0) + 1)
|
||||
data.perfDelivered = String(Number(data.perfDelivered || 0) + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
const drive = () => {
|
||||
if (stopped) return
|
||||
step()
|
||||
requestAnimationFrame(drive)
|
||||
}
|
||||
const handle = requestAnimationFrame(drive)
|
||||
const timer = window.setInterval(step, 250)
|
||||
return () => {
|
||||
stopped = true
|
||||
cancelAnimationFrame(handle)
|
||||
window.clearInterval(timer)
|
||||
}
|
||||
}, [])
|
||||
return null
|
||||
}
|
||||
|
||||
createRoot(root).render(
|
||||
<SWRConfig value={swrConfig}>
|
||||
<ThemeProvider theme={createTheme()}>
|
||||
<AppStoreProvider>
|
||||
<AppDataProvider>
|
||||
<ProxyPage />
|
||||
<ScrollDriver />
|
||||
</AppDataProvider>
|
||||
</AppStoreProvider>
|
||||
</ThemeProvider>
|
||||
</SWRConfig>,
|
||||
)
|
||||
@@ -1,17 +0,0 @@
|
||||
import { startReplay } from './replay'
|
||||
|
||||
// Thin loader: error handlers must precede scene module evaluation so any
|
||||
// startup failure surfaces in perfError.
|
||||
const data = document.documentElement.dataset
|
||||
window.addEventListener('error', (event) => {
|
||||
data.perfError = event.message
|
||||
})
|
||||
window.addEventListener('unhandledrejection', (event) => {
|
||||
data.perfError = String(event.reason)
|
||||
})
|
||||
|
||||
data.perfStage = 'loader'
|
||||
await import('./proxy-scene')
|
||||
data.perfStage = 'scene'
|
||||
startReplay()
|
||||
data.perfStage = 'replay'
|
||||
@@ -1,37 +0,0 @@
|
||||
export interface Frame {
|
||||
sequence: number
|
||||
timestamp: number
|
||||
payload: ILogItem[] | IConnections
|
||||
}
|
||||
export const params = new URLSearchParams(location.search)
|
||||
export const scenario = params.get('scenario') ?? 'traffic'
|
||||
export const layer = params.get('layer') ?? 'component'
|
||||
const listeners = new Set<(frame: Frame) => void>()
|
||||
export const subscribe = (listener: (frame: Frame) => void) => {
|
||||
listeners.add(listener)
|
||||
return () => {
|
||||
listeners.delete(listener)
|
||||
}
|
||||
}
|
||||
export function startReplay() {
|
||||
const data = document.documentElement.dataset
|
||||
let previous = 0
|
||||
data.perfReceived = '0'
|
||||
data.perfGaps = '0'
|
||||
const socket = new WebSocket(`ws://127.0.0.1:${params.get('port')}`)
|
||||
socket.onmessage = ({ data: raw }) => {
|
||||
const frame = JSON.parse(raw) as Frame
|
||||
if (frame.sequence !== previous + 1)
|
||||
data.perfGaps = String(Number(data.perfGaps) + 1)
|
||||
previous = frame.sequence
|
||||
data.perfReceived = String(previous)
|
||||
data.perfSourceTime = String(frame.timestamp)
|
||||
for (const listener of listeners) listener(frame)
|
||||
}
|
||||
socket.onerror = () => {
|
||||
data.perfError = 'replay socket failed'
|
||||
}
|
||||
socket.onclose = () => {
|
||||
data.perfError = 'replay socket closed'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
import { isDeepStrictEqual } from 'node:util'
|
||||
|
||||
export const SCHEMA = 'traffic-webview-v3'
|
||||
export const phases = ['foreground', 'hidden', 'restored']
|
||||
export const roles = ['webview', 'main']
|
||||
export const quantile = (values, p) => {
|
||||
const v = values.filter(Number.isFinite).sort((a, b) => a - b)
|
||||
if (!v.length) return null
|
||||
const index = (v.length - 1) * p
|
||||
return (
|
||||
v[Math.floor(index)] +
|
||||
(v[Math.ceil(index)] - v[Math.floor(index)]) * (index % 1)
|
||||
)
|
||||
}
|
||||
export function delta(previous, next) {
|
||||
if (
|
||||
!previous ||
|
||||
previous.pid !== next.pid ||
|
||||
previous.start !== next.start ||
|
||||
![previous.time, next.time, previous.cpu, next.cpu].every(
|
||||
Number.isFinite,
|
||||
) ||
|
||||
next.time <= previous.time ||
|
||||
next.cpu < previous.cpu
|
||||
)
|
||||
return null
|
||||
return ((next.cpu - previous.cpu) / (next.time - previous.time)) * 100000
|
||||
}
|
||||
export function summarize(rows, seconds) {
|
||||
const output = {}
|
||||
for (const phase of phases)
|
||||
for (const role of roles) {
|
||||
const selected = rows.filter((r) => r.phase === phase && r.role === role)
|
||||
const samples = selected.map((r, i) => ({
|
||||
...r,
|
||||
percent: delta(selected[i - 1], r),
|
||||
cpuDelta: i ? r.cpu - selected[i - 1].cpu : null,
|
||||
}))
|
||||
const valid = samples.filter((r) => Number.isFinite(r.percent))
|
||||
const memory = samples.map((r) => r.rss)
|
||||
const span =
|
||||
samples.length > 1 ? samples.at(-1).time - samples[0].time : 0
|
||||
const continuous =
|
||||
samples.length > 1 &&
|
||||
samples.every(
|
||||
(r) =>
|
||||
[r.time, r.cpu, r.rss].every(Number.isFinite) &&
|
||||
Number.isInteger(r.pid) &&
|
||||
r.pid > 0 &&
|
||||
/^\d+$/.test(r.start) &&
|
||||
r.time >= 0 &&
|
||||
r.cpu >= 0 &&
|
||||
r.rss > 0,
|
||||
) &&
|
||||
samples.every(
|
||||
(r, i) =>
|
||||
!i ||
|
||||
(r.time > samples[i - 1].time &&
|
||||
r.time - samples[i - 1].time < 2500 &&
|
||||
r.cpu >= samples[i - 1].cpu &&
|
||||
r.pid === samples[i - 1].pid &&
|
||||
r.start === samples[i - 1].start),
|
||||
)
|
||||
output[`${phase}/${role}`] = {
|
||||
count: samples.length,
|
||||
cpuCount: valid.length,
|
||||
missing: Math.max(0, Math.floor(seconds) - samples.length),
|
||||
coverage: Math.min(1, samples.length / seconds),
|
||||
continuous,
|
||||
observedSeconds: span / 1000,
|
||||
intervalCoverage: Math.min(1, span / ((seconds - 1) * 1000)),
|
||||
cpuMean: null,
|
||||
cpuP50: quantile(
|
||||
valid.map((r) => r.percent),
|
||||
0.5,
|
||||
),
|
||||
cpuP95: quantile(
|
||||
valid.map((r) => r.percent),
|
||||
0.95,
|
||||
),
|
||||
cpuPeak: quantile(
|
||||
valid.map((r) => r.percent),
|
||||
1,
|
||||
),
|
||||
cpuSeconds: valid.length
|
||||
? valid.reduce((sum, r) => sum + r.cpuDelta, 0)
|
||||
: null,
|
||||
rssP50: quantile(memory, 0.5),
|
||||
rssP95: quantile(memory, 0.95),
|
||||
rssPeak: quantile(memory, 1),
|
||||
rssDelta: continuous ? samples.at(-1).rss - samples[0].rss : null,
|
||||
rssSlopeBytesPerSecond:
|
||||
span >= 60000 && continuous
|
||||
? (samples.at(-1).rss - samples[0].rss) / (span / 1000)
|
||||
: null,
|
||||
}
|
||||
output[`${phase}/${role}`].cpuMean =
|
||||
valid.length && span > 0
|
||||
? (output[`${phase}/${role}`].cpuSeconds / span) * 100000
|
||||
: null
|
||||
}
|
||||
return output
|
||||
}
|
||||
export function replayValues(sequence) {
|
||||
return {
|
||||
up: 100000 + (sequence % 20) * 10000,
|
||||
down: 500000 + (sequence % 30) * 20000,
|
||||
}
|
||||
}
|
||||
export const validVisibility = (s) =>
|
||||
typeof s.hidden === 'boolean' &&
|
||||
(s.phase === 'hidden'
|
||||
? s.visible === false && s.hidden
|
||||
: phases.includes(s.phase) && s.visible === true && !s.hidden)
|
||||
export const validObservation = (s) =>
|
||||
validWorkload(s) &&
|
||||
validVisibility(s) &&
|
||||
s.nativeFocused === false &&
|
||||
s.appActive === false &&
|
||||
s.top === true &&
|
||||
s.clickThrough === true &&
|
||||
[s.now, s.source, s.worker, s.draw].every(
|
||||
(v) => Number.isFinite(v) && v > 0,
|
||||
) &&
|
||||
s.now >= s.source &&
|
||||
s.now - s.source < 2500 &&
|
||||
s.now >= s.worker &&
|
||||
s.now - s.worker < 3500 &&
|
||||
s.now >= s.draw &&
|
||||
(s.phase === 'hidden' || s.now - s.draw < 2500)
|
||||
export function validWorkload(s) {
|
||||
if (!s) return false
|
||||
const expected = replayValues(s.points)
|
||||
return (
|
||||
Number.isInteger(s.received) &&
|
||||
Number.isInteger(s.points) &&
|
||||
s.points > 0 &&
|
||||
s.received >= s.points &&
|
||||
s.received - s.points < 60 &&
|
||||
s.lastUp === expected.up &&
|
||||
s.lastDown === expected.down &&
|
||||
s.gaps === 0
|
||||
)
|
||||
}
|
||||
export function compare(a, b, threshold = null) {
|
||||
const stats = new Map()
|
||||
const text = (value) => typeof value === 'string' && value.length > 0
|
||||
const object = (value) =>
|
||||
value && typeof value === 'object' && !Array.isArray(value)
|
||||
const expectedMarks = [
|
||||
'ready',
|
||||
...phases.flatMap((phase) => [phase, `${phase}:end`]),
|
||||
]
|
||||
const valid = (x) =>
|
||||
x?.schema === SCHEMA &&
|
||||
text(x?.harnessSha256) &&
|
||||
[
|
||||
'head',
|
||||
'sourceSha256',
|
||||
'binarySha256',
|
||||
'frontendSha256',
|
||||
'buildSettingsSha256',
|
||||
'mode',
|
||||
'buildCommand',
|
||||
'binary',
|
||||
'toolchain',
|
||||
].every((key) => text(x.build?.[key])) &&
|
||||
typeof x.build.dirty === 'string' &&
|
||||
object(x.build.buildEnvironment) &&
|
||||
[
|
||||
'method',
|
||||
'mode',
|
||||
'toolchain',
|
||||
'buildSettingsSha256',
|
||||
'platform',
|
||||
'machine',
|
||||
'arch',
|
||||
'host',
|
||||
'hardware',
|
||||
'power',
|
||||
'powerSource',
|
||||
'webkit',
|
||||
'replay',
|
||||
'automation',
|
||||
].every((key) => text(x.contract?.[key])) &&
|
||||
object(x.contract.buildEnvironment) &&
|
||||
x.build.buildSettingsSha256 === x.contract.buildSettingsSha256 &&
|
||||
[
|
||||
'warmup',
|
||||
'intervalMs',
|
||||
'transitionSeconds',
|
||||
'readinessAllowanceSeconds',
|
||||
].every((key) => Number.isFinite(x.contract[key]) && x.contract[key] > 0) &&
|
||||
x.contract.scenario === 'traffic' &&
|
||||
typeof x.contract.consoleLocked === 'boolean' &&
|
||||
x.contract.windowPolicy === 'nonactivating-top-click-through-v1' &&
|
||||
x.contract.replayMs === 200 &&
|
||||
x.contract.rangeMinutes === 10 &&
|
||||
['window', 'viewport'].every(
|
||||
(key) =>
|
||||
Array.isArray(x.contract[key]) &&
|
||||
x.contract[key].length === (key === 'window' ? 2 : 3) &&
|
||||
x.contract[key].every((v) => Number.isFinite(v) && v > 0),
|
||||
) &&
|
||||
Number.isFinite(x.contract?.seconds) &&
|
||||
x.contract.seconds >= 5 &&
|
||||
Array.isArray(x.contract.phaseTargets) &&
|
||||
x.contract.phaseTargets.length === phases.length &&
|
||||
x.contract.phaseTargets.every((n) => Number.isInteger(n) && n > 0) &&
|
||||
Array.isArray(x.runs) &&
|
||||
x.runs.length &&
|
||||
x.runs.every((r) => {
|
||||
if (
|
||||
!r?.ok ||
|
||||
!Array.isArray(r.samples) ||
|
||||
!r.samples.every(
|
||||
(s) => s && roles.includes(s.role) && phases.includes(s.phase),
|
||||
) ||
|
||||
!Array.isArray(r.marks) ||
|
||||
!r.marks.every((m) => m && typeof m.name === 'string')
|
||||
)
|
||||
return false
|
||||
stats.set(r, summarize(r.samples, x.contract.seconds))
|
||||
return (
|
||||
r.cleanup?.mainExited &&
|
||||
r.cleanup?.driverClosed &&
|
||||
r.cleanup?.webviewExited &&
|
||||
Array.isArray(r.consoleStates) &&
|
||||
r.consoleStates.length === expectedMarks.length &&
|
||||
r.consoleStates.every(
|
||||
(s, i) =>
|
||||
s &&
|
||||
s.name === (i ? expectedMarks[i] : 'initial') &&
|
||||
typeof s.locked === 'boolean' &&
|
||||
Number.isFinite(s.time) &&
|
||||
s.time > 0 &&
|
||||
(!i || s.time >= r.consoleStates[i - 1].time),
|
||||
) &&
|
||||
Number.isInteger(r.replay?.sent) &&
|
||||
r.replay.sent > 0 &&
|
||||
Number.isFinite(r.replay.maxLateMs) &&
|
||||
r.replay.maxLateMs >= 0 &&
|
||||
r.replay.maxLateMs < x.contract.replayMs &&
|
||||
!r.replay.error &&
|
||||
r.actualWarmupMs >= x.contract.warmup * 1000 &&
|
||||
Array.isArray(r.observations) &&
|
||||
r.observations.length > 0 &&
|
||||
r.observations.every(
|
||||
(s, i) =>
|
||||
validObservation(s) && (!i || s.now > r.observations[i - 1].now),
|
||||
) &&
|
||||
r.marks.length === expectedMarks.length &&
|
||||
r.marks.every(
|
||||
(m, i) =>
|
||||
m.name === expectedMarks[i] &&
|
||||
Number.isFinite(m.time) &&
|
||||
m.time > 0 &&
|
||||
(!i ||
|
||||
(validObservation({ ...m, phase: m.name.split(':')[0] }) &&
|
||||
/^[a-f0-9]{64}$/.test(m.pixelsSha256))) &&
|
||||
(!phases.includes(m.name) ||
|
||||
(m.target === x.contract.phaseTargets[phases.indexOf(m.name)] &&
|
||||
m.received === m.target)) &&
|
||||
(!i || m.time > r.marks[i - 1].time),
|
||||
) &&
|
||||
roles.every((role) =>
|
||||
r.samples
|
||||
.filter((s) => s.role === role)
|
||||
.every(
|
||||
(s, i, rows) =>
|
||||
!i ||
|
||||
(s.pid === rows[i - 1].pid &&
|
||||
s.start === rows[i - 1].start &&
|
||||
s.time > rows[i - 1].time &&
|
||||
s.cpu >= rows[i - 1].cpu &&
|
||||
phases.indexOf(s.phase) >= phases.indexOf(rows[i - 1].phase)),
|
||||
),
|
||||
) &&
|
||||
validStats(stats.get(r)) &&
|
||||
phases.every((phase) => {
|
||||
const start = r.marks.find((m) => m.name === phase)
|
||||
const end = r.marks.find((m) => m.name === `${phase}:end`)
|
||||
const observed = r.observations.filter((s) => s.phase === phase)
|
||||
return (
|
||||
start &&
|
||||
end &&
|
||||
observed.length > 0 &&
|
||||
[
|
||||
start.deadlineIndex,
|
||||
end.deadlineIndex,
|
||||
start.senderSent,
|
||||
end.senderSent,
|
||||
].every((n) => Number.isInteger(n) && n >= 0) &&
|
||||
end.deadlineIndex > start.deadlineIndex &&
|
||||
end.senderSent >= start.senderSent &&
|
||||
end.senderSent <= r.replay.sent &&
|
||||
start.senderSent >= start.received &&
|
||||
end.senderSent >= end.received &&
|
||||
Math.abs(
|
||||
end.received -
|
||||
start.received -
|
||||
(end.deadlineIndex - start.deadlineIndex),
|
||||
) <= 2 &&
|
||||
observed.every(
|
||||
(s) =>
|
||||
s.now >= start.now &&
|
||||
s.now <= end.now &&
|
||||
s.received >= start.received &&
|
||||
s.received <= end.received,
|
||||
) &&
|
||||
end.worker > start.worker &&
|
||||
(phase === 'hidden' ||
|
||||
(end.draw > start.draw &&
|
||||
end.pixelsSha256 !== start.pixelsSha256))
|
||||
)
|
||||
})
|
||||
)
|
||||
})
|
||||
if (![a, b].every(valid))
|
||||
return { verdict: 'invalid', reason: 'failed, malformed or missing runs' }
|
||||
if (
|
||||
[a, b].some((x) =>
|
||||
x.runs.some((r) =>
|
||||
r.consoleStates.some((s) => s.locked !== x.contract.consoleLocked),
|
||||
),
|
||||
)
|
||||
)
|
||||
return {
|
||||
verdict: 'incomparable',
|
||||
reason: 'console lock state changed at observed boundaries',
|
||||
}
|
||||
if (
|
||||
!isDeepStrictEqual(a.contract, b.contract) ||
|
||||
['mode', 'buildCommand', 'toolchain', 'buildEnvironment'].some(
|
||||
(key) => !isDeepStrictEqual(a.build[key], b.build[key]),
|
||||
) ||
|
||||
a.harnessSha256 !== b.harnessSha256
|
||||
)
|
||||
return {
|
||||
verdict: 'incomparable',
|
||||
reason: 'harness, platform, build mode, workload or environment differ',
|
||||
}
|
||||
for (const phase of phases) {
|
||||
for (const name of [phase, `${phase}:end`]) {
|
||||
const sizes = [a, b].map((x) =>
|
||||
x.runs.map((r) => r.marks.find((m) => m.name === name)?.received),
|
||||
)
|
||||
if (!sizes.flat().every(Number.isFinite))
|
||||
return { verdict: 'invalid', reason: 'missing observed workload size' }
|
||||
if (
|
||||
Math.abs(quantile(sizes[0], 0.5) - quantile(sizes[1], 0.5)) > 2 ||
|
||||
sizes.some((s) => Math.max(...s) - Math.min(...s) > 2)
|
||||
)
|
||||
return {
|
||||
verdict: 'incomparable',
|
||||
reason: `${name}: input size varies by more than two replay points`,
|
||||
}
|
||||
}
|
||||
}
|
||||
const same = a.build.binarySha256 === b.build.binarySha256
|
||||
const enough = a.runs.length >= 3 && b.runs.length >= 3
|
||||
const metrics = {}
|
||||
for (const phase of phases)
|
||||
for (const role of roles)
|
||||
for (const metric of ['cpuMean', 'rssP50']) {
|
||||
const key = `${phase}/${role}`
|
||||
const av = a.runs.map((r) => stats.get(r)[key][metric])
|
||||
const bv = b.runs.map((r) => stats.get(r)[key][metric])
|
||||
const before = quantile(av, 0.5),
|
||||
after = quantile(bv, 0.5)
|
||||
const noise = Math.max(...av) - Math.min(...av)
|
||||
const candidateRange = Math.max(...bv) - Math.min(...bv)
|
||||
const overlap =
|
||||
Math.max(...av) >= Math.min(...bv) &&
|
||||
Math.max(...bv) >= Math.min(...av)
|
||||
metrics[`${key}/${metric}`] = {
|
||||
before,
|
||||
after,
|
||||
delta: after - before,
|
||||
baselineRange: noise,
|
||||
candidateRange,
|
||||
verdict:
|
||||
same ||
|
||||
!enough ||
|
||||
threshold === null ||
|
||||
!av.every(Number.isFinite) ||
|
||||
!bv.every(Number.isFinite) ||
|
||||
overlap ||
|
||||
Math.abs(after - before) <=
|
||||
Math.max(
|
||||
noise,
|
||||
candidateRange,
|
||||
(Math.abs(before) * threshold) / 100,
|
||||
)
|
||||
? 'inconclusive'
|
||||
: after < before
|
||||
? 'lower'
|
||||
: 'higher',
|
||||
}
|
||||
}
|
||||
return {
|
||||
verdict: 'inconclusive',
|
||||
kind: same ? 'A/A' : 'A/B',
|
||||
reason: same
|
||||
? 'same binary; natural variation only'
|
||||
: 'inspect independent-run metrics; no universal pass threshold',
|
||||
metrics,
|
||||
}
|
||||
}
|
||||
export function markdown(report) {
|
||||
const lines = [
|
||||
'# Home traffic graph - replay measurement',
|
||||
'',
|
||||
`Success: ${report.runs.filter((r) => r.ok).length}/${report.runs.length}`,
|
||||
'',
|
||||
'CPU: one fully occupied core = 100%. Memory: process resident size bytes, not exclusive memory. Null = unavailable; first CPU observation has no delta. Slope requires 60 seconds of continuous observations.',
|
||||
'',
|
||||
'| Run / stage / role | CPU mean / P50 / P95 / peak (%) | CPU s | RSS P50 / P95 / peak / delta (bytes) | Samples / coverage |',
|
||||
'|---|---|---|---|---|',
|
||||
]
|
||||
for (const [i, run] of report.runs.entries()) {
|
||||
if (run.error) lines.push(`\nRun ${i + 1} failed: ${run.error}\n`)
|
||||
for (const [key, s] of Object.entries(run.stats))
|
||||
lines.push(
|
||||
`| ${i + 1}/${key} | ${[s.cpuMean, s.cpuP50, s.cpuP95, s.cpuPeak].map((v) => v?.toFixed(2) ?? 'unavailable').join(' / ')} | ${s.cpuSeconds?.toFixed(3) ?? 'unavailable'} | ${[s.rssP50, s.rssP95, s.rssPeak, s.rssDelta].map((v) => v ?? 'unavailable').join(' / ')} | ${s.count} / ${(s.coverage * 100).toFixed(1)}% |`,
|
||||
)
|
||||
}
|
||||
lines.push(
|
||||
'',
|
||||
'Scope: loopback replay → public traffic append boundary → production Worker → homepage Canvas component. Mihomo and its network/subscription chain are not running. Shared GPU/network processes are unavailable and excluded. Process statistics do not identify function hotspots, component CPU or retained objects; memory growth is not proof of a leak.',
|
||||
'',
|
||||
'Next measurement: use WebKit CPU sampling for the highest-CPU foreground/restored phase; use Allocation/Heap captures for repeatable RSS growth. React Compiler is an untested local A/B candidate only.',
|
||||
)
|
||||
return lines.join('\n') + '\n'
|
||||
}
|
||||
export const validStats = (stats) =>
|
||||
Object.values(stats).every(
|
||||
(s) =>
|
||||
s.continuous &&
|
||||
s.coverage >= 0.8 &&
|
||||
s.intervalCoverage >= 0.8 &&
|
||||
s.cpuCount >= 3,
|
||||
)
|
||||
@@ -0,0 +1,340 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdirSync } from 'node:fs'
|
||||
import { test } from 'node:test'
|
||||
|
||||
import {
|
||||
compare,
|
||||
delta,
|
||||
phases,
|
||||
roles,
|
||||
quantile,
|
||||
summarize,
|
||||
validWorkload,
|
||||
replayValues,
|
||||
SCHEMA,
|
||||
validVisibility,
|
||||
} from './report.mjs'
|
||||
const latest = (sequence) => {
|
||||
const { up, down } = replayValues(sequence)
|
||||
return { lastUp: up, lastDown: down }
|
||||
}
|
||||
const observation = (phase, now) => ({
|
||||
phase,
|
||||
now,
|
||||
source: now - 100,
|
||||
worker: now - 100,
|
||||
draw: now - 100,
|
||||
visible: phase !== 'hidden',
|
||||
hidden: phase === 'hidden',
|
||||
focused: false,
|
||||
nativeFocused: false,
|
||||
appActive: false,
|
||||
top: true,
|
||||
clickThrough: true,
|
||||
})
|
||||
const rows = phases.flatMap((phase, phaseIndex) =>
|
||||
roles.flatMap((role) =>
|
||||
Array.from({ length: 5 }, (_, i) => ({
|
||||
phase,
|
||||
role,
|
||||
pid: role === 'main' ? 1 : 2,
|
||||
start: '1',
|
||||
time: (phaseIndex * 5 + i) * 1000,
|
||||
cpu: (phaseIndex * 5 + i) / 10,
|
||||
rss: 100 + i,
|
||||
})),
|
||||
),
|
||||
)
|
||||
const run = {
|
||||
ok: true,
|
||||
samples: rows,
|
||||
cleanup: { mainExited: true, driverClosed: true, webviewExited: true },
|
||||
replay: { sent: 130, maxLateMs: 10 },
|
||||
actualWarmupMs: 3000,
|
||||
observations: phases.map((phase, i) => ({
|
||||
...observation(phase, 2000 + i * 10000),
|
||||
received: 35 + i * 35,
|
||||
points: 34 + i * 35,
|
||||
gaps: 0,
|
||||
...latest(34 + i * 35),
|
||||
})),
|
||||
marks: [
|
||||
{ name: 'ready', time: 1 },
|
||||
...phases.flatMap((name, i) => [
|
||||
{
|
||||
name,
|
||||
target: 35 + i * 35,
|
||||
deadlineIndex: 35 + i * 35,
|
||||
senderSent: 35 + i * 35,
|
||||
received: 35 + i * 35,
|
||||
points: 34 + i * 35,
|
||||
...latest(34 + i * 35),
|
||||
gaps: 0,
|
||||
time: 1000 + i * 10000,
|
||||
...observation(name, 1000 + i * 10000),
|
||||
pixelsSha256: 'a'.repeat(64),
|
||||
},
|
||||
{
|
||||
name: `${name}:end`,
|
||||
deadlineIndex: 60 + i * 35,
|
||||
senderSent: 60 + i * 35,
|
||||
received: 60 + i * 35,
|
||||
points: 59 + i * 35,
|
||||
...latest(59 + i * 35),
|
||||
gaps: 0,
|
||||
time: 6000 + i * 10000,
|
||||
...observation(name, 6000 + i * 10000),
|
||||
pixelsSha256: 'b'.repeat(64),
|
||||
},
|
||||
]),
|
||||
],
|
||||
}
|
||||
run.consoleStates = run.marks.map((m, i) => ({
|
||||
name: i ? m.name : 'initial',
|
||||
time: m.time,
|
||||
locked: false,
|
||||
}))
|
||||
const baseline = {
|
||||
schema: SCHEMA,
|
||||
harnessSha256: 'fixture-harness',
|
||||
build: {
|
||||
head: 'fixture-head',
|
||||
dirty: '',
|
||||
sourceSha256: 'fixture-source',
|
||||
binarySha256: 'same',
|
||||
frontendSha256: 'fixture-assets',
|
||||
buildSettingsSha256: 'fixture-settings',
|
||||
mode: 'release',
|
||||
buildCommand: 'fixture-build',
|
||||
binary: '/fixture/app',
|
||||
toolchain: 'fixture-tools',
|
||||
buildEnvironment: {},
|
||||
},
|
||||
contract: {
|
||||
scenario: 'traffic',
|
||||
replayMs: 200,
|
||||
consoleLocked: false,
|
||||
windowPolicy: 'nonactivating-top-click-through-v1',
|
||||
seconds: 5,
|
||||
warmup: 2,
|
||||
phaseTargets: [35, 70, 105],
|
||||
transitionSeconds: 2,
|
||||
readinessAllowanceSeconds: 5,
|
||||
intervalMs: 1000,
|
||||
rangeMinutes: 10,
|
||||
window: [1000, 700],
|
||||
viewport: [1000, 668, 2],
|
||||
method: 'fixture-method',
|
||||
mode: 'release',
|
||||
toolchain: 'fixture-tools',
|
||||
buildSettingsSha256: 'fixture-settings',
|
||||
platform: 'macOS',
|
||||
machine: 'fixture-model',
|
||||
arch: 'arm64',
|
||||
host: 'fixture-host',
|
||||
hardware: 'fixture-hardware',
|
||||
power: 'fixture-power',
|
||||
powerSource: 'AC',
|
||||
webkit: 'fixture-webkit',
|
||||
replay: 'fixture-5Hz',
|
||||
automation: 'fixture-wdio',
|
||||
buildEnvironment: {},
|
||||
},
|
||||
runs: [run, run, run],
|
||||
}
|
||||
test('quantiles, CPU units, first observation and PID reuse', () => {
|
||||
assert.equal(quantile([0, 10, 20], 0.95), 19)
|
||||
assert.equal(delta(undefined, rows[0]), null)
|
||||
assert.equal(delta(rows[0], rows[1]), 10)
|
||||
assert.equal(delta(rows[0], { ...rows[1], start: '2' }), null)
|
||||
assert.equal(delta(rows[0], { ...rows[1], time: NaN }), null)
|
||||
assert.equal(summarize(rows, 5)['hidden/main'].cpuMean, 10)
|
||||
assert.equal(summarize([], 5)['hidden/main'].cpuSeconds, null)
|
||||
})
|
||||
test('report schema: A/A, failed, incomparable and corrupt samples', () => {
|
||||
assert.equal(compare(baseline, baseline).kind, 'A/A')
|
||||
assert.equal(
|
||||
compare(baseline, { ...baseline, schema: 'old' }).verdict,
|
||||
'invalid',
|
||||
)
|
||||
for (const change of [
|
||||
{ appActive: true },
|
||||
{ nativeFocused: true },
|
||||
{ top: false },
|
||||
{ top: undefined },
|
||||
{ clickThrough: false },
|
||||
{ clickThrough: undefined },
|
||||
{ hidden: true },
|
||||
{ worker: 3000 },
|
||||
{ now: 6000 },
|
||||
{ draw: 3000 },
|
||||
{ worker: null },
|
||||
]) {
|
||||
const invalid = structuredClone(baseline)
|
||||
Object.assign(invalid.runs[0].observations[0], change)
|
||||
assert.equal(compare(baseline, invalid).verdict, 'invalid')
|
||||
}
|
||||
for (const key of ['draw', 'pixelsSha256']) {
|
||||
const stalled = structuredClone(baseline)
|
||||
stalled.runs[0].marks[2][key] = stalled.runs[0].marks[1][key]
|
||||
assert.equal(compare(baseline, stalled).verdict, 'invalid')
|
||||
}
|
||||
const missingPhase = structuredClone(baseline)
|
||||
missingPhase.runs[0].observations.pop()
|
||||
assert.equal(compare(baseline, missingPhase).verdict, 'invalid')
|
||||
const consoleDrift = structuredClone(baseline)
|
||||
consoleDrift.runs[0].consoleStates[3].locked = true
|
||||
assert.equal(compare(baseline, consoleDrift).verdict, 'incomparable')
|
||||
consoleDrift.runs[0].consoleStates[3].locked = null
|
||||
assert.equal(compare(baseline, consoleDrift).verdict, 'invalid')
|
||||
assert.equal(
|
||||
validVisibility({ phase: 'restored', visible: true, hidden: true }),
|
||||
false,
|
||||
)
|
||||
const missedPeriod = structuredClone(baseline)
|
||||
missedPeriod.runs[0].replay.maxLateMs = 200
|
||||
assert.equal(compare(baseline, missedPeriod).verdict, 'invalid')
|
||||
const delayed = {
|
||||
received: 100,
|
||||
points: 97,
|
||||
gaps: 0,
|
||||
lastUp: 270000,
|
||||
lastDown: 640000,
|
||||
}
|
||||
assert.equal(validWorkload(delayed), true)
|
||||
assert.equal(validWorkload(null), false)
|
||||
assert.equal(validWorkload({ ...delayed, points: 96 }), false)
|
||||
assert.equal(validWorkload({ ...delayed, points: 98 }), false)
|
||||
assert.equal(validWorkload({ ...delayed, received: 157 }), false)
|
||||
assert.equal(validWorkload({ ...delayed, lastDown: 660000 }), false)
|
||||
const missedAnchor = structuredClone(baseline)
|
||||
missedAnchor.runs[0].marks[1].received++
|
||||
assert.equal(compare(baseline, missedAnchor).verdict, 'invalid')
|
||||
const droppedInputs = structuredClone(baseline)
|
||||
const end = droppedInputs.runs[0].marks[2]
|
||||
end.received -= 10
|
||||
end.points -= 10
|
||||
Object.assign(end, latest(end.points))
|
||||
assert.equal(compare(droppedInputs, droppedInputs).verdict, 'invalid')
|
||||
const workerLag = structuredClone(baseline)
|
||||
workerLag.runs[0].observations[0].points -= 3
|
||||
assert.equal(compare(baseline, workerLag).verdict, 'invalid')
|
||||
const inputDrift = structuredClone(baseline)
|
||||
inputDrift.runs = baseline.runs.map((r) => structuredClone(r))
|
||||
inputDrift.runs[0].marks[2].received += 3
|
||||
inputDrift.runs[0].marks[2].points += 3
|
||||
inputDrift.runs[0].marks[2].deadlineIndex += 3
|
||||
inputDrift.runs[0].marks[2].senderSent += 3
|
||||
Object.assign(
|
||||
inputDrift.runs[0].marks[2],
|
||||
latest(inputDrift.runs[0].marks[2].points),
|
||||
)
|
||||
assert.equal(compare(baseline, inputDrift).verdict, 'incomparable')
|
||||
const snapshotPhase = structuredClone(baseline)
|
||||
snapshotPhase.runs[0].marks[2].points++
|
||||
Object.assign(
|
||||
snapshotPhase.runs[0].marks[2],
|
||||
latest(snapshotPhase.runs[0].marks[2].points),
|
||||
)
|
||||
assert.equal(compare(baseline, snapshotPhase).kind, 'A/A')
|
||||
const changedSettings = structuredClone(baseline)
|
||||
changedSettings.build.buildSettingsSha256 =
|
||||
changedSettings.contract.buildSettingsSha256 = 'changed-settings'
|
||||
assert.equal(compare(baseline, changedSettings).verdict, 'incomparable')
|
||||
assert.equal(
|
||||
compare(baseline, { ...baseline, harnessSha256: 'changed' }).verdict,
|
||||
'incomparable',
|
||||
)
|
||||
assert.equal(
|
||||
compare(baseline, {
|
||||
...baseline,
|
||||
contract: { ...baseline.contract, seconds: 6 },
|
||||
}).verdict,
|
||||
'incomparable',
|
||||
)
|
||||
assert.equal(
|
||||
compare(baseline, { ...baseline, runs: [{ ...run, ok: false }] }).verdict,
|
||||
'invalid',
|
||||
)
|
||||
const corrupt = structuredClone(baseline)
|
||||
corrupt.runs[0].samples[1].time = 0
|
||||
assert.equal(compare(baseline, corrupt).verdict, 'invalid')
|
||||
const shifted = structuredClone(baseline)
|
||||
shifted.runs[0].samples
|
||||
.filter((s) => s.phase === 'hidden')
|
||||
.forEach((s) => {
|
||||
s.time -= 5000
|
||||
})
|
||||
assert.equal(compare(baseline, shifted).verdict, 'invalid')
|
||||
const badMarks = structuredClone(baseline)
|
||||
badMarks.runs[0].marks.forEach((m) => {
|
||||
m.time = -1
|
||||
})
|
||||
assert.equal(compare(baseline, badMarks).verdict, 'invalid')
|
||||
const clustered = structuredClone(baseline)
|
||||
clustered.runs[0].samples.forEach((s) => {
|
||||
s.time /= 1000
|
||||
})
|
||||
assert.equal(compare(baseline, clustered).verdict, 'invalid')
|
||||
for (const [section, key] of [
|
||||
['contract', 'platform'],
|
||||
['build', 'sourceSha256'],
|
||||
]) {
|
||||
const missing = structuredClone(baseline)
|
||||
delete missing[section][key]
|
||||
assert.equal(compare(missing, missing).verdict, 'invalid')
|
||||
}
|
||||
assert.equal(
|
||||
compare(baseline, {
|
||||
...baseline,
|
||||
contract: { ...baseline.contract, platform: 'other-macOS' },
|
||||
}).verdict,
|
||||
'incomparable',
|
||||
)
|
||||
for (const malformed of [
|
||||
null,
|
||||
{},
|
||||
{ runs: [null] },
|
||||
{ ...baseline, runs: [{ ...run, samples: null }] },
|
||||
])
|
||||
assert.equal(compare(baseline, malformed).verdict, 'invalid')
|
||||
const noisy = structuredClone(baseline)
|
||||
noisy.runs = baseline.runs.map((r) => structuredClone(r))
|
||||
noisy.build.binarySha256 = 'different'
|
||||
noisy.runs.forEach((r, i) =>
|
||||
r.samples.forEach((s) => {
|
||||
s.cpu *= [0.1, 0.2, 10][i]
|
||||
}),
|
||||
)
|
||||
assert.equal(
|
||||
compare(baseline, noisy, 5).metrics['foreground/webview/cpuMean'].verdict,
|
||||
'inconclusive',
|
||||
)
|
||||
})
|
||||
test('macOS collector agrees with process.cpuUsage on a busy owned process', {
|
||||
skip: process.platform !== 'darwin',
|
||||
}, () => {
|
||||
mkdirSync('target/perf', { recursive: true })
|
||||
execFileSync('cc', [
|
||||
'-Wall',
|
||||
'-Wextra',
|
||||
'-Werror',
|
||||
'scripts/perf/sample.c',
|
||||
'-o',
|
||||
'target/perf/test-sample',
|
||||
])
|
||||
const sample = () =>
|
||||
Number(
|
||||
execFileSync('target/perf/test-sample', [String(process.pid)], {
|
||||
encoding: 'utf8',
|
||||
}).split(' ')[2],
|
||||
)
|
||||
const first = sample(),
|
||||
cpu = process.cpuUsage(),
|
||||
start = performance.now()
|
||||
while (performance.now() - start < 500) Math.sqrt(Math.random())
|
||||
const used = process.cpuUsage(cpu),
|
||||
measured = sample() - first
|
||||
assert.ok(Math.abs(measured - (used.user + used.system) / 1e6) < 0.05)
|
||||
})
|
||||
@@ -0,0 +1,674 @@
|
||||
import { spawn, execFileSync } from 'node:child_process'
|
||||
import { createHash, randomUUID } from 'node:crypto'
|
||||
import {
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
writeFileSync,
|
||||
openSync,
|
||||
closeSync,
|
||||
realpathSync,
|
||||
} from 'node:fs'
|
||||
import { createServer } from 'node:net'
|
||||
import { resolve, dirname } from 'node:path'
|
||||
import { setTimeout as sleep } from 'node:timers/promises'
|
||||
import { parseArgs } from 'node:util'
|
||||
|
||||
import { createTauriCapabilities } from '@wdio/tauri-service'
|
||||
import { remote } from 'webdriverio'
|
||||
import { WebSocketServer } from 'ws'
|
||||
|
||||
import {
|
||||
delta,
|
||||
summarize,
|
||||
markdown,
|
||||
phases,
|
||||
roles,
|
||||
validStats,
|
||||
validWorkload,
|
||||
replayValues,
|
||||
SCHEMA,
|
||||
validObservation,
|
||||
validVisibility,
|
||||
} from './report.mjs'
|
||||
|
||||
const { values } = parseArgs({
|
||||
args: process.argv.slice(2).filter((v) => v !== '--'),
|
||||
options: {
|
||||
output: { type: 'string', default: `target/perf/runs/${Date.now()}` },
|
||||
binary: { type: 'string', default: 'target/perf/build/clash-verge' },
|
||||
repeat: { type: 'string', default: '3' },
|
||||
seconds: { type: 'string', default: '20' },
|
||||
warmup: { type: 'string', default: '10' },
|
||||
'fail-phase': { type: 'string' },
|
||||
},
|
||||
})
|
||||
const seconds = Number(values.seconds),
|
||||
warmup = Number(values.warmup),
|
||||
repeat = Number(values.repeat)
|
||||
const replayMs = 200
|
||||
if (process.platform !== 'darwin') throw new Error('macOS only')
|
||||
function readConsole() {
|
||||
const consoleState = JSON.parse(
|
||||
execFileSync('/usr/bin/plutil', ['-convert', 'json', '-o', '-', '-'], {
|
||||
input: execFileSync('/usr/sbin/ioreg', ['-n', 'Root', '-d1', '-a']),
|
||||
encoding: 'utf8',
|
||||
}),
|
||||
)
|
||||
const locked = consoleState.IOConsoleLocked
|
||||
if (typeof locked !== 'boolean')
|
||||
throw new Error('Environment unavailable: unknown console lock state')
|
||||
return locked
|
||||
}
|
||||
function checkConsole() {
|
||||
const locked = readConsole()
|
||||
if (locked)
|
||||
throw new Error(
|
||||
'Environment unavailable: an unlocked graphical session is required; window focus is not required',
|
||||
)
|
||||
return locked
|
||||
}
|
||||
const consoleLocked = checkConsole()
|
||||
if (
|
||||
![seconds, warmup, repeat].every(Number.isFinite) ||
|
||||
seconds < 5 ||
|
||||
warmup < 2 ||
|
||||
repeat < 1 ||
|
||||
!Number.isInteger(repeat)
|
||||
)
|
||||
throw new Error('Require seconds >= 5, warmup >= 2, integer repeat >= 1')
|
||||
const phaseTargets = phases.map(
|
||||
(_, i) =>
|
||||
Math.ceil(((warmup + 5) * 1000) / replayMs) +
|
||||
i * Math.ceil(((seconds + 2) * 1000) / replayMs),
|
||||
)
|
||||
if ((phaseTargets[2] * replayMs) / 1000 + seconds + 5 >= 600)
|
||||
throw new Error(
|
||||
'Total replay including transition allowance must be < 10 minutes',
|
||||
)
|
||||
const binary = realpathSync(values.binary),
|
||||
output = resolve(values.output)
|
||||
const webcontentBinary = realpathSync(
|
||||
'/System/Library/Frameworks/WebKit.framework/Versions/A/XPCServices/com.apple.WebKit.WebContent.xpc/Contents/MacOS/com.apple.WebKit.WebContent',
|
||||
)
|
||||
const build = JSON.parse(readFileSync(`${binary}.json`))
|
||||
const hash = (data) => createHash('sha256').update(data).digest('hex')
|
||||
if (hash(readFileSync(binary)) !== build.binarySha256)
|
||||
throw new Error('Binary does not match build manifest')
|
||||
try {
|
||||
execFileSync('git', ['check-ignore', '-q', '--no-index', output])
|
||||
} catch {
|
||||
throw new Error('Output directory must be Git ignored')
|
||||
}
|
||||
mkdirSync(dirname(output), { recursive: true })
|
||||
mkdirSync(output)
|
||||
execFileSync('cc', ['-O2', 'scripts/perf/sample.c', '-o', `${output}/sample`])
|
||||
const command = (name, args) =>
|
||||
execFileSync(name, args, { encoding: 'utf8' }).trim()
|
||||
const report = {
|
||||
schema: SCHEMA,
|
||||
build,
|
||||
contract: {
|
||||
scenario: 'traffic',
|
||||
replayMs,
|
||||
consoleLocked,
|
||||
method: 'mach-rusage-v0-seconds/rss-bytes-v1',
|
||||
mode: build.mode,
|
||||
buildSettingsSha256: build.buildSettingsSha256,
|
||||
buildEnvironment: build.buildEnvironment,
|
||||
toolchain: build.toolchain,
|
||||
platform: command('sw_vers', []),
|
||||
machine: command('sysctl', ['-n', 'hw.model']),
|
||||
arch: process.arch,
|
||||
host: hash(command('scutil', ['--get', 'LocalHostName'])),
|
||||
hardware: command('sysctl', ['hw.ncpu', 'hw.memsize']),
|
||||
power: command('pmset', ['-g', 'custom']),
|
||||
powerSource: command('pmset', ['-g', 'batt']).split('\n')[0],
|
||||
webkit: command('defaults', [
|
||||
'read',
|
||||
'/System/Library/Frameworks/WebKit.framework/Resources/Info',
|
||||
'CFBundleVersion',
|
||||
]),
|
||||
seconds,
|
||||
warmup,
|
||||
phaseTargets,
|
||||
transitionSeconds: 2,
|
||||
readinessAllowanceSeconds: 5,
|
||||
intervalMs: 1000,
|
||||
window: [1000, 700],
|
||||
windowPolicy: 'nonactivating-top-click-through-v1',
|
||||
rangeMinutes: 10,
|
||||
replay:
|
||||
'deterministic-v1, 5Hz, no prefill, append boundary, default bezier, blur pause false',
|
||||
automation:
|
||||
'wdio plugin 1.3.0; 20Hz macOS runloop pump plus one WebDriver observation/second',
|
||||
},
|
||||
runs: [],
|
||||
}
|
||||
report.units = {
|
||||
time: 'monotonic milliseconds',
|
||||
cpu: 'cumulative CPU seconds',
|
||||
percent: 'one CPU core = 100%',
|
||||
rss: 'resident size bytes',
|
||||
start: 'Mach process start ticks',
|
||||
}
|
||||
report.monotonicOriginEpochMs = performance.timeOrigin
|
||||
report.harnessSha256 = hash(
|
||||
['run.mjs', 'report.mjs', 'sample.c']
|
||||
.map((p) => readFileSync(`scripts/perf/${p}`))
|
||||
.join('\n'),
|
||||
)
|
||||
let interrupted = false
|
||||
const abort = new AbortController()
|
||||
const pause = (ms) => sleep(ms, undefined, { signal: abort.signal })
|
||||
for (const signal of ['SIGINT', 'SIGTERM'])
|
||||
process.on(signal, () => {
|
||||
interrupted = true
|
||||
abort.abort()
|
||||
})
|
||||
const assert = (value, reason) => {
|
||||
if (!value) throw new Error(reason)
|
||||
}
|
||||
const drawn = (s) => s.now >= s.draw && s.now - s.draw < 2500
|
||||
const marker = (s) => ({
|
||||
...s,
|
||||
pixelsSha256: hash(s.pixels),
|
||||
pixels: undefined,
|
||||
ua: undefined,
|
||||
token: undefined,
|
||||
})
|
||||
async function freePort() {
|
||||
const server = createServer()
|
||||
await new Promise((done) => server.listen(0, '127.0.0.1', done))
|
||||
const port = server.address().port
|
||||
await new Promise((done) => server.close(done))
|
||||
return port
|
||||
}
|
||||
for (let iteration = 0; iteration < repeat && !interrupted; iteration++) {
|
||||
const initialLocked = checkConsole()
|
||||
const token = randomUUID(),
|
||||
port = await freePort()
|
||||
const run = {
|
||||
token,
|
||||
ok: false,
|
||||
samples: [],
|
||||
observations: [],
|
||||
consoleStates: [
|
||||
{ name: 'initial', locked: initialLocked, time: Date.now() },
|
||||
],
|
||||
marks: [],
|
||||
stats: {},
|
||||
cleanup: {},
|
||||
replay: { sent: 0, maxLateMs: 0 },
|
||||
}
|
||||
report.runs.push(run)
|
||||
const replay = new WebSocketServer({ host: '127.0.0.1', port: 0 })
|
||||
await new Promise((done) => replay.on('listening', done))
|
||||
let sequence = 0,
|
||||
replayStarted,
|
||||
timer
|
||||
replay.on('connection', () => {
|
||||
if (replayStarted !== undefined) {
|
||||
run.replay.error = 'unexpected replay reconnection'
|
||||
clearTimeout(timer)
|
||||
return
|
||||
}
|
||||
replayStarted = performance.now()
|
||||
timer = setTimeout(send, replayMs)
|
||||
})
|
||||
const deadlineIndex = () =>
|
||||
Math.floor((performance.now() - replayStarted) / replayMs)
|
||||
function send() {
|
||||
const deadline = replayStarted + (sequence + 1) * replayMs
|
||||
const late = performance.now() - deadline
|
||||
if (late < 0) {
|
||||
timer = setTimeout(send, Math.ceil(-late))
|
||||
return
|
||||
}
|
||||
run.replay.maxLateMs = Math.max(run.replay.maxLateMs, late)
|
||||
if (late >= replayMs) {
|
||||
run.replay.error = `replay source missed a complete ${replayMs} ms period`
|
||||
return
|
||||
}
|
||||
sequence++
|
||||
run.replay.sent = sequence
|
||||
const timestamp = Date.now()
|
||||
const point = JSON.stringify({
|
||||
sequence,
|
||||
timestamp,
|
||||
...replayValues(sequence),
|
||||
})
|
||||
for (const socket of replay.clients)
|
||||
if (socket.readyState === 1) socket.send(point)
|
||||
timer = setTimeout(
|
||||
send,
|
||||
Math.max(
|
||||
0,
|
||||
replayStarted + (sequence + 1) * replayMs - performance.now(),
|
||||
),
|
||||
)
|
||||
}
|
||||
const log = openSync(`${output}/${iteration + 1}.log`, 'w')
|
||||
const child = spawn(binary, [], {
|
||||
env: {
|
||||
...process.env,
|
||||
PERF_TOKEN: token,
|
||||
PERF_REPLAY_PORT: String(replay.address().port),
|
||||
TAURI_WEBDRIVER_PORT: String(port),
|
||||
},
|
||||
stdio: ['ignore', log, log],
|
||||
})
|
||||
closeSync(log)
|
||||
let browser, childError, previous, mainStart
|
||||
const identities = {}
|
||||
child.on('error', (error) => {
|
||||
childError = error
|
||||
})
|
||||
const exited = new Promise((done) => child.once('exit', done))
|
||||
const alive = () =>
|
||||
!childError && child.exitCode === null && child.signalCode === null
|
||||
const collect = (pids) =>
|
||||
command(`${output}/sample`, pids.map(String))
|
||||
.split('\n')
|
||||
.map((line) => {
|
||||
const [pid, start, cpu, rss, ...path] = line.split(' ')
|
||||
return {
|
||||
pid: Number(pid),
|
||||
start,
|
||||
cpu: Number(cpu),
|
||||
rss: Number(rss),
|
||||
path: path.join(' '),
|
||||
time: performance.now(),
|
||||
}
|
||||
})
|
||||
const identify = (role, row) => {
|
||||
assert(
|
||||
row.path === (role === 'main' ? binary : webcontentBinary),
|
||||
`unexpected ${role} process executable: ${row.path}`,
|
||||
)
|
||||
assert(
|
||||
BigInt(row.start) >= BigInt(mainStart),
|
||||
'process predates owned application',
|
||||
)
|
||||
const identity = `${row.pid}/${row.start}`
|
||||
assert(
|
||||
!identities[role] || identities[role] === identity,
|
||||
'process identity changed during scenario',
|
||||
)
|
||||
identities[role] = identity
|
||||
}
|
||||
const state = async (action = 'state', pixels = false) =>
|
||||
browser.execute(
|
||||
async (action, pixels) => {
|
||||
const native = await window.__TAURI_INTERNALS__.invoke('perf_state', {
|
||||
action,
|
||||
})
|
||||
const canvas = document.querySelector('canvas')
|
||||
return {
|
||||
...native,
|
||||
now: Date.now(),
|
||||
hidden: document.hidden,
|
||||
focused: document.hasFocus(),
|
||||
received: Number(document.documentElement.dataset.perfReceived),
|
||||
source: Number(document.documentElement.dataset.perfSourceTime),
|
||||
gaps: Number(document.documentElement.dataset.perfGaps),
|
||||
worker: Number(document.documentElement.dataset.perfWorker),
|
||||
points: Number(document.documentElement.dataset.perfPoints),
|
||||
lastUp: Number(document.documentElement.dataset.perfLastUp),
|
||||
lastDown: Number(document.documentElement.dataset.perfLastDown),
|
||||
draw: Number(canvas?.dataset.perfDraw),
|
||||
pixels: pixels ? canvas?.toDataURL() : null,
|
||||
ua: navigator.userAgent,
|
||||
}
|
||||
},
|
||||
action,
|
||||
pixels,
|
||||
)
|
||||
const checked = async (action, pixels) => {
|
||||
assert(!interrupted, 'interrupted')
|
||||
assert(!run.replay.error, run.replay.error)
|
||||
assert(
|
||||
alive(),
|
||||
`owned app exited: ${childError ?? child.exitCode ?? child.signalCode}`,
|
||||
)
|
||||
const value = await state(action, pixels)
|
||||
assert(!run.replay.error, run.replay.error)
|
||||
run.lastObservation = { ...value, pixels: undefined, ua: undefined }
|
||||
assert(
|
||||
value.token === token && value.main === child.pid,
|
||||
'instance identity mismatch',
|
||||
)
|
||||
if (!identities.webview) {
|
||||
run.initialAttribution = collect([value.webview])[0]
|
||||
identify('webview', run.initialAttribution)
|
||||
}
|
||||
assert(
|
||||
value.nativeFocused === false && value.appActive === false,
|
||||
'measurement window unexpectedly activated',
|
||||
)
|
||||
assert(
|
||||
value.top === true && value.clickThrough === true,
|
||||
'measurement window must be natively topmost and click-through',
|
||||
)
|
||||
return value
|
||||
}
|
||||
try {
|
||||
mainStart = collect([child.pid])[0].start
|
||||
const deadline = Date.now() + 30000
|
||||
while (true) {
|
||||
assert(
|
||||
Date.now() < deadline && !interrupted && alive(),
|
||||
'embedded WebDriver readiness deadline or app exit',
|
||||
)
|
||||
try {
|
||||
if (
|
||||
(
|
||||
await fetch(`http://127.0.0.1:${port}/status`, {
|
||||
signal: AbortSignal.timeout(500),
|
||||
})
|
||||
).ok
|
||||
)
|
||||
break
|
||||
} catch {}
|
||||
await pause(100)
|
||||
}
|
||||
const listener = command('lsof', [
|
||||
'-nP',
|
||||
'-a',
|
||||
'-p',
|
||||
String(child.pid),
|
||||
`-iTCP:${port}`,
|
||||
'-sTCP:LISTEN',
|
||||
])
|
||||
assert(
|
||||
listener.includes(`127.0.0.1:${port}`) && !listener.includes(`*:${port}`),
|
||||
'driver must belong to this app and bind loopback',
|
||||
)
|
||||
const capabilities = createTauriCapabilities(binary)
|
||||
delete capabilities['wdio:tauriServiceOptions']
|
||||
browser = await remote({
|
||||
hostname: '127.0.0.1',
|
||||
port,
|
||||
capabilities,
|
||||
logLevel: 'error',
|
||||
connectionRetryCount: 0,
|
||||
connectionRetryTimeout: 5000,
|
||||
})
|
||||
const handles = await browser.getWindowHandles()
|
||||
assert(handles.length === 1, 'expected exactly one measurement WebView')
|
||||
await browser.switchToWindow(handles[0])
|
||||
// Replay's parent effect starts the socket after the graph installs its listeners.
|
||||
await browser.waitUntil(
|
||||
async () => {
|
||||
const s = await checked()
|
||||
return (
|
||||
validWorkload(s) &&
|
||||
s.received >= 3 &&
|
||||
s.now >= s.worker &&
|
||||
s.now - s.worker < 2500
|
||||
)
|
||||
},
|
||||
{
|
||||
timeout: 15000,
|
||||
interval: 100,
|
||||
timeoutMsg: 'traffic effects/Worker not ready before show',
|
||||
},
|
||||
)
|
||||
run.initialData = run.lastObservation
|
||||
await checked('show')
|
||||
await browser.waitUntil(
|
||||
async () => {
|
||||
const s = await checked()
|
||||
return validObservation({ phase: 'foreground', ...s })
|
||||
},
|
||||
{
|
||||
timeout: 15000,
|
||||
interval: 250,
|
||||
timeoutMsg: 'traffic data path/page not ready',
|
||||
},
|
||||
)
|
||||
run.userAgent = (await checked()).ua
|
||||
run.backgroundLoad = command('sysctl', ['-n', 'vm.loadavg'])
|
||||
const viewport = await browser.execute(() => [
|
||||
innerWidth,
|
||||
innerHeight,
|
||||
devicePixelRatio,
|
||||
])
|
||||
run.viewport = { dom: viewport, driver: await browser.getWindowRect() }
|
||||
const driverScale = run.viewport.driver.width / 1000
|
||||
assert(
|
||||
viewport[0] === 1000 &&
|
||||
viewport[1] > 0 &&
|
||||
viewport[1] <= 700 &&
|
||||
(driverScale === 1 || driverScale === viewport[2]) &&
|
||||
run.viewport.driver.height / driverScale === 700,
|
||||
`unexpected window dimensions: ${JSON.stringify(run.viewport)}`,
|
||||
)
|
||||
assert(
|
||||
!report.contract.viewport ||
|
||||
JSON.stringify(report.contract.viewport) === JSON.stringify(viewport),
|
||||
'viewport changed between runs',
|
||||
)
|
||||
report.contract.viewport = viewport
|
||||
run.marks.push({ name: 'ready', time: Date.now() })
|
||||
const readyAt = performance.now()
|
||||
assert(
|
||||
phaseTargets[0] - (await checked()).received >=
|
||||
(warmup * 1000) / replayMs,
|
||||
'readiness exceeded fixed replay allowance',
|
||||
)
|
||||
for (const phase of phases) {
|
||||
run.consoleStates.push({
|
||||
name: phase,
|
||||
locked: readConsole(),
|
||||
time: Date.now(),
|
||||
})
|
||||
const operation = performance.now()
|
||||
let s = await checked(phase === 'hidden' ? 'hide' : 'show', true)
|
||||
assert(
|
||||
s.visible === (phase !== 'hidden'),
|
||||
`${phase}: native visibility mismatch`,
|
||||
)
|
||||
const beforeDraw = s.draw
|
||||
await browser.waitUntil(
|
||||
async () => {
|
||||
s = await checked('state', true)
|
||||
return (
|
||||
validVisibility({ phase, ...s }) &&
|
||||
(phase === 'hidden' || (s.draw > beforeDraw && drawn(s)))
|
||||
)
|
||||
},
|
||||
{
|
||||
timeout: 5000,
|
||||
interval: 100,
|
||||
timeoutMsg: `${phase}: window/Canvas readiness deadline`,
|
||||
},
|
||||
)
|
||||
const operationMs = performance.now() - operation
|
||||
const target = phaseTargets[phases.indexOf(phase)]
|
||||
await browser.waitUntil(
|
||||
async () => {
|
||||
s = await checked('state', true)
|
||||
assert(
|
||||
s.received <= target,
|
||||
`${phase}: missed replay anchor ${target}`,
|
||||
)
|
||||
return s.received === target
|
||||
},
|
||||
{
|
||||
timeout: Math.max(1000, (target - s.received) * replayMs + 1000),
|
||||
interval: 50,
|
||||
timeoutMsg: `${phase}: replay anchor deadline`,
|
||||
},
|
||||
)
|
||||
assert(
|
||||
validObservation({ phase, ...s }),
|
||||
`${phase}: invalid traffic observation`,
|
||||
)
|
||||
const first = s,
|
||||
start = performance.now(),
|
||||
firstIndex = deadlineIndex(),
|
||||
phaseEpoch = Date.now()
|
||||
if (phase === 'foreground') {
|
||||
run.actualWarmupMs = start - readyAt
|
||||
assert(
|
||||
run.actualWarmupMs >= warmup * 1000,
|
||||
'insufficient actual warmup',
|
||||
)
|
||||
}
|
||||
run.marks.push({
|
||||
name: phase,
|
||||
time: phaseEpoch,
|
||||
operationMs,
|
||||
transitionMs: start - operation,
|
||||
target,
|
||||
...marker(s),
|
||||
deadlineIndex: firstIndex,
|
||||
senderSent: run.replay.sent,
|
||||
})
|
||||
previous = {}
|
||||
if (values['fail-phase'] === phase)
|
||||
throw new Error(`injected failure at ${phase}`)
|
||||
while (performance.now() - start < seconds * 1000) {
|
||||
const tick = performance.now()
|
||||
s = await checked()
|
||||
run.observations.push({ phase, ...run.lastObservation })
|
||||
assert(
|
||||
validObservation({ phase, ...s }),
|
||||
`${phase}: invalid visibility, workload or freshness`,
|
||||
)
|
||||
assert(
|
||||
performance.now() - replayStarted < 600000,
|
||||
'replay exceeded raw history window',
|
||||
)
|
||||
const samples = collect(roles.map((role) => s[role]))
|
||||
run.attribution = {
|
||||
main: s.main,
|
||||
webview: s.webview,
|
||||
observed: samples,
|
||||
}
|
||||
for (let i = 0; i < roles.length; i++) {
|
||||
const row = { ...samples[i], phase, role: roles[i] }
|
||||
identify(row.role, row)
|
||||
row.percent = delta(previous[row.role], row)
|
||||
row.cpuDelta =
|
||||
row.percent === null ? null : row.cpu - previous[row.role].cpu
|
||||
run.samples.push(row)
|
||||
previous[row.role] = row
|
||||
}
|
||||
await pause(Math.max(0, 1000 - (performance.now() - tick)))
|
||||
}
|
||||
s = await checked('state', true)
|
||||
const endIndex = deadlineIndex()
|
||||
const expected = endIndex - firstIndex
|
||||
assert(
|
||||
validObservation({ phase, ...s }) &&
|
||||
s.worker > first.worker &&
|
||||
Math.abs(s.received - first.received - expected) <= 2,
|
||||
`${phase}: unstable or lost workload`,
|
||||
)
|
||||
if (phase !== 'hidden')
|
||||
assert(
|
||||
s.draw > first.draw && s.pixels !== first.pixels,
|
||||
`${phase}: Canvas did not render fresh data`,
|
||||
)
|
||||
run.marks.push({
|
||||
name: `${phase}:end`,
|
||||
time: s.now,
|
||||
...marker(s),
|
||||
deadlineIndex: endIndex,
|
||||
senderSent: run.replay.sent,
|
||||
})
|
||||
run.consoleStates.push({
|
||||
name: `${phase}:end`,
|
||||
locked: readConsole(),
|
||||
time: Date.now(),
|
||||
})
|
||||
}
|
||||
run.stats = summarize(run.samples, seconds)
|
||||
assert(
|
||||
validStats(run.stats),
|
||||
'insufficient coverage or process discontinuity',
|
||||
)
|
||||
run.ok = true
|
||||
} catch (error) {
|
||||
run.error = String(error)
|
||||
process.exitCode = 1
|
||||
} finally {
|
||||
await browser?.deleteSession().catch(() => {})
|
||||
try {
|
||||
if (alive() && collect([child.pid])[0].start === mainStart) {
|
||||
child.kill('SIGTERM')
|
||||
await Promise.race([exited, sleep(5000)])
|
||||
if (alive() && collect([child.pid])[0].start === mainStart) {
|
||||
child.kill('SIGKILL')
|
||||
await Promise.race([exited, sleep(2000)])
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
run.cleanup.error = String(error)
|
||||
}
|
||||
clearTimeout(timer)
|
||||
for (const socket of replay.clients) socket.terminate()
|
||||
await new Promise((done) => replay.close(done))
|
||||
run.cleanup.mainExited =
|
||||
child.exitCode !== null || child.signalCode !== null
|
||||
if (identities.webview) {
|
||||
const [pid, start] = identities.webview.split('/')
|
||||
const remains = () => {
|
||||
try {
|
||||
return collect([pid])[0].start === start
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
const deadline = Date.now() + 5000
|
||||
while (remains() && Date.now() < deadline) await sleep(100)
|
||||
run.cleanup.webviewExited = !remains()
|
||||
}
|
||||
try {
|
||||
await fetch(`http://127.0.0.1:${port}/status`, {
|
||||
signal: AbortSignal.timeout(500),
|
||||
})
|
||||
run.cleanup.driverClosed = false
|
||||
} catch {
|
||||
run.cleanup.driverClosed = true
|
||||
}
|
||||
if (
|
||||
!run.cleanup.mainExited ||
|
||||
!run.cleanup.driverClosed ||
|
||||
run.cleanup.webviewExited === false
|
||||
) {
|
||||
run.ok = false
|
||||
run.error = `${run.error ?? ''} cleanup failed`
|
||||
process.exitCode = 1
|
||||
}
|
||||
run.stats = summarize(run.samples, seconds)
|
||||
writeFileSync(
|
||||
`${output}/${iteration + 1}.json`,
|
||||
JSON.stringify(run, null, 2),
|
||||
)
|
||||
const columns = [
|
||||
'phase',
|
||||
'role',
|
||||
'time',
|
||||
'pid',
|
||||
'start',
|
||||
'cpu',
|
||||
'percent',
|
||||
'rss',
|
||||
]
|
||||
writeFileSync(
|
||||
`${output}/${iteration + 1}.csv`,
|
||||
[
|
||||
columns.join(','),
|
||||
...run.samples.map((r) =>
|
||||
columns.map((c) => r[c] ?? 'unavailable').join(','),
|
||||
),
|
||||
].join('\n'),
|
||||
)
|
||||
writeFileSync(`${output}/summary.json`, JSON.stringify(report, null, 2))
|
||||
writeFileSync(`${output}/report.md`, markdown(report))
|
||||
}
|
||||
console.log(`Run ${iteration + 1}: ${run.ok ? 'passed' : run.error}`)
|
||||
}
|
||||
console.log(`Reports: ${output}`)
|
||||
@@ -0,0 +1,20 @@
|
||||
#include <libproc.h>
|
||||
#include <mach/mach_time.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/resource.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
mach_timebase_info_data_t timebase;
|
||||
if (mach_timebase_info(&timebase) != KERN_SUCCESS) return 1;
|
||||
for (int i = 1; i < argc; i++) {
|
||||
int pid = atoi(argv[i]);
|
||||
struct rusage_info_v0 r;
|
||||
char path[PROC_PIDPATHINFO_MAXSIZE];
|
||||
if (pid <= 0 || proc_pid_rusage(pid, RUSAGE_INFO_V0, (rusage_info_t *)&r)) return 1;
|
||||
if (proc_pidpath(pid, path, sizeof(path)) <= 0) return 1;
|
||||
printf("%d %llu %.9f %llu %s\n", pid, r.ri_proc_start_abstime,
|
||||
((double)r.ri_user_time + r.ri_system_time) * timebase.numer / timebase.denom / 1e9, r.ri_resident_size, path);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
import { ThemeProvider, createTheme } from '@mui/material'
|
||||
import dayjs from 'dayjs'
|
||||
import relativeTime from 'dayjs/plugin/relativeTime'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { SWRConfig } from 'swr'
|
||||
|
||||
import { VirtualList } from '../../src/components/base/virtual-list'
|
||||
import { ConnectionRowItem } from '../../src/components/connection/connection-row-item'
|
||||
import { useConnectionRowViews } from '../../src/components/connection/connection-row-view'
|
||||
import LogItem from '../../src/components/log/log-item'
|
||||
import { initializeLanguage } from '../../src/services/i18n'
|
||||
import { setPreloadConfig } from '../../src/services/preload'
|
||||
|
||||
import { layer, scenario, subscribe } from './replay'
|
||||
import '../../src/assets/styles/page.scss'
|
||||
|
||||
const searchState = {
|
||||
text: '',
|
||||
matchCase: false,
|
||||
matchWholeWord: false,
|
||||
useRegularExpression: false,
|
||||
}
|
||||
export function Components() {
|
||||
const [logs, setLogs] = useState<ILogItem[]>([])
|
||||
const [connections, setConnections] = useState<IConnectionsItem[]>([])
|
||||
useEffect(
|
||||
() =>
|
||||
subscribe(({ payload }) => {
|
||||
if (scenario === 'logs')
|
||||
setLogs((previous) =>
|
||||
previous.concat(payload as ILogItem[]).slice(-1000),
|
||||
)
|
||||
else setConnections((payload as IConnections).connections)
|
||||
}),
|
||||
[],
|
||||
)
|
||||
const rows = useConnectionRowViews(connections)
|
||||
return (
|
||||
<VirtualList
|
||||
count={scenario === 'logs' ? logs.length : rows.length}
|
||||
estimateSize={scenario === 'logs' ? 50 : 56}
|
||||
style={{ height: 640, margin: 24 }}
|
||||
renderItem={(index) =>
|
||||
scenario === 'logs' ? (
|
||||
<LogItem
|
||||
value={logs[logs.length - 1 - index]}
|
||||
searchState={searchState}
|
||||
/>
|
||||
) : (
|
||||
<ConnectionRowItem
|
||||
row={rows[index]}
|
||||
closed={false}
|
||||
onShowDetail={() => {}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
dayjs.extend(relativeTime)
|
||||
const root = document.getElementById('root')!
|
||||
setPreloadConfig({
|
||||
language: 'en',
|
||||
theme_mode: 'light',
|
||||
pause_render_traffic_stats_on_blur: false,
|
||||
} as IVergeConfig)
|
||||
await initializeLanguage('en')
|
||||
const Scene =
|
||||
layer === 'component'
|
||||
? Components
|
||||
: scenario === 'logs'
|
||||
? (await import('../../src/pages/logs')).default
|
||||
: (await import('../../src/pages/connections')).default
|
||||
createRoot(root).render(
|
||||
<SWRConfig value={{ revalidateOnFocus: false, revalidateOnReconnect: false }}>
|
||||
<ThemeProvider theme={createTheme()}>
|
||||
<Scene />
|
||||
</ThemeProvider>
|
||||
</SWRConfig>,
|
||||
)
|
||||
@@ -1,30 +0,0 @@
|
||||
// Aliased in place of '@tauri-apps/api/core' only by the perf build. The
|
||||
// direct relative import keeps the original module outside the alias so this
|
||||
// shim can forward to it. Invocation stays byte-identical for every scenario
|
||||
// except proxy, which needs the JavaScript invoke adapter.
|
||||
import {
|
||||
Channel,
|
||||
convertFileSrc,
|
||||
invoke as realInvoke,
|
||||
type InvokeArgs,
|
||||
type InvokeOptions,
|
||||
} from '../../node_modules/@tauri-apps/api/core.js'
|
||||
|
||||
import { mockCommand } from './invoke-mock'
|
||||
import { scenario } from './replay'
|
||||
|
||||
const proxied = scenario === 'proxy'
|
||||
|
||||
export const invoke = async <T>(
|
||||
cmd: string,
|
||||
args?: InvokeArgs,
|
||||
options?: InvokeOptions,
|
||||
): Promise<T> => {
|
||||
if (proxied) {
|
||||
const mocked = mockCommand(cmd)
|
||||
if (mocked !== undefined) return mocked as T
|
||||
}
|
||||
return realInvoke(cmd, args, options)
|
||||
}
|
||||
|
||||
export { Channel, convertFileSrc }
|
||||
@@ -1,52 +0,0 @@
|
||||
import { ThemeProvider, createTheme } from '@mui/material'
|
||||
import { useEffect } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { SWRConfig } from 'swr'
|
||||
|
||||
import { EnhancedCanvasTrafficGraph } from '../../src/components/home/enhanced-canvas-traffic-graph'
|
||||
import { useTrafficMonitorEnhanced } from '../../src/hooks/use-traffic-monitor'
|
||||
import { initializeLanguage } from '../../src/services/i18n'
|
||||
import { setPreloadConfig } from '../../src/services/preload'
|
||||
|
||||
setPreloadConfig({
|
||||
pause_render_traffic_stats_on_blur: false,
|
||||
} as IVergeConfig)
|
||||
await initializeLanguage('en')
|
||||
export function Replay() {
|
||||
const {
|
||||
graphData: { appendData },
|
||||
} = useTrafficMonitorEnhanced({ subscribe: false })
|
||||
useEffect(() => {
|
||||
let received = 0,
|
||||
previous = 0,
|
||||
gaps = 0
|
||||
const socket = new WebSocket(
|
||||
`ws://127.0.0.1:${new URLSearchParams(location.search).get('port')}`,
|
||||
)
|
||||
socket.onmessage = ({ data }) => {
|
||||
const point = JSON.parse(data)
|
||||
appendData(point)
|
||||
if (previous && point.sequence !== previous + 1) gaps++
|
||||
previous = point.sequence
|
||||
document.documentElement.dataset.perfReceived = String(++received)
|
||||
document.documentElement.dataset.perfGaps = String(gaps)
|
||||
document.documentElement.dataset.perfSourceTime = String(point.timestamp)
|
||||
}
|
||||
return () => socket.close()
|
||||
}, [appendData])
|
||||
return (
|
||||
<main
|
||||
aria-label="Home traffic graph replay"
|
||||
style={{ width: 920, height: 360, margin: 32 }}
|
||||
>
|
||||
<EnhancedCanvasTrafficGraph />
|
||||
</main>
|
||||
)
|
||||
}
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<SWRConfig value={{ revalidateOnFocus: false, revalidateOnReconnect: false }}>
|
||||
<ThemeProvider theme={createTheme()}>
|
||||
<Replay />
|
||||
</ThemeProvider>
|
||||
</SWRConfig>,
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"include": ["../../src", "./*.tsx", "./*.ts"]
|
||||
"include": ["../../src", "./*.tsx"]
|
||||
}
|
||||
|
||||
@@ -6,11 +6,5 @@ export default mergeConfig(
|
||||
defineConfig({
|
||||
root: 'scripts/perf',
|
||||
build: { outDir: '../../target/perf/dist', target: 'safari16' },
|
||||
resolve: {
|
||||
alias: {
|
||||
'@tauri-apps/api/core': new URL('./tauri-core-shim.ts', import.meta.url)
|
||||
.pathname,
|
||||
},
|
||||
},
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { parseArgs } from 'node:util'
|
||||
|
||||
const { values } = parseArgs({
|
||||
options: {
|
||||
'dry-run': { type: 'boolean', default: false },
|
||||
check: { type: 'boolean', default: false },
|
||||
version: { type: 'string' },
|
||||
file: { type: 'string', default: 'Changelog.md' },
|
||||
},
|
||||
})
|
||||
|
||||
async function main() {
|
||||
let version = values.version
|
||||
if (!version) {
|
||||
const response = await fetch(
|
||||
'https://github.com/MetaCubeX/mihomo/releases/latest/download/version.txt',
|
||||
{ signal: AbortSignal.timeout(30_000) },
|
||||
)
|
||||
if (!response.ok)
|
||||
throw new Error(`Failed to fetch Mihomo version: ${response.status}`)
|
||||
version = await response.text()
|
||||
}
|
||||
version = version.trim().replace(/^v?/, 'v')
|
||||
if (!/^v\d+\.\d+\.\d+$/.test(version))
|
||||
throw new Error(`Invalid stable Mihomo version: ${version}`)
|
||||
|
||||
const content = readFileSync(values.file, 'utf8')
|
||||
const title = /^## .+$/m.exec(content)
|
||||
if (!title) throw new Error('Could not find changelog title.')
|
||||
const start = title.index + title[0].length
|
||||
const end = content.indexOf('\n## ', start)
|
||||
const section = content.slice(start, end === -1 ? undefined : end)
|
||||
const line =
|
||||
/^(\s*-\s*(?:\*\*)?\s*Mihomo(?:\(Meta\))?\s*内核升级至\s*)v?\d+(?:\.\d+)+(?:[-+][^\s*]+)?((?:\*\*)?[\t ]*)$/m
|
||||
const nextSection = line.test(section)
|
||||
? section.replace(line, `$1${version}$2`)
|
||||
: `\n\n- **Mihomo 内核升级至 ${version}**${section.replace(/^\n*/, '\n\n')}`
|
||||
const nextContent =
|
||||
content.slice(0, start) +
|
||||
nextSection +
|
||||
(end === -1 ? '' : content.slice(end))
|
||||
const changed = content !== nextContent
|
||||
|
||||
if (process.env.GITHUB_OUTPUT)
|
||||
appendFileSync(
|
||||
process.env.GITHUB_OUTPUT,
|
||||
`version=${version}\nchanged=${changed}\n`,
|
||||
)
|
||||
if (!changed) {
|
||||
console.log(`Mihomo version in changelog is already ${version}`)
|
||||
return
|
||||
}
|
||||
|
||||
const diff = spawnSync(
|
||||
'diff',
|
||||
[
|
||||
'-u',
|
||||
'--label',
|
||||
`a/${values.file}`,
|
||||
'--label',
|
||||
`b/${values.file}`,
|
||||
values.file,
|
||||
'-',
|
||||
],
|
||||
{ input: nextContent, encoding: 'utf8' },
|
||||
)
|
||||
if (diff.error) throw diff.error
|
||||
if (diff.status !== 1)
|
||||
throw new Error(diff.stderr || 'Could not preview changelog diff.')
|
||||
process.stdout.write(diff.stdout)
|
||||
if (process.env.GITHUB_STEP_SUMMARY)
|
||||
appendFileSync(
|
||||
process.env.GITHUB_STEP_SUMMARY,
|
||||
`### Mihomo ${version}\n\n\`\`\`diff\n${diff.stdout}\`\`\`\n`,
|
||||
)
|
||||
if (values.check) {
|
||||
process.exitCode = 1
|
||||
return
|
||||
}
|
||||
if (!values['dry-run']) writeFileSync(values.file, nextContent)
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error('sync-mihomo-version failed:', error.message)
|
||||
process.exitCode = 1
|
||||
})
|
||||
+18
-21
@@ -8,7 +8,7 @@ repository = "https://github.com/clash-verge-rev/clash-verge-rev.git"
|
||||
default-run = "clash-verge"
|
||||
build = "build.rs"
|
||||
edition = "2024"
|
||||
rust-version = "1.100"
|
||||
rust-version = "1.99"
|
||||
|
||||
[lib]
|
||||
name = "app_lib"
|
||||
@@ -17,6 +17,8 @@ crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
[features]
|
||||
default = ["custom-protocol"]
|
||||
custom-protocol = ["tauri/custom-protocol"]
|
||||
verge-dev = ["clash-verge-logging/color", "clash_verge_service_ipc/development-channel"]
|
||||
dev-sidecar = ["verge-dev"]
|
||||
tauri-dev = ["dep:tauri-plugin-devtools"]
|
||||
tokio-trace = ["clash-verge-logging/tokio-trace"]
|
||||
chrome-trace = ["clash-verge-logging/chrome-trace"]
|
||||
@@ -27,7 +29,7 @@ perf-harness = ["dep:tauri-plugin-wdio-webdriver"]
|
||||
identifier = "io.github.clash-verge-rev.clash-verge-rev"
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2.7.6", features = [] }
|
||||
tauri-build = { version = "2.7.4", features = [] }
|
||||
|
||||
[dependencies]
|
||||
clash-verge-draft = { workspace = true }
|
||||
@@ -52,9 +54,9 @@ log = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
serde_yaml_ng = { workspace = true }
|
||||
tristr = { workspace = true }
|
||||
smartstring = { workspace = true, features = ["serde"] }
|
||||
socket2 = { workspace = true }
|
||||
warp = { version = "0.4.4", features = ["server"] }
|
||||
warp = { version = "0.4.3", features = ["server"] }
|
||||
open = "5.4.5"
|
||||
rfd = { version = "0.18.0", default-features = false, features = ["common-controls-v6", "xdg-portal"] }
|
||||
dirs = "7.0.0"
|
||||
@@ -65,17 +67,17 @@ boa_engine = "0.22.0"
|
||||
http-body-util = "0.1.5"
|
||||
percent-encoding = "2.3.2"
|
||||
reqwest = { workspace = true }
|
||||
sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs.git", rev = "2c9d0a538052aac6e44ad413156a6e848da262b9", version = "0.7.2", features = [
|
||||
sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs.git", branch = "main", features = [
|
||||
"guard",
|
||||
] }
|
||||
network-interface = { version = "2.0.5", features = ["serde"] }
|
||||
tauri-plugin-shell = "2.6.0"
|
||||
tauri-plugin-opener = "2.7.3"
|
||||
tauri-plugin-opener = "2.7.2"
|
||||
tauri-plugin-dialog = "2.8.4"
|
||||
tauri-plugin-fs = "2.7.1"
|
||||
tauri-plugin-deep-link = "2.6.3"
|
||||
tauri-plugin-window-state = "2.5.0"
|
||||
zip = "9.6.0"
|
||||
zip = "9.4.2"
|
||||
flate2 = "1.1.11"
|
||||
reqwest_dav = "0.3.3"
|
||||
aes-gcm = { version = "0.11.1" }
|
||||
@@ -84,20 +86,21 @@ sha2 = "0.11.1"
|
||||
getrandom = "0.4.3"
|
||||
futures = "0.3.34"
|
||||
gethostname = "1.1.0"
|
||||
tauri-plugin-notification = "2.8.1"
|
||||
scopeguard = "1.2.0"
|
||||
tauri-plugin-notification = "2.8.0"
|
||||
backon = { version = "1.6.0", features = ["tokio-sleep"] }
|
||||
tauri-plugin-http = "2.9.0"
|
||||
tauri-plugin-http = "2.8.3"
|
||||
tracing = { workspace = true }
|
||||
tauri-plugin-devtools = { version = "2.2.3", optional = true }
|
||||
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "7e4fa8642cf6c394ed88b5a969420d8eab60087f" }
|
||||
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "7a03d16f4d39b1bb885b7babe66b9e153e34b615" }
|
||||
async-trait = "0.1.92"
|
||||
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", features = [
|
||||
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", tag = "v2.7.7", version = "2.7.7", features = [
|
||||
"client",
|
||||
] }
|
||||
arc-swap = "1.9.5"
|
||||
arc-swap = "1.9.4"
|
||||
tokio-rustls = "0.26.6"
|
||||
rustls = { version = "0.23.46", features = ["ring"] }
|
||||
webpki-roots = "1.0.12"
|
||||
webpki-roots = "1.0.11"
|
||||
dark-light = "3.0.0"
|
||||
bytes = "1.12.1"
|
||||
tokio-util = { version = "0.7.20", features = ["time"] }
|
||||
@@ -138,16 +141,10 @@ objc2-app-kit = { version = "0.3.2", features = [
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
deelevate = { workspace = true }
|
||||
quick-xml = "0.42.0"
|
||||
runas = "=1.2.0"
|
||||
winreg = "0.56.0"
|
||||
windows-service = "0.8.1"
|
||||
windows = { version = "0.62.2", features = [
|
||||
"Win32_System_Com",
|
||||
"Win32_System_Ole",
|
||||
"Win32_System_TaskScheduler",
|
||||
"Win32_System_Variant",
|
||||
] }
|
||||
windows = { version = "0.62.2", features = ["Win32_Globalization"] }
|
||||
windows-sys.workspace = true
|
||||
|
||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
||||
@@ -157,7 +154,7 @@ tauri-plugin-updater = "2.14.1"
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
warp = { version = "0.4.4", features = ["test"] }
|
||||
warp = { version = "0.4.3", features = ["test"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -17,8 +17,6 @@
|
||||
"autostart:allow-disable",
|
||||
"autostart:allow-is-enabled",
|
||||
"core:window:allow-set-theme",
|
||||
"core:window:allow-set-background-color",
|
||||
"core:webview:allow-set-webview-background-color",
|
||||
"notification:default",
|
||||
"http:default",
|
||||
"http:allow-fetch",
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
// bundles (PR #8131), so this generator must stay an example, never a bin.
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut args = std::env::args_os().skip(1);
|
||||
let output = args.next().map_or_else(
|
||||
|| std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../src/services/bindings.ts"),
|
||||
std::path::PathBuf::from,
|
||||
);
|
||||
let output = args
|
||||
.next()
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../src/services/bindings.ts"));
|
||||
if args.next().is_some() {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "expected at most one output path").into());
|
||||
}
|
||||
|
||||
@@ -70,7 +70,6 @@ ${StrLoc}
|
||||
|
||||
Var PassiveMode
|
||||
Var UpdateMode
|
||||
Var KeepAutoLaunch
|
||||
Var NoShortcutMode
|
||||
Var WixMode
|
||||
Var OldMainBinaryName
|
||||
@@ -334,9 +333,6 @@ Function PageLeaveReinstall
|
||||
${EndIf}
|
||||
|
||||
reinst_uninstall:
|
||||
${If} $R0 = 1
|
||||
StrCpy $KeepAutoLaunch 1
|
||||
${EndIf}
|
||||
!insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}"
|
||||
|
||||
HideWindow
|
||||
@@ -349,7 +345,6 @@ Function PageLeaveReinstall
|
||||
ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" ""
|
||||
ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"
|
||||
${IfThen} $UpdateMode = 1 ${|} StrCpy $R1 "$R1 /UPDATE" ${|} ; append /UPDATE
|
||||
${IfThen} $KeepAutoLaunch = 1 ${|} StrCpy $R1 "$R1 /KEEPAUTOLAUNCH" ${|}
|
||||
${IfThen} $PassiveMode = 1 ${|} StrCpy $R1 "$R1 /P" ${|} ; append /P
|
||||
StrCpy $R1 "$R1 _?=$4" ; append uninstall directory
|
||||
ExecWait '$R1' $0
|
||||
@@ -1103,11 +1098,6 @@ Function un.onInit
|
||||
${IfNot} ${Errors}
|
||||
StrCpy $UpdateMode 1
|
||||
${EndIf}
|
||||
|
||||
${GetOptions} $CMDLINE "/KEEPAUTOLAUNCH" $KeepAutoLaunch
|
||||
${IfNot} ${Errors}
|
||||
StrCpy $KeepAutoLaunch 1
|
||||
${EndIf}
|
||||
FunctionEnd
|
||||
|
||||
Section Uninstall
|
||||
@@ -1301,24 +1291,6 @@ Section Uninstall
|
||||
DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${PRODUCTNAME}"
|
||||
${EndIf}
|
||||
|
||||
${If} $UpdateMode <> 1
|
||||
${AndIf} $KeepAutoLaunch <> 1
|
||||
; UAC can run the uninstaller under a different account from the desktop user.
|
||||
StrCpy $R0 0
|
||||
${Do}
|
||||
EnumRegKey $R1 HKU "" $R0
|
||||
${If} $R1 == ""
|
||||
${ExitDo}
|
||||
${EndIf}
|
||||
StrCpy $R3 "$R1\Software\Microsoft\Windows\CurrentVersion\Run"
|
||||
ReadRegStr $R2 HKU "$R3" "Clash Verge Auto Launch"
|
||||
${If} $R2 == "$\"$INSTDIR\${MAINBINARYNAME}.exe$\""
|
||||
DeleteRegValue HKU "$R3" "Clash Verge Auto Launch"
|
||||
${EndIf}
|
||||
IntOp $R0 $R0 + 1
|
||||
${Loop}
|
||||
${EndIf}
|
||||
|
||||
; Delete app data if the checkbox is selected
|
||||
; and if not updating
|
||||
${If} $DeleteAppDataCheckboxState = 1
|
||||
|
||||
@@ -8,8 +8,8 @@ use crate::{
|
||||
feat,
|
||||
utils::dirs,
|
||||
};
|
||||
use smartstring::alias::String;
|
||||
use tauri::{AppHandle, Manager as _, ipc::Channel};
|
||||
use tristr::alias::String;
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::CmdResult;
|
||||
use crate::{cmd::StringifyErr as _, feat};
|
||||
use feat::LocalBackupFile;
|
||||
use tristr::alias::String;
|
||||
use smartstring::alias::String;
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
|
||||
@@ -12,8 +12,8 @@ use crate::{
|
||||
},
|
||||
};
|
||||
use clash_verge_logging::{Type, logging, logging_error};
|
||||
use smartstring::alias::String;
|
||||
use tokio::fs;
|
||||
use tristr::alias::String;
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use anyhow::Result;
|
||||
use tristr::alias::String;
|
||||
use smartstring::alias::String;
|
||||
|
||||
pub type CmdResult<T = ()> = Result<T, CommandFailure>;
|
||||
|
||||
|
||||
@@ -18,11 +18,9 @@ use crate::{
|
||||
};
|
||||
use clash_verge_draft::{Draft, SharedDraft};
|
||||
use clash_verge_logging::{Type, logging, logging_error};
|
||||
use std::{
|
||||
mem::DropGuard,
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
use tristr::alias::String;
|
||||
use scopeguard::defer;
|
||||
use smartstring::alias::String;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
static CURRENT_SWITCHING_PROFILE: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
@@ -210,10 +208,10 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn restore_previous_profile(prev_profile: &str) -> CmdResult<()> {
|
||||
async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> {
|
||||
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
|
||||
let restore_profiles = IProfiles {
|
||||
current: Some(prev_profile.into()),
|
||||
current: Some(prev_profile.to_owned()),
|
||||
items: None,
|
||||
};
|
||||
Config::profiles()
|
||||
@@ -322,6 +320,7 @@ async fn perform_config_update(
|
||||
#[derive(Default, serde::Deserialize, specta::Type)]
|
||||
#[serde(default)]
|
||||
pub struct ProfileSelection {
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub current: Option<String>,
|
||||
}
|
||||
|
||||
@@ -329,9 +328,13 @@ pub struct ProfileSelection {
|
||||
#[serde(default)]
|
||||
pub struct ProfileCreate {
|
||||
#[serde(rename = "type")]
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub itype: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub name: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub desc: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub url: Option<String>,
|
||||
pub option: Option<PrfOption>,
|
||||
}
|
||||
@@ -353,10 +356,15 @@ impl From<ProfileCreate> for PrfItem {
|
||||
#[serde(default)]
|
||||
pub struct ProfilePatch {
|
||||
#[serde(rename = "type")]
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub itype: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub name: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub desc: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub file: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub url: Option<String>,
|
||||
pub selected: Option<Vec<crate::config::PrfSelected>>,
|
||||
pub extra: Option<crate::config::PrfExtra>,
|
||||
@@ -392,9 +400,9 @@ pub async fn patch_profiles_config(profiles: ProfileSelection) -> CmdResult<Vali
|
||||
logging!(info, Type::Cmd, "当前正在切换配置,放弃请求");
|
||||
return Ok(ValidationOutcome::Busy);
|
||||
}
|
||||
let _switching_profile = DropGuard::new((), |()| {
|
||||
defer! {
|
||||
CURRENT_SWITCHING_PROFILE.store(false, Ordering::Release);
|
||||
});
|
||||
}
|
||||
let _profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
|
||||
|
||||
let profiles = IProfiles {
|
||||
|
||||
@@ -83,7 +83,8 @@ fn runtime_group_scopes(config: Option<&Mapping>) -> BTreeMap<String, GroupScope
|
||||
.get("exclude-type")
|
||||
.and_then(|types| types.as_str())
|
||||
.filter(|types| !types.is_empty())
|
||||
.map_or_default(|types| types.split('|').map(str::to_owned).collect());
|
||||
.map(|types| types.split('|').map(str::to_owned).collect())
|
||||
.unwrap_or_default();
|
||||
Some((
|
||||
name,
|
||||
GroupScope {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::CmdResult;
|
||||
use crate::{cmd::StringifyErr as _, config::Config, core::CoreManager, utils::yaml_emitter};
|
||||
use anyhow::{Context as _, anyhow};
|
||||
use smartstring::alias::String;
|
||||
use std::collections::HashMap;
|
||||
use tristr::alias::String;
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
@@ -36,7 +36,10 @@ pub async fn get_runtime_logs() -> CmdResult<RuntimeLogs> {
|
||||
|
||||
#[derive(serde::Serialize, specta::Type)]
|
||||
#[serde(transparent)]
|
||||
pub struct RuntimeLogs(HashMap<String, Vec<(String, String)>>);
|
||||
pub struct RuntimeLogs(
|
||||
#[specta(type = HashMap<std::string::String, Vec<(std::string::String, std::string::String)>>)]
|
||||
HashMap<String, Vec<(String, String)>>,
|
||||
);
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
|
||||
@@ -11,8 +11,8 @@ use crate::{
|
||||
utils::dirs,
|
||||
};
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use smartstring::alias::String;
|
||||
use tokio::fs;
|
||||
use tristr::alias::String;
|
||||
|
||||
/// 保存profiles的配置
|
||||
#[tauri::command]
|
||||
|
||||
@@ -34,8 +34,8 @@ async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str)
|
||||
SERVICE_MANAGER.handle_service_status(status).await
|
||||
};
|
||||
#[cfg(windows)]
|
||||
return finish_service_installation(result, error_code, async |reason| {
|
||||
manager.continue_with_sidecar(Some(reason)).await
|
||||
return finish_service_installation(result, error_code, |reason| async move {
|
||||
manager.continue_with_sidecar(Some(&reason)).await
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -46,13 +46,14 @@ async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str)
|
||||
}
|
||||
|
||||
#[cfg(any(windows, test))]
|
||||
async fn finish_service_installation<Fallback>(
|
||||
async fn finish_service_installation<Fallback, FallbackFuture>(
|
||||
installation: anyhow::Result<()>,
|
||||
error_code: &str,
|
||||
fallback: Fallback,
|
||||
) -> CmdResult<ServiceInstallOutcome>
|
||||
where
|
||||
Fallback: AsyncFnOnce(&str) -> anyhow::Result<()>,
|
||||
Fallback: FnOnce(String) -> FallbackFuture,
|
||||
FallbackFuture: std::future::Future<Output = anyhow::Result<()>>,
|
||||
{
|
||||
let Err(error) = installation else {
|
||||
return Ok(ServiceInstallOutcome::Installed);
|
||||
@@ -74,7 +75,7 @@ where
|
||||
return Err(proxy_aware_coded_error(&error, error_code));
|
||||
}
|
||||
let reason = reasons.join("\n");
|
||||
fallback(reason.as_str())
|
||||
fallback(reason.clone())
|
||||
.await
|
||||
.map_err(|error| proxy_aware_coded_error(&error, "SERVICE_SIDECAR_FAILED"))?;
|
||||
Ok(ServiceInstallOutcome::Sidecar { reason })
|
||||
@@ -190,7 +191,7 @@ mod tests {
|
||||
None => anyhow::anyhow!("{reason}"),
|
||||
}
|
||||
.context("install service failed");
|
||||
let result = finish_service_installation(Err(error), "SERVICE_INSTALL_FAILED", async |_| {
|
||||
let result = finish_service_installation(Err(error), "SERVICE_INSTALL_FAILED", |_| async {
|
||||
fallback_called.set(true);
|
||||
anyhow::ensure!(fallback_ready, "another core is running");
|
||||
Ok(())
|
||||
|
||||
@@ -4,7 +4,7 @@ use crate::{
|
||||
config::{Config, IVerge},
|
||||
core, feat,
|
||||
};
|
||||
use tristr::alias::String;
|
||||
use smartstring::alias::String;
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
|
||||
@@ -99,7 +99,7 @@ impl IClashTemp {
|
||||
"tauri://localhost",
|
||||
"http://tauri.localhost",
|
||||
// Only enable this in dev mode
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(feature = "verge-dev")]
|
||||
"http://localhost:3000",
|
||||
"https://yacd.metacubex.one",
|
||||
"https://metacubex.github.io",
|
||||
|
||||
@@ -20,10 +20,10 @@ use backon::{ExponentialBuilder, Retryable as _};
|
||||
use clash_verge_draft::Draft;
|
||||
use clash_verge_logging::{Type, logging, logging_error};
|
||||
use serde_yaml_ng::{Mapping, Value};
|
||||
use smartstring::alias::String;
|
||||
use std::{collections::HashSet, path::PathBuf};
|
||||
use tokio::sync::{Mutex, MutexGuard, OnceCell};
|
||||
use tokio::time::sleep;
|
||||
use tristr::alias::String;
|
||||
|
||||
pub(crate) struct Config {
|
||||
clash_config: Draft<IClashTemp>,
|
||||
@@ -34,9 +34,6 @@ pub(crate) struct Config {
|
||||
|
||||
static CONFIG_WRITE_LOCK: Mutex<()> = Mutex::const_new(());
|
||||
|
||||
static RUNTIME_YAML_CACHE: parking_lot::Mutex<Option<(u64, std::sync::Arc<std::string::String>)>> =
|
||||
parking_lot::Mutex::new(None);
|
||||
|
||||
impl Config {
|
||||
async fn global() -> &'static Self {
|
||||
static CONFIG: OnceCell<Config> = OnceCell::const_new();
|
||||
@@ -194,7 +191,7 @@ impl Config {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let error_msg = config_result.err().map_or_default(|err| err.to_string());
|
||||
let error_msg = config_result.err().map(|err| err.to_string()).unwrap_or_default();
|
||||
logging!(warn, Type::Config, "生成配置文件失败,使用默认配置: {error_msg}");
|
||||
CoreManager::global()
|
||||
.use_default_config(NoticeStatus::ConfigValidateError, "")
|
||||
@@ -208,7 +205,7 @@ impl Config {
|
||||
Self::write_runtime_file(&yaml).await
|
||||
}
|
||||
|
||||
pub(crate) async fn runtime_config_yaml() -> Result<std::sync::Arc<std::string::String>> {
|
||||
pub(crate) async fn runtime_config_yaml() -> Result<std::string::String> {
|
||||
let runtime = Self::runtime().await;
|
||||
AsyncHandler::spawn_blocking(move || {
|
||||
let runtime_lastest = runtime.latest_arc();
|
||||
@@ -218,17 +215,8 @@ impl Config {
|
||||
.as_ref()
|
||||
.or_else(|| runtime_data.config.as_ref())
|
||||
.ok_or_else(|| anyhow!("failed to generate runtime config, might need to restart application"))?;
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
std::hash::Hash::hash(config, &mut hasher);
|
||||
let key = std::hash::Hasher::finish(&hasher);
|
||||
if let Some((cached_key, cached)) = RUNTIME_YAML_CACHE.lock().as_ref()
|
||||
&& *cached_key == key
|
||||
{
|
||||
return Ok(std::sync::Arc::clone(cached));
|
||||
}
|
||||
let yaml_str = std::sync::Arc::new(serde_yaml_ng::to_string(config)?);
|
||||
*RUNTIME_YAML_CACHE.lock() = Some((key, std::sync::Arc::clone(&yaml_str)));
|
||||
Ok(yaml_str)
|
||||
let yaml_str = serde_yaml_ng::to_string(config)?;
|
||||
Ok(format!("# Generated by Clash Verge\n\n{}", yaml_str))
|
||||
})
|
||||
.await
|
||||
.map_err(|join| anyhow!("runtime serialization task failed: {join}"))?
|
||||
@@ -236,7 +224,7 @@ impl Config {
|
||||
|
||||
pub(crate) async fn write_runtime_file(yaml: &str) -> Result<PathBuf> {
|
||||
let path = dirs::app_home_dir()?.join(files::RUNTIME_CONFIG);
|
||||
help::save_yaml_str(&path, yaml, Some("# Generated by Clash Verge")).await?;
|
||||
help::save_yaml_str(&path, yaml).await?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
use crate::core::notify::NoticeStatus;
|
||||
use crate::utils::help;
|
||||
use anyhow::Result;
|
||||
use clash_verge_draft::DraftTransaction;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_yaml_ng::{Mapping, Value};
|
||||
use sha2::{Digest as _, Sha256};
|
||||
use smartstring::alias::String;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use tristr::alias::String;
|
||||
|
||||
use super::{Config, IVerge};
|
||||
use crate::core::handle::Handle;
|
||||
@@ -50,7 +49,9 @@ pub(crate) fn dns_override_source(profile_uid: &str, config: &Mapping) -> Result
|
||||
digest.update(profile_uid.as_bytes());
|
||||
digest.update([0]);
|
||||
digest.update(serde_json::to_vec(&canonical)?);
|
||||
Ok(Some(help::hex_encode(&digest.finalize()).into()))
|
||||
Ok(Some(
|
||||
digest.finalize().iter().map(|byte| format!("{byte:02x}")).collect(),
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -109,6 +110,7 @@ impl DnsOverrideState {
|
||||
pub struct ProfileDnsSettings {
|
||||
pub enabled: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub confirmation: Option<String>,
|
||||
}
|
||||
|
||||
|
||||
@@ -11,9 +11,9 @@ use crate::{
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_yaml_ng::Mapping;
|
||||
use smartstring::alias::String;
|
||||
use std::time::Duration;
|
||||
use tokio::fs;
|
||||
use tristr::alias::String;
|
||||
// TODO, use other re-export
|
||||
use reqwest_dav::re_exports::url::form_urlencoded;
|
||||
use tauri::Url;
|
||||
@@ -26,24 +26,30 @@ pub(super) fn normalize_profile_home_url(raw: &str) -> Option<String> {
|
||||
}
|
||||
|
||||
url.host_str()?;
|
||||
Some(url.as_str().into())
|
||||
Some(url.to_string().into())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)]
|
||||
#[serde(default)]
|
||||
pub struct PrfItem {
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub uid: Option<String>,
|
||||
|
||||
/// enum value: remote | local | script | merge
|
||||
#[serde(rename = "type")]
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub itype: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub name: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub file: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub desc: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub url: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -58,16 +64,20 @@ pub struct PrfItem {
|
||||
pub option: Option<PrfOption>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub home: Option<String>,
|
||||
|
||||
#[serde(skip)]
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub file_data: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)]
|
||||
#[serde(default)]
|
||||
pub struct PrfSelected {
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub name: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub now: Option<String>,
|
||||
}
|
||||
|
||||
@@ -83,6 +93,7 @@ pub struct PrfExtra {
|
||||
#[serde(default)]
|
||||
pub struct PrfOption {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub user_agent: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -105,10 +116,15 @@ pub struct PrfOption {
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub allow_auto_update: Option<bool>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub merge: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub script: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub rules: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub proxies: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub groups: Option<String>,
|
||||
}
|
||||
|
||||
@@ -355,10 +371,9 @@ impl PrfItem {
|
||||
|
||||
let uid = help::get_uid("R").into();
|
||||
let file = format!("{uid}.yaml").into();
|
||||
let name = name.map_or_else(
|
||||
|| filename.map_or_else(|| "Remote File".into(), |s| s.into()),
|
||||
|s| s.to_owned(),
|
||||
);
|
||||
let name = name
|
||||
.map(|s| s.to_owned())
|
||||
.unwrap_or_else(|| filename.map(|s| s.into()).unwrap_or_else(|| "Remote File".into()));
|
||||
let data = resp.text();
|
||||
|
||||
let data = data.trim_start_matches('\u{feff}');
|
||||
|
||||
@@ -17,6 +17,7 @@ use clash_verge_logging::{Type, logging};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_yaml_ng::Mapping;
|
||||
use smartstring::alias::String;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
@@ -29,7 +30,6 @@ use std::{
|
||||
};
|
||||
use tauri_plugin_mihomo::models::{Proxies, ProxyType};
|
||||
use tokio::{fs, task::JoinHandle};
|
||||
use tristr::alias::String;
|
||||
|
||||
pub(crate) static PROFILE_WRITE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
|
||||
|
||||
@@ -51,6 +51,7 @@ const SELECTED_NODES_FIRST_PASS_BUDGET: Duration = Duration::from_secs(3);
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)]
|
||||
#[serde(default)]
|
||||
pub struct IProfiles {
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub current: Option<String>,
|
||||
|
||||
pub items: Option<Vec<PrfItem>>,
|
||||
@@ -604,7 +605,7 @@ async fn fetch_proxies_with_timeout() -> Result<Proxies> {
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
async fn select_node_with_timeout(group_name: &str, node: &str) -> Result<()> {
|
||||
async fn select_node_with_timeout(group_name: &String, node: &String) -> Result<()> {
|
||||
tokio::time::timeout(MIHOMO_OPERATION_TIMEOUT, async {
|
||||
handle::Handle::mihomo().select_node_for_group(group_name, node).await
|
||||
})
|
||||
@@ -753,27 +754,30 @@ fn current_item_mut(profiles: &mut IProfiles) -> Option<&mut PrfItem> {
|
||||
|
||||
/// Records a backend-made selection so the next core start restores it.
|
||||
pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result<()> {
|
||||
let group_name = String::from(group_name);
|
||||
let node = String::from(node);
|
||||
persist_selected_update(true, move |mut profiles| async move {
|
||||
let Some(item) = current_item_mut(&mut profiles) else {
|
||||
return Ok((profiles, false));
|
||||
};
|
||||
|
||||
let selected = item.selected.get_or_insert_with(Vec::new);
|
||||
let mut selected = item.selected.clone().unwrap_or_default();
|
||||
match selected
|
||||
.iter_mut()
|
||||
.find(|entry| entry.name.as_deref() == Some(group_name))
|
||||
.find(|entry| entry.name.as_ref() == Some(&group_name))
|
||||
{
|
||||
Some(entry) => {
|
||||
if entry.now.as_deref() == Some(node) {
|
||||
if entry.now.as_ref() == Some(&node) {
|
||||
return Ok((profiles, false));
|
||||
}
|
||||
entry.now = Some(node.into());
|
||||
entry.now = Some(node);
|
||||
}
|
||||
None => selected.push(PrfSelected {
|
||||
name: Some(group_name.into()),
|
||||
now: Some(node.into()),
|
||||
name: Some(group_name),
|
||||
now: Some(node),
|
||||
}),
|
||||
}
|
||||
item.selected = Some(selected);
|
||||
profiles.save_file().await?;
|
||||
Ok((profiles, true))
|
||||
})
|
||||
@@ -792,17 +796,12 @@ pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
|
||||
return Ok((profiles, false));
|
||||
};
|
||||
|
||||
let Some(mut selected) = item.selected.take() else {
|
||||
return Ok((profiles, false));
|
||||
};
|
||||
let mut selected = item.selected.clone().unwrap_or_default();
|
||||
if !remove_selected_node(&mut selected, group_name) {
|
||||
item.selected = Some(selected);
|
||||
return Ok((profiles, false));
|
||||
}
|
||||
|
||||
if !selected.is_empty() {
|
||||
item.selected = Some(selected);
|
||||
}
|
||||
item.selected = (!selected.is_empty()).then_some(selected);
|
||||
profiles.save_file().await?;
|
||||
Ok((profiles, true))
|
||||
})
|
||||
@@ -810,7 +809,7 @@ pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
|
||||
}
|
||||
|
||||
async fn persist_reconciled_selected(
|
||||
profile_uid: &str,
|
||||
profile_uid: &String,
|
||||
original_selected: &[PrfSelected],
|
||||
selected: Vec<PrfSelected>,
|
||||
generation: u64,
|
||||
@@ -819,17 +818,19 @@ async fn persist_reconciled_selected(
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let profile_uid = profile_uid.clone();
|
||||
let original_selected = original_selected.to_vec();
|
||||
persist_selected_update(false, move |mut profiles| async move {
|
||||
if !is_activation_current(generation) || profiles.current.as_deref() != Some(profile_uid) {
|
||||
if !is_activation_current(generation) || profiles.current.as_ref() != Some(&profile_uid) {
|
||||
return Ok((profiles, false));
|
||||
}
|
||||
|
||||
let profile = profiles
|
||||
.items
|
||||
.as_mut()
|
||||
.and_then(|items| items.iter_mut().find(|item| item.uid.as_deref() == Some(profile_uid)))
|
||||
.and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(&profile_uid)))
|
||||
.with_context(|| format!("failed to find the profile item \"uid:{profile_uid}\""))?;
|
||||
if profile.selected.as_deref().unwrap_or(&[]) != original_selected {
|
||||
if profile.selected.as_deref().unwrap_or(&[]) != original_selected.as_slice() {
|
||||
return Ok((profiles, false));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use serde_yaml_ng::{Mapping, Value};
|
||||
use smartstring::alias::String;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use tristr::alias::String;
|
||||
|
||||
use crate::enhance::field::use_keys;
|
||||
|
||||
|
||||
@@ -8,26 +8,33 @@ use anyhow::Result;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use log::LevelFilter;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tristr::alias::String;
|
||||
use smartstring::alias::String;
|
||||
|
||||
/// ### `verge.yaml` schema
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)]
|
||||
#[serde(default)]
|
||||
pub struct IVerge {
|
||||
/// silent | error | warn | info | debug | trace
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub app_log_level: Option<String>,
|
||||
|
||||
/// Maximum app log size in KiB.
|
||||
pub app_log_max_size: Option<u64>,
|
||||
|
||||
pub app_log_max_count: Option<usize>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub language: Option<String>,
|
||||
|
||||
/// `light` or `dark` or `system`
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub theme_mode: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub tray_event: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub env_type: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub start_page: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub startup_script: Option<String>,
|
||||
|
||||
pub traffic_graph: Option<bool>,
|
||||
@@ -45,18 +52,23 @@ pub struct IVerge {
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub tray_icon: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub menu_icon: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(type = Option<Vec<std::string::String>>)]
|
||||
pub menu_order: Option<Vec<String>>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub proxy_group_tools_position: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub notice_position: Option<String>,
|
||||
|
||||
pub collapse_navbar: Option<bool>,
|
||||
@@ -81,25 +93,32 @@ pub struct IVerge {
|
||||
pub enable_dns_settings: Option<bool>,
|
||||
|
||||
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
|
||||
#[specta(type = std::collections::BTreeMap<std::string::String, super::dns::ProfileDnsSettings>)]
|
||||
pub profile_dns_settings: std::collections::BTreeMap<String, super::dns::ProfileDnsSettings>,
|
||||
|
||||
pub use_default_bypass: Option<bool>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub system_proxy_bypass: Option<String>,
|
||||
|
||||
pub proxy_guard_duration: Option<u64>,
|
||||
|
||||
pub proxy_auto_config: Option<bool>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub pac_file_content: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub proxy_host: Option<String>,
|
||||
|
||||
pub theme_setting: Option<IVergeTheme>,
|
||||
#[specta(type = Option<Vec<std::string::String>>)]
|
||||
pub web_ui_list: Option<Vec<String>>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub clash_core: Option<String>,
|
||||
|
||||
/// format: {func},{key}
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(type = Option<Vec<std::string::String>>)]
|
||||
pub hotkeys: Option<Vec<String>>,
|
||||
|
||||
pub enable_global_hotkey: Option<bool>,
|
||||
@@ -109,9 +128,8 @@ pub struct IVerge {
|
||||
|
||||
pub auto_close_connection: Option<bool>,
|
||||
|
||||
pub auto_switch_selector_group: Option<bool>,
|
||||
|
||||
pub auto_check_update: Option<bool>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub default_latency_test: Option<String>,
|
||||
|
||||
pub default_latency_timeout: Option<i16>,
|
||||
@@ -191,6 +209,7 @@ pub struct IVerge {
|
||||
pub enable_tray_speed: Option<bool>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub tray_proxy_groups_display_mode: Option<String>,
|
||||
pub tray_inline_outbound_modes: Option<bool>,
|
||||
|
||||
@@ -210,24 +229,38 @@ pub struct IVerge {
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)]
|
||||
#[serde(default)]
|
||||
pub struct IVergeTestItem {
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub uid: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub name: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub icon: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)]
|
||||
#[serde(default)]
|
||||
pub struct IVergeTheme {
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub primary_color: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub secondary_color: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub primary_text: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub secondary_text: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub info_color: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub error_color: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub warning_color: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub success_color: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub font_family: Option<String>,
|
||||
#[specta(type = Option<std::string::String>)]
|
||||
pub css_injection: Option<String>,
|
||||
}
|
||||
|
||||
@@ -370,7 +403,6 @@ impl IVerge {
|
||||
use_default_bypass: Some(true),
|
||||
proxy_guard_duration: Some(30),
|
||||
auto_close_connection: Some(true),
|
||||
auto_switch_selector_group: Some(true),
|
||||
auto_check_update: Some(true),
|
||||
enable_builtin_enhanced: Some(true),
|
||||
auto_log_clean: Some(2), // 1: 1天, 2: 7天, 3: 30天, 4: 90天
|
||||
@@ -459,7 +491,6 @@ impl IVerge {
|
||||
patch_opt_field!(self, patch, enable_global_hotkey);
|
||||
|
||||
patch_opt_field!(self, patch, auto_close_connection);
|
||||
patch_opt_field!(self, patch, auto_switch_selector_group);
|
||||
patch_opt_field!(self, patch, auto_check_update);
|
||||
patch_opt_field!(self, patch, default_latency_test);
|
||||
patch_opt_field!(self, patch, default_latency_timeout);
|
||||
|
||||
@@ -70,8 +70,6 @@ pub mod files {
|
||||
pub mod tun {
|
||||
pub const DEFAULT_STACK: &str = "mips";
|
||||
|
||||
pub const DEFAULT_MTU: u16 = 1500;
|
||||
|
||||
pub const DNS_HIJACK: &[&str] = &["any:53"];
|
||||
|
||||
/// Saved dialog fields; `enable` belongs to the verge switch.
|
||||
|
||||
@@ -279,7 +279,8 @@ async fn cleanup_auto_backups() -> Result<()> {
|
||||
.and_then(|meta| meta.modified())
|
||||
.ok()
|
||||
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
|
||||
.map_or(0, |dur| dur.as_secs());
|
||||
.map(|dur| dur.as_secs())
|
||||
.unwrap_or(0);
|
||||
|
||||
files.push((path, modified));
|
||||
}
|
||||
|
||||
@@ -1,31 +1,34 @@
|
||||
#[cfg(target_os = "windows")]
|
||||
use crate::utils::schtasks;
|
||||
use crate::{config::Config, core::handle::Handle};
|
||||
use anyhow::Result;
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
use clash_verge_logging::logging_error;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
use tauri_plugin_autostart::ManagerExt as _;
|
||||
#[cfg(target_os = "windows")]
|
||||
use tauri_plugin_clash_verge_sysinfo::is_current_app_handle_admin;
|
||||
|
||||
pub async fn update_launch() -> Result<()> {
|
||||
let enable_auto_launch = { Config::verge().await.latest_arc().enable_auto_launch };
|
||||
let is_enable = enable_auto_launch.unwrap_or(false);
|
||||
logging!(info, Type::System, "Setting auto-launch enabled state to: {is_enable}");
|
||||
|
||||
let app_handle = Handle::app_handle();
|
||||
cfg_select! {
|
||||
target_os = "windows" => {
|
||||
use crate::utils::schtasks;
|
||||
use tauri_plugin_clash_verge_sysinfo::is_current_app_handle_admin;
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let is_admin = is_current_app_handle_admin(Handle::app_handle());
|
||||
schtasks::set_auto_launch(is_enable, is_admin).await?;
|
||||
}
|
||||
|
||||
let is_admin = is_current_app_handle_admin(app_handle);
|
||||
schtasks::set_auto_launch(is_enable, is_admin).await?;
|
||||
}
|
||||
_ => {
|
||||
use clash_verge_logging::logging_error;
|
||||
use tauri_plugin_autostart::ManagerExt as _;
|
||||
|
||||
let autostart_manager = app_handle.autolaunch();
|
||||
if is_enable {
|
||||
logging_error!(Type::System, "{:?}", autostart_manager.enable());
|
||||
} else {
|
||||
logging_error!(Type::System, "{:?}", autostart_manager.disable());
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
let app_handle = Handle::app_handle();
|
||||
let autostart_manager = app_handle.autolaunch();
|
||||
if is_enable {
|
||||
logging_error!(Type::System, "{:?}", autostart_manager.enable());
|
||||
} else {
|
||||
logging_error!(Type::System, "{:?}", autostart_manager.disable());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ use arc_swap::{ArcSwap, ArcSwapOption};
|
||||
use backon::{ConstantBuilder, Retryable as _};
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use reqwest_dav::list_cmd::{ListEntity, ListFile, ListMultiStatus};
|
||||
use smartstring::alias::String;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
env::{consts::OS, temp_dir},
|
||||
@@ -14,7 +15,6 @@ use std::{
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{fs, time::timeout};
|
||||
use tristr::alias::String;
|
||||
use zip::write::SimpleFileOptions;
|
||||
|
||||
const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user