mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-05 05:50:04 +08:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74b815db59 | ||
|
|
e2ae9feb2a | ||
|
|
99def2004b | ||
|
|
084f8d36a7 | ||
|
|
112c5f0e13 | ||
|
|
0cba206e13 | ||
|
|
72c3653a8a | ||
|
|
6f81fb91b3 | ||
|
|
c6c963e9da | ||
|
|
287752daff |
@@ -265,14 +265,6 @@ jobs:
|
|||||||
node-version: '26.14.0'
|
node-version: '26.14.0'
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
|
|
||||||
- name: Pnpm install and check
|
|
||||||
run: |
|
|
||||||
pnpm i
|
|
||||||
pnpm run prebuild ${{ matrix.target }}
|
|
||||||
|
|
||||||
- name: Release ${{ env.TAG_CHANNEL }} Version
|
|
||||||
run: pnpm release-version autobuild-latest
|
|
||||||
|
|
||||||
- name: 'Setup for linux'
|
- name: 'Setup for linux'
|
||||||
run: |-
|
run: |-
|
||||||
sudo ls -lR /etc/apt/
|
sudo ls -lR /etc/apt/
|
||||||
@@ -317,6 +309,14 @@ jobs:
|
|||||||
gcc-arm-linux-gnueabihf \
|
gcc-arm-linux-gnueabihf \
|
||||||
g++-arm-linux-gnueabihf
|
g++-arm-linux-gnueabihf
|
||||||
|
|
||||||
|
- name: Pnpm install and check
|
||||||
|
run: |
|
||||||
|
pnpm i
|
||||||
|
pnpm run prebuild ${{ matrix.target }}
|
||||||
|
|
||||||
|
- name: Release ${{ env.TAG_CHANNEL }} Version
|
||||||
|
run: pnpm release-version autobuild-latest
|
||||||
|
|
||||||
- name: Tauri Build for Linux
|
- name: Tauri Build for Linux
|
||||||
run: |
|
run: |
|
||||||
export PKG_CONFIG_ALLOW_CROSS=1
|
export PKG_CONFIG_ALLOW_CROSS=1
|
||||||
|
|||||||
@@ -107,6 +107,14 @@ jobs:
|
|||||||
node-version: '26.14.0'
|
node-version: '26.14.0'
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
|
|
||||||
|
- name: Add Rust Target
|
||||||
|
if: github.event.inputs[matrix.input] == 'true'
|
||||||
|
run: |
|
||||||
|
# Ensure cross target is installed for the pinned toolchain; fallback without explicit toolchain if needed
|
||||||
|
rustup target add ${{ matrix.target }} --toolchain 1.100.1 || rustup target add ${{ matrix.target }}
|
||||||
|
rustup target list --installed
|
||||||
|
echo "Rust target ${{ matrix.target }} installed."
|
||||||
|
|
||||||
- name: Pnpm install and check
|
- name: Pnpm install and check
|
||||||
if: github.event.inputs[matrix.input] == 'true'
|
if: github.event.inputs[matrix.input] == 'true'
|
||||||
run: |
|
run: |
|
||||||
@@ -117,14 +125,6 @@ jobs:
|
|||||||
if: github.event.inputs[matrix.input] == 'true'
|
if: github.event.inputs[matrix.input] == 'true'
|
||||||
run: pnpm release-version ${{ env.TAG_NAME }}
|
run: pnpm release-version ${{ env.TAG_NAME }}
|
||||||
|
|
||||||
- name: Add Rust Target
|
|
||||||
if: github.event.inputs[matrix.input] == 'true'
|
|
||||||
run: |
|
|
||||||
# Ensure cross target is installed for the pinned toolchain; fallback without explicit toolchain if needed
|
|
||||||
rustup target add ${{ matrix.target }} --toolchain 1.100.1 || rustup target add ${{ matrix.target }}
|
|
||||||
rustup target list --installed
|
|
||||||
echo "Rust target ${{ matrix.target }} installed."
|
|
||||||
|
|
||||||
- name: Tauri build
|
- name: Tauri build
|
||||||
if: github.event.inputs[matrix.input] == 'true'
|
if: github.event.inputs[matrix.input] == 'true'
|
||||||
uses: tauri-apps/tauri-action@v1
|
uses: tauri-apps/tauri-action@v1
|
||||||
|
|||||||
@@ -333,11 +333,6 @@ jobs:
|
|||||||
node-version: '26.14.0'
|
node-version: '26.14.0'
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
|
|
||||||
- name: Pnpm install and check
|
|
||||||
run: |
|
|
||||||
pnpm i
|
|
||||||
pnpm run prebuild ${{ matrix.target }}
|
|
||||||
|
|
||||||
- name: 'Setup for linux'
|
- name: 'Setup for linux'
|
||||||
run: |-
|
run: |-
|
||||||
sudo ls -lR /etc/apt/
|
sudo ls -lR /etc/apt/
|
||||||
@@ -382,6 +377,11 @@ jobs:
|
|||||||
gcc-arm-linux-gnueabihf \
|
gcc-arm-linux-gnueabihf \
|
||||||
g++-arm-linux-gnueabihf
|
g++-arm-linux-gnueabihf
|
||||||
|
|
||||||
|
- name: Pnpm install and check
|
||||||
|
run: |
|
||||||
|
pnpm i
|
||||||
|
pnpm run prebuild ${{ matrix.target }}
|
||||||
|
|
||||||
- name: Build for Linux
|
- name: Build for Linux
|
||||||
run: |
|
run: |
|
||||||
export PKG_CONFIG_ALLOW_CROSS=1
|
export PKG_CONFIG_ALLOW_CROSS=1
|
||||||
|
|||||||
Generated
+4
-14
@@ -1342,8 +1342,8 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "clash_verge_service_ipc"
|
name = "clash_verge_service_ipc"
|
||||||
version = "2.8.2"
|
version = "2.8.3"
|
||||||
source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?branch=main#3e06ff153e9cb19ae20e0a61f861b371d3f7b2aa"
|
source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?rev=fd00f5af2363517e67de57a7ead67737175ac376#fd00f5af2363517e67de57a7ead67737175ac376"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"kode-bridge",
|
"kode-bridge",
|
||||||
@@ -3995,9 +3995,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "kode-bridge"
|
name = "kode-bridge"
|
||||||
version = "0.6.0"
|
version = "0.6.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b17456ae84ba9c0da0f189bf00d13019805b89563ba846cd15ccd8c4bd6a2713"
|
checksum = "e125a6b7f2e7ce5d560ce9517083e27549345a6492ca68194cd96b42e3b27acb"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytes",
|
"bytes",
|
||||||
"futures",
|
"futures",
|
||||||
@@ -4005,7 +4005,6 @@ dependencies = [
|
|||||||
"httparse",
|
"httparse",
|
||||||
"libc",
|
"libc",
|
||||||
"parking_lot 0.13.0",
|
"parking_lot 0.13.0",
|
||||||
"path-tree",
|
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
"rand 0.10.2",
|
"rand 0.10.2",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -5157,15 +5156,6 @@ version = "0.2.3"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
|
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "path-tree"
|
|
||||||
version = "0.8.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "c2a97453bc21a968f722df730bfe11bd08745cb50d1300b0df2bda131dece136"
|
|
||||||
dependencies = [
|
|
||||||
"smallvec",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pathsearch"
|
name = "pathsearch"
|
||||||
version = "0.2.0"
|
version = "0.2.0"
|
||||||
|
|||||||
+1
-1
@@ -74,7 +74,7 @@ clash-verge-runtime-bundle = { path = "crates/clash-verge-runtime-bundle" }
|
|||||||
clash-verge-proxy-view = { path = "crates/clash-verge-proxy-view" }
|
clash-verge-proxy-view = { path = "crates/clash-verge-proxy-view" }
|
||||||
clash-verge-profile = { path = "crates/clash-verge-profile" }
|
clash-verge-profile = { path = "crates/clash-verge-profile" }
|
||||||
clash-verge-backup-archive = { path = "crates/clash-verge-backup-archive" }
|
clash-verge-backup-archive = { path = "crates/clash-verge-backup-archive" }
|
||||||
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", default-features = false }
|
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", rev = "fd00f5af2363517e67de57a7ead67737175ac376", version = "2.8.3", default-features = false }
|
||||||
tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" }
|
tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" }
|
||||||
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
|
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
|
||||||
tracing = "0.1.44"
|
tracing = "0.1.44"
|
||||||
|
|||||||
@@ -23,6 +23,7 @@
|
|||||||
GitHub, so they never reach users. -->
|
GitHub, so they never reach users. -->
|
||||||
## v2.6.0
|
## v2.6.0
|
||||||
|
|
||||||
|
- 使用 2.6.x 服务模式时请安装随附的服务,2.5.x 客户端无法使用新版服务
|
||||||
- **Mihomo 内核升级至 v1.19.34**
|
- **Mihomo 内核升级至 v1.19.34**
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
@@ -49,6 +50,7 @@
|
|||||||
|
|
||||||
**🖥️ Windows**
|
**🖥️ Windows**
|
||||||
|
|
||||||
|
- 修复 Windows 服务启动失败后自动切换内核,现显示原因并等待用户选择
|
||||||
- 修复 Windows 普通用户因权限不足无法开启「开机自启」
|
- 修复 Windows 普通用户因权限不足无法开启「开机自启」
|
||||||
|
|
||||||
**🍎 macOS**
|
**🍎 macOS**
|
||||||
|
|||||||
+20
-17
@@ -9,7 +9,7 @@ import AdmZip from 'adm-zip'
|
|||||||
import { HttpsProxyAgent } from 'https-proxy-agent'
|
import { HttpsProxyAgent } from 'https-proxy-agent'
|
||||||
import { extract } from 'tar'
|
import { extract } from 'tar'
|
||||||
|
|
||||||
import { resolveServiceRelease } from './service-release.mjs'
|
import { resolveServiceBundle as serviceBundleFromMetadata } from './service-release.mjs'
|
||||||
import { log_debug, log_error, log_info, log_success } from './utils.mjs'
|
import { log_debug, log_error, log_info, log_success } from './utils.mjs'
|
||||||
|
|
||||||
/** Prepares platform resources, caching versions and unchanged files unless `--force` is used. */
|
/** Prepares platform resources, caching versions and unchanged files unless `--force` is used. */
|
||||||
@@ -581,23 +581,30 @@ async function resolveServiceBundle() {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
const cargoManifest = await fsp.readFile(
|
const metadata = JSON.parse(
|
||||||
path.join(cwd, 'src-tauri', 'Cargo.toml'),
|
execFileSync(
|
||||||
'utf8',
|
'cargo',
|
||||||
|
[
|
||||||
|
'metadata',
|
||||||
|
'--locked',
|
||||||
|
'--format-version',
|
||||||
|
'1',
|
||||||
|
'--filter-platform',
|
||||||
|
SIDECAR_HOST,
|
||||||
|
],
|
||||||
|
{ cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },
|
||||||
|
),
|
||||||
)
|
)
|
||||||
const serviceDependency = cargoManifest
|
const bundle = serviceBundleFromMetadata(metadata, SIDECAR_HOST, platform)
|
||||||
.split(/\r?\n/)
|
if (bundle.manifest) {
|
||||||
.find((line) => line.trimStart().startsWith('clash_verge_service_ipc ='))
|
|
||||||
const sourcePath = serviceDependency?.match(/\bpath\s*=\s*"([^"]+)"/)?.[1]
|
|
||||||
if (sourcePath) {
|
|
||||||
const manifest = path.resolve(cwd, 'src-tauri', sourcePath, 'Cargo.toml')
|
|
||||||
const targetDirectory = path.join(cwd, 'target', 'bundled-service')
|
const targetDirectory = path.join(cwd, 'target', 'bundled-service')
|
||||||
execFileSync(
|
execFileSync(
|
||||||
'cargo',
|
'cargo',
|
||||||
[
|
[
|
||||||
'build',
|
'build',
|
||||||
|
'--locked',
|
||||||
'--manifest-path',
|
'--manifest-path',
|
||||||
manifest,
|
bundle.manifest,
|
||||||
'--target-dir',
|
'--target-dir',
|
||||||
targetDirectory,
|
targetDirectory,
|
||||||
'--target',
|
'--target',
|
||||||
@@ -605,7 +612,7 @@ async function resolveServiceBundle() {
|
|||||||
'--release',
|
'--release',
|
||||||
'--features',
|
'--features',
|
||||||
'standalone,client',
|
'standalone,client',
|
||||||
'--bins',
|
...SERVICE_BINARIES.flatMap((name) => ['--bin', name]),
|
||||||
],
|
],
|
||||||
{ stdio: 'inherit' },
|
{ stdio: 'inherit' },
|
||||||
)
|
)
|
||||||
@@ -620,11 +627,7 @@ async function resolveServiceBundle() {
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const { archiveFile, downloadURL } = resolveServiceRelease(
|
const { archiveFile, downloadURL } = bundle
|
||||||
cargoManifest,
|
|
||||||
SIDECAR_HOST,
|
|
||||||
platform,
|
|
||||||
)
|
|
||||||
const tempDir = path.join(TEMP_DIR, 'clash-verge-service-ipc')
|
const tempDir = path.join(TEMP_DIR, 'clash-verge-service-ipc')
|
||||||
const tempArchive = path.join(tempDir, archiveFile)
|
const tempArchive = path.join(tempDir, archiveFile)
|
||||||
|
|
||||||
|
|||||||
+24
-11
@@ -1,22 +1,35 @@
|
|||||||
const SERVICE_URL_PREFIX =
|
const SERVICE_URL_PREFIX =
|
||||||
'https://github.com/clash-verge-rev/clash-verge-service-ipc/releases/download'
|
'https://github.com/clash-verge-rev/clash-verge-service-ipc/releases/download'
|
||||||
|
|
||||||
export function resolveServiceRelease(cargoManifest, host, platform) {
|
export function resolveServiceBundle(metadata, host, platform) {
|
||||||
const dependency = cargoManifest
|
const app = metadata.packages.find(
|
||||||
.split(/\r?\n/)
|
(pkg) =>
|
||||||
.find((line) => line.trimStart().startsWith('clash_verge_service_ipc ='))
|
pkg.name === 'clash-verge' && metadata.workspace_members.includes(pkg.id),
|
||||||
const packageVersion = dependency?.match(/\bversion\s*=\s*"([^"]+)"/)?.[1]
|
)
|
||||||
if (!packageVersion) {
|
const dependency = app?.dependencies.find(
|
||||||
throw new Error(
|
(dep) => dep.name === 'clash_verge_service_ipc',
|
||||||
'clash_verge_service_ipc dependency must declare an inline version',
|
)
|
||||||
)
|
const edge = metadata.resolve.nodes
|
||||||
|
.find((node) => node.id === app?.id)
|
||||||
|
?.deps.find((dep) => dep.name === 'clash_verge_service_ipc')
|
||||||
|
const service = metadata.packages.find((pkg) => pkg.id === edge?.pkg)
|
||||||
|
if (!service || !dependency) {
|
||||||
|
throw new Error('Cargo did not resolve the desktop IPC client dependency')
|
||||||
|
}
|
||||||
|
if (!service.source || new URL(service.source).searchParams.has('rev')) {
|
||||||
|
return { manifest: service.manifest_path }
|
||||||
}
|
}
|
||||||
|
|
||||||
const version = `v${packageVersion}`
|
const declared = dependency.req.replace(/^[=^]/, '')
|
||||||
|
if (declared !== service.version) {
|
||||||
|
throw new Error(
|
||||||
|
`Service release version ${declared} differs from the resolved IPC client ${service.version}`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
const version = `v${declared}`
|
||||||
const archiveExt = platform === 'win32' ? 'zip' : 'tar.gz'
|
const archiveExt = platform === 'win32' ? 'zip' : 'tar.gz'
|
||||||
const archiveFile = `clash-verge-service-ipc-${version}-${host}.${archiveExt}`
|
const archiveFile = `clash-verge-service-ipc-${version}-${host}.${archiveExt}`
|
||||||
return {
|
return {
|
||||||
version,
|
|
||||||
archiveFile,
|
archiveFile,
|
||||||
downloadURL: `${SERVICE_URL_PREFIX}/${version}/${archiveFile}`,
|
downloadURL: `${SERVICE_URL_PREFIX}/${version}/${archiveFile}`,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,17 +8,7 @@ use crate::{
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Eq, serde::Serialize, specta::Type)]
|
async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str) -> CmdResult {
|
||||||
#[serde(tag = "status", rename_all = "camelCase")]
|
|
||||||
pub enum ServiceInstallOutcome {
|
|
||||||
Installed,
|
|
||||||
#[cfg_attr(not(any(windows, test)), allow(dead_code))]
|
|
||||||
Sidecar {
|
|
||||||
reason: String,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str) -> CmdResult<ServiceInstallOutcome> {
|
|
||||||
let manager = CoreManager::global();
|
let manager = CoreManager::global();
|
||||||
let result = {
|
let result = {
|
||||||
let _lifecycle = manager.lifecycle_lock.lock().await;
|
let _lifecycle = manager.lifecycle_lock.lock().await;
|
||||||
@@ -33,56 +23,12 @@ async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str)
|
|||||||
}
|
}
|
||||||
SERVICE_MANAGER.handle_service_status(status).await
|
SERVICE_MANAGER.handle_service_status(status).await
|
||||||
};
|
};
|
||||||
#[cfg(windows)]
|
result.map_err(|error| proxy_aware_coded_error(&error, error_code))
|
||||||
return finish_service_installation(result, error_code, async |reason| {
|
|
||||||
manager.continue_with_sidecar(Some(reason)).await
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
|
|
||||||
#[cfg(not(windows))]
|
|
||||||
result
|
|
||||||
.map(|()| ServiceInstallOutcome::Installed)
|
|
||||||
.map_err(|error| proxy_aware_coded_error(&error, error_code))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(windows, test))]
|
|
||||||
async fn finish_service_installation<Fallback>(
|
|
||||||
installation: anyhow::Result<()>,
|
|
||||||
error_code: &str,
|
|
||||||
fallback: Fallback,
|
|
||||||
) -> CmdResult<ServiceInstallOutcome>
|
|
||||||
where
|
|
||||||
Fallback: AsyncFnOnce(&str) -> anyhow::Result<()>,
|
|
||||||
{
|
|
||||||
let Err(error) = installation else {
|
|
||||||
return Ok(ServiceInstallOutcome::Installed);
|
|
||||||
};
|
|
||||||
let Some(failure) = error.downcast_ref::<clash_verge_service_ipc::management::InstallationVerificationError>()
|
|
||||||
else {
|
|
||||||
return Err(proxy_aware_coded_error(&error, error_code));
|
|
||||||
};
|
|
||||||
let reasons = failure
|
|
||||||
.status
|
|
||||||
.cores
|
|
||||||
.iter()
|
|
||||||
.filter_map(|core| match &core.availability {
|
|
||||||
clash_verge_service_ipc::CoreAvailability::Rejected { reason } => Some(format!("{}: {reason}", core.name)),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
if reasons.is_empty() {
|
|
||||||
return Err(proxy_aware_coded_error(&error, error_code));
|
|
||||||
}
|
|
||||||
let reason = reasons.join("\n");
|
|
||||||
fallback(reason.as_str())
|
|
||||||
.await
|
|
||||||
.map_err(|error| proxy_aware_coded_error(&error, "SERVICE_SIDECAR_FAILED"))?;
|
|
||||||
Ok(ServiceInstallOutcome::Sidecar { reason })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn install_service() -> CmdResult<ServiceInstallOutcome> {
|
pub async fn install_service() -> CmdResult {
|
||||||
execute_service_operation_sync(ServiceStatus::InstallRequired, "SERVICE_INSTALL_FAILED").await
|
execute_service_operation_sync(ServiceStatus::InstallRequired, "SERVICE_INSTALL_FAILED").await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,13 +43,13 @@ pub async fn uninstall_service() -> CmdResult {
|
|||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn reinstall_service() -> CmdResult<ServiceInstallOutcome> {
|
pub async fn reinstall_service() -> CmdResult {
|
||||||
execute_service_operation_sync(ServiceStatus::ReinstallRequired, "SERVICE_REINSTALL_FAILED").await
|
execute_service_operation_sync(ServiceStatus::ReinstallRequired, "SERVICE_REINSTALL_FAILED").await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn repair_service() -> CmdResult<ServiceInstallOutcome> {
|
pub async fn repair_service() -> CmdResult {
|
||||||
execute_service_operation_sync(ServiceStatus::ForceReinstallRequired, "SERVICE_REPAIR_FAILED").await
|
execute_service_operation_sync(ServiceStatus::ForceReinstallRequired, "SERVICE_REPAIR_FAILED").await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,7 +57,7 @@ pub async fn repair_service() -> CmdResult<ServiceInstallOutcome> {
|
|||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn continue_with_sidecar() -> CmdResult {
|
pub async fn continue_with_sidecar() -> CmdResult {
|
||||||
crate::core::CoreManager::global()
|
crate::core::CoreManager::global()
|
||||||
.continue_with_sidecar(None)
|
.continue_with_sidecar()
|
||||||
.await
|
.await
|
||||||
.map_err(|error| proxy_aware_coded_error(&error, "SERVICE_SIDECAR_FAILED"))
|
.map_err(|error| proxy_aware_coded_error(&error, "SERVICE_SIDECAR_FAILED"))
|
||||||
}
|
}
|
||||||
@@ -122,12 +68,6 @@ pub fn get_sidecar_failure() -> crate::core::notification::SidecarFailureSnapsho
|
|||||||
crate::core::notification::sidecar_failure_snapshot()
|
crate::core::notification::sidecar_failure_snapshot()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
#[specta::specta]
|
|
||||||
pub fn take_service_fallback_notice() -> Option<crate::core::service::ServiceFallbackNotice> {
|
|
||||||
crate::core::service::take_service_fallback_notice()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub fn get_core_startup_error() -> Option<crate::core::manager::CoreFailure> {
|
pub fn get_core_startup_error() -> Option<crate::core::manager::CoreFailure> {
|
||||||
@@ -153,72 +93,3 @@ pub fn sync_runtime_providers() {
|
|||||||
request_runtime_provider_sync(timing::RUNTIME_PROVIDER_SETTLE);
|
request_runtime_provider_sync(timing::RUNTIME_PROVIDER_SETTLE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
|
|
||||||
mod tests {
|
|
||||||
use super::{ServiceInstallOutcome, finish_service_installation};
|
|
||||||
use clash_verge_service_ipc::{
|
|
||||||
CoreAvailability, CoreInspection, InstallationStatus, ProtocolInfo, management::InstallationVerificationError,
|
|
||||||
};
|
|
||||||
use std::cell::Cell;
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn rejected_installation_reports_sidecar_only_after_successful_continuation() {
|
|
||||||
let reason = "core path C:\\ is writable by Everyone";
|
|
||||||
for (availability, fallback_ready) in [
|
|
||||||
(None, false),
|
|
||||||
(Some(CoreAvailability::Missing), false),
|
|
||||||
(Some(CoreAvailability::DigestMismatch), false),
|
|
||||||
(Some(CoreAvailability::Rejected { reason: reason.into() }), false),
|
|
||||||
(Some(CoreAvailability::Rejected { reason: reason.into() }), true),
|
|
||||||
] {
|
|
||||||
let fallback_called = Cell::new(false);
|
|
||||||
let rejected = matches!(&availability, Some(CoreAvailability::Rejected { .. }));
|
|
||||||
let error = match availability {
|
|
||||||
Some(availability) => anyhow::Error::new(InstallationVerificationError {
|
|
||||||
status: InstallationStatus {
|
|
||||||
service_sha256: String::new(),
|
|
||||||
protocol: ProtocolInfo::current(),
|
|
||||||
cores: vec![CoreInspection {
|
|
||||||
name: "verge-mihomo.exe".into(),
|
|
||||||
availability,
|
|
||||||
}],
|
|
||||||
core_busy: false,
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
None => anyhow::anyhow!("{reason}"),
|
|
||||||
}
|
|
||||||
.context("install service failed");
|
|
||||||
let result = finish_service_installation(Err(error), "SERVICE_INSTALL_FAILED", async |_| {
|
|
||||||
fallback_called.set(true);
|
|
||||||
anyhow::ensure!(fallback_ready, "another core is running");
|
|
||||||
Ok(())
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
|
|
||||||
assert_eq!(fallback_called.get(), rejected);
|
|
||||||
if rejected && fallback_ready {
|
|
||||||
assert_eq!(
|
|
||||||
result,
|
|
||||||
Ok(ServiceInstallOutcome::Sidecar {
|
|
||||||
reason: format!("verge-mihomo.exe: {reason}")
|
|
||||||
})
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
let error = result.expect_err("an unavailable fallback must remain an error");
|
|
||||||
assert_eq!(
|
|
||||||
error.code.as_deref(),
|
|
||||||
Some(if rejected {
|
|
||||||
"SERVICE_SIDECAR_FAILED"
|
|
||||||
} else {
|
|
||||||
"SERVICE_INSTALL_FAILED"
|
|
||||||
})
|
|
||||||
);
|
|
||||||
if rejected {
|
|
||||||
assert!(error.detail.contains("another core is running"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -88,8 +88,8 @@ fn plan_config_application(attempt: &StageAttempt) -> ConfigApplication {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn ask_to_stage(path: &std::path::Path) -> StageAttempt {
|
async fn ask_to_stage(path: &std::path::Path, session: &clash_verge_service_ipc::OwnerSessionProof) -> StageAttempt {
|
||||||
match crate::core::service::stage_runtime_by_service(path).await {
|
match crate::core::service::stage_runtime_by_service(path, session).await {
|
||||||
Ok(StageRequest::Answered(outcome)) => StageAttempt::Answered(outcome),
|
Ok(StageRequest::Answered(outcome)) => StageAttempt::Answered(outcome),
|
||||||
Ok(StageRequest::Refused { code, message }) => {
|
Ok(StageRequest::Refused { code, message }) => {
|
||||||
let message = message.into();
|
let message = message.into();
|
||||||
@@ -433,10 +433,10 @@ impl CoreManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn attempt_staging(&self, path: &std::path::Path) -> StageAttempt {
|
async fn attempt_staging(&self, path: &std::path::Path) -> StageAttempt {
|
||||||
if !crate::core::service::active_service_supports_runtime_staging() {
|
let Ok(session) = crate::core::service::active_service_session() else {
|
||||||
return StageAttempt::Unsupported;
|
return StageAttempt::Unsupported;
|
||||||
}
|
};
|
||||||
stage_with_confirmation(timing::STAGE_CONFIRM_TIMEOUT, || ask_to_stage(path)).await
|
stage_with_confirmation(timing::STAGE_CONFIRM_TIMEOUT, || ask_to_stage(path, &session)).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reload the Core from `path`, and replace the Core if it will not take it.
|
/// Reload the Core from `path`, and replace the Core if it will not take it.
|
||||||
|
|||||||
@@ -188,48 +188,6 @@ where
|
|||||||
apply_proxy().await
|
apply_proxy().await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(any(target_os = "windows", test))]
|
|
||||||
async fn run_service_start_with_sidecar_fallback<Start, StartFuture, Check, CheckFuture, Fallback, FallbackFuture>(
|
|
||||||
start_service: Start,
|
|
||||||
confirm_idle: Check,
|
|
||||||
start_sidecar: Fallback,
|
|
||||||
record_unavailable: impl FnOnce(std::string::String),
|
|
||||||
) -> Result<()>
|
|
||||||
where
|
|
||||||
Start: FnOnce() -> StartFuture,
|
|
||||||
StartFuture: std::future::Future<Output = Result<()>>,
|
|
||||||
Check: FnOnce() -> CheckFuture,
|
|
||||||
CheckFuture: std::future::Future<Output = Result<()>>,
|
|
||||||
Fallback: FnOnce(anyhow::Error) -> FallbackFuture,
|
|
||||||
FallbackFuture: std::future::Future<Output = Result<()>>,
|
|
||||||
{
|
|
||||||
let Err(error) = start_service().await else {
|
|
||||||
return Ok(());
|
|
||||||
};
|
|
||||||
let refusal = error.downcast_ref::<crate::core::service::ServiceStartRefusal>();
|
|
||||||
let location_refused = refusal.is_some_and(|refusal| {
|
|
||||||
refusal.code == clash_verge_service_ipc::ServiceErrorCode::InvalidInstallLocation as u16
|
|
||||||
});
|
|
||||||
if refusal.is_some() && !location_refused {
|
|
||||||
return Err(error);
|
|
||||||
}
|
|
||||||
// A lost start response can hide a running core; the shared check must resolve occupancy.
|
|
||||||
if let Err(probe_error) = confirm_idle().await {
|
|
||||||
let error = error.context(format!("Sidecar fallback was not safe: {probe_error:#}"));
|
|
||||||
record_unavailable(format!("{error:#}"));
|
|
||||||
return Err(error);
|
|
||||||
}
|
|
||||||
logging!(
|
|
||||||
warn,
|
|
||||||
Type::Core,
|
|
||||||
"Service could not start the core; falling back to Sidecar: {error:#}"
|
|
||||||
);
|
|
||||||
let reason = format!("{error:#}");
|
|
||||||
start_sidecar(error)
|
|
||||||
.await
|
|
||||||
.map_err(|error| error.context(format!("Sidecar fallback failed after Service failure: {reason}")))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn run_sidecar_termination_transition<Clear, ClearFuture, Terminate, TerminateFuture>(
|
async fn run_sidecar_termination_transition<Clear, ClearFuture, Terminate, TerminateFuture>(
|
||||||
clear_proxy: Clear,
|
clear_proxy: Clear,
|
||||||
terminate_sidecar: Terminate,
|
terminate_sidecar: Terminate,
|
||||||
@@ -326,11 +284,7 @@ where
|
|||||||
start_sidecar().await
|
start_sidecar().await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn report_sidecar_failure(error: anyhow::Error, service_rejection: Option<&str>) -> anyhow::Error {
|
fn report_sidecar_failure(error: anyhow::Error) -> anyhow::Error {
|
||||||
let error = match service_rejection {
|
|
||||||
Some(reason) => error.context(format!("Service core rejected: {reason}; Sidecar fallback failed")),
|
|
||||||
None => error,
|
|
||||||
};
|
|
||||||
// Proxy failures have their own pending state and recovery dialog.
|
// Proxy failures have their own pending state and recovery dialog.
|
||||||
if SysproxyFailure::from_chain(&error).is_none() {
|
if SysproxyFailure::from_chain(&error).is_none() {
|
||||||
crate::core::notification::record_sidecar_failure(format!("{error:#}").into());
|
crate::core::notification::record_sidecar_failure(format!("{error:#}").into());
|
||||||
@@ -368,12 +322,11 @@ impl CoreManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip_all, level = "info", fields(status = tracing::field::Empty, tun_disabled = false, readiness_generation = tracing::field::Empty))]
|
#[tracing::instrument(skip_all, level = "info", fields(status = tracing::field::Empty, tun_disabled = false, readiness_generation = tracing::field::Empty))]
|
||||||
pub async fn continue_with_sidecar(&self, service_rejection: Option<&str>) -> Result<()> {
|
pub async fn continue_with_sidecar(&self) -> Result<()> {
|
||||||
if !self.try_start_config_update() {
|
if !self.try_start_config_update() {
|
||||||
return Err(report_sidecar_failure(
|
return Err(report_sidecar_failure(anyhow::anyhow!(
|
||||||
anyhow::anyhow!("configuration update is already running"),
|
"configuration update is already running"
|
||||||
service_rejection,
|
)));
|
||||||
));
|
|
||||||
}
|
}
|
||||||
let _config_update = DropGuard::new((), |()| {
|
let _config_update = DropGuard::new((), |()| {
|
||||||
self.finish_config_update();
|
self.finish_config_update();
|
||||||
@@ -390,11 +343,8 @@ impl CoreManager {
|
|||||||
if !can_allow_sidecar_for_session(&mode, &status) {
|
if !can_allow_sidecar_for_session(&mode, &status) {
|
||||||
anyhow::bail!("Sidecar continuation is not allowed from {mode:?} / {status:?}");
|
anyhow::bail!("Sidecar continuation is not allowed from {mode:?} / {status:?}");
|
||||||
}
|
}
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
if matches!(*mode, RunningMode::NotRunning) {
|
if matches!(*mode, RunningMode::NotRunning) {
|
||||||
clash_verge_service_ipc::execution::check_sidecar_available()
|
crate::core::service::release_service_core_for_sidecar().await?;
|
||||||
.await
|
|
||||||
.map_err(super::state::explain_core_occupancy)?;
|
|
||||||
}
|
}
|
||||||
if !matches!(status, ServiceStatus::SidecarAllowed) {
|
if !matches!(status, ServiceStatus::SidecarAllowed) {
|
||||||
SERVICE_MANAGER.allow_sidecar_for_session()?;
|
SERVICE_MANAGER.allow_sidecar_for_session()?;
|
||||||
@@ -447,7 +397,7 @@ impl CoreManager {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
.await;
|
.await;
|
||||||
result.map_err(|error| report_sidecar_failure(error, service_rejection))
|
result.map_err(report_sidecar_failure)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip_all, level = "info", fields(readiness_generation = tracing::field::Empty))]
|
#[tracing::instrument(skip_all, level = "info", fields(readiness_generation = tracing::field::Empty))]
|
||||||
@@ -463,6 +413,7 @@ impl CoreManager {
|
|||||||
let _life = self.lifecycle_lock.lock().await;
|
let _life = self.lifecycle_lock.lock().await;
|
||||||
|
|
||||||
self.controlled_stop_core_inner().await?;
|
self.controlled_stop_core_inner().await?;
|
||||||
|
crate::core::service::release_service_core_for_sidecar().await?;
|
||||||
|
|
||||||
let result = run_uninstall_transition(
|
let result = run_uninstall_transition(
|
||||||
|| async {
|
|| async {
|
||||||
@@ -638,8 +589,6 @@ impl CoreManager {
|
|||||||
self.rollback_failed_start().await;
|
self.rollback_failed_start().await;
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
crate::utils::resolve::dns::sync_public_dns().await;
|
crate::utils::resolve::dns::sync_public_dns().await;
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
self.try_sidecar_after_service_unavailable().await?;
|
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
if Handle::global().is_exiting() {
|
if Handle::global().is_exiting() {
|
||||||
@@ -648,27 +597,15 @@ impl CoreManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let result = match startup {
|
let result = match startup {
|
||||||
StartupDecision::Service => {
|
StartupDecision::Service => self.start_core_by_service().await.inspect_err(|error| {
|
||||||
#[cfg(target_os = "windows")]
|
if error
|
||||||
|
.downcast_ref::<crate::core::service::ServiceStartRefusal>()
|
||||||
|
.is_none()
|
||||||
{
|
{
|
||||||
run_service_start_with_sidecar_fallback(
|
crate::core::runstate::RUN_STATE
|
||||||
|| self.start_core_by_service(),
|
.observe(crate::core::runstate::ServiceHealth::Unavailable(format!("{error:#}")));
|
||||||
|| async {
|
|
||||||
clash_verge_service_ipc::execution::check_sidecar_available()
|
|
||||||
.await
|
|
||||||
.map_err(super::state::explain_core_occupancy)
|
|
||||||
},
|
|
||||||
|error| self.start_sidecar_after_service_failure(error),
|
|
||||||
|reason| {
|
|
||||||
crate::core::runstate::RUN_STATE
|
|
||||||
.observe(crate::core::runstate::ServiceHealth::Unavailable(reason));
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
#[cfg(not(target_os = "windows"))]
|
}),
|
||||||
self.start_core_by_service().await
|
|
||||||
}
|
|
||||||
StartupDecision::Sidecar => self.start_core_by_sidecar().await,
|
StartupDecision::Sidecar => self.start_core_by_sidecar().await,
|
||||||
StartupDecision::Wait => Ok(()),
|
StartupDecision::Wait => Ok(()),
|
||||||
};
|
};
|
||||||
@@ -684,53 +621,6 @@ impl CoreManager {
|
|||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
async fn try_sidecar_after_service_unavailable(&self) -> Result<()> {
|
|
||||||
use crate::core::runstate::{RUN_STATE, ServiceHealth};
|
|
||||||
|
|
||||||
let state = RUN_STATE.state();
|
|
||||||
if state.pending.is_some() || state.op_in_flight || Handle::global().is_exiting() {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
let reason = match state.health {
|
|
||||||
ServiceHealth::Unavailable(reason) => reason,
|
|
||||||
ServiceHealth::VersionMismatch => "registered service is unavailable or incompatible".to_owned(),
|
|
||||||
_ => return Ok(()),
|
|
||||||
};
|
|
||||||
if let Err(error) = clash_verge_service_ipc::execution::check_sidecar_available()
|
|
||||||
.await
|
|
||||||
.map_err(super::state::explain_core_occupancy)
|
|
||||||
{
|
|
||||||
logging!(
|
|
||||||
warn,
|
|
||||||
Type::Core,
|
|
||||||
"Service unavailable ({reason}); Sidecar fallback withheld: {error:#}"
|
|
||||||
);
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
self.start_sidecar_after_service_failure(anyhow::anyhow!(reason)).await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
async fn start_sidecar_after_service_failure(&self, error: anyhow::Error) -> Result<()> {
|
|
||||||
use crate::core::runstate::RUN_STATE;
|
|
||||||
|
|
||||||
if Handle::global().is_exiting() {
|
|
||||||
return Err(error.context("application exited before Sidecar fallback"));
|
|
||||||
}
|
|
||||||
let reason = format!("{error:#}");
|
|
||||||
RUN_STATE.allow_sidecar_after_service_refusal(reason.clone())?;
|
|
||||||
logging!(warn, Type::Core, "Starting Sidecar with Service unavailable: {reason}");
|
|
||||||
let result = self.start_core_by_sidecar().await;
|
|
||||||
if result.is_err() {
|
|
||||||
SERVICE_MANAGER.withdraw_sidecar_allowance();
|
|
||||||
self.rollback_failed_start().await;
|
|
||||||
} else {
|
|
||||||
crate::core::service::notify_service_fallback(&reason);
|
|
||||||
}
|
|
||||||
result.map_err(|error| error.context(format!("Service failure before Sidecar startup: {reason}")))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tracing::instrument(skip_all, level = "info", fields(mode = ?*self.get_running_mode()))]
|
#[tracing::instrument(skip_all, level = "info", fields(mode = ?*self.get_running_mode()))]
|
||||||
pub async fn stop_core(&self) -> Result<()> {
|
pub async fn stop_core(&self) -> Result<()> {
|
||||||
let _life = self.lifecycle_lock.lock().await;
|
let _life = self.lifecycle_lock.lock().await;
|
||||||
@@ -846,13 +736,6 @@ impl CoreManager {
|
|||||||
let is_admin = is_current_app_handle_admin(Handle::app_handle());
|
let is_admin = is_current_app_handle_admin(Handle::app_handle());
|
||||||
|
|
||||||
if !should_wait_for_service(tun_enabled, service_ready, is_admin) {
|
if !should_wait_for_service(tun_enabled, service_ready, is_admin) {
|
||||||
if tun_enabled && !service_ready && is_admin {
|
|
||||||
logging!(
|
|
||||||
info,
|
|
||||||
Type::Core,
|
|
||||||
"service unavailable while app is elevated; starting sidecar immediately"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -865,8 +748,6 @@ impl CoreManager {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Failing to become ready is not fatal here: the caller falls back to Sidecar, and a
|
|
||||||
// transient transport failure must not overwrite the last confirmed install state.
|
|
||||||
let attempts = (timing::SERVICE_WAIT_MAX.as_millis() / timing::SERVICE_WAIT_INTERVAL.as_millis()) as usize;
|
let attempts = (timing::SERVICE_WAIT_MAX.as_millis() / timing::SERVICE_WAIT_INTERVAL.as_millis()) as usize;
|
||||||
let wait = crate::core::runstate::RUN_STATE.await_ready(attempts, timing::SERVICE_WAIT_INTERVAL);
|
let wait = crate::core::runstate::RUN_STATE.await_ready(attempts, timing::SERVICE_WAIT_INTERVAL);
|
||||||
let _ = tokio::time::timeout(timing::SERVICE_WAIT_MAX, wait).await;
|
let _ = tokio::time::timeout(timing::SERVICE_WAIT_MAX, wait).await;
|
||||||
@@ -1410,46 +1291,6 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn blocked_windows_fallback_records_failure_without_starting_sidecar() {
|
|
||||||
use crate::core::runstate::{FakeEnv, RunStateStore, ServiceHealth};
|
|
||||||
|
|
||||||
for idle in [false, true] {
|
|
||||||
let store = RunStateStore::new(FakeEnv::new());
|
|
||||||
store.observe(ServiceHealth::Ready);
|
|
||||||
let started = AtomicBool::new(false);
|
|
||||||
let result = super::run_service_start_with_sidecar_fallback(
|
|
||||||
|| async {
|
|
||||||
Err(crate::core::service::ServiceStartRefusal {
|
|
||||||
code: clash_verge_service_ipc::ServiceErrorCode::InvalidInstallLocation as u16,
|
|
||||||
core_path: "verge-mihomo.exe".into(),
|
|
||||||
message: "no administrator-approved copy is installed".into(),
|
|
||||||
}
|
|
||||||
.into())
|
|
||||||
},
|
|
||||||
|| async move {
|
|
||||||
anyhow::ensure!(idle, "another core is running");
|
|
||||||
Ok(())
|
|
||||||
},
|
|
||||||
|_| async {
|
|
||||||
started.store(true, Ordering::SeqCst);
|
|
||||||
Ok(())
|
|
||||||
},
|
|
||||||
|reason| store.observe(ServiceHealth::Unavailable(reason)),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
assert_eq!(started.load(Ordering::SeqCst), idle);
|
|
||||||
assert_eq!(result.is_ok(), idle);
|
|
||||||
assert!(!store.state().sidecar_allowed);
|
|
||||||
if !idle {
|
|
||||||
assert!(store.state().service_needs_attention());
|
|
||||||
assert!(!store.state().service_usable());
|
|
||||||
assert!(result.is_err_and(|error| format!("{error:#}").contains("another core is running")));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn failed_service_install_can_continue_with_an_existing_sidecar() {
|
fn failed_service_install_can_continue_with_an_existing_sidecar() {
|
||||||
assert!(can_allow_sidecar_for_session(
|
assert!(can_allow_sidecar_for_session(
|
||||||
|
|||||||
@@ -11,27 +11,14 @@ use crate::{
|
|||||||
use anyhow::{Context as _, Result};
|
use anyhow::{Context as _, Result};
|
||||||
use clash_verge_logging::Type;
|
use clash_verge_logging::Type;
|
||||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
||||||
use futures::{
|
use futures::{FutureExt as _, future::Shared};
|
||||||
FutureExt as _,
|
|
||||||
future::{Map, Shared},
|
|
||||||
};
|
|
||||||
use log::Level;
|
use log::Level;
|
||||||
use std::num::NonZeroUsize;
|
use std::num::NonZeroUsize;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::sync::Arc;
|
|
||||||
use tauri_plugin_mihomo::MihomoExt as _;
|
use tauri_plugin_mihomo::MihomoExt as _;
|
||||||
use tauri_plugin_shell::ShellExt as _;
|
use tauri_plugin_shell::ShellExt as _;
|
||||||
use tauri_plugin_shell::process::CommandChild;
|
use tauri_plugin_shell::process::CommandChild;
|
||||||
use tokio::task::{JoinError, JoinHandle};
|
use tokio::sync::oneshot;
|
||||||
|
|
||||||
pub(super) fn explain_core_occupancy(error: anyhow::Error) -> anyhow::Error {
|
|
||||||
let detail = error.to_string();
|
|
||||||
if detail.starts_with("process verge-mihomo") && detail.ends_with("; refusing a second core") {
|
|
||||||
error.context(clash_verge_i18n::t!("core.alreadyRunning").into_owned())
|
|
||||||
} else {
|
|
||||||
error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> {
|
fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> {
|
||||||
@@ -146,18 +133,10 @@ fn should_clear_terminated_sidecar(
|
|||||||
matches!(running_mode, RunningMode::Sidecar) && current_generation == Some(terminated_generation)
|
matches!(running_mode, RunningMode::Sidecar) && current_generation == Some(terminated_generation)
|
||||||
}
|
}
|
||||||
|
|
||||||
type ShareExitResult = fn(Result<(), JoinError>) -> Result<(), Arc<JoinError>>;
|
|
||||||
type SidecarExit = Shared<Map<JoinHandle<()>, ShareExitResult>>;
|
|
||||||
|
|
||||||
fn share_exit(exit: JoinHandle<()>) -> SidecarExit {
|
|
||||||
let share_error: ShareExitResult = |result| result.map_err(Arc::new);
|
|
||||||
exit.map(share_error).shared()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
pub(super) struct SidecarSession {
|
pub(super) struct SidecarSession {
|
||||||
process: Option<SidecarProcess>,
|
process: Option<SidecarProcess>,
|
||||||
exit: Option<SidecarExit>,
|
exit: Option<Shared<oneshot::Receiver<()>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -195,10 +174,7 @@ impl CoreManager {
|
|||||||
#[tracing::instrument(skip_all, level = "info", fields(pid = tracing::field::Empty))]
|
#[tracing::instrument(skip_all, level = "info", fields(pid = tracing::field::Empty))]
|
||||||
pub(super) async fn start_core_by_sidecar(&self) -> Result<()> {
|
pub(super) async fn start_core_by_sidecar(&self) -> Result<()> {
|
||||||
self.wait_for_sidecar_exit().await?;
|
self.wait_for_sidecar_exit().await?;
|
||||||
let execution = clash_verge_service_ipc::execution::reserve_sidecar()
|
service::require_service_core_released()?;
|
||||||
.await
|
|
||||||
.inspect_err(service::record_residual_service)
|
|
||||||
.map_err(explain_core_occupancy)?;
|
|
||||||
self.core_stopped();
|
self.core_stopped();
|
||||||
|
|
||||||
let sidecar_ipc = dirs::sidecar_ipc_path()?;
|
let sidecar_ipc = dirs::sidecar_ipc_path()?;
|
||||||
@@ -221,13 +197,11 @@ impl CoreManager {
|
|||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
discard_unwritable_core_cache(&config_dir);
|
discard_unwritable_core_cache(&config_dir);
|
||||||
|
|
||||||
#[cfg(unix)]
|
|
||||||
let previous_mask = unsafe { tauri_plugin_clash_verge_sysinfo::libc::umask(0o077) };
|
|
||||||
let command = app_handle
|
let command = app_handle
|
||||||
.shell()
|
.shell()
|
||||||
.sidecar(clash_core.as_str())
|
.sidecar(clash_core.as_str())
|
||||||
.map_err(|error| anyhow::anyhow!("failed to build sidecar command for core {clash_core:?}: {error:#}"))?;
|
.map_err(|error| anyhow::anyhow!("failed to build sidecar command for core {clash_core:?}: {error:#}"))?;
|
||||||
let command = command.args([
|
let command = command.kill_on_drop(true).args([
|
||||||
"-d",
|
"-d",
|
||||||
dirs::path_to_str(&config_dir)?,
|
dirs::path_to_str(&config_dir)?,
|
||||||
"-f",
|
"-f",
|
||||||
@@ -244,6 +218,13 @@ impl CoreManager {
|
|||||||
"LISTEN_NAMEDPIPE_SDDL",
|
"LISTEN_NAMEDPIPE_SDDL",
|
||||||
crate::core::owner_identity::current_user_pipe_sddl()?,
|
crate::core::owner_identity::current_user_pipe_sddl()?,
|
||||||
);
|
);
|
||||||
|
#[cfg(unix)]
|
||||||
|
let restore_mask = std::mem::DropGuard::new(
|
||||||
|
unsafe { tauri_plugin_clash_verge_sysinfo::libc::umask(0o077) },
|
||||||
|
|mask| {
|
||||||
|
unsafe { tauri_plugin_clash_verge_sysinfo::libc::umask(mask) };
|
||||||
|
},
|
||||||
|
);
|
||||||
let (mut rx, child) = command.spawn().map_err(|error| {
|
let (mut rx, child) = command.spawn().map_err(|error| {
|
||||||
anyhow::anyhow!(
|
anyhow::anyhow!(
|
||||||
"failed to start sidecar core {clash_core:?} with config {} and data directory {}: {error:#}",
|
"failed to start sidecar core {clash_core:?} with config {} and data directory {}: {error:#}",
|
||||||
@@ -251,35 +232,10 @@ impl CoreManager {
|
|||||||
config_dir.display()
|
config_dir.display()
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
let (terminated, termination) = tokio::sync::oneshot::channel();
|
|
||||||
let exit = execution.release_after_exit(child.pid(), termination);
|
|
||||||
self.sidecar.lock().exit = Some(share_exit(exit));
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
let job = {
|
|
||||||
match create_and_assign_sidecar_job(child.pid()) {
|
|
||||||
Ok(job) => job,
|
|
||||||
Err(job_error) => {
|
|
||||||
let pid = child.pid();
|
|
||||||
|
|
||||||
let error = match child.kill() {
|
|
||||||
Ok(()) => job_error,
|
|
||||||
Err(kill_error) => anyhow::anyhow!(
|
|
||||||
"failed to configure Job Object for sidecar PID {pid}: \
|
|
||||||
{job_error:#}; failed to terminate child: {kill_error:#}"
|
|
||||||
),
|
|
||||||
};
|
|
||||||
|
|
||||||
logging!(error, Type::Core, "Failed to start sidecar: {error:#}");
|
|
||||||
return Err(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
unsafe {
|
drop(restore_mask);
|
||||||
tauri_plugin_clash_verge_sysinfo::libc::umask(previous_mask)
|
let (terminated, termination) = oneshot::channel();
|
||||||
};
|
self.sidecar.lock().exit = Some(termination.shared());
|
||||||
|
|
||||||
let pid = child.pid();
|
let pid = child.pid();
|
||||||
tracing::Span::current().record("pid", pid);
|
tracing::Span::current().record("pid", pid);
|
||||||
|
|
||||||
@@ -317,6 +273,30 @@ impl CoreManager {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
let job = {
|
||||||
|
match create_and_assign_sidecar_job(child.pid()) {
|
||||||
|
Ok(job) => job,
|
||||||
|
Err(job_error) => {
|
||||||
|
let pid = child.pid();
|
||||||
|
|
||||||
|
let error = match child.kill() {
|
||||||
|
Ok(()) => {
|
||||||
|
self.sidecar.lock().exit.take();
|
||||||
|
job_error
|
||||||
|
}
|
||||||
|
Err(kill_error) => anyhow::anyhow!(
|
||||||
|
"failed to configure Job Object for sidecar PID {pid}: \
|
||||||
|
{job_error:#}; failed to terminate child: {kill_error:#}"
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
logging!(error, Type::Core, "Failed to start sidecar: {error:#}");
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let readiness = poll_sidecar_readiness(SIDECAR_READINESS_ATTEMPTS, SIDECAR_READINESS_INTERVAL, || async {
|
let readiness = poll_sidecar_readiness(SIDECAR_READINESS_ATTEMPTS, SIDECAR_READINESS_INTERVAL, || async {
|
||||||
tokio::time::timeout(SIDECAR_READINESS_PROBE_TIMEOUT, async {
|
tokio::time::timeout(SIDECAR_READINESS_PROBE_TIMEOUT, async {
|
||||||
handle::Handle::mihomo().get_version().await
|
handle::Handle::mihomo().get_version().await
|
||||||
@@ -330,7 +310,10 @@ impl CoreManager {
|
|||||||
proxy_control::stop_guard().await;
|
proxy_control::stop_guard().await;
|
||||||
self.core_stopped();
|
self.core_stopped();
|
||||||
return match child.kill() {
|
return match child.kill() {
|
||||||
Ok(()) => Err(readiness_error),
|
Ok(()) => {
|
||||||
|
self.sidecar.lock().exit.take();
|
||||||
|
Err(readiness_error)
|
||||||
|
}
|
||||||
Err(kill_error) => Err(anyhow::anyhow!(
|
Err(kill_error) => Err(anyhow::anyhow!(
|
||||||
"{readiness_error:#}; failed to terminate unready sidecar PID {pid}: {kill_error:#}"
|
"{readiness_error:#}; failed to terminate unready sidecar PID {pid}: {kill_error:#}"
|
||||||
)),
|
)),
|
||||||
@@ -358,8 +341,11 @@ impl CoreManager {
|
|||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
drop(process.job);
|
drop(process.job);
|
||||||
|
|
||||||
if let Err(error) = process.child.kill() {
|
match process.child.kill() {
|
||||||
logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}");
|
Ok(()) => {
|
||||||
|
self.sidecar.lock().exit.take();
|
||||||
|
}
|
||||||
|
Err(error) => logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let result = self.wait_for_sidecar_exit().await;
|
let result = self.wait_for_sidecar_exit().await;
|
||||||
@@ -393,12 +379,13 @@ impl CoreManager {
|
|||||||
|
|
||||||
#[tracing::instrument(skip_all, level = "info", fields(config_file = %config_file.display()))]
|
#[tracing::instrument(skip_all, level = "info", fields(config_file = %config_file.display()))]
|
||||||
pub(super) async fn start_core_by_service_with_config(&self, config_file: &Path) -> Result<()> {
|
pub(super) async fn start_core_by_service_with_config(&self, config_file: &Path) -> Result<()> {
|
||||||
// 交接时等待 sidecar 释放 ext-controller 通道。
|
self.wait_for_sidecar_exit().await?;
|
||||||
|
let start = tokio::sync::OnceCell::new();
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
{
|
{
|
||||||
use crate::constants::timing;
|
use crate::constants::timing;
|
||||||
retry_service_start(timing::SERVICE_START_RETRIES, timing::SERVICE_START_RETRY_DELAY, || {
|
retry_service_start(timing::SERVICE_START_RETRIES, timing::SERVICE_START_RETRY_DELAY, || {
|
||||||
service::run_core_by_service(config_file)
|
service::run_core_by_service(config_file, &start)
|
||||||
})
|
})
|
||||||
.await?;
|
.await?;
|
||||||
self.mark_core_ready();
|
self.mark_core_ready();
|
||||||
@@ -410,7 +397,7 @@ impl CoreManager {
|
|||||||
|
|
||||||
#[cfg(not(target_os = "windows"))]
|
#[cfg(not(target_os = "windows"))]
|
||||||
{
|
{
|
||||||
service::run_core_by_service(config_file).await?;
|
service::run_core_by_service(config_file, &start).await?;
|
||||||
self.mark_core_ready();
|
self.mark_core_ready();
|
||||||
self.core_started(RunningMode::Service);
|
self.core_started(RunningMode::Service);
|
||||||
self.restore_selected_nodes().await;
|
self.restore_selected_nodes().await;
|
||||||
@@ -556,20 +543,6 @@ mod readiness_tests {
|
|||||||
time::Duration,
|
time::Duration,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn core_occupancy_explanation_preserves_the_original_error() {
|
|
||||||
for detail in [
|
|
||||||
"process verge-mihomo remains after IPC failure; refusing a second core",
|
|
||||||
"process verge-mihomo-alpha.exe (PID 123) is still running; refusing a second core",
|
|
||||||
] {
|
|
||||||
let error = super::explain_core_occupancy(anyhow::anyhow!(detail));
|
|
||||||
assert_eq!(error.to_string(), clash_verge_i18n::t!("core.alreadyRunning"));
|
|
||||||
assert_eq!(error.root_cause().to_string(), detail);
|
|
||||||
}
|
|
||||||
let error = super::explain_core_occupancy(anyhow::anyhow!("could not inspect remaining cores"));
|
|
||||||
assert_eq!(error.to_string(), "could not inspect remaining cores");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn sidecar_readiness_poll_is_bounded_and_accepts_a_real_api_response() -> anyhow::Result<()> {
|
async fn sidecar_readiness_poll_is_bounded_and_accepts_a_real_api_response() -> anyhow::Result<()> {
|
||||||
let attempts = Arc::new(AtomicUsize::new(0));
|
let attempts = Arc::new(AtomicUsize::new(0));
|
||||||
@@ -730,6 +703,65 @@ mod tests {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn forced_parent_exit_releases_the_sidecar_job() -> Result<()> {
|
||||||
|
use std::io::{BufRead as _, BufReader, Write as _};
|
||||||
|
use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _, OwnedHandle};
|
||||||
|
use windows_sys::Win32::{
|
||||||
|
Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT},
|
||||||
|
System::Threading::{OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject},
|
||||||
|
};
|
||||||
|
|
||||||
|
const HELPER: &str = "CVR_TEST_SIDECAR_JOB_PARENT";
|
||||||
|
if std::env::var_os(HELPER).is_some() {
|
||||||
|
let mut child = spawn_long_lived()?;
|
||||||
|
let _job = create_and_assign_sidecar_job(child.id()).inspect_err(|_| {
|
||||||
|
let _ = child.kill();
|
||||||
|
let _ = child.wait();
|
||||||
|
})?;
|
||||||
|
println!("\nSIDECAR_PID={}", child.id());
|
||||||
|
std::io::stdout().flush()?;
|
||||||
|
std::io::stdin().read_line(&mut String::new())?;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut parent = std::mem::DropGuard::new(
|
||||||
|
Command::new(std::env::current_exe()?)
|
||||||
|
.args(["forced_parent_exit_releases_the_sidecar_job", "--nocapture"])
|
||||||
|
.env(HELPER, "1")
|
||||||
|
.stdin(Stdio::piped())
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.spawn()?,
|
||||||
|
|mut parent| {
|
||||||
|
let _ = parent.kill();
|
||||||
|
let _ = parent.wait();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let stdout = parent
|
||||||
|
.stdout
|
||||||
|
.take()
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("missing helper stdout"))?;
|
||||||
|
let mut pid = None;
|
||||||
|
for line in BufReader::new(stdout).lines() {
|
||||||
|
if let Some(value) = line?.strip_prefix("SIDECAR_PID=") {
|
||||||
|
pid = Some(value.parse()?);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let pid = pid.ok_or_else(|| anyhow::anyhow!("helper did not report its child"))?;
|
||||||
|
let raw = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) };
|
||||||
|
anyhow::ensure!(!raw.is_null(), "could not open helper child {pid}");
|
||||||
|
let child = unsafe { OwnedHandle::from_raw_handle(raw) };
|
||||||
|
assert_eq!(unsafe { WaitForSingleObject(child.as_raw_handle(), 0) }, WAIT_TIMEOUT);
|
||||||
|
parent.kill()?;
|
||||||
|
parent.wait()?;
|
||||||
|
assert_eq!(
|
||||||
|
unsafe { WaitForSingleObject(child.as_raw_handle(), 5000) },
|
||||||
|
WAIT_OBJECT_0
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn returns_err_for_invalid_pid() {
|
fn returns_err_for_invalid_pid() {
|
||||||
// Windows PIDs are multiples of four; this one is effectively impossible.
|
// Windows PIDs are multiples of four; this one is effectively impossible.
|
||||||
|
|||||||
@@ -19,9 +19,6 @@ pub enum NoticeStatus {
|
|||||||
ServiceCoreRepairRequired,
|
ServiceCoreRepairRequired,
|
||||||
#[serde(rename = "service_core::app_data_not_owned")]
|
#[serde(rename = "service_core::app_data_not_owned")]
|
||||||
ServiceCoreAppDataNotOwned,
|
ServiceCoreAppDataNotOwned,
|
||||||
#[serde(rename = "service_core::sidecar_fallback")]
|
|
||||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
|
||||||
ServiceCoreSidecarFallback,
|
|
||||||
#[serde(rename = "dns_override::auto_disabled")]
|
#[serde(rename = "dns_override::auto_disabled")]
|
||||||
DnsOverrideAutoDisabled,
|
DnsOverrideAutoDisabled,
|
||||||
#[serde(rename = "enhance::discarded_keys")]
|
#[serde(rename = "enhance::discarded_keys")]
|
||||||
@@ -81,14 +78,13 @@ impl NoticeStatus {
|
|||||||
/// test both derive their variant list from here; expected strings stay
|
/// test both derive their variant list from here; expected strings stay
|
||||||
/// hand-written in the test so renames cannot slip through.
|
/// hand-written in the test so renames cannot slip through.
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub const ALL: [Self; 33] = [
|
pub const ALL: [Self; 32] = [
|
||||||
Self::ImportSubUrlOk,
|
Self::ImportSubUrlOk,
|
||||||
Self::ImportSubUrlError,
|
Self::ImportSubUrlError,
|
||||||
Self::SetConfigError,
|
Self::SetConfigError,
|
||||||
Self::CoreStartError,
|
Self::CoreStartError,
|
||||||
Self::ServiceCoreRepairRequired,
|
Self::ServiceCoreRepairRequired,
|
||||||
Self::ServiceCoreAppDataNotOwned,
|
Self::ServiceCoreAppDataNotOwned,
|
||||||
Self::ServiceCoreSidecarFallback,
|
|
||||||
Self::DnsOverrideAutoDisabled,
|
Self::DnsOverrideAutoDisabled,
|
||||||
Self::EnhanceDiscardedKeys,
|
Self::EnhanceDiscardedKeys,
|
||||||
Self::TunModeAutoDisabled,
|
Self::TunModeAutoDisabled,
|
||||||
@@ -132,7 +128,6 @@ mod tests {
|
|||||||
"core_start::error",
|
"core_start::error",
|
||||||
"service_core::repair_required",
|
"service_core::repair_required",
|
||||||
"service_core::app_data_not_owned",
|
"service_core::app_data_not_owned",
|
||||||
"service_core::sidecar_fallback",
|
|
||||||
"dns_override::auto_disabled",
|
"dns_override::auto_disabled",
|
||||||
"enhance::discarded_keys",
|
"enhance::discarded_keys",
|
||||||
"tun_mode::auto_disabled",
|
"tun_mode::auto_disabled",
|
||||||
|
|||||||
@@ -390,10 +390,10 @@ fn service_proxy_config(verge: &IVerge, mixed_port: u16, pac_port: u16) -> Resul
|
|||||||
/// the write's, so it stays a failure.
|
/// the write's, so it stays a failure.
|
||||||
fn service_apply_result(requested: &MacosProxyConfig, outcome: ProxyApplyOutcome) -> Result<()> {
|
fn service_apply_result(requested: &MacosProxyConfig, outcome: ProxyApplyOutcome) -> Result<()> {
|
||||||
match outcome {
|
match outcome {
|
||||||
ProxyApplyOutcome::Applied | ProxyApplyOutcome::NotRequested => Ok(()),
|
ProxyApplyOutcome::Applied => Ok(()),
|
||||||
// Direct fallback satisfies a disable request.
|
// Direct fallback satisfies a disable request.
|
||||||
ProxyApplyOutcome::DirectFallback { .. } if matches!(requested, MacosProxyConfig::Disabled) => Ok(()),
|
ProxyApplyOutcome::DirectFallback { .. } if matches!(requested, MacosProxyConfig::Disabled) => Ok(()),
|
||||||
// Older helpers encode a failed service lookup as fallback even when no OS write occurred.
|
// The service reports a missing network service as fallback before any OS write.
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
ProxyApplyOutcome::DirectFallback { message }
|
ProxyApplyOutcome::DirectFallback { message }
|
||||||
if message == sysproxy::Error::NoActiveNetworkService.to_string() =>
|
if message == sysproxy::Error::NoActiveNetworkService.to_string() =>
|
||||||
|
|||||||
@@ -67,17 +67,9 @@ impl RunStateEnv for RealEnv {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn trusted_install_evidence(&self) -> Result<bool> {
|
async fn trusted_install_evidence(&self) -> Result<bool> {
|
||||||
let registered = tokio::task::spawn_blocking(crate::core::service::trusted_service_evidence)
|
tokio::task::spawn_blocking(crate::core::service::trusted_service_evidence)
|
||||||
.await
|
.await
|
||||||
.context("service registration probe did not finish")??;
|
.context("service registration probe did not finish")?
|
||||||
// A helper that outlived its registration is a broken Service, not an absent one.
|
|
||||||
#[cfg(unix)]
|
|
||||||
if !registered && let Err(error) = clash_verge_service_ipc::execution::check_sidecar_available().await {
|
|
||||||
return Ok(error
|
|
||||||
.downcast_ref::<clash_verge_service_ipc::execution::ResidualServiceError>()
|
|
||||||
.is_some());
|
|
||||||
}
|
|
||||||
Ok(registered)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_elevated(&self) -> bool {
|
fn is_elevated(&self) -> bool {
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ pub use env::FakeEnv;
|
|||||||
pub use env::{RealEnv, RunStateEnv};
|
pub use env::{RealEnv, RunStateEnv};
|
||||||
pub use health::{PendingAction, RunState, RunStateView, ServiceHealth};
|
pub use health::{PendingAction, RunState, RunStateView, ServiceHealth};
|
||||||
pub use owner::{OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch};
|
pub use owner::{OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch};
|
||||||
pub use probe::{CORE_REJECTED_PREFIX, ServiceVersionCheck, ServiceVersionReply, classify_service_version_reply};
|
pub use probe::{ServiceVersionCheck, ServiceVersionReply, classify_service_version_reply};
|
||||||
|
|
||||||
use crate::core::manager::RunningMode;
|
use crate::core::manager::RunningMode;
|
||||||
use health::StoredService;
|
use health::StoredService;
|
||||||
@@ -336,21 +336,6 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
pub fn allow_sidecar_after_service_refusal(&self, reason: String) -> Result<()> {
|
|
||||||
let mut state = self.service.lock();
|
|
||||||
if state.operation_running || state.service.pending.is_some() {
|
|
||||||
bail!("cannot fall back while a service operation is pending");
|
|
||||||
}
|
|
||||||
// Publish the refusal and allowance together so it never asks the UI for a repair.
|
|
||||||
state.service.health = ServiceHealth::Unavailable(reason);
|
|
||||||
state.service.allow_sidecar();
|
|
||||||
state.bump();
|
|
||||||
drop(state);
|
|
||||||
self.announce();
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Requests installation only for a confirmed absent Service.
|
/// Requests installation only for a confirmed absent Service.
|
||||||
pub fn require_install_for_session(&self) -> Result<()> {
|
pub fn require_install_for_session(&self) -> Result<()> {
|
||||||
let mut state = self.service.lock();
|
let mut state = self.service.lock();
|
||||||
|
|||||||
+188
-164
@@ -10,8 +10,8 @@ use crate::{
|
|||||||
owner_identity::current_owner_credentials,
|
owner_identity::current_owner_credentials,
|
||||||
proxy_control,
|
proxy_control,
|
||||||
runstate::{
|
runstate::{
|
||||||
CORE_REJECTED_PREFIX, OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch, PendingAction, RUN_STATE,
|
OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch, PendingAction, RUN_STATE, ReadyWaitError,
|
||||||
ReadyWaitError, RunState, RunStateEnv, RunStateStore, ServiceHealth,
|
RunState, RunStateEnv, RunStateStore, ServiceHealth,
|
||||||
},
|
},
|
||||||
tray::Tray,
|
tray::Tray,
|
||||||
},
|
},
|
||||||
@@ -22,9 +22,9 @@ use clash_verge_draft::Draft;
|
|||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use clash_verge_runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of};
|
use clash_verge_runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of};
|
||||||
use clash_verge_service_ipc::{
|
use clash_verge_service_ipc::{
|
||||||
MacosProxyConfig, OwnerCredentials, OwnerIdentity, OwnerSessionProof, ProtocolInfo, ProxyApplyOutcome,
|
MacosProxyConfig, OwnerCredentials, OwnerIdentity, OwnerSessionProof, ProxyApplyOutcome, RemoteProvider,
|
||||||
RemoteProvider, RuntimeAsset, RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode,
|
RuntimeAsset, RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot,
|
||||||
ServiceStatusSnapshot, StageRuntimeOutcome, StartClashRequest, WriterConfig,
|
StageRuntimeOutcome, StartClashRequest, WriterConfig,
|
||||||
};
|
};
|
||||||
use clash_verge_task::scheduled_task::{self, Mailbox, Next, ScheduledTask};
|
use clash_verge_task::scheduled_task::{self, Mailbox, Next, ScheduledTask};
|
||||||
use clash_verge_task::watch_task;
|
use clash_verge_task::watch_task;
|
||||||
@@ -44,45 +44,21 @@ use std::{
|
|||||||
use tokio::{sync::watch, time::Instant};
|
use tokio::{sync::watch, time::Instant};
|
||||||
|
|
||||||
static OWNER_MONITOR_GENERATION: AtomicU64 = AtomicU64::new(0);
|
static OWNER_MONITOR_GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||||
static ACTIVE_SERVICE_SESSION: Mutex<Option<ActiveServiceSession>> = Mutex::new(None);
|
static PENDING_SERVICE_START: Mutex<Option<PendingServiceStart>> = Mutex::new(None);
|
||||||
static PENDING_SERVICE_FALLBACK_NOTICE: Mutex<Option<String>> = Mutex::new(None);
|
static ACTIVE_SERVICE_SESSION: Mutex<Option<Arc<OwnerSessionProof>>> = Mutex::new(None);
|
||||||
static PENDING_SERVICE_REPAIR_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);
|
static PENDING_SERVICE_OWNER_NOTICE: Mutex<Option<String>> = Mutex::new(None);
|
||||||
|
|
||||||
/// Why the Service was unavailable when the core fell back to Sidecar.
|
#[cfg(windows)]
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, specta::Type)]
|
|
||||||
#[serde(tag = "kind", content = "reason", rename_all = "camelCase")]
|
|
||||||
pub enum ServiceFallbackNotice {
|
|
||||||
Unavailable,
|
|
||||||
CoreRejected(String),
|
|
||||||
NotAutoStarted,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The release installer registers AutoStart.
|
/// The release installer registers AutoStart.
|
||||||
const SERVICE_NOT_AUTO_STARTED: &str = "the Windows service is stopped and no longer starts with Windows";
|
const SERVICE_NOT_AUTO_STARTED: &str = "the Windows service is stopped and no longer starts with Windows";
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
pub(crate) fn is_not_auto_started(reason: &str) -> bool {
|
pub(crate) fn is_not_auto_started(reason: &str) -> bool {
|
||||||
// Detection prefixes its own context to the reason.
|
// Detection prefixes its own context to the reason.
|
||||||
reason.contains(SERVICE_NOT_AUTO_STARTED)
|
reason.contains(SERVICE_NOT_AUTO_STARTED)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
pub(crate) fn notify_service_fallback(reason: &str) {
|
|
||||||
*PENDING_SERVICE_FALLBACK_NOTICE.lock() = Some(reason.to_owned());
|
|
||||||
Handle::notice(NoticeStatus::ServiceCoreSidecarFallback, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn take_service_fallback_notice() -> Option<ServiceFallbackNotice> {
|
|
||||||
let reason = PENDING_SERVICE_FALLBACK_NOTICE.lock().take()?;
|
|
||||||
Some(if reason.starts_with(CORE_REJECTED_PREFIX) {
|
|
||||||
ServiceFallbackNotice::CoreRejected(reason)
|
|
||||||
} else if is_not_auto_started(&reason) {
|
|
||||||
ServiceFallbackNotice::NotAutoStarted
|
|
||||||
} else {
|
|
||||||
ServiceFallbackNotice::Unavailable
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn take_service_repair_notice() -> bool {
|
pub(crate) fn take_service_repair_notice() -> bool {
|
||||||
PENDING_SERVICE_REPAIR_NOTICE.swap(false, Ordering::Relaxed)
|
PENDING_SERVICE_REPAIR_NOTICE.swap(false, Ordering::Relaxed)
|
||||||
}
|
}
|
||||||
@@ -100,14 +76,27 @@ fn app_data_owner_command(credentials: &OwnerCredentials) -> Option<String> {
|
|||||||
Some(format!("sudo chown -R {uid}:{gid} '{path}'"))
|
Some(format!("sudo chown -R {uid}:{gid} '{path}'"))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Capabilities of the service session that owns the running Core.
|
|
||||||
/// They are discarded with that session rather than cached across service upgrades.
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct ActiveServiceSession {
|
struct PendingServiceStart {
|
||||||
proof: Arc<OwnerSessionProof>,
|
token: String,
|
||||||
supports_runtime_staging: bool,
|
service_replaced: bool,
|
||||||
supports_runtime_file_read: bool,
|
}
|
||||||
supports_runtime_geo_read: bool,
|
|
||||||
|
impl PendingServiceStart {
|
||||||
|
const fn new(token: String) -> Self {
|
||||||
|
Self {
|
||||||
|
token,
|
||||||
|
service_replaced: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn released_after_repair(&self, status: &ServiceStatusSnapshot) -> bool {
|
||||||
|
self.service_replaced
|
||||||
|
&& !status.is_active
|
||||||
|
&& status.active_generation.is_none()
|
||||||
|
&& status.core_pid.is_none()
|
||||||
|
&& !status.desired_core_should_be_running
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn generate_service_session_token() -> Result<String> {
|
fn generate_service_session_token() -> Result<String> {
|
||||||
@@ -125,89 +114,14 @@ fn generate_service_session_token() -> Result<String> {
|
|||||||
pub(crate) fn active_service_session() -> Result<Arc<OwnerSessionProof>> {
|
pub(crate) fn active_service_session() -> Result<Arc<OwnerSessionProof>> {
|
||||||
ACTIVE_SERVICE_SESSION
|
ACTIVE_SERVICE_SESSION
|
||||||
.lock()
|
.lock()
|
||||||
.as_ref()
|
.clone()
|
||||||
.map(|session| Arc::clone(&session.proof))
|
|
||||||
.context("service owner session is not active")
|
.context("service owner session is not active")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns false unless the active service session explicitly supports in-place staging.
|
|
||||||
pub(crate) fn active_service_supports_runtime_staging() -> bool {
|
|
||||||
ACTIVE_SERVICE_SESSION
|
|
||||||
.lock()
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(|session| session.supports_runtime_staging)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn active_service_supports_runtime_file_read() -> bool {
|
|
||||||
ACTIVE_SERVICE_SESSION
|
|
||||||
.lock()
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(|session| session.supports_runtime_file_read)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn active_service_supports_runtime_geo_read() -> bool {
|
|
||||||
ACTIVE_SERVICE_SESSION
|
|
||||||
.lock()
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(|session| session.supports_runtime_geo_read)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn clear_active_service_session() {
|
pub(crate) fn clear_active_service_session() {
|
||||||
ACTIVE_SERVICE_SESSION.lock().take();
|
ACTIVE_SERVICE_SESSION.lock().take();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Default)]
|
|
||||||
struct ServiceCapabilities {
|
|
||||||
runtime_staging: bool,
|
|
||||||
runtime_file_read: bool,
|
|
||||||
runtime_geo_read: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ServiceCapabilities {
|
|
||||||
const fn of(info: &ProtocolInfo) -> Self {
|
|
||||||
Self {
|
|
||||||
runtime_staging: info.supports_runtime_staging(),
|
|
||||||
runtime_file_read: info.supports_runtime_file_read(),
|
|
||||||
runtime_geo_read: info.supports_runtime_geo_read(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Failed capability probes must not block startup.
|
|
||||||
#[tracing::instrument(skip_all, level = "info", fields(supported = tracing::field::Empty))]
|
|
||||||
async fn probe_service_capabilities() -> ServiceCapabilities {
|
|
||||||
match clash_verge_service_ipc::get_version().await {
|
|
||||||
Ok(response) if response.code == 0 => {
|
|
||||||
let capabilities = response
|
|
||||||
.data
|
|
||||||
.as_ref()
|
|
||||||
.map_or_else(ServiceCapabilities::default, ServiceCapabilities::of);
|
|
||||||
tracing::Span::current().record("supported", capabilities.runtime_staging);
|
|
||||||
capabilities
|
|
||||||
}
|
|
||||||
Ok(response) => {
|
|
||||||
tracing::Span::current().record("supported", false);
|
|
||||||
logging!(
|
|
||||||
warn,
|
|
||||||
Type::Service,
|
|
||||||
"服务协议查询返回 {}: {};配置变更将走重启路径",
|
|
||||||
response.code,
|
|
||||||
response.message
|
|
||||||
);
|
|
||||||
ServiceCapabilities::default()
|
|
||||||
}
|
|
||||||
Err(error) => {
|
|
||||||
tracing::Span::current().record("supported", false);
|
|
||||||
logging!(
|
|
||||||
warn,
|
|
||||||
Type::Service,
|
|
||||||
"无法查询服务协议版本: {error:#};配置变更将走重启路径"
|
|
||||||
);
|
|
||||||
ServiceCapabilities::default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn session_matches_status(proof: &OwnerSessionProof, is_active: bool, active_generation: Option<u64>) -> bool {
|
fn session_matches_status(proof: &OwnerSessionProof, is_active: bool, active_generation: Option<u64>) -> bool {
|
||||||
is_active && active_generation == Some(proof.generation)
|
is_active && active_generation == Some(proof.generation)
|
||||||
}
|
}
|
||||||
@@ -600,7 +514,26 @@ pub(crate) fn run_privileged_service_action(action: PendingAction) -> Result<()>
|
|||||||
PendingAction::Reinstall => (reinstall_service, "reinstall service"),
|
PendingAction::Reinstall => (reinstall_service, "reinstall service"),
|
||||||
PendingAction::ForceReinstall => (force_reinstall_service, "force reinstall service"),
|
PendingAction::ForceReinstall => (force_reinstall_service, "force reinstall service"),
|
||||||
};
|
};
|
||||||
tokio::task::block_in_place(operation).with_context(|| format!("{label} failed"))
|
tokio::task::block_in_place(|| {
|
||||||
|
let pending_token = match action {
|
||||||
|
PendingAction::Reinstall | PendingAction::ForceReinstall => PENDING_SERVICE_START
|
||||||
|
.lock()
|
||||||
|
.as_ref()
|
||||||
|
.map(|pending| pending.token.clone()),
|
||||||
|
PendingAction::Install | PendingAction::Uninstall => None,
|
||||||
|
};
|
||||||
|
operation().with_context(|| format!("{label} failed"))?;
|
||||||
|
// Full repair acquires the stopped-service guard before replacing the daemon.
|
||||||
|
if let Some(token) = pending_token
|
||||||
|
&& let Some(pending) = PENDING_SERVICE_START
|
||||||
|
.lock()
|
||||||
|
.as_mut()
|
||||||
|
.filter(|pending| pending.token == token)
|
||||||
|
{
|
||||||
|
pending.service_replaced = true;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds the same runtime bundle description for both service start and staging.
|
/// Builds the same runtime bundle description for both service start and staging.
|
||||||
@@ -648,12 +581,11 @@ impl StageRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Requests in-place staging. `Err` means no answer; refusals are returned for caller policy.
|
/// Requests in-place staging. `Err` means no answer; refusals are returned for caller policy.
|
||||||
pub(super) async fn stage_runtime_by_service(config_file: &Path) -> Result<StageRequest> {
|
pub(super) async fn stage_runtime_by_service(config_file: &Path, session: &OwnerSessionProof) -> Result<StageRequest> {
|
||||||
let session = active_service_session()?;
|
|
||||||
let credentials = current_owner_credentials()?;
|
let credentials = current_owner_credentials()?;
|
||||||
let runtime = collect_service_runtime_bundle(config_file).await?;
|
let runtime = collect_service_runtime_bundle(config_file).await?;
|
||||||
|
|
||||||
let response = clash_verge_service_ipc::stage_runtime(&credentials, &session, &runtime)
|
let response = clash_verge_service_ipc::stage_runtime(&credentials, session, &runtime)
|
||||||
.await
|
.await
|
||||||
.context("无法连接到Clash Verge Service")?;
|
.context("无法连接到Clash Verge Service")?;
|
||||||
if response.code > 0 {
|
if response.code > 0 {
|
||||||
@@ -700,27 +632,86 @@ fn record_service_start_refusal<E: RunStateEnv>(
|
|||||||
refusal.into()
|
refusal.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sidecar stays blocked until a reinstall replaces the residual helper, so ask for repair.
|
pub(super) fn require_service_core_released() -> Result<()> {
|
||||||
pub(super) fn record_residual_service(error: &anyhow::Error) {
|
anyhow::ensure!(
|
||||||
if let Some(residual) = error.downcast_ref::<clash_verge_service_ipc::execution::ResidualServiceError>() {
|
PENDING_SERVICE_START.lock().is_none() && ACTIVE_SERVICE_SESSION.lock().is_none(),
|
||||||
RUN_STATE.observe(ServiceHealth::Unavailable(residual.to_string()));
|
"the previous Service core has not confirmed exit"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn release_service_core_for_sidecar() -> Result<()> {
|
||||||
|
let pending = PENDING_SERVICE_START.lock().clone();
|
||||||
|
if pending.is_none() {
|
||||||
|
if active_service_session().is_ok() {
|
||||||
|
return stop_core_by_service().await;
|
||||||
|
}
|
||||||
|
if matches!(RUN_STATE.state().health, ServiceHealth::NotInstalled) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
let credentials = current_owner_credentials()?;
|
||||||
|
let status = tokio::time::timeout(
|
||||||
|
Duration::from_secs(2),
|
||||||
|
clash_verge_service_ipc::get_status(&credentials),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.context("timed out confirming the previous Service core exited")??;
|
||||||
|
anyhow::ensure!(status.code == 0, "Service status failed: {}", status.message);
|
||||||
|
let status = status.data.context("Service omitted owner status")?;
|
||||||
|
let Some(pending) = pending else {
|
||||||
|
anyhow::ensure!(
|
||||||
|
!status.is_active || (status.core_pid.is_none() && !status.desired_core_should_be_running),
|
||||||
|
"the Service is running or recovering this owner's core; stop it before switching"
|
||||||
|
);
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
if pending.released_after_repair(&status) {
|
||||||
|
PENDING_SERVICE_START.lock().take();
|
||||||
|
clear_active_service_session();
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
// A lost Start reply may have committed. Only its proposed token can stop that generation.
|
||||||
|
let generation = status
|
||||||
|
.active_generation
|
||||||
|
.context("the previous Service start has not confirmed exit; repair the Service before switching")?;
|
||||||
|
let stopped = clash_verge_service_ipc::stop_clash(
|
||||||
|
&credentials,
|
||||||
|
&OwnerSessionProof {
|
||||||
|
generation,
|
||||||
|
token: pending.token,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
anyhow::ensure!(
|
||||||
|
stopped.code == 0,
|
||||||
|
"could not confirm Service core exit: {}",
|
||||||
|
stopped.message
|
||||||
|
);
|
||||||
|
PENDING_SERVICE_START.lock().take();
|
||||||
|
clear_active_service_session();
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 尝试使用服务启动core
|
/// 尝试使用服务启动core
|
||||||
#[tracing::instrument(skip_all, level = "info", fields(generation = tracing::field::Empty, staging = tracing::field::Empty, code = tracing::field::Empty, outcome = tracing::field::Empty))]
|
#[tracing::instrument(skip_all, level = "info", fields(generation = tracing::field::Empty, code = tracing::field::Empty, outcome = tracing::field::Empty))]
|
||||||
pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()> {
|
async fn start_with_existing_service(
|
||||||
clear_active_service_session();
|
config_file: &Path,
|
||||||
|
start: &tokio::sync::OnceCell<StartClashRequest>,
|
||||||
|
) -> Result<()> {
|
||||||
let credentials = current_owner_credentials()?;
|
let credentials = current_owner_credentials()?;
|
||||||
let runtime = collect_service_runtime_bundle(config_file).await?;
|
let request = start
|
||||||
let request = StartClashRequest {
|
.get_or_try_init(|| async {
|
||||||
runtime,
|
Ok::<_, anyhow::Error>(StartClashRequest {
|
||||||
proposed_session_token: generate_service_session_token()?,
|
runtime: collect_service_runtime_bundle(config_file).await?,
|
||||||
macos_proxy: None,
|
proposed_session_token: generate_service_session_token()?,
|
||||||
};
|
})
|
||||||
|
})
|
||||||
let response = match clash_verge_service_ipc::start_clash(&credentials, &request).await {
|
.await?;
|
||||||
|
let previous = PENDING_SERVICE_START
|
||||||
|
.lock()
|
||||||
|
.replace(PendingServiceStart::new(request.proposed_session_token.clone()));
|
||||||
|
let response = match clash_verge_service_ipc::start_clash(&credentials, request).await {
|
||||||
Ok(response) => response,
|
Ok(response) => response,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
tracing::Span::current().record("outcome", "ipc-unreachable");
|
tracing::Span::current().record("outcome", "ipc-unreachable");
|
||||||
@@ -732,6 +723,16 @@ pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()
|
|||||||
if response.code > 0 {
|
if response.code > 0 {
|
||||||
tracing::Span::current().record("code", response.code);
|
tracing::Span::current().record("code", response.code);
|
||||||
tracing::Span::current().record("outcome", "refused");
|
tracing::Span::current().record("outcome", "refused");
|
||||||
|
if matches!(response.code,
|
||||||
|
code if code == ServiceErrorCode::InvalidInstallLocation as u16
|
||||||
|
|| code == ServiceErrorCode::InvalidRuntimeAsset as u16
|
||||||
|
|| code == ServiceErrorCode::AppDataRootNotOwned as u16
|
||||||
|
|| code == ServiceErrorCode::UnauthorizedOwner as u16
|
||||||
|
|| code == ServiceErrorCode::ProtocolMismatch as u16
|
||||||
|
|| code == ServiceErrorCode::ProxyClearFailed as u16
|
||||||
|
) {
|
||||||
|
*PENDING_SERVICE_START.lock() = previous;
|
||||||
|
}
|
||||||
let err_msg = response.message;
|
let err_msg = response.message;
|
||||||
logging!(
|
logging!(
|
||||||
error,
|
error,
|
||||||
@@ -754,43 +755,39 @@ pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()
|
|||||||
&RUN_STATE,
|
&RUN_STATE,
|
||||||
ServiceStartRefusal {
|
ServiceStartRefusal {
|
||||||
code: response.code,
|
code: response.code,
|
||||||
core_path: request.runtime.core_path,
|
core_path: request.runtime.core_path.clone(),
|
||||||
message: err_msg,
|
message: err_msg,
|
||||||
},
|
},
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let result = response.data.context("Clash Verge Service 未返回会话信息")?;
|
let result = response.data.context("Clash Verge Service 未返回会话信息")?;
|
||||||
tracing::Span::current().record("generation", result.session.generation);
|
tracing::Span::current().record("generation", result.generation);
|
||||||
let capabilities = probe_service_capabilities().await;
|
*ACTIVE_SERVICE_SESSION.lock() = Some(Arc::new(OwnerSessionProof {
|
||||||
tracing::Span::current().record("staging", capabilities.runtime_staging);
|
generation: result.generation,
|
||||||
*ACTIVE_SERVICE_SESSION.lock() = Some(ActiveServiceSession {
|
token: request.proposed_session_token.clone(),
|
||||||
proof: Arc::new(OwnerSessionProof {
|
}));
|
||||||
generation: result.session.generation,
|
|
||||||
token: request.proposed_session_token,
|
|
||||||
}),
|
|
||||||
supports_runtime_staging: capabilities.runtime_staging,
|
|
||||||
supports_runtime_file_read: capabilities.runtime_file_read,
|
|
||||||
supports_runtime_geo_read: capabilities.runtime_geo_read,
|
|
||||||
});
|
|
||||||
|
|
||||||
|
PENDING_SERVICE_START.lock().take();
|
||||||
// PAC follows the Running Mode; the caller opens it via `core_started(Service)`.
|
// PAC follows the Running Mode; the caller opens it via `core_started(Service)`.
|
||||||
start_owner_monitor();
|
start_owner_monitor();
|
||||||
tracing::Span::current().record("outcome", "started");
|
tracing::Span::current().record("outcome", "started");
|
||||||
PENDING_SERVICE_FALLBACK_NOTICE.lock().take();
|
|
||||||
PENDING_SERVICE_REPAIR_NOTICE.store(false, Ordering::Relaxed);
|
PENDING_SERVICE_REPAIR_NOTICE.store(false, Ordering::Relaxed);
|
||||||
PENDING_SERVICE_OWNER_NOTICE.lock().take();
|
PENDING_SERVICE_OWNER_NOTICE.lock().take();
|
||||||
logging!(
|
logging!(
|
||||||
info,
|
info,
|
||||||
Type::Service,
|
Type::Service,
|
||||||
"服务成功启动核心 (session generation {})",
|
"服务成功启动核心 (session generation {})",
|
||||||
result.session.generation
|
result.generation
|
||||||
);
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
// 以服务启动core
|
// 以服务启动core
|
||||||
pub(super) async fn run_core_by_service(config_file: &Path) -> Result<()> {
|
pub(super) async fn run_core_by_service(
|
||||||
|
config_file: &Path,
|
||||||
|
start: &tokio::sync::OnceCell<StartClashRequest>,
|
||||||
|
) -> Result<()> {
|
||||||
SERVICE_MANAGER.refresh().await?;
|
SERVICE_MANAGER.refresh().await?;
|
||||||
|
|
||||||
let status = SERVICE_MANAGER.current().await;
|
let status = SERVICE_MANAGER.current().await;
|
||||||
@@ -799,7 +796,7 @@ pub(super) async fn run_core_by_service(config_file: &Path) -> Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
logging!(info, Type::Service, "服务已运行且版本匹配,直接使用");
|
logging!(info, Type::Service, "服务已运行且版本匹配,直接使用");
|
||||||
start_with_existing_service(config_file).await
|
start_with_existing_service(config_file, start).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn capture_generation_before<F, Fut, T>(generation: &AtomicU64, operation: F) -> (u64, T)
|
async fn capture_generation_before<F, Fut, T>(generation: &AtomicU64, operation: F) -> (u64, T)
|
||||||
@@ -956,11 +953,10 @@ type ProviderLoadTimes = HashMap<(&'static str, String), Option<u64>>;
|
|||||||
|
|
||||||
#[tracing::instrument(level = "info", fields(synced = tracing::field::Empty, pending = tracing::field::Empty))]
|
#[tracing::instrument(level = "info", fields(synced = tracing::field::Empty, pending = tracing::field::Empty))]
|
||||||
async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
|
async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
|
||||||
if !active_service_supports_runtime_file_read() {
|
let Ok(session) = active_service_session() else {
|
||||||
return Ok(ProviderSync::default());
|
return Ok(ProviderSync::default());
|
||||||
}
|
};
|
||||||
let credentials = current_owner_credentials()?;
|
let credentials = current_owner_credentials()?;
|
||||||
let session = active_service_session()?;
|
|
||||||
let app_dir = dirs::app_home_dir()?;
|
let app_dir = dirs::app_home_dir()?;
|
||||||
let runtime = Config::runtime().await;
|
let runtime = Config::runtime().await;
|
||||||
let mut outcome = ProviderSync::default();
|
let mut outcome = ProviderSync::default();
|
||||||
@@ -1046,14 +1042,10 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
|
|||||||
|
|
||||||
/// Pulls geo databases the service core rewrote, because validation reads the app dir.
|
/// Pulls geo databases the service core rewrote, because validation reads the app dir.
|
||||||
pub(crate) async fn sync_runtime_geo_by_service() {
|
pub(crate) async fn sync_runtime_geo_by_service() {
|
||||||
if !active_service_supports_runtime_geo_read() {
|
let Ok(session) = active_service_session() else {
|
||||||
return;
|
return;
|
||||||
}
|
};
|
||||||
let (Ok(credentials), Ok(session), Ok(app_dir)) = (
|
let (Ok(credentials), Ok(app_dir)) = (current_owner_credentials(), dirs::app_home_dir()) else {
|
||||||
current_owner_credentials(),
|
|
||||||
active_service_session(),
|
|
||||||
dirs::app_home_dir(),
|
|
||||||
) else {
|
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
for asset in GEO_ASSETS {
|
for asset in GEO_ASSETS {
|
||||||
@@ -1641,7 +1633,7 @@ fn session_matches_active_status(is_active: bool, active_generation: Option<u64>
|
|||||||
ACTIVE_SERVICE_SESSION
|
ACTIVE_SERVICE_SESSION
|
||||||
.lock()
|
.lock()
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.is_some_and(|session| session_matches_status(&session.proof, is_active, active_generation))
|
.is_some_and(|session| session_matches_status(session, is_active, active_generation))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn cancel_owner_monitors() {
|
fn cancel_owner_monitors() {
|
||||||
@@ -1709,6 +1701,11 @@ async fn recover_after_owner_loss_while_locked(reason: OwnerRecoveryReason) {
|
|||||||
if policy.reset_system_proxy {
|
if policy.reset_system_proxy {
|
||||||
clear_proxy_after_owner_loss().await;
|
clear_proxy_after_owner_loss().await;
|
||||||
}
|
}
|
||||||
|
if matches!(reason, OwnerRecoveryReason::TransportFailure)
|
||||||
|
&& let Ok(session) = active_service_session()
|
||||||
|
{
|
||||||
|
*PENDING_SERVICE_START.lock() = Some(PendingServiceStart::new(session.token.clone()));
|
||||||
|
}
|
||||||
clear_active_service_session();
|
clear_active_service_session();
|
||||||
CoreManager::global().core_stopped();
|
CoreManager::global().core_stopped();
|
||||||
// A displaced Service may still run TUN for its new owner, and DNS settings are system-wide.
|
// A displaced Service may still run TUN for its new owner, and DNS settings are system-wide.
|
||||||
@@ -1995,6 +1992,33 @@ mod tests {
|
|||||||
ServiceStatus::from_run_state(&store.settled().await)
|
ServiceStatus::from_run_state(&store.settled().await)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_idle_snapshot_releases_an_ambiguous_start_only_after_repair() {
|
||||||
|
let mut pending = super::PendingServiceStart::new("lost-reply".into());
|
||||||
|
let mut status = clash_verge_service_ipc::ServiceStatusSnapshot {
|
||||||
|
is_active: false,
|
||||||
|
active_generation: None,
|
||||||
|
core_pid: None,
|
||||||
|
desired_core_should_be_running: false,
|
||||||
|
service_state: clash_verge_service_ipc::ServiceLifecycleState::Running,
|
||||||
|
core_started_at: None,
|
||||||
|
last_core_exit_reason: None,
|
||||||
|
restart_count: 0,
|
||||||
|
last_recovery_at: None,
|
||||||
|
desired_generation: 0,
|
||||||
|
desired_updated_at: 0,
|
||||||
|
desired_persistence_error: None,
|
||||||
|
};
|
||||||
|
assert!(!pending.released_after_repair(&status));
|
||||||
|
pending.service_replaced = true;
|
||||||
|
assert!(pending.released_after_repair(&status));
|
||||||
|
status.active_generation = Some(1);
|
||||||
|
assert!(!pending.released_after_repair(&status));
|
||||||
|
status.active_generation = None;
|
||||||
|
status.desired_core_should_be_running = true;
|
||||||
|
assert!(!pending.released_after_repair(&status));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn mismatched_active_generation_displaces_local_session() {
|
fn mismatched_active_generation_displaces_local_session() {
|
||||||
let proof = OwnerSessionProof {
|
let proof = OwnerSessionProof {
|
||||||
|
|||||||
@@ -51,7 +51,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
|||||||
cmd::apply_dns_config,
|
cmd::apply_dns_config,
|
||||||
cmd::set_dns_override,
|
cmd::set_dns_override,
|
||||||
cmd::take_dns_override_notice,
|
cmd::take_dns_override_notice,
|
||||||
cmd::take_service_fallback_notice,
|
|
||||||
cmd::get_core_startup_error,
|
cmd::get_core_startup_error,
|
||||||
cmd::take_service_repair_notice,
|
cmd::take_service_repair_notice,
|
||||||
cmd::take_service_owner_notice,
|
cmd::take_service_owner_notice,
|
||||||
|
|||||||
@@ -60,34 +60,20 @@ it.each([
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
it('reports the permission refusal and finishes after installation falls back to Sidecar', async () => {
|
it('leaves the choice open when installation fails', async () => {
|
||||||
store.runState = {
|
store.runState = { service: 'notInstalled', mode: 'NotRunning' } as RunState
|
||||||
service: 'notInstalled',
|
const error = new Error('core path is writable by Everyone')
|
||||||
mode: 'NotRunning',
|
vi.mocked(installService).mockRejectedValue(error)
|
||||||
} as unknown as RunState
|
vi.mocked(getRuntimeState).mockResolvedValue(store.runState)
|
||||||
const reason = 'core path C:\\ is writable by Everyone'
|
|
||||||
vi.mocked(installService).mockResolvedValue({ status: 'sidecar', reason })
|
|
||||||
vi.mocked(getRuntimeState).mockResolvedValue({
|
|
||||||
service: 'unavailable',
|
|
||||||
mode: 'Sidecar',
|
|
||||||
sidecarAllowed: true,
|
|
||||||
serviceNeedsAttention: false,
|
|
||||||
} as RunState)
|
|
||||||
|
|
||||||
const dialog = ServiceMigrationDialog()
|
|
||||||
dialog.props.onOk()
|
|
||||||
await vi.waitFor(() => {
|
|
||||||
expect(showNotice.warning).toHaveBeenCalledWith(
|
|
||||||
'settings.feedback.notifications.clashService.permissionFallback',
|
|
||||||
{ reason },
|
|
||||||
0,
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
|
ServiceMigrationDialog().props.onOk()
|
||||||
|
await vi.waitFor(() => expect(getRuntimeState).toHaveBeenCalled())
|
||||||
|
expect(showNotice.error).toHaveBeenCalledWith(
|
||||||
|
'layout.components.serviceMigration.errors.actionFailed',
|
||||||
|
error,
|
||||||
|
)
|
||||||
expect(restartCore).not.toHaveBeenCalled()
|
expect(restartCore).not.toHaveBeenCalled()
|
||||||
expect(showNotice.error).not.toHaveBeenCalled()
|
expect(vi.mocked(useState).mock.results[2].value[1]).not.toHaveBeenCalledWith(
|
||||||
expect(showNotice.success).not.toHaveBeenCalled()
|
|
||||||
expect(vi.mocked(useState).mock.results[2].value[1]).toHaveBeenLastCalledWith(
|
|
||||||
false,
|
false,
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import {
|
|||||||
reinstallService,
|
reinstallService,
|
||||||
repairService,
|
repairService,
|
||||||
restartCore,
|
restartCore,
|
||||||
type ServiceInstallOutcome,
|
|
||||||
} from '@/services/cmds'
|
} from '@/services/cmds'
|
||||||
import { mutate } from '@/services/mutate'
|
import { mutate } from '@/services/mutate'
|
||||||
import { showNotice } from '@/services/notice-service'
|
import { showNotice } from '@/services/notice-service'
|
||||||
@@ -70,26 +69,26 @@ export const ServiceMigrationDialog = () => {
|
|||||||
const handleServiceAction = async () => {
|
const handleServiceAction = async () => {
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
setWorkflowIncomplete(true)
|
setWorkflowIncomplete(true)
|
||||||
let outcome: ServiceInstallOutcome | undefined
|
let installed = false
|
||||||
try {
|
try {
|
||||||
if (remedy === 'install') {
|
if (remedy === 'install') {
|
||||||
const result = await mutate(() => installService(), {
|
const result = await mutate(() => installService(), {
|
||||||
id: 'install-service',
|
id: 'install-service',
|
||||||
errorNotice: false,
|
errorNotice: false,
|
||||||
})
|
})
|
||||||
if (result.ok) outcome = result.value
|
installed = result.ok
|
||||||
} else if (remedy === 'repair') {
|
} else if (remedy === 'repair') {
|
||||||
const result = await mutate(() => repairService(), {
|
const result = await mutate(() => repairService(), {
|
||||||
id: 'repair-service',
|
id: 'repair-service',
|
||||||
errorNotice: false,
|
errorNotice: false,
|
||||||
})
|
})
|
||||||
if (result.ok) outcome = result.value
|
installed = result.ok
|
||||||
} else {
|
} else {
|
||||||
const result = await mutate(() => reinstallService(), {
|
const result = await mutate(() => reinstallService(), {
|
||||||
id: 'reinstall-service',
|
id: 'reinstall-service',
|
||||||
errorNotice: false,
|
errorNotice: false,
|
||||||
})
|
})
|
||||||
if (result.ok) outcome = result.value
|
installed = result.ok
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
showNotice.error(
|
showNotice.error(
|
||||||
@@ -108,21 +107,10 @@ export const ServiceMigrationDialog = () => {
|
|||||||
error,
|
error,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (!outcome || !initialRefreshSucceeded) {
|
if (!installed || !initialRefreshSucceeded) {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (outcome.status === 'sidecar') {
|
|
||||||
setWorkflowIncomplete(false)
|
|
||||||
setLoading(false)
|
|
||||||
showNotice.warning(
|
|
||||||
'settings.feedback.notifications.clashService.permissionFallback',
|
|
||||||
{ reason: outcome.reason },
|
|
||||||
0,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
let restartSucceeded = false
|
let restartSucceeded = false
|
||||||
try {
|
try {
|
||||||
const result = await mutate(() => restartCore(), {
|
const result = await mutate(() => restartCore(), {
|
||||||
@@ -214,6 +202,9 @@ export const ServiceMigrationDialog = () => {
|
|||||||
? 'layout.components.serviceMigration.message'
|
? 'layout.components.serviceMigration.message'
|
||||||
: 'layout.components.serviceMigration.unavailableMessage',
|
: 'layout.components.serviceMigration.unavailableMessage',
|
||||||
)}
|
)}
|
||||||
|
{!showCheckingMessage && runState?.serviceUnavailableReason && (
|
||||||
|
<div>{runState.serviceUnavailableReason}</div>
|
||||||
|
)}
|
||||||
</Alert>
|
</Alert>
|
||||||
</BaseDialog>
|
</BaseDialog>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import {
|
|||||||
restartCore,
|
restartCore,
|
||||||
type FailedOperation,
|
type FailedOperation,
|
||||||
type PendingFailure,
|
type PendingFailure,
|
||||||
type ServiceInstallOutcome,
|
|
||||||
} from '@/services/cmds'
|
} from '@/services/cmds'
|
||||||
import { mutate } from '@/services/mutate'
|
import { mutate } from '@/services/mutate'
|
||||||
import { showNotice } from '@/services/notice-service'
|
import { showNotice } from '@/services/notice-service'
|
||||||
@@ -23,7 +22,6 @@ import {
|
|||||||
type ServiceRequestReason,
|
type ServiceRequestReason,
|
||||||
} from '@/services/service-request'
|
} from '@/services/service-request'
|
||||||
import { useAppReads } from '@/store/app-store-context'
|
import { useAppReads } from '@/store/app-store-context'
|
||||||
import getSystem from '@/utils/get-system'
|
|
||||||
|
|
||||||
type Remedy = 'installAndRestart' | 'reinstallAndRestart' | 'restartOnly'
|
type Remedy = 'installAndRestart' | 'reinstallAndRestart' | 'restartOnly'
|
||||||
|
|
||||||
@@ -105,30 +103,20 @@ export const SysproxyPrivilegeDialog = () => {
|
|||||||
|
|
||||||
const handleFix = async () => {
|
const handleFix = async () => {
|
||||||
try {
|
try {
|
||||||
let outcome: ServiceInstallOutcome | undefined
|
|
||||||
if (remedy === 'reinstallAndRestart') {
|
if (remedy === 'reinstallAndRestart') {
|
||||||
setStep('installing')
|
setStep('installing')
|
||||||
const result = await mutate(() => reinstallService(), {
|
const result = await mutate(() => reinstallService(), {
|
||||||
id: 'reinstall-service',
|
id: 'reinstall-service',
|
||||||
errorNotice: false,
|
errorNotice: false,
|
||||||
})
|
})
|
||||||
if (result.ok) outcome = result.value
|
if (!result.ok) return
|
||||||
} else if (remedy === 'installAndRestart') {
|
} else if (remedy === 'installAndRestart') {
|
||||||
setStep('installing')
|
setStep('installing')
|
||||||
const result = await mutate(() => installService(), {
|
const result = await mutate(() => installService(), {
|
||||||
id: 'install-service',
|
id: 'install-service',
|
||||||
errorNotice: false,
|
errorNotice: false,
|
||||||
})
|
})
|
||||||
if (result.ok) outcome = result.value
|
if (!result.ok) return
|
||||||
}
|
|
||||||
if (outcome?.status === 'sidecar') {
|
|
||||||
showNotice.warning(
|
|
||||||
'settings.feedback.notifications.clashService.permissionFallback',
|
|
||||||
{ reason: outcome.reason },
|
|
||||||
0,
|
|
||||||
)
|
|
||||||
close()
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
setStep('restarting')
|
setStep('restarting')
|
||||||
await mutate(() => restartCore(), {
|
await mutate(() => restartCore(), {
|
||||||
@@ -137,14 +125,7 @@ export const SysproxyPrivilegeDialog = () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
const runState = await readRunState()
|
const runState = await readRunState()
|
||||||
const usingAdminFallback =
|
if (runState.mode === 'Service') {
|
||||||
remedy !== 'reinstallAndRestart' &&
|
|
||||||
getSystem() === 'windows' &&
|
|
||||||
runState.mode === 'Sidecar' &&
|
|
||||||
runState.isAdmin &&
|
|
||||||
runState.sidecarAllowed &&
|
|
||||||
runState.service === 'unavailable'
|
|
||||||
if (runState.mode === 'Service' || usingAdminFallback) {
|
|
||||||
if (restoring !== undefined) {
|
if (restoring !== undefined) {
|
||||||
setStep('applying')
|
setStep('applying')
|
||||||
await mutate(() => patchVergeConfig(restoring), {
|
await mutate(() => patchVergeConfig(restoring), {
|
||||||
@@ -152,15 +133,13 @@ export const SysproxyPrivilegeDialog = () => {
|
|||||||
errorNotice: false,
|
errorNotice: false,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
if (!usingAdminFallback) {
|
showNotice.success(
|
||||||
showNotice.success(
|
remedy === 'reinstallAndRestart'
|
||||||
remedy === 'reinstallAndRestart'
|
? 'layout.components.serviceMigration.success'
|
||||||
? 'layout.components.serviceMigration.success'
|
: restoring === undefined
|
||||||
: restoring === undefined
|
? 'settings.sections.proxyControl.messages.installedCheckProxy'
|
||||||
? 'settings.sections.proxyControl.messages.installedCheckProxy'
|
: 'settings.sections.proxyControl.messages.installedProxyRestored',
|
||||||
: 'settings.sections.proxyControl.messages.installedProxyRestored',
|
)
|
||||||
)
|
|
||||||
}
|
|
||||||
close()
|
close()
|
||||||
} else {
|
} else {
|
||||||
showNotice.error(
|
showNotice.error(
|
||||||
|
|||||||
@@ -33,14 +33,6 @@ export const useServiceInstaller = () => {
|
|||||||
'settings.statuses.clashService.installing',
|
'settings.statuses.clashService.installing',
|
||||||
)
|
)
|
||||||
if (!installResult.ok) return
|
if (!installResult.ok) return
|
||||||
if (installResult.value.status === 'sidecar') {
|
|
||||||
showNotice.warning(
|
|
||||||
'settings.feedback.notifications.clashService.permissionFallback',
|
|
||||||
{ reason: installResult.value.reason },
|
|
||||||
0,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
showNotice.success(
|
showNotice.success(
|
||||||
'settings.feedback.notifications.clashService.installSuccess',
|
'settings.feedback.notifications.clashService.installSuccess',
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -44,12 +44,10 @@ export const commands = {
|
|||||||
getSidecarFailure: () =>
|
getSidecarFailure: () =>
|
||||||
__TAURI_INVOKE<SidecarFailureSnapshot_Serialize>('get_sidecar_failure'),
|
__TAURI_INVOKE<SidecarFailureSnapshot_Serialize>('get_sidecar_failure'),
|
||||||
entryLightweightMode: () => __TAURI_INVOKE<null>('entry_lightweight_mode'),
|
entryLightweightMode: () => __TAURI_INVOKE<null>('entry_lightweight_mode'),
|
||||||
installService: () =>
|
installService: () => __TAURI_INVOKE<null>('install_service'),
|
||||||
__TAURI_INVOKE<ServiceInstallOutcome>('install_service'),
|
|
||||||
uninstallService: () => __TAURI_INVOKE<null>('uninstall_service'),
|
uninstallService: () => __TAURI_INVOKE<null>('uninstall_service'),
|
||||||
reinstallService: () =>
|
reinstallService: () => __TAURI_INVOKE<null>('reinstall_service'),
|
||||||
__TAURI_INVOKE<ServiceInstallOutcome>('reinstall_service'),
|
repairService: () => __TAURI_INVOKE<null>('repair_service'),
|
||||||
repairService: () => __TAURI_INVOKE<ServiceInstallOutcome>('repair_service'),
|
|
||||||
continueWithSidecar: () => __TAURI_INVOKE<null>('continue_with_sidecar'),
|
continueWithSidecar: () => __TAURI_INVOKE<null>('continue_with_sidecar'),
|
||||||
syncRuntimeProviders: () => __TAURI_INVOKE<void>('sync_runtime_providers'),
|
syncRuntimeProviders: () => __TAURI_INVOKE<void>('sync_runtime_providers'),
|
||||||
getClashInfo: () => __TAURI_INVOKE<ClashInfo_Serialize>('get_clash_info'),
|
getClashInfo: () => __TAURI_INVOKE<ClashInfo_Serialize>('get_clash_info'),
|
||||||
@@ -99,10 +97,6 @@ export const commands = {
|
|||||||
}),
|
}),
|
||||||
takeDnsOverrideNotice: () =>
|
takeDnsOverrideNotice: () =>
|
||||||
__TAURI_INVOKE<boolean>('take_dns_override_notice'),
|
__TAURI_INVOKE<boolean>('take_dns_override_notice'),
|
||||||
takeServiceFallbackNotice: () =>
|
|
||||||
__TAURI_INVOKE<ServiceFallbackNotice | null>(
|
|
||||||
'take_service_fallback_notice',
|
|
||||||
),
|
|
||||||
getCoreStartupError: () =>
|
getCoreStartupError: () =>
|
||||||
__TAURI_INVOKE<CoreFailure | null>('get_core_startup_error'),
|
__TAURI_INVOKE<CoreFailure | null>('get_core_startup_error'),
|
||||||
takeServiceRepairNotice: () =>
|
takeServiceRepairNotice: () =>
|
||||||
@@ -627,7 +621,6 @@ export type NoticeStatus =
|
|||||||
| 'core_start::error'
|
| 'core_start::error'
|
||||||
| 'service_core::repair_required'
|
| 'service_core::repair_required'
|
||||||
| 'service_core::app_data_not_owned'
|
| 'service_core::app_data_not_owned'
|
||||||
| 'service_core::sidecar_fallback'
|
|
||||||
| 'dns_override::auto_disabled'
|
| 'dns_override::auto_disabled'
|
||||||
| 'enhance::discarded_keys'
|
| 'enhance::discarded_keys'
|
||||||
| 'tun_mode::auto_disabled'
|
| 'tun_mode::auto_disabled'
|
||||||
@@ -1040,12 +1033,6 @@ export type SaveProxyPortsOutcome =
|
|||||||
| { status: 'saved' }
|
| { status: 'saved' }
|
||||||
| { status: 'conflict'; port: number; transport: ListenerTransport }
|
| { status: 'conflict'; port: number; transport: ListenerTransport }
|
||||||
|
|
||||||
/** Why the Service was unavailable when the core fell back to Sidecar. */
|
|
||||||
export type ServiceFallbackNotice =
|
|
||||||
| { kind: 'unavailable' }
|
|
||||||
| { kind: 'coreRejected'; reason: string }
|
|
||||||
| { kind: 'notAutoStarted' }
|
|
||||||
|
|
||||||
export type ServiceHealthKind =
|
export type ServiceHealthKind =
|
||||||
| 'unknown'
|
| 'unknown'
|
||||||
| 'ready'
|
| 'ready'
|
||||||
@@ -1053,10 +1040,6 @@ export type ServiceHealthKind =
|
|||||||
| 'versionMismatch'
|
| 'versionMismatch'
|
||||||
| 'unavailable'
|
| 'unavailable'
|
||||||
|
|
||||||
export type ServiceInstallOutcome =
|
|
||||||
| { status: 'installed' }
|
|
||||||
| { status: 'sidecar'; reason: string }
|
|
||||||
|
|
||||||
/** A removal has a revision too, so a delayed read cannot restore a resolved failure. */
|
/** A removal has a revision too, so a delayed read cannot restore a resolved failure. */
|
||||||
export type SidecarFailureSnapshot =
|
export type SidecarFailureSnapshot =
|
||||||
| SidecarFailureSnapshot_Serialize
|
| SidecarFailureSnapshot_Serialize
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import {
|
|||||||
type RunState,
|
type RunState,
|
||||||
getCoreStartupError,
|
getCoreStartupError,
|
||||||
takeDnsOverrideNotice,
|
takeDnsOverrideNotice,
|
||||||
takeServiceFallbackNotice,
|
|
||||||
takeServiceRepairNotice,
|
takeServiceRepairNotice,
|
||||||
} from '@/services/cmds'
|
} from '@/services/cmds'
|
||||||
import { showNotice } from '@/services/notice-service'
|
import { showNotice } from '@/services/notice-service'
|
||||||
@@ -24,7 +23,6 @@ vi.mock('@/services/cmds', () => ({
|
|||||||
getPendingFailures: vi.fn().mockResolvedValue([]),
|
getPendingFailures: vi.fn().mockResolvedValue([]),
|
||||||
takeDiscardedKeysNotice: vi.fn().mockResolvedValue(null),
|
takeDiscardedKeysNotice: vi.fn().mockResolvedValue(null),
|
||||||
takeDnsOverrideNotice: vi.fn().mockResolvedValue(false),
|
takeDnsOverrideNotice: vi.fn().mockResolvedValue(false),
|
||||||
takeServiceFallbackNotice: vi.fn().mockResolvedValue(null),
|
|
||||||
takeServiceRepairNotice: vi.fn().mockResolvedValue(false),
|
takeServiceRepairNotice: vi.fn().mockResolvedValue(false),
|
||||||
takeServiceOwnerNotice: vi.fn().mockResolvedValue(null),
|
takeServiceOwnerNotice: vi.fn().mockResolvedValue(null),
|
||||||
}))
|
}))
|
||||||
@@ -179,22 +177,3 @@ it('offers service reinstallation for a startup path refusal even before listene
|
|||||||
reason: 'serviceLocationRefused',
|
reason: 'serviceLocationRefused',
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
it('explains a startup core rejection instead of the generic fallback notice', async () => {
|
|
||||||
const reason =
|
|
||||||
'approved core was rejected: core path "C:\\" has an untrusted write ACE'
|
|
||||||
vi.mocked(takeServiceFallbackNotice)
|
|
||||||
.mockResolvedValueOnce({ kind: 'coreRejected', reason })
|
|
||||||
.mockResolvedValue(null)
|
|
||||||
|
|
||||||
const bus = await mountBus()
|
|
||||||
bus.onSubscribed()
|
|
||||||
bus.handlers['verge://notice-message'](['service_core::sidecar_fallback', ''])
|
|
||||||
await flush()
|
|
||||||
|
|
||||||
expect(showNotice.warning).toHaveBeenCalledExactlyOnceWith(
|
|
||||||
'settings.feedback.notifications.clashService.permissionFallback',
|
|
||||||
{ reason },
|
|
||||||
0,
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|||||||
@@ -92,7 +92,6 @@ export const createEventBus = (deps: BusHandlerDeps) => {
|
|||||||
deps.readPendingFailures()
|
deps.readPendingFailures()
|
||||||
deps.handleNotice(['dns_override::auto_disabled', ''])
|
deps.handleNotice(['dns_override::auto_disabled', ''])
|
||||||
deps.handleNotice(['enhance::discarded_keys', ''])
|
deps.handleNotice(['enhance::discarded_keys', ''])
|
||||||
deps.handleNotice(['service_core::sidecar_fallback', ''])
|
|
||||||
deps.handleNotice(['service_core::repair_required', ''])
|
deps.handleNotice(['service_core::repair_required', ''])
|
||||||
deps.handleNotice(['service_core::app_data_not_owned', ''])
|
deps.handleNotice(['service_core::app_data_not_owned', ''])
|
||||||
deps.handleNotice(['core_start::error', ''])
|
deps.handleNotice(['core_start::error', ''])
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ export type {
|
|||||||
FailedOperation,
|
FailedOperation,
|
||||||
PendingFailure,
|
PendingFailure,
|
||||||
SidecarFailureSnapshot,
|
SidecarFailureSnapshot,
|
||||||
ServiceInstallOutcome,
|
|
||||||
ProxyPortSettings,
|
ProxyPortSettings,
|
||||||
ListenerTransport,
|
ListenerTransport,
|
||||||
ListenerProbe,
|
ListenerProbe,
|
||||||
@@ -234,10 +233,6 @@ export async function takeDnsOverrideNotice() {
|
|||||||
return commands.takeDnsOverrideNotice()
|
return commands.takeDnsOverrideNotice()
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function takeServiceFallbackNotice() {
|
|
||||||
return commands.takeServiceFallbackNotice()
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getCoreStartupError() {
|
export async function getCoreStartupError() {
|
||||||
return commands.getCoreStartupError()
|
return commands.getCoreStartupError()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import {
|
|||||||
getCoreStartupError,
|
getCoreStartupError,
|
||||||
takeDiscardedKeysNotice,
|
takeDiscardedKeysNotice,
|
||||||
takeDnsOverrideNotice,
|
takeDnsOverrideNotice,
|
||||||
takeServiceFallbackNotice,
|
|
||||||
takeServiceOwnerNotice,
|
takeServiceOwnerNotice,
|
||||||
takeServiceRepairNotice,
|
takeServiceRepairNotice,
|
||||||
} from '@/services/cmds'
|
} from '@/services/cmds'
|
||||||
@@ -111,30 +110,6 @@ const handlers: Record<
|
|||||||
console.error('Failed to read the pending service owner notice', error)
|
console.error('Failed to read the pending service owner notice', error)
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
'service_core::sidecar_fallback': () => {
|
|
||||||
void takeServiceFallbackNotice()
|
|
||||||
.then((notice) => {
|
|
||||||
if (notice?.kind === 'coreRejected') {
|
|
||||||
showNotice.warning(
|
|
||||||
'settings.feedback.notifications.clashService.permissionFallback',
|
|
||||||
{ reason: notice.reason },
|
|
||||||
0,
|
|
||||||
)
|
|
||||||
} else if (notice?.kind === 'notAutoStarted') {
|
|
||||||
requestService({ reason: 'serviceNotAutoStarted' })
|
|
||||||
} else if (notice) {
|
|
||||||
showNotice.warning(
|
|
||||||
'settings.feedback.notifications.clashService.sidecarFallback',
|
|
||||||
)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
console.error(
|
|
||||||
'Failed to read the pending service fallback notice',
|
|
||||||
error,
|
|
||||||
)
|
|
||||||
})
|
|
||||||
},
|
|
||||||
'dns_override::auto_disabled': () => {
|
'dns_override::auto_disabled': () => {
|
||||||
void takeDnsOverrideNotice()
|
void takeDnsOverrideNotice()
|
||||||
.then((pending) => {
|
.then((pending) => {
|
||||||
|
|||||||
Reference in New Issue
Block a user