Compare commits

...
29 Commits
Author SHA1 Message Date
Tunglies c8a8d2034c refactor(deps): replace once_cell with std OnceLock and LazyLock 2026-10-01 14:34:20 +08:00
Tunglies f17ccdc227 refactor(core): replace macOS network monitor slot with armed latch 2026-10-01 14:34:19 +08:00
Tunglies 92303ce60d refactor(port): store startup block reason in a OnceLock 2026-10-01 14:34:19 +08:00
Tunglies ecd60d317a refactor(service): drop redundant provider sync serial lock 2026-10-01 14:34:19 +08:00
Tunglies c2b6c0378e refactor(port): fold startup-core-blocked flag into reason slot 2026-10-01 14:34:19 +08:00
Tunglies adbe3ffec4 refactor(notify): fold sequence counter into entries lock 2026-10-01 14:34:19 +08:00
Tunglies a146d78b9f refactor(updater): drop write-only pending_* slots 2026-10-01 14:34:19 +08:00
Tunglies 1552f8e2f9 fix(events): close run-state race and restore single error toasts
Self-review findings: the bus now re-reads the run-state snapshot in
onSubscribed so an event racing the store's initial read cannot leave a
stale snapshot (the ordering the old layout listener guaranteed), and the
patch hooks pass errorNotice:false so GuardState/page handlers remain the
only error toast, matching the pre-migration behavior.
2026-10-01 14:34:17 +08:00
Tunglies 70d1298bc9 docs: add frontend architecture guardrails for src
Layering rules for the contract flow: generated contract as the only
wire-typing source, event bus as the only listen/emit site, pure-reducer
store for event-derived state, the mutate funnel for user intent, and
invoke only in the services layer — each backed by the CI gates.
2026-10-01 14:34:17 +08:00
Tunglies 42ec30633b refactor(proxies): route proxy/home/misc commands through the mutate funnel
Ports mode switching (page and home card), chain runtime updates, node
selection with tray sync, selection recording, provider updates and
syncs, and lightweight-mode entry onto the funnel; every site keeps its
existing optimistic/revert and error-handling behavior.
2026-10-01 14:34:17 +08:00
Tunglies 4a6f0da237 refactor(profiles): route profile operations through the mutate funnel
Ports profile create/import/reorder/delete/update/patch/save-file and
enhance calls onto the funnel; retry and editor flows keep their own
error handling with errorNotice:false. Per-uid ids keep the update
worker pool concurrent under the funnel's in-flight dedupe.
2026-10-01 14:34:17 +08:00
Tunglies 3e91458799 refactor(settings): route settings-domain commands through the mutate funnel
Ports port saving, webdav/local backup operations, core change/restart/
upgrade, service install/uninstall/repair flows, the system-proxy toggle
queue, the DNS override toggle, and app lifecycle commands onto the single
funnel. Bespoke flows keep their own error handling via errorNotice:false;
simple flows gain the funnel's default error toast and revalidation.
2026-10-01 14:34:17 +08:00
Tunglies 763338dade feat(mutate): single funnel for user-intent commands and invoke gate
Adds src/services/mutate.ts: one path for optimistic apply, services-layer
invoke, Busy handling, failure rollback, and the error toast, with busy
bookkeeping mirrored into the app store. The patch hooks (verge, clash,
profiles) now route through it. Moves the remaining direct invokes
(unlock ×3, DNS ×4) into cmds.ts and turns on the invoke-only-in-services
architecture gate in CI.
2026-10-01 14:34:17 +08:00
Tunglies 5b53c32de1 refactor(notice): make the notice table exhaustive and drop dead wire entries
D5 cleanup, frontend and backend in one commit: removes the six
config_validate::* statuses that never receive a backend send and the
set_config::ok send (enum variants, golden list 41→34, send point in
restart_clash_core), their frontend handlers, and the five i18n keys only
those handlers used. The notice table is now typed as a Record over the
generated NoticeStatus union, so a status without a frontend entry fails
to compile. The info status (sent by the silent updater for breaking
change notices, previously dropped with a console warning) now shows an
info toast — the one deliberate behavior delta.
2026-10-01 14:34:17 +08:00
Tunglies 43cf001e68 feat(events): route all backend events through a single event bus and store
Adds src/services/bus (the only listen/emit site: one handler per contract
event plus the frontend-internal test-all event) and the React
context/reducer app store. Migrates the five scattered subscriptions
(layout events, pending failures, proxy refresh, profile update/timer,
test-all), deletes the old glue (events.ts, use-listen, use-layout-events,
LoadingCacheProvider), moves run state into the store, and adds an
architecture gate script wired into CI. Behavior is unchanged; the
run-state query's poll/focus safety net is preserved by the store
provider.
2026-10-01 14:34:17 +08:00
Tunglies 5bf0de0d0b feat(contract): export wire contract from backend and generate frontend types
Adds a zero-dependency `frontend-contract` bin that serializes the real
NoticeStatus variants and FrontendEvent payloads, scripts/gen-contract.mjs
which emits the committed src/services/contract.ts, and a CI job that
regenerates it and fails on a non-empty diff. events.ts now derives its
event map from the generated contract instead of hand-typed shapes.
2026-10-01 14:34:17 +08:00
Tunglies 96d68b057a chore(core): document watcher exit conditions 2026-10-01 14:34:16 +08:00
Tunglies 917d97f335 docs(backend): record dead wire contract entries 2026-10-01 14:34:16 +08:00
Tunglies 5364468ad4 test(feat): freeze representative effect registry mappings 2026-10-01 14:34:16 +08:00
Tunglies 866899593e ci(backend): add architecture ban gates 2026-10-01 14:34:16 +08:00
Tunglies 079414253e refactor(core): complete bounded service retry migration 2026-10-01 14:34:16 +08:00
Tunglies 6de4df8c9f refactor(core): coalesce burst refresh announcements 2026-10-01 14:34:16 +08:00
Tunglies 86605f197d docs: add src-tauri architecture guardrails 2026-10-01 14:34:16 +08:00
Tunglies 5375ce360f refactor(utils): migrate remaining bounded retry loops 2026-10-01 14:34:16 +08:00
Tunglies 9d1b400299 refactor(core): fold tray, hotkey, autostart updates into effect ensures 2026-10-01 14:34:16 +08:00
Tunglies 7aed7be2f1 refactor(core): derive refresh announcements from transaction commit 2026-10-01 14:34:16 +08:00
Tunglies 438f6f7461 refactor(feat): declarative effect registry for verge and clash patches 2026-10-01 14:34:16 +08:00
Tunglies edcd76f27d refactor(utils): unified retry and strategy-list helpers 2026-10-01 14:34:16 +08:00
Tunglies 7eb24d8c69 refactor(core): type notice statuses behind the frozen wire contract 2026-10-01 14:34:16 +08:00
149 changed files with 3973 additions and 1835 deletions
+26
View File
@@ -0,0 +1,26 @@
name: Backend Guardrails
on:
pull_request:
paths:
- "src-tauri/**"
- ".github/workflows/backend-guardrails.yml"
workflow_dispatch:
permissions:
contents: read
jobs:
banned-patterns:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- name: No Handle::refresh calls in feat
run: '! grep -rn "Handle::refresh" src-tauri/src/feat'
- name: No notice_message outside core/notify
run: '! grep -rn "notice_message(" src-tauri/src --include="*.rs" | grep -v "core/notify"'
- name: No manual update-flag chains
run: '! grep -rnE "determine_update_flags|UpdateFlags" src-tauri/src'
+79
View File
@@ -85,3 +85,82 @@ jobs:
- name: Run Knip
if: steps.check_frontend.outputs.frontend == 'true'
run: pnpm knip:check
- name: Architecture gates (listen/emit only in the event bus, invoke only in services)
if: steps.check_frontend.outputs.frontend == 'true'
run: node scripts/check-architecture.mjs listen emit invoke
contract-parity:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v7
- name: Check contract inputs
id: check_inputs
uses: dorny/paths-filter@v4
with:
filters: |
contract:
- 'src/services/contract.ts'
- 'scripts/gen-contract.mjs'
- 'src-tauri/src/core/notify/**'
- 'src-tauri/src/bin/**'
- 'src-tauri/src/lib.rs'
- '.github/workflows/frontend-check.yml'
- name: Skip if contract inputs unchanged
if: steps.check_inputs.outputs.contract != 'true'
run: echo "No contract inputs changed, skipping parity check."
- name: Install Rust Stable
if: steps.check_inputs.outputs.contract == 'true'
uses: dtolnay/rust-toolchain@master
with:
toolchain: stable
- name: Rust Cache
if: steps.check_inputs.outputs.contract == 'true'
uses: Swatinem/rust-cache@v2
with:
prefix-key: 'v1-rust'
key: 'rust-shared-stable-ubuntu-22.04-x86_64-unknown-linux-gnu-contract'
workspaces: |
. -> target
cache-all-crates: true
cache-workspace-crates: true
- name: Install dependencies
if: steps.check_inputs.outputs.contract == 'true'
run: |
sudo apt-get update
sudo apt-get install -y libxslt1.1 libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev patchelf
- name: Install pnpm
if: steps.check_inputs.outputs.contract == 'true'
uses: pnpm/action-setup@v6
with:
run_install: false
- uses: actions/setup-node@v7
if: steps.check_inputs.outputs.contract == 'true'
with:
node-version: '24.21.0'
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
if: steps.check_inputs.outputs.contract == 'true'
- name: Provision sidecar placeholders for tauri-build
if: steps.check_inputs.outputs.contract == 'true'
run: |
mkdir -p src-tauri/sidecar src-tauri/resources dist
touch dist/index.html
for bin in clash-verge-service clash-verge-service-install clash-verge-service-uninstall verge-mihomo verge-mihomo-alpha; do
touch "src-tauri/sidecar/${bin}-x86_64-unknown-linux-gnu"
done
- name: Regenerate contract and require empty diff
if: steps.check_inputs.outputs.contract == 'true'
run: |
pnpm gen:contract
git diff --exit-code -- src/services/contract.ts
Generated
-1
View File
@@ -1114,7 +1114,6 @@ dependencies = [
"objc2",
"objc2-app-kit",
"objc2-foundation",
"once_cell",
"open",
"parking_lot",
"percent-encoding",
+2 -1
View File
@@ -17,7 +17,8 @@
"ignoreBinaries": ["rustc", "cc"],
"ignoreDependencies": ["lint-staged"],
"ignoreIssues": {
"src/types/generated/**": ["exports", "types"]
"src/types/generated/**": ["exports", "types"],
"src/services/contract.ts": ["exports", "types"]
},
"cycles": {
"dynamicImports": true
+2
View File
@@ -30,6 +30,8 @@
"i18n:check": "node scripts/cleanup-unused-i18n.mjs",
"i18n:format": "node scripts/cleanup-unused-i18n.mjs --align --apply",
"i18n:types": "node scripts/generate-i18n-keys.mjs",
"gen:contract": "node scripts/gen-contract.mjs",
"arch:check": "node scripts/check-architecture.mjs listen emit invoke",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
+84
View File
@@ -0,0 +1,84 @@
import fs from 'node:fs'
import path from 'node:path'
/**
* Architecture grep gates for the frontend contract flow. Select gates via
* argv:
*
* node scripts/check-architecture.mjs listen emit invoke
*
* - listen/emit: the Tauri event API may only be used under src/services/bus/**
* (the event bus). Detected as a bare `listen(`/`emit(` call (member calls
* like `this.emit(` are unrelated class methods) or as importing the name
* from '@tauri-apps/api/event'.
* - invoke: `invoke(` calls may exist only under src/services/**.
*/
const ROOT = path.resolve(import.meta.dirname, '..')
const SRC = path.join(ROOT, 'src')
const tauriEventImport = (name) =>
new RegExp(
`import\\s*\\{[^}]*\\b${name}\\b[^}]*\\}\\s*from\\s*'@tauri-apps/api/event'`,
)
const GATES = {
listen: {
patterns: [/(?<![.\w])listen\(/, tauriEventImport('listen')],
allowed: (file) => file.startsWith('src/services/bus/'),
description: 'Tauri listen outside the event bus (src/services/bus)',
},
emit: {
patterns: [/(?<![.\w])emit\(/, tauriEventImport('emit')],
allowed: (file) => file.startsWith('src/services/bus/'),
description: 'Tauri emit outside the event bus (src/services/bus)',
},
invoke: {
patterns: [/\binvoke\(/],
allowed: (file) => file.startsWith('src/services/'),
description: 'invoke( outside the services layer (src/services)',
},
}
const walk = (dir) => {
const entries = fs.readdirSync(dir, { withFileTypes: true })
return entries.flatMap((entry) => {
const full = path.join(dir, entry.name)
if (entry.isDirectory()) return walk(full)
return /\.(ts|tsx|js|jsx|mts|mjs)$/.test(entry.name) ? [full] : []
})
}
const selected = process.argv.slice(2)
if (selected.length === 0) {
console.error('usage: check-architecture.mjs <gate>... (listen|emit|invoke)')
process.exit(2)
}
let violations = 0
for (const gate of selected) {
const rule = GATES[gate]
if (!rule) {
console.error(`unknown gate: ${gate}`)
process.exit(2)
}
for (const file of walk(SRC)) {
const relative = path.relative(ROOT, file).replaceAll('\\', '/')
if (rule.allowed(relative)) continue
const lines = fs.readFileSync(file, 'utf8').split('\n')
lines.forEach((line, index) => {
if (rule.patterns.some((pattern) => pattern.test(line))) {
violations += 1
console.error(
`[arch] ${rule.description}: ${relative}:${index + 1}: ${line.trim()}`,
)
}
})
}
}
if (violations > 0) {
console.error(`[arch] ${violations} violation(s) found`)
process.exit(1)
}
console.log('[arch] no violations')
+91
View File
@@ -0,0 +1,91 @@
import { execFileSync } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
/**
* Regenerates src/services/contract.ts from the backend wire contract.
* Source of truth: `cargo run -p clash-verge --bin frontend-contract` inside
* src-tauri, which serializes the same enum variants and event payloads the
* app emits at runtime. CI reruns this and fails on a non-empty diff.
*/
const ROOT = path.resolve(import.meta.dirname, '..')
const OUT = path.join(ROOT, 'src/services/contract.ts')
const contract = JSON.parse(
execFileSync(
'cargo',
['run', '-p', 'clash-verge', '--bin', 'frontend-contract', '-q'],
{
cwd: path.join(ROOT, 'src-tauri'),
encoding: 'utf8',
maxBuffer: 16 * 1024 * 1024,
},
),
)
if (contract.version !== 1) {
throw new Error(`unsupported wire contract version: ${contract.version}`)
}
/** TS type per event, derived from the serialized sample payload's JSON shape. */
const payloadType = (name, sample) => {
if (sample === null) return 'null'
if (typeof sample === 'string') return 'string'
if (Array.isArray(sample)) {
if (name === 'verge://notice-message') return '[NoticeStatus, string]'
throw new Error(`unexpected array payload for ${name}`)
}
if (typeof sample === 'object') {
const keys = Object.keys(sample)
if (keys.length === 1 && keys[0] === 'uid') return '{ uid: string }'
if (name === 'verge://run-state-changed') return 'RunState'
throw new Error(`unexpected object payload for ${name}: ${keys.join(',')}`)
}
throw new Error(`unexpected payload for ${name}`)
}
const needsRunState = contract.events.some(
(e) => e.name === 'verge://run-state-changed',
)
if (!needsRunState)
throw new Error('run-state-changed event missing from contract')
const lines = []
lines.push(
'// @generated by scripts/gen-contract.mjs from the backend wire contract. DO NOT EDIT.',
)
lines.push('// Regen: pnpm gen:contract')
lines.push('')
lines.push("import type { RunState } from './cmds'")
lines.push('')
lines.push(
'/** Wire status strings from NoticeStatus; keep in sync via `pnpm gen:contract`. */',
)
lines.push('export type NoticeStatus =')
for (const status of contract.noticeStatuses) {
lines.push(` | ${JSON.stringify(status)}`)
}
lines.push('')
lines.push('/** Event name → payload type for every backend-emitted event. */')
lines.push('export interface VergeEventPayloads {')
for (const event of contract.events) {
const key = JSON.stringify(event.name)
lines.push(` ${key}: ${payloadType(event.name, event.sample)}`)
}
lines.push('}')
lines.push('')
const content = `${lines.join('\n')}\n`
fs.writeFileSync(OUT, content)
// Match the repo's biome style so CI parity (`git diff --exit-code`) is stable.
execFileSync(
process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm',
['exec', 'biome', 'format', '--write', path.relative(ROOT, OUT)],
{ cwd: ROOT, stdio: 'ignore' },
)
console.log(
`[gen-contract] wrote ${path.relative(ROOT, OUT)}: ${contract.events.length} events, ${contract.noticeStatuses.length} statuses`,
)
+38
View File
@@ -0,0 +1,38 @@
# Backend Architecture Guardrails
These rules supplement the repository's root `AGENTS.md`.
1. **Keep configuration ownership in `config`.** Configuration writes must use
its draft and persistence APIs. Patch orchestration must use
`feat/effects.rs` and `feat/executor.rs`; refresh notifications must use
`core::notify::announce` after successful persistence and commit. This keeps
failed transactions from publishing state. Independent transactions retain
their boundaries and announce via `after_commit`; runtime-only profile
activation announces after successful application. New cross-layer
exceptions require a rationale in the PR and an update to this file.
2. **Register every new `IVerge` field.** Add one row, including an explicit
`NoEffect` where appropriate, to the exhaustive registry and preserve its
platform attributes. Keep the serialized-field coverage test passing. Manual
field-to-flag chains hide missing effects and are forbidden. No exceptions.
3. **Use `utils::retry` for bounded retries.** Do not introduce handwritten retry
loops, including `loop` plus `sleep`; preserve attempt budgets, delays and
terminal errors. Permanent watchers are the exception and must document
their exit conditions. Traversal of distinct data or port candidates is not
a retry policy.
4. **Keep notifications typed.** Send notice statuses through `NoticeStatus` and
use `Arc<str>` for notice message payloads. Preserve the event names and
status strings pinned by the golden tests. Status additions or changes
require frontend and backend changes in the same PR and an updated golden
list; this protects the wire contract. No exceptions.
5. **Preserve lock order.** The order is `config_write` before
`config_update_in_progress` before `lifecycle_lock`. Patch callers must use
the executor's guarded claim instead of independently combining these locks;
this preserves Busy rejection and prevents inverted acquisition. Existing
lifecycle and independent port transactions keep their established locking
boundaries. A new lock requires registering its position in this rule before
introducing acquisition sites.
6. **Prefer reconciliation.** Express new effects as idempotent `ensure`
operations in `EFFECT_ORDER` so repeated application converges on the same
state. A trigger chain is an exception only with a code comment explaining
why the operation cannot be idempotent. Configuration rollback does not
authorize reverse OS effects.
-1
View File
@@ -66,7 +66,6 @@ dunce = "1.0.5"
nanoid = "0.5"
chrono = { workspace = true }
boa_engine = "0.22.0"
once_cell = { version = "1.21.4", features = ["parking_lot"] }
percent-encoding = "2.3.2"
reqwest = { workspace = true }
regex = { workspace = true }
+8
View File
@@ -0,0 +1,8 @@
//! Prints the frontend wire contract as JSON to stdout. Zero new dependencies:
//! the payload is derived from the same serializers the app uses at runtime.
//! Consumed by scripts/gen-contract.mjs; CI regenerates and diffs the committed
//! TypeScript artifact.
fn main() {
println!("{}", app_lib::frontend_wire_contract());
}
+4 -3
View File
@@ -1,4 +1,5 @@
use super::{CmdResult, CommandFailure, WithErrorCode as _, proxy_aware_coded_error, proxy_aware_error};
use crate::core::notify::NoticeStatus;
use crate::feat;
use crate::utils::{dirs, yaml_emitter};
use crate::{
@@ -56,14 +57,14 @@ pub async fn change_clash_core(clash_core: String) -> CmdResult<Option<CommandFa
match CoreManager::global().restart_core().await {
Ok(_) => {
handle::Handle::notice_message("config_core::change_success", clash_core);
handle::Handle::notice(NoticeStatus::ConfigCoreChangeSuccess, clash_core.as_str());
handle::Handle::refresh_clash();
Ok(None)
}
Err(err) => {
let failed = err.context("core changed but failed to restart");
let error_msg: String = format!("{failed:#}").into();
handle::Handle::notice_message("config_core::change_error", error_msg.clone());
handle::Handle::notice(NoticeStatus::ConfigCoreChangeError, error_msg.as_str());
logging!(error, Type::Core, "core changed but failed to restart: {error_msg}");
Ok(Some(proxy_aware_coded_error(&failed, "CORE_CHANGE_FAILED")))
}
@@ -72,7 +73,7 @@ pub async fn change_clash_core(clash_core: String) -> CmdResult<Option<CommandFa
Err(err) => {
let error_msg: String = format!("{err:#}").into();
logging!(error, Type::Core, "failed to change core: {error_msg}");
handle::Handle::notice_message("config_core::change_error", error_msg);
handle::Handle::notice(NoticeStatus::ConfigCoreChangeError, error_msg.as_str());
Ok(Some(proxy_aware_coded_error(&err, "CORE_CHANGE_FAILED")))
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
use crate::module::lightweight;
use crate::core::lightweight;
use super::CmdResult;
+2 -1
View File
@@ -1,6 +1,7 @@
use super::{CmdResult, StringifyErr as _, WithErrorCode as _, coded_error};
use crate::cmd::validate::{ValidationNoticeTarget, handle_validation_notice};
use crate::config::profiles;
use crate::core::notify::NoticeStatus;
use crate::utils::window_manager::WindowManager;
use crate::{
config::{
@@ -282,7 +283,7 @@ async fn handle_update_error<E: std::fmt::Display>(
logging!(warn, Type::Cmd, "更新过程发生错误: {}", e,);
discard_and_restore(current_profile).await?;
let message: String = e.to_string().into();
handle::Handle::notice_message("config_validate::boot_error", message.clone());
handle::Handle::notice(NoticeStatus::ConfigValidateBootError, message.as_str());
Ok(ValidationOutcome::invalid_from_message(message))
}
+1
View File
@@ -84,6 +84,7 @@ pub async fn sync_tray_proxy_selection() -> CmdResult<()> {
}
async fn run_tray_sync_loop() {
// Permanent watcher: keeps syncing until a pass finds no pending sync request.
loop {
match Tray::global().update_menu().await {
Ok(_) => {
+1 -1
View File
@@ -3,11 +3,11 @@ use crate::{
cmd::StringifyErr as _,
cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
config::{Config, IProfiles, PrfItem},
core::auto_backup::{AutoBackupManager, AutoBackupTrigger},
core::{
CoreManager, handle,
validate::{CoreConfigValidator, ValidationOutcome},
},
module::auto_backup::{AutoBackupManager, AutoBackupTrigger},
utils::dirs,
};
use clash_verge_logging::{Type, logging, logging_error};
+17 -16
View File
@@ -1,3 +1,4 @@
use crate::core::notify::NoticeStatus;
use crate::core::{
handle,
validate::{ValidationErrorKind, ValidationOutcome},
@@ -11,27 +12,27 @@ pub enum ValidationNoticeTarget {
Script,
}
const fn notice_key(kind: ValidationErrorKind, target: ValidationNoticeTarget) -> &'static str {
const fn notice_key(kind: ValidationErrorKind, target: ValidationNoticeTarget) -> NoticeStatus {
match kind {
ValidationErrorKind::FileMissing => "config_validate::file_not_found",
ValidationErrorKind::FileMissing => NoticeStatus::ConfigValidateFileNotFound,
ValidationErrorKind::FileRead => match target {
ValidationNoticeTarget::Script => "config_validate::script_error",
_ => "config_validate::yaml_read_error",
ValidationNoticeTarget::Script => NoticeStatus::ConfigValidateScriptError,
_ => NoticeStatus::ConfigValidateYamlReadError,
},
ValidationErrorKind::YamlSyntax => match target {
ValidationNoticeTarget::Merge => "config_validate::merge_syntax_error",
ValidationNoticeTarget::Script => "config_validate::script_error",
ValidationNoticeTarget::Runtime => "config_validate::yaml_syntax_error",
ValidationNoticeTarget::Merge => NoticeStatus::ConfigValidateMergeSyntaxError,
ValidationNoticeTarget::Script => NoticeStatus::ConfigValidateScriptError,
ValidationNoticeTarget::Runtime => NoticeStatus::ConfigValidateYamlSyntaxError,
},
ValidationErrorKind::YamlMapping => match target {
ValidationNoticeTarget::Merge => "config_validate::merge_mapping_error",
ValidationNoticeTarget::Script => "config_validate::script_error",
ValidationNoticeTarget::Runtime => "config_validate::yaml_mapping_error",
ValidationNoticeTarget::Merge => NoticeStatus::ConfigValidateMergeMappingError,
ValidationNoticeTarget::Script => NoticeStatus::ConfigValidateScriptError,
ValidationNoticeTarget::Runtime => NoticeStatus::ConfigValidateYamlMappingError,
},
ValidationErrorKind::ScriptSyntax => "config_validate::script_syntax_error",
ValidationErrorKind::ScriptMissingMain => "config_validate::script_missing_main",
ValidationErrorKind::ProcessTerminated => "config_validate::process_terminated",
ValidationErrorKind::CoreRejected | ValidationErrorKind::Timeout => "config_validate::error",
ValidationErrorKind::ScriptSyntax => NoticeStatus::ConfigValidateScriptSyntaxError,
ValidationErrorKind::ScriptMissingMain => NoticeStatus::ConfigValidateScriptMissingMain,
ValidationErrorKind::ProcessTerminated => NoticeStatus::ConfigValidateProcessTerminated,
ValidationErrorKind::CoreRejected | ValidationErrorKind::Timeout => NoticeStatus::ConfigValidateError,
}
}
@@ -40,12 +41,12 @@ pub fn handle_validation_notice(outcome: &ValidationOutcome, target: ValidationN
ValidationOutcome::Invalid { kind, message } => {
let status = notice_key(*kind, target);
logging!(warn, Type::Config, "{} 验证失败: {}", file_type, message);
handle::Handle::notice_message(status, message.to_owned());
handle::Handle::notice(status, message.as_str());
}
ValidationOutcome::Busy | ValidationOutcome::Skipped { .. } => {
let message = outcome.to_string();
logging!(warn, Type::Config, "{} 验证跳过: {}", file_type, message);
handle::Handle::notice_message("config_validate::error", message);
handle::Handle::notice(NoticeStatus::ConfigValidateError, message.as_str());
}
ValidationOutcome::Valid => {}
}
+17 -10
View File
@@ -1,4 +1,5 @@
use super::{IClashTemp, IProfiles, IVerge, MixedPort};
use crate::core::notify::NoticeStatus;
use crate::{
config::{PrfItem, profiles_append_item_to_safe, runtime::IRuntime},
constants::{files, timing},
@@ -69,6 +70,12 @@ impl Config {
CONFIG_WRITE_LOCK.lock().await
}
pub(crate) fn try_lock_config_write() -> Result<MutexGuard<'static, ()>> {
CONFIG_WRITE_LOCK
.try_lock()
.map_err(|_| anyhow!("configuration update is already running"))
}
pub async fn init_config_before_window() -> Result<()> {
Self::ensure_default_profile_items().await?;
@@ -106,7 +113,7 @@ impl Config {
if let Some((msg_type, msg_content)) = validation_result {
sleep(timing::STARTUP_ERROR_DELAY).await;
handle::Handle::notice_message(msg_type, msg_content);
handle::Handle::notice(msg_type, msg_content.as_str());
}
Self::runtime().await.apply();
@@ -137,14 +144,14 @@ impl Config {
Ok(())
}
async fn generate_and_validate() -> Result<Option<(&'static str, String)>> {
async fn generate_and_validate() -> Result<Option<(NoticeStatus, String)>> {
if let Err(err) = Self::generate().await {
let error_msg: String = err.to_string().into();
logging!(error, Type::Config, "生成运行时配置失败: {}", error_msg);
CoreManager::global()
.use_default_config("config_validate::boot_error", &error_msg)
.use_default_config(NoticeStatus::ConfigValidateBootError, &error_msg)
.await?;
return Ok(Some(("config_validate::boot_error", error_msg)));
return Ok(Some((NoticeStatus::ConfigValidateBootError, error_msg)));
}
logging!(debug, Type::Config, "生成运行时配置成功");
@@ -171,25 +178,25 @@ impl Config {
error_msg
);
CoreManager::global()
.use_default_config("config_validate::boot_error", &error_msg)
.use_default_config(NoticeStatus::ConfigValidateBootError, &error_msg)
.await?;
Ok(Some(("config_validate::boot_error", error_msg)))
Ok(Some((NoticeStatus::ConfigValidateBootError, error_msg)))
}
Err(err) => {
logging!(warn, Type::Config, "验证过程执行失败: {err:#}");
CoreManager::global()
.use_default_config("config_validate::process_terminated", "")
.use_default_config(NoticeStatus::ConfigValidateProcessTerminated, "")
.await?;
Ok(Some(("config_validate::process_terminated", String::new())))
Ok(Some((NoticeStatus::ConfigValidateProcessTerminated, String::new())))
}
}
} else {
let error_msg = config_result.err().map(|err| err.to_string()).unwrap_or_default();
logging!(warn, Type::Config, "生成配置文件失败,使用默认配置: {error_msg}");
CoreManager::global()
.use_default_config("config_validate::error", "")
.use_default_config(NoticeStatus::ConfigValidateError, "")
.await?;
Ok(Some(("config_validate::error", String::new())))
Ok(Some((NoticeStatus::ConfigValidateError, String::new())))
}
}
+5 -3
View File
@@ -1,3 +1,4 @@
use crate::core::notify::NoticeStatus;
use anyhow::Result;
use clash_verge_draft::DraftTransaction;
use serde::{Deserialize, Serialize};
@@ -138,12 +139,13 @@ impl Config {
}
// The runtime is already committed; a disk failure cannot undo its effective settings.
transaction.commit();
Handle::refresh_verge();
if state.requested && !state.enabled {
PENDING_DNS_OVERRIDE_NOTICE.store(true, Ordering::Relaxed);
Handle::notice_message("dns_override::auto_disabled", "");
Handle::notice(NoticeStatus::DnsOverrideAutoDisabled, "");
}
verge.data_arc().save_file().await
verge.data_arc().save_file().await?;
Handle::refresh_verge();
Ok(())
}
}
+9 -15
View File
@@ -1,4 +1,5 @@
use super::{Config, IClashTemp, IVerge, MixedPort};
use crate::core::notify::NoticeStatus;
use crate::{
constants::timing,
core::{
@@ -14,14 +15,13 @@ use crate::{
use anyhow::{Context as _, Result, anyhow, bail};
use clash_verge_draft::DraftTransaction;
use clash_verge_logging::{Type, logging};
use once_cell::sync::Lazy;
use parking_lot::Mutex;
use serde_yaml_ng::Value;
use std::{
collections::HashSet,
net::SocketAddr,
str::FromStr as _,
sync::atomic::{AtomicBool, Ordering},
sync::{LazyLock, OnceLock},
};
#[derive(Clone, Copy)]
@@ -30,9 +30,8 @@ struct MixedPortFallback {
current: u16,
}
static PENDING_FALLBACK_NOTICE: Lazy<Mutex<Option<MixedPortFallback>>> = Lazy::new(|| Mutex::new(None));
static STARTUP_CORE_BLOCKED: AtomicBool = AtomicBool::new(false);
static STARTUP_CORE_BLOCK_REASON: Lazy<Mutex<Option<String>>> = Lazy::new(|| Mutex::new(None));
static PENDING_FALLBACK_NOTICE: LazyLock<Mutex<Option<MixedPortFallback>>> = LazyLock::new(|| Mutex::new(None));
static STARTUP_CORE_BLOCK_REASON: OnceLock<String> = OnceLock::new();
impl Config {
pub(crate) async fn resolve_startup_mixed_port() -> Result<bool> {
@@ -147,17 +146,12 @@ impl Config {
}
pub(crate) fn block_startup_core(error: &anyhow::Error) {
STARTUP_CORE_BLOCKED.store(true, Ordering::Release);
*STARTUP_CORE_BLOCK_REASON.lock() = Some(error.to_string());
let _ = STARTUP_CORE_BLOCK_REASON.set(error.to_string());
report_fallback_error(error.to_string());
}
pub(crate) fn startup_core_block_reason() -> Option<String> {
if STARTUP_CORE_BLOCKED.load(Ordering::Acquire) {
STARTUP_CORE_BLOCK_REASON.lock().clone()
} else {
None
}
STARTUP_CORE_BLOCK_REASON.get().cloned()
}
pub(crate) fn notify_startup_mixed_port_fallback() {
@@ -166,8 +160,8 @@ impl Config {
};
AsyncHandler::spawn(move || async move {
tokio::time::sleep(timing::STARTUP_ERROR_DELAY).await;
Handle::notice_message(
"mixed_port::fallback",
Handle::notice(
NoticeStatus::MixedPortFallback,
format!("{},{}", change.original, change.current),
);
});
@@ -196,7 +190,7 @@ fn report_fallback_error(message: String) {
);
AsyncHandler::spawn(move || async move {
tokio::time::sleep(timing::STARTUP_ERROR_DELAY).await;
Handle::notice_message("mixed_port::fallback_error", message);
Handle::notice(NoticeStatus::MixedPortFallbackError, message);
});
}
+155 -148
View File
@@ -2,6 +2,8 @@ use super::{
PrfOption,
prfitem::{PrfItem, PrfSelected, normalize_profile_home_url},
};
use crate::core::notify::{Refresh, announce};
use crate::utils::retry::{RetryError, RetryPolicy, retry, retry_with_state};
use crate::{
core::{handle, tray::Tray},
utils::{
@@ -16,6 +18,7 @@ use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use serde_yaml_ng::Mapping;
use smartstring::alias::String;
use std::num::NonZeroUsize;
use std::{
collections::{HashMap, HashSet},
path::{Component, Path},
@@ -600,19 +603,21 @@ fn is_activation_current(generation: u64) -> bool {
}
async fn fetch_proxies_with_timeout() -> Result<Proxies> {
tokio::time::timeout(MIHOMO_OPERATION_TIMEOUT, async {
loop {
match handle::Handle::mihomo().get_proxies().await {
Ok(proxies) => return proxies,
Err(err) => {
logging!(debug, Type::Config, "mihomo proxies are not ready yet: {err:#}");
tokio::time::sleep(Duration::from_millis(500)).await;
}
}
}
})
let interval = Duration::from_millis(500);
let attempts =
NonZeroUsize::MIN.saturating_add((MIHOMO_OPERATION_TIMEOUT.as_millis() / interval.as_millis()) as usize + 1);
tokio::time::timeout(
MIHOMO_OPERATION_TIMEOUT,
retry(RetryPolicy::fixed(attempts, interval), |_| async {
handle::Handle::mihomo().get_proxies().await.map_err(|error| {
logging!(debug, Type::Config, "mihomo proxies are not ready yet: {error:#}");
RetryError::Retry(error)
})
}),
)
.await
.context("timed out while waiting for mihomo proxies")
.context("timed out while waiting for mihomo proxies")?
.map_err(Into::into)
}
async fn select_node_with_timeout(group_name: &String, node: &String) -> Result<()> {
@@ -691,51 +696,58 @@ async fn update_tray_after_activation(generation: u64) {
}
}
async fn persist_selected_update<F, Fut>(supersede: bool, edit: F) -> Result<()>
where
F: FnOnce(IProfiles) -> Fut + Send,
Fut: std::future::Future<Output = Result<(IProfiles, bool)>> + Send,
{
let changed = Config::profiles().await.with_data_modify(edit).await?;
if changed {
if supersede {
supersede_selected_activation();
}
announce(Refresh::Profiles);
}
Ok(())
}
/// 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);
let recorded = Config::profiles()
.await
.with_data_modify(move |mut profiles| async move {
let Some(current) = profiles.current.clone() else {
return Ok((profiles, false));
};
let Some(item) = profiles
.items
.as_mut()
.and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(&current)))
else {
return Ok((profiles, false));
};
persist_selected_update(true, move |mut profiles| async move {
let Some(current) = profiles.current.clone() else {
return Ok((profiles, false));
};
let Some(item) = profiles
.items
.as_mut()
.and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(&current)))
else {
return Ok((profiles, false));
};
let mut selected = item.selected.clone().unwrap_or_default();
match selected
.iter_mut()
.find(|entry| entry.name.as_ref() == Some(&group_name))
{
Some(entry) => {
if entry.now.as_ref() == Some(&node) {
return Ok((profiles, false));
}
entry.now = Some(node);
let mut selected = item.selected.clone().unwrap_or_default();
match selected
.iter_mut()
.find(|entry| entry.name.as_ref() == Some(&group_name))
{
Some(entry) => {
if entry.now.as_ref() == Some(&node) {
return Ok((profiles, false));
}
None => selected.push(PrfSelected {
name: Some(group_name),
now: Some(node),
}),
entry.now = Some(node);
}
item.selected = Some(selected);
profiles.save_file().await?;
Ok((profiles, true))
})
.await?;
if recorded {
supersede_selected_activation();
handle::Handle::refresh_profiles();
}
Ok(())
None => selected.push(PrfSelected {
name: Some(group_name),
now: Some(node),
}),
}
item.selected = Some(selected);
profiles.save_file().await?;
Ok((profiles, true))
})
.await
}
fn remove_selected_node(selected: &mut Vec<PrfSelected>, group_name: &str) -> bool {
@@ -745,36 +757,28 @@ fn remove_selected_node(selected: &mut Vec<PrfSelected>, group_name: &str) -> bo
}
pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
let cleared = Config::profiles()
.await
.with_data_modify(move |mut profiles| async move {
let Some(current) = profiles.current.clone() else {
return Ok((profiles, false));
};
let Some(item) = profiles
.items
.as_mut()
.and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(&current)))
else {
return Ok((profiles, false));
};
persist_selected_update(true, move |mut profiles| async move {
let Some(current) = profiles.current.clone() else {
return Ok((profiles, false));
};
let Some(item) = profiles
.items
.as_mut()
.and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(&current)))
else {
return Ok((profiles, false));
};
let mut selected = item.selected.clone().unwrap_or_default();
if !remove_selected_node(&mut selected, group_name) {
return Ok((profiles, false));
}
let mut selected = item.selected.clone().unwrap_or_default();
if !remove_selected_node(&mut selected, group_name) {
return Ok((profiles, false));
}
item.selected = (!selected.is_empty()).then_some(selected);
profiles.save_file().await?;
Ok((profiles, true))
})
.await?;
if cleared {
supersede_selected_activation();
handle::Handle::refresh_profiles();
}
Ok(())
item.selected = (!selected.is_empty()).then_some(selected);
profiles.save_file().await?;
Ok((profiles, true))
})
.await
}
async fn persist_reconciled_selected(
@@ -787,34 +791,27 @@ async fn persist_reconciled_selected(
return Ok(());
}
let profiles = Config::profiles().await;
let profile_uid = profile_uid.clone();
let original_selected = original_selected.to_vec();
let updated = profiles
.with_data_modify(move |mut profiles| async move {
if !is_activation_current(generation) || profiles.current.as_ref() != Some(&profile_uid) {
return Ok((profiles, false));
}
persist_selected_update(false, move |mut profiles| async move {
if !is_activation_current(generation) || profiles.current.as_ref() != Some(&profile_uid) {
return Ok((profiles, false));
}
let profile = profiles
.items
.as_mut()
.and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(&profile_uid)))
.with_context(|| format!("failed to find the profile item \"uid:{profile_uid}\""))?;
if profile.selected.as_deref().unwrap_or(&[]) != original_selected.as_slice() {
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)))
.with_context(|| format!("failed to find the profile item \"uid:{profile_uid}\""))?;
if profile.selected.as_deref().unwrap_or(&[]) != original_selected.as_slice() {
return Ok((profiles, false));
}
profile.selected = (!selected.is_empty()).then_some(selected);
profiles.save_file().await?;
Ok((profiles, true))
})
.await?;
if updated {
handle::Handle::refresh_profiles();
}
Ok(())
profile.selected = (!selected.is_empty()).then_some(selected);
profiles.save_file().await?;
Ok((profiles, true))
})
.await
}
/// Returns recorded selections whose groups have not reached the requested node.
@@ -836,48 +833,58 @@ fn unsettled_selections(selected: &[PrfSelected], proxies: &Proxies) -> Vec<Stri
/// Retries selections while provider-backed groups finish loading.
async fn settle_pending_selections(selected: &[PrfSelected], completed: &mut HashMap<String, String>, generation: u64) {
let deadline = Instant::now() + SELECTED_NODES_SETTLE_DEADLINE;
loop {
tokio::time::sleep(SELECTED_NODES_SETTLE_INTERVAL).await;
if !is_activation_current(generation) {
return;
}
let Ok(snapshot) = fetch_proxies_with_timeout().await else {
// Unreachable core: the deadline still applies, so this cannot spin forever.
if Instant::now() >= deadline {
return;
}
continue;
};
if !is_activation_current(generation) {
return;
}
let pending = unsettled_selections(selected, &snapshot);
if pending.is_empty() {
return;
}
if Instant::now() >= deadline {
logging!(
warn,
Type::Config,
"gave up putting back {} selected node(s) the core never loaded: {}",
pending.len(),
pending.iter().map(String::as_str).collect::<Vec<_>>().join(", ")
);
return;
}
let plan = reconcile_selected_nodes(selected, None, &snapshot);
if apply_activations(&plan.activations, completed, generation)
.await
.is_none()
{
return;
}
if is_activation_current(generation) {
handle::Handle::refresh_clash();
}
}
let attempts = NonZeroUsize::MIN.saturating_add(
(SELECTED_NODES_SETTLE_DEADLINE.as_millis() / SELECTED_NODES_SETTLE_INTERVAL.as_millis()) as usize,
);
tokio::time::sleep(SELECTED_NODES_SETTLE_INTERVAL).await;
let _ = retry_with_state(
RetryPolicy::fixed(attempts, SELECTED_NODES_SETTLE_INTERVAL),
(selected, completed, generation, deadline),
|state, _| {
Box::pin(async move {
let (selected, completed, generation, deadline) = state;
if !is_activation_current(*generation) {
return Ok(());
}
let Ok(snapshot) = fetch_proxies_with_timeout().await else {
return if Instant::now() >= *deadline {
Ok(())
} else {
Err(RetryError::Retry(()))
};
};
if !is_activation_current(*generation) {
return Ok(());
}
let pending = unsettled_selections(selected, &snapshot);
if pending.is_empty() {
return Ok(());
}
if Instant::now() >= *deadline {
logging!(
warn,
Type::Config,
"gave up putting back {} selected node(s) the core never loaded: {}",
pending.len(),
pending.iter().map(String::as_str).collect::<Vec<_>>().join(", ")
);
return Ok(());
}
let plan = reconcile_selected_nodes(selected, None, &snapshot);
if apply_activations(&plan.activations, completed, *generation)
.await
.is_none()
{
return Ok(());
}
if is_activation_current(*generation) {
announce(Refresh::Clash);
}
Err(RetryError::Retry(()))
})
},
)
.await;
}
/// Releases the first-pass waiter even when restoration exits early.
@@ -920,7 +927,7 @@ async fn activate_selected_nodes_worker(
}
if is_activation_current(generation) {
handle::Handle::refresh_clash();
announce(Refresh::Clash);
}
let plan = if needs_confirmation {
@@ -944,7 +951,7 @@ async fn activate_selected_nodes_worker(
return Ok(());
};
if confirmed_activated_count > 0 && is_activation_current(generation) {
handle::Handle::refresh_clash();
announce(Refresh::Clash);
}
confirmed_plan
} else {
@@ -1034,7 +1041,7 @@ fn activate_selected_nodes_with(repair: SelectionRepair) -> tokio::sync::oneshot
if selected.is_empty() {
if is_activation_current(generation) {
handle::Handle::refresh_clash();
announce(Refresh::Clash);
}
return Ok(());
}
@@ -1046,7 +1053,7 @@ fn activate_selected_nodes_with(repair: SelectionRepair) -> tokio::sync::oneshot
if let Err(err) = result {
logging!(error, Type::Config, "failed to activate selected nodes: {err:#}");
// The profile itself is already active even if node restoration failed.
handle::Handle::refresh_clash();
announce(Refresh::Clash);
}
update_tray_after_activation(generation).await;
logging!(debug, Type::Config, "activating selected nodes done!");
+57
View File
@@ -0,0 +1,57 @@
use crate::{
config::{Config, IVerge},
core::{autostart, hotkey, lightweight, tray},
};
use anyhow::Result;
use futures::future::BoxFuture;
pub(crate) fn ensure_autostart(_patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move { autostart::update_launch().await })
}
pub(crate) fn ensure_hotkey(patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move {
if let Some(hotkeys) = &patch.hotkeys {
hotkey::Hotkey::global().update(hotkeys.to_owned()).await?;
}
Ok(())
})
}
pub(crate) fn ensure_tray_menu(_patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move { tray::Tray::global().update_menu().await })
}
pub(crate) fn ensure_tray_icon(patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move {
tray::Tray::global()
.update_icon(&Config::verge().await.latest_arc())
.await?;
#[cfg(target_os = "macos")]
if let Some(enabled) = patch.enable_tray_speed {
tray::Tray::global().update_speed_task(enabled);
}
#[cfg(not(target_os = "macos"))]
let _ = patch;
Ok(())
})
}
pub(crate) fn ensure_tray_tooltip(_patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move { tray::Tray::global().update_tooltip().await })
}
pub(crate) fn ensure_tray_click(_patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move { tray::Tray::global().update_click_behavior().await })
}
pub(crate) fn ensure_lightweight(patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move {
if patch.enable_auto_light_weight_mode.unwrap_or(false) {
lightweight::enable_auto_light_weight_mode().await;
} else {
lightweight::disable_auto_light_weight_mode();
}
Ok(())
})
}
@@ -7,8 +7,8 @@ use crate::{
use anyhow::Result;
use chrono::Local;
use clash_verge_logging::{Type, logging};
use once_cell::sync::OnceCell;
use parking_lot::RwLock;
use std::sync::OnceLock;
use std::{
path::PathBuf,
sync::{
@@ -92,7 +92,7 @@ pub struct AutoBackupManager {
impl AutoBackupManager {
pub fn global() -> &'static Self {
static INSTANCE: OnceCell<AutoBackupManager> = OnceCell::new();
static INSTANCE: OnceLock<AutoBackupManager> = OnceLock::new();
INSTANCE.get_or_init(|| {
let (tx, _rx) = watch::channel(AutoBackupSettings::default());
Self {
+2 -2
View File
@@ -4,9 +4,9 @@ use anyhow::Error;
use arc_swap::{ArcSwap, ArcSwapOption};
use backon::{ConstantBuilder, Retryable as _};
use clash_verge_logging::{Type, logging};
use once_cell::sync::OnceCell;
use reqwest_dav::list_cmd::{ListEntity, ListFile, ListMultiStatus};
use smartstring::alias::String;
use std::sync::OnceLock;
use std::{
collections::HashMap,
env::{consts::OS, temp_dir},
@@ -58,7 +58,7 @@ pub struct WebDavClient {
impl WebDavClient {
pub fn global() -> &'static Self {
static WEBDAV_CLIENT: OnceCell<WebDavClient> = OnceCell::new();
static WEBDAV_CLIENT: OnceLock<WebDavClient> = OnceLock::new();
WEBDAV_CLIENT.get_or_init(|| Self {
config: ArcSwapOption::new(None),
clients: ArcSwap::new(Arc::new(HashMap::new())),
+4 -3
View File
@@ -1,8 +1,9 @@
use crate::core::notify::NoticeStatus;
use crate::process::AsyncHandler;
use crate::singleton;
use crate::utils::notification::{NotificationEvent, notify_event};
use crate::utils::window_manager::WindowManager;
use crate::{config::Config, core::handle, feat, module::lightweight::entry_lightweight_mode};
use crate::{config::Config, core::handle, core::lightweight::entry_lightweight_mode, feat};
use anyhow::{Result, bail};
use arc_swap::ArcSwap;
use clash_verge_logging::{Type, logging};
@@ -177,7 +178,7 @@ impl Hotkey {
"Hotkey profile reactivation failed validation: {}",
message.as_str()
);
handle::Handle::notice_message("reactivate_profiles::error", message);
handle::Handle::notice(NoticeStatus::ReactivateProfilesError, message);
}
Err(err) => {
logging!(
@@ -186,7 +187,7 @@ impl Hotkey {
"Failed to reactivate subscriptions via hotkey: {}",
err
);
handle::Handle::notice_message("reactivate_profiles::error", err.to_string());
handle::Handle::notice(NoticeStatus::ReactivateProfilesError, err.to_string());
}
});
}
+35 -3
View File
@@ -1,4 +1,5 @@
use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
use crate::core::notify::NoticeStatus;
use crate::core::service::StageRequest;
use crate::{
config::{Config, IProfiles, runtime::IRuntime},
@@ -129,7 +130,31 @@ where
}
impl CoreManager {
pub async fn use_default_config(&self, error_key: &str, error_msg: &str) -> Result<()> {
pub(crate) fn claim_config_update(
&self,
_config_write: &tokio::sync::MutexGuard<'_, ()>,
) -> Result<ConfigUpdateGuard<'_>> {
if !self.try_start_config_update() {
anyhow::bail!("configuration update is already running");
}
Ok(ConfigUpdateGuard(self))
}
pub(crate) async fn update_config_in_patch(&self, _update: &ConfigUpdateGuard<'_>) -> Result<()> {
if handle::Handle::global().is_exiting() {
anyhow::bail!("application is exiting");
}
self.set_last_update(Instant::now());
Config::generate().await?;
let outcome = self.validate_and_apply_draft().await?;
if outcome.is_valid() {
Ok(())
} else {
Err(anyhow!("{outcome}"))
}
}
pub async fn use_default_config(&self, status: NoticeStatus, message: &str) -> Result<()> {
use crate::constants::files::RUNTIME_CONFIG;
let runtime_path = dirs::app_home_dir()?.join(RUNTIME_CONFIG);
@@ -145,7 +170,7 @@ impl CoreManager {
});
help::save_yaml(&runtime_path, &clash_config, Some("# Clash Verge Runtime")).await?;
handle::Handle::notice_message(error_key, error_msg);
handle::Handle::notice(status, message);
Ok(())
}
@@ -299,6 +324,14 @@ impl CoreManager {
/// Validates and applies the caller's transaction, committing only on success.
async fn validate_and_apply(&self, transaction: DraftTransaction<'_>) -> Result<ValidationOutcome> {
let outcome = self.validate_and_apply_draft().await?;
if outcome.is_valid() {
transaction.commit();
}
Ok(outcome)
}
async fn validate_and_apply_draft(&self) -> Result<ValidationOutcome> {
// One serialization feeds check and run files; the core never applies unvalidated bytes.
let yaml = Config::runtime_config_yaml().await?;
let outcome = CoreConfigValidator::global()
@@ -310,7 +343,6 @@ impl CoreManager {
let run_path = Config::write_runtime_file(&yaml).await?;
self.apply_config(run_path).await?;
transaction.commit();
Ok(ValidationOutcome::Valid)
}
+13 -8
View File
@@ -840,29 +840,34 @@ impl CoreManager {
AsyncHandler::spawn(|| async move {
let manager = Self::global();
let started = Instant::now();
loop {
use crate::utils::retry::{RetryError, RetryPolicy, retry};
let attempts = std::num::NonZeroUsize::MIN.saturating_add(
(timing::SERVICE_HANDOFF_WINDOW.as_millis() / timing::SERVICE_HANDOFF_INTERVAL.as_millis()) as usize,
);
let _ = retry(RetryPolicy::fixed(attempts, std::time::Duration::ZERO), |_| async {
if started.elapsed() >= timing::SERVICE_HANDOFF_WINDOW {
logging!(
info,
Type::Core,
"service handoff window elapsed; staying in sidecar mode"
);
break;
return Ok(());
}
// The window is checked before waiting, including the final handoff attempt.
tokio::time::sleep(timing::SERVICE_HANDOFF_INTERVAL).await;
if !matches!(*manager.get_running_mode(), RunningMode::Sidecar) {
break;
return Ok(());
}
match manager.try_handoff_sidecar_to_service().await {
HandoffOutcome::Done => break,
HandoffOutcome::Done => Ok(()),
HandoffOutcome::Failed => {
logging!(warn, Type::Core, "handoff attempt failed; staying in sidecar mode");
break;
Ok(())
}
HandoffOutcome::NotReady => {}
HandoffOutcome::NotReady => Err(RetryError::Retry(())),
}
}
})
.await;
manager.handoff_watcher_running.store(false, Ordering::Release);
});
}
+46 -37
View File
@@ -1,11 +1,12 @@
mod config;
pub(crate) use config::ConfigUpdateGuard;
mod lifecycle;
mod state;
use anyhow::Result;
use arc_swap::{ArcSwap, ArcSwapOption};
use clash_verge_logging::{LogRing, Type, logging};
use once_cell::sync::Lazy;
use std::sync::LazyLock;
use std::{
fmt,
sync::{
@@ -21,7 +22,7 @@ use crate::singleton;
#[cfg(target_os = "windows")]
use std::os::windows::io::OwnedHandle;
pub(crate) static CLASH_LOGGER: Lazy<Arc<LogRing>> = Lazy::new(|| Arc::new(LogRing::new()));
pub(crate) static CLASH_LOGGER: LazyLock<Arc<LogRing>> = LazyLock::new(|| Arc::new(LogRing::new()));
tokio::task_local! {
static PROFILE_SELECTIONS_PENDING_COMMIT: bool;
@@ -284,48 +285,56 @@ impl CoreManager {
anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}");
}
let mut retries = 0;
loop {
match self.start_core().await {
Ok(()) => {
crate::config::Config::notify_startup_mixed_port_fallback();
return Ok(!matches!(*self.get_running_mode(), RunningMode::NotRunning));
}
Err(start_error) if retries < MAX_PORT_FALLBACK_RETRIES => {
if !matches!(*self.get_running_mode(), RunningMode::NotRunning) {
use crate::utils::retry::{RetryError, RetryPolicy, retry};
retry(
RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add(MAX_PORT_FALLBACK_RETRIES),
std::time::Duration::ZERO,
),
|retries| async move {
match self.start_core().await {
Ok(()) => {
crate::config::Config::notify_startup_mixed_port_fallback();
return Err(start_error);
Ok(!matches!(*self.get_running_mode(), RunningMode::NotRunning))
}
match crate::config::Config::resolve_startup_mixed_port().await {
Ok(true) => {
retries += 1;
tracing::Span::current().record("retries", retries);
logging!(
warn,
Type::Core,
"Retrying core startup after mixed proxy port fallback ({}/{}): {start_error:#}",
retries,
MAX_PORT_FALLBACK_RETRIES
);
}
Ok(false) => {
Err(start_error) if retries < MAX_PORT_FALLBACK_RETRIES => {
if !matches!(*self.get_running_mode(), RunningMode::NotRunning) {
crate::config::Config::notify_startup_mixed_port_fallback();
return Err(start_error);
return Err(RetryError::Stop(start_error));
}
Err(fallback_error) => {
crate::config::Config::block_startup_core(&fallback_error);
return Err(start_error.context(format!(
"the mixed proxy port fallback did not rescue core startup: {fallback_error:#}"
)));
match crate::config::Config::resolve_startup_mixed_port().await {
Ok(true) => {
let retries = retries + 1;
tracing::Span::current().record("retries", retries);
logging!(
warn,
Type::Core,
"Retrying core startup after mixed proxy port fallback ({}/{}): {start_error:#}",
retries,
MAX_PORT_FALLBACK_RETRIES
);
Err(RetryError::Retry(start_error))
}
Ok(false) => {
crate::config::Config::notify_startup_mixed_port_fallback();
Err(RetryError::Stop(start_error))
}
Err(fallback_error) => {
crate::config::Config::block_startup_core(&fallback_error);
Err(RetryError::Stop(start_error.context(format!(
"the mixed proxy port fallback did not rescue core startup: {fallback_error:#}"
))))
}
}
}
Err(error) => {
crate::config::Config::notify_startup_mixed_port_fallback();
Err(RetryError::Stop(error))
}
}
Err(error) => {
crate::config::Config::notify_startup_mixed_port_fallback();
return Err(error);
}
}
}
},
)
.await
}
}
+30 -31
View File
@@ -1,6 +1,7 @@
#[cfg(test)]
use super::claim_core_readiness_generation;
use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
use crate::utils::retry::{RetryError, RetryPolicy, retry};
use crate::{
AsyncHandler,
config::Config,
@@ -11,6 +12,7 @@ use crate::{
use anyhow::{Context as _, Result};
use clash_verge_logging::Type;
use log::Level;
use std::num::NonZeroUsize;
use std::path::Path;
use tauri_plugin_mihomo::MihomoExt as _;
use tauri_plugin_shell::ShellExt as _;
@@ -41,14 +43,15 @@ async fn retry_service_start<Start, StartFuture>(
mut start: Start,
) -> Result<()>
where
Start: FnMut() -> StartFuture,
StartFuture: std::future::Future<Output = Result<()>>,
Start: FnMut() -> StartFuture + Send,
StartFuture: std::future::Future<Output = Result<()>> + Send,
{
let mut last_error = None;
for attempt in 0..attempts {
match start().await {
Ok(()) => return Ok(()),
Err(error) => {
let attempts = NonZeroUsize::new(attempts).ok_or_else(|| anyhow::anyhow!("service start failed"))?;
retry(RetryPolicy::fixed(attempts, retry_delay), |attempt| {
// The Windows Service IPC future would otherwise inflate every enclosing lifecycle future.
let future = Box::pin(start());
async move {
future.await.map_err(|error| {
logging!(
warn,
Type::Core,
@@ -60,16 +63,14 @@ where
.downcast_ref::<service::ServiceStartRefusal>()
.is_some_and(|refusal| service::StageRequest::is_about_the_bundle(refusal.code))
{
return Err(error);
RetryError::Stop(error)
} else {
RetryError::Retry(error)
}
last_error = Some(error);
if attempt + 1 < attempts {
tokio::time::sleep(retry_delay).await;
}
}
})
}
}
Err(last_error.unwrap_or_else(|| anyhow::anyhow!("service start failed")))
})
.await
}
impl CoreManager {
@@ -95,14 +96,16 @@ async fn poll_sidecar_readiness<F, Fut>(
mut probe: F,
) -> Result<()>
where
F: FnMut() -> Fut,
Fut: std::future::Future<Output = Result<()>>,
F: FnMut() -> Fut + Send,
Fut: std::future::Future<Output = Result<()>> + Send,
{
let mut last_error = None;
for attempt in 0..max_attempts {
match probe().await {
Ok(()) => return Ok(()),
Err(error) => {
let attempts = NonZeroUsize::new(max_attempts)
.context("sidecar readiness was configured with no attempts")
.context("Mihomo API did not become ready")?;
retry(RetryPolicy::fixed(attempts, retry_delay), |attempt| {
let future = probe();
async move {
future.await.map_err(|error| {
logging!(
debug,
Type::Core,
@@ -110,16 +113,12 @@ where
attempt + 1,
max_attempts
);
last_error = Some(error);
}
RetryError::Retry(error)
})
}
if attempt + 1 < max_attempts {
tokio::time::sleep(retry_delay).await;
}
}
Err(last_error
.unwrap_or_else(|| anyhow::anyhow!("sidecar readiness was configured with no attempts"))
.context("Mihomo API did not become ready"))
})
.await
.context("Mihomo API did not become ready")
}
fn should_clear_terminated_sidecar(running_mode: &RunningMode, current_pid: Option<u32>, terminated_pid: u32) -> bool {
+5 -2
View File
@@ -1,13 +1,15 @@
pub(crate) mod app_effects;
pub mod auto_backup;
pub mod autostart;
pub mod backup;
pub mod handle;
pub mod hotkey;
pub mod lightweight;
pub mod listener;
pub mod logger;
pub mod manager;
#[cfg(target_os = "macos")]
pub mod network_watch;
pub mod notification;
pub mod notify;
pub(crate) mod owner_identity;
pub mod proxy_control;
pub mod proxy_view;
@@ -22,3 +24,4 @@ pub mod validate;
pub mod win_uwp;
pub use self::{manager::CoreManager, timer::Timer, updater::SilentUpdater};
pub use notify::{handle, notification};
+11 -4
View File
@@ -5,13 +5,13 @@
use crate::{config::Config, core::CoreManager, core::proxy_control, process::AsyncHandler};
use clash_verge_logging::{Type, logging};
use parking_lot::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use sysproxy::NetworkServiceMonitor;
static MONITOR: Mutex<Option<NetworkServiceMonitor>> = Mutex::new(None);
static ARMED: AtomicBool = AtomicBool::new(false);
pub fn is_armed() -> bool {
MONITOR.lock().is_some()
ARMED.load(Ordering::Acquire)
}
/// Subscribe to the primary IPv4 service on the main run loop. Armed on return, so a service
@@ -21,7 +21,14 @@ pub fn start() {
AsyncHandler::spawn(reapply);
}) {
Ok(monitor) => {
*MONITOR.lock() = Some(monitor);
if ARMED
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.is_err()
{
return;
}
// Dropping the monitor stops network notifications, so it must outlive the call.
std::mem::forget(monitor);
logging!(
debug,
Type::Core,
+139
View File
@@ -0,0 +1,139 @@
use super::{handle::Handle, notification::FrontendEvent};
use anyhow::Result;
use parking_lot::Mutex;
use std::{cell::RefCell, future::Future, time::Duration};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Refresh {
Clash,
Verge,
Profiles,
Proxies,
}
tokio::task_local! {
static PENDING: RefCell<Vec<Refresh>>;
}
const REFRESH_WINDOW: Duration = Duration::from_millis(20);
static BATCH: RefreshBatch = RefreshBatch(Mutex::new(Vec::new()));
#[derive(Default)]
struct RefreshBatch(Mutex<Vec<Refresh>>);
impl RefreshBatch {
fn enqueue(&self, refresh: Refresh) -> bool {
let mut pending = self.0.lock();
let start_window = pending.is_empty();
if !pending.contains(&refresh) {
pending.push(refresh);
}
start_window
}
async fn flush(&self, emit: impl Fn(Refresh)) {
// A fixed window bounds latency even under a continuous stream of refreshes.
tokio::time::sleep(REFRESH_WINDOW).await;
let refreshes = std::mem::take(&mut *self.0.lock());
for refresh in refreshes {
emit(refresh);
}
}
}
pub fn announce(refresh: Refresh) {
if PENDING.try_with(|pending| pending.borrow_mut().push(refresh)).is_err() && BATCH.enqueue(refresh) {
crate::AsyncHandler::spawn(|| BATCH.flush(emit));
}
}
fn emit(refresh: Refresh) {
Handle::send_event(match refresh {
Refresh::Clash => FrontendEvent::RefreshClash,
Refresh::Verge => FrontendEvent::RefreshVerge,
Refresh::Profiles => FrontendEvent::RefreshProfiles,
Refresh::Proxies => FrontendEvent::RefreshProxyConfig,
});
}
async fn collect_committed<T: Send>(operation: impl Future<Output = Result<T>> + Send) -> Result<(T, Vec<Refresh>)> {
PENDING
.scope(RefCell::new(Vec::new()), async {
let value = operation.await?;
let refreshes = PENDING.with(|pending| pending.take());
Ok((value, refreshes))
})
.await
}
pub async fn after_commit<T: Send>(operation: impl Future<Output = Result<T>> + Send) -> Result<T> {
let (value, refreshes) = collect_committed(operation).await?;
// Nested transactions hand their notifications to the outer transaction.
for refresh in refreshes {
announce(refresh);
}
Ok(value)
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn only_successful_transactions_publish_refreshes() -> Result<()> {
let (_, refreshes) = collect_committed(async {
announce(Refresh::Clash);
after_commit(async {
announce(Refresh::Verge);
Ok(())
})
.await?;
let failed = after_commit(async {
announce(Refresh::Profiles);
Err::<(), _>(anyhow::anyhow!("persistence failed"))
})
.await;
assert!(failed.is_err());
announce(Refresh::Clash);
Ok(())
})
.await?;
assert_eq!(refreshes, [Refresh::Clash, Refresh::Verge, Refresh::Clash]);
Ok(())
}
#[tokio::test]
async fn bursts_keep_each_refresh_kind_and_rearm_during_delivery() -> Result<()> {
let batch = RefreshBatch::default();
let delivered = Mutex::new(Vec::new());
assert!(batch.enqueue(Refresh::Clash));
for refresh in [Refresh::Verge, Refresh::Clash, Refresh::Profiles, Refresh::Proxies] {
assert!(!batch.enqueue(refresh));
}
tokio::time::timeout(Duration::from_secs(1), async {
batch
.flush(|refresh| {
delivered.lock().push(refresh);
if refresh == Refresh::Clash {
assert!(batch.enqueue(Refresh::Clash));
assert!(!batch.enqueue(Refresh::Clash));
}
})
.await;
batch.flush(|refresh| delivered.lock().push(refresh)).await;
})
.await?;
assert_eq!(
*delivered.lock(),
[
Refresh::Clash,
Refresh::Verge,
Refresh::Profiles,
Refresh::Proxies,
Refresh::Clash
]
);
assert!(batch.enqueue(Refresh::Verge));
Ok(())
}
}
@@ -1,6 +1,10 @@
use super::NoticeStatus;
use crate::{APP_HANDLE, singleton};
use smartstring::alias::String;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use tauri::AppHandle;
use tauri_plugin_mihomo::{Mihomo, MihomoExt as _};
@@ -36,19 +40,11 @@ impl Handle {
}
pub fn refresh_clash() {
Self::send_event(FrontendEvent::RefreshClash);
super::announce(super::Refresh::Clash);
}
pub fn refresh_verge() {
Self::send_event(FrontendEvent::RefreshVerge);
}
pub fn refresh_profiles() {
Self::send_event(FrontendEvent::RefreshProfiles);
}
pub fn refresh_proxy_config() {
Self::send_event(FrontendEvent::RefreshProxyConfig);
super::announce(super::Refresh::Verge);
}
/// Push a Run State snapshot to the frontend.
@@ -80,13 +76,10 @@ impl Handle {
Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid });
}
pub fn notice_message<S: AsRef<str>, M: Into<String>>(status: S, msg: M) {
let status_str = status.as_ref();
let msg_str = msg.into();
pub fn notice(status: NoticeStatus, message: impl Into<Arc<str>>) {
Self::send_event(FrontendEvent::NoticeMessage {
status: status_str,
message: msg_str,
status,
message: message.into(),
});
}
@@ -102,7 +95,7 @@ impl Handle {
self.is_exiting.load(Ordering::Acquire)
}
fn send_event(event: FrontendEvent) {
pub(super) fn send_event(event: FrontendEvent) {
let handle = Self::global();
if handle.is_exiting() {
return;
+174
View File
@@ -0,0 +1,174 @@
mod announce;
pub use announce::{Refresh, after_commit, announce};
pub mod desktop;
pub mod handle;
pub mod notification;
pub use notification::frontend_wire_contract;
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub enum NoticeStatus {
#[serde(rename = "info")]
Info,
#[serde(rename = "import_sub_url::ok")]
ImportSubUrlOk,
#[serde(rename = "import_sub_url::error")]
ImportSubUrlError,
#[serde(rename = "set_config::error")]
SetConfigError,
#[serde(rename = "core_start::error")]
CoreStartError,
#[serde(rename = "service_core::repair_required")]
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
ServiceCoreRepairRequired,
#[serde(rename = "service_core::app_data_not_owned")]
ServiceCoreAppDataNotOwned,
#[serde(rename = "service_core::sidecar_fallback")]
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
ServiceCoreSidecarFallback,
#[serde(rename = "dns_override::auto_disabled")]
DnsOverrideAutoDisabled,
#[serde(rename = "enhance::discarded_keys")]
EnhanceDiscardedKeys,
#[serde(rename = "tun_mode::auto_disabled")]
TunModeAutoDisabled,
#[serde(rename = "tun_mode::auto_disable_failed")]
TunModeAutoDisableFailed,
#[serde(rename = "app_restart::core_stop_failed")]
AppRestartCoreStopFailed,
#[serde(rename = "app_quit::core_stop_failed")]
AppQuitCoreStopFailed,
#[serde(rename = "update_with_clash_proxy")]
UpdateWithClashProxy,
#[serde(rename = "update_failed_even_with_clash")]
UpdateFailedEvenWithClash,
#[serde(rename = "reactivate_profiles::error")]
ReactivateProfilesError,
#[serde(rename = "update_failed")]
UpdateFailed,
#[serde(rename = "config_validate::boot_error")]
ConfigValidateBootError,
#[serde(rename = "config_validate::error")]
ConfigValidateError,
#[serde(rename = "config_validate::process_terminated")]
ConfigValidateProcessTerminated,
#[serde(rename = "config_validate::script_error")]
ConfigValidateScriptError,
#[serde(rename = "config_validate::script_syntax_error")]
ConfigValidateScriptSyntaxError,
#[serde(rename = "config_validate::script_missing_main")]
ConfigValidateScriptMissingMain,
#[serde(rename = "config_validate::file_not_found")]
ConfigValidateFileNotFound,
#[serde(rename = "config_validate::yaml_syntax_error")]
ConfigValidateYamlSyntaxError,
#[serde(rename = "config_validate::yaml_read_error")]
ConfigValidateYamlReadError,
#[serde(rename = "config_validate::yaml_mapping_error")]
ConfigValidateYamlMappingError,
#[serde(rename = "config_validate::merge_syntax_error")]
ConfigValidateMergeSyntaxError,
#[serde(rename = "config_validate::merge_mapping_error")]
ConfigValidateMergeMappingError,
#[serde(rename = "config_core::change_success")]
ConfigCoreChangeSuccess,
#[serde(rename = "config_core::change_error")]
ConfigCoreChangeError,
#[serde(rename = "mixed_port::fallback")]
MixedPortFallback,
#[serde(rename = "mixed_port::fallback_error")]
MixedPortFallbackError,
}
impl NoticeStatus {
/// Every variant in golden order. The wire-contract export and the golden
/// test both derive their variant list from here; expected strings stay
/// hand-written in the test so renames cannot slip through.
pub const ALL: [Self; 34] = [
Self::Info,
Self::ImportSubUrlOk,
Self::ImportSubUrlError,
Self::SetConfigError,
Self::CoreStartError,
Self::ServiceCoreRepairRequired,
Self::ServiceCoreAppDataNotOwned,
Self::ServiceCoreSidecarFallback,
Self::DnsOverrideAutoDisabled,
Self::EnhanceDiscardedKeys,
Self::TunModeAutoDisabled,
Self::TunModeAutoDisableFailed,
Self::AppRestartCoreStopFailed,
Self::AppQuitCoreStopFailed,
Self::UpdateWithClashProxy,
Self::UpdateFailedEvenWithClash,
Self::ReactivateProfilesError,
Self::UpdateFailed,
Self::ConfigValidateBootError,
Self::ConfigValidateError,
Self::ConfigValidateProcessTerminated,
Self::ConfigValidateScriptError,
Self::ConfigValidateScriptSyntaxError,
Self::ConfigValidateScriptMissingMain,
Self::ConfigValidateFileNotFound,
Self::ConfigValidateYamlSyntaxError,
Self::ConfigValidateYamlReadError,
Self::ConfigValidateYamlMappingError,
Self::ConfigValidateMergeSyntaxError,
Self::ConfigValidateMergeMappingError,
Self::ConfigCoreChangeSuccess,
Self::ConfigCoreChangeError,
Self::MixedPortFallback,
Self::MixedPortFallbackError,
];
}
#[cfg(test)]
mod tests {
use super::NoticeStatus;
#[test]
fn notice_status_wire_contract() -> Result<(), serde_json::Error> {
let statuses = NoticeStatus::ALL;
let expected = [
"info",
"import_sub_url::ok",
"import_sub_url::error",
"set_config::error",
"core_start::error",
"service_core::repair_required",
"service_core::app_data_not_owned",
"service_core::sidecar_fallback",
"dns_override::auto_disabled",
"enhance::discarded_keys",
"tun_mode::auto_disabled",
"tun_mode::auto_disable_failed",
"app_restart::core_stop_failed",
"app_quit::core_stop_failed",
"update_with_clash_proxy",
"update_failed_even_with_clash",
"reactivate_profiles::error",
"update_failed",
"config_validate::boot_error",
"config_validate::error",
"config_validate::process_terminated",
"config_validate::script_error",
"config_validate::script_syntax_error",
"config_validate::script_missing_main",
"config_validate::file_not_found",
"config_validate::yaml_syntax_error",
"config_validate::yaml_read_error",
"config_validate::yaml_mapping_error",
"config_validate::merge_syntax_error",
"config_validate::merge_mapping_error",
"config_core::change_success",
"config_core::change_error",
"mixed_port::fallback",
"mixed_port::fallback_error",
];
let actual: Vec<_> = statuses
.into_iter()
.map(serde_json::to_value)
.collect::<Result<_, _>>()?;
assert_eq!(actual, expected.map(serde_json::Value::from));
Ok(())
}
}
@@ -1,24 +1,22 @@
use super::NoticeStatus;
use clash_verge_logging::{Type, logging};
use once_cell::sync::Lazy;
use parking_lot::Mutex;
use serde_json::json;
use smartstring::alias::String;
use std::{
collections::HashMap,
future::Future,
sync::atomic::{AtomicU64, Ordering},
};
use std::sync::Arc;
use std::sync::LazyLock;
use std::{collections::HashMap, future::Future};
use tauri::{AppHandle, Emitter as _, Manager as _, WebviewWindow};
#[derive(Debug)]
#[derive(Debug, Clone)]
pub enum FrontendEvent<'a> {
RefreshClash,
RefreshVerge,
RefreshProfiles,
RefreshProxyConfig,
NoticeMessage {
status: &'a str,
message: String,
status: NoticeStatus,
message: Arc<str>,
},
ProfileChanged {
current_profile_id: &'a String,
@@ -89,16 +87,23 @@ pub struct PendingFailure {
/// Non-destructive pending state, indexed by stable code.
#[derive(Debug, Default)]
struct FailureTable {
entries: Mutex<HashMap<String, PendingFailure>>,
sequence: AtomicU64,
entries: Mutex<FailureEntries>,
}
#[derive(Debug, Default)]
struct FailureEntries {
map: HashMap<String, PendingFailure>,
sequence: u64,
}
impl FailureTable {
fn record(&self, operation: FailedOperation, code: &str, detail: String) {
// Sequence assignment and replacement must share one ordering lock.
let mut entries = self.entries.lock();
entries.sequence = entries.sequence.wrapping_add(1);
// Preserve an unanswered request over a later restore.
let operation = entries
.map
.get(code)
.filter(|existing| existing.operation.outranks(operation))
.map_or(operation, |existing| existing.operation);
@@ -106,13 +111,13 @@ impl FailureTable {
code: code.into(),
detail,
operation,
sequence: self.sequence.fetch_add(1, Ordering::AcqRel).wrapping_add(1),
sequence: entries.sequence,
};
entries.insert(code.into(), failure);
entries.map.insert(code.into(), failure);
}
fn snapshot(&self) -> Vec<PendingFailure> {
let mut failures: Vec<PendingFailure> = self.entries.lock().values().cloned().collect();
let mut failures: Vec<PendingFailure> = self.entries.lock().map.values().cloned().collect();
failures.sort_by_key(|failure| failure.sequence);
failures
}
@@ -120,17 +125,21 @@ impl FailureTable {
/// Return whether a guard failure was retired.
fn retire_guard(&self) -> bool {
let mut entries = self.entries.lock();
let before = entries.len();
entries.retain(|_, failure| failure.operation != FailedOperation::SystemProxyGuard);
before != entries.len()
let before = entries.map.len();
entries
.map
.retain(|_, failure| failure.operation != FailedOperation::SystemProxyGuard);
before != entries.map.len()
}
/// Return whether any proxy failure was retired.
fn retire_system_proxy(&self, asked: FailedOperation) -> bool {
let mut entries = self.entries.lock();
let before = entries.len();
entries.retain(|_, failure| !failure.operation.retired_by_success_of(asked));
before != entries.len()
let before = entries.map.len();
entries
.map
.retain(|_, failure| !failure.operation.retired_by_success_of(asked));
before != entries.map.len()
}
}
@@ -229,7 +238,7 @@ pub fn what_was_asked() -> FailedOperation {
.unwrap_or(FailedOperation::SystemProxyRestore)
}
static PENDING_FAILURES: Lazy<FailureTable> = Lazy::new(FailureTable::default);
static PENDING_FAILURES: LazyLock<FailureTable> = LazyLock::new(FailureTable::default);
pub fn record_failure(operation: FailedOperation, code: &str, detail: impl Into<String>) {
PENDING_FAILURES.record(operation, code, detail.into());
@@ -237,7 +246,7 @@ pub fn record_failure(operation: FailedOperation, code: &str, detail: impl Into<
}
pub fn has_pending_failure(code: &str) -> bool {
PENDING_FAILURES.entries.lock().contains_key(code)
PENDING_FAILURES.entries.lock().map.contains_key(code)
}
/// Return unresolved failures oldest first without clearing them.
@@ -283,9 +292,10 @@ impl NotificationSystem {
FrontendEvent::RefreshVerge => ("verge://refresh-verge-config", Ok(json!("yes"))),
FrontendEvent::RefreshProfiles => ("verge://refresh-profiles", Ok(json!("yes"))),
FrontendEvent::RefreshProxyConfig => ("verge://refresh-proxy-config", Ok(serde_json::Value::Null)),
FrontendEvent::NoticeMessage { status, message } => {
("verge://notice-message", serde_json::to_value((status, message)))
}
FrontendEvent::NoticeMessage { status, message } => (
"verge://notice-message",
serde_json::to_value((status, message.as_ref())),
),
FrontendEvent::ProfileChanged { current_profile_id } => ("profile-changed", Ok(json!(current_profile_id))),
FrontendEvent::TimerUpdated { profile_index } => ("verge://timer-updated", Ok(json!(profile_index))),
FrontendEvent::ProfileUpdateStarted { uid } => ("profile-update-started", Ok(json!({ "uid": uid }))),
@@ -313,3 +323,106 @@ impl NotificationSystem {
}
}
}
#[cfg(test)]
mod wire_tests {
use super::*;
#[test]
fn frontend_event_wire_contract() -> Result<(), serde_json::Error> {
let uid = String::from("profile");
for (event, name, payload) in super::sample_frontend_events(&uid) {
let (actual_name, actual_payload) = NotificationSystem::serialize_event(event);
assert_eq!(actual_name, name);
assert_eq!(actual_payload?, payload);
}
Ok(())
}
}
/// One sample per `FrontendEvent` variant, paired with its wire name and payload.
/// Shared by the wire golden test and the contract export so the two cannot drift.
fn sample_frontend_events(uid: &String) -> Vec<(FrontendEvent<'_>, &'static str, serde_json::Value)> {
vec![
(
FrontendEvent::RefreshClash,
"verge://refresh-clash-config",
json!("yes"),
),
(
FrontendEvent::RefreshVerge,
"verge://refresh-verge-config",
json!("yes"),
),
(FrontendEvent::RefreshProfiles, "verge://refresh-profiles", json!("yes")),
(
FrontendEvent::RefreshProxyConfig,
"verge://refresh-proxy-config",
json!(null),
),
(
FrontendEvent::NoticeMessage {
status: NoticeStatus::Info,
message: Arc::from("ok"),
},
"verge://notice-message",
json!(["info", "ok"]),
),
(
FrontendEvent::TimerUpdated { profile_index: uid },
"verge://timer-updated",
json!("profile"),
),
(
FrontendEvent::RunStateChanged {
state: json!({"running": true}),
},
"verge://run-state-changed",
json!({"running": true}),
),
(
FrontendEvent::PendingFailuresChanged,
"verge://pending-failures-changed",
json!(null),
),
(
FrontendEvent::ProfileChanged {
current_profile_id: uid,
},
"profile-changed",
json!("profile"),
),
(
FrontendEvent::ProfileUpdateStarted { uid },
"profile-update-started",
json!({"uid": "profile"}),
),
(
FrontendEvent::ProfileUpdateCompleted { uid },
"profile-update-completed",
json!({"uid": "profile"}),
),
]
}
/// Machine-readable form of the frontend wire contract: every event name with a
/// serialized sample payload, plus every notice status string. The sample
/// payload's JSON shape (string / null / array / object) is what the frontend
/// generator maps to TypeScript types. `ThemeChanged` is a Tauri built-in
/// linux-only window event, not part of this contract.
pub fn frontend_wire_contract() -> serde_json::Value {
let uid = String::from("sample");
let events: Vec<_> = sample_frontend_events(&uid)
.into_iter()
.map(|(event, _, _)| {
let (name, payload) = NotificationSystem::serialize_event(event);
json!({ "name": name, "sample": payload.unwrap_or(serde_json::Value::Null) })
})
.collect();
let statuses: Vec<_> = NoticeStatus::ALL
.iter()
// A unit variant with a string rename cannot fail to serialize.
.filter_map(|status| serde_json::to_value(status).ok())
.collect();
json!({ "version": 1, "events": events, "noticeStatuses": statuses })
}
+25 -16
View File
@@ -522,25 +522,34 @@ pub async fn clear() -> Result<()> {
/// A failed system call is usually a transient RPC hiccup, so give it a few tries.
async fn clear_with_retry() -> Result<()> {
for attempt in 1..CLEAR_ATTEMPTS {
match clear_inner().await {
Err(error)
use crate::utils::retry::{RetryError, RetryPolicy, retry};
retry(
RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add((CLEAR_ATTEMPTS - 1) as usize),
CLEAR_RETRY_DELAY,
),
|attempt| async move {
clear_inner().await.map_err(|error| {
if matches!(
SysproxyFailure::from_chain(&error),
Some(SysproxyFailure::SystemCallFailed)
) =>
{
logging!(
warn,
Type::Core,
"clearing the system proxy failed (attempt {attempt}/{CLEAR_ATTEMPTS}); retrying: {error:#}"
);
tokio::time::sleep(CLEAR_RETRY_DELAY).await;
}
other => return other,
}
}
clear_inner().await
) {
if attempt + 1 < CLEAR_ATTEMPTS as usize {
logging!(
warn,
Type::Core,
"clearing the system proxy failed (attempt {}/{CLEAR_ATTEMPTS}); retrying: {error:#}",
attempt + 1
);
}
RetryError::Retry(error)
} else {
RetryError::Stop(error)
}
})
},
)
.await
}
#[tracing::instrument(skip_all, level = "info", fields(route = tracing::field::Empty))]
+15 -14
View File
@@ -19,8 +19,8 @@ use std::{
use anyhow::{Context as _, Result, bail};
use arc_swap::ArcSwap;
use clash_verge_logging::{Type, logging};
use once_cell::sync::Lazy;
use parking_lot::Mutex;
use std::sync::LazyLock;
use tokio::sync::Notify;
#[cfg(test)]
@@ -35,7 +35,7 @@ use health::StoredService;
use probe::{CurrentServiceProbe, classify_service_health, probe_outcome};
/// The process-wide Run State, observing the real machine.
pub static RUN_STATE: Lazy<RunStateStore<RealEnv>> = Lazy::new(|| RunStateStore::new(RealEnv));
pub static RUN_STATE: LazyLock<RunStateStore<RealEnv>> = LazyLock::new(|| RunStateStore::new(RealEnv));
/// Distinguishes silence from a reply that updated Service health with a rejection.
#[derive(Debug)]
@@ -130,20 +130,21 @@ impl<E: RunStateEnv> RunStateStore<E> {
/// Retries transport failures but stops at the first readable reply, including a rejection.
pub async fn await_ready(&self, attempts: usize, interval: Duration) -> Result<RunState, ReadyWaitError> {
let mut last_error = None;
for attempt in 0..attempts {
use crate::utils::retry::{RetryError, RetryPolicy, retry};
let attempts = std::num::NonZeroUsize::new(attempts).ok_or_else(|| {
ReadyWaitError::Unreachable(anyhow::anyhow!(
"service readiness wait was configured with no attempts"
))
})?;
retry(RetryPolicy::fixed(attempts, interval), |_| async {
match self.env.probe_service_version().await {
Ok(reply) => return self.record_reply(&reply).map_err(ReadyWaitError::Rejected),
Err(error) => last_error = Some(error),
Ok(reply) => self
.record_reply(&reply)
.map_err(|error| RetryError::Stop(ReadyWaitError::Rejected(error))),
Err(error) => Err(RetryError::Retry(ReadyWaitError::Unreachable(error))),
}
if attempt + 1 < attempts {
tokio::time::sleep(interval).await;
}
}
Err(ReadyWaitError::Unreachable(last_error.unwrap_or_else(|| {
anyhow::anyhow!("service readiness wait was configured with no attempts")
})))
})
.await
}
fn record_reply(&self, reply: &ServiceVersionReply) -> Result<RunState> {
+110 -85
View File
@@ -1,3 +1,4 @@
use crate::core::notify::NoticeStatus;
use crate::utils::dirs;
use crate::{
config::{Config, runtime::IRuntime},
@@ -25,8 +26,8 @@ use clash_verge_service_ipc::{
RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot,
StageRuntimeOutcome, StartClashRequest, WriterConfig,
};
use once_cell::sync::Lazy;
use parking_lot::Mutex;
use std::sync::LazyLock;
use std::{
collections::HashMap,
env::current_exe,
@@ -38,7 +39,7 @@ use std::{
};
static OWNER_MONITOR_GENERATION: AtomicU64 = AtomicU64::new(0);
static ACTIVE_SERVICE_SESSION: Lazy<Mutex<Option<ActiveServiceSession>>> = Lazy::new(|| Mutex::new(None));
static ACTIVE_SERVICE_SESSION: LazyLock<Mutex<Option<ActiveServiceSession>>> = LazyLock::new(|| Mutex::new(None));
static PENDING_SERVICE_FALLBACK_NOTICE: AtomicBool = AtomicBool::new(false);
static PENDING_SERVICE_REPAIR_NOTICE: AtomicBool = AtomicBool::new(false);
static PENDING_SERVICE_OWNER_NOTICE: Mutex<Option<String>> = Mutex::new(None);
@@ -46,7 +47,7 @@ static PENDING_SERVICE_OWNER_NOTICE: Mutex<Option<String>> = Mutex::new(None);
#[cfg(target_os = "windows")]
pub(crate) fn notify_service_fallback() {
PENDING_SERVICE_FALLBACK_NOTICE.store(true, Ordering::Relaxed);
Handle::notice_message("service_core::sidecar_fallback", "");
Handle::notice(NoticeStatus::ServiceCoreSidecarFallback, "");
}
pub(crate) fn take_service_fallback_notice() -> bool {
@@ -314,35 +315,40 @@ 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)> {
for _ in 0..32 {
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) => return Ok((temporary_path, file)),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(error) => {
return Err(error).with_context(|| {
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()
)
});
}))),
}
}
}
bail!(
"failed to create a unique temporary development Service core in {}",
directory.display()
},
)
}
@@ -886,11 +892,11 @@ pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()
#[cfg(target_os = "windows")]
if response.code == ServiceErrorCode::InvalidInstallLocation as u16 {
PENDING_SERVICE_REPAIR_NOTICE.store(true, Ordering::Relaxed);
Handle::notice_message("service_core::repair_required", "");
Handle::notice(NoticeStatus::ServiceCoreRepairRequired, "");
}
if response.code == ServiceErrorCode::AppDataRootNotOwned as u16 {
*PENDING_SERVICE_OWNER_NOTICE.lock() = app_data_owner_command(&credentials);
Handle::notice_message("service_core::app_data_not_owned", "");
Handle::notice(NoticeStatus::ServiceCoreAppDataNotOwned, "");
}
start_owner_monitor();
return Err(record_service_start_refusal(
@@ -1002,7 +1008,6 @@ fn decode_hex(encoded: &str) -> Result<Vec<u8>> {
}
static PROVIDER_SYNC_QUEUED: AtomicBool = AtomicBool::new(false);
static PROVIDER_SYNC_SERIAL: Lazy<tokio::sync::Mutex<()>> = Lazy::new(|| tokio::sync::Mutex::new(()));
static SYNC_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
const RUNTIME_PROVIDER_SYNC_ATTEMPTS: u32 = 4;
const CONTENT_COMPARE_CHUNK: usize = 64 * 1024;
@@ -1013,38 +1018,44 @@ pub(crate) fn request_runtime_provider_sync(delay: Duration) {
}
AsyncHandler::spawn(move || async move {
tokio::time::sleep(delay).await;
for attempt in 1..=RUNTIME_PROVIDER_SYNC_ATTEMPTS {
let outcome = {
let _serial = PROVIDER_SYNC_SERIAL.lock().await;
use crate::utils::retry::{RetryError, RetryPolicy, retry};
let _ = retry(
RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add((RUNTIME_PROVIDER_SYNC_ATTEMPTS - 1) as usize),
constants::timing::RUNTIME_PROVIDER_SYNC_RETRY_DELAY,
),
|index| async move {
let attempt = index as u32 + 1;
if attempt == 1 {
PROVIDER_SYNC_QUEUED.store(false, Ordering::Release);
}
sync_runtime_providers_by_service().await
};
match outcome {
Ok(ProviderSync { pending: 0, .. }) => return,
Ok(ProviderSync { pending, .. }) if attempt < RUNTIME_PROVIDER_SYNC_ATTEMPTS => {
logging!(
info,
Type::Service,
"{pending} provider caches are not ready yet; retrying"
);
let outcome = sync_runtime_providers_by_service().await;
match outcome {
Ok(ProviderSync { pending: 0, .. }) => Ok(()),
Ok(ProviderSync { pending, .. }) if attempt < RUNTIME_PROVIDER_SYNC_ATTEMPTS => {
logging!(
info,
Type::Service,
"{pending} provider caches are not ready yet; retrying"
);
Err(RetryError::Retry(()))
}
Ok(ProviderSync { pending, .. }) => {
logging!(warn, Type::Service, "{pending} provider caches were not synced");
Ok(())
}
Err(error) => {
logging!(
warn,
Type::Service,
"failed to sync provider caches from the service: {error:#}"
);
Ok(())
}
}
Ok(ProviderSync { pending, .. }) => {
logging!(warn, Type::Service, "{pending} provider caches were not synced");
return;
}
Err(error) => {
logging!(
warn,
Type::Service,
"failed to sync provider caches from the service: {error:#}"
);
return;
}
}
tokio::time::sleep(constants::timing::RUNTIME_PROVIDER_SYNC_RETRY_DELAY).await;
}
},
)
.await;
});
}
@@ -1352,21 +1363,29 @@ async fn create_sync_temp(target: &Path) -> Result<(PathBuf, tokio::fs::File)> {
.file_name()
.map(|name| name.to_string_lossy())
.unwrap_or_default();
for _ in 0..8 {
let sequence = SYNC_TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed);
let temp = target.with_file_name(format!(".{name}.sync-{}-{sequence}.tmp", std::process::id()));
match tokio::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temp)
.await
{
Ok(file) => return Ok((temp, file)),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(error) => return Err(error).with_context(|| format!("failed to create {}", temp.display())),
}
}
bail!("no free temporary name beside {}", target.display())
use crate::utils::retry::{RetryError, RetryPolicy, retry};
retry(
RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(7), std::time::Duration::ZERO),
|_| async {
let sequence = SYNC_TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed);
let temp = target.with_file_name(format!(".{name}.sync-{}-{sequence}.tmp", std::process::id()));
match tokio::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temp)
.await
{
Ok(file) => Ok((temp, file)),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Err(RetryError::Retry(
anyhow::anyhow!("no free temporary name beside {}", target.display()),
)),
Err(error) => Err(RetryError::Stop(
anyhow::anyhow!(error).context(format!("failed to create {}", temp.display())),
)),
}
},
)
.await
}
async fn same_contents(temp: &Path, target: &Path) -> bool {
@@ -1610,7 +1629,7 @@ fn report_service_core_stopped(status: &ServiceStatusSnapshot) {
);
logging!(error, Type::Service, "service core stopped: {detail}");
CoreManager::global().record_startup_error(CoreFailure::ServiceCoreStopped(detail));
Handle::notice_message("core_start::error", "");
Handle::notice(NoticeStatus::CoreStartError, "");
}
/// Samples ownership, treating every unusable reply as unreadable.
@@ -1733,22 +1752,28 @@ async fn recover_after_owner_loss_while_locked(reason: OwnerRecoveryReason) {
}
async fn clear_proxy_after_owner_loss() {
let mut last_error = None;
for attempt in 1..=3 {
match proxy_control::clear().await {
Ok(()) => return,
Err(error) => {
use crate::utils::retry::{RetryError, RetryPolicy, retry};
let result = retry(
RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add(2),
Duration::from_millis(100),
),
|index| async move {
let attempt = index + 1;
proxy_control::clear().await.map_err(|error| {
logging!(
warn,
Type::Service,
"proxy clear attempt {attempt}/3 after owner loss failed: {error:#}"
);
last_error = Some(error);
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
}
if let Some(error) = last_error {
RetryError::Retry(error)
})
},
)
.await;
if let Err(error) = result {
// The existing recovery path also waits after its final failed clear.
tokio::time::sleep(Duration::from_millis(100)).await;
logging!(
error,
Type::Service,
+2 -2
View File
@@ -1,14 +1,14 @@
use crate::config::{IProfilePreview, IVerge};
use crate::core::lightweight;
use crate::core::tray::menu_def::TrayAction;
use crate::module::lightweight;
use crate::process::AsyncHandler;
use crate::singleton;
use crate::utils::window_manager::WindowManager;
use crate::{
Type, cmd,
config::Config,
core::lightweight::is_in_lightweight_mode,
feat, logging,
module::lightweight::is_in_lightweight_mode,
utils::{dirs::find_target_icons, help},
};
use clash_verge_limiter::{Limiter, SystemClock, SystemLimiter};
+12 -19
View File
@@ -2,19 +2,15 @@ use crate::{config::Config, singleton, utils::dirs};
use anyhow::{Context as _, Result};
use chrono::Utc;
use clash_verge_logging::{Type, logging};
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::{
path::PathBuf,
sync::atomic::{AtomicBool, Ordering},
};
use tauri_plugin_updater::{Update, UpdaterExt as _};
use tauri_plugin_updater::UpdaterExt as _;
pub struct SilentUpdater {
update_ready: AtomicBool,
pending_bytes: RwLock<Option<Vec<u8>>>,
pending_update: RwLock<Option<Update>>,
pending_version: RwLock<Option<String>>,
}
singleton!(SilentUpdater, SILENT_UPDATER);
@@ -23,9 +19,6 @@ impl SilentUpdater {
const fn new() -> Self {
Self {
update_ready: AtomicBool::new(false),
pending_bytes: RwLock::new(None),
pending_update: RwLock::new(None),
pending_version: RwLock::new(None),
}
}
@@ -388,12 +381,14 @@ impl SilentUpdater {
// The new webview may not accept evaluation immediately.
std::thread::spawn(move || {
for i in 0..10 {
std::thread::sleep(std::time::Duration::from_millis(100 * (i + 1)));
if window.eval(&js).is_ok() {
return;
}
}
use crate::utils::retry::{RetryError, RetryPolicy, retry_sync};
let _ = retry_sync(
RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(9), std::time::Duration::ZERO),
|index| {
std::thread::sleep(std::time::Duration::from_millis(100 * (index as u64 + 1)));
window.eval(&js).map_err(RetryError::Retry)
},
);
});
logging!(info, Type::System, "Update splash window shown");
@@ -447,8 +442,8 @@ impl SilentUpdater {
Type::System,
"Silent updater: breaking change detected in v{version}, notifying frontend"
);
super::handle::Handle::notice_message(
"info",
super::handle::Handle::notice(
super::notify::NoticeStatus::Info,
format!("New version v{version} contains breaking changes. Please update manually."),
);
return Ok(());
@@ -474,9 +469,6 @@ impl SilentUpdater {
logging!(warn, Type::System, "Silent updater: failed to write cache: {e:#}");
}
*self.pending_bytes.write() = Some(bytes);
*self.pending_update.write() = Some(update);
*self.pending_version.write() = Some(version.clone());
self.update_ready.store(true, Ordering::Release);
logging!(
@@ -488,6 +480,7 @@ impl SilentUpdater {
}
pub async fn start_background_check(&self, app_handle: tauri::AppHandle) {
// Permanent watcher: daily update cycles for the lifetime of the app.
logging!(info, Type::System, "Silent updater: background task started");
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
+2 -1
View File
@@ -1,3 +1,4 @@
use crate::core::notify::NoticeStatus;
mod chain;
pub mod field;
mod merge;
@@ -436,7 +437,7 @@ fn notify_discarded_keys(keys: Vec<String>) {
drop(notice);
if should_notify {
Handle::notice_message("enhance::discarded_keys", "");
Handle::notice(NoticeStatus::EnhanceDiscardedKeys, "");
}
}
+9 -8
View File
@@ -1,3 +1,5 @@
use crate::core::notify::NoticeStatus;
use crate::core::notify::{Refresh, announce};
use crate::{
config::{Config, MixedPort},
core::{CoreManager, handle, tray},
@@ -7,13 +9,13 @@ use crate::{
};
use bytes::BytesMut;
use clash_verge_logging::{Type, logging};
use once_cell::sync::Lazy;
use serde_yaml_ng::{Mapping, Value};
use smartstring::alias::String;
use std::sync::Arc;
use std::sync::LazyLock;
#[allow(clippy::expect_used)]
static TLS_CONFIG: Lazy<Arc<rustls::ClientConfig>> = Lazy::new(|| {
static TLS_CONFIG: LazyLock<Arc<rustls::ClientConfig>> = LazyLock::new(|| {
let root_store = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
let config = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
.with_safe_default_protocol_versions()
@@ -26,11 +28,10 @@ static TLS_CONFIG: Lazy<Arc<rustls::ClientConfig>> = Lazy::new(|| {
pub async fn restart_clash_core() {
match CoreManager::global().restart_core().await {
Ok(_) => {
handle::Handle::refresh_clash();
handle::Handle::notice_message("set_config::ok", "ok");
announce(Refresh::Clash);
}
Err(err) => {
handle::Handle::notice_message("set_config::error", format!("{err:#}"));
handle::Handle::notice(NoticeStatus::SetConfigError, format!("{err:#}"));
logging!(error, Type::Core, "restart core failed: {err:#}");
}
}
@@ -53,8 +54,8 @@ pub async fn restart_app() {
if !cleanup_result.core_stopped {
handle::Handle::global().clear_is_exiting();
handle::Handle::notice_message(
"app_restart::core_stop_failed",
handle::Handle::notice(
NoticeStatus::AppRestartCoreStopFailed,
cleanup_result.stop_error.unwrap_or_default(),
);
return;
@@ -95,7 +96,7 @@ pub async fn change_clash_mode(mode: String) -> Result<(), String> {
let clash_data = clash.data_arc();
if clash_data.save_config().await.is_ok() {
handle::Handle::refresh_clash();
announce(Refresh::Clash);
tray::Tray::global().update_menu_and_icon().await;
}
+19 -295
View File
@@ -1,279 +1,17 @@
use crate::{
config::{Config, IVerge},
core::{CoreManager, autostart, handle, hotkey, logger, proxy_control, tray},
module::{auto_backup::AutoBackupManager, lightweight},
};
use crate::config::{Config, IVerge};
use anyhow::Result;
use bitflags::bitflags;
use clash_verge_draft::{DraftTransaction, SharedDraft};
use clash_verge_logging::{Type, logging, logging_error};
use clash_verge_draft::SharedDraft;
use serde_yaml_ng::Mapping;
use tokio::sync::MutexGuard;
/// Patch Clash configuration
pub async fn patch_clash(patch: &Mapping) -> Result<()> {
Config::clash().await.edit_draft(|d| d.patch_config(patch));
let res = {
// 激活订阅
if patch.get("secret").is_some() || patch.get("external-controller").is_some() {
Config::generate().await?;
CoreManager::global().restart_core().await?;
} else if patch.get("allow-lan").is_some() {
CoreManager::global().update_config_checked().await?;
} else {
if patch.get("mode").is_some() {
tray::Tray::global().update_menu_and_icon().await;
}
CoreManager::global().update_config_checked().await?;
}
handle::Handle::refresh_clash();
<Result<()>>::Ok(())
};
match res {
Ok(()) => {
Config::clash().await.apply();
// 分离数据获取和异步调用
let clash_data = Config::clash().await.data_arc();
clash_data.save_config().await?;
Ok(())
}
Err(err) => {
Config::clash().await.discard();
Err(err)
}
}
}
// Define update flags as bitflags for better performance
bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct UpdateFlags: u16 {
const RESTART_CORE = 1 << 0;
const CLASH_CONFIG = 1 << 1;
const VERGE_CONFIG = 1 << 2;
const LAUNCH = 1 << 3;
const SYS_PROXY = 1 << 4;
const SYSTRAY_ICON = 1 << 5;
const HOTKEY = 1 << 6;
const SYSTRAY_MENU = 1 << 7;
const SYSTRAY_TOOLTIP = 1 << 8;
const SYSTRAY_CLICK_BEHAVIOR = 1 << 9;
const LIGHT_WEIGHT = 1 << 10;
const LANGUAGE = 1 << 11;
const LOG_LEVEL = 1 << 12;
const LOG_FILE = 1 << 13;
const GROUP_SYS_TRAY = Self::SYSTRAY_MENU.bits()
| Self::SYSTRAY_TOOLTIP.bits()
| Self::SYSTRAY_ICON.bits();
}
}
fn determine_update_flags(patch: &IVerge) -> UpdateFlags {
let tun_mode = patch.enable_tun_mode;
let auto_launch = patch.enable_auto_launch;
let system_proxy = patch.enable_system_proxy;
let pac = patch.proxy_auto_config;
let pac_content = &patch.pac_file_content;
let proxy_bypass = &patch.system_proxy_bypass;
let language = &patch.language;
let mixed_port = patch.verge_mixed_port;
#[cfg(target_os = "macos")]
let tray_icon = &patch.tray_icon;
#[cfg(not(target_os = "macos"))]
let tray_icon: Option<String> = None;
let common_tray_icon = patch.common_tray_icon;
let sysproxy_tray_icon = patch.sysproxy_tray_icon;
let tun_tray_icon = patch.tun_tray_icon;
#[cfg(not(target_os = "windows"))]
let redir_enabled = patch.verge_redir_enabled;
#[cfg(not(target_os = "windows"))]
let redir_port = patch.verge_redir_port;
#[cfg(target_os = "linux")]
let tproxy_enabled = patch.verge_tproxy_enabled;
#[cfg(target_os = "linux")]
let tproxy_port = patch.verge_tproxy_port;
let socks_enabled = patch.verge_socks_enabled;
let socks_port = patch.verge_socks_port;
let http_enabled = patch.verge_http_enabled;
let http_port = patch.verge_port;
#[cfg(target_os = "macos")]
let enable_tray_speed = patch.enable_tray_speed;
#[cfg(not(target_os = "macos"))]
let enable_tray_speed: Option<bool> = None;
// let enable_tray_icon = patch.enable_tray_icon;
let enable_global_hotkey = patch.enable_global_hotkey;
let tray_event = &patch.tray_event;
let home_cards = patch.home_cards.as_ref();
let enable_auto_light_weight = patch.enable_auto_light_weight_mode;
let enable_external_controller = patch.enable_external_controller;
let tray_proxy_groups_display_mode = &patch.tray_proxy_groups_display_mode;
let tray_inline_outbound_modes = patch.tray_inline_outbound_modes;
let enable_proxy_guard = patch.enable_proxy_guard;
let proxy_guard_duration = patch.proxy_guard_duration;
let log_level = &patch.app_log_level;
let log_max_size = patch.app_log_max_size;
let log_max_count = patch.app_log_max_count;
#[cfg(target_os = "windows")]
let restart_core_needed = socks_enabled.is_some()
|| http_enabled.is_some()
|| socks_port.is_some()
|| http_port.is_some()
|| mixed_port.is_some()
|| enable_external_controller.is_some();
#[cfg(not(target_os = "windows"))]
let mut restart_core_needed = socks_enabled.is_some()
|| http_enabled.is_some()
|| socks_port.is_some()
|| http_port.is_some()
|| mixed_port.is_some()
|| enable_external_controller.is_some();
#[cfg(not(target_os = "windows"))]
{
restart_core_needed |= redir_enabled.is_some() || redir_port.is_some();
}
#[cfg(target_os = "linux")]
{
restart_core_needed |= tproxy_enabled.is_some() || tproxy_port.is_some();
restart_core_needed |= tun_mode == Some(true);
}
let mut update_flags = UpdateFlags::empty();
if restart_core_needed {
update_flags.insert(UpdateFlags::RESTART_CORE);
}
if tun_mode.is_some() {
update_flags.insert(UpdateFlags::CLASH_CONFIG | UpdateFlags::GROUP_SYS_TRAY);
}
if enable_global_hotkey.is_some() || home_cards.is_some() {
update_flags.insert(UpdateFlags::VERGE_CONFIG);
}
if auto_launch.is_some() {
update_flags.insert(UpdateFlags::LAUNCH);
}
if system_proxy.is_some() {
update_flags.insert(UpdateFlags::SYS_PROXY | UpdateFlags::GROUP_SYS_TRAY);
}
if proxy_bypass.is_some()
|| pac_content.is_some()
|| pac.is_some()
|| enable_proxy_guard.is_some()
|| proxy_guard_duration.is_some()
{
update_flags.insert(UpdateFlags::SYS_PROXY);
}
if language.is_some() {
update_flags.insert(UpdateFlags::LANGUAGE | UpdateFlags::SYSTRAY_MENU | UpdateFlags::SYSTRAY_TOOLTIP);
}
if common_tray_icon.is_some()
|| sysproxy_tray_icon.is_some()
|| tun_tray_icon.is_some()
|| tray_icon.is_some()
|| enable_tray_speed.is_some()
{
update_flags.insert(UpdateFlags::SYSTRAY_ICON);
}
if patch.hotkeys.is_some() {
update_flags.insert(UpdateFlags::HOTKEY | UpdateFlags::SYSTRAY_MENU);
}
if tray_event.is_some() {
update_flags.insert(UpdateFlags::SYSTRAY_CLICK_BEHAVIOR);
}
if enable_auto_light_weight.is_some() {
update_flags.insert(UpdateFlags::LIGHT_WEIGHT);
}
if tray_proxy_groups_display_mode.is_some() {
update_flags.insert(UpdateFlags::SYSTRAY_MENU);
}
if log_level.is_some() {
update_flags.insert(UpdateFlags::LOG_LEVEL);
}
if log_max_size.is_some() || log_max_count.is_some() {
update_flags.insert(UpdateFlags::LOG_FILE);
}
if tray_inline_outbound_modes.is_some() {
update_flags.insert(UpdateFlags::SYSTRAY_MENU);
}
update_flags
}
#[allow(clippy::cognitive_complexity)]
async fn process_terminated_flags(update_flags: UpdateFlags, patch: &IVerge) -> Result<()> {
// Process updates based on flags
if update_flags.contains(UpdateFlags::RESTART_CORE) {
Config::generate().await?;
CoreManager::global().restart_core().await?;
}
if update_flags.contains(UpdateFlags::CLASH_CONFIG) {
CoreManager::global().update_config_checked().await?;
handle::Handle::refresh_clash();
}
if update_flags.contains(UpdateFlags::LAUNCH) {
autostart::update_launch().await?;
}
if update_flags.contains(UpdateFlags::LANGUAGE)
&& let Some(language) = &patch.language
{
clash_verge_i18n::set_locale(language.as_str());
}
if update_flags.contains(UpdateFlags::SYS_PROXY) {
let manager = CoreManager::global();
let _lifecycle = manager.lifecycle_lock.lock().await;
// Turning it off only writes OS state, so it must stay available while the Core is down.
if Config::verge()
.await
.latest_arc()
.enable_system_proxy
.unwrap_or_default()
{
manager.apply_proxy_after_start().await?;
} else {
proxy_control::apply().await?;
proxy_control::refresh_guard().await?;
}
}
if update_flags.contains(UpdateFlags::HOTKEY)
&& let Some(hotkeys) = &patch.hotkeys
{
hotkey::Hotkey::global().update(hotkeys.to_owned()).await?;
}
if update_flags.contains(UpdateFlags::SYSTRAY_MENU) {
tray::Tray::global().update_menu().await?;
}
if update_flags.contains(UpdateFlags::SYSTRAY_ICON) {
tray::Tray::global()
.update_icon(&Config::verge().await.latest_arc())
.await?;
#[cfg(target_os = "macos")]
if patch.enable_tray_speed.is_some() {
tray::Tray::global().update_speed_task(patch.enable_tray_speed.unwrap_or(false));
}
}
if update_flags.contains(UpdateFlags::SYSTRAY_TOOLTIP) {
tray::Tray::global().update_tooltip().await?;
}
if update_flags.contains(UpdateFlags::SYSTRAY_CLICK_BEHAVIOR) {
tray::Tray::global().update_click_behavior().await?;
}
if update_flags.contains(UpdateFlags::LIGHT_WEIGHT) {
if patch.enable_auto_light_weight_mode.unwrap_or(false) {
lightweight::enable_auto_light_weight_mode().await;
} else {
lightweight::disable_auto_light_weight_mode();
}
}
if update_flags.contains(UpdateFlags::LOG_LEVEL) {
logger::Logger::global().update_log_level(patch.get_log_level())?;
}
if update_flags.contains(UpdateFlags::LOG_FILE) {
let log_max_size = patch.app_log_max_size.unwrap_or(128);
let log_max_count = patch.app_log_max_count.unwrap_or(8);
logger::update_log_config(log_max_size, log_max_count).await?;
}
Ok(())
let config_write = Config::try_lock_config_write()?;
super::executor::apply(
&config_write,
super::executor::Patch::Clash(patch),
super::effects::clash_effects(patch),
)
.await
}
/// Apply a patch, then reconcile TUN when its setting changes.
@@ -289,7 +27,7 @@ pub async fn patch_verge(patch: &IVerge, not_save_file: bool) -> Result<()> {
/// Apply a patch without post-update reconciliation.
pub(super) async fn apply_verge_patch(patch: &IVerge, not_save_file: bool) -> Result<()> {
let config_write = Config::lock_config_write().await;
let config_write = Config::try_lock_config_write()?;
apply_verge_patch_locked(&config_write, patch, not_save_file).await
}
@@ -300,29 +38,15 @@ pub(super) async fn apply_verge_patch_locked(
patch: &IVerge,
not_save_file: bool,
) -> Result<()> {
let verge = Config::verge().await;
// Hold the claim across side effects so concurrent transactions cannot share this draft.
let transaction = DraftTransaction::begin(vec![&verge])?;
verge.edit_draft(|d| d.patch_config(patch));
let update_flags = determine_update_flags(patch);
logging!(debug, Type::Setup, "Determined update flags: {:?}", update_flags);
// A failed patch rolls back to what the user already had; it never invents a value for them.
process_terminated_flags(update_flags, patch).await?;
transaction.commit();
announce_verge_change();
logging_error!(Type::Backup, AutoBackupManager::global().refresh_settings().await);
if !not_save_file {
// 分离数据获取和异步调用
let verge_data = verge.data_arc();
verge_data.save_file().await?;
}
Ok(())
}
fn announce_verge_change() {
handle::Handle::refresh_verge();
super::executor::apply(
_config_write,
super::executor::Patch::Verge {
patch,
persist: !not_save_file,
},
super::effects::verge_effects(patch),
)
.await
}
pub async fn fetch_verge_config() -> Result<SharedDraft<IVerge>> {
+23 -16
View File
@@ -359,24 +359,31 @@ fn stage_core(target: &Path, package: &[u8], version: &str) -> Result<StagedCore
}
fn create_staging_file(directory: &Path, core_name: &OsStr) -> Result<(PathBuf, File)> {
for _ in 0..32 {
let generation = STAGING_GENERATION.fetch_add(1, Ordering::Relaxed);
let path = directory.join(format!(
".{}.{}.{generation}.tmp",
core_name.to_string_lossy(),
std::process::id()
));
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 = STAGING_GENERATION.fetch_add(1, Ordering::Relaxed);
let path = directory.join(format!(
".{}.{}.{generation}.tmp",
core_name.to_string_lossy(),
std::process::id()
));
match File::options().write(true).create_new(true).open(&path) {
Ok(file) => return Ok((path, file)),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(error) => {
return Err(error).with_context(|| format!("failed to create {}", path.display()));
match File::options().write(true).create_new(true).open(&path) {
Ok(file) => Ok((path, file)),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Err(RetryError::Retry(
anyhow::anyhow!("failed to create a unique staging file in {}", directory.display()),
)),
Err(error) => Err(RetryError::Stop(
anyhow::Error::from(error).context(format!("failed to create {}", path.display())),
)),
}
}
}
bail!("failed to create a unique staging file in {}", directory.display())
},
)
}
#[cfg(windows)]
+12 -3
View File
@@ -1,3 +1,4 @@
use crate::core::notify::{Refresh, announce};
use anyhow::{Result, ensure};
use clash_verge_draft::DraftTransaction;
use serde::Serialize;
@@ -10,7 +11,7 @@ use crate::{
profiles::PROFILE_WRITE_LOCK,
},
constants::files::DNS_CONFIG,
core::{CoreManager, handle::Handle},
core::CoreManager,
utils::dirs,
};
@@ -25,6 +26,14 @@ pub async fn set_dns_override(
profile_uid: String,
enabled: bool,
confirmation: Option<String>,
) -> Result<DnsOverrideOutcome> {
crate::core::notify::after_commit(Box::pin(set_dns_override_inner(profile_uid, enabled, confirmation))).await
}
async fn set_dns_override_inner(
profile_uid: String,
enabled: bool,
confirmation: Option<String>,
) -> Result<DnsOverrideOutcome> {
let _profile_write = PROFILE_WRITE_LOCK.lock().await;
let _config_write = Config::lock_config_write().await;
@@ -74,8 +83,8 @@ pub async fn set_dns_override(
}
transaction.commit();
Handle::refresh_verge();
Handle::refresh_clash();
verge.data_arc().save_file().await?;
announce(Refresh::Verge);
announce(Refresh::Clash);
Ok(outcome)
}
+296
View File
@@ -0,0 +1,296 @@
use crate::config::IVerge;
use std::collections::BTreeSet;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(super) enum Effect {
RestartCore,
ClashConfig,
VergeConfig,
Autostart,
SystemProxy,
TrayIcon,
Hotkey,
TrayMenu,
TrayTooltip,
TrayClick,
Lightweight,
Language,
LogLevel,
LogFile,
}
pub(super) type Effects = BTreeSet<Effect>;
macro_rules! select_field {
($effects:ident, $field:ident, NoEffect) => { let _ = $field; };
($effects:ident, $field:ident, [$($effect:ident),*]) => {
if $field.is_some() { $effects.extend([$(Effect::$effect),*]); }
};
($effects:ident, $field:ident, Tun) => {
select_field!($effects, $field, [ClashConfig, TrayMenu, TrayTooltip, TrayIcon]);
#[cfg(target_os = "linux")]
if *$field == Some(true) { $effects.insert(Effect::RestartCore); }
};
}
macro_rules! verge_registry {
($( $(#[$cfg:meta])* $field:ident => $rule:tt; )*) => {
pub(super) fn verge_effects(patch: &IVerge) -> Effects {
// No rest pattern: even fields omitted by serde must be classified at compile time.
let IVerge { $( $(#[$cfg])* $field, )* } = patch;
let mut effects = Effects::new();
$( $(#[$cfg])* { select_field!(effects, $field, $rule); } )*
effects
}
#[cfg(test)]
const VERGE_FIELDS: &[&str] = &[ $( $(#[$cfg])* stringify!($field), )* ];
};
}
verge_registry! {
app_log_level => [LogLevel];
app_log_max_size => [LogFile];
app_log_max_count => [LogFile];
language => [Language, TrayMenu, TrayTooltip];
theme_mode => NoEffect;
tray_event => [TrayClick];
env_type => NoEffect;
start_page => NoEffect;
startup_script => NoEffect;
traffic_graph => NoEffect;
enable_memory_usage => NoEffect;
enable_group_icon => NoEffect;
pause_render_traffic_stats_on_blur => NoEffect;
common_tray_icon => [TrayIcon];
#[cfg(target_os = "macos")]
tray_icon => [TrayIcon];
menu_icon => NoEffect;
menu_order => NoEffect;
proxy_group_tools_position => NoEffect;
notice_position => NoEffect;
collapse_navbar => NoEffect;
sysproxy_tray_icon => [TrayIcon];
tun_tray_icon => [TrayIcon];
enable_tun_mode => Tun;
enable_auto_launch => [Autostart];
enable_silent_start => NoEffect;
enable_system_proxy => [SystemProxy, TrayMenu, TrayTooltip, TrayIcon];
enable_proxy_guard => [SystemProxy];
enable_bypass_check => NoEffect;
enable_dns_settings => NoEffect;
profile_dns_settings => NoEffect;
use_default_bypass => NoEffect;
system_proxy_bypass => [SystemProxy];
proxy_guard_duration => [SystemProxy];
proxy_auto_config => [SystemProxy];
pac_file_content => [SystemProxy];
proxy_host => NoEffect;
theme_setting => NoEffect;
web_ui_list => NoEffect;
clash_core => NoEffect;
hotkeys => [Hotkey, TrayMenu];
enable_global_hotkey => [VergeConfig];
home_cards => [VergeConfig];
auto_close_connection => NoEffect;
auto_check_update => NoEffect;
default_latency_test => NoEffect;
default_latency_timeout => NoEffect;
enable_auto_delay_detection => NoEffect;
auto_delay_detection_interval_minutes => NoEffect;
enable_builtin_enhanced => NoEffect;
proxy_layout_column => NoEffect;
test_list => NoEffect;
auto_log_clean => NoEffect;
enable_auto_backup_schedule => NoEffect;
auto_backup_interval_hours => NoEffect;
auto_backup_on_change => NoEffect;
#[cfg(not(target_os = "windows"))]
verge_redir_port => [RestartCore];
#[cfg(not(target_os = "windows"))]
verge_redir_enabled => [RestartCore];
#[cfg(target_os = "linux")]
verge_tproxy_port => [RestartCore];
#[cfg(target_os = "linux")]
verge_tproxy_enabled => [RestartCore];
verge_mixed_port => [RestartCore];
verge_socks_port => [RestartCore];
verge_socks_enabled => [RestartCore];
verge_port => [RestartCore];
verge_http_enabled => [RestartCore];
webdav_url => NoEffect;
webdav_username => NoEffect;
webdav_password => NoEffect;
#[cfg(target_os = "macos")]
enable_tray_speed => [TrayIcon];
tray_proxy_groups_display_mode => [TrayMenu];
tray_inline_outbound_modes => [TrayMenu];
enable_auto_light_weight_mode => [Lightweight];
auto_light_weight_minutes => NoEffect;
enable_hover_jump_navigator => NoEffect;
hover_jump_navigator_delay => NoEffect;
enable_external_controller => [RestartCore];
}
pub(super) fn clash_effects(patch: &serde_yaml_ng::Mapping) -> Effects {
use clash_verge_logging::{Type, logging};
let mut effects = Effects::new();
for key in patch.keys() {
effects.extend(match key.as_str() {
Some("secret" | "external-controller") => &[Effect::RestartCore][..],
Some("allow-lan") => &[Effect::ClashConfig][..],
Some("mode") => &[Effect::ClashConfig, Effect::TrayMenu, Effect::TrayIcon][..],
_ => {
logging!(
warn,
Type::Config,
"Unregistered Clash configuration key {key:?}; reloading configuration"
);
&[Effect::ClashConfig][..]
}
});
}
// These branches were exclusive: restart supersedes reload, and allow-lan precedes mode.
if effects.contains(&Effect::RestartCore) {
effects.retain(|effect| *effect == Effect::RestartCore);
} else if patch.contains_key("allow-lan") {
effects.retain(|effect| *effect == Effect::ClashConfig);
}
if patch.is_empty() {
effects.insert(Effect::ClashConfig);
}
effects
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_serialized_verge_field_is_registered() -> Result<(), serde_json::Error> {
let fields: std::collections::BTreeMap<String, serde_json::Value> =
serde_json::from_value(serde_json::to_value(IVerge::default())?)?;
for field in fields.keys() {
assert!(VERGE_FIELDS.contains(&field.as_str()), "unregistered field: {field}");
}
let unique: BTreeSet<_> = VERGE_FIELDS.iter().collect();
assert_eq!(unique.len(), VERGE_FIELDS.len());
Ok(())
}
fn verge_patch(mutate: impl FnOnce(&mut IVerge)) -> IVerge {
let mut patch = IVerge::default();
mutate(&mut patch);
patch
}
#[test]
fn representative_verge_patches_map_to_frozen_effects() {
assert_eq!(verge_effects(&IVerge::default()), Effects::new());
let cases: [(IVerge, &[Effect]); 7] = [
(
verge_patch(|p| p.verge_mixed_port = Some(27899)),
&[Effect::RestartCore],
),
(
verge_patch(|p| p.language = Some("zh".into())),
&[Effect::TrayMenu, Effect::TrayTooltip, Effect::Language],
),
(
verge_patch(|p| p.hotkeys = Some(vec!["CmdOrCtrl+K".into()])),
&[Effect::Hotkey, Effect::TrayMenu],
),
(
verge_patch(|p| p.enable_system_proxy = Some(true)),
&[
Effect::SystemProxy,
Effect::TrayIcon,
Effect::TrayMenu,
Effect::TrayTooltip,
],
),
(
verge_patch(|p| p.system_proxy_bypass = Some("localhost".into())),
&[Effect::SystemProxy],
),
(
verge_patch(|p| p.tray_event = Some("show_main_window".into())),
&[Effect::TrayClick],
),
(verge_patch(|p| p.theme_mode = Some("dark".into())), &[]),
];
for (patch, expected) in cases {
assert_eq!(
verge_effects(&patch),
expected.iter().copied().collect::<Effects>(),
"patch mapping drifted for {expected:?}"
);
}
let tun = verge_patch(|p| p.enable_tun_mode = Some(true));
#[cfg(target_os = "linux")]
assert_eq!(
verge_effects(&tun),
[
Effect::RestartCore,
Effect::ClashConfig,
Effect::TrayIcon,
Effect::TrayMenu,
Effect::TrayTooltip,
]
.into_iter()
.collect::<Effects>()
);
#[cfg(not(target_os = "linux"))]
assert_eq!(
verge_effects(&tun),
[
Effect::ClashConfig,
Effect::TrayIcon,
Effect::TrayMenu,
Effect::TrayTooltip,
]
.into_iter()
.collect::<Effects>()
);
}
fn clash_mapping(pairs: &[(&str, &str)]) -> serde_yaml_ng::Mapping {
let mut mapping = serde_yaml_ng::Mapping::new();
for (key, value) in pairs {
mapping.insert((*key).into(), (*value).into());
}
mapping
}
#[test]
fn clash_keys_map_to_frozen_effects() {
let cases: [(serde_yaml_ng::Mapping, &[Effect]); 7] = [
(clash_mapping(&[]), &[Effect::ClashConfig]),
(clash_mapping(&[("secret", "s")]), &[Effect::RestartCore]),
(
clash_mapping(&[("mode", "rule")]),
&[Effect::ClashConfig, Effect::TrayIcon, Effect::TrayMenu],
),
(clash_mapping(&[("allow-lan", "true")]), &[Effect::ClashConfig]),
(clash_mapping(&[("not-a-known-key", "1")]), &[Effect::ClashConfig]),
// Restart supersedes reload; allow-lan precedes mode.
(
clash_mapping(&[("secret", "s"), ("mode", "rule")]),
&[Effect::RestartCore],
),
(
clash_mapping(&[("allow-lan", "true"), ("mode", "rule")]),
&[Effect::ClashConfig],
),
];
for (patch, expected) in cases {
assert_eq!(
clash_effects(&patch),
expected.iter().copied().collect::<Effects>(),
"clash mapping drifted for {expected:?}"
);
}
}
}
+195
View File
@@ -0,0 +1,195 @@
use super::effects::{Effect, Effects};
use crate::core::notify::{Refresh, announce};
use crate::{
config::{
Config, IVerge,
snapshot::{capture_config_files, restore_files},
},
core::auto_backup::AutoBackupManager,
core::{CoreManager, logger, manager::ConfigUpdateGuard, proxy_control},
};
use anyhow::Result;
use clash_verge_draft::DraftTransaction;
use clash_verge_logging::{Type, logging_error};
use futures::future::BoxFuture;
use serde_yaml_ng::Mapping;
use tokio::sync::MutexGuard;
pub(super) enum Patch<'a> {
Verge { patch: &'a IVerge, persist: bool },
Clash(&'a Mapping),
}
struct EffectContext<'a> {
patch: &'a IVerge,
manager: &'a CoreManager,
update: &'a ConfigUpdateGuard<'a>,
}
type Ensure = for<'a> fn(&'a EffectContext<'_>) -> BoxFuture<'a, Result<()>>;
const EFFECT_ORDER: &[(Effect, Ensure)] = &[
(Effect::RestartCore, ensure_restart),
(Effect::ClashConfig, ensure_clash),
(Effect::VergeConfig, ensure_verge),
(Effect::Autostart, ensure_autostart),
(Effect::Language, ensure_language),
(Effect::SystemProxy, ensure_system_proxy),
(Effect::Hotkey, ensure_hotkey),
(Effect::TrayMenu, ensure_tray_menu),
(Effect::TrayIcon, ensure_tray_icon),
(Effect::TrayTooltip, ensure_tray_tooltip),
(Effect::TrayClick, ensure_tray_click),
(Effect::Lightweight, ensure_lightweight),
(Effect::LogLevel, ensure_log_level),
(Effect::LogFile, ensure_log_file),
];
macro_rules! ensure {
($name:ident, $ctx:ident, $body:block) => {
fn $name<'a>($ctx: &'a EffectContext<'_>) -> BoxFuture<'a, Result<()>> {
Box::pin(async move $body)
}
};
}
ensure!(ensure_restart, ctx, {
Config::generate().await?;
ctx.manager.restart_core_during_config_update().await
});
ensure!(ensure_clash, ctx, {
ctx.manager.update_config_in_patch(ctx.update).await?;
announce(Refresh::Clash);
Ok(())
});
ensure!(ensure_verge, _ctx, { Ok(()) });
ensure!(ensure_autostart, ctx, {
crate::core::app_effects::ensure_autostart(ctx.patch).await
});
ensure!(ensure_language, ctx, {
if let Some(language) = &ctx.patch.language {
clash_verge_i18n::set_locale(language.as_str());
}
Ok(())
});
ensure!(ensure_system_proxy, ctx, {
let _lifecycle = ctx.manager.lifecycle_lock.lock().await;
// Disabling only writes OS state and must remain available when the Core is stopped.
if Config::verge()
.await
.latest_arc()
.enable_system_proxy
.unwrap_or_default()
{
ctx.manager.apply_proxy_after_start().await
} else {
proxy_control::apply().await?;
proxy_control::refresh_guard().await
}
});
ensure!(ensure_hotkey, ctx, {
crate::core::app_effects::ensure_hotkey(ctx.patch).await
});
ensure!(ensure_tray_menu, ctx, {
crate::core::app_effects::ensure_tray_menu(ctx.patch).await
});
ensure!(ensure_tray_icon, ctx, {
crate::core::app_effects::ensure_tray_icon(ctx.patch).await
});
ensure!(ensure_tray_tooltip, ctx, {
crate::core::app_effects::ensure_tray_tooltip(ctx.patch).await
});
ensure!(ensure_tray_click, ctx, {
crate::core::app_effects::ensure_tray_click(ctx.patch).await
});
ensure!(ensure_lightweight, ctx, {
crate::core::app_effects::ensure_lightweight(ctx.patch).await
});
ensure!(ensure_log_level, ctx, {
logger::Logger::global().update_log_level(ctx.patch.get_log_level())
});
ensure!(ensure_log_file, ctx, {
logger::update_log_config(
ctx.patch.app_log_max_size.unwrap_or(128),
ctx.patch.app_log_max_count.unwrap_or(8),
)
.await
});
async fn apply_inner(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: Effects) -> Result<()> {
let manager = CoreManager::global();
let update = manager.claim_config_update(config_write)?;
let clash = Config::clash().await;
let verge = Config::verge().await;
let runtime = Config::runtime().await;
let transaction = match patch {
Patch::Verge { .. } => DraftTransaction::begin(vec![&verge, &runtime])?,
Patch::Clash(_) => DraftTransaction::begin(vec![&clash, &runtime])?,
};
let snapshots = capture_config_files().await?;
let empty = IVerge::default();
let context = EffectContext {
patch: match &patch {
Patch::Verge { patch, .. } => patch,
Patch::Clash(_) => &empty,
},
manager,
update: &update,
};
match &patch {
Patch::Verge { patch, .. } => verge.edit_draft(|draft| draft.patch_config(patch)),
Patch::Clash(patch) => clash.edit_draft(|draft| draft.patch_config(patch)),
}
let result: Result<()> = async {
for (effect, ensure) in EFFECT_ORDER {
if effects.contains(effect) {
ensure(&context).await?;
}
}
match patch {
Patch::Verge { persist: true, .. } => verge.latest_arc().save_file().await?,
Patch::Verge { persist: false, .. } => {}
Patch::Clash(_) => clash.latest_arc().save_config().await?,
}
Ok(())
}
.await;
if let Err(error) = result {
transaction.rollback();
return match restore_files(&snapshots).await {
Ok(()) => Err(error),
Err(rollback_error) => Err(proxy_control::rollback_failure(error, rollback_error)),
};
}
transaction.commit();
match patch {
Patch::Verge { .. } => {
logging_error!(Type::Backup, AutoBackupManager::global().refresh_settings().await);
announce(Refresh::Verge);
}
Patch::Clash(_) => announce(Refresh::Clash),
}
Ok(())
}
pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: Effects) -> Result<()> {
crate::core::notify::after_commit(apply_inner(config_write, patch, effects)).await
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn config_claim_is_exclusive_and_released_on_drop() -> Result<()> {
let write_lock = tokio::sync::Mutex::new(());
let write = write_lock.lock().await;
let manager = CoreManager::default();
let first = manager.claim_config_update(&write)?;
assert!(manager.claim_config_update(&write).is_err());
drop(first);
assert!(manager.claim_config_update(&write).is_ok());
drop(write);
Ok(())
}
}
+8 -4
View File
@@ -1,3 +1,4 @@
use crate::core::notify::{Refresh, announce};
use crate::{
config::{
Config, MixedPort,
@@ -5,7 +6,6 @@ use crate::{
},
core::{
CoreManager,
handle::Handle,
listener::{
ListenerProbe, ListenerProbeOutcome, ProxyPortSettings, SaveProxyPortsOutcome,
probe_listener as probe_listener_sync, probe_proxy_port_change,
@@ -27,8 +27,12 @@ pub async fn probe_listener(request: ListenerProbe) -> Result<ListenerProbeOutco
.context("listener probe task failed")
}
#[allow(clippy::cognitive_complexity)]
pub async fn save_proxy_ports(settings: ProxyPortSettings) -> Result<SaveProxyPortsOutcome> {
crate::core::notify::after_commit(Box::pin(save_proxy_ports_inner(settings))).await
}
#[allow(clippy::cognitive_complexity)]
async fn save_proxy_ports_inner(settings: ProxyPortSettings) -> Result<SaveProxyPortsOutcome> {
settings.validate()?;
let _config_write = Config::lock_config_write().await;
let manager = CoreManager::global();
@@ -126,8 +130,8 @@ pub async fn save_proxy_ports(settings: ProxyPortSettings) -> Result<SaveProxyPo
transaction.commit();
// The save landed, so the port the app had borrowed is now irrelevant.
let _ = ScopeGuard::into_inner(borrowed_port);
Handle::refresh_clash();
Handle::refresh_verge();
announce(Refresh::Clash);
announce(Refresh::Verge);
logging!(info, Type::Config, "Proxy port configuration applied and persisted");
Ok(SaveProxyPortsOutcome::Saved)
}
+2
View File
@@ -3,6 +3,8 @@ mod clash;
mod config;
mod core_upgrade;
mod dns;
mod effects;
mod executor;
mod icon;
mod listener;
mod profile;
+74 -56
View File
@@ -1,3 +1,5 @@
use crate::core::notify::NoticeStatus;
use crate::core::notify::{Refresh, announce};
use crate::{
cmd,
config::{Config, PrfItem, PrfOption, profiles::profiles_update_item_safe},
@@ -43,7 +45,7 @@ pub async fn switch_proxy_node(group_name: &str, proxy_name: &str) {
{
Ok(_) => {
record_switched_node(group_name, proxy_name).await;
handle::Handle::refresh_proxy_config();
announce(Refresh::Proxies);
let _ = tray::Tray::global().update_menu().await;
return;
}
@@ -100,7 +102,7 @@ async fn should_update_profile(uid: &String, ignore_auto_update: bool) -> Result
}
}
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty))]
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))]
async fn perform_profile_update(
uid: &String,
url: &String,
@@ -108,7 +110,7 @@ async fn perform_profile_update(
option: Option<&PrfOption>,
is_mannual_trigger: bool,
) -> Result<()> {
let mut merged_opt = PrfOption::merge(opt, option);
let merged_opt = PrfOption::merge(opt, option);
let profiles = Config::profiles().await;
let profiles_arc = profiles.latest_arc();
let profile_name = profiles_arc
@@ -117,66 +119,82 @@ async fn perform_profile_update(
.and_then(|item| item.name.clone())
.unwrap_or_else(|| String::from("UnKnown Profile"));
match PrfItem::from_url(url, None, None, merged_opt.as_ref()).await {
Ok(mut item) => {
logging!(info, Type::Config, "[订阅更新] 更新订阅配置成功");
profiles_update_item_safe(uid, &mut item).await?;
return Ok(());
}
Err(err) => {
logging!(
warn,
Type::Config,
"[订阅更新] 直接更新失败: {},尝试使用Clash代理更新",
mask_err(&format!("{err:#}"))
);
}
#[derive(Clone, Copy)]
enum Strategy {
Configured,
Clash,
System,
}
merged_opt.get_or_insert_with(PrfOption::default).self_proxy = Some(true);
merged_opt.get_or_insert_with(PrfOption::default).with_proxy = Some(false);
match PrfItem::from_url(url, None, None, merged_opt.as_ref()).await {
Ok(mut item) => {
logging!(info, Type::Config, "[订阅更新] 使用 Clash代理 更新订阅配置成功");
let result =
crate::utils::retry::try_strategies(Strategy::Configured, [Strategy::Clash, Strategy::System], |strategy| {
let mut options = merged_opt.clone();
async move {
let (name, success, failure) = match strategy {
Strategy::Configured => (
"configured",
"[订阅更新] 更新订阅配置成功",
"[订阅更新] 直接更新失败: {},尝试使用Clash代理更新",
),
Strategy::Clash => (
"clash",
"[订阅更新] 使用 Clash代理 更新订阅配置成功",
"[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新",
),
Strategy::System => (
"system",
"[订阅更新] 使用 系统代理 更新订阅配置成功",
"[订阅更新] 系统代理更新失败: {},所有重试均已失败",
),
};
match strategy {
Strategy::Configured => {}
Strategy::Clash | Strategy::System => {
let option = options.get_or_insert_with(PrfOption::default);
option.self_proxy = Some(matches!(strategy, Strategy::Clash));
option.with_proxy = Some(matches!(strategy, Strategy::System));
}
}
tracing::Span::current().record("strategy", name);
let started = std::time::Instant::now();
let result = PrfItem::from_url(url, None, None, options.as_ref()).await;
let elapsed_field = match strategy {
Strategy::Configured => "configured_elapsed",
Strategy::Clash => "clash_elapsed",
Strategy::System => "system_elapsed",
};
tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed()));
match &result {
Ok(_) => logging!(info, Type::Config, "{success}"),
Err(error) => logging!(
warn,
Type::Config,
"{}",
failure.replace("{}", &mask_err(&format!("{error:#}")))
),
}
result
}
})
.await;
let last_err = match result {
Ok((strategy, mut item)) => {
// A persistence error must not replay a successful download with another transport.
profiles_update_item_safe(uid, &mut item).await?;
handle::Handle::notice_message("update_with_clash_proxy", profile_name);
if !matches!(strategy, Strategy::Configured) {
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str());
}
return Ok(());
}
Err(err) => {
logging!(
warn,
Type::Config,
"[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新",
mask_err(&format!("{err:#}"))
);
}
}
merged_opt.get_or_insert_with(PrfOption::default).self_proxy = Some(false);
merged_opt.get_or_insert_with(PrfOption::default).with_proxy = Some(true);
let last_err = match PrfItem::from_url(url, None, None, merged_opt.as_ref()).await {
Ok(mut item) => {
logging!(info, Type::Config, "[订阅更新] 使用 系统代理 更新订阅配置成功");
profiles_update_item_safe(uid, &mut item).await?;
handle::Handle::notice_message("update_with_clash_proxy", profile_name);
return Ok(());
}
Err(err) => {
logging!(
warn,
Type::Config,
"[订阅更新] 系统代理更新失败: {},所有重试均已失败",
mask_err(&format!("{err:#}"))
);
err
}
Err(error) => error,
};
let last_err = mask_err(&last_err.to_string());
if is_mannual_trigger {
handle::Handle::notice_message("update_failed_even_with_clash", format!("{profile_name} - {last_err}"));
handle::Handle::notice(
NoticeStatus::UpdateFailedEvenWithClash,
format!("{profile_name} - {last_err}"),
);
}
bail!(last_err)
}
@@ -201,7 +219,7 @@ pub async fn update_profile(uid: &String, option: Option<&PrfOption>, is_mannual
match CoreManager::global().update_config_with_force(is_mannual_trigger).await {
Ok(outcome) if outcome.is_valid() => {
logging_error!(Type::Config, Config::sync_dns_override().await);
handle::Handle::refresh_clash();
announce(Refresh::Clash);
}
Ok(outcome @ (ValidationOutcome::Skipped { .. } | ValidationOutcome::Busy)) if !is_mannual_trigger => {
logging!(info, Type::Config, "[订阅更新] 本次配置刷新已跳过: {}", outcome);
@@ -218,7 +236,7 @@ pub async fn update_profile(uid: &String, option: Option<&PrfOption>, is_mannual
message
};
logging!(error, Type::Config, "[订阅更新] 更新失败: {}", message);
handle::Handle::notice_message("update_failed", &message);
handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str());
bail!(message);
}
}
+2 -1
View File
@@ -1,3 +1,4 @@
use crate::core::notify::{Refresh, announce};
use crate::{
config::{Config, IVerge, MixedPort},
core::{
@@ -83,7 +84,7 @@ pub async fn toggle_tun_mode(not_save_file: Option<bool>) -> bool {
.await
{
Ok(_) => {
handle::Handle::refresh_verge();
announce(Refresh::Verge);
// Reconciliation may immediately disable unavailable TUN; report the resulting state.
Config::verge().await.latest_arc().enable_tun_mode.unwrap_or(false)
}
+4 -2
View File
@@ -1,5 +1,7 @@
//! Reconciles TUN with current Core and Service availability.
use crate::core::notify::NoticeStatus;
use std::sync::atomic::{AtomicBool, Ordering};
use clash_verge_logging::{Type, logging};
@@ -75,10 +77,10 @@ pub async fn reconcile_tun_availability() {
// Skip recursive reconciliation for this internal patch.
match super::apply_verge_patch_locked(&config_write, &patch, false).await {
Ok(()) => Handle::notice_message("tun_mode::auto_disabled", ""),
Ok(()) => Handle::notice(NoticeStatus::TunModeAutoDisabled, ""),
Err(error) => {
logging!(error, Type::Core, "failed to turn TUN mode off: {error:#}");
Handle::notice_message("tun_mode::auto_disable_failed", "");
Handle::notice(NoticeStatus::TunModeAutoDisableFailed, "");
}
}
}
+5 -4
View File
@@ -1,6 +1,7 @@
use crate::config::Config;
use crate::core::lightweight;
use crate::core::notify::NoticeStatus;
use crate::core::{CoreManager, handle};
use crate::module::lightweight;
use crate::utils;
use crate::utils::window_manager::WindowManager;
use clash_verge_logging::{Type, logging};
@@ -128,8 +129,8 @@ pub async fn quit() -> clash_verge_signal::ShutdownOutcome {
if should_abort_exit_after_cleanup(cleanup_result.core_stopped) {
handle::Handle::global().clear_is_exiting();
handle::Handle::notice_message(
"app_quit::core_stop_failed",
handle::Handle::notice(
NoticeStatus::AppQuitCoreStopFailed,
cleanup_result.stop_error.unwrap_or_default(),
);
return clash_verge_signal::ShutdownOutcome::Canceled;
@@ -230,7 +231,7 @@ pub async fn clean_session_ending_best_effort() -> CleanupResult {
#[cfg(target_os = "macos")]
pub async fn hide() {
use crate::module::lightweight::add_light_weight_timer;
use crate::core::lightweight::add_light_weight_timer;
let enable_auto_light_weight_mode = Config::verge()
.await
+8 -5
View File
@@ -7,7 +7,6 @@ mod constants;
mod core;
mod enhance;
mod feat;
mod module;
mod process;
pub mod utils;
@@ -19,13 +18,17 @@ use crate::{
};
use anyhow::Result;
use clash_verge_logging::{Type, logging};
use once_cell::sync::OnceCell;
use std::sync::OnceLock;
use tauri::{AppHandle, Manager as _};
#[cfg(target_os = "macos")]
use tauri_plugin_autostart::MacosLauncher;
use tauri_plugin_deep_link::DeepLinkExt as _;
pub static APP_HANDLE: OnceCell<AppHandle> = OnceCell::new();
pub static APP_HANDLE: OnceLock<AppHandle> = OnceLock::new();
// Re-exported for src/bin/frontend-contract.rs; the wire contract stays owned
// by core::notify.
pub use crate::core::notify::frontend_wire_contract;
/// Application initialization helper functions
mod app_init {
use super::*;
@@ -333,7 +336,7 @@ pub fn run() -> std::process::ExitCode {
mod event_handlers {
#[cfg(target_os = "macos")]
use crate::module::lightweight;
use crate::core::lightweight;
use crate::utils::window_manager::WindowManager;
use crate::{
config::Config,
@@ -488,7 +491,7 @@ pub fn run() -> std::process::ExitCode {
}),
#[allow(unused_variables)]
tauri::RunEvent::ExitRequested { api, code, .. } => {
if module::lightweight::is_in_lightweight_mode() && !handle::Handle::global().is_exiting() {
if core::lightweight::is_in_lightweight_mode() && !handle::Handle::global().is_exiting() {
api.prevent_exit();
} else if code.is_none() {
api.prevent_exit();
-2
View File
@@ -1,2 +0,0 @@
pub mod auto_backup;
pub mod lightweight;
+2 -1
View File
@@ -1,3 +1,4 @@
use crate::core::notify::NoticeStatus;
use crate::{config::with_encryption, process::AsyncHandler};
use anyhow::{Context as _, Result, anyhow, bail};
use clash_verge_logging::{Type, logging};
@@ -58,7 +59,7 @@ fn parse_mapping(yaml_str: String, path: PathBuf) -> Result<Mapping> {
let error_msg = format!("YAML syntax error in {}: {}", path.display(), err);
logging!(error, Type::Config, "{}", error_msg);
crate::core::handle::Handle::notice_message("config_validate::yaml_syntax_error", &error_msg);
crate::core::handle::Handle::notice(NoticeStatus::ConfigValidateYamlSyntaxError, error_msg.as_str());
bail!("YAML syntax error: {}", err)
}
+53 -36
View File
@@ -109,44 +109,61 @@ fn current_user_home() -> anyhow::Result<PathBuf> {
}
.max(1024);
loop {
if buffer_size > MAX_BUFFER_SIZE {
anyhow::bail!("effective-user home lookup exceeded the maximum buffer size");
}
use crate::utils::retry::{RetryError, RetryPolicy, retry_sync};
retry_sync(
RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add(11),
std::time::Duration::ZERO,
),
|_| {
if buffer_size > MAX_BUFFER_SIZE {
return Err(RetryError::Stop(anyhow::anyhow!(
"effective-user home lookup exceeded the maximum buffer size"
)));
}
let mut passwd = std::mem::MaybeUninit::<libc::passwd>::zeroed();
let mut result = std::ptr::null_mut();
let mut buffer = vec![0_u8; buffer_size];
let code = unsafe {
libc::getpwuid_r(
uid,
passwd.as_mut_ptr(),
buffer.as_mut_ptr().cast(),
buffer.len(),
&mut result,
)
};
if code == libc::ERANGE {
buffer_size = buffer_size.saturating_mul(2);
continue;
}
if code != 0 {
return Err(std::io::Error::from_raw_os_error(code).into());
}
if result.is_null() {
anyhow::bail!("effective user {uid} has no password database entry");
}
let mut passwd = std::mem::MaybeUninit::<libc::passwd>::zeroed();
let mut result = std::ptr::null_mut();
let mut buffer = vec![0_u8; buffer_size];
let code = unsafe {
libc::getpwuid_r(
uid,
passwd.as_mut_ptr(),
buffer.as_mut_ptr().cast(),
buffer.len(),
&mut result,
)
};
if code == libc::ERANGE {
buffer_size = buffer_size.saturating_mul(2);
return Err(RetryError::Retry(anyhow::anyhow!(
"effective-user home lookup exceeded the maximum buffer size"
)));
}
if code != 0 {
return Err(RetryError::Stop(std::io::Error::from_raw_os_error(code).into()));
}
if result.is_null() {
return Err(RetryError::Stop(anyhow::anyhow!(
"effective user {uid} has no password database entry"
)));
}
let passwd = unsafe { passwd.assume_init() };
if passwd.pw_dir.is_null() {
anyhow::bail!("effective user {uid} has no home directory");
}
let home = unsafe { CStr::from_ptr(passwd.pw_dir) };
if home.to_bytes().is_empty() {
anyhow::bail!("effective user {uid} has an empty home directory");
}
return Ok(PathBuf::from(std::ffi::OsStr::from_bytes(home.to_bytes())));
}
let passwd = unsafe { passwd.assume_init() };
if passwd.pw_dir.is_null() {
return Err(RetryError::Stop(anyhow::anyhow!(
"effective user {uid} has no home directory"
)));
}
let home = unsafe { CStr::from_ptr(passwd.pw_dir) };
if home.to_bytes().is_empty() {
return Err(RetryError::Stop(anyhow::anyhow!(
"effective user {uid} has an empty home directory"
)));
}
Ok(PathBuf::from(std::ffi::OsStr::from_bytes(home.to_bytes())))
},
)
}
pub const fn move_decision(
+2 -1
View File
@@ -8,9 +8,10 @@ pub mod linux;
#[cfg(target_os = "macos")]
pub mod macos_launch_guard;
pub(crate) mod network;
pub mod notification;
pub use crate::core::notify::desktop as notification;
pub mod port;
pub mod resolve;
pub mod retry;
#[cfg(target_os = "windows")]
pub mod schtasks;
pub mod server;
+3 -2
View File
@@ -1,3 +1,4 @@
use crate::core::notify::NoticeStatus;
use std::sync::atomic::{AtomicBool, Ordering};
use anyhow::Result;
@@ -13,8 +14,8 @@ use crate::{
service::{SERVICE_MANAGER, ServiceManager},
tray::Tray,
},
core::{auto_backup::AutoBackupManager, lightweight::auto_lightweight_boot},
feat,
module::{auto_backup::AutoBackupManager, lightweight::auto_lightweight_boot},
process::AsyncHandler,
utils::{init, server, window_manager::WindowManager},
};
@@ -223,7 +224,7 @@ async fn init_core_manager() -> bool {
Err(error) => {
logging!(error, Type::Setup, "core manager initialization failed: {error:#}");
CoreManager::global().record_startup_error(CoreFailure::StartFailed(format!("{error:#}")));
Handle::notice_message("core_start::error", "");
Handle::notice(NoticeStatus::CoreStartError, "");
false
}
}
+8 -7
View File
@@ -1,3 +1,4 @@
use crate::core::notify::NoticeStatus;
use anyhow::Result;
use percent_encoding::percent_decode_str;
use smartstring::alias::String;
@@ -93,18 +94,18 @@ async fn import_subscription(url: &str, name: Option<&String>) {
if let Err(e) = profiles::profiles_append_item_safe(&mut item).await {
logging!(error, Type::Config, "failed to import subscription url: {:?}", e);
Config::profiles().await.discard();
handle::Handle::notice_message("import_sub_url::error", e.to_string());
handle::Handle::notice(NoticeStatus::ImportSubUrlError, e.to_string());
return;
}
if let Err(e) = profiles::profiles_save_file_safe().await {
logging!(error, Type::Config, "failed to save imported subscription: {e:#}");
handle::Handle::notice_message("import_sub_url::error", e.to_string());
handle::Handle::notice(NoticeStatus::ImportSubUrlError, e.to_string());
return;
}
logging_error!(Type::Timer, Timer::global().refresh().await);
handle::Handle::notice_message(
"import_sub_url::ok",
handle::Handle::notice(
NoticeStatus::ImportSubUrlOk,
"", // 空 msg 传入,我们不希望导致 后端-前端-后端 死循环,这里只做提醒。
);
@@ -116,7 +117,7 @@ async fn fetch_profile_item(url: &str, name: Option<&String>) -> Option<PrfItem>
Ok(item) => Some(item),
Err(e) => {
logging!(error, Type::Config, "failed to parse profile from url: {:?}", e);
handle::Handle::notice_message("import_sub_url::error", e.to_string());
handle::Handle::notice(NoticeStatus::ImportSubUrlError, e.to_string());
None
}
}
@@ -149,11 +150,11 @@ async fn refresh_core_config() {
Ok(outcome) => {
let message = outcome.to_string();
logging!(warn, Type::Config, "Apply config failed: {}", message);
handle::Handle::notice_message("config_validate::error", message);
handle::Handle::notice(NoticeStatus::ConfigValidateError, message);
}
Err(err) => {
logging!(error, Type::Config, "Apply config error: {err:#}");
handle::Handle::notice_message("update_failed", format!("{err}"));
handle::Handle::notice(NoticeStatus::UpdateFailed, format!("{err}"));
}
}
}
+237
View File
@@ -0,0 +1,237 @@
use backon::{BackoffBuilder as _, ExponentialBackoff, ExponentialBuilder};
use std::{future::Future, num::NonZeroUsize, time::Duration};
#[derive(Clone, Copy, Debug)]
pub enum Backoff {
Fixed(Duration),
#[allow(dead_code)]
Exponential {
base: Duration,
cap: Duration,
},
}
#[derive(Clone, Copy, Debug)]
pub struct RetryPolicy {
pub attempts: NonZeroUsize,
pub backoff: Backoff,
pub jitter: bool,
}
impl RetryPolicy {
pub const fn fixed(attempts: NonZeroUsize, delay: Duration) -> Self {
Self {
attempts,
backoff: Backoff::Fixed(delay),
jitter: false,
}
}
fn delays(self) -> ExponentialBackoff {
let (base, cap, factor) = match self.backoff {
Backoff::Fixed(delay) => (delay, delay, 1.0),
Backoff::Exponential { base, cap } => (base, cap, 2.0),
};
let mut builder = ExponentialBuilder::default()
.with_min_delay(base)
.with_max_delay(cap)
.with_factor(factor)
.with_max_times(self.attempts.get() - 1);
if self.jitter {
builder = builder.with_jitter();
}
builder.build()
}
}
pub enum RetryError<E> {
Retry(E),
Stop(E),
}
pub async fn retry<T: Send, E: Send, Fut: Future<Output = Result<T, RetryError<E>>> + Send>(
policy: RetryPolicy,
mut operation: impl FnMut(usize) -> Fut + Send,
) -> Result<T, E> {
let mut result = operation(0).await;
for (index, delay) in policy.delays().enumerate() {
match result {
Ok(_) | Err(RetryError::Stop(_)) => break,
Err(RetryError::Retry(_)) => {
if !delay.is_zero() {
tokio::time::sleep(delay).await;
}
}
}
result = operation(index + 1).await;
}
result.map_err(|error| match error {
RetryError::Retry(error) | RetryError::Stop(error) => error,
})
}
pub async fn try_strategies<
S: Copy + Send,
T: Send,
E: Send,
Fut: Future<Output = Result<T, E>> + Send,
const N: usize,
>(
first: S,
rest: [S; N],
mut operation: impl FnMut(S) -> Fut + Send,
) -> Result<(S, T), E> {
retry(
RetryPolicy {
attempts: NonZeroUsize::MIN.saturating_add(N),
backoff: Backoff::Fixed(Duration::ZERO),
jitter: false,
},
move |attempt| {
let strategy = if attempt == 0 { first } else { rest[attempt - 1] };
let future = operation(strategy);
async move { future.await.map(|value| (strategy, value)).map_err(RetryError::Retry) }
},
)
.await
}
pub async fn retry_with_state<S: Send, T: Send, E: Send>(
policy: RetryPolicy,
mut state: S,
mut operation: impl for<'a> FnMut(&'a mut S, usize) -> futures::future::BoxFuture<'a, Result<T, RetryError<E>>> + Send,
) -> Result<T, E> {
let mut result = operation(&mut state, 0).await;
for (index, delay) in policy.delays().enumerate() {
match result {
Ok(_) | Err(RetryError::Stop(_)) => break,
Err(RetryError::Retry(_)) => {
if !delay.is_zero() {
tokio::time::sleep(delay).await;
}
}
}
result = operation(&mut state, index + 1).await;
}
result.map_err(|error| match error {
RetryError::Retry(error) | RetryError::Stop(error) => error,
})
}
pub fn retry_sync<T, E>(
policy: RetryPolicy,
mut operation: impl FnMut(usize) -> Result<T, RetryError<E>>,
) -> Result<T, E> {
let mut result = operation(0);
for (index, delay) in policy.delays().enumerate() {
match result {
Ok(_) | Err(RetryError::Stop(_)) => break,
Err(RetryError::Retry(_)) => {
if !delay.is_zero() {
std::thread::sleep(delay);
}
}
}
result = operation(index + 1);
}
result.map_err(|error| match error {
RetryError::Retry(error) | RetryError::Stop(error) => error,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn retries_stop_at_success_terminal_error_or_attempt_limit() {
let policy = RetryPolicy {
attempts: NonZeroUsize::MIN.saturating_add(2),
backoff: Backoff::Fixed(Duration::ZERO),
jitter: false,
};
let mut calls = 0;
let success = retry(policy, |attempt| {
calls += 1;
async move {
if attempt == 1 {
Ok(7)
} else {
Err(RetryError::Retry(attempt))
}
}
})
.await;
assert_eq!((success, calls), (Ok(7), 2));
calls = 0;
let stopped = retry(policy, |_| {
calls += 1;
async move { Err::<(), _>(RetryError::Stop("terminal")) }
})
.await;
assert_eq!((stopped, calls), (Err("terminal"), 1));
calls = 0;
let exhausted = retry(policy, |attempt| {
calls += 1;
async move { Err::<(), _>(RetryError::Retry(attempt)) }
})
.await;
assert_eq!((exhausted, calls), (Err(2), 3));
}
#[tokio::test]
async fn strategies_preserve_order_and_the_last_failure() {
let mut visited = Vec::new();
let result = try_strategies("direct", ["clash", "system"], |strategy| {
visited.push(strategy);
async move { Err::<(), _>(strategy) }
})
.await;
assert_eq!(result, Err("system"));
assert_eq!(visited, ["direct", "clash", "system"]);
}
#[tokio::test]
async fn stateful_and_sync_retries_preserve_progress_and_stop() {
let policy = RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(2), Duration::ZERO);
let result = retry_with_state(policy, Vec::new(), |visited, attempt| {
Box::pin(async move {
visited.push(attempt);
if visited.len() == 3 {
Ok(visited.clone())
} else {
Err(RetryError::Retry(()))
}
})
})
.await;
assert_eq!(result, Ok(vec![0, 1, 2]));
let mut visited = Vec::new();
let result = retry_sync(policy, |attempt| {
visited.push(attempt);
if attempt == 1 {
Err::<(), _>(RetryError::Stop("terminal"))
} else {
Err(RetryError::Retry("retry"))
}
});
assert_eq!(result, Err("terminal"));
assert_eq!(visited, [0, 1]);
}
#[test]
fn backoff_keeps_the_attempt_budget_and_exponential_cap() {
let policy = RetryPolicy {
attempts: NonZeroUsize::MIN.saturating_add(4),
backoff: Backoff::Exponential {
base: Duration::from_millis(10),
cap: Duration::from_millis(25),
},
jitter: false,
};
assert_eq!(
policy.delays().collect::<Vec<_>>(),
[10, 20, 25, 25].map(Duration::from_millis)
);
}
}
+33 -21
View File
@@ -1,18 +1,18 @@
use super::resolve;
use crate::{
config::{Config, DEFAULT_PAC, MixedPort},
module::lightweight,
core::lightweight,
process::AsyncHandler,
utils::{dirs, window_manager::WindowManager},
};
use anyhow::{Context as _, Result, bail};
use clash_verge_logging::{Type, logging};
use once_cell::sync::OnceCell;
use parking_lot::Mutex;
use reqwest::ClientBuilder;
use serde::{Deserialize, Serialize};
use std::io::{Read as _, Write as _};
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use tokio::sync::oneshot;
@@ -33,9 +33,9 @@ struct InstanceRecord {
token: String,
}
static SHUTDOWN_SENDER: OnceCell<Mutex<Option<oneshot::Sender<()>>>> = OnceCell::new();
static EMBEDDED_PORT: OnceCell<u16> = OnceCell::new();
static INSTANCE_LOCK: OnceCell<std::fs::File> = OnceCell::new();
static SHUTDOWN_SENDER: OnceLock<Mutex<Option<oneshot::Sender<()>>>> = OnceLock::new();
static EMBEDDED_PORT: OnceLock<u16> = OnceLock::new();
static INSTANCE_LOCK: OnceLock<std::fs::File> = OnceLock::new();
const PAC_INITIAL_AVAILABLE: bool = false;
static PAC_AVAILABLE: AtomicBool = AtomicBool::new(PAC_INITIAL_AVAILABLE);
static COMMANDS_READY: AtomicBool = AtomicBool::new(false);
@@ -54,22 +54,34 @@ pub async fn check_singleton() -> Result<SingletonDisposition> {
.context("failed to initialize singleton lock")?;
if !try_lock_instance(&lock).context("failed to acquire singleton lock")? {
let deadline = std::time::Instant::now() + Duration::from_secs(20);
loop {
if std::time::Instant::now() >= deadline {
bail!("another app instance is starting");
}
// A restarting instance releases this lock only after spawning this
// process, and its embedded server is already down, so waiting on
// the notify probe alone can never promote this instance.
if try_lock_instance(&lock).context("failed to acquire singleton lock")? {
break;
}
if let Ok(record) = read_instance_record(&record_path)
&& notify_existing_instance(&record).await
{
return Ok(SingletonDisposition::Secondary);
}
tokio::time::sleep(Duration::from_millis(50)).await;
use crate::utils::retry::{RetryError, RetryPolicy, retry};
let secondary = retry(
RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add(400),
Duration::from_millis(50),
),
|_| async {
if std::time::Instant::now() >= deadline {
return Err(RetryError::Stop(anyhow::anyhow!("another app instance is starting")));
}
// A restarting primary releases the lock after spawning us, with its server down.
if try_lock_instance(&lock)
.context("failed to acquire singleton lock")
.map_err(RetryError::Stop)?
{
return Ok(false);
}
if let Ok(record) = read_instance_record(&record_path)
&& notify_existing_instance(&record).await
{
return Ok(true);
}
Err(RetryError::Retry(anyhow::anyhow!("another app instance is starting")))
},
)
.await?;
if secondary {
return Ok(SingletonDisposition::Secondary);
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
/// Implements `global()` using the supplied `OnceCell` static.
/// Implements `global()` using the supplied `OnceLock` static.
#[macro_export]
macro_rules! singleton {
($struct_name:ty, $instance_name:ident) => {
+2 -2
View File
@@ -1,8 +1,8 @@
use crate::{core::handle, utils::resolve::window::build_new_window};
use clash_verge_limiter::Limiter;
use clash_verge_logging::{Type, logging};
use once_cell::sync::Lazy;
use std::pin::Pin;
use std::sync::LazyLock;
use std::time::Duration;
use tauri::{Manager as _, WebviewWindow, Wry};
@@ -26,7 +26,7 @@ pub enum WindowState {
}
const WINDOW_OPERATION_DEBOUNCE_MS: u64 = 625;
static WINDOW_OPERATION_LIMITER: Lazy<Limiter> = Lazy::new(|| {
static WINDOW_OPERATION_LIMITER: LazyLock<Limiter> = LazyLock::new(|| {
Limiter::new(
Duration::from_millis(WINDOW_OPERATION_DEBOUNCE_MS),
clash_verge_limiter::SystemClock,
+36
View File
@@ -0,0 +1,36 @@
# Frontend Architecture Guardrails
These rules supplement the repository's root `AGENTS.md`. They define the
layering introduced by the frontend contract flow; violating any of them is
rework, not a review note.
1. **Contract is generated, never hand-typed.** Event names, payload shapes,
and the `NoticeStatus` union come from `src/services/contract.ts`
(`@generated`). Regenerate with `pnpm gen:contract` after changing the
backend wire contract, and commit the result; CI regenerates and fails on
a diff. Adding a backend status requires updating the exhaustive notice
table (`src/services/notice-handlers.ts`) in the same PR — the
`Record<NoticeStatus, …>` type enforces it. No exceptions.
2. **`listen(`/`emit(` live only in the event bus.** All Tauri event
subscriptions and emissions go through `src/services/bus/`, which mounts
exactly once at the layout root and registers exactly one handler per
event name. Components and pages never touch `@tauri-apps/api/event`.
Window-lifecycle helpers that do not use the event-module API may stay
with their owning component.
3. **Event-derived state lives in the app store.** Cross-component state
produced by events is written only through pure reducer actions dispatched
by the bus or the funnel (`src/store/`). Handlers may perform documented
side effects (SWR revalidation, notices) but must not write store state
directly. New event-consumed state needs a reducer action first, not a
local `useState` in a page.
4. **User intent funnels through `mutate`.** Every mutating backend command
call goes through `src/services/mutate.ts` — components, hooks, and
dialogs included. Give each intent a stable `id`; express optimistic
writes as `optimistic`/`rollback` and success refreshes as `revalidate`/
`onFulfilled`. Flows with bespoke error UX keep it via `errorNotice:
false`; suppressing both the funnel's and the site's handling is a bug.
5. **`invoke(` lives only in services.** Backend commands are wrapped in
`src/services/cmds.ts`; mihomo-plugin mutations are governed by rule 4.
Pages and components import the wrapper, never `@tauri-apps/api/core`. CI
greps for this and rule 2 (`node scripts/check-architecture.mjs listen
emit invoke` must stay clean).
+5 -1
View File
@@ -16,6 +16,7 @@ import {
useCoreDataStatus,
} from '@/providers/app-data-context'
import { patchClashMode } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import { setCacheData } from '@/services/query-client'
import type { TranslationKey } from '@/types/generated/i18n-keys'
@@ -90,7 +91,10 @@ export const ClashModeCard = () => {
setOptimisticMode(mode)
try {
await patchClashMode(mode)
await mutate(() => patchClashMode(mode), {
id: 'patch-clash-mode',
errorNotice: false,
})
} catch (error) {
setOptimisticMode(null)
showNotice.error(error)
+5 -1
View File
@@ -26,6 +26,7 @@ import { useNavigate } from 'react-router'
import { useAppRefreshers } from '@/providers/app-data-context'
import { updateProfile } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import { isValidUrl } from '@/utils/network'
import { openExternalUrl } from '@/utils/open-external-url'
@@ -297,7 +298,10 @@ export const HomeProfileCard = ({
setUpdating(true)
try {
await updateProfile(current.uid, current.option)
await mutate(() => updateProfile(current.uid, current.option), {
id: `update-profile:${current.uid}`,
errorNotice: false,
})
onProfileUpdated?.()
// 刷新首页数据
+2 -2
View File
@@ -6,7 +6,6 @@ import {
import { isSortable } from '@dnd-kit/react/sortable'
import { Add, NetworkCheck } from '@mui/icons-material'
import { Box, IconButton, Tooltip, alpha, styled } from '@mui/material'
import { emit } from '@tauri-apps/api/event'
import { nanoid } from 'nanoid'
import { useEffect, useRef, useMemo, useCallback } from 'react'
import { useTranslation } from 'react-i18next'
@@ -20,6 +19,7 @@ import { SortableItem } from '@/components/base'
import { TestItem } from '@/components/test/test-item'
import { TestViewer, type TestViewerRef } from '@/components/test/test-viewer'
import { useVerge } from '@/hooks/use-verge'
import { emitTestAll } from '@/services/bus'
import { EnhancedCard } from './enhanced-card'
@@ -178,7 +178,7 @@ export const TestCard = () => {
)
const handleTestAll = useCallback(() => {
emit('verge://test-all')
emitTestAll()
}, [])
const handleCreateTest = useCallback(() => {
@@ -8,18 +8,24 @@ import {
type RunState,
} from '@/services/cmds'
import { showNotice } from '@/services/notice-service'
import { useQuery } from '@/services/query-client'
import { ServiceMigrationDialog } from './service-migration-dialog'
const store = vi.hoisted(() => ({
dispatch: vi.fn(),
runState: null as RunState | null,
}))
vi.mock('react', () => ({ useState: vi.fn() }))
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}))
vi.mock('@mui/material', () => ({ Alert: 'div' }))
vi.mock('@/components/base', () => ({ BaseDialog: 'dialog' }))
vi.mock('@/hooks/use-visibility', () => ({ useVisibility: () => true }))
vi.mock('@/hooks/use-system-state', () => ({ runStateQueryKey: ['state'] }))
vi.mock('@/store/app-store-context', () => ({
useAppDispatch: () => store.dispatch,
useRunState: () => store.runState,
}))
vi.mock('@/services/cmds', () => ({
getRuntimeState: vi.fn(),
installService: vi.fn(),
@@ -28,13 +34,10 @@ vi.mock('@/services/cmds', () => ({
vi.mock('@/services/notice-service', () => ({
showNotice: { warning: vi.fn(), error: vi.fn(), success: vi.fn() },
}))
vi.mock('@/services/query-client', () => ({
useQuery: vi.fn(),
setCacheData: vi.fn(),
}))
beforeEach(() => {
vi.clearAllMocks()
store.runState = null
vi.mocked(useState)
.mockReturnValueOnce([false, vi.fn()])
.mockReturnValueOnce([false, vi.fn()])
@@ -50,9 +53,7 @@ it.each([
] satisfies Partial<RunState>[])(
'does not offer Sidecar continuation from %j',
(state) => {
vi.mocked(useQuery).mockReturnValue({ data: state } as ReturnType<
typeof useQuery
>)
store.runState = state as unknown as RunState
const dialog = ServiceMigrationDialog()
expect(dialog.props.open).toBe(true)
expect(dialog.props.disableCancel).toBe(true)
@@ -60,9 +61,10 @@ it.each([
)
it('reports the permission refusal and finishes after installation falls back to Sidecar', async () => {
vi.mocked(useQuery).mockReturnValue({
data: { service: 'notInstalled', mode: 'NotRunning' },
} as ReturnType<typeof useQuery>)
store.runState = {
service: 'notInstalled',
mode: 'NotRunning',
} as unknown as RunState
const reason = 'core path C:\\ is writable by Everyone'
vi.mocked(installService).mockResolvedValue({ status: 'sidecar', reason })
vi.mocked(getRuntimeState).mockResolvedValue({
@@ -98,9 +100,7 @@ it.each([
] satisfies Partial<RunState>[])(
'offers Sidecar continuation from %j',
(state) => {
vi.mocked(useQuery).mockReturnValue({ data: state } as ReturnType<
typeof useQuery
>)
store.runState = state as unknown as RunState
expect(ServiceMigrationDialog().props.disableCancel).toBe(false)
},
)
@@ -3,8 +3,6 @@ import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { BaseDialog } from '@/components/base'
import { runStateQueryKey } from '@/hooks/use-system-state'
import { useVisibility } from '@/hooks/use-visibility'
import {
continueWithSidecar,
getRuntimeState,
@@ -12,25 +10,19 @@ import {
reinstallService,
repairService,
restartCore,
type RunState,
type ServiceInstallOutcome,
} from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import { setCacheData, useQuery } from '@/services/query-client'
import { useAppDispatch, useRunState } from '@/store/app-store-context'
export const ServiceMigrationDialog = () => {
const { t } = useTranslation()
const pageVisible = useVisibility()
const [loading, setLoading] = useState(false)
const [stateRefreshFailed, setStateRefreshFailed] = useState(false)
const [workflowIncomplete, setWorkflowIncomplete] = useState(false)
const { data: runState } = useQuery({
queryKey: runStateQueryKey,
queryFn: getRuntimeState,
enabled: true,
retry: 1,
refetchInterval: pageVisible ? 30000 : false,
})
const dispatch = useAppDispatch()
const runState = useRunState()
// Whether the service needs a decision is derived once, in Rust, and travels with the
// snapshot; a failed refresh is treated as needing one, since we cannot tell otherwise.
const needsDecision =
@@ -64,11 +56,11 @@ export const ServiceMigrationDialog = () => {
runState.service === 'unavailable')),
)
// One cache entry to refresh, so there is nothing left to keep coherent by hand.
// One store entry to refresh, so there is nothing left to keep coherent by hand.
const refreshRunState = async () => {
try {
const data = await getRuntimeState()
await setCacheData<RunState>(runStateQueryKey, data)
dispatch({ type: 'runState/loaded', runState: data })
setStateRefreshFailed(false)
return data
} catch (error) {
@@ -83,11 +75,23 @@ export const ServiceMigrationDialog = () => {
let outcome: ServiceInstallOutcome | undefined
try {
if (remedy === 'install') {
outcome = await installService()
const result = await mutate(() => installService(), {
id: 'install-service',
errorNotice: false,
})
if (result.ok) outcome = result.value
} else if (remedy === 'repair') {
outcome = await repairService()
const result = await mutate(() => repairService(), {
id: 'repair-service',
errorNotice: false,
})
if (result.ok) outcome = result.value
} else {
outcome = await reinstallService()
const result = await mutate(() => reinstallService(), {
id: 'reinstall-service',
errorNotice: false,
})
if (result.ok) outcome = result.value
}
} catch (error) {
showNotice.error(
@@ -123,8 +127,11 @@ export const ServiceMigrationDialog = () => {
let restartSucceeded = false
try {
await restartCore()
restartSucceeded = true
const result = await mutate(() => restartCore(), {
id: 'restart-core',
errorNotice: false,
})
restartSucceeded = result.ok
} catch (error) {
showNotice.error(
'layout.components.serviceMigration.errors.restartFailed',
@@ -154,7 +161,10 @@ export const ServiceMigrationDialog = () => {
setWorkflowIncomplete(true)
let startupError: unknown
try {
await continueWithSidecar()
await mutate(() => continueWithSidecar(), {
id: 'continue-with-sidecar',
errorNotice: false,
})
} catch (error) {
startupError = error
}
@@ -14,6 +14,7 @@ import {
type PendingFailure,
type ServiceInstallOutcome,
} from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import {
clearServiceRequest,
@@ -103,10 +104,18 @@ export const SysproxyPrivilegeDialog = () => {
let outcome: ServiceInstallOutcome | undefined
if (remedy === 'reinstallAndRestart') {
setStep('installing')
outcome = await reinstallService()
const result = await mutate(() => reinstallService(), {
id: 'reinstall-service',
errorNotice: false,
})
if (result.ok) outcome = result.value
} else if (remedy === 'installAndRestart') {
setStep('installing')
outcome = await installService()
const result = await mutate(() => installService(), {
id: 'install-service',
errorNotice: false,
})
if (result.ok) outcome = result.value
}
if (outcome?.status === 'sidecar') {
showNotice.warning(
@@ -118,7 +127,10 @@ export const SysproxyPrivilegeDialog = () => {
return
}
setStep('restarting')
await restartCore()
await mutate(() => restartCore(), {
id: 'restart-core',
errorNotice: false,
})
const runState = await getRuntimeState()
const usingAdminFallback =
@@ -131,7 +143,10 @@ export const SysproxyPrivilegeDialog = () => {
if (runState.mode === 'Service' || usingAdminFallback) {
if (restoring !== undefined) {
setStep('applying')
await patchVergeConfig(restoring)
await mutate(() => patchVergeConfig(restoring), {
id: 'sysproxy-privilege-restore',
errorNotice: false,
})
}
if (!usingAdminFallback) {
showNotice.success(
@@ -42,6 +42,7 @@ import {
readProfileFile,
saveProfileFile,
} from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import { useThemeMode } from '@/services/states'
import type { TranslationKey } from '@/types/generated/i18n-keys'
@@ -472,7 +473,11 @@ export const GroupsEditorViewer = (props: Props) => {
setCurrData(nextData)
}
if (!(await saveProfileFile(property, nextData))) {
const result = await mutate(() => saveProfileFile(property, nextData), {
id: `save-profile-file:${property}`,
errorNotice: false,
})
if (!(result.ok && result.value === true)) {
await fetchContent()
onClose()
return
+35 -18
View File
@@ -39,8 +39,12 @@ import {
updateProfile,
viewProfile,
} from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import { useLoadingCache, useSetLoadingCache } from '@/services/states'
import {
useProfileLoadingCache,
useSetProfileLoading,
} from '@/store/app-store-context'
import type { TranslationKey } from '@/types/generated/i18n-keys'
import { debugLog } from '@/utils/debug'
import { isValidUrl } from '@/utils/network'
@@ -105,8 +109,8 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const { t } = useTranslation()
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null)
const [position, setPosition] = useState({ left: 0, top: 0 })
const loadingCache = useLoadingCache()
const setLoadingCache = useSetLoadingCache()
const loadingCache = useProfileLoadingCache()
const setProfileLoading = useSetProfileLoading()
const [showNextUpdate, setShowNextUpdate] = useState(false)
const showNextUpdateRef = useRef(false)
@@ -116,17 +120,9 @@ const ProfileItemBase = (props: ProfileItemProps) => {
)
const setLoading = useCallback(
(loading: boolean) => {
setLoadingCache((cache) => {
const next = new Set(cache)
if (loading) {
next.add(itemData.uid)
} else {
next.delete(itemData.uid)
}
return next
})
setProfileLoading([itemData.uid], loading)
},
[itemData.uid, setLoadingCache],
[itemData.uid, setProfileLoading],
)
const { uid, name = 'Profile', extra, updated = 0, option } = itemData
@@ -374,7 +370,10 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const onOpenFile = useLockFn(async () => {
setAnchorEl(null)
try {
await viewProfile(itemData.uid)
await mutate(() => viewProfile(itemData.uid), {
id: 'view-profile',
errorNotice: false,
})
} catch (err) {
showNotice.error(err)
}
@@ -403,7 +402,10 @@ const ProfileItemBase = (props: ProfileItemProps) => {
try {
const payload = Object.keys(option).length > 0 ? option : undefined
await updateProfile(itemData.uid, payload)
await mutate(() => updateProfile(itemData.uid, payload), {
id: `update-profile:${itemData.uid}`,
errorNotice: false,
})
void mutateProfiles()
} catch {
@@ -591,7 +593,11 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const handleSaveProfileDocument = useLockFn(async () => {
const currentValue = profileDocument.value
if (!(await saveProfileFile(uid, currentValue))) {
const result = await mutate(() => saveProfileFile(uid, currentValue), {
id: `save-profile-file:${uid}`,
errorNotice: false,
})
if (!(result.ok && result.value === true)) {
await profileDocument.reload()
return
}
@@ -602,7 +608,11 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const handleSaveMergeDocument = useLockFn(async () => {
const mergeUid = option?.merge ?? ''
const currentValue = mergeDocument.value
if (!(await saveProfileFile(mergeUid, currentValue))) {
const result = await mutate(() => saveProfileFile(mergeUid, currentValue), {
id: `save-profile-file:${mergeUid}`,
errorNotice: false,
})
if (!(result.ok && result.value === true)) {
await mergeDocument.reload()
return
}
@@ -613,7 +623,14 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const handleSaveScriptDocument = useLockFn(async () => {
const scriptUid = option?.script ?? ''
const currentValue = scriptDocument.value
if (!(await saveProfileFile(scriptUid, currentValue))) {
const result = await mutate(
() => saveProfileFile(scriptUid, currentValue),
{
id: `save-profile-file:${scriptUid}`,
errorNotice: false,
},
)
if (!(result.ok && result.value === true)) {
await scriptDocument.reload()
return
}
+10 -2
View File
@@ -15,6 +15,7 @@ import { useTranslation } from 'react-i18next'
import { EditorViewer } from '@/components/profile/editor-viewer'
import { useEditorDocument } from '@/hooks/use-editor-document'
import { viewProfile, readProfileFile, saveProfileFile } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import { EnhanceHint } from './enhance-hint'
@@ -63,7 +64,10 @@ export const ProfileMore = (props: Props) => {
const onOpenFile = useLockFn(async () => {
setAnchorEl(null)
try {
await viewProfile(id)
await mutate(() => viewProfile(id), {
id: 'view-profile',
errorNotice: false,
})
} catch (err) {
showNotice.error(err)
}
@@ -96,7 +100,11 @@ export const ProfileMore = (props: Props) => {
const handleSave = useLockFn(async () => {
const currentValue = document.value
if (!(await saveProfileFile(id, currentValue))) {
const result = await mutate(() => saveProfileFile(id, currentValue), {
id: `save-profile-file:${id}`,
errorNotice: false,
})
if (!(result.ok && result.value === true)) {
await document.reload()
return
}
+35 -7
View File
@@ -17,6 +17,7 @@ import { useTranslation } from 'react-i18next'
import { BaseDialog, Switch } from '@/components/base'
import { useProfiles } from '@/hooks/use-profiles'
import { createProfile, patchProfile } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import { version } from '@root/package.json'
@@ -128,26 +129,38 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
if (!isRemote) {
if (openType === 'new') {
await createProfile(item, fileDataRef.current)
await mutate(() => createProfile(item, fileDataRef.current), {
id: 'create-profile',
errorNotice: false,
})
} else {
if (!form.uid) {
throw new Error(
t('profiles.modals.profileForm.errors.uidMissing'),
)
}
await patchProfile(form.uid, item)
await mutate(() => patchProfile(form.uid, item), {
id: 'patch-profile',
errorNotice: false,
})
}
} else {
try {
if (openType === 'new') {
await createProfile(item, fileDataRef.current)
await mutate(() => createProfile(item, fileDataRef.current), {
id: 'create-profile',
errorNotice: false,
})
} else {
if (!form.uid) {
throw new Error(
t('profiles.modals.profileForm.errors.uidMissing'),
)
}
await patchProfile(form.uid, item)
await mutate(() => patchProfile(form.uid, item), {
id: 'patch-profile',
errorNotice: false,
})
}
} catch {
showNotice.info(
@@ -164,16 +177,31 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
}
if (openType === 'new') {
await createProfile(retryItem, fileDataRef.current)
await mutate(
() => createProfile(retryItem, fileDataRef.current),
{
id: 'create-profile',
errorNotice: false,
},
)
} else {
if (!form.uid) {
throw new Error(
t('profiles.modals.profileForm.errors.uidMissing'),
)
}
await patchProfile(form.uid, retryItem)
await mutate(() => patchProfile(form.uid, retryItem), {
id: 'patch-profile',
errorNotice: false,
})
await patchProfile(form.uid, { option: originalOptions })
await mutate(
() => patchProfile(form.uid, { option: originalOptions }),
{
id: 'patch-profile',
errorNotice: false,
},
)
}
showNotice.success(
@@ -30,6 +30,7 @@ import { useTranslation } from 'react-i18next'
import { BaseSearchBox, MonacoEditor } from '@/components/base'
import { ProxyItem } from '@/components/profile/proxy-item'
import { readProfileFile, saveProfileFile } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import { useThemeMode } from '@/services/states'
import type { MonacoEditorInstance } from '@/types/monaco'
@@ -329,7 +330,11 @@ export const ProxiesEditorViewer = (props: Props) => {
const handleSave = useLockFn(async () => {
try {
if (!(await saveProfileFile(property, currData))) {
const result = await mutate(() => saveProfileFile(property, currData), {
id: `save-profile-file:${property}`,
errorNotice: false,
})
if (!(result.ok && result.value === true)) {
await fetchContent()
onClose()
return
@@ -32,6 +32,7 @@ import { useTranslation } from 'react-i18next'
import { BaseSearchBox, MonacoEditor, Switch } from '@/components/base'
import { RuleItem } from '@/components/profile/rule-item'
import { readProfileFile, saveProfileFile } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import { useThemeMode } from '@/services/states'
import type { TranslationKey } from '@/types/generated/i18n-keys'
@@ -570,7 +571,11 @@ export const RulesEditorViewer = (props: Props) => {
const handleSave = useLockFn(async () => {
try {
if (!(await saveProfileFile(property, currData))) {
const result = await mutate(() => saveProfileFile(property, currData), {
id: `save-profile-file:${property}`,
errorNotice: false,
})
if (!(result.ok && result.value === true)) {
await fetchContent()
onClose()
return
+17 -4
View File
@@ -24,6 +24,7 @@ import { updateProxyProvider } from 'tauri-plugin-mihomo-api'
import { useAppRefreshers, useProxiesData } from '@/providers/app-data-context'
import { syncRuntimeProviders } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import parseTraffic from '@/utils/parse-traffic'
@@ -57,10 +58,16 @@ export const ProviderButton = () => {
try {
setUpdating((prev) => ({ ...prev, [name]: true }))
await updateProxyProvider(name)
await mutate(() => updateProxyProvider(name), {
id: `update-proxy-provider-${name}`,
errorNotice: false,
})
await refreshProxy()
void syncRuntimeProviders()
void mutate(() => syncRuntimeProviders(), {
id: 'sync-runtime-providers',
errorNotice: false,
})
showNotice.success(
'proxies.feedback.notifications.provider.updateSuccess',
@@ -97,7 +104,10 @@ export const ProviderButton = () => {
for (const name of allProviders) {
try {
await updateProxyProvider(name)
await mutate(() => updateProxyProvider(name), {
id: `update-proxy-provider-${name}`,
errorNotice: false,
})
setUpdating((prev) => ({ ...prev, [name]: false }))
} catch (err) {
console.error(`更新 ${name} 失败`, err)
@@ -105,7 +115,10 @@ export const ProviderButton = () => {
}
await refreshProxy()
void syncRuntimeProviders()
void mutate(() => syncRuntimeProviders(), {
id: 'sync-runtime-providers',
errorNotice: false,
})
showNotice.success('proxies.feedback.notifications.provider.allUpdated')
} catch (err) {
+36 -7
View File
@@ -45,6 +45,7 @@ import { useRuntimeConfig } from '@/hooks/use-clash'
import { useRecordSelection } from '@/hooks/use-record-selection'
import { useAppRefreshers, useProxiesData } from '@/providers/app-data-context'
import { updateProxyChainConfigInRuntime } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import {
selectGlobalChainNodes,
selectRuleChainMembers,
@@ -444,7 +445,10 @@ export const ProxyChain = ({
if (isConnected) {
setIsConnecting(true)
try {
await updateProxyChainConfigInRuntime(null)
await mutate(() => updateProxyChainConfigInRuntime(null), {
id: 'update-proxy-chain-runtime',
errorNotice: false,
})
const targetGroup =
mode === 'global'
@@ -453,12 +457,22 @@ export const ProxyChain = ({
if (targetGroup) {
try {
await selectNodeForGroup(targetGroup, 'DIRECT')
await mutate(() => selectNodeForGroup(targetGroup, 'DIRECT'), {
id: 'select-proxy-node',
errorNotice: false,
})
recordSelection(targetGroup, 'DIRECT')
} catch {
if (currentProxyChain.length >= 1) {
try {
await selectNodeForGroup(targetGroup, currentProxyChain[0].name)
await mutate(
() =>
selectNodeForGroup(targetGroup, currentProxyChain[0].name),
{
id: 'select-proxy-node',
errorNotice: false,
},
)
recordSelection(targetGroup, currentProxyChain[0].name)
} catch {
// ignore
@@ -471,7 +485,10 @@ export const ProxyChain = ({
localStorage.removeItem('proxy-chain-exit-node')
localStorage.removeItem('proxy-chain-items')
await closeAllConnections()
await mutate(() => closeAllConnections(), {
id: 'close-all-connections',
errorNotice: false,
})
await refreshProxy()
onUpdateChain([])
@@ -502,7 +519,10 @@ export const ProxyChain = ({
// 第一步:保存链式代理配置
const chainProxies = currentProxyChain.map((node) => node.name)
debugLog('Saving chain config:', chainProxies)
await updateProxyChainConfigInRuntime(chainProxies)
await mutate(() => updateProxyChainConfigInRuntime(chainProxies), {
id: 'update-proxy-chain-runtime',
errorNotice: false,
})
debugLog('Chain configuration saved successfully')
// 第二步:连接到代理链的最后一个节点
@@ -516,7 +536,13 @@ export const ProxyChain = ({
const targetGroup = mode === 'global' ? 'GLOBAL' : selectedGroup
await selectNodeForGroup(targetGroup || 'GLOBAL', lastNode.name)
await mutate(
() => selectNodeForGroup(targetGroup || 'GLOBAL', lastNode.name),
{
id: 'select-proxy-node',
errorNotice: false,
},
)
// The chain moves the group like any other selection, so the profile has to learn about
// it: what the profile holds is what gets re-applied the next time the core starts.
recordSelection(targetGroup || 'GLOBAL', lastNode.name)
@@ -593,7 +619,10 @@ export const ProxyChain = ({
<IconButton
size="small"
onClick={() => {
updateProxyChainConfigInRuntime(null)
mutate(() => updateProxyChainConfigInRuntime(null), {
id: 'update-proxy-chain-runtime',
errorNotice: false,
})
localStorage.removeItem('proxy-chain-group')
localStorage.removeItem('proxy-chain-exit-node')
localStorage.removeItem('proxy-chain-items')
+7 -7
View File
@@ -4,11 +4,10 @@ import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router'
import { runStateQueryKey } from '@/hooks/use-system-state'
import { useSystemState } from '@/hooks/use-system-state'
import { useAppRefreshers } from '@/providers/app-data-context'
import { openLogsDir, restartCore } from '@/services/cmds'
import { showNotice } from '@/services/notice-service'
import { revalidateQuery } from '@/services/query-client'
import { mutate } from '@/services/mutate'
import type { ProxyEmptyStateReason } from './proxy-empty-state-model'
@@ -20,15 +19,16 @@ export const ProxyEmptyState = ({ reason }: Props) => {
const { t } = useTranslation()
const navigate = useNavigate()
const { refreshProxy } = useAppRefreshers()
const { mutateSystemState } = useSystemState()
const [isRestarting, setIsRestarting] = useState(false)
const handleRestart = useLockFn(async () => {
setIsRestarting(true)
try {
await restartCore()
await Promise.all([refreshProxy(), revalidateQuery(runStateQueryKey)])
} catch (error) {
showNotice.error(error)
await mutate(() => restartCore(), { id: 'restart-core' })
await Promise.all([refreshProxy(), mutateSystemState()])
} catch {
// the funnel already notified
} finally {
setIsRestarting(false)
}
+5 -1
View File
@@ -24,6 +24,7 @@ import { useTranslation } from 'react-i18next'
import { useProxiesData } from '@/providers/app-data-context'
import { updateProxyChainConfigInRuntime } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import {
isInteractableMember,
type ProxyGroupView,
@@ -404,7 +405,10 @@ export function ProxyGroupsChain(props: ProxyGroupsChainProps) {
handleGroupMenuClose()
if (mode === 'rule') {
updateProxyChainConfigInRuntime(null)
mutate(() => updateProxyChainConfigInRuntime(null), {
id: 'update-proxy-chain-runtime',
errorNotice: false,
})
localStorage.removeItem('proxy-chain-group')
localStorage.removeItem('proxy-chain-exit-node')
localStorage.removeItem('proxy-chain-items')
+17 -4
View File
@@ -23,6 +23,7 @@ import { updateRuleProvider } from 'tauri-plugin-mihomo-api'
import { useAppRefreshers, useRulesData } from '@/providers/app-data-context'
import { syncRuntimeProviders } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
const TypeBox = styled(Box)<{ component?: React.ElementType }>(({ theme }) => ({
@@ -50,11 +51,17 @@ export const ProviderButton = () => {
try {
setUpdating((prev) => ({ ...prev, [name]: true }))
await updateRuleProvider(name)
await mutate(() => updateRuleProvider(name), {
id: `update-rule-provider-${name}`,
errorNotice: false,
})
await refreshRules()
await refreshRuleProviders()
void syncRuntimeProviders()
void mutate(() => syncRuntimeProviders(), {
id: 'sync-runtime-providers',
errorNotice: false,
})
showNotice.success(
'rules.feedback.notifications.provider.updateSuccess',
@@ -91,7 +98,10 @@ export const ProviderButton = () => {
for (const name of allProviders) {
try {
await updateRuleProvider(name)
await mutate(() => updateRuleProvider(name), {
id: `update-rule-provider-${name}`,
errorNotice: false,
})
setUpdating((prev) => ({ ...prev, [name]: false }))
} catch (err) {
console.error(`更新 ${name} 失败`, err)
@@ -100,7 +110,10 @@ export const ProviderButton = () => {
await refreshRules()
await refreshRuleProviders()
void syncRuntimeProviders()
void mutate(() => syncRuntimeProviders(), {
id: 'sync-runtime-providers',
errorNotice: false,
})
showNotice.success('rules.feedback.notifications.provider.allUpdated')
} catch (err) {
@@ -15,6 +15,7 @@ import { useTranslation } from 'react-i18next'
import { useVerge } from '@/hooks/use-verge'
import { saveWebdavConfig, createWebdavBackup } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { errorDetail, showNotice } from '@/services/notice-service'
import {
buildWebdavSignature,
@@ -119,7 +120,13 @@ export const BackupConfigViewer = memo(
try {
setLoading(true)
await saveWebdavConfig(trimmedUrl, trimmedUsername, data.password)
await mutate(
() => saveWebdavConfig(trimmedUrl, trimmedUsername, data.password),
{
id: 'save-webdav-config',
errorNotice: false,
},
)
await mutateVerge(
(current) =>
current
@@ -156,7 +163,10 @@ export const BackupConfigViewer = memo(
try {
setLoading(true)
await createWebdavBackup().then(async () => {
await mutate(() => createWebdavBackup(), {
id: 'create-webdav-backup',
errorNotice: false,
}).then(async () => {
showNotice.success('settings.modals.backup.messages.backupCreated')
await onBackupSuccess()
})
@@ -35,6 +35,7 @@ import {
restoreLocalBackup,
restoreWebDavBackup,
} from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import {
buildWebdavSignature,
@@ -228,17 +229,29 @@ export const BackupHistoryViewer = ({
try {
if (action === 'delete') {
if (actionIsLocal) {
await deleteLocalBackup(filename)
await mutate(() => deleteLocalBackup(filename), {
id: 'delete-local-backup',
errorNotice: false,
})
} else {
await deleteWebdavBackup(filename)
await mutate(() => deleteWebdavBackup(filename), {
id: 'delete-webdav-backup',
errorNotice: false,
})
}
setPendingConfirmation(null)
await fetchRows()
} else {
if (actionIsLocal) {
await restoreLocalBackup(filename)
await mutate(() => restoreLocalBackup(filename), {
id: 'restore-local-backup',
errorNotice: false,
})
} else {
await restoreWebDavBackup(filename)
await mutate(() => restoreWebDavBackup(filename), {
id: 'restore-webdav-backup',
errorNotice: false,
})
}
setPendingConfirmation(null)
showNotice.success('settings.modals.backup.messages.restoreSuccess')
@@ -265,8 +278,11 @@ export const BackupHistoryViewer = ({
const savePath = await save({ defaultPath: filename })
if (!savePath || Array.isArray(savePath)) return
try {
await exportLocalBackup(filename, savePath)
showNotice.success('settings.modals.backup.messages.localBackupExported')
await mutate(() => exportLocalBackup(filename, savePath), {
id: 'export-local-backup',
errorNotice: false,
successNotice: 'settings.modals.backup.messages.localBackupExported',
})
} catch (ignoreError: unknown) {
showNotice.error(
'settings.modals.backup.messages.localBackupExportFailed',
+17 -7
View File
@@ -19,6 +19,7 @@ import {
createWebdavBackup,
importLocalBackup,
} from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { errorDetail, showNotice } from '@/services/notice-service'
import { buildWebdavSignature, setWebdavStatus } from '@/services/webdav-status'
@@ -55,12 +56,18 @@ export function BackupViewer({ ref }: { ref?: Ref<DialogRef> }) {
try {
setBusyAction(target)
if (target === 'local') {
await createLocalBackup()
showNotice.success('settings.modals.backup.messages.localBackupCreated')
await mutate(() => createLocalBackup(), {
id: 'create-local-backup',
errorNotice: false,
successNotice: 'settings.modals.backup.messages.localBackupCreated',
})
} else {
await createWebdavBackup()
showNotice.success('settings.modals.backup.messages.backupCreated')
setWebdavStatus(webdavSignature, 'ready')
await mutate(() => createWebdavBackup(), {
id: 'create-webdav-backup',
errorNotice: false,
successNotice: 'settings.modals.backup.messages.backupCreated',
onFulfilled: () => setWebdavStatus(webdavSignature, 'ready'),
})
}
} catch (error) {
console.error(error)
@@ -86,8 +93,11 @@ export function BackupViewer({ ref }: { ref?: Ref<DialogRef> }) {
if (!selected || Array.isArray(selected)) return
try {
setLocalImporting(true)
await importLocalBackup(selected)
showNotice.success('settings.modals.backup.messages.localBackupImported')
await mutate(() => importLocalBackup(selected), {
id: 'import-local-backup',
errorNotice: false,
successNotice: 'settings.modals.backup.messages.localBackupImported',
})
openHistory('local')
} catch (error) {
console.error(error)
@@ -21,6 +21,7 @@ import { BaseDialog, DialogRef } from '@/components/base'
import { useClash, useClashInfo } from '@/hooks/use-clash'
import { useVerge } from '@/hooks/use-verge'
import { changeClashCore, restartCore, upgradeClashCore } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
const VALID_CORE = [
@@ -60,8 +61,16 @@ export function ClashCoreViewer({ ref }: { ref?: Ref<DialogRef> }) {
try {
setChangingCore(core)
closeAllConnections()
const errorMsg = await changeClashCore(core)
void mutate(() => closeAllConnections(), {
id: 'close-all-connections',
errorNotice: false,
})
const result = await mutate(() => changeClashCore(core), {
id: 'change-clash-core',
errorNotice: false,
})
if (!result.ok) return
const errorMsg = result.value
if (errorMsg) {
showNotice.error(errorMsg)
@@ -83,28 +92,33 @@ export function ClashCoreViewer({ ref }: { ref?: Ref<DialogRef> }) {
const onRestart = useLockFn(async () => {
try {
setRestarting(true)
await restartCore()
showNotice.success(
t('settings.feedback.notifications.clash.restartSuccess'),
)
await mutate(() => restartCore(), {
id: 'restart-core',
successNotice: t(
'settings.feedback.notifications.clash.restartSuccess',
),
})
setRestarting(false)
} catch (err) {
} catch {
setRestarting(false)
showNotice.error(err)
}
})
const onUpgrade = useLockFn(async () => {
try {
setUpgrading(true)
const report = await upgradeClashCore()
showNotice.success(
report.upgraded
? t('settings.feedback.notifications.clash.versionUpdated')
: t('settings.feedback.notifications.clash.alreadyLatestVersion'),
)
} catch (err) {
showNotice.error(err)
await mutate(() => upgradeClashCore(), {
id: 'upgrade-clash-core',
onFulfilled: (report) => {
showNotice.success(
report.upgraded
? t('settings.feedback.notifications.clash.versionUpdated')
: t('settings.feedback.notifications.clash.alreadyLatestVersion'),
)
},
})
} catch {
// the funnel already notified
} finally {
setUpgrading(false)
}
@@ -15,7 +15,8 @@ import { useTranslation } from 'react-i18next'
import { BaseDialog, Switch } from '@/components/base'
import { useDisplayedMixedPort } from '@/hooks/use-displayed-mixed-port'
import { useVerge } from '@/hooks/use-verge'
import { saveProxyPorts } from '@/services/cmds'
import { saveProxyPorts, type ProxyPortSettings } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import getSystem from '@/utils/get-system'
@@ -57,22 +58,31 @@ export const ClashPortViewer = forwardRef<ClashPortViewerRef>((_, ref) => {
)
// 添加保存请求,防止GUI卡死
const { loading, runAsync: saveSettings } = useRequest(saveProxyPorts, {
manual: true,
onSuccess: (outcome) => {
if (outcome.status === 'conflict') {
showNotice.error('settings.modals.clashPort.messages.portInUse', {
port: outcome.port,
})
return
}
setOpen(false)
showNotice.success('settings.modals.clashPort.messages.saved')
const { loading, runAsync: saveSettings } = useRequest(
async (settings: ProxyPortSettings) =>
mutate(() => saveProxyPorts(settings), {
id: 'save-proxy-ports',
errorNotice: false,
}),
{
manual: true,
onSuccess: (result) => {
if (!result.ok) return
const outcome = result.value
if (outcome.status === 'conflict') {
showNotice.error('settings.modals.clashPort.messages.portInUse', {
port: outcome.port,
})
return
}
setOpen(false)
showNotice.success('settings.modals.clashPort.messages.saved')
},
onError: (error) => {
showNotice.error('settings.modals.clashPort.messages.saveFailed', error)
},
},
onError: (error) => {
showNotice.error('settings.modals.clashPort.messages.saveFailed', error)
},
})
)
useImperativeHandle(ref, () => ({
open: () => {
+10 -11
View File
@@ -13,7 +13,6 @@ import {
TextField,
Typography,
} from '@mui/material'
import { invoke } from '@tauri-apps/api/core'
import { useLockFn } from 'ahooks'
import * as yaml from 'js-yaml'
import type { Ref } from 'react'
@@ -36,6 +35,12 @@ import {
import { useClash } from '@/hooks/use-clash'
import { useProfiles } from '@/hooks/use-profiles'
import { useVerge } from '@/hooks/use-verge'
import {
applyDnsConfig,
getDnsConfigContent,
saveDnsConfig,
validateDnsConfig,
} from '@/services/cmds'
import { showNotice } from '@/services/notice-service'
import { useThemeMode } from '@/services/states'
import type { MonacoEditorInstance } from '@/types/monaco'
@@ -465,10 +470,7 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
const initDnsConfig = useCallback(async () => {
try {
const dnsConfig = await invoke<string | null>(
'get_dns_config_content',
{},
)
const dnsConfig = await getDnsConfigContent()
if (dnsConfig !== null) {
const config = yaml.load(dnsConfig) as any
@@ -517,12 +519,9 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
config = parsedConfig as Record<string, any>
}
await invoke('save_dns_config', { dnsConfig: config })
await saveDnsConfig(config)
const validation = await invoke<ValidationOutcome>(
'validate_dns_config',
{},
)
const validation = await validateDnsConfig()
if (validation.status !== 'valid') {
const errorMsg =
@@ -559,7 +558,7 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
}
if (dnsEnabled) {
await invoke('apply_dns_config', { apply: true })
await applyDnsConfig(true)
mutateClash()
}
@@ -7,6 +7,7 @@ import { useTranslation } from 'react-i18next'
import { BaseDialog, Switch } from '@/components/base'
import { useClash } from '@/hooks/use-clash'
import { restartCore } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
// Development origins must never be persisted into production configuration.
@@ -135,7 +136,10 @@ export const HeaderConfiguration = forwardRef<ClashHeaderConfigingRef>(
),
},
})
await restartCore()
await mutate(() => restartCore(), {
id: 'restart-core',
errorNotice: false,
})
await mutateClash()
},
{
@@ -14,6 +14,7 @@ import { useTranslation } from 'react-i18next'
import { BaseDialog, DialogRef, Switch, TooltipIcon } from '@/components/base'
import { useVerge } from '@/hooks/use-verge'
import { entry_lightweight_mode } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
export function LiteModeViewer({ ref }: { ref?: Ref<DialogRef> }) {
@@ -72,7 +73,12 @@ export function LiteModeViewer({ ref }: { ref?: Ref<DialogRef> }) {
color: 'primary.main',
'&:hover': { textDecoration: 'underline' },
}}
onClick={async () => await entry_lightweight_mode()}
onClick={async () =>
await mutate(() => entry_lightweight_mode(), {
id: 'entry-lightweight-mode',
errorNotice: false,
})
}
>
{t('shared.actions.enable')}
</Typography>
+5 -1
View File
@@ -21,6 +21,7 @@ import {
} from '@/components/base'
import { useClash } from '@/hooks/use-clash'
import { enhanceProfiles } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import getSystem from '@/utils/get-system'
import { areValidIpCidrs } from '@/utils/network'
@@ -129,7 +130,10 @@ export function TunViewer({ ref }: { ref?: Ref<DialogRef> }) {
)
setOpen(false)
showNotice.success('settings.modals.tun.messages.applied')
void enhanceProfiles().catch((err: any) => {
void mutate(() => enhanceProfiles(), {
id: 'enhance-profiles',
errorNotice: false,
}).catch((err: any) => {
showNotice.error(err)
})
} catch (err: any) {
@@ -16,6 +16,7 @@ import type { Options as ReactMarkdownOptions } from 'react-markdown'
import { BaseDialog, DialogRef } from '@/components/base'
import { useUpdate } from '@/hooks/use-update'
import { restartApp } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import { useSetUpdateState, useUpdateState } from '@/services/states'
import { openExternalUrl } from '@/utils/open-external-url'
@@ -270,8 +271,14 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
}
try {
await updateInfo.downloadAndInstall(onDownloadEvent)
await restartApp()
await mutate(() => updateInfo.downloadAndInstall(onDownloadEvent), {
id: 'install-app-update',
errorNotice: false,
})
await mutate(() => restartApp(), {
id: 'restart-app',
errorNotice: false,
})
} catch (err: any) {
showNotice.error(err)
} finally {
+14 -2
View File
@@ -12,6 +12,7 @@ import { useDisplayedMixedPort } from '@/hooks/use-displayed-mixed-port'
import { useProfiles } from '@/hooks/use-profiles'
import { useVerge } from '@/hooks/use-verge'
import { invoke_uwp_tool, setDnsOverride } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import getSystem from '@/utils/get-system'
@@ -74,7 +75,10 @@ const SettingClash = ({ onError }: Props) => {
}
const onUpdateGeo = async () => {
try {
await updateGeo()
await mutate(() => updateGeo(), {
id: 'update-geo',
errorNotice: false,
})
showNotice.success('settings.feedback.notifications.clash.geoDataUpdated')
} catch (err: any) {
showNotice.error(err)
@@ -90,7 +94,15 @@ const SettingClash = ({ onError }: Props) => {
if (!profileUid) return
setDnsUpdating(true)
try {
const outcome = await setDnsOverride(profileUid, enable, confirmation)
const result = await mutate(
() => setDnsOverride(profileUid, enable, confirmation),
{
id: 'set-dns-override',
errorNotice: false,
},
)
if (!result.ok) return
const outcome = result.value
if (outcome.status === 'confirmation_required') {
setDnsConfirmation({ profileUid, source: outcome.source })
} else {
@@ -13,6 +13,7 @@ import {
openDevTools,
openLogsDir,
} from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import { checkUpdateSafe as checkUpdate } from '@/services/update'
import { version } from '@root/package.json'
@@ -61,7 +62,10 @@ const SettingVergeAdvanced = ({ onError: _ }: Props) => {
}
const onExportDiagnosticInfo = useCallback(async () => {
await exportDiagnosticInfo()
await mutate(() => exportDiagnosticInfo(), {
id: 'export-diagnostic-info',
errorNotice: false,
})
showNotice.success('shared.feedback.notifications.common.copySuccess', 1000)
}, [])
@@ -128,7 +132,12 @@ const SettingVergeAdvanced = ({ onError: _ }: Props) => {
/>
<SettingItem
onClick={openDevTools}
onClick={() => {
void mutate(() => openDevTools(), {
id: 'open-devtools',
errorNotice: false,
}).catch(() => {})
}}
label={t('settings.components.verge.advanced.fields.openDevTools')}
/>
@@ -145,7 +154,10 @@ const SettingVergeAdvanced = ({ onError: _ }: Props) => {
<SettingItem
onClick={() => {
exitApp()
void mutate(() => exitApp(), {
id: 'exit-app',
errorNotice: false,
}).catch(() => {})
}}
label={t('settings.components.verge.advanced.fields.exit')}
/>
+15 -6
View File
@@ -1,15 +1,15 @@
import { LanguageRounded } from '@mui/icons-material'
import { Box, Divider, MenuItem, Menu, styled, alpha } from '@mui/material'
import { useLockFn } from 'ahooks'
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { BaseLoading } from '@/components/base'
import { useIconCache } from '@/hooks/use-icon-cache'
import { cmdTestDelay } from '@/services/cmds'
import delayManager from '@/services/delay'
import { subscribeVergeEvents } from '@/services/events'
import { showNotice } from '@/services/notice-service'
import { useTestAllCounter } from '@/store/app-store-context'
import { TestBox } from './test-box'
@@ -52,10 +52,19 @@ export const TestItem = ({ itemData, onEdit, onDelete: removeTest }: Props) => {
{ label: t('shared.actions.delete'), handler: onDelete },
]
useEffect(
() => subscribeVergeEvents({ 'verge://test-all': () => onDelay() }),
[url, onDelay],
)
// Store bump replaces the per-item event subscription; skip the initial
// mount value and call through a ref so url changes do not re-trigger tests.
const testAllCounter = useTestAllCounter()
const onDelayRef = useRef(onDelay)
onDelayRef.current = onDelay
const mountedRef = useRef(false)
useEffect(() => {
if (!mountedRef.current) {
mountedRef.current = true
return
}
void onDelayRef.current()
}, [testAllCounter])
return (
<Box>
+11 -5
View File
@@ -8,6 +8,7 @@ import {
getRuntimeConfig,
patchClashConfig,
} from '@/services/cmds'
import { mutate } from '@/services/mutate'
import {
revalidateQuery,
setCacheData,
@@ -104,8 +105,11 @@ export const useClash = () => {
}
const patchClash = useLockFn(async (patch: Partial<IConfigData>) => {
await patchClashConfig(patch)
mutateClash()
await mutate(() => patchClashConfig(patch), {
id: 'patch-clash-config',
revalidate: [['getRuntimeConfig']],
errorNotice: false,
})
})
const version = versionData?.meta
@@ -132,9 +136,11 @@ export const useClashInfo = () => {
validatePorts(patch)
await patchClashConfig(patch)
mutateInfo()
revalidateQuery(['getClashConfig'])
await mutate(() => patchClashConfig(patch), {
id: 'patch-clash-info',
revalidate: [['getClashInfo'], ['getClashConfig']],
errorNotice: false,
})
})
const invalidateClashConfig = () => revalidateQuery(['getClashConfig'])
-15
View File
@@ -1,15 +0,0 @@
import { listen, EventCallback } from '@tauri-apps/api/event'
import { useCallback } from 'react'
export const useListen = () => {
const addListener = useCallback(
async <T>(eventName: string, handler: EventCallback<T>) => {
return await listen(eventName, handler)
},
[],
)
return {
addListener,
}
}
+18 -15
View File
@@ -1,18 +1,12 @@
import { useCallback, useRef } from 'react'
import { getProfiles, patchProfile, patchProfilesConfig } from '@/services/cmds'
import {
fetchCacheData,
revalidateQuery,
setCacheData,
useQuery,
} from '@/services/query-client'
import { mutate } from '@/services/mutate'
import { fetchCacheData, setCacheData, useQuery } from '@/services/query-client'
import { debugLog } from '@/utils/debug'
const profilesQueryKey = ['getProfiles'] as const
export const revalidateProfiles = () => revalidateQuery(profilesQueryKey)
export const fetchProfilesIntoCache = () =>
fetchCacheData(profilesQueryKey, getProfiles)
@@ -49,16 +43,25 @@ export const useProfiles = () => {
const patchProfiles = useCallback(
async (value: Partial<IProfilesConfig>) => {
try {
const outcome = await patchProfilesConfig(value)
const result = await mutate(() => patchProfilesConfig(value), {
id: 'patch-profiles-config',
onFulfilled: (outcome) => {
if (outcome.status === 'valid') {
void setCacheData<IProfilesConfig>(profilesQueryKey, (current) =>
current ? { ...current, ...value } : current,
)
}
},
})
if (outcome.status === 'valid') {
await setCacheData<IProfilesConfig>(profilesQueryKey, (current) =>
current ? { ...current, ...value } : current,
)
} else if (outcome.status !== 'busy') {
if (!result.ok) {
// Backend Busy keeps local state untouched, as before.
return result.value ?? { status: 'busy' }
}
const outcome = result.value
if (outcome.status !== 'valid' && outcome.status !== 'busy') {
await mutateProfiles()
}
return outcome
} catch (error) {
await mutateProfiles()
+13 -3
View File
@@ -12,6 +12,7 @@ import {
} from '@/hooks/use-record-selection'
import { useVerge } from '@/hooks/use-verge'
import { syncTrayProxySelection } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { debugLog } from '@/utils/debug'
// 缓存连接清理
@@ -58,7 +59,10 @@ export const useProxySelection = (options: ProxySelectionOptions = {}) => {
// 切换节点
const syncTraySelection = useCallback(() => {
syncTrayProxySelection().catch((error) => {
mutate(() => syncTrayProxySelection(), {
id: 'sync-tray-selection',
errorNotice: false,
}).catch((error) => {
console.error('[ProxySelection] 托盘状态同步失败:', error)
})
}, [])
@@ -75,9 +79,15 @@ export const useProxySelection = (options: ProxySelectionOptions = {}) => {
try {
if (isFixedProxy) {
await unfixedProxy(groupName)
await mutate(() => unfixedProxy(groupName), {
id: 'select-proxy-node',
errorNotice: false,
})
} else {
await selectNodeForGroup(groupName, proxyName)
await mutate(() => selectNodeForGroup(groupName, proxyName), {
id: 'select-proxy-node',
errorNotice: false,
})
}
onSuccess?.()
syncTraySelection()

Some files were not shown because too many files have changed in this diff Show More