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 | |
|---|---|---|---|
|
|
1e632846b2 | ||
|
|
ad830fad30 | ||
|
|
4f22cbc451 | ||
|
|
80e5aed793 | ||
|
|
e8aafac962 | ||
|
|
6bb7d71156 | ||
|
|
09d05b3f36 | ||
|
|
a85640a571 | ||
|
|
08d09cc5f3 | ||
|
|
43be8ead4c | ||
|
|
48eab2c21e | ||
|
|
e4abdb8c0d | ||
|
|
34103b3eba | ||
|
|
3d01cc6df4 | ||
|
|
b0d0b9a944 | ||
|
|
3eb6883e12 | ||
|
|
0218267ed5 |
@@ -29,7 +29,6 @@
|
||||
"biomejs.biome"
|
||||
],
|
||||
"settings": {
|
||||
"rust-analyzer.cargo.features": ["verge-dev"],
|
||||
"rust-analyzer.check.command": "clippy",
|
||||
"editor.formatOnSave": true,
|
||||
"editor.defaultFormatter": "biomejs.biome",
|
||||
|
||||
@@ -1,10 +1,275 @@
|
||||
---
|
||||
name: Agentic Workflows
|
||||
description: Create, update, debug, and upgrade GitHub Agentic Workflows (gh-aw).
|
||||
description: GitHub Agentic Workflows (gh-aw) - Create, debug, and upgrade AI-powered workflows with intelligent prompt routing.
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
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.
|
||||
# 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`
|
||||
|
||||
@@ -124,8 +124,8 @@
|
||||
},
|
||||
"ghcr.io/github/gh-aw-node": {
|
||||
"image": "ghcr.io/github/gh-aw-node",
|
||||
"digest": "sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f"
|
||||
"digest": "sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc"
|
||||
},
|
||||
"ghcr.io/github/github-mcp-server:v2.1.0": {
|
||||
"image": "ghcr.io/github/github-mcp-server:v2.1.0",
|
||||
|
||||
@@ -1,40 +1,193 @@
|
||||
---
|
||||
name: agentic-workflows
|
||||
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.
|
||||
description: Route gh-aw design, creation, diagnosis, patching, active debugging, upgrades, and local SDLC issue requests to the right strategies.
|
||||
---
|
||||
|
||||
# Agentic Workflows Router
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
| 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` |
|
||||
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.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
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.
|
||||
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>
|
||||
|
||||
+8
-8
@@ -1,5 +1,5 @@
|
||||
# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"5d34fe2fef444fe0fb34cfe938ea9ec0fa83c8758fd19e2756159b4a1e0a1e34","body_hash":"ca82fafbe18061d7c8bd708dc18e91b9116faf0c921a7fa35be1538d47a2b005","compiler_version":"v1.3.1","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}}
|
||||
# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_DEFAULT_OTLP_ENDPOINT","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"dfe97a19c8249d41e2adfc95f92db2b8facea58f","version":"v1.3.1"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14@sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.14@sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.14@sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c"},{"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"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f","pinned_image":"ghcr.io/github/gh-aw-node@sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f"},{"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"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","add_labels","noop","remove_labels","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"6ad93a5e01ad6b6c6bd0":{"name":"Agentic Workflows"}}}
|
||||
# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"4ca5835c0c9cd01f3432b873f5a177ca6d3d1dbd6a35939e2058dcb37aa224b4","body_hash":"ca82fafbe18061d7c8bd708dc18e91b9116faf0c921a7fa35be1538d47a2b005","compiler_version":"v1.3.1","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}}
|
||||
# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_DEFAULT_OTLP_ENDPOINT","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"dfe97a19c8249d41e2adfc95f92db2b8facea58f","version":"v1.3.1"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14@sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.14@sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.14@sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c"},{"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"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc","pinned_image":"ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc"},{"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"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","add_labels","noop","remove_labels","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"03cbf8931deff21d5116":{"name":"Agentic Workflows"}}}
|
||||
# This file was automatically generated by gh-aw (v1.3.1). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md
|
||||
#
|
||||
# ___ _ _
|
||||
@@ -48,7 +48,7 @@
|
||||
#
|
||||
# Container images used:
|
||||
# - ghcr.io/github/gh-aw-mcpg:v0.5.10@sha256:629ddcd68a48ab02e7db8af527d2756c6db563b00c1d31d8aa8fcbac96f01c59
|
||||
# - ghcr.io/github/gh-aw-node@sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f
|
||||
# - ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc
|
||||
# - ghcr.io/github/github-mcp-server:v2.1.0@sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a
|
||||
# - ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa
|
||||
# - ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0
|
||||
@@ -653,10 +653,10 @@ jobs:
|
||||
GH_AW_SKILL_DIR: ".github/skills"
|
||||
run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh"
|
||||
- name: Make Copilot quota exhaustion non-blocking
|
||||
run: "node <<'NODE'\nconst fs = require('fs');\nconst harnessPath = `${process.env.RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs`;\nconst harness = fs.readFileSync(harnessPath, 'utf8');\nconst quotaBranch = [\n ' if (isQuotaExceeded) {',\n ' log(`attempt ${attempt + 1}: Copilot quota exceeded — not retrying`);',\n ' return { action: \"stop\" };',\n ' }',\n].join('\\n');\nconst nonBlockingQuotaBranch = [\n ' let quotaErrorMsg = null;',\n ' if (isQuotaExceeded) {',\n ' log(`attempt ${attempt + 1}: Copilot quota exceeded — not retrying`);',\n ' quotaErrorMsg = { action: \"stop\" };',\n ' }',\n ' if (/\\\\b429\\\\b|Too Many Requests/i.test(result.output)) {',\n ' log(`attempt ${attempt + 1}: Copilot quota unavailable — exiting 0`);',\n ' quotaErrorMsg = { action: \"stop\", exitCode: 0 };',\n ' }',\n ' if (quotaErrorMsg) {',\n ' return quotaErrorMsg;',\n ' }',\n].join('\\n');\n\nif (harness.split(quotaBranch).length !== 2) {\n throw new Error('Unexpected Copilot quota branch; re-audit the gh-aw upgrade');\n}\nfs.writeFileSync(harnessPath, harness.replace(quotaBranch, nonBlockingQuotaBranch));\nNODE"
|
||||
run: "node <<'NODE'\nconst fs = require('fs');\nconst harnessPath = `${process.env.RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs`;\nconst harness = fs.readFileSync(harnessPath, 'utf8');\nconst quotaBranch = [\n ' if (isQuotaExceeded && (result.retryAfterMs == null || /\\\\bquota exceeded\\\\b/i.test(result.output))) {',\n ' log(`attempt ${attempt + 1}: Copilot quota exceeded — not retrying`);',\n ' return { action: \"stop\" };',\n ' }',\n].join('\\n');\nconst nonBlockingQuotaBranch = [\n ' let quotaErrorMsg = null;',\n ' if (isQuotaExceeded && (result.retryAfterMs == null || /\\\\bquota exceeded\\\\b/i.test(result.output))) {',\n ' log(`attempt ${attempt + 1}: Copilot quota exceeded — not retrying`);',\n ' quotaErrorMsg = { action: \"stop\" };',\n ' }',\n ' if (/\\\\b429\\\\b|Too Many Requests/i.test(result.output)) {',\n ' log(`attempt ${attempt + 1}: Copilot quota unavailable — exiting 0`);',\n ' quotaErrorMsg = { action: \"stop\", exitCode: 0 };',\n ' }',\n ' if (quotaErrorMsg) {',\n ' return quotaErrorMsg;',\n ' }',\n].join('\\n');\n\nif (harness.split(quotaBranch).length !== 2) {\n throw new Error('Unexpected Copilot quota branch; re-audit the gh-aw upgrade');\n}\nfs.writeFileSync(harnessPath, harness.replace(quotaBranch, nonBlockingQuotaBranch));\nNODE"
|
||||
|
||||
- name: Download container images
|
||||
run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-mcpg:v0.5.10@sha256:629ddcd68a48ab02e7db8af527d2756c6db563b00c1d31d8aa8fcbac96f01c59 ghcr.io/github/gh-aw-node@sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f ghcr.io/github/github-mcp-server:v2.1.0@sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0 ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14@sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12 ghcr.io/github/gh-aw-firewall/router:0.29.14@sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0 ghcr.io/github/gh-aw-firewall/squid:0.29.14@sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c
|
||||
run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-mcpg:v0.5.10@sha256:629ddcd68a48ab02e7db8af527d2756c6db563b00c1d31d8aa8fcbac96f01c59 ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc ghcr.io/github/github-mcp-server:v2.1.0@sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0 ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14@sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12 ghcr.io/github/gh-aw-firewall/router:0.29.14@sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0 ghcr.io/github/gh-aw-firewall/squid:0.29.14@sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c
|
||||
- name: Prepare Safe Outputs Directories
|
||||
run: |
|
||||
mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs"
|
||||
@@ -901,12 +901,12 @@ jobs:
|
||||
|
||||
mkdir -p "$HOME/.copilot"
|
||||
GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node)
|
||||
cat << GH_AW_MCP_CONFIG_e60cdf7f84db3d47_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs"
|
||||
cat << GH_AW_MCP_CONFIG_d448207cb151e2cb_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs"
|
||||
{
|
||||
"mcpServers": {
|
||||
"safeoutputs": {
|
||||
"type": "stdio",
|
||||
"container": "ghcr.io/github/gh-aw-node@sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f",
|
||||
"container": "ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc",
|
||||
"mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"],
|
||||
"args": ["-w", "\${GITHUB_WORKSPACE}"],
|
||||
"entrypoint": "sh",
|
||||
@@ -965,7 +965,7 @@ jobs:
|
||||
}
|
||||
}
|
||||
}
|
||||
GH_AW_MCP_CONFIG_e60cdf7f84db3d47_EOF
|
||||
GH_AW_MCP_CONFIG_d448207cb151e2cb_EOF
|
||||
- name: Mount MCP servers as CLIs
|
||||
id: mount-mcp-clis
|
||||
continue-on-error: true
|
||||
|
||||
@@ -47,14 +47,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) {',
|
||||
' if (isQuotaExceeded && (result.retryAfterMs == null || /\\bquota exceeded\\b/i.test(result.output))) {',
|
||||
' log(`attempt ${attempt + 1}: Copilot quota exceeded — not retrying`);',
|
||||
' return { action: "stop" };',
|
||||
' }',
|
||||
].join('\n');
|
||||
const nonBlockingQuotaBranch = [
|
||||
' let quotaErrorMsg = null;',
|
||||
' if (isQuotaExceeded) {',
|
||||
' if (isQuotaExceeded && (result.retryAfterMs == null || /\\bquota exceeded\\b/i.test(result.output))) {',
|
||||
' log(`attempt ${attempt + 1}: Copilot quota exceeded — not retrying`);',
|
||||
' quotaErrorMsg = { action: "stop" };',
|
||||
' }',
|
||||
|
||||
Generated
+6
-6
@@ -1,5 +1,5 @@
|
||||
# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"d6b72464a3766dd7d74aefe4c7dd982ae7ae2db951f8040f978feca9166adb39","body_hash":"deddd98c5fa425a91487fb5f50dc59ac61ae395bdcd4dff6543f1e8e563a7d73","compiler_version":"v1.3.1","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}}
|
||||
# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_DEFAULT_OTLP_ENDPOINT","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"dfe97a19c8249d41e2adfc95f92db2b8facea58f","version":"v1.3.1"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14@sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.14@sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.14@sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c"},{"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"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f","pinned_image":"ghcr.io/github/gh-aw-node@sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f"},{"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"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","noop","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"6ad93a5e01ad6b6c6bd0":{"name":"Agentic Workflows"}}}
|
||||
# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_DEFAULT_OTLP_ENDPOINT","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"dfe97a19c8249d41e2adfc95f92db2b8facea58f","version":"v1.3.1"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14@sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.14@sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.14@sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c"},{"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"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc","pinned_image":"ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc"},{"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"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","noop","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"03cbf8931deff21d5116":{"name":"Agentic Workflows"}}}
|
||||
# This file was automatically generated by gh-aw (v1.3.1). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md
|
||||
#
|
||||
# ___ _ _
|
||||
@@ -47,7 +47,7 @@
|
||||
#
|
||||
# Container images used:
|
||||
# - ghcr.io/github/gh-aw-mcpg:v0.5.10@sha256:629ddcd68a48ab02e7db8af527d2756c6db563b00c1d31d8aa8fcbac96f01c59
|
||||
# - ghcr.io/github/gh-aw-node@sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f
|
||||
# - ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc
|
||||
# - ghcr.io/github/github-mcp-server:v2.1.0@sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a
|
||||
# - ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa
|
||||
# - ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0
|
||||
@@ -695,7 +695,7 @@ jobs:
|
||||
GH_AW_SKILL_DIR: ".github/skills"
|
||||
run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh"
|
||||
- name: Download container images
|
||||
run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-mcpg:v0.5.10@sha256:629ddcd68a48ab02e7db8af527d2756c6db563b00c1d31d8aa8fcbac96f01c59 ghcr.io/github/gh-aw-node@sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f ghcr.io/github/github-mcp-server:v2.1.0@sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0 ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14@sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12 ghcr.io/github/gh-aw-firewall/router:0.29.14@sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0 ghcr.io/github/gh-aw-firewall/squid:0.29.14@sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c
|
||||
run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-mcpg:v0.5.10@sha256:629ddcd68a48ab02e7db8af527d2756c6db563b00c1d31d8aa8fcbac96f01c59 ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc ghcr.io/github/github-mcp-server:v2.1.0@sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0 ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14@sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12 ghcr.io/github/gh-aw-firewall/router:0.29.14@sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0 ghcr.io/github/gh-aw-firewall/squid:0.29.14@sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c
|
||||
- name: Prepare Safe Outputs Directories
|
||||
run: |
|
||||
mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs"
|
||||
@@ -904,12 +904,12 @@ jobs:
|
||||
|
||||
mkdir -p "$HOME/.copilot"
|
||||
GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node)
|
||||
cat << GH_AW_MCP_CONFIG_c4ee643bb7646e79_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs"
|
||||
cat << GH_AW_MCP_CONFIG_e9f853f8279889ed_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs"
|
||||
{
|
||||
"mcpServers": {
|
||||
"safeoutputs": {
|
||||
"type": "stdio",
|
||||
"container": "ghcr.io/github/gh-aw-node@sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f",
|
||||
"container": "ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc",
|
||||
"mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"],
|
||||
"args": ["-w", "\${GITHUB_WORKSPACE}"],
|
||||
"entrypoint": "sh",
|
||||
@@ -967,7 +967,7 @@ jobs:
|
||||
}
|
||||
}
|
||||
}
|
||||
GH_AW_MCP_CONFIG_c4ee643bb7646e79_EOF
|
||||
GH_AW_MCP_CONFIG_e9f853f8279889ed_EOF
|
||||
- name: Mount MCP servers as CLIs
|
||||
id: mount-mcp-clis
|
||||
continue-on-error: true
|
||||
|
||||
+6
-6
@@ -1,5 +1,5 @@
|
||||
# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"e44852fbf56eab99e67b3f6a306f75195603ece6ed130e55652a2467efed1415","body_hash":"7835f25016082d56592b67f4d2bf5b839eb02a6fa8f03d65699ed6bae979c5ad","compiler_version":"v1.3.1","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}}
|
||||
# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_DEFAULT_OTLP_ENDPOINT","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"dfe97a19c8249d41e2adfc95f92db2b8facea58f","version":"v1.3.1"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14@sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.14@sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.14@sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c"},{"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"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f","pinned_image":"ghcr.io/github/gh-aw-node@sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f"},{"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"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","noop","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"6ad93a5e01ad6b6c6bd0":{"name":"Agentic Workflows"}}}
|
||||
# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_DEFAULT_OTLP_ENDPOINT","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"dfe97a19c8249d41e2adfc95f92db2b8facea58f","version":"v1.3.1"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14@sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.14@sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.14@sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c"},{"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"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc","pinned_image":"ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc"},{"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"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","noop","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"03cbf8931deff21d5116":{"name":"Agentic Workflows"}}}
|
||||
# This file was automatically generated by gh-aw (v1.3.1). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md
|
||||
#
|
||||
# ___ _ _
|
||||
@@ -47,7 +47,7 @@
|
||||
#
|
||||
# Container images used:
|
||||
# - ghcr.io/github/gh-aw-mcpg:v0.5.10@sha256:629ddcd68a48ab02e7db8af527d2756c6db563b00c1d31d8aa8fcbac96f01c59
|
||||
# - ghcr.io/github/gh-aw-node@sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f
|
||||
# - ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc
|
||||
# - ghcr.io/github/github-mcp-server:v2.1.0@sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a
|
||||
# - ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa
|
||||
# - ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0
|
||||
@@ -676,7 +676,7 @@ jobs:
|
||||
GH_AW_SKILL_DIR: ".github/skills"
|
||||
run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh"
|
||||
- name: Download container images
|
||||
run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-mcpg:v0.5.10@sha256:629ddcd68a48ab02e7db8af527d2756c6db563b00c1d31d8aa8fcbac96f01c59 ghcr.io/github/gh-aw-node@sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f ghcr.io/github/github-mcp-server:v2.1.0@sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0 ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14@sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12 ghcr.io/github/gh-aw-firewall/router:0.29.14@sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0 ghcr.io/github/gh-aw-firewall/squid:0.29.14@sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c
|
||||
run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-mcpg:v0.5.10@sha256:629ddcd68a48ab02e7db8af527d2756c6db563b00c1d31d8aa8fcbac96f01c59 ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc ghcr.io/github/github-mcp-server:v2.1.0@sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0 ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14@sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12 ghcr.io/github/gh-aw-firewall/router:0.29.14@sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0 ghcr.io/github/gh-aw-firewall/squid:0.29.14@sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c
|
||||
- name: Prepare Safe Outputs Directories
|
||||
run: |
|
||||
mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs"
|
||||
@@ -887,12 +887,12 @@ jobs:
|
||||
|
||||
mkdir -p "$HOME/.copilot"
|
||||
GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node)
|
||||
cat << GH_AW_MCP_CONFIG_e60cdf7f84db3d47_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs"
|
||||
cat << GH_AW_MCP_CONFIG_d448207cb151e2cb_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs"
|
||||
{
|
||||
"mcpServers": {
|
||||
"safeoutputs": {
|
||||
"type": "stdio",
|
||||
"container": "ghcr.io/github/gh-aw-node@sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f",
|
||||
"container": "ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc",
|
||||
"mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"],
|
||||
"args": ["-w", "\${GITHUB_WORKSPACE}"],
|
||||
"entrypoint": "sh",
|
||||
@@ -951,7 +951,7 @@ jobs:
|
||||
}
|
||||
}
|
||||
}
|
||||
GH_AW_MCP_CONFIG_e60cdf7f84db3d47_EOF
|
||||
GH_AW_MCP_CONFIG_d448207cb151e2cb_EOF
|
||||
- name: Mount MCP servers as CLIs
|
||||
id: mount-mcp-clis
|
||||
continue-on-error: true
|
||||
|
||||
+4
-7
@@ -81,23 +81,20 @@ pnpm run prebuild
|
||||
pnpm run prebuild --force # Re-download and overwrite Mihomo core and service binaries
|
||||
```
|
||||
|
||||
### Prepare the Development Service Source
|
||||
### Service Development
|
||||
|
||||
`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`.
|
||||
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.
|
||||
|
||||
### Run the Development Server
|
||||
|
||||
Run these commands from the root of `clash-verge-rev`:
|
||||
|
||||
```bash
|
||||
pnpm dev # Build the development service and start the desktop app
|
||||
pnpm dev:diff # Alias of pnpm dev
|
||||
pnpm dev # Start the desktop app in debug mode
|
||||
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 or build the development service.
|
||||
For frontend-only development, use `pnpm web:dev`. It does not start the Rust backend.
|
||||
|
||||
### Build the Project
|
||||
|
||||
|
||||
Generated
+7
-7
@@ -1224,8 +1224,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clash_verge_service_ipc"
|
||||
version = "2.8.1"
|
||||
source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?tag=v2.8.1#9d4ea7d27fb3c43804bd18f3bb3b686528763239"
|
||||
version = "2.8.2"
|
||||
source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?branch=main#3e06ff153e9cb19ae20e0a61f861b371d3f7b2aa"
|
||||
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.59.0",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3373,7 +3373,7 @@ dependencies = [
|
||||
"js-sys",
|
||||
"log",
|
||||
"wasm-bindgen",
|
||||
"windows-core 0.62.2",
|
||||
"windows-core 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4909,7 +4909,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.45.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7875,7 +7875,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.4.3",
|
||||
"getrandom 0.3.4",
|
||||
"once_cell",
|
||||
"rustix 1.1.4",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -9204,7 +9204,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
+7
-2
@@ -28,6 +28,8 @@
|
||||
<details>
|
||||
<summary><strong> 🐞 修复问题 </strong></summary>
|
||||
|
||||
- 修复「外部控制器」复制成功的提示一闪而过
|
||||
- 修复订阅的规则、代理组、节点编辑器快速连续操作时条目可能重复或错位
|
||||
- 修复检测更新后又发布新版时,应用内更新失败
|
||||
- 修复订阅响应过大导致内存占用过高,限制单次下载为 4 MiB
|
||||
- 修复全局模式默认停在 `DIRECT` 或 `REJECT` 导致流量未经代理,现自动切换到第一个策略组
|
||||
@@ -37,9 +39,10 @@
|
||||
- 修复断开链式代理时清空已选节点,导致再次连接需要重新选择
|
||||
- 修复「连接」页表格排序时表头换行、标题位置跳动
|
||||
- 修复「TUN 设置」未手动保存时,界面显示的默认 MTU 1500 未生效
|
||||
- 修复连接详情较窄时操作按钮偏离右侧
|
||||
- 修复「链式代理」节点列表按名称排序,未保持订阅中的节点顺序
|
||||
- 修复规则模式下 Muse AI 解锁检测显示错误的出口地区
|
||||
- 修复使用系统代理时 IP 信息显示直连地址
|
||||
- 修复使用系统代理或本地代理认证时首页 IP 信息显示直连地址或报错
|
||||
|
||||
**🖥️ Windows**
|
||||
|
||||
@@ -61,18 +64,20 @@
|
||||
<summary><strong> ✨ 新增功能 </strong></summary>
|
||||
|
||||
- 新增连接页面按网络协议(TCP/UDP)筛选连接
|
||||
- 新增从连接详情设置域名、进程或源/目标 IP 规则,支持识别主域、匹配子域、自定义 IP 网段及修改已有规则
|
||||
- 新增规则模式下在规则流量未经过的代理组选节点时,自动将首个包含该组的 `select` 代理组切换到该组,可在「杂项设置」关闭
|
||||
- 新增「杂项设置」中的「更新通道」,可选择直连 GitHub 或经代理从 GitHub 下载更新
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong> 🚀 优化改进 </strong></summary>
|
||||
|
||||
- 优化设置页打开时的开销:布局设置弹窗首次打开时才加载图标
|
||||
- 优化连接、规则和日志筛选:切换页面后保留过滤条件
|
||||
- 优化全局模式代理列表:仅显示 `GLOBAL` 节点,选中其中的策略组时才显示该组
|
||||
- 优化设置页开关和选项所在行的鼠标悬停高亮,便于对应说明与控件
|
||||
- 优化首页「当前节点」卡片:按规则指向的代理组逐级显示和切换实际生效的节点,选中后下拉菜单自动收起
|
||||
- 优化延迟测试:节点超时后自动重测一次再显示结果,减少网络波动造成的误报
|
||||
|
||||
**🍎 macOS**
|
||||
|
||||
|
||||
@@ -108,11 +108,10 @@ pnpm run prebuild
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
`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.
|
||||
`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.
|
||||
|
||||
## Contributions
|
||||
|
||||
|
||||
+4
-7
@@ -4,11 +4,7 @@
|
||||
"license": "GPL-3.0-only",
|
||||
"scripts": {
|
||||
"prepare": "husky || true",
|
||||
"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": "cross-env RUST_BACKTRACE=full tauri dev",
|
||||
"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",
|
||||
@@ -75,13 +71,14 @@
|
||||
"react-dom": "19.3.1",
|
||||
"react-error-boundary": "6.1.6",
|
||||
"react-hook-form": "^7.88.0",
|
||||
"react-i18next": "18.0.1",
|
||||
"react-i18next": "18.0.3",
|
||||
"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"
|
||||
},
|
||||
@@ -116,7 +113,7 @@
|
||||
"https-proxy-agent": "^9.1.0",
|
||||
"husky": "^9.1.7",
|
||||
"jiti": "^2.7.0",
|
||||
"knip": "6.45.1",
|
||||
"knip": "6.47.0",
|
||||
"lint-staged": "^17.5.1",
|
||||
"sass": "^1.104.1",
|
||||
"tar": "^7.5.22",
|
||||
|
||||
Generated
+26
-10
@@ -284,8 +284,8 @@ importers:
|
||||
specifier: ^7.88.0
|
||||
version: 7.88.0(react@19.3.1)
|
||||
react-i18next:
|
||||
specifier: 18.0.1
|
||||
version: 18.0.1(@types/react@19.3.0)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3)
|
||||
specifier: 18.0.3
|
||||
version: 18.0.3(@types/react@19.3.0)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3)
|
||||
react-markdown:
|
||||
specifier: 10.1.0
|
||||
version: 10.1.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
||||
@@ -304,6 +304,9 @@ importers:
|
||||
tauri-plugin-mihomo-api:
|
||||
specifier: github:clash-verge-rev/tauri-plugin-mihomo#main
|
||||
version: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f
|
||||
tldts:
|
||||
specifier: 7.4.19
|
||||
version: 7.4.19
|
||||
types-pac:
|
||||
specifier: ^1.0.3
|
||||
version: 1.0.3
|
||||
@@ -402,8 +405,8 @@ importers:
|
||||
specifier: ^2.7.0
|
||||
version: 2.7.0
|
||||
knip:
|
||||
specifier: 6.45.1
|
||||
version: 6.45.1
|
||||
specifier: 6.47.0
|
||||
version: 6.47.0
|
||||
lint-staged:
|
||||
specifier: ^17.5.1
|
||||
version: 17.5.1
|
||||
@@ -3345,8 +3348,8 @@ packages:
|
||||
keyv@5.6.0:
|
||||
resolution: {integrity: sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==}
|
||||
|
||||
knip@6.45.1:
|
||||
resolution: {integrity: sha512-zp3zXKy2cZWiIttdlWU5fisKxVQaLSU6471ej0KGz1GdHdaHxpzTAO/LIyFNc3gU3v1W7LJaqvYumoO3l/u+6A==}
|
||||
knip@6.47.0:
|
||||
resolution: {integrity: sha512-nYmQnk0YqDXIJrYViJz88c8xw3tBDkpuAmofo58EkVPnKr6DnRKYtf6oIqcGVHZvXDE+gtmFuYx277/QsWng+A==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
hasBin: true
|
||||
|
||||
@@ -3792,8 +3795,8 @@ packages:
|
||||
peerDependencies:
|
||||
react: ^16.8.0 || ^17 || ^18 || ^19
|
||||
|
||||
react-i18next@18.0.1:
|
||||
resolution: {integrity: sha512-kPWXI0E/lrPj3+/umcKNzYZVnWmEedLiamMzDIHfbs+5ANf6yzvlZsjKou8f7kaGkfMMDLIZBejV+4aSN1CyBw==}
|
||||
react-i18next@18.0.3:
|
||||
resolution: {integrity: sha512-S84rtVuaKuiRtoCOspbGEaDlFjka+KvK/A5YCOr4LQ41XF3iJOrJ5rqQTD/jJHFVUf6X1i4ZMN5PGGgpz8NN6g==}
|
||||
engines: {node: '>=22'}
|
||||
peerDependencies:
|
||||
'@types/react': '*'
|
||||
@@ -4044,6 +4047,13 @@ packages:
|
||||
resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
|
||||
engines: {node: '>=12.0.0'}
|
||||
|
||||
tldts-core@7.5.2:
|
||||
resolution: {integrity: sha512-8W1topazDwhMKbm2I83IPa57Ow5VUxFgLbXv42+vSILnv8FY5OHvdEY/tS6WoWeMbxkHZQhra5cmeFHriKptSQ==}
|
||||
|
||||
tldts@7.4.19:
|
||||
resolution: {integrity: sha512-48dH6aSpQnpbzDUc4vIQZ1VjB8tkK+e8c1yx05/SZK+rkssgjEOlxDd/yU8/a4vGYQ9vRgJr9dwMq9TJ0b3X2Q==}
|
||||
hasBin: true
|
||||
|
||||
trim-lines@3.0.1:
|
||||
resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}
|
||||
|
||||
@@ -7297,7 +7307,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@keyv/serialize': 1.1.1
|
||||
|
||||
knip@6.45.1:
|
||||
knip@6.47.0:
|
||||
dependencies:
|
||||
formatly: 0.11.4
|
||||
get-tsconfig: 4.14.3
|
||||
@@ -7883,7 +7893,7 @@ snapshots:
|
||||
dependencies:
|
||||
react: 19.3.1
|
||||
|
||||
react-i18next@18.0.1(@types/react@19.3.0)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3):
|
||||
react-i18next@18.0.3(@types/react@19.3.0)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3):
|
||||
dependencies:
|
||||
html-parse-stringify: 4.0.1
|
||||
i18next: 27.0.1(typescript@6.0.3)
|
||||
@@ -8147,6 +8157,12 @@ snapshots:
|
||||
fdir: 6.5.0(picomatch@4.0.7)
|
||||
picomatch: 4.0.7
|
||||
|
||||
tldts-core@7.5.2: {}
|
||||
|
||||
tldts@7.4.19:
|
||||
dependencies:
|
||||
tldts-core: 7.5.2
|
||||
|
||||
trim-lines@3.0.1: {}
|
||||
|
||||
trough@2.2.0: {}
|
||||
|
||||
@@ -1,280 +0,0 @@
|
||||
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
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,181 +0,0 @@
|
||||
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)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function checkDevelopmentServiceVersion() {
|
||||
const [guiOutput, daemonOutput] = await Promise.all([
|
||||
run(
|
||||
'cargo',
|
||||
[
|
||||
'metadata',
|
||||
'--locked',
|
||||
'--format-version=1',
|
||||
'--manifest-path',
|
||||
join(repositoryRoot, 'Cargo.toml'),
|
||||
],
|
||||
{ stdio: ['inherit', 'pipe', 'inherit'] },
|
||||
),
|
||||
run(
|
||||
'cargo',
|
||||
[
|
||||
'metadata',
|
||||
'--locked',
|
||||
'--no-deps',
|
||||
'--format-version=1',
|
||||
'--manifest-path',
|
||||
serviceManifest,
|
||||
],
|
||||
{ stdio: ['inherit', 'pipe', 'inherit'] },
|
||||
),
|
||||
])
|
||||
const gui = JSON.parse(guiOutput)
|
||||
const daemon = JSON.parse(daemonOutput).packages.find(
|
||||
(pkg) => resolve(pkg.manifest_path) === serviceManifest,
|
||||
)
|
||||
const app = gui.packages.find(
|
||||
(pkg) =>
|
||||
resolve(pkg.manifest_path) ===
|
||||
join(repositoryRoot, 'src-tauri', 'Cargo.toml'),
|
||||
)
|
||||
const dependency = gui.resolve?.nodes
|
||||
.find((node) => node.id === app?.id)
|
||||
?.deps.find((dep) => dep.name === 'clash_verge_service_ipc')
|
||||
const sdk = gui.packages.find((pkg) => pkg.id === dependency?.pkg)
|
||||
if (!daemon || !sdk)
|
||||
throw new Error('Cargo did not resolve the development Service and GUI SDK')
|
||||
if (daemon.version !== sdk.version) {
|
||||
throw new Error(
|
||||
`Development Service ${daemon.version} does not match the resolved GUI SDK ${sdk.version} (${sdk.manifest_path}). ` +
|
||||
'Align the GUI dependency explicitly before starting development. Building the sibling daemon does not update the SDK.',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function prepareDevelopmentService() {
|
||||
await access(serviceManifest)
|
||||
await checkDevelopmentServiceVersion()
|
||||
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
@@ -1,570 +0,0 @@
|
||||
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
-1
@@ -220,7 +220,7 @@ pub fn run() -> std::process::ExitCode {
|
||||
.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")
|
||||
if !matches!(scenario.as_str(), "traffic" | "logs" | "connections" | "proxy")
|
||||
|| !matches!(layer.as_str(), "page" | "component" | "dom")
|
||||
{
|
||||
return Err("invalid perf scene".into());
|
||||
|
||||
@@ -2,6 +2,8 @@ import { layer, scenario, startReplay } from './replay'
|
||||
|
||||
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'
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
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>,
|
||||
)
|
||||
@@ -0,0 +1,17 @@
|
||||
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'
|
||||
@@ -0,0 +1,30 @@
|
||||
// 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 }
|
||||
@@ -6,5 +6,11 @@ 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,
|
||||
},
|
||||
},
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -17,8 +17,6 @@ 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"]
|
||||
@@ -93,7 +91,7 @@ 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" }
|
||||
async-trait = "0.1.92"
|
||||
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", tag = "v2.8.1", version = "2.8.1", features = [
|
||||
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", features = [
|
||||
"client",
|
||||
] }
|
||||
arc-swap = "1.9.5"
|
||||
|
||||
@@ -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, |reason| async move {
|
||||
manager.continue_with_sidecar(Some(&reason)).await
|
||||
return finish_service_installation(result, error_code, async |reason| {
|
||||
manager.continue_with_sidecar(Some(reason)).await
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -46,14 +46,13 @@ async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str)
|
||||
}
|
||||
|
||||
#[cfg(any(windows, test))]
|
||||
async fn finish_service_installation<Fallback, FallbackFuture>(
|
||||
async fn finish_service_installation<Fallback>(
|
||||
installation: anyhow::Result<()>,
|
||||
error_code: &str,
|
||||
fallback: Fallback,
|
||||
) -> CmdResult<ServiceInstallOutcome>
|
||||
where
|
||||
Fallback: FnOnce(String) -> FallbackFuture,
|
||||
FallbackFuture: std::future::Future<Output = anyhow::Result<()>>,
|
||||
Fallback: AsyncFnOnce(&str) -> anyhow::Result<()>,
|
||||
{
|
||||
let Err(error) = installation else {
|
||||
return Ok(ServiceInstallOutcome::Installed);
|
||||
@@ -75,7 +74,7 @@ where
|
||||
return Err(proxy_aware_coded_error(&error, error_code));
|
||||
}
|
||||
let reason = reasons.join("\n");
|
||||
fallback(reason.clone())
|
||||
fallback(reason.as_str())
|
||||
.await
|
||||
.map_err(|error| proxy_aware_coded_error(&error, "SERVICE_SIDECAR_FAILED"))?;
|
||||
Ok(ServiceInstallOutcome::Sidecar { reason })
|
||||
@@ -191,7 +190,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(())
|
||||
|
||||
@@ -99,7 +99,7 @@ impl IClashTemp {
|
||||
"tauri://localhost",
|
||||
"http://tauri.localhost",
|
||||
// Only enable this in dev mode
|
||||
#[cfg(feature = "verge-dev")]
|
||||
#[cfg(debug_assertions)]
|
||||
"http://localhost:3000",
|
||||
"https://yacd.metacubex.one",
|
||||
"https://metacubex.github.io",
|
||||
|
||||
@@ -753,8 +753,6 @@ 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));
|
||||
@@ -763,17 +761,17 @@ pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result
|
||||
let selected = item.selected.get_or_insert_with(Vec::new);
|
||||
match selected
|
||||
.iter_mut()
|
||||
.find(|entry| entry.name.as_ref() == Some(&group_name))
|
||||
.find(|entry| entry.name.as_deref() == Some(group_name))
|
||||
{
|
||||
Some(entry) => {
|
||||
if entry.now.as_ref() == Some(&node) {
|
||||
if entry.now.as_deref() == Some(node) {
|
||||
return Ok((profiles, false));
|
||||
}
|
||||
entry.now = Some(node.clone());
|
||||
entry.now = Some(node.into());
|
||||
}
|
||||
None => selected.push(PrfSelected {
|
||||
name: Some(group_name),
|
||||
now: Some(node),
|
||||
name: Some(group_name.into()),
|
||||
now: Some(node.into()),
|
||||
}),
|
||||
}
|
||||
profiles.save_file().await?;
|
||||
@@ -821,19 +819,17 @@ async fn persist_reconciled_selected(
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let profile_uid = String::from(profile_uid);
|
||||
let original_selected = original_selected.to_vec();
|
||||
persist_selected_update(false, move |mut profiles| async move {
|
||||
if !is_activation_current(generation) || profiles.current.as_ref() != Some(&profile_uid) {
|
||||
if !is_activation_current(generation) || profiles.current.as_deref() != Some(profile_uid) {
|
||||
return Ok((profiles, false));
|
||||
}
|
||||
|
||||
let profile = profiles
|
||||
.items
|
||||
.as_mut()
|
||||
.and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(&profile_uid)))
|
||||
.and_then(|items| items.iter_mut().find(|item| item.uid.as_deref() == Some(profile_uid)))
|
||||
.with_context(|| format!("failed to find the profile item \"uid:{profile_uid}\""))?;
|
||||
if profile.selected.as_deref().unwrap_or(&[]) != original_selected.as_slice() {
|
||||
if profile.selected.as_deref().unwrap_or(&[]) != original_selected {
|
||||
return Ok((profiles, false));
|
||||
}
|
||||
|
||||
|
||||
@@ -112,10 +112,6 @@ pub struct IVerge {
|
||||
pub auto_switch_selector_group: Option<bool>,
|
||||
|
||||
pub auto_check_update: Option<bool>,
|
||||
|
||||
/// `auto`, `github` or `github_proxy`
|
||||
pub update_channel: Option<String>,
|
||||
|
||||
pub default_latency_test: Option<String>,
|
||||
|
||||
pub default_latency_timeout: Option<i16>,
|
||||
@@ -465,7 +461,6 @@ impl IVerge {
|
||||
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, update_channel);
|
||||
patch_opt_field!(self, patch, default_latency_test);
|
||||
patch_opt_field!(self, patch, default_latency_timeout);
|
||||
patch_opt_field!(self, patch, enable_auto_delay_detection);
|
||||
|
||||
@@ -19,6 +19,7 @@ use anyhow::{Result, ensure};
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use clash_verge_service_ipc::{MacosProxyConfig, OwnerSessionProof, ProxyApplyOutcome};
|
||||
use std::{
|
||||
borrow::Borrow,
|
||||
future::Future,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
time::Duration,
|
||||
@@ -271,7 +272,7 @@ impl ServiceProxyOperations {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn run_guard_request<Mode, ActiveProof, Request, RequestFuture>(
|
||||
async fn run_guard_request<Mode, ActiveProof, Proof, Request, RequestFuture>(
|
||||
&self,
|
||||
captured_generation: u64,
|
||||
captured_proof: &OwnerSessionProof,
|
||||
@@ -282,14 +283,15 @@ impl ServiceProxyOperations {
|
||||
) -> Result<bool>
|
||||
where
|
||||
Mode: FnOnce() -> bool,
|
||||
ActiveProof: FnOnce() -> Result<OwnerSessionProof>,
|
||||
ActiveProof: FnOnce() -> Result<Proof>,
|
||||
Proof: Borrow<OwnerSessionProof>,
|
||||
Request: FnOnce() -> RequestFuture,
|
||||
RequestFuture: Future<Output = Result<ProxyApplyOutcome>>,
|
||||
{
|
||||
self.run_service_operation(|| async move {
|
||||
if !guard_generation_is_current(&self.guard_generation, captured_generation)
|
||||
|| !is_service_mode()
|
||||
|| !active_proof().is_ok_and(|active| active == *captured_proof)
|
||||
|| !active_proof().is_ok_and(|active| active.borrow() == captured_proof)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
@@ -48,15 +48,12 @@ impl RunStateEnv for RealEnv {
|
||||
crate::config::Config::verge().await.latest_arc().get_valid_clash_core(),
|
||||
std::env::consts::EXE_SUFFIX
|
||||
);
|
||||
let status = clash_verge_service_ipc::inspect_installation(&[clash_verge_service_ipc::CoreRequirement {
|
||||
name: name.clone(),
|
||||
sha256: None,
|
||||
}])
|
||||
.await?;
|
||||
let requirements = [clash_verge_service_ipc::CoreRequirement { name, sha256: None }];
|
||||
let status = clash_verge_service_ipc::inspect_installation(&requirements).await?;
|
||||
status
|
||||
.cores
|
||||
.into_iter()
|
||||
.find(|core| core.name == name)
|
||||
.find(|core| core.name == requirements[0].name)
|
||||
.map(|core| core.availability)
|
||||
} else {
|
||||
None
|
||||
|
||||
+71
-490
@@ -27,13 +27,18 @@ use clash_verge_service_ipc::{
|
||||
StageRuntimeOutcome, StartClashRequest, WriterConfig,
|
||||
};
|
||||
use parking_lot::Mutex;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::sync::LazyLock;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
env::current_exe,
|
||||
future::Future,
|
||||
path::{Path, PathBuf},
|
||||
process::Command as StdCommand,
|
||||
sync::atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
},
|
||||
time::{Duration, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
@@ -98,23 +103,29 @@ fn app_data_owner_command(credentials: &OwnerCredentials) -> Option<String> {
|
||||
/// They are discarded with that session rather than cached across service upgrades.
|
||||
#[derive(Clone)]
|
||||
struct ActiveServiceSession {
|
||||
proof: OwnerSessionProof,
|
||||
proof: Arc<OwnerSessionProof>,
|
||||
supports_runtime_staging: bool,
|
||||
supports_runtime_file_read: bool,
|
||||
supports_runtime_geo_read: bool,
|
||||
}
|
||||
|
||||
fn generate_service_session_token() -> Result<String> {
|
||||
use std::fmt::Write as _;
|
||||
|
||||
let mut bytes = [0_u8; 32];
|
||||
getrandom::fill(&mut bytes).context("failed to generate service owner session")?;
|
||||
Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())
|
||||
let mut token = String::with_capacity(bytes.len() * 2);
|
||||
for byte in bytes {
|
||||
let _ = write!(token, "{byte:02x}");
|
||||
}
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
pub(crate) fn active_service_session() -> Result<OwnerSessionProof> {
|
||||
pub(crate) fn active_service_session() -> Result<Arc<OwnerSessionProof>> {
|
||||
ACTIVE_SERVICE_SESSION
|
||||
.lock()
|
||||
.as_ref()
|
||||
.map(|session| session.proof.clone())
|
||||
.map(|session| Arc::clone(&session.proof))
|
||||
.context("service owner session is not active")
|
||||
}
|
||||
|
||||
@@ -248,7 +259,7 @@ fn path_entry_exists_without_follow(path: &Path) -> std::io::Result<bool> {
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn macos_service_install_markers() -> Vec<String> {
|
||||
static MACOS_SERVICE_INSTALL_MARKERS: LazyLock<Vec<String>> = LazyLock::new(|| {
|
||||
vec![
|
||||
format!(
|
||||
"/Library/LaunchDaemons/{}.plist",
|
||||
@@ -258,16 +269,14 @@ fn macos_service_install_markers() -> Vec<String> {
|
||||
"/Library/PrivilegedHelperTools/{}.bundle",
|
||||
clash_verge_service_ipc::MACOS_SERVICE_ID
|
||||
),
|
||||
#[cfg(not(feature = "verge-dev"))]
|
||||
"/Library/LaunchDaemons/io.github.clashverge.helper.plist".to_owned(),
|
||||
#[cfg(not(feature = "verge-dev"))]
|
||||
"/Library/PrivilegedHelperTools/io.github.clashverge.helper".to_owned(),
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn macos_service_install_marker_exists() -> std::io::Result<bool> {
|
||||
for marker in macos_service_install_markers() {
|
||||
for marker in MACOS_SERVICE_INSTALL_MARKERS.iter() {
|
||||
if path_entry_exists_without_follow(Path::new(&marker))? {
|
||||
return Ok(true);
|
||||
}
|
||||
@@ -319,13 +328,11 @@ pub(crate) fn service_stop_reason() -> Result<Option<&'static str>> {
|
||||
if status.current_state != ServiceState::Stopped {
|
||||
return Ok(None);
|
||||
}
|
||||
// The development channel registers an on-demand start.
|
||||
if !cfg!(feature = "verge-dev")
|
||||
&& service
|
||||
.query_config()
|
||||
.context("failed to query Windows service configuration")?
|
||||
.start_type
|
||||
!= ServiceStartType::AutoStart
|
||||
if service
|
||||
.query_config()
|
||||
.context("failed to query Windows service configuration")?
|
||||
.start_type
|
||||
!= ServiceStartType::AutoStart
|
||||
{
|
||||
return Ok(Some(SERVICE_NOT_AUTO_STARTED));
|
||||
}
|
||||
@@ -362,201 +369,6 @@ pub(crate) fn trusted_service_evidence() -> Result<bool> {
|
||||
/// Stateless legacy façade over [`RUN_STATE`] retained for existing call sites.
|
||||
pub struct ServiceManager;
|
||||
|
||||
#[cfg(any(all(target_os = "macos", feature = "verge-dev"), test))]
|
||||
static SERVICE_CORE_STAGING_GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
#[cfg(any(all(target_os = "macos", feature = "verge-dev"), test))]
|
||||
fn create_service_core_staging_file(directory: &Path, core_name: &std::ffi::OsStr) -> Result<(PathBuf, std::fs::File)> {
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry_sync};
|
||||
retry_sync(
|
||||
RetryPolicy::fixed(
|
||||
std::num::NonZeroUsize::MIN.saturating_add(31),
|
||||
std::time::Duration::ZERO,
|
||||
),
|
||||
|_| {
|
||||
let generation = SERVICE_CORE_STAGING_GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||
let temporary_name = format!(
|
||||
".{}.{}.{generation}.tmp",
|
||||
core_name.to_string_lossy(),
|
||||
std::process::id()
|
||||
);
|
||||
let temporary_path = directory.join(temporary_name);
|
||||
match std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temporary_path)
|
||||
{
|
||||
Ok(file) => Ok((temporary_path, file)),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
|
||||
Err(RetryError::Retry(anyhow::anyhow!(
|
||||
"failed to create a unique temporary development Service core in {}",
|
||||
directory.display()
|
||||
)))
|
||||
}
|
||||
Err(error) => Err(RetryError::Stop(anyhow::Error::from(error).context({
|
||||
format!(
|
||||
"failed to create temporary development Service core {}",
|
||||
temporary_path.display()
|
||||
)
|
||||
}))),
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(any(all(target_os = "macos", feature = "verge-dev"), test))]
|
||||
fn service_core_path_for(source: &Path, home: Option<&Path>, stage_for_macos_dev: bool) -> Result<PathBuf> {
|
||||
service_core_path_for_with_publisher(
|
||||
source,
|
||||
home,
|
||||
stage_for_macos_dev,
|
||||
"service-core",
|
||||
|temporary_path, final_path| {
|
||||
std::fs::rename(temporary_path, final_path).with_context(|| {
|
||||
format!(
|
||||
"failed to publish development Service core {} over {}",
|
||||
temporary_path.display(),
|
||||
final_path.display()
|
||||
)
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(any(all(target_os = "macos", feature = "verge-dev"), all(test, unix)))]
|
||||
fn service_tool_path_for(source: &Path, home: Option<&Path>, stage_for_macos_dev: bool) -> Result<PathBuf> {
|
||||
service_core_path_for_with_publisher(
|
||||
source,
|
||||
home,
|
||||
stage_for_macos_dev,
|
||||
"service-tools",
|
||||
|temporary_path, final_path| {
|
||||
std::fs::rename(temporary_path, final_path).with_context(|| {
|
||||
format!(
|
||||
"failed to publish development Service tool {} over {}",
|
||||
temporary_path.display(),
|
||||
final_path.display()
|
||||
)
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(any(all(target_os = "macos", feature = "verge-dev"), test))]
|
||||
#[cfg_attr(not(unix), allow(unreachable_code, unused_assignments, unused_variables))]
|
||||
fn service_core_path_for_with_publisher<F>(
|
||||
source: &Path,
|
||||
home: Option<&Path>,
|
||||
stage_for_macos_dev: bool,
|
||||
staging_directory_name: &str,
|
||||
publisher: F,
|
||||
) -> Result<PathBuf>
|
||||
where
|
||||
F: FnOnce(&Path, &Path) -> Result<()>,
|
||||
{
|
||||
if !stage_for_macos_dev {
|
||||
return Ok(source.to_path_buf());
|
||||
}
|
||||
|
||||
let home = home
|
||||
.filter(|path| !path.as_os_str().is_empty())
|
||||
.context("HOME is unavailable for development Service core staging")?;
|
||||
let core_name = source
|
||||
.file_name()
|
||||
.filter(|name| !name.is_empty())
|
||||
.with_context(|| format!("development Service core source has no file name: {}", source.display()))?;
|
||||
let source_metadata = std::fs::symlink_metadata(source)
|
||||
.with_context(|| format!("failed to inspect development Service core source {}", source.display()))?;
|
||||
if !source_metadata.file_type().is_file() {
|
||||
bail!(
|
||||
"development Service core source is not an ordinary file: {}",
|
||||
source.display()
|
||||
);
|
||||
}
|
||||
let mut source_file = std::fs::File::open(source)
|
||||
.with_context(|| format!("failed to open development Service core source {}", source.display()))?;
|
||||
|
||||
let staging_directory = home
|
||||
.join("Applications/.clash-verge-rev-dev")
|
||||
.join(staging_directory_name);
|
||||
std::fs::create_dir_all(&staging_directory).with_context(|| {
|
||||
format!(
|
||||
"failed to create development Service core staging directory {}",
|
||||
staging_directory.display()
|
||||
)
|
||||
})?;
|
||||
let final_path = staging_directory.join(core_name);
|
||||
let (temporary_path, mut temporary_file) = create_service_core_staging_file(&staging_directory, core_name)?;
|
||||
|
||||
let publish_result = (|| -> Result<()> {
|
||||
std::io::copy(&mut source_file, &mut temporary_file).with_context(|| {
|
||||
format!(
|
||||
"failed to copy development Service core from {} to {}",
|
||||
source.display(),
|
||||
temporary_path.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
|
||||
let mut permissions = temporary_file
|
||||
.metadata()
|
||||
.with_context(|| format!("failed to inspect temporary Service core {}", temporary_path.display()))?
|
||||
.permissions();
|
||||
permissions.set_mode(0o755);
|
||||
temporary_file.set_permissions(permissions).with_context(|| {
|
||||
format!(
|
||||
"failed to set executable permissions on temporary Service core {}",
|
||||
temporary_path.display()
|
||||
)
|
||||
})?;
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
bail!("development Service core staging requires Unix executable permissions");
|
||||
|
||||
temporary_file
|
||||
.sync_all()
|
||||
.with_context(|| format!("failed to sync temporary Service core {}", temporary_path.display()))?;
|
||||
drop(temporary_file);
|
||||
publisher(&temporary_path, &final_path)?;
|
||||
Ok(())
|
||||
})();
|
||||
|
||||
if let Err(error) = publish_result {
|
||||
match std::fs::remove_file(&temporary_path) {
|
||||
Ok(()) => return Err(error),
|
||||
Err(cleanup_error) if cleanup_error.kind() == std::io::ErrorKind::NotFound => return Err(error),
|
||||
Err(cleanup_error) => {
|
||||
return Err(error).with_context(|| {
|
||||
format!(
|
||||
"failed to clean temporary development Service core {}: {cleanup_error}",
|
||||
temporary_path.display()
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(final_path)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg_attr(not(feature = "verge-dev"), allow(clippy::unnecessary_wraps))]
|
||||
fn macos_service_tool_path(source: &Path) -> Result<PathBuf> {
|
||||
#[cfg(feature = "verge-dev")]
|
||||
{
|
||||
let home = std::env::var_os("HOME")
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(PathBuf::from);
|
||||
service_tool_path_for(source, home.as_deref(), true)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "verge-dev"))]
|
||||
Ok(source.to_path_buf())
|
||||
}
|
||||
|
||||
fn service_core_path(clash_core: &str, bin_ext: &str) -> Result<PathBuf> {
|
||||
let sibling = current_exe()
|
||||
.map_err(|error| {
|
||||
@@ -566,18 +378,8 @@ fn service_core_path(clash_core: &str, bin_ext: &str) -> Result<PathBuf> {
|
||||
})?
|
||||
.with_file_name(format!("{clash_core}{bin_ext}"));
|
||||
|
||||
#[cfg(all(target_os = "macos", feature = "verge-dev"))]
|
||||
{
|
||||
let home = std::env::var_os("HOME")
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(PathBuf::from);
|
||||
service_core_path_for(&sibling, home.as_deref(), true)
|
||||
}
|
||||
|
||||
#[cfg(not(all(target_os = "macos", feature = "verge-dev")))]
|
||||
Ok(sibling)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn escape_osascript_double_quoted_string(value: &str) -> String {
|
||||
value.replace('\\', "\\\\").replace('"', "\\\"")
|
||||
@@ -588,24 +390,12 @@ fn shell_single_quote(value: &str) -> String {
|
||||
format!("'{}'", value.replace('\'', r"'\''"))
|
||||
}
|
||||
|
||||
fn packaged_service_tool_path(file_name: &str, packaged_path: impl FnOnce() -> Result<PathBuf>) -> Result<PathBuf> {
|
||||
#[cfg(feature = "verge-dev")]
|
||||
{
|
||||
drop(packaged_path);
|
||||
let directory = std::env::var_os("CLASH_VERGE_DEV_SERVICE_DIR")
|
||||
.context("CLASH_VERGE_DEV_SERVICE_DIR is missing from the development session")?;
|
||||
let directory = PathBuf::from(directory);
|
||||
if !directory.is_absolute() {
|
||||
bail!("CLASH_VERGE_DEV_SERVICE_DIR must be an absolute path");
|
||||
}
|
||||
Ok(directory.join(file_name))
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "verge-dev"))]
|
||||
{
|
||||
let _ = file_name;
|
||||
packaged_path()
|
||||
fn uninstaller_tool_path(packaged_path: impl FnOnce() -> Result<PathBuf>) -> Result<PathBuf> {
|
||||
let uninstall_path = packaged_path()?;
|
||||
if !uninstall_path.exists() {
|
||||
bail!(format!("uninstaller not found: {uninstall_path:?}"));
|
||||
}
|
||||
Ok(uninstall_path)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
@@ -636,14 +426,6 @@ pub(super) fn run_maybe_elevated(program: &Path, hide_window: bool) -> Result<st
|
||||
Ok(status)
|
||||
}
|
||||
|
||||
fn uninstaller_tool_path(file_name: &str, packaged_path: impl FnOnce() -> Result<PathBuf>) -> Result<PathBuf> {
|
||||
let uninstall_path = packaged_service_tool_path(file_name, packaged_path)?;
|
||||
if !uninstall_path.exists() {
|
||||
bail!(format!("uninstaller not found: {uninstall_path:?}"));
|
||||
}
|
||||
Ok(uninstall_path)
|
||||
}
|
||||
|
||||
fn ensure_uninstall_success(status: &std::process::ExitStatus) -> Result<()> {
|
||||
if !status.success() {
|
||||
bail!(
|
||||
@@ -658,9 +440,8 @@ fn ensure_uninstall_success(status: &std::process::ExitStatus) -> Result<()> {
|
||||
fn uninstall_service() -> Result<()> {
|
||||
logging!(info, Type::Service, "uninstall service");
|
||||
|
||||
let uninstall_path = uninstaller_tool_path("clash-verge-service-uninstall.exe", || {
|
||||
Ok(dirs::service_path()?.with_file_name("clash-verge-service-uninstall.exe"))
|
||||
})?;
|
||||
let uninstall_path =
|
||||
uninstaller_tool_path(|| Ok(dirs::service_path()?.with_file_name("clash-verge-service-uninstall.exe")))?;
|
||||
|
||||
let status = run_maybe_elevated(&uninstall_path, true)?;
|
||||
ensure_uninstall_success(&status)
|
||||
@@ -670,7 +451,7 @@ fn uninstall_service() -> Result<()> {
|
||||
fn uninstall_service() -> Result<()> {
|
||||
logging!(info, Type::Service, "uninstall service");
|
||||
|
||||
let uninstall_path = uninstaller_tool_path("clash-verge-service-uninstall", || {
|
||||
let uninstall_path = uninstaller_tool_path(|| {
|
||||
Ok(tauri::utils::platform::current_exe()?.with_file_name("clash-verge-service-uninstall"))
|
||||
})?;
|
||||
|
||||
@@ -718,11 +499,9 @@ fn linux_running_as_root() -> bool {
|
||||
fn uninstall_service() -> Result<()> {
|
||||
logging!(info, Type::Service, "uninstall service");
|
||||
|
||||
let uninstall_path = uninstaller_tool_path("clash-verge-service-uninstall", || {
|
||||
Ok(dirs::service_path()?.with_file_name("clash-verge-service-uninstall"))
|
||||
})?;
|
||||
let uninstall_path =
|
||||
uninstaller_tool_path(|| Ok(dirs::service_path()?.with_file_name("clash-verge-service-uninstall")))?;
|
||||
|
||||
let uninstall_path = macos_service_tool_path(&uninstall_path)?;
|
||||
let uninstall_shell: String = uninstall_path.to_string_lossy().into_owned();
|
||||
|
||||
// clash_verge_i18n::sync_locale(Config::verge().await.latest_arc().language.as_deref());
|
||||
@@ -735,7 +514,7 @@ fn uninstall_service() -> Result<()> {
|
||||
|
||||
// logging!(debug, Type::Service, "uninstall command: {}", command);
|
||||
|
||||
let status = StdCommand::new("osascript").args(vec!["-e", &command]).status()?;
|
||||
let status = StdCommand::new("osascript").args(["-e", command.as_str()]).status()?;
|
||||
|
||||
ensure_uninstall_success(&status)
|
||||
}
|
||||
@@ -757,13 +536,10 @@ fn install_service() -> Result<()> {
|
||||
|
||||
fn invoke_service_install(cores: &[clash_verge_service_ipc::management::CoreSource], core_only: bool) -> Result<()> {
|
||||
let name = format!("clash-verge-service-install{}", std::env::consts::EXE_SUFFIX);
|
||||
let installer = packaged_service_tool_path(&name, || {
|
||||
#[cfg(target_os = "linux")]
|
||||
let executable = tauri::utils::platform::current_exe()?;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let executable = dirs::service_path()?;
|
||||
Ok(executable.with_file_name(&name))
|
||||
})?;
|
||||
#[cfg(target_os = "linux")]
|
||||
let installer = tauri::utils::platform::current_exe()?.with_file_name(&name);
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let installer = dirs::service_path()?.with_file_name(&name);
|
||||
#[cfg(unix)]
|
||||
let gid = Some(tauri_plugin_clash_verge_sysinfo::current_gid());
|
||||
#[cfg(windows)]
|
||||
@@ -917,10 +693,9 @@ pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()
|
||||
|
||||
let credentials = current_owner_credentials()?;
|
||||
let runtime = collect_service_runtime_bundle(config_file).await?;
|
||||
let proposed_session_token = generate_service_session_token()?;
|
||||
let request = StartClashRequest {
|
||||
runtime,
|
||||
proposed_session_token: proposed_session_token.clone(),
|
||||
proposed_session_token: generate_service_session_token()?,
|
||||
macos_proxy: None,
|
||||
};
|
||||
|
||||
@@ -969,10 +744,10 @@ pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()
|
||||
let capabilities = probe_service_capabilities().await;
|
||||
tracing::Span::current().record("staging", capabilities.runtime_staging);
|
||||
*ACTIVE_SERVICE_SESSION.lock() = Some(ActiveServiceSession {
|
||||
proof: OwnerSessionProof {
|
||||
proof: Arc::new(OwnerSessionProof {
|
||||
generation: result.session.generation,
|
||||
token: proposed_session_token,
|
||||
},
|
||||
token: request.proposed_session_token,
|
||||
}),
|
||||
supports_runtime_staging: capabilities.runtime_staging,
|
||||
supports_runtime_file_read: capabilities.runtime_file_read,
|
||||
supports_runtime_geo_read: capabilities.runtime_geo_read,
|
||||
@@ -1254,7 +1029,11 @@ async fn sync_runtime_geo(
|
||||
let Ok(local) = tokio::fs::metadata(target).await else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some((Some(_), _, Some(runtime_mtime_ns))) = read_chunk(credentials, session, asset, u64::MAX).await? else {
|
||||
let request = RuntimeFileRequest {
|
||||
destination: asset.to_owned(),
|
||||
offset: u64::MAX,
|
||||
};
|
||||
let Some((Some(_), _, Some(runtime_mtime_ns))) = read_chunk(credentials, session, &request).await? else {
|
||||
return Ok(());
|
||||
};
|
||||
// A newer local file is a change the next staging still has to copy into the runtime.
|
||||
@@ -1301,7 +1080,7 @@ async fn publish_fetched(
|
||||
let manager = CoreManager::global();
|
||||
let _lifecycle = manager.lifecycle_lock.lock().await;
|
||||
let unchanged = matches!(*manager.get_running_mode(), RunningMode::Service)
|
||||
&& active_service_session().is_ok_and(|current| current == *session);
|
||||
&& active_service_session().is_ok_and(|current| *current == *session);
|
||||
let declared = if unchanged {
|
||||
match applied_remote_providers(runtime, app_dir) {
|
||||
Ok(declared) => declared,
|
||||
@@ -1354,8 +1133,13 @@ async fn fetch_runtime_file(
|
||||
|
||||
let mut written = 0_u64;
|
||||
let mut identity = None;
|
||||
let mut request = RuntimeFileRequest {
|
||||
destination: destination.to_owned(),
|
||||
offset: 0,
|
||||
};
|
||||
loop {
|
||||
let (hex, len, mtime_ns) = match read_chunk(credentials, session, destination, written).await? {
|
||||
request.offset = written;
|
||||
let (hex, len, mtime_ns) = match read_chunk(credentials, session, &request).await? {
|
||||
Some(chunk) => chunk,
|
||||
None => return Ok(Fetch::SessionLost),
|
||||
};
|
||||
@@ -1386,8 +1170,11 @@ async fn recheck_identity(
|
||||
session: &OwnerSessionProof,
|
||||
cache: &FetchedCache,
|
||||
) -> Result<Fetch> {
|
||||
let destination = &cache.declared.provider.destination;
|
||||
Ok(match read_chunk(credentials, session, destination, cache.len).await? {
|
||||
let request = RuntimeFileRequest {
|
||||
destination: cache.declared.provider.destination.to_owned(),
|
||||
offset: cache.len,
|
||||
};
|
||||
Ok(match read_chunk(credentials, session, &request).await? {
|
||||
None => Fetch::SessionLost,
|
||||
Some((Some(hex), len, mtime_ns)) if hex.is_empty() && (len, mtime_ns) == (cache.len, cache.mtime_ns) => {
|
||||
Fetch::Complete { len, mtime_ns }
|
||||
@@ -1400,14 +1187,9 @@ async fn recheck_identity(
|
||||
async fn read_chunk(
|
||||
credentials: &OwnerCredentials,
|
||||
session: &OwnerSessionProof,
|
||||
destination: &str,
|
||||
offset: u64,
|
||||
request: &RuntimeFileRequest,
|
||||
) -> Result<Option<(Option<String>, u64, Option<u64>)>> {
|
||||
let request = RuntimeFileRequest {
|
||||
destination: destination.to_owned(),
|
||||
offset,
|
||||
};
|
||||
let response = clash_verge_service_ipc::read_runtime_file(credentials, session, &request)
|
||||
let response = clash_verge_service_ipc::read_runtime_file(credentials, session, request)
|
||||
.await
|
||||
.context("无法连接到Clash Verge Service")?;
|
||||
if response.code == ServiceErrorCode::NotActive as u16
|
||||
@@ -1960,10 +1742,6 @@ impl ServiceManager {
|
||||
}
|
||||
|
||||
pub async fn detect_startup_status(&self) {
|
||||
if cfg!(feature = "dev-sidecar") {
|
||||
RUN_STATE.accept_sidecar();
|
||||
return;
|
||||
}
|
||||
RUN_STATE.observe_current_health().await;
|
||||
}
|
||||
|
||||
@@ -1997,8 +1775,9 @@ impl ServiceManager {
|
||||
async fn apply_service_status(&self, status: ServiceStatus) -> Result<()> {
|
||||
// Use the caller's action; a racing observation may clear the stored pending action.
|
||||
let Some(action) = requested_action(&status) else {
|
||||
self.set_status(status.clone());
|
||||
return report_non_actionable_status(status);
|
||||
let reported = report_non_actionable_status(&status);
|
||||
self.set_status(status);
|
||||
return reported;
|
||||
};
|
||||
// Atomically record the request and capture the Sidecar allowance it clears.
|
||||
let sidecar_allowed_before = RUN_STATE.request_action(action);
|
||||
@@ -2033,7 +1812,7 @@ async fn run_action_restoring_sidecar<E: RunStateEnv>(
|
||||
}
|
||||
|
||||
/// Explain a status that asks for no privileged action, refusing the ones we cannot act on.
|
||||
fn report_non_actionable_status(status: ServiceStatus) -> Result<()> {
|
||||
fn report_non_actionable_status(status: &ServiceStatus) -> Result<()> {
|
||||
match status {
|
||||
ServiceStatus::Checking => bail!("service status is still being checked"),
|
||||
ServiceStatus::Ready => logging!(info, Type::Service, "服务就绪,直接启动"),
|
||||
@@ -2130,19 +1909,12 @@ mod tests {
|
||||
use super::{
|
||||
ServiceHealth, ServiceStatus, capture_generation_before, claim_owner_recovery_generation,
|
||||
generate_service_session_token, mark_service_unavailable_after_owner_loss, owner_recovery_policy,
|
||||
service_core_path_for, session_matches_status,
|
||||
session_matches_status,
|
||||
};
|
||||
#[cfg(unix)]
|
||||
use super::{service_core_path_for_with_publisher, service_tool_path_for};
|
||||
use crate::core::runstate::{FakeEnv, OwnerRecoveryReason, PendingAction, RunStateStore};
|
||||
use anyhow::bail;
|
||||
use clash_verge_service_ipc::OwnerSessionProof;
|
||||
#[cfg(unix)]
|
||||
use std::cell::Cell;
|
||||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// A Run State backed by a scripted environment, so these tests never touch the global.
|
||||
fn fake_store() -> RunStateStore<FakeEnv> {
|
||||
@@ -2158,197 +1930,6 @@ mod tests {
|
||||
ServiceStatus::from_run_state(&store.settled().await)
|
||||
}
|
||||
|
||||
static TEST_DIRECTORY_GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TestDirectory(PathBuf);
|
||||
|
||||
impl TestDirectory {
|
||||
fn new(label: &str) -> anyhow::Result<Self> {
|
||||
let generation = TEST_DIRECTORY_GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"clash-verge-rev-service-{label}-{}-{generation}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir(&path)?;
|
||||
Ok(Self(path))
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestDirectory {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn staging_directory(home: &Path) -> PathBuf {
|
||||
home.join("Applications/.clash-verge-rev-dev/service-core")
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn service_tools_staging_directory(home: &Path) -> PathBuf {
|
||||
home.join("Applications/.clash-verge-rev-dev/service-tools")
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn staging_temporary_entries(home: &Path, core_name: &str) -> anyhow::Result<Vec<PathBuf>> {
|
||||
let directory = staging_directory(home);
|
||||
if !directory.exists() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
Ok(std::fs::read_dir(directory)?
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.path())
|
||||
.filter(|path| {
|
||||
path.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.is_some_and(|name| name.starts_with(&format!(".{core_name}.")) && name.ends_with(".tmp"))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nondevelopment_service_core_selection_preserves_sibling_without_staging() -> anyhow::Result<()> {
|
||||
let root = TestDirectory::new("release-path")?;
|
||||
let home = root.path().join("home");
|
||||
let source = root.path().join("target/debug/verge-mihomo");
|
||||
|
||||
let selected = service_core_path_for(&source, Some(&home), false)?;
|
||||
|
||||
assert_eq!(selected, source);
|
||||
assert!(!staging_directory(&home).exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn development_service_core_uses_exact_layout_and_executable_bytes() -> anyhow::Result<()> {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
|
||||
let root = TestDirectory::new("development-path")?;
|
||||
let home = root.path().join("home");
|
||||
let source = root.path().join("verge-mihomo");
|
||||
std::fs::write(&source, b"development core")?;
|
||||
|
||||
let selected = service_core_path_for(&source, Some(&home), true)?;
|
||||
|
||||
assert_eq!(
|
||||
selected,
|
||||
home.join("Applications/.clash-verge-rev-dev/service-core/verge-mihomo")
|
||||
);
|
||||
assert_eq!(std::fs::read(&selected)?, b"development core");
|
||||
let metadata = std::fs::symlink_metadata(&selected)?;
|
||||
assert!(metadata.file_type().is_file());
|
||||
assert_ne!(metadata.permissions().mode() & 0o111, 0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn development_service_tool_uses_safe_layout_and_executable_bytes() -> anyhow::Result<()> {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
|
||||
let root = TestDirectory::new("development-service-tool")?;
|
||||
let home = root.path().join("home");
|
||||
let source = root.path().join("clash-verge-service-install");
|
||||
std::fs::write(&source, b"development installer")?;
|
||||
|
||||
let selected = service_tool_path_for(&source, Some(&home), true)?;
|
||||
|
||||
assert_eq!(
|
||||
selected,
|
||||
service_tools_staging_directory(&home).join("clash-verge-service-install")
|
||||
);
|
||||
assert_eq!(std::fs::read(&selected)?, b"development installer");
|
||||
assert_ne!(std::fs::metadata(&selected)?.permissions().mode() & 0o111, 0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn development_service_core_refresh_atomically_replaces_bytes() -> anyhow::Result<()> {
|
||||
let root = TestDirectory::new("refresh")?;
|
||||
let home = root.path().join("home");
|
||||
let source = root.path().join("verge-mihomo");
|
||||
std::fs::write(&source, b"first core")?;
|
||||
let selected = service_core_path_for(&source, Some(&home), true)?;
|
||||
assert_eq!(
|
||||
selected,
|
||||
home.join("Applications/.clash-verge-rev-dev/service-core/verge-mihomo")
|
||||
);
|
||||
|
||||
std::fs::write(&source, b"second core")?;
|
||||
let refreshed = service_core_path_for(&source, Some(&home), true)?;
|
||||
|
||||
assert_eq!(refreshed, selected);
|
||||
assert_eq!(std::fs::read(&refreshed)?, b"second core");
|
||||
assert!(staging_temporary_entries(&home, "verge-mihomo")?.is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn failed_development_refresh_preserves_good_core_and_cleans_temporary_entry() -> anyhow::Result<()> {
|
||||
let root = TestDirectory::new("failed-refresh")?;
|
||||
let home = root.path().join("home");
|
||||
let source = root.path().join("verge-mihomo");
|
||||
std::fs::write(&source, b"known good core")?;
|
||||
let selected = service_core_path_for(&source, Some(&home), true)?;
|
||||
|
||||
std::fs::write(&source, b"replacement core")?;
|
||||
let publish_attempted = Cell::new(false);
|
||||
let result = service_core_path_for_with_publisher(
|
||||
&source,
|
||||
Some(&home),
|
||||
true,
|
||||
"service-core",
|
||||
|temporary, final_path| {
|
||||
publish_attempted.set(true);
|
||||
assert_ne!(temporary, final_path, "publisher must receive the temporary path");
|
||||
assert!(std::fs::symlink_metadata(temporary)?.file_type().is_file());
|
||||
assert_eq!(std::fs::read(temporary)?, b"replacement core");
|
||||
anyhow::bail!("injected post-creation publish failure")
|
||||
},
|
||||
);
|
||||
let error = match result {
|
||||
Ok(path) => anyhow::bail!("failed publication selected {}", path.display()),
|
||||
Err(error) => error.to_string(),
|
||||
};
|
||||
|
||||
assert!(publish_attempted.get());
|
||||
assert!(error.contains("injected post-creation publish failure"));
|
||||
assert_eq!(std::fs::read(&selected)?, b"known good core");
|
||||
assert!(staging_temporary_entries(&home, "verge-mihomo")?.is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn development_service_core_replaces_final_symlink_without_following_it() -> anyhow::Result<()> {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let root = TestDirectory::new("symlink")?;
|
||||
let home = root.path().join("home");
|
||||
let source = root.path().join("verge-mihomo");
|
||||
std::fs::write(&source, b"selected core")?;
|
||||
let final_path = home.join("Applications/.clash-verge-rev-dev/service-core/verge-mihomo");
|
||||
std::fs::create_dir_all(final_path.parent().unwrap_or_else(|| Path::new(".")))?;
|
||||
let symlink_target = root.path().join("must-not-change");
|
||||
std::fs::write(&symlink_target, b"target bytes")?;
|
||||
symlink(&symlink_target, &final_path)?;
|
||||
|
||||
let selected = service_core_path_for(&source, Some(&home), true)?;
|
||||
|
||||
assert_eq!(selected, final_path);
|
||||
assert!(std::fs::symlink_metadata(&selected)?.file_type().is_file());
|
||||
assert_eq!(std::fs::read(&selected)?, b"selected core");
|
||||
assert_eq!(std::fs::read(&symlink_target)?, b"target bytes");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mismatched_active_generation_displaces_local_session() {
|
||||
let proof = OwnerSessionProof {
|
||||
@@ -2442,7 +2023,7 @@ mod tests {
|
||||
&store,
|
||||
super::ServiceStartRefusal {
|
||||
code: code as u16,
|
||||
core_path: "/development/service-core/verge-mihomo".into(),
|
||||
core_path: "/fixture/service-core/verge-mihomo".into(),
|
||||
message: "no administrator-approved copy is installed".into(),
|
||||
},
|
||||
);
|
||||
@@ -2468,7 +2049,7 @@ mod tests {
|
||||
&store,
|
||||
super::ServiceStartRefusal {
|
||||
code: clash_verge_service_ipc::ServiceErrorCode::ProxyClearFailed as u16,
|
||||
core_path: "/development/service-core/verge-mihomo".into(),
|
||||
core_path: "/fixture/service-core/verge-mihomo".into(),
|
||||
message: "SystemConfiguration operation failed: lock preferences (status 3002)".into(),
|
||||
},
|
||||
);
|
||||
@@ -2553,7 +2134,7 @@ mod tests {
|
||||
#[test]
|
||||
fn legacy_socket_alone_is_not_install_evidence() {
|
||||
assert!(
|
||||
!super::macos_service_install_markers()
|
||||
!super::MACOS_SERVICE_INSTALL_MARKERS
|
||||
.iter()
|
||||
.any(|marker| marker == "/tmp/verge/clash-verge-service.sock")
|
||||
);
|
||||
|
||||
@@ -21,6 +21,7 @@ use super::handle;
|
||||
use anyhow::Result;
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::LazyLock;
|
||||
use std::time::Duration;
|
||||
use tauri::{
|
||||
AppHandle, Wry,
|
||||
@@ -40,6 +41,14 @@ type ProxyMenuItem = (Option<Submenu<Wry>>, Vec<Box<dyn IsMenuItem<Wry>>>);
|
||||
const TRAY_CLICK_DEBOUNCE_MS: u64 = 300;
|
||||
pub const TRAY_ID: &str = "clash-verge-rev-tray";
|
||||
|
||||
static TOOLTIP_VERSION: LazyLock<&'static str> = LazyLock::new(|| {
|
||||
let v = env!("CARGO_PKG_VERSION");
|
||||
v.split_once('+').map_or_else(
|
||||
|| v,
|
||||
|(main, rest)| Box::leak(format!("{main}+{}", rest.split('.').next().unwrap_or("")).into_boxed_str()),
|
||||
)
|
||||
});
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct TrayMenuOptions<'a> {
|
||||
mode: Option<&'a str>,
|
||||
@@ -352,11 +361,7 @@ impl Tray {
|
||||
let tun_text = clash_verge_i18n::t!("tray.tooltip.tun");
|
||||
let profile_text = clash_verge_i18n::t!("tray.tooltip.profile");
|
||||
|
||||
let v = env!("CARGO_PKG_VERSION");
|
||||
let reassembled_version = v.split_once('+').map_or_else(
|
||||
|| v.into(),
|
||||
|(main, rest)| format!("{main}+{}", rest.split('.').next().unwrap_or("")),
|
||||
);
|
||||
let reassembled_version = *TOOLTIP_VERSION;
|
||||
|
||||
let tooltip = format!(
|
||||
"Clash Verge {}\n{}: {}\n{}: {}\n{}: {}",
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
use crate::{
|
||||
config::{Config, MixedPort},
|
||||
singleton,
|
||||
utils::dirs,
|
||||
};
|
||||
use crate::{config::Config, singleton, utils::dirs};
|
||||
use anyhow::{Context as _, Result};
|
||||
use chrono::Utc;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
@@ -201,40 +197,16 @@ pub enum DownloadEvent {
|
||||
}
|
||||
|
||||
const MIRRORS: [&str; 2] = ["https://update.hwdns.net/", "https://gh-proxy.org/"];
|
||||
const GITHUB_ENDPOINT: &str =
|
||||
"https://github.com/clash-verge-rev/clash-verge-rev/releases/download/updater/update.json";
|
||||
/// A source delivering less than this per window is dropped for the next one.
|
||||
const MIN_PROGRESS: u64 = 1024 * 1024;
|
||||
const PROGRESS_WINDOW: Duration = Duration::from_secs(30);
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum UpdateChannel {
|
||||
/// The configured endpoints with mirror fallbacks.
|
||||
Auto,
|
||||
Github,
|
||||
/// GitHub through the Core's mixed port.
|
||||
GithubProxy,
|
||||
}
|
||||
|
||||
impl UpdateChannel {
|
||||
async fn current() -> Self {
|
||||
match Config::verge().await.latest_arc().update_channel.as_deref() {
|
||||
Some("github") => Self::Github,
|
||||
Some("github_proxy") => Self::GithubProxy,
|
||||
_ => Self::Auto,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The manifest's URL, then the other mirror, then GitHub itself; only GitHub outside `Auto`.
|
||||
fn download_sources(url: &tauri::Url, channel: UpdateChannel) -> Vec<tauri::Url> {
|
||||
/// The manifest's URL, then the other mirror, then GitHub itself.
|
||||
fn download_sources(url: &tauri::Url) -> Vec<tauri::Url> {
|
||||
let origin = MIRRORS
|
||||
.iter()
|
||||
.find_map(|mirror| url.as_str().strip_prefix(mirror))
|
||||
.unwrap_or(url.as_str());
|
||||
if channel != UpdateChannel::Auto {
|
||||
return vec![tauri::Url::parse(origin).unwrap_or_else(|_| url.clone())];
|
||||
}
|
||||
let mut sources = vec![url.clone()];
|
||||
if origin.starts_with("https://github.com/") {
|
||||
let candidates = MIRRORS.iter().map(|mirror| format!("{mirror}{origin}"));
|
||||
@@ -252,7 +224,7 @@ fn download_sources(url: &tauri::Url, channel: UpdateChannel) -> Vec<tauri::Url>
|
||||
/// Tries every source with a throughput floor, then again stopping only on a stall, so a link
|
||||
/// that is slow everywhere still finishes.
|
||||
async fn download(update: &Update, on_event: impl Fn(DownloadEvent) + Sync) -> Result<Vec<u8>> {
|
||||
let sources = download_sources(&update.download_url, UpdateChannel::current().await);
|
||||
let sources = download_sources(&update.download_url);
|
||||
let mut last_error = None;
|
||||
for floor in [MIN_PROGRESS, 1] {
|
||||
for url in &sources {
|
||||
@@ -310,16 +282,7 @@ impl SilentUpdater {
|
||||
/// Checks the server; Windows receives `/LANG` to suppress the NSIS language dialog,
|
||||
/// see `packages/windows/installer.nsi`.
|
||||
async fn check(app_handle: &tauri::AppHandle) -> Result<Option<Update>> {
|
||||
let channel = UpdateChannel::current().await;
|
||||
let mut updater_builder = app_handle.updater_builder();
|
||||
if channel != UpdateChannel::Auto {
|
||||
updater_builder = updater_builder.endpoints(vec![tauri::Url::parse(GITHUB_ENDPOINT)?])?;
|
||||
}
|
||||
if channel == UpdateChannel::GithubProxy {
|
||||
let port = MixedPort::desired().await;
|
||||
// The resulting `Update` keeps this proxy for its download.
|
||||
updater_builder = updater_builder.proxy(tauri::Url::parse(&format!("http://127.0.0.1:{port}"))?);
|
||||
}
|
||||
let updater_builder = app_handle.updater_builder();
|
||||
#[cfg(target_os = "windows")]
|
||||
let updater_builder = {
|
||||
let verge_lang = Config::verge().await.latest_arc().language.clone();
|
||||
@@ -620,7 +583,8 @@ impl SilentUpdater {
|
||||
|
||||
logging!(info, Type::System, "Silent updater: checking for updates...");
|
||||
|
||||
let update = match Self::check(app_handle).await {
|
||||
let updater = app_handle.updater()?;
|
||||
let update = match updater.check().await {
|
||||
Ok(Some(update)) => update,
|
||||
Ok(None) => {
|
||||
logging!(info, Type::System, "Silent updater: no update available");
|
||||
@@ -628,11 +592,11 @@ impl SilentUpdater {
|
||||
}
|
||||
Err(e) => {
|
||||
logging!(warn, Type::System, "Silent updater: check failed: {e}");
|
||||
return Err(e);
|
||||
return Err(e.into());
|
||||
}
|
||||
};
|
||||
|
||||
let version = update.version.clone();
|
||||
let version = update.version.as_str();
|
||||
logging!(info, Type::System, "Silent updater: update available: v{version}");
|
||||
|
||||
if let Some(body) = &update.body
|
||||
@@ -664,7 +628,7 @@ impl SilentUpdater {
|
||||
};
|
||||
let bytes = bytes?;
|
||||
logging!(info, Type::System, "Silent updater: download complete");
|
||||
Self::write_cache(&bytes, &version)?;
|
||||
Self::write_cache(&bytes, version)?;
|
||||
}
|
||||
|
||||
// Serialized with `discard_pending` in the verge patch, which holds the same lock.
|
||||
|
||||
@@ -526,11 +526,7 @@ fn enforce_tun(mut config: Mapping, snapshot: Mapping) -> Mapping {
|
||||
if snapshot.is_empty() {
|
||||
return config;
|
||||
}
|
||||
let mut tun = config
|
||||
.get("tun")
|
||||
.and_then(Value::as_mapping)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let mut tun = take_mapping(&mut config, "tun");
|
||||
tun.extend(snapshot);
|
||||
config.insert(Value::from("tun"), Value::Mapping(tun));
|
||||
config
|
||||
@@ -673,8 +669,12 @@ fn builtin_hy_alpn(mut config: Mapping) -> Mapping {
|
||||
for proxy in proxies.iter_mut() {
|
||||
let Some(proxy) = proxy.as_mapping_mut() else { continue };
|
||||
let is_hysteria = proxy.get("type").and_then(Value::as_str) == Some("hysteria");
|
||||
if is_hysteria && let Some(Value::String(alpn)) = proxy.get("alpn").cloned() {
|
||||
proxy.insert("alpn".into(), Value::Sequence(vec![Value::String(alpn)]));
|
||||
if is_hysteria
|
||||
&& let Some(alpn) = proxy.get_mut("alpn")
|
||||
&& let Value::String(text) = alpn
|
||||
{
|
||||
let text = std::mem::take(text);
|
||||
*alpn = Value::Sequence(vec![Value::String(text)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,7 +92,6 @@ verge_registry! {
|
||||
auto_close_connection => NoEffect;
|
||||
auto_switch_selector_group => NoEffect;
|
||||
auto_check_update => NoEffect;
|
||||
update_channel => NoEffect;
|
||||
default_latency_test => NoEffect;
|
||||
default_latency_timeout => NoEffect;
|
||||
enable_auto_delay_detection => NoEffect;
|
||||
|
||||
@@ -20,6 +20,7 @@ use anyhow::{Context as _, Result, anyhow, bail};
|
||||
use clash_verge_draft::DraftTransaction;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use std::mem::DropGuard;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub async fn probe_listener(request: ListenerProbe) -> Result<ListenerProbeOutcome> {
|
||||
AsyncHandler::spawn_blocking(move || probe_listener_sync(&request))
|
||||
@@ -40,7 +41,7 @@ pub async fn save_proxy_ports(settings: ProxyPortSettings) -> Result<SaveProxyPo
|
||||
});
|
||||
|
||||
// Read first because transaction rollback discards all claimed drafts.
|
||||
let current = current_runtime_mapping().await?;
|
||||
let current = Arc::new(current_runtime_mapping().await?);
|
||||
|
||||
let clash = Config::clash().await;
|
||||
let verge = Config::verge().await;
|
||||
@@ -63,10 +64,10 @@ pub async fn save_proxy_ports(settings: ProxyPortSettings) -> Result<SaveProxyPo
|
||||
Config::generate()
|
||||
.await
|
||||
.context("failed to generate candidate proxy port configuration")?;
|
||||
let candidate = latest_runtime_mapping().await?;
|
||||
let candidate = Arc::new(latest_runtime_mapping().await?);
|
||||
|
||||
let was_running = !matches!(*manager.get_running_mode(), RunningMode::NotRunning);
|
||||
let assessment = probe_proxy_ports(current.clone(), candidate.clone(), was_running).await?;
|
||||
let assessment = probe_proxy_ports(Arc::clone(¤t), Arc::clone(&candidate), was_running).await?;
|
||||
if let Some(outcome) = rejected_save_outcome(assessment)? {
|
||||
return Ok(outcome);
|
||||
}
|
||||
@@ -159,8 +160,8 @@ async fn latest_runtime_mapping() -> Result<serde_yaml_ng::Mapping> {
|
||||
}
|
||||
|
||||
async fn probe_proxy_ports(
|
||||
current: serde_yaml_ng::Mapping,
|
||||
candidate: serde_yaml_ng::Mapping,
|
||||
current: Arc<serde_yaml_ng::Mapping>,
|
||||
candidate: Arc<serde_yaml_ng::Mapping>,
|
||||
current_core_is_running: bool,
|
||||
) -> Result<ListenerProbeOutcome> {
|
||||
AsyncHandler::spawn_blocking(move || probe_proxy_port_change(¤t, &candidate, current_core_is_running))
|
||||
|
||||
@@ -153,7 +153,7 @@ fn handle_singleton_startup(
|
||||
}
|
||||
|
||||
pub fn run() -> std::process::ExitCode {
|
||||
#[cfg(all(target_os = "macos", not(debug_assertions), not(test), not(feature = "verge-dev")))]
|
||||
#[cfg(all(target_os = "macos", not(debug_assertions), not(test)))]
|
||||
if utils::macos_launch_guard::enforce_before_initialization() == utils::macos_launch_guard::LaunchDisposition::Exit
|
||||
{
|
||||
return std::process::ExitCode::SUCCESS;
|
||||
|
||||
+10
-10
@@ -8,14 +8,14 @@ use std::{
|
||||
};
|
||||
use tauri::Manager as _;
|
||||
|
||||
#[cfg(not(feature = "verge-dev"))]
|
||||
#[cfg(not(debug_assertions))]
|
||||
pub static APP_ID: &str = "io.github.clash-verge-rev.clash-verge-rev";
|
||||
#[cfg(not(feature = "verge-dev"))]
|
||||
#[cfg(not(debug_assertions))]
|
||||
pub static BACKUP_DIR: &str = "clash-verge-rev-backup";
|
||||
|
||||
#[cfg(feature = "verge-dev")]
|
||||
#[cfg(debug_assertions)]
|
||||
pub static APP_ID: &str = "io.github.clash-verge-rev.clash-verge-rev.dev";
|
||||
#[cfg(feature = "verge-dev")]
|
||||
#[cfg(debug_assertions)]
|
||||
pub static BACKUP_DIR: &str = "clash-verge-rev-backup-dev";
|
||||
|
||||
pub static CLASH_CONFIG: &str = "config.yaml";
|
||||
@@ -219,9 +219,9 @@ fn sidecar_ipc_path_for(
|
||||
|
||||
let root = std::ffi::CStr::from_bytes_until_nul(&buffer)
|
||||
.map_err(|_| anyhow::anyhow!("macOS per-user temporary directory is not NUL-terminated"))?;
|
||||
#[cfg(feature = "verge-dev")]
|
||||
#[cfg(debug_assertions)]
|
||||
let filename = "verge-mihomo-dev.sock";
|
||||
#[cfg(not(feature = "verge-dev"))]
|
||||
#[cfg(not(debug_assertions))]
|
||||
let filename = "verge-mihomo.sock";
|
||||
let path = PathBuf::from(OsStr::from_bytes(root.to_bytes())).join(filename);
|
||||
|
||||
@@ -238,7 +238,7 @@ fn sidecar_ipc_path_for(
|
||||
|
||||
#[cfg(windows)]
|
||||
fn sidecar_ipc_path_for(_app_root: &std::path::Path, identity: &clash_verge_service_ipc::OwnerIdentity) -> PathBuf {
|
||||
PathBuf::from(sidecar_pipe_name(identity, cfg!(feature = "verge-dev")))
|
||||
PathBuf::from(sidecar_pipe_name(identity, cfg!(debug_assertions)))
|
||||
}
|
||||
|
||||
#[cfg(any(windows, test))]
|
||||
@@ -285,9 +285,9 @@ mod ipc_tests {
|
||||
|
||||
assert!(!path.starts_with(app_root));
|
||||
assert!(path.as_os_str().as_bytes().len() < 104);
|
||||
#[cfg(feature = "verge-dev")]
|
||||
#[cfg(debug_assertions)]
|
||||
assert_eq!(path.file_name(), Some(OsStr::new("verge-mihomo-dev.sock")));
|
||||
#[cfg(not(feature = "verge-dev"))]
|
||||
#[cfg(not(debug_assertions))]
|
||||
assert_eq!(path.file_name(), Some(OsStr::new("verge-mihomo.sock")));
|
||||
assert_eq!(path, sidecar_ipc_path_for(Path::new("/different/root"), &identity)?);
|
||||
assert!(path.parent().is_some_and(Path::is_dir));
|
||||
@@ -312,7 +312,7 @@ mod ipc_tests {
|
||||
path,
|
||||
Path::new(&format!(
|
||||
r"\\.\pipe\verge-mihomo-sidecar-{}-{}",
|
||||
if cfg!(feature = "verge-dev") { "dev" } else { "release" },
|
||||
if cfg!(debug_assertions) { "dev" } else { "release" },
|
||||
clash_verge_service_ipc::owner_key(&identity)
|
||||
))
|
||||
);
|
||||
|
||||
@@ -166,9 +166,6 @@ fn start_embedded_server(listener: tokio::net::TcpListener, token: String) {
|
||||
let (shutdown_tx, shutdown_rx) = oneshot::channel();
|
||||
let _ = SHUTDOWN_SENDER.set(Mutex::new(Some(shutdown_tx)));
|
||||
|
||||
#[cfg(feature = "verge-dev")]
|
||||
let auth = instance_auth(token);
|
||||
#[cfg(not(feature = "verge-dev"))]
|
||||
let auth = instance_auth(token);
|
||||
|
||||
let visible = warp::path!("commands" / "visible").and_then(|| async {
|
||||
|
||||
@@ -53,6 +53,15 @@ const StyledTextField = styled(TextField)(({ theme }) => ({
|
||||
},
|
||||
}))
|
||||
|
||||
const iconStyle = {
|
||||
style: {
|
||||
height: '24px',
|
||||
width: '24px',
|
||||
cursor: 'pointer',
|
||||
} as React.CSSProperties,
|
||||
inheritViewBox: true,
|
||||
}
|
||||
|
||||
const useControllableState = <T,>(options: {
|
||||
controlled: T | undefined
|
||||
defaultValue: T
|
||||
@@ -119,15 +128,6 @@ export const BaseSearchBox = ({
|
||||
defaultValue: defaultUseRegularExpression,
|
||||
})
|
||||
|
||||
const iconStyle = {
|
||||
style: {
|
||||
height: '24px',
|
||||
width: '24px',
|
||||
cursor: 'pointer',
|
||||
} as React.CSSProperties,
|
||||
inheritViewBox: true,
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
onSearchRef.current = onSearch
|
||||
}, [onSearch])
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import { styled } from '@mui/material/styles'
|
||||
import { default as MuiSwitch, SwitchProps } from '@mui/material/Switch'
|
||||
|
||||
/**
|
||||
* MUI Switch delivers the boolean as the second onChange argument, so
|
||||
* switch handlers use this adapter to stay boolean-only.
|
||||
*/
|
||||
export const switchChangeValue = (_event: unknown, value: boolean): boolean =>
|
||||
value
|
||||
|
||||
export const Switch = styled((props: SwitchProps) => (
|
||||
<MuiSwitch
|
||||
focusVisibleClassName=".Mui-focusVisible"
|
||||
|
||||
@@ -10,7 +10,7 @@ export { BaseSplitChipEditor } from './base-split-chip-editor'
|
||||
export { BaseStyledSelect } from './base-styled-select'
|
||||
export { BaseStyledTextField } from './base-styled-text-field'
|
||||
export { MonacoEditor } from './monaco-editor'
|
||||
export { Switch } from './base-switch'
|
||||
export { Switch, switchChangeValue } from './base-switch'
|
||||
export { TooltipIcon } from './base-tooltip-icon'
|
||||
export { VirtualList, type VirtualListHandle } from './virtual-list'
|
||||
export {
|
||||
|
||||
@@ -5,10 +5,24 @@ import { useCallback, useImperativeHandle, useState, type Ref } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { closeConnection } from 'tauri-plugin-mihomo-api'
|
||||
|
||||
import { useProfiles } from '@/hooks/use-profiles'
|
||||
import parseTraffic from '@/utils/parse-traffic'
|
||||
|
||||
import {
|
||||
getConnectionRuleTargets,
|
||||
type ConnectionRuleKind,
|
||||
} from './connection-rule'
|
||||
import {
|
||||
ConnectionRuleDialog,
|
||||
type ConnectionRuleTarget,
|
||||
} from './connection-rule-dialog'
|
||||
|
||||
export interface ConnectionDetailRef {
|
||||
open: (detail: IConnectionsItem, closed: boolean) => void
|
||||
open: (
|
||||
detail: IConnectionsItem,
|
||||
closed: boolean,
|
||||
preferredKind?: ConnectionRuleKind,
|
||||
) => void
|
||||
close: () => void
|
||||
}
|
||||
|
||||
@@ -16,7 +30,12 @@ export function ConnectionDetail({ ref }: { ref?: Ref<ConnectionDetailRef> }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [detail, setDetail] = useState<IConnectionsItem | null>(null)
|
||||
const [closed, setClosed] = useState(false)
|
||||
const [preferredKind, setPreferredKind] =
|
||||
useState<ConnectionRuleKind>('domain')
|
||||
const theme = useTheme()
|
||||
const [ruleTarget, setRuleTarget] = useState<ConnectionRuleTarget | null>(
|
||||
null,
|
||||
)
|
||||
|
||||
const onClose = useCallback(() => {
|
||||
setOpen(false)
|
||||
@@ -25,51 +44,90 @@ export function ConnectionDetail({ ref }: { ref?: Ref<ConnectionDetailRef> }) {
|
||||
}, [])
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
open: (detail: IConnectionsItem, closed: boolean) => {
|
||||
open: (
|
||||
detail: IConnectionsItem,
|
||||
closed: boolean,
|
||||
preferredKind = 'domain',
|
||||
) => {
|
||||
if (open) return
|
||||
setOpen(true)
|
||||
setDetail(detail)
|
||||
setClosed(closed)
|
||||
setPreferredKind(preferredKind)
|
||||
},
|
||||
close: onClose,
|
||||
}))
|
||||
|
||||
return (
|
||||
<Snackbar
|
||||
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
sx={{
|
||||
'.MuiSnackbarContent-root': {
|
||||
maxWidth: '520px',
|
||||
maxHeight: '480px',
|
||||
overflowY: 'auto',
|
||||
backgroundColor: theme.palette.background.paper,
|
||||
color: theme.palette.text.primary,
|
||||
},
|
||||
}}
|
||||
message={
|
||||
detail ? (
|
||||
<InnerConnectionDetail
|
||||
data={detail}
|
||||
closed={closed}
|
||||
onClose={onClose}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
<>
|
||||
<Snackbar
|
||||
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
sx={{
|
||||
'.MuiSnackbarContent-root': {
|
||||
width: '520px',
|
||||
maxWidth: 'calc(100vw - 32px)',
|
||||
boxSizing: 'border-box',
|
||||
maxHeight: '480px',
|
||||
overflowY: 'auto',
|
||||
backgroundColor: theme.palette.background.paper,
|
||||
color: theme.palette.text.primary,
|
||||
},
|
||||
'.MuiSnackbarContent-message': { width: '100%', minWidth: 0 },
|
||||
}}
|
||||
message={
|
||||
detail ? (
|
||||
<InnerConnectionDetail
|
||||
data={detail}
|
||||
closed={closed}
|
||||
preferredKind={preferredKind}
|
||||
onClose={onClose}
|
||||
onAddRule={(target) => {
|
||||
setRuleTarget(target)
|
||||
onClose()
|
||||
}}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
{ruleTarget && (
|
||||
<ConnectionRuleDialog
|
||||
target={ruleTarget}
|
||||
onClose={() => setRuleTarget(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
interface InnerProps {
|
||||
data: IConnectionsItem
|
||||
closed: boolean
|
||||
preferredKind: ConnectionRuleKind
|
||||
onClose?: () => void
|
||||
onAddRule: (target: ConnectionRuleTarget) => void
|
||||
}
|
||||
|
||||
const InnerConnectionDetail = ({ data, closed, onClose }: InnerProps) => {
|
||||
const InnerConnectionDetail = ({
|
||||
data,
|
||||
closed,
|
||||
preferredKind,
|
||||
onClose,
|
||||
onAddRule,
|
||||
}: InnerProps) => {
|
||||
const { t } = useTranslation()
|
||||
const { current } = useProfiles()
|
||||
const { metadata, rulePayload } = data
|
||||
const targets = getConnectionRuleTargets(metadata)
|
||||
const canAddRule = Boolean(
|
||||
current?.uid &&
|
||||
current.option?.rules &&
|
||||
(targets.domain ||
|
||||
targets.process ||
|
||||
targets.source ||
|
||||
targets.destination),
|
||||
)
|
||||
const theme = useTheme()
|
||||
const chains = [...data.chains].reverse().join(' / ')
|
||||
const rule = rulePayload ? `${data.rule}(${rulePayload})` : data.rule
|
||||
@@ -105,7 +163,7 @@ const InnerConnectionDetail = ({ data, closed, onClose }: InnerProps) => {
|
||||
{ label: t('connections.components.fields.rule'), value: rule },
|
||||
{
|
||||
label: t('connections.components.fields.process'),
|
||||
value: `${metadata.process}${metadata.processPath ? `(${metadata.processPath})` : ''}`,
|
||||
value: `${metadata.process ?? ''}${metadata.processPath ? `(${metadata.processPath})` : ''}`,
|
||||
},
|
||||
{
|
||||
label: t('connections.components.fields.time'),
|
||||
@@ -132,7 +190,14 @@ const InnerConnectionDetail = ({ data, closed, onClose }: InnerProps) => {
|
||||
const onDelete = useLockFn(async () => closeConnection(data.id))
|
||||
|
||||
return (
|
||||
<Box sx={{ userSelect: 'text', color: theme.palette.text.secondary }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: '100%',
|
||||
minWidth: 0,
|
||||
userSelect: 'text',
|
||||
color: theme.palette.text.secondary,
|
||||
}}
|
||||
>
|
||||
{information.map((each) => (
|
||||
<div key={each.label}>
|
||||
<b>{each.label}</b>
|
||||
@@ -147,8 +212,32 @@ const InnerConnectionDetail = ({ data, closed, onClose }: InnerProps) => {
|
||||
</div>
|
||||
))}
|
||||
|
||||
{!closed && (
|
||||
<Box sx={{ textAlign: 'right' }}>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
justifyContent: 'flex-end',
|
||||
gap: 1,
|
||||
flexWrap: 'wrap',
|
||||
mt: 1,
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
variant="outlined"
|
||||
disabled={!canAddRule}
|
||||
onClick={() => {
|
||||
if (!current?.uid || !current.option?.rules) return
|
||||
onAddRule({
|
||||
metadata: { ...metadata },
|
||||
profileUid: current.uid,
|
||||
profileName: current.name || current.uid,
|
||||
rulesUid: current.option.rules,
|
||||
preferredKind,
|
||||
})
|
||||
}}
|
||||
>
|
||||
{t('connections.ruleDialog.entry')}
|
||||
</Button>
|
||||
{!closed && (
|
||||
<Button
|
||||
variant="contained"
|
||||
title={t('connections.components.actions.closeConnection')}
|
||||
@@ -159,6 +248,18 @@ const InnerConnectionDetail = ({ data, closed, onClose }: InnerProps) => {
|
||||
>
|
||||
{t('connections.components.actions.closeConnection')}
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
{!canAddRule && (
|
||||
<Box sx={{ mt: 1, typography: 'caption' }}>
|
||||
{t(
|
||||
targets.domain ||
|
||||
targets.process ||
|
||||
targets.source ||
|
||||
targets.destination
|
||||
? 'connections.ruleDialog.noProfile'
|
||||
: 'connections.ruleDialog.noMetadata',
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
@@ -7,11 +7,12 @@ import { closeConnection } from 'tauri-plugin-mihomo-api'
|
||||
|
||||
import { RelativeTime } from './connection-relative-time'
|
||||
import type { ConnectionRowView } from './connection-row-view'
|
||||
import type { ConnectionRuleKind } from './connection-rule'
|
||||
|
||||
interface Props {
|
||||
row: ConnectionRowView
|
||||
closed: boolean
|
||||
onShowDetail: (id: string) => void
|
||||
onShowDetail: (id: string, preferredKind?: ConnectionRuleKind) => void
|
||||
}
|
||||
|
||||
const tagStyle = {
|
||||
@@ -86,7 +87,17 @@ export const ConnectionRowItem = memo(
|
||||
<div style={tagsStyle}>
|
||||
<span style={tagStyle}>{row.network}</span>
|
||||
<span style={tagStyle}>{row.type}</span>
|
||||
{row.process && <span style={tagStyle}>{row.process}</span>}
|
||||
{row.process && (
|
||||
<span
|
||||
style={tagStyle}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onShowDetail(row.id, 'process')
|
||||
}}
|
||||
>
|
||||
{row.process}
|
||||
</span>
|
||||
)}
|
||||
{row.chains && <span style={tagStyle}>{row.chains}</span>}
|
||||
<span style={tagStyle}>
|
||||
<RelativeTime start={row.time} />
|
||||
|
||||
@@ -0,0 +1,525 @@
|
||||
import {
|
||||
Alert,
|
||||
Autocomplete,
|
||||
Box,
|
||||
Button,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
FormControlLabel,
|
||||
MenuItem,
|
||||
Radio,
|
||||
RadioGroup,
|
||||
TextField,
|
||||
Typography,
|
||||
} from '@mui/material'
|
||||
import { useLockFn } from 'ahooks'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import {
|
||||
useClashConfigData,
|
||||
useProxiesData,
|
||||
} from '@/providers/app-data-context'
|
||||
import { getProfiles, readProfileFile, saveProfileFile } from '@/services/cmds'
|
||||
import { mutate } from '@/services/mutate'
|
||||
import { showNotice } from '@/services/notice-service'
|
||||
|
||||
import {
|
||||
getConnectionIPRule,
|
||||
getConnectionRuleTargets,
|
||||
getConnectionRules,
|
||||
getConnectionRootDomain,
|
||||
isConnectionRuleDomain,
|
||||
findConnectionRule,
|
||||
saveConnectionRule,
|
||||
type ConnectionRuleKind,
|
||||
} from './connection-rule'
|
||||
|
||||
export interface ConnectionRuleTarget {
|
||||
metadata: IConnectionsItem['metadata']
|
||||
profileUid: string
|
||||
profileName: string
|
||||
rulesUid: string
|
||||
preferredKind: ConnectionRuleKind
|
||||
}
|
||||
|
||||
type DomainScope = 'DOMAIN' | 'DOMAIN-SUFFIX' | 'ROOT-DOMAIN'
|
||||
|
||||
function getInitialKind(target: ConnectionRuleTarget) {
|
||||
const targets = getConnectionRuleTargets(target.metadata)
|
||||
return targets[target.preferredKind]
|
||||
? target.preferredKind
|
||||
: ((['domain', 'process', 'source', 'destination'] as const).find(
|
||||
(kind) => targets[kind],
|
||||
) ?? 'domain')
|
||||
}
|
||||
|
||||
export function ConnectionRuleDialog({
|
||||
target,
|
||||
onClose,
|
||||
}: {
|
||||
target: ConnectionRuleTarget
|
||||
onClose: () => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const { proxyView } = useProxiesData()
|
||||
const { clashConfig } = useClashConfigData()
|
||||
const targets = getConnectionRuleTargets(target.metadata)
|
||||
const [rootDomain, setRootDomain] = useState<string>()
|
||||
const [kind, setKind] = useState<ConnectionRuleKind>(() =>
|
||||
getInitialKind(target),
|
||||
)
|
||||
const [policy, setPolicy] = useState<string | null>(null)
|
||||
const [scope, setScope] = useState<DomainScope>('DOMAIN')
|
||||
const [matchingInput, setMatchingInput] = useState(
|
||||
() => targets[getInitialKind(target)]?.value ?? '',
|
||||
)
|
||||
const [rules, setRules] = useState<string[] | null>(null)
|
||||
const [loadAttempt, setLoadAttempt] = useState(0)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const selected = targets[kind]
|
||||
const matchingRoot = kind === 'domain' && scope === 'ROOT-DOMAIN'
|
||||
const editingDomain = kind === 'domain' && scope === 'DOMAIN-SUFFIX'
|
||||
const editingIP = kind === 'source' || kind === 'destination'
|
||||
const matchingValue = matchingRoot
|
||||
? (rootDomain ?? '')
|
||||
: editingDomain || editingIP
|
||||
? matchingInput
|
||||
: (selected?.value ?? '')
|
||||
const invalidDomain =
|
||||
editingDomain &&
|
||||
!isConnectionRuleDomain(matchingInput, targets.domain?.value ?? '')
|
||||
const ipRule = editingIP
|
||||
? getConnectionIPRule(matchingInput, kind === 'source')
|
||||
: undefined
|
||||
const invalidIP = editingIP && !ipRule
|
||||
const invalidValue = invalidDomain || invalidIP
|
||||
const condition = editingIP
|
||||
? ipRule
|
||||
: selected
|
||||
? {
|
||||
type:
|
||||
kind === 'domain' && scope !== 'DOMAIN'
|
||||
? 'DOMAIN-SUFFIX'
|
||||
: selected.type,
|
||||
value: kind === 'domain' ? matchingValue.trim() : selected.value,
|
||||
}
|
||||
: undefined
|
||||
const existing =
|
||||
rules && condition && !invalidValue
|
||||
? findConnectionRule(rules, condition)
|
||||
: undefined
|
||||
const modifying = Boolean(existing)
|
||||
const groups = proxyView
|
||||
? proxyView.groups.length || !proxyView.global
|
||||
? proxyView.groups
|
||||
: [proxyView.global]
|
||||
: []
|
||||
const policies = [
|
||||
...new Set(['DIRECT', 'REJECT', ...groups.map((group) => group.name)]),
|
||||
]
|
||||
|
||||
const kindLabels = {
|
||||
domain: t('connections.ruleDialog.domain'),
|
||||
process: t('connections.components.fields.process'),
|
||||
source: t('connections.ruleDialog.sourceIp'),
|
||||
destination: t('connections.ruleDialog.destinationIp'),
|
||||
}
|
||||
|
||||
const unavailablePolicy = Boolean(policy && !policies.includes(policy))
|
||||
const blocked = loading || saving || rules === null
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
const ruleTargets = getConnectionRuleTargets(target.metadata)
|
||||
Promise.all([
|
||||
readProfileFile(target.rulesUid),
|
||||
ruleTargets.domain
|
||||
? getConnectionRootDomain(ruleTargets.domain.value)
|
||||
: undefined,
|
||||
])
|
||||
.then(([content, root]) => {
|
||||
const loadedRules = getConnectionRules(content)
|
||||
const initialKind = getInitialKind(target)
|
||||
const selectedTarget = ruleTargets[initialKind]
|
||||
const initial = selectedTarget
|
||||
? (findConnectionRule(loadedRules, selectedTarget) ??
|
||||
(initialKind === 'domain'
|
||||
? findConnectionRule(loadedRules, {
|
||||
...selectedTarget,
|
||||
type: 'DOMAIN-SUFFIX',
|
||||
})
|
||||
: undefined))
|
||||
: undefined
|
||||
if (cancelled) return
|
||||
setRootDomain(root)
|
||||
setRules(loadedRules)
|
||||
setPolicy(initial?.policy ?? null)
|
||||
setScope(initial?.type === 'DOMAIN-SUFFIX' ? 'DOMAIN-SUFFIX' : 'DOMAIN')
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!cancelled)
|
||||
setError(err instanceof Error ? err.message : String(err))
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [target, loadAttempt])
|
||||
|
||||
const handleSave = useLockFn(async () => {
|
||||
if (
|
||||
blocked ||
|
||||
!condition ||
|
||||
invalidValue ||
|
||||
!policy ||
|
||||
!policies.includes(policy)
|
||||
)
|
||||
return
|
||||
if (/[\r\n,]/u.test(condition.value) || /[\r\n,]/u.test(policy)) {
|
||||
setError(t('connections.ruleDialog.unsupportedValue'))
|
||||
return
|
||||
}
|
||||
setSaving(true)
|
||||
setError('')
|
||||
try {
|
||||
const result = await mutate(
|
||||
async () => {
|
||||
const checkProfile = async () => {
|
||||
const profiles = await getProfiles()
|
||||
const current = profiles.items?.find(
|
||||
(item) => item.uid === profiles.current,
|
||||
)
|
||||
if (
|
||||
profiles.current !== target.profileUid ||
|
||||
current?.option?.rules !== target.rulesUid
|
||||
) {
|
||||
throw new Error(t('connections.ruleDialog.profileChanged'))
|
||||
}
|
||||
}
|
||||
await checkProfile()
|
||||
const content = await readProfileFile(target.rulesUid)
|
||||
const updated = saveConnectionRule(content, condition, policy)
|
||||
await checkProfile()
|
||||
return saveProfileFile(target.rulesUid, updated)
|
||||
},
|
||||
{ id: `save-profile-file:${target.rulesUid}`, errorNotice: false },
|
||||
)
|
||||
if (!result.ok || !result.value) {
|
||||
setError(t('connections.ruleDialog.applyFailed'))
|
||||
return
|
||||
}
|
||||
showNotice.success('connections.ruleDialog.saved')
|
||||
onClose()
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<Dialog open onClose={saving ? undefined : onClose} fullWidth maxWidth="sm">
|
||||
<DialogTitle>
|
||||
{t(
|
||||
modifying
|
||||
? 'connections.ruleDialog.modifyTitle'
|
||||
: 'connections.ruleDialog.title',
|
||||
)}
|
||||
</DialogTitle>
|
||||
<DialogContent>
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 1 }}>
|
||||
<TextField
|
||||
select
|
||||
fullWidth
|
||||
size="small"
|
||||
label={t('connections.ruleDialog.matchBy')}
|
||||
value={kind}
|
||||
disabled={blocked}
|
||||
onChange={(event) => {
|
||||
const next = event.target.value as ConnectionRuleKind
|
||||
const nextTarget = targets[next]
|
||||
const rule =
|
||||
rules && nextTarget
|
||||
? (findConnectionRule(rules, nextTarget) ??
|
||||
(next === 'domain'
|
||||
? findConnectionRule(rules, {
|
||||
...nextTarget,
|
||||
type: 'DOMAIN-SUFFIX',
|
||||
})
|
||||
: undefined))
|
||||
: undefined
|
||||
setMatchingInput(nextTarget?.value ?? '')
|
||||
setKind(next)
|
||||
setPolicy(rule?.policy ?? null)
|
||||
setScope(
|
||||
rule?.type === 'DOMAIN-SUFFIX' ? 'DOMAIN-SUFFIX' : 'DOMAIN',
|
||||
)
|
||||
}}
|
||||
>
|
||||
{(['domain', 'process', 'source', 'destination'] as const).map(
|
||||
(option) => (
|
||||
<MenuItem
|
||||
key={option}
|
||||
value={option}
|
||||
disabled={!targets[option]}
|
||||
>
|
||||
{kindLabels[option]}
|
||||
{!targets[option] &&
|
||||
` · ${t('connections.ruleDialog.unavailable')}`}
|
||||
</MenuItem>
|
||||
),
|
||||
)}
|
||||
</TextField>
|
||||
{kind === 'process' ? (
|
||||
<>
|
||||
{target.metadata.process?.trim() && (
|
||||
<TextField
|
||||
fullWidth
|
||||
size="small"
|
||||
label={kindLabels.process}
|
||||
value={target.metadata.process}
|
||||
slotProps={{
|
||||
input: { readOnly: true },
|
||||
htmlInput: { title: target.metadata.process },
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{selected?.type === 'PROCESS-PATH' && (
|
||||
<TextField
|
||||
fullWidth
|
||||
size="small"
|
||||
label={t('connections.ruleDialog.fullPath')}
|
||||
value={selected.value}
|
||||
slotProps={{
|
||||
input: { readOnly: true },
|
||||
htmlInput: { title: selected.value },
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<TextField
|
||||
fullWidth
|
||||
size="small"
|
||||
label={
|
||||
editingDomain || matchingRoot
|
||||
? t('connections.ruleDialog.matchingDomain')
|
||||
: kindLabels[kind]
|
||||
}
|
||||
value={matchingValue}
|
||||
disabled={(editingDomain || editingIP) && blocked}
|
||||
onChange={(event) => {
|
||||
const value = event.target.value
|
||||
setMatchingInput(value)
|
||||
const nextCondition = editingIP
|
||||
? getConnectionIPRule(value, kind === 'source')
|
||||
: isConnectionRuleDomain(value, targets.domain?.value ?? '')
|
||||
? { type: 'DOMAIN-SUFFIX', value: value.trim() }
|
||||
: undefined
|
||||
const match =
|
||||
rules && nextCondition
|
||||
? findConnectionRule(rules, nextCondition)
|
||||
: undefined
|
||||
if (match) setPolicy(match.policy)
|
||||
}}
|
||||
error={invalidValue}
|
||||
helperText={
|
||||
editingDomain || matchingRoot ? (
|
||||
<>
|
||||
{t('connections.ruleDialog.connectionHost', {
|
||||
host: targets.domain?.value,
|
||||
})}
|
||||
{invalidDomain && (
|
||||
<>
|
||||
<br />
|
||||
{t('connections.ruleDialog.invalidDomain')}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
) : invalidIP ? (
|
||||
t('connections.ruleDialog.invalidIp')
|
||||
) : undefined
|
||||
}
|
||||
slotProps={{
|
||||
input: { readOnly: !editingDomain && !editingIP },
|
||||
htmlInput: {
|
||||
title: condition?.value,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
{kind === 'domain' && (
|
||||
<RadioGroup
|
||||
row
|
||||
aria-label={t('connections.ruleDialog.domainScope')}
|
||||
value={scope}
|
||||
onChange={(_, value) => {
|
||||
const nextScope = value as DomainScope
|
||||
setScope(nextScope)
|
||||
setMatchingInput(targets.domain?.value ?? '')
|
||||
const match =
|
||||
rules && targets.domain
|
||||
? findConnectionRule(rules, {
|
||||
type: nextScope === 'DOMAIN' ? 'DOMAIN' : 'DOMAIN-SUFFIX',
|
||||
value:
|
||||
nextScope === 'ROOT-DOMAIN'
|
||||
? (rootDomain ?? '')
|
||||
: targets.domain.value,
|
||||
})
|
||||
: undefined
|
||||
setPolicy(match?.policy ?? null)
|
||||
}}
|
||||
sx={{ mt: 0.5 }}
|
||||
>
|
||||
<FormControlLabel
|
||||
value="DOMAIN"
|
||||
control={<Radio size="small" />}
|
||||
disabled={blocked}
|
||||
label={t('connections.ruleDialog.exactDomain')}
|
||||
/>
|
||||
<FormControlLabel
|
||||
value="DOMAIN-SUFFIX"
|
||||
control={<Radio size="small" />}
|
||||
disabled={blocked}
|
||||
label={t('connections.ruleDialog.allSubdomains')}
|
||||
/>
|
||||
{rootDomain &&
|
||||
rootDomain.toLowerCase() !==
|
||||
targets.domain?.value.toLowerCase() && (
|
||||
<FormControlLabel
|
||||
value="ROOT-DOMAIN"
|
||||
control={<Radio size="small" />}
|
||||
disabled={blocked}
|
||||
label={t('connections.ruleDialog.rootDomain', {
|
||||
domain: rootDomain,
|
||||
})}
|
||||
/>
|
||||
)}
|
||||
</RadioGroup>
|
||||
)}
|
||||
{(kind === 'source' || kind === 'destination') && (
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
|
||||
{t(
|
||||
kind === 'source'
|
||||
? 'connections.ruleDialog.sourceHint'
|
||||
: 'connections.ruleDialog.destinationHint',
|
||||
)}
|
||||
</Typography>
|
||||
)}
|
||||
{kind === 'process' && (
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
|
||||
{selected?.type === 'PROCESS-PATH'
|
||||
? t('connections.ruleDialog.processPathHint')
|
||||
: t('connections.ruleDialog.processNameHint')}
|
||||
</Typography>
|
||||
)}
|
||||
<Autocomplete
|
||||
size="small"
|
||||
options={
|
||||
unavailablePolicy && policy ? [policy, ...policies] : policies
|
||||
}
|
||||
getOptionLabel={(value) =>
|
||||
value === 'DIRECT'
|
||||
? t('proxies.components.enums.policies.DIRECT')
|
||||
: value === 'REJECT'
|
||||
? t('proxies.components.enums.policies.REJECT')
|
||||
: value
|
||||
}
|
||||
getOptionDisabled={(value) => !policies.includes(value)}
|
||||
value={policy}
|
||||
onChange={(_, value) => setPolicy(value)}
|
||||
disabled={blocked}
|
||||
loading={loading}
|
||||
renderInput={(params) => (
|
||||
<TextField
|
||||
{...params}
|
||||
label={t('rules.modals.editor.form.labels.proxyPolicy')}
|
||||
margin="normal"
|
||||
error={unavailablePolicy}
|
||||
helperText={
|
||||
unavailablePolicy
|
||||
? t('connections.ruleDialog.policyUnavailable')
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{clashConfig && clashConfig.mode !== 'rule' && (
|
||||
<Alert severity="info" sx={{ mt: 2 }}>
|
||||
{t('connections.ruleDialog.ruleModeHint')}
|
||||
</Alert>
|
||||
)}
|
||||
{error && (
|
||||
<Box sx={{ mt: 2 }}>
|
||||
<Alert severity="error">
|
||||
{error}
|
||||
{rules === null && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
setLoadAttempt((attempt) => attempt + 1)
|
||||
}}
|
||||
>
|
||||
{t('shared.actions.retry')}
|
||||
</Button>
|
||||
)}
|
||||
</Alert>
|
||||
</Box>
|
||||
)}
|
||||
<Typography
|
||||
variant="caption"
|
||||
color="text.secondary"
|
||||
sx={{ display: 'block', mt: 2, overflowWrap: 'anywhere' }}
|
||||
>
|
||||
{t(
|
||||
modifying
|
||||
? 'connections.ruleDialog.editDestination'
|
||||
: 'connections.ruleDialog.destination',
|
||||
{
|
||||
name: target.profileName,
|
||||
},
|
||||
)}
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="caption"
|
||||
color="text.secondary"
|
||||
sx={{ display: 'block' }}
|
||||
>
|
||||
{t('connections.ruleDialog.newConnections')}
|
||||
</Typography>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button disabled={saving} onClick={onClose}>
|
||||
{t('shared.actions.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
loading={saving}
|
||||
disabled={
|
||||
blocked ||
|
||||
!condition ||
|
||||
invalidValue ||
|
||||
!policy ||
|
||||
!policies.includes(policy)
|
||||
}
|
||||
onClick={handleSave}
|
||||
>
|
||||
{t(
|
||||
modifying
|
||||
? 'connections.ruleDialog.saveAndApply'
|
||||
: 'connections.ruleDialog.addAndApply',
|
||||
)}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { dump, loadAll } from 'js-yaml'
|
||||
import isFQDN from 'validator/es/lib/isFQDN'
|
||||
import isIP from 'validator/es/lib/isIP'
|
||||
import isIPRange from 'validator/es/lib/isIPRange'
|
||||
|
||||
export type ConnectionRuleKind = 'domain' | 'process' | 'source' | 'destination'
|
||||
|
||||
function getAddressRule(address: string | undefined, source: boolean) {
|
||||
const ip = address?.trim()
|
||||
if (!ip || !isIP(ip)) return undefined
|
||||
return getConnectionIPRule(`${ip}/${isIP(ip, 4) ? 32 : 128}`, source)
|
||||
}
|
||||
|
||||
export function getConnectionIPRule(value: string, source: boolean) {
|
||||
const cidr = value.trim()
|
||||
if (cidr.includes('%') || !isIPRange(cidr)) return undefined
|
||||
const ipv4 = isIP(cidr.split('/')[0], 4)
|
||||
return {
|
||||
type: source ? 'SRC-IP-CIDR' : ipv4 ? 'IP-CIDR' : 'IP-CIDR6',
|
||||
value: cidr,
|
||||
}
|
||||
}
|
||||
|
||||
export function getConnectionRuleTargets(
|
||||
metadata: Pick<
|
||||
IConnectionsItem['metadata'],
|
||||
| 'host'
|
||||
| 'process'
|
||||
| 'processPath'
|
||||
| 'sourceIP'
|
||||
| 'destinationIP'
|
||||
| 'remoteDestination'
|
||||
>,
|
||||
) {
|
||||
const host = metadata.host?.trim() ?? ''
|
||||
const path = metadata.processPath
|
||||
const name = metadata.process
|
||||
const domain =
|
||||
host && !isIP(host) && isFQDN(host, { require_tld: false })
|
||||
? { type: 'DOMAIN', value: host }
|
||||
: undefined
|
||||
const process = path?.trim()
|
||||
? { type: 'PROCESS-PATH', value: path }
|
||||
: name?.trim()
|
||||
? { type: 'PROCESS-NAME', value: name }
|
||||
: undefined
|
||||
const source = getAddressRule(metadata.sourceIP, true)
|
||||
const destination =
|
||||
getAddressRule(metadata.destinationIP, false) ??
|
||||
getAddressRule(metadata.remoteDestination, false)
|
||||
return { domain, process, source, destination }
|
||||
}
|
||||
|
||||
export function isConnectionRuleDomain(value: string, host: string) {
|
||||
const domain = value.trim()
|
||||
if (!domain || isIP(domain) || !isFQDN(domain, { require_tld: false }))
|
||||
return false
|
||||
const normalized = domain.toLowerCase()
|
||||
const current = host.toLowerCase()
|
||||
return (
|
||||
normalized === current ||
|
||||
(domain.split('.').length >= 2 && current.endsWith(`.${normalized}`))
|
||||
)
|
||||
}
|
||||
|
||||
export async function getConnectionRootDomain(host: string) {
|
||||
const { parse } = await import('tldts')
|
||||
const { domain, isIcann, isPrivate } = parse(host, {
|
||||
allowPrivateDomains: true,
|
||||
})
|
||||
return domain && (isIcann || isPrivate) ? domain : undefined
|
||||
}
|
||||
|
||||
function parseRuleExtension(content: string) {
|
||||
const documents = loadAll(content)
|
||||
if (documents.length > 1) {
|
||||
throw new Error('The rule extension must contain a single YAML document.')
|
||||
}
|
||||
const parsed = documents[0]
|
||||
if (
|
||||
parsed !== undefined &&
|
||||
parsed !== null &&
|
||||
(typeof parsed !== 'object' ||
|
||||
Array.isArray(parsed) ||
|
||||
Object.getPrototypeOf(parsed) !== Object.prototype)
|
||||
) {
|
||||
throw new Error('The rule extension must be a YAML mapping.')
|
||||
}
|
||||
const config = (parsed ?? {}) as Record<string, unknown>
|
||||
for (const key of ['prepend', 'append', 'delete']) {
|
||||
const sequence = config[key]
|
||||
if (
|
||||
sequence != null &&
|
||||
(!Array.isArray(sequence) ||
|
||||
sequence.some((item) => typeof item !== 'string'))
|
||||
) {
|
||||
throw new Error('The rule extension contains an invalid rule list.')
|
||||
}
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
interface RuleCondition {
|
||||
type: string
|
||||
value: string
|
||||
}
|
||||
|
||||
function matchesConnectionRule(raw: string, target: RuleCondition) {
|
||||
const parts = raw.split(',').map((part) => part.trim())
|
||||
const hasNoResolve =
|
||||
(target.type === 'IP-CIDR' || target.type === 'IP-CIDR6') &&
|
||||
parts.length === 4 &&
|
||||
parts[3] === 'no-resolve'
|
||||
if (parts.length !== 3 && !hasNoResolve) return false
|
||||
if (target.type === 'DOMAIN' || target.type === 'DOMAIN-SUFFIX') {
|
||||
return (
|
||||
parts[0] === target.type &&
|
||||
parts[1].toLowerCase() === target.value.toLowerCase()
|
||||
)
|
||||
}
|
||||
return parts[0] === target.type && parts[1] === target.value
|
||||
}
|
||||
|
||||
export function getConnectionRules(content: string): string[] {
|
||||
const config = parseRuleExtension(content)
|
||||
return [
|
||||
...((config.prepend ?? []) as string[]),
|
||||
...((config.append ?? []) as string[]),
|
||||
]
|
||||
}
|
||||
|
||||
export function findConnectionRule(rules: string[], target: RuleCondition) {
|
||||
for (const raw of rules) {
|
||||
if (matchesConnectionRule(raw, target)) {
|
||||
const [type, , policy] = raw.split(',').map((part) => part.trim())
|
||||
return { type, policy }
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function saveConnectionRule(
|
||||
content: string,
|
||||
target: RuleCondition,
|
||||
policy: string,
|
||||
): string {
|
||||
const config = parseRuleExtension(content)
|
||||
const rule = `${target.type},${target.value},${policy}`
|
||||
let replaced = false
|
||||
for (const key of ['prepend', 'append']) {
|
||||
if (!Array.isArray(config[key])) continue
|
||||
config[key] = (config[key] as string[]).flatMap((raw) => {
|
||||
if (!matchesConnectionRule(raw, target)) return [raw]
|
||||
if (replaced) return []
|
||||
replaced = true
|
||||
return [raw.split(',').length === 4 ? `${rule},no-resolve` : rule]
|
||||
})
|
||||
}
|
||||
if (!replaced) {
|
||||
config.prepend = [rule, ...((config.prepend ?? []) as string[])]
|
||||
}
|
||||
return dump(config, { forceQuotes: true })
|
||||
}
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
getConnectionStartTime,
|
||||
getConnectionTypeLabel,
|
||||
} from './connection-row-view'
|
||||
import type { ConnectionRuleKind } from './connection-rule'
|
||||
|
||||
const ROW_HEIGHT = 40
|
||||
const RESIZE_HANDLE_WIDTH = 6
|
||||
@@ -257,7 +258,7 @@ const renderCell = (
|
||||
interface RowComponentProps {
|
||||
row: IConnectionsItem
|
||||
columns: DisplayColumn[]
|
||||
onShowDetail: (id: string) => void
|
||||
onShowDetail: (id: string, preferredKind?: ConnectionRuleKind) => void
|
||||
getSnapshot: (row: IConnectionsItem) => TableRowSnapshot
|
||||
borderColor: string
|
||||
virtualTop: number
|
||||
@@ -273,7 +274,22 @@ const RowComponent = memo(
|
||||
virtualTop,
|
||||
}: RowComponentProps) {
|
||||
const handleClick = useCallback(
|
||||
() => onShowDetail(row.id),
|
||||
(event: ReactMouseEvent<HTMLDivElement>) => {
|
||||
const field =
|
||||
event.target instanceof Element
|
||||
? event.target.closest<HTMLElement>('[data-connection-field]')
|
||||
?.dataset.connectionField
|
||||
: undefined
|
||||
const preferredKind =
|
||||
field === 'process'
|
||||
? 'process'
|
||||
: field === 'source'
|
||||
? 'source'
|
||||
: field === 'remoteDestination'
|
||||
? 'destination'
|
||||
: 'domain'
|
||||
onShowDetail(row.id, preferredKind)
|
||||
},
|
||||
[onShowDetail, row.id],
|
||||
)
|
||||
const snapshot = getSnapshot(row)
|
||||
@@ -295,6 +311,7 @@ const RowComponent = memo(
|
||||
{columns.map((column) => (
|
||||
<div
|
||||
key={column.field}
|
||||
data-connection-field={column.field}
|
||||
style={{
|
||||
boxSizing: 'border-box',
|
||||
flex: `0 0 ${column.size}px`,
|
||||
@@ -328,7 +345,7 @@ const RowComponent = memo(
|
||||
|
||||
interface Props {
|
||||
connections: IConnectionsItem[]
|
||||
onShowDetail: (id: string) => void
|
||||
onShowDetail: (id: string, preferredKind?: ConnectionRuleKind) => void
|
||||
columnManagerOpen: boolean
|
||||
onCloseColumnManager: () => void
|
||||
}
|
||||
@@ -343,7 +360,8 @@ export const ConnectionTable = (props: Props) => {
|
||||
const onShowDetailRef = useRef(rawOnShowDetail)
|
||||
onShowDetailRef.current = rawOnShowDetail
|
||||
const onShowDetail = useCallback(
|
||||
(id: string) => onShowDetailRef.current(id),
|
||||
(id: string, preferredKind?: ConnectionRuleKind) =>
|
||||
onShowDetailRef.current(id, preferredKind),
|
||||
[],
|
||||
)
|
||||
const { t } = useTranslation()
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
useEffectEvent,
|
||||
useImperativeHandle,
|
||||
useMemo,
|
||||
useReducer,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react'
|
||||
@@ -20,7 +19,6 @@ import {
|
||||
formatTrafficHourMinute,
|
||||
formatTrafficMinuteSecond,
|
||||
formatTrafficName,
|
||||
isSameTrafficData,
|
||||
} from '@/utils/traffic-sampler'
|
||||
|
||||
export interface EnhancedCanvasTrafficGraphRef {
|
||||
@@ -74,16 +72,200 @@ const GRAPH_CONFIG = {
|
||||
|
||||
const STALE_DATA_THRESHOLD = 2500 // ms without fresh data => drop FPS
|
||||
|
||||
// Static sx/style identities keep the emotion cache effective; the remaining
|
||||
// dynamic props (tooltip position, legend colors) stay inline or memoized.
|
||||
const rootSx = {
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
position: 'relative',
|
||||
bgcolor: 'action.hover',
|
||||
borderRadius: 1,
|
||||
cursor: 'pointer',
|
||||
overflow: 'hidden',
|
||||
}
|
||||
|
||||
const canvasStyle = {
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
display: 'block',
|
||||
} as const
|
||||
|
||||
const hoverCanvasStyle = {
|
||||
position: 'absolute',
|
||||
inset: 0,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
display: 'block',
|
||||
pointerEvents: 'none',
|
||||
} as const
|
||||
|
||||
const overlaySx = {
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
pointerEvents: 'none',
|
||||
}
|
||||
|
||||
const timeRangeBadgeSx = {
|
||||
position: 'absolute',
|
||||
top: 6,
|
||||
left: 40,
|
||||
fontSize: '11px',
|
||||
fontWeight: 'bold',
|
||||
color: 'text.secondary',
|
||||
cursor: 'pointer',
|
||||
pointerEvents: 'all',
|
||||
px: 1,
|
||||
py: 0.5,
|
||||
borderRadius: 0.5,
|
||||
bgcolor: 'rgba(0,0,0,0.05)',
|
||||
'&:hover': {
|
||||
bgcolor: 'rgba(0,0,0,0.1)',
|
||||
},
|
||||
}
|
||||
|
||||
const legendsSx = {
|
||||
position: 'absolute',
|
||||
top: 6,
|
||||
right: 8,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 0.5,
|
||||
}
|
||||
|
||||
const chartStyleHintSx = {
|
||||
position: 'absolute',
|
||||
bottom: 6,
|
||||
right: 8,
|
||||
fontSize: '10px',
|
||||
color: 'text.disabled',
|
||||
opacity: 0.7,
|
||||
}
|
||||
|
||||
const diagnosticsSx = {
|
||||
position: 'absolute',
|
||||
bottom: 6,
|
||||
left: 8,
|
||||
fontSize: '9px',
|
||||
color: 'text.disabled',
|
||||
opacity: 0.6,
|
||||
lineHeight: 1.2,
|
||||
}
|
||||
|
||||
const tooltipTimeSx = { color: 'text.secondary', mb: 0.2 }
|
||||
const tooltipUpSx = { color: 'secondary.main', fontWeight: 500 }
|
||||
const tooltipDownSx = { color: 'primary.main', fontWeight: 500 }
|
||||
|
||||
interface TimeDisplayStrategy {
|
||||
maxLabels: number
|
||||
formatTime: (timestamp: number) => string
|
||||
intervalSeconds: number
|
||||
minPixelDistance: number
|
||||
}
|
||||
|
||||
const TIME_DISPLAY_STRATEGIES: Record<TimeRange, TimeDisplayStrategy> = {
|
||||
1: {
|
||||
maxLabels: 6,
|
||||
formatTime: formatTrafficMinuteSecond,
|
||||
intervalSeconds: 10,
|
||||
minPixelDistance: 35,
|
||||
},
|
||||
5: {
|
||||
maxLabels: 6,
|
||||
formatTime: formatTrafficHourMinute,
|
||||
intervalSeconds: 30,
|
||||
minPixelDistance: 38,
|
||||
},
|
||||
10: {
|
||||
maxLabels: 8,
|
||||
formatTime: formatTrafficHourMinute,
|
||||
intervalSeconds: 60,
|
||||
minPixelDistance: 40,
|
||||
},
|
||||
}
|
||||
|
||||
// Per-draw buffers live at module scope: drawing runs synchronously on the
|
||||
// main thread, so slots never overlap a concurrent reader.
|
||||
const yAxisTicks = [
|
||||
{ label: '', y: 0 },
|
||||
{ label: '', y: 0 },
|
||||
{ label: '', y: 0 },
|
||||
]
|
||||
const yAxisTickLabels = new Map<number, string>()
|
||||
const formatYAxisTickLabel = (bytes: number): string => {
|
||||
const cached = yAxisTickLabels.get(bytes)
|
||||
if (cached !== undefined) return cached
|
||||
|
||||
const label =
|
||||
bytes === 0
|
||||
? '0'
|
||||
: bytes < 1024
|
||||
? `${Math.round(bytes)}B`
|
||||
: bytes < 1024 * 1024
|
||||
? `${Math.round(bytes / 1024)}KB`
|
||||
: `${(bytes / (1024 * 1024)).toFixed(1)}MB`
|
||||
if (yAxisTickLabels.size >= 256) yAxisTickLabels.clear()
|
||||
yAxisTickLabels.set(bytes, label)
|
||||
return label
|
||||
}
|
||||
|
||||
const getYAxisTicks = (
|
||||
topValue: number,
|
||||
bottomValue: number,
|
||||
height: number,
|
||||
) => {
|
||||
const padding = GRAPH_CONFIG.padding
|
||||
|
||||
const topY = padding.top + 10
|
||||
const bottomY = height - padding.bottom - 5
|
||||
const middleY = (topY + bottomY) / 2
|
||||
const middleValue = (bottomValue + topValue) / 2
|
||||
|
||||
const [bottomTick, middleTick, topTick] = yAxisTicks
|
||||
bottomTick.label = formatYAxisTickLabel(bottomValue)
|
||||
bottomTick.y = bottomY
|
||||
middleTick.label = formatYAxisTickLabel(middleValue)
|
||||
middleTick.y = middleY
|
||||
topTick.label = formatYAxisTickLabel(topValue)
|
||||
topTick.y = topY
|
||||
|
||||
return yAxisTicks
|
||||
}
|
||||
|
||||
interface TimeAxisPoint {
|
||||
x: number
|
||||
label: string
|
||||
}
|
||||
const timeAxisPoints: TimeAxisPoint[] = []
|
||||
const resetTimeAxisPoints = () => {
|
||||
timeAxisPoints.length = 0
|
||||
}
|
||||
const pushTimeAxisPoint = (x: number, label: string) => {
|
||||
let slot = timeAxisPoints[timeAxisPoints.length]
|
||||
if (!slot) {
|
||||
slot = { x: 0, label: '' }
|
||||
timeAxisPoints.push(slot)
|
||||
}
|
||||
slot.x = x
|
||||
slot.label = label
|
||||
}
|
||||
|
||||
// Gradient stop strings are pure functions of the theme color; the colors
|
||||
// memo builds them once per theme.
|
||||
const GRADIENT_ALPHA_HEX = Math.round(GRAPH_CONFIG.alpha.gradient * 255)
|
||||
.toString(16)
|
||||
.padStart(2, '0')
|
||||
const makeGradientStops = (color: string) => ({
|
||||
start: `${color}${GRADIENT_ALPHA_HEX}`,
|
||||
end: `${color}00`,
|
||||
})
|
||||
|
||||
interface EnhancedCanvasTrafficGraphProps {
|
||||
ref?: Ref<EnhancedCanvasTrafficGraphRef>
|
||||
}
|
||||
|
||||
const displayDataReducer = (
|
||||
current: ITrafficDataPoint[],
|
||||
payload: ITrafficDataPoint[],
|
||||
): ITrafficDataPoint[] =>
|
||||
isSameTrafficData(current, payload) ? current : payload
|
||||
|
||||
export const EnhancedCanvasTrafficGraph = memo(
|
||||
function EnhancedCanvasTrafficGraph({
|
||||
ref,
|
||||
@@ -94,11 +276,9 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
const pause_render_traffic_stats_on_blur =
|
||||
verge.verge?.pause_render_traffic_stats_on_blur ?? true
|
||||
|
||||
const { dataPoints, requestRange, samplerStats } =
|
||||
useTrafficGraphDataEnhanced()
|
||||
|
||||
const [timeRange, setTimeRange] = useState<TimeRange>(10)
|
||||
const [chartStyle, setChartStyle] = useState<'bezier' | 'line'>('bezier')
|
||||
const [badgeStats, setBadgeStats] = useState({ points: 0, compressed: 0 })
|
||||
|
||||
const initialFocusState =
|
||||
typeof document !== 'undefined' ? !document.hidden : true
|
||||
@@ -129,66 +309,49 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
const lastDataTimestampRef = useRef<number>(0)
|
||||
const dataStaleRef = useRef<boolean>(false)
|
||||
|
||||
const [displayData, dispatchDisplayData] = useReducer(
|
||||
displayDataReducer,
|
||||
[],
|
||||
)
|
||||
const debounceTimeoutRef = useRef<number | null>(null)
|
||||
// Live snapshot data for the rAF draw path; React state only tracks the
|
||||
// diagnostics badge inputs so steady-state snapshots stop re-rendering.
|
||||
const displayDataRef = useRef<ITrafficDataPoint[]>([])
|
||||
const yScaleRef = useRef<{ topValue: number; bottomValue: number }>({
|
||||
topValue: 1024,
|
||||
bottomValue: 0,
|
||||
})
|
||||
|
||||
const colors = useMemo(
|
||||
() => ({
|
||||
const colors = useMemo(() => {
|
||||
const base = {
|
||||
up: theme.palette.secondary.main,
|
||||
down: theme.palette.primary.main,
|
||||
grid: theme.palette.divider,
|
||||
text: theme.palette.text.secondary,
|
||||
background: theme.palette.background.paper,
|
||||
}
|
||||
return {
|
||||
...base,
|
||||
gradient: {
|
||||
up: makeGradientStops(base.up),
|
||||
down: makeGradientStops(base.down),
|
||||
},
|
||||
}
|
||||
}, [theme])
|
||||
|
||||
const legendSx = useMemo(
|
||||
() => ({
|
||||
up: {
|
||||
fontSize: '11px',
|
||||
fontWeight: 'bold',
|
||||
color: colors.up,
|
||||
textAlign: 'right',
|
||||
},
|
||||
down: {
|
||||
fontSize: '11px',
|
||||
fontWeight: 'bold',
|
||||
color: colors.down,
|
||||
textAlign: 'right',
|
||||
},
|
||||
}),
|
||||
[theme],
|
||||
[colors],
|
||||
)
|
||||
|
||||
const updateDisplayData = useCallback((newData: ITrafficDataPoint[]) => {
|
||||
if (debounceTimeoutRef.current !== null) {
|
||||
window.clearTimeout(debounceTimeoutRef.current)
|
||||
}
|
||||
debounceTimeoutRef.current = window.setTimeout(() => {
|
||||
dispatchDisplayData(newData)
|
||||
}, 50)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
updateDisplayData(dataPoints)
|
||||
|
||||
return () => {
|
||||
if (debounceTimeoutRef.current !== null) {
|
||||
window.clearTimeout(debounceTimeoutRef.current)
|
||||
debounceTimeoutRef.current = null
|
||||
}
|
||||
}
|
||||
}, [dataPoints, updateDisplayData])
|
||||
|
||||
useEffect(() => {
|
||||
requestRange(timeRange)
|
||||
}, [requestRange, timeRange])
|
||||
|
||||
useEffect(() => {
|
||||
if (displayData.length === 0) {
|
||||
lastDataTimestampRef.current = 0
|
||||
dataStaleRef.current = false
|
||||
return
|
||||
}
|
||||
|
||||
const latestTimestamp =
|
||||
displayData[displayData.length - 1]?.timestamp ?? null
|
||||
if (latestTimestamp) {
|
||||
lastDataTimestampRef.current = latestTimestamp
|
||||
const age = Date.now() - latestTimestamp
|
||||
const stale = age > STALE_DATA_THRESHOLD
|
||||
dataStaleRef.current = stale
|
||||
} else {
|
||||
dataStaleRef.current = false
|
||||
}
|
||||
}, [displayData])
|
||||
|
||||
const handleFocusStateChange = useEffectEvent((focused: boolean) => {
|
||||
isWindowFocusedRef.current = focused
|
||||
|
||||
@@ -270,14 +433,9 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
[],
|
||||
)
|
||||
|
||||
const yScale = useMemo(
|
||||
() => computeYScale(displayData),
|
||||
[computeYScale, displayData],
|
||||
)
|
||||
|
||||
const handleMouseMove = useCallback(
|
||||
(event: React.MouseEvent<HTMLElement>) => {
|
||||
if (displayData.length === 0) return
|
||||
if (displayDataRef.current.length === 0) return
|
||||
|
||||
pendingMousePositionRef.current = {
|
||||
clientX: event.clientX,
|
||||
@@ -294,7 +452,8 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
if (!pendingMousePosition) return
|
||||
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas || displayData.length === 0) return
|
||||
const data = displayDataRef.current
|
||||
if (!canvas || data.length === 0) return
|
||||
|
||||
const rect = canvas.getBoundingClientRect()
|
||||
const mouseX = pendingMousePosition.clientX - rect.left
|
||||
@@ -309,11 +468,11 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
0,
|
||||
Math.min(1, relativeMouseX / effectiveWidth),
|
||||
)
|
||||
const dataIndex = Math.round(ratio * (displayData.length - 1))
|
||||
const dataIndex = Math.round(ratio * (data.length - 1))
|
||||
|
||||
if (dataIndex < 0 || dataIndex >= displayData.length) return
|
||||
if (dataIndex < 0 || dataIndex >= data.length) return
|
||||
|
||||
const dataPoint = displayData[dataIndex]
|
||||
const dataPoint = data[dataIndex]
|
||||
|
||||
const [upValue, upUnit] = parseTraffic(dataPoint.up)
|
||||
const [downValue, downUnit] = parseTraffic(dataPoint.down)
|
||||
@@ -322,7 +481,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
? formatTrafficName(dataPoint.timestamp)
|
||||
: t('home.components.traffic.unknownTime')
|
||||
|
||||
const { topValue: tvH, bottomValue: bvH } = yScale
|
||||
const { topValue: tvH, bottomValue: bvH } = yScaleRef.current
|
||||
const upY = calculateY(dataPoint.up, rect.height, tvH, bvH)
|
||||
const downY = calculateY(dataPoint.down, rect.height, tvH, bvH)
|
||||
const highlightY =
|
||||
@@ -359,7 +518,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
})
|
||||
})
|
||||
},
|
||||
[displayData, calculateY, yScale, t],
|
||||
[calculateY, t],
|
||||
)
|
||||
|
||||
const handleMouseLeave = useCallback(() => {
|
||||
@@ -375,45 +534,6 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
)
|
||||
}, [])
|
||||
|
||||
const getYAxisTicks = useCallback(
|
||||
(topValue: number, bottomValue: number, height: number) => {
|
||||
const formatTrafficValue = (bytes: number): string => {
|
||||
if (bytes === 0) return '0'
|
||||
if (bytes < 1024) return `${Math.round(bytes)}B`
|
||||
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)}KB`
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)}MB`
|
||||
}
|
||||
|
||||
const padding = GRAPH_CONFIG.padding
|
||||
|
||||
const topY = padding.top + 10
|
||||
const bottomY = height - padding.bottom - 5
|
||||
const middleY = (topY + bottomY) / 2
|
||||
const middleValue = (bottomValue + topValue) / 2
|
||||
|
||||
const ticks = [
|
||||
{
|
||||
value: bottomValue,
|
||||
label: formatTrafficValue(bottomValue),
|
||||
y: bottomY,
|
||||
},
|
||||
{
|
||||
value: middleValue,
|
||||
label: formatTrafficValue(middleValue),
|
||||
y: middleY,
|
||||
},
|
||||
{
|
||||
value: topValue,
|
||||
label: formatTrafficValue(topValue),
|
||||
y: topY,
|
||||
},
|
||||
]
|
||||
|
||||
return ticks
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
const drawYAxis = useCallback(
|
||||
(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
@@ -425,8 +545,6 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
const padding = GRAPH_CONFIG.padding
|
||||
const ticks = getYAxisTicks(topValue, bottomValue, height)
|
||||
|
||||
if (ticks.length === 0) return
|
||||
|
||||
ctx.save()
|
||||
|
||||
ticks.forEach((tick, index) => {
|
||||
@@ -470,37 +588,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
|
||||
ctx.restore()
|
||||
},
|
||||
[colors.grid, colors.text, colors.background, getYAxisTicks],
|
||||
)
|
||||
|
||||
const getTimeDisplayStrategy = useCallback(
|
||||
(timeRangeMinutes: TimeRange) => {
|
||||
switch (timeRangeMinutes) {
|
||||
case 1:
|
||||
return {
|
||||
maxLabels: 6,
|
||||
formatTime: formatTrafficMinuteSecond,
|
||||
intervalSeconds: 10,
|
||||
minPixelDistance: 35,
|
||||
}
|
||||
case 5:
|
||||
return {
|
||||
maxLabels: 6,
|
||||
formatTime: formatTrafficHourMinute,
|
||||
intervalSeconds: 30,
|
||||
minPixelDistance: 38,
|
||||
}
|
||||
case 10:
|
||||
default:
|
||||
return {
|
||||
maxLabels: 8,
|
||||
formatTime: formatTrafficHourMinute,
|
||||
intervalSeconds: 60,
|
||||
minPixelDistance: 40,
|
||||
}
|
||||
}
|
||||
},
|
||||
[],
|
||||
[colors.grid, colors.text, colors.background],
|
||||
)
|
||||
|
||||
const drawTimeAxis = useCallback(
|
||||
@@ -516,7 +604,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
const effectiveWidth = width - padding.left - padding.right
|
||||
const timeAxisY = height - padding.bottom + 14
|
||||
|
||||
const strategy = getTimeDisplayStrategy(timeRange)
|
||||
const strategy = TIME_DISPLAY_STRATEGIES[timeRange]
|
||||
|
||||
ctx.save()
|
||||
ctx.fillStyle = colors.text
|
||||
@@ -533,15 +621,13 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
Math.ceil((data.length * minPixelDistance) / effectiveWidth),
|
||||
)
|
||||
|
||||
const timePoints: Array<{ index: number; x: number; label: string }> =
|
||||
[]
|
||||
resetTimeAxisPoints()
|
||||
|
||||
if (data.length > 0 && data[0].timestamp) {
|
||||
timePoints.push({
|
||||
index: 0,
|
||||
x: padding.left,
|
||||
label: strategy.formatTime(data[0].timestamp),
|
||||
})
|
||||
pushTimeAxisPoint(
|
||||
padding.left,
|
||||
strategy.formatTime(data[0].timestamp),
|
||||
)
|
||||
}
|
||||
|
||||
for (
|
||||
@@ -553,41 +639,37 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
if (!point.timestamp) continue
|
||||
|
||||
const x = padding.left + (i / (data.length - 1)) * effectiveWidth
|
||||
timePoints.push({
|
||||
index: i,
|
||||
x,
|
||||
label: strategy.formatTime(point.timestamp),
|
||||
})
|
||||
pushTimeAxisPoint(x, strategy.formatTime(point.timestamp))
|
||||
}
|
||||
|
||||
if (data.length > 1 && data[data.length - 1].timestamp) {
|
||||
const lastX = width - padding.right
|
||||
const lastPoint = timePoints[timePoints.length - 1]
|
||||
const lastPoint = timeAxisPoints[timeAxisPoints.length - 1]
|
||||
|
||||
if (!lastPoint || lastX - lastPoint.x >= minPixelDistance) {
|
||||
timePoints.push({
|
||||
index: data.length - 1,
|
||||
x: lastX,
|
||||
label: strategy.formatTime(data[data.length - 1].timestamp),
|
||||
})
|
||||
pushTimeAxisPoint(
|
||||
lastX,
|
||||
strategy.formatTime(data[data.length - 1].timestamp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
timePoints.forEach((point, index) => {
|
||||
if (index === 0) {
|
||||
for (let i = 0; i < timeAxisPoints.length; i++) {
|
||||
const point = timeAxisPoints[i]
|
||||
if (i === 0) {
|
||||
ctx.textAlign = 'left'
|
||||
} else if (index === timePoints.length - 1) {
|
||||
} else if (i === timeAxisPoints.length - 1) {
|
||||
ctx.textAlign = 'right'
|
||||
} else {
|
||||
ctx.textAlign = 'center'
|
||||
}
|
||||
|
||||
ctx.fillText(point.label, point.x, timeAxisY)
|
||||
})
|
||||
}
|
||||
|
||||
ctx.restore()
|
||||
},
|
||||
[colors.text, timeRange, getTimeDisplayStrategy],
|
||||
[colors.text, timeRange],
|
||||
)
|
||||
|
||||
const drawGrid = useCallback(
|
||||
@@ -632,6 +714,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
width: number,
|
||||
height: number,
|
||||
color: string,
|
||||
gradientStops: { start: string; end: string },
|
||||
withGradient = false,
|
||||
topValue: number,
|
||||
bottomValue: number,
|
||||
@@ -655,13 +738,8 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
0,
|
||||
height - padding.bottom,
|
||||
)
|
||||
gradient.addColorStop(
|
||||
0,
|
||||
`${color}${Math.round(GRAPH_CONFIG.alpha.gradient * 255)
|
||||
.toString(16)
|
||||
.padStart(2, '0')}`,
|
||||
)
|
||||
gradient.addColorStop(1, `${color}00`)
|
||||
gradient.addColorStop(0, gradientStops.start)
|
||||
gradient.addColorStop(1, gradientStops.end)
|
||||
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(getX(0), getY(0))
|
||||
@@ -752,6 +830,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
|
||||
const drawGraph = useCallback(() => {
|
||||
const canvas = canvasRef.current
|
||||
const displayData = displayDataRef.current
|
||||
if (!canvas || displayData.length === 0) {
|
||||
clearCanvas(canvasRef.current)
|
||||
clearCanvas(hoverCanvasRef.current)
|
||||
@@ -765,7 +844,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
// Clear using CSS dimensions; context is already scaled by DPR.
|
||||
ctx.clearRect(0, 0, cssWidth, cssHeight)
|
||||
|
||||
const { topValue, bottomValue } = yScale
|
||||
const { topValue, bottomValue } = yScaleRef.current
|
||||
|
||||
drawYAxis(ctx, cssWidth, cssHeight, topValue, bottomValue)
|
||||
|
||||
@@ -780,6 +859,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
cssWidth,
|
||||
cssHeight,
|
||||
colors.down,
|
||||
colors.gradient.down,
|
||||
true,
|
||||
topValue,
|
||||
bottomValue,
|
||||
@@ -792,6 +872,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
cssWidth,
|
||||
cssHeight,
|
||||
colors.up,
|
||||
colors.gradient.up,
|
||||
true,
|
||||
topValue,
|
||||
bottomValue,
|
||||
@@ -804,9 +885,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
)
|
||||
canvas.dataset.perfDraw = String(displayData.at(-1)?.timestamp ?? 0)
|
||||
}, [
|
||||
displayData,
|
||||
colors,
|
||||
yScale,
|
||||
drawYAxis,
|
||||
drawGrid,
|
||||
drawTimeAxis,
|
||||
@@ -817,6 +896,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
|
||||
const drawHoverOverlay = useCallback(() => {
|
||||
const canvas = hoverCanvasRef.current
|
||||
const displayData = displayDataRef.current
|
||||
if (!canvas || displayData.length < 2) {
|
||||
clearCanvas(canvas)
|
||||
return
|
||||
@@ -854,7 +934,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
|
||||
ctx.restore()
|
||||
}
|
||||
}, [displayData, colors, syncCanvasSize, clearCanvas])
|
||||
}, [colors, syncCanvasSize, clearCanvas])
|
||||
|
||||
const shouldSkipGraphDraw = useCallback(() => {
|
||||
if (!isDocumentVisibleRef.current) return true
|
||||
@@ -897,6 +977,55 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
})
|
||||
}, [drawGraph, drawHoverOverlay, shouldSkipGraphDraw])
|
||||
|
||||
const handleSnapshot = useCallback(
|
||||
(message: ITrafficWorkerSnapshotMessage) => {
|
||||
const data = message.dataPoints
|
||||
displayDataRef.current = data
|
||||
yScaleRef.current = computeYScale(data)
|
||||
|
||||
if (data.length === 0) {
|
||||
lastDataTimestampRef.current = 0
|
||||
dataStaleRef.current = false
|
||||
} else {
|
||||
const latestTimestamp = data[data.length - 1]?.timestamp ?? null
|
||||
if (latestTimestamp) {
|
||||
lastDataTimestampRef.current = latestTimestamp
|
||||
const age = Date.now() - latestTimestamp
|
||||
const stale = age > STALE_DATA_THRESHOLD
|
||||
dataStaleRef.current = stale
|
||||
} else {
|
||||
dataStaleRef.current = false
|
||||
}
|
||||
}
|
||||
|
||||
scheduleDrawGraph()
|
||||
// The badge is the only snapshot content that still renders; keeping
|
||||
// its state here confines re-renders to actual badge changes, and the
|
||||
// visibility gate skips hidden-phase renders — the re-prime snapshot
|
||||
// on regaining visibility refreshes it.
|
||||
if (!isDocumentVisibleRef.current) return
|
||||
setBadgeStats((prev) =>
|
||||
prev.points === data.length &&
|
||||
prev.compressed === message.samplerStats.compressedBufferSize
|
||||
? prev
|
||||
: {
|
||||
points: data.length,
|
||||
compressed: message.samplerStats.compressedBufferSize,
|
||||
},
|
||||
)
|
||||
},
|
||||
[computeYScale, scheduleDrawGraph],
|
||||
)
|
||||
|
||||
const { requestRange } = useTrafficGraphDataEnhanced({
|
||||
subscribe: false,
|
||||
onSnapshot: handleSnapshot,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
requestRange(timeRange)
|
||||
}, [requestRange, timeRange])
|
||||
|
||||
useEffect(() => {
|
||||
tooltipDataRef.current = tooltipData
|
||||
scheduleHoverDraw()
|
||||
@@ -966,119 +1095,36 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
position: 'relative',
|
||||
bgcolor: 'action.hover',
|
||||
borderRadius: 1,
|
||||
cursor: 'pointer',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
sx={rootSx}
|
||||
onClick={toggleStyle}
|
||||
onMouseMove={handleMouseMove}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
display: 'block',
|
||||
}}
|
||||
onClick={toggleStyle}
|
||||
/>
|
||||
<canvas ref={canvasRef} style={canvasStyle} onClick={toggleStyle} />
|
||||
|
||||
{tooltipData.visible && (
|
||||
<canvas
|
||||
ref={hoverCanvasRef}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
inset: 0,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
display: 'block',
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
/>
|
||||
<canvas ref={hoverCanvasRef} style={hoverCanvasStyle} />
|
||||
)}
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
>
|
||||
<Box sx={overlaySx}>
|
||||
<Box
|
||||
component="div"
|
||||
onClick={handleTimeRangeClick}
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
top: 6,
|
||||
left: 40,
|
||||
fontSize: '11px',
|
||||
fontWeight: 'bold',
|
||||
color: 'text.secondary',
|
||||
cursor: 'pointer',
|
||||
pointerEvents: 'all',
|
||||
px: 1,
|
||||
py: 0.5,
|
||||
borderRadius: 0.5,
|
||||
bgcolor: 'rgba(0,0,0,0.05)',
|
||||
'&:hover': {
|
||||
bgcolor: 'rgba(0,0,0,0.1)',
|
||||
},
|
||||
}}
|
||||
sx={timeRangeBadgeSx}
|
||||
>
|
||||
{getTimeRangeText()}
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
top: 6,
|
||||
right: 8,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 0.5,
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
fontSize: '11px',
|
||||
fontWeight: 'bold',
|
||||
color: colors.up,
|
||||
textAlign: 'right',
|
||||
}}
|
||||
>
|
||||
<Box sx={legendsSx}>
|
||||
<Box sx={legendSx.up}>
|
||||
{t('home.components.traffic.legends.upload')}
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
fontSize: '11px',
|
||||
fontWeight: 'bold',
|
||||
color: colors.down,
|
||||
textAlign: 'right',
|
||||
}}
|
||||
>
|
||||
<Box sx={legendSx.down}>
|
||||
{t('home.components.traffic.legends.download')}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
bottom: 6,
|
||||
right: 8,
|
||||
fontSize: '10px',
|
||||
color: 'text.disabled',
|
||||
opacity: 0.7,
|
||||
}}
|
||||
>
|
||||
<Box sx={chartStyleHintSx}>
|
||||
{t(
|
||||
chartStyle === 'bezier'
|
||||
? 'home.components.traffic.chartStyles.smooth'
|
||||
@@ -1086,20 +1132,10 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
bottom: 6,
|
||||
left: 8,
|
||||
fontSize: '9px',
|
||||
color: 'text.disabled',
|
||||
opacity: 0.6,
|
||||
lineHeight: 1.2,
|
||||
}}
|
||||
>
|
||||
<Box sx={diagnosticsSx}>
|
||||
{t('home.components.traffic.diagnostics', {
|
||||
points: displayData.length,
|
||||
compressed: samplerStats.compressedBufferSize,
|
||||
points: badgeStats.points,
|
||||
compressed: badgeStats.compressed,
|
||||
fps: GRAPH_CONFIG.targetFPS,
|
||||
})}
|
||||
</Box>
|
||||
@@ -1127,15 +1163,9 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
whiteSpace: 'nowrap',
|
||||
}}
|
||||
>
|
||||
<Box sx={{ color: 'text.secondary', mb: 0.2 }}>
|
||||
{tooltipData.timestamp}
|
||||
</Box>
|
||||
<Box sx={{ color: 'secondary.main', fontWeight: 500 }}>
|
||||
↑ {tooltipData.upSpeed}
|
||||
</Box>
|
||||
<Box sx={{ color: 'primary.main', fontWeight: 500 }}>
|
||||
↓ {tooltipData.downSpeed}
|
||||
</Box>
|
||||
<Box sx={tooltipTimeSx}>{tooltipData.timestamp}</Box>
|
||||
<Box sx={tooltipUpSx}>↑ {tooltipData.upSpeed}</Box>
|
||||
<Box sx={tooltipDownSx}>↓ {tooltipData.downSpeed}</Box>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
@@ -131,6 +131,15 @@ const CompactStatCard = memo(
|
||||
// 添加显示名称
|
||||
CompactStatCard.displayName = 'CompactStatCard'
|
||||
|
||||
// Element identity is stable, so CompactStatCard's memo comparison holds
|
||||
// across per-second parsedData updates.
|
||||
const uploadSpeedIcon = <ArrowUpwardRounded fontSize="small" />
|
||||
const downloadSpeedIcon = <ArrowDownwardRounded fontSize="small" />
|
||||
const activeConnectionsIcon = <LinkRounded fontSize="small" />
|
||||
const uploadedIcon = <CloudUploadRounded fontSize="small" />
|
||||
const downloadedIcon = <CloudDownloadRounded fontSize="small" />
|
||||
const memoryUsageIcon = <MemoryRounded fontSize="small" />
|
||||
|
||||
const fallbackSx = {
|
||||
p: 2,
|
||||
minHeight: 200,
|
||||
@@ -252,35 +261,35 @@ export const EnhancedTrafficStats = () => {
|
||||
const statCards = useMemo(() => {
|
||||
const cards: StatCardProps[] = [
|
||||
{
|
||||
icon: <ArrowUpwardRounded fontSize="small" />,
|
||||
icon: uploadSpeedIcon,
|
||||
title: t('home.components.traffic.metrics.uploadSpeed'),
|
||||
value: parsedData.up,
|
||||
unit: `${parsedData.upUnit}/s`,
|
||||
color: 'secondary' as const,
|
||||
},
|
||||
{
|
||||
icon: <ArrowDownwardRounded fontSize="small" />,
|
||||
icon: downloadSpeedIcon,
|
||||
title: t('home.components.traffic.metrics.downloadSpeed'),
|
||||
value: parsedData.down,
|
||||
unit: `${parsedData.downUnit}/s`,
|
||||
color: 'primary' as const,
|
||||
},
|
||||
{
|
||||
icon: <LinkRounded fontSize="small" />,
|
||||
icon: activeConnectionsIcon,
|
||||
title: t('home.components.traffic.metrics.activeConnections'),
|
||||
value: parsedData.connectionsCount,
|
||||
unit: '',
|
||||
color: 'success' as const,
|
||||
},
|
||||
{
|
||||
icon: <CloudUploadRounded fontSize="small" />,
|
||||
icon: uploadedIcon,
|
||||
title: t('shared.labels.uploaded'),
|
||||
value: parsedData.uploadTotal,
|
||||
unit: parsedData.uploadTotalUnit,
|
||||
color: 'secondary' as const,
|
||||
},
|
||||
{
|
||||
icon: <CloudDownloadRounded fontSize="small" />,
|
||||
icon: downloadedIcon,
|
||||
title: t('shared.labels.downloaded'),
|
||||
value: parsedData.downloadTotal,
|
||||
unit: parsedData.downloadTotalUnit,
|
||||
@@ -290,7 +299,7 @@ export const EnhancedTrafficStats = () => {
|
||||
|
||||
if (displayMemory) {
|
||||
cards.push({
|
||||
icon: <MemoryRounded fontSize="small" />,
|
||||
icon: memoryUsageIcon,
|
||||
title: t('home.components.traffic.metrics.memoryUsage'),
|
||||
value: parsedData.inuse,
|
||||
unit: parsedData.inuseUnit,
|
||||
|
||||
@@ -23,6 +23,8 @@ import { emitTestAll } from '@/services/bus'
|
||||
|
||||
import { EnhancedCard } from './enhanced-card'
|
||||
|
||||
const TEST_LIST_SENSORS = [PointerSensor]
|
||||
|
||||
// 自定义滚动条样式
|
||||
const ScrollBox = styled(Box)(({ theme }) => ({
|
||||
maxHeight: '180px',
|
||||
@@ -87,18 +89,18 @@ export const TestCard = () => {
|
||||
x.uid === uid ? { ...x, ...patch } : x,
|
||||
)
|
||||
|
||||
mutateVerge({ ...verge, test_list: newList })
|
||||
mutateVerge((prev) => ({ ...prev, test_list: newList }))
|
||||
},
|
||||
[testList, verge, mutateVerge],
|
||||
[testList, mutateVerge],
|
||||
)
|
||||
|
||||
const onDeleteTestListItem = useCallback(
|
||||
(uid: string) => {
|
||||
const newList = testList.filter((x) => x.uid !== uid)
|
||||
patchVerge({ test_list: newList })
|
||||
mutateVerge({ ...verge, test_list: newList })
|
||||
mutateVerge((prev) => ({ ...prev, test_list: newList }))
|
||||
},
|
||||
[testList, verge, patchVerge, mutateVerge],
|
||||
[testList, patchVerge, mutateVerge],
|
||||
)
|
||||
|
||||
const onDragEnd = useCallback(
|
||||
@@ -129,7 +131,7 @@ export const TestCard = () => {
|
||||
newList.splice(newIndex, 0, removed)
|
||||
|
||||
// 优化:先本地更新,再异步 patch,避免UI卡死
|
||||
mutateVerge({ ...verge, test_list: newList })
|
||||
mutateVerge((prev) => ({ ...prev, test_list: newList }))
|
||||
const patchFn = () => {
|
||||
try {
|
||||
patchVerge({ test_list: newList })
|
||||
@@ -141,7 +143,7 @@ export const TestCard = () => {
|
||||
setTimeout(patchFn, 0)
|
||||
}
|
||||
},
|
||||
[testList, verge, mutateVerge, patchVerge],
|
||||
[testList, mutateVerge, patchVerge],
|
||||
)
|
||||
|
||||
// 仅在verge首次加载时初始化测试列表
|
||||
@@ -205,7 +207,7 @@ export const TestCard = () => {
|
||||
}
|
||||
>
|
||||
<ScrollBox>
|
||||
<DragDropProvider sensors={[PointerSensor]} onDragEnd={onDragEnd}>
|
||||
<DragDropProvider sensors={TEST_LIST_SENSORS} onDragEnd={onDragEnd}>
|
||||
{renderTestItems}
|
||||
</DragDropProvider>
|
||||
</ScrollBox>
|
||||
|
||||
@@ -42,6 +42,39 @@ const TrafficUnavailableFallback = () => {
|
||||
)
|
||||
}
|
||||
|
||||
// Stable identities keep the emotion sx cache effective across the ~1Hz
|
||||
// traffic-driven re-renders of LayoutTraffic.
|
||||
const boxStyle: Pick<BoxProps, 'sx'> = {
|
||||
sx: {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
whiteSpace: 'nowrap',
|
||||
},
|
||||
}
|
||||
const memoryBoxStyle: Pick<BoxProps, 'sx'> = {
|
||||
sx: {
|
||||
...boxStyle.sx,
|
||||
cursor: 'auto',
|
||||
},
|
||||
}
|
||||
const iconStyle: Pick<SvgIconProps, 'sx'> = {
|
||||
sx: { mr: '8px', fontSize: 16 },
|
||||
}
|
||||
const valStyle: Pick<TypographyProps, 'component' | 'sx'> = {
|
||||
component: 'span',
|
||||
sx: { flex: '1 1 56px', userSelect: 'none', textAlign: 'center' },
|
||||
}
|
||||
const unitStyle: Pick<TypographyProps, 'component' | 'color' | 'sx'> = {
|
||||
component: 'span',
|
||||
color: 'grey.500',
|
||||
sx: {
|
||||
flex: '0 1 27px',
|
||||
userSelect: 'none',
|
||||
fontSize: '12px',
|
||||
textAlign: 'right',
|
||||
},
|
||||
}
|
||||
|
||||
export const LayoutTraffic = () => {
|
||||
const { t } = useTranslation()
|
||||
const { verge } = useVerge()
|
||||
@@ -74,31 +107,6 @@ export const LayoutTraffic = () => {
|
||||
const [down, downUnit] = parseTraffic(traffic?.down || 0)
|
||||
const [inuse, inuseUnit] = parseTraffic(memory?.inuse || 0)
|
||||
|
||||
const boxStyle: Pick<BoxProps, 'sx'> = {
|
||||
sx: {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
whiteSpace: 'nowrap',
|
||||
},
|
||||
}
|
||||
const iconStyle: Pick<SvgIconProps, 'sx'> = {
|
||||
sx: { mr: '8px', fontSize: 16 },
|
||||
}
|
||||
const valStyle: Pick<TypographyProps, 'component' | 'sx'> = {
|
||||
component: 'span',
|
||||
sx: { flex: '1 1 56px', userSelect: 'none', textAlign: 'center' },
|
||||
}
|
||||
const unitStyle: Pick<TypographyProps, 'component' | 'color' | 'sx'> = {
|
||||
component: 'span',
|
||||
color: 'grey.500',
|
||||
sx: {
|
||||
flex: '0 1 27px',
|
||||
userSelect: 'none',
|
||||
fontSize: '12px',
|
||||
textAlign: 'right',
|
||||
},
|
||||
}
|
||||
|
||||
return (
|
||||
<ErrorBoundary
|
||||
FallbackComponent={TrafficUnavailableFallback}
|
||||
@@ -120,9 +128,6 @@ export const LayoutTraffic = () => {
|
||||
<Box
|
||||
title={`${t('home.components.traffic.metrics.uploadSpeed')}`}
|
||||
{...boxStyle}
|
||||
sx={{
|
||||
...boxStyle.sx,
|
||||
}}
|
||||
>
|
||||
<ArrowUpwardRounded
|
||||
{...iconStyle}
|
||||
@@ -137,9 +142,6 @@ export const LayoutTraffic = () => {
|
||||
<Box
|
||||
title={`${t('home.components.traffic.metrics.downloadSpeed')}`}
|
||||
{...boxStyle}
|
||||
sx={{
|
||||
...boxStyle.sx,
|
||||
}}
|
||||
>
|
||||
<ArrowDownwardRounded
|
||||
{...iconStyle}
|
||||
@@ -154,11 +156,7 @@ export const LayoutTraffic = () => {
|
||||
{displayMemory && (
|
||||
<Box
|
||||
title={`${t('home.components.traffic.metrics.memoryUsage')} `}
|
||||
{...boxStyle}
|
||||
sx={{
|
||||
...boxStyle.sx,
|
||||
cursor: 'auto',
|
||||
}}
|
||||
{...memoryBoxStyle}
|
||||
color={'disabled'}
|
||||
>
|
||||
<MemoryRounded {...iconStyle} />
|
||||
|
||||
@@ -13,7 +13,8 @@ const upLineWidth = 4
|
||||
const downLineAlpha = 1
|
||||
const downLineWidth = 4
|
||||
const sampleIntervalMs = 1000
|
||||
const animationDurationMs = sampleIntervalMs
|
||||
const animationDurationMs = 150
|
||||
const scrollTransform = `translateX(${-100 / (maxPoint + 1)}%)`
|
||||
|
||||
const zeroTraffic: Traffic = { up: 0, down: 0, upTotal: 0, downTotal: 0 }
|
||||
const createDefaultList = () =>
|
||||
@@ -203,12 +204,8 @@ export function TrafficGraph({ ref }: { ref?: Ref<TrafficRef> }) {
|
||||
performance.now() - animationStartRef.current,
|
||||
animationDurationMs,
|
||||
)
|
||||
const step = canvas.getBoundingClientRect().width / (maxPoint + 1)
|
||||
animation = canvas.animate(
|
||||
[
|
||||
{ transform: 'translateX(0)' },
|
||||
{ transform: `translateX(${-step}px)` },
|
||||
],
|
||||
[{ transform: 'translateX(0)' }, { transform: scrollTransform }],
|
||||
{ duration: animationDurationMs, easing: 'linear', fill: 'forwards' },
|
||||
)
|
||||
animation.currentTime = elapsed
|
||||
|
||||
@@ -5,6 +5,8 @@ import { type PointerEvent, useCallback } from 'react'
|
||||
import { useWindowControls } from '@/hooks/use-window'
|
||||
import getSystem from '@/utils/get-system'
|
||||
|
||||
const OS = getSystem()
|
||||
|
||||
const RESIZE_HANDLES = [
|
||||
{ direction: 'North', position: 'north' },
|
||||
{ direction: 'NorthEast', position: 'north-east' },
|
||||
@@ -38,7 +40,7 @@ export const WindowResizeHandles = () => {
|
||||
[currentWindow],
|
||||
)
|
||||
|
||||
if (getSystem() !== 'linux' || maximized) return null
|
||||
if (OS !== 'linux' || maximized) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -59,7 +61,6 @@ export const WindowResizeHandles = () => {
|
||||
}
|
||||
|
||||
export const WindowControls = () => {
|
||||
const OS = getSystem()
|
||||
const { maximized, minimize, close, toggleMaximize } = useWindowControls()
|
||||
|
||||
// 通过前端对 tauri 窗口进行翻转全屏时会短暂地与系统图标重叠渲染。
|
||||
|
||||
@@ -2,6 +2,7 @@ import { styled, Box } from '@mui/material'
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
import type { SearchState } from '@/components/base'
|
||||
import { buildRegex } from '@/utils/search-matcher'
|
||||
|
||||
const Item = styled(Box)(({ theme: { palette, typography } }) => ({
|
||||
padding: '8px 0',
|
||||
@@ -47,62 +48,74 @@ interface Props {
|
||||
searchState?: SearchState
|
||||
}
|
||||
|
||||
// Compiling per row multiplied by high-frequency log appends; searchState is
|
||||
// React state, so identity reuse is safe until the search inputs change.
|
||||
let highlightRegexCache: { state: SearchState; regex: RegExp | null } | null =
|
||||
null
|
||||
|
||||
const getHighlightRegex = (searchState: SearchState): RegExp | null => {
|
||||
if (highlightRegexCache?.state === searchState)
|
||||
return highlightRegexCache.regex
|
||||
|
||||
const searchText = searchState.text
|
||||
let pattern: string
|
||||
|
||||
if (searchState.useRegularExpression) {
|
||||
try {
|
||||
new RegExp(searchText)
|
||||
pattern = searchText
|
||||
} catch {
|
||||
pattern = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
}
|
||||
} else {
|
||||
const escaped = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
pattern = searchState.matchWholeWord ? `\\b${escaped}\\b` : escaped
|
||||
}
|
||||
|
||||
const flags = searchState.matchCase ? 'g' : 'gi'
|
||||
const regex = buildRegex(pattern, flags)
|
||||
highlightRegexCache = { state: searchState, regex }
|
||||
return regex
|
||||
}
|
||||
|
||||
const LogItem = ({ value, searchState }: Props) => {
|
||||
const renderHighlightText = (text: string) => {
|
||||
if (!searchState?.text.trim()) return text
|
||||
|
||||
try {
|
||||
const searchText = searchState.text
|
||||
let pattern: string
|
||||
const regex = getHighlightRegex(searchState)
|
||||
if (!regex) return text
|
||||
|
||||
if (searchState.useRegularExpression) {
|
||||
try {
|
||||
new RegExp(searchText)
|
||||
pattern = searchText
|
||||
} catch {
|
||||
pattern = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
}
|
||||
} else {
|
||||
const escaped = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
pattern = searchState.matchWholeWord ? `\\b${escaped}\\b` : escaped
|
||||
const elements: ReactNode[] = []
|
||||
let lastIndex = 0
|
||||
let match: RegExpExecArray | null
|
||||
|
||||
while ((match = regex.exec(text)) !== null) {
|
||||
const start = match.index
|
||||
const matchText = match[0]
|
||||
|
||||
if (matchText === '') {
|
||||
regex.lastIndex += 1
|
||||
continue
|
||||
}
|
||||
|
||||
const flags = searchState.matchCase ? 'g' : 'gi'
|
||||
const regex = new RegExp(pattern, flags)
|
||||
const elements: ReactNode[] = []
|
||||
let lastIndex = 0
|
||||
let match: RegExpExecArray | null
|
||||
|
||||
while ((match = regex.exec(text)) !== null) {
|
||||
const start = match.index
|
||||
const matchText = match[0]
|
||||
|
||||
if (matchText === '') {
|
||||
regex.lastIndex += 1
|
||||
continue
|
||||
}
|
||||
|
||||
if (start > lastIndex) {
|
||||
elements.push(text.slice(lastIndex, start))
|
||||
}
|
||||
|
||||
elements.push(
|
||||
<span key={`highlight-${start}`} className="highlight">
|
||||
{matchText}
|
||||
</span>,
|
||||
)
|
||||
|
||||
lastIndex = start + matchText.length
|
||||
if (start > lastIndex) {
|
||||
elements.push(text.slice(lastIndex, start))
|
||||
}
|
||||
|
||||
if (lastIndex < text.length) {
|
||||
elements.push(text.slice(lastIndex))
|
||||
}
|
||||
elements.push(
|
||||
<span key={`highlight-${start}`} className="highlight">
|
||||
{matchText}
|
||||
</span>,
|
||||
)
|
||||
|
||||
return elements.length ? elements : text
|
||||
} catch {
|
||||
return text
|
||||
lastIndex = start + matchText.length
|
||||
}
|
||||
|
||||
if (lastIndex < text.length) {
|
||||
elements.push(text.slice(lastIndex))
|
||||
}
|
||||
|
||||
return elements.length ? elements : text
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Alert, Box, Typography } from '@mui/material'
|
||||
import { useMemo } from 'react'
|
||||
import { Trans, useTranslation } from 'react-i18next'
|
||||
|
||||
const stageHints = {
|
||||
@@ -14,26 +15,31 @@ interface Props {
|
||||
|
||||
export const EnhanceHint = ({ stage }: Props) => {
|
||||
const { t } = useTranslation()
|
||||
const orderComponents = Object.fromEntries(
|
||||
Object.keys(stageHints).map((key) => [
|
||||
key,
|
||||
<Box
|
||||
key={key}
|
||||
component={key === stage ? 'strong' : 'span'}
|
||||
sx={
|
||||
key === stage
|
||||
? {
|
||||
fontWeight: 'bold',
|
||||
color: 'primary.contrastText',
|
||||
bgcolor: 'primary.main',
|
||||
borderRadius: 0.5,
|
||||
px: 0.5,
|
||||
boxDecorationBreak: 'clone',
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>,
|
||||
]),
|
||||
// The component map identity changes only when the active stage changes.
|
||||
const orderComponents = useMemo(
|
||||
() =>
|
||||
Object.fromEntries(
|
||||
Object.keys(stageHints).map((key) => [
|
||||
key,
|
||||
<Box
|
||||
key={key}
|
||||
component={key === stage ? 'strong' : 'span'}
|
||||
sx={
|
||||
key === stage
|
||||
? {
|
||||
fontWeight: 'bold',
|
||||
color: 'primary.contrastText',
|
||||
bgcolor: 'primary.main',
|
||||
borderRadius: 0.5,
|
||||
px: 0.5,
|
||||
boxDecorationBreak: 'clone',
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>,
|
||||
]),
|
||||
),
|
||||
[stage],
|
||||
)
|
||||
|
||||
return (
|
||||
|
||||
@@ -56,6 +56,8 @@ interface GroupedVirtualListProps<T> {
|
||||
style?: CSSProperties
|
||||
}
|
||||
|
||||
const GROUPED_LIST_SENSORS = [PointerSensor, KeyboardSensor]
|
||||
|
||||
/**
|
||||
* 用于编辑规则/节点/代理组功能的 prepend/original/append 分组虚拟化列表
|
||||
*/
|
||||
@@ -141,7 +143,7 @@ export function GroupedVirtualList<T>(props: GroupedVirtualListProps<T>) {
|
||||
|
||||
return (
|
||||
<DragDropProvider
|
||||
sensors={[PointerSensor, KeyboardSensor]}
|
||||
sensors={GROUPED_LIST_SENSORS}
|
||||
onDragStart={onDragStart}
|
||||
onDragOver={onDragOver}
|
||||
onDragEnd={onDragEnd}
|
||||
|
||||
@@ -176,7 +176,10 @@ export const GroupsEditorViewer = (props: Props) => {
|
||||
},
|
||||
})
|
||||
const [groupList, setGroupList] = useState<IProxyGroupConfig[]>([])
|
||||
const [proxyPolicyList, setProxyPolicyList] = useState<string[]>([])
|
||||
const [originPolicy, setOriginPolicy] = useState<{
|
||||
proxyNames: string[]
|
||||
groupNames: string[]
|
||||
}>({ proxyNames: [], groupNames: [] })
|
||||
const [proxyProviderList, setProxyProviderList] = useState<string[]>([])
|
||||
const [prependSeq, setPrependSeq] = useState<IProxyGroupConfig[]>([])
|
||||
const [appendSeq, setAppendSeq] = useState<IProxyGroupConfig[]>([])
|
||||
@@ -218,7 +221,7 @@ export const GroupsEditorViewer = (props: Props) => {
|
||||
group={item}
|
||||
onDelete={() => {
|
||||
if (isDeleted) {
|
||||
setDeleteSeq(deleteSeq.filter((v) => v !== item.name))
|
||||
setDeleteSeq((prev) => prev.filter((v) => v !== item.name))
|
||||
} else {
|
||||
setDeleteSeq((prev) => [...prev, item.name])
|
||||
}
|
||||
@@ -233,7 +236,7 @@ export const GroupsEditorViewer = (props: Props) => {
|
||||
type="prepend"
|
||||
group={item}
|
||||
onDelete={() => {
|
||||
setPrependSeq(prependSeq.filter((v) => v.name !== item.name))
|
||||
setPrependSeq((prev) => prev.filter((v) => v.name !== item.name))
|
||||
}}
|
||||
/>
|
||||
)
|
||||
@@ -244,7 +247,7 @@ export const GroupsEditorViewer = (props: Props) => {
|
||||
type="append"
|
||||
group={item}
|
||||
onDelete={() => {
|
||||
setAppendSeq(appendSeq.filter((v) => v.name !== item.name))
|
||||
setAppendSeq((prev) => prev.filter((v) => v.name !== item.name))
|
||||
}}
|
||||
/>
|
||||
)
|
||||
@@ -255,21 +258,22 @@ export const GroupsEditorViewer = (props: Props) => {
|
||||
activeIndex: number,
|
||||
overIndex: number,
|
||||
) => {
|
||||
const list = category === 'prepend' ? prependSeq : appendSeq
|
||||
const filtered =
|
||||
category === 'prepend' ? filteredPrependSeq : filteredAppendSeq
|
||||
const setList = category === 'prepend' ? setPrependSeq : setAppendSeq
|
||||
const activeRealIndex = findRealIndex(list, filtered, activeIndex)
|
||||
const overRealIndex = findRealIndex(list, filtered, overIndex)
|
||||
if (
|
||||
activeRealIndex < 0 ||
|
||||
overRealIndex < 0 ||
|
||||
activeRealIndex === overRealIndex
|
||||
) {
|
||||
return
|
||||
}
|
||||
// Recompute inside the updater: two writes in one batch must not read the same pre-batch array.
|
||||
setList((prev) => {
|
||||
const filtered = prev.filter((v) => match(v.name))
|
||||
const activeRealIndex = findRealIndex(prev, filtered, activeIndex)
|
||||
const overRealIndex = findRealIndex(prev, filtered, overIndex)
|
||||
if (
|
||||
activeRealIndex < 0 ||
|
||||
overRealIndex < 0 ||
|
||||
activeRealIndex === overRealIndex
|
||||
) {
|
||||
return prev
|
||||
}
|
||||
|
||||
setList(arrayMove(list, activeRealIndex, overRealIndex))
|
||||
return arrayMove(prev, activeRealIndex, overRealIndex)
|
||||
})
|
||||
}
|
||||
|
||||
const fetchContent = useCallback(async () => {
|
||||
@@ -353,6 +357,9 @@ export const GroupsEditorViewer = (props: Props) => {
|
||||
}
|
||||
}, [prependSeq, appendSeq, deleteSeq])
|
||||
|
||||
// Origin policy names come from profile files that this dialog never
|
||||
// rewrites while open, so they are read once per open; the live seq states
|
||||
// are folded in by the derived proxyPolicyList below.
|
||||
const fetchProxyPolicy = useCallback(async () => {
|
||||
const data = await readProfileFile(profileUid)
|
||||
const proxiesData = await readProfileFile(proxiesUid)
|
||||
@@ -388,17 +395,13 @@ export const GroupsEditorViewer = (props: Props) => {
|
||||
(name): name is string => typeof name === 'string' && name.length > 0,
|
||||
)
|
||||
|
||||
const computedPolicyList = builtinProxyPolicies.concat(
|
||||
prependSeq.map((group: IProxyGroupConfig) => group.name),
|
||||
(originGroupsObj?.['proxy-groups'] || [])
|
||||
.map((group: IProxyGroupConfig) => group.name)
|
||||
.filter((name) => !deleteSeq.includes(name)),
|
||||
appendSeq.map((group: IProxyGroupConfig) => group.name),
|
||||
setOriginPolicy({
|
||||
proxyNames,
|
||||
)
|
||||
|
||||
setProxyPolicyList(Array.from(new Set(computedPolicyList)))
|
||||
}, [appendSeq, deleteSeq, prependSeq, profileUid, proxiesUid])
|
||||
groupNames: (originGroupsObj?.['proxy-groups'] || []).map(
|
||||
(group) => group.name,
|
||||
),
|
||||
})
|
||||
}, [profileUid, proxiesUid])
|
||||
const fetchProfile = useCallback(async () => {
|
||||
const data = await readProfileFile(profileUid)
|
||||
const mergeData = await readProfileFile(mergeUid)
|
||||
@@ -442,6 +445,16 @@ export const GroupsEditorViewer = (props: Props) => {
|
||||
fetchProxyPolicy()
|
||||
}, [fetchProxyPolicy, open])
|
||||
|
||||
const proxyPolicyList = useMemo(() => {
|
||||
const computedPolicyList = builtinProxyPolicies.concat(
|
||||
prependSeq.map((group) => group.name),
|
||||
originPolicy.groupNames.filter((name) => !deleteSeq.includes(name)),
|
||||
appendSeq.map((group) => group.name),
|
||||
originPolicy.proxyNames,
|
||||
)
|
||||
return Array.from(new Set(computedPolicyList))
|
||||
}, [appendSeq, deleteSeq, originPolicy, prependSeq])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
fetchContent()
|
||||
@@ -1019,14 +1032,20 @@ export const GroupsEditorViewer = (props: Props) => {
|
||||
onClick={() => {
|
||||
try {
|
||||
validateGroup()
|
||||
const values = formIns.getValues()
|
||||
for (const item of [...prependSeq, ...groupList]) {
|
||||
if (item.name === formIns.getValues().name) {
|
||||
if (item.name === values.name) {
|
||||
throw new Error(
|
||||
t('profiles.modals.groupsEditor.errors.nameExists'),
|
||||
)
|
||||
}
|
||||
}
|
||||
setPrependSeq([formIns.getValues(), ...prependSeq])
|
||||
// Recheck inside the updater so a same-batch second click cannot duplicate the entry.
|
||||
setPrependSeq((prev) =>
|
||||
prev.some((v) => v.name === values.name)
|
||||
? prev
|
||||
: [values, ...prev],
|
||||
)
|
||||
} catch (err) {
|
||||
showNotice.error(err)
|
||||
}
|
||||
@@ -1043,14 +1062,20 @@ export const GroupsEditorViewer = (props: Props) => {
|
||||
onClick={() => {
|
||||
try {
|
||||
validateGroup()
|
||||
const values = formIns.getValues()
|
||||
for (const item of [...appendSeq, ...groupList]) {
|
||||
if (item.name === formIns.getValues().name) {
|
||||
if (item.name === values.name) {
|
||||
throw new Error(
|
||||
t('profiles.modals.groupsEditor.errors.nameExists'),
|
||||
)
|
||||
}
|
||||
}
|
||||
setAppendSeq([...appendSeq, formIns.getValues()])
|
||||
// Recheck inside the updater so a same-batch second click cannot duplicate the entry.
|
||||
setAppendSeq((prev) =>
|
||||
prev.some((v) => v.name === values.name)
|
||||
? prev
|
||||
: [...prev, values],
|
||||
)
|
||||
} catch (err) {
|
||||
showNotice.error(err)
|
||||
}
|
||||
|
||||
@@ -61,6 +61,31 @@ const round = keyframes`
|
||||
to { transform: rotate(360deg); }
|
||||
`
|
||||
|
||||
type ContextMenuItem = {
|
||||
label: string
|
||||
handler: () => void
|
||||
disabled: boolean
|
||||
}
|
||||
|
||||
const menuLabels: Record<string, TranslationKey> = {
|
||||
home: 'profiles.components.menu.home',
|
||||
select: 'profiles.components.menu.select',
|
||||
shareQrCode: 'profiles.components.menu.shareQrCode',
|
||||
editInfo: 'profiles.components.menu.editInfo',
|
||||
editFile: 'profiles.components.menu.editFile',
|
||||
editRules: 'profiles.components.menu.editRules',
|
||||
editProxies: 'profiles.components.menu.editProxies',
|
||||
editGroups: 'profiles.components.menu.editGroups',
|
||||
extendConfig: 'profiles.components.menu.extendConfig',
|
||||
extendScript: 'profiles.components.menu.extendScript',
|
||||
openFile: 'profiles.components.menu.openFile',
|
||||
update: 'profiles.components.menu.update',
|
||||
updateViaProxy: 'profiles.components.menu.updateViaProxy',
|
||||
delete: 'shared.actions.delete',
|
||||
} as const
|
||||
|
||||
const EMPTY_CONTEXT_MENU: ContextMenuItem[] = []
|
||||
|
||||
export interface ProfileItemProps {
|
||||
id: string
|
||||
index: number
|
||||
@@ -68,13 +93,13 @@ export interface ProfileItemProps {
|
||||
activating: boolean
|
||||
itemData: IProfileItem
|
||||
mutateProfiles: () => Promise<void>
|
||||
onSelect: (force: boolean) => void
|
||||
onEdit: () => void
|
||||
onSave?: (prev?: string, curr?: string) => void
|
||||
onDelete: () => void
|
||||
onSelect: (uid: string, force: boolean) => void
|
||||
onEdit: (item: IProfileItem) => void
|
||||
onSave?: (uid: string, prev?: string, curr?: string) => void
|
||||
onDelete: (uid: string) => void
|
||||
batchMode?: boolean
|
||||
isSelected?: boolean
|
||||
onSelectionChange?: () => void
|
||||
onSelectionChange?: (uid: string) => void
|
||||
timerUpdateRevision: number
|
||||
completedUpdateRevision: number
|
||||
}
|
||||
@@ -322,7 +347,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
|
||||
|
||||
const onEditInfo = () => {
|
||||
setAnchorEl(null)
|
||||
onEdit()
|
||||
onEdit(itemData)
|
||||
}
|
||||
|
||||
const onShareQrCode = () => {
|
||||
@@ -362,7 +387,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
|
||||
|
||||
const onForceSelect = () => {
|
||||
setAnchorEl(null)
|
||||
onSelect(true)
|
||||
onSelect(id, true)
|
||||
}
|
||||
|
||||
const onOpenFile = useLockFn(async () => {
|
||||
@@ -412,175 +437,158 @@ const ProfileItemBase = (props: ProfileItemProps) => {
|
||||
}
|
||||
})
|
||||
|
||||
type ContextMenuItem = {
|
||||
label: string
|
||||
handler: () => void
|
||||
disabled: boolean
|
||||
}
|
||||
|
||||
const menuLabels: Record<string, TranslationKey> = {
|
||||
home: 'profiles.components.menu.home',
|
||||
select: 'profiles.components.menu.select',
|
||||
shareQrCode: 'profiles.components.menu.shareQrCode',
|
||||
editInfo: 'profiles.components.menu.editInfo',
|
||||
editFile: 'profiles.components.menu.editFile',
|
||||
editRules: 'profiles.components.menu.editRules',
|
||||
editProxies: 'profiles.components.menu.editProxies',
|
||||
editGroups: 'profiles.components.menu.editGroups',
|
||||
extendConfig: 'profiles.components.menu.extendConfig',
|
||||
extendScript: 'profiles.components.menu.extendScript',
|
||||
openFile: 'profiles.components.menu.openFile',
|
||||
update: 'profiles.components.menu.update',
|
||||
updateViaProxy: 'profiles.components.menu.updateViaProxy',
|
||||
delete: 'shared.actions.delete',
|
||||
} as const
|
||||
|
||||
const urlModeMenu: ContextMenuItem[] = [
|
||||
...(hasHome
|
||||
? [
|
||||
{
|
||||
label: menuLabels.home,
|
||||
handler: onOpenHome,
|
||||
disabled: false,
|
||||
} satisfies ContextMenuItem,
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label: menuLabels.select,
|
||||
handler: onForceSelect,
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.shareQrCode,
|
||||
handler: onShareQrCode,
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editInfo,
|
||||
handler: onEditInfo,
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editFile,
|
||||
handler: onEditFile,
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editRules,
|
||||
handler: onEditRules,
|
||||
disabled: !option?.rules,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editProxies,
|
||||
handler: onEditProxies,
|
||||
disabled: !option?.proxies,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editGroups,
|
||||
handler: onEditGroups,
|
||||
disabled: !option?.groups,
|
||||
},
|
||||
{
|
||||
label: menuLabels.extendConfig,
|
||||
handler: onEditMerge,
|
||||
disabled: !option?.merge,
|
||||
},
|
||||
{
|
||||
label: menuLabels.extendScript,
|
||||
handler: onEditScript,
|
||||
disabled: !option?.script,
|
||||
},
|
||||
{
|
||||
label: menuLabels.openFile,
|
||||
handler: onOpenFile,
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.update,
|
||||
handler: () => onUpdate(0),
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.updateViaProxy,
|
||||
handler: () => onUpdate(2),
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.delete,
|
||||
handler: () => {
|
||||
setAnchorEl(null)
|
||||
if (batchMode) {
|
||||
if (onSelectionChange) {
|
||||
onSelectionChange()
|
||||
}
|
||||
} else {
|
||||
setConfirmOpen(true)
|
||||
}
|
||||
},
|
||||
disabled: false,
|
||||
},
|
||||
]
|
||||
const fileModeMenu: ContextMenuItem[] = [
|
||||
{
|
||||
label: menuLabels.select,
|
||||
handler: onForceSelect,
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editInfo,
|
||||
handler: onEditInfo,
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editFile,
|
||||
handler: onEditFile,
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editRules,
|
||||
handler: onEditRules,
|
||||
disabled: !option?.rules,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editProxies,
|
||||
handler: onEditProxies,
|
||||
disabled: !option?.proxies,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editGroups,
|
||||
handler: onEditGroups,
|
||||
disabled: !option?.groups,
|
||||
},
|
||||
{
|
||||
label: menuLabels.extendConfig,
|
||||
handler: onEditMerge,
|
||||
disabled: !option?.merge,
|
||||
},
|
||||
{
|
||||
label: menuLabels.extendScript,
|
||||
handler: onEditScript,
|
||||
disabled: !option?.script,
|
||||
},
|
||||
{
|
||||
label: menuLabels.openFile,
|
||||
handler: onOpenFile,
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.delete,
|
||||
handler: () => {
|
||||
setAnchorEl(null)
|
||||
if (batchMode) {
|
||||
if (onSelectionChange) {
|
||||
onSelectionChange()
|
||||
}
|
||||
} else {
|
||||
setConfirmOpen(true)
|
||||
}
|
||||
},
|
||||
disabled: false,
|
||||
},
|
||||
]
|
||||
// The context menu is closed on almost every render; building its items
|
||||
// only while open keeps the idle path allocation-free.
|
||||
const menuItems: ContextMenuItem[] =
|
||||
anchorEl === null
|
||||
? EMPTY_CONTEXT_MENU
|
||||
: hasUrl
|
||||
? [
|
||||
...(hasHome
|
||||
? [
|
||||
{
|
||||
label: menuLabels.home,
|
||||
handler: onOpenHome,
|
||||
disabled: false,
|
||||
} satisfies ContextMenuItem,
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label: menuLabels.select,
|
||||
handler: onForceSelect,
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.shareQrCode,
|
||||
handler: onShareQrCode,
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editInfo,
|
||||
handler: onEditInfo,
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editFile,
|
||||
handler: onEditFile,
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editRules,
|
||||
handler: onEditRules,
|
||||
disabled: !option?.rules,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editProxies,
|
||||
handler: onEditProxies,
|
||||
disabled: !option?.proxies,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editGroups,
|
||||
handler: onEditGroups,
|
||||
disabled: !option?.groups,
|
||||
},
|
||||
{
|
||||
label: menuLabels.extendConfig,
|
||||
handler: onEditMerge,
|
||||
disabled: !option?.merge,
|
||||
},
|
||||
{
|
||||
label: menuLabels.extendScript,
|
||||
handler: onEditScript,
|
||||
disabled: !option?.script,
|
||||
},
|
||||
{
|
||||
label: menuLabels.openFile,
|
||||
handler: onOpenFile,
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.update,
|
||||
handler: () => onUpdate(0),
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.updateViaProxy,
|
||||
handler: () => onUpdate(2),
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.delete,
|
||||
handler: () => {
|
||||
setAnchorEl(null)
|
||||
if (batchMode) {
|
||||
if (onSelectionChange) {
|
||||
onSelectionChange(id)
|
||||
}
|
||||
} else {
|
||||
setConfirmOpen(true)
|
||||
}
|
||||
},
|
||||
disabled: false,
|
||||
},
|
||||
]
|
||||
: [
|
||||
{
|
||||
label: menuLabels.select,
|
||||
handler: onForceSelect,
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editInfo,
|
||||
handler: onEditInfo,
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editFile,
|
||||
handler: onEditFile,
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editRules,
|
||||
handler: onEditRules,
|
||||
disabled: !option?.rules,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editProxies,
|
||||
handler: onEditProxies,
|
||||
disabled: !option?.proxies,
|
||||
},
|
||||
{
|
||||
label: menuLabels.editGroups,
|
||||
handler: onEditGroups,
|
||||
disabled: !option?.groups,
|
||||
},
|
||||
{
|
||||
label: menuLabels.extendConfig,
|
||||
handler: onEditMerge,
|
||||
disabled: !option?.merge,
|
||||
},
|
||||
{
|
||||
label: menuLabels.extendScript,
|
||||
handler: onEditScript,
|
||||
disabled: !option?.script,
|
||||
},
|
||||
{
|
||||
label: menuLabels.openFile,
|
||||
handler: onOpenFile,
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: menuLabels.delete,
|
||||
handler: () => {
|
||||
setAnchorEl(null)
|
||||
if (batchMode) {
|
||||
if (onSelectionChange) {
|
||||
onSelectionChange(id)
|
||||
}
|
||||
} else {
|
||||
setConfirmOpen(true)
|
||||
}
|
||||
},
|
||||
disabled: false,
|
||||
},
|
||||
]
|
||||
|
||||
const boxStyle = {
|
||||
height: 26,
|
||||
@@ -599,7 +607,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
|
||||
await profileDocument.reload()
|
||||
return
|
||||
}
|
||||
onSave?.(profileDocument.savedValue, currentValue)
|
||||
onSave?.(id, profileDocument.savedValue, currentValue)
|
||||
profileDocument.markSaved(currentValue)
|
||||
})
|
||||
|
||||
@@ -614,7 +622,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
|
||||
await mergeDocument.reload()
|
||||
return
|
||||
}
|
||||
onSave?.(mergeDocument.savedValue, currentValue)
|
||||
onSave?.(id, mergeDocument.savedValue, currentValue)
|
||||
mergeDocument.markSaved(currentValue)
|
||||
})
|
||||
|
||||
@@ -632,7 +640,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
|
||||
await scriptDocument.reload()
|
||||
return
|
||||
}
|
||||
onSave?.(scriptDocument.savedValue, currentValue)
|
||||
onSave?.(id, scriptDocument.savedValue, currentValue)
|
||||
scriptDocument.markSaved(currentValue)
|
||||
})
|
||||
|
||||
@@ -646,7 +654,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
|
||||
e.stopPropagation()
|
||||
return
|
||||
}
|
||||
onSelect(false)
|
||||
onSelect(id, false)
|
||||
}}
|
||||
onContextMenu={(event) => {
|
||||
const { clientX, clientY } = event
|
||||
@@ -687,7 +695,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
if (onSelectionChange) {
|
||||
onSelectionChange()
|
||||
onSelectionChange(id)
|
||||
}
|
||||
}}
|
||||
>
|
||||
@@ -853,7 +861,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
|
||||
e.preventDefault()
|
||||
}}
|
||||
>
|
||||
{(hasUrl ? urlModeMenu : fileModeMenu).map((item) => (
|
||||
{menuItems.map((item) => (
|
||||
<MenuItem
|
||||
key={item.label}
|
||||
onClick={item.handler}
|
||||
@@ -897,7 +905,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
|
||||
profileUid={uid!}
|
||||
property={option?.rules ?? ''}
|
||||
open={true}
|
||||
onSave={onSave}
|
||||
onSave={(prev, curr) => onSave?.(id, prev, curr)}
|
||||
onClose={() => setRulesOpen(false)}
|
||||
/>
|
||||
)}
|
||||
@@ -906,7 +914,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
|
||||
profileUid={uid!}
|
||||
property={option?.proxies ?? ''}
|
||||
open={true}
|
||||
onSave={onSave}
|
||||
onSave={(prev, curr) => onSave?.(id, prev, curr)}
|
||||
onClose={() => setProxiesOpen(false)}
|
||||
/>
|
||||
)}
|
||||
@@ -917,7 +925,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
|
||||
profileUid={uid!}
|
||||
property={option?.groups ?? ''}
|
||||
open={true}
|
||||
onSave={onSave}
|
||||
onSave={(prev, curr) => onSave?.(id, prev, curr)}
|
||||
onClose={() => {
|
||||
setGroupsOpen(false)
|
||||
}}
|
||||
@@ -963,7 +971,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
|
||||
onCancel={() => setConfirmOpen(false)}
|
||||
onClose={() => setConfirmOpen(false)}
|
||||
onOk={() => {
|
||||
onDelete()
|
||||
onDelete(id)
|
||||
setConfirmOpen(false)
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -112,9 +112,12 @@ export const ProfileMore = (props: Props) => {
|
||||
document.markSaved(currentValue)
|
||||
})
|
||||
|
||||
// document gets a fresh identity every render; setValue is the stable
|
||||
// useState setter, so the callback keys on it instead.
|
||||
const { setValue } = document
|
||||
const handleResetToDefault = useCallback(() => {
|
||||
document.setValue(DEFAULT_SCRIPT)
|
||||
}, [document])
|
||||
setValue(DEFAULT_SCRIPT)
|
||||
}, [setValue])
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -61,21 +61,26 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
|
||||
},
|
||||
})
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
create: () => {
|
||||
setOpenType('new')
|
||||
setOpen(true)
|
||||
},
|
||||
edit: (item: IProfileItem) => {
|
||||
if (item) {
|
||||
Object.entries(item).forEach(([key, value]) => {
|
||||
setValue(key as any, value)
|
||||
})
|
||||
}
|
||||
setOpenType('edit')
|
||||
setOpen(true)
|
||||
},
|
||||
}))
|
||||
// The handle only closes over stable form/state setters.
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
create: () => {
|
||||
setOpenType('new')
|
||||
setOpen(true)
|
||||
},
|
||||
edit: (item: IProfileItem) => {
|
||||
if (item) {
|
||||
Object.entries(item).forEach(([key, value]) => {
|
||||
setValue(key as any, value)
|
||||
})
|
||||
}
|
||||
setOpenType('edit')
|
||||
setOpen(true)
|
||||
},
|
||||
}),
|
||||
[setValue],
|
||||
)
|
||||
|
||||
const handleOk = useLockFn(
|
||||
handleSubmit(async (form) => {
|
||||
|
||||
@@ -123,7 +123,7 @@ export const ProxiesEditorViewer = (props: Props) => {
|
||||
proxy={item}
|
||||
onDelete={() => {
|
||||
if (isDeleted) {
|
||||
setDeleteSeq(deleteSeq.filter((v) => v !== item.name))
|
||||
setDeleteSeq((prev) => prev.filter((v) => v !== item.name))
|
||||
} else {
|
||||
setDeleteSeq((prev) => [...prev, item.name])
|
||||
}
|
||||
@@ -138,7 +138,7 @@ export const ProxiesEditorViewer = (props: Props) => {
|
||||
type="prepend"
|
||||
proxy={item}
|
||||
onDelete={() => {
|
||||
setPrependSeq(prependSeq.filter((v) => v.name !== item.name))
|
||||
setPrependSeq((prev) => prev.filter((v) => v.name !== item.name))
|
||||
}}
|
||||
/>
|
||||
)
|
||||
@@ -149,7 +149,7 @@ export const ProxiesEditorViewer = (props: Props) => {
|
||||
type="append"
|
||||
proxy={item}
|
||||
onDelete={() => {
|
||||
setAppendSeq(appendSeq.filter((v) => v.name !== item.name))
|
||||
setAppendSeq((prev) => prev.filter((v) => v.name !== item.name))
|
||||
}}
|
||||
/>
|
||||
)
|
||||
@@ -160,27 +160,28 @@ export const ProxiesEditorViewer = (props: Props) => {
|
||||
activeIndex: number,
|
||||
overIndex: number,
|
||||
) => {
|
||||
const list = category === 'prepend' ? prependSeq : appendSeq
|
||||
const filtered =
|
||||
category === 'prepend' ? filteredPrependSeq : filteredAppendSeq
|
||||
const setList = category === 'prepend' ? setPrependSeq : setAppendSeq
|
||||
const activeRealIndex = findRealIndex(list, filtered, activeIndex)
|
||||
const overRealIndex = findRealIndex(list, filtered, overIndex)
|
||||
if (
|
||||
activeRealIndex < 0 ||
|
||||
overRealIndex < 0 ||
|
||||
activeRealIndex === overRealIndex
|
||||
) {
|
||||
return
|
||||
}
|
||||
// Recompute inside the updater: two writes in one batch must not read the same pre-batch array.
|
||||
setList((prev) => {
|
||||
const filtered = prev.filter((v) => hasValidName(v) && match(v.name))
|
||||
const activeRealIndex = findRealIndex(prev, filtered, activeIndex)
|
||||
const overRealIndex = findRealIndex(prev, filtered, overIndex)
|
||||
if (
|
||||
activeRealIndex < 0 ||
|
||||
overRealIndex < 0 ||
|
||||
activeRealIndex === overRealIndex
|
||||
) {
|
||||
return prev
|
||||
}
|
||||
|
||||
setList(arrayMove(list, activeRealIndex, overRealIndex))
|
||||
return arrayMove(prev, activeRealIndex, overRealIndex)
|
||||
})
|
||||
}
|
||||
|
||||
// 优化:异步分片解析,避免主线程阻塞,解析完成后批量setState
|
||||
const handleParseAsync = (cb: (proxies: IProxyConfig[]) => void) => {
|
||||
const proxies: IProxyConfig[] = []
|
||||
const names: string[] = []
|
||||
const names = new Set<string>()
|
||||
let uris: string
|
||||
try {
|
||||
uris = atob(proxyUri)
|
||||
@@ -198,9 +199,9 @@ export const ProxiesEditorViewer = (props: Props) => {
|
||||
const uri = lines[idx]
|
||||
try {
|
||||
const proxy = parseUri(uri.trim())
|
||||
if (!names.includes(proxy.name)) {
|
||||
if (!names.has(proxy.name)) {
|
||||
proxies.push(proxy)
|
||||
names.push(proxy.name)
|
||||
names.add(proxy.name)
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
|
||||
@@ -318,7 +318,7 @@ export const RulesEditorViewer = (props: Props) => {
|
||||
ruleRaw={item}
|
||||
onDelete={() => {
|
||||
if (isDeleted) {
|
||||
setDeleteSeq(deleteSeq.filter((v) => v !== item))
|
||||
setDeleteSeq((prev) => prev.filter((v) => v !== item))
|
||||
} else {
|
||||
setDeleteSeq((prev) => [...prev, item])
|
||||
}
|
||||
@@ -333,13 +333,13 @@ export const RulesEditorViewer = (props: Props) => {
|
||||
type="prepend"
|
||||
ruleRaw={item}
|
||||
onDelete={() => {
|
||||
setPrependSeq(prependSeq.filter((v) => v !== item))
|
||||
setPrependSeq((prev) => prev.filter((v) => v !== item))
|
||||
}}
|
||||
onAppend={() => {
|
||||
setAppendSeq((prev) =>
|
||||
prev.includes(item) ? prev : [...prev, item],
|
||||
)
|
||||
setPrependSeq(prependSeq.filter((v) => v !== item))
|
||||
setPrependSeq((prev) => prev.filter((v) => v !== item))
|
||||
}}
|
||||
/>
|
||||
)
|
||||
@@ -350,13 +350,13 @@ export const RulesEditorViewer = (props: Props) => {
|
||||
type="append"
|
||||
ruleRaw={item}
|
||||
onDelete={() => {
|
||||
setAppendSeq(appendSeq.filter((v) => v !== item))
|
||||
setAppendSeq((prev) => prev.filter((v) => v !== item))
|
||||
}}
|
||||
onPrepend={() => {
|
||||
setPrependSeq((prev) =>
|
||||
prev.includes(item) ? prev : [...prev, item],
|
||||
)
|
||||
setAppendSeq(appendSeq.filter((v) => v !== item))
|
||||
setAppendSeq((prev) => prev.filter((v) => v !== item))
|
||||
}}
|
||||
/>
|
||||
)
|
||||
@@ -367,21 +367,22 @@ export const RulesEditorViewer = (props: Props) => {
|
||||
activeIndex: number,
|
||||
overIndex: number,
|
||||
) => {
|
||||
const list = category === 'prepend' ? prependSeq : appendSeq
|
||||
const filtered =
|
||||
category === 'prepend' ? filteredPrependSeq : filteredAppendSeq
|
||||
const setList = category === 'prepend' ? setPrependSeq : setAppendSeq
|
||||
const activeRealIndex = findRealIndex(list, filtered, activeIndex)
|
||||
const overRealIndex = findRealIndex(list, filtered, overIndex)
|
||||
if (
|
||||
activeRealIndex < 0 ||
|
||||
overRealIndex < 0 ||
|
||||
activeRealIndex === overRealIndex
|
||||
) {
|
||||
return
|
||||
}
|
||||
// Recompute inside the updater: two writes in one batch must not read the same pre-batch array.
|
||||
setList((prev) => {
|
||||
const filtered = prev.filter(match)
|
||||
const activeRealIndex = findRealIndex(prev, filtered, activeIndex)
|
||||
const overRealIndex = findRealIndex(prev, filtered, overIndex)
|
||||
if (
|
||||
activeRealIndex < 0 ||
|
||||
overRealIndex < 0 ||
|
||||
activeRealIndex === overRealIndex
|
||||
) {
|
||||
return prev
|
||||
}
|
||||
|
||||
setList(arrayMove(list, activeRealIndex, overRealIndex))
|
||||
return arrayMove(prev, activeRealIndex, overRealIndex)
|
||||
})
|
||||
}
|
||||
|
||||
const fetchContent = useCallback(async () => {
|
||||
@@ -748,8 +749,9 @@ export const RulesEditorViewer = (props: Props) => {
|
||||
onClick={() => {
|
||||
try {
|
||||
const raw = validateRule()
|
||||
if (prependSeq.includes(raw)) return
|
||||
setPrependSeq([raw, ...prependSeq])
|
||||
setPrependSeq((prev) =>
|
||||
prev.includes(raw) ? prev : [raw, ...prev],
|
||||
)
|
||||
} catch (err: any) {
|
||||
showNotice.error(err)
|
||||
}
|
||||
@@ -766,8 +768,9 @@ export const RulesEditorViewer = (props: Props) => {
|
||||
onClick={() => {
|
||||
try {
|
||||
const raw = validateRule()
|
||||
if (appendSeq.includes(raw)) return
|
||||
setAppendSeq([...appendSeq, raw])
|
||||
setAppendSeq((prev) =>
|
||||
prev.includes(raw) ? prev : [...prev, raw],
|
||||
)
|
||||
} catch (err: any) {
|
||||
showNotice.error(err)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import * as yaml from 'js-yaml'
|
||||
import {
|
||||
getRecord,
|
||||
rebindNode,
|
||||
sameSource,
|
||||
type ProxyNodeView,
|
||||
type ProxyViewV1,
|
||||
} from '@/types/proxy-view'
|
||||
@@ -20,22 +21,47 @@ export const rebindProxyChainItems = (
|
||||
items: readonly ProxyChainItem[],
|
||||
candidates: readonly ProxyNodeView[],
|
||||
proxyView: ProxyViewV1,
|
||||
): ProxyChainItem[] =>
|
||||
items.map((item) => {
|
||||
): ProxyChainItem[] => {
|
||||
// The proxy view refreshes on a fixed cadence; reusing item and array
|
||||
// identities while the rebound values are equal keeps persistence effects
|
||||
// and memoized chain rows from reprocessing identical content.
|
||||
let reboundItems: ProxyChainItem[] | undefined
|
||||
items.forEach((item, index) => {
|
||||
const rebound = rebindNode(candidates, {
|
||||
name: item.name,
|
||||
source: item.source,
|
||||
})
|
||||
const record =
|
||||
rebound === undefined ? undefined : getRecord(proxyView, rebound.recordId)
|
||||
return {
|
||||
const source = rebound?.source ?? item.source
|
||||
const type = rebound?.type ?? item.type
|
||||
const delay = record?.history.at(-1)?.delay
|
||||
const sourceReused =
|
||||
item.source === source ||
|
||||
(item.source !== undefined &&
|
||||
source !== undefined &&
|
||||
sameSource(item.source, source))
|
||||
|
||||
if (
|
||||
item.recordId === rebound?.recordId &&
|
||||
sourceReused &&
|
||||
item.type === type &&
|
||||
item.delay === delay
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
reboundItems ??= [...items]
|
||||
reboundItems[index] = {
|
||||
...item,
|
||||
recordId: rebound?.recordId,
|
||||
source: rebound?.source ?? item.source,
|
||||
type: rebound?.type ?? item.type,
|
||||
delay: record?.history.at(-1)?.delay,
|
||||
source,
|
||||
type,
|
||||
delay,
|
||||
}
|
||||
})
|
||||
return reboundItems ?? (items as ProxyChainItem[])
|
||||
}
|
||||
|
||||
interface ParsedChainConfig {
|
||||
proxies?: Array<{
|
||||
|
||||
@@ -57,6 +57,8 @@ const chainPointerSensor = PointerSensor.configure({
|
||||
activationConstraints: () => undefined,
|
||||
})
|
||||
|
||||
const CHAIN_SENSORS = [chainPointerSensor, KeyboardSensor]
|
||||
|
||||
type RuntimeConfigWithProxySequence = IConfigData & { proxies?: unknown }
|
||||
|
||||
interface ProxyChainProps {
|
||||
@@ -665,10 +667,7 @@ export const ProxyChain = ({
|
||||
</Button>
|
||||
</Box>
|
||||
) : (
|
||||
<DragDropProvider
|
||||
sensors={[chainPointerSensor, KeyboardSensor]}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
<DragDropProvider sensors={CHAIN_SENSORS} onDragEnd={handleDragEnd}>
|
||||
<Box sx={{ borderRadius: 1, minHeight: 60, p: 1 }}>
|
||||
{currentProxyChain.map((proxy, index) => (
|
||||
<SortableProxyChainItem
|
||||
|
||||
@@ -31,9 +31,9 @@ interface Props {
|
||||
url?: string
|
||||
groupName: string
|
||||
headState: HeadState
|
||||
onLocation: () => void
|
||||
onCheckDelay: () => void
|
||||
onHeadState: (val: Partial<HeadState>) => void
|
||||
onLocation: (groupName: string) => void
|
||||
onCheckDelay: (groupName: string) => void
|
||||
onHeadState: (groupName: string, val: Partial<HeadState>) => void
|
||||
}
|
||||
|
||||
export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
|
||||
@@ -76,7 +76,7 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
|
||||
// 因此对写入 headState 的动作做防抖,避免每输入一个字符就过滤一次。
|
||||
const { run: applyFilter, flush: flushFilter } = useDebounceFn(
|
||||
(state: SearchState) => {
|
||||
onHeadState({
|
||||
onHeadState(groupName, {
|
||||
filterText: state.text,
|
||||
filterMatchCase: state.matchCase,
|
||||
filterMatchWholeWord: state.matchWholeWord,
|
||||
@@ -125,7 +125,7 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
}}
|
||||
onChange={(e) => onHeadState({ testUrl: e.target.value })}
|
||||
onChange={(e) => onHeadState(groupName, { testUrl: e.target.value })}
|
||||
sx={{ flex: '1 1 auto', input: { py: 0.65, px: 1 } }}
|
||||
/>
|
||||
)}
|
||||
@@ -155,8 +155,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
|
||||
e.stopPropagation()
|
||||
if (!headState.open)
|
||||
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
|
||||
flushSync(() => onHeadState({ open: true }))
|
||||
onLocation()
|
||||
flushSync(() => onHeadState(groupName, { open: true }))
|
||||
onLocation(groupName)
|
||||
}}
|
||||
>
|
||||
<MyLocationRounded fontSize="inherit" />
|
||||
@@ -171,16 +171,16 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
|
||||
e.stopPropagation()
|
||||
if (!headState.open)
|
||||
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
|
||||
flushSync(() => onHeadState({ open: true }))
|
||||
flushSync(() => onHeadState(groupName, { open: true }))
|
||||
// Remind the user that it is custom test url
|
||||
if (testUrl?.trim() && textState !== 'filter') {
|
||||
onHeadState({ textState: 'url' })
|
||||
onHeadState(groupName, { textState: 'url' })
|
||||
}
|
||||
if (testUrl?.trim() && !isValidUrl(testUrl)) {
|
||||
showNotice.warning('proxies.feedback.warnings.invalidTestUrl')
|
||||
return
|
||||
}
|
||||
onCheckDelay()
|
||||
onCheckDelay(groupName)
|
||||
}}
|
||||
>
|
||||
<NetworkCheckRounded fontSize="inherit" />
|
||||
@@ -201,8 +201,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
|
||||
e.stopPropagation()
|
||||
if (!headState.open)
|
||||
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
|
||||
flushSync(() => onHeadState({ open: true }))
|
||||
onHeadState({
|
||||
flushSync(() => onHeadState(groupName, { open: true }))
|
||||
onHeadState(groupName, {
|
||||
sortType: ((sortType + 1) % 3) as ProxySortType,
|
||||
})
|
||||
}}
|
||||
@@ -219,7 +219,7 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
onHeadState({
|
||||
onHeadState(groupName, {
|
||||
textState: textState === 'url' ? null : 'url',
|
||||
})
|
||||
setTimeout(() => inputRef.current?.focus())
|
||||
@@ -245,8 +245,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
|
||||
e.stopPropagation()
|
||||
if (!headState.open)
|
||||
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
|
||||
flushSync(() => onHeadState({ open: true }))
|
||||
onHeadState({ showType: !showType })
|
||||
flushSync(() => onHeadState(groupName, { open: true }))
|
||||
onHeadState(groupName, { showType: !showType })
|
||||
}}
|
||||
>
|
||||
{showType ? (
|
||||
@@ -265,8 +265,10 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
|
||||
e.stopPropagation()
|
||||
if (!headState.open && textState !== 'filter')
|
||||
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
|
||||
flushSync(() => onHeadState({ open: true }))
|
||||
onHeadState({ textState: textState === 'filter' ? null : 'filter' })
|
||||
flushSync(() => onHeadState(groupName, { open: true }))
|
||||
onHeadState(groupName, {
|
||||
textState: textState === 'filter' ? null : 'filter',
|
||||
})
|
||||
setTimeout(() => inputRef.current?.focus())
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -93,7 +93,7 @@ interface ProxyGroupsChainProps {
|
||||
// Shared callbacks
|
||||
onCheckAll: (groupName: string) => void
|
||||
onHeadState: (groupName: string, patch: Partial<HeadState>) => void
|
||||
onLocation: (group: any) => void
|
||||
onLocation: (groupName: string) => void
|
||||
onGroupSelect: (groupName: string) => void
|
||||
onScrollToTop: () => void
|
||||
}
|
||||
@@ -245,7 +245,7 @@ function ProxyVirtualList({
|
||||
activeStickyIndex: number | null
|
||||
isChainMode?: boolean
|
||||
measureElement: (node: Element | null) => void
|
||||
onLocation: (group: any) => void
|
||||
onLocation: (groupName: string) => void
|
||||
onCheckAll: (groupName: string) => void
|
||||
onHeadState: (groupName: string, patch: Partial<HeadState>) => void
|
||||
onChangeProxy: (group: ProxyGroupView, member: ResolvedProxyMember) => void
|
||||
|
||||
@@ -60,6 +60,23 @@ const ProxyGroupsChain = lazy(() =>
|
||||
})),
|
||||
)
|
||||
|
||||
const SCROLL_POSITIONS_KEY = 'proxy-scroll-positions'
|
||||
type ScrollPositions = Record<string, number>
|
||||
let scrollPositionsCache: ScrollPositions | undefined
|
||||
|
||||
// Scroll handling runs per frame and is throttled to 500ms writes; keep the
|
||||
// parsed object so saves do not re-read and re-parse localStorage each time.
|
||||
const readScrollPositions = (): ScrollPositions | undefined => {
|
||||
if (scrollPositionsCache) return scrollPositionsCache
|
||||
try {
|
||||
const raw = localStorage.getItem(SCROLL_POSITIONS_KEY)
|
||||
if (raw) scrollPositionsCache = JSON.parse(raw) as ScrollPositions
|
||||
} catch (e) {
|
||||
console.error('Error restoring scroll position:', e)
|
||||
}
|
||||
return scrollPositionsCache
|
||||
}
|
||||
|
||||
function useStableCallback<T extends (...args: any[]) => any>(fn: T): T {
|
||||
const ref = useRef(fn)
|
||||
ref.current = fn
|
||||
@@ -150,13 +167,12 @@ function useProxyRenderState(
|
||||
|
||||
const saveScrollPosition = useCallback(
|
||||
(scrollTop: number) => {
|
||||
const scrollPositions = localStorage.getItem('proxy-scroll-positions')
|
||||
? JSON.parse(localStorage.getItem('proxy-scroll-positions') ?? '{}')
|
||||
: {}
|
||||
const scrollPositions = readScrollPositions() ?? {}
|
||||
scrollPositions[scrollPositionKey] = scrollTop
|
||||
scrollPositionsCache = scrollPositions
|
||||
try {
|
||||
localStorage.setItem(
|
||||
'proxy-scroll-positions',
|
||||
SCROLL_POSITIONS_KEY,
|
||||
JSON.stringify(scrollPositions),
|
||||
)
|
||||
} catch (e) {
|
||||
@@ -167,15 +183,10 @@ function useProxyRenderState(
|
||||
)
|
||||
|
||||
const getScrollPosition = useCallback(() => {
|
||||
try {
|
||||
const savedPositions = localStorage.getItem('proxy-scroll-positions')
|
||||
if (savedPositions) {
|
||||
const positions = JSON.parse(savedPositions)
|
||||
const savedPosition = positions[scrollPositionKey]
|
||||
return savedPosition ?? 0
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error restoring scroll position:', e)
|
||||
const savedPositions = readScrollPositions()
|
||||
if (savedPositions) {
|
||||
const savedPosition = savedPositions[scrollPositionKey]
|
||||
return savedPosition ?? 0
|
||||
}
|
||||
}, [scrollPositionKey])
|
||||
|
||||
@@ -240,9 +251,13 @@ function ChainProxyGroups(props: {
|
||||
|
||||
const rangeExtractor = useCallback(
|
||||
(range: Parameters<typeof defaultRangeExtractor>[0]) => {
|
||||
const activeStickyIndex = [...stickyGroupIndexes]
|
||||
.reverse()
|
||||
.find((index) => index <= range.startIndex)
|
||||
let activeStickyIndex: number | undefined
|
||||
for (let i = stickyGroupIndexes.length - 1; i >= 0; i--) {
|
||||
if (stickyGroupIndexes[i] <= range.startIndex) {
|
||||
activeStickyIndex = stickyGroupIndexes[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
activeStickyIndexRef.current = activeStickyIndex ?? null
|
||||
|
||||
const indexes = defaultRangeExtractor(range)
|
||||
@@ -324,16 +339,20 @@ function ChainProxyGroups(props: {
|
||||
scrollTopRef.current = 0
|
||||
}, [])
|
||||
|
||||
const handleLocation = useStableCallback((group: ProxyGroupView) => {
|
||||
if (!group) return
|
||||
const { name, now } = group
|
||||
const handleLocation = useStableCallback((groupName: string) => {
|
||||
// Flat (type 1) headers such as GLOBAL carry the same live group.
|
||||
const headerIndex = renderList.findIndex(
|
||||
(e) => (e.type === 0 || e.type === 1) && e.group?.name === groupName,
|
||||
)
|
||||
const now = renderList[headerIndex]?.group?.now
|
||||
if (!now) return
|
||||
|
||||
const index = renderList.findIndex(
|
||||
(item) =>
|
||||
item.group?.name === name &&
|
||||
((item.type === 2 && item.member?.member.ref.name === now) ||
|
||||
(item.type === 4 &&
|
||||
item.memberCol?.some(({ member }) => member.ref.name === now))),
|
||||
(e) =>
|
||||
e.group?.name === groupName &&
|
||||
((e.type === 2 && e.member?.member.ref.name === now) ||
|
||||
(e.type === 4 &&
|
||||
e.memberCol?.some(({ member }) => member.ref.name === now))),
|
||||
)
|
||||
|
||||
if (index >= 0) {
|
||||
@@ -496,13 +515,17 @@ function NormalProxyGroups(props: { mode: string }) {
|
||||
[globalGroupName, select, setHeadState],
|
||||
)
|
||||
|
||||
const handleLocation = useStableCallback((group: ProxyGroupView) => {
|
||||
if (!group) return
|
||||
const { name, now } = group
|
||||
const handleLocation = useStableCallback((groupName: string) => {
|
||||
// Flat (type 1) headers such as GLOBAL carry the same live group.
|
||||
const headerIndex = renderList.findIndex(
|
||||
(e) => (e.type === 0 || e.type === 1) && e.group?.name === groupName,
|
||||
)
|
||||
const now = renderList[headerIndex]?.group?.now
|
||||
if (!now) return
|
||||
|
||||
const index = renderList.findIndex(
|
||||
(e) =>
|
||||
e.group?.name === name &&
|
||||
e.group?.name === groupName &&
|
||||
((e.type === 2 && e.member?.member.ref.name === now) ||
|
||||
(e.type === 4 &&
|
||||
e.memberCol?.some(({ member }) => member.ref.name === now))),
|
||||
@@ -516,21 +539,20 @@ function NormalProxyGroups(props: { mode: string }) {
|
||||
}
|
||||
})
|
||||
|
||||
const handleGroupLocationByName = useCallback(
|
||||
(groupName: string) => {
|
||||
const index = renderList.findIndex(
|
||||
(item) => item.type === 0 && item.group?.name === groupName,
|
||||
)
|
||||
// Stable identity: this feeds the sticky-header render callback; a
|
||||
// [renderList] dep would re-create it on every list rebuild.
|
||||
const handleGroupLocationByName = useStableCallback((groupName: string) => {
|
||||
const index = renderList.findIndex(
|
||||
(item) => item.type === 0 && item.group?.name === groupName,
|
||||
)
|
||||
|
||||
if (index >= 0) {
|
||||
stickyListRef.current?.scrollToIndex(index, {
|
||||
align: 'start',
|
||||
behavior: 'smooth',
|
||||
})
|
||||
}
|
||||
},
|
||||
[renderList],
|
||||
)
|
||||
if (index >= 0) {
|
||||
stickyListRef.current?.scrollToIndex(index, {
|
||||
align: 'start',
|
||||
behavior: 'smooth',
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const proxyGroupNames = useMemo(() => {
|
||||
const names = renderList
|
||||
|
||||
@@ -30,9 +30,9 @@ interface Props {
|
||||
url?: string
|
||||
groupName: string
|
||||
headState: HeadState
|
||||
onLocation: () => void
|
||||
onCheckDelay: () => void
|
||||
onHeadState: (val: Partial<HeadState>) => void
|
||||
onLocation: (groupName: string) => void
|
||||
onCheckDelay: (groupName: string) => void
|
||||
onHeadState: (groupName: string, val: Partial<HeadState>) => void
|
||||
}
|
||||
|
||||
const defaultSx: SxProps = {}
|
||||
@@ -81,7 +81,7 @@ export const ProxyHead = ({
|
||||
size="small"
|
||||
color="inherit"
|
||||
title={t('proxies.page.tooltips.locate')}
|
||||
onClick={onLocation}
|
||||
onClick={() => onLocation(groupName)}
|
||||
>
|
||||
<MyLocationRounded />
|
||||
</IconButton>
|
||||
@@ -95,13 +95,13 @@ export const ProxyHead = ({
|
||||
// Remind the user that it is custom test url
|
||||
if (testUrl?.trim() && textState !== 'filter') {
|
||||
debugLog(`[ProxyHead] 使用自定义测试URL: ${testUrl}`)
|
||||
onHeadState({ textState: 'url' })
|
||||
onHeadState(groupName, { textState: 'url' })
|
||||
}
|
||||
if (testUrl?.trim() && !isValidUrl(testUrl)) {
|
||||
showNotice.warning('proxies.feedback.warnings.invalidTestUrl')
|
||||
return
|
||||
}
|
||||
onCheckDelay()
|
||||
onCheckDelay(groupName)
|
||||
}}
|
||||
>
|
||||
<NetworkCheckRounded />
|
||||
@@ -118,7 +118,9 @@ export const ProxyHead = ({
|
||||
][sortType]
|
||||
}
|
||||
onClick={() =>
|
||||
onHeadState({ sortType: ((sortType + 1) % 3) as ProxySortType })
|
||||
onHeadState(groupName, {
|
||||
sortType: ((sortType + 1) % 3) as ProxySortType,
|
||||
})
|
||||
}
|
||||
>
|
||||
{sortType !== 1 && sortType !== 2 && <SortRounded />}
|
||||
@@ -131,7 +133,9 @@ export const ProxyHead = ({
|
||||
color="inherit"
|
||||
title={t('proxies.page.tooltips.delayCheckUrl')}
|
||||
onClick={() =>
|
||||
onHeadState({ textState: textState === 'url' ? null : 'url' })
|
||||
onHeadState(groupName, {
|
||||
textState: textState === 'url' ? null : 'url',
|
||||
})
|
||||
}
|
||||
>
|
||||
{textState === 'url' ? (
|
||||
@@ -149,7 +153,7 @@ export const ProxyHead = ({
|
||||
? t('proxies.page.tooltips.showBasic')
|
||||
: t('proxies.page.tooltips.showDetail')
|
||||
}
|
||||
onClick={() => onHeadState({ showType: !showType })}
|
||||
onClick={() => onHeadState(groupName, { showType: !showType })}
|
||||
>
|
||||
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
|
||||
</IconButton>
|
||||
@@ -159,7 +163,9 @@ export const ProxyHead = ({
|
||||
color="inherit"
|
||||
title={t('proxies.page.tooltips.filter')}
|
||||
onClick={() =>
|
||||
onHeadState({ textState: textState === 'filter' ? null : 'filter' })
|
||||
onHeadState(groupName, {
|
||||
textState: textState === 'filter' ? null : 'filter',
|
||||
})
|
||||
}
|
||||
>
|
||||
{textState === 'filter' ? <SearchOffRounded /> : <SearchRounded />}
|
||||
@@ -176,7 +182,7 @@ export const ProxyHead = ({
|
||||
useRegularExpression: filterUseRegularExpression,
|
||||
}}
|
||||
onSearch={(_, state) =>
|
||||
onHeadState({
|
||||
onHeadState(groupName, {
|
||||
filterText: state.text,
|
||||
filterMatchCase: state.matchCase,
|
||||
filterMatchWholeWord: state.matchWholeWord,
|
||||
@@ -197,7 +203,7 @@ export const ProxyHead = ({
|
||||
size="small"
|
||||
variant="outlined"
|
||||
placeholder={t('proxies.page.placeholders.delayCheckUrl')}
|
||||
onChange={(e) => onHeadState({ testUrl: e.target.value })}
|
||||
onChange={(e) => onHeadState(groupName, { testUrl: e.target.value })}
|
||||
sx={{ ml: 0.5, flex: '1 1 auto', input: { py: 0.65, px: 1 } }}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -33,7 +33,7 @@ interface RenderProps {
|
||||
item: IRenderItem
|
||||
stickyed?: boolean
|
||||
isChainMode?: boolean
|
||||
onLocation: (group: IRenderItem['group']) => void
|
||||
onLocation: (groupName: string) => void
|
||||
onCheckAll: (groupName: string) => void
|
||||
onHeadState: (groupName: string, patch: Partial<HeadState>) => void
|
||||
onChangeProxy: (
|
||||
@@ -179,9 +179,9 @@ const ProxyGroupHeader = (props: RenderProps) => {
|
||||
url={group.testUrl!}
|
||||
groupName={group.name}
|
||||
headState={headState!}
|
||||
onLocation={() => onLocation(group)}
|
||||
onCheckDelay={() => onCheckAll(group.name)}
|
||||
onHeadState={(p) => onHeadState(group.name, p)}
|
||||
onLocation={onLocation}
|
||||
onCheckDelay={onCheckAll}
|
||||
onHeadState={onHeadState}
|
||||
/>
|
||||
{!toolsOnLeft && proxyCount}
|
||||
</ProxyGroupHeaderBlock>
|
||||
@@ -270,9 +270,9 @@ export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
|
||||
url={group.testUrl!}
|
||||
groupName={group.name}
|
||||
headState={headState!}
|
||||
onLocation={() => onLocation(group)}
|
||||
onCheckDelay={() => onCheckAll(group.name)}
|
||||
onHeadState={(p) => onHeadState(group.name, p)}
|
||||
onLocation={onLocation}
|
||||
onCheckDelay={onCheckAll}
|
||||
onHeadState={onHeadState}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -175,15 +175,19 @@ export const useRenderList = (
|
||||
chainOccurrencesRef.current = chainOccurrences
|
||||
const chainDelayGroup =
|
||||
mode === 'rule' && selectedGroup ? selectedGroup : CHAIN_DELAY_GROUP
|
||||
const chainDelayKey = chainOccurrences
|
||||
.map(({ member }) => {
|
||||
if (member.kind !== 'node') return `${member.kind}:${member.ref.name}`
|
||||
const source = member.node.source
|
||||
return source.kind === 'provider'
|
||||
? `provider:${source.providerName}:${source.proxyName}`
|
||||
: `core:${source.proxyName}`
|
||||
})
|
||||
.join('\u0000')
|
||||
const chainDelayKey = useMemo(
|
||||
() =>
|
||||
chainOccurrences
|
||||
.map(({ member }) => {
|
||||
if (member.kind !== 'node') return `${member.kind}:${member.ref.name}`
|
||||
const source = member.node.source
|
||||
return source.kind === 'provider'
|
||||
? `provider:${source.providerName}:${source.proxyName}`
|
||||
: `core:${source.proxyName}`
|
||||
})
|
||||
.join('\u0000'),
|
||||
[chainOccurrences],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isChainMode || !chainDelayKey) return
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
} from '@mui/material'
|
||||
import { useLockFn } from 'ahooks'
|
||||
import dayjs from 'dayjs'
|
||||
import { useState } from 'react'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { updateRuleProvider } from 'tauri-plugin-mihomo-api'
|
||||
|
||||
@@ -42,6 +42,11 @@ export const ProviderButton = () => {
|
||||
const { t } = useTranslation()
|
||||
const [open, setOpen] = useState(false)
|
||||
const { ruleProviders } = useRulesData()
|
||||
|
||||
const sortedProviderEntries = useMemo(
|
||||
() => Object.entries(ruleProviders || {}).sort(),
|
||||
[ruleProviders],
|
||||
)
|
||||
const { refreshRules, refreshRuleProviders } = useAppRefreshers()
|
||||
const [updating, setUpdating] = useState<Record<string, boolean>>({})
|
||||
|
||||
@@ -166,121 +171,119 @@ export const ProviderButton = () => {
|
||||
|
||||
<DialogContent>
|
||||
<List sx={{ py: 0, minHeight: 250 }}>
|
||||
{Object.entries(ruleProviders || {})
|
||||
.sort()
|
||||
.map(([key, item]) => {
|
||||
const provider = item
|
||||
const time = dayjs(provider.updatedAt)
|
||||
const isUpdating = updating[key]
|
||||
{sortedProviderEntries.map(([key, item]) => {
|
||||
const provider = item
|
||||
const time = dayjs(provider.updatedAt)
|
||||
const isUpdating = updating[key]
|
||||
|
||||
return (
|
||||
<ListItem
|
||||
key={key}
|
||||
sx={[
|
||||
{
|
||||
p: 0,
|
||||
mb: '8px',
|
||||
borderRadius: 2,
|
||||
overflow: 'hidden',
|
||||
transition: 'all 0.2s',
|
||||
},
|
||||
({ palette: { mode, primary } }) => {
|
||||
const bgcolor = mode === 'light' ? '#ffffff' : '#24252f'
|
||||
const hoverColor =
|
||||
mode === 'light'
|
||||
? alpha(primary.main, 0.1)
|
||||
: alpha(primary.main, 0.2)
|
||||
return (
|
||||
<ListItem
|
||||
key={key}
|
||||
sx={[
|
||||
{
|
||||
p: 0,
|
||||
mb: '8px',
|
||||
borderRadius: 2,
|
||||
overflow: 'hidden',
|
||||
transition: 'all 0.2s',
|
||||
},
|
||||
({ palette: { mode, primary } }) => {
|
||||
const bgcolor = mode === 'light' ? '#ffffff' : '#24252f'
|
||||
const hoverColor =
|
||||
mode === 'light'
|
||||
? alpha(primary.main, 0.1)
|
||||
: alpha(primary.main, 0.2)
|
||||
|
||||
return {
|
||||
backgroundColor: bgcolor,
|
||||
'&:hover': {
|
||||
backgroundColor: hoverColor,
|
||||
borderColor: alpha(primary.main, 0.3),
|
||||
},
|
||||
}
|
||||
},
|
||||
]}
|
||||
>
|
||||
<ListItemText
|
||||
sx={{ px: 2, py: 1 }}
|
||||
primary={
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
variant="subtitle1"
|
||||
component="div"
|
||||
noWrap
|
||||
title={key}
|
||||
sx={{ display: 'flex', alignItems: 'center' }}
|
||||
>
|
||||
<span style={{ marginRight: '8px' }}>{key}</span>
|
||||
<TypeBox component="span">
|
||||
{provider.ruleCount}
|
||||
</TypeBox>
|
||||
</Typography>
|
||||
|
||||
<Typography
|
||||
variant="body2"
|
||||
color="text.secondary"
|
||||
noWrap
|
||||
>
|
||||
<small>{t('shared.labels.updateAt')}: </small>
|
||||
{time.fromNow()}
|
||||
</Typography>
|
||||
</Box>
|
||||
return {
|
||||
backgroundColor: bgcolor,
|
||||
'&:hover': {
|
||||
backgroundColor: hoverColor,
|
||||
borderColor: alpha(primary.main, 0.3),
|
||||
},
|
||||
}
|
||||
secondary={
|
||||
<Box sx={{ display: 'flex' }}>
|
||||
<TypeBox component="span">
|
||||
{typeof provider.vehicleType === 'string'
|
||||
? provider.vehicleType
|
||||
: provider.vehicleType.Unknown}
|
||||
</TypeBox>
|
||||
<TypeBox component="span">
|
||||
{typeof provider.behavior === 'string'
|
||||
? provider.behavior
|
||||
: provider.behavior.Unknown}
|
||||
</TypeBox>
|
||||
</Box>
|
||||
}
|
||||
/>
|
||||
<Divider orientation="vertical" flexItem />
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<IconButton
|
||||
size="small"
|
||||
color="primary"
|
||||
onClick={() => updateProvider(key)}
|
||||
disabled={isUpdating}
|
||||
aria-label={t('rules.page.provider.actions.update')}
|
||||
},
|
||||
]}
|
||||
>
|
||||
<ListItemText
|
||||
sx={{ px: 2, py: 1 }}
|
||||
primary={
|
||||
<Box
|
||||
sx={{
|
||||
animation: isUpdating
|
||||
? 'spin 1s linear infinite'
|
||||
: 'none',
|
||||
'@keyframes spin': {
|
||||
'0%': { transform: 'rotate(0deg)' },
|
||||
'100%': { transform: 'rotate(360deg)' },
|
||||
},
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
title={t('rules.page.provider.actions.update')}
|
||||
>
|
||||
<RefreshRounded />
|
||||
</IconButton>
|
||||
</Box>
|
||||
</ListItem>
|
||||
)
|
||||
})}
|
||||
<Typography
|
||||
variant="subtitle1"
|
||||
component="div"
|
||||
noWrap
|
||||
title={key}
|
||||
sx={{ display: 'flex', alignItems: 'center' }}
|
||||
>
|
||||
<span style={{ marginRight: '8px' }}>{key}</span>
|
||||
<TypeBox component="span">
|
||||
{provider.ruleCount}
|
||||
</TypeBox>
|
||||
</Typography>
|
||||
|
||||
<Typography
|
||||
variant="body2"
|
||||
color="text.secondary"
|
||||
noWrap
|
||||
>
|
||||
<small>{t('shared.labels.updateAt')}: </small>
|
||||
{time.fromNow()}
|
||||
</Typography>
|
||||
</Box>
|
||||
}
|
||||
secondary={
|
||||
<Box sx={{ display: 'flex' }}>
|
||||
<TypeBox component="span">
|
||||
{typeof provider.vehicleType === 'string'
|
||||
? provider.vehicleType
|
||||
: provider.vehicleType.Unknown}
|
||||
</TypeBox>
|
||||
<TypeBox component="span">
|
||||
{typeof provider.behavior === 'string'
|
||||
? provider.behavior
|
||||
: provider.behavior.Unknown}
|
||||
</TypeBox>
|
||||
</Box>
|
||||
}
|
||||
/>
|
||||
<Divider orientation="vertical" flexItem />
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<IconButton
|
||||
size="small"
|
||||
color="primary"
|
||||
onClick={() => updateProvider(key)}
|
||||
disabled={isUpdating}
|
||||
aria-label={t('rules.page.provider.actions.update')}
|
||||
sx={{
|
||||
animation: isUpdating
|
||||
? 'spin 1s linear infinite'
|
||||
: 'none',
|
||||
'@keyframes spin': {
|
||||
'0%': { transform: 'rotate(0deg)' },
|
||||
'100%': { transform: 'rotate(360deg)' },
|
||||
},
|
||||
}}
|
||||
title={t('rules.page.provider.actions.update')}
|
||||
>
|
||||
<RefreshRounded />
|
||||
</IconButton>
|
||||
</Box>
|
||||
</ListItem>
|
||||
)
|
||||
})}
|
||||
</List>
|
||||
</DialogContent>
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
Tooltip,
|
||||
} from '@mui/material'
|
||||
import { useLockFn } from 'ahooks'
|
||||
import { useState, type Ref } from 'react'
|
||||
import { useRef, useState, type Ref } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { BaseDialog, DialogRef, Switch } from '@/components/base'
|
||||
@@ -26,6 +26,10 @@ export function ControllerViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
const { t } = useTranslation()
|
||||
const [open, setOpen] = useState(false)
|
||||
const [copySuccess, setCopySuccess] = useState<null | string>(null)
|
||||
// A second copy within the window must not be hidden by the first timer.
|
||||
const copySuccessTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(
|
||||
undefined,
|
||||
)
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
|
||||
const { clashInfo, patchInfo } = useClashInfo()
|
||||
@@ -36,6 +40,14 @@ export function ControllerViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
verge?.enable_external_controller ?? false,
|
||||
)
|
||||
|
||||
// A reopen within the window must not replay the previous session's toast.
|
||||
const closeDialog = () => {
|
||||
clearTimeout(copySuccessTimerRef.current)
|
||||
copySuccessTimerRef.current = undefined
|
||||
setCopySuccess(null)
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
// 对话框打开时初始化配置
|
||||
useSettingDialog(ref, 'controller-viewer', open, () => ({
|
||||
open: async () => {
|
||||
@@ -44,7 +56,7 @@ export function ControllerViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
setSecret(clashInfo?.secret || '')
|
||||
setEnableController(verge?.enable_external_controller ?? false)
|
||||
},
|
||||
close: () => setOpen(false),
|
||||
close: closeDialog,
|
||||
}))
|
||||
|
||||
// 保存配置
|
||||
@@ -78,7 +90,7 @@ export function ControllerViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
}
|
||||
|
||||
showNotice.success('shared.feedback.notifications.common.saveSuccess')
|
||||
setOpen(false)
|
||||
closeDialog()
|
||||
} catch (err) {
|
||||
showNotice.error(
|
||||
'shared.feedback.notifications.common.saveFailed',
|
||||
@@ -96,7 +108,11 @@ export function ControllerViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
setCopySuccess(type)
|
||||
setTimeout(() => setCopySuccess(null))
|
||||
clearTimeout(copySuccessTimerRef.current)
|
||||
copySuccessTimerRef.current = setTimeout(
|
||||
() => setCopySuccess(null),
|
||||
2000,
|
||||
)
|
||||
} catch (err) {
|
||||
console.warn('[ControllerViewer] copy to clipboard failed:', err)
|
||||
showNotice.error(
|
||||
@@ -122,8 +138,8 @@ export function ControllerViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
)
|
||||
}
|
||||
cancelBtn={t('shared.actions.cancel')}
|
||||
onClose={() => setOpen(false)}
|
||||
onCancel={() => setOpen(false)}
|
||||
onClose={closeDialog}
|
||||
onCancel={closeDialog}
|
||||
onOk={onSave}
|
||||
>
|
||||
<span data-settings-dialog="controller-viewer" />
|
||||
|
||||
@@ -51,6 +51,25 @@ const Item = styled(ListItem)(() => ({
|
||||
},
|
||||
}))
|
||||
|
||||
// Static editor settings; a per-render object would re-trigger Monaco's
|
||||
// updateOptions and listener resubscription on every keystroke. The minimap
|
||||
// depends on the live window width and is applied at editor mount instead.
|
||||
const MONACO_OPTIONS = {
|
||||
tabSize: 2,
|
||||
mouseWheelZoom: true,
|
||||
quickSuggestions: {
|
||||
strings: true,
|
||||
comments: true,
|
||||
other: true,
|
||||
},
|
||||
padding: {
|
||||
top: 33,
|
||||
},
|
||||
fontFamily: MONACO_FONT_FAMILY,
|
||||
fontLigatures: false,
|
||||
smoothScrolling: true,
|
||||
} as const
|
||||
|
||||
type NameserverPolicy = Record<string, any>
|
||||
|
||||
function parseNameserverPolicy(str: string): NameserverPolicy {
|
||||
@@ -520,9 +539,21 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
}
|
||||
})
|
||||
|
||||
const handleYamlChange = (value?: string) => {
|
||||
const handleYamlChange = useCallback((value?: string) => {
|
||||
setYamlContent(value || '')
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleEditorMount = useCallback(
|
||||
(editorInstance: MonacoEditorInstance) => {
|
||||
editorRef.current = editorInstance
|
||||
editorInstance.updateOptions({
|
||||
minimap: {
|
||||
enabled: document.documentElement.clientWidth >= 1500,
|
||||
},
|
||||
})
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
const handleChange = (field: string) => (event: any) => {
|
||||
const value =
|
||||
@@ -1052,27 +1083,8 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
value={yamlContent}
|
||||
theme={themeMode === 'light' ? 'light' : 'vs-dark'}
|
||||
className="flex-grow"
|
||||
onMount={(editorInstance) => {
|
||||
editorRef.current = editorInstance
|
||||
}}
|
||||
options={{
|
||||
tabSize: 2,
|
||||
minimap: {
|
||||
enabled: document.documentElement.clientWidth >= 1500,
|
||||
},
|
||||
mouseWheelZoom: true,
|
||||
quickSuggestions: {
|
||||
strings: true,
|
||||
comments: true,
|
||||
other: true,
|
||||
},
|
||||
padding: {
|
||||
top: 33,
|
||||
},
|
||||
fontFamily: MONACO_FONT_FAMILY,
|
||||
fontLigatures: false,
|
||||
smoothScrolling: true,
|
||||
}}
|
||||
onMount={handleEditorMount}
|
||||
options={MONACO_OPTIONS}
|
||||
onChange={handleYamlChange}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -42,6 +42,8 @@ const HOTKEY_FUNC_LABELS: Record<(typeof HOTKEY_FUNC)[number], string> = {
|
||||
reactivate_profiles: 'settings.modals.hotkey.functions.reactivateProfiles',
|
||||
}
|
||||
|
||||
const EMPTY_KEYS: string[] = []
|
||||
|
||||
export const HotkeyViewer = forwardRef<DialogRef>((props, ref) => {
|
||||
const { t } = useTranslation()
|
||||
const [open, setOpen] = useState(false)
|
||||
@@ -132,7 +134,7 @@ export const HotkeyViewer = forwardRef<DialogRef>((props, ref) => {
|
||||
<ItemWrapper key={func} data-setting-target={HOTKEY_FUNC_LABELS[func]}>
|
||||
<Typography>{t(HOTKEY_FUNC_LABELS[func])}</Typography>
|
||||
<HotkeyInput
|
||||
value={hotkeyMap[func] ?? []}
|
||||
value={hotkeyMap[func] ?? EMPTY_KEYS}
|
||||
onChange={(v) => setHotkeyMap((m) => ({ ...m, [func]: v }))}
|
||||
/>
|
||||
</ItemWrapper>
|
||||
|
||||
@@ -14,10 +14,16 @@ import { convertFileSrc } from '@tauri-apps/api/core'
|
||||
import { join } from '@tauri-apps/api/path'
|
||||
import { open as openDialog } from '@tauri-apps/plugin-dialog'
|
||||
import { exists } from '@tauri-apps/plugin-fs'
|
||||
import { forwardRef, useEffect, useState } from 'react'
|
||||
import { forwardRef, useEffect, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { BaseDialog, DialogRef, Switch, TooltipIcon } from '@/components/base'
|
||||
import {
|
||||
BaseDialog,
|
||||
DialogRef,
|
||||
Switch,
|
||||
TooltipIcon,
|
||||
switchChangeValue,
|
||||
} from '@/components/base'
|
||||
import { DEFAULT_HOVER_DELAY } from '@/components/proxy/proxy-group-navigator'
|
||||
import { useVerge } from '@/hooks/use-verge'
|
||||
import { useWindowDecorations } from '@/hooks/use-window'
|
||||
@@ -62,9 +68,16 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
||||
|
||||
const { decorated, toggleDecorations } = useWindowDecorations()
|
||||
|
||||
// Icon paths are only reachable from the open dialog; both settings sections
|
||||
// mount this viewer, so an eager read would double ~11 IPC calls per visit.
|
||||
// Loaded once per mount, deferred to the first open.
|
||||
const iconsLoadedRef = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || iconsLoadedRef.current) return
|
||||
iconsLoadedRef.current = true
|
||||
initIconPath()
|
||||
}, [])
|
||||
}, [open])
|
||||
|
||||
async function initIconPath() {
|
||||
const appDir = await getAppDir()
|
||||
@@ -104,12 +117,11 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
||||
close: () => setOpen(false),
|
||||
}))
|
||||
|
||||
const onSwitchFormat = (_e: any, value: boolean) => value
|
||||
const onError = (err: any) => {
|
||||
showNotice.error(err)
|
||||
}
|
||||
const onChangeData = (patch: Partial<IVergeConfig>) => {
|
||||
mutateVerge({ ...verge, ...patch })
|
||||
mutateVerge((prev) => ({ ...prev, ...patch }))
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -134,7 +146,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
||||
value={decorated}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onFormat={switchChangeValue}
|
||||
onChange={async () => {
|
||||
await toggleDecorations()
|
||||
}}
|
||||
@@ -151,7 +163,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
||||
value={verge?.traffic_graph ?? true}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onFormat={switchChangeValue}
|
||||
onChange={(e) => onChangeData({ traffic_graph: e })}
|
||||
onGuard={(e) => patchVerge({ traffic_graph: e })}
|
||||
>
|
||||
@@ -167,7 +179,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
||||
value={verge?.enable_memory_usage ?? true}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onFormat={switchChangeValue}
|
||||
onChange={(e) => onChangeData({ enable_memory_usage: e })}
|
||||
onGuard={(e) => patchVerge({ enable_memory_usage: e })}
|
||||
>
|
||||
@@ -185,7 +197,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
||||
value={verge?.enable_group_icon ?? true}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onFormat={switchChangeValue}
|
||||
onChange={(e) => onChangeData({ enable_group_icon: e })}
|
||||
onGuard={(e) => patchVerge({ enable_group_icon: e })}
|
||||
>
|
||||
@@ -203,7 +215,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
||||
value={verge?.pause_render_traffic_stats_on_blur ?? true}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onFormat={switchChangeValue}
|
||||
onChange={(e) =>
|
||||
onChangeData({ pause_render_traffic_stats_on_blur: e })
|
||||
}
|
||||
@@ -271,7 +283,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
||||
value={verge?.enable_hover_jump_navigator ?? true}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onFormat={switchChangeValue}
|
||||
onChange={(e) => onChangeData({ enable_hover_jump_navigator: e })}
|
||||
onGuard={(e) => patchVerge({ enable_hover_jump_navigator: e })}
|
||||
>
|
||||
@@ -373,7 +385,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
||||
value={verge?.collapse_navbar ?? false}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onFormat={switchChangeValue}
|
||||
onChange={(e) => onChangeData({ collapse_navbar: e })}
|
||||
onGuard={(e) => patchVerge({ collapse_navbar: e })}
|
||||
>
|
||||
@@ -420,7 +432,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
||||
value={verge?.enable_tray_speed ?? false}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onFormat={switchChangeValue}
|
||||
onChange={(e) => onChangeData({ enable_tray_speed: e })}
|
||||
onGuard={(e) => patchVerge({ enable_tray_speed: e })}
|
||||
>
|
||||
@@ -440,7 +452,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
||||
}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onFormat={switchChangeValue}
|
||||
onChange={(e) => onChangeData({ enable_tray_icon: e })}
|
||||
onGuard={(e) => patchVerge({ enable_tray_icon: e })}
|
||||
>
|
||||
@@ -494,7 +506,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
||||
value={verge?.tray_inline_outbound_modes ?? false}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onFormat={switchChangeValue}
|
||||
onChange={(e) => onChangeData({ tray_inline_outbound_modes: e })}
|
||||
onGuard={(e) => patchVerge({ tray_inline_outbound_modes: e })}
|
||||
>
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
TextField,
|
||||
} from '@mui/material'
|
||||
import { useLockFn } from 'ahooks'
|
||||
import { forwardRef, useState } from 'react'
|
||||
import { forwardRef, useMemo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { BaseDialog, DialogRef, Switch, TooltipIcon } from '@/components/base'
|
||||
@@ -17,6 +17,20 @@ import { showNotice } from '@/services/notice-service'
|
||||
|
||||
import { useSettingDialog } from '../settings-search-context'
|
||||
|
||||
const APP_LOG_LEVEL_OPTIONS = [
|
||||
'trace',
|
||||
'debug',
|
||||
'info',
|
||||
'warn',
|
||||
'error',
|
||||
'silent',
|
||||
].map((level) => ({
|
||||
value: level,
|
||||
label: level[0].toUpperCase() + level.slice(1).toLowerCase(),
|
||||
}))
|
||||
|
||||
const PROXY_LAYOUT_COLUMN_VALUES = [1, 2, 3, 4, 5]
|
||||
|
||||
const buildInitialValues = (verge?: IVergeConfig | null) => ({
|
||||
appLogLevel: verge?.app_log_level ?? 'warn',
|
||||
appLogMaxSize: verge?.app_log_max_size ?? 128,
|
||||
@@ -24,7 +38,6 @@ const buildInitialValues = (verge?: IVergeConfig | null) => ({
|
||||
autoCloseConnection: verge?.auto_close_connection ?? true,
|
||||
autoSwitchSelectorGroup: verge?.auto_switch_selector_group ?? true,
|
||||
autoCheckUpdate: verge?.auto_check_update ?? true,
|
||||
updateChannel: verge?.update_channel || 'auto',
|
||||
enableBuiltinEnhanced: verge?.enable_builtin_enhanced ?? true,
|
||||
proxyLayoutColumn: verge?.proxy_layout_column || 6,
|
||||
enableAutoDelayDetection: verge?.enable_auto_delay_detection ?? false,
|
||||
@@ -39,6 +52,40 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
|
||||
const { t } = useTranslation()
|
||||
const { verge, patchVerge } = useVerge()
|
||||
|
||||
const autoLogCleanOptions = useMemo(
|
||||
() => [
|
||||
{
|
||||
key: t('settings.modals.misc.options.autoLogClean.never'),
|
||||
value: 0,
|
||||
},
|
||||
{
|
||||
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
|
||||
n: 1,
|
||||
}),
|
||||
value: 1,
|
||||
},
|
||||
{
|
||||
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
|
||||
n: 7,
|
||||
}),
|
||||
value: 2,
|
||||
},
|
||||
{
|
||||
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
|
||||
n: 30,
|
||||
}),
|
||||
value: 3,
|
||||
},
|
||||
{
|
||||
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
|
||||
n: 90,
|
||||
}),
|
||||
value: 4,
|
||||
},
|
||||
],
|
||||
[t],
|
||||
)
|
||||
|
||||
const [open, setOpen] = useState(false)
|
||||
const [values, setValues] = useState(() => buildInitialValues(null))
|
||||
|
||||
@@ -59,7 +106,6 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
|
||||
auto_close_connection: values.autoCloseConnection,
|
||||
auto_switch_selector_group: values.autoSwitchSelectorGroup,
|
||||
auto_check_update: values.autoCheckUpdate,
|
||||
update_channel: values.updateChannel,
|
||||
enable_builtin_enhanced: values.enableBuiltinEnhanced,
|
||||
proxy_layout_column: values.proxyLayoutColumn,
|
||||
enable_auto_delay_detection: values.enableAutoDelayDetection,
|
||||
@@ -106,9 +152,9 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
|
||||
}))
|
||||
}
|
||||
>
|
||||
{['trace', 'debug', 'info', 'warn', 'error', 'silent'].map((i) => (
|
||||
<MenuItem value={i} key={i}>
|
||||
{i[0].toUpperCase() + i.slice(1).toLowerCase()}
|
||||
{APP_LOG_LEVEL_OPTIONS.map(({ value, label }) => (
|
||||
<MenuItem value={value} key={value}>
|
||||
{label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
@@ -244,36 +290,6 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
|
||||
/>
|
||||
</ListItem>
|
||||
|
||||
<ListItem
|
||||
data-setting-target="settings.modals.misc.fields.updateChannel"
|
||||
sx={{ padding: '5px 2px' }}
|
||||
>
|
||||
<ListItemText
|
||||
primary={t('settings.modals.misc.fields.updateChannel')}
|
||||
/>
|
||||
<Select
|
||||
size="small"
|
||||
sx={{ width: 160, '> div': { py: '7.5px' } }}
|
||||
value={values.updateChannel}
|
||||
onChange={(e) =>
|
||||
setValues((v) => ({
|
||||
...v,
|
||||
updateChannel: e.target.value as string,
|
||||
}))
|
||||
}
|
||||
>
|
||||
<MenuItem value="auto">
|
||||
{t('settings.modals.misc.options.updateChannel.auto')}
|
||||
</MenuItem>
|
||||
<MenuItem value="github">
|
||||
{t('settings.modals.misc.options.updateChannel.github')}
|
||||
</MenuItem>
|
||||
<MenuItem value="github_proxy">
|
||||
{t('settings.modals.misc.options.updateChannel.githubProxy')}
|
||||
</MenuItem>
|
||||
</Select>
|
||||
</ListItem>
|
||||
|
||||
<ListItem
|
||||
data-setting-target="settings.modals.misc.fields.enableBuiltinEnhanced"
|
||||
sx={{ padding: '5px 2px' }}
|
||||
@@ -317,7 +333,7 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
|
||||
<MenuItem value={6} key={6}>
|
||||
{t('settings.modals.misc.options.proxyLayoutColumns.auto')}
|
||||
</MenuItem>
|
||||
{[1, 2, 3, 4, 5].map((i) => (
|
||||
{PROXY_LAYOUT_COLUMN_VALUES.map((i) => (
|
||||
<MenuItem value={i} key={i}>
|
||||
{i}
|
||||
</MenuItem>
|
||||
@@ -344,36 +360,7 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
|
||||
}
|
||||
>
|
||||
{/* 1: 1天, 2: 7天, 3: 30天, 4: 90天*/}
|
||||
{[
|
||||
{
|
||||
key: t('settings.modals.misc.options.autoLogClean.never'),
|
||||
value: 0,
|
||||
},
|
||||
{
|
||||
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
|
||||
n: 1,
|
||||
}),
|
||||
value: 1,
|
||||
},
|
||||
{
|
||||
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
|
||||
n: 7,
|
||||
}),
|
||||
value: 2,
|
||||
},
|
||||
{
|
||||
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
|
||||
n: 30,
|
||||
}),
|
||||
value: 3,
|
||||
},
|
||||
{
|
||||
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
|
||||
n: 90,
|
||||
}),
|
||||
value: 4,
|
||||
},
|
||||
].map((i) => (
|
||||
{autoLogCleanOptions.map((i) => (
|
||||
<MenuItem key={i.value} value={i.value}>
|
||||
{i.key}
|
||||
</MenuItem>
|
||||
|
||||
@@ -84,6 +84,19 @@ const splitBypass = (value?: string) =>
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
const OS = getSystem()
|
||||
|
||||
const DEFAULT_BYPASS =
|
||||
OS === 'windows'
|
||||
? 'localhost;127.*;192.168.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;*.local;<local>'
|
||||
: OS === 'linux'
|
||||
? 'localhost,127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,::1'
|
||||
: '127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,localhost,*.local,*.crashlytics.com,<local>'
|
||||
|
||||
const DEFAULT_BYPASS_CHIPS = splitBypass(DEFAULT_BYPASS)
|
||||
|
||||
const BYPASS_SEPARATOR = OS === 'windows' ? ';' : ','
|
||||
|
||||
const buildInitialValues = (verge?: IVergeConfig | null) => ({
|
||||
guard: verge?.enable_proxy_guard,
|
||||
enable_bypass_check: verge?.enable_bypass_check ?? true,
|
||||
@@ -97,8 +110,7 @@ const buildInitialValues = (verge?: IVergeConfig | null) => ({
|
||||
|
||||
export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
|
||||
const { t } = useTranslation()
|
||||
const systemName = getSystem()
|
||||
const isWindows = systemName === 'windows'
|
||||
const isWindows = OS === 'windows'
|
||||
const validReg = useMemo(() => getValidReg(isWindows), [isWindows])
|
||||
|
||||
const [open, setOpen] = useState(false)
|
||||
@@ -130,17 +142,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
|
||||
queryFn: getEmbeddedServerPort,
|
||||
})
|
||||
|
||||
const separator = useMemo(() => (isWindows ? ';' : ','), [isWindows])
|
||||
|
||||
const defaultBypass = () => {
|
||||
if (isWindows) {
|
||||
return 'localhost;127.*;192.168.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;*.local;<local>'
|
||||
}
|
||||
if (systemName === 'linux') {
|
||||
return 'localhost,127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,::1'
|
||||
}
|
||||
return '127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,localhost,*.local,*.crashlytics.com,<local>'
|
||||
}
|
||||
const separator = BYPASS_SEPARATOR
|
||||
|
||||
const { systemProxyAddress } = useSystemData()
|
||||
const displayedMixedPort = useDisplayedMixedPort()
|
||||
@@ -326,7 +328,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
|
||||
Promise.resolve().then(async () => {
|
||||
try {
|
||||
if (Object.keys(patch).length > 0) {
|
||||
mutateVerge({ ...verge, ...patch })
|
||||
mutateVerge((prev) => ({ ...prev, ...patch }))
|
||||
}
|
||||
if (Object.keys(patch).length > 0) {
|
||||
await patchVerge(patch)
|
||||
@@ -503,7 +505,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
|
||||
checked={value.use_default}
|
||||
onChange={(_, e) => {
|
||||
if (!e && !value.bypass) {
|
||||
const nextBypass = defaultBypass()
|
||||
const nextBypass = DEFAULT_BYPASS
|
||||
setValue((v) => ({
|
||||
...v,
|
||||
use_default: e,
|
||||
@@ -575,7 +577,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
|
||||
/>
|
||||
<Box sx={{ padding: '0 2px 5px' }}>
|
||||
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
|
||||
{splitBypass(defaultBypass()).map((item) => (
|
||||
{DEFAULT_BYPASS_CHIPS.map((item) => (
|
||||
<Chip key={item} label={item} size="small" />
|
||||
))}
|
||||
</Box>
|
||||
|
||||
@@ -20,6 +20,12 @@ import { showNotice } from '@/services/notice-service'
|
||||
|
||||
import { useSettingDialog } from '../settings-search-context'
|
||||
|
||||
const textProps = {
|
||||
size: 'small',
|
||||
autoComplete: 'off',
|
||||
sx: { width: 135 },
|
||||
} as const
|
||||
|
||||
export function ThemeViewer(props: { ref?: React.Ref<DialogRef> }) {
|
||||
const { ref } = props
|
||||
const { t } = useTranslation()
|
||||
@@ -45,12 +51,6 @@ export function ThemeViewer(props: { ref?: React.Ref<DialogRef> }) {
|
||||
close: () => setOpen(false),
|
||||
}))
|
||||
|
||||
const textProps = {
|
||||
size: 'small',
|
||||
autoComplete: 'off',
|
||||
sx: { width: 135 },
|
||||
} as const
|
||||
|
||||
const handleChange = (field: keyof typeof theme) => (e: any) => {
|
||||
setTheme((t) => ({ ...t, [field]: e.target.value }))
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
} from '@mui/material'
|
||||
import { useLockFn } from 'ahooks'
|
||||
import type { Ref } from 'react'
|
||||
import { useState } from 'react'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import {
|
||||
@@ -58,8 +58,9 @@ export function TunViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
dnsMode: '',
|
||||
})
|
||||
|
||||
const routeExcludeAddressItems = splitRouteExcludeAddress(
|
||||
values.routeExcludeAddress,
|
||||
const routeExcludeAddressItems = useMemo(
|
||||
() => splitRouteExcludeAddress(values.routeExcludeAddress),
|
||||
[values.routeExcludeAddress],
|
||||
)
|
||||
const routeExcludeAddressError =
|
||||
values.autoRoute &&
|
||||
|
||||
@@ -114,6 +114,84 @@ const getAlertTypeFromClassName = (
|
||||
return match?.[1] as GitHubAlertType | null
|
||||
}
|
||||
|
||||
const openUrlWithNotice = (url: string) => {
|
||||
void openExternalUrl(url).catch(showNotice.error)
|
||||
}
|
||||
|
||||
// Renderer map is static; a per-render identity would remount every link and
|
||||
// blockquote subtree while download progress re-renders the dialog.
|
||||
const MARKDOWN_COMPONENTS: ReactMarkdownOptions['components'] = {
|
||||
a: ({ href, children, ...props }) => {
|
||||
const isFragment = href?.startsWith('#') ?? false
|
||||
const renderedHref = isFragment
|
||||
? `#${UPDATE_MARKDOWN_ID_PREFIX}${href?.slice(1)}`
|
||||
: href
|
||||
? '#'
|
||||
: undefined
|
||||
|
||||
return (
|
||||
<a
|
||||
{...props}
|
||||
href={renderedHref}
|
||||
target={undefined}
|
||||
rel={undefined}
|
||||
onClick={(event) => {
|
||||
if (isFragment) return
|
||||
event.preventDefault()
|
||||
if (!href) return
|
||||
openUrlWithNotice(href)
|
||||
}}
|
||||
onAuxClick={(event) => {
|
||||
if (isFragment) return
|
||||
event.preventDefault()
|
||||
if (event.button === 1 && href) {
|
||||
openUrlWithNotice(href)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
)
|
||||
},
|
||||
blockquote: ({ className, children }) => {
|
||||
const alertType = getAlertTypeFromClassName(className)
|
||||
|
||||
if (!alertType) {
|
||||
return <blockquote className={className}>{children}</blockquote>
|
||||
}
|
||||
|
||||
return (
|
||||
<Box
|
||||
component="blockquote"
|
||||
className={className}
|
||||
sx={(theme) => {
|
||||
const color = GITHUB_ALERTS[alertType].color
|
||||
return {
|
||||
m: '12px 0 18px',
|
||||
px: 2,
|
||||
py: 1,
|
||||
borderLeft: `4px solid ${color}`,
|
||||
borderRadius: 1,
|
||||
bgcolor: alpha(color, theme.palette.mode === 'dark' ? 0.16 : 0.08),
|
||||
'& p': {
|
||||
my: 0.75,
|
||||
},
|
||||
'& .markdown-alert-title': {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 0.75,
|
||||
fontWeight: 700,
|
||||
lineHeight: 1.4,
|
||||
},
|
||||
}
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</Box>
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
const findFirstTextNode = (node: MarkdownNode): MarkdownNode | null => {
|
||||
if (node.type === 'text') return node
|
||||
for (const child of node.children ?? []) {
|
||||
@@ -185,14 +263,7 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
})
|
||||
const { downloaded, total } = download
|
||||
|
||||
const openUrlWithNotice = (url: string) => {
|
||||
void openExternalUrl(url).catch(showNotice.error)
|
||||
}
|
||||
|
||||
const progress = useMemo(() => {
|
||||
if (total <= 0) return 0
|
||||
return Math.min((downloaded / total) * 100, 100)
|
||||
}, [downloaded, total])
|
||||
const progress = total <= 0 ? 0 : Math.min((downloaded / total) * 100, 100)
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
open: () => {
|
||||
@@ -212,8 +283,8 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
) as Record<GitHubAlertType, string>,
|
||||
[t],
|
||||
)
|
||||
const remarkGitHubAlertsPlugin = useMemo(
|
||||
() => () => remarkGitHubAlerts(githubAlertLabels),
|
||||
const remarkPlugins = useMemo(
|
||||
() => [() => remarkGitHubAlerts(githubAlertLabels)],
|
||||
[githubAlertLabels],
|
||||
)
|
||||
|
||||
@@ -475,83 +546,8 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
{open && (
|
||||
<Suspense fallback={<LinearProgress />}>
|
||||
<LazyReactMarkdown
|
||||
remarkPlugins={[remarkGitHubAlertsPlugin]}
|
||||
components={{
|
||||
a: ({ href, children, ...props }) => {
|
||||
const isFragment = href?.startsWith('#') ?? false
|
||||
const renderedHref = isFragment
|
||||
? `#${UPDATE_MARKDOWN_ID_PREFIX}${href?.slice(1)}`
|
||||
: href
|
||||
? '#'
|
||||
: undefined
|
||||
|
||||
return (
|
||||
<a
|
||||
{...props}
|
||||
href={renderedHref}
|
||||
target={undefined}
|
||||
rel={undefined}
|
||||
onClick={(event) => {
|
||||
if (isFragment) return
|
||||
event.preventDefault()
|
||||
if (!href) return
|
||||
openUrlWithNotice(href)
|
||||
}}
|
||||
onAuxClick={(event) => {
|
||||
if (isFragment) return
|
||||
event.preventDefault()
|
||||
if (event.button === 1 && href) {
|
||||
openUrlWithNotice(href)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
)
|
||||
},
|
||||
blockquote: ({ className, children }) => {
|
||||
const alertType = getAlertTypeFromClassName(className)
|
||||
|
||||
if (!alertType) {
|
||||
return (
|
||||
<blockquote className={className}>{children}</blockquote>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Box
|
||||
component="blockquote"
|
||||
className={className}
|
||||
sx={(theme) => {
|
||||
const color = GITHUB_ALERTS[alertType].color
|
||||
return {
|
||||
m: '12px 0 18px',
|
||||
px: 2,
|
||||
py: 1,
|
||||
borderLeft: `4px solid ${color}`,
|
||||
borderRadius: 1,
|
||||
bgcolor: alpha(
|
||||
color,
|
||||
theme.palette.mode === 'dark' ? 0.16 : 0.08,
|
||||
),
|
||||
'& p': {
|
||||
my: 0.75,
|
||||
},
|
||||
'& .markdown-alert-title': {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 0.75,
|
||||
fontWeight: 700,
|
||||
lineHeight: 1.4,
|
||||
},
|
||||
}
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</Box>
|
||||
)
|
||||
},
|
||||
}}
|
||||
remarkPlugins={remarkPlugins}
|
||||
components={MARKDOWN_COMPONENTS}
|
||||
>
|
||||
{markdownContent}
|
||||
</LazyReactMarkdown>
|
||||
|
||||
@@ -5,7 +5,13 @@ import { useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { updateGeo, type LogLevel } from 'tauri-plugin-mihomo-api'
|
||||
|
||||
import { BaseDialog, DialogRef, Switch, TooltipIcon } from '@/components/base'
|
||||
import {
|
||||
BaseDialog,
|
||||
DialogRef,
|
||||
Switch,
|
||||
TooltipIcon,
|
||||
switchChangeValue,
|
||||
} from '@/components/base'
|
||||
import { useClash } from '@/hooks/use-clash'
|
||||
import { useClashLog } from '@/hooks/use-clash-log'
|
||||
import { useDisplayedMixedPort } from '@/hooks/use-displayed-mixed-port'
|
||||
@@ -69,7 +75,6 @@ const SettingClash = ({ onError }: Props) => {
|
||||
const corsRef = useRef<DialogRef>(null)
|
||||
const tunnelRef = useRef<DialogRef>(null)
|
||||
|
||||
const onSwitchFormat = (_e: any, value: boolean) => value
|
||||
const onChangeData = (patch: Partial<IConfigData>) => {
|
||||
mutateClash((old) => ({ ...old!, ...patch }), false)
|
||||
}
|
||||
@@ -173,7 +178,7 @@ const SettingClash = ({ onError }: Props) => {
|
||||
value={allowLan ?? false}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onFormat={switchChangeValue}
|
||||
onChange={(e) => onChangeData({ 'allow-lan': e })}
|
||||
onGuard={(e) => patchClash({ 'allow-lan': e })}
|
||||
>
|
||||
@@ -213,7 +218,7 @@ const SettingClash = ({ onError }: Props) => {
|
||||
value={ipv6 ?? false}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onFormat={switchChangeValue}
|
||||
onChange={(e) => onChangeData({ ipv6: e })}
|
||||
onGuard={(e) => patchClash({ ipv6: e })}
|
||||
>
|
||||
@@ -235,7 +240,7 @@ const SettingClash = ({ onError }: Props) => {
|
||||
value={unifiedDelay ?? false}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onFormat={switchChangeValue}
|
||||
onChange={(e) => onChangeData({ 'unified-delay': e })}
|
||||
onGuard={(e) => patchClash({ 'unified-delay': e })}
|
||||
>
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { Box } from '@mui/material'
|
||||
import React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { Switch, TooltipIcon } from '@/components/base'
|
||||
import { Switch, TooltipIcon, switchChangeValue } from '@/components/base'
|
||||
import ProxyControlSwitches from '@/components/shared/proxy-control-switches'
|
||||
import { useVerge } from '@/hooks/use-verge'
|
||||
|
||||
@@ -20,12 +19,8 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
|
||||
const { enable_auto_launch, enable_silent_start } = verge ?? {}
|
||||
|
||||
const onSwitchFormat = (
|
||||
_e: React.ChangeEvent<HTMLInputElement>,
|
||||
value: boolean,
|
||||
) => value
|
||||
const onChangeData = (patch: Partial<IVergeConfig>) => {
|
||||
mutateVerge({ ...verge, ...patch })
|
||||
mutateVerge((prev) => ({ ...prev, ...patch }))
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -52,7 +47,7 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
value={enable_auto_launch ?? false}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onFormat={switchChangeValue}
|
||||
onChange={(e) => {
|
||||
onChangeData({ enable_auto_launch: e })
|
||||
}}
|
||||
@@ -85,7 +80,7 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
value={enable_silent_start ?? false}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onFormat={switchChangeValue}
|
||||
onChange={(e) => onChangeData({ enable_silent_start: e })}
|
||||
onGuard={(e) => patchVerge({ enable_silent_start: e })}
|
||||
>
|
||||
|
||||
@@ -72,7 +72,7 @@ const SettingVergeBasic = ({ onError }: Props) => {
|
||||
const backupRef = useRef<DialogRef>(null)
|
||||
|
||||
const onChangeData = (patch: any) => {
|
||||
mutateVerge({ ...verge, ...patch })
|
||||
mutateVerge((prev) => ({ ...prev, ...patch }))
|
||||
}
|
||||
|
||||
const onCopyClashEnv = useCallback(async () => {
|
||||
|
||||
@@ -483,7 +483,6 @@ const settingsCatalog: readonly SettingEntry[] = [
|
||||
'settings.modals.misc.fields.autoSwitchSelectorGroup':
|
||||
'auto switch select group',
|
||||
'settings.modals.misc.fields.autoCheckUpdate': 'auto check update',
|
||||
'settings.modals.misc.fields.updateChannel': 'update channel source',
|
||||
'settings.modals.misc.fields.enableBuiltinEnhanced':
|
||||
'enable builtin enhanced',
|
||||
'settings.modals.misc.fields.proxyLayoutColumns': 'proxy layout columns',
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
TextField,
|
||||
Typography,
|
||||
} from '@mui/material'
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import getSystem from '@/utils/get-system'
|
||||
@@ -21,6 +21,9 @@ import {
|
||||
type SearchDialog,
|
||||
} from './settings-search-context'
|
||||
|
||||
// Constant for the runtime; module-level like the other getSystem() callers.
|
||||
const OS = getSystem()
|
||||
|
||||
export function SettingsSearch({
|
||||
children,
|
||||
}: {
|
||||
@@ -40,11 +43,17 @@ export function SettingsSearch({
|
||||
const originalScrollRef = useRef(0)
|
||||
const resultScrollRef = useRef(0)
|
||||
const cancelLocateRef = useRef<() => void>(() => {})
|
||||
const results = searchSettings(
|
||||
query,
|
||||
getSystem(),
|
||||
(key) => t(key),
|
||||
(key) => t(key, { lng: 'en' }),
|
||||
// The catalog scan touches every entry with translations; memoizing keeps
|
||||
// unrelated state (arrow-key selection) from re-running it.
|
||||
const results = useMemo(
|
||||
() =>
|
||||
searchSettings(
|
||||
query,
|
||||
OS,
|
||||
(key) => t(key),
|
||||
(key) => t(key, { lng: 'en' }),
|
||||
),
|
||||
[query, t],
|
||||
)
|
||||
const searching = !!query.trim()
|
||||
const scroller = () =>
|
||||
|
||||
@@ -163,7 +163,7 @@ const ProxyControlSwitches = ({
|
||||
})
|
||||
return false
|
||||
}
|
||||
mutateVerge({ ...verge, enable_tun_mode: value })
|
||||
mutateVerge((prev) => ({ ...prev, enable_tun_mode: value }))
|
||||
await patchVerge({ enable_tun_mode: value })
|
||||
}
|
||||
|
||||
|
||||
+22
-12
@@ -1,5 +1,6 @@
|
||||
import { useLockFn } from 'ahooks'
|
||||
import i18n from 'i18next'
|
||||
import { useCallback } from 'react'
|
||||
import { getVersion } from 'tauri-plugin-mihomo-api'
|
||||
|
||||
import {
|
||||
@@ -86,23 +87,29 @@ export const useClashMode = (shouldFetch: boolean = true) => {
|
||||
}
|
||||
|
||||
export const useClash = () => {
|
||||
const { data: clash, refetch } = useRuntimeConfig()
|
||||
const { data: clash } = useRuntimeConfig()
|
||||
|
||||
const { data: versionData, refetch: mutateVersion } = useQuery({
|
||||
queryKey: ['getVersion'],
|
||||
queryFn: getVersion,
|
||||
})
|
||||
|
||||
const mutateClash = (updater?: MutateClashUpdater, revalidate?: boolean) => {
|
||||
if (updater === undefined) {
|
||||
return refetch()
|
||||
}
|
||||
void setCacheData<IConfigData>(['getRuntimeConfig'], updater)
|
||||
if (revalidate !== false) {
|
||||
return refetch()
|
||||
}
|
||||
return Promise.resolve()
|
||||
}
|
||||
// Stable identity: consumers pass mutateClash into their own callbacks.
|
||||
// revalidateQuery hits the same cache key refetch would, without capturing
|
||||
// the per-render refetch closure.
|
||||
const mutateClash = useCallback(
|
||||
(updater?: MutateClashUpdater, revalidate?: boolean) => {
|
||||
if (updater === undefined) {
|
||||
return revalidateQuery(['getRuntimeConfig'])
|
||||
}
|
||||
void setCacheData<IConfigData>(['getRuntimeConfig'], updater)
|
||||
if (revalidate !== false) {
|
||||
return revalidateQuery(['getRuntimeConfig'])
|
||||
}
|
||||
return Promise.resolve()
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
const patchClash = useLockFn(async (patch: Partial<IConfigData>) => {
|
||||
await mutate(() => patchClashConfig(patch), {
|
||||
@@ -143,7 +150,10 @@ export const useClashInfo = () => {
|
||||
})
|
||||
})
|
||||
|
||||
const invalidateClashConfig = () => revalidateQuery(['getClashConfig'])
|
||||
const invalidateClashConfig = useCallback(
|
||||
() => revalidateQuery(['getClashConfig']),
|
||||
[],
|
||||
)
|
||||
|
||||
return {
|
||||
clashInfo,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useSyncExternalStore } from 'react'
|
||||
import { useCallback, useMemo, useSyncExternalStore } from 'react'
|
||||
|
||||
import delayManager, { type DelaySnapshot } from '@/services/delay'
|
||||
import type { ResolvedProxyMember } from '@/types/proxy-view'
|
||||
@@ -32,7 +32,7 @@ export const useGroupsDelays = (
|
||||
groups: readonly string[],
|
||||
): ReadonlyMap<string, DelaySnapshot> => {
|
||||
// Group membership must remain unambiguous when names contain spaces.
|
||||
const groupKey = JSON.stringify(groups)
|
||||
const groupKey = useMemo(() => JSON.stringify(groups), [groups])
|
||||
|
||||
const subscribe = useCallback(
|
||||
(onSettle: () => void) => {
|
||||
|
||||
@@ -12,6 +12,9 @@ const FLUSH_DELAY_MS = 50
|
||||
type LogType = ILogItem['type']
|
||||
|
||||
const DEFAULT_LOG_TYPES: LogType[] = ['debug', 'info', 'warning', 'error']
|
||||
// Shared empty fallback: a fresh [] would give `refresh` a new identity on
|
||||
// every render and re-run the snapshot effect while logs stream.
|
||||
const EMPTY_LOGS: ILogItem[] = []
|
||||
const LOG_LEVEL_FILTERS: Record<LogLevel, LogType[]> = {
|
||||
DEBUG: DEFAULT_LOG_TYPES,
|
||||
INFO: ['info', 'warning', 'error'],
|
||||
@@ -55,7 +58,7 @@ export const useLogData = () => {
|
||||
|
||||
const { response, refresh, setData } = useMihomoWsSubscription<ILogItem[]>({
|
||||
subscriptionKey: enableLog ? 'getClashLog' : null,
|
||||
fallbackData: [],
|
||||
fallbackData: EMPTY_LOGS,
|
||||
connect: () => MihomoWebSocket.connect_logs(logLevel),
|
||||
setupHandlers: ({ next, scheduleReconnect, isMounted }) => {
|
||||
let flushTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
@@ -61,7 +61,7 @@ export function useProxyDelayState(
|
||||
}
|
||||
const cachedUpdate = delayManager.getDelayUpdate(name, groupName)
|
||||
if (cachedUpdate) {
|
||||
setDelayState({ ...cachedUpdate })
|
||||
setDelayState(cachedUpdate)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -48,10 +48,14 @@ export const useSystemProxyState = () => {
|
||||
// Coalesce rapid clicks so only the latest requested state is applied.
|
||||
const pendingRef = useRef<boolean | null>(null)
|
||||
const busyRef = useRef(false)
|
||||
// The drain loop outlives the render it started in; reading the config
|
||||
// through a ref keeps mid-loop revalidations visible to later iterations.
|
||||
const vergeRef = useRef(verge)
|
||||
vergeRef.current = verge
|
||||
|
||||
const toggleSystemProxy = async (enabled: boolean) => {
|
||||
// Roll failed optimistic writes back to the latest confirmed state.
|
||||
let confirmed = verge?.enable_system_proxy ?? false
|
||||
let confirmed = vergeRef.current?.enable_system_proxy ?? false
|
||||
mutateVerge((prev) =>
|
||||
prev ? { ...prev, enable_system_proxy: enabled } : prev,
|
||||
)
|
||||
@@ -69,7 +73,7 @@ export const useSystemProxyState = () => {
|
||||
errorNotice: false,
|
||||
})
|
||||
confirmed = target
|
||||
if (!target && verge?.auto_close_connection) {
|
||||
if (!target && vergeRef.current?.auto_close_connection) {
|
||||
await mutate(() => closeAllConnections(), {
|
||||
id: 'close-all-connections',
|
||||
errorNotice: false,
|
||||
|
||||
@@ -158,9 +158,11 @@ const EMPTY_DATA: ITrafficDataPoint[] = []
|
||||
export const useTrafficMonitorEnhanced = (options?: {
|
||||
subscribe?: boolean
|
||||
enabled?: boolean
|
||||
onSnapshot?: (message: ITrafficWorkerSnapshotMessage) => void
|
||||
}) => {
|
||||
const subscribeToSnapshots = options?.subscribe ?? true
|
||||
const enabled = options?.enabled ?? true
|
||||
const onSnapshot = options?.onSnapshot
|
||||
const isVisible = useVisibility()
|
||||
const [latestSnapshot, setLatestSnapshot] = useState<{
|
||||
dataPoints: ITrafficDataPoint[]
|
||||
@@ -174,6 +176,8 @@ export const useTrafficMonitorEnhanced = (options?: {
|
||||
const currentRangeRef = useRef<number>(WORKER_CONFIG.defaultRangeMinutes)
|
||||
const isVisibleRef = useRef(isVisible)
|
||||
isVisibleRef.current = isVisible
|
||||
const onSnapshotRef = useRef(onSnapshot)
|
||||
onSnapshotRef.current = onSnapshot
|
||||
|
||||
// 注册引用计数与Worker生命周期
|
||||
useEffect(() => {
|
||||
@@ -186,9 +190,12 @@ export const useTrafficMonitorEnhanced = (options?: {
|
||||
client.start(currentRangeRef.current)
|
||||
|
||||
let unsubscribe: (() => void) | undefined
|
||||
if (subscribeToSnapshots) {
|
||||
if (subscribeToSnapshots || onSnapshot) {
|
||||
unsubscribe = client.onSnapshot((message) => {
|
||||
if (!isVisibleRef.current) return
|
||||
// onSnapshot is the always-live channel (ignores visibility); the
|
||||
// state mirror below keeps its original always-latest contract.
|
||||
onSnapshotRef.current?.(message)
|
||||
if (!subscribeToSnapshots || !isVisibleRef.current) return
|
||||
setLatestSnapshot({
|
||||
dataPoints: message.dataPoints,
|
||||
samplerStats: message.samplerStats,
|
||||
@@ -203,14 +210,14 @@ export const useTrafficMonitorEnhanced = (options?: {
|
||||
client.stop()
|
||||
}
|
||||
}
|
||||
}, [enabled, subscribeToSnapshots])
|
||||
}, [enabled, subscribeToSnapshots, onSnapshot])
|
||||
|
||||
// Re-prime snapshot ingestion after every visible transition
|
||||
useEffect(() => {
|
||||
if (enabled && subscribeToSnapshots && isVisible) {
|
||||
if (enabled && isVisible && (subscribeToSnapshots || onSnapshot)) {
|
||||
clientRef.current?.requestSnapshot()
|
||||
}
|
||||
}, [enabled, subscribeToSnapshots, isVisible])
|
||||
}, [enabled, subscribeToSnapshots, onSnapshot, isVisible])
|
||||
|
||||
// 添加流量数据
|
||||
const appendData = useCallback(
|
||||
@@ -244,8 +251,12 @@ export const useTrafficMonitorEnhanced = (options?: {
|
||||
/**
|
||||
* 图表数据Hook
|
||||
*/
|
||||
export const useTrafficGraphDataEnhanced = () => {
|
||||
const { graphData, samplerStats } = useTrafficMonitorEnhanced()
|
||||
export const useTrafficGraphDataEnhanced = (options?: {
|
||||
subscribe?: boolean
|
||||
enabled?: boolean
|
||||
onSnapshot?: (message: ITrafficWorkerSnapshotMessage) => void
|
||||
}) => {
|
||||
const { graphData, samplerStats } = useTrafficMonitorEnhanced(options)
|
||||
|
||||
return {
|
||||
...graphData,
|
||||
|
||||
+25
-19
@@ -3,12 +3,16 @@ import { useCallback } from 'react'
|
||||
import { getVergeConfig, patchVergeConfig } from '@/services/cmds'
|
||||
import { mutate } from '@/services/mutate'
|
||||
import { getPreloadConfig, setPreloadConfig } from '@/services/preload'
|
||||
import { setCacheData, useQuery } from '@/services/query-client'
|
||||
import {
|
||||
revalidateQuery,
|
||||
setCacheData,
|
||||
useQuery,
|
||||
} from '@/services/query-client'
|
||||
|
||||
export const useVerge = () => {
|
||||
const initialVergeConfig = getPreloadConfig()
|
||||
|
||||
const { data: verge, refetch } = useQuery({
|
||||
const { data: verge } = useQuery({
|
||||
queryKey: ['getVergeConfig'],
|
||||
queryFn: async () => {
|
||||
const config = await getVergeConfig()
|
||||
@@ -20,23 +24,25 @@ export const useVerge = () => {
|
||||
staleTime: 5000,
|
||||
})
|
||||
|
||||
const mutateVerge = (
|
||||
updaterOrData?:
|
||||
| IVergeConfig
|
||||
| ((prev: IVergeConfig | undefined) => IVergeConfig | undefined)
|
||||
| undefined,
|
||||
) => {
|
||||
if (updaterOrData === undefined) {
|
||||
void refetch()
|
||||
return
|
||||
}
|
||||
void setCacheData<IVergeConfig>(
|
||||
['getVergeConfig'],
|
||||
typeof updaterOrData === 'function'
|
||||
? (current) => updaterOrData(current ?? verge)
|
||||
: updaterOrData,
|
||||
)
|
||||
}
|
||||
// Stable identity: many consumers list mutateVerge in their own callback
|
||||
// deps, so a per-render closure here would churn their memoization too.
|
||||
// The updater receives the live cache value (preload snapshot when the
|
||||
// cache is still empty) instead of a render-time snapshot, so an older
|
||||
// render cannot clobber a newer cache write.
|
||||
const mutateVerge = useCallback(
|
||||
(
|
||||
updater?: (prev: IVergeConfig | undefined) => IVergeConfig | undefined,
|
||||
) => {
|
||||
if (updater === undefined) {
|
||||
void revalidateQuery(['getVergeConfig'])
|
||||
return
|
||||
}
|
||||
void setCacheData<IVergeConfig>(['getVergeConfig'], (current) =>
|
||||
updater(current ?? getPreloadConfig() ?? undefined),
|
||||
)
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
// Callers own the error toast (GuardState onCatch / page onError), so the
|
||||
// funnel must not add a second one.
|
||||
|
||||
@@ -30,5 +30,41 @@
|
||||
"title": "الأعمدة",
|
||||
"dragHandle": "Drag handle"
|
||||
}
|
||||
},
|
||||
"ruleDialog": {
|
||||
"title": "Add rule…",
|
||||
"matchBy": "Match by",
|
||||
"domain": "Domain",
|
||||
"unavailable": "Not available",
|
||||
"destination": "Add to the prepend rules of “{{name}}”.",
|
||||
"newConnections": "New connections will match the updated configuration.",
|
||||
"processPathHint": "Matches all destinations accessed by processes at this path.",
|
||||
"processNameHint": "Matches all destinations accessed by processes with this name.",
|
||||
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
|
||||
"addAndApply": "Add and apply",
|
||||
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
|
||||
"applyFailed": "The rule could not be applied. Your selection has been kept.",
|
||||
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
|
||||
"saved": "Rule saved and configuration applied.",
|
||||
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
|
||||
"noProfile": "No active profile with an editable rule extension is available.",
|
||||
"entry": "Configure rule…",
|
||||
"modifyTitle": "Modify rule",
|
||||
"domainScope": "Domain scope",
|
||||
"exactDomain": "Only this domain",
|
||||
"allSubdomains": "This domain and all its subdomains",
|
||||
"rootDomain": "النطاق الرئيسي وجميع نطاقاته الفرعية ({{domain}})",
|
||||
"policyUnavailable": "This policy is no longer available. Choose another policy.",
|
||||
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
|
||||
"saveAndApply": "Save and apply",
|
||||
"sourceIp": "Source IP",
|
||||
"destinationIp": "Destination IP",
|
||||
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
|
||||
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
|
||||
"fullPath": "Full path",
|
||||
"connectionHost": "Current connection domain: {{host}}",
|
||||
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
|
||||
"matchingDomain": "Matching domain",
|
||||
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -413,7 +413,6 @@
|
||||
"autoCloseConnections": "إغلاق الاتصالات تلقائيًا",
|
||||
"autoSwitchSelectorGroup": "تبديل مجموعة select تلقائيًا",
|
||||
"autoCheckUpdate": "فحص التحديث تلقائيًا",
|
||||
"updateChannel": "قناة التحديث",
|
||||
"enableBuiltinEnhanced": "تفعيل التحسين المدمج",
|
||||
"proxyLayoutColumns": "أعمدة عرض الوكيل",
|
||||
"autoLogClean": "تنظيف السجلات تلقائيًا",
|
||||
@@ -436,11 +435,6 @@
|
||||
"autoLogClean": {
|
||||
"never": "عدم التنظيف أبدًا",
|
||||
"retainDays": "الاحتفاظ لمدة {{n}} يومًا"
|
||||
},
|
||||
"updateChannel": {
|
||||
"auto": "تلقائي (مرايا)",
|
||||
"github": "GitHub",
|
||||
"githubProxy": "GitHub عبر الوكيل"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -30,5 +30,41 @@
|
||||
"title": "Spalten",
|
||||
"dragHandle": "Ziehpunkt"
|
||||
}
|
||||
},
|
||||
"ruleDialog": {
|
||||
"title": "Add rule…",
|
||||
"matchBy": "Match by",
|
||||
"domain": "Domain",
|
||||
"unavailable": "Not available",
|
||||
"destination": "Add to the prepend rules of “{{name}}”.",
|
||||
"newConnections": "New connections will match the updated configuration.",
|
||||
"processPathHint": "Matches all destinations accessed by processes at this path.",
|
||||
"processNameHint": "Matches all destinations accessed by processes with this name.",
|
||||
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
|
||||
"addAndApply": "Add and apply",
|
||||
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
|
||||
"applyFailed": "The rule could not be applied. Your selection has been kept.",
|
||||
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
|
||||
"saved": "Rule saved and configuration applied.",
|
||||
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
|
||||
"noProfile": "No active profile with an editable rule extension is available.",
|
||||
"entry": "Configure rule…",
|
||||
"modifyTitle": "Modify rule",
|
||||
"domainScope": "Domain scope",
|
||||
"exactDomain": "Only this domain",
|
||||
"allSubdomains": "This domain and all its subdomains",
|
||||
"rootDomain": "Hauptdomain und alle Subdomains ({{domain}})",
|
||||
"policyUnavailable": "This policy is no longer available. Choose another policy.",
|
||||
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
|
||||
"saveAndApply": "Save and apply",
|
||||
"sourceIp": "Source IP",
|
||||
"destinationIp": "Destination IP",
|
||||
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
|
||||
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
|
||||
"fullPath": "Full path",
|
||||
"connectionHost": "Current connection domain: {{host}}",
|
||||
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
|
||||
"matchingDomain": "Matching domain",
|
||||
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -413,7 +413,6 @@
|
||||
"autoCloseConnections": "Verbindungen automatisch schließen",
|
||||
"autoSwitchSelectorGroup": "Select-Gruppe automatisch umschalten",
|
||||
"autoCheckUpdate": "Automatisch auf Updates prüfen",
|
||||
"updateChannel": "Update-Kanal",
|
||||
"enableBuiltinEnhanced": "Eingebaute Verbesserungen aktivieren",
|
||||
"proxyLayoutColumns": "Anzahl der Spalten im Proxy-Layout",
|
||||
"autoLogClean": "Protokolle automatisch bereinigen",
|
||||
@@ -436,11 +435,6 @@
|
||||
"autoLogClean": {
|
||||
"never": "Nie bereinigen",
|
||||
"retainDays": "{{n}} Tage behalten"
|
||||
},
|
||||
"updateChannel": {
|
||||
"auto": "Automatisch (Mirrors)",
|
||||
"github": "GitHub",
|
||||
"githubProxy": "GitHub über Proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -30,5 +30,41 @@
|
||||
"title": "Columns",
|
||||
"dragHandle": "Drag handle"
|
||||
}
|
||||
},
|
||||
"ruleDialog": {
|
||||
"title": "Add rule…",
|
||||
"matchBy": "Match by",
|
||||
"domain": "Domain",
|
||||
"unavailable": "Not available",
|
||||
"destination": "Add to the prepend rules of “{{name}}”.",
|
||||
"newConnections": "New connections will match the updated configuration.",
|
||||
"processPathHint": "Matches all destinations accessed by processes at this path.",
|
||||
"processNameHint": "Matches all destinations accessed by processes with this name.",
|
||||
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
|
||||
"addAndApply": "Add and apply",
|
||||
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
|
||||
"applyFailed": "The rule could not be applied. Your selection has been kept.",
|
||||
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
|
||||
"saved": "Rule saved and configuration applied.",
|
||||
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
|
||||
"noProfile": "No active profile with an editable rule extension is available.",
|
||||
"entry": "Configure rule…",
|
||||
"modifyTitle": "Modify rule",
|
||||
"domainScope": "Domain scope",
|
||||
"exactDomain": "Only this domain",
|
||||
"allSubdomains": "This domain and all its subdomains",
|
||||
"rootDomain": "Root domain and all its subdomains ({{domain}})",
|
||||
"policyUnavailable": "This policy is no longer available. Choose another policy.",
|
||||
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
|
||||
"saveAndApply": "Save and apply",
|
||||
"sourceIp": "Source IP",
|
||||
"destinationIp": "Destination IP",
|
||||
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
|
||||
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
|
||||
"fullPath": "Full path",
|
||||
"connectionHost": "Current connection domain: {{host}}",
|
||||
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
|
||||
"matchingDomain": "Matching domain",
|
||||
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -413,7 +413,6 @@
|
||||
"autoCloseConnections": "Auto Close Connections",
|
||||
"autoSwitchSelectorGroup": "Auto Switch Select Group",
|
||||
"autoCheckUpdate": "Auto Check Update",
|
||||
"updateChannel": "Update Channel",
|
||||
"enableBuiltinEnhanced": "Enable Builtin Enhanced",
|
||||
"proxyLayoutColumns": "Proxy Layout Columns",
|
||||
"autoLogClean": "Auto Log Clean",
|
||||
@@ -436,11 +435,6 @@
|
||||
"autoLogClean": {
|
||||
"never": "Never Clean",
|
||||
"retainDays": "Retain {{n}} Days"
|
||||
},
|
||||
"updateChannel": {
|
||||
"auto": "Auto (Mirrors)",
|
||||
"github": "GitHub",
|
||||
"githubProxy": "GitHub via Proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user